text
stringlengths
8
267k
meta
dict
Q: Facebook App users on Google map I need to create a Google map that would display all my app users. The problem is, that that Facebook doesn't seem to provide enough information to do that, country at most. I'd like to display user position on map at least to the proximity of the city. The only option I see, is to track user's location using their IP. What are the other options? A: If the user has provided it, you can get their current location (city, state, country) by prompting for the 'user_location' and/or 'friends_location' permissions. You might also want to check out the 'user_checkins' and/or 'friends_checkins' permissions for more timely and accurate locations. http://developers.facebook.com/docs/reference/api/user/ Or as a fallback, like you say, you can usually get an approximate location by their IP. But that's not always very accurate.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: "real" execution time limit Using set_time_limit() or max_execution_time, does not "really" limits (except on Windows) the execution time, because as stated in PHP manual: Note: The set_time_limit() function and the configuration directive max_execution_time only affect the execution time of the script itself. Any time spent on activity that happens outside the execution of the script such as system calls using system(), stream operations, database queries, etc. is not included when determining the maximum time that the script has been running. This is not true on Windows where the measured time is real. A solution is proposed in PHP comments to have a "real" execution time limit like what I'm looking for, but I found it unclear/confusing. A: I might be wrong, but as far as I understand you ask for explanation of the "PHP comments" solution code. The trick is to spawn a child process, using pcntl_fork function, which will terminate the original (parent) process after some timeout. Function pcntl_fork returns process id of newly created child process inside a parent process execution thread and zero inside child process execution thread. That means parent process will execute the code under if statement and the child process will execute code under else. And as we can see from the code, the parent process will perform endless loop while child process will wait 5 seconds and then kill his parent. So basically you want to do something like this: $real_execution_time_limit = 60; // one minute if (pcntl_fork()) { // some long time code which should be // terminated after $real_execution_time_limit seconds passed if it's not // finished by that time } else { sleep($real_execution_time_limit); posix_kill(posix_getppid(), SIGKILL); } I hope I've exlained it well. Let me know if you sill have question regarding this solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: What is the default timeout when calling the Facebook API using C# SDK? Below is the code used to connect to the Facebook API, will it have a default timeout? I was wondering this because I think this code should be put in a try/catch statement in case the request to Facebook times out. ConnectSession _connectSession = new ConnectSession(GetApplicationKey(), GetSecretKey()); Api _facebookAPI = new Api(_connectSession); _facebookAPI.Friends.Get(); Does anyone know the default time out (if any) for the above calls? Thanks! A: Generally its somewhere around 12s. You can see time out reports in your application insights to help debug and monitor them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569577", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HttpContext Class and its Thread Safety I have an Singleton object in application that has following property: private AllocationActionsCollection AllocationActions { get { return HttpContext.Current.Session["AllocationOptions.AllocationActions"] as AllocationActionsCollection; } set { HttpContext.Current.Session["AllocationOptions.AllocationActions"] = value; } } I'm dealing with one error (HttpContext.Current.Session["AllocationOptions.AllocationActions"] is null even though it is supposed to me always set to valid instance...). I just read in MSDN that HttpContext instance member are not guaranteed to be thread safe! I wonder if that could be the issue. There could be a resources race somewhere in application and the moment where HttpContext.Current.Session["AllocationOptions.AllocationActions"] is null is the moment where AllocationActions setter is used using this statement: AllocationActions = new AllocationActionsCollection(Instance.CacheId); My questions are: a) I'm shocked that HttpContext.Current.Session is not thread safe. How to safely use that property then? b) do you have any ideas why that Session variable can be null (even though I'm pretty sure I'm setting it before it's used for the first time)? Thanks,Pawel EDIT 1: a) line that initializes session variable is set every 2 minutes with following statement (executed in Page_Load) AllocationActions = new AllocationActionsCollection(Instance.CacheId); b) code that calls getter is called in event handlers (like Button_Click) c) there is not custom threading in application. only common HTTP Handler A: A singleton object is realized by restricting the instantiation of a class to one object. HttpContext.Current.Session is an area dedicated to a single user; any object stored in Session will be available only for the user/session that created it. Any object stored in Application will be available only for every user/session. Any static object also, will be available only for every user/session. Suggested implementations always use static objects.. why didn't you? A: HttpContext.Current returns a separate HttpContext instance for each request. There can be multiple threads processing requests, but each request will get its own HttpContext instance. So any given instance is not being used by multiple threads, and thread safety is not an issue. So unless you're manually spinning up multiple threads of your own for a single request, you are threadsafe. A: The thread safety of the HttpContext class is pretty standard for .NET. The basic rule of the thumb (unless explicitly specified) is that static members are thread safe and instance members aren't. In any case it is hard to tell why your session variable is null without looking more into the code that sets/resets it. Or perhaps you are calling your get_AllocationActions method from a different session than the one you set it in. Again, more code would help. A: To access the session property safely you would just wrap the access in a lock statement and use the SyncRoot object of the session class.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569578", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SITE_ROOT = URL + Variable? Possible Duplicate: SITE_ROOT = Variable? How can I get this: define ('SITE_ROOT', $_SERVER['DOCUMENT_ROOT'] . SITE_BASE); to look something like this: define ('SITE_ROOT', [variable from domain.com/dir/data.php] ); I'd very much appreciate if someone could help me with a solution. Many thanks. A: You probably need to include the data.php file before you define the SITE_ROOT constant. Like this: <?php require_once('data.php'); define('SITE_ROOT', $yourVariableFromDataDotPHP); ?> Although it looks a bit weird...don't know the context of course.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: How to rotate bar chart like the example "CPTTestApp-iPhone" provided in core plot? I am trying to have my bar chart have the same rotate behaviour as in the example provided in core plot. I am using xcode4 and been googling with no luck for a while to get this working . If i copy my code in the example it does work fine, how can I do it for my own project? See images below Portrait Landscape A: Add this: $self.hostingView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);$ Credit isn't mine, the answer was also on Stack Overflow somewhere else...can't find it. PS: Obviously replace <self.hostingView> with whatever CPTGraphHostingView you allocated to host your graph and plots in.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: decorators in python I am trying to understand the functioning of decorators. What am i doing wrong in the following code. Please do correct it As I have understood when aFunction() is called it in turn calls myDecorator() which also makes a call to afunction(). Right? Also how to pass parameters into afunction() class myDecorator(object): def __init__(self, f): print "inside myDecorator.__init__()" f(1) # Prove that function definition has completed def __call__(self): print "inside myDecorator.__call__()" @myDecorator def aFunction(*a): print a print "inside aFunction()" print "Finished decorating aFunction()" aFunction(2) A: class myDecorator(object): def __init__(self, f): print "inside myDecorator.__init__()" # save a reference to the real function, so it can be called later self.f = f def __call__(self, *args, **kwargs): print "inside myDecorator.__call__()" # call the real function and return its result # passing it any and all arguments return self.f(*args, **kwargs) @myDecorator def aFunction(*a): print a print "inside aFunction()" print "Finished decorating aFunction()" aFunction(1) print "Finished calling aFunction() A: Your __call__ method is missing the parameter, which you give to aFunction. class myDecorator(object): def __init__(self, f): print "inside myDecorator.__init__()" f(1) # Prove that function definition has completed self.__function = f def __call__(self, *args): # the *args magic is here to mirror the original parameter list of # the decorated function. But it is better to place here parameter list # of the function you want to decorate, in order to minimize error possibilities print "inside myDecorator.__call__()" return self.__function(*args) @myDecorator def aFunction(*a): print a print "inside aFunction()" print "Finished decorating aFunction()" aFunction(1) aFunction('a', 23, 42) A: f, in __init__, needs to be saved, then the __call__ method needs to call it. Something like this: class myDecorator(object): def __init__(self, f): print "inside myDecorator.__init__()" self.f = f print "function has been saved" def __call__(self, *args): print "inside myDecorator.__call__()" result = self.f(args) print "done with f()" return result @myDecorator def aFunction(*a): print a print "inside aFunction()" aFunction(1) What happens with decoration is that the original function is replaced with whatever the decorator returns. Your original code, however, was not saving any reference to aFunction so it was getting lost.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: facebook FB.ui feed dialog customize option not working I have a facebook app which has feed dialog link. on Clicking the link the feed dialog opens up. I try to customize the friends who shall be able see the wallpost. This opens up the custom privacy dialog, but closes the feed dialog. So I cannot move forward with the wall post. This happens when: The app is being used as a page tab AND The display mode is iframe. This does not happens if: The app is being used as an app (apps.facebook.com/app_name) OR The display mode is popup. Please advice... A: there is currently a bug in facebooks feed dialogs and the privacy dropdown... facebook should sort this out soon. In addition, you should report this issue here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implement custom cell in TTTableView to a TTViewController I have TTViewController include a TTTableView inside and init TTTableView like below: - (void)loadView{ appTableView = [[TTTableView alloc] initWithFrame:CGRectMake(10, 20, self.view.width - 20, (self.view.height - 44 - 49)/2 - 40)]; appTableView.backgroundColor = [UIColor clearColor]; appTableView.delegate = self; appTableView.separatorStyle = UITableViewCellSeparatorStyleNone; [self.view addSubview:appTableView]; } and in - (void)requestDidFinishLoad:(TTURLRequest*)request { appTableView.dataSource = [TTListDataSource dataSourceWithObjects: [CustomTTTableSubtitleItem itemWithTitle:result.resourceName text:textCombine ],nil]; } I've coded this: - (Class)tableView:(UITableView*)tableView cellClassForObject:(id) object { if ([object isKindOfClass:[CustomTTTableSubtitleItem class]]) { NSLog(@"here"); return [CustomTTTableSubtitleItemCell class]; } else { return [self tableView:tableView cellClassForObject:object]; } } and of course I added protocol @interface TestController : TTViewController<TTTableViewDelegate,TTTableViewDataSource> but seems -(Class)tableView:(UITableView*)tableView cellClassForObject:(id) object not be called... anything I missed? A: the - (Class)tableView:(UITableView*)tableView cellClassForObject:(id) object is a TTTableViewDataSource function, so you will have to extend the TTListDataSource into your own data source class, and override this function there and not under TTViewController. In your TTViewController, create the custom data source: /////////////////////////////////////////////////////////////////////////////////////////////////// - (void)requestDidFinishLoad:(TTURLRequest*)request { self.dataSource = [[[YourDataDataSource alloc] initWithResults:results] autorelease]; } and in your custom TTTableViewDataSource have your - (Class)tableView:(UITableView*)tableView cellClassForObject:(id) object custom function
{ "language": "en", "url": "https://stackoverflow.com/questions/7569593", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iOS - I'm confused how memory is being handled here? UIImage API Reference Document:- initWithContentsOfFile: Initializes and returns the image object with the contents of the specified file. - (id)initWithContentsOfFile:(NSString *)path Parameters path The path to the file. This path should include the filename extension that identifies the type of the image data. Return Value An initialized UIImage object, or nil if the method could not find the file or initialize the image from its contents. Considering this scenario, suppose I have a class, it could be extension of any class. Just took UIImage for example. @interface myImage : UIImage { BOOL isDefaultSet; } -(id)initWithDefaultImage; @end @implementation myImage -(id)initWithDefaultImage { NSString *path = [[NSBundle mainBundle] pathForResource:@"someInvalidImage" ofType:@"png"]; idDefaultSet = YES; return [self initWithContentsOfFile:path]; } @end //somewhere in other class: NSString *path = [[NSBundle mainBundle] pathForResource:@"someInvalidImage" ofType:@"png"]; myImage *myObject = [[myImage alloc] initWithDefaultImage]; UIImage *yourObject = [[UIImage alloc] initWithContentsOfFile:path]; now here in both cases, "alloc" gives "retainCount+1" and if initWithDefaultImage/initWithContentsOfFile returned nil due to some issue - lets say (invalid file path), this memory will be leaked as myObject/yourObject will be set to nil even though the allocation was made before init. I have seen many implementations for extended classes/interfaces in this manner. I'm confused how memory is being handled here? can anyone share view on this? A: Usually the corresponding initializer releases self (the new object) before returning nil, as in: - (id)initWithFoo { self = [super init]; if (!self) return nil; if (someInitializingFailed) { [self release]; return nil; } return self; } You can assume that -[UIImage initWithContentsOfFile:] is implementing the same pattern. So unless Instruments does tell you there's a leak you don't need to do any special handling in your case. A: if [super init] returns nil, nil is returned. so the control returns from method and if (someInitializingFailed) block will never be executed and memory will be leaked as alloc is already executed before calling "initWithFoo" if [super init] returns nil, super's init has already cleaned after itself and released the memory allocated by alloc. From Handling Initialization Failure: You should call the release method on self only at the point of failure. If you get nil back from an invocation of the superclass’s initializer, you should not also call release. A: You are right, sometimes people forget to handle this leak. The allocated memory needs to be released if we cannot proceed with the initialisation. -(id)initWithDefaultImage { NSString *path = [[NSBundle mainBundle] pathForResource:@"someInvalidImage" ofType:@"png"]; if (path != nil) { self = [super initWithContentsOfFile:path]; } else // cannot proceed with init { [self release]; self = nil; } return self; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569596", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I get multiple characters from a string? I'm trying to get the 5th, 6th and 7th digits from a list of digits. E.g. I want to get the year out of the variable dateofbirth, and save it as a separate variable called dob, as an int. Here is what I have: int dateofbirth = 17031989 String s = Integer.toString(dateofbirth); int dob = s.charAt(5); What would I have to put in the parentheses after s.charAt to get a few digits in a row? A: No need for the string conversion: int dateofbirth = 17031989; System.out.println(dateofbirth%10000); //1989 If you did want to do it as a string, then the substring() method would be your friend. You'd also need to use Integer.parseInt() to convert the string back into an integer. Taking a character value as an integer will give you the ASCII value of that character, not an integer representing that character! A: You want to use String.substring (untested): int dateofbirth = 17031989; String s = Integer.toString(dateofbirth); String year = s.substring(4, 8); int yearInt = Integer.parseInt(year); A: s.substring(5) will give you everything starting from index 5. You could also give a second argument to indicate where you want the substring to end. A: If you are handling dates, you could use SimpleDateFormat and Calendar to pull out the year: SimpleDateFormat formatter = new SimpleDateFormat("ddMMyyyy"); Calendar cal = Calendar.getInstance(); cal.setTime(formatter.parse(Integer.toString(dateofbirth))); int year = cal.get(Calendar.YEAR); A: you do: String s = String.valueOf(dateofbirth); int yourInt = Integer.parseInt(s.substring(startIndex,length)) A: Check out String.substring() ! http://download.oracle.com/javase/6/docs/api/java/lang/String.html#substring%28int%29 A: This approach won't work for several reasons: * *s.charAt(5) will give you the ASCII code of the 6th character (which is not 9). *There is no method to get several chars If you want to extract 1989 from this string you should use substring and then convert this string into an Integer using Integer.valueOf() A: Integer.parseInt(s.subString(4)) A: From the JRE documentation: getChars
{ "language": "en", "url": "https://stackoverflow.com/questions/7569599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to upload a web application to free server I am using net-beans 7 and I wrote a server said app on java with db. Now I want to upload it to free global server. I tried amazon but need a credit card. Tried to work with Google app engine but have problems with net-beans and Google configurations. Can you give me a link for simple way to load my app to free server and how it will work with the db that I wrote that works with derby. thanks a lot!! A: You could use Amazon Web Services Free Usage Tier. Another option is jelastic.com (I didn't test it yet). They offer free use for small applications: Starts free: That's right! If you want to deploy a demo for your customers, deploy a small application for you and your friends, or experiment and deploy an app for internal QA, it won't cost you a penny!
{ "language": "en", "url": "https://stackoverflow.com/questions/7569604", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: App fabric without SQL Server whatsoever I got VPS with limited memory and my WCF service is hosted using AppFabric. Since memory is limited and I am not using SQL server for anything other than AppFabric prerequisite im thinking about uninstalling SQL Server. (instance can eat up to 200mb memory at times). I am not using any DB related features of AppFabric like dashboard or caching. I like IIS extensions and simplicity for WCF service manipulations however, and I am thinking those do not require Sql Server actually. I am unable to just try it out so wonder if someone has such experience, or can predict result of uninstalling SQL server on appfabric behaviour. A: Instead of uninstalling SQL Server you could just stop the SQL Server process. Set the process to manual startup. That way if you need SQL Server in the future you can just start the process. A: As @Shiraz Bhajiji illudes to if you are using SQLServer as the configuration store, you will need to reconfigure it to use file based configuration instead, it sounds like you are only using a single AppFabric instance, but if you are or needed to use multiple instances the config file would need to be accessible to all instances. Again it isn't necessarily relevant to you, but if you have multiple app fabric instances, the sql server configuration option is a much more robust approach. With the file based approach, if you configure things incorrectly one app fabric node going down can take down the entire cluster. The SQLServer approach does represent a single point of failure however, if you are using clustering etc you can easily mitigate this. Again I appreciate I'm getting a little off topic here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569605", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DDD and Factories Hi I have a few questions regarding Domain Driven Design and using Factories / Factory Methods. Per the Domain Driven Design Blue Book (Eric EVan's Book) it states that complex constructors should be encapsulated inside Factories / Factory Methods / Builders so there is a consistent place where you check all the invariants, so my question is regarding this: Let's say I am developing a magic organizer application where you can make CRUD like operations on magic effects (like a post on a blog + several attributes like effect duration, materials used (list of strings), patter associated with the magic effect) and some of the invariants are that a magic effect must always have a title, a content of the magic effect, a duration and an optional patter and must be published by a user registered in the application. So since I have quite a few invariants I have a EffectBuilder that builds MagicEffect objects and checks all the invariants. Is it ok to do something like this in the user class? public class User { // Several attributes and business methods public MagicEffect publishEffect(final String title, final String content, final Long duration, final Collection<String> elements) [ EffectBuilder builder = new EffectBuilder(); builder.withAuthor(this); builder.withTitle(title); builder.withContent(content); builder.withDuration(duration); builder.withElements(elements); return builder.build(); } }; Or should I do something like: public class User { // Several attributes and business methods public EffectBuilder publishEffect() [ EffectBuilder builder = new EffectBuilder(); builder.withAuthor(this); return builder; } }; And somewhere else User user = userRepository.findById(userId); MagicEffect effect = user.publishEffect().withTitle(title).withContent(content).withDuration(duration).withElements(elements).build(); userRepository.save(user); I mean the first example I have a huge method with huge amount of parameters but I make sure all the invariants are set in the effect when it's built, in the other scenario I programatically improve the code readability by having a fluent interface but I canot make sure the invariants are met 100% of the time. Which is the better approach? Is there a more balanced approach of doing it? Thanks Pablo A: I think that your second approach is better. The whole point of Builder is to avoid large list of parameters like you have in your first example. Builder is not responsible for enforcing invariants in the object that it builds. Object itself enforces them. I think it is perfectly fine to have an instance of EffectBuilder without Title or with a default title. As long as the MagicEffect itself enforces 'Every effect should have a title' invariant.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569611", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Best sql practice for related records Hi I need be able to link related applications and am trying to work out the best practice table structure for saving, updating and deleting. I have the following table: APPLICATION{ApplicationId, Name, Description} I need to be able to say Application 1 is linked to 2 and 3. Therefore if you open application 2 you'd see that it is linked to application 1 and 3. Then application 3 is linked to 1 and 2. What is the best table structure for a linked table? EDIT My main query is will I need a record for each join ie for applications 1, 2 and 3 would I need 6 records? 1->2, 1->3, 2->1, 2->3, 3->1, 3->2 ?? If not what is the best query to return all linked apps for a given id? A: application_association ------------------------- application_1_id application_2_id relationship_type begin_dt end_dt use relationship_type to specify how the applications are related, and use the dates to specify when that relationship was valid edit: maybe there is a collective misinterpretation of your use of the word 'linked'. If you instead mean 'grouped' then you might consider a structure like the following: group ------------------ group_id name application_group ------------------- application_id group_id here you can just place applications into the same 'group' and then query them all back when they are in the same group. A: Two more tables. One for association type: create table ApplicationAssocType ( Id int identity(1,1) ,[Description] varchar(128) not null ) And one for the association itself: create table ApplicationAssoc ( Id int identity(1,1) ,ApplicationId1 int not null references Appliation(ApplicationId) ,ApplicationId2 int not null references Appliation(ApplicationId) ,ApplicationAssocTypeId int not null references ApplicationAssocType(Id) ) [Edit] To clarify, you'd add a record for each individual link. Add any fields to ApplicationAssoc which pertain to the relationship between the applications specified. A: CREATE TABLE AppLink (App1 int, App2 int) This is endlessly extendable for as many relations as you need. A: Application entity has a many to many relationship with itself, so you need another table to store that mapping: APP_Relationship (ApplicationId, RelatedApplicationId) A: LinkedApplication{ID, ApplicationId, LinkedApplicationId} A: You need a link table which basically allows you to have a many-to-many relationship between Application and itself. CREATE TABLE lnkApplication (ApplicationID1 int, ApplicationID2 int) GO ALTER TABLE [dbo].[lnkApplication] WITH NOCHECK ADD CONSTRAINT [FK_ApplicationLink1] FOREIGN KEY([ApplicationID1]) REFERENCES [dbo].[tblApplication] ([ApplicationID]) GO ALTER TABLE [dbo].[lnkApplication] WITH NOCHECK ADD CONSTRAINT [FK_ApplicationLink2] FOREIGN KEY([ApplicationID2]) REFERENCES [dbo].[tblApplication] ([ApplicationID]) GO
{ "language": "en", "url": "https://stackoverflow.com/questions/7569614", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MVC3 load common data for views I am developing an MVC3 "movie list" application containing several "sites" depending on the request hostname. I am trying to use a strongly typed ViewModel like this (examples are simplified to get to the essence of the question): class ViewModelBase { public int siteId { get; private set; } public ViewModelBase(DbContext db) { siteId = <here I want to make a db-lookup based on the request hostname> <== This is my problem } } class MoviesIndexViewModel : ViewModelBase { public List<Movie> movies { get; private set; } public MoviesIndexViewModel(DbContext db) : base(db) { movies = db.Movies.where(m => m.SiteId == siteId).ToList(); } } An my controller would then just do this: public class MoviesController : Controller { public ActionResult Index() { var model = new MoviesIndexViewModel(new MySpecialDbContext()); return View(model); } } Question is: How will I get the "request host header" into the code line shown above? I know how to make the actual DB-lookup, but can I just access any request parameters here? Or should I supply something through parameters to the constructor? A: I would not use Dbcontext in my view models. Read about Separation of concerns Instead, use OnResultExecuting in your BaseController to add the common data: protected override void OnResultExecuting(ResultExecutingContext filterContext) { var baseModel = filterContext.Controller.ViewData.Model as YourCustomModel; if (baseModel != null) { // call a repository or whatever to add information to the model. } base.OnResultExecuting(filterContext); } Update yes. The controller is the glue between the "model" (repositores, webservices or any other data source) and the view. The ViewModel is just an abstraction to move away logic from the view. Here is the three main reasons you should use a view model: http://blog.gauffin.org/2011/07/three-reasons-to-why-you-should-use-view-models/ And an alternative approach to handle common view data: http://blog.gauffin.org/2011/09/getting-information-into-the-layout-without-using-viewbag/
{ "language": "en", "url": "https://stackoverflow.com/questions/7569617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a "Find in Files" shortcut in Eclipse? Is there a "Find in Files" shortcut in Eclipse, as there is in Visual Studio (Ctrl+Shift+F)? I have looked in these two lists: * *Eclipse Shortcuts *"Show All Shortcuts" shortcut: Ctrl+Shift+L. Thanks. A: select workspace and press Ctrl-H Which dialog is selected, depends on which file type is selected in the Project Explorer view. For example, if you selected a .js file and press Ctrl-H, it will bring up the dialog with the "Javascript Search" tab selected. If you want to search all files, you can press Ctrl-F7 to select the Project Explorer view, use arrow keys to select a folder above your files, then press Ctrl-H (or select a file, whose type doesn't trigger a custom dialog tab). A: Yes, there is shortcuts for searching Eclipse, these shortcuts are very useful when we search for particular html, jsp , xml, java, properties ,class, jar,search file with keywords. * *Ctrl+H is used open Tag, in that you can select type of file Remote Search, File search, git search, java search, javascript search , etc *Ctrl+Shift+R is used to search all files in the current project *Ctrl+Shift+T is used to search all files in the workspace A: Thanks to the other two solutions, but here is the complete answer I was looking for, which addresses how I search all the text within the files, not just types, methods, packages, constructors, and fields: * *Ctrl+H to open the "Search" dialog box *"File Search" tab, if it does not appear, expand the window or use the left/right arrows *type in the text to search for *Use "*.java", in my case since I am coding in Java, to search just these files *Click "Search" A: press Ctrl + H . Then choose "File Search" tab. additional search options search for resources press Ctrl + Shift + R search for Java types press Ctrl + Shift + T A: Source: Eclipse: Default to "File Search" Tab in Search Dialog * *Go to your key bindings Windows > Preferences > General > Keys *Unbind the Shorcut "Ctrl+H" for the "Open Search Dialog" *Filter/Search for "File Search" and use the "Ctrl+H" here instead. A: If you are using only the File Search, you can Disable all other Searches in the Search Panel (Customize... lower left Corner). Then you have the File Search everytime you Press Ctrl+H A: * *Ctrl+H to bring up the search box *Click 'Customize' in the lower left *Checkmark 'Remember last used page' *Click OK. *Select the file search tab and do a search A: I believe adding plug-ins power your needs. If you install Plug-in named InstaSearch it makes your searching faster inside current active working projects. It shows the result as you type. http://marketplace.eclipse.org/content/instasearch#.VIp-_5_PGPQ A: As pointed out, CTRL + H opens the Search dialog. Since I use only Find in Files (and set File name patterns when needed), I clicked on Customize... button on the bottom of the Search dialog. It opens Search Page Selection dialog, where I turned off all other options. You can also click on Remember last used page in the same dialog. A: If you want to use the type-specific search (Java, Javascript ...etc) you can use Ctrl+H, which opens the search dialog, then click the Search button. If you simply want to search for all text occurrences in the whole the workspace click the word (or select the text) you want to search then hit Ctrl+Alt+G. You will directly get all the found occurrences without even using a dialog box. I find Ctrl+Alt+G is the best solution because it shows the variable name in different by related files (e.g. Java and XML, or Javascript and HTML) while still having the type-specific search feature available through Ctrl+H You can rebind the Ctrl+Alt+G to finding text in a project or a working set instead of the whole workspace if that's more appealing to you. A: Ctrl+Alt+F (Find Text in Project -Customized Key) Note - Ctrl+Alt+G is for Find text in a workspace, not in a project How to customize this Key Window->Preferance->General->Keys-> Search for 'Find Text in Project'->Type 'Ctrl+Alt+F' in binding ->Apply Note - this will be helpful if the developer is working on multiple project simultaneously.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569630", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "93" }
Q: Problem in uninstalling visual studio 2010 professional I have Visual Studio 2010 Professional, i just got new Ultimate edition of Visual Studio 2010. I'm trying to uninstall the previous Professional version but it isn't working * *When i try uninstalling through control panel it just freezes on generating setup script and after few times Operating becomes not responding, i waited for an hour but it didn't worked *Then i downloaded the Microsoft Utlity Visual Studio 2010 Uninstall Utility and that also didn't worked for me, it again stuck in the middle of the progress bar with no reason Can anyone tell me if he has any idea whats going on and how i can uninstall it A: You don't have to uninstall VS2010 Pro to upgrade to Ultimate. Just run the Ultimate installer without doing anything to your existing VS2010 Pro installation and your version will be upgraded.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Fixed width of collapse panel in C#, winform? In winform application, i am using multiple collapse panels and each one contains dynamic controls added. But the problem is, the width of the collapse panels changes dymanically (width reduces on collapsed mode and increases while expanded) but i want fixed width on both mode. Even i handled collapsablePanel1_PanelStateChanged event and set constant width, but no use. private void collapsablePanel1_PanelStateChanged(object sender, EventArgs e) { this.collapsablePanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowOnly; this.Width = collapsablePanel1.Width; } How do i get fixed width collapse panels during expaned/collapes state?
{ "language": "en", "url": "https://stackoverflow.com/questions/7569641", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Performance tool - leak If I testing my codes with performance tool - leaks, and it doesn't detect any leaks. Does that mean the codes is not leaking any memory? I have a Jail-broken iPhone, which I can monitor the available memory. If anyone knows, it's SBSettings. I tested my app which has a UITableView and I can see the available memory dropping when I am scrolling through the tableView. From 300MB to 30MB, where it seems like it can't drop further. It usually doesn't drop that much with other apps other than games. I am using a custom UITableViewCell with 2 buttons, 1 textView and 3 UILabels. So, yeah. If performance tool does not detect any leak, am I safe? - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"StatusTableCell"; StatusTableCell *cell = (StatusTableCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"StatusTableCell" owner:nil options:nil]; for (id currentObjects in topLevelObjects){ if ([currentObjects isKindOfClass:[StatusTableCell class]]){ cell = (StatusTableCell *) currentObjects; break; } } [cell.cancelButton addTarget:self action:@selector(cancelButton:) forControlEvents:UIControlEventTouchUpInside]; } /// some other stuff return cell; } A: You should consider value of LiveBytes in performance tool if it is increasing with app running, it is an issue. This might happen with tableviews if you are not using reusable cells. Check for it if you have reusable cells or not. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reusablecell"]; if(!cell) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"reusablecell"]; [cell autorelease]; } //update cell here return cell; } A: No, you're not necessarily safe. A memory leak occurs when the program no longer has a reference to an object. So if an object is released, but an object it was retaining is not (not released properly in the dealloc method, for example), you get a leak. However, if the owning object is never released itself, no leak is detected. To look for these kinds of memory problems, run the allocations instruments tool. Click on the Mark Heap button, and perform some kind of repeatable action in the app (for example, select a row in a table view to push a detail view on to the nav stack, then tap the back button). Click on the Mark Heap button again. Then repeat the action a few times. Ideally you should see no heap growth, and no persistent objects between heap shots.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569642", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Developing for HTML5 canvas using Box2D engine but NOT in Javascript Basically I have the following constraints for an upcoming project/game: * *Drawing should be done in the HTML5 canvas element *Use the Box2D physic engine (or equivalent physics engine) *Game logic (and as much code as possible) should be in Java, as I'm profficient in Java and it would be nice to be able to port the project to Android. It can be summed up in this: I want to develop games/projects in the HTML5 canvas element, using some kind of physics engine while avoiding the mess of javascript. (preferably but not necessarily through Java) Is this possible? Would it be viable? I've looked at GWT but I'm unsure how efficient it would be for animation, and how I would go about to incorporate Box2D. (or another physics engine in Java for example, but would the translation to javascript be fast enough?) A: I know that GWT compiles Java to JavaScript, but it does so in the boundaries of its framework, so I don't know how easy it would be to use GWT in your project. If you find JavaScript too frustrating, check out CoffeeScript. It slim and sharp, can interoperate with JavaScript (in your case Box2D JS port) seamlessly. A: Google's PlayN (formerly ForPlay) was used for the web version of Angry Birds, using Box2D. It's mainly intended to use WebGL for the rendering, but can use the canvas element when WebGL is not available (Angry Birds requires Flash, for the audio). http://code.google.com/p/playn/ http://www.youtube.com/watch?v=F_sbusEUz5w
{ "language": "en", "url": "https://stackoverflow.com/questions/7569643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Implementing A Controller for Authorization I use Spring and Spring Security 3 at my application. All my clients side are static HTML files. I have a navigation bar that includes buttons like: * *List *Edit *Delete *Update When a user clicks any of them another page loads at bottom. Users have roles at my application. Some users do not have edit and delete authorization, while others do. That buttons should be visible to users which have the authorization. If a user doesn't have edit the correct permission he/she must not see the edit button. I have the buttons defined in an HTML file: navigation.html. I figured out that: there will be many navigation.html files. One of them includes all buttons(for admin) one of them just includes list button. If a user requests that navigation.html I want to send the correct one. So I can have that ability: <logout logout-url="/j_spring_security_logout" logout-success-url="/login.html"/> similar to that user will request that file from an URL(as like /navigation). There will be a controller to handle it so will return any of that navigation files. Does that design sound correct? If so, how can I implement that? Any other simple solutions are welcome I am new to Spring and Spring Security. A: For general Spring Security use, you don't need to write your own code to enable authorization. I generally configure Spring Security in XML to control access at a gross level to various resources based on Roles. Then, I annotate the controllers and/or handler methods to restrict more precisely. Example: <?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns:security="http://www.springframework.org/schema/security" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"> <security:global-method-security secured-annotations="enabled"> </security:global-method-security> <security:http auto-config="true" disable-url-rewriting="true"> <security:intercept-url pattern="/*.do" access="ROLE_USER" /> <security:intercept-url pattern="/index.jsp" access="ROLE_USER" /> <security:intercept-url pattern="/**" access="IS_AUTHENTICATED_ANONYMOUSLY" /> <security:intercept-url pattern="/login.jsp" filters="none" /> <security:form-login login-page="/login.jsp" /> <security:logout /> </security:http> <security:authentication-manager> <security:authentication-provider> <security:password-encoder hash="md5" /> <security:jdbc-user-service data-source-ref="my-ds"/> </security:authentication-provider> </security:authentication-manager> </beans:beans> And then in the Controller: @Secured({"ROLE_SPECIAL_USER"}) @RequestMapping("/somespecial.do") Within a JSP: <%@ taglib prefix="authz" uri="http://www.springframework.org/security/tags" %> <authz:authorize ifAnyGranted="ROLE_SPECIAL_USER"> ...some special JSP code... </authz:authorize> A: Based on your using static HTML, I would think that the design you specify would be reasonable. Have a Controller that maps to navigation.html, and it would simply look at the granted authorities of the current user and return the correct static html view name for the html file that has all (and only) the appropriate controls.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569647", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SessionContext.getBusinessObject() in EJB3 & JNDI lookup In EJB2, one needed to use getEJBBusinessObject() method in a EJB to pass reference to itself when calling another (local/remote) bean. Does the same apply for EJB3? e.g. @Stateless public class MyBean implements MyBeanLocal { @Resource private SessionContext sessionContext; public void myMethod() { OtherBeanLocal otherBean = ...; // getting reference to other local EJB. MyBeanLocal myBean = sessionContext.getBusinessObject(MyBeanLocal.class); b.aMethod(myBean); } // Edit: calling myMethodTwo() from inside of myMethodOne() public void myMethodOne() { MyBeanLocal myBean = sessionContext.getBusinessObject(MyBeanLocal.class); myBean.myMethodTwo(); } public void myMethodTwo() { ... } ... } Also, if I fetch my local bean using getBusinessObject() method, is it the same as if I use common JNDI lookup? I've tested both approach, and both work, but I'm not sure if bean object is processed the same way by the container. Edit: Is fetching the reference to ejb itself, when calling myMethodTwo() from inside myMethodOne() of the same ejb, in EJB3, still needed? Is it allowed to call methods inside the same ejb through this reference? How will this address transactions, if I decide to use some? A: Yes, the same applies to EJB 3. Yes, getBusinessObject is the EJB 3 analog to getEJBObject (or getEJBLocalObject). All of those methods return a proxy for the current bean object. For stateless session beans, this is basically the same as looking up through JNDI, though it's likely to perform better since it avoids JNDI overhead.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569648", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: ASP Photo Processing - List Photo colors Like the the amazing "histogram" property in Ruby (RMagicK), that computes a list of colors in a photo, in order of frequency - is there anything similar to this for Classic ASP/.NET, in the form of a third-party plugin or component? Regards A: It sounds like RMagick is a derivative of ImageMagick. The Windows version has an installer that allows you to install a COM component. (You will have to check this in the installer for it to be installed). Link This COM component can be used from classic ASP. I have some classic ASP code that uses ImageMagick, the syntax is a bit unusual. Please note that this won't function on its own, because it depends om some other functions, but it will give you an idea of how to use the COM component: function DrawPoly(destFile, coordinates, fillcolor, strokecolor) ' Draws a single polygon and returns a result-image Dim img: Set img = CreateObject("ImageMagickObject.MagickImage.1") dim polygon, DrawCommand, DrawResult polygon = trim(coordinates) polygon = normalizeCoordinates(polygon,10) DrawCommand = "polygon " & trim(polygon) DrawResult = img.Convert(Server.Mappath(destFile), "-matte", "-fill", fillColor, "-stroke", strokeColor, "-draw", DrawCommand, Server.Mappath(destFile)) If Err.Number <> 0 Then Response.Write(Err.Number & ": " & Err.Description & vbCrLf & msgs) DrawPoly = destFile Set img = nothing end function I don't know how to perform a histogram, but I hope this piece of code together with the imagemagick docs will get you there. Erik
{ "language": "en", "url": "https://stackoverflow.com/questions/7569652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Where can I find JavaEE packages' sources? I'm developing a JavaEE system (distributed on Weblogic App Server), but I don't have the sources for the JavaEE packages (javax.ejb.*, for instance). Where can I find the sources (not javadoc) for these packages? A: Try in the default Maven repository; search for "javax.ejb", then download the source. That's quite often the easiest way, saving you from clicking through EULAs and the like. That said, this source code is only good for plugging into an IDE to get source code completion — implementations are application-server specific (see Balusc answer). A: Java EE is an abstract API. It exist of just contracts (as you see in javadocs), not concrete code. The application servers are the concrete implementations. So, if you're looking for the source, you should look at the application server vendor's homepage for a source code download link. However, you're unlucky with Weblogic. It is not open source. I've never used Weblogic (I am an open source fan), so I'm not sure if the source is provided along the Weblogic license, you might want to contact Weblogic support team. Other servers, like Tomcat, Payara, WildFly, etc are open source. WebSphere has also a "Community Edition" which is open source. You could grab the javax.* API source code from any of them, but there is no guarantee that they are exactly the same as Weblogic uses. And still then, they do not provide the concrete Weblogic implementation code (like as the code in org.apache.*, com.sun.* and org.wildfly.* packages in aforementioned open source servers). See also: * *What exactly is Java EE?
{ "language": "en", "url": "https://stackoverflow.com/questions/7569658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Print unique value for keys I have an array of dicts like this: { "album_image" = "BauerOVTDDVD.jpg"; "album_title" = "Zuid-Afrika, Om Van Te Dromen"; "album_year" = 2005; "track_duration" = xxx; "track_title" = "Ik Neem Voor Jou De Laatste Trein"; }, { "album_image" = "BauerOVTDDVD.jpg"; "album_title" = "Zuid-Afrika, Om Van Te Dromen"; "album_year" = 2005; "track_duration" = xxx; "track_title" = "Als De Avond Voor Ons Is Gevallen"; }, { "album_image" = "BauerOVTDDVD.jpg"; "album_title" = "Zuid-Afrika, Om Van Te Dromen"; "album_year" = 2005; "track_duration" = "3'26"; "track_title" = "'n Handje Vol Geluk"; }, { "album_image" = "BauerOVTDDVD.jpg"; "album_title" = "Zuid-Afrika, Om Van Te Dromen"; "album_year" = 2005; "track_duration" = "3'22"; "track_title" = "'n Klein Sterretje"; } So there's a different track_title for each track title. Some of these track titles share an album. I only want to print unique album titles. This is the data I have to work with. Should i create a new dict with just album titles? A: If you only want the album title, you can use an NSSet for that. NSMutableSet *titles = [NSMutableSet alloc] init]; [trackArray enumerateObjectsUsingBlock:^(id object, NSUInteger idx, BOOL *stop) { [titles addObject:[object objectForKey:@"album_title"]]; }]; [titles release]; A: You could create a set of the album titles: NSArray *albumTitlesWithDuplicates = [sourceArray valueForKey:@"album_title"]; NSSet *uniqueAlbumTitles = [NSSet setWithArray:albumTitlesWithDuplicates];
{ "language": "en", "url": "https://stackoverflow.com/questions/7569660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make a JavaScript menu more functional I wonder simply which way is the best practice to make this menu dynamic. I don't want to make a function for each Element. Should I push them into an Array then loop through them? <div id="nav"> <div id="button1"></div> <div id="button2"></div> <div id="button3"></div> <div id="button4"></div> </div> <div id="navHover"> <div id="hoverButton1"></div> <div id="hoverButton2"></div> <div id="hoverButton3"></div> <div id="hoverButton4"></div> </div> <script type="text/javascript"> var buttonOne = document.getElementById('button1'); var buttonOneHover = document.getElementById('hoverButton1'); buttonOne.addEventListener('mouseover', buttonOneBlock, false); buttonOne.addEventListener('mouseout', buttonOneNone, false); buttonOneHover.addEventListener('mouseover', buttonOneBlock, false); buttonOneHover.addEventListener('mouseout', buttonOneNone, false); function buttonOneBlock() { var buttonOneHover = document.getElementById('hoverButton1'); buttonOneHover.style.display = 'block'; } function buttonOneNone() { var buttonOneHover = document.getElementById('hoverButton1'); buttonOneHover.style.display = 'none'; } </script> #nav { width: 960px; height: 20px; background-color: white; margin: auto; } #button1, #button2, #button3, #button4 { width: 100px; height: 20px; background-color: red; float: left; margin-left: 10px; } #navHover { width: 960px; height: 20px; background-color: white; margin: auto; } #hoverButton1, #hoverButton2, #hoverButton3, #hoverButton4 { width: 100px; height: 20px; background-color: orange; float: left; margin-left: 10px; display: none; } A: Here’s a straightforward generalization of that: function setupButton(i) { var button = document.getElementById('button' + i); var buttonHover = document.getElementById('hoverButton' + i); button.addEventListener('mouseover', buttonBlock, false); button.addEventListener('mouseout', buttonNone, false); buttonHover.addEventListener('mouseover', buttonBlock, false); buttonHover.addEventListener('mouseout', buttonNone, false); function buttonBlock() { buttonHover.style.display = 'block'; } function buttonNone() { buttonHover.style.display = 'none'; } } for (var i = 1; i <= 4; ++i) { setupButton(i) }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569663", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple form issue with Rails 3 I've been trying recently to show a list of the fields modified with success on submitting a form. The only problem is that my form (I use simple form) doesn't show the errors when there are some and the form can't be submitted. Here's my code simplified : def update @wizard.assign_attributes(params[:wizard]) # Get changed attributes if @wizard.save # Set the success flash with fields modified redirect_to @wizard else @title = "Edition du profil" render 'edit' end end The view : <%= simple_form_for @wizard do |f| %> <%= f.input :email %> <%= f.input :story %> <%= f.submit "Modifier", :class => "btn success small" %> <% end %> The model : class Wizard < ActiveRecord::Base has_secure_password attr_accessible :email, :story, :password, :password_confirmation, :password_digest serialize :ranks, Array validates_presence_of :email, :first_name, :last_name, :gender, :story validates_presence_of :password, :password_confirmation, :unless => Proc.new { |w| w.password_digest.present? } # Other validations here has_one :subject, :foreign_key => "teacher_id" ROLES = %w[teacher] scope :with_role, lambda { |role| {:conditions => "roles_bitmask & #{2**ROLES.index(role.to_s)} > 0"} } # Other functions here end Has anyone an idea ? Thank you in advance ! A: It has probably something to do with how you overwrote AR. I remember some plugin getting in trouble with assign_attributes. Meanwhile you can try : @wizard.assign_attributes(params[:wizard], :without_protection => true) If that works it will at least narrow down the problem to mass assignment. A: you perhaps missing this part in edit/new view.Where @wizard is your model_name. Write this piece of code in the form tag. <% if @wizard.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@wizard.errors.count, "error") %> prohibited this task from being saved:</h2> <ul> <% @wizard.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %>
{ "language": "en", "url": "https://stackoverflow.com/questions/7569667", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: doctrine, symfony 1.4: How do I fix this 'Integrity constraint violation' I have defined this entity in schema.yml Jobsearch: tableName: jobsearch columns: seeker_id: primary: true type: integer notnull: true autoincrement: false empmode: type: string(50) pensum: type: integer active: type: boolean relations: Privateaccount: local: seeker_id foreign: id alias: seeker it has a foreign key reference to Privateaccount: tableName: privateaccount columns: id: primary: true unique: true type: integer notnull: true autoincrement: true firstname: type: string(255) lastname: type: string(255) inheritance: extends: sfGuardUser type: column_aggregation keyField: type keyValue: Privateaccount I made a symfony action for testing purpose, it is supposed to save a Jobsearch to db: public function executeTest(sfWebRequest $request) { $test = new Jobsearch(); $test->setSeeker( $this->getUser()->getGuardUser() ) ; // set the user that is logged in $test->save(); } $test->save() results in this error: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (test2.sf_guard_user_profile, CONSTRAINT sf_guard_user_profile_user_id_sf_guard_user_id FOREIGN KEY (user_id) REFERENCES sf_guard_user (id) ON DELETE CASCADE) I don't see why the foreign key constraint is failing. What has caused the error? EDIT: If I change primary to false in seeker_id, it does work. But I want the Foreign Key to be the Primary Key. If possible, how do I make that work? A: Try changing the schema.yml to Jobsearch: tableName: jobsearch columns: seeker_id: primary: true type: integer notnull: true autoincrement: false empmode: type: string(50) pensum: type: integer active: type: boolean relations: Seeker: class: Privateaccount local: seeker_id and Privateaccount: tableName: privateaccount columns: firstname: type: string(255) lastname: type: string(255) inheritance: extends: sfGuardUser type: column_aggregation keyField: type keyValue: Privateaccount Doctrine creates the id field by default. Don't declare it. Finally, it should work. public function executeTest(sfWebRequest $request) { $test = new Jobsearch(); $test->setSeekerId( $this->getUser()->getGuardUser()->getId() ) ; // set the user that is logged in $test->save(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Scala, how do I translate from hard coded files to using resources? At the moment I have something similar to the following for (line <- Source.fromFile(new File(myFile)).getLines) {} Suppose instead of myFile I want to use getClass.getResource("/filename") What is the syntax for doing this whilst retaining the ability to still read line by line? A: Source.fromInputStream(getClass.getResourceAsStream("/filename"))
{ "language": "en", "url": "https://stackoverflow.com/questions/7569671", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: A smart way to retrieve allowed file types from plist Scenario: I like to define the allowed file types (content types) in the Info.plist file of my Cocoa application. Therefore, I added them like the following example shows. # Extract from Info.plist [...] <key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeName</key> <string>public.png</string> <key>CFBundleTypeIconFile</key> <string>png.icns</string> <key>CFBundleTypeRole</key> <string>Viewer</string> <key>LSIsAppleDefaultForType</key> <true/> <key>LSItemContentTypes</key> <array> <string>public.png</string> </array> </dict> [...] Further, my application allows to open files using an NSOpenPanel. The panel allows to set the allowed file types through the following selector: setAllowedFileTypes:. The documentation states that UTI can be used. The file type can be a common file extension, or a UTI. A custom solution: I wrote the following helper method to extract the UTI from the Info.plist file. /** Returns a collection of uniform type identifiers as defined in the plist file. @returns A collection of UTI strings. */ + (NSArray*)uniformTypeIdentifiers { static NSArray* contentTypes = nil; if (!contentTypes) { NSArray* documentTypes = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDocumentTypes"]; NSMutableArray* contentTypesCollection = [NSMutableArray arrayWithCapacity:[documentTypes count]]; for (NSDictionary* documentType in documentTypes) { [contentTypesCollection addObjectsFromArray:[documentType objectForKey:@"LSItemContentTypes"]]; } contentTypes = [NSArray arrayWithArray:contentTypesCollection]; contentTypesCollection = nil; } return contentTypes; } Instead of [NSBundle mainBundle] also CFBundleGetInfoDictionary(CFBundleGetMainBundle()) can be used. Questions: * *Do you know a smarter way to extract the content type information from the Info.plist file? Is there a Cocoa-build-in function? *How do you deal with the definition of folders that can contained there, e.g. public.folder? Note: Throughout my research, I found this article quite informative: Simplifying Data Handling with Uniform Type Identifiers. A: Here is how I read information from a plist (it can be the info.plist or any other plist you have in you project provided you set the correct path) NSString *resourcePath = [[NSBundle mainBundle] resourcePath]; NSString *fullPath = [NSString stringWithFormat:@"%@/path/to/your/plist/my.plist", resourcePath]; NSData *plistData = [NSData dataWithContentsOfFile:fullPath]; NSDictionary *plistDictionary = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:0 errorDescription:nil]; NSArray *fileTypes = [plistDictionary objectForKey:@"CFBundleDocumentTypes"];
{ "language": "en", "url": "https://stackoverflow.com/questions/7569672", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Difference between the old game.achievement / new open graph I'm confused about the new version of the Open Graph (beta). I'm currently implementing the achievements functionality into a facebook app'. I'd like to know if there's a difference between : * *Old game.achievements in the og:type meta tag, and... *New implementation of the Open Graph (beta) with fully customizable objects/actions Am I supposed to use the new Open Graph (beta) to post my achievements instead of the old way with game.achievement ? Is it two totally different things ? Or is the game.achievement a predefined object type with predefined behaviors ? Just to know what i should implement today according to the new announcements...! Thanks in advance ! F.S. A: Achievements are just one global pre-defined action in the new Open Graph. Use the global game.achievement for achievements and use custom Actions and Objects for anything that doesn't fit into an already globally defined schema.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569679", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript in Delphi: [Something] is not a function I am attempting to create a form in delphi with a TWebBrowser making use of javascript. I have a save and load class that allows users to save out certain properties on the form and then load them back in later. However, when loading (Which creates a new form, initializes it and the javascript it uses) the program tells me that the javascript functions I am trying to use, which at any other time work fine, "is null or undefined, not a function object". So far as I can tell, the javascript only finishes loading on my final end; statement in delphi, so the functions (so far as my program is concerned) do not exist at that moment in time. My question is this: how can I get my javascript application to tell my Delphi form when it has finished initializing so it knows when to access the desired function? A: Try using the OnDocumentComplete event of the TWebBrowser control.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot add or update a child row when parent exists When executing the following query it results in a "Cannot add or update a child row" error. Normally this happens when the record in the parent table (upload.id) does not exist. In this case, though, the record in the parent does exist. UPDATE user SET callcenterId='4' ,name='Roel' ,login='roel@example.com' ,type='admin' ,email='roel@example.com' ,active='Y' ,sessionId='' ,sessionLastActive='2011-09-27 10:23:37' ,autoLoginCode='' ,autoLogin='Y' ,avatarId='1648' WHERE id = '4' Full error Cannot add or update a child row: a foreign key constraint fails (callcenter_ontwikkel/user, CONSTRAINT fk_user_upload FOREIGN KEY (avatarId) REFERENCES upload (id) ON DELETE NO ACTION ON UPDATE NO ACTION)
{ "language": "en", "url": "https://stackoverflow.com/questions/7569682", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nuget - packing a solution with multiple projects (targeting multiple frameworks) Say I have the following solution with multiple versions of the same code each targeting a different framework and I would like to generate a nuget package from it. SharedLib.sln SharedLib.Net35.csproj packages.config SharedLib.Net40.csproj packages.config SharedLib.Phone.csproj packages.config SharedLib.SL4.csproj packages.config The expected nupkg has the following structure SharedLib.1.0.nupkg lib/net35/SharedLib.dll lib/net40/SharedLib.dll lib/sl4-wp/SharedLib.dll lib/sl4/SharedLib.dll nuget.exe pack SharedLib.SL4.csproj will automatically determine that the target framework is SilverLight4 and place the binaries in lib/sl4 I know I can add a SharedLib.SL4.nuspec file with a <file> section to include binaries from the other projects but is there a way to make nuget automatically place the combined solution output into the proper structure (and also detect dependencies in packages.config from all projects? A: No, there's currently no way to do this other than to write a custom build script that puts the files in the right place and then runs NuGet pack on them, or to take the .nuspec approach you described. This is a feature we'd like to have, but haven't thought of a good way to do it. However, your post just gave me an idea. Today, you can point nuget pack at a .csproj file. We could consider an approach that allowed you to point it at a .sln file and if the project names follow some convention, we'd package all the projects into a single package. If you really want this feature, consider logging an issue in the NuGet issue tracker. http://nuget.codeplex.com/workitem/list/basic
{ "language": "en", "url": "https://stackoverflow.com/questions/7569685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Need help understand and INSERT/UPDATE procedure I have an INSERT/UPDATE Procedure that will only seem to update when I change the existing "name". I added a code field to the java, and want to update the code to the existing table without having to modify the "name" because it already exists. If I modify the "name" then the "code" will get updated to that row in the table. Can someone help me understand whats going or what I need to modify? thanks PROCEDURE update_things (things IN OUT things_bean, user_id IN NUMBER) IS t_things things_bean; BEGIN -- If there is already an id set ... this is an update IF things.ID <> 0 THEN SELECT things_bean (ID, NAME, code, work, foo) INTO t_things FROM things WHERE things.ID = ID; IF NOT things.equals (t_things) THEN things.foo:= t_things.foo; things.foo.modified_date := SYSDATE; things.foo.modified_by := user_id; UPDATE things SET NAME = things.NAME, code = things.code, foo= things.foo WHERE ID = things.ID; END IF; END update_things; A: looks to me like you should check this call: things.equals(t_things) to make sure your code value is part of the equality check.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Linking multiple arrays after parsing from XML I have parsed many differend xml to check, if - for example - a document is online or not and putting it into an array and "echo" the online documents this way: <?php // //Array $externdoc[123] = "Example 1"; $externdoc[456] = "Example 2"; $externdoc[789] = "Example 3"; $externdoc[2562] = "Example 4"; $externdoc[78545] = "Example 5"; // func foreach($externdoc as $nr => $name) { $xml = simplexml_load_file("http://www.example.com/docs.php?live_id=".$nr); if($xml->liveDocs->download!=0) { echo 'Download: '. $xml->liveDocs->download.' '.$name.; } } ?> Now here is the interesting part of my question. I would like to link each array with a different URL like this: <?php // //Array $externdoc[123] = "Example 1"; $externdoc [url] = 'http://www.example.com/docs/1.php'; $externdoc[456] = "Example 2"; $externdoc [url] = 'http://www.example.com/docs/2.php'; $externdoc[789] = "Example 3"; $externdoc [url] = 'http://www.example.com/docs/3.php'; $externdoc[2562] = "Example 4"; $externdoc [url] = 'http://www.example.com/docs/4.php'; $externdoc[78545] = "Example 5"; $externdoc [url] = 'http://www.example.com/docs/5.php'; // func foreach($externdoc as $nr => $name) { $xml = simplexml_load_file("http://www.example.com/docs.php?live_id=".$nr); if($xml->liveDocs->download!=0) { echo '<a href="HOW DO I LINK IT?"> Download: '. $xml->liveDocs->download.' '.$name.; } } ?> Any suggestions are welcome! A: Create a composite for each entry, the first exemplary: $externdoc[123] = array("Example 1", 'http://www.example.com/docs/1.php'); Inside the foreach you can then refer to the title and the URL: foreach($externdoc as $nr => $entry) { list($name, $url) = $entry; # name and URL in a variable of it's own ... Hope this is helpful, this is basically to create an array Docs of arrays. Instead of using one array per entry/item, you can also use stdClass objects Docs which can have multiple properties as well (like an array can have multiple key/value pairs).
{ "language": "en", "url": "https://stackoverflow.com/questions/7569693", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: For what it's worth starting an string in C# with @ Possible Duplicate: What's the @ in front of a string for .NET? when to use @ in c#? I'm quite new at C# programming and, in many examples, in particular at MSDN, the following code piece appears quite frequently: string NewString = @"Hello World"; I'm quite curious about what's the effect of the @ signal used in this code... is by any chance different than string NewString = "Hello World"; A: The @ introduces a raw string, which isn't preprocessed for escape sequences, such as \t. It is very convenient for regular expressions, which almost always include backslashes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JPA composite key @OneToMany I have the following existing DB schema, which I'd like to recreate with Java and plain JPA annotations (using hibernate as provider, so hibernate specific annotations would work as a last resort): CREATE TABLE users ( user_id NUMBER NOT NULL -- pk ); CREATE TABLE userdata_keys ( userdata_key_id NUMBER NOT NULL, -- pk key VARCHAR2(128) NOT NULL ); CREATE TABLE users_userdata ( user_id NUMBER NOT NULL, -- fk users.user_id userdata_key_id NUMBER NOT NULL, -- fk userdata_keys.userdata_key_id value VARCHAR2(256) ); I've thus created the following classes and annotations: class User { @Id Long id; @OneToMany Set<Userdata> userdata; } class UserdataKey { @Id Long id; String key; } class Userdata { String value; @EmbeddedId UserdataId userdataId; } @Embeddable class UserdataId { User user; UserdataKey userdataKey; } I left out columnName attributes and other attributes of the entities here. It does however not quite work as intended. If I do not specify a mappedBy attribute for User.userdata, hibernate will automatically create a table USERS_USERS_USERDATA, but as far as I've seen does not use it. It does however use the table which I specified for the Userdata class. Since I'm rather new to Java and hibernate as well, all I do to test this currently is looking at the DB schema hibernate creates when persisting a few sample entries. As a result, I'm entirely puzzled as to whether I'm doing this the right way at all. I read the hibernate documentation and quite a bunch of Google results, but none of them seemed to deal with what I want to do (composite key with "subclasses" with their own primary key). A: The mappedBy attribute is mandatory at one of the sides of every bidirectional association. When the association is a one-to-many, the mappedBy attribute is placed ot the one- side (i.e. on the User's userdata field in your case). That's because when an association is bidirectional, one side of the association is always the inverse of the other, so there's no need to tell twice to Hibernate how the association is mapped (i.e. which join column or join table to use). If you're ready to recreate the schema, I would do it right (and easier), and use a surrogate auto-generated key in users_userdata rather than a composite one. This will be much easier to handle, in all the layers of your application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Naming ivar the same as the class name I've never considered this a problem, until I ran the Xcode "Analyze" feature. Say I have a class called dude and I have created an instance of class and synthesized it so self.dude is available. This works just fine. However, in the dealloc if I put: [self.dude release]; I get an Analyzer warning because really what it should be is: [dude release]; However, this spawns another warning, as Analyzer thinks I am sending the release to the class name, not to the ivar. Now, if the ivar is named something different than the class, there is no problem and [ivar release]; works without Analyzer warnings. Should I take this as a general indication that it is not wise to name an ivar the same as a class name? It has never interfered with my product compilation or execution, but the Analyzer opens new questions about this. A: You should start you class names with uppercase letters (Dude) and instance variables (and other variables for that matter) with lower case letters (dude). This avoids the problem entirely and you'd also be following the standard naming conventions for Objective-C. A: It definitely is not a common practice to start a class name with a lower case letter. Objective-C/Cocoa convention is that you start a class name with a capital, and the method name and the instance variable name with a lower case letter. Just follow the common practice and name your class Dude and name your ivar dude.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Threads - Sharing variables I have a system that is multi-threaded. I want to create a object in a thread, and every object that runs in this thread can view this object. Example, When i use GetCurrentThreadID i always get same id, if i call it from the same thread. I want to call, for example, getSharedObject and always see the same object if i call it from the same object. So I need to write this object in a memory location that any object inside the same thread can see this object. Is there anyway to do that, using the Windows API? Or I have to do it by myself? thanks! A: If the variable where you save the object pointer is global, then any code in your thread can access it. And any code from any other thread can, too, for that matter. If you want that each thread sees a different object, then you want Thread Local Storage. See the win32 functions TlsAlloc, TlsSetValue, TlsGetValue and TlsFree. See also __declspec( thread ) here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Search JS Object for Value Say I have an object: userInfo And I want to search each node of userInfo to see if the key 'username' has a value equal to foo. userInfo[x].username == "foo" Is there a better way of doing the following? var matchFound = false; for (var i = 0, len = userInfo.length; i < len; i++) matchFound = userInfo[i].username == "foo"; A: There isn't really a better (more efficient) way without introducing another data structure. The answer really depends on your usage but you could do a few different things: * *Create separate 'indexes' using hashes. These structures would map keys to the items or the index in the source array. JavaScript objects/hashes support key based lookup and should be efficient. userinfo[x].username = "foo"; // Index the objects usersByName = {}; usersByName["foo"] = userinfo[x]; // -- OR -- index the array indices var usersByName["foo"] = x; // Test for key "foo" in usersByName; // true You'll have to put in a little more work to maintain consistency between the index and the source array. It's probably best to wrap both in another object to manage the contents of both. This approach is nice if there are multiple fields that you want to look objects up by. *If you don't care about the order of the collection you could just change the whole thing to a hash and index by username var userinfo = {}; userinfo["foo"] = {username: "foo", firstName: "Foo", lastName: "Bar"}; One thing to think about, though, is if the efficiency gains are going to outweigh the increased code complexity of maintaining indexes. If you aren't doing a lot of searches and you don't have tons of items in the userinfo collection it may make more sense to just write a general use searching function or use a library like what Philip Schweiger was mentioning. function findObjectByAttribute (items, attribute, value) { for (var i = 0; i < items.length; i++) { if (items[i][attribute] === value) { return items[i]; } } return null; } var userinfo = []; userinfo[0] = {username: "foo"}; console.log(findObjectByAttribute(userinfo, "username", "foo")); A: No need for the ternary operator, consider the following: var matchFound = false; for (var i = 0, len = userInfo.length; i < len; i++) { matchFound = userInfo[i].username == "foo"; if(matchFound){ break; } } A: The underscore JS library has some handy methods to work with data collections - for instance, the select method Implementing it would like like this: var userInfo = { 'x':{ username: "foo", password:'dlji' }, 'y':{ username: "bar" , password:'adfasf' }, 'z': { username: 'foo', password:'d3alj4i' } }; var found = _.select(userInfo, function(node){ return node.username === "foo" }); console.dir (found); Underscore isn't very large, and while you can do this in native JS too, I think it does a good job implementing the solutions you'd come up with on your own. Basically, it gives you a lot of the JS features you'd think should be there anyway.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: The given System.Uri cannot be converted into a Windows.Foundation.Uri I'm trying to programmatically load a BitmapImage in a XAML Metro app. Here's my code: var uri = new Uri("/Images/800x600/BackgroundTile.bmp", UriKind.RelativeOrAbsolute); var imageSource = new BitmapImage(uri); The second line crashes with a System.ArgumentException: The given System.Uri cannot be converted into a Windows.Foundation.Uri. Please see http://go.microsoft.com/fwlink/?LinkID=215849 for details. The link just goes to the MSDN home page, so it's no use. I've also tried removing the leading /, in case WinRT has different expectations about relative URIs, but I still get the same exception. Why am I getting this exception for what seems to be a perfectly valid URI? A: In the Consumer Preview, the correct URL format has apparently changed to ms-appx:/Images/800x600/BackgroundTile.bmp A: You will need to use the page's BaseUri property or the image control's BaseUri property like this: //using the page's BaseUri property BitmapImage bitmapImage = new BitmapImage(this.BaseUri,"/Images/800x600/BackgroundTile.bmp"); image.Source = bitmapImage; or //using the image control's BaseUri property image.Source = new BitmapImage(image.BaseUri,"/Images/800x600/BackgroundTile.bmp"); you can see the reason and solution here A: Judging from the documentation for Windows.Foundation.Uri, it looks like WinRT doesn't support relative URIs. I tried a pack:// URI, but that gave me a UriFormatException, so apparently that's not the way to do it in WinRT either. I found the answer on this thread: MS invented yet another URI format for WinRT resources. This works: new Uri("ms-resource://MyAssembly/Images/800x600/BackgroundTile.bmp") Note that you don't add your actual assembly name -- the MyAssembly part is literal text. A: In case you're still having issues or are being asked to find an app to open the link, are you trying to use a WebView? If so, try using ms-appx-web instead of ms-appx. An example: this.webBrowser.Navigate(new Uri("ms-appx-web:///level/level/level/index.html")); Also note the lack of the URIKind parameter--evidently not needed at all in these instances. (I believe you may need to vary the leading forward slashes depending on your reference) A: This would work in XAML but would not work in code... so each control or page has a BaseUri property which you can use to build the proper uri for assets... here is an example: imageIcon.Source = new BitmapImage(new Uri(this.BaseUri, "Assets/file.gif")); // Or use the base uri from the imageIcon, same thing imageIcon.Source = new BitmapImage(new Uri(imageIcon.BaseUri, "Assets/file.gif")); also you would need to set the build action to "Content" rather than Embedded Resource... otherwise you need to use the ms-resource:// protocol. A: I know this is old but I hope this helps. I wrote this in XAML and it worked for me. The Ide I'm using is vs-2015 with win-10. <Window> <Grid> <Grid.Background> <ImageBrush ImageSource="NameOfYourImage.JPG or any Image type"/> </Grid.Background> <GroupBox x:Name="groupBox" Header="GroupBox" HorizontalAlignment="Left" Height="248" Margin="58,33,0,0" VerticalAlignment="Top" Width="411"> <GroupBox.Background> <ImageBrush ImageSource="NameOfYourImage.JPG or any Image type"/> </GroupBox.Background> </GroupBox> </Grid> </Window> A: MVVM ;) public static ImageSource SetImageSource(string uriPath)//.com/image or some path { // this method very good for mvvm ;) try { //In Model - public ImageSource AccountPhoto { get; set; } //AccountPhoto = SetImageSource("some path"); return return new BitmapImage() { CreateOptions = BitmapCreateOptions.IgnoreImageCache, UriSource = new Uri(uriPath) }; } catch { Debug.WriteLine("Bad uri, set default image."); return return new BitmapImage() { CreateOptions = BitmapCreateOptions.IgnoreImageCache, UriSource = new Uri("ms-appx:///Avatar/Account Icon.png") }; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Linq like search across multiple fields I'm trying to create a simple address screen where the user has a single "google" style query box which searches across all address fields i.e. address line 1, town, city, post code etc. I'm using .net and EF with an SQL database. I've tried IEnumerable<T> results = from x in dbSet where (x.AddressLine1 + x.AddressLine2 + x.AddressLine3 + x.Town + x.City + x.County + x.Postcode).Contains(Query) select x; This does not match any results when it should. If i change it to IEnumerable<T> results = from x in dbSet where x.AddressLine1.Contains(Query) select x; It matches and returns results but obviously its not searching across all fields. First question why is my first example not working and second is this the best way to implement this or is it going to struggle under pressure. A: Try this: IEnumerable<T> results = from x in dbSet where x.AddressLine1.Contains(Query) || x.AddressLine2.Contains(Query) || x.AddressLine3.Contains(Query) || x.Town.Contains(Query) || x.City.Contains(Query) || x.County.Contains(Query) || x.Postcode select x; For more complicated searches using Linq, I use LinqKit A: Your current approach will require a full table scan with some sub-string matching operation on each row - I can't imagine this being performant on a large table. What you really should do is use SQL fulltext. There is no native support for this in EF but you could use a stored procedure or store query. A: what happens if you use this IEnumerable<T> results = from x in dbSet where x.AddressLine1.ToString().Contains(Query) || x.AddressLine2.ToString().Contains(Query) || x.AddressLine3.ToString().Contains(Query) || x.Town.ToString().Contains.(Query)|| x.City.ToString().Contains.(Query) || x.Postcode.ToString().Contains(Query) select x;
{ "language": "en", "url": "https://stackoverflow.com/questions/7569725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Retrieve value from a Json Array I'm having difficulty in retrieving values from a Json array. I have a Json dataset that has been created using json_encode. This is how it appears after using json_decode and displaying using print_r: Array ( [0] => stdClass Object ( [postID] => 1961 [postTitle] => Kiss My Fairy [previewThumb] => 2011/09/Kiss-My-Fairy-Ibiza-essentialibiza-2011_feature.jpg [blogContent] => Ibiza has always had a flair for the extravagant, inhibitions are checked in at the airport when the floods of tourists arrive and the locals have embraced a freedom of partying that has turned the quiet Mediterranean island into the Mecca... ) ) a_post_data_array = 1 The code that achieves this is as follows: $post_data_URL = "http://myurl.com/news/scrape/facebook-like-chart-ID.php?post_name=kiss-my-fairy"; $post_data_response = file_get_contents($post_data_URL); $a_post_data_array=json_decode($post_data_response); I now simply need to retrieve some of the values from this array to use as variables. The array will only ever have 1 set of values. I'm using the following code but it isn't working. echo "**** -- " . $a_post_data_array[post_title] . "<br>"; Can anyone please help? I'm sorry this is so basic. I've been searching online but can't find any examples of this. A: echo "** -- " . $a_post_data_array[0]['post_title']; A: There are multiple issues with your code: * *First you should instruct json_decode to give you a pure array with $data = json_decode($response, TRUE); *Then the result array is a list, and you have to access the first element as $data[0] *The entry you want to access has the key postTitle, not post_title as your example code showed. (And unless that's a predefined constant won't work.) *And you need to put those array keys in quotes, like print $data[0]["postTitle"]; Turn up your error_reporting level for some development help. A: try this PHP code: //$post_data_response = file_get_contents("https://raw.github.com/gist/1245028/80e690bcbe6f1c5b46676547fbd396ebba97339b/Person_John.json"); //$PersonObject = json_decode($post_data_response); // Get Person Object from JSON Source $PersonObject = json_decode('{"ID":"39CA2939-38C0-4C4E-AE6C-CFA5172B8CEB","lastname":"Doe","firstname":"John","age":25,"hobbies":["reading","cinema",{"sports":["volley-ball","snowboard"]}],"address":{}}'); // Get data from Object echo "Person ID => $PersonObject->ID<br>"; echo "Person Name => $PersonObject->firstname<br>"; echo "Person Lastname => $PersonObject->lastname<br>"; echo "Person Age => $PersonObject->age<br>"; echo "Person Hobbies => " . $PersonObject->hobbies[0] . "<br>";
{ "language": "en", "url": "https://stackoverflow.com/questions/7569741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Repository interface null error when called from HomeController I was following this tutorial: http://blog.johanneshoppe.de/2010/10/walkthrough-ado-net-unit-testable-repository-generator/ And I had this issue: MVC3 & EF. Interface for TDD However, now I have my interfaces setup (I am not using ninject due to project restrictions) I am getting a null error here; `Public partial class MyEntitiesRepository : MyEntitiesRepository { public IEnumerable<userdetails> getAlluserDetails() { return this.Context.userDetails.ToList(); }` Context is null. I am using the exact same structure as the tutorial. The header in my MVC controller that calls this is: ` [HandleError] public class HomeController : Controller { private MyEntitiesRepository _repository; ... ... public HomeController() : this(new externalEntities(), new MyEntitiesRepository ()){} public HomeController(externalEntities external, MyEntitiesRepository repository) { _repository = repository; _ContextExt = external; } ` EDIT: context is from: [System.CodeDom.Compiler.GeneratedCode("ADO.NET Unit Testable Repository Generator", "0.5")] public partial class MyEntitiesRepository { /// <summary> /// Gets or sets the specialised object context /// </summary> /// <value>object context</value> #if !DO_NOT_USE_UNITY [Dependency] #endif public IMyEntities Context { get; set; } } } A: I am guessing that in the example they pass the Context in the constructor. They can do this because they are using dependency injection and it will create that instance for you. Since you are not using Ninject, you will more than likely need to construct this Context yourself. If you are unable to use Ninject or any other IoC container then you need to do a better job convincing your bosses to let you. If they still don't let you then you can do poor man's dependency injection I suppose: public class MyEntitiesRepository { private MyDbContext context; public MyEntitiesRepository() : this(new MyDbContext()) { } public MyEntitiesRepository(MyDbContext context) { this.context = context; } } It's better than nothing I suppose? A: Seeing the edit (the Dependency attribute) I guess the project restrictions you are referring to are that instead of Ninject you are to use Microsoft's Unity. Now you can solve your problem using or not using Unity. To start with the latter: Adjust your HomeController and MyEntitiesRepository classes a little: public HomeController() : this(new externalEntities(), new MyEntitiesRepository (new MyEntities())) { } public HomeController(externalEntities external, MyEntitiesRepository repository) { _repository = repository; _ContextExt = external; } public partial class MyEntitiesRepository { public MyEntitiesRepository(IMyEntities context) { this.Context = context; } public IMyEntities Context { get; private set; } } Here I made the assumption that you have a class MyEntities implementing the interface IMyEntities. You could also use Unity. To get to know that framework a little better you could start at MSDN. I don't have any experience with Unity, but some things I noticied are that you need to create MyEntityRepository using a UnityContainer object: IUnityContainer container = new UnityContainer(); ... MyEntityRepository repository = container.Resolve<MyEntityRepository>(); Before that works you need to register a mapping of MyEntities to IMyEntities: container.RegisterType<IMyEntities, MyEntities>(); If you choose to try Unity I suggest you give it a try and ask a new question if you get stuck.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569744", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python List Parsing Probably a simple question, but I am new to Python. I have a file containing email addresses, one per line. I want to read the file and append them together separated by a comma. Is there a more pythonic way of doing this? def getEmailList(file_name): f = open(file_name, 'r') emailstr = '' for line in f: emailstr += line.rstrip() + ',' f.close() return emailstr A: You could do the following: def getEmailList(file_name): with open(file_name) as f: return ",".join(x.rstrip() for x in f) The key features of that version are: * *Using the with statement so that the file is automatically closed when control leaves that block. *Using the list comprehension generator expression x.rstrip() for x in f to strip each line Thanks to agf for that correction *Using str.join to put a ',' between each item in the sequence A: ','.join(line.rstrip() for line in f) A: def getEmailList(file_name): with open(file_name, 'r') as f: result = ", ".join(addr.rstrip() for addr in f) return result A: def getEmaulList(file_name): with open(file_name, "r") as f: data = f.read() emails = ",".join(data.split("\n")) return emails Keeps it simple. A: How about: with open(file_name, 'r') as f: emailstr = ','.join(line.rstrip() for line in f) A: You can use the join method to join together a set of strings. def getEmailList(file_name): with open(file_name, 'r') as f: return ','.join([line.rstrip() for line in f]) A: everything in one shot ",".join([x.replace('\n','') for x in open("yourFile.txt").readlines()])
{ "language": "en", "url": "https://stackoverflow.com/questions/7569748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I output the contents of an array in an html table while using jQuery? How do I display the contents of an array in a HTML table while using jQuery? Here's my script... This outputs the objects in the array on top of the table not in the table. HTML <table> <thead> <tr> <th>ITEM ID</th> <th>NUMBER OF BAGS</th> <th>WEIGHT</th> </tr> </thead> <tbody> <div id="returnlist"></div> </tbody> </table> jQuery var tempList = new Array(); $('#add').click(function(){ var split = $('#onhanditem').val().split('_'); var itemid = split['0']; var kilo = $('#kilo').val(); var bagsReturned = $('#bagsReturned').val(); var totalbagkiloreturned = kilo+'_'+bagsReturned; tempList[itemid] = totalbagkiloreturned; list = ''; // i = ITEM ID | tempList = totalbagkiloreturned for (var i in tempList){ var itemID = i; var split = tempList[i].split('_'); var kilo = split['0']; var numBags = split['1']; list+='<tr><td>'+itemID+'</td><td>'+kilo+'</td><td>'+numBags+'</td></tr>'; } $('#returnlist').html(list); }); }); A: You can't have a div inside a table, it's simply not valid HTML. Try the following HTML instead <table> <thead> <tr> <th>ITEM ID</th> <th>NUMBER OF BAGS</th> <th>WEIGHT</th> </tr> </thead> <tbody id="returnlist"> </tbody> </table> A: As far as I'm aware, the middle of a table isn't a valid location for a <div> tag, which is why it's not being displayed inside the table. Why not put your id on the <tbody> tag instead, and do away with the div altogether?
{ "language": "en", "url": "https://stackoverflow.com/questions/7569750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to use method(s) to add multiple, changing values I'm working on a personal project for a friend and have hit a bit of a roadblock. I can continue as I am and write some really redundant code, but I feel there must be a more efficient way of doing this. What I'm trying to do is write a method that will add three values and display the results to the text box under "Skill Modifier" header (see screenshot). I need to get the method, or a series of methods, to do that for each skill. It needs to get the Skill Modifier value for Balance, Climb, Escape Artist, etc... The method would be something like "CalculateSM" What I have currently: private void btnUpdate_Click(object sender, EventArgs e) { //AM + R + MM =SM //AM = Ability Modifier //R = Rank //MM = Misc Modifier //SM = Skill Modifier decimal balanceMod = balanceAM.Value + balanceR.Value + balanceMM.Value; balanceSM.Text = balanceMod.ToString(); decimal climbMod = climbAM.Value + climbR.Value + climbMM.Value; climbSM.Text = climbMod.ToString(); //etc... } Essentially the biggest issue, for me, is figuring out how to contrive a method that can deal with so many different field names and add them in the same way. I'd like to avoid copy and pasting the same two lines of code fifty times over for each and every skill. Any ideas would be much appreciated! Thank you. A: using fields like this is not very object-oriented. you're probably going to want to introduce a Skills class that implements the method to calculate the final skill score and then use some Skills objects for different skills. public class Skill { int ability, rank, misc; public Skill(int ability, int rank, int misc) { this.ability = ability; this.rank = rank; this.misc = misc; } public int Score { get { return ability + rank + misc; } } Skill balance = new Skill(10, 1, 1); textBalance.Text = balance.Score.ToString(); Skill programming = new Skill(10, 100, 0); textProgramming.Text = programming.Score.ToString(); also, think of a clever way to tie the skills to your user controls. you're not going to like ending up with 50 text boxes that are all alike except for a bit of a name. a first step could be to wire them all up to the same event handler, for example. A: Normally, the approach would be to create a class which represents one row of your skills screen. You could then keep a list of these in some way (say, List<Skill>). You could then quite easily loop through all of them: foreach (Skill skill in character.Skills) { // do something with the skill object } The trick would be to dynamically generate the user interface. It's not actually very hard to do this (although a bit too much code to go into here), by far the easiest approach would be to use something like a DataGridView. It should be fairly easy to google for examples, or just ask if you want specific info. A: Looks like you have an object collection which you could databind to something in the UI (like a data grid or something) Modify the values calculate things, what you could do in some example code: class Skill { public string Name { get; set; } public string KeyAbility { get; set; } public int SkillModifier { get; set; } public int AbilityModifier { get; set; } public int Ranks { get; set; } public int MiscModifier { get; set; } void Calculate() { //Formula goes here //Set the SkillModifier } } Skill balance = new Skill() { Name = "Balance" } Basically you can make a collection of skills, update through what ever UI object you bind to etc. Using fields the way you are atm is very redundant and using OO you can achieve the same with alot less work. Basically in You'd create a collection of the Skill class, with Balance and all other skills you mentioned. Databind this collection to something in the UI, allow for updating, call different methods. You could even implement some inheritance for different type of skills. With a Skill base class. A: What type are balanceAM, balanceR etc? Can they not derive from a base type or interface that you can use to pass to a helper method? private string GetText(IModel modelAM, IModel modelR, IModel modelMM) { return modelAM.Value + modelR.Value + modelMM.Value; } balanceSM.Text = this.GetText(balanceAM, balanceR, balanceMM); A: Ok, the fact that you only have private fields for each individual control is your core problem. You're probably better off creating a list of structs to store them: struct PickYourOwnNameHere { Control SM; Control AM; Control R; Control MM; } List<PickYourOwnNameHere> skills = new List<PickYourOwnNameHere>(); Obviously, populate that list on initialization, and then you can just do: skills.ForEach(skill => skill.SM.Text = (skill.AM.Value + skill.R.Value + skill.MM.Value).ToString() ); I'm doing that syntax from memory, but hopefully you get the idea.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569751", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: formatting a string which contains quotation marks I am having problem formatting a string which contains quotationmarks. For example, I got this std::string: server/register?json={"id"="monkey"} This string needs to have the four quotation marks replaced by \", because it will be used as a c_str() for another function. How does one do this the best way on this string? {"id"="monkey"} EDIT: I need a solution which uses STL libraries only, preferably only with String.h. I have confirmed I need to replace " with \". EDIT2: Nvm, found the bug in the framework A: it is perfectly legal to have the '"' char in a C-string. So the short answer is that you need to do nothing. Escaping the quotes is only required when typing in the source code std::string str("server/register?json={\"id\"=\"monkey\"}") my_c_function(str.c_str());// Nothing to do here However, in general if you want to replace a substring by an other, use boost string algorithms. #include <boost/algorithm/string/replace.hpp> #include <iostream> int main(int, char**) { std::string str = "Hello world"; boost::algorithm::replace_all(str, "o", "a"); //modifies str std::string str2 = boost::algorithm::replace_all_copy(str, "ll", "xy"); //doesn't modify str std::cout << str << " - " << str2 << std::endl; } // Displays : Hella warld - Hexya warld A: If you std::string contains server/register?json={"id"="monkey"}, there's no need to replace anything, as it will already be correctly formatted. The only place you would need this is if you hard-coded the string and assigned it manually. But then, you can just replace the quotes manually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569753", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make the content of a div to be in center in this div, the content's top is higher than the bottom, please tell me what to do now.. .dtestContactDet{ border-bottom:1px solid #D7D7DE; border-bottom:1px solid #D7D7DE ; -khtml-border-bottom:1px solid #D7D7DE; -moz-border-radius:1px solid #D7D7DE; -webkit-border-bottom:1px solid #D7D7DE; } A: Pasting the HTML would help too. The question is a little bit vague, please explain. Do you mean you want to center the div or do you really want to center what's inside the div? If it's the former: .dtestContactDet{ text-align:center; } A: As leonel said. That's the preview.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Paperclip and json, "stack level too deep" I use Paperclip in one of my model : class Event < ActiveRecord::Base belongs_to :continent belongs_to :event_type scope :continent, lambda { |continent| self.scoped.where('continent_id IN ( ? )', continent) unless continent.blank? } scope :event_type, lambda { |eventType| self.scoped.where('event_type_id IN ( ? )', eventType) unless eventType.blank? } scope :in_date, lambda { |date| self.scoped.where('(MONTH(`date_start`) BETWEEN ? AND ?) OR (MONTH(`date_end`) BETWEEN ? AND ?)', date[0],date[1],date[0],date[1]) unless date.blank? } has_attached_file :map, :styles => { :medium => "238x238>", :thumb => "100x100>" } end I make a Ajax request on this action : def filter @events = Event.scoped @events = @events.continent(params[:continents]) unless params[:continents].blank? @events = @events.event_type(params[:event_type]) unless params[:event_type].blank? @events = @events.in_date(params[:months]) unless params[:months].blank? respond_with( @events ) end I call this url to get the json answer. When i did, i get the error : "stack level too deep" Anyone can help me? My trace is here : http://paste.bradleygill.com/index.php?paste_id=316663 A: Stack depth too deep indicates that you ended up in an infinite loop. Your continent scope is the problem, since your method and argument have the same name, when you call the argument within the continent scope, you end up with an infinite loop. Also, why not just write your scopes as a series of class methods? I'm not a huge fan of using lambdas to pass in arguments in scopes, as it makes it somewhat harder to read. Here is an example of having the scopes as class methods class Event < ActiveRecord::Base belongs_to :continent belongs_to :event_type class << self def continent(cont) where('continent_id IN ( ? )', cont) unless cont.blank? end def event_type(eventType) where('event_type_id IN ( ? )', event_type_id) unless event_type_id.blank? end def in_date(date) where('(MONTH(`date_start`) BETWEEN ? AND ?) OR (MONTH(`date_end`) BETWEEN ? AND ?)', date[0],date[1],date[0],date[1]) unless date.blank? end end has_attached_file :map, :styles => { :medium => "238x238>", :thumb => "100x100>" } end
{ "language": "en", "url": "https://stackoverflow.com/questions/7569759", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Symfony 1.4 save all items' froms with one action I want to create thumbnails for 200+ objects with one action in Symfony 1.4. The problem is that thmbnail generation takes place on saving the form. class AuthorForm extends BaseAuthorForm { public function configure() { /* some configs */ } public function save($con = null) { /* create thmbnail from original picture */ } } How can I write an (batch) action to be able to save them all at once, rather than going to each item in the backend and saving? Please note, that just $author->save(); won't work, of course. Thanks! A: You have to fetch the objects, loop through them, create the form and save. Like the following. $authors = Doctrine_Core::getTable('Author')->findAll(); foreach($authors as $author){ $form = new AuthorForm($author); $form->save(); } You'll probably have memory issues if you're running it on a hosting plan (not your dev machine). A better way to get thumbnails is using a plugin like sfImageTransformExtraPlugin (http://www.symfony-project.org/plugins/sfImageTransformExtraPlugin) that generates a cached thumbnail as you need them. You don't even need to go through the trouble of generating the thumbnails. And still can have multiple thumbnail versions of the same photo pretty easily. If you still need to use this way, do some unset stuff during the loop, like the following. $authors = Doctrine_Core::getTable('Author')->findAll(); foreach($authors as $author){ $form = new AuthorForm($author); $form->save(); unset($form, $author); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569765", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: optimise distance calculation in matlab I am a newbie with Matlab and I have the following scenario( which is part of a larger problem). matrix A with 4754x1024 and matrix B with 6800x1024 rows. For every row in matrix A i need to calculate the euclidean distance in matrix B. I am using the following technique to calculate the distance but I find that this is very inefficient and very time consuming in Matlab. for i=1:row_A A_data=A_test(i,:); for j=1:row_B B_data=B_train(j,:); X=[A_data;B_data]; %calculate distance d=pdist(X,'euclidean'); dist(j,i)=d; end end Any suggestions to optimise this because the final step involves performing this operation on 50 such sets of A and B. Thanks and Regards, Bhavya A: I'm not sure what your code is actually doing. Assuming your data has the following properties assert(size(A,2) == size(B,2)) Try d = zeros(size(A,1), size(B,1)); for i = 1:size(A,1) d(i,:) = sqrt(sum(bsxfun(@minus, B, A(i,:)).^2, 2)); end Or possibly better organised by columns (See "Store and Access Data in Columns" in http://www.mathworks.co.uk/company/newsletters/news_notes/june07/patterns.html): At = A.'; Bt = B.'; d = zeros(size(At,2), size(Bt,2)); for i = 1:size(At,2) d(i,:) = sqrt(sum(bsxfun(@minus, Bt, At(:,i)).^2, 1)); end
{ "language": "en", "url": "https://stackoverflow.com/questions/7569772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I present a pick list in a SharePoint 2010 External List form from an association in my BDC model? I have created associations between entities in my .Net assembly BCS model. When I load the model into SharePoint and create external lists, I automatically get an External Item Picker control; enabling me to select an item from a list. This is great because I don't have to program this pick list one way or another... The problem is whenever I modify the form in InfoPath, the External Item Picker seems to break. When I select an item using the External Item Picker (in the InfoPath form) I get an error message "There has been an error while processing the form". This message is displayed as soon as I select an item and try to leave the field; WITHOUT submitting the form. Can anyone tell me why the External Item Picker breaks whenever I modify and publish the list form from InfoPath 2010? It's driving me nuts! Thanks! A: I've ran into the same issue, and found the following answer: It's a bug from the August cumulative update. Source I am in the process of installing the February CU to see if it has the solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can BLTookit Generate Db and Tables I am currently using Entity Framework Code First to generate my MySQL tables and schema from my classes. However, I would like to switch to BlToolkit. Does this ORM support table generation from classes decorated with various attributes? If so, can you give a quick example? I was looking at editable object like this but wasn't sure: public abstract class TestObject : EditableObject<TestObject> { public abstract string FirstName { get; set; } public abstract string LastName { get; set; } } ... I've also seen this: public abstract class PersonAccessor : DataAccessor { [SqlText(@"SELECT * FROM Person WHERE FirstName = @firstName")] public abstract List<Person> GetPersonListByFirstName(string @firstName); [SprocName("sp_GetPersonListByLastName")] public abstract List<Person> GetPersonListByLastName(string @lastName); ... But I'd rather not write the SQL. I am using BLTookit 4.0 with C# on Visual Studio 2010, with MySql 5.3 Thanks! A: You can use T4 templates to generate the classes -> http://bltoolkit.net/Doc.T4Templates.ashx And no, you don't have to write SQL just use the Linq Provider, check the documentation @ http://bltoolkit.net/Doc.Linq.ashx Best is also to get the Full dev version which has loads of examples and unit tests A: I don't know is it possible to created the database and tables with BLToolkit. This is what I would also like to know. As of writing SQL in code, you don't need to do that. You can just write Linq queries for select, but for insert,update and delete the syntax is little different than in Linq2SQL or Linq2Entity, but when you start to use it you'l get used to it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Currency formatting language? I am using a GridView and I need to show the currency in Arabic culture so I used this code which is working very well, DataFormatString="{0:c}" The results will be like this : د.ك.‏ 55.000 Now what I want is to change it like this : 55.000 K.D ??? A: Have you tried DataFormatString = "{0:0.000} K.D."? As shown in this example.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery search text in elements as SQL query LIKE? Hi is there anyway to search text in dom, as we do for SQL query LIKE? i mean, i have. <ul> <li>ab</li> <li>abrecot</li> <li>abus</li> <li>aby</li> <li>abrea</li> </ul> i would like to search for "abre" and so return in text ASC order: <li>abrea</li> <li>abrecot</li> is this possible? definitely the query would looks like doing: SELECT <li> FROM <ul> WHERE text LIKE 'abre%' ORDER BY text ASC; :)) A: As you are looking for elements whose text starts with a specified string, you can use the filter method: var x = $("ul li").filter(function() { return $(this).text().substr(0, 4) === "abre"; }); This will only return elements which have the string "abre" at the start. The other answers using the contains method will return elements with the string found anywhere within them, which does not match your pseudo-SQL query. Here's a working example of the above. A: I think you would want the jQuery 'contains' function, have a look at the docs here: http://api.jquery.com/contains-selector/ Your example would probably look like this: $("li:contains('abre')") EDIT to include the comments here, if you are looking for "starts with", you can do this on an element using the following syntax: $('li[anAttribute^="abre"]') But this assumes you have an attribute to query which i don't think you do, in which case the filters answer will likely suit your needs best. A: The :contains() selector is probably what you're looking for: http://api.jquery.com/contains-selector/ QUOTE: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-latest.js"></script> </head> <body> <div>John Resig</div> <div>George Martin</div> <div>Malcom John Sinclair</div> <div>J. Ohn</div> <script> $("div:contains('John')").css("text-decoration", "underline"); </script> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/7569782", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Object scope and aggressive cleanup on paused Activity instances I have an Activity that contains an AsyncTask as an inner class (as I have seen in most examples). If I fire the AsyncTask and then pause the Activity by navigating away from it, the AsyncTask continues to execute. As I understand it, this is normal and expected behavior. There is a member variable in the Activity that is being accessed by a method call from the AsyncTask. I just got a NullPointerException on it while the AsyncTask was executing in the background while its Activity was paused, which seems to me that it was collected by the GC when the Activity was paused. It would seem to me that the object should not be considered out of scope. There is code still running in the Activity, so why would the Activity's member variables start getting cleaned up already? What is the recommended usage of Activity member variables being accessed via AsyncTasks that are inner classes of the Activity? Here is a sample of the kind of relationships my objects have public class MyActivity { MyCustomService myCustomService; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.some_layout); myCustomService = ServiceLocator.getInstance(MyCustomService.class); } private class FetchDataTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... arg0) { String data = someOtherService.fetchSomeData(); return data; } @Override protected void onPostExecute(String result) { refreshControls(result); } } private void refreshControls(String result) { // this is where the object is null after aggressive cleanup myCustomService.someMethod(); } A: I don't really understand what is causing the NullPointerException. But you might want to check my answer here for a AsyncTask which is not a inner class of the activity but static. Inner async tasks which are started are leaking the context / activity as long as they are running. This might be no problem for short running tasks but if it stucks or performs for a long time it is leaking memory for that time. This might imply the answer to your question...
{ "language": "en", "url": "https://stackoverflow.com/questions/7569789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Default values for integers in structure I can't figure out how to set default value for integer in structure. For example typedef struct { char breed[40]; char coatColor[40]; int maxAge = 20; } Cat; The code above gives me an error on execution - Expected ';' at end of declaration list A: You cannot specify default values in C. What you probably want is an 'init' style function which users of your struct should call first: struct Cat c; Cat_init(&c); // etc. A: In C you cannot give default values in a structure. This syntax just doesn't exist. A: Succinctly, you can't. It simply isn't a feature of C. A: A structure is a type. Types (all types) do not have default values. // THIS DOES NOT WORK typedef char = 'R' chardefault; chardefault ch; // ch contains 'R'? You can assign values to objects in initialization char ch = 'R'; // OK struct whatever obj = {0}; // assign `0` (of the correct type) to all members of struct whatever, recursively if needed A: you can initialize but it's not practical with strings ( better to use your custom functions) typedef struct { char breed[40]; char coatColor[40]; int maxAge; } Cat; Cat c = {"here39characters40404040404044040404040", "here39characters40404040404044040404040", 19 };
{ "language": "en", "url": "https://stackoverflow.com/questions/7569795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ASP.NET image src question I set the value of a image control via the following jquery code: $('.image').click(function () { var imgPath = $(this).attr('src'); var imgName = imgPath.substring(0, imgPath.length - 4); var imgAlt = $(this).attr('alt'); $('#<%= detailedImage.ClientID %>'). attr('src', imgName + '-large.jpg'). attr('alt', imgAlt); The picture shows up perfectly in the browser. However I cannot access it's src attribute: string imgName = detailedImage.Src; imgName is always an empty string. Any suggestions? A: I'm sure there are a number of ways to solve this, depending a lot on factors elsewhere in your page and your application which would contribute to the overall functionality and user experience. But in terms of suggestions, how about this: Instead of trying to maintain the state of the selected image in the image control, separate it out into a different control. Use a standard img HTML element for displaying the image(s) to the user on the client-side and keep that as solely a user experience concern. Don't use it as part of a form. Then create a separate control (a hidden field, a text box which has been styled to not be displayed, etc.) and set the path of the image file as the value of that control in your JavaScript. Something like this: $('.image').click(function () { var imgPath = $(this).attr('src'); var imgName = imgPath.substring(0, imgPath.length - 4); var imgAlt = $(this).attr('alt'); $('#showImage').attr('src', imgName + '-large.jpg').attr('alt', imgAlt); $('#<%= imagePath.ClientID %>').val(imgName + '-large.jpg'); }); Note that the src and alt are being set on a standard img tag (with id showImage in this case) and the value that the server-side code cares about is being set on another control entirely (with server-side id imagePath in this case). I don't have a way of testing this on hand right now, but it's a suggestion. It's possible it may not work, and if that's the case let me know so I can modify/remove this answer. But it seems like it would make sense given that things like TextBox ASP.NET controls are meant to have their values modified on the client-side. (Indeed, in this case you may have better luck with a TextBox styled to not be displayed than with a hidden field.) A: Changing the src of an img, even though the img is placed within a <form> doesn't submit the src to the server. You need to set the new src in something that will be submitted in the form, i.e. a hidden field. Try this: $('.image').click(function () { var imgPath = $(this).attr('src'); var imgName = imgPath.substring(0, imgPath.length - 4); var imgAlt = $(this).attr('alt'); var src = imgName + '-large.jpg'; $('#<%= detailedImage.ClientID %>'). attr('src', src). attr('alt', imgAlt); $('#<%= hiddenInput.ClientID %>').val(src); }); If you now have something like this in your markup: <input type="hidden" id="ImageSource" runat="server" /> You should be able to retrieve ImageSource.Value server-side.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convincing eclipse/GPE to not recompile GWT code when I make a server-only change I'm working with GWT and GAE in Eclipse with the google eclipse plugin. Sometimes I just want to make a quick server fix. I change something in my server code and re-deploy, but the GWT code is all recompiled as well. At this point that takes about 10 minutes, and is a real drag when a customer is waiting on the change. The server code is not in a source path in my GWT modules. Anyone have ideas about convincing GWT that no relevant changes have been made, and that it can skip the recompile? Alternatively, I'd be happy to just manually force the GWT compiler not to run. A: If using maven, set the property gwt.compiler.skip to true. If not, there should be a flag in whatever build setup you are using to force a skip when you know it isn't necessary (and if you can share how you are building, it might be possible to offer more specific instructions). It is very difficult for the compiler to determine that no code which might affect the client has changed, even if you dont change any client or shared code. Generators and linkers both are arbitrary java code that can call anything else on the classpath, and the compiler can't ensure that they don't call into your other classes (and in fact this can be a useful feature, like for RequestFactory proxy validation).
{ "language": "en", "url": "https://stackoverflow.com/questions/7569798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to set editor tooltip color and background in Visual Studio 2010? i am using black scheme and set up color setting for editor tooltips: Sample preview is correct but actual result is different: Is it possible to set up tooltip colors in Visual Studio 2010 properly? A: After installing the Productivity Power Tools and following this post it is at least possible to read the signatures again, but that post gives me little hope how to fix the other color settings. Edit: Installing CSharpIntellisencePresenter makes the Auto-Complete readable in a dark theme, see this question A: I tried using Hack-It to enable the "Custom..." buttons with VS2008 and changed color settings were saved (still present after a VS restart). But I was not changing the colors for the correct item I guess. I am using Visual Assist and I think the 'Editor Tooltip' is not the item I want to change the colors from. You could give it a try... Anyone knows from which item I must change colors to affect Visual Assist tool tips when hovering a function ? For Visual Assist tooltip I need to change Windows theme...
{ "language": "en", "url": "https://stackoverflow.com/questions/7569808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: How can I interact with the Lockscreen layout to display text into it, like this app: I just discovered this application : https://market.android.com/details?id=de.j4velin.lockscreenCalendar It seem that is now possible to write some text inside the lockscreen in the place where the alarm is usually written. I would like to display custom text on this place, but have totally no idea on how to achieve that. This guy succeed to write calendar events at this place. Thank a lot for any clue//snippet that would help me. A: This is astonishingly easy to achieve and astonishingly badly documented. All you need to do is set the alarm string in the system settings, as follows: String message = "This is a test"; Settings.System.putString(context.getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, message); A: It is not the exact thing you asked for,but the code for custom lockscreen can be found here.It might help you. http://code.google.com/p/contactowner/ A: I've never come accross any legit way within the public android APIs to affect the lock screen. Without playing with that app at all I wouldn't know for sure, but my guess is he created that activity that allows him to show whatever text he wants. Then uses a receiver to listen for SCREEN_OFF, or SCREEN_ON events and starts his "lock" activity at that time. It is worth noting: If you choose to do something like this to achieve the affect you're after, it is not going to behave the exact same as the lock screen. The differences may be fairly slight, and could end up being fine for your purposes but be aware that they are there. Also assuming you go this route it wouldn't work if the user has a "pattern" lock as the KeyguardManager is unable to disable that screen programmatically A: you also need to add <uses-permission android:name="android.permission.WRITE_SETTINGS"/> in androidmanifest.xml A: The voted answer will work only if no one else is using the same to display their message. If two receivers are registered for SCREEN_ON/OFF intent action, the latest receiver's message will be displayed. A: With marc1s' solution there are 2 problems, 1. it doesn't look good & you can't change its look&fill e.g. text font or color etc 2. any other application can replace it So its better if you show a view using window manager from a service. So you can show whatever view you want to show. e.g. my code below in onStartCommand of my Service WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE); View mView = mInflater.inflate(R.layout.score, null); WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0, WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON /* | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON */, PixelFormat.RGBA_8888); mWindowManager.addView(mView, mLayoutParams);
{ "language": "en", "url": "https://stackoverflow.com/questions/7569812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Callstack overflow on JSON .each I have a list of JSON objects that I loop through and then (using the jQuery Gmap plugin found here) create markers for that object and add it to the map. Problem is that in each browser I'm getting callstack overflow messages: Uncaught RangeError: Maximum call stack size exceede in Chrome, and Too much recursion in Firefox. I have NO idea why or how to fix it. This is my code: $('#map_canvas').gmap().bind('init', function (evt, map) { var webMethod = '<%= NavigationHelper.GetFullUrl("Components/Services/storelocatorservice.asmx/GetStoresByAddress") %>'; var webParam = '{ "address": "Vaartkom 31/9 3000 Leuven", "language": "<%= Sitecore.Context.Language.CultureInfo.TwoLetterISOLanguageName %>", "radius": "15" }'; $.ajax({ type: "POST", url: webMethod, data: webParam, contentType: "application/json; charset=utf-8", dataType: "json", success: function (msg) { //$('#map_canvas').gmap('set', 'MarkerClusterer', new MarkerClusterer(map)); addMarkers($.parseJSON(msg.d)); } }); }); function addMarkers(json) { $.each(json, function (i, m) { $('#map_canvas').gmap('addMarker', { 'title': m.Name, 'position': new google.maps.LatLng(m.Lat, m.Long), 'name': m.Name, 'zipcode': m.ZipCode, 'id': m.LocationId, 'bounds': true }).click(function () { $('#map_canvas').gmap('openInfoWindow', { 'content': '<h3>' + m.Name + '</h3><p>' + m.ZipCode + '</p><a onclick="getDirections(\'' + m.Id + '\')">Route</a>' }, this); }); }); } Any help is greatly appreciated! A: I have found a fix, not that it fixes the bug itself it just prevents it from happening: I have to set the bounds: false when adding a marker and then it won't overflow the callstack.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569813", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to symbolicate MonoTouch crash dumps and get line numbers out of them? Is it possible to symbolicate MonoTouch crash dumps and get line numbers out of them? If so, how is it done? I have configured my project in the following way: * *Build in release mode *Checked 'Enable debugging' in Project Options -> Build -> iPhone Build -> General tab *Checked 'Emit debugging information' in Project Options -> Build -> Compiler Now, when I run symbolicatecrash against a dump, I get my method names in the stack trace but with only an offset against them (eg '+ 268') rather than a line number. I am using MonoTouch 4.21. A: Short answer: I think the issue is with the ahead-of-time (AOT) compiler - but you better email such question to the mono-devel mailing-list to get a definitive answer. Long answer: Mono compilers/runtime (and that behavior is inherited by MonoTouch) keeps the debugging information, that includes line numbers, for its assemblies inside mdb files. XCode works with DWARF (DSYM) files. When XCode symbolicate a crash dump it looks (only) in the (AOT-produced) DWARF symbols to get its information - i.e. the mdb files are not looked up. Now the Mono debugger (and runtime) can cope with DWARF too (which should fit the bill). However for MonoTouch I'm not sure the AOT compiler (which calls gcc) is producing the final DWARF symbols containing the C# line numbers - resulting in symbols and offsets (both available to gcc) only being available. A: which version of xcode are you using? There was an problem in earlier versions - check https://github.com/chrispix/symbolicatecrash-fix
{ "language": "en", "url": "https://stackoverflow.com/questions/7569814", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Remove subquery from JOIN? In the following query, I would like the remove the subquery from the JOIN statement (since my two SELECT statements are selecting data from same table). How can I use that alias? Thanks in advance for any help. declare @StartDate datetime= '8/01/2011' declare @EndDate datetime = '9/20/2011' declare @PortfolioId int = 6 SELECT Previous.PreviousNAV, Todays.TodaysNAV, ISNULL((Todays.TodaysNAV-Previous.PreviousNAV),0) NetChange, ISNULL((Todays.TodaysNAV-Previous.PreviousNAV) / Todays.TodaysNAV,0) BAMLIndex FROM ( SELECT PortfolioId,ISNULL(NAV,0) PreviousNAV FROM Fireball..NAV WHERE Date BETWEEN @StartDate AND @EndDate and PortfolioId = @PortfolioId ) Previous JOIN ( SELECT PortfolioId,ISNULL(NAV,0) TodaysNAV FROM Fireball..NAV WHERE Date = @EndDate and PortfolioId = @PortfolioId ) Todays ON Previous.PortfolioId = Todays.PortfolioId A: Just eliminate the subqueries entirely. I don't think they add anything to the query. Try this instead: SELECT Previous.NAV as PreviousNAV, Todays.NAV as TodaysNav, ISNULL((Todays.NAV-Previous.NAV),0) NetChange, ISNULL((Todays.NAV-Previous.NAV) / Todays.NAV,0) BAMLIndex FROM Fireball..NAV as Previous JOIN Fireball..NAV as Todays ON Previous.portfolioID = Todays.PortfolioID WHERE Previous.Date BETWEEN @StartDate AND @EndDate AND Previous.PortfolioId = @PortfolioId AND Todays.Date = @EndDate
{ "language": "en", "url": "https://stackoverflow.com/questions/7569817", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Use ".items" on an ObservableCollection ? (loop through it) I got a "well-constituted" ObservableCollection and I'd like to inspect into it. The definition of it is : private Dictionary<string, ObservableCollection<DependencyObject>> _DataPools = new Dictionary<string, ObservableCollection<DependencyObject>>(); (yep it's an obsCol with an obsCol in it, but it IS ok, the problem's not here) I tried 2 different ways but they both don't work... 1) .Items foreach(ObservableCollection<DependencyObject> obj in _DataPools.Items) { blablaaaa; .... } .Items doesn't work but when I look in the C#doc, Items is a valid field... (just like "Count", and "Count" works...) 2) Count + [x] acces : var nbItems = _DataPools.Count; for (int i = 0; i < nbItems; i++) { Console.WriteLine("Items : " + _DataPools[i].XXX); //XXX = ranom method } _DataPools[i] doesn't work but on the web I found a couple of example where it is used oO I tried a couple of other "exotic" things but I really can't go over it... Any help will be welcomed ! Thx in advance and sry for my langage, im french -_- (sry for my president too !) A: _DataPools is a dictionary, not an ObservableCollection. You need to loop over .Values. A: _DataPool is not an observable collection in an observable collection. It's a dictionary that contains observable collections. To get the collections from the dictionary, use the Values property: foreach (ObservableCollection<DependencyObject> obj in _DataPools.Values) { // some code } A: _DataPools is of type Dictionary. you can access the elements of a dictionary with Values property. foreach(ObservableCollection<DependencyObject> obj in _DataPools.Values) A: You are using a Dictionary, therefore you should use the property Keys to loop on keys and Values to loop on your items. This should work: foreach(ObservableCollection<DependencyObject> obj in _DataPools.Values) { blablaaaa; .... }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Telerik Report omitting data After performing a product evaluation by one of the managers other can change the scoring for certain categories. This changes in scoring are stored in the database for reference. The structure of the evaluation is like this: Evaluatoin - Category - Scoring point an evaluation can have many categories which all can have many scoring points. My problem is the following: If I change a scoring point a few times all is entered in the database but in the reports i am only seeing the first scoring point. The rest of them with the same name are left blank but are using space just as it would if all were visible. The stored procedure that is delivering the data is working fine. It bring all data to the report which then displayes it wrong. =Fields.CategoryName is working fine... every category name is displayed correctly =Fields.ScoringPointName is not working... it displayes only the first and leavese all the rest blank... if for example a scoring point name is Product robustnes it would display only the first change of scoring but wouldnt display the rest Any ideas??? A: Found out what the problem was. Maybe it will be helpful for other people I was showing the data in a group header section with grouping =Fields.DefinitionText. Thus it will only repeat if the Fields.DefinitionText is distinct. About the empty space it's caused by the detail section that repeats for every data record. Thus if I want to display all of the data records I have to move the group header section textboxes to the report's detail section. Here and Here are some usefull things about reporting. Cheers
{ "language": "en", "url": "https://stackoverflow.com/questions/7569822", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Send string in PUT request with libcurl My code looks like this: curl = curl_easy_init(); if (curl) { headers = curl_slist_append(headers, client_id_header); headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, "127.0.0.1/test.php"); curl_easy_setopt(curl, CURLOPT_PUT, 1L); res = curl_easy_perform(curl); res = curl_easy_send(curl, json_struct, strlen(json_struct), &io_len); curl_slist_free_all(headers); curl_easy_cleanup(curl); } Which doesnt work, the program just hangs forever. In test.php these are the request headers I get: array(6) { ["Host"]=> string(9) "127.0.0.1" ["Accept"]=> string(3) "*/*" ["Transfer-Encoding"]=> string(7) "chunked" ["X-ClientId"]=> string(36) "php_..." ["Content-Type"]=> string(16) "application/json" ["Expect"]=> string(12) "100-continue" } But the body is empty, means, no json data is sent with the request. What I want to do with libcurl is actually nothing else then these command line script: curl -X PUT -H "Content-Type: application/json" -d '... some json ...' 127.0.0.1/test.php A: Got it :) Dont use curl_easy_setopt(curl, CURLOPT_PUT, 1L); Make a custom request and send the data as POSTFIELDS: curl = curl_easy_init(); if (curl) { headers = curl_slist_append(headers, client_id_header); headers = curl_slist_append(headers, "Content-Type: application/json"); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_URL, request_url); curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT"); /* !!! */ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_struct); /* data goes here */ res = curl_easy_perform(curl); curl_slist_free_all(headers); curl_easy_cleanup(curl); } A: CURLOPT_PUT is deprecated, and has been for a while. You should use CURLOPT_UPLOAD. For unknown amounts of data with HTTP, you should be using chunked transfer encoding. The CURLOPT_UPLOAD docs say: If you use PUT to a HTTP 1.1 server, you can upload data without knowing the size before starting the transfer if you use chunked encoding. You enable this by adding a header like "Transfer-Encoding: chunked" with CURLOPT_HTTPHEADER. With HTTP 1.0 or without chunked transfer, you must specify the size. A: This one did not work for me. I HAD to use UPLOAD and PUT to perform this correctly. The answer that worked for me is here: How do I send long PUT data in libcurl without using file pointers? You need the callback function for READFILE and then use that to copy your data to the pointer curl offers in that callback. What ultimately worked for me was to make sure I set the FILE size using either CURLOPT_INFILESIZE or CURLOPT_INFILESIZE_LARGE depending on your payload. Otherwise you get the problem posted in the backstory. Backstory: I was expecting a JSON request but using either the PUT CURL option or this custom request approach I get the same result as doing this via console curl -H "Accept:application/json" -H "Authorization:authxxxx" -v -X PUT "http://server.xxxdomain.com/path0/path1/path2/state?data1=1&data2=1421468910543&data3=-3" * Adding handle: conn: 0x7fd752003a00 * Adding handle: send: 0 * Adding handle: recv: 0 * Curl_addHandleToPipeline: length: 1 * - Conn 0 (0x7fd752003a00) send_pipe: 1, recv_pipe: 0 * About to connect() to server.xxxdomain.com port 80 (#0) * Trying ipaddress... * Connected to api-qos.boingodev.com (ipaddress) port 80 (#0) > PUT /path0/path1/path2/done?data1=1&data2=1421468910543&data3=-3 HTTP/1.1 > User-Agent: curl/7.30.0 > Host: server.xxxdomain.com > Accept:application/json > Authorization:authxxxx > < HTTP/1.1 411 Length Required * Server nginx/1.1.19 is not blacklisted < Server: nginx/1.1.19 < Date: Sat, 17 Jan 2015 04:32:18 GMT < Content-Type: text/html < Content-Length: 181 < Connection: close < <html> <head><title>411 Length Required</title></head> <body bgcolor="white"> <center><h1>411 Length Required</h1></center> <hr><center>nginx/1.1.19</center> </body> </html> * Closing connection 0 On the other hand making the same request on the console and adding a data field (PUT -d "" URL)gets me what I want: curl -H "Accept:application/json" -H "authxxxx" -v -X PUT -d "" "http://server.xxxdomain.com/path0/path1/path2/state?data1=1&data2=1421468910543&data3=-3" * Adding handle: conn: 0x7fe8aa803a00 * Adding handle: send: 0 * Adding handle: recv: 0 * Curl_addHandleToPipeline: length: 1 * - Conn 0 (0x7fe8aa803a00) send_pipe: 1, recv_pipe: 0 * About to connect() to server.xxxdomain.com port 80 (#0) * Trying ipaddress... * Connected to server.xxxdomain.com (ipaddress) port 80 (#0) > PUT /path0/path1/path2/state?data1=1&data2=1421468910543&data3=-3" HTTP/1.1 > User-Agent: curl/7.30.0 > Host: server.xxxdomain.com > Accept:application/json > Authorization:authxxxx > Content-Length: 0 > Content-Type: application/x-www-form-urlencoded > < HTTP/1.1 200 OK * Server nginx/1.1.19 is not blacklisted < Server: nginx/1.1.19 < Date: Sat, 17 Jan 2015 17:16:59 GMT < Content-Type: application/json < Content-Length: 32 < Connection: keep-alive < * Connection #0 to host server.xxxdomain.com left intact {"code":"0","message":"Success"} In summary it looks like I need to figure out the CURL options that'll do the equivalent of PUT -d "". Also you can see the difference between both response, in one case the return is HTML and the connection is closed. In the other case the Content is JSON and the connection is kept alive. Based on what I've found on error 411: http://www.checkupdown.com/status/E411.html The problem is that the content length needs to be set regardless of whether you use CURLOPT_UPLOAD with CURLOPT_PUT or the CUSTOM option. So, if you have a stream of data you have it seems you HAVE to use the READDATA and READFUNCTION options to determine the length of your data. Note to admin: Keep in mind rep 50 is REQUIRED to post comments so I HAVE NO CHOICE but to make separate posts in order to communicate. So consider this when you are thinking about deleting these posts as it has been done in the past.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: SQL Server 2005 i want to create the hour a task was started out of an datetime On SQL Server 2005 i want to create a representation of the hour that my task was started. I have a datetime that is '2010-10-01 12:30:00.000' which is the actual start time. What i would like to end up with is '12:00' which is the hour the task was started. Any good ideas on how to loose the '30' minutes? A: If you're just wanting to eliminate minutes/seconds/mills from a datetime value, but keep it as a datetime, use DATEADD/DATEDIFF: select DATEADD(hour,DATEDIFF(hour,0,`2010-10-01T12:30:00`),0) Which will return 2010-10-01T12:00:00. A: This will do what you want: SELECT DATEADD(hh, DATEDIFF(hh, '20000101', [DateField]), '20000101') A: declare @dt datetime set @dt = '2010-10-01 12:30:00.000' select convert(char(5), dateadd(hour, datediff(hour, 0, @dt), 0), 108) Result: 12:00 As a datetime declare @dt datetime set @dt = '2010-10-01 12:30:00.000' select dateadd(hour, datediff(hour, 0, @dt), 0) Result: 2010-10-01 12:00:00.000
{ "language": "en", "url": "https://stackoverflow.com/questions/7569831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to tell if an android device is wifi-only? I am trying to find a reliable way to tell if an Android device is wifi-only. I tried a couple of ways: -- Try to get device ID (IMEI/MEID), if I can not get the IMEI/MEID number, then I can assume the device is wifi-only. This doesn't work as some phones do not return a device ID when they are put in flight mode. -- Try to read TelephonyManager.getPhoneType. This doesn't work either as the wifi-only device I am testing with returns PHONE_TYPE_GSM, while I expect it to return PHONE_TYPE_NONE. I wonder if anyone has successfully distinguish wifi-only devices and the non-wifi-only ones. A: You could query the system features in your app to see if that works. PackageManager pm = getPackageManager(); boolean isAPhone = pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY); If you care about GSM/CDMA use the more specific FEATURE_TELEPHONY_GSM or FEATURE_TELEPHONY_CDMA. If the device is lying there is of course not much you can do afaik. A: Following solution worked for me better: TelephonyManager mgr = (TelephonyManager)ctx.getSystemService( Context.TELEPHONY_SERVICE ); return mgr.getPhoneType() != TelephonyManager.PHONE_TYPE_NONE; And following did NOT work on few devices like Nook Tablet: PackageManager pm = ctx.getPackageManager(); return pm.hasSystemFeature( PackageManager.FEATURE_TELEPHONY ); A: I have a similar problem to yours and I checked out several solutions. Only one of them works reliably thus far if (mContext.getSystemService(Context.TELEPHONY_SERVICE) == null) { // wifi-only device } This assumption is wrong. My wifi-only Nexus 7 returns a Telephony Manager object. mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TELEPHONY) This returns false on both my Nexus 7. One of them supports data connections and the other one is wifi-only TelephonyManager telMgr = mContext.getSystemService(Context.TELEPHONY_SERVICE) telMgr.getPhoneType() I expect PHONE_TYPE_NONE for the nexus 7 that is wifi-only and PHONE_TYPE_GSM for the other Nexus 7. I get PHONE_TYPE_NONE for both Nexus 7 if(telMgr.getSimState() == TelephonyManager.SIM_STATE_UNKNOWN) { // Wifi-only device } else if (telMgr.getSimState() == TelephonyManager.SIM_STATE_ABSENT) { // Device that supports data connection, but no SIM card present } This solution worries me. SIM_STATE_UNKNOWN is also used during state transitions. Also, some devices support data connections but don't have a SIM card. My favourite solution is the following ConnectivityManager mConMgr = mContext.getSystemService(Context.CONNECTIVITY_SERVICE) if (mConMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) == null) { //wifi-only device } The only thing that worries me is if there are devices which support TYPE_MOBILE_HIPRI or TYPE_MOBILE_MMS but not TYPE_MOBILE I suspect this is not the case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Java Play Framework Hidden Url Routes Is it possible to hide/mask the urls in the java play framework. The problem I have come across is I want a user to be able to log in and view messages belonging to them but I do not want any old user to find theses messages by simply hacking the url. What I have got is a Notifications controller which has a method called show(long id). my route for this method is: GET /Message/Show Notifications.show i call the function using @Notifications.show(':id') the url for this function is: http://localhost:9000/Message/Show?id=8 Is it possible to remove the parameter off the end of the url so people can not hack into certain urls by guessing parameters. A: This is something that can be achieved with Interceptions. http://www.playframework.org/documentation/1.2.3/controllers#interceptions Inside these classes you can check if the current user is logged in (store in session) A: If I got this right, you want to hide URLs so users don't know them and do not enter them. If they do, they would see content they shouldn't see. This is bad and should not be done this way, take a look at Security through obscurity (Wikipedia), use readable/bookmarkable URLs and build proper login and security mechanisms like leifg suggested. A: This is the approach I used, I do not know if this is the best way around this but it does work how I want it to. Thanks for all the help and ideas. public static void show(long id) { Notification notification = Notification.findById(id); User connectedUser = User.find("byEmail", Security.connected()).first(); if(notification.recipient.equals(connectedUser)) { render(notification); } else { forbidden("This isnt your message stop hacking the urls!"); } } A: Or you could log in the user and fetch only the users message. Why search a complicate solution such as obfuscation/interceptions and whatever when a very simple solution exists. Use the session of the connected user, fetch only his messages and done.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Should I use OVal (Object Validation Framework) even if it requires AspectJ or not? I have a Java Maven project which is developed by multiple people. As I really like doing JUnit Tests and the like, the concept of OVal intrigues me because I can write code like: @NotNull @NotEmpty @Length(max=32) private String name However the disadvantage is that: * *everyone now has to install the AspectJ plugin to his Eclipse *at least for me that gives me an error at each startup (which I can click away but it is still annoying) *I guess AspectJ slows everything down So is it worth it and is there an alternative where I don't need AspectJ? P.S.: This is the error I get in Eclipse: screenshot http://img651.imageshack.us/img651/1089/aspectjerror.png And this is the head of the method getCommonProperties() that it seems to have problems with: public static LinkedHashMap<String,Integer> getCommonProperties ( @NotEmpty @NotNull String endpoint, @NotEmpty @NotNull String where, @Range(min=0, max=1) Double threshold, @Min(1) Integer maxResultSize, @Min(1) Integer sampleSize ) A: OVal does not require the usage of AspectJ per se. Only if you want to use it for programming-by-contract, e.g. automatic method parameter validation. If you do not want to use AspectJ you can use Spring AOP as an alternative to enable method parameter validation of Spring managed services, see http://oval.sourceforge.net/userguide.html#spring-aop A: I do not know the OVal framework, but I do know that AspectJ and the Eclipse tooling is mature. Compile time would be slightly longer due to the weaving process, but probably not significantly longer. My suggestion is that if you find that the framework helps you, then it is worth using. If you can tell me what the error on startup is, then perhaps we can figure out a way so that you don't get it any more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jquery .live problem with IE I have the following code which on focus hides a "dummy" password field (containing the word 'password') and shows a real password input field. It works fine in all browsers expect IE. In IE, it works if I tab to the password field, but if I click on the password field it focuses correctly but I can't type into it. $("#passDummy").live('focus',function () { $(this).hide(); $("#pass").show().focus(); }); Here's a jsfiddle to show it in practice... If I use .focus and .blur rather than .live it also works, but I need to use .live in this case. EDIT: I'm using jquery 1.5.1 (minified version) though it seem to be the case on all subsequent versions too. A: Probably not the answer you want but here it is anyway; Upgrade to the latest jQuery. I tested this with your Jsfiddle and IE8. Using jQuery 1.5.2 I reproduced your problem. Using jQuery 1.6.3 it works as expected. Horrible workaround, but appears to work: $("#pass").show(); setTimeout(function(){$('#pass').focus()},10); Live example: http://jsfiddle.net/etmrR/ I assume this has something to do with the textfield not being shown quick enough to be given the focus in IE.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: return functions for arrays Need a bit of help completing a Javascript program which uses succesive functions. I cant find a way of replacing the return statement with variable so I can use the varable in the second function. The program uses the statement findArrayparts(myArray1, myArray2) to get the function findArrayparts(myArray1, myArray2) to generate a random integer one less then the array length of one of the arrays ( equal lengths). This random integer is then used in the function findArrayparts(myArray1, myArray2) to work out the corresponding array elements and put them into an array which is then displayed in an alert box. <SCRIPT SRC = glossary.js></SCRIPT> <SCRIPT language = "JavaScript"> var myVar1; var myVar2; var myVar3; var myArray1 = ['red', 'orange', 'green', 'blue', 'yellow']; var myArray2 = ['tomatoe', 'orange', 'apples', 'blueberry', 'banana']; // generates random integer and assigns result to myVar1 function getNumberRand(aNum) { //return Math.floor(Math.random() * aNum); myVar1 = Math.floor(Math.random() * aNum); } function findArrayparts(myArray1, myArray2) { // calls getNumberRand function getNumberRand(myArray1.length); // works out characters at same index in both arrays myVar2 = (myArray1(myVar1)); myVar3 = (myArray2(myVar1)); // new array to hold output outputArray = new Array(myVar2, myVar3); // display output outputArray.join(); alert(outputArray); } // Calls findArrayparts function findArrayparts(myArray1, myArray2); </SCRIPT> </HEAD> <BODY> </BODY> </HTML> A: DEMO: http://jsfiddle.net/PjtxY/ var myArray1 = ['red', 'orange', 'green', 'blue', 'yellow']; var myArray2 = ['tomatoe', 'orange', 'apples', 'blueberry', 'banana']; function getNumberRand(aNum) { return Math.floor(Math.random() * aNum); } function findArrayparts(myArray1, myArray2) { // Store return value in local variable var random_num = getNumberRand(myArray1.length); // Use [] square brackets to get array member var myVar2 = myArray1[ random_num ]; var myVar3 = myArray2[ random_num ]; // Store new Array in local variable. var outputArray = new Array(myVar2, myVar3); // Store joined result in a variable var result = outputArray.join(); // Alert the result alert( result ); } findArrayparts(myArray1, myArray2); A: You had it in the commented out line. Just return the value: function getNumberRand(aNum) { return Math.floor(Math.random() * aNum); } A: You had getNumberRand right before you commented it out. You want to return the random number: function getNumberRand(aNum) { return Math.floor(Math.random() * aNum); } Then when you come to want to use the return from that function later on you just assign the result to a variable: function findArrayparts(myArray1, myArray2) { // calls getNumberRand function var myVar1 = getNumberRand(myArray1.length); // works out characters at same index in both arrays myVar2 = (myArray1(myVar1)); myVar3 = (myArray2(myVar1)); ... } A: Why are you using the global variables myVar1, myVar2, myVar3? Use return to get values out of a function. Is this what you're trying to achieve: <script type="text/javascript"> var myArray1 = ['red', 'orange', 'green', 'blue', 'yellow']; var myArray2 = ['tomato', 'orange', 'apples', 'blueberry', 'banana']; function getNumberRand(aNum) { return Math.floor(Math.random() * aNum); } function findArrayparts(myArray1, myArray2) { var index = getNumberRand(myArray1.length); alert(outputArraymyArray1[index] + ', ' + myArray2[index]); } findArrayparts(myArray1, myArray2); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/7569842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: tab based problems in android i am iPhone programmer and new in android development , I developed a tab host based application. Can I switch between activites as I was doing in iphone [self.navigationController pushViewController: and [self.navigationController popViewControllerAnimated: is there any way of doing this like of thing in android? Please help A: Create two xml layouts and write ur necessary codings there.Now create a new activity and for tabhost and add the tabs u need and u need to include the two xml layouts in tab host public class UserCreation extends TabActivity { protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_creation); Resources ressources = getResources(); TabHost tabhost=getTabHost(); Intent createUserIntent=new Intent().setClass(this, UserCreationFragment.class); TabSpec tabspecUserCreation= tabhost.newTabSpec("Create user") .setIndicator("", ressources.getDrawable(R.drawable.insert_user)).setContent(createUserIntent); Intent deleteUserIntent=new Intent().setClass(this, Deleteuser.class); TabSpec tabspecuserDeletion=tabhost.newTabSpec("Delete user").setIndicator("", ressources.getDrawable(R.drawable.del_user)) .setContent(deleteUserIntent); tabhost.addTab(tabspecUserCreation); tabhost.addTab(tabspecuserDeletion); } } refer the following example for better reference Android Tabhost
{ "language": "en", "url": "https://stackoverflow.com/questions/7569843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: selecting Row count between a range of dates based on current Date i am doing a project on hotel reservation.in that i have to show room vacancy of selected week in the page.i am taking the booked room count from hotel Booking table.below is few feilds in booking table. my problem is i have to get sum of HB_Noofrooms between hb_chkDt and hb_chkoDt of each date in selected week. ex. suppose if i take current date and check it,then i have to get 2 as sum. please help me to solve this. A: If you will pass date as parameter for which you need to get vacancy then it's simple query : SELECT SUM(HB_NoOfRooms) FROM Booking WHERE HB_ChkDt <= @PassedDt AND HB_ChkODt >= @PassedDt But if you pass range of dates and want to get date wise vacancy for all in between dates then need to make some complex query. UPDATE : Code to get vacancy for multiple date ranges : DECLARE @strSQL NVARCHAR(MAX) DECLARE @StartDt DATETIME DECLARE @EndDt DATETIME CREATE TABLE #Booking (HB_Id INT, HB_ChkDt DATETIME, HB_ChkODt DATETIME, HB_NoOfRooms INT) INSERT INTO #Booking VALUES (61, '2011-09-07 13:00:00','2011-09-08 13:00:00',1) INSERT INTO #Booking VALUES (67, '2011-09-27 13:00:00','2011-09-28 2:00:00',1) INSERT INTO #Booking VALUES (68, '2011-09-27 13:00:00','2011-09-28 2:00:00',1) INSERT INTO #Booking VALUES (69, '2011-09-28 13:00:00','2011-09-29 2:00:00',1) SET @StartDt = '2011-09-27' SET @EndDt = '2011-09-29' WHILE @StartDt <= @EndDt BEGIN IF @strSQL IS NULL OR @strSQL = '' SET @strSQL = 'SELECT ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + ''' AS Dt, ISNULL(SUM(HB_NoOfRooms),0) AS Vacancy FROM #Booking WHERE CONVERT(VARCHAR(10),HB_ChkDt,102) <= ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + ''' AND CONVERT(VARCHAR(10),HB_ChkODt,102) >= ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + '''' ELSE SET @strSQL = @strSQL + ' UNION ALL SELECT ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + ''' AS Dt, ISNULL(SUM(HB_NoOfRooms),0) AS Vacancy FROM #Booking WHERE CONVERT(VARCHAR(10),HB_ChkDt,102) <= ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + ''' AND CONVERT(VARCHAR(10),HB_ChkODt,102) >= ''' + CAST(CONVERT(VARCHAR(10),@StartDt,102) AS VARCHAR(10)) + '''' SET @StartDt = DATEADD(D,1,@StartDt) END EXEC (@strSQL) DROP TABLE #Booking A: DECLARE @BeginDate date='2010-01-01' DECLARE @EndDate date='2011-01-01' ; With Dates([Date]) as ( SELECT @BeginDate UNION ALL SELECT DATEADD(Day,1,Date) FROm Dates WHERE Dates.date<@EndDate ) SELECT Dates.Date,(SELECT COUNT(HB_No_Of_Rooms) FROM @MyTable WHERE HB_CkdDT>=Dates.date AND HB_ChkODt<=Dates.Date GROUP By HB_No_Of_Rooms ) FROM Dates OPTION(MAXRECURSION 0) A: If you want to retrive the total number of rooms occupied in a week: select sum(HB_NoOfRooms) from Booking where (hb_chkDt >= CONVERT(DATETIME, '2011-09-25 00:00:00') and hb_chkDt < CONVERT(DATETIME, '2011-10-01 00:00:00')) or (HB_ChkODt >= CONVERT(DATETIME, '2011-09-25 00:00:00') and HB_ChkODt < CONVERT(DATETIME, '2011-10-01 00:00:00')) If you want to check the total number of room occupied today: select sum(HB_NoOfRooms) FROM Booking where HB_ChkDt <=SYSDATETIME() AND HB_ChkODt >SYSDATETIME()
{ "language": "en", "url": "https://stackoverflow.com/questions/7569849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why isn't my C++ assembly signed? I have a C++ project, set to /clr, which is referenced by C# projects in the same solution. Unfortunately, it seems the C++ doesn't get properly signed, leading to the error message "assembly doesn't have a strong name." (sn.exe agrees with that error.) However, there is an snk file in the project settings (Linker/Advanced), so it should be signed. Further, all project settings seem to be the same as in another C++ project in the same solution - where everything works. The one thing I have found after tearing my hair over this for hours: When eliminating the /NOLOGO switch for the linker, it becomes apparent that the linker is called twice. I don't have the slightest idea why that might be. Now, in the project that works the linker gets passed the snk file in the command line (/KEYFILE:) for both invocations, in the one that does not work, the second invocation does not get the snk file passed. Why would the linker be invoked twice? What determines that it doesn't get the snk file passed in the second invocation? A: Ok, I found the solution: Apparently, MS blew the SP1 release for VS2010 and you have to go and mess around in the MSBUild installation folder. Here is an article giving the dirty details. (And why this would work in one project, but not in the other I have no idea. And, frankly, I've lost enough hours banging my head against this wall already, and will not investigate any further.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7569851", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Verify CSS is valid syntax What are some guidelines that could be used on CSS to ensure that it is valid at least in syntax only. The four checks that I came up with were ensuring that at least one "{", "}", ";" and ":" exist and if they do exist that the number of "{" and "}" matches and the number of ":" and ";" match. I also check to make sure it starts with a "." and ends with ";}" with all possible combinations of whitespace. Are there any other checks I could run on it just to make sure it is valid syntax? Or better yet does anyone have a regex available that could verify this? I'm extremely new to regex but it seems like it would be able to handle all the checks I've mentioned. A: The simplest suitable regex that I can think of is: (([.#]?[a-zA-Z_-0-9]+\ *)+\{([a-zA-Z-])+\ *\:[^;]+;\})+ It doesn't consider @charset ...; directives and comments (\* ... *\), also it doesn't check for braces in url(...) and "..." pairs in content: "...", but you can try adding this by yourself if you need. A: You can run it through the w3 css validator: http://jigsaw.w3.org/css-validator/
{ "language": "en", "url": "https://stackoverflow.com/questions/7569853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Passing Values to DB and Viewing it w/ 100% JavaScript? How do JavaScript-heavy web applications route freshly-entered data to a database, and then display it to the client, only using JavaScript/HTML? Say Acme Social Network user types profile information into a HTML form and clicks 'submit': * *How would you save that user's profile data to a database? *How would you then display that user's profile data on the profile page? Can it all be done with JS/HTML? A: Well, you could use CouchDB as the backend, or use Node.js with a more traditional DB (or CouchDB), but most people still use a LAMP stack for the backend (often with a framework such as Dancer, Catalyst or Django). A: There's always a server-side programming language that interacts directly with the database and generates pages with that data. On a javascript heavy page, there might be an AJAX call that sends the data to a server-side script to store in the database. Information can be pulled from the server with AJAX requests as well. But there's always server-side code that the front end is interacting with.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What kind of type is this statement? In javascript : is it legal ? var obj = [ id: '1', name: '' ]; type typeof(obj) return n/a A: I guess you want an object (looking at your variable name). In that case it would be: var obj = { id: '1', name: '' }; The [ and ] tokens are used to define an array and must look like: var arr = ['a', 'b', 'c']; If you would like to know more about this in context to JSON, look at JSON A: That is a syntax error in JavaScript. Probably it should be: var obj = { id: '1', name: '' }; That's an object literal. An array literal looks like this: var arr = [ 1, 2, 3 ]; You can put objects inside of arrays too: var objarr = [ { id: '1', name: '' }, { id: '2', name: 'example' } ]; An empty object looks like: var emptyObj = {}; An empty array looks like: var emptyArr = []; A: Square brackets denotes an array, curly ones an object: var obj = []; // short form to declare an array var onj = {}; // short form to declare an object
{ "language": "en", "url": "https://stackoverflow.com/questions/7569859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to do http post using apache httpclient with web authentication? I have searched a LOT for this and could not find a decent solution. The one using credentials provider is bad as it make double the amount of calls opposed to what is required i.e. it fires the request , gets a 401 and only then fires the request with the web auth credentials. Anyone who has used android's httpclient library to do http post requests to a URL behind web auth successfully?? A: For HttpClient 4.0.x you use a HttpRequestInterceptor to enable preemptive authentication - since the AndroidHttpClient class doesn't expose the addRequestInterceptor(..) method you're probably going to have to use the DefaultHttpClient class. This example will spam user1/user1 to any server interested. Adjust the AuthScope if you care even one bit about security. DefaultHttpClient client = new DefaultHttpClient(); client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user1", "user1")); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState state = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (state.getAuthScheme() == null) { BasicScheme scheme = new BasicScheme(); CredentialsProvider credentialsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); Credentials credentials = credentialsProvider.getCredentials(AuthScope.ANY); if (credentials == null) { throw new HttpException(); } state.setAuthScope(AuthScope.ANY); state.setAuthScheme(scheme); state.setCredentials(credentials); } } }, 0); // 0 = first, and you really want to be first.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Case Statement with Dictionary Hi all i wrote the following code, what i am doing is i would like to use Switch case for my dictionary that exists but i am getting an error as Can not implicitly convert string to bool My code is as follows List<string> lst = new List<string>(); lst.Add("Delete"); lst.Add("Reports"); lst.Add("Customer"); Dictionary<int, string> d = new Dictionary<int, string>(); d.Add(1, "Delete"); d.Add(2, "Reports"); foreach (string i in lst) { if (d.ContainsValue(i)) { switch (d.ContainsValue(i)) { case "Delete": // Here i would like to compare my value from dictionary //link1.NavigateUrl = "Reports.aspx"; HyperLink1.NavigateUrl = "Delete.aspx"; break; } } else { HyperLink2.Attributes["OnClick"] = "alert('Not a Valid User to Perform this operation'); return false"; } } A: d.ContainsValue(i) returns boolean. When you do this: case "Delete" You try to compare the bool with a string, so it fails. You need to do this: if (d.ContainsValue(i)) { switch (i) { case "Delete": // Here i would like to compare my value from dictionary //link1.NavigateUrl = "Reports.aspx"; HyperLink1.NavigateUrl = "Delete.aspx"; break; } } A: Try the following: switch (d[i]) It would probably be more efficient to use TryGetValue A: the if inside the switch return a boolean value while the case says it must be a string switch (d.ContainsValue(i)) { case "Delete": // Here i would like to compare my value from dictionary //link1.NavigateUrl = "Reports.aspx"; HyperLink1.NavigateUrl = "Delete.aspx"; break; } try this switch (d[i]) { case "Delete": // Here i would like to compare my value from dictionary //link1.NavigateUrl = "Reports.aspx"; HyperLink1.NavigateUrl = "Delete.aspx"; break; } A: You can do something like this and avoid the switch all together: var lst = new List<string>(); lst.Add("Delete"); lst.Add("Reports"); lst.Add("Customer"); Dictionary<int, string> d = new Dictionary<int, string>(); d.Add(1, "Delete"); d.Add(2, "Reports"); var hyperlinkMap = new Dictionary<string, string>() { { "Delete", "Delete.aspx"}, { "Reports", "Reports.aspx"} }; foreach (var i in lst) { if(d.ContainsValue(i)) { HyperLink1.NavigateUrl = hyperlinkMap[i]; } else { HyperLink2.Attributes["OnClick"] = "alert('Not a Valid User to Perform this operation'); return false"; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7569869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to set the current shell settings to every shell i a bash? I have done some 'source file' at the current bash shell and want that file to be sourced to every shell that is created. How can this be done? A: Add an entry in your .bashrc file. If one doesn't exist, go to your home directory and create one with your favorite text editor. For more info on the .bashrc file and what it can do, check out this site. Also, read the man bash page for an exhaustive amount of detail.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Nullpointer @ managedQuery When I run my code, I get an exception @ managedQuery. Whats wrong? I don't see it. import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.provider.MediaStore; public class FileManager extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } public List<String> getAudioFiles() { List<String> songs = new ArrayList<String>(); //Some audio may be explicitly marked as not being music String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"; String[] projection = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DURATION }; Cursor cursor = managedQuery( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, null, null, MediaStore.Audio.Media._ID); while(cursor.moveToNext()){ songs.add(cursor.getString(0) + "||" + cursor.getString(1) + "||" + cursor.getString(2) + "||" + cursor.getString(3) + "||" + cursor.getString(4) + "||" + cursor.getString(5)); } return songs; } } This is the exception 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): FATAL EXCEPTION: main 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test/com.test.testActivity}: java.lang.NullPointerException 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.os.Handler.dispatchMessage(Handler.java:99) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.os.Looper.loop(Looper.java:130) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.app.ActivityThread.main(ActivityThread.java:3691) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at java.lang.reflect.Method.invokeNative(Native Method) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at java.lang.reflect.Method.invoke(Method.java:507) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at dalvik.system.NativeStart.main(Native Method) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): Caused by: java.lang.NullPointerException 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:90) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.app.Activity.managedQuery(Activity.java:1556) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at com.test.FileManager.getAudioFiles(FileManager.java:35) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at com.test.testActivity.onCreate(testActivity.java:21) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615) 09-27 17:04:20.130: ERROR/AndroidRuntime(4079): ... 11 more A: This may not be helpful but I note that your projection is an array with a length of five and your string building method expects a sixth column (cursor.getString(5)). Of course, that wouldn't cause a NullPointerException at managedQuery, are you sure that's where the exception is occuring? Because that bit looks okay from here (apart from the fact that you define selection criteria but don't use it).
{ "language": "en", "url": "https://stackoverflow.com/questions/7569874", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems accessing elements with namespaces in PHP using DOMDocument Here is my XML fragment: <?xml version="1.0" encoding="UTF-8"?> <ns:searchResult xmlns:ns="http://outerx.org/daisy/1.0"> ... <ns:rows> <ns:row documentId="1440-DFO_MPO" branchId="1" languageId="2" access="read,fullRead,write,publish"> <ns:value>1440-DFO_MPO</ns:value> <ns:value>Navigation for Multimedia</ns:value> </ns:row> </ns:rows> ... Here is my current PHP Code: $dom = new DOMDocument(); $dom->load($xml); $docs = $dom->getElementsByTagNameNS('http://outerx.org/daisy/1.0','row'); print "<ul>"; $c = 0; foreach ($docs as $elem) { print "<li>".$c."</li>"; $c = $c + 1; } print "</ul>"; AFAIK, this snippet should output a list of one item based on the XML fragment. However, it doesn't. I've also tried (without success): $docs = $dom->getElementsByTagName('row'); Edit #1 - Solution Changed $dom->load($xml) to $dom->loadXML($xml); A: Your code works for me. I assume you are passing the XML content in $xml when load() expects it to be a filename or URI. To load XML content directly you have to use * *DOMDocument::loadXML — Load XML from a string See http://codepad.org/oy3U1fmE
{ "language": "en", "url": "https://stackoverflow.com/questions/7569882", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Overlay image with text and convert to image I want to add text to a jpg creating a new image. There will be image_1.jpg already on the server and I want to take the user submitted copy and put it on top of image_1.jpg creating a new image that combines the copy and the original image into a new rasterized jpg I know you can use GD Libraries in php to rasterize copy but can you layer it? My site is written in PHP but I am open to using 3rd party plug-ins. ANSWER:(OLD POST) but what I need http://blog.rafaeldohms.com.br/2008/02/12/adding-text-to-images-in-real-time-with-php/ A: Using GD and Freetype2, if both installed, then you can add text to a JPEG using the following steps. * *create an image resource from the file using imagecreatefromjpeg() *add text to that image using the Freetype2 library, via the function imagefttext() (note you can also use the function imagettftext() if you only have Freetype installed and not Freetype2). *save the modified image using imagejpeg() Example: [I've literally just typed this in to the browser, never run it - so if it needs amendment, apologies.] /** * Annotate an image with text using the GD2 and Freetype2 libraries * * @author Orbling@StackOverflow * * @param string $sourceFileName Source image path * @param string $destinationFileName Destination image path * @param string $text Text to use for annotation * @param string $font Font definition file path * @param float $fontSize Point size of text * @param array $fontColour Font colour definition, expects array('r' => #, 'g' => #, 'b' => #), defaults to black * @param int $x x-coordinate of text annotation * @param int $y y-coordinate of text annotation * @param float $rotation Angle of rotation for text annotation, in degrees, anticlockwise from left-to-right * @param int $outputQuality JPEG quality for output image * * @return bool Success status */ function imageannotate($sourceFileName, $destinationFileName, $text, $font, $fontSize, array $fontColour = NULL, $x, $y, $rotation = 0, $outputQuality = 90) { $image = @imagecreatefromjpeg($sourceFileName); if ($image === false) { return false; } if (is_array($fontColour) && array_key_exists('r', $fontColour) && array_key_exists('g', $fontColour) && array_key_exists('b', $fontColour)) { $colour = imagecolorallocate($image, $fontColour['r'], $fontColour['g'], $fontColour['b']); if ($colour === false) { return false; } } else { $colour = @imagecolorallocate($image, 0, 0, 0); } if (@imagefttext($image, $fontSize, $rotation, $x, $y, $colour, $font, $text) === false) { return false; } return @imagejpeg($image, $destinationFileName, $outputQuality); } NB. For debugging, I would remove the @ symbols.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Open part of html page I want to open part of html page in UIWebView. I found good code, but I can't find tags, which I need. I want to open only text (not title) and comments in different UIWebViews from URL (iOS version): http://smartfiction.ru/random?random What tags I need to use? Thank you very much. A: so, texts starts with these tags : h3 1 h3 p А на самом деле... Thy to use them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SVN: Partial reintegration of a branch? I'm using SVN for version control (with Eclipse / Subversive). We have a branch and a trunk. The branch is for a specialized version of our project. Often, we experiment some changes in the branch, and then decide that those changes are useful in the main-project (trunk) too. But not ALL changes of the branch are needed in the trunk. Some really need to stay only in the branch, since they're only suited for the special functions of that branch. I would like to be able to choose the files that are reintegrated. Ideally I'd like a Synchronize-view from the branch to the trunk BEFORE doing the merge/reintegration, but this isn't possible. How would you deal with this situation? A: I can describe how you do this from Subclipse, and also how you would do it using the command line. First off, you would not use merge --reintegrate. Ideally, the changes you want to merge were all committed in one or more specific revisions on the branch. You would then simply merge those revisions from the branch back to trunk. Subclipse provides a simple UI for selecting the revisions you want to merge from the branch back to trunk it is the "Merge range of revisions" option on the merge wizard. If the revisions contained some other changes you do not want you would have to revert those before committing the merge to trunk. You can do this easily from the Merge Results view. Let's pretend that when you committed the merge to trunk it created r100 You now want to update your branch so that r100 is not merged back to it the next time you synch it with trunk. So to do this you use merge -c 100 --record-only on your branch. In Subclipse UI, this is the "Block revisions" option on the merge wizard. This updates the mergeinfo on the branch and you just need to commit it to the branch. Once you have done this, future synch up merges with trunk will not try to merge that revision back to the branch. Once the branch is done, a normal merge --reintegrate should still work fine and you will not have any problems due to the changes you have already merged from the branch. A: I would advise against trying to manage two independent dimensions of variance (release and feature) with a single version control system mechanism. That is just going to give you an initially small, but endlessly growing, headache. The branches will diverge over time, and you will be stuck doing selective merging forever. http://martinfowler.com/bliki/FeatureBranch.html Feature Branching is a poor man's modular architecture, instead of building systems with the ability to easy swap in and out features at runtime/deploytime they couple themselves to the source control providing this mechanism through manual merging. Best bet is to bite the bullet and restructure the code so that unique code for different variants mostly go in different files. Then just have a few files that use a dependency injection mechanism, or just #if, that mention both variants and set up configuration of the right set of Strategies and Factories and so on. Alternatively, have two teams. When changes are needed to be made to both variants, do them twice. That's at least scalable and predictable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I stream binary data to disk in asp.net with c# How do I stream binary data to disk, where the user first choose the location path? What I have so far: User click in my RadGrid, and I fetch Binary (or byte[] with .ToArrar()). I would like something, where user was ask to browse he's computer for at location and hitting accept/cancel. And accepting would start the stream to write the file. A: Basically you set the response object to oclet type, push in the data and send it off. The client browser determines how it will display any needed dialogs to the user. This is from a download utility page on an internal web app. The full code includes protection against the user trying to read files outside of its path sandbox that I ommited for this example. string document = "... some server document file name ..."; string fullpath = Server.MapPath("your path"+document); Response.ContentType = ExtentionToContentType(document); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", document)); byte[] data = System.IO.File.ReadAllBytes(fullpath); Response.AppendHeader("Content-Length", data.Length.ToString()); Response.BinaryWrite(data); Response.End(); public string ExtentionToContentType(string file) { switch (System.IO.Path.GetExtension(file).ToLower()) { case ".xls": return "application/vnd.ms-excel"; case ".doc": case ".docx": return "application/msword"; case ".ppt": return "application/vnd.ms-powerpoint"; case ".mdb": return "application/x-msaccess"; case ".zip": return "application/zip"; case ".jpg": case ".jpeg": case ".jpe": return "image/jpeg"; case ".tiff": return "image/tiff"; case ".bmp": return "image/bmp"; case ".png": return "image/png"; case ".gif": return "image/gif"; case ".avi": return "video/x-msvideo"; case ".mpeg": return "video/mpeg"; case ".rtf": case ".rtx": return "text/richtext"; case ".txt": return "text/plain"; case ".pdf": return "application/pdf"; default: return "application/x-binary"; } } A: You don't (can't) stream data directly to the user's disk or interact outside of the user's browser. In a web application all you need to do is deliver the content to the user as a standard HTTP response. The user's browser will take care of the rest. There's a really good question/answer about this here. Understand that the HTTP protocol doesn't deal in "files." It deals in requests and responses, each of which consists of headers and a body. So what your web application would do is craft a response which the user's browser might interpret as something that it should save as a file. The headers would provide the browser with what it needs to make this interpretation, and the body would provide the browser with the data. Generally it involves these steps: * *Remove any existing output (don't send page markup or anything like that). *Set your headers accordingly. In this case you'll want to set things like content-length, content-type, and probably content-disposition as a way of suggesting to the browser that it save the response as a file. *Write the bytes of the file to the response stream. *End the response stream.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Ignore mouse focus on tool-tip? I've created something that works like a ToolTip in my Flex application. When I roll over a certain item renderer, I pop up a new control, position it, and remove it on roll out. The order of operations is like this: * *Roll over event handler triggered. *Add the tooltip to this.systemManager.topLevelSystemManager.toolTipChildren. *On creation complete of my tooltip, set x, set y coordinates of the tooltip (on creation complete so the width and height are calculated since they are dynamic). *Roll out event handler triggered. *Remove tooltip. This worked fine when I set the x and y coordinates to be x+10, y+10 from the current mouse position. I wanted to add something that re-positioned the tool-tip if it was going to be drawn partially off screen. I added a step that would calculate if it would be drawn off screen, and re-position the tooltip if it was going to be cut off. The problem with my solution seems to be that it now runs in an infinite loop of redraws, since adding the tool-tip to the screen underneath the mouse triggers the "rollOut" on the item renderer. This triggers the removal of the tooltip, and starts the process over again from 1. So I guess my question is: is there any way to ignore tooltip so it doesn't take the mouse focus away from the item renderer that is now under it? Or are there any other good solutions? Thanks in advance. A: One way is to ensure that the drawn tool-tip also does not come under the mouse. Or you can add a short delay before the tool-tip actually fades after the rollOut. Then you can disable fading if the mouse_over of the new tool-tip is fired. This way the tool-tip will only fade if the mouse leaves BOTH the DisplayObject that triggers the tool-tip AND the tool-tip. A: Probably should have searched a bit more before posting this question. For anyone else looking, I just needed to set mouseEnabled=false and mouseChildren=false options on my tooltip. A: I'd check the currentTarget and target properties of your events, to know who dispatched it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Easiest way to read from and write to files There are a lot of different ways to read and write files (text files, not binary) in C#. I just need something that is easy and uses the least amount of code, because I am going to be working with files a lot in my project. I only need something for string since all I need is to read and write strings. A: These are the best and most commonly used methods for writing to and reading from files: using System.IO; File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it. File.ReadAllText(sFilePathAndName); The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in "File." in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App. Append text to an existing file: private void AppendTextToExistingFile_Click(object sender, EventArgs e) { string sTextToAppend = txtMainUserInput.Text; //first, check to make sure that the user entered something in the text box. if (sTextToAppend == "" || sTextToAppend == null) {MessageBox.Show("You did not enter any text. Please try again");} else { string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a path\filename.txt as string. if (sFilePathAndName == "" || sFilePathAndName == null) { //MessageBox.Show("You cancalled"); //DO NOTHING } else { sTextToAppend = ("\r\n" + sTextToAppend);//create a new line for the new text File.AppendAllText(sFilePathAndName, sTextToAppend); string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\\') + 1); MessageBox.Show("Your new text has been appended to " + sFileNameOnly); }//end nested if/else }//end if/else }//end method AppendTextToExistingFile_Click Get file name from the user via file explorer/open file dialog (you will need this to select existing files). private string getFileNameFromUser()//returns file path\name { string sFileNameAndPath = ""; OpenFileDialog fd = new OpenFileDialog(); fd.Title = "Select file"; fd.Filter = "TXT files|*.txt"; fd.InitialDirectory = Environment.CurrentDirectory; if (fd.ShowDialog() == DialogResult.OK) { sFileNameAndPath = (fd.FileName.ToString()); } return sFileNameAndPath; }//end method getFileNameFromUser Get text from an existing file: private void btnGetTextFromExistingFile_Click(object sender, EventArgs e) { string sFileNameAndPath = getFileNameFromUser(); txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text } A: Use File.ReadAllText and File.WriteAllText. MSDN example excerpt: // Create a file to write to. string createText = "Hello and Welcome" + Environment.NewLine; File.WriteAllText(path, createText); ... // Open the file to read from. string readText = File.ReadAllText(path); A: It's good when reading to use the OpenFileDialog control to browse to any file you want to read. Find the code below: Don't forget to add the following using statement to read files: using System.IO; private void button1_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { textBox1.Text = File.ReadAllText(openFileDialog1.FileName); } } To write files you can use the method File.WriteAllText. A: Or, if you are really about lines: System.IO.File also contains a static method WriteAllLines, so you could do: IList<string> myLines = new List<string>() { "line1", "line2", "line3", }; File.WriteAllLines("./foo", myLines); A: FileStream fs = new FileStream(txtSourcePath.Text,FileMode.Open, FileAccess.Read); using(StreamReader sr = new StreamReader(fs)) { using (StreamWriter sw = new StreamWriter(Destination)) { sw.Writeline("Your text"); } } A: class Program { public static void Main() { //To write in a txt file File.WriteAllText("C:\\Users\\HP\\Desktop\\c#file.txt", "Hello and Welcome"); //To Read from a txt file & print on console string copyTxt = File.ReadAllText("C:\\Users\\HP\\Desktop\\c#file.txt"); Console.Out.WriteLine("{0}",copyTxt); } } A: In addition to File.ReadAllText, File.ReadAllLines, and File.WriteAllText (and similar helpers from File class) shown in another answer you can use StreamWriter/StreamReader classes. Writing a text file: using(StreamWriter writetext = new StreamWriter("write.txt")) { writetext.WriteLine("writing in text file"); } Reading a text file: using(StreamReader readtext = new StreamReader("readme.txt")) { string readText = readtext.ReadLine(); } Notes: * *You can use readtext.Dispose() instead of using, but it will not close file/reader/writer in case of exceptions *Be aware that relative path is relative to current working directory. You may want to use/construct absolute path. *Missing using/Close is very common reason of "why data is not written to file". A: The easiest way to read from a file and write to a file: //Read from a file string something = File.ReadAllText("C:\\Rfile.txt"); //Write to a file using (StreamWriter writer = new StreamWriter("Wfile.txt")) { writer.WriteLine(something); } A: using (var file = File.Create("pricequote.txt")) { ........... } using (var file = File.OpenRead("pricequote.txt")) { .......... } Simple, easy and also disposes/cleans up the object once you are done with it. A: @AlexeiLevenkov pointed me at another "easiest way" namely the extension method. It takes just a little coding, then provides the absolute easiest way to read/write, plus it offers the flexibility to create variations according to your personal needs. Here is a complete example: This defines the extension method on the string type. Note that the only thing that really matters is the function argument with extra keyword this, that makes it refer to the object that the method is attached to. The class name does not matter; the class and method must be declared static. using System.IO;//File, Directory, Path namespace Lib { /// <summary> /// Handy string methods /// </summary> public static class Strings { /// <summary> /// Extension method to write the string Str to a file /// </summary> /// <param name="Str"></param> /// <param name="Filename"></param> public static void WriteToFile(this string Str, string Filename) { File.WriteAllText(Filename, Str); return; } // of course you could add other useful string methods... }//end class }//end ns This is how to use the string extension method, note that it refers automagically to the class Strings: using Lib;//(extension) method(s) for string namespace ConsoleApp_Sandbox { class Program { static void Main(string[] args) { "Hello World!".WriteToFile(@"c:\temp\helloworld.txt"); return; } }//end class }//end ns I would never have found this myself, but it works great, so I wanted to share this. Have fun! A: private void Form1_Load(object sender, EventArgs e) { //Write a file string text = "The text inside the file."; System.IO.File.WriteAllText("file_name.txt", text); //Read a file string read = System.IO.File.ReadAllText("file_name.txt"); MessageBox.Show(read); //Display text in the file } A: * *Reading from file string filePath = @"YOUR PATH"; List<string> lines = File.ReadAllLines(filePath).ToList(); *Writing to file List<string> lines = new List<string>(); string a = "Something to be written" lines.Add(a); File.WriteAllLines(filePath, lines); A: Simply: String inputText = "Hello World!"; File.WriteAllText("yourfile.ext",inputText); //writing var outputText = File.ReadAllText("yourfile.ext"); //reading A: You're looking for the File, StreamWriter, and StreamReader classes.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "441" }
Q: Can I paginate a custom query without overriding the default pagination? In my CakePHP (1.2) app, I have two actions that both use pagination - index and search. In a previous question I learnt that, in order to apply a threshold score to search results, I need to use the HAVING MySQL keyword. Since CakePHP does not support this natively, I need to drop down to a custom query in order to accomplish this. All the guides I can find to custom query pagination involve overriding the paginate() and paginateCount() methods. Since I still want to be able to paginate normally on the index however, I don't want to change the normal pagination behaviour in the model. Is there any way I can (ahem) have my Cake and eat it too? A: Actually if you CAN do it with find you CAN do it with paginate. You can take a look here But to be more especific you can add the conditions/limit/fields/contain/order etc that you use in find to the paginate function. I haven't use group in the paginate but it SHOULD work :D In your case you will have something like this: $this->paginate = array( 'fields' => array( 'Product.category_id', 'COUNT(Product.hotel_id) as total' ), 'group' => array( 'Product.category_id HAVING COUNT(Product.hotel_id) > 1') ) ); $data = $this->paginate('Product'); Hope it works, post a comment of your result, if it doesn't work you will have to override it, because it is not accepting the group condition... though I think it will work since pagination is a find in the end. EDIT: You may try to do something like this: Override the paginate() and paginateCount() but with a tweak, sneak a condition so you can tell if its a pagination with having or not. Something like this: function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()){ //if no having conditions set return the parent paginate if (empty($conditions['having']) return parent::paginate($conditions, $fields, $order, $limit, $page, $recursive, $extra) //if having conditions set return your override //override code here } Then you do something similar in paginateCount(), that way you have a selective paginate. remember to do unset $conditions['having'] once it is not needed or remember to put it somewhere that doesn't affect your find ;) A: Actually getting this to work was more of a headache than you might reasonably expect. Although I basically followed the advice of api55 (thanks!) I also jumped a load of other hurdles: * *It's not possible to do parent::paginateCount(). I overcame this by overriding it with a different (and apparently better) version in app_model.php. *Because paginateCount() is just a wrapper for find('count'), it doesn't accept a fields parameter. This is tricky for me as I rely on this to squeeze in my derived column (score of a full-text search). I got over this by passing the value of fields twice to paginate - once as fields and once as "sneaky". Cake puts any parameters it doesn't recognize into the extra array. *Tying this together, I had an override of paginateCount() in my model that looks to see whether extra has an key called "sneaky". If it does, it does a find('all') and uses the contents of sneaky to populate fields. It's days like today that I have to step back and remember all the good points about using a framework.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: Cocos2d -x crash on sound My game is using Cocos2d-x. When a sound plays, the game crashes randomly on Samsung Galaxy SII, other devices run perfectly. Only a native dump is in the LogCat: 09-27 13:01:32.615: INFO/DEBUG(26994): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 09-27 13:01:32.615: INFO/DEBUG(26994): Build fingerprint: 'samsung/GT-I9100/GT-I9100:2.3.3/GINGERBREAD/XWKF3:user/release-keys' 09-27 13:01:32.615: INFO/DEBUG(26994): pid: 28585, tid: 28596 >>> org.invictus.froggyjumpx <<< 09-27 13:01:32.615: INFO/DEBUG(26994): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad 09-27 13:01:32.615: INFO/DEBUG(26994): r0 00000027 r1 deadbaad r2 a0000000 r3 00000000 09-27 13:01:32.615: INFO/DEBUG(26994): r4 00000001 r5 00000000 r6 00000000 r7 03740de4 09-27 13:01:32.615: INFO/DEBUG(26994): r8 473da344 r9 473da29c 10 00000003 fp 00000000 09-27 13:01:32.615: INFO/DEBUG(26994): ip afd46688 sp 473da1a0 lr afd19471 pc afd15f40 cpsr 60000030 09-27 13:01:32.615: INFO/DEBUG(26994): d0 7149f2ca3f800000 d1 4528470d7149f2ca 09-27 13:01:32.615: INFO/DEBUG(26994): d2 3ff41dd3e0000000 d3 bf3027cebd240f5f 09-27 13:01:32.615: INFO/DEBUG(26994): d4 40013d553e4df297 d5 3e29e751c0198562 09-27 13:01:32.615: INFO/DEBUG(26994): d6 000056223f7e97a6 d7 0000000000000000 09-27 13:01:32.615: INFO/DEBUG(26994): d8 000000003f800000 d9 0000000000000000 09-27 13:01:32.615: INFO/DEBUG(26994): d10 0000000000000000 d11 0000000000000000 09-27 13:01:32.615: INFO/DEBUG(26994): d12 0000000000000000 d13 0000000000000000 09-27 13:01:32.615: INFO/DEBUG(26994): d14 0000000000000000 d15 0000000000000000 09-27 13:01:32.615: INFO/DEBUG(26994): d16 3fe0000000000000 d17 3f4f1dde3470f9aa 09-27 13:01:32.615: INFO/DEBUG(26994): d18 bf56b679c1561707 d19 3f83c93989891198 09-27 13:01:32.620: INFO/DEBUG(26994): d20 3fa55553e1053a42 d21 3f83c93989891198 09-27 13:01:32.620: INFO/DEBUG(26994): d22 3fe39560c0000000 d23 3ef99342e0ee5069 09-27 13:01:32.620: INFO/DEBUG(26994): d24 3ef99342e0ee5069 d25 bfe5d05800000000 09-27 13:01:32.620: INFO/DEBUG(26994): d26 3e555385e0000000 d27 3ef99342e0ee5069 09-27 13:01:32.620: INFO/DEBUG(26994): d28 0000000000000000 d29 0000000000000000 09-27 13:01:32.620: INFO/DEBUG(26994): d30 0000000000000000 d31 0000000000000000 09-27 13:01:32.620: INFO/DEBUG(26994): scr 20000010 09-27 13:01:32.830: INFO/DEBUG(26994): #00 pc 00015f40 /system/lib/libc.so 09-27 13:01:32.830: INFO/DEBUG(26994): #01 pc 000140a4 /system/lib/libc.so 09-27 13:01:32.830: INFO/DEBUG(26994): #02 pc 0001475a /system/lib/libc.so 09-27 13:01:32.830: INFO/DEBUG(26994): #03 pc 0001ac46 /system/lib/libbinder.so 09-27 13:01:32.830: INFO/DEBUG(26994): #04 pc 0001ad40 /system/lib/libbinder.so 09-27 13:01:32.830: INFO/DEBUG(26994): #05 pc 0001ad6c /system/lib/libbinder.so 09-27 13:01:32.830: INFO/DEBUG(26994): #06 pc 0001ad82 /system/lib/libbinder.so 09-27 13:01:32.830: INFO/DEBUG(26994): #07 pc 0001af24 /system/lib/libbinder.so 09-27 13:01:32.840: INFO/DEBUG(26994): #08 pc 000322a4 /system/lib/libmedia.so 09-27 13:01:32.840: INFO/DEBUG(26994): #09 pc 0002f3b4 /system/lib/libmedia.so 09-27 13:01:32.840: INFO/DEBUG(26994): #10 pc 0002fd7e /system/lib/libmedia.so 09-27 13:01:32.840: INFO/DEBUG(26994): #11 pc 0002ff02 /system/lib/libmedia.so 09-27 13:01:32.840: INFO/DEBUG(26994): #12 pc 00004764 /system/lib/libsoundpool.so 09-27 13:01:32.840: INFO/DEBUG(26994): code around pc: 09-27 13:01:32.840: INFO/DEBUG(26994): afd15f20 2c006824 e028d1fb b13368db c064f8df 09-27 13:01:32.840: INFO/DEBUG(26994): afd15f30 44fc2401 4000f8cc 49124798 25002027 09-27 13:01:32.840: INFO/DEBUG(26994): afd15f40 f7f57008 2106eb46 ecbaf7f6 460aa901 09-27 13:01:32.840: INFO/DEBUG(26994): afd15f50 f04f2006 95015380 95029303 e820f7f6 09-27 13:01:32.840: INFO/DEBUG(26994): afd15f60 462aa905 f7f62002 f7f5e82c 2106eb32 09-27 13:01:32.840: INFO/DEBUG(26994): code around lr: 09-27 13:01:32.840: INFO/DEBUG(26994): afd19450 4a0e4b0d e92d447b 589c41f0 26004680 09-27 13:01:32.840: INFO/DEBUG(26994): afd19460 686768a5 f9b5e006 b113300c 47c04628 09-27 13:01:32.840: INFO/DEBUG(26994): afd19470 35544306 37fff117 6824d5f5 d1ef2c00 09-27 13:01:32.840: INFO/DEBUG(26994): afd19480 e8bd4630 bf0081f0 000280cc ffffff88 09-27 13:01:32.840: INFO/DEBUG(26994): afd19490 b086b570 f602fb01 9004460c a804a901 09-27 13:01:32.840: INFO/DEBUG(26994): stack: 09-27 13:01:32.840: INFO/DEBUG(26994): 473da160 afd42684 09-27 13:01:32.840: INFO/DEBUG(26994): 473da164 000c14b8 09-27 13:01:32.840: INFO/DEBUG(26994): 473da168 00000015 09-27 13:01:32.840: INFO/DEBUG(26994): 473da16c afd18539 /system/lib/libc.so 09-27 13:01:32.840: INFO/DEBUG(26994): 473da170 afd4272c 09-27 13:01:32.840: INFO/DEBUG(26994): 473da174 afd426d8 09-27 13:01:32.840: INFO/DEBUG(26994): 473da178 00000000 09-27 13:01:32.845: INFO/DEBUG(26994): 473da17c afd19471 /system/lib/libc.so 09-27 13:01:32.845: INFO/DEBUG(26994): 473da180 00000001 09-27 13:01:32.845: INFO/DEBUG(26994): 473da184 473da1b4 09-27 13:01:32.845: INFO/DEBUG(26994): 473da188 00000000 09-27 13:01:32.845: INFO/DEBUG(26994): 473da18c 03740de4 09-27 13:01:32.845: INFO/DEBUG(26994): 473da190 473da344 09-27 13:01:32.845: INFO/DEBUG(26994): 473da194 afd18793 /system/lib/libc.so 09-27 13:01:32.845: INFO/DEBUG(26994): 473da198 df002777 09-27 13:01:32.845: INFO/DEBUG(26994): 473da19c e3a070ad 09-27 13:01:32.845: INFO/DEBUG(26994): #00 473da1a0 003f5c68 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1a4 0000a000 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1a8 00000006 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1ac afd46470 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1b0 00000000 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1b4 fffffbdf 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1b8 473da344 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1bc 00184440 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1c0 00000013 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1c4 afd140a9 /system/lib/libc.so 09-27 13:01:32.845: INFO/DEBUG(26994): #01 473da1c8 473da29c 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1cc 00000006 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1d0 00000000 09-27 13:01:32.845: INFO/DEBUG(26994): 473da1d4 00006fa9 09-27 13:01:32.850: INFO/DEBUG(26994): 473da1d8 473da344 09-27 13:01:32.850: INFO/DEBUG(26994): 473da1dc afd1475d /system/lib/libc.so Did this happened to anyone else? I don't have access to those files, does anyone has? A: I have found a fix that solves everything for me, both on Google Nexus One and Samsung Galaxy S1. Simply remove any calls to AudioRecord.release(); All i do when i am done with the AudioRecord is audioRecord.Stop() and audioRecord == null. No native errors, no exception, and it records fine when re-instanciated. A: I searched on the net, maybe someone else also faced this problem. It turned out a lot of people have. According to this link, the problem is in the devices sound pool. It's up to the manufacturers to fix the leak. A: It is probably a SoundPool bug. What file format are you using? I'm having issues with Wav and thinking about using Ogg instead. It should be more stable.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569912", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: PHP: How to insert element into an array from variable I need to insert valus into a array.How i do that. my code is below: foreach($number_array as $number) { if(strlen($number)==10) { //How to insert the number values into an array ?? } } A: $new_array = array(); foreach($number_array as $number) { if(strlen($number)==10) { $new_array[] = (int) $number; } } This adds all numbers of the number_array that are of length 10 to the new_array ;) A: Append them onto $array with the [] notation, or use array_push(). // Start with empty array. $array = array(); foreach($number_array as $number) { if(strlen($number)==10) { // Append $number to $array $array[] = $number; // Alternatively, use array_push() array_push($array, $number); } } A: Though both answers are correct; it seems to me that the foreach is useless, you can achieve this just as well with array_filter, which is faster and easier to use (from my point of view, anyway): <?php $newArray = array_filter( $number_array, function( $element ) { return strlen( $element ) === 10; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7569914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can Apache log if users have JS disabled We would like to know how many of our site visitors have JS disabled in order to help us decide whether or not we should develop a non-JS version of our new site design. Is this possible with Apache 2.2? A: Use the <noscript> tag, the block inside this tag won't be used by the browser if js is enabled. Then use it to load a specific url, then you will be able to track this url in your apache logs. An image will maybe do the trick (automatic GET from the browser), never tested but I think it should'nt be loaded if js is enabled. <script type="javascript"> (...) here anything you could want in js, or maybe nothing as well </script> <noscript> <IMG SRC="http://mysite.com/nojs.png" width="0" height="0" alt="nojstracking"> </noscript> No this is quite basic, is loaded at every page request from the user, you cannot track that all requests to nojs.png are different web users, and you cannot compare it to the total number of requests of your websites (and you should be very careful with cache settings of this image response headers). Maybe you'll need to load a different image in the <script> section so that you could compare more easily how many people are requesting the 1st one versus the 2nd one. To get more accurate results you would need something more advanced, catch theses images url with a server side program (PHP, Java?), handle session cookies, and track existing sessions, you will have more control on your log tracking in server side program than just in Apache (is this an already active session, a new user, someone I already know, etc).
{ "language": "en", "url": "https://stackoverflow.com/questions/7569915", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I use a collection within an Oracle SQL statement I want to write an Oracle function that collects some data in multiple steps into a collection variable and use that collection data within a SELECT query like in this very simplified example: CREATE OR REPLACE FUNCTION TESTFUNC01 RETURN VARCHAR2 AS -- INT_LIST is declared globally as "TYPE INT_LIST IS TABLE OF INTEGER" MyList INT_LIST := INT_LIST(); MyName VARCHAR2(512); BEGIN MyList.Extend(3); MyList(0) := 1; MyList(1) := 2; MyList(2) := 3; SELECT Name INTO MyName FROM Item WHERE ItemId NOT IN MyList; RETURN MyName; END TESTFUNC01; Unfortunately the part "NOT IN MyList" is no valid SQL. Is there a way to achieve this? A: If your using oracle 10 you could use the collections extensions: CREATE OR REPLACE FUNCTION TESTFUNC01 RETURN VARCHAR2 AS -- INT_LIST is declared globally as "TYPE INT_LIST IS TABLE OF INTEGER" MyList INT_LIST := INT_LIST(); MyName VARCHAR2(512); BEGIN MyList.Extend(3); MyList(1) := 1; MyList(2) := 2; MyList(3) := 3; SELECT Name INTO MyName FROM Item WHERE ItemId MEMBER OF MyList; RETURN MyName; END TESTFUNC01; for more details see this post A: You can do it like this: CREATE OR REPLACE FUNCTION TESTFUNC01 RETURN VARCHAR2 AS -- INT_LIST is declared globally as "TYPE INT_LIST IS TABLE OF INTEGER" MyList INT_LIST := INT_LIST(); MyName VARCHAR2(512); BEGIN MyList.Extend(3); MyList(1) := 1; MyList(2) := 2; MyList(3) := 3; SELECT Name INTO MyName FROM Item WHERE ItemId NOT IN (SELECT COLUMN_VALUE FROM TABLE(MyList)); RETURN MyName; END TESTFUNC01; Note that I've also changed the list indices. The start with 1 (not 0). A: -- INT_LIST is declared globally as "TYPE INT_LIST IS TABLE OF INTEGER" That looks like a PL/SQL declaration. SELECT statements use the SQL engine. This means you need to declare your TYPE in SQL. CREATE TYPE INT_LIST AS TABLE OF NUMBER(38,0); / Then you can use it in a SELECT statement: SELECT Name INTO MyName FROM Item WHERE ItemId NOT IN (select * from table(MyList)); Of course, you need to make sure that your query returns only one row, or that your program handles the TOO_MANY_ROWS exception. A: What you're looking for is the table function: CREATE OR REPLACE FUNCTION TESTFUNC01 RETURN VARCHAR2 AS -- INT_LIST is declared globally as "TYPE INT_LIST IS TABLE OF INTEGER" MyList INT_LIST := INT_LIST(); MyName VARCHAR2(512); BEGIN MyList.Extend(3); MyList(1) := 1; MyList(2) := 2; MyList(3) := 3; SELECT Name INTO MyName FROM Item WHERE ItemId NOT IN (select * from table(MyList)); RETURN MyName; END TESTFUNC01;
{ "language": "en", "url": "https://stackoverflow.com/questions/7569918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Zend Studio formats txt-sources after upload Zend Studio formats txt-sources after upload. for Ex: <?php echo 'test'; echo 'test'; echo 'test'; ?> after upload this source code looks like: <?php echo 'test'; echo 'test'; echo 'test'; ?> A: Check the file line delimiter option. In both Zend Studio and Eclipse it should be in Windows->Preferences->General->Workspace If you use unix-like server you should use: * *text file encoding: utf-8 *new text file line delimiter: unix Adjust the settings based on the server your script will woork and not on the machine you are developing.
{ "language": "en", "url": "https://stackoverflow.com/questions/7569919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: read the incoming data from web service I have a doubt to be clarified. how can i read the incoming data from web service. What i want is i get data like this [ " hi how r u :) " ]. so i need to fetch this message before it is displayed in list view. sample code: http://pastebin.com/q3mbuSpU So I need to replace the corresponding " :) " with smiley image in local folder before datais displayed in listview from web service. I am working the same topic for more than 1 week. Please guide in in solving this. Thanks in advance. A: i suggest one idea not sure its working or not.. but you have try... 1) Split your response string when space comes and store in string array. 2) check every character of your string array one by one ... if character ascii value is between a to z and A to Z then its data.. and not then its smiley data.....
{ "language": "en", "url": "https://stackoverflow.com/questions/7569920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }