text
stringlengths
8
267k
meta
dict
Q: WCF SOAP Action I am rewriting a legacy asp.net web service in WCF 4.0. My obvious end-goal would be that the new endpoints would exactly match the legacy ones. The problem i encountered is that in the legacy web service they exposed the soap actions as: http://www.my-domain.com/my-action. In WCF from my research it needs to be like: http://www.my-domain/my-service-contract/my-action. I found that you can alter the service contract descriptor by changing the "Name" parameter to the service contact namespace attribute. From my research it seems like there is no way to completely remove this from the exposed soap action. Anyone have any insight into this? A: Using the OperationContractAttribute.Action property you can specify the entire string.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Omniauth is not directing to FB but rather my root? / in my view I have: <%= link_to "Sign in with Facebook", user_omniauth_authorize_path(:facebook) %> Which renders with the link: http://localhost:3000/users/auth/facebook Problem is when I click that link it loads directly to: Started GET "/" for 127.0.0.1 at 2011-09-26 15:35:29 -0700 Processing by PagesController#landing_teaser as HTML Rendered pages/landing_teaser.html.erb within layouts/unauthorized (7.1ms) Completed 200 OK in 13ms (Views: 11.2ms | ActiveRecord: 1.0ms) Here is my routes file: match '/users/auth/facebook/callback' => 'authentications#create' # Devise devise_for :users, :controllers => {:registrations => "registrations"} Any thoughts on why omniauth is failing? Thanks A: Looking at your routes I see that you only define match '/users/auth/facebook/callback' => 'authentications#create' but in devise omniauth tutorial the route contains this (and for the records it should be different if you're using only omniauth) devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" } The only thing I see is that /users/auth/facebook path doesn't match your route file and it goes through some devise (o omniauth) default route. When you clear your cookies you reset the "status" of your browser and it starts a new session. When you have some cookies (maybe of a previous authentication) it recognize your previous session and don't ask you to authenticate again unless you do an explicit logout. I've developed an application which uses devise+omniauth+google apps authentication and it ask me for credentials only once in a while, even when I close the browser and reopen it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ExtJS 4 - Refreshing Summary Feature of Grid Panel Without Refreshing Entire View I'm using ExtJS's GridPanel library to render a list of rows that have a CheckboxModel for selections. There is also a summary row that adds up all of the selected data and displays it in a row at the bottom of the GridPanel. The code for this is: var sm = Ext.create('Ext.selection.CheckboxModel', { ///////// // With large number of rows ... this takes forever ///////// grid.getView().refresh(); ///////// ///////// listeners:{ selectionchange: function(selectionModel, selectedRecords, options){ // Do stuff } } }); var selSumFn = function(column, selModel){ return function(){ var records = selModel.getSelection(), result = 0; //console.log("records:" + records.length); Ext.each(records, function(record){ result += record.get(column) * 1; }); return result; }; }; var grid = Ext.create('Ext.grid.Panel', { autoScroll:true, features: [{ ftype: 'summary' }], store: store, defaults: { sortable:true }, selModel: sm, columns: [ {header: 'Column 1', width: 100, dataIndex: 'col1', summaryType: selSumFn('col1', sm)}, {header: 'Column 2', width: 100, dataIndex: 'col2', summaryType: selSumFn('col2', sm)} ], width: 730, height: 400 , title: 'Data', renderTo: 'data-div', viewConfig: { stripeRows: true }, listeners: {'beforerender' : {fn:function(){this.store.load();}}} }); Is there any way to only refresh the summaryrow feature and not the entire view? Refreshing the view was the only way I could find to refresh the summary row when updates were made to checkbox selections of the GridPanel. A: There is no support for this in Ext 4.0.2a. The grid view builds a single view template with features adding or modifying this template via a multitude of defined hooks. The result is a single template instance that cannot be easily dissected. The best solution I found is to rebuild the template fragment that renders the summary row mimicking what the grid view is doing during the template construction process. Then overwrite the existing DOM for the summary row with a freshly rendered version. I have created a patch (as an override) that adds a refresh() method to the Summary feature. The code turned out to be surprisingly slick. Ext.require('Ext.grid.feature.Summary', function() { Ext.override(Ext.grid.feature.Summary, { refresh: function() { if(this.view.rendered) { var tpl = Ext.create( 'Ext.XTemplate', '{[this.printSummaryRow()]}', this.getFragmentTpl() ); tpl.overwrite(this.getRowEl(), {}); } }, getRowEl: function() { return this.view.el.down('tr.x-grid-row-summary'); } }); }); In your selectionchange listener: selectionchange: function(selectionModel, selectedRecords, options) { grid.getView().getFeature(0).refresh(); } See this JsFiddle for a live demo. Of course this might break in future versions of Ext. However, it could turn out to be quite robust since it delegates most of its work to existing methods. A: If you are using GroupingSummary, you need to use this instead: refresh:function(){ var rowEls = this.view.el.query('tr.x-grid-row-summary'); var i = 1; Ext.Array.each(this.summaryGroups, function(group){ var tpl = new Ext.XTemplate( this.printSummaryRow(i), this.getFragmentTpl() ); tpl.overwrite(rowEls[i-1], {}) i++; },this);
{ "language": "en", "url": "https://stackoverflow.com/questions/7562185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove the last 2 lines of a huge file without reading it I have a 100GB file, and need to remove the last two lines of it. I do not want to read from it since it will take about an hour to get to the bottom of it so sed does not seem to be an option. My disk is also too small to be able to copy that file. What are my options here ? Thanks. A: I'm pretty sure in .Net you can open a FileStream to a file, then move the pointer to a specific byte (which you could calculate), and modify it from there. However, I'm not sure if it has to pass the whole stream when you try to save it, so this might be more useful if you needed to copy just the last 2 lines. A: In C/POSIX, you should be able to use fseek with the SEEK_END option to back up a little bit from the end of the file (say 512 bytes), then read those 512 bytes into memory. From that, you can figure out exactly where the second last line starts and then use truncate or ftruncate to actually truncate the file at that point. If the last two lines are more than 512 bytes (ie, the start of the second last line doesn't show up in the chunk you read), just increase the value to 1024 and try again. Keep going until you find it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity Framework / Unit of Work Architecture Question I'm very familiar with UoW, Repository Pattern, etc. but in seeing various implementations of the pattern for Entity Framework, I'm curious why anyone would have a Save or Add method on their repository. If you use the repository to get you a new instance of an object that I would imagine someone would already public Customer GetNewCustomer() { Customer customer = new Customer(); ... any initialization code here ... _context.Customers.AddObject(customer); return customer; } I know in some designs, you can simply use Customer customer = new Customer(); and its not attached anywhere to the context. However I'm a fan of private constructors so there is a single point of instantiation for a Customer object. With that in mind wouldn't it makes sense to never have an add/save method on the repository when using a UoW pattern and only have this functionality on the IUnitOfWork interface? A: When I follow the Spring idiom in Java, units of work (and transactions) are associated with services. They use model and persistence objects to fulfill a request. Transactions are demarked using aspects. I don't know whether .NET follows a similar idea, but it'd be worth exploring. Have interface-based POCO services and let them own transactions. A: I don't think that your solution is correct. That will add empty customer to current unit of work. That means that later code will have a hard time if it decide not to save customer by the current unit of work. It is quite common that repository have method to save entity. You are combining two patterns used in Domain driven design * *Repository *Object factory Repository's responsibility is to retrieve or store entities. Object factory's responsibility is to handle entity construction. Btw. private constructor of your entity will not be accessible in your repository if repository is not the entity (which would be quite bad). A: ...wouldn't it makes sense to never have an add/save method on the repository when using a UoW pattern and only have this functionality on the IUnitOfWork interface? Yes I think it makes sense to only have the Save method on the IUnitOfWork interface. However, I no longer use the repository pattern with EF. Instead, I now use these variations of the command & query patterns. If you think about it, the EF DbContext is really doing 3 things: 1.) it functions as your repository for reading entity state, 2.) as your repository for mutating entity state, and 3.) as a UnitOfWork for tracking multiple changes and combining them into a single transaction to persist state mutations. So, why not separate these 3 responsibilities into 3 different interfaces? public interface IUnitOfWork { int SaveChanges(); } public interface ICommandEntities : IQueryEntities { void Create(Entity entity); void Update(Entity entity); void Purge(Entity entity); } public interface IQueryEntities { IQueryable<AggregateRoot1> AggregateRoot1s { get; } IQueryable<AggregateRoot2> AggregateRoot2s { get; } IQUeryable<AggregateRootN> AggregateRootNs { get; } IQueryable<TEntity> EagerLoad<TEntity>(IQueryable<TEntity> query, Expression<Func<TEntity, object>> expression) where TEntity : Entity; } You can then implement these 3 interfaces on your DbContext class. This keeps the interfaces nice and segregated, and lets you dependency inject only those methods of the DbContext which you need. For example, your domain should be persistence ignorant, right? In that case, don't give any of your domain classes dependencies on the IUnitOfWork interface. Instead, handle the IUnitOfWork in your IoC composition root (or in an MVC action filter). Then, your query and command handlers deal only with the ICommandEntities and IQueryEntities interfaces.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562193", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When converting a project to use ARC what does "switch case is in protected scope" mean? When converting a project to use ARC what does "switch case is in protected scope" mean? I am converting a project to use ARC, using Xcode 4 Edit -> Refactor -> Convert to Objective-C ARC... One of the errors I get is "switch case is in protected scope" on "some" of the switches in a switch case. Edit, Here is the code: the ERROR is marked on the "default" case: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @""; UITableViewCell *cell ; switch (tableView.tag) { case 1: CellIdentifier = @"CellAuthor"; cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } cell.textLabel.text = [[prefQueries objectAtIndex:[indexPath row]] valueForKey:@"queryString"]; break; case 2: CellIdentifier = @"CellJournal"; cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } cell.textLabel.text = [[prefJournals objectAtIndex:[indexPath row]] valueForKey:@"name"]; NSData * icon = [[prefJournals objectAtIndex:[indexPath row]] valueForKey:@"icon"]; if (!icon) { icon = UIImagePNGRepresentation([UIImage imageNamed:@"blank72"]); } cell.imageView.image = [UIImage imageWithData:icon]; break; default: CellIdentifier = @"Cell"; cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } break; } return cell; } A: There are 2 easy ways to solve this issue: * *You are probably declaring variables. Move the declaration of the variables outside the switch statement *Put the whole case block in between curly brackets {} The compiler can not calculate the code line when the variables are to be released. Causing this error. A: Surround each case itself with braces {}. That should fix the issue (it did for me in one of my projects). A: For me, the problem started on the middle of a switch and curly brackets did not worked out, unless you have to include {} IN ALL previous case statements. For me the error came when I had the statement NSDate *start = [NSDate date]; in the previous case. After I deleted this, then all subsequent case statement came clean from the protected scope error message A: Before: case 2: NSDate *from = [NSDate dateWithTimeIntervalSince1970:1388552400]; [self refreshContents:from toDate:[NSDate date]]; break; I moved NSDate definition before switch, and it fixed the compile problem: NSDate *from; /* <----------- */ switch (index) { .... case 2: from = [NSDate dateWithTimeIntervalSince1970:1388552400]; [self refreshContents:from toDate:[NSDate date]]; break; } A: Declare the variables outside the switch, then instantiate them inside the case. That worked perfectly for me using Xcode 6.2 A: Hard to be sure without looking at the code, but it probably means there's some variable declaration going on inside the switch and the compiler can't tell if there's a clear path to the required dealloc point. A: default: CellIdentifier = @"Cell"; cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { ***initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];*** cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } break; } Note: Check! The syntax of the bold & italicized line. Rectify it and you are good to go. A: Surround with braces {} the code between the case statement and the break in each case. It worked on my code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "284" }
Q: Difference between these two lambdas? These both seem to do the same thing.. I'm wondering which one I should use, you would prefer to read, is more efficient, their differences, et cetera.. Lambda #1 synchronizationContext.Post(m => log.AppendText(message), null); Lambda #2 synchronizationContext.Post(m => log.AppendText(m), message); My only concern is that with the second one, even though it may look more read-able, isn't their boxing and unboxing because of the Post method takes an object and message is a string? Thanks. A: Strings are stored in the managed heap, so they don't need to be boxed/unboxed. Because you don't have do any extra casting (from object to string), I would go with this one: synchronizationContext.Post(m => log.AppendText(message), null);
{ "language": "en", "url": "https://stackoverflow.com/questions/7562202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is an ExpandoObject breaking code that otherwise works just fine? Here's the setup: I have an Open Source project called Massive and I'm slinging around dynamics as a way of creating SQL on the fly, and dynamic result sets on the fly. To do the database end of things I'm using System.Data.Common and the ProviderFactory stuff. Here's a sample that works just fine (it's static so you can run in a Console): static DbCommand CreateCommand(string sql) { return DbProviderFactories.GetFactory("System.Data.SqlClient") .CreateCommand(); } static DbConnection OpenConnection() { return DbProviderFactories.GetFactory("System.Data.SqlClient") .CreateConnection(); } public static dynamic DynamicWeirdness() { using (var conn = OpenConnection()) { var cmd = CreateCommand("SELECT * FROM Products"); cmd.Connection = conn; } Console.WriteLine("It worked!"); Console.Read(); return null; } The result of running this code is "It worked!" Now, if I change the string argument to dynamic - specifically an ExpandoObject (pretend that there's a routine somewhere that crunches the Expando into SQL) - a weird error is thrown. Here's the code: What worked before now fails with a message that makes no sense. A SqlConnection is a DbConnection - moreover if you mouseover the code in debug, you can see that the types are all SQL types. "conn" is a SqlConnection, "cmd" is a SqlCommand. This error makes utterly no sense - but more importantly it's cause by the presence of an ExpandoObject that doesn't touch any of the implementation code. The differences between the two routines are: 1 - I've changed the argument in CreateCommand() to accept "dynamic" instead of string 2 - I've created an ExpandoObject and set a property. It gets weirder. If simply use a string instead of the ExpandoObject - it all works just fine! //THIS WORKS static DbCommand CreateCommand(dynamic item) { return DbProviderFactories.GetFactory("System.Data.SqlClient").CreateCommand(); } static DbConnection OpenConnection() { return DbProviderFactories.GetFactory("System.Data.SqlClient").CreateConnection(); } public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject(); ex.TableName = "Products"; using (var conn = OpenConnection()) { //use a string instead of the Expando var cmd = CreateCommand("HI THERE"); cmd.Connection = conn; } Console.WriteLine("It worked!"); Console.Read(); return null; } If I swap out the argument for CreateCommand() to be my ExpandoObject ("ex") - it causes all of the code to be a "dynamic expression" which is evaluated at runtime. It appears that the runtime evaluation of this code is different than compile-time evaluation... which makes no sense. **EDIT: I should add here that if I hard-code everything to use SqlConnection and SqlCommand explicitly, it works :) - here's an image of what I mean: A: Looking at the exception being thrown, it seems that even though OpenConnection returns a static type (DbConnection) and CreateCommand returns a static type (DbCommand), because the parameter passed to DbConnection is of type dynamic it's essentially treating the following code as a dynamic binding site: var cmd = CreateCommand(ex); cmd.Connection = conn; Because of this, the runtime-binder is trying to find the most specific binding possible, which would be to cast the connection to SqlConnection. Even though the instance is technically a SqlConnection, it's statically typed as DbConnection, so that's what the binder attempts to cast from. Since there's no direct cast from DbConnection to SqlConnection, it fails. What seems to work, taken from this S.O. answer dealing with the underlying exception type, is to actually declare conn as dynamic, rather than using var, in which case the binder finds the SqlConnection -> SqlConnection setter and just works, like so: public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject(); ex.TableName = "Products"; using (dynamic conn = OpenConnection()) { var cmd = CreateCommand(ex); cmd.Connection = conn; } Console.WriteLine("It worked!"); Console.Read(); return null; } That being said, given the fact that you statically typed the return type of CreateCommand to DbConnection, one would have thought the binder would have done a better job of "doing the right thing" in this case, and this may well be a bug in the dynamic binder implementation in C#. A: When you pass the dynamic to CreateCommand, the compiler is treating its return type as a dynamic that it has to resolve at runtime. Unfortunately, you're hitting some oddities between that resolver and the C# language. Fortunately, it's easy to work around by removing your use of var forcing the compiler to do what you expect: public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject (); ex.Query = "SELECT * FROM Products"; using (var conn = OpenConnection()) { DbCommand cmd = CreateCommand(ex); // <-- DON'T USE VAR cmd.Connection = conn; } Console.WriteLine("It worked!"); Console.Read(); return null; } This has been tested on Mono 2.10.5, but I'm sure it works with MS too. A: It appears that the runtime evaluation of this code is different than compile-time evaluation... which makes no sense. That's what's going on. If any part of an invocation is dynamic, the entire invocation is dynamic. Passing a dynamic argument to a method causes the entire method to be invoked dynamically. And that makes the return type dynamic, and so on and so on. That's why it works when you pass a string, you're no longer invoking it dynamically. I don't know specifically why the error occurs, but I guess implicit casts aren't handled automatically. I know there are some other cases of dynamic invocation that behave slightly differently than normal because we hit one of them when doing some of the dynamic POM (page object model) stuff in Orchard CMS. That's an extreme example though, Orchard plugs pretty deeply into dynamic invocation and may simply be doing things that it wasn't designed for. As for "it makes no sense" -- agree that it is unexpected, and hopefully improved on in future revs. I bet there some some subtle reasons over my head that the language experts could explain on why it doesn't work just automatically. This is one reason why I like to limit the dynamic parts of the code. If you're calling something that isn't dynamic with a dynamic value but you know what type you expect it to be, explicitly cast it to prevent the invocation from being dynamic. You get back into 'normal land', compile type checking, refactoring, etc. Just box in the dynamic use where you need it, and no more than that. A: This question piqued my interest, and after a bit of back and forth on twitter I thought it might be worth writing my own take on the issue. After accepting Frank's answer, you mentioned on twitter that it worked, but didn't explain the 'weirdness'. Hopefully this can explain the weirdness, and exlpain why Frank's and Alexander's solutions work, as well as adding a bit of detail to Shane's initial answer. The issue you've encountered is exactly as Shane first described. You are getting type mismatches based on a combination of compile-time type inference (due in part to the use of the var keyword), and runtime type resolution due to use of dynamic. Firstly, compile-time type inference: C# is a statically or strongly typed language. Even dynamic is a static type, but one that bypasses static type checking (as discussed here). Take the following simple situation: class A {} class B : A {} ... A a = new B(); In this situation, the static, or compile-time type of a is A, even though at runtime the actual object is of type B. The compiler will ensure that any use of a conforms only to what class A makes available, and any B specific functionality will require an explicit cast. Even at runtime, a is still considered to be statically A, despite the actual instance being a B. If we change the initial declaration to var a = new B();, the C# compiler now infers the type of a. In this situation, the most specific type it can infer from the information is that a is of type B. Thus, a has a static or compile-time type of B, and the specific instance at runtime will also be of type B. Type inference aims for the most specific type based on the information available. Take the following for example: static A GetA() { return new B(); } ... var a = GetA(); Type inference will now infer a to be of type A as that is the information available to the compiler at the callsite. Consequently, a has a static or compile-time type of A and the compiler ensures that all usage of a conforms to A. Once again, even at runtime, a has a static type of A even though the actual instance is of type B. Secondly, dynamic and runtime-evaluation: As stated in the previous article I linked to, dynamic is still a static type, but the C# compiler does not perform any static type checking on any statement or expression that has a type dynamic. For instance, dynamic a = GetA(); has a static or compile-time type of dynamic, and consequently no compile-time static type checks are performed on a. At run time, this will be a B, and can be used in any situation that accepts a static type of dynamic (i.e. all situations). If it is used in a situation that doesn't accept a B then a run-time error is thrown. However, if an operation involves a conversion from dynamic to another type, that expression is not dynamic. For instance: dynamic a = GetA(); var b = a; // whole expression is dynamic var b2 = (B)a; // whole expression is not dynamic, and b2 has static type of B This is situation is obvious, but it becomes less so in more complex examples. static A GetADynamic(dynamic item) { return new B(); } ... dynamic test = "Test"; var a = GetADynamic(test); // whole expression is dynamic var a2 = GetADynamic((string)test); // whole expression is not dynamic, and a2 has a static type of `A` The second statement here is not dynamic, due to type-casting test to string (even though the parameter type is dynamic). Consequently, the compiler can infer the type of a2 from the return type of GetADynamic and a2 has a static or compile-time type of A. Using this information, it's possible to create a trivial replica of the error you were receiving: class A { public C Test { get; set; } } class B : A { public new D Test { get; set; } } class C {} class D : C {} ... static A GetA() { return new B(); } static C GetC() { return new D(); } static void DynamicWeirdness() { dynamic a = GetA(); var c = GetC(); a.Test = c; } In this example, we get the same run-time exception at line a.Test = c;. a has the static type of dynamic and at run-time will be an instance of B. c is not dynamic. The compiler infers its type to be C using the information available (return type of GetC). Thus, c has a static compile-time type of C, and even though at run-time it will be an instance of D, all uses have to conform to its static type of C. Consequently, we get a run-time error on the third line. The run-time binder evaluates a to be a B, and consequently Test is of type D. However, the static type of c is C and not D, so even though c is actually an instance of D, it can't be assigned without first casting (casting its static type C to D). Moving onto your specific code and problem (finally!!): public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject(); ex.TableName = "Products"; using (var conn = OpenConnection()) { var cmd = CreateCommand(ex); cmd.Connection = conn; } Console.WriteLine("It worked!"); Console.Read(); return null; } ex has the static type of dynamic and consequently all expressions involving it are also dynamic and thus bypass static type checking at compile time. However, nothing in this line using (var conn = OpenConnection()) is dynamic, and consequently all typing is inferred at compile-time. Therefore, conn has a static compile-time type of DbConnection even though at runtime it will be an instance of SqlConnection. All usages of conn will assume it is a DbConnection unless it is cast to change its static type. var cmd = CreateCommand(ex); uses ex, which is dynamic, and consequently the whole expression is dynamic. This means that cmd is evaluated at run-time, and its static type is dynamic. The run-time then evaluates this line cmd.Connection = conn;. cmd is evaluated to be a SqlCommand and thus Connection expects SqlConnection. However, the static type of conn is still DbConnection, so the runtime throws an error as it can't assign an object with static type DbConnection to a field requiring SqlConnection without first casting the static type to SqlConnection. This not only explains why you get the error, but also why the proposed solutions work. Alexander's solution fixed the problem by changing the line var cmd = CreateCommand(ex); to var cmd = CreateCommand((ExpandoObject)ex);. However, this isn't due to passing dynamic across assemblies. Instead, it fits into the situation described above (and in the MSDN article): explicitly casting ex to ExpandoObject means the expression is no longer evaluated as dynamic. Consequently, the compiler is able to infer the type of cmd based on the return type of CreateCommand, and cmd now has a static type of DbCommand (instead of dynamic). The Connection property of DbCommand expects a DbConnection, not a SqlConnection, and so conn is assigned without error. Frank's solution works for essentially the same reason. var cmd = CreateCommand(ex); is a dynamic expression. 'DbCommand cmd = CreateCommand(ex);requires a conversion fromdynamicand consequently falls into the category of expressions involvingdynamicthat are not themselves dynamic. As the static or compile-time type ofcmdis now explicitlyDbCommand, the assignment toConnection` works. Finally, addressing your comments on my gist. Changing using (var conn = OpenConnection()) to using (dynamic conn = OpenConnection()) works because conn is now dyanmic. This means it has a static or compile-time type of dynamic and thus bypasses static type checking. Upon assignment at line cmd.Connection = conn the run-time is now evaluating both 'cmd' and 'conn', and their static types are not coming into play (because they are dynamic). Because they are instances of SqlCommand and SqlConnection respectively, it all works. As for the statement 'the entire block is a dynamic expression - given that then there is no compile time type': as your method DynamicWeirdness returns dynamic, any code that calls it is going to result in dynamic (unless it performs an explicit conversion, as discussed). However, that doesn't mean that all code inside the method is treated as dynamic - only those statements that explicitly involve dynamic types, as discussed. If the entire block was dynamic, you presumably wouldn't be able to get any compile errors, which is not the case. The following, for instance, doesn't compile, demonstrating that the entire block is not dynamic and static / compile-time types do matter: public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject(); ex.TableName = "Products"; using (var conn = OpenConnection()) { conn.ThisMethodDoesntExist(); var cmd = CreateCommand(ex); cmd.Connection = conn; } Console.WriteLine("It worked!"); Console.Read(); return null; } Finally, in regards to your comments about the debug display / console output of the objects: that isn't surprising and doesn't contradict anything here. GetType() and the debugger both output the type of the instance of the object, not the static type of the variable itself. A: You don't need to use the Factory to create the command. Just use conn.CreateCommand(); it will be the correct type and the connection will already be set. A: It's acting as if you're trying to pass dynamics anonymous types across assemblies, which is not supported. Passing an ExpandoObject is supported though. The work-around I have used, when I need to pass across assemblies, and I have tested it successfully, is to cast the dynamic input variable as an ExpandoObject when you pass it in: public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject(); ex.TableName = "Products"; using (var conn = OpenConnection()) { var cmd = CreateCommand((ExpandoObject)ex); cmd.Connection = conn; } Console.WriteLine("It worked!"); Console.Read(); return null; } EDIT: As pointed out in the comments, you CAN pass dynamics across assemblies, you CAN'T pass anonymous types across assemblies without first casting them. The above solution is valid for the same reason as Frank Krueger states above. When you pass the dynamic to CreateCommand, the compiler is treating its return type as a dynamic that it has to resolve at runtime. A: Because you're using dynamic as the argument to CreateCommand(), the cmd variable is also dynamic, which means its type is resolved at runtime to be SqlCommand. By contrast, the conn variable is not dynamic and is compiled to be of type DbConnection. Basically, SqlCommand.Connection is of type SqlConnection, so the conn variable, which is of type DbConnection, is an invalid value to set Connection to. You can fix this by either casting conn to an SqlConnection, or making the conn variable dynamic. The reason it worked fine before was because cmd was actually a DbCommand variable (even so it pointed to the same object), and the DbCommand.Connection property is of type DbConnection. i.e. the SqlCommand class has a new definition of the Connection property. Source issues annotated: public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject(); ex.TableName = "Products"; using (var conn = OpenConnection()) { //'conn' is statically typed to 'DBConnection' var cmd = CreateCommand(ex); //because 'ex' is dynamic 'cmd' is dynamic cmd.Connection = conn; /* 'cmd.Connection = conn' is bound at runtime and the runtime signature of Connection takes a SqlConnection value. You can't assign a statically defined DBConnection to a SqlConnection without cast. */ } Console.WriteLine("It will never get here!"); Console.Read(); return null; } Options for fixing source (pick only 1): * *Cast to statically declare conn as a SqlConnection: using (var conn = (SqlConnection) OpenConnection()) *Use runtime type of conn: using (dynamic conn = OpenConnection()) *Don't dynamic bind CreateCommand: var cmd = CreateCommand((object)ex); *Statically define cmd: DBCommand cmd = CreateCommand(ex);
{ "language": "en", "url": "https://stackoverflow.com/questions/7562205", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "39" }
Q: .htaccess redirect to both index.html and .php Currently I have a landing page html witch the domain points to but if I access /index.php it redirects back to index.html. How could I make the index.php accessible? RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} ^$ RewriteCond %{HTTP_HOST} ^domain.co.nz$ RewriteRule ^$ http://domain.co.nz/index.html [L,R=301] A: You are redireting everything to the html file. Try: # Enable rewiting RewriteEngine on Options +FollowSymLinks # set 'default' file DirectoryIndex index.html # everything else goes to the index.php file, except your sites assets/ RewriteCond $1 !^(index\.php|index\.html|images|css|javascript) RewriteRule ^(.*)$ /index.php/$1
{ "language": "en", "url": "https://stackoverflow.com/questions/7562206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show some certain columns in datagridview in C# After querying from database, I fill the result into dataset, suppose there are 10 columns. And then i have to show 5 of the 10 columns into datagridview. My way is to create a new DataTable with the 5 columns, and copy the value from the original dataset. It works, but i don't think it's a good way. Any suggestion? ----------------------- I am using C# for Form Application. I prefer programic way to implement. A: You can hide selected column by setting Visible to false, like datagridview.Columns[0].Visible = false A: Assuming that you set the dataset as the datasource of the gridview, you can specify which columns do you want to display in the gridview by clicking on the > button in the design view and selecting edit columns. Please see the following article: http://msdn.microsoft.com/en-us/library/ms972948.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/7562209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to display code inside a block how can i display code inside blocks like stackoverflow does this: <p> <strong> strong text <em> strong and emphasised text </em> </strong> <em> just emphasised text </em> </p> note: i have all the text wrapped around a div and retrieved from a database thanks A: The characters making up the HTML code are converted into their corresponding HTML entities... <pre> <code> &lt;p&gt; &lt;strong&gt; strong text &lt;em&gt; strong and emphasised text &lt;/em&gt; &lt;/strong&gt; &lt;em&gt; just emphasised text &lt;/em&gt; &lt;/p&gt; </code> </pre> A: If you want to grab code, then convert it for viewing, just replace the < with &lt; and > with &gt;. Here is a simple demo doing just that. var html = $('#html').html(), code = $.trim(html); // remove leading & trailing carriage returns // replace angled brackets code = code.replace(/[<>]/g, function(m){ return { '<' : '&lt;', '>' : '&gt;' }[m]; }); $('pre').html(code);
{ "language": "en", "url": "https://stackoverflow.com/questions/7562211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: copyright symbol getting converted to? I have a word document which I want to convert into a pdf. However, the copyright symbol keeps getting converted as a question mark '?' So I cannot upload it into Joomla. Any suggestions? A: If you can print the word document out correctly then you should be able to convert it to a PDF file using a PDF printer. My personal choice of preference is Bullzip which can turn anything to PDF, also to PNG, TIFF and other formats as well. It's very versatile & it's free. Here's the link to it: http://www.bullzip.com/products/pdf/info.php Try it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rails 3.1 routing error, Named parameter not working I have a route setup for downloading a document which I need a named parameter for the document name so I get the doc name on the download document. I'm also passing a few unnamed parameters to identify the document. Looks like this: match "download/:name", :to => 'documents#download', :as => "doc_download" And I have my link setup like this: <%= link_to doc.pdf_name, doc_download_url(doc.pdf_name, :prefix => doc.doc_prefix,:num => doc.doc_num, :change => doc.doc_change) %> When I run the page I get the following error: No route matches {:controller=>"documents", :action=>"download", :prefix=>"D", :num=>"002", :change=>0, :name=>"sdr_vor_000.pdf"} The weird thing is the route shows up in my rake routes: doc_download /download/:name(.:format) {:controller=>"documents", :action=>"dow nload"} Ideas? Also if I remove the name parameter or make it optional, it works, but doesn't stick the name into the url. It just gets tacked onto the query string. A: Your name parameter contains a period - by default, the part after the period is interpreted as the format, not part of the name parameter. To allow periods in the filename, amend your route like this (tweak the regex to your needs): match "download/:name", :to => 'documents#download', :constraints => { :name => /[a-z0-9\.]+/i }, :as => "doc_download"
{ "language": "en", "url": "https://stackoverflow.com/questions/7562214", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to style RSS/ATOM feeds? One thing I've noticed is that my blog posts show up very different in my RSS feed than on my actual blog. Presumably, this is because CSS doesn't apply to RSS feeds, so layout is messed up. For example, if in my feed I have something like this: <div class="right-floater">Some right-float text!</div> <p>Normal paragraph text.</p> ...on the blog, it will display properly. In the actual RSS feed, it will be laid out sans CSS and the <div> will be to the left of the <p>, presumably. Is there a way to add in a link to CSS stylesheet information to have reader applications load the styles so that things style properly when viewed in an application like Google Reader? A: It depends on the feed reader, but yes, most will ignore CSS entirely. Some (like Google Reader) will pay attention to the style attribute if it's "simple" enough, so you could write: <div style="float: right">Some right-float text!</div> <p>Normal paragraph text.</p> For security reasons (primarily XSS avoidance), CSS has to pass through a filter. Only "known safe" CSS is allowed through.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562222", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add a Basic Authentication header to a MediaElement's Source request to a secure URL resource? In my Silverlight applicatin, I am using Basic Authentication to communicate with my WCF Web Services. Everything works great, until my MediaElement attempts to request a video of a secure URL resource. I get the authentication dialog. Ideally, I would like to include the UID/PWD in the Authorization header of the MediaElement's request, but I do not know how to do this. If this is not possible, how else can I restrict the access of the media element to only my application for the user logged in? A: We solved this with a workaround... When we authenticate the user with our webservices, we add a server side HTTP only cookie for the session. var creds = string.Format("{0}:{1}", user.Username, user.Password); var bcreds = System.Text.Encoding.UTF8.GetBytes(creds); var base64Creds = Convert.ToBase64String(bcreds); HttpCookie httpCookie = new HttpCookie("Authorization", "Basic " + base64Creds); httpCookie.HttpOnly = true; HttpContext.Current.Response.Cookies.Add(httpCookie); Then we created a custom HttpModule to validate this cookie for access to the media files. In the custom handler we can make sure that the IP address of the request matches the session and that the request is actually coming from our Silverlight application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript lookahead regular expression I'm trying to write a regular expression to parse the following string out into three distinct parts. This is for a highlighting engine I'm writing: "\nOn and available after solution." I have a regular expression that's dynamically created for any word a user might input. In the above example, the word is "on". The regular expression expects a word with any amount of white space ([\s]*) followed by the search word (with no -\w following it, eg: on-time, on-wards should not be a valid result. To complicate this, there can be a -,$,< or > symbol following the example, so on-, on> or on$ are valid. This is why there is a negative lookahead after the search word in my regular expression below. There's a complicated reason for this, but it's not relevant to the question. The last part should be the rest of the sentence. In this example, " and available after solution." So, p1 = "\n" p2 = "On" p3 = " and available after solution" I currently have the following regular expression. test = new RegExp('([\\s]*)(on(?!\\-\\w))([$\\-><]*?\\s(?=[.]*))',"gi") The first part of this regular expression ([\\s]*)(on(?!\\-\\w))[$\\-><]*? works as expected. The last part does not. In the last part, what I'm trying to do is force the regular expression engine to match whitespace before matching additional characters. If it can not match a space, then the regular expression should end. However, when I run this regular expression, I get the following results str1 = "\nOn ly available after solution." test.exec(str1) ["\n On ", "\n ", "On"] So it would appear to me that the last positive look ahead is not working. Thanks for any suggestions, and if anyone needs some clarification, let me know. EDIT: It would appear that my regular expression was not matching because I didn't realize the following caveat: You can use any regular expression inside the lookahead. (Note that this is not the case with lookbehind. I will explain why below.) Any valid regular expression can be used inside the lookahead. If it contains capturing parentheses, the backreferences will be saved. Note that the lookahead itself does not create a backreference. So it is not included in the count towards numbering the backreferences. If you want to store the match of the regex inside a backreference, you have to put capturing parentheses around the regex inside the lookahead, like this: (?=(regex)). The other way around will not work, because the lookahead will already have discarded the regex match by the time the backreference is to be saved. A: * *The dot in the character class [.] means a literal dot. Change it to just . if you wish to match any character. *The lookahead (?=.*) will always match and is completely pointless. Change it to (.*) if you just want to capture that part of the string. A: I think the problem is your positive lookahead on(?!\-\w) is trying to match any on that is not followed by - then \w. I think what you want instead is on(?!\-|\w), which matches on that is not followed by - OR \w
{ "language": "en", "url": "https://stackoverflow.com/questions/7562224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Checking iOS application used memory in instruments I want to make sure I'm reading the allocations plug in correctly. I'm testing an iPad app thats receiving memory warnings 1,2 & 3. I want to know the current used up memory from my app, which I think it has to be the "Live Bytes" column? which marks All Allocations to 2.42 MB which I think its low. What do the other columns report? #Transitory, Overall Bytes ? Also if my app uses only 3 MB of memory can it be killed if I get a memory level 3 warning without releasing? Thank you. A: Don't use the Object Allocations instrument for looking at your total memory usage. It does not display the true total memory size of your application, for reasons that I speculate about in my answer here. Instead, pair Object Allocations with the Memory Monitor instrument, the latter of which will show the true total size of your application. I'm willing to bet that it's way larger than the 2.42 MB you're seeing in Object Allocations (for example, I had an application with 700k of memory usage according to ObjectAlloc, but its actual size was ~25 MB in memory). If you are receiving memory warnings on an iPad, your application is probably chewing up quite a bit of memory. Object Allocations is handy for telling you what you have resident in memory, but it's not an accurate indicator of the size of those items. It's also a great tool for showing you steady increases in allocated objects by using the heap shot functionality (the "Mark Heap" button on the left-hand side of the instrument). A: Your memory usage looks fine. Check to see which app is being sent the memory warnings, it is probably not your app assuming your app is not in the background. The only way you should be getting memory warnings is if the app is in the background and another app needs more memory. When I was looking at logs I noticed other apps were getting them while my app was running, other apps such as Mail or navigation apps (Navigon) do run in the background and will cause memory pressure. You might get a memory warning but should not be terminated. For a description of the memory columns see Explanation of Live Bytes & Overall Bytes. As @Brad points out use the memory monitor tool as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Creating memory efficient thumbnails using an NSImageView (cocoa/OSX) I am creating small NSImageViews (32x32 pixels) from large images often 512x512 or even 4096 x 2048 for an extreme test case. My problem is that with my extreme test case, my applicaiton memory footprint seems to go up by over 15MB when I display my thumbnail, this makes me think the NSImage is being stored in memory as a 4096x2048 instead of 32x32 and I was wondering if there is a way to avoid this. Here is the process I go through to create the NsImageView: • First I create an NSImage using initByReferencingFile: (pointing to the 4096x2048 .png file) • Next I initialize the NSImageView with a call to initWithFrame: • Then I call setImage: to assign my NSImage to the NSImageView • Finally I set the NSImageView to NSScaleProportionally I clearly do nothing to force the NSImage to size down to 32x32 but I have had trouble finding a good way to handle this. A: You can simply create a new 32x32 NSImage from the original and then release the original image. First, create the 32x32 image: NSImage *smallImage = [[NSImage alloc]initWithSize:NSMakeSize(32, 32)]; Then, lock focus on the image and draw the original on to it: NSSize originalSize = [originalImage size]; NSRect fromRect = NSMakeRect(0, 0, originalSize.width, originalSize.height); [smallImage lockFocus]; [originalImage drawInRect:NSMakeRect(0, 0, 32, 32) fromRect:fromRect operation:NSCompositeCopy fraction:1.0f]; [smallImage unlockFocus]; Then you may do as you please with the smaller image: [imageView setImage:smallImage]; Remember to release! [originalImage release]; [smallImage release];
{ "language": "en", "url": "https://stackoverflow.com/questions/7562231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Random access to hash map values What's the best way to design such a container, which can support randomized value access? but the container has to support other operations, such as insert key/value pairs and remove by key, with the best possible time performance. One way to do this is to combine hash map with array, but if hash map is used, what's the best way to do random access of hash map values, i.e., without generating a key. A: If you're talking about data structures, and not existing language support - then you just have to design a data structure to support that. You can do that, for example, by implementing a hash map which will hold, in addition, an array of pointers to its members. You can then translate random access operators to that array, and maintain it with every insertion or removal (that is of course a general idea, some implementation details omitted). Some languages support traversing the data structures through iterators. Although looping on an iterator for a random amount of times is not really random access (performance-wise), it will give you the same result in more time. I would say your question sounds like some algorithms' coursework homework. Why would you want to do it in the real life? What is the problem you're trying to solve? edit In the comments you phrased the problem as: what's the best way to design such a container, which can support randomized value access? but the container has to support other operations, such as insert key/value pairs and remove by key, with the best possible performance. My suggestions above hold, but the question is what is the trade-off. If the "best performance" is time-wise, then my suggestion with the array gives you that. If the best performance is memory-wise then the iterating over the tree would give you that, that's my other suggestion. In general, when you come to a need to design a new data structure, you need to answer the following questions: * *What are the operations required? *What is the time complexity required, for each operation? *What is the memory complexity required for the structure? *Which is more important, memory or time? Sometimes you just can't do in O(1) without additional memory. Sometimes you can do in O(1) with additional O(n) memory, but you can make it with O(lg n) memory if you compromise on O(lg n) time. There are trade offs that you have to make your decision about, I don't know them. So my first suggestion (combining a BST or hash with an array of pointers to its nodes) does all the operations of the BST (map) or hash with the standard complexity of BST/hash operations, and all the read operations of array with the standard complexity (i.e.: random access in O(1) time). Write operations of the array will be with complexity of map/hash, and additional memory footprint is O(n). My second suggestion has no additional memory footprint, but the "random" access is pseudo random: you can just iterate to the point you want instead of directly accessing it. That would make your random access in O(n) while zero additional coding, or wasting memory. Name of the game? Trade-offs. A: If you simply want to inspect the key portion of a unorederd_map, use it's iterators. A: If you mean "without inserting a new element", then find() is the preferred method over []: if (auto it = mymap.find("joe") != mymap.end()) { make_phone_call(it->second); } This is particular to ordered and unordered maps, which are unique among the associative containers for providing the intrusive []-operator. For unordered maps, the lookup time is constant on average.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I select variables in an R dataframe whose names contain a particular string? Two examples would be very helpful for me. How would I select: 1) variables whose names start with b or B (i.e. case-insensitive) or 2) variables whose names contain a 3 df <- data.frame(a1 = factor(c("Hi", "Med", "Hi", "Low"), levels = c("Low", "Med", "Hi"), ordered = TRUE), a2 = c("A", "D", "A", "C"), a3 = c(8, 3, 9, 9), b1 = c(1, 1, 1, 2), b2 = c( 5, 4, 3,2), b3 = c(3, 4, 3, 4), B1 = c(3, 6, 4, 4)) A: I thought it was worth adding that select_vars is retired as of tidyverse version 1.2.1. Now, tidyselect::vars_select() is likely what you're looking for within the "tidyverse". See the documentation here. A: If you just want the variable names: grep("^[Bb]", names(df), value=TRUE) grep("3", names(df), value=TRUE) If you are wanting to select those columns, then either df[,grep("^[Bb]", names(df), value=TRUE)] df[,grep("^[Bb]", names(df))] The first uses selecting by name, the second uses selecting by a set of column numbers. A: While I like the answer above, I wanted to give a "tidyverse" solution as well. If you are doing a lot of pipes and trying to do several things at once, as I often do, you may like this answer. Also, I find this code more "humanly" readable. The function tidyselect::vars_select will select variables from a character vector in the first argument, which should contain the names of the corresponding data frame, based on a select helper function like starts_with or matches library(dplyr) library(tidyselect) df <- data.frame(a1 = factor(c("Hi", "Med", "Hi", "Low"), levels = c("Low", "Med", "Hi"), ordered = TRUE), a2 = c("A", "D", "A", "C"), a3 = c(8, 3, 9, 9), b1 = c(1, 1, 1, 2), b2 = c( 5, 4, 3,2), b3 = c(3, 4, 3, 4), B1 = c(3, 6, 4, 4)) # will select the names starting with a "b" or a "B" tidyselect::vars_select(names(df), starts_with('b', ignore.case = TRUE)) # use select in conjunction with the previous code df %>% select(vars_select(names(df), starts_with('b', ignore.case = TRUE))) # Alternatively tidyselect::vars_select(names(df), matches('^[Bb]')) Note that the default for ignore.case is TRUE, but I put it here to show explicitly, and in case future readers are curious how to adjust the code. The include and exclude arguments are also very useful. For example, you could use vars_select(names(df), matches('^[Bb]'), include = 'a1') if you wanted everything that starts with a "B" or a "b", and you wanted to include "a1" as well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Flash banner, how to give it an (external) html link Is there a cross-browser solution available to give a flash banner an html link, without putting it into the flash itself? (i.e. the Flash has no clickable button in it) I tried giving the surrounding anchor tag a high z-index, but that did not work. I'm using the standard google swfobject to include the flash banner, but am not stuck on using that. Thanks A: Could always have Flash handle the click and pass it up to Javascript through ExternalInterface. Then have your Javascript respond to the call and move the user to the new location. Note, this will only work if the user has Javascript enabled. Javascript code: function myCustomFlashCallMethod() { alert("Hello world!"); } Flash Code: addEventListener(MouseEvent.CLICK, onMouseClick, false, 0, true); function onMouseClick(event:MouseEvent):void { if (ExternalInterface.available) { ExternalInterface.call("myCustomFlashCallMethod"); } } ExternalInterface class reference: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html Adobe's "Using ExternalInterface" write-up: http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7cb2.html A: Yes, there is! Here is the trick: Place your flash banner beside (not inside) the anchor tag and set its wmode="opaque". Also you need to set the position, display and z-index styles of your anchor tag. <div style="position:relative;"> <a href="http://your-target-url" style="position:absolute; top:0; left:0; display:block; width:100%; height:100%; z-index:100;">&nbsp;</a> <embed src="your-flash-banner" type="application/x-shockwave-flash" wmode="opaque"></embed> </div> Edited: To work on IE you have to make it abit dirty. Add one of these styles to the anchor tag too: background:url(spacer.gif); where spacer.gif is a 1px transparent gif. or background-color:#ffffff; /* the background */ filter:alpha(opacity=0); /* Internet Explorer */ -moz-opacity:0; /* Mozilla 1.6 and below */ opacity: 0; /* newer browser and CSS-3 */ This is another IE bug that does not accept clicks on transparent links with display:block.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show a div thats hidden by css on button click I'm pretty new to Jquery and i want to have a hidden div css: display:none and once a button has been clicked the $(..).slideDown will execute and the div will show its conents. I try'd this. <style> .hidden-div{ display:none } </style> <div class="hidden-div"> You can't see me </div> <button onclick="show-div()"> Show Above Div </button> <script> function show-div(){ $('.hidden-div').slideDown('fast'); // more stuff... } </script> This dont really slide it down properly as it overlaps everything else ? Also i try'd just setting the class="hidden-div" to class="display-div" but then the slideDown animation cannot be executed. Now i could say $('hidden-div').hide() just after the div and remove the css altogether but it creates this problem where i see the div and then it gets hidden, its only 0.5sec thing at the start of the page load but its look bad. So anyone know a solution? Found a solution to my own problem.. //rehide the div, not sure why, but it works. $('.hidden-div').hide(); //change class so it no longer display:none //but it will not show the div as .hide() was execute above. $('.hidden-div').attr('class','showing-div'); //Slide it down and everything works. $('.hidden-div').slideDown('fast'); //this can be done in 1 liner. (thank you, Mohsen for chaining explanation) $('.hidden-div').hide().attr('class','showing-div').slideDown('fast'); Hope this is helpful for someone else. A: it's better to use standard javascript and point to that div with id <style> .hidden-div{ display:none } </style> <div class="hidden-div" id="hidden-div"> You can't see me </div> <button onclick="getElementById('hidden-div').style.display = 'block'"> Show Above Div </button> A: $('.hidden-div').show('fast'); Try using < and > instead of [ and ], and format everything properly? A: In your javascript, first remove the class 'hidden-div' using jQuery function removeClass(). See if that helps... A: * *bind events via jQuery, don't use inline JavaScript method *jQuery SlideDown method is not for removing an element. You can use hide or fadeOut *BTW if you want to have an slide down effect and then hiding the element you can chain two methods. *To prevent overlaping you need to use CSS. You can use position:absolute or give a certain height to element's parent. To have both slide down and fade effects and also binding the event using non-inline code you can use this code: $('button').bind('click', function(){ $('.hidden-div').slideDown(500).fadeOut(1000); //500ms slide down and 1s fade out }) Remove that disply:none from the hidden-div class too.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: objective-c block vs selector. which one is better? In objective-c when you are implementing a method that is going to perform a repetitive operations, for example, you need to choice in between the several options that the language brings you: @interface FancyMutableCollection : NSObject { } -(void)sortUsingSelector:(SEL)comparator; // or ... -(void)sortUsingComparator:(NSComparator)cmptr; @end I was wondering which one is better? Objective-c provides many options: selectors, blocks, pointers to functions, instances of a class that conforms a protocol, etc. Some times the choice is clear, because only one method suits your needs, but what about the rest? I don't expect this to be just a matter of fashion. Are there any rules to know when to use selectors and when to use blocks? A: The one that's better is whichever one works better in the situation at hand. If your objects all implement a comparison selector that supports the ordering you want, use that. If not, a block will probably be easier. A: The main difference I can think of is that with blocks, they act like closures so they capture all of the variables in the scope around them. This is good for when you already have the variables there and don't want to create an instance variable just to hold that variable temporarily so that the action selector can access it when it is run. With relation to collections, blocks have the added ability to be run concurrently if there are multiple cores in the system. Currently in the iPhone there isn't, but the iPad 2 does have it and it is probable that future iPhone models will have multiple cores. Using blocks, in this case, would allow your app to scale automatically in the future. In some cases, blocks are just easier to read as well because the callback code is right next to the code that's calling it back. This is not always the case of course, but when sometimes it does simply make the code easier to read. Sorry to refer you to the documentation, but for a more comprehensive overview of the pros/cons of blocks, take a look at this page. As Apple puts it: Blocks represent typically small, self-contained pieces of code. As such, they’re particularly useful as a means of encapsulating units of work that may be executed concurrently, or over items in a collection, or as a callback when another operation has finished. Blocks are a useful alternative to traditional callback functions for two main reasons: They allow you to write code at the point of invocation that is executed later in the context of the method implementation. Blocks are thus often parameters of framework methods. They allow access to local variables. Rather than using callbacks requiring a data structure that embodies all the contextual information you need to perform an operation, you simply access local variables directly. On this page
{ "language": "en", "url": "https://stackoverflow.com/questions/7562256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: signed vs unsigned int in C I am a C beginner and needed a quick clarification regarding ints. When you cast something as an int, which is 32 bits, half of the bits are allocated for negative integers. Thus, if you know that you will always have positive integers, casting something as an unsigned int should maximize your positive bits and thus make more sense when you know that output will always be positive. Is this true? Thank you! A: half of the bits are allocated for negative integers This statement is not true, one bit is allocated to the sign for regular ints. However, you are correct in your assumption. If you are positive the number is positive, using unsigned int will allow you to access number in the range [0,2^32), while the regular int will only only allow [-(2^31),2^31-1], since you do not need the negative values, it leaves you with less positive numbers. A: Not half the bits, just one bit which translates to half of the values. Also not casting but declaring: If you cast something you are reinterpreting it which doesn't give you additional range, it just gives you a potentially different value than the original user intended. A: Only one bit is used to identify whether the number is positive or negative. Casting to unsigned may or may not make sense. Sometimes it's best to have debugger, et al, show the negative number, to make you aware that your number has gone out of range. You especially need to be careful when comparing unsigned numbers -- many a loop has failed to terminate because the countdown value was unsigned and the compare was for < 0. A: One bit is used for +/-, not half. Using unsigned numbers gives you double the range of positive values vs. the signed equivalent.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562257", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to pass data to detail view after being selected in a table view? I have a UITableViewController that has data populated from an NSMutableArray called userList. When specific user is selected, it goes to a detail view, and updates the title in the NavBar, but it wont pass the data to update a UILabel in the UIView. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:NO]; //Attempt at a singleton to pass the data DetailView *details = [[DetailView alloc] init]; details.userNameLbl = [userList objectAtIndex:indexPath.row]; DetailView *detailVC = [[DetailView alloc] initWithNibName:nil bundle:nil]; //This line doesn't pass the data detailVC.userNameLbl.text = [userList objectAtIndex:indexPath.row]; //This line does update the title in the NavBar detailVC.navigationItem.title = [userList objectAtIndex:indexPath.row]; [self.navigationController pushViewController:detailVC animated:YES]; [details release]; [detailVC release]; } Should I be trying to push the data from the table view to the detail view, or have the detail view try to pull the data from the table view? DetailView.h has the following line that is in fact hooked up in IB. IBOutlet UILabel *userNameLbl A: Are you mixing UIViews and UIViewControllers? You should have a DetailViewController class that inherits from UIViewController or some sublcass (like UITableViewController); it will have DetailViewController.m and DetailViewController.h files to declare and define your class. It should have a corresponding nib that defines the UIView that the UIViewController loads; it will have a DetailView.xib file. You can't assign the value to the UILabel directly because UIView hasn't been loaded at the time you need to assign the user name value. In order to do what you want, you should declare a public property (userName) to "push" the value onto the detail view controller from the master controller. Once the detail view is loaded, it can assign the value from the property to the label and nav bar. In your master view controller (UITableViewController): - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:NO]; DetailViewController *detailVC = [[DetailView alloc] initWithNibName:@"DetailView" bundle:nil]; detailVC.userName = [userList objectAtIndex:indexPath.row]; [self.navigationController pushViewController:detailVC animated:YES]; [detailVC release]; } In your detail view controller: DetailViewController.h @property (retain) NSString* userName; @property (nonatomic, retain) IBOutlet UILabel *userNameLbl; DetailViewController.m @synthesize userName; @synthesize userNameLbl; -(void) viewDidLoad { [super viewDidLoad]; self.userNameLbl.text = self.userName; self.navigationItem.title = self.userName; } A: The userNamelbl isn't instantiated until the view is loaded from the nib file. This doesn't happen immediately at initialisation, but will have happened by the time viewDidLoad is called. So, you should to declare a property in DetailView to store your title, and then assign that value to userNamelbl.text in the viewDidLoad method. For example, in your table viewController: DetailView *detailVC = [[DetailView alloc] initWithNibName:nil bundle:nil]; detailVC.userName = [userList objectAtIndex: indexPath.row]; and in your detail viewController: - (void) viewDidLoad { [super viewDidLoad]; self.userNameLbl.text = self.userName; } The viewController's navigationItem property is created when the viewController is initialised, hence you can assign to the navigationItem.title immediately. Swift code let detailVC = DetailView(nibName: nil, bundle: nil) detailVC.userName = userList.objectAtIndex(indexPath.row) as? NSString and class DetailView: UIViewController { @IBOutlet var userNameLbl: UILabel var userName:NSString? override func viewDidLoad() { super.viewDidLoad() self.userNameLbl.text = self.userName } } A: Presumably your DetailView requires the data from your selected row to function? If so, I'd say the 'correct' approach would be to create a custom init method that passed in the data you required. For example: [[DetailView alloc] initWithTitle:(NSString *)title text:(NSString *)text] There's nothing inherently wrong with your approach, but passing the data the view controller requires at its creation is architecturally better (in my opinion, I'm sure someone will disagree!). For example, think of a table view controller - you pass in the table view style in the init method, you don't set it later on. Same for a UIImageView - you have an initWithImage method that lets you set the image at creation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Why does the xml.sax parser in Jython 2.5.2 turn two-character attributes in to tuples? When ever I encounter a 2-character attribute in my XML stream when parsing with xml.sax under Jython 2.5.2 it converts the attribute name to a tuple. No amount of coercion of that name allows me to extract the value for the attribute. I tried passing the tuple or converting it to a string and passing that. Both cases result in: Traceback (most recent call last): File "test.py", line 18, in startElement print '%s = %s' % (k, attrs.getValue(k)) File "/usr/local/Cellar/jython/2.5.2/libexec/Lib/xml/sax/drivers2/drv_javasax.py", line 266, in getValue value = self._attrs.getValue(_makeJavaNsTuple(name)) TypeError: getValue(): 1st arg can't be coerced to String, int I've got some sample code you can run that shows the problem: import xml from xml import sax from xml.sax import handler import traceback class MyXMLHandler( handler.ContentHandler): def __init__(self): pass def startElement(self, name, attrs): for k in attrs.keys(): print 'type(k) = %s' % type(k) if isinstance(k, (list, tuple)): k = ''.join(k) print 'type(k) = %s' % type(k) print 'k = %s' % k try: print '%s = %s' % (k, attrs.getValue(k)) except Exception, e: print '\nError:' traceback.print_exc() print '' if __name__ == '__main__': s = '<TAG A="0" AB="0" ABC="0"/>' print '%s' % s xml.sax.parseString(s, MyXMLHandler()) exit(0) When run, the AB attribute is returned as a tuple but the A and ABC attributes are unicode strings and function properly with the get() method on the Attribute object. Under Jython 2.5.2 this outputs, for me: > jython test.py <TAG A="0" AB="0" ABC="0"/> type(k) = <type 'unicode'> type(k) = <type 'unicode'> k = A A = 0 type(k) = <type 'tuple'> type(k) = <type 'unicode'> k = AB Error: Traceback (most recent call last): File "test.py", line 18, in startElement print '%s = %s' % (k, attrs.getValue(k)) File "/usr/local/Cellar/jython/2.5.2/libexec/Lib/xml/sax/drivers2/drv_javasax.py", line 266, in getValue value = self._attrs.getValue(_makeJavaNsTuple(name)) TypeError: getValue(): 1st arg can't be coerced to String, int type(k) = <type 'unicode'> type(k) = <type 'unicode'> k = ABC ABC = 0 This code functions correctly under Python 2.7.2 on OS X and Python 2.4.3 on CentOS 5.6. I dug around Jython bugs but couldn't find anything similar to this issue. Is it a known Jython xml.sax handling problem? Or have I messed up something in my Handler that's 2.5.2 incompatible? Edit: this appears to be a Jython 2.5.2 bug. I found a reference to it: http://sourceforge.net/mailarchive/message.php?msg_id=27783080 -- suggestions for a workaround welcome. A: So, this is a reported bug in Jython. It took some digging but I found it in their bug archive: http://bugs.jython.org/issue1768 The second comment on the bug provides a work-around for the issue: use the _attrs.getValue() method to retrieve values off the attributes list. Like so: attrs._attrs.getValue('id') My re-written code works if I change the line: print '%s = %s' % (k, attrs.getValue(k)) to: print '%s = %s' % (k, attrs._attrs.getValue(k)) The more flexible works-in-python-and-jython solution is to build a helper: def _attrsGetValue(attrs, name, default=None): value = None if 'jython' in sys.executable.lower(): value = attrs._attrs.getValue(name) if not name: value = default else: value = attrs.get(name, default) return value
{ "language": "en", "url": "https://stackoverflow.com/questions/7562272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to stop flash from overlapping popup content I'm working on a site and the popup windows are going under the flash banner. I've tested this in FF7 and Chromium. I have no idea how can I fix that. Here is the link, I also attached an image. Any suggestion how can I fix this? A: Add wmode="opaque" to the params. A: Set wmode=opaque or wmode=transparent on the SWF. See http://kb2.adobe.com/cps/155/tn_15523.html for more information.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562275", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why #define is bad? Possible Duplicate: When are C++ macros beneficial? Why is #define bad and what is the proper substitute? Someone has told me that #define is bad. Well, I honestly don't not understand why its bad. If its bad, then what other way can I do this then? #include <iostream> #define stop() cin.ignore(numeric_limits<streamsize>::max(), '\n'); A: #define is not inherently bad. However, there are usually better ways of doing what you want. Consider an inline function: inline void stop() { cin.ignore(numeric_limits<streamsize>::max(), '\n'); } (Really, you don't even need inline for a function like that. Just a plain ordinary function would work just fine.) A: It's bad because it's indiscriminate. Anywhere you have stop() in your code will get replaced. The way you solve it is by putting that code into its own method. A: It's not necessarily bad, it's just that most things people have used it for in the past can be done in a much better way. For example, that snippet you provide (and other code macros) could be an inline function, something like (untested): static inline void stop (void) { cin.ignore(numeric_limits<streamsize>::max(), '\n'); } In addition, there are all the other things that code macros force you to do "macro gymnastics" for, such as if you wanted to call the very badly written: #define f(x) x * x * x + x with: int y = f (a + 1); // a + 1 * a + 1 * a + 1 + a + 1 (4a+2, not a^3+a) int z = f (a++); // a++ * a++ * a++ + a++ The first of those will totally surprise you with its results due to the precedence of operators, and the second will give you undefined behaviour. Inline functions do not suffer these problems. The other major thing that macros are used for is for providing enumerated values such as: #define ERR_OK 0 #define ERR_ARG 1 : : #define ERR_MEM 99 and these are better done with enumerations. The main problem with macros is that the substitution is done early in the translation phase, and information is often lost because of this. For example, a debugger generally doesn't know about ERR_ARG since it would have been substituted long before the part of the translation process that creates debugging information. But, having maligned them enough, they're still useful for defining simple variables which can be used for conditional compilation. That's pretty much all I use them for in C++ nowadays. A: In C++, using #define is not forcibly bad, although alternatives should be preferred. There are some context, such as include guards in which there is no other portable/standard alternative. It should be avoided because the C preprocessor operates (as the name suggests) before the compiler. It performs simple textual replacement, without regard to other definitions. This means the result input to the compiler sometimes doesn't make sense. Consider: // in some header file. #define FOO 5 // in some source file. int main () { // pre-compiles to: "int 5 = 2;" // the compiler will vomit a weird compiler error. int FOO = 2; } This example may seem trivial, but real examples exist. Some Windows SDK headers define: #define min(a,b) ((a<b)?(a):(b)) And then code like: #include <Windows.h> #include <algorithm> int main () { // pre-compiles to: "int i = std::((1<2)?(1):(2));" // the compiler will vomit a weird compiler error. int i = std::min(1, 2); } When there are alternatives, use them. In the posted example, you can easily write: void stop() { cin.ignore(numeric_limits<streamsize>::max(), '\n'); } For constants, use real C++ constants: // instead of #define FOO 5 // prefer static const int FOO = 5; This will guarantee that your compiler sees the same thing you do and benefit you with name overrides in nested scopes (a local FOO variable will override the meaning of global FOO) as expected. A: #define by itself is not bad, but it does have some bad properties to it. I'll list a few things that I know of: "Functions" do not act as expected. The following code seems reasonable: #define getmax(a,b) (a > b ? a : b) ...but what happens if I call it as such?: int a = 5; int b = 2; int c = getmax(++a,b); // c equals 7. No, that is not a typo. c will be equal to 7. If you don't believe me, try it. That alone should be enough to scare you. The preprocessor is inherently global Whenever you use a #define to define a function (such as stop()), it acts across ALL included files after being discovered. What this means is that you can actually change libraries that you did not write. As long as they use the function stop() in the header file, you could change the behavior of code you didn't write and didn't modify. Debugging is more difficult. The preprocessor does symbolic replacement before the code ever makes it to the compiler. Thus if you have the following code: #define NUM_CUSTOMERS 10 #define PRICE_PER_CUSTOMER 1.10 ... double something = NUM_CUSTOMERS * PRICE_PER_CUSTOMER; if there is an error on that line, then you will NOT see the convenient variable names in the error message, but rather will see something like this: double something = 10 * 1.10; So that makes it more difficult to find things in code. In this example, it doesn't seem that bad, but if you really get into the habit of doing it, then you can run into some real headaches.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ShowWindowAsync doesn't activate a hidden+minimized window? A given external (not owned by the current process) window (hWnd) is first minimized, then hidden: ShowWindowAsync(hWnd, SW_MINIMIZE); // wait loop inserted here ShowWindowAsync(hWnd, SW_HIDE); The following call properly restores it to the un-minimized (restored) state: ShowWindow(hWnd, SW_RESTORE); However, this call does not: ShowWindowAsync(hWnd, SW_RESTORE); In the second instance with ShowWindowAsync(), the window is un-minimized and no longer hidden, but it is not activated (remains behind other existing windows). Conversely, the first ShowWindow() call correctly activates the window. Is this expected behavior? How can I restore the window (to the foreground) without relying on ShowWindow(), which is synchronous (blocking)? (The wait loop in the example can have a timeout, while ShowWindow() does not allow specification of a timeout.) (WinXP SP3) A: ShowWindowAsync posts a show-window event to the message queue of the given window. In particular, the window is shown by its thread, rather than your thread. And the difference is that your thread is the foreground thread, and can therefore activate another window, which it can't do itself. A: Here's the solution as used: ShowWindowAsync(hWnd, SW_SHOW); // wait loop inserted here ShowWindowAsync(hWnd, SW_RESTORE); This is essentially an inversion of the snippet used to hide the window: ShowWindowAsync(hWnd, SW_MINIMIZE); // wait loop inserted here ShowWindowAsync(hWnd, SW_HIDE);
{ "language": "en", "url": "https://stackoverflow.com/questions/7562280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extracting unique rows from a data table in R I'm migrating from data frames and matrices to data tables, but haven't found a solution for extracting the unique rows from a data table. I presume there's something I'm missing about the [,J] notation, though I've not yet found an answer in the FAQ and intro vignettes. How can I extract the unique rows, without converting back to data frames? Here is an example: library(data.table) set.seed(123) a <- matrix(sample(2, 120, replace = TRUE), ncol = 3) a <- as.data.frame(a) b <- as.data.table(a) # Confirm dimensionality dim(a) # 40 3 dim(b) # 40 3 # Unique rows using all columns dim(unique(a)) # 8 3 dim(unique(b)) # 34 3 # Unique rows using only a subset of columns dim(unique(a[,c("V1","V2")])) # 4 2 dim(unique(b[,list(V1,V2)])) # 29 2 Related question: Is this behavior a result of the data being unsorted, as with the Unix uniq function? A: As mentioned by Seth the data.table package has evolved and now proposes optimized functions for this. To all the ones who don't want to get into the documentation, here is the fastest and most memory efficient way to do what you want : uniqueN(a) And if you only want to choose a subset of columns you could use the 'by' argument : uniqueN(a,by = c('V1','V2')) EDIT : As mentioned in the comments this will only gives the count of unique rows. To get the unique values, use unique instead : unique(a) And for a subset : unique(a[c('V1',"V2")], by=c('V1','V2')) A: Before data.table v1.9.8, the default behavior of unique.data.table method was to use the keys in order to determine the columns by which the unique combinations should be returned. If the key was NULL (the default), one would get the original data set back (as in OPs situation). As of data.table 1.9.8+, unique.data.table method uses all columns by default which is consistent with the unique.data.frame in base R. To have it use the key columns, explicitly pass by = key(DT) into unique (replacing DT in the call to key with the name of the data.table). Hence, old behavior would be something like library(data.table) v1.9.7- set.seed(123) a <- as.data.frame(matrix(sample(2, 120, replace = TRUE), ncol = 3)) b <- data.table(a, key = names(a)) ## key(b) ## [1] "V1" "V2" "V3" dim(unique(b)) ## [1] 8 3 While for data.table v1.9.8+, just b <- data.table(a) dim(unique(b)) ## [1] 8 3 ## or dim(unique(b, by = key(b)) # in case you have keys you want to use them Or without a copy setDT(a) dim(unique(a)) ## [1] 8 3
{ "language": "en", "url": "https://stackoverflow.com/questions/7562284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "28" }
Q: How does a PHP script send an JSON Ajax response to Dojo's xhrGet? I just started using dojo and I'm onto using Ajax in dojo via xhrGet. I understand that whatever you "echo" in PHP is what is returned as the Ajax result, however how does this work with JSON? Does the PHP script echo javascript code that is then directly accessed from the function called by xhrGet? I'm trying to have a PHP script retrieve data from the database, populate three arrays, and make them available in my javascript code, all with xhrGet. Thanks! A: Set the header with PHP before you echo: <?php header('Content-type: application/json'); echo '{"myJsonKey":"myJsonVal"}'; For your specific case, you'd do something like this: <?php $my_records_array = fetch_records($some_criteria); $my_records_json = json_encode($my_records_array); header('Content-type: application/json'); echo $my_records_json; A: Most JavaScript libraries wrap a callback around the AJAX request. I'm not sure about Dojo, but jQuery adds a callback param to the URL when it's sent. Then, when the server responds it triggers that callback which calls your callback to handle the result. As for the actual server side stuff, the server usually just prints the JSON encoded string and passes along an extra header letting the browser know what type of content it is. <?php $rows = $db->fetch($sql); header('Content-type: application/json'); print json_encode($rows); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7562290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: NHibernate Parent Child Mapping I have a parent/child database relationship between the table ACCOUNT and the table USER. Currently I have mapped a bi-directional Fluent mappings like this: public class Account { public virtual IList<User> ListUsers { get; private set; } public virtual void AddUser(User user) { user.Account = this; ListUsers.Add(user); } } MAPPING: HasMany(x => x.ListUsers).Table("UserInfo").KeyColumn("Id_Account").Inverse().Cascade.All().AsList(); public class User { public virtual Account Account { get; set; } public string Username { get; set; } } MAPPING: References(x => x.Account).Column("Id_Account"); In practice I cannot foresee that I will ever want to reference the Account entity from the User entity. Likewise I cannot foresee my wanting to load all of the User entities from the parent Accounts entity. I am fairly new to NHibernate and was wondering is the above method still the best way to go performance wise? Is a bi-directional relationship preferred and should I look to referencing the Id only? Thanks A: * *bi-directional references is the correct approach, in my opinion. If you use lazy-loading on the Account property, then it would only load the account's id anyway. *you specified that the ListUsers property is inverse=true, meaning the User entity is responsible for saving the reference. Therefore, I believe (if I remember correctly) that the line ListUsers.Add(user); is not necessary, since the association will be created by the User entity. So this means that you don't have to load the entire ListUsers collection from the db when you add a user.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Three20 'Back' button on WebController not functioning I am using Three20's WebController in my project and I am having issues with the 'back' arrow on the bottom controls (the <| button). When I load a page and click a link in the WebController you'd expect the back button to enable and if touched bring you back to the original page. But when I hit a link from the original page the back button is not always working, it stays disabled therefore you cannot go back to the original page. It does sometimes work, but it seems random and its rare it does. I looked in the source for three20's WebController and all its doing is using a UIWebView's goBack function. But as I said it does work sometimes, but not most of the time. I have searched the net but found no other reports of this issues, does anyone have any suggestions? Thanks! A: I was able to find my solution. I traced the code and [_webView canGoBack] was returning NO, it was because I was not loading a request, I was rather loading an HTML string which wasn't being saved for use in the back button. I changed my code back to loading requests and it fixed the issue. Solution was found here: http://www.iphonedevsdk.com/forum/iphone-sdk-development/18870-uiwebview-cangoback-always-returns-no.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7562295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting stack trace info for a ruby warning I've been running into some strange errors with UTF strings in ruby 1.9. Often ruby will complain on something like this: warning: regexp match /.../n against to UTF-8 string I'd like to be able to show a full stack trace on a warning, or apply some kind of monkey patch that i can override the default warning functionality. How would i do this? A: If the warning comes from Ruby code(instead of native C), you can overwrite Warning#warn, then the warning becomes an exception you will get the backtrace of course: module Warning def warn(msg) raise msg end end Thanks to: Can you ask ruby to treat warnings as errors? A: Try $DEBUG = true. That will cause at least some warnings to turn into errors.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562307", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Selected columns from DataTable How to get the Selected columns form the DataTable? For e.g my BaseTable has three columns, ColumnA, ColumnB and ColumnC. Now as part of intermediate operations, I need to retrieve all the rows only from the ColumnA. Is there any predefined formula just like DataTable.Select? A: DataView.ToTable Method. DataView view = new DataView(MyDataTable); DataTable distinctValues = view.ToTable(true, "ColumnA"); Now you can select. DataRow[] myRows = distinctValues.Select(); A: From this question: How to select distinct rows in a datatable and store into an array you can get the distinct values: DataView view = new DataView(table); DataTable distinctValues = view.ToTable(true, "ColumnA"); If you're dealing with a large DataTable and care about the performance, I would suggest something like the following in .NET 2.0. I'm assuming the type of the data you're displaying is a string so please change as necessary. Dictionary<string,string> colA = new Dictionary<string,string>(); foreach (DataRow row in table.Rows) { colA[(string)row["ColumnA"]] = ""; } return colA.Keys;
{ "language": "en", "url": "https://stackoverflow.com/questions/7562310", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Referencing files located in another directory in program I am currently working on a server. I've created my own directory but need access to files located in a different directory on the server. Basically, I have code that needs access to the files located in another directory on the server but I do not know how to go about doing this. Is there a command in my code that I can add or is there something on the command line i can type? The error I get in my code looks like this: [aburac1][mcbbigram][/ruths/data/aburac1] python get-contribs.py Traceback (most recent call last): File "get-contribs.py", line 96, in <module> fec_files = filter(lambda x: x.endswith('.fec'),os.listdir(dname)) OSError: [Errno 2] No such file or directory: '1001015' The file 1001015 is located in the directory /ruths/data/fec/efr. So how do I get access to those files from my directory? A: os.chdir("/ruths/data/fec/efr") A: You can specify the whole path when you enter a file name. For example, say you want to open a file "foo.txt" in the directory "/home/docs". You could run the command: f = open("/home/docs/foo.txt") where f is now a handle for your file. Alternatively, the command os.chdir from the module os changes the current working directory. The following snippet has the same effect as above: import os os.chdir("/home/docs") f = open("foo.txt")
{ "language": "en", "url": "https://stackoverflow.com/questions/7562313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php: textarea excel paste to array I know this might ma a simple question, it must have been answered before but it's the kind of question you don't know how to google for. I'm doing an intranet and I have a big texarea in wich te user pastes a 5columns X 365 rows (an optional first column with the 1 to 365 numbers) from excel and ends up in this: 1 $ 37 $ 74 $ 111 $ 148 $ 185 2 $ 37 $ 74 $ 111 $ 148 $ 185 3 $ 37 $ 74 $ 111 $ 148 $ 185 4 $ 37 $ 74 $ 111 $ 148 $ 185 5 $ 37 $ 74 $ 111 $ 148 $ 185 6 $ 57 $ 114 $ 171 $ 228 $ 285 7 $ 57 $ 114 $ 171 $ 228 $ 285 8 $ 57 $ 114 $ 171 $ 228 $ 285 9 $ 57 $ 114 $ 171 $ 228 $ 285 10 $ 57 $ 114 $ 171 $ 228 $ 285 How can I turn this into a php array so I can then insert it into a mysql table? I tought about using explode() but I'm not sure if the space between each column will always be the same, maybe there's a fancier way to do this. If this is already discussed somewhere else just point me to it. Thanks a lot A: Explode per ligne '\n' and then per column '\t' and just ignore the $ <?php $str = " 1 $ 37 $ 74 $ 111 $ 148 $ 185 2 $ 37 $ 74 $ 111 $ 148 $ 185 3 $ 37 $ 74 $ 111 $ 148 $ 185 4 $ 37 $ 74 $ 111 $ 148 $ 185 5 $ 37 $ 74 $ 111 $ 148 $ 185 6 $ 57 $ 114 $ 171 $ 228 $ 285 7 $ 57 $ 114 $ 171 $ 228 $ 285 8 $ 57 $ 114 $ 171 $ 228 $ 285 9 $ 57 $ 114 $ 171 $ 228 $ 285 10 $ 57 $ 114 $ 171 $ 228 $ 285"; $arrayCode = array(); $rows = explode("\n", $str); foreach($rows as $idx => $row) { $row = explode( "\t", $row ); //to get rid of first item (the number) //comment it if you don't need. array_shift ( $row ); foreach( $row as $field ) { //to clean up $ sign $field = trim( $field, "$ "); $arrayCode[$idx][] = $field; } } print_r( $arrayCode ); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/7562314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problem on RadioBoxes with wxRuby I got a situation on wxRuby using Wx::RadioBox. My radioboxes got some ugly background & borders like that : Unlike the demo which got a better style when I run it : here is my code : #!/usr/bin/env ruby # coding: utf-8 require 'wx' include Wx class MainFrame < Frame def initialize() super(nil, :title => "Title", :size => [ 480, 400 ]) #sizer = Wx::BoxSizer.new(Wx::VERTICAL) sampleList = ["Choice1","Choice2","Choice3"] rb = Wx::RadioBox.new(self, -1, "Title1", Wx::Point.new(15,20), Wx::Size.new(100,200), sampleList, 1, Wx::RA_SPECIFY_COLS, DEFAULT_VALIDATOR, "Name1") evt_radiobox(rb) {|event, other| on_debug(sampleList[event.get_int()].to_s(), rb.name.to_s())} #sizer.add(rb, 0, Wx::ALL, 20) rb2 = Wx::RadioBox.new(self, -1, "Title2", Wx::Point.new(150,20), Wx::Size.new(100,200), sampleList, 1, Wx::RA_SPECIFY_COLS, DEFAULT_VALIDATOR, "Name2") evt_radiobox(rb2) {|event| on_debug(sampleList[event.get_int()].to_s(), rb2.name.to_s())} #sizer.add(rb2, 0, Wx::ALL, 20) #set_sizer(sizer) #sizer.fit(self) #sizer.layout() end # show a 'Debug' dialog def on_debug(*params) Wx::message_box("Debug :\n\r\n\r#{params.inspect}", "Debug Box", ICON_INFORMATION|OK) end end class MyApp < App def on_init frame = MainFrame.new frame.show end end MyApp.new.main_loop() And here is the default code : * *samples/bigdemo/wxRadioBox.rbw *It seem's that this code is different from the one on your wxRuby install present in C:\[your Ruby Install]\lib\ruby\gems\1.9.1\gems\wxruby-ruby19-2.0.1-x86-mingw32\samples\bigdemo Any help will be highly appreciated because I really don't know why the aspect is so much different? A: Problem solved by setting up a default background color on the main Frame : self.set_background_colour(Wx::NULL_COLOUR) and here is the code : #!/usr/bin/env ruby # coding: utf-8 require 'wx' include Wx class MainFrame < Frame def initialize() super(nil, :title => "Title", :size => [ 480, 400 ]) #sizer = Wx::BoxSizer.new(Wx::VERTICAL) self.set_background_colour(Wx::NULL_COLOUR) sampleList = ["Choice1","Choice2","Choice3"] rb = Wx::RadioBox.new(self, -1, "Title1", Wx::Point.new(15,20), Wx::Size.new(100,200), sampleList, 1, Wx::RA_SPECIFY_COLS, DEFAULT_VALIDATOR, "Name1") evt_radiobox(rb) {|event, other| on_debug(sampleList[event.get_int()].to_s(), rb.name.to_s())} #sizer.add(rb, 0, Wx::ALL, 20) rb2 = Wx::RadioBox.new(self, -1, "Title2", Wx::Point.new(150,20), Wx::Size.new(100,200), sampleList, 1, Wx::RA_SPECIFY_COLS, DEFAULT_VALIDATOR, "Name2") evt_radiobox(rb2) {|event| on_debug(sampleList[event.get_int()].to_s(), rb2.name.to_s())} #sizer.add(rb2, 0, Wx::ALL, 20) #set_sizer(sizer) #sizer.fit(self) #sizer.layout() end # show a 'Debug' dialog def on_debug(*params) Wx::message_box("Debug :\n\r\n\r#{params.inspect}", "Debug Box", ICON_INFORMATION|OK) end end class MyApp < App def on_init frame = MainFrame.new frame.show end end MyApp.new.main_loop()
{ "language": "en", "url": "https://stackoverflow.com/questions/7562315", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What would be better to do(Pass in the object into the service or the username into the service?) what would be better to do public ActionResult Test() { User user = accountService.GetUser(User.Identity) Product project = productService.GetSomething(user); Store store = storeService.GetSomething(user); } Or public ActionResult Test() { Product project = productService.GetSomething(User.Identity); Store store = storeService.GetSomething(User.Identity); } In the first one I have a service layer that takes in the userName and calls up a repo to get the user record back. Then I pass it along and use it in other service layers. Now in option 2 I pass in the username and in that service layer I call the same repo the accountService would call. Only difference is I am passing in a string vs and object. I see both have up sides and downsides. If your just having one method that needs the users data then it kinda sucks to have to call another service layer to get it and pass it into another one. If you have multiple ones it might potentially save some queries to the database(however I nhibernate might just cache it anyways) A: Law of Demeter : http://en.wikipedia.org/wiki/Law_of_Demeter Or even better, look at this part of the excellent Clean Code Talk from Google: http://www.youtube.com/watch?feature=player_detailpage&v=RlfLCWKxHJ0#t=944s There, Law of demeters gets epxlained very well. Or just view the whole video, they are all good btw. In short, passing the smallest possible component makes the code more readable, more expressive, more testable. The "bigger" the object, the more it hides the intention of the method/constructor using it. And the harder/more complicated it is to create a stub/mock later on, especially because your own classes tend to "grow" over time. If you don't have to create stubs at all (as you use e.g. value types like in your case instead of reference types) it's the best you can achieve. A: Generally the less heavy, the better. While your object may only have three fields, that still means a lot more data, per object, being sent to the web service. Usually, you want to send the tiniest bit of unique identifier that you can get away with. If possible, I would send the UserID assuming it's a numeric data item, and have your service get all the other info it needs from the backend.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UITableView simple question? I have an UITableView on one of my views,so the problem is when the users select a row of the table,the row becomes blue and a view is pushed by an UINavigationController,when i back to the main view the row still with a blue background.How can i make the row look normal,with no background color? A: You can deselect the row, best is to do it when you push the next view: [tableView deselectRowAtIndexPath:indexPath animated:NO];
{ "language": "en", "url": "https://stackoverflow.com/questions/7562323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: SQL Query simple question Just wondering if I'm missing something here: $sql = "SELECT DISTINCT usr.id, CONCAT(usr.username, '".PHP_EOL."' ) as username FROM #__ads AS a RIGHT JOIN #__users WHERE gid= '19' AS usr ON usr.id = a.userid ORDER BY usr.username"; It works when I remove the WHERE gid = '19' part, is it in the wrong place? The gid column only exists in the __users table. Thank you! Edit: got it, just needed to put the Where clause right before the ORDER BY. A: The where clause must come after any joins: $sql = "SELECT DISTINCT usr.id , CONCAT(usr.username, '".PHP_EOL."' ) as username FROM #__ads AS a RIGHT JOIN #__users AS usr ON usr.id = a.userid WHERE gid= '19' ORDER BY usr.username"; A: Assuming you want just the row(s) from #__users where usr.gid= '19' SELECT DISTINCT usr.id, CONCAT(usr.username, '".PHP_EOL."' ) as username FROM #__ads AS a RIGHT JOIN #__users as usr ON usr.id = a.userid WHERE usr.gid= '19' ORDER BY usr.username The alternative SELECT DISTINCT usr.id, CONCAT(usr.username, '".PHP_EOL."' ) as username FROM #__ads AS a RIGHT JOIN #__users as usr ON usr.id = a.userid AND usr.gid= '19' ORDER BY usr.username Would give you all rows from #__users but only join on those matching usr.gid= '19'
{ "language": "en", "url": "https://stackoverflow.com/questions/7562324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't seem to get item to float:right until breaking div -- then allow to get cutoff http://jsfiddle.net/erfjW/2/ I am trying to get this jsfiddle to have the RHS not drop down to the next level when the browser window gets too small. Instead, I would like it to hold position -- as if it was inside of a fixed-width parent container. The content on the LHS should not move. I tried working from the source of SO -- the navbar at the top does basically what I want, except the content is allowed to move away from the LHS. When I tried to tweak this I broke the entire functionality. If this isn't possible in a simple manner I'm open to other suggestions. Thanks. EDIT: The RHS area is a search box. I do not wish it to override URL links which are left-justified. As such, absolute positioning won't work here -- it will render above the URL links instead of allowing itself to be cut off once it hits them. A: Well... as said above, one solution is to use absolute positioning. I made a fiddle for that here. The issue you're running into is that you don't want either side's content to override the other - there's really no way to guarantee this. As you can see from the fiddle, eventually, with a small enough screen size, Content A will override Content B. The way around that is to use a fixed width container, and define a width (in pixels or percentage) for the left and right divs. I made a fiddle for this solution here. A: One simple way would be position: absolute; right: 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Necessary to have non-hd file? I am developing for iPhone 4 retina display using Cocos2d. Well, I enabled retina display, and I have only put -hd graphics in my project. But when I run the project, it tells me that the -hd files are not found! Then, I, for the sake of testing, put non-hd versions in the project. And apparently I don't get the error anymore. This is puzzling. Does it mean I am forced to have -hd and non-hd versions in all my retina-enabled projects? A: Unless you change the implementation of CCFileUtils, that is correct. It will constantly warn you that you are missing files.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What is the correct way to programmatically quit an MFC application? Using windows MFC C++. I have a third party app that calls a user-defined method in my CWinApp derived class. This method is called after InitInstance(). If there is an error in this method, such that an exception is thrown and caught in a try/catch block, I would like to exit the application from the catch block. What is the canonical and correct way to quit? UPDATE: Serge I believe is right that in InitInstance() returning false is the correct way to quit the application. However, now suppose I want to quit from a CDialog derived class's OnInitDialog() handler, what's the correct way to do that. UPDATE 2 For me, I found calling PostMessage(WM_CLOSE) to be the best way from my non-modal CDialog derived class. All other methods of quitting I tried would raise some exception or other in some circumstances. Here's an example of how I use it: BOOL SomeDialog::OnInitDialog() { CDialog::OnInitDialog(); ::OleInitialize(nullptr); try { // ...load settings file here } catch(...) { PostMessage(WM_CLOSE); return TRUE; } // return TRUE unless you set the focus to a control return TRUE; } A: In InitInstance() Exiting the app while you are still in InitInstance(): Simply return FALSE from InitInstance(). In the main message loop It's another story though if you are already in the message loop: The standard way to close an app is to exit the message loop: PostQuitMessage(0), as its name implies, posts a WM_QUIT message. The message loop reacts by exiting the loop and closing the program. But you shouldn't simply do that: You should close the opened windows in your app. Assuming you have only your main window, you should destroy it by calling m_pMainWindow->DestroyWindow(); MFC will react by PostQuitMessage() for you, hence exit the main message loop and close your app. Better yet, you should post a WM_CLOSE to let your main window close gracefully. It may for example decide to save the current document. Beware though: the standard OnClose() handler may prompt user to save dirty documents. User can even cancel the close action using this prompt (Save document? Yes, No, Cancel). Destroying the main window will post a WM_DESTROY message to it. MFC reacts by calling PostQuitMessage(0) to exit the message pump. (Actually, MFC does the call in OnNcDestroy() since WM_NCDESTROY which is the absolute last mesage received by a window) Dialog-based app Call EndDialog(-1); // Or replace -1 by IDCANCEL, whatever This call, as you probably know, will close the dialog. Note that the main dialog of dialog-based app executes in InitInstance(). Closing the dialog will simply exit InitInstance(), which always returns FALSE in such projects. A: Serge - your answer is unfortunately not the best way to do it. PostQuitMessage(0) is the way to go and MFC will destroy the windows for you. You should avoid calling m_pMainWindow->DestroyWindow() directly. A: Simply use: PostQuitMessage(0); Keep in mind your program won't quit instantly from this call, the window/program will receive a WM_QUIT message and then your program will quit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562335", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: How to return keys in original order in a dict I'm reading in a file and storing the info in a dict as it reads from top to bottom. I don't want to print out in a wrong order compared to the original file. Also, a very small question: I remember seeing it somewhere a short form of the if and else statement: if a == 'a': a = 'b' ? a = 'c' Do you know the exact form? Thanks. A: * *Use an OrderedDict. *a = 'b' if a == 'a' else 'c' A: You can use OrderedDict, or you can store the data in a list and index it with a dict, or store it in a dict and save the keys in a list as you go. A: I don't know about the dict but the short form you're looking for is the Does Python have a ternary conditional operator? There's a ternary operator for nearly every language, you can find some example on wikipedia. However, the one in Python is has not the same syntax has the others like explained in the linked SO answer. A: Python dictionaries are unordered (see here). For your second question, see this previous answer. A: Second answer first: a = 'b' if a == 'a' else 'c' (known as a ternary expression) First answer second: Use an OrderedDict, which is available from 2.7 on. If that's not available to you, you can: * *Store the index as part of each value (a pain) *Use a previous Ordered Dictionary implementation
{ "language": "en", "url": "https://stackoverflow.com/questions/7562337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Lambda Extension Method for Converting IEnumerable to List I need a way to create an extension method off of an IEnumerable that will allow me to return a list of SelectListItem's. For example public class Role { public string Name {get;set;} public string RoleUID {get;set;} } IEnumerable<Role> Roles = .../*Get Roles From Database*/ var selectItemList = Roles.ToSelectItemList(p => p.RoleUID,r => r.Name); this would give me a SelectItemList with the Name being the display, and the RoleUID being the value. IMPORTANT I want this to be generic so I can create it with any two properties off of an object, not just an object of type Role. How can I do this? I imagine something like the following public static List<SelectItemList> ToSelectItemList<T,V,K>(this IEnumerable<T>,Func<T,V,K> k) or something, I obviously know that would be incorrect. A: Why not just combine the existing Select and ToList methods? var selectItemList = Roles .Select(p => new SelectListItem { Value = p.RoleUID, Text = p.Name }) .ToList(); If you want to specifically put it into one method then you could define ToSelectListItem as a combination of those two methods. public static List<SelectListItem> ToSelectListItem<T>( this IEnumerable<T> enumerable, Func<T, string> getText, Func<T, string> getValue) { return enumerable .Select(x => new SelectListItem { Text = getText(x), Value = getValue(x) }) .ToList(); } A: How about something like this? (note: I haven't tested this, but it should work. public static List<SelectListItem> ToSelectItemList<T>(this IEnumerable<T> source, Func<T, string> textPropertySelector, Func<T, string> valuePropertySelector, Func<T, bool> isSelectedSelector) { return source .Select(obj => new SelectListItem { Text = textPropertySelector(obj), Value = valuePropertySelector(obj), Selected = isSelectedSelector(obj) }) .ToList(); } and you would use it much like your current one, the only difference is I added another selector to set the Selected boolean property. A: What about using something like this IEnumerable<SelectListItem> data = Roles.Select(f => new SelectListItem { Value = f.RoleUID, Text = f.Name}); It works for me!
{ "language": "en", "url": "https://stackoverflow.com/questions/7562339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Arduino upload error "stk500_recv(): programmer is not responding" in Fedora I am attempting to upload the stock Blink sketch using the Arduino IDE in Fedora Core 15 Linux. I get this error: avrdude: stk500_recv(): programmer is not responding To recreate the issue: * *Plug in the Arduino Uno board via USB cable *Open the Arduino IDE *Menu File → Examples → 1. Basics → Blink *Menu Tools → Serial Port → then check the box for /dev/ttyACM0 *Menu Tools → Board → Arduino Uno *Click the "Play" button to Verify/Compile (this step is successful) *Click the Upload button, to get the error I tried these same exact steps in Windows XP, and the upload was successful, so I must not have Fedora configured correctly. I followed the Arduino Playground instructions, installing the client using yum and adding my user ID to the groups uucp, lock and dialout. I did not follow the RXTX fixup -- Link the proper files part of the guide, since the given command did not return any matches: find ~ -name librxtxSerial.so -o -name RXTXcomm.jar | grep -v Download A: Before uploading your programme, make sure you selected the right board type, from menu Tools → Board. A: Check if you have any jumpers connected to the digital pins 0 or 1. Those pins have also serial communication functions. And because you are uploading on the Arduino board, using the serial connection provided by the USB cable, you don't want the board's serial port to be engaged in other activities via pins 0 or 1. A: In my case, go to menu Tools → Processor and change to ATMega328P (Old Bootloader). Then the problem is solved. But make sure that you do the chmod before upload: sudo chmod a+rw /dev/ttyUSB0 A: This sounds like it was probably caused by a bug that was present in AVRDUDE at the time. A simple yum update AVRDUDE should now fix it. A: For me, changing the cable worked. I was using Ubuntu 17.04 (Zesty Zapus), Arduino Nano with ATmega28 and a USB cable with ferrite choke (I don’t think ferrite choke was the cause). A: Arduino Uno R3, Mac OS X v10.8.3 (Mountain Lion), any version of Arduino.app. For me changing the USB cable fix this error. A: I believe the instruction in Why I can't upload my programs to the Arduino board? that says On Linux, the Uno and Mega 2560 show up as devices of the form /dev/ttyACM0 does not always apply. In my Ubuntu 14.10 (Utopic Unicorn) I can see that port in menu Tools → Serial Port, but when selected and trying to upload to the Arduino Nano V3 I get the error stk500_recv(): programmer is not responding Changing the Tools -> Serial Port to /dev/ttyUSB0 solves the problem. I'm guessing that this may be the case in my system where I had an other device at the same USB port before plugging Arduino there. It may be that after restart the situation might be different; I don't know haven't tested. But whatever is the cause, the good news is that the problem can be solved. You can easily check what is the correct serial port by first checking what ports are available without plugging the Arduino (menu Tools → Serial Port) and then checking again what is the added port after plugging the Arduino in the USB port. A: The fix that worked for me: If you have a USBasp programmer (or other type of ICSP programmer) plugged into your Arduino board (but not plugged into your PC), because you just used it to flash the bootloader of your Arduino board, unplug it from the Arduino. Disconnecting the 5V line between the USBasp programmer and the Arduino was enough for me. Now uploading works (with the USBasp programmer lying on the bench with all but the 5V pin still connected to the Arduino). A: Since this question was posted, a new stable version of Arduino has been released. They are now on 1.0, and it works in Fedora Core Linux 16. It can be downloaded here: http://arduino.cc/en/Main/Software A: After hours of searching, the problem has been solved: Choose menu Tools → Programmer → Arduino as ISP A: For Windows, I tried doing this * *In PowerShell, run devcon status usb*. This should show multiple devices similar, one among which would be USB\VID_2341&PID_8036&MI_00\6&1D9C3F6B&0&0000 Name: Arduino Leonardo (COM3) Driver is running. *Then do reg add "HKLM\SYSTEM\ControlSet001\Enum\USB\VID_2341&PID_8036&MI_00\6&1D9C3F6B&0&0000\Device Parameters" /v "PortName" /t REG_SZ /d "COM3" /f.. Double check COM3 is also listed in Device Manager menu of windows. *Restart the machine and the Arduino IDE. And try uploading again.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How can I retrieve a JPEG image codec in F#? In C#, I can retrieve a JPEG encoder like this: var jpegEncoder = ImageCodecInfo.GetImageEncoders() .Where(e => e.FormatID == ImageFormat.Jpeg.Guid) .Single(); I'd like to do the same in thing F# and I know there's a beautifully succinct way to do it, but I'm just starting out and I can't quite figure it out. I see there's a Where method available hanging off of GetImageEncoders() but I can't figure out what to pass into it. I read Don Syme's blog post on F# and LINQ, but I just don't have enough experience in F# to really understand it. Is there a nice way I can do this same thing in F#? A: #r "System.Drawing" open System.Drawing.Imaging let jpeg = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders() |> Seq.find (fun e -> e.FormatID = ImageFormat.Jpeg.Guid)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: c++11 foreach syntax and custom iterator I am writing an iterator for a container which is being used in place of a STL container. Currently the STL container is being used in many places with the c++11 foreach syntax eg: for(auto &x: C). We have needed to update the code to use a custom class that wraps the STL container: template< typename Type> class SomeSortedContainer{ std::vector<typename Type> m_data; //we wish to iterate over this //container implementation code }; class SomeSortedContainerIterator{ //iterator code }; How do I get auto to use the correct iterator for the custom container so the code is able to be called in the following way?: SomeSortedContainer C; for(auto &x : C){ //do something with x... } In general what is required to ensure that auto uses the correct iterator for a class? A: As others have stated, your container must implement begin() and end() functions (or have global or std:: functions that take instances of your container as parameters). Those functions must return the same type (usually container::iterator, but that is only a convention). The returned type must implement operator*, operator++, and operator!=. A: To be able to use range-based for, your class should provide const_iterator begin() const and const_iterator end() const members. You can also overload the global begin function, but having a member function is better in my opinion. iterator begin() and const_iterator cbegin() const are also recommended, but not required. If you simply want to iterate over a single internal container, that's REALLY easy: template< typename Type> class SomeSortedContainer{ std::vector<Type> m_data; //we wish to iterate over this //container implementation code public: typedef typename std::vector<Type>::iterator iterator; typedef typename std::vector<Type>::const_iterator const_iterator; iterator begin() {return m_data.begin();} const_iterator begin() const {return m_data.begin();} const_iterator cbegin() const {return m_data.cbegin();} iterator end() {return m_data.end();} const_iterator end() const {return m_data.end();} const_iterator cend() const {return m_data.cend();} }; If you want to iterate over anything custom though, you'll probably have to design your own iterators as classes inside your container. class const_iterator : public std::iterator<random_access_iterator_tag, Type>{ typename std::vector<Type>::iterator m_data; const_iterator(typename std::vector<Type>::iterator data) :m_data(data) {} public: const_iterator() :m_data() {} const_iterator(const const_iterator& rhs) :m_data(rhs.m_data) {} //const iterator implementation code }; For more details on writing an iterator class, see my answer here. A: You have two choices: * *you provide member functions named begin and end that can be called like C.begin() and C.end(); *otherwise, you provide free functions named begin and end that can be found using argument-dependent lookup, or in namespace std, and can be called like begin(C) and end(C). A: To my knowledge SomeSortedContainer just needs to provide begin() and end(). And these should return a standard compliant forward iterator, in your case SomeSortedContainerIterator, which would actually wrap a std::vector<Type>::iterator. With standard compliant I mean it has to provide the usual increment and dereferencing operators, but also all those value_type, reference_type, ... typedefs, which in turn are used by the foreach construct to determine the underlying type of the container elements. But you might just forward them from the std::vector<Type>::iterator.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "60" }
Q: Problem with FB.ui apprequest dialog I am trying to send application invites from an Iframe application. I open the dialog like this. function sendRequestToOneRecipient(user_id) { FB.ui({method: 'apprequests', message: 'message', to: user_id, display: 'popup' }, requestCallback(user_id)); } When the dialog opens I get a ton of "Unsafe JavaScript attempt to access frame with URL from frame with URL" error messages. The send and cancel buttons just make the dialog go blank, but not close and it doesn't work. I don't know if it's related or not, but when loading the JS SDK in Chrome I get "Cannot read property 'cb' of undefined" and Firefox says "b is undefined". I do not have any references to the old FeatureLoader.js anymore. A: Thats the code I use to send apprequest, and never had problem either with Chrome or Firefox ... :s They post recently more examples recently here : http://developers.facebook.com/docs/reference/dialogs/requests/ Hope that helps function send_apprequest(){ var post_options = { method: 'apprequests', display: 'iframe', message: "My message", data: "Any data your want to pass", title: "My Title", ref: "Not required but useful for Insights" }; FB.ui(post_options,function(response) { if (response && response.request_ids) { alert('\o/'); } } ); } A: I found the problem. There was an included Javascript file that was conflicting with Facebook's Javascript. I'm not really sure exactly what was conflicting, but it was a JSON library from 2005. Thankfully, it's not being used so I just removed it. This is the copyright information on the file. // VC-JSON /* PROJECT: JDM (Java Dynamic Machine) PROGRAMMER: PRIVATE LICENSE FILE: vc-json/vc-json.js PURPOSE: GO! SERIALIZER & DE-SERIALIZER... Includes functions for: -- JSON/GO! Serialization -- JSON/GO! DE-Serialization -- JSON/GO! Parsing */ var JSON = { version : "0.000a", org: 'http://www.JSON.org', copyright: '(c)2005 JSON.org', license: 'http://www.crockford.com/JSON/license.html'
{ "language": "en", "url": "https://stackoverflow.com/questions/7562360", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android/Java - Find text and replace in WebViewClient I have a WebViewClient that opens in a dialog which i can capture when the URL changes, but on certain URL's I would like to replace certain text but I cant seem to figure out how to get the text of the current webpage that has been loaded so I can search and replace that text. A: Looks like there is already a question about getting the HTML code from a WebView. Please take a look at that: Is it possible to get the HTML code from WebView (Main tutorial is here: http://lexandera.com/2009/01/extracting-html-from-a-webview/) Of course, once you get the HTML code (string) you can do anything that you want such as replacing the text as you wanted! Manipulated HTML string can be loaded into the view with following code snippet: webview.loadData(newHtmlStr, "text/html", "utf-8"); newHtmlStr is the new data and it must be URI-escaped!
{ "language": "en", "url": "https://stackoverflow.com/questions/7562362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Finding by Recursion Sequences of Characters in a Char Array I have a recursion project to find all the sequences(or subsets) of a Char array as such that each character appears in the same order. For Example, for the array Char[] letters = {'A', 'B','C','D'} The one letter sequences are "A","B","C,"D". Two letter sequences are "AB","AC","AD","BC","BD","CD". Three letter sequences are "ABC", "ABD","ACD","BCD" Four letter sequence is "ABCD" Now I thought I was on the right track with the code below, but I'm getting a lot of duplicates. I'm getting really frustrated. If anyone can point me in the right direction, I would appreciate it. // print all subsets of the characters in s public static void combinations(char[] array) { combinations("", array, 0); } // print all subsets of the remaining elements, with given prefix private static void combinations(String prefix, char[] array, int index) { for(int i = index; i < array.length; i++) { System.out.println(prefix + array[i]); } if (index < array.length) { for(int i = index; i < array.length; i++){ combinations(prefix + array[i], array, index+1); } } } Editting out my edit for clarification. A: You seem to have used the wrong variable here: combinations(prefix + array[i], array, index+1); It should be i instead of index: combinations(prefix + array[i], array, i+1); Output: A B C D AB AC AD ABC ABD ABCD ACD BC BD BCD CD Ideone: http://ideone.com/H4Okw A: for (int i = index; i < array.length; i++) { System.out.println(prefix + array[i]); combinations(prefix + array[i], array, i + 1); } The result is: A AB ABC AC B BC C
{ "language": "en", "url": "https://stackoverflow.com/questions/7562366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Website rendering insanely off the mark in IE 8.0.6011.19088IC I've built this website last week, which has worked perfectly across all browsers that I have (even optimized to render nicely on iPad, iPhone, etc). My boss uses a particular version of Internet Explorer that always seems to break websites that I build, but only slightly. This website gets destroyed in her IE: I looked around and found a JavaScript library that I think is made for helping IE<9 render as IE9 would, which I've implemented like so: <!--[if lt IE 9]> <script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script> <![endif]--> But it doesn't seem to make a difference. I've tested the website in multiple versions of IE 8.* and all of them are fine, it's just this specific version (and possibly versions close to it) that are going berserk. Any help and suggestions would be much appreciated. A: One thing worth checking is that the browser is definitely rendering in IE8 mode - try pressing F12 to get the Developer Tools window up, then check that "Browser Mode" isn't set to IE7 or IE8 compatibility mode and that the "Document Mode" is set to IE8 standards. Try adding the following line to the <head>: <meta http-equiv="X-UA-Compatible" content="ie=edge,chrome=1"> A: I'm surprised it's only happening in this one version of IE 8 and not more. Perhaps the other browsers are more forgiving of the following HTML problems. Your code has over 70 validation errors... some are serious like missing tags, open tags, improper nesting, tags out of place, etc... http://validator.w3.org/ Go through and tackle each error one at a time, then once complete, you'll have much more consistent results across various platforms and browsers.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting additional files in LightSwitch I want to add additional files (mostly .xlsx and .docx) to a LightSwitch application and use this files in the application, for example as a filestream. What is the best way/practice to do this? So far I can add files to the client-project (under the file-view). This file then shows in the bin\debug\bin\Server directory when I make a debug-build or publish the application. So now comes the tricky part. How do I get a file stream of this files? In which directory is it installed? A: After hitting the post-button I figured it out myself. This blog post describes how to use embedded resources as images. When you have added a file to the client-project, you have to set build action to “Embedded Resource” and then you can get a stream using the following code: // get the currently executing assembly Assembly assembly = Assembly.GetExecutingAssembly(); // list all available ResourceName's string[] resources = assembly.GetManifestResourceNames(); // creates a StreamReader from the TestFile.txt StreamReader sr = new StreamReader(assembly .GetManifestResourceStream("LightSwitchApplication.TestFile.txt")); // puts the content of the TestFile.txt in a string string text = sr.ReadToEnd();
{ "language": "en", "url": "https://stackoverflow.com/questions/7562386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SlimDX - Set state block I want to set states in SlimDX Direct3d9 device. I have that code at the beging of frameRender function. device.BeginStateBlock(); device.SetRenderState(RenderState.ZEnable, false); device.SetRenderState(RenderState.Lighting, false); device.SetRenderState(RenderState.CullMode, Cull.None); device.EndStateBlock(); But I'm getting this error in debug window: Object of type SlimDX.Direct3D9.StateBlock was not disposed. Stack trace of object creation: I'm getting millions of those lines. All of them say the same thing. How should I dispose those states? How to make it in proper way? A: The only hint i can give you, given your information, is that EndStackeBlock should return a StateBlock object, which is disposable. My guess is, you get these after a LostDevice event? Before you reset the device you need to free all those resources. And of course, the whole reason to make StateBlocks is so that you create them once and reuse them, but it seems you are recreating them everytime and never applying them. So after a while you created a lot of stateblocks without using or disposing any of them. But maybe you can post more code or give more informations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set @model.attribute in razor view? I have a required field, string attribute{get; set} in a class and want to set it's value in razor. Is something like the following possible? @model.attribute = "whatever' A: First, capitalization matters. @model (lowercase "m") is a reserved keyword in Razor views to declare the model type at the top of your view, e.g.: @model MyNamespace.Models.MyModel Later in the file, you can reference the attribute you want with @Model.Attribute (uppercase "M"). @model declares the model. Model references the instantiation of the model. Second, you can assign a value to your model and use it later in the page, but it won't be persistent when the page submits to your controller action unless it's a value in a form field. In order to get the value back in your model during the model binding process, you need to assign the value to a form field, e.g.: Option 1 In your controller action you need to create a model for the first view of your page, otherwise when you try to set Model.Attribute, the Model object will be null. Controller: // This accepts [HttpGet] by default, so it will be used to render the first call to the page public ActionResult SomeAction() { MyModel model = new MyModel(); // optional: if you want to set the property here instead of in your view, you can // model.Attribute = "whatever"; return View(model); } [HttpPost] // This action accepts data posted to the server public ActionResult SomeAction(MyModel model) { // model.Attribute will now be "whatever" return View(model); } View: @{Model.Attribute = "whatever";} @* Only do this here if you did NOT do it in the controller *@ @Html.HiddenFor(m => m.Attribute); @* This will make it so that Attribute = "whatever" when the page submits to the controller *@ Option 2 Or, since models are name-based, you can skip creating the model in your controller and just name a form field the same name as your model property. In this case, setting a hidden field named "Attribute" to "whatever" will ensure that when the page submits, the value "whatever" will get bound to your model's Attribute property during the model-binding process. Note that it doesn't have to be a hidden field, just any HTML input field with name="Attribute". Controller: public ActionResult SomeAction() { return View(); } [HttpPost] // This action accepts data posted to the server public ActionResult SomeAction(MyModel model) { // model.Attribute will now be "whatever" return View(model); } View: @Html.Hidden("Attribute", "whatever");
{ "language": "en", "url": "https://stackoverflow.com/questions/7562393", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "42" }
Q: Facebook Real-time updated does not call our servers We had integrated facebook real-time updates a while ago and it worked fine. Recently we have seen that the callbacks are not happening. we checked our subscriptions and it looks correct. array(2) { [0]=> array(4) { ["object"]=> string(4) "user" ["callback_url"]=> string(62) "https://OUR_CALLBACK_URL" ["fields"]=> array(2) { [0]=> string(7) "friends" [1]=> string(5) "likes" } ["active"]=> bool(true) } [1]=> But when the user makes a like or changes the likes. we do not get a callback. A: Sometimes Facebook does have bugs and it could be a temporary outage too. I would suggest trying to re-register your subscriptions and seeing if that helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setting axis intervals in ggplot I have searched for this and can't believe I can't find it. Perhaps I've been asking the wrong question. I have a set of data laid out in a histogram that has a xlim of $2,000,000. I am trying to set an interval of $100,000 for the breaks (rather than manually listing out every break with break = c(0, 50000, 100000, etc). How can I do this in ggplot? The breaks (ticks) are more important than the labels as I'll likely edit in Illustrator an abbreviated label (100k, etc) p <- ggplot(mcsim, aes(result)) + scale_x_continuous(formatter = "dollar") + geom_histogram(aes(y = (..count..)/sum(..count..))) + scale_y_continuous(formatter = 'percent') Thanks! A: You can use breaks=seq(0, 2000000, by=100000). Effectively you are using seq to generate that vector you don't want to type out by hand.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562398", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: how to center img vertically and horizontally in a container - img may potentially be larger than container I have a container that will contain an image, and this image is loaded from an application and so the dimensions of the container is known while the image will vary. I currently have the following css: #secondary_photos { height: 100px; width: 300px; overflow: hidden; } #secondary_photos .small_photo { float:left; height: 100px; width: 300px; } #secondary_photos .small_photo img{ height: 100%; width: auto; position: absolute; bottom: 0px } #secondary_photos .small_photo img{ height: auto; width: 100%; position: absolute; bottom: 0px } This works 'okay' form me: it loads the image, resizes it to take up 100% of the container's width and positions it so that the bottom-half of the image is displayed within the container - so if the image ends up being 200px high after resizing the width to 300px, only the bottom 100px of the image is displayed (an arbitrary setting). What I'm trying to do is to always display the middle of the image - so in the example above, the image would display pixels 50-150 (from the top).. A: Since it sounds like you don't know the image size on page load, you could use a combination of dead centre and javascript to do what you want. The flow would be as follows: * *Setup markup as in the dead centre example. *When image is loaded, get its width and height. *Set image margin-left to (image width / 2 * -1). *Set image top to (image height / 2 * -1). Since you may also have images that are larger than your container, you could add a conditional check for this: // Get DOM elements var container = document.getElementById('container'); var image = document.getElementById('img'); // Check they're good if(container && img){ var height = image.height; var width = image.width; // Horizontally centre if container is wider than image if(container.offsetWidth > width){ image.style.marginLeft = Math.floor((width / 2 * -1)) + "px"; } // Vertically centre if container is taller than image if(container.offsetHeight > height){ image.style.top = Math.floor((height / 2 * -1)) + "px"; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7562404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: At the risk of sounding dumb: I want to make an HTML audio player that uses for interaction. Thoughts? Basically I am attempting to make an HTML5 audio player but want to do the majority of the controls with canvas. Why? I want to try something new while learning something new. I have gotten everything working so far - that is, a seekable timeline, play/pause buttons, etc. - by essentially using mouse coordinates to decide what the user is clicking on. Im mainly curious what the more experienced web developers out there think of this. Is it dumb? Is there an issue you think I may not foresee? I'll post some code if anyone is really interested, but I havent had any issues so far so I dont really need and troubleshooting. Thanks! A: For a learning experience? Great! You've clearly figured out how <canvas> works, how to manipulate objects on-screen, and how to make those objects interactive. In a production app? Not a chance. What immediately comes to mind: * *It's not accessible. <button> has a semantic meaning that a screen reader can take advantage of. A canvas means nothing; in your example, a blind user has no idea there even are play/pause buttons, much less how to activate them. *You're reinventing the wheel for no real gain. Let the browser handle the details of whether an object was clicked. Have you accounted for zoom? Keyboard interaction? *You lose out on a wide array of pre-baked widgets. *Your implementation is guaranteed to have a bug somewhere. A <button> is guaranteed to be a button. A: There is nothing inherently wrong with this idea, especially if you’re doing it to try something new. What I would add is that <canvas> is generally not that suitable for interactive widgets, although there are exceptions. I suspect you will find that in the end you’re better off using HTML/CSS/DOM and maybe some small <canvas> elements sprinkled around as needed. A: I don't believe there is any benefit in using canvas for some buttons and a moving seek bar. Groovshark and Pandora using divs ant it's totally fine and working great. I can understand that you want to do something experimental but IE8 will be around for next 5 years. So thinking of a canvas only solution is recommended for commercial product.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Django using wrong foreign key for joins I have two relationships between models in Django, a many-to-many between Foo and Bar and a foreign key on Foo pointed towards Bar. When I do a query that involves both Foo and Bar, django insists on using the Foreign Key instead of the M2M to do the join. (The M2M is the real data here, the Foreign Key is just a bit of caching so I can get the most recent Bar created by a certain method.) So for example (where foos is the many-to-many relationship name on Bar) Bar.objects.filter(foos__attribute = True) Doesn't return all of the Bars with that attribute, but only the one Bar that Foo is pointed at with the FK. How can I force it to use the M2M? Or is this a bad idea completely? A: I figured it out, and it was definitely an instance of 'should have used real code for the example'. I had the many-to-many relation on the Bar table called 'foos' (lets say). The foreign key was automatically creating a related_name on the Bar table called 'foo'. I was not actually calling: Bar.objects.filter(foos__attribute = True) Like I said I was. I was calling: Bar.objects.filter(foo__attribute = True) Which was using the automatically-created related name of the Foreign Key 'foo' instead of the name of the many-to-many table 'foos'. So lessons learned: * *Don't let django ever decide the related name for you *Be careful with pluralization! *Post real examples on SA
{ "language": "en", "url": "https://stackoverflow.com/questions/7562406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there any advantage to the pimpl idiom with a templated class? It is my understanding that the primary benefit of the pimpl idiom is to hide the data members in the implementation file instead of the header. However, templates need to be fully defined in the header in order for the compiler to instantiate them on demand. In this case, is there any advantage to using the pimpl idiom for a templated class? A: While the pimpl idiom doesn't really hide anything when used in a templated class, it does allow you to easily write non-throwing swaps (although with C++11 move semantics this is less of a concern). A: In large projects, decoupling translation units alone is a sufficient reason for pimpl. This works even with templates: // main interface template <typename> struct MyImpl; class TheInterface { MyImpl<int> * pimpl; }; // implementation #include "MyImpl.hpp" // heavy-weight template library // TheInterface implementation A: Theres one case that may not strictly be a pimpl idiom, but is similar enough to warrant knowing about. That is to have a typesafe template wrapper over a non-typesafe version. class MapBase { public: void* getForKey(const std::string & k); void setForKey(const std::string & k, void * v); ... }; template<typename T> class MyMap { public: T* getForKey(const std::string &k) { return (T*)base_.getForKey(k); } void setForKey( const std::string &k, const T* v) { base_.setForKey(k, T*v); } private: MapBase base_; }; Now any use of MyMap<T> doesn't need to be exposed to the internals of MapBase, and you only get one implementation of the guts of those functions. I'd also consider making MapBase be an abstract base class to make the decoupling even stronger. As I said, its not exactly a pimpl, but it solves may of the same issues in a similar way. A: I think, if you extend the idiom a bit, you could get at least a bit out of it in some cases. In a template not every operation must necessarily depend on the template parameters. So you can inherit from a Impl class, that itself uses the pimpl idiom, something like this: struct FooPimpl; class FooImpl { protected: FooPimpl* pimpl; public: void myCommonInterfaceMethod(); }; template <typename T> class Foo : public FooImpl { // stuff that depends on T }; Of course, this depends greatly on the circumstances. But I see the pimpl idiom working in a template class context. A: it's still quite usable - consider an auto or shared pointer, which is a template and quite usable for solving and implementing PIMPL. whether it's the best solution depends on the problem. templates need to be fully defined in the header in order for the compiler to instantiate them on demand. you can declare an the template's members and interface, then in your type's cpp file, you can #include the necessary definitions of the specializations and use them there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to identify current logged in user in Dotnetnuke? I have a very simple SQL query that I made which retrieves some user information from a table that is in my DNN database. It displays the information in a "Grid View" via the "Reports" Module that comes standard with DNN 6.0 My problem is not with the query, but rather the view. I need to set a filter/parameter(?) that will only display the records of the current user who is viewing the records. Now I'm not sure if this can even be done in SQL or if I would have to write a custom module myself or whether it's just some custom code that I have to add to the skin/page. After doing research I heard some people also talking about the DNN Core API but I can't find any decent documentation on it. (Nor have I ever used any kind of API before) I'm pretty sure the solution to this is pretty simple it's just that I can't get a straight answer from my research which is just leading me to be more and more confused. As always any help, input, article/tutorial or nudge in the right direction is greatly appreciated. Thank You *EDIT* For the sake of anyone in the future who is looking for this, here is how my SQL Query looks after adding the parameter values. I've stripped it down to show you just the basic: SELECT dbo.Users.UserID FROM dbo.Users WHERE dbo.Users.UserID = @UserID Putting this into to my Reports Query generated the only the records of the User who is currently logged in. Pretty simple! A: The DNN reports module supports tokens. I wrote this blog post awhile back ago: DNN Reports Module Shows an example of using a URL parameter to replace some data in the SQL. I can't recall if it has SQL injection protection or not. In your SQL you can use @UserID and it gets replaced with the logged in users - Userid. You can also use: @PortalID, @TabID
{ "language": "en", "url": "https://stackoverflow.com/questions/7562410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Coregraphics causing big lag on iPad? UIGraphicsBeginImageContext(self.view.bounds.size); [currentStrokeImageView.image drawInRect:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)]; CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound); CGContextSetBlendMode(UIGraphicsGetCurrentContext(), kCGBlendModeNormal); CGContextSetLineWidth(UIGraphicsGetCurrentContext(), dWidth); CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), r, g, b, 1.0f); CGContextBeginPath(UIGraphicsGetCurrentContext()); CGContextMoveToPoint(UIGraphicsGetCurrentContext(), pointA.x, pointA.y); CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), pointB.x, pointB.y); CGContextStrokePath(UIGraphicsGetCurrentContext()); currentStrokeImageView.image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); For some reason this runs with absolutely no lag on the iphone/ipod but on the iPad their is a significant lag while drawing. The code I use is above, any suggestions to fix this? A: The reason why this is so laggy is because you are doing it in the touchesMoved:withEvent:. This method can be called many, many times (obviously) while touch events are received. Because drawing to a graphics context can be a resource intensive operation, I would recommend not doing all the things you are doing there. I would, as much as possible, defer the rendering you are doing to the touchesBegin and touchesEnd methods. If that is not possible, perhaps you could only preform these operations once a certain delta has been reached in the movements, for example, every 2.0f points.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get HTML before its sent to the browser I would like to capture HTML before its gets sent to the browser for caching. Is there a way to do this? A: I've never tried this, but could you hook into the EndRequest event of an HTTP module, and simply read the Response property? Edit: Just tried this - massive fail, at least at a simple level, because the Response isn't readable at that point. Could still be viable if there's a way to redirect the output of the Response at the beginning of a request, and then pipe it through at the end. Edit #2: I was close, but it's more complex than I thought. You need to implement a filter, which is demonstrated nicely here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Random Horizontal Scrollbar on Website A new client has come to me with a strange issue they've got on their website, for some reason it's displaying a horizontal scrollbar, and I'm really not sure how to get rid of it. Help is appreciated. http://www.hearthstoneresort.com/ A: How about setting the body width to 100% instead of 828px in the css file. Or a hack like : overflow:hidden; in css always work. A: add in stylesheet under body tag 'overflow-x: hidden;' body { overflow-x: hidden; } A: You need to remove this width setting under div#tagline p from Hearthstone.css div#tagline p { width: 828px; // remove this because it's positioned absolutely. }
{ "language": "en", "url": "https://stackoverflow.com/questions/7562415", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to execute a windows executable remotely from a java server? I want to execute a program on a windows machine from a java program that is running on a java server in another windows machine and return something from that executable. While I am researching different ways to do this, I don't seem to find any popular approach. What would be a quick but standard way of accomplishing this distributed call? (RPC, CORBA, Sockets??) Thanks A: If both machines run in a trusted LAN environment, then sockets should do the trick. Java has very convenient socket classes built in so it'll be very straightforward to implement. On the executor you'll have to create a ServerSocket. Then, in a loop, accept() a connecting socket, run your program, write data to the socket's output stream and close it. On the connecting side you'll just create a new Socket, read the data from the socket's input stream and close it. If you want to service multiple requests concurrently then it's slightly less straightforward but still quite easy if you know how to program threads. A: Ok if you can't run java on the other machine I'd locally call a .NET application that does the RPC to another .NET application on the other machine. In this case you can use .NET Remoting or WCF (or DCOM if you are forced to). As another option you could stick to Sockets on both Java and .NET side. (I am sure .NET also has a Socket implementation)
{ "language": "en", "url": "https://stackoverflow.com/questions/7562419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sliding Down A Small NSView Over An Existing NSView I'm working with a NSWindow that displays various NSViews when buttons are pressed (a settings panel, essentially). I'm trying to get a smaller NSView to slide out with a NSPopUpButton and some NSButtons from the top of the main NSView when a button is pressed. What's a good starting point for figuring out how to do this?
{ "language": "en", "url": "https://stackoverflow.com/questions/7562420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What version of J2EE am I using on my AWS Elastic BeanStalk Tomcat 6 server? I need to know what version of j2ee I am running on my elastic beanstalk instance but I do not know where to look for it. I am using ami-2537f14c running 32bit tomcat 6. A: Tomcat 6 is a Servlet 2.5 container. Servlet 2.5 is part of Java EE 5. But Tomcat is actually not a full fledged Java EE application server. It's just a simple JSP/Servlet container. The full fledged Java EE 5 application servers are JBoss AS 4.2, 5.x, Glassfish v2, etc. They bundles JSF, EJB, JMS, etc as well. Please note that "J2EE" refers to the old J2EE 1.2, 1.3 and 1.4. Since Java EE 5 (May 2006), it's renamed to "Java EE". Be careful to call it rightly. See also Wikipedia: Java EE version history.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Explain the DateTime.Now design in .Net I have a question regarding the design of the Date object in the .Net framework, more specifically the Now property. I know that Now is a property that is a Date type. (This makes sense since I see the methods .AddHours(), AddYears(), etc) If Now being a class(or struct) how does it return a value directly. For example: How would I create a class or struct in C#/VB.net that would allow me to do the same without calling a property of Now? (VB.Net) Dim WeatherObject as new WeatherReporter() If WeeatherReport had a property called TodaysWeather that was a class how could I then get a value like this Dim PlainTextReport as string=WeeatherReport.TodaysWeather To me it seems like you would have to call a another property off of TodaysWeather. But with the Datetime.Now example you don't. Anyways, I know its an odd question. I was just trying to better understand how some of these objects are set up under the hood Thanks for any light on the matter. Here is an example of code referring to the above question. Public Class WeatherReporter Shared ReadOnly Property TodaysWeather As DayWeather Get TodaysWeather = New DayWeather Return TodaysWeather.Current End Get End Property End Class Public Class DayWeather Public Property Current As String = "Sunny" End Class Now similar to the DateTime.Now object How could one you the weather example like this Dim TheForecast as string=WeatherReporter.TodaysWeather It seems like it would require the following Dim TheForecast as string=WeatherReporter.TodaysWeather.Current I know its a confusing question, lol. thanks for your patience A: Reflecting the source code it's evident that it's simply a property wrapper around a function. public static DateTime Now { get { return UtcNow.ToLocalTime(); } } You don't need to instantiate a DateTime object since the property is marked as static. A: .NET properties are more than merely values - they encapsulate getter and setter methods around underlying values. That being the case, they can initialize objects before returning them. So, for example, DateTime.Now may be implemented like this (without attempting to find its actual implementation via Reflector or Reference Sources...): public static DateTime Now { get { var d = new DateTime() { .Kind = DateTimeKind.Local }; // Logic to determine the current system time and set d to that value return d; } } (ref: MSDN) A: DateTime.Now looks something like this in VB.net... public structure DateTime ...other code... ''// `shared` makes this a class property, not an instance property. ''// This is what lets you say `DateTime.Now` public shared readonly property Now as DateTime get ... do some magic to return the current date/time ... end get end property ... other code ... end class or in C#: public struct DateTime { ... other code ... // `static` works like VB's `shared` here public static DateTime Now { get { /* do your magic to return the current date/time */ } } ... other code ... } A: It's implemented as a static getter method. I believe what your looking for would look something like this in your WeatherReporter class: Public Shared ReadOnly Property TodaysWeather As WeatherReporter Get Return New WeatherReporter(DateTime.Now) End Get End Property That assumes that your WeatherReporter class has a constructor that accepts a DateTime. A: DateTime.Now is a static/Shared property. You don't have to instantiate a new object (using New DateTime()) to call it.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562425", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I load XML into a HTML page? What is the best practice for loading XML into a HTML page? For instance, loading the combined contents of a file.xml and file.xsl into a div or some part of a HTML page. Answers can be IE-specific, as long as they work on IE9. A: An <iframe> seems like the obvious solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook Linter: Extraneous Property Objects of this type do not allow properties named fb:page_id Hi when I run facebook linter on my site (www.mvcc.com.uy) it says: Extraneous Property Objects of this type do not allow properties named fb:page_id. What am I doing wrong here ? A: Typically to get the linter to work properly, you need to add some meta tags in your <head>. Check out more information here: http://developers.facebook.com/docs/opengraph/ Also, the Facebook servers only check your site once a day for new meta tags so don't expect the linter to work for a few days after you've added the meta tags. If you've already done this and you're still experiencing problems - please provide us with examples of your code. A: fb:page_id isn't required for Open Graph pages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding a custom Authors category to Gtk::AboutDialog class I was wondering if there was a way to set a custom Authors category in a Gtk::AboutDialog class via gtkmm. I know there are the following methods: * *set_artists() *set_authors() *set_documenters() *set_translator_credits() But I wanted to add a custom category. Right now I have a program that accepts a bunch of plugins, so on startup when it scans for plugins I would like to populate a "Plugins" page on the about screen once you click credits that shows all of the plugin authors' names (removing duplicates of course). The logic is already there, but it looks quite odd adding them to the artists or documenters categories where they certainly do not belong. Is there an easy way to add a new category besides rolling my own? A: Nice question! In GTK 3, this is fairly easy. You have to do some manipulation of the About dialog's internal children, which may change in future releases, so be warned! I've written a quick-n-dirty example in Vala that does what you want. That was faster for me because I almost never use Gtkmm. It shouldn't be too hard to translate though. using Gtk; int main(string[] args) { Gtk.init(ref args); var dialog = new AboutDialog(); // Fetch internal children, using trickery var box = dialog.get_child() as Box; Box? box2 = null; ButtonBox? buttons = null; Notebook? notebook = null; box.forall( (child) => { if(child.name == "GtkBox") box2 = child as Box; else if(child.name == "GtkButtonBox") buttons = child as ButtonBox; }); box2.forall( (child) => { if(child.name == "GtkNotebook") notebook = child as Notebook; }); // Add a new page to the notebook (put whatever widgets you want in it) var plugin_page_index = notebook.append_page(new Label("Plugin 1\nPlugin 2"), new Label("Plugins")); // Add a button that toggles whether the page is visible var button = new ToggleButton.with_label("Plugins"); button.clicked.connect( (button) => { notebook.page = (button as ToggleButton).active? plugin_page_index : 0; }); buttons.pack_start(button); buttons.set_child_secondary(button, true); // Set some other parameters dialog.program_name = "Test Program"; dialog.logo_icon_name = Gtk.Stock.ABOUT; dialog.version = "0.1"; dialog.authors = { "Author 1", "Author 2" }; dialog.show_all(); // otherwise the new widgets are invisible dialog.run(); return 0; } In GTK 2, this is much more difficult, although probably not impossible. You have to connect to the Credits button's clicked signal, with a handler that runs after the normal handler, and then get a list of toplevel windows and look for the new window that opens. Then you can add another page to that window's GtkNotebook. I would suggest doing it a little differently: add a Plugins button to the action area which opens its own window. Then you don't have to go messing around with internal children. Here's another Vala sample: using Gtk; class PluginsAboutDialog : AboutDialog { private Dialog _plugins_window; private Widget _plugins_widget; public Widget plugins_widget { get { return _plugins_widget; } set { var content_area = _plugins_window.get_content_area() as VBox; if(_plugins_widget != null) content_area.remove(_plugins_widget); _plugins_widget = value; content_area.pack_start(value); }} public PluginsAboutDialog() { _plugins_window = new Dialog(); _plugins_window.title = "Plugins"; _plugins_window.add_buttons(Stock.CLOSE, ResponseType.CLOSE, null); _plugins_window.response.connect((widget, response) => { widget.hide(); }); var buttons = get_action_area() as HButtonBox; // Add a button that opens a plugins window var button = new Button.with_label("Plugins"); button.clicked.connect( (button) => { _plugins_window.show_all(); _plugins_window.run(); }); button.show(); buttons.pack_start(button); buttons.set_child_secondary(button, true); } public static int main(string[] args) { Gtk.init(ref args); var dialog = new PluginsAboutDialog(); // Make a widget for the plugins window var can_be_any_widget = new Label("Plugin 1\nPlugin 2"); dialog.plugins_widget = can_be_any_widget; // Set some other parameters dialog.program_name = "Test Program"; dialog.logo_icon_name = Gtk.Stock.ABOUT; dialog.version = "0.1"; dialog.authors = { "Author 1", "Author 2" }; dialog.run(); return 0; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7562429", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Kill one button event when new button clicked How to kill one button's event when a new button is clicked. I have one event (Button G) running.(has a while loop waiting for some input). I have a another button for quit operation. Now. I cannot click any other button when button G's event is running. How can I solve that? Thanks Hi, @Grokodile thank you for your code. So I commented your code here, Should I put my job logic code where I commented below? Thans using System; using System.ComponentModel; using System.Threading; using System.Windows; using System.Windows.Threading; namespace WpfApplication1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private BackgroundWorker _worker; public MainWindow() { InitializeComponent(); } private void RunButtonClickHandler(object sender, RoutedEventArgs e) { _worker = new BackgroundWorker {WorkerSupportsCancellation = true}; _worker.DoWork += BackgroundWorkerTask; _worker.RunWorkerAsync();        //I should Put my job logic here, right? } private void StopButtonClickHandler(object sender, RoutedEventArgs e) { if (_worker != null && _worker.IsBusy) _worker.CancelAsync(); //I should Put my job logic here, right? } private void BackgroundWorkerTask(object sender, DoWorkEventArgs e) { // this runs on the BackgroundWorker thread. while (_worker.CancellationPending == false) { Thread.Sleep(500); // You have to use the Dispatcher to transfer the effects of // work done in the worker thread back onto the UI thread. Dispatcher.BeginInvoke(new Action(UpdateTime), DispatcherPriority.Normal, null); } } private void UpdateTime() { // Dispatcher runs this on the UI thread. timeTextBlock.Text = DateTime.Now.ToString(); } } } A: Futher to what H.B. and dowhilefor have said, here is a sample that shows starting a task on a background thread using BackgroundWorker with one Button and ending it with another Button, note the use of Dispatcher.BeginInvoke: XAML <Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="80" Width="640" FontSize="16"> <DockPanel VerticalAlignment="Center"> <Button Margin="10,0" x:Name="runButton" DockPanel.Dock="Left" Click="RunButtonClickHandler">Run</Button> <Button Margin="10,0" x:Name="stopButton" DockPanel.Dock="Left" Click="StopButtonClickHandler">Stop</Button> <TextBlock Margin="10,0">The Time Is Now:</TextBlock> <TextBlock x:Name="timeTextBlock" Margin="10,0" /> </DockPanel> </Window> Code Behind using System; using System.ComponentModel; using System.Threading; using System.Windows; using System.Windows.Threading; namespace WpfApplication1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private BackgroundWorker _worker; public MainWindow() { InitializeComponent(); } private void RunButtonClickHandler(object sender, RoutedEventArgs e) { _worker = new BackgroundWorker {WorkerSupportsCancellation = true}; _worker.DoWork += BackgroundWorkerTask; _worker.RunWorkerAsync(); } private void StopButtonClickHandler(object sender, RoutedEventArgs e) { if (_worker != null && _worker.IsBusy) _worker.CancelAsync(); } private void BackgroundWorkerTask(object sender, DoWorkEventArgs e) { // this runs on the BackgroundWorker thread. while (_worker.CancellationPending == false) { Thread.Sleep(500); // You have to use the Dispatcher to transfer the effects of // work done in the worker thread back onto the UI thread. Dispatcher.BeginInvoke(new Action(UpdateTime), DispatcherPriority.Normal, null); } } private void UpdateTime() { // Dispatcher runs this on the UI thread. timeTextBlock.Text = DateTime.Now.ToString(); } } } EDIT - A Little More Explanation RunButtonClickHandler Creates and initializes a BackgroundWorker so that it supports cancellation. Attaches a DoWorkEventHandler to the DoWork event, i.e. BackgroundWorkerTask. Starts excecution of the background operation with the call to RunWorkerAsync, i.e. creates a new thread (actually it uses a thread from the thread pool) and runs the code in BackgroundWorkerTask on that thread. BackgroundWorkerTask If you want to do work that would otherwise cause the UI to freeze when running on the main UI thread (e.g. search for undiscovered prime numbers) then you do it here in the background thread. UpdateTime All WPF Controls inherit from DispatcherObject and are associated with a Dispatcher which manages the execution of work done in the UI's single thread. If you need to do work such as setting the text of a TextBlock, you can't do it from the background thread, trying to do so will cause an exception to be thrown. UpdateTime is queued back onto the UI thread by the Dispatcher when Dispatcher.BeginInvoke is called from BackgroundWorkerTask. This way you can get the results of work done in the background before cancelling the background threads execution. StopButtonClickHandler Changes _worker.CancellationPending to true with the call to CancelAsync causing the while loop to exit and thus for execution to leave the BackgroundWorkerTask event handler. In short, you can do work in two places, either in BackgroundWorkerTask or in UpdateTime, but you can only carry out changes to UI elements from UpdateTime. A: Don't do spin-waiting operations on the UI-thread, use a new Thread or a Timer for example. A: You can't. The UI is running in a single thread, usually called the main or ui thread. With your while loop you are blocking the whole ui thread, thus you can't receive any further input. I suggest you check out BackgroundWorker class and maybe check some more MSDN articles about how the threading and background tasks should be designed to work properly in an ui enviroment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562430", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: delete records in time ranges in SQL Server I have a lot of time ranges in TimeRanges table: StartTime EndTime 2010-01-01 06:00 2010-01-01 18:00 2010-01-01 20:00 2010-01-01 22:00 2010-01-02 06:00 2010-01-02 18:00 2010-01-02 20:00 2010-01-02 22:00 2010-01-03 06:00 2010-01-03 18:00 2010-01-03 20:00 2010-01-03 22:00 2010-01-04 06:00 2010-01-04 18:00 2010-01-04 20:00 2010-01-04 22:00 ... ... 2010-02-01 06:00 2010-02-01 18:00 2010-02-01 20:00 2010-02-01 22:00 2010-02-02 06:00 2010-02-02 18:00 2010-02-02 20:00 2010-02-02 22:00 2010-02-03 06:00 2010-02-03 18:00 2010-02-03 20:00 2010-02-03 22:00 2010-02-04 06:00 2010-02-04 18:00 2010-02-04 20:00 2010-02-04 22:00 ... ... 2011-01-01 06:00 2011-01-01 18:00 2011-01-01 20:00 2011-01-01 22:00 2011-01-02 06:00 2011-01-02 18:00 2011-01-02 20:00 2011-01-02 22:00 2011-01-03 06:00 2011-01-03 18:00 2011-01-03 20:00 2011-01-03 22:00 2011-01-04 06:00 2011-01-04 18:00 2011-01-04 20:00 2011-01-04 22:00 ... ... 2011-02-01 06:00 2011-02-01 18:00 2011-02-01 20:00 2011-02-01 22:00 2011-02-02 06:00 2011-02-02 18:00 2011-02-02 20:00 2011-02-02 22:00 2011-02-03 06:00 2011-02-03 18:00 2011-02-03 20:00 2011-02-03 22:00 2011-02-04 06:00 2011-02-04 18:00 2011-02-04 20:00 2011-02-04 22:00 and I have some filters in TimeFilters table: StartTime EndTime 2010-02-01 00:00 2010-03-01 00:00 2011-02-01 00:00 2011-03-01 00:00 2012-02-01 00:00 2012-03-01 00:00 What I need is to delete the records from TimeRanges table, only those time ranges that are within the TimeFilters table will be retained. To simply put, I want the following records retained: from 2010-02-01 00:00 to 2010-03-01 00:00, like: 2010-02-01 06:00 2010-02-01 18:00 2010-02-01 20:00 2010-02-01 22:00 2010-02-02 06:00 2010-02-02 18:00 2010-02-02 20:00 2010-02-02 22:00 2010-02-03 06:00 2010-02-03 18:00 2010-02-03 20:00 2010-02-03 22:00 2010-02-04 06:00 2010-02-04 18:00 2010-02-04 20:00 2010-02-04 22:00 from 2011-02-01 00:00 to 2011-03-01 00:00, like: 2011-02-01 06:00 2011-02-01 18:00 2011-02-01 20:00 2011-02-01 22:00 2011-02-02 06:00 2011-02-02 18:00 2011-02-02 20:00 2011-02-02 22:00 2011-02-03 06:00 2011-02-03 18:00 2011-02-03 20:00 2011-02-03 22:00 2011-02-04 06:00 2011-02-04 18:00 2011-02-04 20:00 2011-02-04 22:00 What I can do now is to select those records are within TimeFilters into a temporary table, then truncate the TimeRanges table, and put back records from the temporary table, but that's quite time consuming. A: To delete all the records in TimeRanges that do not have a match in TimeFilters, you can do delete TimeRanges from TimeRanges r left join timefilters f on r.StartTime >= f.StartTime and r.EndTime <= f.EndTime where f.StartTime is null The tricky thing here is to do a left join, and delete those TimeRanges that do not have a correspondent filter (when f.startTime or f.endTime are null) After deleting, you can see the results: select * from TimeRanges StartTime EndTime ----------------------- ----------------------- 2010-02-01 06:00:00.000 2010-02-01 18:00:00.000 2010-02-01 20:00:00.000 2010-02-01 22:00:00.000 2010-02-02 06:00:00.000 2010-02-02 18:00:00.000 2010-02-02 20:00:00.000 2010-02-02 22:00:00.000 2010-02-03 06:00:00.000 2010-02-03 18:00:00.000 2010-02-03 20:00:00.000 2010-02-03 22:00:00.000 2010-02-04 06:00:00.000 2010-02-04 18:00:00.000 2010-02-04 20:00:00.000 2010-02-04 22:00:00.000 2011-02-01 06:00:00.000 2011-02-01 18:00:00.000 2011-02-01 20:00:00.000 2011-02-01 22:00:00.000 2011-02-02 06:00:00.000 2011-02-02 18:00:00.000 2011-02-02 20:00:00.000 2011-02-02 22:00:00.000 2011-02-03 06:00:00.000 2011-02-03 18:00:00.000 2011-02-03 20:00:00.000 2011-02-03 22:00:00.000 2011-02-04 06:00:00.000 2011-02-04 18:00:00.000 2011-02-04 20:00:00.000 2011-02-04 22:00:00.000 (16 row(s) affected) A: What you can do is an outer join to get both the matches and the non-matches and then have a condition to extract the non-matches: select * form TimeRanges r join TimeFilters f on r.StartTime between f.StartTime and f.EndTime and r.EndTime between f.StartTime and f.EndTime where f.StartTime is null and f.EndTime is null I don't know if the rest can be done with MySQL, but what you'll want to do is generate a condition that matches each each row that didn't fall between the dates in the filter table. The pseudo code to do this would be as follows: cond=''; while (r = read row) do if (cond=='') { sep=''; } else { sep=' OR '; } cond = cond . sep . '(r.StartDate=' . r->StartDate . ' and r.EndDate=' . r->EndDate . ')'; } # Before running the delete query comment it out and run the query printed by: # print 'select * from TimeRanges where '.cond; run query 'delete from TimeRanges where '.cond; If this can't be done using MySql, then it can be done using a scripting language, such as PHP. A: I assume you have some sort of ID column on your TimeRanges table? If so, would something like this work for you? DELETE TimeRanges WHERE id NOT IN ( SELECT tr.id FROM TimeRanges tr JOIN TimeFilter tf ON tr.startdate >= tf.startdate AND tr.enddate <= tf.enddate )
{ "language": "en", "url": "https://stackoverflow.com/questions/7562437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Google custom site search (business edition) how to make search results showed in a pop up window I have a question about the google custom site search on my site. I have paid 100$ to get custom site search on my site everything works only one thing i can't fix. I have set google site search to display the results on a new page, this worked perfect! The problem is i will get it in a popup window not in a new window on the same page! I have tried to add a popup script but every time i change the extention search.htm it will no longer do antyhing so i can't give it an onclick event or anything!! :( This is the javascript for the search bar: <script src="http://www.google.com/jsapi" type="text/javascript"></script> <script type="text/javascript"> google.load('search', '1', {language : 'en'}); google.setOnLoadCallback(function() { var customSearchControl = new google.search.CustomSearchControl('011481879946604973384:9cjokptmuey'); customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); var options = new google.search.DrawOptions(); options.enableSearchboxOnly("search.htm"); customSearchControl.draw('cse-search-form', options); }, true); </script> and this line: options.enableSearchboxOnly("search.htm"); will make it go to search.htm where the search results displayed Hope some one can help me. Thanks.. A: Use an iframe to show search.htm.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Git remote origin has two branches I am using TortoiseGit for Windows. I see two branches on remote/origin: HEAD 20 minutes ago Some commit message. master 20 minutes ago Some commit message. I am confused why HEAD shows up as a branch; I did not explicitly create a separate branch on origin - it should only be 'master'. It's not really a problem, since they seem to update together anyway. If I execute git branch on origin, it only shows 'master'. Why are there two branches? Is this a TortoiseGit-specific thing, or a Git-specific thing? Thanks! A: It's a git-specific thing. HEAD is a reference to the currently checked out thing, i.e. usually a branch. In your case, HEAD is simply an alias for master. TortoiseGit apparently can't tell an alias ("symbolic ref") from a normal branch, so it appears as if HEAD is an extra branch when it really isn't. The situation is a bit different for remote repositories which usually don't have anything checked out at all. You seem to be looking at a remote repository here. In that case, that repository's HEAD is used to determine which branch is checked out by default when someone clones that repository. That's why, when you clone, some branch or another is checked out: git doesn't just randomly pick a branch, but it looks at the source repository's HEAD to make that decision. A: HEAD is the current revision. It's best answered by this question right here. It will be exactly the same as the currently checked out ref. A: HEAD is the current "head" of the remote repo and would usually be same as the master. It is the current checked out branch / ref and is from the .git/HEAD file in the repo which has content like: ref: refs/heads/master
{ "language": "en", "url": "https://stackoverflow.com/questions/7562442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Passing path to current_page method I have a helper method to help to determine whether or not a navigation menu item should be active/inactive. def events_nav_link nav_item = 'Events' if current_page?(events_path) # additional conditions here # do nothing else nav_item = link_to nav_item, events_path end content_tag(:li, nav_item + vertical_divider, :class => 'first') end I want this link to be inactive not only for the events_path page, but for other pages as well. Problem is that I don't know what param to pass the current_page?(path) method based on this route: map.list_events '/events/:league/:year/:month/:day', :controller => 'events', :action => 'list' This route generates a path such as /pow or /chow/2011/09/25. Leagues can be pow, chow or wow. A: I like unobtrusive JS approach with add/remove classes and unwrap() deactivated links, but it requries specific rules. The Rails way is to use link_to_unless_current built-in helper to highlight and unlink on current page href. A: This is what I do: application_helper.rb: def already_here?(this_controller,this_action) controller_name == this_controller && action_name == this_action ? true : false end in a view: <%= already_here?("users","index") ? "Manage Users" : link_to("Manage Users", users_path, :title => "Manage Users.") %> Of course, you can abstract it further by passing the title of the link and path to the helper if you want, but that's a bit of a hassle (to me). UPDATE: never mind, see mikhailov's answer- much cleaner (why reinvent the wheel?) :) A: You're looking for named routes. In your routes.rb file, add :as => :foo after the route. Then use if current_page(events_path) || current_page(foo_path) in your condition.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android special/hardware keys not generating Javascript events I'm looking to build an application for Android using a Webkit view in Phonegap and have been assessing it for suitability, however I've hit one rather major snag. I have tested this outside of Phonegap as well, and put up a test page here: http://tane.ifies.org/test.html I have a Samsung Galaxy Tab with a physical keyboard. In the Phonegap application, it seems to be completely ignoring special keys, and specifically physical arrow keys on the keyboard. I've written a small test binding the keyup event: window.addEventListener('keyup', function(e) { alert(e.keyCode); }); For all ASCII keys (a-z, 1-9 and keys like / ?, etc) I get a keycode back fine on both the virtual and physical keyboard, but again not for special keys, shift, ctrl or the arrow keys. I also created a textarea - the arrow keys, etc work fine, but still do not seem to produce a key event in my window listener. Is there a different event I need to listen to to capture these keys in Android? I'm not too concerned about this being cross platform, the application is specific to my setup - although I may release it for Android in the future if there is a way to do this across the whole platform.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562451", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: iPhone SDK - what is this control? Is it custom? What is this control? Or is it something that has been custom made? I see it in the Twitter and several other applications. I'm referring to the two triangles, and if you've ever used them, they refresh the view below them, usually going through a list of content items. (I'm not referring to the navigation controller with a back button) A: They are UISegmentedControls with custom images and the style set to UISegmentedControlStyleBar. A: Its right there in Apple's NavBar sample code. You have the entire source code for the project. Search for NavBar within the Documentation and API reference item under the Help menu of Xcode 4.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use Python Framework or Build Own I am an experienced PHP developer (10 years) who has built 3 different custom frameworks for extreme high traffic sites. I have recently started to get into programming a lot of python, usually just for fun (algorithms). I am starting to develop a new site as my side project and wanted to know if I should use a pre-existing python web framework (Django, Pyramids, ect...) or develop my own. I know things might go a lot faster using a pre-existing framework, but from my experience with PHP frameworks and knowing the amount of traffic my side project could generate, whould it be better to develop an extremely light weight framework myself just like I have been doing for a while with PHP? It also might be a good way for me to learn python web development because most of my experience with the language has been for coding algorithms. If I do use a pre-existing framework I was going to try out Pyramid or Django. Also do other companies that use Python for web development and expect high traffic use their own web frameworks or a pre-existing one? A: Learn from existing frameworks, I think. The Python web stack (wsgi, sqlalchemy, template engines, full stack frameworks, microframeworks) has spent a lot of time maturing. You'll have the opportunity to develop fast and learn from existing design.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562454", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In Eclipse Emacs mode, is there any way to remap or add the Alt key to the Esc key? I'm used to the Emacs use of Esc for Metakey. In eclipse may I change the Esc key to be the Alt key? A: Nope, I don't think there's a way to do that. The relevant Eclipse UI docs state: The recognized modifiers keys are M1, M2, M3, M4, ALT, COMMAND, CTRL, and SHIFT. ESC is only a "normal" key. Emacs handles ESC specifically, so that it acts like kind of a modifier. A: On windows plateform you can use AutoHotkey to remap Esc to Alt Just add this to your Autohotkey script : #IfWinActive ahk_class SWT_Window0 $Esc::Alt #IfWinActive you may need to adjust the first line to match the class of your Eclipse window (use the windows spy tool provided in Autohokey).
{ "language": "en", "url": "https://stackoverflow.com/questions/7562455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sench Touch MVC I am pretty new to MVC and I have implemented it in my Sencha touch app. My question is what is the advantage of implementing the Sencha Touch controller Ext.Controller and dispatching to it over using just regular js functions instead? In my experience you can do the same with both but Ext.Controller requires a bit more code to do. A: This question answered it for me, kindly provide by Luis. As for as I can tell you can use the dispatch and the controller to load only the code needed instead of all at once on page load as well as better control on event handling. A: find this below link, you will get clear step by step approach to MVC using sencha touch sencha-touch-mvc-application-from-scratch
{ "language": "en", "url": "https://stackoverflow.com/questions/7562467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Weld and Java SE I'm new to Weld and have been trying to get my head around it's concepts. I have a little experience with Spring and nothing with Guice, so I'm pretty much a novice with the DI frameworks. Here's a tutorial that introduce CDI, but in the context of web apps. I'm interested to see how this works in Java SE alone. I have created the following classes, but have no idea how to test the ItemProcessor's execute method with the DefaultItemDao class (or any other alternative) in a Java SE app. Here're the classes: public class Item { private int value; private int limit; public Item(int v, int l) { value = v; limit = l; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } @Override public String toString() { return "Item [value=" + value + ", limit=" + limit + "]"; } } import java.util.List; public interface ItemDao { List<Item> fetchItems(); } import java.util.ArrayList; import java.util.List; public class DefaultItemDao implements ItemDao { @Override public List<Item> fetchItems() { List<Item> results = new ArrayList<Item>(){{ add(new Item(1,2)); add(new Item(2,3)); }}; return results; } } import java.util.List; import javax.inject.Inject; public class ItemProcessor { @Inject private ItemDao itemDao; public void execute() { List<Item> items = itemDao.fetchItems(); for (Item item : items) { System.out.println("Found item: "+item); } } } And I have no idea how to write a test client for the ItemProcessor class. Can someone help me understand how to write one with CDI? Thanks, Kumar A: I had same question with injection Validator using JavaSE. Finally I managed to solve it. Hope it helps someone! Dependencies i used: <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.0.Alpha2</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator-cdi</artifactId> <version>6.0.0.Alpha2</version> </dependency> <dependency> <groupId>org.jboss.weld.se</groupId> <artifactId>weld-se</artifactId> <version>2.4.3.Final</version> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>javax.el-api</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>2.2.6</version> </dependency> Main method: Weld weld = new Weld().interceptors(Validator.class); WeldContainer container = weld.initialize(); PurchaseOrderService service = container.select(ru.code.service.PurchaseOrderService.class).get(); Customer customer = new Customer(.....); service.createCustomer(customer); weld.shutdown(); PurchaseOrderService.java @Inject private Validator validator; private Set<ConstraintViolation<Customer>> violations; public PurchaseOrderService() { } public void createCustomer(Customer customer) { violations = validator.validate(customer); if (violations.size() > 0) { throw new ConstraintViolationException(violations); } } And also i created beans.xml in resources/META-INF directory: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" bean-discovery-mode="all"> </beans>
{ "language": "en", "url": "https://stackoverflow.com/questions/7562472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Activity Indicator in GWT MAP What I would like to have is an activity indicator, which is displayed after my app is up and running, but while GWT is making AJAX calls. For example have a look at following site : http://www.foodtrucksmap.com/# Any ideas on how to achieve it? A: You can use an activity indicator from here, they are animated gifs so you can display one like this: <g:Image ui:field="activityImage"/> MyResources resources = GWT.create(MyResources.class); this.activityImage.setResource(resources.activityImage()); and in your resources interface you would set the image: public interface MyResources extends ClientBundle{ // use the actual path to your image @Source("../resources/images/activityImage.gif") ImageResource activityImage(); } When you make your async calls: loadingImage.setVisible(true); and in the callback: loadingImage.setVisible(false); A: I had to deal with the same kind of stuff few days back. The way I did was, created an Icon and Overlayed on the map. Icon icon = Icon.newInstance("loading.gif"); // load you gif as icon MarkerOptions options = MarkerOptions.newInstance(); options.setIcon(icon); Marker indicator = new Marker(point, options); So before the Async call and after you map is up, just add the icon to the map using map.addOverlay(indicator); and after the Async call remove the overlay using map.removeOverlay(indicator); I am not sure how correct this approach is, but this is what I did and it worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AutoMapper Projection - date/time I have a DateTime field in my Entity, which needs to map to 2 separate fields in the ViewModel for date and time i.e. // Entity public partial class Event { public Int64 Id { get; set; } public String Title { get; set; } public DateTime StartDateTime { get; set; } public DateTime EndDateTime { get; set; } } // ViewModel public class EventAddEditViewModel { public Int64 Id { get; set; } public String Title { get; set; } public String StartDate { get; set; } public String EndDate { get; set; } public String StartTime { get; set; } public String EndTime { get; set; } } Looking at this example, I have the following mapping: Mapper.CreateMap<Event, EventAddEditViewModel>() .ForMember(dest => dest.StartDate, opt => opt.MapFrom(src => src.StartDateTime.Date)) .ForMember(dest => dest.StartTime, opt => opt.MapFrom(src => src.StartDateTime.TimeOfDay)) .ForMember(dest => dest.EndDate, opt => opt.MapFrom(src => src.EndDateTime.Date)) .ForMember(dest => dest.EndTime, opt => opt.MapFrom(src => src.EndDateTime.TimeOfDay)); which is great. However, how do I reverse the mapping i.e. Mapper.CreateMap() so that it also maps when the form is POSTed? A: I have done something similar to you, however I have StartDateTime as a DateTime Property on my ViewModel, and have two int properties for Hours and Minutes e.g. // ViewModel public class EventAddEditViewModel { public Int64 Id { get; set; } public String Title { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public int StartHour { get; set; } public int EndHour { get; set; } public int StartMinute { get; set; } public int EndMinute { get; set; } } This means that I can do the mapping thus Mapper.CreateMap<Event, EventAddEditViewModel>() .ForMember(dest => dest.StartDate, opt => opt.MapFrom(src => src.StartDateTime.Date)) .ForMember(dest => dest.StartHour, opt => opt.MapFrom(src => src.StartDateTime.Hour)) .ForMember(dest => dest.StartMinute, opt => opt.MapFrom(src => src.StartDateTime.Minute)) .ForMember(dest => dest.EndDate, opt => opt.MapFrom(src => src.StartDateTime.Date)) .ForMember(dest => dest.EndHour, opt => opt.MapFrom(src => src.EndDateTime.Hour)) .ForMember(dest => dest.EndMinute, opt => opt.MapFrom(src => src.StartDateTime.Minute)); Mapper.CreateMap<EventAddEditViewModel, Event>() .ForMember(dest => dest.StartDateTime, opt => opt.MapFrom(src => new DateTime(src.StartDate.Year, src.StartDate.Month, src.StartDate.Day, src.StartHour, src.StartMinute, 0))) .ForMember(dest => dest.EndDateTime, opt => opt.MapFrom(src => new DateTime(src.EndDate.Year, src.EndDate.Month, src.EndDate.Day, src.EndHour, src.EndMinute, 0))); You should consider changing your viewmodel properties along those lines as integers will be easier to work with, however if they have to be strings, you'll need a way to parse out a DateTime object from your strings. Depending upon the format of your strings, something along these lines should work Mapper.CreateMap<EventAddEditViewModel, Event>() .ForMember(dest => dest.StartDateTime, opt => opt.MapFrom(src => DateTime.Parse( src.StartDate + " " + src.StartTime))) .ForMember(dest => dest.EndDateTime, opt => opt.MapFrom(src => DateTime.Parse(src.EndDate + " " + src.EndTime))); A: @StanK, I have simplier mapping syntax for this case: Mapper.CreateMap<EventAddEditViewModel, Event>() .ForMember(dest => dest.StartDateTime, opt => opt.MapFrom(src => src.StartDate.Add(src.StartTime.TimeOfDay))) .ForMember(dest => dest.EndDateTime, opt => opt.MapFrom(src => src.EndDate.Add(src.EndTime.TimeOfDay)));
{ "language": "en", "url": "https://stackoverflow.com/questions/7562476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why do we need prefix, postfix notation I know how each of them can be converted to one another but never really understood what their applications are. The usual infix operation is quite readable, but where does it fail which led to inception of prefix and postfix notation A: Infix notation is easy to read for humans, whereas pre-/postfix notation is easier to parse for a machine. The big advantage in pre-/postfix notation is that there never arise any questions like operator precedence. For example, consider the infix expression 1 # 2 $ 3. Now, we don't know what those operators mean, so there are two possible corresponding postfix expressions: 1 2 # 3 $ and 1 2 3 $ #. Without knowing the rules governing the use of these operators, the infix expression is essentially worthless. Or, to put it in more general terms: it is possible to restore the original (parse) tree from a pre-/postfix expression without any additional knowledge, but the same isn't true for infix expressions. A: Postfix notation, also known as RPN, is very easy to process left-to-right. An operand is pushed onto a stack; an operator pops its operand(s) from the stack and pushes the result. Little or no parsing is necessary. It's used by Forth and by some calculators (HP calculators are noted for using RPN). Prefix notation is nearly as easy to process; it's used in Lisp. A: At least for the case of the prefix notation: The advantage of using a prefix operator is that syntactically, it reads as if the operator is a function call A: Another aspect of prefix/postfix vs. infix is that the arity of the operator (how many arguments it is applied to) no longer has to be limited to exactly 2. It can be more, or sometimes less (0 or 1 when defaults are implied naturally, like zero for addition/subtraction, one for multiplication/division).
{ "language": "en", "url": "https://stackoverflow.com/questions/7562477", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "43" }
Q: nested content_tags escape inner html.. why? So, if I loop through and create a collection of li/a tags, I get as expected.. an array of these tags: (1..5).to_a.map do content_tag(:li) do link_to("boo", "www.boohoo.com") end end => ["<li><a href=\"www.boohoo.com\">boo</a></li>", "<li><a href=\"www.boohoo.com\">boo</a></li>", "<li><a href=\"www.boohoo.com\">boo</a></li>", "<li><a href=\"www.boohoo.com\">boo</a></li>", "<li><a href=\"www.boohoo.com\">boo</a></li>"] I call join on them and I get an expected string... (1..5).to_a.map do content_tag(:li) do link_to("boo", "www.boohoo.com") end end.join => "<li><a href=\"www.boohoo.com\">boo</a></li><li><a href=\"www.boohoo.com\">boo</a></li><li><a href=\"www.boohoo.com\">boo</a></li><li><a href=\"www.boohoo.com\">boo</a></li><li><a href=\"www.boohoo.com\">boo</a></li>" However, if I nest this one level deeper in an ol tag... content_tag(:ol) do (1..5).to_a.map do content_tag(:li) { link_to("boo", "www.boohoo.com") } end.join end => "<ol>&lt;li&gt;&lt;a href=&quot;www.boohoo.com&quot;&gt;boo&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;www.boohoo.com&quot;&gt;boo&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;www.boohoo.com&quot;&gt;boo&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;www.boohoo.com&quot;&gt;boo&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;www.boohoo.com&quot;&gt;boo&lt;/a&gt;&lt;/li&gt;</ol>" I get escaped inner-html madness!!! When looking at the rails source code: def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block) if block_given? options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash) content_tag_string(name, capture(&block), options, escape) else content_tag_string(name, content_or_options_with_block, options, escape) end end private def content_tag_string(name, content, options, escape = true) tag_options = tag_options(options, escape) if options "<#{name}#{tag_options}>#{escape ? ERB::Util.h(content) : content}</#{name}>".html_safe end It deceivingly looks like I can just do: content_tag(:li, nil, nil, false) and not have it escape the content.. However: content_tag(:ol, nil, nil, false) do (1..5).to_a.map do content_tag(:li, nil, nil, false) do link_to("boo", "www.boohoo.com") end end.join end => "<ol>&lt;li&gt;&lt;a href=&quot;www.boohoo.com&quot;&gt;boo&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;www.boohoo.com&quot;&gt;boo&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;www.boohoo.com&quot;&gt;boo&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;www.boohoo.com&quot;&gt;boo&lt;/a&gt;&lt;/li&gt;&lt;li&gt;&lt;a href=&quot;www.boohoo.com&quot;&gt;boo&lt;/a&gt;&lt;/li&gt;</ol>" I still am suffering from unwanted html_escape syndrome... So the only way I know to avoid this is to do: content_tag(:ol) do (1..5).to_a.map do content_tag(:li) do link_to("boo", "www.boohoo.com") end end.join.html_safe end => "<ol><li><a href=\"www.boohoo.com\">boo</a></li><li><a href=\"www.boohoo.com\">boo</a></li><li><a href=\"www.boohoo.com\">boo</a></li><li><a href=\"www.boohoo.com\">boo</a></li><li><a href=\"www.boohoo.com\">boo</a></li></ol>" But.. Why does this happen? A: What happens if you use safe_join? content_tag(:ol) do safe_join (1..5).to_a.map { content_tag(:li) { link_to("boo", "www.boohoo.com") } }, '' end Or just use raw? content_tag(ol) do 1.upto(5) { raw content_tag(:li) { link_to 'boo', 'www.boohoo.com' } # or maybe # raw content_tag(:li) { raw link_to('boo', 'www.boohoo.com') } } end A: It happens because in Rails 3 the SafeBuffer class was introduced which wraps the String class and overrides the default escaping that would otherwise occur when concat is called. In your case, the content_tag(:li) is outputting a proper SafeBuffer, but Array#join doesn't understand SafeBuffers and simply outputs a String. The content_tag(:ol) is then be called with a String as it's value instead of a SafeBuffer and escapes it. So it doesn't so much have to do with nesting as it does to do with join returning a String not a SafeBuffer. Calling html_safe on a String, passing the String to raw, or passing the array to safe_join will all return a proper SafeBuffer and prevent the outer content_tag from escaping it. Now in the case of passing false to the escape argument, this doesn't work when your passing a block to content tag because it is calling capture(&block) ActionView::Helpers::CaptureHelper which is used to pull in the template, or your case the output value of join, which then causes it to call html_escape on the string before it makes its way into the content_tag_string method. # action_view/helpers/tag_helper.rb def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block) if block_given? options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash) # capture(&block) escapes the string from join before being passed content_tag_string(name, capture(&block), options, escape) else content_tag_string(name, content_or_options_with_block, options, escape) end end # action_view/helpers/capture_helper.rb def capture(*args) value = nil buffer = with_output_buffer { value = yield(*args) } if string = buffer.presence || value and string.is_a?(String) ERB::Util.html_escape string end end Since value here is the return value from join, and join returns a String, it calls html_escape before the content_tag code even gets to it with it's own escaping. Some reference links for those interested https://github.com/rails/rails/blob/v3.1.0/actionpack/lib/action_view/helpers/capture_helper.rb https://github.com/rails/rails/blob/v3.1.0/actionpack/lib/action_view/helpers/tag_helper.rb http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/ http://railsdispatch.com/posts/security Edit Another way to handle this is to do a map/reduce instead of map/join since if reduce is not passed an argument it will use the first element and run the given operation using that object, which in the case of map content_tag will be calling the operation on a SafeBuffer. content_tag(:ol) do (1..5).to_a.map do content_tag(:li) do link_to(...) end end.reduce(:<<) # Will concat using the SafeBuffer instead of String with join end As a one-liner content_tag(:ul) { collection.map {|item| content_tag(:li) { link_to(...) }}.reduce(:<<) } Add a little meta-spice to clean things up ul_tag { collection.map_reduce(:<<) {|item| li_link_to(...) } } Who needs html_safe... this is Ruby! A: Not positive, but I think that the html escaping happens at each "layer" (for lack of a better term; each iteration)― what I mean is at the inner block level (1..5)…. and then at the outer block level (content_tag(:ol) do ...
{ "language": "en", "url": "https://stackoverflow.com/questions/7562478", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Localizing a (vb).NET enterprise app into a different language (with a twist) I've built an application and it's big. VB.NET, .NET 3.5. Two years in the making, 12-projects (1 .exe, 11 .dll's), each containing dozens of WinForms. Thousands of business object classes. You get the picture. It's a .NET migration for an existing legacy line of business enterprise application suite. It's nearing the end of development and isn't in production yet but the code looks clean(ish) and the project is likely to be successful. However it was designed in English (all forms and their controls are in English) and with a left-to-right read order. The twist is that I have a new requirement to translate the application in Saudi Arabian and I'd like some suggestions on how I should be tackling this and also a critique of my current thinking to see if you can spot any flaws in my understanding of localization with Microsoft .NET. I'm looking for a technical rather than a business critique of my approach. My Plan: * *Manually (can this be done with a Macro or automation?) parse through each class in each project and replace references to strings in code to strings in a resource file. *Re-align and re-anchor controls to make them suitable for both left-to-right and right-to-left reading order. *Change all of the controls to reference the new project (or form) language resource file. (at this stage there are no noticeable differences to an English-speaking end user) *Have a translator translate all the strings in the new language resource file. *Dynamically determine which resource file to load depending on the system locale. Specific questions: * *Is there a tool available to assist with the migration of strings out of the code and into resource files? *How should I anchor controls to support right-to-left reading order without compromising on the left-to-right reading order that the forms were designed for? *What operating system version does the .NET framework locale support? I presume XP SP1 as a baseline? *Should I use a single resource file per project or per form? *Should translations for any hard coded strings (for message boxes) be written into the code (in an if, else block) or also integrated into one of the new language resource files? -- Any advice that you can offer will be warmly appreciated. This is the first time that I've had to give thought to translation so any tips or thoughts as to the quickest and most sustainable route to success are welcome :-) Thanks in advance for your time, Mike A: This is far simpler than you're guessing, as long as you use the built-in support for localization in Winforms and avoid trying to come up with a custom scheme. Pick a form, set its Localizable property to True. Change the Language property to Arabic (Saudi Arabia). Change the RightToLeft and RightToLeftLayout properties. That's where you're done. Ship the .resx files to a localization service for translation. A: Regarding your in-code strings: Resharper is an excellent tool for extracting strings to a localizable resource file. Take a look at the features: http://www.jetbrains.com/resharper/features/internationalization.html
{ "language": "en", "url": "https://stackoverflow.com/questions/7562488", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the best PHP framework for a large, high traffic, feature rich web app? I know there's a million "what's the best PHP framework" questions out there, but it seems like the answers tend to be skewed towards rapid development and low code bloat. We're looking to rewrite a very large, extremely feature rich, very high traffic web app, so our needs are pretty much the exact opposite. In order of priority, here's our needs: * *High Performance - Lots of complex DB operations, very high traffic. *Feature rich - if there's a technology out there, we're probably using it somewhere in our app. *Customization - there's a fairly good chance that we'll need to overwrite some of the functionality of the framework. From what I've read this is easier in some frameworks than others. *Low learning curve OR lots of knowledgeable developers - we're growing, so we need to be able to get new people up to speed quickly, or we need to be able to hire people who are already familiar with the framework. *Built in testing framework - I'm kind of new to this area, but this is a direction we want to move to streamline our QA process. So, what say you? Codeigniter? CakePHP? Zend? Symfony? Something else entirely? A: I think your priority of 'framework' is missing the mark - if you're looking at high-capacity issues, then it's not so much the framework itself as it is how the framework's components can cache and scale. As is turns out, symfony and Zend do these things well, but you're looking at a large multi-server approach. These are still concerns for lower profile frameworks that are outside of their scope, so you're not learning anything from a framework that can't be understood elsewhere. A: A Custom Framework. A self-written framework to outline the potentials of your website, and perform heavily used functions frequently. A: Except for low learning curve Zend Framework suits you in every other way a)Hight Performance : Can be easily achieved by implementing Zend_Cache b)Complex DB operations : Can be achieved by integrating Docterine with Zend (althoug Zend_Db can do just fine) c)Feature Rich : It got feature which rarely exist in any other framework for example Zend_Lucene , Zend_Amf d)Customization : Since it does not force directory structure and can be used as library as well since most of the components are independent of each other . e)Testing Suit : Its component are built in testing friendly way you can build your own testing suit with Zend_Test
{ "language": "en", "url": "https://stackoverflow.com/questions/7562496", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UPDATE one table column based on another table's column In one table I have fields cat_id, cat_name the table I need to update has several columns but I only want to update one based on the info in the new one. category I would like to update the category field to the cat_id of the corresponding name. in other word IF cat_id='66' and cat_name='STACKOVER' and category='STACKOVER' The result should be category='66' I'm not sure where to start.. A: If I understood you, UPDATE new_category,category SET new_category.category=category.cat_id WHERE new_category.category=category.cat_name should do the job and lead you toward understanding multi-table updates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add pivot-table to a google spreadsheet, via the API I'd like to automatically create one of these pivot tables: https://drive.googleblog.com/2011/05/summarize-your-data-with-pivot-tables.html Given some data and parameters, the script would create a new google spreadsheet, complete with pivot-table and chart, non-interactively. Is this possible? A: It appears that there is a partial answer. I haven't tried it yet, and I wouldn't swear by it till I do. If anyone does try this technique, post here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Using clearbox with a codeigniter site I'm trying to use clearbox with a codeigniter site. I'm not able to get it to work and I have a feeling it has to do with this line which is located in clearbox.js. I'm not sure if it has to be relative to my view file or what. var CB_ScriptDir='clearbox'; // RELATIVE to your html file! Anyone ever used this plugin before? A: I think that if your website stracture is like * *index.html *js (directory) * * *clearbox.js * * * * *clearbox (directory) Than you should set CB_ScriptDir like this: var CB_ScriptDir='js/clearbox'; A: It has to be relative to your index.html page. When you download the clearbox zip file from the developers page, you get a containing folder called "clearbox" which has both clearbox.js and the actual folder clearbox inside it. If you have your zip containing folder at the level of your index.html page, you would set parameters as follows: var CB_ScriptDir='clearbox/clearbox'; // RELATIVE to your html file! If you take both clearbox.js and the folder clearbox out of the containing clearbox folder, your setting would be: var CB_ScriptDir='clearbox'; // RELATIVE to your html file! The confusion is with the zip extracting clearbox inside a folder named clearbox! A: Make a /js dir in the top directory where your index.php resides. Put clearbox.js and folder /clearbox. var CB_ScriptDir='../../../js/clearbox';
{ "language": "en", "url": "https://stackoverflow.com/questions/7562501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting mouse position in keyboard event I'm trying to have a selection wheel appear when the user holds down the Shift key. The wheel should be centred on the mouse's position. However when I test this, pageX and clientX are both undefined on the event object. Is it possible to get the mouse coordinates on a keyboard event? A: No, simply track mousemove events and continuously save the current position in case you get a keyboard event. A: Cache mouse position in a global variable in every mousemove event and use it when a key event fires: var mousePosition = {x:0, y:0}; $(document).bind('mousemove',function(mouseMoveEvent){ mousePosition.x = mouseMoveEvent.pageX; mousePosition.y = mouseMoveEvent.pageY; }); $(document).bind('keyup', function(keyUpEvent){ $('body').append($('<p/>').text('x:' + mousePosition.x + ' * y: ' + mousePosition.y)); }); JSBIN: http://jsbin.com/uxecuj/4 JavaScript without jQuery: var mousePosition = {x:0, y:0}; document.addEventListener('mousemove', function(mouseMoveEvent){ mousePosition.x = mouseMoveEvent.pageX; mousePosition.y = mouseMoveEvent.pageY; }, false); document.addEventListener('keyup', function(keyUpEvent){ var divLog = document.querySelector('#log'), log = 'x:' + mousePosition.x + ' * y: ' + mousePosition.y, p = document.createElement('p').innerHTM = log; divLog.appendChild(p); }, false); A: Here's the POJS equivalent of other answers that is cross browser back to IE 6 (and probably IE 5 but I don't have it to test any more). No global variables even: function addEvent(el, evt, fn) { if (el.addEventListener) { el.addEventListener(evt, fn, false); } else if (el.attachEvent) { el.attachEvent('on' + evt, fn); } } (function () { var x, y; window.onload = function() { addEvent(document.body, 'mousemove', function(e) { // Support IE event model e = e || window.event; x = e.pageX || e.clientX; y = e.pageY || e.clientY; }); // Show coords, assume element with id "d0" exists addEvent(document.body, 'keypress', function() { document.getElementById('d0').innerHTML = x + ',' + y; }); } }()); But there are bigger issues. Key events are only dispatched if an element that can receive keyboard input is focused (input, textarea, and so on). Also, if the user scrolls the screen without moving the mouse, the coordinates will probably be wrong. An alternative solution is to use CSS to replace the cursor with a custom animation. A: If you're using jQuery, you can do the following (assuming you have an image with id="wheelImage" and whose position is set to absolute), write the following inside your keydown event. Here we use the global properties pageX and pageY that are passed to any handler. You can also use jQuery's shiftKey property to check if the shift key has been pressed. $().keydown(function(e) { if (e.shiftKey) { e.preventDefault(); $('#wheelImage').css('left',e.pageX ).css('top', e.pageY); } }); A: Cache the mouse position. var x = 0, y = 0; document.addEventListener('mousemove', function(e){ x = e.pageX y = e.pageY; }, false); document.addEventListener('keyup', function(e){ console.log(x + ' ' + y); }, false); Or with JS Ninja Library. var x = 0, y = 0; $(document).mousemove(function(e){ x = e.pageX y = e.pageY; }); $(document).keypressed(function() { console.log(x + ' ' + y); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7562503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Batch-File to search current absolute path to find a file or directory? I am trying to search the current directory path and find a certain file or directory that is adjacent to that path. For example: if the current directory of the script is C:\Temp\Dir1\Dir2\Dir3\Dir4\Dir5\Dir6\Test.bat , and if "jars" is a directory located at C:\Temp\jars , then search upwards to find the directory where "jars" is located. This is how I implemented it but I am wondering if there is an easier/shorter way to do it? @echo off SET TITLE=%~nx0 SET SEARCHFOR=jars\Site.jar SET MYDIR=%~p0 SET MYDRIVE=%~d0 SET DIRCHAIN=%MYDIR:\= % :: searches first 4 levels of depth but can be increased if necessary ECHO Searching in directory chain: %MYDRIVE% %DIRCHAIN% FOR /F "tokens=1-4 delims= " %%G IN ("%DIRCHAIN%") DO ( if exist %MYDRIVE%\%SEARCHFOR% ( SET APPHOME=%MYDRIVE% GOTO APPHOMESET ) if exist %MYDRIVE%\%%G\%SEARCHFOR% ( SET APPHOME=%MYDRIVE%\%%G GOTO APPHOMESET ) if exist %MYDRIVE%\%%G\%%H\%SEARCHFOR% ( SET APPHOME=%MYDRIVE%\%%G\%%H\ GOTO APPHOMESET ) if exist %MYDRIVE%\%%G\%%H\%%I\%SEARCHFOR% ( SET APPHOME=%MYDRIVE%\%%G\%%H\%%I GOTO APPHOMESET ) if exist %MYDRIVE%\%%G\%%H\%%I\%%J\%SEARCHFOR% ( SET APPHOME=%MYDRIVE%\%%G\%%H\%%I\%%J GOTO APPHOMESET ) GOTO FAILED ) :FAILED ECHO Did not discover location of APPHOME containing %SEARCHFOR% ECHO Searched no deeper than %MYDRIVE%\%%G\%%H\%%I\%%J :APPHOMESET SET JREHOME=%APPHOME%\Javasoft\jre echo APPHOME is %APPHOME% echo JREHOME is %JREHOME% pause A: The idea is roughly as follows: * *Get the path to the batch script as the current working directory. *Concatenate the subdirectory name. *If the resulting path exists, return the path and exit. *If the current working directory is essentially the root directory, return Not found and exit. *Get the parent directory of the current working directory and repeat from step #2. Here goes: @ECHO OFF SET "subdir=%~1" SET "dir=%~f0" :loop CALL :getdir "%dir%" IF EXIST "%dir%\%subdir%\" ( ECHO %dir%\%subdir% GOTO :EOF ) IF "%dir:~-1%" == ":" ( ECHO Directory "%subdir%" not found. GOTO :EOF ) GOTO loop :getdir SET "dir=%~dp1" SET "dir=%dir:~0,-1%"
{ "language": "en", "url": "https://stackoverflow.com/questions/7562506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android CONTENT TYPE - Is vnd.android.cursor.dir some standard constant defined by android? I have very basic understanding problem of Content types. I went through lot of examples and text explaining the above term, but still have some basic understanding problem. Can some clarify me please. In the android notepad example, and many others, it is mentioned vnd.android.cursor.dir/ resolves to a list of items in a directory and vnd.android.cursor.item/ refers to specific item in a directory. Is this vnd.android.cursor.dir some standard constant defined by android. Where did this come from?, or can i change it like vn.com.android.myexample.dir/ How is this even resolved and what is its purpose, why not use the full CONTENT_URI? Sorry, i'm totally lost, and don't understand this. A: Documentation: https://developer.android.com/guide/topics/providers/content-provider-basics#MIMETypeReference The MIME types returned by ContentProvider.getType have two distinct parts: type/subType The type portion indicates the well known type that is returned for a given URI by the ContentProvider, as the query methods can only return Cursors the type should always be: * *vnd.android.cursor.dir for when you expect the Cursor to contain 0 through infinity items or * *vnd.android.cursor.item for when you expect the Cursor to contain 1 item The subType portion can be either a well known subtype or something unique to your application. So when using a ContentProvider you can customize the second subType portion of the MIME type, but not the first portion. e.g a valid MIME type for your apps ContentProvider could be: vnd.android.cursor.dir/vnd.myexample.whatever The MIME type returned from a ContentProvider can be used by an Intent to determine which activity to launch to handle the data retrieved from a given URI. A: Where did this come from?, or can I change it like vn.com.android.myexample.dir/ No, because "vnd" stands for vendor in MIME Registration trees, android in this case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562509", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "52" }
Q: Singleton in singleton I have a singleton in singleton data structure. Currently my implementation is like below: public class Singleton { private Object embInstance; private Singleton() { embInstance = new Object(); } private static class SingletonHolder { public static final Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.instance; } public Object getEmbInstance() { return embInstance; } public Object resetEmbInstance() { embInstance = null; } } My question are: * *Does 'private Singleton()' have to be empty or is it OK to add some code in it? *Is this implementation thread-safe with respect to embInstance? *This implementation is not lazy-loading for embInstance. How to implement a thread-safe lazy-loading for embInstance? Thanks! A: * *it's ok to add some code to your private, no-args constructor. *I believe the SingletonHolder class will only be initialized once, therefore instance will be guaranteed to be assigned exactly once. However, within the Singleton class you have setters and getters that are not synchronized, so you may have some threading issues there wrt embInstance. *thread-safe lazy-loading: same as lazy-loading, but do it inside a synchronized block: public static Object getInstance() { if(embInstance == null) { synchronized(Singleton.class) { if(embInstance == null) { embInstance = new Singleton(); } } } return embInstance; } Note that this code is both efficient (no synchronization required once your data is initialized) and thread-safe (initialization occurs inside a synchronized block). Hope that helps. A: The synchronized keyword keeps the methods thread-safe. The getEmbInstance() is the standard way to do lazy instantiation. public class Singleton { private Object embInstance; private Singleton() { } private static class SingletonHolder { public static final Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.instance; } public synchronized Object getEmbInstance() { if (embInstance == null) embInstance = new Object(); return embInstance; } public synchronized Object resetEmbInstance() { embInstance = null; } } A: ....eh ...isn't that overcomplexifying things? Why have a singleton in a singleton? Why so many classes? Moreover, you have a method to 'reset' your singleton to null, but none to actually instantiate a new one. Why not simply: public class Singleton { private static Singleton instance; private Singleton() { } public static synchronized Singleton getInstance() { if (instance == null) instance = new Singleton(); // The "lazy loading" :p return instance; } } A: * *Not sure, what you mean. It is certainly syntactically acceptable to have code in the Singleton constructor *This is not inherently thread safe. If embInstance is accessed by multiple threads even if it is via getEmbInstance, it will suffer from race conditions. You must use synchronized to access it if you wish for threadsafety. *To implement a thread-safe lazy load, you must have a lock that prevents changes to Singleton. You can just use the instance of Singleton to lock it as such: synchronized(this) Also, you don't need SingletonHolder you can just have a public static Singleton instance in the Singleton class itself. A: public class A { A a; private A() {} synchronized public static A getOb() { if (a == null) { a = new A(); } return a; } } You should use synchronized for thread-safety in Singleton.
{ "language": "en", "url": "https://stackoverflow.com/questions/7562512", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inviting Facebook friends through iPhone App I've been searching this question, and I haven't been able to find anything that works. I have an iPhone app that allows users to link their Facebook account. It would look something like this: Once a user has successfully linked to FB, I want to present them with a list of their FB friends and an option to invite selected friends. FB Friend 1........... Invite FB Friend 2........... Invite ... FB Friend 1000..... Invite Basically, I want to send a message to FB friends that says something like "Check out this app". I'm pretty sure this has to go to either their notifications or wall and cannot go as a FB message, but I can't figure out how to do it. Also, I don't need to select a group of friends to invite -- this can be done one at a time. So it would look like this: FB Friend 1........... invited FB Friend 2........... Invite ... FB Friend 1000..... Invite Thanks so much for any help you can provide. A: Unfortunately there isn't anything in the iOS SDK that presents the apprequests dialog, and a user has to have installed/approved your application before you can send them application notifications via a POST request... Requests are a great way to enable users to invite their friends, accept a gift or help them complete a mission in your app. There are now two types of requests that can be sent from an app: User-generated requests: These requests are confirmed by a user’s explicit action on a request dialog. These requests update the bookmark count for the recipient. You send requests by using the recently launched Request Dialog. App-generated requests: These requests can be initiated and sent only to users who have authorized your app. Developers can send these requests using the Graph API. Use these requests to update the bookmark count to encourage a user to re-engage in the app (e.g., your friend finished her move in a game and it’s now your turn). The only way to get this is via Facebook's Requests 2.0 dialog (which is not currently available to the Facebook iOS SDK): http://developers.facebook.com/blog/post/453 See more here in this related question... Sending application requests that appear in the left column on Facebook home page?
{ "language": "en", "url": "https://stackoverflow.com/questions/7562516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Porting C# code to run on OSX We have a console app that runs in .NET 3.5. It connects to a USB device and spits out data received from it. I'd like to port this over to OSX and have some questions about the strategy to do this. The USB Driver is already installed on OSX. Mono looks promising but I don't get it. Does the end user have to install Mono or run something? After looking at some other posts it seems that you can write a bash script and do some hacking to get the program installed...but I can't find a really good explanation of this. it also seems that mono wouldn't be installed in this process. These posts were also from '09 so I'm wondering if something has changed to make this easier. My question is, what's a good way to approach running/porting a C# console app to OSX. A: .NET is compiled down to IDL (bytecode) on all platforms including the windows platform. It is then run on the CLR (common language runtime iirc) which is a similar concept to the Java Virtual Machine. It just so happens that on most Windows machines that this CLR is installed by default. So if you wish your application to run on another platform you first need a CLR for that platform. Mono does include a CLR which can run on OSX. So either you (as part of your package/ bundle ) or the user would need to install this before your .NET will run. The other issue you have is that .NET also contains certain API's which are not part of the ECMA standard which your application may or may not use. Some of these API's are present in mono, some of them are not. Those that are not usually have an equivalent or similar API which you can use to achieve the same thing however you may need to alter your application to deal with that scenario. It really depends on what .NET api's your application is using as to how difficult it will be to port. I am guessing you are probably using winforms as part of your application so here is the guide from the mono site for that portion of the API http://www.mono-project.com/Guide:_Porting_Winforms_Applications A: You can bundle the Mono installer with your application (or your own build of Mono). You might even have the option of statically linking the mono runtime into your application on the Mac, I can't remember if it's supported (yet) or not. I'm pretty sure you can. Also, wrt gordatron's warnings, if you use Path.Combine() to create paths instead of hard-coding \ as your path separator (which you should be doing anyway), you won't have to worry about having file system path problems. For a nice easy way to check if your app uses any features which aren't available in Mono, you can use http://www.mono-project.com/MoMA to check for unsupported methods/classes and any other potentially non-cross-platform blockers like P/Invokes. For a console application, I don't see you running into many issues (although you'll likely need to interface with the USB hardware differently than you do in Windows).
{ "language": "en", "url": "https://stackoverflow.com/questions/7562517", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I insert content to DIV on the top of existing content using jquery? Using the .append() function inserts content at the bottom. How to add to the top of the existing content? A: Use .prepend()
{ "language": "en", "url": "https://stackoverflow.com/questions/7562523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }