text
stringlengths 8
267k
| meta
dict |
---|---|
Q: In Linq to EF 4.0, I want to return rows matching a list or all rows if the list is empty. How do I do this in an elegant way? This sort of thing:
Dim MatchingValues() As Integer = {5, 6, 7}
Return From e in context.entity
Where MatchingValues.Contains(e.Id)
...works great. However, in my case, the values in MatchingValues are provided by the user. If none are provided, all rows ought to be returned. It would be wonderful if I could do this:
Return From e in context.entity
Where (MatchingValues.Length = 0) OrElse (MatchingValues.Contains(e.Id))
Alas, the array length test cannot be converted to SQL. I could, of course, code this:
If MatchingValues.Length = 0 Then
Return From e in context.entity
Else
Return From e in context.entity
Where MatchingValues.Contains(e.Id)
End If
This solution doesn't scale well. My application needs to work with 5 such lists, which means I'd need to code 32 queries, one for every situation.
I could also fill MatchingValues with every existing value when the user doesn't want to use the filter. However, there could be thousands of values in each of the five lists. Again, that's not optimal.
There must be a better way. Ideas?
A: Give this a try: (Sorry for the C# code, but you get the idea)
IQueryable<T> query = context.Entity;
if (matchingValues.Length < 0) {
query = query.Where(e => matchingValues.Contains(e.Id));
}
You could do this with the other lists aswell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: LI elements have float left to be aligned to the right in a container? In this code the LI elements have float:left and are aligned to the left of the container. I want to make them aligned to the right. How do I do this with CSS?
For example:
[..................................Item1.Item2]
Here is the HTML code:
<div class="menu">
<ul>
<li>Item1</li>
<li>Item2</li>
</ul>
</div>
P.S. The order of LI's must not be reverse.
A: Try this
<div class="menu">
<ul>
<li>Item1</li>
<li>Item2</li>
</ul>
</div>
CSS
.menu
{ float:right;
}
.menu li
{ float:left;
}
Or Use float:right to ul like
.menu ul
{ float:right;
}
.menu li
{ float:left;
}
JSFiddle Example
A: Make the lis inline and put text-align:right on the ul
.menu li {
display:inline;
}
.menu ul {
text-align:right;
}
http://jsfiddle.net/XKARB/
A: reverse the order of the lis in your html, and use float: right
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: connection failed : Bad Url (null) error while sending POST data from Xcode to classic ASP page. In my iphone project, I need to pass member Id and pwd to a web server. I have tried my code with Synchronous as well as asynchronous request but I always get error : connection failed: Bad URL (null). can any one please help me to find what's wrong with the code?
My code:
NSString *post =[NSString stringWithFormat:@"memberId=%@&pwd=%@",txtUName.text,txtPwd.text];
NSLog(@"%@",post);
NSURL *url = [NSURL
URLWithString:@"http://testweb.talkfusion.com/videocenter/xlogin.asp%@"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
//set up the request to the website
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"%@",data);
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
A: The %@ at the end in your url is wrong. POST-data are not part of the url.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I resize and paintComponent inside a frame Write a program that fills the window with a larrge ellipse. The ellipse shoud touch the window boundaries, even if the window is resized.
I have the following code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
public class EllipseComponent extends JComponent {
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
Ellipse2D.Double ellipse = new Ellipse2D.Double(0,0,150,200);
g2.draw(ellipse);
g2.setColor(Color.red);
g2.fill(ellipse);
}
}
And the main class:
import javax.swing.JFrame;
public class EllipseViewer {
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(150, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
EllipseComponent component = new EllipseComponent();
frame.add(component);
frame.setVisible(true);
}
}
A: in your EllipseComponent you do:
Ellipse2D.Double ellipse = new Ellipse2D.Double(0,0,getWidth(),getHeight());
I'd also recommend the changes given by Hovercraft Full Of Eels. In this simple case it might not be an issue but as the paintComponent method grows in complexity you realy want as little as possible to be computed in the paintComponent method.
A: Do not resize components within paintComponent. In fact, do not create objects or do any program logic within this method. The method needs to be lean, fast as possible, do drawing, and that's it. You must understand that you do not have complete control over when or even if this method is called, and you certainly don't want to add code to it unnecessarily that may slow it down.
You should create your ellipse in the class's constructor. To resize it according to the JComponent's size and on change of size, use a ComponentListener.:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;
public class EllipseComponent extends JComponent {
Ellipse2D ellipse = null;
public EllipseComponent {
ellipse = new Ellipse2D.Double(0,0,150,200);
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
// set the size of your ellipse here
// based on the component's width and height
}
});
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
g2.draw(ellipse);
g2.setColor(Color.red);
g2.fill(ellipse);
}
}
Caveat: code not run nor tested
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WAP, How to Publish to Web with Web Deploy? I want to publish my web application on a hosting server.
Domain: mysite.com
Folder: mysite.com/TestWAP
*
*Can I use one-click deployment on typical discount shared hosting?
*Will I need to make any installation on the server first, and how is
this done?
*With the above details, what would I specify in the
"Service URL" and "Site/Application" fields?
A: Check out these resources:
How to: Deploy a Web Application Project Using One-Click Publish and Web Deploy
Walkthrough: Deploying a Web Application Project Using One-Click Publish
ASP.NET Web Application Project Deployment FAQ
A: Build, publish local with a manual first time setup on shared host. From then on publish through Visual Studio Publish - FTP option.
A: I think you are looking for this.
Configure the Web Deployment Handler
Hope this help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android - EditText as search box doesn't work I would like to enable search functionality to EditText. My requirement is like this:
when someone types with some letter, suppose the user types 'a', then it should show all the words which starts with 'a' should be shown as a drop down list. For example, if I first typed "copy" in the EditText, if again, I cleared the EditText and tried to type "co", then it should show the drop-down list "copy","come","cow"....
I want to enable this feature to my EditText view. It worked when I had a ListView with only a textview inside, but now that I have two textview in my ListView it doesn't work.
This is my activity:
public class sedactivity extends Activity {
ListView lview;
ListViewAdapter lviewAdapter;
EditText ed;
private static final String first[] = {
"America",
"Busta",
"Cactus",
"Fire",
"Garden",
"Hollywood",
"King",};
private static final String second[] = {
"Uniti",
"Chiusa",
"Verde",
"Fiamme",
"Aperto",
"Boulevard",
"Kong",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText)findViewById(R.id.EditText1);
lview = (ListView) findViewById(R.id.listView2);
lviewAdapter = new ListViewAdapter(this, first, second);
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
lview.setTextFilterEnabled(true);
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<first.length;i++)
{
if(textlength<=first[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) first[i].subSequence(0, textlength)))
{
arr_sort.add(first[i]);
}
}
}
}});}
}
And this is my ListView Adapter
public class ListViewAdapter extends BaseAdapter{
Activity context;
String title[];
String description[];
public ListViewAdapter(Activity context, String[] title, String[] description) {
super();
this.context = context;
this.title = title;
this.description = description;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
return convertView;
}
}
A: I think an AutoCompleteTextView might be more suitable to implement this feature.
A: Check out this example to create your own Listener to check the values inside Edittext on key press event - How to implement your own Listener
A: Instead of extending BaseAdapter you extend ArrayAdapter. It implements the Filterable interface for you. In TextWatcher call getFilter().filter(text); method.
public void afterTextChanged(Editable s) {
listview.getAdapter().getFilter().filter(s);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: EntityFramework SQL Server 2000?
Possible Duplicate:
Entity Framework v2 doesn't support sql 2000?
I have a windows forms application that access a SQL Server 2000 server. Originally this application was written with Visual Studio 2008. Since then we have migrated to Visual Studio 2010 and when I try to add new entities to the .edmx (using Update Model from Database) I get a message saying that EntityFramwork only works with SQL Server 2005 or greater.
Did something change in VS2010? I was definitely able to add entities before.
A: EF4's support for SQL Server 2000 is spotty; things like First and FirstOrDefault (or any functions that result in a TOP expression) will not work, for example. While the runtime may generate code that is compatible, the designer is no longer compatible with anything older than SQL Server 2005.
Unfortunately, that's what you're stuck with. Your best option (in the short term) would probably be to mirror a copy of your database in a SQL Server 2005 Express instance and point the designer to that.
While I realize that companies can have a significant investment in software and upgrading is not always feasible, SQL Server 2000 is 11 -- almost 12 -- years old, and it's not really reasonable to expect cutting-edge tools to support technology this old when multiple versions have been released since then.
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use Facebook Application to write a notification to Users i'm developing an application for a university exam, using Appengine and Gwt (Google products) and i'd like to implement Facebook this way:
- give the ability to a FB user to login to the application through facebook (did this implementing the oAuth2.0 flow, so now i have the user's access token and his permissions)
- since the application is for being notified when a professor publishes some material for his course (this is all handled by appengine), i'd like to notify the user when a professor publishes some material, through a wall post or a note from my application in a way that it writes to the user something about the new published material.
I've been looking through EVERY single resource online, and couldn't find an answer: a lot of similar questions but no answers.
Writing the POST is not a problem, and for the moment i'm trying with the api graph explorer.
I manage to write on the user's wall/note as if he's writing himself or (if the user likes the application) write all the likers a wall post/note (but the same to everyone).
But i don't find a way to send personalized wall posts/notes to every user in response to some specific material published.
FB doesn't allow to do this because is considered spamming?
A: You can't directly post things to your user's wall as a way of notifying them - wall posts are intended to be things the user posts from within your app (for instance, they find something in your app interesting and choose to share it with their friends, so they click a 'Share' button).
You could try using an App-Generated Request (http://developers.facebook.com/docs/channels/#requests). This will increment the user's Bookmark Counter, and when they click on it they will enter your app and you can show them the latest news.
OR, you could ask for the 'email' permission for your app, and send the user an email notification when something is new.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to synchronize access to a global variable with very frequent reads / very rare writes? I’m working on debug logging infrastructure for a server application. Each logging point in source code specifies its level (CRITICAL, ERROR, etc.) among other parameters.
So in source code logging point looks as:
DBG_LOG_HIGH( … )
which is a macro that expands to
if ( CURRENT_DEBUG_LOG_LEVEL >= DEBUG_LOG_LEVEL_HIGH ) {
// prepare and emit log record
}
where DEBUG_LOG_LEVEL_HIGH is a predefined constant (let’s say 2) and CURRENT_DEBUG_LOG_LEVEL is some expression that evaluates to the current debug logging level set by the user.
The simplest approach would be to define CURRENT_DEBUG_LOG_LEVEL as:
extern int g_current_debug_log_level;
#define CURRENT_DEBUG_LOG_LEVEL (g_current_debug_log_level)
I would like to allow user to change the current debug logging level during the application execution and its okay for the change to take a few seconds to take effect. The application is multi-threaded and changes to g_current_debug_log_level can be easily serialized (for instance by CRITICAL_SECTION) but in order not to impact performance expression ( CURRENT_DEBUG_LOG_LEVEL >= DEBUG_LOG_LEVEL_HIGH ) should execute as fast as possible so I would like to avoid using any thread synchronization mechanism there.
So my questions are:
*
*Can the absence of synchronization in g_current_debug_log_level reads cause incorrect value to be read? While it should not affect application correctness because user could have set the current debug logging level to the incorrect value anyway it might affect the application performance because it might cause it to emit very high volume of debug log for uncontrollable period of time.
*Will my solution guarantee that change in the current debug logging level will reach all the threads after the acceptable amount of time (let’s say a few seconds)? Ideally I would like level change operation to be synchronous so that when user receives acknowledgement on level change operation she can count on subsequent log to be emitted according the new level.
I would also greatly appreciate any suggestions for alternative implementations that satisfies the above requirements (minimal performance impact for level comparison and synchronous level change with no more than a few seconds latency).
A: There is nothing that requires that a write made on one thread on one core will ever become visible to another thread reading on another core, without providing some sort of fence to create a 'happens before' edge between the write and the read.
So to be strictly correct, you would need to insert the appropriate memory fence / barrier instructions after the write to the log level, and before each read. Fence operations aren't cheap, but they are cheaper than a full blown mutex.
In practice though, given a concurrent application that is using locking elsewhere, and the given fact that your program will continue to operate more or less correctly if the write does not become visible, it is likely that the write will become visible incidentally due to other fencing operations within a short timescale and meet your requirements. So you can probably get away with just writing it and skipping the fences.
But using proper fencing to enforce the happens before edge is really the correct answer. FWIW, C++11 provides an explicit memory model which defines the semantics and exposes these sorts of fencing operations at the language level. But as far as I know no compiler yet implements the new memory model. So for C/C++ you need use lock from a library or explicit fencing.
A: Assuming you're on Windows and Windows only runs on x86 (which is mostly-true for now but may change...), and assuming only one thread ever writes to the variable, you can get away without doing any synchronization whatsoever.
To be "correct", you should be using a reader-writer lock of some form.
A: Given your current implementation, I suggest you take a look at atomic operations. If this is intended for Windows only, look at Interlocked Variable Access
A: Look at the new Slim Reader/Writer locks available on Vista and 7. They should do what you want with as little overhead as possible:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937(v=vs.85).aspx
A: On x86 and x64 volatile will impose very few direct costs. There may be some indirect costs related to forcing re-fetch of unrelated variables (accesses to volatile variables are treated as compiler-level memory fences for all other 'address taken' variables). Think of a volatile variable as like a function call in that the compiler will lose information about the state of memory across the call.
On Itanium, volatile has some cost but it's not too bad. On ARM, the MSVC compiler defaults to not providing barriers (and not providing ordering) for volatile.
One important thing is that there should be at least one access to this log level variable in your program, otherwise it might be turned into a constant and optimized out. This could be a problem if you were intending to set the variable through no mechanism other than the debugger.
A: Define ordinal variable visible in the scope and update it as appropriate (when the log level changes)
If the data is correctly aligned (i.e. default one), then you don't need anything special except declaring your current log variable a "volatile". This would work for LONG size (32 bit ordinal).
So your solution would be:
extern volatile long g_globalLogLevel;
No need for external synchronization (i.e. RWlock/CriticalSection/Spin etc)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How do I send an AJAX request upon page unload / leaving? window.onbeforeunload = function() {
return $j.ajax({
url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + "&time_on_page=" + getSeconds()
});
}
this what I have, but it returns an alert with [object Object]
how do I just execute the AJAX?
note: when I just don't return anything, the server doesn't show that it is receiving the ajax request.
A: You don't need to return anything, just fire the ajax call.
window.onbeforeunload = function(e) {
e.preventDefault();
$j.ajax({ url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + &time_on_page=" + getSeconds()
});
}
If you are using jQuery, you can try binding to the .unload() event instead.
A: onbeforeunload allows you to return a string, which is shown in the 'Do you want to leave' confirmation. If you return nothing, the page is exited as normal. In your case, you return the jqXHR object that is returned by the JQuery ajax method.
You should just execute the Ajax call and return nothing.
A: Why are you returning the reference of function to global pool? It should be like this:
window.onbeforeunload = function() {
$j.ajax({
url: "/view/action?&recent_tracking_id=" + $recent_tracking_id + "&time_on_page=" + getSeconds()
});
}
A: To the best of my understanding, the onbeforeunload function will only return an alert. This was done to prevent the annoying popups of a few years back.
I was building a chat client a while back and the only way i could figure out to do something like this is to do a setInterval function that updated a timestamp, then checked for timed out users and removed them. That way users that didnt "check in" within a certain interval would be removed from the room by other users still logged in.
Not pretty, or ideal, but did the trick.
A: Doing standard ajax calls in a page unload handler is being actively disabled by browsers, because waiting for it to complete delays the next thing happening in the window (for instance, loading a new page).
In the rare case when you need to send information as the user is navigating away from the page (as Aaron says, avoid this where possibl), you can do it with sendBeacon. sendBeacon lets you send data to your server without holding up the page you're doing it in:
window.addEventListener("unload", function() {
navigator.sendBeacon("/log", yourDataHere);
});
The browser will send the data without preventing / delaying whatever is happening in the window (closing it, moving to a new paeg, etc.).
Note that the unload event may not be reliable, particularly on mobile devices. You might combine the above with sending a beacon on visibilitychange as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert List to Dictionary > I would like to take a list of objects and convert it to a dictionary where the key is a field in the object, and the value is a list of a different field in the objects that match on the key. I can do this now with a loop but I feel this should be able to be accomplished with linq and not having to write the loop. I was thinking a combination of GroupBy and ToDictionary but have been unsuccessful so far.
Here's how I'm doing it right now:
var samplesWithSpecificResult = new Dictionary<string, List<int>>();
foreach(var sample in sampleList)
{
List<int> sampleIDs = null;
if (samplesWithSpecificResult.TryGetValue(sample.ResultString, out sampleIDs))
{
sampleIDs.Add(sample.ID);
continue;
}
sampleIDs = new List<int>();
sampleIDs.Add(sample.ID);
samplesWithSpecificResult.Add(sample.ResultString, sampleIDs);
}
The farthest I can get with .GroupBy().ToDictionay() is Dictionary<sample.ResultString, List<sample>>.
Any help would be appreciated.
A: Try the following
var dictionary = sampleList
.GroupBy(x => x.ResultString, x => x.ID)
.ToDictionary(x => x.Key, x => x.ToList());
The GroupBy clause will group every Sample instance in the list by its ResultString member, but it will keep only the Id part of each sample. This means every element will be an IGrouping<string, int>.
The ToDictionary portion uses the Key of the IGrouping<string, int> as the dictionary Key. IGrouping<string, int> implements IEnumerable<int> and hence we can convert that collection of samples' Id to a List<int> with a call to ToList, which becomes the Value of the dictionary for that given Key.
A: Yeah, super simple. The key is that when you do a GroupBy on IEnumerable<T>, each "group" is an object that implements IEnumerable<T> as well (that's why I can say g.Select below, and I'm projecting the elements of the original sequence with a common key):
var dictionary =
sampleList.GroupBy(x => x.ResultString)
.ToDictionary(
g => g.Key,
g => g.Select(x => x.ID).ToList()
);
See, the result of sampleList.GroupBy(x => x.ResultString) is an IEnumerable<IGrouping<string, Sample>> and IGrouping<T, U> implements IEnumerable<U> so that every group is a sequence of Sample with the common key!
A: Dictionary<string, List<int>> resultDictionary =
(
from sample in sampleList
group sample.ID by sample.ResultString
).ToDictionary(g => g.Key, g => g.ToList());
You might want to consider using a Lookup instead of the Dictionary of Lists
ILookup<string, int> idLookup = sampleList.ToLookup(
sample => sample.ResultString,
sample => sample.ID
);
used thusly
foreach(IGrouping<string, int> group in idLookup)
{
string resultString = group.Key;
List<int> ids = group.ToList();
//do something with them.
}
//and
List<int> ids = idLookup[resultString].ToList();
A: var samplesWithSpecificResult =
sampleList.GroupBy(s => s.ResultString)
.ToDictionary(g => g.Key, g => g.Select(s => s.ID).ToList());
What we 're doing here is group the samples based on their ResultString -- this puts them into an IGrouping<string, Sample>. Then we project the collection of IGroupings to a dictionary, using the Key of each as the dictionary key and enumerating over each grouping (IGrouping<string, Sample> is also an IEnumerable<Sample>) to select the ID of each sample to make a list for the dictionary value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: Fastest .NET way to retrieve the most metadata from files in a remote network share? Of the available .NET System.IO methods/classes, what is the most efficient way to retrieve an entire directory listing on a remote network share (assume a slow, non-LAN speed link)?
For 10,000+ files, need to grab:
*
*Name
*Size
*Date Last Modified
*Date Created
There appears to be a huge performance difference in the amount of time it takes to loop through FileInfo objects for this information vs. the amount of time that Windows Explorer can display the same thing.
A: Yes, this is a side-effect of a design choice made in .NET 1.0 for the FileInfo class. It doesn't store the property values when the FileInfo object is constructed, it is retrieved from the file when you use the property getter. That way you always get the up-to-date value of the property. Which of course matters a great deal for the size and date properties, they mutate easily. The round-trip through the network however makes it slow.
It was solved in .NET 4 with the added DirectoryInfo.EnumerateXxxx() methods. The emphasis on an enumerator made it now obvious that you got a potentially stale copy of the file info. But avoiding the round-trip.
Solves your problem if you can use .NET 4. You'll need to pinvoke FindFirstFile, FindNextFile, FindClose if you can't.
A: For best performance, you're probably going to want to use Win32 APIs like FindFirstFile, FindNextFile, GetFileAttributesEx, and GetFileSizeEx.
If you'd like to avoid Win32 calls, Directory.EnumerateFiles is more efficient than Directory.GetFiles, because it lazily enumerates over the files as they're requested, which may internally use more efficient Win32 APIs. However, since you're going over the network, you may actually want to call Directory.GetFiles to grab them all at once. Experiment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get unique count by matchin partial string in logs I want to find out how many users have blue colors & how many of them have red color for all unique users?
[2011-09-30 18:15:01:559 GMT+00:00][137D3B5A5F196F81A405858E6A5AA01F.maps-358-thread-1][com.abc.myaction.myfilter] INFO [email protected] userid=1234
[2011-09-30 18:15:01:559 GMT+00:00][237D3B5A5F197F81A405858E6A5AA0WD.maps-158-thread1][com.abc.myaction.myfilter] INFO [email protected] userid=4235
[2011-09-30 18:15:01:559 GMT+00:00][337D3B5A5F198F81A405858E6A5AA0GW.maps-258-thread-1][com.abc.myaction.myfilter] INFO [email protected] userid=7645
[2011-09-30 18:14:58:768 GMT+00:00][237D3B5A5F198F81A405858E6A5AA09F.http-8080-11][com.pqr.abclogging.mywrapper] DEBUG redColor=true blueColor=false
[2011-09-30 18:14:58:768 GMT+00:00][237D3B5A5F197F81A405858E6A5AA0WD.http-8080-11][com.fff.filter] DEBUG redColor=true blueColor=false
[2011-09-30 18:14:58:768 GMT+00:00][137D3B5A5F196F81A405858E6A5AA01F.http-8080-11][com.xyz.wrapper] DEBUG redColor=false blueColor=true
[2011-09-30 18:14:58:768 GMT+00:00][337D3B5A5F198F81A405858E6A5AA0GW.http-8080-11][com.xyz.wrapper] DEBUG redColor=false blueColor=true
In above log, I've to get all distinct users & then for each user, I need to get their session id & them match it within the line that contains the DEBUG & check if redColor=true or not.
So, in above case, the output should be:
No of users with red color = 1 (Note: 237D3B5A5F198F81A405858E6A5AA09F does not match with anything, hence not counted even though its red flag is true) No of users with blue color = 2
Is this possible within splunk?
A: First, have you extracted a field for sessionid? In my example below, I am assuming it is available
sourcetype=yoursourcetype | transaction sessionid | search debug
| eval redCount = if(isnull(mvfind(redColor,"true")), 0, 1)
| eval blueCount = if(isnull(mvfind(blueColor,"true")), 0, 1)
| search redCount > 0 OR blueCount > 0
| stats avg(redCount) avg(blueCount) by userid
| stats sum(redCount) as red sum(blueCount) as blue dc(userid) as totalUsers
| fields + totalUsers red blue
I'd suggest that you try just the first line of the search first. If that works, run the first 2 lines, then 3, etc. I set up so you could test it out that way. Also, replace yoursourcetype with the appropriate sourcetype of your data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the most efficient way to subtract one list from another? I am trying to subtract List_1 (50k lines) from List_2 (100k lines) , when an item in List_1 is an exact match for an item in List_2. I am using grep, specifically:
grep -v -f List_1.csv List_2.csv > Magic_List.csv
I know this is not the most efficient way to do this, but what is? sed? awk? comm? SQL? How might I accomplish this in the most efficient way possible?
A: This is one of the most efficient ways IMHO, you need to add -F though:
grep -Fvf List_1.csv List_2.csv > Magic_List.csv
A: Most efficient way is to use a trie data structure or a hash function for the 2nd list and for each item in the first list search in your trie.
A: You'd have to benchmark it to find the most efficient method. This is, however, what comm is for, so I'd guess it would be a pretty tool.
comm -13 List_1.csv List_2.csv > Magic_List.csv
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: tag not working properly I have a GWT app and Im trying to put fb social plugin comment in side of my page. However I have the folowing problem.
If I put the tag in my .html it works perfect, but If I put id dynamically (like with an HTML widjet), It does not work. It just does not display anything.
Can anyone help me? Im having this problem in general, not only with the fb:comment tag.
Note: If I use the iframe implementation of, for example, "fb:like", it works perfect.
A: My understanding of facebook's api is that it loads your content, and parses out the tags in the fb namespace, replacing them before the actual content is drawn for the user. In contrast, none of the GWT compiled code (or indeed any Javascript code) gets a chance to make changes to the dom until the page has loaded in the browser fully, after facebook has made the changes it needs to.
My advice: Put the fb namespaced tags on the initial page, but perhaps wrap them in a div and mark them as display:none. Then you can grab them from your GWT code and wrap them up in a widget, only to be displayed when you are ready.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding new value to nested observable array created with knockout.mapping plugin and knockoutjs So close to getting this to work as expected. I am getting data from a JSON request and then using the mapping plugin to map it. I want to add new values to a nested array on a click binding.
Right now in my code I am getting an error that addPoint is not defined.
View:
<table>
<tbody data-bind='template: {name: "statRowTemplate", foreach: stats }'></tbody>
</table>
<script id="statRowTemplate" type="text/html">
{{if type() != "column"}}
<tr>
<td><label>Name: </label><input data-bind="value: name" /></td>
<td>
<label>Plot Points: </label><ul class="list-plot-points" data-bind="template: {name: 'dataTemplate' , foreach: data}"></ul>
<button data-bind="click: addPoint">Add Point</button>
</td>
</tr>
{{/if}}
</script>
<script type="text/html" id="dataTemplate">
<li>
<input data-bind="value: val" />
</li>
</script>
<button data-bind="click: saveChanges">Save Changes</button>
View Model
var viewModel = {};
$.getJSON('data-forecast-accuracy.json', function(result) {
function mappedData(data) {
this.val = data;
}
//override toJSON to turn it back into a single val
mappedData.prototype.toJSON = function() {
return parseInt(ko.utils.unwrapObservable(this.val), 10); //parseInt if you want or not
};
var mapping = {
'data': {
create: function(options) {
return new mappedData(options.data)
}
}
}
viewModel.stats = ko.mapping.fromJS(result, mapping);
viewModel.addPoint = function() {
this.stats.data.push(new mappedData(0));
}
viewModel.saveChanges = function() {
var unmapped = ko.mapping.toJSON(viewModel.stats);
//console.log(unmapped);
$.post('save-changes.php', {data: unmapped})
.success(function(results) { console.log("success")})
.error(function() { console.log("error"); })
.complete(function() { console.log("complete"); });
}
ko.applyBindings(viewModel);
});
The JSON:
[{"type":"spline","marker":{"symbol":"diamond"},"name":"Cumulative","data":[10,17,18,18,16,17,18,19]},{"type":"spline","marker":{"symbol":"circle"},"name":"Monthly","data":[10,22,20,19,8,20,25,23]}]
I was able to adjust this jsfiddle from an earlier response to add points to the single array. I need to find a way to implement this across the generated mapping.
http://jsfiddle.net/vv2Wx/1/
A: The reason you're getting "addPoint is not defined" error is because you're inside a template for a child property of the view model. Inside the template, the binding context is a stat object, not your view model.
Bottom line: Knockout is looking for a stat.addPoint function, which doesn't exist, so you get the error.
What you probably want to do is reference the parent binding context, your view model. In KO 1.3 beta, you can access parent binding contexts like this:
<button data-bind="click: $.parent.addPoint">Add Point</button>
If you're stuck on an old version of Knockout that doesn't provide access to the parent binding context, let me know, there are some additional options, such as making your view model globally accessible, then just binding to that fully qualified name.
A: Where you are binding against addPoint the context is an item in stats rather than your view model.
If viewModel has global scope, then you can do: click: viewModel.addPoint. You will want to make sure that this is set correctly in your addPoint method. Easiest way is to bind the method to your viewModel variable like:
viewModel.addPoint = function() {
this.stats.data.push(new mappedData(0));
}.bind(viewModel);
If viewModel does not have global scope, then you can pass it in via templateOptions. This would be like:
<tbody data-bind='template: {name: "statRowTemplate",
foreach: stats, templateOptions: { add: addPoints } }'></tbody>
Then, call it like: <button data-bind="click: $item.add">Add Point</button>
Finally, if you are using KO 1.3 beta, then you can do: <button data-bind="click: $root.addPoint">Add Point</button>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Entity Datagrid : best way to add computed values? I have a WPF datagrid databound to a collectionviewsource, which is itself based of a entity query
In my grid for example I have 3 columns Number1, Number2, Number3, all properties of an entity. If I want to add a column called SumNumber which is equal to Number1+Number2+Number3, what is the best way to do that so that when I change Number1, the value in SumNumber is updated ?
Thanks in advance
I'm almost there but I'm getting another error. See below a snippet of code
public partial class MyEntity
{
public double MyCustomizedProperty{get;set;}
public MyEntity()
{
this.PropertyChanged += Entity_PropertyChanged;
}
void Entity_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName )
{
case "Date" :
MyCustomizedProperty = DateTime.Now.Second;
ReportPropertyChanged("MyCustomizedProperty");
break;
}
}
}
That compiles and all, but when I change "Date" I get a runtime error :
The property 'SigmaFinal' does not have a valid entity mapping on the entity object. For more information, see the Entity Framework documentation.
I suppose this is due to the fact that the property is not in the OnStateManager. Can you please let me know how to fix that ?
Thanks
A: I would either create a Converter that would take all 3 values and return the sum of them, or I would expand the Entity Framework class to include an extra property
Here's an example of expanding the EF class to include the extra property:
public partial class MyEntity
{
public MyEntity()
{
// Hook up PropertyChanged event to alert the UI
// to update the Sum when any of the Values change
this.PropertyChanged += MyEntity_PropertyChanged;
}
void MyEntity_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch e.PropertyName
{
case "Value1":
case "Value2":
case "Value3":
ReportPropertyChanged("SumValues");
break;
}
}
public int SumValues
{
get
{
return Value1 + Value2 + Value3;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JQuery: How to show/hide a series of form labels onde after another I am trying to make a stream of show / hide fields in a form with jQuery.
This is the form:
<form>
<label for="onde" class="onde">
<b>qua qua text</b>
<textarea name="onde" id="onde"></textarea>
<a class="next">Continue</a>
</label>
<label for="tentou">
<b>bla bla text</b>
<textarea name="tentou" id="tentou"></textarea>
<a class="next">Continue</a>
</label>
<label for="quase">
<b>yada yada text</b>
<textarea name="quase" id="quase"></textarea>
</label>
<input type="submit" id="submit" value="Send">
</form>
So, when I click on a.next, I need to hide the label of which the anchor tag belongs and show the next tag.
The problem here is that actually I don't know the labels names (not even the real number of labels in the form), for they will be dynamically generated.
The last task will be make the submit bottom show when the last label will be visible.
Till now this is what I got:
$('a.next').click(function(event) {
$(this).fadeIn('slow');
$(this).css('display','block');
});
But... I can't go any longer...
A: Just give a common class to your text areas. Suppose we have given class 'ta'
Now here is the code
EDIT:
$(document).ready(function(){
var i=0;
$(".next").click(function(){
$("label:eq("+i+")").fadeOut(200);
i++;
$("label:eq("+i+")").fadeIn(200);
});
});
This is the jquery code you need.
JS fiddle
This is the working fiddle you need.
A: This should do what you want..
$('a.next').click(function(event) {
var label = $(this).closest('label');
label.hide();
label.nextAll('label:first').fadeIn('slow');
});
demo at http://jsfiddle.net/gaby/fhuU4/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what does this error messsage "Invalid token character ':' in token "Accept:text"" mean in spring mvc 3? Stacktrace is listed below. Really could not figure out what it means. Thanks for any help.
Caused by: java.lang.IllegalArgumentException: Invalid token character ':' in token "Accept:text"
at org.springframework.http.MediaType.checkToken(MediaType.java:282) ~[spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.http.MediaType.<init>(MediaType.java:254) ~[spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.http.MediaType.parseMediaType(MediaType.java:584) ~[spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.http.MediaType.parseMediaTypes(MediaType.java:602) ~[spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.view.ContentNegotiatingViewResolver.getMediaTypes(ContentNegotiatingViewResolver.java:306) ~[spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.view.ContentNegotiatingViewResolver.resolveViewName(ContentNegotiatingViewResolver.java:366) ~[spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.resolveViewName(DispatcherServlet.java:1078) ~[spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1027) ~[spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817) ~[spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) ~[spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) ~[spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
... 53 common frames omitted
A: This exception mean that you have incorrect mediaType format. the correct media type is "application/json", "text/html", "image/png";
I just looked at the the source code of org.springframework.http.MediaType and these are correct separators for MediaType.
BitSet separators = new BitSet(128);
separators.set('(');
separators.set(')');
separators.set('<');
separators.set('>');
separators.set('@');
separators.set(',');
separators.set(';');
separators.set(':');
separators.set('\\');
separators.set('\"');
separators.set('/');
separators.set('[');
separators.set(']');
separators.set('?');
separators.set('=');
separators.set('{');
separators.set('}');
separators.set(' ');
separators.set('\t');
':' is not defined there and this is the reason why does this exception is thrown, now this is your turn to find out why do you have Accept HTTP Header parameter instead of correct media Type ("application/json", "image/jpg", "application/octec-stream", etc...).
Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JQuery Template - Calls ${$item.function()} more than is specified in the template Jquery-tmpl seems to call functions you attach to item multiple times.
JSfiddle: http://jsfiddle.net/abQwc/2/
The console.log's show rowCount got called 4 times for each item rendered by the template.
Template:
<h1 class="${$item.rowCount() % 2 == 0 ? "even" : "odd"}">${Name} - ${Payload}</h1
Data:
data = [
{ Name: "1", Payload: "Data1" },
{ Name: "2", Payload: "Data2" },
{ Name: "3", Payload: "Data3" }
]
Script:
$(function() {$( "#template" )
.tmpl(data, {
rowCount: function(){
var rowCount = 0;
return function(){
console.log(this.data.Payload);
return ++rowCount;
}
}()
})
.appendTo( "body" )})
Why? I've already figured out how to get around it, but it reeks of witchcraft.
A: I replaced:
${$item.rowCount() % 2 == 0 ? "even" : "odd"}
...
return function(){
console.log(this.data.Payload);
return ++counter;
}
with
${$item.rowCount()}
....
return function() {
console.log(this.data.Payload);
return (++counter) % 2 ? 'even' : 'odd';
}
and was able to get it to work. However, the Options parameter was still getting executed 4 times for each item. I believe calculations like that in tmpl are still iffy at best.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using jQuery with node.js I have found out that you can use jQuery with node.js but all examples are for DOM and HTML manipulation.
Do you think using it for array iterations ( for each ) etc would be ok or a bit overkill?
A: NodeJS already has all the EcmaScript 5 Array Extras builtin. For example if you want all the odd squares:
[1,2,3,4,5,6,7,8,9].map(function(n){
return n*n;
}).filter(function(n){
return n%2;
});
//-> [1, 9, 25, 49, 81]
If you would like to see the other methods on the arrays, you can go to my JavaScript Array Cheat Sheet.
If you want the sum of all the cubes, you can:
[1,2,3,4,5,6,7,8,9].map(function(n){
return n * n * n;
}).reduce(function(p, n){
return p + n;
});
//-> 2025
A: Most of the common jQuery utilities are already in implemented in the V8 engine, which node.js is built on.
for example, compare:
*
*$.each with Array::forEach
*$.map with Array::map
*$.inArray with Array::indexOf
*$.trim with String::trim
One of the best things about node.js is that most of the ES5 spec is already there.
A: Underscore.js is a much smaller utility library for manipulating objects.
http://documentcloud.github.com/underscore/
npm install underscore
EDIT:
However, node.js has much better support for ES5 than browsers, and it's likely that you may not even need a library for manipulating objects. See keeganwatkins' answer.
A: jQuery has some nifty non-DOM features you can borrow -
https://github.com/jquery/jquery/tree/master/src
Just strip out what you do not need (like a reference to window).
A: If there are just a few functions you want to add, an alternative to adding a full library is to just implement the functions you want:
Many functions that are partially supported on some browsers are documented in MDN with compatibility code that can be used to add the function: Array.forEach
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Developing/using a custom Resource Plugin in Zend Framework We have used Zend_Log, which is configured in application.ini differently for different circumstances. We initialize it/get it in the bootstrap and store it in the registry:
$r = $this->getPluginResource('log');
$logger = $r->getLog();
But we've subclassed Zend_Log (say, Our_Log) to add customized features, and want to get it the same way. So then we have to make a new Resource Plugin. That seems quite easy - just copy Application/Resource/Log.php, rename the file to Ourlog.php, rename the class to class Zend_Application_Resource_Ourlog. For now, let's not worry about "Our_Log", the class -- just use the new Resource Plugin to get a Zend_Log, to reduce the variables.
So then, our new code in the bootstrap is:
$r = $this->getPluginResource('ourlog');
$logger = $r->getLog();
but of course this doesn't work, error applying method to non-object "r". According to the documentation,
"As long as you register the prefix path for this resource plugin, you
can then use it in your application."
but how do you register a prefix path? That would have been helpful. But that shouldn't matter, I used the same prefix path as the default, and I know the file is being read because I "require" it.
Anyway, any guidance on what simple step I'm missing would be greatly appreciated.
Thanks for the pointers -- so close, so close (I think). I thought I was getting it...
Okay, so I renamed the class Xyz_Resource_Xyzlog, I put it in library/Xyz/Resource/Xyzlog.php
Then, because I don't love ini files, in the bootstrap I put:
$loader=$this->getPluginLoader();
$loader->addPrefixPath('Xyz_Resource','Xyz/Resource/');
$r = $this->getPluginResource('xyzlog');
if (!is_object($r)) die ('Not an object!!');
Sudden Death. So, okay, do the ini:
pluginPaths.Xyz_Resource='Xyz/Resource/'
The same. No help. I believed that the basepaths of the plugin paths would include the PHP "include" paths. Am I mistaken in that? Any other ideas? I'll happily write up what finally works for me to help some other poor soul in this circumstance. Something to do with Name Spaces, maybe?
A: Plugin classes are resolved using the plugin loader, which works slightly differently to the autoloader; so just requiring the class in doesn't help you here. Instead, add this to your application.ini:
pluginPaths.Application_Resource = "Application/Resource"
you should then be able to use the class as normal. Since your path above will be checked before the default Zend one, you can also name your class 'Log' and still extend the Logger resource to override the standard functionality.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Nesting with three levels of quotations I am trying to create a php variable that has three levels of nested quotes. How do I make a third level around "tackEvent", "downloads", "all", and "nofilter"? The double quotes that I have there are not working.
$outputList .= "<a href=files/".$content_file ." onClick='_gaq.push
(["_trackEvent", "downloads", "all", "nofilter"]);' >" . $content_name .
"</a>";
A: From here:
*
*Outer quote = " (This marks the beginning and end of the string)
*Inner quote = \" (Escaped as to not flag "beginning/end of string")
*Third-tier quote = ' (Literal quote)
*Fourth-tier quote = \' (Literal quote that will be generated as an
escaped outer quote)
A: *
*Outer quote: "
*Inner quote: '
*Third-tier quote: \"
*Fourth-tier quote: "
A: $outputList .= <<<LINK
<a href="files/$content_file" onClick="_gaq.push(['_trackEvent', 'downloads', 'all', 'nofilter']);">$content_name</a>
LINK;
This is using heredoc syntax.
A: From the manual:
To specify a literal single quote, escape it with a backslash (\). To
specify a literal backslash, double it (\\).
This applies to strings in double quotes as well.
$str = "I am a string with a quote that says, \"I like quotes\"";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Is it practical to use Mongo's capped collection a memory cache? Is it practical to use Mongo's capped collections as poor man's memcache assuming it will be kept in memory most of the time?
A: Yes. This is a perfectly acceptable use of a MongoDB capped collection. I am assuming you will have many more reads than writes, so make sure you use an index as well.
MongoDB Capped Collections: Applications
A: You can definitely use capped collections for this purpose. But it's important to know the basic limitations.
*
*Data will expire based on insert order not time-to-expire
*Data that is frequently accessed may still be pushed out of memory
*_id columns are not defined on Capped Collections by default, you will need to ensure those indexes.
*The objects cannot be modified in a way that changes the size of the object. For example, you could increment an existing integer, but you cannot add a field or modify a string value on the entry.
*The capped collections cannot be sharded.
Because of #1 & #4 & #5, you are definitely losing some the core Memcache functionality.
There is a long-outstanding JIRA ticket for TTL-based capped collections which is probably exactly what you want.
Of course, the big question in this whole debate is "where is the extra RAM". Many people who use MongoDB as their primary store simply drop Memcache. If you have a bunch of extra RAM sitting around, why not just use it store the actual data instead of copies of that data?
A: As said by Gates VP, capped collections are usable and easy to manage. However you can also use non-capped collections if you :
*
*have a dedicated server for your "poor's man memcache"
*have a lot of data, which cannot fit on one server (or you want to query very fast)
*are ok with dealing with TTL yourself (just add one field)
MongoDB cache (mmap on Unix-like systems) will provides a "unlimited" memcache, caching frequently accessed values.
As said on the mongo FAQ page :
The goal is for Mongo to be an alternative to an ORM/memcached/mysql stack
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to save var value outside ajax success function? I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
A: You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
A: I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Devise API authentication I am working on a rails web application that also provides JSON based API for mobile devices . mobile clients are expected to first obtain a token with (email/pass), then clients will make subsequential API calls with the token.
I am pretty new to Devise, and I am looking for a Devise API look like authenticate(email, pass) and expect it to return true/false, then based on that I will either create and hand back the token or return a decline message. but seems Devise doesn't provide something like this.
I am aware that Devise 1.3 provides JSON based auth, but that's a bit different from what I need - I need to generate token and handle back to client, then after that auth is done using the token instead.
Can someone please give some pointers?
A: There is a devise configuration called :token_authenticatable. So if you add that to the devise method in your "user", then you can authenticate in your API just by calling
"/api/v1/recipes?qs=sweet&auth_token=[@user.auth_token]"
You'll probably want this in your user as well:
before_save :ensure_authentication_token
UPDATE (with API authorization code)
The method you're looking for are:
resource = User.find_for_database_authentication(:login=>params[:user_login][:login])
resource.valid_password?(params[:user_login][:password])
here's my gist with a full scale JSON/API login with devise
A: I would recommend reading through the Devise Wiki, as Devise natively supports token authentication as one of it's modules. I have not personally worked with token authentication in Devise, but Brandon Martin has an example token authentication example here.
A: Devise is based on Warden, an authentification middleware for Rack.
If you need to implement your own (alternative) way to authenticate a user, you should have a look at Warden in combination with the strategies that ship with Devise: https://github.com/plataformatec/devise/tree/master/lib/devise/strategies
A: If token auth just isn't what you want to do, you can also return a cookie and have the client include the cookie in the request header. It works very similar to the web sessions controller.
In an API sessions controller
class Api::V1::SessionsController < Devise::SessionsController
skip_before_action :authenticate_user!
skip_before_action :verify_authenticity_token
def create
warden.authenticate!(:scope => :user)
render :json => current_user
end
end
In Routes
namespace :api, :defaults => { :format => 'json' } do
namespace :v1 do
resource :account, :only => :show
devise_scope :user do
post :sessions, :to => 'sessions#create'
delete :session, :to => 'sessions#destroy'
end
end
end
Then you can do this sort of thing (examples are using HTTPie)
http -f POST localhost:3000/api/v1/sessions user[email][email protected] user[password]=passw0rd
The response headers will have a session in the Set-Cookie header. Put the value of this in subsequent requests.
http localhost:3000/api/v1/restricted_things/1 'Cookie:_my_site_session=<sessionstring>; path=/; HttpOnly'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: Sql Query needed im storing date in mysql database with timestamp in (int) type column.
but how can i get this ( CURRENT ) month current rows only?
What should be the sql query to fetch desired data?
A: Calculate the timestamp of the first and last secondof the month and use sqls BETWEEN
A: Add the year as well and you can use the date functions:
SELECT * FROM table WHERE YEAR(FROM_UNIXTIME(timestamp_field)) = YEAR(NOW()) AND MONTH(FROM_UNIXTIME(timestamp_field)) = MONTH(NOW())
A: $begin = strtotime(date('m/01/Y'));
$end = strtotime(date('m/t/Y'));
$sql = "SELECT * FROM table WHERE date >= $begin AND date <= $end"
This is probably the easiest and fastest solution. Using a SQL function like FROM_UNIXTIME() can work, but it can lead to performance issues down the road.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mink selectors: any way to get the element in base of the content inside? for example, given the text of a link, retrieve the hole link element.
I tried this:
$page = $this->getSession()->getPage();
$page->find('content', 'Italiano');
But it says:
Selector "content" is not registered.
EDIT: after check the links of the everzet's answers I have this:
$el = $page->find('named', array(
'content', $this->getMainContext()->getSession()->getSelectorsHandler()->xpathLiteral('Pound')));
$el->click();
but I'm getting this error about click() function:
When I choose "Pound sterling" #
MyFirm\FrontendBundle\Features\Context\CurrencyControllerContext::iChoose()
error:_click(_byXPath("(//html/./descendant-or-self::*[contains(normalize-space(.),
'Pound')])[1]"))
TypeError: parent.tagName is undefined
([object
HTMLHtmlElement],"A",1)@http://myfirm.localhost/s/spr/concat.js:3286
([object
HTMLHtmlElement],"A")@http://myfirm.localhost/s/spr/concat.js:3762
([object
HTMLHtmlElement])@http://myfirm.localhost/s/spr/concat.js:331
([object HTMLHtmlElement],false,false,(void
0))@http://myfirm.localhost/s/spr/concat.js:708
([object
HTMLHtmlElement])@http://myfirm.localhost/s/spr/concat.js:478
()@http://myfirm.localhost/s/spr/concat.js:3016
()@http://myfirm.localhost/s/spr/concat.js:3016
@http://myfirm.localhost/s/spr/concat.js:2822
<a
href='/s/dyn/Log_getBrowserScript?href=null&n=3286'>Click for
browser script
This is the beginning of the output of var_dump($el):
object(Behat\Mink\Element\NodeElement)#438 (2) {
["xpath":"Behat\Mink\Element\NodeElement":private]=>
string(74) "(//html/./descendant-or-self::*[contains(normalize-space(.), 'Pound')])[1]"
And the output of $el->getTagName() is 'html'.
Is that because I'm trying to click something that is not an element but just content? In that case, any way to get the element from the content?
A: You should use:
$page = $this->getSession()->getPage();
$page->find('css', 'Italiano');
This is using the CSS selectors, and it works like a magic!
But make sure 'Italiano' refers to an element on the page (I would use '#Italiano' if it's an ID).
You can read the traversing pages documentation here.
A: Don't use content selector. Because in almost any case it will provide results, that you don't expect. For example, when you're doing content(Pound), you're expecting that it'll return you an element, that contains this text. The reality is, every parent element of target one is containing your "Pound" text, including <html/>. That's why you get <html/> at the end ;-)
Minks selectors are well-explained in the manual:
*
*http://mink.behat.org
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: pyqt: long process in file open dialog I have little experience in GUI programming but I'm writing a GUI application with PyQt. With this application, user can open a binary file and do some editing with it.
When the file is opened, I do some processing that takes a while (~15s). So when the user pick the file and press the "Open" button in the file open dialog, the GUI is frozen. What's the best way to achieve a better user experience?
Thanks
A: Load in the background showing the progress via a Gauge in the statusbar.
To to this, you can initiate the loading using QThread. Your thread class can look as follows (assuming parent will have an attribute progress):
QtFileLoader(QtCore.QThread):
def __init__(self,parent=None, filepath=None):
QtCore.QThread.__init__(self,parent)
self.data = None
self.filepath = filepath
def run(self):
""" load data in parts and update the progess par """
chunksize = 1000
filesize = ... # TODO: get length of file
n_parts = int(filesize/chunksize) + 1
with open(self.filepath, 'rb') as f:
for i in range(n_parts):
self.data += f.read(chunksize)
self.parent.progress = i
The question whether to use QThread or trheading.Thread is discussed here
edit (according to hint of @Nathan):
On the parent, a timerfunction should check, say each 100ms, the value of self.parent.progress and set the progressbar accordingly. This way, the progressbar is set from within the main thread of the GUI.
A: You need to periodically ask the application to process events pending on the event queue. You do so by calling the processEvents() method of the QApplication instance. If you can intersperse your calculations with calls to processEvents(), the GUI, and progress bars, will update themselves. Note that this is not the same as making the GUI responsive.
To make the GUI responsive while performing your load, you will need to split the load operation into a background thread. You cannot perform GUI operations from the background thread, though the background thread can emit signals that cross thread boundaries. Here is an article on multi-threaded PyQt programming.
A: You are looking for some method to do the job in a different thread that that of the GUI mainloop.
You could check here to start
Major gui frameworks as wxpython and pyQt have methods to run long running applications without freezing the gui. Personally I prefer to use directly the python thread module
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to get profile images with facebook graph api I need to get all of the user profile images,
Mean I need more then the user profile image
I tried to get album, and to extract the images form it, but without success
A: You need
*
*Valid access_token
*user_photos permissions
After that, get photos
A: You could do this with a FQL query:
select pid, src, link, caption
from photo
where aid in
(SELECT aid
FROM album
WHERE owner=me()
and name="Profile Pictures")
This would require user_photos extended permission.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Static Objects | Custom ConfigurationManager for Environment Independent Web.config I am working on a typical .net web app which is first deployed at test environment - ENV- T
and then after complete testing it is moved to Production ENV - P.
Our hosting provider will not deploy anything directly on Prod instead it is first deployed on Test and then they sync it to PROD.
Also these two environment Env-T and Env-P are totally different. So the Web.Config settings are different too.
So to deploy anything on ENV-P we have to change the web.config of ENV-T as per Env-P. And then ask the hosting vendor to sync the application and then we have to revert.
To solve this issue i thought of making the Web.config environment independent. So i wrote a custom ConfiguraitonManager class which will identify the current environment in which the application is working in and will load values accordingly.
High level Approach : We will have two Web.config one in ENV-T folder and another in ENV-P folder. Depending upon the machine name we will identify the environment. If it is ENV-T load the Web.Config values from ENV-T folder and if it is ENV-P load the values from ENV-P folder.
Here is the my class :
public static class ConfigurationManager
{
static Configuration _config;
static NameValueCollection nameValueColl;
public static NameValueCollection AppSettings
{
get
{
if (nameValueColl == null)
{
if (_config == null)
_config = LoadConfig();
nameValueColl = new NameValueCollection();
foreach (KeyValueConfigurationElement configElement in _config.AppSettings.Settings)
{
nameValueColl.Add(configElement.Key, configElement.Value);
}
}
return nameValueColl;
}
}
private static Configuration LoadConfig()
{
string basePath = string.Empty;
if (System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath != null)
{
basePath = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
}
string machineName = System.Environment.MachineName;
if (machineName.Equals("MachineA"))
{
_config = WebConfigurationManager.OpenWebConfiguration(basePath + "Test");
}
else if (machineName.ToLower().Equals("MachineB"))
{
_config = WebConfigurationManager.OpenWebConfiguration(basePath + "Prod");
}
return _config;
}
}
Now all i have to do is write
ConfigurationManager.AppSettings["KEY1"]
to read the Appsetting key "KEY1" and i get the correct value for that particular environment.
Question :
I have a key
<add key="NoOfRecords" value="50"/> .
For some reason after several hits ( in a day or two) the value i get for NoOfRecords key is 50,50,50,50,50 instead of 50.
Possible reason :
If i add a key,value say "NoOfRecords","50" to a NameValueCollection object which Already has "NoOfRecords","50" it will store the value as
"NoOfRecords","50,50".
But again how this is possible cause just before this code block i am creating a new object and also i have a null check for this nameValueColl variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JMX MBean to manage dynamic set of properties The problem might sound similar to many resolved ones, but I did not shoot this target yet.
I am about to create a MBean that will allow me to specify dynamic set of key-value pairs.
(It is easy to create a solution to specify pre-defined set of params. But what about dynamic ones)
The most relevant code snippets i could find was usage of CompositeData, TabularData
The api is next:
applyNewProperties(Properties props)
UI is next:
mbean method applyNewProperties
Parameters: props
name1 value1
name2 value2
name3 value3
.....
namen value n
The purpose is that jmx-connsole would show it in table form:
input name 1 input value 1
input name 2 input value 2
input name 3 input value 3
....
input name n input value n
A: The easiest approach would probably be to create an MXBean (which is available since Java 6) which allows you to return objects like maps (or completely custom objects) which are then mapped into Open Types like CompositeData or TabularData instances.
A: Java 7 brought us DynamicMBean - https://docs.oracle.com/javase/7/docs/api/javax/management/DynamicMBean.html
I believe that's what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: When do you call the super method in viewWillAppear, viewDidDisappear, etc...? In UIViewController's documentation, Apple suggests calling the super at some point in the implementation of viewWillAppear, viewDidAppear, viewWillDisappear, viewDidDisappear, etc... For example, the discussion on viewDidDisappear is:
You can override this method to perform additional tasks associated
with dismissing or hiding the view. If you override this method, you
must call super at some point in your implementation.
My question is does it matter when the super method is called and, if so, what is the correct time to call it? Should super be called as the first line of the method, the last line, or somewhere in the middle depending on your particular needs?
A: In viewDidAppear call super first so that your calls will override.
In viewWillDisappear it seems to be a toss up, I have researched that extensively and could not find a conclusive answer and it seems to be 50/50. I have decided to call super last in my code in the same manner we call super last in dealloc.
A: I generally will call these first within my implementation. In most cases it shouldn't matter though.
A: For UIViewController's view life cycle methods, I'd say that there is no silver bullet rule for determining when to call super, what you should be aware of is that sometimes you must call it regardless of whether it should be at the begging or at the end of the method. For instance, citing from viewDidDisappear(_:):
You can override this method to perform additional tasks associated
with dismissing or hiding the view. If you override this method, you
must call super at some point in your implementation.
However, as a general practice we usually call the super method at the beginning in methods that related to initialization, setup or configurations; On the other hand, we usually call the super method at the end in methods related to deinitialization or similar methods.
Here is an example of XCTestCase class's invocation methods:
override func setUp() {
super.setUp()
// do the setups, such as creating the mock objects...
}
override func tearDown() {
// make your objects no be nil for the next test...
super.tearDown()
}
So (as another example), when it comes to the viewWillAppear and viewDidDisappear methods:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// my code...
}
override func viewDidDisappear(_ animated: Bool) {
// my code
super.viewDidDisappear(animated)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: What is the "right" way to return a new class object from a VBA function? I am looking for the proper way to create and return a new class object in VBA.
I am familiar with the following pattern for returning a new Type variable (returned by value):
Public Type Foo
x as Integer
y as Integer
End Type
Public Function NewFoo() as Foo
NewFoo.x = 4
NewFoo.y = 2
End Function
What would be the equivalent syntax for a new Class object (returned by reference)?
Public Function NewMyClass() As MyClass
''// ...?
End Function
A: If you want to return an Object in VBA you have to set it to the Method name
Public Function NewMyClass() As MyClass
Set NewMyClass = CreateObject("Some.MyClass");
End Function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: iOS UITableView Cell loads incorrectly after scroll? I'm having 2 UITableView in a view and I added the UITableViewCellAccessoryDisclosureIndicator only at the 2nd table row 5 and row 7.
But after scrolling the 2nd table down (which row 1 disappears) and then scroll back to top (which row 1 appears), row 1 now has the UITableViewCellAccessoryDisclosureIndicator?! Did row 1 somehow become row 5 or row 7??? Below is my code for cellForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.textColor = [UIColor blueColor];
cell.detailTextLabel.textColor = [UIColor blackColor];
if (tableView == table1)
{
cell.textLabel.text = [title1 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [list1 objectAtIndex:indexPath.row];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
else if (tableView == table2)
{
cell.textLabel.text = [title2 objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [list2 objectAtIndex:indexPath.row];
if (indexPath.row == 5 || indexPath.row == 7)
{
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
else
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
}
return cell;
}
Thanks a lot!
A: UITableViewCells are reused to optimize performance. This happens in [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; You need to explicitly set any properties you would like on the cell at each call of tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
.
Something like this should resolve the issue:
if (indexPath.row == 5 || indexPath.row == 7)
{
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
else
{
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.accessoryType = UITableViewCellAccessoryNone;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: bash read loop premature EOF In the following code I expect the while loop to execute three times, once for each matching line in the input build.cfg file. This is in fact what does happen, but only if I comment out the guts of the case blocks -- i.e. the subshells starting with ( mkdir work ... and ( cd product ....
When executed as shown below, the loop executes only once (for BUILDTYPE == build)
When run with -x, it's clear that the shell loops back and executes the read but gets EOF, as there are no errors and execution continues with the setStatus line.
Clearly, something in the subshell is interfering with the outer pipeline file descriptors. Can someone explain exactly why this is happening?
egrep "^\s*$BRANCH" $ETC/build.cfg | ( while read BRANCH TARGET SVNSRC SVNTAG BUILDTYPE DISTTYPE DISTARGS
do
echo ----- $TARGET $BUILDTYPE
pushd $WORKSPACE/$BUILDUID
case $BUILDTYPE in
build)
echo ">>> BUILD"
( mkdir work
cp product/buildcontrol/buildConfig_example.xml work/defaultBuildConfig.xml
cd product
./build installer-all )
;;
tma)
echo ">>> TMA"
( cd product
./build -f ..${SVNTAG}build.xml )
;;
*)
;;
esac
popd
done )
setStatus 3
A: If anything inside the subshell eats your input, then you have several choices:
*
*Check what inside ./build wants some input and supply that input or
*cut of standard input of the subshells by using ( ... ) < /dev/null
A: Some command should be reading from stdin. Try running the commands inside the loop with stdin redirected:
./build installer-all < /dev/null
...
./build -f ..${SVNTAG}build.xml < /dev/null
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facebook FB.ui oauth dialog error I'm having problems making a dialog box to ask for a user to log into my facebook tab to enter a contest.
We're trying to use the FB.ui oauth dialog box with the following code.
FB.ui({
client_id: '12345',
method: 'oauth',
scope: 'email,user_birthday',
response_type: 'token',
redirect_uri: "https://mydomain.com/test.php" // Change this to proper address
});
When we include the redirect_uri we get the following message
API Error Code: 100 API
Error Description: Invalid parameter
Error Message: The "redirect_uri" parameter cannot be used in conjunction
with the "next" parameter, which is deprecated.
We are not using the next parameter anywhere though, so not sure why it is saying that.
When we take away the redirect_uri we get the following message.
API Error Code: 191 API
Error Description: The specified URL is not owned by the application
Error Message: redirect_uri is not owned by the application.
A: I would use the FB.login method as opposed to this given you are operating within a tab application.
Within your FB.init:
window.fbAsyncInit = function(){
FB.init({
appId: 'your_app_id',
status: true,
cookie: true,
xfbml: true,
oauth: true
});
FB.Canvas.setAutoGrow(true);
};
FB.getLoginStatus(function(response){
if(response.status == 'connected'){
callyourfunctiontoentercompetition();
}else{
FB.login(function(response){
if(response.status == 'connected'){
callyourfunctiontoentercompetition();
}else{
handlethecancelpermissions();
}
});
}
});
A: Turns out there was a few things wrong, In my app settings I had to select "Website" and put in my site's URL, this allowed me to add the "app domain" and save it. This cleared up the 191 Error. Having website not checked off your App Domain will not save. After that it was rather simple.
Here the code that I used.
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_ID',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelURL : 'http://www.your_domain.ca/channel.html', // channel.html file
oauth : true // enable OAuth 2.0
});
// This should be fired on a user initiated action
FB.ui({ method: 'oauth', perms: 'email' }, function() { callback() });
};
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
function callback() {
FB.getLoginStatus(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
//Get user information from here
});
}
});
}
</script>
A: make sure the request that u r making is coming from the same domain as the one you have registered in facebook api
A: In a tab you don't need to pass any parameter other than method and perms(or scope when Facebook changes it)
FB.getLoginStatus(function(response){
if(response.status == 'connected'){
alert("User connected");
}else{
FB.ui({
method: 'oauth',
perms: 'email,user_birthday' //change perms to scope when Facebook supports it
}, function(response){
if(response.session){
alert("User connected");
}else if(response.installed != '1'){
alert("User canceled");
}
});
}
}
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best practice for JS files being loaded? I'm faced with a dilemma. I started a project using Backbone.js and have many many JS files (views, models, controllers, templates, collections), but I didn't want to have to load them each using the script element in my HTML file.
My idea was to load one file (bootstrap.js) and within that, load all the required JavaScript files for my web app (minus 3rd party libraries, which will get loaded using <script> before bootstrap.js).
Would using the jquery getScript function work to load all the JS files from within bootstrap.js? What's best practice? I just don't want to have like 20-30 <script></script> lines in my HTML file when I don't need to - just trying to keep it nice and clean.
A: You should concatenate them all before deploying. You can also run YUI Compressor on them for speed and size optimizations.
But my favourite way is keep them separate during development, and 1 big file before deploying. Some server-side script will make this easy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: String Comparison return value (Is is used in applications that sorts characters ?) When we use strcmp(str1, str2); or str1.compare(str2); the return values are like -1, 0 and 1, for str1 < str2, str1 == str2 or str1 > str2 respectively.
The question is, is it defined like this for a specific reason?
For instance, in binary tree sorting algorithm, we push smaller values to the left child and larger values to the right child. This strcmp or string::compare functions seem to be perfect for that. However, does anyone use string matching in order to sort a tree (integer index are easier to use) ?
So, what is the actual purpose of the three return values ( -1, 0, 1). Why cant it just return 1 for true, and 0 for false?
Thanks
A: The purpose of having three return values is exactly what it seems like: to answer all questions about string comparisons at once.
Everyone has different needs. Some people sometimes need a simple less-than test; strncmp provides this. Some people need equality testing; strncmp provides this. Some people really do need to know the full relationship between two strings; strncmp provides this.
What you absolutely don't want is someone writing this:
if(strless(lhs, rhs))
{
}
else if(strequal(lhs, rhs))
{
}
That's doing two potentially expensive comparison operations. strless also knows if they were equal, because it had to get to the end of both strings to return that it was not less.
Oh, and FYI: the return values isn't -1 or +1; it's greater than zero or less than zero. Or zero if they're equal.
A: It's useful for certain cases where knowing all three cases is important. Use operator< for string when you just care about a boolean comparison.
A: It could, but then you would need multiple functions for sorting and comparison. With strcmp() returning smaller, equal or bigger, you can use them easily for comparison and for sorting.
Remember that BSTs are not the only place where you would like to compare strings. You might want to sort a name list or similar. Also, it is not uncommon to have a string as key in a tree too.
A: As others have stated, there are real purposes for comparison of strings with < > == implications. For example; fixed length numbers assigned to strings will resolve correctly; ie: "312235423" > "312235422". On some occasions this is useful.
However the feature you're asking for, true/false for solutions still works with the given return values.
if (-1)
{
// resolves true
}
else if (1)
{
// also resolves true
}
else if (0)
{
// resolves false
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Metro client consuming WCF wsdl, response object's properties not set I am attempting to consume a WCF web service from a Java client using JAX-WS and the Metro libraries. I have successfully generated the client using wsimport, and can open a session with the server, however the session token being returned by the service is not being set into Java's response object. The service then returns an error when I pass a null string into endSession which sends a message that has no body content when it expects the SessionToken.
Here is the gist of my 'main()' method
public static void main(String[] args) {
MyService service = new MyService()
MyPort port = service.getBasicHttpBinding();
EmulateRequest request = new EmulateRequest();
request.setUnimportantProperties();
SessionTokenResponse session = port.beginSessionAndEmulate(request);
port.endSession(session.getSessionToken());
}
The error I am getting is that the sessionToken in the session object is null. I have determined that the sessionToken is never set. I cannot step into the beginSession method because the port is a dynamically generated proxy.
The request I am sending is this:
<?xml version='1.0' encoding='UTF-8'?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<EmulateRequest xmlns="http://My.Namespace">
<UnimportantProperties>XXXX</UnimportantProperties>
</EmulateRequest>
</S:Body>
</S:Envelope>
And the response I receive is this:
<?xml version='1.0' encoding='UTF-8'?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<o:Security xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:mustUnderstand="1">
<u:Timestamp u:Id="_0">
<u:Created>2011-09-30T17:49:38.570Z</u:Created>
<u:Expires>2011-09-30T17:54:38.570Z</u:Expires>
</u:Timestamp>
</o:Security>
</s:Header>
<s:Body>
<SessionTokenResponse>
<Errors />
<Messages />
<Warnings />
<SessionToken>e579dd3e-34df-4396-ae42-1ebf03c9f301</SessionToken>
</SessionTokenResponse>
</s:Body>
</s:Envelope>
In the WSDL, my SessionTokenResponse object is defined as the following:
xmlns:tns="http:\\MyNamespace"
<wsdl:types>
<xs:complexType name="SessionTokenResponse">
<xs:complexContent>
<xs:extension base="Response">
<xs:sequence>
<xs:element name="SessionToken" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Response">
<xs:sequence>
<xs:element name="Errors">
<xs:complexType>
<xs:sequence>
<xs:element name="Error" minOccurs="0" maxOccurs="unbounded" type="Error"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Messages">
<xs:complexType>
<xs:sequence>
<xs:element name="Message" minOccurs="0" maxOccurs="unbounded" type="Message"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Warnings">
<xs:complexType>
<xs:sequence>
<xs:element name="Warning" minOccurs="0" maxOccurs="unbounded" type="Warning"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</wsdl:types>
<wsdl:message name="EmulateRequestMessage">
<wsdl:part name="EmulateRequest" element="tns:EmulateRequest"/>
</wsdl:message>
<wsdl:message name="SessionTokenResponseMessage">
<wsdl:part name="SessionTokenResponse" element="tns:SessionTokenResponse"/>
</wsdl:message>
<wsdl:portType msc:usingSession="false" name="MyPortName">
<wsdl:operation name="BeginSessionAndEmulate">
<wsdl:input wsaw:Action="http://MyNamespace/BeginSessionAndEmulate" name="EmulateRequestMessage" message="tns:EmulateRequestMessage"/>
<wsdl:output wsaw:Action="http://MyNamespace/BeginSessionAndEmulateResponse" name="SessionTokenResponseMessage" message="tns:SessionTokenResponseMessage"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="BasicHttpBinding" type="tns:MyBindingName">
<wsdl:operation name="BeginSessionAndEmulate">
<wsp:PolicyReference URI="#BasicHttpBinding_policy"/>
<wsdl:input name="EmulateRequestMessage">
<soap:body use="literal" parts="EmulateRequest"/>
</wsdl:input>
<wsdl:output name="SessionTokenResponseMessage">
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="MyService">
<wsdl:port name="BasicHttpBinding" binding="tns:BasicHttpBinding">
<soap:address location="https://MyServiceLocation"/>
</wsdl:port>
</wsdl:service>
/** Generated by WsImport *************************************/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SessionTokenResponse", propOrder = {
"sessionToken"
})
public class SessionTokenResponse
extends Response
{
@XmlElement(name = "SessionToken")
public String sessionToken;
public String getSessionToken() {
return sessionToken;
}
public void setSessionToken(String value) {
this.sessionToken = value;
}
}
There are of course other operations, but I have posted the relevant operation and types only.
Does anyone have experience with Metro enough to tell me which dumb setting I forgot?
Thanks
A: Fixed, the web service was not providing namespace information in the response. When the response looks like the following then it works fine:
<SessionTokenResponse xmlns="http://My.Namespace">
<Errors />
<Messages />
<Warnings />
<SessionToken>e579dd3e-34df-4396-ae42-1ebf03c9f301</SessionToken>
</SessionTokenResponse>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Telerik RadEditor HTTP POST VALUE not being updated (ASP.NET Web Forms) I am currently writing a ContentManager in ASP.NET. I have a preview button which uses jQuery to post the form data to new window and shows how a page would look without saving it to the database and effecting the live site. Although its been somewhat of a hassle to get ASP.NET to post directly to the page I am trying to preview, I've finally worked it all out using a series of jQuery code. It worked beautifully, I loaded all the post values into the page using Request.Form and displayed them on the page. Unfortunately for some reason the Telerik RadEditor's I was using were posting me the values they had been assigned on the C# Page_Load event and did not reflect the text changes I made. If anyone could help me out that would be great.
function showPreview()
{
url = "<%= (SiteManager.GetSite()).Url + this.Filename %>?preview=true";
var specs = "width=1010,height=700,location=0,resizeable=1,status=1,scrollbars=1";
window.open(url, 'PagePreview', specs).moveTo(25, 25);
$("#__VIEWSTATE").remove();
$("#__EVENTTARGET").remove();
$("#__EVENTARGUMENT").remove();
$("#aspnetForm").removeAttr("action");
$("#aspnetForm").attr("target","PagePreview");
$("#aspnetForm").attr("action", url);
$("#aspnetForm").submit();
}
Here is all the post data I am receiving from the tererik RADEDITOR ::
[ctl00_MainContentPlaceHolder_SideContentRadEditor_dialogOpener_Window_ClientState] => [ctl00_MainContentPlaceHolder_SideContentRadEditor_dialogOpener_ClientState] => [ctl00$MainContentPlaceHolder$SideContentRadEditor] => [ctl00_MainContentPlaceHolder_SideContentRadEditor_ClientState] => [ctl00_MainContentPlaceHolder_ContentRadEditor_dialogOpener_Window_ClientState] => [ctl00_MainContentPlaceHolder_ContentRadEditor_dialogOpener_ClientState] => [ctl00$MainContentPlaceHolder$ContentRadEditor] => %3cp%3eTestPageContent%3c/p%3e
This is the html value of the text editor (shown above) %3cp%3eTestPageContent%3c/p%3e
This is the value in the RadEditor that was loaded during the Page_Load event.
I changed the value to "Test". But it was not sent over the POST Request, it sent what was loaded in the page load.
A: The editor content area is separate from the textarea used to submit the content during a POST request. The editor will automatically try to save the content in the hidden textarea when the form is submitted, but in your case no event is fired because it happens programmatically (i.e. you call .submit()). You will need to tell the editor to save its content manually before you do the postback. The code is pretty basic - get a reference to the editor and call .saveContent():
//Grab a reference to the editor
var editor = $find("<%=theEditor.ClientID%>");
//Store the content in the hidden textarea so it can be posted to the server
editor.saveContent();
A: One solution would be to grab the current HTML in the editor in your showPreview method and pass that manually. To do that, add a hidden input element in your page to hold the HTML content:
<input type="hidden" id="htmlContent" name="htmlContent" />
Then, you can set that intput's value in showPreview like this:
function showPreview()
{
url = "<%= (SiteManager.GetSite()).Url + this.Filename %>?preview=true";
var specs = "width=1010,height=700,location=0,resizeable=1,status=1,scrollbars=1";
window.open(url, 'PagePreview', specs).moveTo(25, 25);
$("#__VIEWSTATE").remove();
$("#__EVENTTARGET").remove();
$("#__EVENTARGUMENT").remove();
// *** Begin New Code ***
//Grab a reference to the editor
var editor = $find("<%=theEditor.ClientID%>");
//Get the current HTML content
var html = editor.get_html()
//Put that HTML into this input so it will get posted
$("#htmlContent").val(html);
// *** End New Code ***
$("#aspnetForm").removeAttr("action");
$("#aspnetForm").attr("target","PagePreview");
$("#aspnetForm").attr("action", url);
$("#aspnetForm").submit();
}
Then when you want to get the HTML during the postback you can just use Request.Form["htmlContent"]
One caveat: Since you'll be posting raw HTML, ASP.NET's Request Validation might cause problems. One of the major purposes of that validation is to make sure that HTML content doesn't get posted back to the server - the very thing you're trying to accomplish. You could of course turn the validation off (see the link above) but the validation is there for a reason. Another solution might be to do some basic encoding of the HTML before you post it. If you just replace all less-than symbol (<) with something before posting it, ASP.Net will be happy. Then you just need to 'un-replace' it during the postback.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: PHP Countdown - How Do i use Else If for hours when there is less than 1 day left I need some php help
here is my code
<?php
// Define your target date here
$targetYear = get_theme_option('episode_countdown_year');
$targetMonth = get_theme_option('episode_countdown_month');
$targetDay = get_theme_option('episode_countdown_day');
$targetHour = 21;
$targetMinute= 00;
$targetSecond= 00;
date_default_timezone_set ( "America/New_York" );
// Sets the default time zone, in this case GMT -08
$dateFormat = ( "Y-m-d H:i:s" );
// Check the PHP Documentation for date uses.
$targetDate = mktime (
$targetHour,
$targetMinute,
$targetSecond,
$targetMonth,
$targetDay,
$targetYear
);
// Sets up our timer
$actualDate = time();
// Gets the actual date
$secondsDiff = $targetDate - $actualDate;
// Finds the difference between the target date and the actual date
// These do some simple arithmatic to get days, hours, and minutes out of seconds.
$remainingDay = floor ( $secondsDiff / 60 / 60 / 24);
$remainingHour = floor ( ( $secondsDiff - ( $remainingDay
*60 * 60 * 24) ) / 60 / 60 );
$remainingMinutes = floor ( ( $secondsDiff - ( $remainingDay
*60 * 60 * 24) - ( $remainingHour * 60 * 60 ) ) / 60 );
$remainingSeconds = floor ( ( $secondsDiff - ( $remainingDay
*60 * 60 * 24) - ( $remainingHour * 60 * 60 ) ) -
( $remainingMinutes * 60 ) );
$targetDateDisplay = date($dateFormat,$targetDate);
$actualDateDisplay = date($dateFormat,$actualDate);
// Sets up displays of actual and target
?>
<?php if( $targetDate > $actualDate ) {?>
description: '<?php echo $remainingDay; ?> Day(s) / <?php echo $remainingHour; ?> Hour(s) / <?php echo $remainingMinutes; ?> Minute(s) Left..',
picture: '<?php echo $my_url ?>/cache/image-<?php echo $remainingDay; ?>-d.png'
<?php } else { ?>
description: 'Now Showing!',
picture: '<?php echo $my_url ?>/image-now.php'
<?php } ?>
my question is
How can I add the else if code, if there is less than 1 day left
so I can hide the remainingDay, so only the hours and minutes are showing
I tried this but that didnt work
<?php } else if( $remainingDay < $actualDate ) {?>
A: No need to have <?php on the line right after ?>, just keep it open. But if you just want to have code for less than one day, try: (sorry i edited so much)
<?php if( $targetDate > $actualDate ) {
if($remainingHour < 24){ //main change here..
//have < 1 day code here
} else {
echo "description: '$remainingDay Day(s) / $remainingHour Hour(s) / $remainingMinutes Minute(s) Left..'
picture: '$my_url /cache/image-$remainingDay-d.png'";
} else { ?>
description: 'Now Showing!',
picture: '<?php echo $my_url ?>/image-now.php'
<?php } ?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: C++ Template Instantiation - Why must mine always be explicit, unlike STL? Any one of my C++ projects will generate a linker error unless I include an explicit template instantiation for every templated class/method/function I author and use.
STL classes seem to have no such problem.
Is there some simple code of conduct (pun intended) I can adhere to which allows deferred instantiation like that of STL?
Thanks for listening.
A: For templates you need to put all the template code and methods into headers rather than source files. The standard library does this.
A: You should put most parts of a template within the header file. This applies equally to template classes as well as template functions within normal classes.
The exception that you should know to this rule is that when you specialize a template, you need to put the specialization in the implementation/.cpp file because a specialization is a concrete type. The actual template definitions on the other hand will need to be run through multiple times, one for each template parameter type used with the template - so they must go in the header file (they're not concrete type-wise).
e.g. put:
template typename<T> foo(T val) { std::cerr << "DEFAULT"; }
in the header file and its specialization for an int:
template<> foo<int>(int val) { std::cerr << "INT"; }
in the cpp file because the int version is a concrete, fully defined function whereas the T version is a template definition which will be used many time to generate many concrete functions.
A: Most of the time a template class is defined completely in the header file. This allows the compiler to generate the body of code on the fly if it hasn't already come across the combination of function and template parameters that you're using.
You can still use a template with separate header and implementation files, but it's much less convenient. As you've discovered, you must anticipate each template parameter and put that combination in the implementation file, so that the compiler can generate the necessary code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python object hierarchy, and REST resources? I am currently running into an "architectural" problem in my Python app (using Twisted) that uses a REST api, and I am looking for feedback.
Warning ! long post ahead!
Lets assume the following Object hiearchy:
class Device(object):
def __init__():
self._driver=Driver()
self._status=Status()
self._tasks=TaskManager()
def __getattr__(self, attr_name):
if hasattr(self._tasks, attr_name):
return getattr(self._tasks, attr_name)
else:
raise AttributeError(attr_name)
class Driver(object):
def __init__(self):
self._status=DriverStatus()
def connect(self):
"""some code here"""
def disconnect(self):
"""some code here"""
class DriverStatus(object):
def __init__(self):
self._isConnected=False
self._isPluggedIn=False
I also have a rather deep object hiearchy (the above elements are only a sub part of it) So, right now this gives me following resources, in the rest api (i know, rest isn't about url hierarchy, but media types, but this is for simplicity's sake):
/rest/environments
/rest/environments/{id}
/rest/environments/{id}/devices/
/rest/environments/{id}/devices/{deviceId}
/rest/environments/{id}/devices/{deviceId}/driver
/rest/environments/{id}/devices/{deviceId}/driver/driverstatus
I switched a few months back from a "dirty" soap type Api to REST, but I am becoming unsure about how to handle what seems like added complexity:
*
*Proliferation of REST resources/media types : for example instead of having just a Device resource I now have all these resources:
*
*Device
*DeviceStatus
*Driver
*DriverStatus
While these all make sense from a Resfull point of view, is it normal to have a lot of sub resources that each map to a separate python class ?
*Mapping a method rich application core to a Rest-Full api : in Rest resources should be nouns, not verbs : are there good rules /tips to inteligently define a set of resources from a set of methods ? (The most comprehensive example I found so far seems to be this article)
*Api logic influencing application structure: should an application's API logic at least partially guide some of its internal logic, or is it good practice to apply separation of concerns ? Ie , should I have an intermediate layer of "resource" objects that have the job of communicating with the application core , but that do not map one to one to the core's classes ?
*How would one correctly handle the following in a rest-full way : I need to be able to display a list of available driver types (ie class names, not Driver instance) in the client : would this mean creating yet another resource like "DriverTypes" ?
These are rather long winded questions, so thanks for your patience, and any pointers, feedback and criticism is more than welcome !
To S.Lott:
*
*By "too fragmented resources" what i meant was, lots of different sub resources that basically still apply to the same server side entity
*For The "connection" : So that would be a modified version of the "DriverStatus" resource then ? I consider the connection to be always existing, hence the use of "PUT" , but would that be bad thing considering "PUT" should be idempotent ?
*You are right about "stopping coding and rethinking", that is the reason I asked all these questions and putting things down, on paper to get a better overview.
-The thing is, right now the basic "real world objects" as you put them make sense to me as rest resources /collections of resources, and they are correctly manipulated via POST, GET, UPDATE, DELETE , but I am having a hard time getting my head around the Rest approach for things that I do not instinctively view as "Resources".
A: Rule 1. REST is about objects. Not methods.
The REST "resources" have become too fragmented
False. Always false. REST resources are independent. They can't be "too" fragmented.
instead of having just a Device resource I now have all these resources:
Device DeviceStatus Driver DriverStatus
While these all make sense
from a [RESTful] point of view, is it normal to have a lot of sub
resources that each map to a separate python class ?
Actually, they don't make sense. Hence your question.
Device is a thing. /rest/environments/{id}/devices/{deviceId}
It has status. You should consider providing the status and the device information together as a single composite document that describes a device.
Just because your relational database is normalized does not mean your RESTful objects need to be precisely as normalized as your database. While it's simpler (and many frameworks make it very, very simple to do this) it may not be meaningful.
consider the connection to be always existing, hence the use of "PUT"
, but would that be bad thing considering "PUT" should be idempotent ?
Connections do not always exist. They may come and go.
While a relational database may have a many-to-many association table which you can UPDATE, that's a peculiar special case that doesn't really make much sense outside the world of DBA's.
The connection between two RESTful things is rarely a separate thing. It's an attribute of each of the RESTful things.
It's perfectly unclear what this "connection" thing is. You talk vaguely about it, but provide no details.
Lacking any usable facts, I'll guess that you're connecting devices to drivers and there's some kind of [Device]<-[Driver Status]->[Driver] relationship. The connection from device to driver can be a separate RESTful resource.
It can just as easily be an attribute of Device or Driver that does not actually have a separate, visible, RESTful resource.
[Again. Some frameworks like Django-Piston make it trivial to simple expose the underlying classes. This may not always be appropriate, however.]
are there good rules /tips to inteligently define a set of resources from a set of methods ?
Yes. Don't do it. Resources aren't methods. Pretty much that's that.
If you have a lot of methods -- outside CRUD -- then you may have a data model issue. You may have too few classes of things expressed in your relational model and too many stateful updates of things.
Stateful objects are not inherently evil, but they need to be examined critically. In some cases, a PUT to change status of an object perhaps should have been a POST to add to the history of an object. The "current" state is the last thing POSTed.
Also.
You don't have to trivialize each resource as a class of things. You can have resources which are collections. You can POST a fairly complex document to a composite (properly a Facade) "resource". That complex document can imply several CRUD operations in the database.
You're wandering away from simple RESTful. Your question remains intentionally murky. "method rich application core" doesn't mean much. Without concrete examples, it's impossible to imagine.
Api logic influencing application structure
If these are somehow different, you're probably creating needless, no-value complexity.
is it good practice to apply separation of concerns ?
Always. Why ask?
a lot of this seems to come from my confusion about how to map a rather method rich api to a Rest-Full one , where resources should be nouns, not verbs : so when is it wise to consider an element a rest "resource"?
A resource is defined by your problem domain. It's usually something tangible. The methods (as in "method-rich API" are usually irrelevant. They're CRUD (Create, Retrieve, Update, Delete) operations. If you have something that's not essentially CRUD, you have to STOP coding. STOP writing code, and rethink the API to make it CRUD-like.
CRUD - Create-Retrieve-Update-Delete maps to REST's POST-GET-PUT-DELETE. If you can't recast your problem domain into those terms, stop coding. Stop coding until you get to CRUD rules.
i need to be able to display a list of available driver types (ie class names, not Driver instance) in the client : would this mean creating yet another resource like "DriverTypes" ?
Correct. They're already part of your problem domain. You already have this class defined. You're just making it available through REST.
Here's the point. The problem domain has real-world objects. You have class definitions. They're tangible things. REST transfers the state of those tangible things.
Your software may have intangible things like "associations" or "links" or "connections" other junk that's part of the software solution. This junk doesn't matter very much. It's implementation detail. Not real-world things.
An "association" is always visible from both of the two real-world RESTful resources. One resource may have an foreign-key like reference that allows the client to do a RESTful fetch of another, related object. Or a resource may have a collection of other, related objects, and a single GET retrieves an object and a collection of related objects.
Either way, the real-world RESTful resources are what's available. The relationship is merely implied. Even if it's a physical many-to-many database table -- that doesn't mean it must be exposed. [Again. Some frameworks make it trivially easy to expose everything. This isn't always good.]
A: You can represent the path portion /rest with a Site object, but environments in the path must be a Resource. From there you have to handle the hierarchy yourself in the render_* methods of environments. The request object you get will have a postpath attribute that gives you the remainder of the path (i.e. after /rest/environments). You'll have to parse out the id, detect whether or not devices is given in the path, and if so pass the remainder of the path (and the request) down to your devices collection. Unfortunately, Twisted will not handle this decision for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I set the GridView RowHeaderColumn to a TemplateField? I have a standard ASP.NET GridView and I'd like the first column (a emplateField) to be rendered as <th>, or in ASP.NET terms, I'd like to set it to the GridView RowHeaderColumn property. But that property is looking for the name of a DataItem (from a BoundColumn).
How can I render my TemplateField with <th> tags?
A: Finally found a workaround for this. I am not sure if this code has anything to do with good ASP.NET practices, but it does the trick:
public class FirstColumnHeaderGridView : GridView
{
protected override void InitializeRow(GridViewRow row, DataControlField[] fields)
{
DataControlFieldCell cell = new DataControlFieldHeaderCell(fields[0]);
DataControlCellType header = DataControlCellType.DataCell;
fields[0].InitializeCell(cell, header, row.RowState, row.RowIndex);
row.Cells.Add(cell);
DataControlField[] newFields = new DataControlField[fields.Length - 1];
for (int i = 1; i < fields.Length; i++)
{
newFields[i - 1] = fields[i];
}
base.InitializeRow(row, newFields);
}
}
Let me explain what is going on here. We are creating a special type of GridView, that will render its first column using <th> tags no matter how this column is created. For this we are overriding the InitializeRow method. This method basically configures cells for the row. We are handling the first cell, and let standard GridView take care of the rest.
The configuration we are applying to the cell is fully taken from the GridView implementation and is enough for the cell to be rendered with <th> tag instead of <td>.
After that workaround the usage is absolutely standard - register our class as a server control and use it as usual GridView:
<%@ Register Assembly="WebApplication1" Namespace="WebApplication1" TagPrefix="wa1" %>
...
<wa1:FirstColumnHeaderGridView ID="Grid1" runat="server" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
Will be inside th
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
Will be inside td
</ItemTemplate>
</asp:TemplateField>
</Columns>
</wa1:FirstColumnHeaderGridView>
A: Is this what you mean?
<Columns>
<asp:TemplateField HeaderText="Código" ItemStyle-Width="9%">
<HeaderTemplate>
<asp:Label runat="server" Text="CodigoSAP"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblCodigoSAP" Text='<%# Bind("CodigoSAP") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
I'm almost sure I'm getting the wrong idea, what do you say?
A: Late to the game, but we needed to set scope="row" in a middle column, not the first. To make it generic, in a derived GridView class I added the following property (similar to the GridView's built-in RowHeaderColumn property):
public int? RowHeaderColumnIndex
{
get { return (int?)ViewState["RowHeaderColumnIndex"]; }
set { ViewState["RowHeaderColumnIndex"] = value; }
}
Then set the scope:
protected override void OnRowCreated(GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && RowHeaderColumnIndex.HasValue)
{
e.Row.Cells[RowHeaderColumnIndex.Value].Attributes["scope"] = "row";
}
}
When you place your custom grid just set RowHeaderColumnIndex="0" for the first column, "1" for the 2nd column and so on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Script for adding an image at the very end of the last paragraph for multiple blocks For each article on a page, I would like to insert an image at the very end of the last paragraph. My HTML looks like this:
<div class="storycontent">
<p>One</p>
<p>Two</p>
<p>Three</p>
</div>
There may be several of those sections or only one. There is also an unknown number of <p></p> tags.
What I would like to do is insert an <img /> at the very end of the last <p> before the closing tag.
Here is what I have so far, but it is only appending the image tag to the very last <p> on the page, and not the last one in the storycontent <div>
jQuery('.storycontent').each(
function(){
jQuery(this).last('p').append(img);
//img is a var which contains an Image() element;
}
);
A: You're misusing the last() method, which doesn't take any argument and returns the last matched element. You should write something like:
jQuery(this).find("p").last().append($(img).clone());
Or:
jQuery("p", this).last().append($(img).clone());
Or even:
jQuery("p:last", this).append($(img).clone());
Also note that you cannot add the same element to the DOM multiple times, since the element will be moved into its new parent if it's already part of the DOM. A simple solution is to clone() it, as the code above does.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regex - Replace the first comma and last comma from the csv list but leave the middle one I'm new to regex... but here goes.
So, Let's say I have this data.
13579,24680,13579,24680
13579,24680,13579,24680
13579,24680,13579,24680
13579,24680,13579,24680
So what I want is for it to replace the first comma, and the last comma with nothing. So I just end up with:
1357924680,1357924680
1357924680,1357924680
1357924680,1357924680
1357924680,1357924680
After it goes through.
I was thinking of a pattern somewhere along ^([^,]+),
But as you can tell, this doesn't work. Any suggestions or should I rethink what I use to do this?
A: Try something like this:
regex: ^([^,]+),([^,]+),([^,]+),([^,]+)$
options: multiline
replace $1$2,$3$4
A: This works in perl:
$match =~ s/^(.*?),(.*),(.*?)$/$1$2$3/;
A: Try
^(\d+),(\d+),(\d+),(\d+)
replace with
$1$2,$3$4
See it here on Regexr
Dependent on the way you access your text, you need to use the multiline modifier.
A: Ruby example
"13579,24680,13579,24680".gsub(/(.*?),(.*),(.*?)/,'\1\2\3')
=> "1357924680,1357924680"
and another example without using regex because it's always worth a try
"%s%s,%s%s" % "13579,24680,13579,24680".split(',')
=> "1357924680,1357924680"
A: kent$ echo "13579,24680,13579,24680
"|sed -r 's#(^[0-9]+),(.*?),([0-9]+)$#\1\2\3#'
1357924680,1357924680
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use Friendly_Id w/ STI? I'm pretty stumped about how to setup the friendly_id (4.0.0.beta12) gem to work properly with STI models.
Here is the model setup:
class Car < ActiveRecord::Base
extend FriendlyId
friendly_id :name, :use => :slugged
end
class Ford < Car
end
class Toyota < Car
end
If i try something like this:
Toyota.create!(name: "test")
Ford.create!(name: "test")
The resulting error is:
(0.1ms) BEGIN
Ford Load (0.2ms) SELECT `cars`.* FROM `cars` WHERE `cars`.`type` IN ('Ford') AND (`slug` = 'test' OR `slug` LIKE 'test--%') AND (id <> 7606) ORDER BY LENGTH(`slug`) DESC, `slug` DESC LIMIT 1
(0.5ms) UPDATE `cars` SET `slug` = 'test', `updated_at` = '2011-09-30 15:06:08' WHERE `cars`.`type` IN ('Ford') AND `cars`.`id` = 7606
(0.1ms) ROLLBACK
ActiveRecord::RecordNotUnique: Mysql2::Error: Duplicate entry 'test' for key 2: UPDATE `cars` SET `slug` = 'test', `updated_at` = '2011-09-30 15:06:08' WHERE `cars`.`type` IN ('Ford') AND `cars`.`id` = 7606
The problem is that friendly_id's select looks for the slug w/ type set to 'Ford' and comes up clean (as the slug 'test' already belongs to a record for type 'Toyota'). Assuming that no slug with the name 'test' exists, it then tries to save the record with the slug 'test' and everything goes to hell.
Any ideas?
Thank you!
A: Maybe you could add a timestamp to the id, it would stop conflicts. Although it isn't the ideal solution.
A: This post explains how to do it:
http://ruby.zigzo.com/2011/10/08/how-to-use-the-friendly_id-gem-w-sti-models/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Wrap child elements into 2 divs equally I have a HTML code like this:
<li>one</li>
<li>two</li>
<li>era</li>
<li>jeu</li>
<li>iuu</li>
<li>iij</li>
<li>emu</li>
<li>our</li>
I need to wrap them into 2 element equally (or like 5:6 if total is 11), like this:
<ul>
<li>one</li>
<li>two</li>
<li>era</li>
<li>jeu</li>
</ul>
<ul>
<li>iuu</li>
<li>iij</li>
<li>emu</li>
<li>our</li>
</ul>
This should work on any amount of <li>'s. Can you suggest an elegant solution with jQuery?
A: var $li = $('li'),
half = Math.floor($li.length/2);
$li.filter(function(i){ return i < half; }).wrapAll('<ul>');
$li.filter(function(i){ return i >= half; }).wrapAll('<ul>');
Demo
A: You can divide by 2 and then round down or up (depending on whether you want 4:5 or 5:4). After doing that, replace the lis with a ul containing the lis (first clone them, because otherwise the lis would have been moved around, and would not be able to be replaced because their original position is lost).
http://jsfiddle.net/TBhYX/
var li = $('li'),
amount = li.length,
left = amount / 2 | 0, // '| 0' rounds down
right = amount - left;
var leftElems = li.slice(0, left);
leftElems.replaceWith($('<ul>').append(leftElems.clone(true)));
var rightElems = li.slice(left, amount);
rightElems.replaceWith($('<ul>').append(rightElems.clone(true)));
You could also generalize these last two parts: http://jsfiddle.net/TBhYX/1/.
var li = $('li'),
amount = li.length,
left = amount / 2 | 0,
right = amount - left;
$.each([ [ 0, left],
[left, amount] ], function(i, v) {
var elems = li.slice.apply(li, v);
elems.replaceWith(
$('<ul>').append(elems.clone(true))
);
});
A: First you can use .each from jQuery and count them...
http://api.jquery.com/jQuery.each/
Then create the 2 ul, and then take only half of them and put them in the first ul. and then in the second...
Example code:
<div class="take_those">
<li>One</li>
<li>Ein</li>
</div>
<ul class="first">
</ul>
<ul class="second">
</ul>
See what the elements are like
$(document).ready(function() {
var total_items = 0;
total_items = $(".take_those li").length;
$(".take_those li").each(function(i) {
if(i<(total_items/2)) {
$(".first").append("<li>"+$(this).html()+"</li>");
} else {
$(".second").append("<li>"+$(this).html()+"</li>");
}
});
});
Or something like that...
Did this help you?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Trouble with click toggle animation I am having some issues with this jQuery nav I am building. When you click "Find zip", the zip code finder is supposed to fall down to 175px, then when clicked again, fly back up to 90px.
This set used work perfectly the first time, however it got stuck at 90px shortly there after. After a little playing around, it plays both animation consecutively, no break, no click. Does anyone know what I am doing wrong? Thanks in advance for the help.
$(document).ready(function() {
$('a#find-zip').click(function(event) {
$("div#zip-drop").toggle().stop().animate( { top: 180 }, { duration: 'slow', easing: 'easeOutBack'})
$("div#zip-drop").toggle().stop().animate( { top: 90 }, { duration: 'slow', easing: 'easeOutBack'})
});
A: $(document).ready(function() {
var toggle = true;
$('a#find-zip').click(function(event) {
if (toggle === true){
$("div#zip-drop").animate( { top: 180 }, { duration: 'slow', easing: 'easeOutBack'});
toggle = false;
}
else{
$("div#zip-drop").animate( { top: 90 }, { duration: 'slow', easing: 'easeOutBack'});
toggle = true;
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c# Thread Contention with SqlDataReaders and SqlDataAdapters We notice that inside of our .Net application we have contention when it comes to using SqlDataReader. While we understand that SqlDataReader is not ThreadSafe, it should scale. The following code is a simple example to show that we cannot scale our application because there is contention on the SqlDataReader GetValue method. We are not bound by CPU, Disk, or Network; Just the internal contention on the SqlDataReader. We can run the application 10 times with 1 thread and it scales linearly, but 10 threads in 1 app does not scale. Any thoughts on how to scale reading from SQL Server in a single c# application?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.Globalization;
namespace ThreadAndSQLTester
{
class Host
{
/// <summary>
/// Gets or sets the receive workers.
/// </summary>
/// <value>The receive workers.</value>
internal List<Worker> Workers { get; set; }
/// <summary>
/// Gets or sets the receive threads.
/// </summary>
/// <value>The receive threads.</value>
internal List<Thread> Threads { get; set; }
public int NumberOfThreads { get; set; }
public int Sleep { get; set; }
public int MinutesToRun { get; set; }
public bool IsRunning { get; set; }
private System.Timers.Timer runTime;
private object lockVar = new object();
public Host()
{
Init(1, 0, 0);
}
public Host(int numberOfThreads, int sleep, int minutesToRun)
{
Init(numberOfThreads, sleep, minutesToRun);
}
private void Init(int numberOfThreads, int sleep, int minutesToRun)
{
this.Workers = new List<Worker>();
this.Threads = new List<Thread>();
this.NumberOfThreads = numberOfThreads;
this.Sleep = sleep;
this.MinutesToRun = minutesToRun;
SetUpTimer();
}
private void SetUpTimer()
{
if (this.MinutesToRun > 0)
{
this.runTime = new System.Timers.Timer();
this.runTime.Interval = TimeSpan.FromMinutes(this.MinutesToRun).TotalMilliseconds;
this.runTime.Elapsed += new System.Timers.ElapsedEventHandler(runTime_Elapsed);
this.runTime.Start();
}
}
void runTime_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
this.runTime.Stop();
this.Stop();
this.IsRunning = false;
}
public void Start()
{
this.IsRunning = true;
Random r = new Random(DateTime.Now.Millisecond);
for (int i = 0; i < this.NumberOfThreads; i++)
{
string threadPoolId = Math.Ceiling(r.NextDouble() * 10).ToString();
Worker worker = new Worker("-" + threadPoolId); //i.ToString());
worker.Sleep = this.Sleep;
this.Workers.Add(worker);
Thread thread = new Thread(worker.Work);
worker.Name = string.Format("WorkerThread-{0}", i);
thread.Name = worker.Name;
this.Threads.Add(thread);
thread.Start();
Debug.WriteLine(string.Format(CultureInfo.InvariantCulture, "Started new Worker Thread. Total active: {0}", i + 1));
}
}
public void Stop()
{
if (this.Workers != null)
{
lock (lockVar)
{
for (int i = 0; i < this.Workers.Count; i++)
{
//Thread thread = this.Threads[i];
//thread.Interrupt();
this.Workers[i].IsEnabled = false;
}
for (int i = this.Workers.Count - 1; i >= 0; i--)
{
Worker worker = this.Workers[i];
while (worker.IsRunning)
{
Thread.Sleep(32);
}
}
foreach (Thread thread in this.Threads)
{
thread.Abort();
}
this.Workers.Clear();
this.Threads.Clear();
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Threading;
using System.ComponentModel;
using System.Data.OleDb;
namespace ThreadAndSQLTester
{
class Worker
{
public bool IsEnabled { get; set; }
public bool IsRunning { get; set; }
public string Name { get; set; }
public int Sleep { get; set; }
private string dataCnString { get; set; }
private string logCnString { get; set; }
private List<Log> Logs { get; set; }
public Worker(string threadPoolId)
{
this.Logs = new List<Log>();
SqlConnectionStringBuilder cnBldr = new SqlConnectionStringBuilder();
cnBldr.DataSource = @"trgcrmqa3";
cnBldr.InitialCatalog = "Scratch";
cnBldr.IntegratedSecurity = true;
cnBldr.MultipleActiveResultSets = true;
cnBldr.Pooling = true;
dataCnString = GetConnectionStringWithWorkStationId(cnBldr.ToString(), threadPoolId);
cnBldr = new SqlConnectionStringBuilder();
cnBldr.DataSource = @"trgcrmqa3";
cnBldr.InitialCatalog = "Scratch";
cnBldr.IntegratedSecurity = true;
logCnString = GetConnectionStringWithWorkStationId(cnBldr.ToString(), string.Empty);
IsEnabled = true;
}
private string machineName { get; set; }
private string GetConnectionStringWithWorkStationId(string connectionString, string connectionPoolToken)
{
if (string.IsNullOrEmpty(machineName)) machineName = Environment.MachineName;
SqlConnectionStringBuilder cnbdlr;
try
{
cnbdlr = new SqlConnectionStringBuilder(connectionString);
}
catch
{
throw new ArgumentException("connection string was an invalid format");
}
cnbdlr.WorkstationID = machineName + connectionPoolToken;
return cnbdlr.ConnectionString;
}
public void Work()
{
int i = 0;
while (this.IsEnabled)
{
this.IsRunning = true;
try
{
Log log = new Log();
log.WorkItemId = Guid.NewGuid();
log.StartTime = DateTime.Now;
List<object> lst = new List<object>();
using (SqlConnection cn = new SqlConnection(this.dataCnString))
{
try
{
cn.Open();
using (SqlCommand cmd = new SqlCommand("Analysis.spSelectTestData", cn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
using (SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) // DBHelper.ExecuteReader(cn, cmd))
{
while (dr.Read())
{
CreateClaimHeader2(dr, lst);
}
dr.Close();
}
cmd.Cancel();
}
}
catch { }
finally
{
cn.Close();
}
}
log.StopTime = DateTime.Now;
log.RouteName = this.Name;
log.HostName = this.machineName;
this.Logs.Add(log);
i++;
if (i > 1000)
{
Console.WriteLine(string.Format("Thread: {0} executed {1} items.", this.Name, i));
i = 0;
}
if (this.Sleep > 0) Thread.Sleep(this.Sleep);
}
catch { }
}
this.LogMessages();
this.IsRunning = false;
}
private void CreateClaimHeader2(IDataReader reader, List<object> lst)
{
lst.Add(reader["ClaimHeaderID"]);
lst.Add(reader["ClientCode"]);
lst.Add(reader["MemberID"]);
lst.Add(reader["ProviderID"]);
lst.Add(reader["ClaimNumber"]);
lst.Add(reader["PatientAcctNumber"]);
lst.Add(reader["Source"]);
lst.Add(reader["SourceID"]);
lst.Add(reader["TotalPayAmount"]);
lst.Add(reader["TotalBillAmount"]);
lst.Add(reader["FirstDateOfService"]);
lst.Add(reader["LastDateOfService"]);
lst.Add(reader["MaxStartDateOfService"]);
lst.Add(reader["MaxValidStartDateOfService"]);
lst.Add(reader["LastUpdated"]);
lst.Add(reader["UpdatedBy"]);
}
/// <summary>
/// Toes the data table.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">The data.</param>
/// <returns></returns>
public DataTable ToDataTable<T>(IEnumerable<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
if (props == null) throw new ArgumentNullException("Table properties.");
if (data == null) throw new ArgumentNullException("data");
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item) ?? DBNull.Value;
}
table.Rows.Add(values);
}
return table;
}
private void LogMessages()
{
using (SqlConnection cn = new SqlConnection(this.logCnString))
{
try
{
cn.Open();
DataTable dt = ToDataTable(this.Logs);
Console.WriteLine(string.Format("Logging {0} records for Thread: {1}", this.Logs.Count, this.Name));
using (SqlCommand cmd = new SqlCommand("Analysis.spInsertWorkItemRouteLog", cn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@dt", dt);
cmd.ExecuteNonQuery();
}
Console.WriteLine(string.Format("Logged {0} records for Thread: {1}", this.Logs.Count, this.Name));
}
finally
{
cn.Close();
}
}
}
}
}
A: 1.A DataReader works in a connected environment,
whereas DataSet works in a disconnected environment.
2.A DataSet represents an in-memory cache of data consisting of any number of inter related DataTable objects. A DataTable object represents a tabular block of in-memory data.
SqlDataAdapter or sqlDataReader
A: Difference between SqlDataAdapter or sqlDataReader ?
Ans : 1.A DataReader works in a connected environment,
whereas DataSet works in a disconnected environment.
2.A DataSet represents an in-memory cache of data consisting of any number of inter related DataTable objects. A DataTable object represents a tabular block of in-memory data.
SqlDataAdapter or sqlDataReader
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What are the troubleshooting steps to troubleshoot if jquery events are not firing off? If a jquery event is not firing off, what are troubleshooting steps to figure out what causing why the event is not firing off?
A: The steps I take:
*
*Check the error console in your favorite javascript debugger and make sure there are no javascript errors of any kind. If there are, fix/eliminate them.
*Make sure your jQuery selectors that install the event handlers are actually working. You might have the selector not quite right, you might be calling it too early before that object is in the page or before that part of the page has been parsed.
*Set a breakpoint in the first statement of the event handler to prove to yourself that it's not getting called.
*Check that you're actually installing the event handler on the right object. For a mouse click, make sure that nothing is on top of the desired element.
*Beyond this, it's specific to what type of event you're talking about. Any further help would need sample code that you've reduced to a jsFiddle that shows what doesn't work.
A: *
*first of all make sure the jQuery is loaded
*check the firebug and see if there are any errors follow this link
*check whether the elements you are trying to bind the events to are present in the DOM, you can make it sure by wrapping all jQuery code inside the ready handler like
$(document).ready(function{
});
or the short form
$(function(){
});
*if you are using multiple javascript libraries like jquery and mootools together there might be a conflict to resolve it there is noConflict
*if you are using visual studio(i dont know if it works else where also) place the key word debugger to stop the execution of the script and proceed step by step
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Vertically centering text Link to my jsbin
I am having a bit of unexpected trouble. I would like to vertically center the "Thing2" text. However the css property vertical-algin: middle doesn't seem to be working.
So I'd like to know 2 things:
*
*Why isn't it working?
*Is the way I'm doing it (by adding a main class to each then a styling class) the easiest way to do this?
Note
This is just a proof of concept of an overall idea that I have. So obviously class names and ids will change.
A: You can't vertically align text in that way, see http://www.w3.org/wiki/CSS/Properties/vertical-align
Try instead setting a line height on your container div equal to the height of the div if you just want to vertically align a single line of text.
e.g.
.metroSmall {
line-height: 87.5px;
}
This is a nice post detailing a few different ways of vertically aligning html elements: http://blog.themeforest.net/tutorials/vertical-centering-with-css/
If you are only supporting the latest browsers you can also use the new table, and table-cell display styles, which support vertical alignment in the same way that tables do.
e.g.
.metroSmall {
display: table-cell;
vertical-align: middle;
}
Bear in mind this won't work on earlier browsers such as internet explorer 6 though.
A: The way i vertically center things is to set the line-height to the height of the container
try adding line-height: 87.5px to .about
A: Try Using This http://jsfiddle.net/YUruZ/
Use CSS style display property table and table-cell
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the best way to return agregate column with non agregate column in result set of a view I need to compare the final balances of two tables from different clients grouped by ID. The tables have the same ID's But one has multiple ID entries and the other does not. I need to sum row from the table with multiple entries so I have just one final number to do calculations with.
Table1:
ID, cost, traceNumber, TheDate
1, 200, 1001, 10/07/2011
1, -20, 1002, 10/08/2011
1, 130, 1003, 10/10/2011
2, 300, 1005, 10/10/2011
Table2:
ID, cost
1, 200
2, 300
Result for ID 1, would be 310 compared to table2 of 200 with a difference of 110
The Query will look something like this.
SELECT DISTINCT
Table1.ID,
Table1.TheDate ,
Table1.traceNumber,
Table1.[cost] AS Frost_Balance,
SUM(Table1.[cost]) AS SUM_Frost_Balance,
Table2.[cost] AS Ternean_Balance,
SUM(Table1.[cost]) - Table2.[cost] AS Ending_Balance,
FROM
Table1
INNER JOIN Table2 ON Table1.ID =Table2.CustomerID
GROUP BY
dbo.Frost.ID
The query has to display multiple columns in the result set because it is going to be used to report on. I tried grouping by all columns in the result set but that gave me wrong results. Is there another way to compute the column that needs to be summed up?
A: You can use a "Window Aggregate Function" like this:
select
table1.*,
sum(table1.cost) over (partition by table1.id) sum_frost_balance,
table2.cost,
sum(table1.cost) over (partition by table1.id) - table2.cost ending_balance
from table1
join table2 on table1.id = table2.id
A: Is this what you're trying to do?
-- Data setup
CREATE TABLE [Table1]
(
[ID] INT,
[cost] INT,
[traceNumber] INT,
[TheDate] DATE
)
INSERT [Table1]
VALUES (1, 200, 1001, '10/07/2011'),
(1, -20, 1002, '10/08/2011'),
(1, 130, 1003, '10/10/2011'),
(2, 300, 1005, '10/10/2011')
CREATE TABLE [Table2]
(
[ID] INT,
[cost] INT
)
INSERT [Table2]
VALUES (1, 200),
(2, 300)
-- Query
;WITH [cteTable1Sum] AS
(
SELECT [ID], SUM([cost]) AS [cost]
FROM [Table1]
GROUP BY [ID]
)
SELECT [Table1].[ID],
[Table1].[TheDate],
[Table1].[traceNumber],
[Table1].[cost] AS [Frost_Balance],
cte.[cost] AS [SUM_Frost_Balance],
[Table2].[cost] AS [Ternean_Balance],
cte.[cost] - [Table2].[cost] AS [Ending_Balance]
FROM [Table1]
INNER JOIN [Table2]
ON [Table1].[ID] = [Table2].[ID]
INNER JOIN [cteTable1Sum] cte
ON [Table1].[ID] = cte.[ID]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get back anonymous type
Possible Duplicate:
Accessing C# Anonymous Type Objects
Working with C# Anonymous Types
I'm using linq to entities to get id and full name from a table with customers.
public IQueryable RegresaClientesPorEmpresa(int id_emp)
{
var clientes = from c in context.clientes
where c.IDEmpresa == id_emp
select new
{
c.IDCliente,
NomComp = c.Nombres +" "+ c.ApellidoP +" "+ c.ApellidoM
};
return clientes;
}
The result is used as the datasource of a combobox, then when SelectionChangeCommitted is triggered in my combo, I want the selected item to be added to a listbox:
var clientes = operaciones.RegresaClientesPorEmpresa(2);
combo_cliente.DataSource = clientes;
combo_cliente.DisplayMember = "NomComp";
combo_cliente.ValueMember = "IDCliente";
listBox_grupo.DisplayMember = "NomComp";
listBox_grupo.ValueMember = "IDCliente";
private void combo_cliente_SelectionChangeCommitted(object sender, EventArgs e)
{
listBox_grupo.Items.Add(combo_cliente.SelectedItem);
}
Until here everything is fine. Finally I want to get all "IDCliente"'s values from all items added to my listbox, the problem is that I don't know how to do it because every item is an Anonymous data type. Can anyone help me?
A: The scope of an anonymous type is limited to the method in which it is "declared" (well it's not really declared, but you see what I mean). If you want to use the result of your query in another method, create a named type to hold the results.
A: You shouldn't return anonymous types from your methods if you're expecting to access their properties. It'll be easier on you if you define a class instead, because that establishes the contract of your method.
A: just create a class to avoid anonymous type.
class Foo
{
public string NomComp {get ; set;}
public string IDCliente {get ; set;}
}
and do
select new Foo
{
...
}
to save some hassle.
or You can define
T Cast<T>(object obj, T type)
{
return (T)obj;
}
and then use
object anonymousObject = GetSelection();
var selection = Cast(anonymousObject , new { IDCliente="", NomComp ="" });
and then you should be able to do selection.NomComp to get the property value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: is there any function in sql which may return the result from first two alphabet or the first alphabet? I am working on oracle10g. I was curious to know that is there any SQL function which may give results from the starting alphabet of a string.
For example, if I have road-1, road-A, road-89 and I want to know total number of such road sets without using the sql count() function.
A: For values that start with road:
SELECT YourColumn, COUNT(*) Total
FROM YourTable
WHERE YourColumn LIKE 'road%'
For values that contains road somewhere:
SELECT YourColumn, COUNT(*) Total
FROM YourTable
WHERE YourColumn LIKE '%road%'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When an object is locked, and this object is replaced, is the lock maintained? Let's say I have this java code:
synchronized(someObject)
{
someObject = new SomeObject();
someObject.doSomething();
}
Is the instance of SomeObject still locked by the time doSomething() is called on it?
A: The thread will still own the monitor for the original value of someObject until the end of the synchronized block. If you imagine that there were two methods, Monitor.enter(Object) and Monitor.exit(Object) then the synchronized block would act something like:
SomeObject tmp = someObject;
Monitor.enter(tmp);
try
{
someObject = new SomeObject();
someObject.doSomething();
}
finally
{
Monitor.exit(tmp);
}
From section 14.19 of the JLS:
A synchronized statement is executed by first evaluating the Expression.
If evaluation of the Expression completes abruptly for some reason, then the synchronized statement completes abruptly for the same reason.
Otherwise, if the value of the Expression is null, a NullPointerException is thrown.
Otherwise, let the non-null value of the Expression be V. The executing thread locks the lock associated with V. Then the Block is executed. If execution of the Block completes normally, then the lock is unlocked and the synchronized statement completes normally. If execution of the Block completes abruptly for any reason, then the lock is unlocked and the synchronized statement then completes abruptly for the same reason.
Note how the evaluation only occurs once.
A: The lock applies to an object, not a variable. After someObject = new SomeObject(); the variable someObject references a new object, the lock is still on the old one.
Bye and bye very dangerous.
A: I believe the previous instance of someObject is locked and your new instance is not locked.
A: It's important to understand the difference between synchronized methods and synchronized statements.
Take a look at this page which explains it pretty well: http://download.oracle.com/javase/tutorial/essential/concurrency/locksync.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do I read from a pointer that looks like "process name" + address? As the title says I'm trying to read from an address I found in Cheat Engine's pointer scan. But the only problem is the only pointers I've ever had to work with are just Pointer Address + Offset. I am using C# .Net 4.0 from Visual Studio 2010. I think I remember seeing something about this before but I didn't think to much about it as it didn't apply to me at the time.
Something about getting the Process or Module ID and adding it to the pointer address then adding the offset and reading from there? But I can't remember the commands to get a processes ID or Module ID :/
Also this is a level 5 pointer I'm working with, I've only used level 1 or 2 pointers but I'm guessing it's around the same. Just read the address from the pointers until I get a base address to write to.
If it helps my pointer looks like this:
"ProcessName.exe"+003E6D98
"It might help if you said why in the world you need to play with pointers from .NET" - John Saunders
I am making a trainer for one of my games. I've made them before just not with this type of pointer and I forgot exactly how to handle this type of address. I think I have to get the module's id but I've forgotten how. I'm actually pretty good with memory and pointers I just usually have the average address without the process name next to it.
A: OP answered in question - put as CW answer
string sProcessName = "MyProcessName.exe";
Process[] MyProcesses = Process.GetProcessesByName(sProcessName);
IntPtr hProcModuleBA = MyProcesses[0].MainModule.BaseAddress;
IntPtr PointerAddr = new IntPtr(MyPointer.ToInt32() + BaseAddress.ToInt32());
This will search through your processes for sProcessName, add it to an array 'MyProcesses'. I chose the first one in the list to get the BaseAddress from. It was 40000 :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: using variable extracted from selector I am trying to use list elements to toggle between corresponding panels, I also want to do this using variables, just so I can orient myself with their use better. Here is my html and code below. I am tring to extract the i from the the "icon" id clicked, and use that i to open a corresponding "panel" id, with the attached i afterward. Any help would be appreciated! thanks!
html
<div id="icon0" class="icon">
<a href=""><img src="Images/film_icon.png"/></a>
</div>
<div id="icon1" class="icon">
<a href=""><img src="Images/film_icon.png"/></a>
</div>
<div id="icon2" class="icon">
<a href=""><img src="Images/film_icon.png"/></a>
</div>
<div id="icon3" class="icon">
<a href=""><img src="Images/film_icon.png"/></a>
</div>
html panels:
<div id="panel0" class="panel">0000</div>
<div id="panel1" class="panel">1111</div>
<div id="panel2" class="panel">2222</div>
<div id="panel3" class="panel">3333</div>
Jquery
for(var i=0; i<4; i++){
$('#icon'+i).click( function() {
$('#panel'+i).fadeOut(400);
return false;
A: <script type="text/javascript">
$(document).ready(function(){
var iconPrefix = "icon";
var panelPrefix = "panel";
$("[id^='"+iconPrefix +"']").each(
function(index, Element){
$("#"+iconPrefix +index).click(function(event){
$("#"+panelPrefix +index).fadeToggle(400);
});
}
);
});
</script>
A: Ok collect all your icons in an object, first, then whenever one is clicked get the index and trigger the fade on the corresponding panel:
var $icons = $(".icons");
$icons.each(function() {
$(this).click(function(evt) {
var thisIndex = parseInt($(this).index());
$("#panel"+thisIndex).fadeToggle(4000);
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to iterate step with right shift in Python? Is it possible to use right shift as the step argument in xrange?
Basically I'm trying to do this (pseudo-code)
for i in xrange(35926661, 0, _value_>>6):
//logic
A: No.
xrange always works by adding the third parameter. You cannot tell it to do something like a right shift instead.
A while loop will work, there may be better solutions but its hard to say without more information about what you are doing.
A: You can define a custom xrange-like function using a generator:
def lrange(a, b, f):
num = a
comp = operator.lt if (a < b) else operator.gt
while comp(num, b):
yield num
num = f(num)
Then:
for x in lrange(35926661, 0, lambda x: x>>6):
print(x)
http://codepad.org/0pYfWqSF
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Change height using CSS I have seen a question here about the same, but I can't get any of the answers to work (at least on Chrome).
This question is only for <br>, I know plenty of other techniques to change the height but in this case I can't change the HTML.
bla<BR><BR>bla<BR>bla<BR><BR>bla
CSS:
br {
display: block;
margin-bottom: 2px;
font-size:2px;
line-height: 2px;
}
Desired effect: smaller inter-line height.
The only thing I can get to work is display:none, but then all line break are removed.
Here's a fiddle for it using some of the techniques, but see that it renders the exact same as without any CSS.
A: This feels very hacky, but in chrome 41 on ubuntu I can make a <br> slightly stylable:
br {
content: "";
margin: 2em;
display: block;
font-size: 24%;
}
I control the spacing with the font size.
Update
I made some test cases to see how the response changes as browsers update.
*{outline: 1px solid hotpink;}
div {
display: inline-block;
width: 10rem;
margin-top: 0;
vertical-align: top;
}
h2 {
display: block;
height: 3rem;
margin-top:0;
}
.old br {
content: "";
margin: 2em;
display: block;
font-size: 24%;
outline: red;
}
.just-font br {
content: "";
display: block;
font-size: 200%;
}
.just-margin br {
content: "";
display: block;
margin: 2em;
}
.brbr br {
content: "";
display: block;
font-size: 100%;
height: 1em;
outline: red;
display: block;
}
<div class="raw">
<h2>Raw <code>br</code>rrrrs</h2>
bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
<div class="old">
<h2>margin & font size</h2>
bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
<div class="just-font">
<h2>only font size</h2>
bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
<div class="just-margin">
<h2>only margin</h2>
bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
<div class="brbr">
<h2><code>br</code>others vs only <code>br</code>s</h2>
bla<BR><BR>bla<BR>bla<BR><BR>bla
</div>
They all have their own version of strange behaviour. Other than the browser default, only the last one respects the difference between one and two brs.
A: Use the content property and style that content. Content behavior is then adjusted using pseudo elements. Pseudo elements ::before and ::after both work in Mac Safari 10.0.3.
Here element br content is used as the element anchor for element br::after content. Element br is where br spacing can be styled. br::after is the place where br::after content can be displayed and styled. Looks pretty, but not a 2px <br>.
br { content: ""; display: block; margin: 1rem 0; }
br::after { content: "› "; /* content: " " space ignored */; float: left; margin-right: 0.5rem; }
The br element line-height property is ignored. If negative values are applied to either or both selectors to give vertical 'lift' to br tags in display, then correct vertical spacing occurs, but display incrementally indents display content following each br tag. The indent is exactly equal to the amount that lift varies from actual typographic line-height. If you guess the right lift, there is no indent but a single pile-up line exactly equal to raw glyph height, jammed between previous and following lines.
Further, a trailing br tag will cause the following html display tag to inherit the br:after content styling. Also, pseudo elements cause <br> <br> to be interpreted as a single <br>. While pseudo-class br:active causes each <br> to be interpreted separately. Finally, using br:active ignores pseudo element br:after and all br:active styling. So, all that's required is this:
br:active { }
which is no help for creating a 2px high <br> display. And here the pseudo class :active is ignored!
br:active { content: ""; display: block; margin: 1.25em 0; }
br { content: ""; display: block; margin: 1rem; }
br::after { content: "› "; /* content: " " space ignored */; float: left; margin-right: 0.5rem; }
This is a partial solution only. Pseudo class and pseudo element may provide solution, if tweaked. This may be part of CSS solution. (I only have Safari, try it in other browsers.)
Learn web development: pseudo classes and pseudo elements
Pay attention to global elements - BR at Mozilla.org
A: You can't change the height of the br tag itself, as it's not an element that takes up space in the page. It's just an instruction to create a new line.
You can change the line height using the line-height style. That will change the distance between the text blocks that you have separated by empty lines, but natually also the distance between lines in a text block.
For completeness: Text blocks in HTML is usually done using the p tag around text blocks. That way you can control the line height inside the p tag, and also the spacing between the p tags.
A: The line height of the br tag can be different from the line height of the rest of the text inside a paragraph text by setting font-size for br tag.
Example: br { font-size: 200%; }
A: You can control the <br> height if you put it inside a height limited div. Try:
<div style="height:2px;"><br></div>
A: As the 'margin' doesn't work in Chrome, that's why I used 'border' instead.
br {
display: block;
content: "";
border-bottom: 10px solid transparent; // Works in Chrome/Safari
}
@-moz-document url-prefix() {
br {
margin-bottom: 10px; // As 'border-bottom' doesn't work in firefox and 'margin-bottom' doesn't work in Chrome/Safari.
}
}
A: Take a look at the line-height property. Trying to style the <br> tag is not the answer.
Example:
<p id="single-spaced">
This<br> text
<br> is
<br> single-spaced.
</p>
<p id="double-spaced" style="line-height: 200%;">
This<br> text
<br> is
<br> double-spaced.
</p>
A: The BR is anything but 'extra-special': it is still a valid XML tag that you can give attributes to. For example, you don't have to encase it with a span to change the line-height, rather you can apply the line height directly to the element.
You could do it with inline CSS:
This is a small line
<br />
break. Whereas, this is a BIG line
<br />
<br style="line-height:40vh"/>
break!
Notice how two line breaks were used instead of one. This is because of how CSS inline elements work. Unfourtunately, the most awesome css feature possible (the lh unit) is still not there yet with any browser compatibility as of 2019. Thus, I have to use JavaScript for the demo below.
addEventListener("load", function(document, getComputedStyle){"use strict";
var allShowLineHeights = document.getElementsByClassName("show-lh");
for (var i=0; i < allShowLineHeights.length; i=i+1|0) {
allShowLineHeights[i].textContent = getComputedStyle(
allShowLineHeights[i]
).lineHeight;
}
}.bind(null, document, getComputedStyle), {once: 1, passive: 1});
.show-lh {padding: 0 .25em}
.r {background: #f77}
.g {background: #7f5}
.b {background: #7cf}
This is a small line
<span class="show-lh r"></span><br /><span class="show-lh r"></span>
break. Whereas, this is a BIG line
<span class="show-lh g"></span><br /><span class="show-lh g"></span>
<span class="show-lh b"></span><br style="line-height:40vh"/><span class="show-lh b"></span>
break!
You can even use any CSS selectors you want like ID's and classes.
#biglinebreakid {
line-height: 450%;
// 9x the normal height of a line break!
}
.biglinebreakclass {
line-height: 1em;
// you could even use calc!
}
This is a small line
<br />
break. Whereas, this is a BIG line
<br />
<br id="biglinebreakid" />
break! You can use any CSS selectors you want for things like this line
<br />
<br class="biglinebreakclass" />
break!
You can find our more about line-height at the W3C docs.
Basically, BR tags are not some void in world of CSS styling: they still can be styled. However, I would recommend only using line-height to style BR tags. They were never intended to be anything more than a line-break, and as such they might not always work as expected when using them as something else. Observe how even after applying tons of visual effects, the line break is still invisible:
#paddedlinebreak {
display: block;
width: 6em;
height: 6em;
background: orange;
line-height: calc(6em + 100%);
outline: 1px solid red;
border: 1px solid green;
}
<div style="outline: 1px solid yellow;margin:1em;display:inline-block;overflow:visible">
This is a padded line
<br id="paddedlinebreak" />
break.
</div>
A work-around for things such as margins and paddings is to instead style a span with a br in it like so.
#paddedlinebreak {
background: orange;
line-height: calc(6em + 100%);
padding: 3em;
}
<div style="outline: 1px solid yellow;margin:1em;display:inline-block;overflow:visible">
This is a padded line
<span id="paddedlinebreak"><br /></span>
break.
</div>
Notice how the orange blob above is the span that contains the br.
A:
#biglinebreakid {
line-height: 450%;
// 9x the normal height of a line break!
}
.biglinebreakclass {
line-height: 1em;
// you could even use calc!
}
This is a small line
<br />
break. Whereas, this is a BIG line
<br />
<br id="biglinebreakid" />
break! You can use any CSS selectors you want for things like this line
<br />
<br class="biglinebreakclass" />
break!
A: You can write br tag as show
<br style="content:''; padding: 10px 0;" />
Change padding value to 10px to anything you like.
Note: As padding is specified, height increases in both directions(top and bottom)
A: The line height of the <br> can be different from the line height of the rest of the text inside a <p>. You can control the line height of your <br> tags independently of the rest of the text by enclosing two of them in a <span> that is styled. Use the line-height css property, as others have suggested.
<p class="normalLineHeight">
Lots of text here which will display on several lines with normal line height if you put it in a narrow container...
<span class="customLineHeight"><br><br></span>
After a custom break, this text will again display on several lines with normal line height...
</p>
A: <font size="4"> <font color="#ffe680">something here</font><br>
I was trying all these methods but most didn't work properly for me, eventually I accidentally did this and it works great, it works on chrome and safari (the only things I tested on). Replace the colour code thing with your background colour code and the text will be invisible. you can also adjust the font size to make the line break bigger or smaller depending on your desire. It is really simple.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "99"
} |
Q: Can I improve the resolution of Thread.Sleep? Thread.Sleep() resolution varies from 1 to 15.6ms
Given this console app:
class Program
{
static void Main()
{
int outer = 100;
int inner = 100;
Stopwatch sw = new Stopwatch();
for (int j = 0; j < outer; j++)
{
int i;
sw.Restart();
for (i = 0; i < inner; i++)
Thread.Sleep(1);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
}
}
I expected the output to be 100 numbers close to 100. Instead, I get something like this:
99
99
99
100
99
99
99
106
106
99
99
99
100
100
99
99
99
99
101
99
99
99
99
99
101
99
99
99
99
101
99
99
99
100
99
99
99
99
99
103
99
99
99
99
100
99
99
99
99
813
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1559
1560
1559
1559
1559
1559
1558
1558
1558
1558
1558
1558
1558
1558
1558
1558
1558
1558
1558
1558
1558
1558
1558
1558
1558
1559
1558
1558
1558
1558
1558
But sometimes I won't get any accurate results; it will be ~1559 every time.
Why isn't it consistent?
Some googling taught me that 15.6ms is the length of a timeslice, so that explains the ~1559 results. But why is it that I sometimes get the right result, and other times I just get a multiple of 15.6? (e.g. Thread.Sleep(20) will usually give ~31.2ms)
How is it affected by hardware or software?
I ask this because of what led me to discover it:
I had been developing my application on a 32 bit dual-core machine. Today my machine was upgraded to 64bit quad-core with a complete OS re-install. (Windows 7 and .NET 4 in both cases, however I can't be sure the older machine had W7 SP1; the new one does.)
Upon running my application on the new machine, I immediatey notice my forms take longer to fade out. I have a custom method to fade my forms which uses Thread.Sleep() with values varying from 10 to 50. On the old system this seemed to work perfectly every time. On the new system it's taking much longer to fade than it should.
Why did this bahavior change between my old system and my new system? Is this related to hardware, or software?
Can I make it consistently accurate? (~1ms resolution)
Is there something I can do in my program to make Thread.Sleep() reliably accurate to about 1ms? Or even 10ms?
A: The answer is not to use Thread.Sleep and instead use a high resolution timer. You'll need to do your fade in a busy loop, but it sounds like that would be no problem. You simply cannot expect high resolution from Thread.Sleep and it is notorious for behaving differently on different hardware.
You can use the Stopwatch class on .net which uses high-resolution performance counters if they are supported on the hardware.
A:
“The Sleep function suspends the execution of the current thread for at least the specified interval.”
-> http://social.msdn.microsoft.com/Forums/en/clr/thread/facc2b57-9a27-4049-bb32-ef093fbf4c29
A: I can answer one of my questions: Can I make it consistently accurate? (~1ms resolution)
Yes, it seems that I can, using timeBeginPeriod() and timeEndPeriod().
I've tested this and it works.
Some things I've read suggest that calling timeBeginPeriod(1) for the duration of the application is a bad idea. However, calling it at the start of a short method and then clearing it with timeEndPeriod() at the end of the method should be okay.
Nevertheless I will also investigate using timers.
A: You have a program running on your machine that is calling timeBeginPeriod() and timeEndPeriod(). Typically a media related program that uses timeSetEvent() to set a one millisecond timer. It affects the resolution of Sleep() as well.
You could pinvoke these functions yourself to get consistent behavior. Not terribly reasonable for UI effects though. It is rather unfriendly to battery life on a laptop.
Sleeping for 20 msec and actually getting 2/64 seconds is otherwise logical, the cpu simply won't wake up soon enough to notice that 20 msec have passed. You only get multiples of 1/64 seconds. So a reasonable choice for a Timer that implements fading effects is 15 msec, giving you 64 fps animation worst case. Assuming that your effect draws fast enough. You'll be a bit off if timeBeginPeriod was called but not by much. Calculating the animation stage from the clock works too but is a bit overkill in my book.
A: Your approach is wrong. You will never get sleep to be accurate, and the more busy your machine is, the more wrong your sleep loop will become.
What you should be doing is looking at how much time has passed and adapting accordingly. Although spinning around Sleep is a bad idea, "better" ways of doing it will be significantly more complex. I'll keep my suggested solution simple.
*
*Call DateTime.Now.Ticks and save it in a variable (startTick).
*In your loop, call Sleep as you are already doing.
*Call DateTime.Now.Ticks again and subtract startTick from it - this value will be how many 100 nanosecond units of time have passed since you started the fade (timeSinceStart).
*Using timeSinceStart calculate how much you should be faded with that much time elapsed.
*Repeat until you have completely faded it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How to set up multiple django versions on single apache service? I'm using Windows XP and want to know how can I create multiple django versions on a single apache service through virtual host(of course).
I'm trying to do that with one instance of python too. Should i create 1 instance of python for each django version or django needs only its eggs to work, so I can have several eggs in just one python version?
A: You can do something like this in your httpd.conf
NameVirtualHost 0.0.0.0:80
<VirtualHost 0.0.0.0:80>
ServerName myserver.com
ServerAdmin [email protected]
DocumentRoot "/path/to/html/root"
ErrorLog "/path/to/apache-error.log"
CustomLog "/path/to/apache-access.log" common
Options ExecCGI FollowSymLinks MultiViews
AddHandler wsgi-script .wsgi
WSGIDaemonProcess djangoapp1
WSGIProcessGroup djangoapp1
WSGIScriptAlias / /path/to/djangoapp1.wsgi
Alias /static /path/to/static/files
DirectoryIndex index.html index.cgi
AddHandler cgi-script .cgi .pl
</VirtualHost>
NameVirtualHost 0.0.0.0:81
<VirtualHost 0.0.0.0:81>
ServerName myserver.com
ServerAdmin [email protected]
DocumentRoot "/path/to/html/root"
ErrorLog "/path/to/apache-error.log"
CustomLog "/path/to/apache-access.log" common
Options ExecCGI FollowSymLinks MultiViews
AddHandler wsgi-script .wsgi
WSGIDaemonProcess djangoapp2
WSGIProcessGroup djangoapp2
WSGIScriptAlias / /path/to/djangoapp2.wsgi
Alias /static /path/to/static/files
DirectoryIndex index.html index.cgi
AddHandler cgi-script .cgi .pl
</VirtualHost>
And then, in your djangoapp1.wsgi/djangoapp2.wsgi script you can define the different django versions and applications:
#!/usr/bin/python
import os
import sys
sys.path.append('')
sys.path.append('/path/to/python2.7/site-packages')
sys.path.append('/path/to/python2.7/dist-packages/Django-1.3-py2.7.egg ')
... etc ...
sys.path.append('/path/to/djangoapp1/src')
os.environ['DJANGO_SETTINGS_MODULE'] = 'djangoapp1.settings'
os.environ['PYTHON_EGG_CACHE'] = '/tmp'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
A: Method 1:
put django source anywhere you want and manually specify path to django source in your manage.py and wsgi.py:
import os
os.path.insert(0, 'path-to-django-source');
You can also use virtualenv. Virtualenv fixes paths for console apps automatically, however for wsgi.py you still have to write down path's manually.
Method 2:
Use zc.buildout and djangorecipe, it will do all the stuff for you including:
*
*donwloads django
*download other modules
*creates wsgi.py at project-dir\bin\wsgi
*creates manage.py at project-dir\bin\django.exe
All this is done with a single config file buildout.cfg- here you list your modules and other settings, and then you run a command: buildout -N.
However buildout might not be a good solution if you have tight deadlines because there will be things you'll need learn about it but if you are planning to do more python apps I definitely recommend trying it.
Here are some examples for django+buildout setup:
http://www.google.lt/search?q=django+buildout+template+OR+skeleton
An update to your comment
You cannot install two django versions system wide.
What you can do though is either:
*
*Do not install django, just drop the django-base/django folder into your project path. You will have to compile the internationalization files manually (if you use i18n):
cd django\conf
python ..\..\manage.py compilemessages
*Or, install django with python setup.py install, but use extra arguments to change installation destination. Python documentation covers few different methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: LDAP Export: Need to change DN on export I'm trying to export the DN from Active Directory, but rather than have the CN equal to the displayName, need it to be the SAMAccountName. Can anyone help with this? I've tried adfind with the -replacedn switch and it changed the CN to SAMAccountName, but not the value. Thanks!
Example:
dn: CN=young\, neil,DC=example,DC=com
displayName: young\, neil
SAMAccountName: nyoung
Want the export output to be:
dn: CN=nyoung,DC=example,DC=com
A: This is not something you can easily change.
When they create users in Active Directory, as you type First Name and then Last Name the ADUC MMC tool builds a displayName of First Last, and uses that by default as the CN= component.
You could go and rename every object to cn=sAMAccountName value, but you would also have to force everyone with access to create a user to start doing that as well.
If you have an Identity Management solution of some kind creating the users, and not using manual processes this is trivial to implement. And for large solutions, it is really the only scalable model for CN values in AD. After all sAMAccountName must be domain unique, so this guarantees no naming collisions in CN parts of DN's.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Implementing a timer for an auto-logoff feature in an embedded system (Java) I'll try my best to explain the situation at hand. I'm developing an auto-logoff feature for an authentication application that runs in an embedded system and should work cooperatively with its own internal auto-logout system. First I'll briefly explain the native auto logoff. If I set it to 60 seconds and I'm in one of the system's screens, it will monitor and reset the timer upon user interaction. After being idle for 60 seconds, the system will call the Java authentication application and it logs off. This is easily done. Once an user logs in, the application starts a thread that just waits. When the application is brought back (upon timeout), a call for the notify() method is made, releasing the thread and executing the logout proccess. Relatively simple, right?
Now things get ugly. This embedded system supports multiple Java applications, as it is expected. But the system built-in auto logout will only keep track of things should the user be interacting with one of the system's native screens, if he's using another Java application, it will do nothing. So, in order to counter that, I need to come up with some way to implement an internal timer that works in conjunction with the workings described above.
In other words, should the system be in "Java mode" I need to use a coded timer, anything else I use the timer described in the first paragraph. The system itself doesn't help much, since there's no support to check in which state the machine is, so I'm pretty much left with only Java to do the job.
I've given it a lot of thought today but I'm just stuck. Any fresh ideas?
BTW, it supports only Java up to 1.4 so no advanced concurrency classes for me.
Edit: I forgot to mention that I can't just code a regular timer, since I can't capture native events from the system (I can capture events from other Java applications though) and a Java timer overrides the native timer function. That's why I need some "coordinate work" between them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Few questions about SVN I work on a large scale project, now I did many changes + add new files in various directories, how can I find what I added (I know what I added, but lets assume I forgot...) so I can 'add' to the repository?
also, how can I commit all the changes at once?
thanks,
A: if you use the command line version of svn, go to the topmost directory and run svn st. That command will tell you which files have been updated, deleted or are not tracked.
To commit run svn commit -m "commit message" and it will commit all the files.
If you have deleted or created files, but haven't deleted or added them with subversion you will need to run svn rm path/to/file for the files you've removed and svn add path/to/file for the files you've added. svn st lists these files.
A: To commit all changes at once you have to invoke commit at the level of the the root folder of your project.
All the changes (updated/modified/deleted files) will be listed on the Tortoise's commit window.
A: I'm assuming that you are using Tortoise, You should be able to go to the root directory and do a checkin. It will pull up all the files that you have either - made changes to or added. Please make sure you go through your list and uncheck any of them you changed but did not mean to change otherwise you will break you
A: In response to George, I think the original poster is asking about which new files he's created but has not yet performed an svn-add on them. That is to say these would be files that svn does not yet know about. Is that what you're asking?
I don't know of a straightforward way to do this, but you could initiate a commit at a root level and (assuming you're using tortoise) click the "show unversioned files." This would then let you see all files in the directory structure that svn doesn't yet know about. Obviously there are likely to be other unversioned files in this list, so depending on how many there are, this method may or may not be useful for you.
A: I use TortoiseSVN as the interface to svn. The right click menu gives you an option to check for modifications. This will identify all new files (non-versioned) and all modified files in your working directory.
You can then highlight all the new files and add them, or highlight all the modified files and commit them.
Dave
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Any way to create an arbitrary tone with Basic4android? Is there any way with Basic4Android to make it emit a sound of arbitrary frequency (meaning, I don't want to have pre-recorded sound files) and duration?
In some "traditional" Basic languages this would be done via e.g. a BEEP command followed by the desired frequency and duration.
Basic4Android doesn't seem to support any equivalent command.
I am looking for this feature in order to program a Morse Code generating app and for this purpose I need to stay flexible regarding the audio frequency tone (must be user selectable) between e.g. 500Hz and lets say 1000 Hz as well as variable duration in milliseconds (in order to be able to generate variable user selectable speeds of the morse code dashes and dots and silent breaks inbetween)...
It's simply not practical or near to impossible to do this with prerecorded WAV's or you would end up in a huge WAV collection for all frequency/speed combinations.
It seems to be possible in Android to do so, see example here:
http://marblemice.blogspot.com/2010/...n-android.html
As far as I can interpret this code it calculates a sine wave tone "on the fly" at the desired frequency into a buffer array and uses that buffer data to generate and play it as a PCM stream.
Since above code seems to be quite simple I wonder if a clever Java programming guy would come up with a simple Basic4Android "Tone Generator" library which others could use for this purpose?
Unfortunately, I am only an old fashioned VisualBasic guy and making my first steps with Basic4Android...for creating my own library my skills are simply too lousy.
A: The Audio library was updated and you can now use the Beeper object to play "beep" sounds.
Dim b As Beeper
b.Initialize(300, 500) '300 milliseconds, 500hz
b.Beep
Updated library link
A: This is definitely possible to do on Android, in a java-based application. I don't know if Basic4Android can do this "natively" (I'd never heard of Basic4Android before this), but it appears that you can create libraries in java that can then be accessed by Basic4Android, so it would be theoretically possible to create a java library that does this and then call it from your B4A app.
However, since this would entail learning some java and the Android plugin for Eclipse anyway, maybe you should just take the plunge and learn java for Android? I'm a long-term Visual Basic guy myself (started in 1995), and it wasn't really that difficult to transition to C# and thence to java.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Interactive image plotting with matplotlib I am transitioning from Matlab to NumPy/matplotlib. A feature in matplotlib that seems to be lacking is interactive plotting. Zooming and panning is useful, but a frequent use case for me is this:
I plot a grayscale image using imshow() (both Matlab and matplotlib do well at this). In the figure that comes up, I'd like to pinpoint a certain pixel (its x and y coordinates) and get its value.
This is easy to do in the Matlab figure, but is there a way to do this in matplotlib?
This appears to be close, but doesn't seem to be meant for images.
A: custom event handlers are what you are going to need for this. It's not hard, but it's not "it just works" either.
This question seems pretty close to what you are after. If you need any clarification, I'd be happy to add more info.
A: I'm sure you have managed to do this already. Slightly(!) modifying the link, I've written the following code that gives you the x and y coordinates once clicked within the drawing area.
from pylab import *
import sys
from numpy import *
from matplotlib import pyplot
class Test:
def __init__(self, x, y):
self.x = x
self.y = y
def __call__(self,event):
if event.inaxes:
print("Inside drawing area!")
print("x: ", event.x)
print("y: ", event.y)
else:
print("Outside drawing area!")
if __name__ == '__main__':
x = range(10)
y = range(10)
fig = pyplot.figure("Test Interactive")
pyplot.scatter(x,y)
test = Test(x,y)
connect('button_press_event',test)
pyplot.show()
Additionally, this should make it easier to understand the basics of interactive plotting than the one provided in the cookbook link.
P.S.: This program would provide the exact pixel location. The value at that location should give us the grayscale value of respective pixel.
Also the following could help:
http://matplotlib.sourceforge.net/users/image_tutorial.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: antlr c# errors when integrating into VS2008 I am following the tutorial at: http://www.antlr.org/wiki/pages/viewpage.action?pageId=557075
When I get to step 11, compile with VS I am getting the following:
Error The type or namespace name 'AstParserRuleReturnScope' could not be found
Error The type or namespace name 'GrammarRule' could not be found
Error The type or namespace name 'GrammarRuleAttribute' could not be found
etc.
Any tips from anyone? There is little to no documentation to help me here.
Thanks!
A: Use ANTLRWorks 1.4 to generate the code if you are using the compiled runtime dlls. Otherwise, if you use the latest version of ANTLRWorks I believe you need to get the latest version of the runtime and compile it.
A: You most likely just need a more recent version of the ANTLR .NET runtime. The latest version can be found at: http://www.antlr.org/wiki/display/ANTLR3/Antlr3CSharpReleases
ANTLR version 3.4.1 has been working for me with ANTLRWorks 1.4.3 parsers & lexers; before upgrading the runtime, I was getting the same errors as you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Create set of all possible matches for a given regex I'm wondering how to find a set of all matches to a given regex with a finite number of matches.
For example:
All of these example you can assume they start with ^ and end with $
`hello?` -> (hell, hello)
`[1-9][0-9]{0,3}` -> (1,2,3 ..., 9998, 9999)
`My (cat|dog) is awesome!` -> (My cat is awesome!, My dog is awesome!)
`1{1,10}` -> (1,11, ..., 111111111, 1111111111)
`1*` -> //error
`1+` -> //error
`(1|11){2}` -> (1,11,111,1111) //notice how it doesn't repeat any of the possibilities
I'd also be interested if there was a way of retrieving count a unique a solutions to the regex or if there is a way to determine if the regex has a finite solutions.
It would be nice if the algorithm could parse any regex, but a powerful enough subset of the regex would be fine.
I'm interested in a PHP solution to this problem, but other languages would also be fine.
EDIT:
I've learned in my Formal Theory class about DFA which can be used to implement regex (and other regular languages). If I could transform the regex into a DFA the solution seems fairly straight forward to me, but that transformation seems rather tricky to me.
EDIT 2:
Thanks for all the suggestions, see my post about the public github project I'm working on to "answer" this question.
A: The transformation from a regex to a DFA is pretty straightforward. The issue you'll run into there, though, is that the DFA generated can contain loops (e.g, for * or +), which will make it impossible to expand fully. Additionally, {n,n} can't be represented cleanly in a DFA, as a DFA has no "memory" of how many times it's looped.
What a solution to this problem will boil down to is building a function which tokenizes and parses a regular expression, then returns an array of all possible matches. Using recursion here will help you a lot.
A starting point, in pseudocode, might look like:
to GenerateSolutionsFor(regex):
solutions = [""]
for token in TokenizeRegex(regex):
if token.isConstantString:
for sol in solutions: sol.append(token.string)
else if token.isLeftParen:
subregex = get content until matching right paren
subsols = GenerateSolutionsFor(subregex)
for sol in solutions:
for subsol in subsols:
sol.append(subsol)
else if token.isVerticalBar:
solutions.add(GenerateSolutionsFor(rest of the regex))
else if token.isLeftBrace:
...
A:
I'm wondering how to find a set of all matches to a given regex with a finite number of matches.
Because you're only considering regular expressions denoting finite languages, you're actually considering a subset of the regular expressions over an alphabet. In particular, you're not dealing with regular expressions constructed using the Kleene star operator. This suggests a simple recursive algorithm for constructing the set of strings denoted by the regular expressions without Kleene star over an alphabet Σ.
LANG(a) = {a} for all a ∈ Σ
LANG(x ∪ y) = LANG(x) ∪ LANG(y)
LANG(xy) = {vw : v ∈ LANG(x) ∧ w ∈ LANG(y)}
Consider a regular expression such as a(b ∪ c)d. This is precisely the structure of your cats and dogs example. Executing the algorithm will correctly determine the language denoted by the regular expression:
LANG(a((b ∪ c)d)) = {xy : x ∈ LANG(a) ∧ y ∈ LANG((b ∪ c)d)}
= {xy : x ∈ {a} ∧ y ∈ {vw : v ∈ LANG(b ∪ c) ∧ w ∈ LANG{d}}}
= {ay : y ∈ {vw : v ∈ (LANG(b) ∪ LANG(c)) ∧ w ∈ {d}}}
= {ay : y ∈ {vd : v ∈ {b} ∪ {c}}
= {ay : y ∈ {vd : v ∈ {b,c}}}
= {ay : y ∈ {bd, cd}}
= {abd, acd}
You also ask whether there is an algorithm that determines whether a regular language is finite. The algorithm consists in constructing the deterministic finite automaton accepting the language, then determining whether the transition graph contains a walk from the start state to a final state containing a cycle. Note that the subset of regular expressions constructed without Kleene star denote finite languages. Because the union and concatenation of finite sets is finite, this follows by easy induction.
A: This probably doesn't answer all your questions / needs, but maybe it's a good starting point. I was searching for a solution for auto-generating data that matches a regexp a while ago, and i found this perl module Parse::RandGen, Parse::RandGen::RegExp, which worked quite impressivly good for my needs:
http://metacpan.org/pod/Parse::RandGen
A: You might want to look at this Regex library, which parses a RegEx syntax (albeit a bit different from the perl standard) and can construct a DFA from it: http://www.brics.dk/automaton/
A: I have begun working on a solution on Github. It can already lex most examples and give the solution set for finite regex.
It currently passes the following unit tests.
<?php
class RegexCompiler_Tests_MatchTest extends PHPUnit_Framework_TestCase
{
function dataProviderForTestSimpleRead()
{
return array(
array( "^ab$", array( "ab" ) ),
array( "^(ab)$", array( "ab" ) ),
array( "^(ab|ba)$", array( "ab", "ba" ) ),
array( "^(ab|(b|c)a)$", array( "ab", "ba", "ca" ) ),
array( "^(ab|ba){0,2}$", array( "", "ab", "ba", "abab", "abba", "baab", "baba" ) ),
array( "^(ab|ba){1,2}$", array( "ab", "ba", "abab", "abba", "baab", "baba" ) ),
array( "^(ab|ba){2}$", array( "abab", "abba", "baab", "baba" ) ),
array( "^hello?$", array( "hell", "hello" ) ),
array( "^(0|1){3}$", array( "000", "001", "010", "011", "100", "101", "110", "111" ) ),
array( "^[1-9][0-9]{0,1}$", array_map( function( $input ) { return (string)$input; }, range( 1, 99 ) ) ),
array( '^\n$', array( "\n" ) ),
array( '^\r$', array( "\r" ) ),
array( '^\t$', array( "\t" ) ),
array( '^[\\\\\\]a\\-]$', array( "\\", "]", "a", "-" ) ), //the regex is actually '^[\\\]a\-]$' after PHP string parsing
array( '^[\\n-\\r]$', array( chr( 10 ), chr( 11 ), chr( 12 ), chr( 13 ) ) ),
);
}
/**
* @dataProvider dataProviderForTestSimpleRead
*/
function testSimpleRead( $regex_string, $expected_matches_array )
{
$lexer = new RegexCompiler_Lexer();
$actualy_matches_array = $lexer->lex( $regex_string )->getMatches();
sort( $actualy_matches_array );
sort( $expected_matches_array );
$this->assertSame( $expected_matches_array, $actualy_matches_array );
}
}
?>
I would like to build an MatchIterator class that could handle infinite lists as well as one that would randomly generate matches from the regex. I'd also like to look into building regex from a match set as a way of optimizing lookups or compressing data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Any default Entity Framework validation with ASP.NET MVC3? This question states that if Entity Framework and code first is used, some default validation is performed. I am using Entity Framework database-first and would like to use MVC 3 unobtrusive javascript validation. Is there some default validation that will be performed, such as client-side checking for numbers when the database column is INTEGER, or client-side checking of string length against VARCHAR column lengths?
A: There should be no client side check unless you add the jQuery.
There are some default checking: DateTime field is always required. I don't have a complete list though.
For code first, you have detailed data annotation already in place, which specifies each field in the database. This annotation will enable a lot of default validation.
However, if it is database first, all you get from the EF is a group of partial classes (corresponding to the tables) with no annotation. The data annotation is usually added in a separate metadata file. Without this extra annotation, no default validation is there. EF simply hands the task of annotation to the programmer.
A: check this out for exactly what you are looking for. You might have to install Nuget and get some Asp.Net MVC 3 scaffolding to help you with the templates for these default validation you want. Good luck!
Hanlet
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Nested class in JavaScript I'm a totally newbie in JavaScript, which i need for a new project. And now I have a problem:
var main = new function() {
this.init = new function() {
//access something.init();
};
this.something = new function () {
this.init = function(){
//do something
//execute somethingother()
};
this.somethingother = function(){
//do something
};
};
};
main.init();
Can you please help me?
A: If you want to nest functions inside function - you CAN, but you should learn javascript syntax, how lexical scope and variable hoisting works, and overall - read Douglas Crockford's articles (or watch his videos).
The code you have shown will not work, try to look at my modification of it, and understand the difference.
var Main = function() {
/* this function is a constructor */
var m = this; // store scope
// do your init stuff
m.boringCollection = {
/* simple object with function inside */
/* notice JSON style formatting */
doStuff : function(){
//do something
},
doOtherStuff : function(){
//do something else
};
};
m.coolConstructor = function () {
var cc = this; // store scope
var sleep = true; // just an example variable
cc.moveMyself = function(){
//do something
};
cc.init = function() {
sleep = false; // just an example
cc.moveMyself(); // will work
cc.work(); // will FAIL, because function work is defined after its called
};
cc.work = function() {
// do some work
};
};
};
var main = new Main(); // make new instance of Main
main.boringCollection.doOtherStuff(); // will work
main.coolConstructor.init(); // will NOT work
var scrappy = new main.coolConstructor(); // make new instance of m.coolConstructor
scrappy.init(); // will work
A: JavaScript doesn't have classes out of the box. You need to implement classes yourself.
One popular implementation is JS.Class, if you don't want to write your own implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Can changes to a dll be made, while keeping compatibility with pre-compiled executables? We have a lot of executables that reference one of our dlls. We found a bug in one of our dlls and don't want to have to re-compile and redistribute all of our executables to fix it.
My understanding is that dlls will keep their compatibility with their executables so long as you don't change anything in the header file. So no new class members, no new functions, etc... but a change to the logic within a function should be fine. Is this correct? If it is compiler specific, please let me know, as this may be an issue.
A: Your understanding is correct. So long as you change the logic but not the interface then you will not run into compatibility issues.
Where you have to be careful is if the interface to the DLL is more than just the function signatures. For example if the original DLL accepted an int parameter but the new DLL enforced a constraint that the value of this parameter must be positive, say, then you would break old programs.
A: This will work. As long as the interface to the DLL remains the same, older executables can load it and use it just fine. That being said, you're starting down a very dangerous road. As time goes by and you patch more and more DLLs, you may start to see strange behaviour on customer installations that is virtually impossible to diagnose. This arises from unexpected interactions between different versions of your various components. Historically, this problem was known as DLL hell.
In my opinion, it is a much better idea to rebuild, retest, and redistribute the entire application. I would even go further and suggest that you use application manifests to ensure that your executables can only work with specific versions of your DLLs. It may seem like a lot of work now, but it can really save you a lot of headaches in the future.
A: It depends
in theory yes, if you load the dll with with LoadLibrary and haven't changed the interface you should be fine.
If you OTOH link with the .dll file using some .lib stub there is no guarantee it will work.
That is one of the reasons why COM was invented.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: PHP Parse XML issues when XML has variables Pls see snippet of XML file below:
<products>
<product>
<id>2589527</id>
<name>Samsung PS42C450</name>
<manufacturer>Samsung</manufacturer>
<manufacturer-id>22</manufacturer-id>
<description>42 in, Widescreen, Plasma, HD Ready, Samsung DNIe+ ,</description>
<category>Sound and Vision > Vision > TVs</category>
<category-id>2</category-id>
<number-of-retailers>16</number-of-retailers>
<image-url height="217" width="300">http://images.pricerunner.com/product/300x217/101294172/Samsung-PS42C450.jpg</image-url>
<rating type="average">
<average>4,1</average>
</rating>
<rating type="professional">
<average>4,1</average>
<num-ratings>1</num-ratings>
</rating>
<lowest-price currency="GBP">354.44</lowest-price>
<highest-price currency="GBP">549.00</highest-price>
</product>
</products>
I'm having problems parsing image-url, lowest-price and highest-price
I'm trying:
$lowprice = $products->lowest-price;
$highprice = $products->highest-price;
$imageURL = $products->image-url;
But they are returning nothing - any ideas what I'm doing wrong?
A: use $products->{'lowest-price'}. (with curly braces you can use special characters such as the minus sign)
Shai.
A: $products->lowest-price;
PHP will interpret as
($products->lowest) minus price;
There's no "lowest" in your $products object, and price is almost certainly not a defined constant, so both show up as null, get cast to 0's, and end up producing 0-0=0
A: It's probably because of the dash (assuming other properties work). Try encapsulating them with curly braces, like
$products->{highest-price};
A: There are (maybe) two unrelated issues.
1. XML structure
Your (broken) code, e.g. $products->lowest-price is wanting to access the lowest-price element which is a child of $products. Assuming the variable is named after the element, you have a little more work to do. The XML is structured like
<products>
└─ <product>
└─ <lowest-price>
So if $products is the `products> element, then three steps are needed.
$products->product->lowest-price
The above may be a non-issue, and simply unfortunate variable naming.
2. Dash (-) in element name
When presented with $a->b-c, PHP sees that as $a->b <minus> c as b-c is not a valid label (and no a valid object property name). As noted on the "SimpleXML Basic usage" manual page (link), the appropriate solution is to use the variable property syntax ala.
$products->product->{'lowest-price'}
See: http://php.net/simplexml.examples-basic (Example #3)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A potentially dangerous Request.Form value was detected from the client (wresult="I am also getting a request validation error when using WIF. I get correctly sent to the STS, but on the way back, I get this validation error.
I followed all the instructions.
<httpRuntime requestValidationMode="2.0" />
check!
[ValidateInput(false)]
check!
<pages validateRequest="false" >
check!
I tried a custom validator, but it never gets instantiated.
Error stack:
[HttpRequestValidationException (0x80004005): A potentially dangerous Request.Form value was detected from the client (wresult="trust:RequestSecuri...").]
System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection) +11396740
System.Web.HttpRequest.ValidateNameValueCollection(NameValueCollection nvc, RequestValidationSource requestCollection) +82
System.Web.HttpRequest.get_Form() +212
Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.IsSignInResponse(HttpRequest request) +26
Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.CanReadSignInResponse(HttpRequest request, Boolean onPage) +145
Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args) +108
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +270
Any suggestions?
A: See this answer if you are running .NET 4.5 which takes advantage of an updated request validator built in to ASP.NET.
A: <httpRuntime requestValidationMode="2.0"/>
after this add
<configuration>
<system.web>
<pages validateRequest="false" />
</system.web>
</configuration>
also in mvc3 there is an AllowHtml attribute
[AllowHtml]
public string Property{ get; set; }
here are some useful links
ASP.NET MVC – pages validateRequest=false doesn’t work?
Why is ValidateInput(False) not working?
A: You can put both constructs together in the system.web section as per ASP.NET : A potentially dangerous Request.Form value was detected from the client.
Note that this is standard ASP.NET functionality. It is not connected to WIF.
A: In MVC 3 (not sure about 2) you can add a global filter in global.asax.cs e.g.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ValidateInputAttribute(false));
}
That coupled with the following should allow all data in and display it correctly and safely I think:
<httpRuntime encoderType="Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary"/>
in web.config and using (note colon):
<%: Model.Something %>
or in Razor:
@Model.Something
and in some cases in Javascript:
@Html.Raw(Ajax.JavaScriptStringEncode(Model.Something))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: How to solve a crossdomain policy security exception in C# I have been trying to create a C# IRC client, I've got everything working, and when connecting to some networks it throws a socket policy exception as follows:
System.Security.SecurityException: Unable to connect, as no valid
crossdomain policy was found at
System.Net.Sockets.Socket.Connect_internal (IntPtr sock,
System.Net.SocketAddress sa, System.Int32& error, Boolean
requireSocketPolicyFile) [0x00000] in :0 at
System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP,
Boolean requireSocketPolicy) [0x00000] in :0 at
System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP)
[0x00000] in :0 at
System.Net.Sockets.TcpClient.Connect (System.Net.IPEndPoint
remote_end_point) [0x00000] in :0 at
system.Net.Sockets.TcpClient.Connect (System.Net.IPAddress[]
ipAddresses, Int32 port) [0x00000] in :0
Here's the code I am using to connect:
//connect the client
client = new TcpClient(serverAddress, serverPort);
The moment it tries to connect to most IRC servers it throws that exception, but for some it doesn't, as you probably realize I need the client to connect to any irc server that allows it.
I have tried searching for solutions on Google but all it came up with was Silverlight exceptions, I am not using Silverlight. I've been trying to resolve this for a week with no luck, I've been programming for 8 years, and I am quite adept at solving problems, but this is beyond me so any help is appreciated.
Regards, Amy.
A: Have you tried running the assembly as an administrator? If that works then it's a security issue and you need to specify the permission your program requires. So, if "Run as Admin" works, check: http://msdn.microsoft.com/en-us/library/system.net.socketpermissionattribute%28v=VS.110%29.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TraceSource.TraceEvent() fails logging when Exception message contains non-printable characters I have a call to TraceSource.TraceEvent() that is sometimes not writing to the Azure Diagnostics logs.
public class WorkerRole : RoleEntryPoint
{
private TraceSource trace = new TraceSource(
"ImportService", SourceLevels.Information);
public override void Run()
{
...
try
{
...
}
catch (Exception ex)
{
bool hasMsg = !string.IsNullOrEmpty(ex.Message);
trace.TraceEvent(TraceEventType.Error, 0,
"ex has message: " + hasMsg.ToString()); // this gets logged
trace.TraceEvent(TraceEventType.Error, 0,
"Inner exception message: " + ex.Message); // this does not
}
}
}
In certain cases, and I can't tell which since I can't read the Exception message, the second call is not found in the WADLogsTable. Are there certain characters that are not allowed, either by TraceSource or by DiagnosticMonitor?
To further narrow this down, the Exception in question is actually the InnerException of Exception: "There is an error in XML document (72, -499)". The XML that causes the Exception contains invalid character entities, eg . Could it be that the Exception message contains some of these character entities and the TraceSource fails to log them?
Edit: I was able to finally repro this in my dev environment and so I was able to examine the Exception in the debugger. The exception that won't log is an XmlException:
'', hexadecimal value 0x11, is an invalid character. Line 72, position -499.
In between the quotes is the non-printable character - it shows up as a black triangle in the debugger. So, this leads me to believe that my suspicion is correct - Some piece of the logging mechanism doesn't like the non-printable character. So, which piece? Or, more importantly, since it looks like I need to start sanitizing all of my strings when tracing, which characters should I look for to remove?
Is there some built in function that will sanitize a string, removing non-printable characters?
A: Interesting. It looks like you'll need to HTML encode the exception string. This will turn quotes into e.g. " and your ASCII non-printing character into , or similar.
So:
trace.TraceEvent(TraceEventType.Error, 0,
"ex has message: " + HttpUtility.HtmlEncode(hasMsg.ToString()));
trace.TraceEvent(TraceEventType.Error, 0,
"Inner exception message: " + HttpUtility.HtmlEncode(ex.Message));
should work just fine.
Frustratingly, HttpUtility is in System.Web, you'll need to add a reference to System.Web.dll to get this to go.
A: The answer to another question helped me to figure out a solution. I added a couple of extension methods for convenience:
public static string RemoveControlChars(this string s)
{
return Regex.Replace(s, @"(?![\r\n])\p{Cc}", "");
}
public static void TraceEvent(this TraceSource trace,
TraceEventType eventType, MyEvtEnum eventId, string message)
{
trace.TraceEvent(eventType, (int)eventId, message.RemoveControlChars());
}
I like the added benefit of not having to cast MyEvtEnum to int every time I call TraceEvent and it adds a natural overload, so this feels like a double win.
It bothers me that I have to do this at all. One of the primary uses of a diagnostics system is to log Exceptions. Such a diagnostics system should be able to handle any string that an Exception message might contain. I also lose line breaks, which is frustrating. Edit: Losing line breaks was a side effect of RemoveControlChars(). I didn't realize that \r and \n are included as "control characters". I've updated my regular expression to not replace \r and \n characters.
I don't like accepting my own answer, so if you have an alternate solution or an improvement to mine, please post it and if it's better, I'll accept it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I share a local Subversion repository between a Mac workstation and a Windows virtual machine? I would like to share a Subversion repository between my main computer running OS X Lion and a virtual machine running Windows 7 hosted in this computer (via VMware). I am unsure what is the best way to go about this.
I am thinking of setting up Apache and Subversion server on the OS X side and hopefully that would allow my virtual to access the repository from the Windows virtual using something like Tortoise SVN and accessing the repository at http://macHostName/pathToRepository. This seems feasible since the OS X side is always running.
An alternative could be setting up Apache and Subversion on the Windows virtual, which would require me to run the virtual everytime I want to access the repository from the OS X side. Perhaps Subversion can be set up in IIS? That would save some time if I don't need to install Apache.
Either way, I am unsure of the best way to go about this set up and what the caveats of each option are. I also haven't found a good walkthrough that will show how to set up a Subversion server on any OS using Apache.
Then, there is also the option of using svnserve, which I am unfamiliar with. Will a repository not served by an HTTP server like Apache be accessible for whoever is not serving it from the OS X host and the Windows virtual?
Any pointers will be appreciated.
A: Both Apache and svnserve are using network protocols, so the basic network setup between your host and your guest regarding routing and firewalls will be the same.
If you already have Apache installed and are familiar to it, I recommend to use it. Otherwise my recommendation is svnserve, because it is much simpler to setup and configure. The SVN-Book has a chapter for setting up svnserve both in Windows and in OSX.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: good references for comparing languages? I'm familiar with several computer languages (Java, C, C++, Python, Scheme, Javascript) but am only vaguely with the terminology for analyzing and comparing them (things like dynamic/static binding, dynamic/static types, pass-by-value vs. pass-by-reference, closures, operator overloading, etc.).
Is there a whitepaper or easily-readable-book that discusses these topics in enough depth for me to be able to look at an unfamiliar computer language and say to myself, "Oh, it has dynamic binding and static types", and to say "That's different from C++ because ... but similar because ..."?
A: If you like learning by example, Rosetta Code is a great resource. Its Language Comparison Table might be a good place to start.
I've found it helpful both for theoretical comparisons ("How do C++ and Java's respective exception handling systems differ?") and for practical work ("I know how to do a foreach() in PHP; what's the syntax for the equivalent operation in PERL?").
A: This free ebook may be somewhat heavier than what you are looking for, but is comprehensive:
Practical Foundations for Programming Languages (pdf 1.5Mb)
Here is an extract of the TOC:
I Judgements and Rules
1 Syntactic Objects
2 Inductive Definitions
3 Hypothetical and General Judgements
II Levels of Syntax
4 Concrete Syntax
5 Abstract Syntax
III Statics and Dynamics
6 Statics
7 Dynamics
8 Type Safety
9 Evaluation Dynamics
IV Function Types
10 Function Definitions and Values
11 Godel’s System T
12 Plotkin’s PCF
V Finite Data Types
13 Product Types
14 Sum Types
15 Pattern Matching
16 Generic Programming
VI Infinite Data Types
17 Inductive and Co-Inductive Types
18 Recursive Types
VII Dynamic Types
19 The Untyped l-Calculus
20 Dynamic Typing
21 Hybrid Typing
VIII Variable Types
22 Girard’s System F
23 Abstract Types
24 Constructors and Kinds
IX Subtyping
25 Subtyping
26 Singleton Kinds
X Classes and Meth
27 Dynamic Dispatch
28 Inheritance
XI Control Effects
29 Control Stacks
30 Exceptions
31 Continuations
XII Types and Propos
32 Constructive Logic
33 Classical Logic
XIII Symbols
34 Symbols
35 Fluid Binding
36 Dynamic Classification
XIV Storage Effects
37 Modernized Algol
38 Mutable Data Structures
XV Laziness
39 Lazy Evaluation
40 Polarization
XVI Parallelism
41 Nested Parallelism
42 Futures and Speculation
XVII Concurrency
43 Process Calculus
45 Distributed Algol
XVIII Modularity
46 Components and Linking
47 Type Abstractions and Type Classes
48 Hierarchy and Parameterization
XIX Equivalence
49 Equational Reasoning
50 Equational Reasoning
51 Parametricity
52 Process Equivalence
XX Appendices
A Mathematical Preliminaries
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Use linq to make a projection of an anonymous class with a list Suppose I have these classes:
public MyClass
{
public Property1 {get; set;}
public Property2 {get; set;}
public Property3 {get; set;}
public Property4 {get; set;}
public Property5 {get; set;}
public Property6 {get; set;}
public Property7 {get; set;}
public Property8 {get; set;}
public List<MySecondClass> MyList {get; set;}
}
public MySecondClass
{
public SecondProperty1 {get; set;}
public SecondProperty2 {get; set;}
public SecondProperty3 {get; set;}
public SecondProperty4 {get; set;}
public SecondProperty5 {get; set;}
}
Supposing that everything is instantiated, how would I use linq to make a projection that just had Property1 and Property2 and a list that just had SecondProperty4 and SecondProperty5?
Something like:
myClass.Select(x=> new { Property1 = x.Property1,
Property2 = x.Property2,
//Some Way To add The list here
}
NOTE: Just to clarify myClass is a List<MyClass> object.
A: myClass.Select(x=> new { Property1 = x.Property1,
Property2 = x.Property2,
SecondList = x.MyList.Select(i => new { i.SecondProperty4, i.SecondProperty5 }).ToList()
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CALayer anchorPoint doesn't work as expected with CGAffineTransform I have a CALayer, containing few sublayers (CATextLayers).
I'm applying transformations on the CALayer on some usual gestures (zoom, pan).
Everything works perfectly fine except that the scaling (zoom) is done towards the bottom left corner instead of the center of the screen.
I found some info in the CoreAnimation programming guide and I tried setting the anchor point to the center of my screen so that every transformation would be done towards that anchor....But it doesn't seem to be working as expected.
Here's my code :
// inside the init function :
_layerMgr = [[CALayer alloc] init];
_layerMgr.frame = [[UIScreen mainScreen] bounds];
_layerMgr.anchorPoint = CGPointMake(0.5, 0.5);
// done on gesture events :
CGAffineTransform tt = CGAffineTransformMakeTranslation( offset.x,
-offset.y);
CGAffineTransform st = CGAffineTransformMakeScale( scale ,scale );
CGAffineTransform rt = CGAffineTransformMakeRotation(rotation);
transform = CGAffineTransformConcat( tt, CGAffineTransformConcat(
st,rt) );
_layerMgr.transform = CATransform3DMakeAffineTransform(_transform);
Maybe the problem comes from my subviews ? I've added them using the addSubView method...nothing fancy...
A: try to transform on "YOUR" _layerMgr.transform instead of creating a new one:
for example:
[_layerMgr setTransform:CGAffineTransformScale (_layerMgr.transform, 2, 2)];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Simple way to check if input is in focus and to disable mouseleave function if true I have to admit that I'm definitely no jQuery genius but what seems like asimple solution has just totally eluded me.
Basically I have a drop down script working on a nested ul to display on rollover of its parent. In one of the nested ul I have a form that I would like to stop the mouseleave event if any of the inputs in the form are being entered into.
Here's the original code:
$(document).ready(function() {
/*------- navigation -------*/
$('.top_menu li').hover(function(){
var index = $('.top_menu li').index(this);
if($(this).children('ul').length != 0)
{
$(this).children('ul').show();
}
});
$('.top_menu li').mouseleave(function(){
$(this).children('ul').hide();
});
$('.login_cart li,.login_cart_captu li').hover(function(){
var index = $('.login_cart li').index(this);
if($(this).children('ul').length != 0)
{
$(this).children('ul').show();
}
});
$('.login_cart li,.login_cart_captu li').mouseleave(function(){
$(this).children('ul').hide();
});
});
I'm really only concerned with the .login_cart li portion of the script - that's the only one that has the form within it.
I've tried with a simple if/else statement to not hide if an input has focus but that hasn't worked so far.
Any help anyone could give me or to shed some light on this would be absolutely wonderful.
Thanks in advance!
A: you can bind the focus event of the form elements to a function that unbinds the mouseleave event from the .login_cart li:
$("#<form-id> input").focus(function() {
$(".login_cart li, .login_cart_captu li").unbind("mouseleave");
}
You'll just have to replace with the id of your form or you can use whatever selector you want to select your form.
A: jQuery 1.6 and newer has :focus built in. Not tested with .not(), but have tested this with a ! in front and .is(":focus"), just looked nicer with .not(); but both should do the same.
$('.login_cart li,.login_cart_captu li').mouseleave(function(){
if ($("#<form-id> input").not(":focus")) {
$(this).children('ul').hide();
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Disable Interpolation when Scaling a NOTE: This has to do with how existing canvas elements are rendered when scaled up, not to do with how lines or graphics are rendered onto a canvas surface. In other words, this has everything to do with interpolation of scaled elements, and nothing to do with antialiasing of graphics being drawn on a canvas. I'm not concerned with how the browser draws lines; I care about how the browser renders the canvas element itself when it is scaled up.
Is there a canvas property or browser setting I can change programmatically to disable interpolation when scaling <canvas> elements? A cross-browser solution is ideal but not essential; Webkit-based browsers are my main target. Performance is very important.
This question is most similar but does not illustrate the problem sufficiently. For what it's worth, I have tried image-rendering: -webkit-optimize-contrast to no avail.
The application will be a "retro" 8-bit styled game written in HTML5+JS to make it clear what I need.
To illustrate, here is an example. (live version)
Suppose I have a 21x21 canvas...
<canvas id='b' width='21' height='21'></canvas>
...which has css that makes the element 5 times larger (105x105):
canvas { border: 5px solid #ddd; }
canvas#b { width: 105px; height: 105px; } /* 5 * 21 = 105 */
I draw a simple 'X' on the canvas like so:
$('canvas').each(function () {
var ctx = this.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(21,21);
ctx.moveTo(0,21);
ctx.lineTo(21,0);
ctx.stroke();
});
The image on the left is what Chromium (14.0) renders. The image on the right is what I want (hand-drawn for illustrative purposes).
A: New answer 7/31/2012
This is finally in the canvas spec!
The specification has recently added a property called imageSmoothingEnabled, which defaults to true and determines if images drawn on non-integer coordinates or drawn scaled will use a smoother algorithm. If it is set to false then nearest-neighbor is used, producing a less smooth image and instead just making larger looking pixels.
Image smoothing has only recently been added to the canvas specification and isn’t supported by all browsers, but some browsers have implemented vendor-prefixed versions of this property. On the context there exists mozImageSmoothingEnabled in Firefox and webkitImageSmoothingEnabled in Chrome and Safari, and setting these to false will stop anti-aliasing from occurring. Unfortunately, at the time of writing, IE9 and Opera have not implemented this property, vendor prefixed or otherwise.
Preview: JSFiddle
Result:
A: In google chrome, canvas image patterns aren't interpolated.
Here is a working example edited from the namuol answer http://jsfiddle.net/pGs4f/
ctx.scale(4, 4);
ctx.fillStyle = ctx.createPattern(image, 'repeat');
ctx.fillRect(0, 0, 64, 64);
A: Last Updated: 2014-09-12
Is there a canvas property or browser setting I can change programmatically to disable interpolation when scaling elements?
The answer is maybe some day. For now, you'll have to resort to hack-arounds to get what you want.
image-rendering
The working draft of CSS3 outlines a new property, image-rendering that should do what I want:
The image-rendering property provides a hint to the user-agent about what aspects of an image are most important to preserve when the image is scaled, to aid the user-agent in the choice of an appropriate scaling algorithm.
The specification outlines three accepted values: auto, crisp-edges, and pixelated.
pixelated:
When scaling the image up, the "nearest neighbor" or similar algorithm must be used, so that the image appears to be simply composed of very large pixels. When scaling down, this is the same as auto.
Standard? Cross-browser?
Since this is merely a working draft, there's no guarantee that this will become standard. Browser support is currently spotty, at best.
The Mozilla Developer Network has a pretty thorough page dedicated to the current state of the art which I highly recommend reading.
The Webkit developers initially chose to tentatively implement this as -webkit-optimize-contrast, but Chromium/Chrome don't seem to be using a version of Webkit that implements this.
Update: 2014-09-12
Chrome 38 now supports image-rendering: pixelated!
Firefox has a bug report open to get image-rendering: pixelated implemented, but -moz-crisp-edges works for now.
Solution?
The most cross-platform, CSS-only solution so far is thus:
canvas {
image-rendering: optimizeSpeed; /* Older versions of FF */
image-rendering: -moz-crisp-edges; /* FF 6.0+ */
image-rendering: -webkit-optimize-contrast; /* Safari */
image-rendering: -o-crisp-edges; /* OS X & Windows Opera (12.02+) */
image-rendering: pixelated; /* Awesome future-browsers */
-ms-interpolation-mode: nearest-neighbor; /* IE */
}
Sadly this wont work on all major HTML5 platforms yet (Chrome, in particular).
Of course, one could manually scale up images using nearest-neighbor interpolation onto high-resolution canvas surfaces in javascript, or even pre-scale images server-side, but in my case this will be forbiddingly costly so it is not a viable option.
ImpactJS uses a texture pre-scaling technique to get around all this FUD. Impact's developer, Dominic Szablewski, wrote a very in-depth article about this (he even ended up citing this question in his research).
See Simon's answer for a canvas-based solution that relies on the imageSmoothingEnabled property (not available in older browsers, but simpler than pre-scaling and pretty widely-supported).
Live Demo
If you'd like to test the CSS properties discussed in the MDN article on canvas elements, I've made this fiddle which should display something like this, blurry or not, depending on your browser:
A: Edit 7/31/2012 - This functionality is now in the canvas spec! See separate answer here:
https://stackoverflow.com/a/11751817/154112
Old answer is below for posterity.
Depending on your desired effect, you have this as one option:
var can = document.getElementById('b');
var ctx = can.getContext('2d');
ctx.scale(5,5);
$('canvas').each(function () {
var ctx = this.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(21,21);
ctx.moveTo(0,21);
ctx.lineTo(21,0);
ctx.stroke();
});
http://jsfiddle.net/wa95p/
Which creates this:
Probably not what you want. But if you were merely looking to have zero blur then that would be the ticket so I'll offer it just in case.
A more difficult option is to use pixel manipulation and write an algorithm yourself for the job. Each pixel of the first image becomes a 5x5 block of pixels on the new image. It wouldn't be too hard to do with imagedata.
But Canvas and CSS alone won't help you here for scaling one to the other with the exact effect you desire.
A: Saviski's workaround explicated here is promising, because it works on:
*
*Chrome 22.0.1229.79 Mac OS X 10.6.8
*Chrome 22.0.1229.79 m Windows 7
*Chromium 18.0.1025.168 (Developer Build 134367 Linux) Ubuntu 11.10
*Firefox 3.6.25 Windows 7
But not works in the following, but the same effect can be achieved using CSS image-rendering:
*
*Firefox 15.0.1 Mac OS X 10.6.8 (image-rendering:-moz-crisp-edges works in this )
*Opera 12.02 Mac OS X 10.6.8 (image-rendering:-o-crisp-edges works in this )
*Opera 12.02 Windows 7 (image-rendering:-o-crisp-edges works in this )
The problematic are these, because ctx.XXXImageSmoothingEnabled is not working and image-rendering is not working:
*
*Safari 5.1.7 Mac OS X 10.6.8. (image-rendering:-webkit-optimize-contrast NOT works)
*Safari 5.1.7 Windows 7 (image-rendering:-webkit-optimize-contrast NOT works)
*IE 9 Windows 7 (-ms-interpolation-mode:nearest-neighbor NOT works)
A: All you have to do is set the image-rendering: pixelated CSS property on the <canvas>. This is now supported by all browsers. (https://caniuse.com/mdn-css_properties_image-rendering_pixelated)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "147"
} |
Q: Encoding issues crawling non-english websites I'm trying to get the contents of a webpage as a string, and I found this question addressing how to write a basic web crawler, which claims to (and seems to) handle the encoding issue, however the code provided there, which works for US/English websites, fails to properly handle other languages.
Here is a full Java class that demonstrates what I'm referring to:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class I18NScraper
{
static
{
System.setProperty("http.agent", "");
}
public static final String IE8_USER_AGENT = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; WOW64; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.2)";
//https://stackoverflow.com/questions/1381617/simplest-way-to-correctly-load-html-from-web-page-into-a-string-in-java
private static final Pattern CHARSET_PATTERN = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
public static String getPageContentsFromURL(String page) throws UnsupportedEncodingException, MalformedURLException, IOException {
Reader r = null;
try {
URL url = new URL(page);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setRequestProperty("User-Agent", IE8_USER_AGENT);
Matcher m = CHARSET_PATTERN.matcher(con.getContentType());
/* If Content-Type doesn't match this pre-conception, choose default and
* hope for the best. */
String charset = m.matches() ? m.group(1) : "ISO-8859-1";
r = new InputStreamReader(con.getInputStream(),charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
}
return buf.toString();
} finally {
if(r != null){
r.close();
}
}
}
private static final Pattern TITLE_PATTERN = Pattern.compile("<title>([^<]*)</title>");
public static String getDesc(String page){
Matcher m = TITLE_PATTERN.matcher(page);
if(m.find())
return m.group(1);
return page.contains("<title>")+"";
}
public static void main(String[] args) throws UnsupportedEncodingException, MalformedURLException, IOException{
System.out.println(getDesc(getPageContentsFromURL("http://yandex.ru/yandsearch?text=%D0%A0%D0%B5%D0%B7%D1%83%D0%BB%D1%8C%D1%82%D0%B0%D1%82%D0%BE%D0%B2&lr=223")));
}
}
Which outputs:
??????????? — ??????: ??????? 360 ??? ???????
Though it ought to be:
Результатов — Яндекс: Нашлось 360 млн ответов
Can you help me understand what I'm doing wrong? Trying things like forcing UTF-8 do not help, despite that being the charset listed in the source and the HTTP header.
A: Determining the right charset encoding can be tricky.
You need to use a combination of
a) the HTML META Content-Type tag:
<META http-equiv="Content-Type" content="text/html; charset=EUC-JP">
b) the HTTP response header:
Content-Type: text/html; charset=utf-8
c) Heuristics to detect charset from bytes (see this question)
The reason for using all three is:
*
*(a) and (b) might be missing
*the META Content-Type might be wrong (see this question)
What to do if (a) and (b) are both missing?
In that case you need to use some heuristics to determine the correct encoding - see this question.
I find this sequence to be the most reliable for robustly identifying the charset encoding of an HTML page:
*
*Use HTTP response header Content-Type (if exists)
*Use an encoding detector on the response content bytes
*use HTML META Content-Type
but you might choose to swap 2 and 3.
A: The problem you are seeing is that the encoding on your Mac doesn't support Cyrillic script. I'm not sure if it's true on an Oracle JVM, but when Apple was producing their own JVMs, the default character encoding for Java was MacRoman.
When you start your program, specify the file.encoding system property to set the character encoding to UTF-8 (which is what Mac OS X uses by default). Note that you have to set it when you launch: java -Dfile.encoding=UTF-8 ...; if you set it programatically (with a call to System.setProperty()), it's too late, and the setting will be ignored.
Whenever Java needs to encode characters to bytes—for example, when it's converting text to bytes to write to the standard output or error streams—it will use the default unless you explicitly specify a different one. If the default encoding can't encode a particular character, a suitable replacement character is substituted.
If the encoding can handle the Unicode replacement character, U+FFFD, (�) that's used. Otherwise, a question mark (?) is a commonly used replacement character.
A: Apache Tika contains an implementation of what you want here. Many people use it for this. You could also look into Apache Nutch. On the other hand, then you wouldn't have to implement your own crawler at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Using .htaccess to redirect a domain to another URL I have a site running wordpress, it's the full site. One of the pages is like a contact-us form located at www.ourdomain.com/contact-us/
I also have a URL like contactourdomain.com and I want it to redirect to www.ourdomain.com/contact-us/
We used to do this with a redirect on network solutions, but I prefer to have it all done right on the server if possible. I've got it sort of working but when you visit the link is still says contactourdomain.com/contact-us/ as the URL, and that breaks all the other ones.
Any suggestions?
A: .htaccess
Options -MultiViews
RewriteEngine on
RewriteBase /
# Rewrite
RewriteRule ^(.*)$ http://www.ourdomain.com/contact-us//$1 [L]
A: if you add this in .htaccess is it working?:
RewriteRule ^$ contact-us/ [R=301,L]
keep me posted..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Google plus one button is not visible while loading it on partial postback asp.net While implementing google plus one button through addthis on one our localized pages where the following data was retrieved from a backend (assume database), facing a wierd problem, the plus button is not getting loaded. we ajax based partial postback
The following html is added to the page only during a partial postback
<div class="addthis_toolbox addthis_default_style" style="float:right;">
<a class="addthis_button_google_plusone" g:plusone:size="small"></a>
</div>
At the same time , the script is included through
ScriptManager.RegisterStartupScript(Page, typeof(string),
"RegisterHTMLScript" + scriptID,
scriptstring,
false);
Value of scriptstring is
<script type="text/javascript">
var addthis_config = {"data_track_clickback":true};
if (window.addthis) {
addthis.toolbox('.addthis_toolbox');
addthis.init();
}
else {
$.getScript('http://s7.addthis.com/js/250/addthis_widget.js#username=XXXXX&domready=1');
$.getScript('https://apis.google.com/js/plusone.js');
}
</script>
I am not able to see any client errors, but at the same time +1 button is not visible. What could be wrong?
Instead of RegisterStartupScript, I tried
1. adding ScriptReference programatically to the current script manager.
2. RegisterClientScriptInclude method on script manager.
But almost same result.
A: Here it goes,
During a partial postback, ASP.NET AJAX needs to know the list of dependent scripts that are to be downloaded so that it can announce "DOCUMENT IS READY" once all of them are downloaded.
In ASP.NET 3.5 and below adding "notifyscriptloaded" is the only means for ASP.NET to know a dependent script resource has to be loaded - during a partial postback.
When you register a script with notifyscriptloaded, ASP.NET waits till the script is downloaded and makes sure to call document ready only after downloading this. This way it ensures document ready of the script is being fired as expected.
NOTE: ASP.NET 4.0 does NOT need this (I am not sure how it is done in it however).
So the problem now is very clear. When using an external 3rd party javascript file as a reference, ASP.NET limits us to refer it only from static page header (or master page). There is no way to download the script during partial postback - Unless you have the control over thhird party script and add "notifyscriptloaded" in it.
Solution, I had to make this external third party script a static reference in page header. This did not hurt me because, I anyway had several instances of +1 button across multiple pages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I plot the densities from a histogram? So I want to do something like this in R:
x <- rnorm(1000, 100, 50)
h <- hist(x, breaks="fd")
z <- plot(h$breaks, h$density)
The problem is that the $breaks field in the histogram has one more value than the $density field? is there an easy way around this problem?
A: Turns out all I needed to do was to set the freq field to FALSE
So I just did hist(rnorm(1000, 100, 50), freq="FALSE") and that did a histogram of relative frequencies.
A: I'm not sure exactly what the problem is, but you could just drop either the first or last element of h$breaks to plot the points at either endpoint, or you could drop the last element and then add half the bin width to plot them at the midpoints:
plot(h$breaks[-length(h$breaks)] + 5, h$density)
That just fixes your specific problem, though. There may be a better way of using hist in general, if you expanded on what you're trying to do a bit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Boosting Solr Range Query Is there a way to boost based on a range query in solr.
I've tried adding the boost to the end of the range, but it doesn't seem to apply the boost to the score. I've run the query without the "(: ||" to ensure that I'm getting results that are both inside and outside the range. The score reflects that boosting is taking place, but the items that match the boosted portion of the query do not recieve extra points.
Smaple Query:
q=lastName:(Smith) (*:* || dob:[1980-09-30T12:09:42.3804564-07:00Z TO 1983-09-30T12:09:42.3844564-07:00Z]^100)
Does anyone know how I can get solr to incorporate the boosted field into the result scores?
A: I'm fairly new to this, but I think you would use a boost query to elevate those results:
&bq=dob:[1980-09-30T12:09:42.3804564-07:00Z TO 1983-09-30T12:09:42.3844564-07:00Z]^100
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Website youtube embedded video keeps playing I'm using the iframe youtube gave me to embed a video on my website.
I also am using a css popup which i learned from this page
http://www.pat-burt.com/web-development/how-to-do-a-css-popup-without-opening-a-new-window/
So my html code looks like this
<div id="blanket" style="display:none;"></div>
<div id="popUpDiv" style="display:none;">
<font size="4" color="#ffffff"><a style="color: #ffffff" href="javascript:void(null)" onclick="popup('popUpDiv')">Close</a><br></font>
<iframe width="560" height="315" src="http://www.youtube.com/embed/h3Pb6IyFvfg" frameborder="0" allowfullscreen></iframe>
</div>
<a href="javascript:void(null)" onclick="popup('popUpDiv')" class="more_details">more details</a>
And everything is working as i want it to however if I switch my browser to either internet explorer or chrome when i select close to close the popup the video keeps playing? I've done some googling and found others with my same issue however I only could find code that didn't work as it was supposed to.
Basically I'd like to stop the video when the popup is closed how could this be done. Thank you for any help
A: I faced the same problem before.
What I did is remove the src of the iframe when I close the popup and put it back on when I open it in jQuery. This way, i'm sure the video won't keep playing when the popup is closed.
Edit Added an Exemple:
Add an optional parameter in your function containing the video url
<a href="javascript:void(null)" onclick="popup('popUpDiv', 'http://www.youtube.com/embed/NWHfY_lvKIQ')" class="more_details">more details</a>
Set the src of your iframe in your function with the video url
function popup(pPopup, pYt){ //pYt optional
$('iframe').attr('src', pYt);
}
Add this line in your code when you want to remove the source
$('iframe').attr('src', '');
A: You can also ditch the iframe code and use a youtube embed. Then in your javascript event you can player.pauseVideo(); where player is your embedded object.
Use the Youtube Player API: http://code.google.com/apis/youtube/js_api_reference.html#Playback_controls
A: Changing the display of the frame isn't going to stop the video. You would have to remove the iframe element when the popup closes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Uncaught TypeError: Object [object DOMWindow] has no method 'set' on backbone-min.js I am receiving this error message when including backbone in my application,
Uncaught TypeError: Object [object DOMWindow] has no method 'set'
but I have jquery (1.4.4) and underscore.js (1.1.7) loaded before backbone, why is this method still missing?
A: Or you are instantiating a model without new prefix which would cause it to be bound to global window instead of this. SO reference.
A: Based solely on the error message, I would search your code for this.set. It appears that you're referencing thiswith the expectation that it's a model, but the function isn't bound correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: which method is used to register the device token for push notification? I am able to get the deviceToken in the below method, now I want to know how to register the deviceToken for push notification,because I am not sure after getting the device token which method or API is used to register the device token for Push Notification and how this registration process works?
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"APN device token: %@", deviceToken);
}
A: Well, to start I want to make sure that if you are running the following in the registerForRemoteNotificationTypes when the app launches. Here is what you can add to your AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
// Send the deviceToken to server right HERE!!! (the code for this is below)
NSLog(@"Inform the server of this device token: %@", deviceToken);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
// Place your code for what to do when the ios device receives notification
NSLog(@"The user info: %@", userInfo);
}
- (void)application:(UIApplication *) didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
// Place your code for what to do when the registration fails
NSLog(@"Registration Error: %@", err);
}
When you mention registering the device token for push notification you have to send the deviceToken to you server that is sending the push notifications and have the server save it in the database for the push. Here is an example of how you can send this to your server.
NSString *host = @"yourhost";
NSString *URLString = @"/register.php?id=";
URLString = [URLString stringByAppendingString:id];
URLString = [URLString stringByAppendingString:@"&amp;amp;amp;amp;devicetoken="];
NSString *dt = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
dt = [dt stringByReplacingOccurrencesOfString:@" " withString:@""];
URLString = [URLString stringByAppendingString:dt];
URLString = [URLString stringByAppendingString:@"&amp;amp;amp;amp;devicename="];
URLString = [URLString stringByAppendingString:[[UIDevice alloc] name]];
NSURL *url = [[NSURL alloc] initWithScheme:@"http" host:host path:URLString];
NSLog(@"FullURL=%@", url);
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
if you need anymore help I will be happy to help. Contact me on either website: Austin Web and Mobile Guru or Austin Web Design
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Difference between ClassLoader.getSystemResourceAsStream and getClass().getResourceAsStream() Given this code:
/* 1 */ InputStream in1 = ClassLoader.getSystemResourceAsStream("foobar.txt");
/* 2 */ InputStream in2 = this.getClass().getResourceAsStream("/foobar.txt");
Do both return the same resource (I think the answer's "yes")?
Do they both access the "same" classpath? Why is the method name in #1 "get System ResourceAsStream", but for #2 it's just "getResourceAsStream"?
Thanks
A: According to the javadoc
Open for reading, a resource of the specified name from the search
path used to load classes. This method locates the resource through
the system class loader (see getSystemClassLoader()).
The classloader used to load this is not necessarily the system classloader. In a simple desktop app, this will probably be true. But webapps - amongst other things - typically have more complex classpath hierarchies and so that won't necessarily be the same. In a complex classpath, therefore what's returned will also depend on how many copies of 'foobar.txt' are floating around your classpath.
The short answer is that you can't assume that they will return a stream for the same resource.
A: The key difference is the class loader.
The following uses the System ClassLoader
ClassLoader.getSystemResourceAsStream("foobar.txt");
While this one uses the Classloader returned by getClass()
this.getClass().getResourceAsStream("/foobar.txt");
In other words, whether both statements behave exactly the same or not, depends on the application classloader. For a simple application, both refer to the same classloader. However, for most applications (like a web application running within Servlet container), that will not be the case.
In general, I would say getClass().getResourceAsStream() will be the better choice as it will use the same classloader as the Class the code belongs to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: CSS selector to hide first of a set To start, I have no control over the html. I am looking for a CSS solution. CSS2/3 are fine. I have no idea why I can't figure this out, but hey it's Friday. I guess my brain is scrambled.
http://jsfiddle.net/mrtsherman/PDBmU/13/
I need to hide the span.smalltext containing (Documentation x.x.x). In the fiddle I highlighted this with a red box.
<div class="result">
<span class="icon icon-page" title="Page">Page:</span>
<a href="/display/">Create</a>
<!-- Hide this span -->
<span class="smalltext" style="border: 1px solid red;">
(<a href="/display/doc">Documentation x.x.x</a>)
</span>
<br>
... <span class="search-highlight"><strong>search</strong></span> project ...
<br>
<span class="smalltext">
Jun 17, 2011 14:57
</span>
</div>
<!-- ## The above structure is repeated many times. I would like to hide all of them. -->
I tried something like this so far - but it didn't work
div.result span.smalltext:first-child {display: none;}
A: Could...
.result a + .smalltext {
display:none;
}
... do it? I also made a jsFiddle demo
A: .result span:nth-of-type(2) {display:none}
works too... albeit messy like :P
A:
I just need the correct selector.
Something like div.result
span.smalltext:first-child {display: none;}
See this answer for why your attempt did not work: Why doesn't this CSS :first-child selector work?
Use .result > span:first-child + a + .smalltext instead.
This selector will work in all browsers (except IE6).
A: Two different approaches I'd say, either CSS or jQuery
CSS:
.result span:nth-of-type(2) {font-weight:bold;}
JS:
$('.result').each(function(){
$(this).find('.smalltext:first').css('background-color', 'red');
});
That's as long as the HTML really doesn't change. Fiddle'd it, too http://jsfiddle.net/PDBmU/19/
/edit
Obviously the css attributes given in this example are for demonstration purpose, you'd need display:none; or display:hidden; depending on wanted output
A: i'm not sure, how stable this is, as your output could contain a lot of a + spans, but this should work with your example
.result > a + span {
display: none;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I do basic html validation within a column in a SQL Server database? I have a database table with HTML snippets (not whole documents) in a column and I need to do some basic HTML validation of the contents. My initial need is to just be able to run a one time query+validation report, not anything more complicated than that.
A: I would suggest using Regex -
http://msdn.microsoft.com/en-us/magazine/cc163473.aspx
Example -
select dbo.RegexMatch( N'123-45-6789', N'^\d{3}-\d{2}-\d{4}$' )
Or stricly t-sql -
http://blogs.msdn.com/b/khen1234/archive/2005/05/11/416392.aspx
However, CLR User-Defined Functions are probably the way to go.
A: SQL Server does have some XML validation capabilities built in for a field of type XML. Given that HTML is a subset of XML you might be able to twist that functionality to make SQL Server do the work for you.
A: I read Jeff's post here http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html and realized that I need to use a real parser after all.
It looks like http://tidy.sourceforge.net/ will get me what I need, I'll just have to write an ugly script that goes row by row and shells out to Tidy.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Validation on a single DataGridView column How can I perform validation on a particular DataGridViewTextBoxColumn column in my DataGridView, so that a user is required to enter a value into it?
A: i think you are looking for datagrid view text box column validation right ? if so would you pls take a look at this link
http://www.codeproject.com/Questions/93691/Validations-inside-DataGridView-TextboxColumn.aspx
EDIT 1:
you Can use this solution but it validates only numbers ,or if you want to validate the text you can change the code..
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
DataGridViewTextBoxCell cell = dataGridView1[2, e.RowIndex] as DataGridViewTextBoxCell;
if (cell != null)
{
if (e.ColumnIndex == 2)
{
char[] chars = e.FormattedValue.ToString().ToCharArray();
foreach (char c in chars)
{
if (char.IsDigit(c) == false)
{
MessageBox.Show("You have to enter digits only");
e.Cancel = true;
break;
}
}
}
}
}
NOTE: this code is not tested ..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Like button with layout=button_count blows out the default 90px I am using an iframe version of the FBL Like button with the button_count layout. I also have set show_faces=false. This layout used to show ( and the code generator still shows ) just the like button and a count box with the number of likes.
Now it seems to be displaying a my name linked to the right of the like button and then a string below my name with the number of other users who like the page. The Like button documentation says that the default width is 90 pixels and this is what I specify in the iframe code, however this new layout does not fit within 90 px.
Does anyone know how I can get the old layout back or is this a case of facebook changing functionality and not updating the docs?
A: Try this: for all the query strings in src, change all the & to &
A: Just set data-layout="button_count", and you'll get a smaller version.
A: That is the standard view format.
layout=button_count is the layout that you are lookign for to accomplish this.
Minimum width: 90 pixels. Default width: 90 pixels. Height: 20 pixels
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-send="false" data-layout="button_count" data-width="90" data-show-faces="false" data-font="lucida grande"></div>
•layout - there are three options.
•standard - displays social text to the right of the button and friends' profile photos below. Minimum width: 225 pixels. Default width: 450 pixels. Height: 35 pixels (without photos) or 80 pixels (with photos).
•button_count - displays the total number of likes to the right of the button. Minimum width: 90 pixels. Default width: 90 pixels. Height: 20 pixels.
•box_count - displays the total number of likes above the button. Minimum width: 55 pixels. Default width: 55 pixels. Height: 65 pixels.
Source: Facebook Developers
A: I think this is a case of Facebook changing functionality without updating the docs.
It seems the iFrame version of the like button now ignores the button_count layout parameter and displays the standard layout anyways. To solve it just switch to the HTML5 or XFBML version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Additional argument to process during start of app from CLI c# I have made a HTML parser thanks to the help of this website but I am running into a new obstacle. I have a webserver that hosts configuration files that I want parsed. Instead of loading my app and inserting the link I want to just pass on a argument to my app directly from the website, for example:
htmlparser.exe http://thisismyconfig.com/config.cfg
And I want the app to load up and run the parse function in my code. It is a .NET application and I think I need to utilize ClickOnce but not too sure. Any help is appreciated, thank you!
UPDATE***
Ok, so with the following code my app does what it should but it faces one last problem (site keeps formatting the code incorrectly):
private void Form1_Load(object sender, EventArgs e)
{
string[] args = Environment.GetCommandLineArgs();
foreach (string arg in args)
{
MyURL = args[1];
runtimeButton_Click(sender, e);
}
}
but my URL that I feed it in the argument is:
http://jossc/configtc.aspx?IP=201.73.128.15&m=c
What is going on?
For some reason it removes the last 4 characters: &m=c
A: So you've got a console app and you want to hand to it the HTTP address to a config file?
You don't need ClickOnce for that. Inside your console app, look at Environment.CommandLine to get the command line arguments passed to your app. See MSDN's Command Line Parsing Tutorial for more info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Intermittent "UDT not defined" error when compiling VBA but code runs without errors I'm building an Access database and I'm getting a "User-defined type not defined" error when I compile the project using Debug > Compile, but the database opens and runs without any runtime errors, and everything seems to work. No location in the code is given, just an error dialog.
The UDT error doesn't happen every time, but it does happen most of the time. If I don't have any forms open when I compile and I have recently opened Access it seems to work. If I open a form and try again (after making a superficial change so it will allow me to recompile) I get the error.
This is not true consistently however. I often get the error when no forms are open, but I ALWAYS get the error when forms are open. It doesn't seem to matter if they are open in design or form view.
What could be causing this? What kind of error should I be looking for?
Using Access 2010.
A: Thanks HansUp, a decompile seems to have resolved the issue.
The instructions you linked were helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Load all AJAX content, including images, before rendering I'm working on a project that needs to automatically load content and insert it at the beginning of a page without disturbing the page's vertical scroll position. Inserting the content, calculating its height, and then adding that to the page's scroll position has worked for me so far, but now I'm encountering issues where it doesn't get the correct height if there are images (presumably because those images haven't loaded yet). How can I load the images before inserting the content into the page, so that it calculates the correct height upon insertion? Or is there an even better way to go about doing this?
Some (simplified) code for reference:
$.ajax({
type: "POST",
url: post_url,
dataType: "json",
data: post_data,
success: function(data, stat, jqXHR) {
if (data.content.length) {
var updates = build_content(data.content);
$(updates).insertAfter("#" + id + " .reload_button");
// Works if there's no external content
$("#" + id).scrollTop($("#" + id).scrollTop() + $(updates).height());
}
}
});
Update: I've tried using .load() to wait until the content as fully loaded:
(...)
var updates = build_posts(data.response.posts).hide();
$(updates).insertAfter("#" + id + " .reload_button");
console.log("Waiting for DOM to load completely @ " + new Date().getTime());
updates.ready(function() {
console.log("Done @ " + new Date().getTime());
$(updates).show();
(...)
It was apparently loaded the same millisecond that it inserted the content, which can't be right since it had to load an image as well. Am I making an obvious mistake here?
Update: using .load instead of .ready just causes the callback function never to run at all. The documentation says that it's buggy and might not be called if the images were cached by the browser, but I don't know if this is really what's happening.
A: I ultimately solved this with Alexander Dickson's waitForImages jQuery plugin. I don't know why .load() refused to work, but so far this plugin has had no issues, so I'm sticking with it.
A: You can take a look at the masonry-jquery plugin there is a function imageloaded that meets your requirement.
A: You can't really control the order of items loading in a page. Sure, you could load the images first, using JavaScript and put them in the cache first, but you'd have to parse the incoming HTML before inserting it into the DOM to make this work.
You may want to experiment with rendering to a hidden Iframe, then copying the content from there into your page after it renders there.
A: If these images are in the initial markup, then you should be able to run your code within a load event handler. The load event should only be triggered once all content (including images) is loaded.
A: If there is a known maximum height of the content then you could simply style your page to allow for it to load content somewhere without disturbing the page.
Here is a very simple jsFiddle example that when you scroll down the page and and click an item (arbitrary event) to "load" the top content, the scroll position is not affected.
A: In addition to success and error $.ajax also has a complete handler that executes code on completion of the ajax call.
Don't really have an example that would be relevant to your code, and I'm not sure it's what you are looking for or if you have already checked it out, but I'm thinking if you ran your function in the complete handler instead of the success handler the images should already be loaded and ready to go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why isn't my objective-C child class inheriting the property of it's parent? In the .h and .m files of my parent class (WebServiceMessage) I have the following lines:
@property(nonatomic, retain) NSMutableData *receivedData;
@synthesize receivedData;
My child class has the following definition:
@interface RegistrationMessage : WebServiceMessage{...}
-(bar)foo;
So in theory, the child class should be able to use receivedData without needing to declare it itself -- it should inherit the existence of that variable from it's parent.
@implementation RegistrationMessage
...
-(bar)foo{
self.receivedData=[NSMutableData data];//Error: Property 'receivedData' not found on object of type 'Class'
}
I've checked, and I'm using #import for the parent class in both the .h and the .m files, just to be sure, but the error is still showing up.
A: Based on the error, it looks like you're omitting an important detail: foo is not an instance method, it's a class method (that is, it's + (void)foo rather than - (void)foo). You can only set properties (or instance variables in general) on instances.
A: Something is missing the the code that you duid not show, the below compiles fine:
@interface WebServiceMessage : NSObject
@property(nonatomic, retain) NSMutableData *receivedData;
@end
@implementation WebServiceMessage
@synthesize receivedData;
@end
@interface RegistrationMessage : WebServiceMessage
-(void)foo;
@end
@implementation RegistrationMessage
-(void)foo {
self.receivedData = [NSMutableData data];
}
@end
I did have to get rid of the bar return type because it is an unknown type and there was no return statement in method foo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7615060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.