text stringlengths 8 267k | meta dict |
|---|---|
Q: GetSystemInfo always returns 0 for dwAllocationGranularity on Win7 from Win Service I'm attempting to get the allocation granularity size using GetSystemInfo() from a C# 3.5 windows service application on Windows 7. However the SYSTEM_INFO struct always has 0 in dwAllocationGranularity when it is returned from the call (other fields have data filled in as expected)
The SYSTEM_INFO struct looks like this with PROCESSOR_ARCHITECTURE and PROCESSOR_TYPE enums omitted for brevity:
public struct SYSTEM_INFO
{
public PROCESSOR_ARCHITECTURE wProcessorArchitecture;
public ushort wReserved;
public uint dwPageSize;
public int lpMinimumApplicationAddress;
public int lpMaximumApplicationAddress;
public uint dwActiveProcessorMask;
public uint dwNumberOfProcessors;
public PROCESSOR_TYPE dwProcessorType;
public uint dwAllocationGranularity;
public ushort wProcessorLevel;
public ushort wProcessorRevision;
}
The extern call to GetSystemInfo is this:
[DllImport("kernel32")]
public static extern void GetSystemInfo(ref SYSTEM_INFO SystemInfo);
The calling code is like this:
SYSTEM_INFO sysInfo = new SYSTEM_INFO();
GetSystemInfo(ref sysInfo);
The Output SYS_INFO struct after running code is:
dwActiveProcessorMask 4294901759
dwAllocationGranularity 0
dwNumberOfProcessors 2047
dwPageSize 4096
dwProcessorType 15
lpMaximumApplicationAddress 0
lpMinimumApplicationAddress 65536
wProcessorArchitecture 9
wProcessorLevel 4
wProcessorRevision 0
wReserved 0
Any ideas what I'm missing or suggestions on other ways to get this info (I don't want to hard code to 64Kb JIC it is changed at some point)? Thanks.
A: You also don't have 2047 processors :) The declaration is wrong, it will fail in 64-bit mode. lpMin/MaxApplicationAddress and dwActiveProcessorMask are IntPtr.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I change a value for a key at a specific index? I have been stuck trying to figure out how to change a value for a key at a specific index. For example if I have the following data,
Index | slideNumber | Title
--------------------------------------------
1 | 5 | test 1
2 | 2 | test 2
3 | 5 | test 3
4 | 7 | test 4
5 | 9 | test 5
If I want to change the value of slideNumber at index 3, how would I do that? Thank you in advance!
A: Edit (thanks for the suggestion @morningstar):
This would probably be a quicker way to do it:
- (void)newSlideNumber:(NSInteger)slideNumber
forIndex:(NSInteger)index {
NSError *error = NULL;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Slides"
inManagedObjectContext:self.managedObjectContext]];
[request setPredicate:[NSPredicate predicateWithFormat:@"Index == %d", index]];
NSArray *results = [self.managedObjectContext executeFetchRequest:request
error:&error];
[request release];
if ([results count]) {
[(NSManagedObject *)[results objectAtIndex:0] setValue:[NSNumber numberWithInteger:slideNumber]
forKey:@"slideNumber"];
} else if (error) {
NSLog(@"%@", [error description]);
} else {
NSLog(@"predicateWithFormat (Index == %d) did not match any objects!", index);
}
}
Orig
Are you doing this with CoreData? If so, here is a guide (untested and probably wont work exactly as it is if copy/pasted. Just to be used as an example):
- (void)newSlideNumber:(NSInteger)slideNumber forIndex:(NSInteger)index withTitle:(NSString *)title {
NSError *error = NULL;
// Delete the objects first, then recreate them:
[self deleteObjectsForEntityNamewithPred:@"MyEntityName" withPredicate:[NSPredicate predicateWithFormat:@"Index == %d", index]]; // This method is the one defined below
// Get the managed object from your context:
NSManagedObject *managedObjectStore = [NSEntityDescription insertNewObjectForEntityForName:@"MyEntityName" inManagedObjectContext:self.managedObjectContext];
// Set the new values:
[managedObjectStore setValue:[NSNumber numberWithInteger:index] forKey:@"Index"];
[managedObjectStore setValue:[NSNumber numberWithInteger:slideNumber] forKey:@"slideNumber"];
[managedObjectStore setValue:title forKey:@"Title"];
// Save the context
[self.managedObjectContext save:&error];
if (error) {
NSLog(@"%@", [error description]);
}
}
- (void)deleteObjectsForEntityNamewithPred:(NSString *)entityName withPredicate:(NSPredicate *)pred {
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entity];
[request setPredicate:pred];
NSError *error = NULL;
NSArray *results = [self.managedObjectContext executeFetchRequest:request error:&error];
[request release];
if (error) {
NSLog(@"%@", [error description]);
}
for (NSManagedObject *managedObject in results) {
[self.managedObjectContext deleteObject:managedObject];
}
}
Some Reference Docs:
NSPersistentStoreCoordinator Class Reference
NSManagedObjectContext Class Reference
NSManagedObjectModel Class Reference
A: Assuming that your Core Data Entity has three attributes: index, slideNumber, title
You can retrieve the correct entity (an instance of a row in that table if you are thinking like a database which I recommend against) with the following code:
NSManagedObjectContext *moc = ...;
NSInteger myIndex = 3;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@"index == %i", myIndex]];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
if (error && !results) {
NSLog(@"Error %@\n%@", [error localizedDescription], [error userInfo]);
}
NSManagedObject *myEntity = [results lastObject];
Now that we have the entity, editing a value is a simple KVC call away:
[myEntity setValue:[NSNumber numberWithInteger:5 forKey:@"slideNumber"];
From there, you will probably want to save your changes:
NSManagedObjectContext *moc = ...;
NSError *error = nil;
if (![moc save:&error]) {
NSLog(@"Error %@\n%@", [error localizedDescription], [error userInfo]);
}
It is best to think of Core Data as an object graph and NOT as a table in a database. The database is just a means to persist the data.
I also recommend reading up on KVC (Key Value Coding). You can avoid using KVC if you want by subclassing your NSManagedObjects but it is unnecessary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: apply list-style-type to ul or li I cant seem to find a conclusive answer on whether i should be applying the style list-style-type ( or any of it's relatives ) to ul/ol tags or to the li tag. This is probably because it doesn't make any difference but maybe someone could confirm that and offer a suggestion as to best practice.
A: As you can see from the W3C documentation, it applies to elements with display: list-item, that means to ul and ol elements.
A: the best practice is to assign list styles to the list itself (ul, ol), and li's will have it because of the cascading
from w3 css2.1 recommendation:
Inheritance will transfer the 'list-style' values from OL and UL elements to LI elements. This is the recommended way to specify list style information.
however, ie6 and 7 won't recognize this inheritance correctly, so you'll have to apply the list styles to li elements if you plan to support them
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Textfield event is never called in delegate In my interface I have:
@interface MainViewController : UIViewController <SKProductsRequestDelegate, SKPaymentTransactionObserver, UITextFieldDelegate> {
UITextField *Stock;
// ....
}
This is the implementation I have:
- (BOOL)Stock:(UITextField *)textField shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
if([[textField text] isEqualToString:@"\n"]) {
[textField resignFirstResponder];
return NO;
}
return YES;
}
In the viewDidLoad I have Stock.delegate = self;
I am expecting this method is called after any character is typed in the text field. But this routine is never called. What is the problem?
Thanks
A: If this is a UITextField, you've just implemented a random method. The actual delegate method is
-textField:shouldChangeCharactersInRange:replacementString:
Try providing that one.
A: Did you wire the TextField (Stock in your case) Delegate to FileOwner ?
If not then try this in viewDidLoad method of the Controller
Stock.delegate = self;
Or you can just wire it in IB.
A: *
*Declare MainViewController conforming UITextFieldDelegate:
@interface MainViewController : UIViewController < UITextFieldDelegate >
*To be called this method of UITextFieldDelegate should be declared as:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
*In code or in IB MainViewController should be set to be delegate.
Correct and it will be fired as supposed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Include() - Header and Footer I use php include() for my header, footer, navigation etc.
I have the following code repeated on each of my pages
<?php include 'includes/header.php'; ?>
Is there a faster way to do this? Can I store the data i am including somewhere for loading speed??
A: *
*If you aren't experiencing any problems with loading pages, you shouldn't be concerned of a faster ways.
*If you're experiencing some problems with page loading, these problems certainly NOT from the way you're including headers. You have to profile your site execution and find real part that slows whole thing down.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Return of memory at the termination of a C++ program When a C++ program terminates, the RAM used during the run gets cleaned and is returned to the system, correct?
Question 1)
Is this memory returned managed by C++ language features or by the computer hardware itself?
Question 2)
Does the memory get returned efficiently/safely, if I terminate a run using ctrl+Z in Unix terminal?
A:
When a C++ program terminates, the RAM used during the run gets cleaned and is returned to the system, correct?
Correct. By System, I hope you mean, Operating System.
Question 1) Is this memory returned managed by C++ language features or by the computer hardware itself?
The returned memory is managed by the operating system (if I correctly understand the question). And before returning to the OS, the memory is managed by the process; in low-level, which means, managed by various language features, such as allocation- deallocation mechanism, constructors, destructors, RAII, etc.
Question 2) Does the memory get returned efficiently/safely, if I terminate a run using ctrl+Z in Unix terminal?
Ctrl+Z suspends the process. It doesn't terminate it. So the memory doesn't get returned to the OS as long as the process is not terminated.
In linux, Ctrl+C terminates the process, then the memory returns to the OS.
A: *
*Typically both. At least assuming normal termination, destructors will run, which will typically free the memory associated with those objects. Once your program exits, the OS will free all the memory that was owned by that process.
*A forced termination often won't run the destructors and such, but any reasonable operating system is going to clean up after a process terminates, whether it did so cleanly or not. There are limits though, so if you've used things like lock files, it probably can't clean those up.
A:
Q: When a C++ program terminates, the RAM used during the run gets
cleaned and is returned to the system, correct?
A: Correct. This is true for ANY program, regardless of the language it was written in, and regardless of whether it's Linux, Windows or another OS
Q Is this memory returned managed by C++ language features or by the
computer hardware itself?
A: Neither: the operating system is responsible for managing a process's memory.
Q: Does the memory get returned efficiently/safely, if I terminate a
run using ctrl+Z in Unix terminal?
A: OS resources (such as memory) are freed. But you can leave files corrupted, IPCs locked, and other Bad Things that are beyond the OS's control if you kill a program gracelessly.
'Hope that helps
A:
Is this memory returned managed by C++ language features or by the computer hardware itself?
Both occur, assuming a proper shutdown (vs. a crash or kill). The standard C/C++ library deallocates any (non-leaked) memory it allocated via OS system calls and ultimately the OS cleans up any leaked memory.
Does the memory get returned efficiently/safely, if I terminate a run using ctrl+Z in Unix terminal?
Ctrl-Z suspends a process on Unix. If you terminate it using kill or kill -9, the memory will be reclaimed (safely / efficiently) by the OS.
A: They say that dynamically allocated memory is only returned by you, the programmer. For example, a
myclass *obj = new myclass();
always has to have a corresponding
delete obj;
somwehere, or else your program will leak memory, meaning the operating system could think that certain parts of memory are used when in fact they are not - after too many leaks your memory might be used up by false memory entirely and you won't be able to do anything with it.
However, "C++" (effectively meaning "the compiler") takes care of everything that you allocate on the stack, like
myclass obj;
as long as your destructors actually correctly deletes anything which you dynamically create inside that class.
In practice however, if you leak memory, modern operating systems will take care of it and usually clean it up. Usually there's some system in place where the OS will be able to recognize what parts of the memory you actually used, and then simply free everything in there as soon as the application is terminated.
Memory leaks usually only really create problems when your application needs so much memory that it needs to correctly free up some from time to time, or when you continuously leak memory in a loop (like in games), on systems with limited memory (like consoles).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Xcode 4 Hangs on Exception I'm running my app in Xcode 4 using the simulator. Whenever an exception is thrown and the debugger shows me the line at which it crashed, Xcode wont allow me to kill the app. I can edit my code, even rebuild it, but I can't terminate the current run. I have been killing Xcode all together and restarting, but there has to be something I'm missing, right?
A: When i first downloaded Xcode it did the same thing to me but a clean Re- Install fixed it for me.
A: What happens when you go to the debugger console and enter "kill"? It should ask you to confirm that you want to kill the running inferior process, and once you confirm that, the inferior (the application it's debugging) should be murdered.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Side-by-side divs with different height I have placed two divs next to each other, I have specified the same height for both but the second one appears to be higher than the first one. Why is this happening, they should have the same height but they aren't.
body {
font-family: Arial, Helvetica, sans-serif;
background : #CD8C95;
}
div {
height:30em;
}
div#links {
font-size:18px;
font-family:Geneva, Arial, Helvetica, sans-serif;
background : #EEDD82;
padding-top: 15%;
padding-left: 10px;
width : 12em;
float:left;
}
div#content {
padding-left: 5em;
padding-top:10em;
background:#FFA07A;
float:left;
width:20em;
}
A: As you can see in the W3C documentation, the actual dimensions of a box are produced by the height/width, plus the margins and paddings. Since you specified different margins/paddings for your divs, you have different actual heights.
A: Because of the different amount of padding, which is being calculated after the height. In other words, the height of div#links is 30em + 15%, and the height of div#content is 30em + 10em. See the W3C's box model documentation.
You could add a CSS box-sizing rule such as box-sizing: border-box or box-sizing: padding-box to fix this in browsers that support it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: execute a sql script file from cx_oracle? Is there a way to execute a sql script file using cx_oracle in python.
I need to execute my create table scripts in sql files.
A: PEP-249, which cx_oracle tries to be compliant with, doesn't really have a method like that.
However, the process should be pretty straight forward. Pull the contents of the file into a string, split it on the ";" character, and then call .execute on each member of the resulting array. I'm assuming that the ";" character is only used to delimit the oracle SQL statements within the file.
f = open('tabledefinition.sql')
full_sql = f.read()
sql_commands = full_sql.split(';')
for sql_command in sql_commands:
curs.execute(sql_command)
A: Another option is to use SQL*Plus (Oracle's command line tool) to run the script. You can call this from Python using the subprocess module - there's a good walkthrough here: http://moizmuhammad.wordpress.com/2012/01/31/run-oracle-commands-from-python-via-sql-plus/.
For a script like tables.sql (note the deliberate error):
CREATE TABLE foo ( x INT );
CREATE TABLER bar ( y INT );
You can use a function like the following:
from subprocess import Popen, PIPE
def run_sql_script(connstr, filename):
sqlplus = Popen(['sqlplus','-S', connstr], stdin=PIPE, stdout=PIPE, stderr=PIPE)
sqlplus.stdin.write('@'+filename)
return sqlplus.communicate()
connstr is the same connection string used for cx_Oracle. filename is the full path to the script (e.g. 'C:\temp\tables.sql'). The function opens a SQLPlus session (with '-S' to silence its welcome message), then queues "@filename" to send to it - this will tell SQLPlus to run the script.
sqlplus.communicate sends the command to stdin, waits for the SQL*Plus session to terminate, then returns (stdout, stderr) as a tuple. Calling this function with tables.sql above will give the following output:
>>> output, error = run_sql_script(connstr, r'C:\temp\tables.sql')
>>> print output
Table created.
CREATE TABLER bar (
*
ERROR at line 1:
ORA-00901: invalid CREATE command
>>> print error
This will take a little parsing, depending on what you want to return to the rest of your program - you could show the whole output to the user if it's interactive, or scan for the word "ERROR" if you just want to check whether it ran OK.
A: Into cx_Oracle library you can find a method used by tests to load scripts: run_sql_script
I modified this method in my project like this:
def run_sql_script(self, connection, script_path):
cursor = connection.cursor()
statement_parts = []
for line in open(script_path):
if line.strip() == "/":
statement = "".join(statement_parts).strip()
if not statement.upper().startswith('CREATE PACKAGE'):
statement = statement[:-1]
if statement:
try:
cursor.execute(statement)
except Exception as e:
print("Failed to execute SQL:", statement)
print("Error:", str(e))
statement_parts = []
else:
statement_parts.append(line)
The commands into script file must be separated by "/".
I hope it can be of help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Remote client configuration I'm looking for an approach: We have several applications that work with third-party applications. The settings of our applications have to be changed regularly (e.g. with every event, the third party tools require changed config items). The mentioned settings reside in the config-Files of our applications. Those applications are mostly operated in a LAN.
How can those changing (and required) settings be distributed in a elegant way so we change the settings once and the other applications pull those settings? Are there existing components in .net? How would you approach this problem? Maybe create a service and make all the applications act as config clients? Hope for some ideas!
A: Create an updater for all distributed application (this will be one time update) and distribute one more time. That updater will read the updates from server and update the application config, and restart itself. You should have versions or date time stamp so that your updater will update only when there is change in your DB. BigL approach wont work if application is not online, but this will. You can skip the update if service is not available.
A: That's an interesting question maybe you could try to store the settings in a central database and your applications would load the settings from there directly or through a service. I think i would choose a compact sql database.
And you need to store the settings in app.config too and if you start your app then look for the service and if available then update the settings in the local config if needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is the rightmost character captured in backreference when using a character class with quantifiers? If I have pattern ([a-z]){2,4} and string "ab", what would I expect to see in backreference \1 ?
I'm getting "b", but why "b" rather than "a"?
I'm sure there is a valid explanation, but reading around various sites explaining regexes, I haven't found one. Anybody?
A: I'm not sure why nobody put this as an answer, but just for anyone hitting this page with a similar question, the answer is essentially that this regex:
([a-z]){2-4}
will match a single character between a and z at least 2 and as many as 4 times. It will match each character separately, overwriting anything previously matched and stored into the backreference (that is, whatever is between the () characters in the expression).
A similar expression (suggested in the comments on the question):
([a-z]{2,4})
moves the back-reference to surround the entire match (2-4 characters a-z) instead of a single character.
The parentheses represent a capture into a back-reference. When the repetition is inside the capture (the second example), it will capture all characters that make up that repetition. When the repetition is outside the capture (the first example), it will capture one letter, then repeat the process, capturing the next letter into the same back-reference, thus overwriting it. In this case, it will then repeat that process up to 2 more times, overwriting it each time.
So, matching against the target abc will result in \1 equaling c. Matching the target against abcd will result in \1 equaling d. With more letters, and depending upon the function (and language) used to run the regular expression, the target abcde might fail to match, or might result in the back-reference \1 equaling d (because the e is not part of the match).
The first example expression can be used to get abc or abcd if you use the whole match back-reference (often times $& or $0, but also \& or \0 and in Tcl, just an & character) - this returns the entire string matched by the entire regular expression.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OSGi Remote DS product configuration works only inside Eclipse I'm working on Eclipse STS 2.7.2 with Java JDK 1.6, Windows XP SP3. I work behind a proxy which requires authentication.
I wrote two simple client and server plugins which work using DS and Zookeeper discovery. They refer to an IHello interface bundled in a third plugin.
The server publishes a simple Hello service which returns a string "hello" when invoked on 192.16.23.28:6666/hello and starts Zookeper with VM arguments
-Dzoodiscovery.dataDir=bla
-Dzoodiscovery.flavor=zoodiscovery.flavor.standalone=192.168.23.28:3030;clientPort=3031
xml is:
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="NOLINKALLOWED" name="it.eng.test.remote.ds.helloservice">
<implementation class="it.eng.test.remote.ds.helloservice.HelloService"/>
<property name="service.exported.interfaces" type="String" value="*"/>
<property name="service.exported.configs" type="String" value="ecf.generic.server"/>
<property name="ecf.exported.containerfactoryargs" type="String" value="ecftcp://192.168.23.28:6666/hello"/>
<service>
<provide interface="it.eng.test.remote.ds.hello.IHello"/>
</service>
</scr:component>
the client starts Zookeeper with VM arguments
-Dzoodiscovery.autoStart=true
-Dzoodiscovery.flavor=zoodiscovery.flavor.standalone=192.168.23.28:3031;clientPort=3030
In both cases the OSGi framework is started with the -console -consoleLog -clean arguments.
I then created two separated run configuration for both server and client (Run as->run configurations..) adding all required bundles (most important ones: org.eclipse.ecf.provider.remoteservice and org.eclipse.ecf.provider.zookeeper) and their dependencies.
Based on that configuration I defined two separated product configurations (new->product definition->select run configuration) for both client and server.
Now, if I run them by clicking on the link "Launch an Eclipse application" inside the respective product configuration, everything works. The server publishes the service, the client gets it and shows "Hello" on output. netstat -a | grep 6666 shows that someone is listening on that port and netstat -a | grep 30 shows that port 3030 and 3031 are being used.
Eclipse is configured to use my proxy correctly.
If I export them as an Eclipse product based on the aforementioned configurations (export->eclipse product->select product configuration), I get two folders: client and server.
Inside them there's everything needed to run the applications inside an external OSGi framework, including configuration files for both the framework (config.ini) and the VM (eclipse.ini).
The applications are started with STS.exe -console which opens an OSGi console with all the required bundles installed and started.
Starting the server works, I see someone listening on 6666 and zookeeper reports that the service has been published.
If I start the client, nothing happens. No output, no connections on 3030 and 3031, no errors. It simply does nothing, zookeeper however says it has started discovery.
Using localhost instead of my IP changes nothing, it still works inside Eclipse but not outside.
A: The exported application had its configuration stored in: ./eclipse.ini and the OSGi framework configuration was in ./configuration/config.ini
eclipse.ini contained the parameters needed by the Java VM for zookepeer to work:
-consoleLog
-console
-clean
-vmargs
-Declipse.ignoreApp=true
-Dosgi.noShutdown=true
-Dzoodiscovery.autoStart=true;
-Dzoodiscovery.flavor=zoodiscovery.flavor.standalone=localhost:3031;clientPort=3030
Launching the application was ok but that file wasn't read.
manually launching the application as:
java -Dzoodiscovery.autoStart=true; -Dzoodiscovery.flavor=zoodiscovery.flavor.standalone=192.168.23.28:3031;clientPort=3030 -jar org.eclipse.osgi_3.7.0.v20110613.jar -console -configuration c:\temp\zooc\configuration\
from within ./plugins where all the jars were worked.
Guess the .exe made automatically by Eclipse wasn't well configured to read its config file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Highcharts scatter plot with variable line width I want to plot a scatter chart with lines connecting each point. Is it possible to vary the width of the line between each segment?
For example, I want the line from point A to point B to have a width of 5. I want the line between point B and point C to have a width of 2.
Sure, I could use the renderer to manually draw the lines, but then I have to handle the coordinates and scaling manually.
(FWIW, here's an example of a scatter plot with connecting lines.)
A: There is no configuration option to do this. The difficult way would be, as you say, to implement it your self with help of the renderer.
You can configure individual points with color and size:
data: [{
x: 161.2,
y: 51.6,
marker: {
radius: 15,
fillColor: 'rgb(255, 0, 0)'
}
}]
but the line that connects two markers do not have any individual settings.
A: There is a way to do this without using the renderer, however it is very much a hack.
The basic premise is that you can adjust the thickness of a line in Highcharts after render time by manipulating the SVG or VML attributes, and you can prevent Highcharts from changing it back. Therefore all you need to do is break up your series into two point series and chart them all at once. Code below, fiddle can be seen here http://jsfiddle.net/39rL9/
$(document).ready(function() {
//Define the data points
DATA = [
{x: 2,y: 4,thickness: 1},
{x: 7,y: 8,thickness: 8},
{x: 10,y: 10,thickness: 2},
{x: 22,y: 2,thickness: 10},
{x: 11,y: 20,thickness: 15},
{x: 5,y: 15,thickness: 2}
]
//Format the data into two point series
//and create an object that can be put
//directly into the "series" option
var finalSeries = [];
for (var i=0; i < DATA.length-1; i++) {
finalSeries[i]={};
finalSeries[i].data = [];
finalSeries[i].data.push(DATA[i]);
finalSeries[i].data.push(DATA[i+1])
};
//A function to change the thickness of
//the lines to the proper size
function changeLineThick(){
var drawnSeries = $(".highcharts-series")
for (var i=0; i < drawnSeries.length; i++) {
drawnSeries.eq(i)
.children("path")
.eq(3) //this could change depending on your series styling
.attr("stroke-width",DATA[i].thickness)
};
}
//Define and render the HighChart
chart = new Highcharts.Chart({
chart: {
renderTo: "chart-container",
defaultSeriesType: "scatter"
},
plotOptions: {
scatter: {
lineWidth: 2
}
},
symbols: ["circle","circle","circle","circle","circle","circle"],
series: finalSeries
})
changeLineThick();
//prevent Highcharts from reverting the line
//thincknesses by constantly setting them
//to the values you want
$("#chart-container").mousemove(function(){changeLineThick()})
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get JSON object data from a webpage using javascript I am new to web and I need to get JSON object for a webpage that has data displayed this:
{
"expires": "2011-09-24T01:00:00",
"currencies": {
"BZD": {
"a": "2.02200",
"b": "1.94826"
},
"YER": {
"a": "220.050",
"b": "212.950"
}
}
I tried use jquery's $.getJSON to get the object but it didn't work.
<script>
$.getJSON("http://m.somewebsite.com/data",
{
format: "json"
},
function(data) {
document.getElementById('test').innerHTML = data;
});
</script>
I am wondering how to get this information correctly?
A: In order for this to work, you need to define jsonp, jsonp allows you to gain read access to another site's document, as the alternate version is barred.
$.getJSON("http://m.somewebsite.com/data?callback=?", { format: "json" }, function(data) { document.write(data); });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Combine zip archives in ANT with both filtering and case-sensativity I want to combine several zip files together using ANT, but I've got three restrictions that cause the standard techniques to fail:
*
*There are files (with known filenames) that I do not want included in the final archive.
*Some of the source archives contain files with the same name, but different capitalization.
*The machine that runs the script uses a case-insensitive filesystem.
To make my problem concrete, here's an example source archive. I do not know the file names represented by a.txt and A.txt, but I do know the filename b.txt.
$ touch a.txt ; zip src.zip a.txt ; rm a.txt
$ touch A.txt ; zip src.zip A.txt ; rm A.txt
$ touch b.txt ; zip src.zip b.txt ; rm b.txt
$ unzip -l src.zip
Archive: src.zip
Length Date Time Name
-------- ---- ---- ----
0 09-23-11 11:35 a.txt
0 09-23-11 11:35 A.txt
0 09-23-11 11:36 b.txt
-------- -------
0 3 files
And here's what I want: (everything from the original archive except b.txt)
$ ant
$ unzip -l expected.zip
Archive: expected.zip
Length Date Time Name
-------- ---- ---- ----
0 09-23-11 11:35 a.txt
0 09-23-11 11:35 A.txt
-------- -------
0 2 files
The two techniques that I've found recommended on the internet are:
<target name="unzip-then-rezip">
<!-- Either a.txt or A.txt is lost during unzip and
does not appear in out.zip -->
<delete dir="tmp"/>
<delete file="out.zip"/>
<mkdir dir="tmp"/>
<unzip src="src.zip" dest="tmp"/>
<zip destfile="out.zip" basedir="tmp" excludes="b.txt"/>
</target>
<target name="direct-zip">
<!-- Have not found a way to exclude b.txt from out.zip -->
<delete file="out.zip"/>
<zip destfile="out.zip">
<zipgroupfileset dir="." includes="*.zip" />
</zip>
</target>
Using unzip-then-rezip, I loose either a.txt or A.txt because the underlying filesystem is case-insensitive and can not store both files. Using direct-zip seems like the right way to go, but I have yet to find a way to filter out the files I don't want included.
I'm about to resort to creating my own ANT task to do the job, but I'd much rather use standard ANT tasks (or even ant-contrib), even if there's a performance or readability penalty.
A: I ended up creating a custom ANT task to solve the problem. The task accepts nested excludes elements which provide regular expressions that are matched against the entires in the source zip file.
As an added bonus, I was also able address another problem: renaming zip entries using regular expressions using a nested rename element.
The ANT code looks something like this:
<filter-zip srcfile="tmp.zip" tgtfile="target.zip">
<exclude pattern="^b\..*$"/>
<rename pattern="^HELLO/(.*)" replacement="hello/$1"/>
</filter-zip>
The kernel of the ANT task looks something like this:
zIn = new ZipInputStream(new FileInputStream(srcFile));
zOut = new ZipOutputStream(new FileOutputStream(tgtFile));
ZipEntry entry = null;
while ((entry = zIn.getNextEntry()) != null) {
for (Rename renameClause : renameClauses) {
...
}
for (Exclude excludeClause : excludeClauses) {
...
}
zOut.putNextEntry(...);
// Copy zIn to zOut
zOut.closeEntry();
zIn.closeEntry();
}
In my original question, I said I wanted to combine several zip files together. This is pretty straight forward using the 'direct-zip' method in the original question. I use this to create an intermediate zip file (tmp.zip) which I then use as the source to my filter-zip task:
<zip destfile="tmp.zip">
<zipgroupfileset dir="." includes="*.zip" />
</zip>
At the moment my filter-zip task runs a little slower then the zip (assemble all the zips) task... so the performance is (probably) pretty close to ideal. Combining the two steps together would be a nice little exercise, but not very high ROI for me.
A: Have a look at Ant's Resource Collections, especially things like restrict that allow you to filter files (and zip file contents etc.) in quite flexible ways.
This snippet seems to what you want (on my machine at least - OSX):
<project default="combine">
<target name="combine">
<delete file="expected.zip" />
<zip destfile="expected.zip">
<restrict>
<zipfileset src="src.zip" />
<not>
<name name="b.txt" />
</not>
</restrict>
</zip>
</target>
</project>
The input file:
$ unzip -l src.zip
Archive: src.zip
Length Date Time Name
-------- ---- ---- ----
0 09-24-11 00:55 a.txt
0 09-24-11 00:55 A.txt
0 09-24-11 00:55 b.txt
-------- -------
0 3 files
The output file:
$ unzip -l expected.zip
Archive: expected.zip
Length Date Time Name
-------- ---- ---- ----
0 09-24-11 00:55 A.txt
0 09-24-11 00:55 a.txt
-------- -------
0 2 files
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Replace anchor text with PHP (and regular expression) I have a string that contains a lot of links and I would like to adjust them before they are printed to screen:
I have something like the following:
<a href="http://www.dont_replace_this.com">replace_this</a>
and would like to end up with something like this
<a href="http://www.dont_replace_this.com">replace this</a>
Normally I would just use something like:
echo str_replace("_"," ",$url);
In in this case I can't do that as the URL contains underscores so it breaks my links, the thought was that I could use regular expression to get around this.
Any ideas?
A: Here's the regex: <a(.+?)>.+?<\/a>.
What I'm doing is preserving the important dynamic stuff within the anchor tag, and and replacing it with the following function:
preg_replace('/<a(.+?)>.+?<\/a>/i',"<a$1>REPLACE</a>",$url);
A: This will cover most cases, but I suggest you review to make sure that nothing unexpected was missed or changed.
pattern = "/_(?=[^>]*<)/";
preg_replace($pattern,"",$url);
A: You can use this regular expression
(>(.*)<\s*/)
along with preg_replace_callback .
EDIT :
$replaced_text = preg_replace_callback('~(>(.*)<\s*/)~g','uscore_replace', $text);
function uscore_replace($matches){
return str_replace('_','',$matches[1]); //try this with 1 as index if it fails try 0, I am not entirely sure
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Setting up a maven project for already made jars I have some jar files that I need to include in my build - I'd rather not specify them as system dependencies - that creates a nightmare for setup. I have been uploading them to artifactory and then they can be pulled down directly, but I won't always have access to artifactory while building.
What I was thinking of doing is creating a project that has these jar files in them. It could be one per or all of them (open to suggestion). I was wondering if there is a graceful way to handle this?
What I have done (which is clearly a hack) have a project that takes the jar and during the compile phase it unpacks the jar into the target/classes directory. It then packs those class files back during the package phase. it essentially creates the same jar file again...massively hackey. Could I add the jar into the resource area or is there a different project type I could use? I am open to any ideas.
A: You may try to use install:install-file. I would go about it in the following way.
*
*Create project that contains all your jars in some location
*Configure install:install-file in pom of this project to install jars in repository in some early phase.
*Make sure that this pom is executed before anything else that depend on it. List it as first module.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Circular references, objective - c I had this problem with import statements with my own classes using forward declarations to fix that. I have a method that uses type CTFramesetterRef. So I needed to add the CoreText framework. If I declare the method in my .h file, do I just
#import <CoreText/CoreText.h>
in my .h file and not my .m file. Are there any hard and fast rules for this? Sometimes I see code that has it in the .m, sometimes in the .h. To me it seems like what I see is declare it in the .m if you can, if you have to put it in the .h, put it there instead, and if you can use a forward declaration for a class, then do that. Just not sure what the proper way to do things are. Thanks.
A: "declare it in the .m if you can, if you have to put it in the .h, put it there instead, and if you can use a forward declaration for a class, then do that." - I would say this is the proper way to do that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Would hiding iframes during the resize of a container DIV speed up the response? Folks,
I have a DIV that contains a number of IFrames (long story). The DIV can be resized by the user, and the iFrames change size along with it. However, the resizing process is slow and choppy, with the size changing in "bursts".
Would hiding the iFrames during the resize speed this up?
Is there a best practice for temporarily hiding an iFrame? I seem to remember people elsewhere recommending slightly exotic methods for hiding them, although I don't recall why.
Thanks,
Ann L.
A: Another option would be to show a 'bounding box' or 'preview' of the area in which you are applying the resize. Similar to The dotted border you see when re sizing the example here
A: The less there is on the screen, the faster the reflow. If you can hide elements until a complex DOM change is complete you'll force an additional redraw at the end, but the intermediate steps should be faster.
A: One way to solve this problem is to not carry out the actual resize on the resize event (which leads to the choppiness because it gets called so often), but rather to set a timer on the resize and only do the actual resize when the window size hasn't changed for a second or two. Then, the user can freely resize the window and when they pause, it lays out the interior without any of the intermediate choppiness. In general, it works like this:
var resizeTimer = null;
function doActualResize() {
resizeTimer = null;
// do your window interior resize here
// won't get called more than once per second because of timer
}
window.onresize = function() {
// clear any prior timer that hasn't fired yet
if (resizeTimer) {
clearTimeout(resizeTimer);
}
// set new timer to wait for 1 second of no further resize motion
resizeTimer = setTimeout(doActualResize, 1000);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can we create a Java class object and call its method in JSP without scriptlets? Suppose there is a class named as Demo which is not a Javabean and has a method m1(), I want to call this method m1() from my JSP page without using scriptlets. How can I do this?
A: Create a servlet and do the job in doGet() method.
@WebServlet(urlPatterns={"/page"})
public class PageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
new Demo().m1();
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
}
or if it returns some object as result and you need it to be available as ${result} in EL,
@WebServlet(urlPatterns={"/page"})
public class PageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object result = new Demo().m1();
request.setAttribute("result", result);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
}
}
(note that page.jsp is hidden in /WEB-INF folder to prevent direct access without invoking the servlet first)
Now invoke http://localhost:8080/context/page instead of http://localhost:8080/context/page.jsp.
A: I would personally recommend using a solution based on JSTL and Expression Language:
A JSTL primer, Part 1: The expression language
Expression Language
"A primary feature of JSP technology version 2.0 is its support for an expression language (EL). An expression language makes it possible to easily access application data stored in JavaBeans components. For example, the JSP expression language allows a page author to access a bean using simple syntax such as ${name} for a simple variable or ${name.foo.bar} for a nested property. "
This will allow you to use tags instead of scriptlets in the form:
<c:out value="${demo.m1}"/>
JSTL will also allow you to perform conditions, iterations, and much more through the use of tags.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem In OutPut Of Divided Number
Possible Duplicate:
Divide problem
Why does c# show the output of this code as 0??
MessageBox.Show((5/6).ToString);
A: Because unless you specify that you want the operation to result in a Double the operation results in an Integer, and so the fractional result is dropped and you are left with just the whole number of 0.
A: It is dividing an integer by and integer and will return an integer, I believe it always returns the floor value. Try Messagebox.Show((5.0/6.0).ToString());
A: 5/6 is basically integral division, which turns out to be 0. The type of both operands is int.
I think what you want is : 5.0/6.0.
In fact, 5.0/6.0, 5/6.0, 5.0/6, all would give same result. That is, as long as, one operand is double, it would be a double division, and the type of the result would be double as well.
A: Because you are doing integer division. If you want non-integer division you should do something like 5 / 6d
A: The compiler assumes that the numbers are Int, which must be whole numbers. Thus, it is rounding the answer. To return the decimal answer, use this:
MessageBox.Show((5d/6d).ToString());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get line break from UITextView I'm building a small messaging app for the iPhone. When the user writes a message in my UITextView I save it to an online database. Then I download that and display it to another user. The problem is that the string that I send to the DB do not include the "\n"-sign from the Uitextview that the user typed in, When I try to display the message it displays it in one line instead of the formatting the user inputed.
I somehow want to get all newline-signs from the UitextView and save them inside the text in the DB so I can display the message with the right formatting.
How do I do this in Objective C?
A: UITextView supports the '\n' newline, and its text property will contains them.
You can try this to confirm that a UITextView supports them (note that textView is a UITextView):
if ([self.textView.text rangeOfString:@"\n"].location != NSNotFound) {
NSLog(@"newline found");
}
Or this
self.textView.text = @"new\nline";
So may be you problem is elsewhere in the code that persist the user string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: arguments in functions python This is a subtle question about notation.
I want to call a function with specific arguments, but without having to redefine it.
For example, min() with a key function on the second argument key = itemgetter(1) would look like:
min_arg2 = lambda p,q = min(p,q, key = itemgetter(1))
I'm hoping to just call it as something like min( *itemgetter(1) )...
Does anyone know how to do this? Thank you.
A: Using functools (as in Duncan's answer) is a better approach, however you can use a lambda expression, you just didn't get the syntax correct:
min_arg2 = lambda p,q: min(p,q, key=itemgetter(1))
A: You want to use functools.partial():
min_arg2 = functools.partial(min, key=itemgetter(1))
See http://docs.python.org/library/functools.html for the docs.
Example:
>>> import functools
>>> from operator import itemgetter
>>> min_arg2 = functools.partial(min, key=itemgetter(1))
>>> min_arg2(vals)
('b', 0)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Password validation in JSF 2 i am just wondering what is the best way to validate password confirmation in JSF 2
A: The best way to validate anything you need in JSF is use MyFaces Extval. It support cross field validation, which is a typical use case for validate passwords. See this blog for more information about it.
A: You can use RichFaces 4 client-side! validation based on Bean Validation (JSR303).
Bean:
@Size(min = 5, max = 15)
private String password1;
@Size(min = 5, max = 15)
private String password2;
@AssertTrue(message = "Passwords don't match")
public boolean checkPassword() {
return password1.equals(password1);
}
Page:
<rich:graphValidator value="#{bean}" id="crossField">
<h:inputText value="#{bean.password1}"/>
<h:inputText value="#{bean.password2}"/>
<rich:message for="crossField"/>
</rich:graphValidator>
Refer here for more examples.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: plexus-compiler-eclipse error: Type mismatch: cannot convert from Object to byte[] I'm using plexus-compiler-eclipse-1.8.2 to compile my project using the eclipse compiler from maven. I'm using clone() to create a copy of an array:
byte[] copy = orig.clone();
and I get the following error:
Type mismatch: cannot convert from Object to byte[]
The same code compiles without this error with javac. Has anyone encountered this issue?
Thanks!
A: We must not rely on error/warning other than the ones given by the javac compile command. That includes both IDE warnings and command-line build tools like ant or maven. Sure its very user friendly to use them and not javac directly but when in doubt or contradictory results javac always has the final word. For example, using JDK1.6.0_29 on Eclipse Helios didn't raised any warning/nor error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Protecting memory from changing Is there a way to protect an area of the memory?
I have this struct:
#define BUFFER 4
struct
{
char s[BUFFER-1];
const char zc;
} str = {'\0'};
printf("'%s', zc=%d\n", str.s, str.zc);
It is supposed to operate strings of lenght BUFFER-1, and garantee that it ends in '\0'.
But compiler gives error only for:
str.zc='e'; /*error */
Not if:
str.s[3]='e'; /*no error */
If compiling with gcc and some flag might do, that is good as well.
Thanks,
Beco
A: To detect errors at runtime take a look at the -fstack-protector-all option in gcc. It may be of limited use when attempting to detect very small overflows like the one your described.
Unfortunately you aren't going to find a lot of info on detecting buffer overflow scenarios like the one you described at compile-time. From a C language perspective the syntax is totally correct, and the language gives you just enough rope to hang yourself with. If you really want to protect your buffers from yourself you can write a front-end to array accesses that validates the index before it allows access to the memory you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java thread safe recursion I have nested class CRecursion which has method that do recursion.
This CRecursion created in many threads. Is safe call from thread method from main class?
Thanks.
class A {
method1() {....}
for(int i=0;i<100;i++){
execute(new CRecursion(...))
}
protected CRecursion {
calculate (par){
if (some_condition) {
calculate(par1)
} else {
String s=method1(value);
.....
}
}
....
}
Variable value is Object. But internal for each method.
A: If the objects used by the recursive routine are confined to the same thread, then yes, the recursive routine is thread-safe. It would help to read this related StackOverflow question on thread confinement and it's impact on thread-safety.
In this particular case (with the code that you've posted), you'll need to ensure that:
*
*The arguments to the constructor of CRecursion must not be shared across multiple threads. If they are shared, then the following point becomes relevant.
*Any objects that are shared across multiple threads, must not be accessed (read from or written to) in the recursion routine.
*The recursion routine uses local variables that are confined to the current stack frame. The routine must not access any other shared storage area (other than the Java call stack) to exchange data between invocations.
A: *
*Are you sharing any data between threads?
If answer to the above question is NO, then the call is implicitly thread safe.
If you are worried that local variables will be garbled via multiple call to the same method from different threads, then you are mistaken. Each invocation of a method creates its own seperate copy of those variables.
In essence if you are not sharing any data your call is thread safe.
Technically, you can still share data and be thread safe, the only condition is that all access to the shared data must be a read operation.
A: We need more details about your calculate method to answer your question. If you are only using locally scoped variables (ie, variables / data you create within the method) then you are fine.
If you are accessing data within the class, but only reading that data, then you are fine.
If you are accessing data within the class, and are writing to that data, you may have a problem. This is what the keyword synchronized is for... you can synchronize a block / blocks of code so that only one block can be executed at any given time. Of course, there is usually a speed trade-off for this.
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to efficiently find out if a sequence has at least n items? Just naively using Seq.length may be not good enough as will blow up on infinite sequences.
Getting more fancy with using something like ss |> Seq.truncate n |> Seq.length will work, but behind the scene would involve double traversing of the argument sequence chunk by IEnumerator's MoveNext().
The best approach I was able to come up with so far is:
let hasAtLeast n (ss: seq<_>) =
let mutable result = true
use e = ss.GetEnumerator()
for _ in 1 .. n do result <- e.MoveNext()
result
This involves only single sequence traverse (more accurately, performing e.MoveNext() n times) and correctly handles boundary cases of empty and infinite sequences. I can further throw in few small improvements like explicit processing of specific cases for lists, arrays, and ICollections, or some cutting on traverse length, but wonder if any more effective approach to the problem exists that I may be missing?
Thank you for your help.
EDIT: Having on hand 5 overall implementation variants of hasAtLeast function (2 my own, 2 suggested by Daniel and one suggested by Ankur) I've arranged a marathon between these. Results that are tie for all implementations prove that Guvante is right: a simplest composition of existing algorithms would be the best, there is no point here in overengineering.
Further throwing in the readability factor I'd use either my own pure F#-based
let hasAtLeast n (ss: seq<_>) =
Seq.length (Seq.truncate n ss) >= n
or suggested by Ankur the fully equivalent Linq-based one that capitalizes on .NET integration
let hasAtLeast n (ss: seq<_>) =
ss.Take(n).Count() >= n
A: Here's a short, functional solution:
let hasAtLeast n items =
items
|> Seq.mapi (fun i x -> (i + 1), x)
|> Seq.exists (fun (i, _) -> i = n)
Example:
let items = Seq.initInfinite id
items |> hasAtLeast 10000
And here's an optimally efficient one:
let hasAtLeast n (items:seq<_>) =
use e = items.GetEnumerator()
let rec loop n =
if n = 0 then true
elif e.MoveNext() then loop (n - 1)
else false
loop n
A: Using Linq this would be as simple as:
let hasAtLeast n (ss: seq<_>) =
ss.Take(n).Count() >= n
Seq take method blows up if there are not enough elements.
Example usage to show it traverse seq only once and till required elements:
seq { for i = 0 to 5 do
printfn "Generating %d" i
yield i }
|> hasAtLeast 4 |> printfn "%A"
A: Functional programming breaks up work loads into small chunks that do very generic tasks that do one simple thing. Determining if there are at least n items in a sequence is not a simple task.
You already found both the solutions to this "problem", composition of existing algorithms, which works for the majority of cases, and creating your own algorithm to solve the issue.
However I have to wonder whether your first solution wouldn't work. MoveNext() is only called n times on the original method for certain, Current is never called, and even if MoveNext() is called on some wrapper class the performance implications are likely tiny unless n is huge.
EDIT:
I was curious so I wrote a simple program to test out the timing of the two methods. The truncate method was quicker for a simple infinite sequence and one that had Sleep(1). It looks like I was right when your correction sounded like overengineering.
I think clarification is needed to explain what is happening in those methods. Seq.truncate takes a sequence and returns a sequence. Other than saving the value of n it doesn't do anything until enumeration. During enumeration it counts and stops after n values. Seq.length takes an enumeration and counts, returning the count when it ends. So the enumeration is only enumerated once, and the amount of overhead is a couple of method calls and two counters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Running VBA functions in a server side Access database from a WCF service I've been researching for days and I've gotten to the point where my WCF service creates an Access object via com/interop. I've ran the OpenCurrentDatabase call for the Access object without an error but Application.CurrentDB is still nothing/null. If the CurrentDB is nothing then I surely can't call Application.Run "myFunction" I realize WCF services aren't meant to be user interactive, but it's a long story why I'm trying to go this route. Basically I need to have a proof of concept ready sooner rather than later and the alternative (correct) route involves the complete re-writing of a large complex access VBA application. It's not a permissions issue, I have the IIS user names added to the security tab. What I really need is a way to set Environment.UserInteractive to true so my WCF service can create an instance of Access on my server machine, run the VBA functions, close out, return true. I'm using VS 2010 for the WCF, IIS 7 for my server, Access 2010 for the VBA application. Please help!
A: The answer is to have the WCF service write the access macro name to a database and have a desktop application on the server machine monitor the database. The desktop application loads access, performs the actions, and writes back to the database upon completion. The WCF service monitors the database waiting for an "operation complete" status and returns the result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: CSS & Forms - Resisting the urge to go to table layouts I am struggling with how to write the correct CSS for positioning some data entry forms. I'm not sure what the "proper" way to do it is.
An example of what I am trying to create a layout for:
Last Name Middle Initial First Name DOB
||||||||||||| |||||| |||||||||||||||| ||||||||||
City State Zip
|||||||| |||| |||||||||
Basically I have my labels and the ||| are representing my form elements (text boxes, dropdowns etc). I don't know the proper way to create classes for these elements without just creating one time use classes that specify a specific width that is only for these elements.
Also, how do I get all of these elements aligned properly and multiple items per line? Do I need to float each element?
Would I do something like:
<div class="last-name">
<div class="label">
<label>Last Name</label>
</div>
<div class="field">
<input type="text" />
</div>
</div>
<div class="middle-initial">
<div class="label">
<label>Middle INitial</label>
</div>
<div class="field">
<input type="text" />
</div>
</div>
...
<div class="clear"></div>
last-name and middle-initial etc would all be classes that would be used once and floated to the left. I'm not sure if this is a good way to go about it or not? Is there a better way to do this kind of positioning with CSS so I can avoid using tables?
A: I would choose to mark up this particular layout using fieldsets:
<form>
<fieldset class="personal">
<label>
<span>Last Name</span>
<input type="text" ... />
</label>
<label>
<span>Middle Initial</span>
<input type="text" ... />
</label>
...
</fieldset>
<fieldset class="address">
<label>
<span>City</span>
<input type="text" ... />
</label>
</fieldset>
</form>
I'd float all the labels, make the spans or inputs use display:block, and most everything should fall into place.
A: IMO, this is tabular data.
I don't think it's necessarily a shame to use a <table> for this.
Related discussion: Proper definition for "tabular data" in HTML
A: Here is my version without tables: http://jsfiddle.net/dy4bv/5/ (increase a little HTML part to fit all fields)
Maybe it will be helpful.
A: You could always use display:table and display:table-cell.
So using your example code above, you would do something like this
div.last-name, div.middle-initial{
display:table-cell;
padding:1em;
}
Example: http://jsfiddle.net/5LBgp/
EDIT
A bit more context to add to the answers from @Pekka and @Pete Wilson:
I foresee two big problems with styling this as a table
*
*if you ever want to change the styling, you will need to hack away at the HTML, probably even redo it completely. Your code will be more future friendly if you use divs.
*screen readers and such will likely make a mess of it, not understanding that the table is not really a table.
A: It's not a bad thing to use table layout when the data you're laying out is a table! That's what you have here, imo: a table. So save yourself some grief and treat it that way. We've been so beat up by CSS purists and semantic-web lunatics that I suggest the pendulum has swung too far: now we tie ourselves in knots over-CSSifying our layouts. Or at least I do. I spend way too much time trying to avoid table layout.
The outcome is that a lot of my pages have to do browser checking. And the extra time (hey! the 80-20 rule again!) to deal with browser quirks is way more than it should be. I'd have saved a lot of time, and had more robust pages, if I'd just thought a little bit instead of going for the never-any-tables, always-pure-CSS solution every time. Table handling is solid like a rock in every browser with no problems and no frustrations.
Just my experience.
A: I am not a web developer, but i've had a crack.
*
*http://jsfiddle.net/dy4bv/28/
This is based on @Samich's design, but instead of using a pile of divs with magic clearing divs interspersed, i've split the rows up into items in a ul. I use labels for the warm fuzzy semantic feeling. The styling is done by making the label-and-field divs inline-block, so they flow from left to right, but the labels and fields themselves block, so they stack vertically (this is a very crude idea, i know). As @zzzzBov pointed out, you can then use the field IDs to hang widths off.
A: No, that is not tabular data. Here's a test if you're ever wondering if something is tabular data: What are the table headers?
As for the layout, whenever I get something that I have trouble laying out, I back up and ask if the design is the problem and in this case I think the answer to that question is: yes.
Is that a user friendly design? no. It's difficult to scan and will be slow for users to identify errors if there are submit errors.
Luke Wroblewski has some great information on his blog and in his book Web Form Design: Filling in the Blanks about how to design human friendly forms.
A: Just to unload these 2 pennies...
The first column is "PropertyDescription" and the second column is "PropertyValue", while each row is a "Property" items -- voilà, a table!
Still prefer CSS, but this can certainly be classified as tabular data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do i change a symfony form error message? I am using symfony 1.4.
I have a form like this:
validator:
$this->setValidator('name', new sfValidatorString(array('required' => true)));
view:
<?php echo $form['name']->renderError() ?>
How do i change the default "required" error message to, for example, "This field is required" ?
Edit: Also, how do i get rid of <ul> and <li> tags generated by the renderError(). method ? I just want the text to be displayed, no additional markup.
Note: This is an obvious question, but since I took a long time to find out, i think the question diserves to be asked here.
A: 1.Change the required message:
new sfValidatorString(
array(
'required' => true,
),
array(
'required'=>'You custom required message'
));
2.Create a new formatter class.
3.Redefine the attribute you want.
<?php
class myWidgetFormSchemaFormatter extends sfWidgetFormSchemaFormatter
{
protected
$rowFormat = '',
$helpFormat = '%help%',
$errorRowFormat = '%errors%',
$errorListFormatInARow = " <ul class=\"error_list\">\n%errors% </ul>\n",
$errorRowFormatInARow = " <li>%error%</li>\n",
$namedErrorRowFormatInARow = " <li>%name%: %error%</li>\n",
$decoratorFormat = '',
$widgetSchema = null,
$translationCatalogue = null;
4.In the configure method of your symfony form add
$oDecorator = new myWidgetFormSchemaFormatter($this->getWidgetSchema());
$this->getWidgetSchema()->addFormFormatter('myCustom', $oDecorator);
$this->getWidgetSchema()->setFormFormatterName('myCustom');
A: new sfValidatorString(array('required' => true), array('required'=>'This field is required'))
And you can create a custom WidgetFormSchemaFormatter by extending sfWidgetFormSchemaFormatter to format your form output.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Multiline function calls in Coffeescript Hi everyone: Suppose I have a function "foo" that should receive two functions as parameters. If I have two lambda functions, I can call "foo" as follows:
foo (-> 1),(-> 2)
In this case, "foo" receives two functions, one that just returns 1 and another that returns 2.
However, usually lambda functions are more complicated, so putting both functions on a single line is impractical. Instead, I would like to write two multiline lambda functions. However, I can't figure out for the life of me how to accomplish this in coffeescript- Ideally, I would want to write it as follows, but it throws an error:
foo
->
1
,
->
2
The best I can come up with that works is super ugly:
foo.apply [
->
1
,
->
2
]
Can any Coffeescript guru show me how I can do this, without getting an error? Thanks!
A: I believe this is one situation where anonymous functions seem to not be the answer. They are very practical and idiomatic in a lot of situations but even they have limitations and can be less readable if used in extreme situations.
I would define the two functions in variables and then use them as parameters:
func1 = ->
x = 2
y = 3
z = x+y
return z+2*y
func2 = ->
a = "ok"
return a + " if you want this way"
foo func1, func2
But if you decide lambdas would be preferable, just use the parenthesis around the parameters of foo:
foo ((->
x = 2
y = 3
z = x+y
return z+2*y
),(->
a = "ok"
return a + " if you want this way"
)
)
It is not because you are using CoffeScript that you should avoid parenthesis at any cost :)
A: This should suffice (you could indent the second lamda if you want):
f (->
x = 1
1 + 2 * x),
->
y = 2
2 * y
given the function f:
f = (a,b) -> a() + b()
the result should give 3 + 4 = 7
A: Functions are implicitly called if a variable or function follows them. That's why
foo
->
2
,
->
3
won't work; the coffeescript compiler only sees a variable followed by an unexpected indent on the next line. Explicitly calling it
foo(
->
2
, ->
3
)
will work.
You can implicitly call a function with multiple paramenters, you just need to line up the comma with the beginning of the function call
foo ->
2
, ->
3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Adobe Flash iPhone Game Development like Words/Hanging with Friends possible? Adobe Flash CS 5 and 5.5 offers the ability to create applications for the iPhone. Would it be possible to create a multiplayer turn style game like the iPhone game Words/Hanging with Friends/Chess with friends?
If so anyone have any good places to start with. My only problem would be making multiplayer and turn style work. I am only curious as I am not up to coding par enough to do this with Objective C.
Thanks all!
A: Yes it would be possible. You could leverage a service like the Flash Collaboration Service (also known as LiveCycle Collaboration Service) to manage the state between games:
http://www.adobe.com/devnet/flashplatform/services/collaboration.html
You would not be able to leverage GameCenter integration without a Native Extension.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS: Anybody gotten libtar or libarchive to build? (Problem with configure script.) I'm having a problem building libraries that have a "configure" script, namely such scripts are not meant for compiling for iOS.
Is there a set of environment variables that I can set to induce "configure" to work for iOS?
I tried setting CC but that was not nearly enough.
Thanks.
A: Github project with static libraries and headers that build properly for iOS.
From the readme (Nov 2011):
LibArchive Static Library for iOS Unfortunately, while
libarchive.dylib and libbz2.dylib are included in the iOS SDK, the
header files are not. This means that they are private APIs and cannot
be used if you intend to submit to the App Store.
Never fear! This repository contains everything you need to build a
static version of libarchive for iOS. libbz2 is also included for
extra goodness.
To keep naming of things sane, we build the library as libarc.a.
For iOS 4.3+ copy the header files and library from the
build-for-iOS-4.3 directory into your project.
For iOS 4.2 copy the header files and library from the
build-for-iOS-4.2 directory into your project.
If you need to build this for an earlier version of iOS, you can
easily modify the build.sh script to point to whatever SDKs you like.
It should build fine on 3.x.
TO GET IT FULLY LINKING you must also include libz.dylib in your list
of linked libraries. To do this in XCode 4, click on your project,
choose the Build Phases tab, go to Link Binary With Libraries, press
+, and choose libz.dylib from the (long) list of possible libraries to link against. This is because libarc.a links dynamically to libz.dylib
-- this is okay since, for whatever reason, AAPL saw fit to include the libz headers in the iOS SDK.
The current libarchive version is 2.8.4. The bzlib2 version is 1.0.6.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: On transition of pictures in slideshow using javascript the whole page shakes I am using javascript to display a slideshow on my JSP. In slideshow the picture fadein and fadeout every 3sec. On every transition of a picture the whole jsp shakes. I have also cropped the pictures to same size and are not that heavy to load.
my javascript code is:-
<script type="text/javascript">
var imgs = [
'images/tern.jpg',
'images/airplane.JPG',
'images/sf_night.jpg',
'images/aerial.jpg',
'images/airbusa380.jpg'];
var cnt = imgs.length;
$(function () {
setInterval(Slider, 3000);
var $imageSlide = $('img[id$=imageSlide]');
// set the image control to the last image
$imageSlide.attr('src', imgs[cnt - 1]);
});
function Slider() {
$('#imageSlide').fadeOut("slow", function () {
$(this).attr('src', imgs[(imgs.length++) % cnt]).fadeIn("slow");
});
}
</script>
then in the body i just call this:-
<body>
<div>
<img id="imageSlide" alt="" src="" />
</div>
</body>
A: The page is re-flowing the layout every time you switch the <img> source since you do not explicitly set the width and height attributes. When the new image SRC is switched, it sets the width/height to 0x0, and then back to the full size once the image finishes loading.
Set an explicit width and height so it doesn't adjust the image size (thus changing the layout) between each image switch.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: QPID - Spring CachingConnectionFactory - Reconnect Spring Configuration
<bean id="jmsQueueConnectionFactory" class="org.apache.qpid.client.AMQConnectionFactory">
<constructor-arg index="0"
value="amqp://guest:guest@localhost/test?brokerlist='tcp://localhost:5672'" />
</bean>
<bean id="cachingConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory" ref="jmsQueueConnectionFactory" />
<property name="sessionCacheSize" value="1" />
<property name="reconnectOnException" value="true" />
</bean>
<bean id="myDestination" class="org.apache.qpid.client.AMQAnyDestination">
<constructor-arg index="0" value="ADDR:myqueue; {create: always}" />
</bean>
<bean id="myServiceBean" class="com.test.MyService" />
<bean id="myContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="cachingConnectionFactory" />
<property name="exceptionListener" ref="cachingConnectionFactory" />
<property name="messageListener" ref="myServiceBean" />
<property name="concurrentConsumers" value="1" />
<property name="autoStartup" value="true" />
<property name="destination" ref="myDestination" />
<property name="recoveryInterval" value="10000" />
</bean>
MyService.java
public class MyService implements MessageListener {
public void onMessage(Message msg) {
log.info("----On Message called :"+msg+", :"+msg.getClass().getName());
}
}
When I restart QPID
Without reconnectOnException=true,I keep getting this exception ,but not reconneting
3203 [myContainer-1] DEBUG org.springframework.jms.connection.CachingConnectionFactory - Creating cached JMS Session for mode 1: org.apache.qpid.client.AMQSession_0_10@1d03a4e
3312 [myContainer-1] DEBUG org.springframework.jms.connection.CachingConnectionFactory - Creating cached JMS MessageConsumer for destination ['myqueue'/None; {
'create': 'always'
}]: org.apache.qpid.client.BasicMessageConsumer_0_10@8a2023
99109 [myContainer-1] WARN org.springframework.jms.listener.DefaultMessageListenerContainer - Setup of JMS message listener invoker failed for destination ''myqueue'/None; {
'create': 'always'
}' - trying to recover. Cause: timed out waiting for session to become open (state=DETACHED)
org.apache.qpid.transport.SessionException: timed out waiting for session to become open (state=DETACHED)
at org.apache.qpid.transport.Session.invoke(Session.java:630)
at org.apache.qpid.transport.Session.invoke(Session.java:559)
at org.apache.qpid.transport.SessionInvoker.executionSync(SessionInvoker.java:84)
at org.apache.qpid.transport.Session.sync(Session.java:782)
at org.apache.qpid.transport.Session.sync(Session.java:770)
at org.apache.qpid.client.BasicMessageConsumer_0_10.getMessageFromQueue(BasicMessageConsumer_0_10.java:423)
at org.apache.qpid.client.BasicMessageConsumer.receive(BasicMessageConsumer.java:407)
at org.springframework.jms.connection.CachedMessageConsumer.receive(CachedMessageConsumer.java:74)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveMessage(AbstractPollingMessageListenerContainer.java:429)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.doReceiveAndExecute(AbstractPollingMessageListenerContainer.java:310)
at org.springframework.jms.listener.AbstractPollingMessageListenerContainer.receiveAndExecute(AbstractPollingMessageListenerContainer.java:263)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.invokeListener(DefaultMessageListenerContainer.java:1058)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.executeOngoingLoop(DefaultMessageListenerContainer.java:1050)
at org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker.run(DefaultMessageListenerContainer.java:947)
at java.lang.Thread.run(Thread.java:619)
99109 [myContainer-1] INFO org.springframework.jms.listener.DefaultMessageListenerContainer - Successfully refreshed JMS Connection
..
281125 [myContainer-3] INFO org.springframework.jms.listener.DefaultMessageListenerContainer - Successfully refreshed JMS Connection
With reconnectOnException=true ,Its getting connected and disconnected
13015 [IoReceiver - localhost/127.0.0.1:5672] WARN org.springframework.jms.connection.CachingConnectionFactory - Encountered a JMSException - resetting the underlying JMS Connection
javax.jms.JMSException: connection aborted
at org.apache.qpid.client.AMQConnectionDelegate_0_10.closed(AMQConnectionDelegate_0_10.java:303)
at org.apache.qpid.transport.Connection.closed(Connection.java:568)
at org.apache.qpid.transport.network.Assembler.closed(Assembler.java:110)
at org.apache.qpid.transport.network.InputHandler.closed(InputHandler.java:202)
at org.apache.qpid.transport.network.io.IoReceiver.run(IoReceiver.java:150)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.apache.qpid.transport.ConnectionException: connection aborted
at org.apache.qpid.transport.Connection.closed(Connection.java:541)
... 4 more
13031 [IoReceiver - localhost/127.0.0.1:5672] DEBUG org.springframework.jms.connection.CachingConnectionFactory - Closing shared JMS Connection: AMQConnection:
Host: localhost
Port: 5672
Virtual Host: test
Client ID: localhost
Active session count: 1
73031 [IoReceiver - localhost/127.0.0.1:5672] DEBUG org.springframework.jms.connection.CachingConnectionFactory - Could not close shared JMS Connection
org.apache.qpid.client.JMSAMQException: timed out waiting for session to become open (state=DETACHED)
at org.apache.qpid.client.AMQConnection.stop(AMQConnection.java:824)
at org.springframework.jms.connection.SingleConnectionFactory.closeConnection(SingleConnectionFactory.java:422)
at org.springframework.jms.connection.SingleConnectionFactory.resetConnection(SingleConnectionFactory.java:321)
at org.springframework.jms.connection.CachingConnectionFactory.resetConnection(CachingConnectionFactory.java:197)
at org.springframework.jms.connection.SingleConnectionFactory.onException(SingleConnectionFactory.java:302)
at org.springframework.jms.connection.ChainedExceptionListener.onException(ChainedExceptionListener.java:57)
at org.apache.qpid.client.AMQConnectionDelegate_0_10.closed(AMQConnectionDelegate_0_10.java:306)
...
at org.apache.qpid.transport.network.io.IoReceiver.run(IoReceiver.java:150)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.apache.qpid.AMQException: timed out waiting for session to become open (state=DETACHED) [error code 541: internal error]
at org.apache.qpid.client.AMQSession_0_10.setCurrentException(AMQSession_0_10.java:1050)
at org.apache.qpid.client.AMQSession_0_10.sync(AMQSession_0_10.java:1030)
at org.apache.qpid.client.AMQSession_0_10.sendSuspendChannel(AMQSession_0_10.java:857)
at org.apache.qpid.client.AMQSession.suspendChannel(AMQSession.java:3006)
at org.apache.qpid.client.AMQSession.stop(AMQSession.java:2341)
at org.apache.qpid.client.AMQConnection.stop(AMQConnection.java:820)
... 11 more
104875 [myContainer-1] INFO org.springframework.jms.connection.CachingConnectionFactory - Established shared JMS Connection: AMQConnection:
Host: localhost
Port: 5672
Virtual Host: test
Client ID: localhost
Active session count: 0
104875 [myContainer-1] INFO org.springframework.jms.listener.DefaultMessageListenerContainer - Successfully refreshed JMS Connection
104875 [myContainer-2] DEBUG org.springframework.jms.connection.CachingConnectionFactory - Creating cached JMS Session for mode 1: org.apache.qpid.client.AMQSession_0_10@191e4c
104937 [IoReceiver - localhost/127.0.0.1:5672] WARN org.springframework.jms.connection.CachingConnectionFactory - Encountered a JMSException - resetting the underlying JMS Connection
javax.jms.JMSException: 404
at org.apache.qpid.client.AMQConnection.exceptionReceived(AMQConnection.java:1230)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.apache.qpid.AMQException: ch=0 id=0 ExecutionException(errorCode=NOT_FOUND, commandId=0, description=Queue: myqueue not found) [error code 404: not found]
at org.apache.qpid.client.AMQSession_0_10.setCurrentException(AMQSession_0_10.java:1050)
... 29 more
104937 [IoReceiver - localhost/127.0.0.1:5672] DEBUG org.springframework.jms.connection.CachingConnectionFactory - Closing shared JMS Connection: AMQConnection:
Host: localhost
Port: 5672
A: Have you tried omitting the exceptionListener setting on the DMLC? I don't recall ever needing to specify that, and it seems like your connection is being invalidated after connection recovery has been initiated.
Also, assuming you're not using JBoss 4, you might try using the DMLC's built-in caching mechanism (via the cacheLevel setting) instead of using a caching connection factory for your consumers; you may even get better performance, since DMLC can cache sessions and consumers as well as connections.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Select last non-NA value in a row, by row I have a data frame where each row is a vector of values of varying lengths. I would like to create a vector of the last true value in each row.
Here is an example data frame:
df <- read.table(tc <- textConnection("
var1 var2 var3 var4
1 2 NA NA
4 4 NA 6
2 NA 3 NA
4 4 4 4
1 NA NA NA"), header = TRUE); close(tc)
The vector of values I want would therefore be c(2,6,3,4,1).
I just can't figure out how to get R to identify the last value.
Any help is appreciated!
A: Here's an answer using matrix subsetting:
df[cbind( 1:nrow(df), max.col(!is.na(df),"last") )]
This max.col call will select the position of the last non-NA value in each row (or select the first position if they are all NA).
A: Do this by combining three things:
*
*Identify NA values with is.na
*Find the last value in a vector with tail
*Use apply to apply this function to each row in the data.frame
The code:
lastValue <- function(x) tail(x[!is.na(x)], 1)
apply(df, 1, lastValue)
[1] 2 6 3 4 1
A: Here's another version that removes all infinities, NA, and NaN's before taking the first element of the reversed input:
apply(df, 1, function(x) rev(x[is.finite(x)])[1] )
# [1] 2 6 3 4 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: JavaScript -- split off one branch of a hierarchical array or JSON object I have a JSON object that is a nested array that is of the following form:
{
"name": "Math",
"children": [
{
"name": "Trigonometry",
"children": [
{
"name": "Right Triangles and an Introduction to Trigonometry",
"children": [
{
"name": "The Pythagorean Theorem",
"children": [
{
"name": "The Pythagorean Theorem",
"size": 30
},
{
"name": "Pythagorean Triples",
"size": 52
},
{
"name": "Converse of the Pythagorean Theorem",
"size": 13
}
]
}
]
}
]
},
{
"name": "Algebra",
"children": [
{
"name": "Equations and Functions",
"children": [
{
"name": "Variable Expressions",
"children": [
{
"name": "Evaluate Algebraic Expressions",
"size": 26
}
]
}
]
}
]
}
]
}
The full array is actually much larger and can be seen here. I'm using it to build interactive graphs and charts using D3.js (or perhaps other libraries). Because it's so large, I'd like to be able to split the array by branch. In other words, to carve out particular branches of the array.
For instance, is there a way to just pull out the node "Trigonometry" and all its children? Or "Algebra" and all its children? Then "Trigonometry" or "Algebra" would become the new root or parent node.
A: There is no built-in way to do something like this, although the comment about a JSON query language might give you the right work-around.
Really, the problem is that you have structured your data in a way that makes it very hard to use. If instead of
{
name: "key",
children: [...]
}
you just did
{
"key": [...]
}
then you could simply do myObject["key"] to get the array you want.
For example:
var math = {
"Trigonometry": {
"Right Triangles and an Introduction to Trigonometry": {
"The Pythagorean Theorem": {
"The Pythagorean Theorem": 30,
"Pythagorean Triples": 52,
"Converse of the Pythagorean Theorem": 13
}
}
},
"Algebra": {
"Equations and Functions": {
"Variable Expressions": {
"Evaluate Algebraic Expressions": 26
}
}
}
};
var trigonometry = math["Trigonometry"];
var expressionsAndFunctions = math["Algebra"]["Expressions and Functions"];
As a bonus, that's much shorter!
A: Array's splice function should do it. What that will do is remove the element at a given index and return it.
If you just want a shortcut to a specific branch, couldn't you also just use
var trig = tree['trigonometry'];
to get there. This wouldn't change the original object, buy will give you a simpler way to access nodes deep inside.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: implementing complex check constraints I have the following tables:
CREATE TABLE group_systems
(
group_name,
system_name,
section_name,
created_date,
decom_date,
status (Active, Deactivate)
)
CREATE TABLE systems
(
system_name,
section_name
)
A system is identified by the key (system_name, section_name). There can be dup system names but no dup section name.
In the groups table, I want to enforce the constraint that only one system in a section in a group can be active. However, because the groups table is also a history table, I can't just use the unique constraint (group_name, section_name, system_name). I have to use a check constraint that runs a subquery. There's also some additional constraints that are subqueries.
The problem is that inserting a benchmark of 100k records takes a long time (due to the subqueries).
Is it better to build another table active_systems_for_groups that references back to the group_systems table? That way, I can add the unique constraint to active_systems_for_groups that enforces only one active system per section per group and keep building complex constraints by adding more tables.
Is there a better way to handle complex check constraints?
A: You can enforce the "single active record" pattern in two ways:
*
*The solution you suggest, which is to create a table that holds only the primary key values of the active records from the multiple-records-allowed table. Those values also serve as a primary key in the active records table.
*Adding a column to another table that represents the objects that can have only a single active record each. In this case that would mean adding a column active_group_name to systems. This column would be a foreign key to the multiple-records-allowed table.
Which is preferable depends, in part, on whether every section is required to have an active group, whether it's common (but not required) for a section to have an active group, or whether it's only occasionally true that a section has an active group.
In the first case (required), you would use option (2) and the column could be declared NOT NULL, preserving complete normalization. In the second case (common) you would need to make the column NULLable but I'd probably still use that technique for convenience of JOINs. In the third case (occasional), I'd probably use option (1) since it might well improve performance when JOINing to get the active records.
A: Since you never answered which RDBMS you're using I'll throw this out there for others who might be interested in another way to easily handle this constraint in SQL Server (2008 or later).
You can use a filtered unique index to effectively put a constraint on the number of "active" rows for a given type. As an example:
CREATE UNIQUE INDEX My_Table_active_IDX ON My_Table (some_pk) WHERE active = 1
This approach has several advantages:
*
*It's declarative
*It's self-contained within the single table (no
FKs, no other objects that you need to keep updated, etc.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problem calling a C++ program from C# I have a C++ program (Test.exe) that takes in a number N (passed as command line argument) and generates coordinates for N rectangles written to a text file.
I have tested this via the command line and in Visual Studio, and on both occasions the file is written with the expected output.
In a C# program I enter N in a textbox, click a button and my event code is as follows:
Process p = new Process();
p.StartInfo.FileName = "Test.exe";
p.StartInfo.Arguments = num;
p.Start();
// read the file that Test.exe created
A file is not written by Test.exe.
Any suggestions as to why Test.exe doesn't write the file when it is called from the C# program?
Problem Found
The file was being written in the directory where the C# program was executed from NOT from where the C++ program was located.
A: I guess you forgot p.WaitForExit() right after the p.Start() line.
A: Two points:
*
*Make sure the working directory of Test.exe (StartInfo.WorkingDirectory) is set to a directory where the process has write access, and
*If Test.exe needs process elevation, use StartInfo.UseShellExecute = true and StartInfo.Verb = "runas" to start an elevated process. Your C# program needs to be an elevated process to do this, you can use an application manifest file for this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to send back information from the detail view to master view I have a master view with a tableview, then I go to the detail and modify it. what is the best practice to get the modify value, store it to my NSArray and update my tableview ?
I have made a delegate method in my detail view to call back my master view after modification, is it good? If you have a simple example with modify detail view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Incremental Assignment I have been working with C++ for many years, but just realized something fishy about incremental assignment.
I have this snippet
a = 4;
b = 2;
c = 0;
c = c + a > b; printf("a: %d\tb: %d\tc: %d\n",a,b,c);
c = c + a > b; printf("a: %d\tb: %d\tc: %d\n",a,b,c);
c += a < b; printf("a: %d\tb: %d\tc: %d\n",a,b,c);
c += a > b; printf("a: %d\tb: %d\tc: %d\n",a,b,c);
c += a > b; printf("a: %d\tb: %d\tc: %d\n",a,b,c);
And the result is
a: 4 b: 2 c: 1
a: 4 b: 2 c: 1
a: 4 b: 2 c: 1
a: 4 b: 2 c: 2
a: 4 b: 2 c: 3
If you note, the first two lines are the same. Or 'c' doesn't get updated after the first c = c + a > b;
However, the value of c gets updated when we use the incremental assignment +=
Any thoughts?
A: < has lower precedence than +.
c = c + a > b; is interpreted as c = (c + a) > b;
It is just so, there doesn't need to be a reason, but if there was one, it might be that people more often compare arithmetic expressions than use the results of comparisons in arithmetic expressions..
A: In the first line, c + a > b is true, which converts to 1, so the first line reads c = 1;. Rinse and repeat.
A: The compiler interprets your code as c = (c + a) > b where you probably want it to be interpreted as c = c + (a > b).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android SeparatedListAdapter - How to use custom object as List Item? I have a basic object called Employee. You can retrieve an Employee's name and id using .getName() and .getId().
I want to use Jeff Sharkey's SeparatedListAdapter to build a sectioned list. For the list items though, I need to use my custom Employee objects for the items instead of just lists of Strings.
In the included examples for the SeparatedListAdapter, he uses an ArrayAdapter<String> and a SimpleAdapter() for populating the list.
Is there any way to use a custom object/class, like my Employee class? The reason I'm needing to do this, is that when I click on an item in the list, I want to retrieve the actual Employee object that I used for that item and then retrieve the ID of the employee so I can display information pertaining to that Employee.
I'm a little bit confused on how to use Adapters properly. Should I make my own adapter or something?
A: You'll need to implement your custom adapter. Ex:
class CustomAdapter extends ArrayAdapter<Employee>
and when use it on SeparatedListAdapter:
CustomAdapter workersAdapter = new CustomAdapter(this, resourceID, workersList);
SeparatedListAdapter separated = new SeparatedListAdapter(this);
...
separated.addSection("Workers", workersAdapter);
Edit:
Overrride getView Method in your CustomAdapter to create views with Employee info. Like this:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if(convertView == null){
view = convertView;
}else
view = mInflater.inflate(R.layout.your_row, null);
Employee e = getItem(position);
((TextView)view.findViewById(R.id.textview_id)).setText(e.getId());
//...
return view;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery to select anchor tag by going through UL tag I want to select anchor tag in a div, but I want to select from the child ul tag as I am trying to create a dropdown.
My HTML code is as below:
<div>
<a href='#'>Dropper 1</a>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
<a href='#'>Dropper 2</a>
<ul>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
</div>
My JQuery code is as below:
$(document).ready(function(){
$('ul').each(function(){
$(this).parent().click(function(){ $('ul',this).show("1000"); });
$(this).parent().mouseleave(function(){ $('ul',this).hide("1000"); });
});
})
CSS for the UL code is as below:
ul {display:none;}
Now the UL is hidden and I want to select anchor using the UL. The above function is working right now because it is picking DIV as a parent and on clicking a div, ul is shown, but because the size of div is as same size of anchor tag so if anyone is clicking on div is same as clicking its child that is anchor and when click on anchor takes place then browser's default behavior is to scroll to top because of href='#'. I want to select that anchor to stop the scroll by using event.preventDefault();
Just tell me the way to select that anchor tag by going through UL
A: I think this is what you wanted:
$('ul').each(function() {
$(this).prev('a').click(function(e) {
e.preventDefault();
$(this).next().show("1000");
});
$(this).mouseout(function() {
$(this).hide("1000");
});
});
http://jsfiddle.net/ghLCv/2/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS RTP library/tutorial/example I'm wondering about the availability of a library to send and receive realtime text updates (between device and server) in a messaging-type app. I'm not really sure where to look, or what to search for, but my preliminary searches haven't had much success. Any help is much appreciated. Thanks!
A: How about XMPP (Extensible Messaging and Presence Protocol)? It has a very decent framework in Objective-C - http://code.google.com/p/xmppframework/.
If it's an option for you, WebSockets also come handy here. Try using zimt for instance or UnittWebSocketClient API.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loading xib dynamically but wrong one displaying I have an universal app that I am trying to share a viewController code with. I have this:
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
AboutController *screen = [[AboutController alloc] initWithNibName:@"iPhoneAboutController" bundle:nil];
screen.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:screen animated:YES];
}
else
{
AboutController *screen = [[AboutController alloc] initWithNibName:nil bundle:nil];
screen.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self presentModalViewController:screen animated:YES];
}
Although this is loading, and when I step through the code, it does hit the xib for the iPhone but it seems to always be loading the iPad version. I know this because in the xib file for the iPhone, I have manually added different background images and it never shows. In the iPhone simulator it shows the iPad version where it is off screen.
Also, if I step through the code in the controller, it does show that the load is the iPhone yet display is all iPad objects. In the iPhone xib, I do have the Files Owner set to the AboutController.
This is the first time I am attempting to "share code". I know I can just create separate class files with the same code but this seems senseless. Any help is greatly appreciated.
Geo...
A: For starters: make sure you don't override nib initialization in your AboutController.
If not, try cleaning your project (also delete your app's folders in ~/Library/Developer/Xcode/DerivedData). Also uninstall the app from device and then rebuild.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trying to use the Rails session flash, but getting nil.[] errors? <%# Flash-based notifications %>
<% if flash[:error].present? or flash[:notice].present? %>
<div class="messages <%= flash[:error] ? 'error' : 'notice' %>">
<ul id="feedback">
<% if flash[:error].present? %>
<li><%= flash[:error] %></li>
<% end %>
<% if flash[:notice].present? %>
<li><%= flash[:notice] %></li>
<% end %>
</ul>
</div>
<% end %>
For some reason, as simple as it seems, my attempt to read from the flash inside a partial is producing this error, because the flash is set to nil. Do I need to initialize it manually, or something?
This is Rails 3.1.0. The error is on line 2 of the code snippet, where it tries to access flash[:error].
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
I must be missing something. I'm definitely not overriding it anywhere.
A: They key here is that you are trying to access the flash inside a partial. You will need to do the following in your render method to pass the flash hash through to the partial:
render YOUR_PARTIAL, :flash => flash
http://guides.rubyonrails.org/layouts_and_rendering.html#passing-local-variables
EDIT:
Easier solution: rename your partial to anything but _flash.
Because your partial was called flash, this happened:
Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the :object option:
The flash object was being overwritten by a local variable created with the name of the partial.
To clarify this a bit, let's say you have a comment model and you render the comments in the partial, you may do something like:
#_comment.html.erb
<h1>comment.user.name</h1>
<p>comment.body</p>
You would call this partial by doing something along the lines of:
render @customer
Now replace the word customer with flash and you will see why this was an issue.
This functionality that is usually convenience is what caused the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Copying from grid_graph to adjacency_list with boost::copy_graph I'm using the boost graph library and trying to initalise a MutableGraph to start life as a grid.
Edges will be added and removed later in life, so I think adjacency_list<vecS,listS,undirectedS> is the right choice.
My reading about BGL indicated that the sensible way to initalise it with these edges would be to take advantage of boost::grid_graph by using
boost::copy_graph to copy from a boost::grid_graph that can make all the initial edges for me for free.
I thought that made sense - copy_graph copies from a model of VertexListGraph to a model of a MutableGraph, which is exactly what I have.
I initially tried using the 2-argument version of copy_graph, with the vague hope that something sensible would happen with the defaults for the rest. That turned out not to be the case, grid_graph (for reasons I couldn't quite figure out) doesn't seem to have a facility for using PropertyMaps with either edges or vertices, so the default vertex_copy and edge_copy failed (with a compiler error) copying the properties.
Since the 2-argument version clearly didn't seem appropriate I move on and tried to implement my own binary operator for copying vertices and edges. Even with a 'no-op' copy this doesn't work as well as I'd hope (i.e. it doesn't compile).
I've put together a minimum working example that illustrates the problem:
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/grid_graph.hpp>
#include <boost/graph/copy.hpp>
struct Position {
int x, y;
};
struct VertexProperties {
Position pos;
};
typedef boost::adjacency_list<boost::vecS, boost::listS, boost::undirectedS,
VertexProperties> Graph;
struct MyCopy {
template <typename S, typename D>
void operator()(const S& /*src*/, D& /*dest*/) {
// Nothing for now, deduced types to try and just make it compile
// TODO: set values for pos to reflect position on grid.
}
};
int main() {
boost::array<std::size_t, 2> lengths = { { 3, 3 } };
boost::grid_graph<2> grid(lengths);
Graph graph;
MyCopy copier;
// Using 3-Arg version of copy_graph so we can specify a custom way of copying to create the properties
boost::copy_graph(grid,graph,boost::bgl_named_params<MyCopy,boost::vertex_copy_t,
boost::bgl_named_params<MyCopy,boost::edge_copy_t> >(copier));
}
This example doesn't compile:
g++ -Wextra -Wall -O2 -g -o copytest.o -c copytest.cc
In file included from /usr/include/boost/graph/grid_graph.hpp:24:0,
from copytest.cc:2:
/usr/include/boost/iterator/transform_iterator.hpp: In constructor ‘boost::transform_iterator<UnaryFunction, Iterator, Reference, Value>::transform_iterator() [with UnaryFunc = boost::detail::grid_graph_vertex_at<boost::grid_graph<2u> >, Iterator = boost::counting_iterator<unsigned int, boost::use_default, boost::use_default>, Reference = boost::use_default, Value = boost::use_default]’:
/usr/include/boost/graph/copy.hpp:115:55: instantiated from ‘static void boost::detail::copy_graph_impl<0>::apply(const Graph&, MutableGraph&, CopyVertex, CopyEdge, Orig2CopyVertexIndexMap, IndexMap) [with Graph = boost::grid_graph<2u>, MutableGraph = boost::adjacency_list<boost::vecS, boost::listS, boost::undirectedS, VertexProperties>, CopyVertex = MyCopy, CopyEdge = MyCopy, IndexMap = boost::grid_graph_index_map<boost::grid_graph<2u>, boost::array<unsigned int, 2u>, unsigned int>, Orig2CopyVertexIndexMap = boost::iterator_property_map<__gnu_cxx::__normal_iterator<void**, std::vector<void*, std::allocator<void*> > >, boost::grid_graph_index_map<boost::grid_graph<2u>, boost::array<unsigned int, 2u>, unsigned int>, void*, void*&>]’
/usr/include/boost/graph/copy.hpp:327:5: instantiated from ‘void boost::copy_graph(const VertexListGraph&, MutableGraph&, const boost::bgl_named_params<P, T, R>&) [with VertexListGraph = boost::grid_graph<2u>, MutableGraph = boost::adjacency_list<boost::vecS, boost::listS, boost::undirectedS, VertexProperties>, P = MyCopy, T = boost::vertex_copy_t, R = boost::bgl_named_params<MyCopy, boost::edge_copy_t>]’
/mnt/home/ajw/code/hpcwales/copytest.cc:31:66: instantiated from here
/usr/include/boost/iterator/transform_iterator.hpp:100:26: error: no matching function for call to ‘boost::detail::grid_graph_vertex_at<boost::grid_graph<2u> >::grid_graph_vertex_at()’
/usr/include/boost/graph/grid_graph.hpp:104:7: note: candidates are: boost::detail::grid_graph_vertex_at<Graph>::grid_graph_vertex_at(const Graph*) [with Graph = boost::grid_graph<2u>]
/usr/include/boost/graph/grid_graph.hpp:100:33: note: boost::detail::grid_graph_vertex_at<boost::grid_graph<2u> >::grid_graph_vertex_at(const boost::detail::grid_graph_vertex_at<boost::grid_graph<2u> >&)
My analysis of that error is that it seems to be trying to default construct part of the internals of grid_graph, which can't be default constructed, for some reason that isn't terribly clear to me.
(clang doesn't really tell me anything I can't see from g++ here).
Questions:
*
*Is this the right way to go about initalising a mutable graph to start as a regular grid? I initially thought it was much easier than writing a function to do so myself, but now I'm not so sure!
*Why is the default value of orig_to_copy and/or vertex_index not appropriate here? I'm assuming that those two are the cause of the error. (Which, if any, of those is actually causing the problem? I can't decipher what the root cause of the current error is).
*What is the "correct" way of fixing this?
A: You are on the right track, but there are two things that need to be changed in your code. The first is that there is a special method of defining custom vertex properties. The second is that there is a different syntax (more preferred and probably the only one that is correct) for BGL named parameters.
On the first item, please refer to the section of the documentation titled Custom Vertex Properties. Essentially, in order to define a custom vertex property, you need to first define a "tag type" (a struct with a name ending in _t):
struct vertex_position_t {
typedef boost::vertex_property_tag kind;
};
Then you include the tag type somewhere in the boost::property template that defines internally-stored vertex properties:
typedef boost::property<boost::vertex_index_t, std::size_t,
boost::property<vertex_position_t, Position> > VertexProperties;
The above typedef defines two internally-stored properties: index and the custom "position".
On the second item, the preferred way to use named parameters is a "method chaining-like" syntax. For example, if a function accepts two named parameters, named_param1 and named_param2, there are two functions in the boost namespace named named_param1 and named_param2, respectfully. The boost::named_param1 function accepts the value for the named_param1 parameter and returns an object having a named_param2 method (similarly, the boost::named_param2 function accepts the value for the named_param2 parameter and returns an object having a named_param1 method). You call the method to set the value for that named parameter (which in turn returns another object having methods for other supported named parameters).
In order to pass values val1 and val2 for named parameters named_param1 and named_param2, you can either use:
boost::named_parameter1(val1).named_param2(val2)
or:
boost::named_parameter2(val2).named_param1(val1)
For reference, here is a complete program that copies a grid to an object of the Graph type:
#include <cassert>
#include <cstddef>
#include <cstdlib>
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/copy.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/grid_graph.hpp>
#include <boost/property_map/property_map.hpp>
struct vertex_position_t {
typedef boost::vertex_property_tag kind;
};
struct Position {
std::size_t x, y;
Position()
: x(0), y(0)
{
}
};
typedef boost::property<boost::vertex_index_t, std::size_t, boost::property<vertex_position_t, Position> > VertexProperties;
typedef boost::adjacency_list<boost::vecS, boost::listS, boost::undirectedS, VertexProperties> Graph;
typedef boost::graph_traits<Graph> GraphTraits;
namespace detail {
typedef boost::grid_graph<2> Grid;
typedef boost::graph_traits<Grid> GridTraits;
struct grid_to_graph_vertex_copier {
typedef boost::property_map< Grid, boost::vertex_index_t>::type grid_vertex_index_map;
typedef boost::property_map< ::Graph, boost::vertex_index_t>::type graph_vertex_index_map;
typedef boost::property_map< ::Graph, ::vertex_position_t>::type graph_vertex_position_map;
const Grid& grid;
grid_vertex_index_map grid_vertex_index;
graph_vertex_index_map graph_vertex_index;
graph_vertex_position_map graph_vertex_position;
grid_to_graph_vertex_copier(const Grid& grid_, Graph& graph)
: grid(grid_), grid_vertex_index(get(boost::vertex_index_t(), grid_)),
graph_vertex_index(get(boost::vertex_index_t(), graph)),
graph_vertex_position(get(::vertex_position_t(), graph))
{
}
private:
Position grid_vertex_index_to_position(std::size_t idx) const {
unsigned num_dims = grid.dimensions();
assert(grid.dimensions() == 2);
idx %= grid.length(0) * grid.length(1);
Position ret;
ret.x = idx % grid.length(0);
ret.y = idx / grid.length(0);
return ret;
}
public:
void operator()(GridTraits::vertex_descriptor grid_vertex, ::GraphTraits::vertex_descriptor graph_vertex) const {
std::size_t idx = get(grid_vertex_index, grid_vertex);
put(graph_vertex_index, graph_vertex, idx);
Position pos = grid_vertex_index_to_position(idx);
std::cout << "grid_vertex = " << idx << ", pos.x = " << pos.x << ", pos.y = " << pos.y << std::endl;
put(graph_vertex_position, graph_vertex, pos);
}
};
struct grid_to_graph_edge_copier {
void operator()(GridTraits::edge_descriptor grid_edge, ::GraphTraits::edge_descriptor graph_edge) const {
}
};
}
int main()
{
boost::array<std::size_t, 2> lengths = { { 3, 5 } };
detail::Grid grid(lengths);
Graph graph;
boost::copy_graph(grid, graph, boost::vertex_copy(detail::grid_to_graph_vertex_copier(grid, graph))
.edge_copy(detail::grid_to_graph_edge_copier()));
std::cout << std::endl;
boost::write_graphviz(std::cout, graph);
return EXIT_SUCCESS;
}
When I ran this, I received the following output:
grid_vertex = 0, pos.x = 0, pos.y = 0
grid_vertex = 1, pos.x = 1, pos.y = 0
grid_vertex = 2, pos.x = 2, pos.y = 0
grid_vertex = 3, pos.x = 0, pos.y = 1
grid_vertex = 4, pos.x = 1, pos.y = 1
grid_vertex = 5, pos.x = 2, pos.y = 1
grid_vertex = 6, pos.x = 0, pos.y = 2
grid_vertex = 7, pos.x = 1, pos.y = 2
grid_vertex = 8, pos.x = 2, pos.y = 2
grid_vertex = 9, pos.x = 0, pos.y = 3
grid_vertex = 10, pos.x = 1, pos.y = 3
grid_vertex = 11, pos.x = 2, pos.y = 3
grid_vertex = 12, pos.x = 0, pos.y = 4
grid_vertex = 13, pos.x = 1, pos.y = 4
grid_vertex = 14, pos.x = 2, pos.y = 4
graph G {
0;
1;
2;
3;
4;
5;
6;
7;
8;
9;
10;
11;
12;
13;
14;
0--1 ;
1--2 ;
3--4 ;
4--5 ;
6--7 ;
7--8 ;
9--10 ;
10--11 ;
12--13 ;
13--14 ;
1--0 ;
2--1 ;
4--3 ;
5--4 ;
7--6 ;
8--7 ;
10--9 ;
11--10 ;
13--12 ;
14--13 ;
0--3 ;
1--4 ;
2--5 ;
3--6 ;
4--7 ;
5--8 ;
6--9 ;
7--10 ;
8--11 ;
9--12 ;
10--13 ;
11--14 ;
3--0 ;
4--1 ;
5--2 ;
6--3 ;
7--4 ;
8--5 ;
9--6 ;
10--7 ;
11--8 ;
12--9 ;
13--10 ;
14--11 ;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: What is the complexity of these Dictionary methods? Can anyone explain what is the complexity of the following Dictionary methods?
ContainsKey(key)
Add(key,value);
I'm trying to figure out the complexity of a method I wrote:
public void DistinctWords(String s)
{
Dictionary<string,string> d = new Dictionary<string,string>();
String[] splitted = s.split(" ");
foreach ( String ss in splitted)
{
if (!d.containskey(ss))
d.add(ss,null);
}
}
I assumed that the 2 dictionary methods are of log(n) complexity where n is the number of keys in the dictionary. Is this correct?
A: That is not correct, generally dictionaries / hashtable lookup is O(1). To do this it will generate a hash from the key your are looking for and only compare it to items that have the same hash - with a good hashing algorithm this is considered O(1) overall (amortized O(1) - only in the rare occasion that the capacity must be increased for an addition you have O(n)).
A: It's written in the documentation for Dictionary...
The Dictionary generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1), because the Dictionary class is implemented as a hash table.
And for the Add function:
If Count is less than the capacity, this method approaches an O(1) operation. If the capacity must be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count.
A: Both methods have constant complexity:
*
*ContainsKey(key) - O(1)
*Add(key,value) - O(1)
A: This routine, as a whole, is, effectively, O(m) time complexity, with m being the number of strings in your search.
This is because Dictionary.Contains and Dictionary.Add are both (normally) O(1) operations.
(It's slightly more complicated than that, as Dictionary.Add can be O(n) for n items in the Dictionary, but only when the dictionary capacity is small. As such, if you construct your dictionary with a large enough capacity up front, it would be O(m) for m string entries.)
That being said, if you're only using the Dictionary for existence checking, you could use a HashSet<string>. This would allow you to write:
public void DistinctWords(String s)
{
HashSet<string> hash = new HashSet<string>(s.Split(' '));
// Use hash here...
As your dictionary is a local variable, and not stored (at least in your code), you could also use LINQ:
var distinctWords = s.Split(' ').Distinct();
A: Both are constant time:
http://msdn.microsoft.com/en-us/library/kw5aaea4.aspx
http://msdn.microsoft.com/en-us/library/k7z0zy8k.aspx
One caveat however:
"If Count is less than the capacity, this method approaches an O(1) operation. If the capacity must be increased to accommodate the new element, this method becomes an O(n) operation, where n is Count."
A: The ContainsKey and Add method are close to O(1).
ContainsKey documentation:
This method approaches an O(1) operation.
Add documentation:
If Count is less than the capacity, this method approaches an O(1)
operation. If the capacity must be increased to accommodate the new
element, this method becomes an O(n) operation, where n is Count.
If you are using Framework 3.5 or later, you can use a HashSet<T> instead of a dictionary with dummy values:
public void DistinctWords(String s) {
HashSet<string> d = new HashSet<string(s.split(" "));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: PHP sessions in Internet Explorer Having an issue with the intranet I'm developing for my company. It's hosted locally on our server and uses PHP. It has a login script which works fine with Firefox and Chrome, but when I try to login with Internet Explorer it just takes me back to the main login page and doesn't execute the script at all. I think it has something to do with the PHP session and generating a new session ID, any ideas? Here my code
$//If there are input validations, redirect back to the login form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: index.htm");
exit();
}
//Create query
$qry="SELECT * FROM employees WHERE username='$login' AND password='$password'";
$result=mysql_query($qry);
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) == 1) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['ID'];
$_SESSION['SESS_fname'] = $member['fname'];
$_SESSION['SESS_lname'] = $member['lname'];
$_SESSION['SESS_username'] = $member['username'];
session_write_close();
header("location: login_success.php");
exit();
}else {
//Login failed
header("location: login-failed.php");
exit();
}
}else {
die("Query failed");
}
Any suggestions?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Core-Plot: Removing line that connects points in Scatterplot? I would like to simply show scatterplot points. Actually, two sets of scatterplot points with different colors.
However, it seems that the default condition of a scatterplot is to connect the dots. I've tried to set the CPTMutableLineStyle properties to nil, but the line still shows.
A: You can hide lines in Core Plot by setting the corresponding line style to nil.
scatterPlot.dataLineStyle = nil;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Specific file name regex with optional text I am trying to build a regular expression for a specific name with optional text in the middle. This alone is fairly easy:
^(pom)(.*?)([.]xml)$
However, there is one constraint I would like to have. This may be is possible, perhaps it isn't (I haven't been able to find anything like this). There can be additional text within the file name but if it is there, it has to be preceded with an underscore. The following example should help illustrate what I am trying to get:
pom.xml - SUCCEED
pomdxml - FAIL
pomd.xml - FAIL
pom_asdf.xml - SUCCEED
pom_.xml - FAIL
Thank you in advance for your knowledge and help!
A: Here you go:
^(pom)(_.+)?(\.xml)$
A: Just use an optional group.
^(pom)(_.*)?(\.xml)$
A: This also worked for me
^pom(_\w+)*([.]xml)$
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Chapter 5 of Hartl book Why does routing requires get() for user.new? Around listing 5.29 of the Hartl rails tutorial (http://ruby.railstutorial.org/) there is a discussion of a routing error that forces you to call the get method on users/new and not just a match method. This is later rectified by calling to the resources method in the next chapter.
My general question is why don't we have to call get() on the PagesController actions in the following listing.
#5.29
SampleApp::Application.routes.draw do
get "users/new"
match '/signup', :to => 'users#new'
match '/contact', :to => 'pages#contact'
match '/about', :to => 'pages#about'
match '/help', :to => 'pages#help'
root :to => 'pages#home'
end
A: The difference is in the types of HTTP requests the routes will match.
By using get "users/new" the route will only match HTTP GET requests.
match "users/new" would actually match all types of HTTP requests.
You can use get instead of match for your other routes if you only expect GET requests for them (which appears to be the case).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Node.js error handling guarantee with net.createConnection I was wondering if Node.js provides any guarantee that the error handler will catch all errors in code like the following:
var c = net.createConnection(port, host);
c.on('error', function (e) { ... });
I've had to deal with code where other statements intervened between the call to createConnection and the statement which sets the error handler, and this sometimes caused errors internal to createConnection to percolate to the top level (presumably because these errors sometimes occurred before the error handler had been set). But unless I'm missing something, this could in principle happen in the code above -- it's just not very likely. Is there any way of actually guaranteeing that all errors which occur within createConnection will get passed to the error handler?
A: It will only happen if there are bugs in node.
JavaScript is single threaded, the process will not normally be interrupted between attaching the event handler and creating the connection.
No error generated in javascript land will be uncaught by that code.
So if there was a bug in node, there could probably be some errors your code would not catch. If you had some dodgy low level code running in the background causing mayhem it could be possible that some errors would occur that your code would not catch.
But under normal usage, your code is "threadsafe". Your binding the event handler before any errors occur because your code is blocking and nothing can throw errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How do sites like Google, Yahoo, etc store their user/pass? How do big websites store the millions of user/pass combinations? I'm asking about how things are stored in the database - or do they even use a database? How do they scan through the millions of entries almost instantly?
A: Hashed index. If you use a numeric, unique userid you can assume few collisions (if set up correctly) and hash indexes are your best bet.
http://en.wikipedia.org/wiki/Hash_table
And yes, they do use databases. Typically multiple load balanced servers. See this question for ideas on load balancing for SQL server as there are multiple approaches:
https://stackoverflow.com/questions/761502/sql-server-load-balancing
One popular way to load balance is called "federating" by Microsoft, but it pretty much spreads the query request and lets it be serviced by multiple servers (afaik).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mutating method send to immutable object This the snippet of code where I get an error:
//sourceArray is a NSMutablearray
NSMutableDictionary *dayOfWeekDictionary= [sourceArray objectAtIndex:indexpath.row];
[dayOfWeekDictionary setObject:[NSNumber numberWithBool:YES] forKey:@"isSelected"];//line 2
What I’ve come to know from googling is that there is some stuff in assigning immutable object into mutable object.
I get an error at line 2. Any suggestions?
A: If [sourceArray objectAtIndex:indexpath.row] returns an immutable dictionary, simply assigning it to a variable of type NSMutableDictionary * doesn’t automatically convert it to a mutable dictionary. You could write this instead:
NSMutableDictionary *dayOfWeekDictionary= [NSMutableDictionary dictionaryWithDictionary:[sourceArray objectAtIndex:indexpath.row]];
By using +[NSMutableDictionary dictionaryWithDictionary:], you get a mutable dictionary based on another dictionary (which can be either mutable or immutable). Note that you do not own this dictionary, hence you don’t have to release it. Also note that this is not the same dictionary object as the one stored in the array. If you need both the array and dayOfWeekDictionary to be the same dictionary, then you should add a mutable dictionary to the array.
A: Are you sure there is an instance of NSMutableDictionary in [sourceArray objectAtIndex:indexpath.row]?
I suggest placing a break point at line 2 and inspecting the content of dayOfWeekDictionary.
AND
In your comment, you set an instance of NSMutableArray into the variable dayOfWeekDictionary of type NSMutableDictionary, if you try to call [dayOfWeekDictionary setObject:[NSNumber numberWithBool:YES] forKey:@"isSelected"]; the application will crash with an unrecognized selector sent to instance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL Regex - Find where there are 10 numbers in a row in a field I need to find records where there are 10 numbers in a row in the field. e.g. 1234567890, 8884265555 etc. The field will contain text as well so I need to see if any 10-digit strings exist anywhere within the field.
I have got this far...
SELECT * FROM `comments` WHERE detail REGEXP '[0-9]{10}'
My that returns where there 10 numbers anywhere in the field instead of all in a row. I am trying to detect phone numbers. Thanks!
A: The regular expression [0-9]{10} does imply that ten digits in a row (only) should be matched. So, your issue must be elsewhere.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Designing a forward-looking Windows 7 tablet GUI app I'm building a tablet application with basic browser-like functionality (mostly, view a pre-defined selection of Web pages and PDFs). For various reasons (such as the need to run another traditional Windows application on the same device), it needs to run on Windows, so designing it for a modern tablet platform like iOS or Android is out of the question. At the same time, it's too soon for Windows 8 / Metro.
Nonetheless,
*
*running traditional (desktop-like) Windows applications on the tablet is unappealing; at the very least, I need far bigger and simpler controls.
*I'd like to design it more or less with the upcoming Windows 8 in mind, ideally so that a future Metro style-based version of the same app won't feel too foreign to the user, and ideally also won't require too much of a code redesign.
Coming from either a .NET or Web background, what's the best framework, thinking forward, to use here? WPF (or even Windows Forms?), Silverlight or HTML?
And, UI-wise, is there a set of controls (or, in the case of HTML, a stylesheet / set of scripts) that mimic or approach Metro style? I assume that, for copyright reasons, I can't simply use those from Windows 8 in Windows 7.
A:
Coming from either a .NET or Web background, what's the best
framework, thinking forward, to use here? WPF (or even Windows
Forms?), Silverlight or HTML?
What i advise you is to choose WPF. Or if WPF isn't your priority choose any XAML interface based technology. If you are trying to built a lightweight application that can even run in Windows8 you can choose silver-light (browser based application). XAML based technology will be better because Windows 8 Metro style supports XAML
And, UI-wise, is there a set of controls (or, in the case of HTML, a
stylesheet / set of scripts) that mimic or approach Metro style? I
assume that, for copyright reasons, I can't simply use those from
Windows 8 in Windows 7.
I don't think it would be problem of copyrights, but just in case don't exactly copy the interface, try to built something that resembles in such a way that user won't feel much difference in terms of use when he shifts himself to windows 8 version
A:
And, UI-wise, is there a set of controls (or, in the case of HTML, a stylesheet / set of scripts) that mimic or approach Metro style? I assume that, for copyright reasons, I can't simply use those from Windows 8 in Windows 7.
If you are looking for a Metro themed wpf components, you can use DotNetBar from devcomponents.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Where do you put jquery javascript code in a CodeIgniter application? If I have this line in my view:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
Do I also put my actual script in my view?
<script type="text/javascript">
$(document).ready(function() {
alert("Hello world!");
}); </script>
Or do I put my actual javascript somewhere else and send it to the view somehow?
Thanks.
A: This is how i do it. For page specific javascript i include it in the page itself. For other javascript that would need to be run on most pages i put it in the global javascript, mine is called main.js.
So, as an example, say you would like to hide some_div on page load, and this div is on a specific page.
<body>
<div id="content">
<div id="some_div">
</div>
</div>
</body>
Then you would just do that in the page specific javascript.
An example of the main/global javscript file would be js that you want run on each page. So some examples are fadeIn animations for the content area, if all/most your pages have a content area and you would like to fade the content in on every page load, then the global java script would be a good place to put it so you don't have repeated code. Another example is if you want to make all inputs with a class="calendar" into a datepicker, then in your global js file you would just do.
$(function(){
$('.calendar').datepicker()
});
This way you don't have to do that for each page and have repeated code. Long story short, if you are going to use the same js code in other pages too then might as well put it in a global js file.
In relation to codeigniter. What i did was create a "view partial" (really just a view) for all my js and css files. So in my view js.php i have:
<script type="text/javascript" src="/javascript/jquery.js" /> </script>
<script type="text/javascript" src="/javascript/jquery-ui.js" /> </script>
<script type="text/javascript" src="/javascript/main.js" /> </script>
Then i just reference this view partial in the view page that i need to include the scripts i.e
<?php $this->load->view('/common/js') ?>
This way i don't need to manually include the javascript files i need for each view.
A: When developing a codeigniter application, I usually use a template which loads three views:
*
*Scripts View
*Header View
*Main View
*Footer View
In the Scripts View, I load the common JavaScript libraries that are required by every page (e.g. jQuery etc).
For page specific JavaScript, there are two options that you could follow:
*
*You could include the JavaScript on the View page itself, but that would make it cluttered and difficult to maintain.
*Another way is to create a JavaScript file for every view that you load that needs to have page specific JavaScript and then loading that file in the view like any other JavaScript. The drawback to this is that the server requests are doubled.
In the end, it really comes down to what you are really comfortable with and the efficiency.
A: I have all of my js in a folder and call it when i need them.
This is more orderly in my opinion, but theres no rule stating you can't have javascript in your views. if its something simple that wont get re-used, then go ahead and keep it in the view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: JavaScript: convert objects to array of objects I have thousands of legacy code that stores array information in a non array.
For example:
container.object1 = someobject;
container.object2 = someotherobject;
container.object3 = anotherone;
What I want to have is:
container.objects[1], container.objects[2], container.objects[3] etc.
The 'object' part of the name is constant. The number part is the position it should be in the array.
How do I do this?
A: Assuming that object1, object2, etc... are sequential (like an array), then you can just iterate through the container object and find all the sequential objectN properties that exist and add them to an array and stop the loop when one is missing.
container.objects = []; // init empty array
var i = 1;
while (container["object" + i]) {
container.objects.push(container["object" + i]);
i++;
}
If you want the first item object1 to be in the [1] spot instead of the more typical [0] spot in the array, then you need to put an empty object into the array's zeroth slot to start with since your example doesn't have an object0 item.
container.objects = [{}]; // init array with first item empty as an empty object
var i = 1;
while (container["object" + i]) {
container.objects.push(container["object" + i]);
i++;
}
A: An alternate way to do this is by using keys.
var unsorted = objectwithobjects;
var keys = Object.keys(unsorted);
var items = [];
for (var j=0; j < keys.length; j++) {
items[j] = unsorted[keys[j]];
}
You can add an if-statement to check if a key contains 'object' and only add an element to your entry in that case (if 'objectwithobjects' contains other keys you don't want).
A: That is pretty easy:
var c = { objects: [] };
for (var o in container) {
var n = o.match(/^object(\d+)$/);
if (n) c.objects[n[1]] = container[o];
}
Now c is your new container object, where c.object[1] == container.object1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Porting an HTML5 Canvas WebGL game to Flash ActionScript 3.0 I had created an HTML5 Canvas WebGL game in January for the Mozilla Game On 2010 competition (pretty late, I know - I never released it until yesterday). Now I want to port it to Flash ActionScript 3.0 for a college assignment.
I'm well versed with both static languages like C/C++ and Java; and dynamic languages like Python and JavaScript. However I don't know ActionScript, but since it's a subset of ECMAScript it should be pretty easy to understand.
I want to learn programming in ActionScript 3.0 so that I may be able to port my game in Flash. To be more specific, I want to know more about:
*
*How is ActionScript different from Browser and Server-Side JavaScript, and basics.
*OpenGL programming in ActionScript (including loading textures, shaders, etc).
*How to create a HUD in Flash using a 2D HTML5 Canvas like API (in my game I have 2 canvases, one for the 3D game and another overlaying it for the heads-up display).
*Support for vector and matrix calculations in ActionScript.
*How to load assets like audio and sprites in Flash.
I would appreciate it if you would provide me a link to a page from where I can learn more about these topics. A more direct hands-on approach would be preferable.
It would be even more helpful if you would check my source code in JavaScript and suggest the best possible way for me to tackle this problem.
The code for the main game engine and the game itself may be found in my Github repository.
A: ActionScript and JavaScript are very similar at their core. In some ways you can think of ActionScript as more like a robust library layered on top of ECMAScript. There are a few differences (namely ActionScript likes to think of itself as a class-based oop, where as JavaScript is prototype-based), but if you are comfortable with one, then you should be pretty at ease with the other.
ActionScript has a class based inheritance system and supports interfaces (but you can still do some prototypical magic if you want, but its not recommended). It also supports strongly-typed objects.
var object:MovieClip = new MovieClip();
This will strongly type the object variable as a instance of the MovieClip class.
If your game is very 3D intensive, then you'll want to look into the new Flash 11 Stage3D and Context3D classes. These expose a low level GPU accelerated API that before Flash 11 wasn't possible. You can do interesting 3D stuff with Flash 10, but you are usually using drawTriangles(), which was not hardware accelerated. Flash 11 is currently in beta, but it should be out very soon. There are beta versions of the Flex SDK that should let you compile targeting the Flash 11 player.
There are also quite a few 3D libraries that are built on-top of these low-level api. If you goggle around for them, they are easy to find. But I would recommend getting a solid understanding of how ActionScript works before diving into the 3D libraries.
The HUD stuff in flash is simple whether you go with Flash 11 or Flash 10. For "classic" flash, you'll want to get familiar with the display tree concept they use in flash. Just make sure the display order is correct, and your HUD DisplayObject will always be "on-top" of your rendering DisplayObject
For Flash 11, StageVideo and Stage3D objects sit directly above the stage, but behind all normal flash DisplayObjects that are attached to the stage. So in that case, I would let the Stage3D api take care of all of your heavy rendering lifting, and use the traditional display stack for your HUD elements.
You'll probably also want to grab yourself Flash Builder over Flash CS5.5. If you are a programmer (which I am assuming you are since you are posting here), it wont make your eyes bleed trying to code. FB is based off eclipse, and its pretty decent but not perfect. But if you grab yourself the free Flex SDK, and don't mind using the command line, you can get started compiling swfs pretty quick and cheap (aka free).
Also, look into FlashDevelop. I haven't used it in a while, since switching to FB for its built in profiler, but it might be of use to you.
Importing images and audio is pretty straight-forward with the Flex SDK.
[Embed(source="logo.gif")]
public var LogoBitmapData:Class;
and then later instantiate the class:
var bitmapData:BitmapData = (new LogoBitmapData()) as BitmapData;
And then use it where ever you want to.
Just a note about the Flex. Flex is a set of UI libraries built on top of the normal Flash API, the Flex SDK includes the libraries and tools to compile MXML and ActionScript code files. So, despite it sounding like you should use the Flex SDK to compile Flex apps, you can use it to compile straight ActionScript code as well.
There are built in classes for Vector3D and Matrix3D.
As far as tutorials or references, I don't have any to offer really. I've found that most of the information on the internet about ActionScript programming is pretty hit or miss (when you can find something thats not written by a graphic designer). I'd dig around in here and see if you can find anything that makes sense to you.
There is obviously a lot more I could go into about this stuff, but hopefully this will give you a push in the right direction.
A: Welcome to AS3 :)
@32bitkit beat me to the IDE info, but I'd absolutely recommend Flash Builder. It's a real tool and worth the money if you're going to be doing any real AS3 work.
As far as actual tutorials, Senocular is known for writing some of the best content out there. He has a number of great tutorials here, but the following two are especially excellent introductory tutorials for AS3:
*
*AS3 Introduction in Flash CS3 This tutorial is good because it explains the differences between AS2 (very JavaScript-like) and AS3. Ignore the fact that it's based on using the Flash "IDE."
*AS3 Introduction Without Learning Flex This one is useful because it give more of an introduction to the language itself, without all of the trappings of the IDE or the Flex framework. It will help you understand the language itself.
As shown in that second tutorial, an AS3-based project will inherit from the flash.display.Sprite class. You can view the docs for that here. Perhaps it sounds silly, but you'll honestly learn quite a lot about AS3 by just browsing the AS3 Reference docs. Adobe has done a good job with those.
Another thing to be aware of in AS3 is how events are handled. This tutorial explains how the EventDispatcher class functions as the base of the event management. You can use the built-in events or dispatch your own.
HTH!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OpenGL rotating textured planes in 3D space I'm wondering if anyone could point me to any resources that would deal in rotating one or several 2D textured planes in 3D space. Something like this but with openGL (preferably C++):
I'm attempting to do pretty much the exact same thing but no matter how I order my operations I'm getting right-screwy results. So I figure asking for some resources on the subject is better than posting tons of code and asking for people to fix my problems for me. :)
A: If you havent already, do a search for 'NeHe tutorials'. An excellent set of OpenGL tutorials.
Here is a link to the rotation tutorial, includes all the source code in downloadable format and the tutorial walks you through each relevant line.
http://nehe.gamedev.net/tutorial/rotation/14001/
I believe this is working in a 2D space, the step up to 3D probably involves a bit more matrix math but...doable
A: The NeHe tutorials are a very popular place to learn the basics of OpenGL. In particular, the tutorial about texture mapping should help you:
http://nehe.gamedev.net/tutorial/texture_mapping/12038/
Mind you though that these tutorials are written for older OpenGL versions which are more beginner friendly IMHO.
A: You should look into scene graphs. Basically it is a way to define a bunch of objects (2D textured planes) and their transforms in 3D space. This allows you to define transforms that work on multiple nodes (objects) as well as single nodes. You can make a pretty simple one in C++ with little effort, or use one such as OpenSG or OSG (slight learning curve needed).
Wikipedia - http://en.wikipedia.org/wiki/Scene_graph
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I Create Chrome Application Shortcuts Programmatically from a Web Page? I've thought about using Chrome and HTML5 local storage to create a useful app and sell it. The problem I think I would have, however, is the delivery mechanism to get this installed on one's computer. Let's say the app was wikipedia.com (although it isn't). Manually one can go there with Chrome, then choose the wrench icon, Tools, Create Application Shortcuts, and make a desktop and application menu icon for the app.
Okay, fine, but is there a way I can compose a web page link or form button such that it does this for me? In other words, one clicks a button or link and it shows the Create Application Shortcuts form. I am hoping that there's this little-known way on Google Chrome to use either HTML or Javascript to trigger showing that form.
As for those who don't have Chrome, I can detect that and give them a button they click that emails them. In the email, it will give them instructions for installing Chrome and then another link so that they can visit this page in Chrome in order to get the button that shows the Create Application Shortcuts form.
A: For now, until a better answer can be provided, this is sort of the technique for deploying a desktop app with Chrome, the manual way, and without having to register in the Chrome Store:
*
*After the user purchases a product, email them the serial number for registering their product and a web URL to install this new product.
*The web URL is the actual URL of the web app. However, it doesn't display its normal content by default. Instead, the web app is in "installer mode". It does this by looking at a 200 year persistent, encrypted, registration cookie that may not already be installed. (Note if they delete cookies, there's no harm done -- it just asks them to re-register again.)
*The first thing the web app does in Installer Mode is detect user agent. If it finds this is not Chrome, it gives them a link to install Chrome and tells them to follow the instruction email again that they have already been sent, but using Chrome to do this. (You might also want to provide a form to resend them the instructions and serial number again.)
*The user either installs Chrome and returns back to this page again, or is already a Chrome user. The Installer Mode then shows a message that reads, please press the ALT-F key in Chrome, or press the Wrench icon in your toolbar, and choose Tools > Create Application Shortcuts, check the two checkboxes, click OK, and then click the "Task Performed" button below.
*The user follows the instructions and creates their desktop/application shortcut and then clicks "Task Performed".
*The user then sees a registration form where they are to type in their serial number they were emailed. The user enters this in and clicks the Register button.
*The server validates the registration and then stores a persistent, 200 year encrypted cookie that basically says, "This guy is registered." This keeps the web app from running in Installer Mode.
*The Installer Mode is still active, however, and shows them the final prompt: "You may close your browser and run the icon for the new app from your desktop or application shortcut that you created. The icon is named '{insert name here}'."
*They close their browser and doubleclick the icon. The application loads, the registration cookie is read, and the web app no longer runs in Installer Mode -- it shows the application content like it normally would. Besides the fact that this is not a 100% truly automated install, the only drawback is that, since the main page is not a local file (cached), the web app can't really work offline completely. Sure, it can use HTML5 offline storage, but doubleclicking the desktop shortcut will always connect to your web app site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Craigslist API - how to post with RSS data? http://www.craigslist.org/about/bulk_posting_interface - it says, "New postings are submitted to craigslist in RSS format with additional craigslist-specific elements via HTTPS POST"
How do I post a form passing rss data?
I was hoping to just have something like this:
<form action="https://post.craigslist.org/bulk-rss/post" type="post">
<input type="hidden" name="area" value="richmond" />
<input type="hidden" name="category" value="free" />
<input type="hidden" name="reply-email" value="x@y.com" />
</form>
But, it says I have to supply the data in RSS format.
So is it something like this?
<form action="https://post.craigslist.org/bulk-rss/post" type="post">
<input type="hidden" value="{all the RSS data goes here??}" />
</form>
Any help is super appreciated. Eventually I'd like to build an android app that posts to Criagslist, but, just want to get a simple html form to test for proof of concept for now. Thanks!
A: I've been trying to figure this out, too, but from what I have read about this RSS interface it is only available for non-free categories like employment and real estate postings. Those categories require you to purchase blocks of posting credits.
IMO this is a good reason not to use Craigs List. If anything, they should open up the RSS interface to all categories and perhaps limit the rate of posting for free ads and/or let people buy blocks for other categories.
A: The format of the request will look like this
<?xml version="1.0" encoding="UTF-8"?>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/" xmlns:cl="http://www.craigslist.org/about/cl-bulk-ns/1.0">
<channel>
<items>
<rdf:li rdf:resource="NYCBrokerHousingSample1" />
</items>
<cl:auth username="Vusername@gmail.com" password="password" accountID="14" />
</channel>
<item rdf:about="NYCBrokerHousingSample1">
<cl:category>fee</cl:category>
<cl:area>nyc</cl:area>
<cl:subarea>mnh</cl:subarea>
<cl:neighborhood>Upper West Side</cl:neighborhood>
<cl:housingInfo price="1450" bedrooms="0" sqft="600" />
<cl:replyEmail privacy="C">bulkuser@bulkposterz.net</cl:replyEmail>
<cl:brokerInfo companyName="Joe Sample and Associates" feeDisclosure="fee disclosure here" />
<title>Spacious Sunny Studio in Upper West Side</title>
<description><![CDATA[posting body here]]></description>
</item>
<item rdf:about="NYCBrokerHousingSample2">
<cl:category>fee</cl:category>
<cl:area>nyc</cl:area>
<cl:subarea>mnh</cl:subarea>
<cl:neighborhood>Chelsea</cl:neighborhood>
<cl:housingInfo price="2175" bedrooms="1" sqft="850" catsOK="1" />
<cl:mapLocation city="New York" state="NY" crossStreet1="23rd Street" crossStreet2="9th Avenue" latitude="40.746492" longitude="-74.001326" />
<cl:replyEmail privacy="C" otherContactInfo="212.555.1212">bulkuser@bulkposterz.net</cl:replyEmail>
<cl:brokerInfo companyName="Joe Sample and Associates" feeDisclosure="fee disclosure here" />
<title>1BR Charmer in Chelsea</title>
<description><![CDATA[posting body goes here]]></description>
<cl:PONumber>Purchase Order 094122</cl:PONumber>
<cl:image position="1">/9j/4AAQSkZJRgABAQEASABIAAD/4QCARXhpZgAATU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUA
AAABAAAASgEbAAUAAAABAAAAUgEoAAMAAAABAAIAAIdpAAQAAAABAAAAWgAAAAAAAABIAAAAAQAA
AEgAAAABAAKgAgAEAAAAAQAAABCgAwAEAAAAAQAAABAAAAAA/9sAQwABAQEBAQEBAQEBAQEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB/9sAQwEBAQEB
AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
AQEB/8AAEQgAEAAQAwERAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//E
ALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJ
ChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeI
iYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq
8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQH
BQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJico
KSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZ
mqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/a
AAwDAQACEQMRAD8A+4/jzpGrf8FNf2Kv27P+ClX7T/x08Z+Dv2ZvBPhL9orw/wDsDfs4eHvHUvgD
4Y3V58NrDxH4Q+H3xN+KMVvPbN8Q/iL48+Klja6VoXhu8nb/AInQn0C2k1TQ9T0nQLL+0eH61Hwt
444A8MOFchwWN4px+M4bxHiFxNiMAswzWMMzqYbG5jlWVOcZrLsty/Kak6uIxUIq1C2Il7LEUq2I
n/QeWVIcF8R8McHZJlmHxGdYnEZPV4pzerhVisbGOMnSxGLweCbUvqmEwuBnKdWtFL93aq+SpCdW
TPgHpOr/APBMz9in9hT/AIKV/swfHTxn4x/Zm8beFP2ePD37fP7OHiHx1L4/+GNrefEey8PeD/iB
8TfhdFcT3LfD34i+A/ilfXWl674bs51zrLQaDcSaXoem6toF6+IatHxS454+8MOKshwOC4pwOM4k
xPh7xNhsAsvzSdPLKmJxuXZXmrgorMstzDKYRq0MTOL/AHPNiIqriKtHEQeaVKfGnEfE/B2dZZh8
PnWGr5vV4WzijhfquNlHByq4jC4PGtcv1vCYrBRU6VaSf7vmqrnqThVj8N/ttfspePP2M9M+NP7L
37Yl/wDHvXP2C/hX8Of2nPHX/BNw/C/wdeap8DtV+PHxWtvGuvfDlP2hPFvhu6TWNE8W/D7xH4lF
lo2k+ILCTTZtXW+1iC50zwFqOuJ4u+84F4ty/jarkfFfBdPh+h4g5tmXC2A8Tf7VxsaWfUeH8ong
cPmT4cwmKi6FfB5jhsM6leth6ntVRcKDjVzCnQ+p/S8N55heIp5bnfD0cqp8U47GZLheMPruIjDM
4ZXgZYeljHlOHrJ06lDF0aLlUqUpe0UHCm1PFQpOg79ib9lPx1+2bpHwU/Zd/Y6vfj5oX7B/xU+H
X7M3jr/gpM3xQ8H3emfAzTfjt8KYPBevfEJf2evFviS6fWda8X/EHxD4baw1zSPD+nx6XFq50/Wp
rrU/Aen6LH4ROOuLcBwTWz3ivjSHD1fxAynMuKMB4YrKsbGrn1XIM3njsPlz4jweFgqFHB5bhsT7
ShWxFV1XR9pQUKWYVKzxhxJnmG4dqZnnfEMcrqcUYHF5zhuD/qWIjPM55ZjpYmlhP7WoUV7OnQwl
KtzUqlWXO6fPTShiZVHi`enter code here`P//Z</cl:image>
</item>
</rdf:RDF>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Needing different approach with validation rule for distinct actions in same Controller I have a controle to handle some information that can be either saved or updated on DB.
I'm using public $validation to store an array with the validation rules that would look like this:
public $validation = array(
array(
'field' => 'modelname[column1]',
'label' => 'Column 1',
'rules' => 'required'
),
array(
'field' => 'modelname[column1]',
'label' => 'Column 2',
'rules' => 'required'
),
);
and I'm using my own validation function with callbacks in this same $validation. Like this:
array(
'field' => 'modelname[column3]',
'label' => 'Column 3',
'rules' => 'callback_column3|required'
),
array(
'field' => 'modelname[column4]',
'label' => 'Column4',
'rules' => 'callback_column4|required'
),
Which is handled with an action in the Controller.
The problem is that:
For add ( save ) I have to check the uniqueness of the value, that's the function of the callback_column4 ( let's say ) and if it's not unique it returns false. But, I can't return false for the edit (update) because I'm reading and editing something that's, obviously, in the DB.
So, what should I do to distinguish the two different action when validating.
PS: I have already tried to use subarrays with the Class/action ( http://codeigniter.com/user_guide/libraries/form_validation.html#savingtoconfig ) name but I'm using a Core_Model abstraction that plays the role of calling
$this->form_validation->set_rules($this->validation);
$this->form_validation->run()
A: You could add validation rules for that input in the controller method that is calling it rather than trying to put everything in the same array. That way you can keep your public validation var for all of the other rules but just set the one that is causing issues for you independently.
You could also create two separate arrays for your validation rules and call each one for its respective method. i.e.
$this->form_validation->set_rules($this->create_validation);
and
$this->form_validation->set_rules($this->edit_validation);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using an asp page to set flags for sql or any way to avoid a sql injection I was wondering if it is possible to have my asp code set flags for my sql database? Although if you have a better suggestion for what to do to avoid a sql injection through the address bar I will take that too.
A: Basic steps to prevent sql injection attacks are:
*
*Parametrize your queries; that is, do things like:
insert into tables (column, colum2, column) values (?,?,?)
And have your code pass parameters to the query.
*Use stored procedures if you can, and fit well your situation (with one caveat - 3rd point below).
*If you use stored procs, don't use dynamic SQL inside them or that will expose you again to sql injection attacks. What I mean by that is to avoid concatenating strings inside the stored proc in order to construct your statements.
*Validate user input (both, client and server side - never trust javascript validation)
I think following those 4 points will make your application immune to sql injection attacks.
I recommend you also read the article posted by jdavies below. It gives some additional useful information.
A: Take a look at the following Microsoft article, which discusses exactly what you require, in depth and for different data access strategies.
How To: Protect From SQL Injection in ASP.NET
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to generate an XOAUTH parameter using OAuth2.0 for use with Gmail IMAP protocol? I have a user authorized to access their gmail through imap using OAuth2.0. I have the OAuth2.0 access token (and refresh token). But I am having trouble figuring out how to map that into an XOAUTH parameter. All the documentation for generating the XOAUTH parameter are written assuming OAuth1.0.
I can follow the sample code make this work with OAuth1.0. But my server is using OAuth2.0 for other things and I want to use the same code.
A: From my Googling, I don't think it's currently possible to construct an XOAUTH param for IMAP using the OAuth2 access token. This is something Google really needs to add ASAP.
See http://groups.google.com/group/oauth2-dev/browse_thread/thread/c1235d5f21e7b438?pli=1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: ExtJS: programatically replacing elements in a ComboBox I just typed up another post and halfway through I figured out my problem. Let's see if it happens again.
I need to be able to update another drop down if a given one is selected. My problem is the secondary drop down isn't loaded the first time; nothing happens on the page. If the user selects the same element a second time, then everything works fine.
I'm programatically generating a bunch of ComboBoxes:
var item = new Ext.form.ComboBox({
store: store,
id: input.id,
name: input.id,
displayField: 'description',
valueField: 'id',
mode: 'local',
forceSelection: true,
triggerAction: 'all',
emptyText: 'Select one...',
typeAhead: false,
editable: true,
allowBlank: allowBlank,
selectOnFocus:true,
fieldLabel: input.label,
listeners: {
scope: this,
'select': checkDependencies
},
autoHeight: true
});
My problem occurs when I try to update the dependent drop down. Here's the function that gets called when the user selects an option:
function checkDependencies(el, ev){
debug(el);
debug(el.value);
var val = el.value;
if (Ext.isArray(dependencies[val])) {
var id = dependencies[val]['changeId'];
var input = Ext.getCmp(id);
var vals = dependencies[val]["vals"];
input.store.removeAll();
gridForm.doLayout();
debug("num elements: " + vals.length);
input.autoHeight = true;
for (var i=0;i<vals.length;i++) {
input.store.add(vals[i]);
}
gridForm.doLayout(false,true);
}
}
It hits all the debug lines. There are elements in the list, but like I said, the first time the user selects an element it doesn't work, but subsequent selections work fine.
I ended up putting doLayouts eveywhere, but it didn't seem to help.
A: Try setting queryMode: 'local' on the secondary box, and in your checkDependencies, doing input.lastQuery = ''.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Abstract Models and Foreign Keys in Django I am working on a django project in which I create a set of three abstract models that I will use for a variety of apps later on. The problem I am running into is that I want to connect those models via ForeignKey but django tells me that it can't assign foreignkeys to an abstract model.
My current solution is to assign foreignkeys when I instanciate the class in my other apps. However, I am writing a Manager for the abstract classes (book and pages) right now and would need to access these foreignkeys. What I am basically trying to do is to get the number of words a book has in a stateless manner, hence without storing it in a field of the page or book.
The model looks similar to this:
class Book(models.Models):
name = models.CharField(...)
author = models.CharField(...)
...
class Meta:
abstract = True
class Page(models.Models):
book = models.ForeignKey(Book)
chapter = models.CharField(...)
...
class Meta:
abstract = True
class Word(models.Models):
page = models.ForeignKey(Page)
line = models.IntegerField(...)
...
class Meta:
abstract = True
Note that this model here is just to give an example of what I am trying to do, hence whether this model (Book-Page-Word) makes sense from an implementation standpoint is not needed.
A: How about this approach? I'm considering using it myself to delay the relationship definition until I inherit.
# This is a very very contrived (but simple) example.
def AbstractBook(AuthorModel):
class AbstractBookClass(Model):
name = CharField(max_length=10)
author = ForeignKey(AuthorModel)
class Meta:
abstract = True
return AbstractBookClass
class AbstractAuthor(Model):
name = CharField(max_length=10)
class Meta:
abstract = True
class BadAuthor(AbstractAuthor):
pass
class BadBook(AbstractBook(BadAuthor)):
pass
class GoodAuthor(AbstractAuthor):
pass
class GoodBook(AbstractBook(GoodAuthor)):
pass
A: Maybe what you need here is a GenericForeignKey, since you don't actually know what model your ForeignKeys will point to? That means that you'll loose some of the "type-safety" guarantees of a normal relation, but it will allow you to specify those relationships in a more general way. See https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#django.contrib.contenttypes.generic.GenericForeignKey
Django model inheritance is a cool thing, and nice as a shortcut for making your models DRYer, but doesn't always play nicely with the polymorphic ideas we generally have of classes.
A: Two things:
1) The way you constructed your schema, you will need a GenericForeignKey, as already mentioned. But you must take into account that Book through Page have a many-to-many relationship with Word, while a GenericForeignKey just realizes a one-to-many. Django has nothing out-of-the-box yet for the normalized schema. What you will have to do (if you care about normalization) is to implement the intermediate (with "through" for concrete Models) yourself.
2) If you care about language processing, using a relational database (with or without Django's ORM) is not a very efficient approach, considering the resulting database size and query time after a few dozen books. Add to that the extra columns you will need to look up for your joins because of the abstract Models, and it will soon become very impractical. I think that it would be more beneficial to look into other approaches, for example storing only the aggregates and/or denormalizing (even looking into non-relational storage systems in this case), based on your queries and views.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Ajax call not being made in jQuery I have this jQuery code that runs on form submit:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var name = $("#problem_name").val();
var problem_blurb = $("#problem_blurb").val();
var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
if(name=='' || problem_blurb == '')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "problems/add_problem.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
And in the directory named /problems/ I have a php file add_problem.php and that file simply has this so I can see in the logs that it is being called:
<?php
echo ".......in problem";
?>
But this never gets written to the logs. Is there something wrong with my ajax call? I know that the js gets to the ajax part fine because I had some alert statements there that I took out.
A: If the file that contains this javascript is not located in the same directory that contains problems/ you should change:
url: "problems/add_problem.php",
to
url: "/problems/add_problem.php",
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Are there any recommended patterns for retrying operations? I'm working on a script which continually monitors a set of files to ensure that they're no more than four hours old. During the time when these files are being copied, they may be seen as missing by the script, so I'm manually retrying once inside of a try...catch... block. E.g.:
try
{
report.age = getFileAgeInMilliSeconds(report.filePath);
// If the file is over age threshhold.
if ( report.age > REPORT_AGE_THRESHOLD )
{
// Generate an alert and push it onto the stack.
downtimeReportAlerts.push(generateOldFileAlert(report));
}
}
// If we have trouble...
catch (e)
{
// Find out what the error was and handle it as well as possible.
switch (e.number)
{
case FILE_NOT_FOUND_ERROR_CODE:
// Try once more.
WScript.Sleep(FILE_STAT_RETRY_INTERVAL);
try
{
report.age = getFileAgeInMilliSeconds(report.filePath);
// If the file is over age threshhold.
if ( report.age > REPORT_AGE_THRESHOLD )
{
// Generate an alert and push it onto the stack.
downtimeReportAlerts.push(generateOldFileAlert(report));
}
}
// If we have trouble this time...
catch (e)
{
switch (e.number)
{
case FILE_NOT_FOUND_ERROR_CODE:
// Add an alert to the stack.
downtimeReportAlerts.push(generateFileUnavailableAlert(report));
break;
default:
// No idea what the error is. Let it bubble up.
throw(e);
break;
}
}
break;
default:
// No idea what the error is. Let it bubble up.
throw(e);
break;
}
}
Are there any established patterns for retrying an operation in this type of scenario? I was thinking of trying to rewrite this into a recursive function, since there's a lot of duplicate code where errors could creep in here, but I wasn't sure how and thought I'd check if there's a better solution first.
A: A recursive method that attempts to perform the push would most likely be the way to go, still utilizing a try..catch to retry the recursive method (perhaps even still with a "sleep" involved and any other specific error handling). I would introduce a RETRY_COUNT constant defining how many times it should be called recursively so it does not get into a continuous loop if no other error is encountered and just increment an "attemptCount" variable to keep track of how many times it has attempted to execute so you can break out of the loop after it reaches the RETRY_COUNT.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Programmatically registering a performance counter in the registry I'm trying to register a performance counter and part of this process includes adding some textual descriptions to a specific registry key. For English this key is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Perflib\009 which apparently is also known as HKEY_PERFORMANCE_TEXT. There are a pair of values under there (Counter, Help) that have REG_MULTI_SZ data, and I need to modify them to accomplish my goal.
The official way of doing this is by using a tool called lodctr along with a .h and .ini file. There is also a function for doing this programmatically, but my understanding is that it is just a simple wrapper around calling the lodctr program. I found the prospect of maintaining, distributing, and keeping synchronized 3 separate files a bit cumbersome, so I previously wrote code to do this and it worked fine under Windows XP (and possibly Vista, though I don't remember for sure).
Now I'm trying to use the same code on Windows 7 and it doesn't work. The problem is that whenever I try to set the registry values it fails with ERROR_BADKEY; even regedit fails to modify the values, so it's not a problem with my code. I ran Process Monitor against it and noticed that there was no activity at the driver level, so it seems this access must be getting blocked in user-mode code (e.g. advapi32.dll or wherever). I understand why Microsoft would try to prevent people from doing this as it is very easy to screw up, and doing so will screw up the entire performance counter collection on the machine.
I'm going to debug lodctr and see what the magic is purely out of curiosity, but I'm wondering if anybody has run into this before? Are there any alternatives other than the lodctr utility? Perhaps calling the NT registry API directly? I would really prefer to avoid the hassle of the lodctr method if possible.
A minimal example to reproduce the issue:
HKEY hKey = NULL;
LONG nResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Perflib\\009"), 0, KEY_ALL_ACCESS, &hKey);
if(ERROR_SUCCESS == nResult)
{
LPCTSTR lpData = _T("bar");
DWORD cbData = (_tcsclen(lpData) + 1) * sizeof(TCHAR);
nResult = RegSetValueEx(hKey, _T("foo"), 0, REG_SZ, (const BYTE*)lpData, cbData);
// here nResult == ERROR_BADKEY
RegCloseKey(hKey);
hKey = NULL;
}
EDIT 1:
I spent about an hour or so trying to debug the official APIs and couldn't figure it out so I tried some more Google. After a while I came across this KB article which explains the RegSetValueEx behavior. Since it mentioned modifying system files that got me to thinking that perhaps this particular registry data is backed by a mapped file. Then I came across another KB article that mentions Perfc009.dat and Perfh009.dat in the system32 folder. Opened these up in a hex editor and sure enough it is the raw REG_MULTI_SZ data I am trying to modify. Now that I know that maybe I can take another look and figure it out, though I am bored with it for now.
A: Never mind, I give up. It's easier to just go with the flow. Instead of trying to modify the registry directly, I will create the .h and .ini files programmatically and invoke the relevant functions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Grouping and processing groups inside plpgsql functions I need to perform a sophisticated group processing, like here. I get some rows from a complex query, the row set looks like this:
key val
-------
foo 1
foo 2
foo 3
bar 10
bar 15
baz 22
baz 44
...
And here is a pseudocode I want to implement in plpgsql:
result = new array()
group = new array()
current_key = null
for (record in (select * from superComplexQuery())) {
if (current_key == null) {
current_key = record.key
}
if (current_key != record.key) {
result.add(processRows(group))
group.clear()
current_user = record.key
}
group.add(record)
}
if (group.size() > 0) {
result.add(processRows(group))
}
return result
I.e., we must process 3 "foo" rows, then 2 "bar" rows, then 2 "baz rows" etc. And result of each processRows is added to resulting collection.
Maybe I should use another approach, but I don't know what it must be.
EDIT: processRows should output a record. Thus, the output of the whole procedure will be a set of rows, where each row is a result of processRows(group). One example of such calculation is given in first sentence of this question: Selecting positive aggregate value and ignoring negative in Postgres SQL , i.e. the calculation involves some iteration and aggregation with some complex rules.
A: The right approach was to use User-Defined Aggregates
I.e. I successfully implemented my own aggregate function and the code looks like
select my_complex_aggregation((input_field_1, input_field_2, input_field_3))
from my_table
group by key
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding a new column at the start of an excel table in an excel I am wondering how one can insert a new column at the beginning of an excel spreadsheet using C sharp.net. I am using Microsoft.Office.Interop.Excel; I want to use OLEO to do this, but I don't see that happening. I have been searching google on how to do this for the last two days now. I can't understand why there are not more tutorials on this?
A: Checkout out the Range.Insert method which you can call on a range of cells to insert entire rows/columns in front of them:
Worksheet sheet = (Worksheet) workBookIn.Sheets[1]; // Worksheet indexes are one based
Range rng = sheet.get_Range("A1", Missing.Value);
rng.EntireColumn.Insert(XlInsertShiftDirection.xlShiftToRight,
XlInsertFormatOrigin.xlFormatFromRightOrBelow);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to select a highest float value from mysql with active record class codeigniter I want to select a highest float number from my database. E.g i have a software in my db with 4 different versions (like app 1.0, app 2.0, app 4.0). I want to select 4.0 using $this->db->order_by("version", "DESC") function. But it's not working. this query returns the last added version. I am using codeigniter framework.
A: If your version is actually a float e.g. 1.0 not app 1.0 then you could do
$this->db->select_max('version')->limit(1);
See the Active Record User Guide
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facebook Open graph Meta tags errors i'm having an issue with the new facebook meta tags the type of object is a song.
i took the example from here.
here
<meta property="og:type" content="Song" />
<meta property="og:title" content="artist name - track name" />
<meta property="og:description" content="content" />
<meta property="og:image" content="artist image full url" />
<meta property="testappwebsite:song:url" content="the full track uri PAGE." />
<meta property="testappwebsite:song:type" content="audio/mp3" />
<meta property="fb:app_id" content="my app id" />
this is the errors i'm getting.
the wierd thing is that when i take the url and put it in my status. i'm getting the correct image, but i'm not getting the title that i added to the meta tag, instead i'm getting the document title.
is there any built in objects for song audio ?? because i cannot find it.
A:
Song is uppercase in your example - not sure if that has any bearing. See here:
http://ogp.me/ under Audio...
<html xmlns:og="http://ogp.me/ns#">
<head>
...
[REQUIRED TAGS]
<meta property="og:audio" content="http://example.com/amazing.mp3" />
<meta property="og:audio:title" content="Amazing Song" />
<meta property="og:audio:artist" content="Amazing Band" />
<meta property="og:audio:album" content="Amazing Album" />
<meta property="og:audio:type" content="application/mp3" />
...
</head>
A: Did you put the <meta> tags into your <head>? Only the <head> is actually parsed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Starteam to SVN migration, alternatives to Polarion? Does anyone know of an alternative to Polarion to migrate Starteam (2006v2) to SVN? Our source alone is 10GB, not including all the revision history. Whenever I run Polarion svnimporter, i get a "Java out of memory" exception. I'm not sure what is causing all the memory use, but I'm not really sure where to go from here. Any suggestions (that allow me to at least keep some history) would be much appreciated.
Thanks!
A: I am in the process of migrating a medium sized project form StarTeam to Subversion. I too had to deal with many JVM crashes due to the VM running out of memory. Seems that either the Polarion library/tool or the StarTeam.jar file they utilize from StarTeam has a massive memory leak. In any case, I seem to have gotten past it (fingers crossed) by doing the following:
java -Xmx2048m -cp svnimporter.jar:starteam80.jar org.polarion.svnimporter.main.Main full config.properties
Now it has been running for about 3 days on roughly 11 thousand files.. and is only half complete.. so this is a SLOW process to say the least.
I have found no other tools out there.... so good luck.
A: About a decade ago, we did a StarTeam to ClearCase migration. I was hired to write a program to do the migration. Unfortunately, StarTeam has an extremely limited command line interface and no real API. Almost all of the StarTeam commands had to be pre-fixed by a 50 character login string. Maybe that's changed in the last decade.
Have you tried increasing the memory allocation for Java? By default, the JVM will only use 64Mb of memory. Many Java applications need way more. At the Java command, you can give it something like -Xmx256m to give it 256 megabytes of memory. I see that Polarion's software is Java based, but I didn't end up downloading it because they wanted my name and email. (It just isn't worth the hassle.) However, I take it there's a batch script or shell script that executes the program.
Is it possible to only do a directory/module or two at a time? Many sites use multiple Subversion repositories -- one for each module -- instead of one grand repository for all modules together. Besides, you can always dump and load all the Subversion repositories into one big repository if that's what you really want. A bit more elbow grease, but if it works, you get to keep your entire history.
What we ended up doing is just converting over a few tagged points for the history and not everything. Our theory is that if you really needed the detail history, you could go back to the StarTeam repository.
What happened changed my view of these things: The truth is that we couldn't build much of the old stuff anyway since it depended upon the way it was in StarTeam, so even if we kept the history, it didn't do us too much good. And, it also gave us the opportunity to restructure everything and dump the obsolete stuff -- something we probably wouldn't have done if we could actually keep the history.
And, in the end, no one missed the history anyway. The StarTeam repository used SQLServer for maintaining the repository database. That database crashed not long after the conversion. We didn't find out about it until almost a year later. I was simply trying to see if StarTeam was still working, and discovered the issue.
So, see if upping the memory of the Java process helps, or see if you can do the conversion piecemeal. If that doesn't help, you might want to ask yourself if the history really needs to come over, or if it's okay if you just do a few tagged points and the tips of active branches.
If someone really needs the history, the can go back to the old StarTeam system.
I wish I could give you more help, but I didn't have much more luck with StarTeam myself.
Reply
Is the StarTeam CLI that bad? It should be possible to write a simple script to list revisions and then check them out from starteam and into SVN in a big loop or something, shouldn't it?
You'd think so. After all, I've managed to write my own conversion routines for ClearCase, CVS, Subversion, to whatever. However when I did this a decade ago, the StarTeam CLI is awful, the documentation is awful, and Borland (which owns StarTeam) was no help at all.
There's no login for the command line tool. Each command must provide credentials which means putting in a 50 or so character string in each command. It also means that the CLI has no clue about what you're actually looking at. You can't do a svn info like command. You just have a bunch of stuff checked out.
There's no way to go through a detailed history via the command line. For example, there's no way to find out all the revisions, and check them out one at a time like you could with Subversion or even CVS.
There was a C API, but it was also fairly limited. I see there's now a Java API which is probably what Polarion is using.
I was thinking maybe there's a StarTeam to CVS package which might help things a bit. After you convert to CVS, you could take that and convert it to Subversion. Alas, except for a few souls out in the bleakness of the Internet world asking the same question, I could find nothing on the subject.
I tried downloading the API information or the command line documentation to see if I can figure anything out, but the website is down.
Sorry I can't help you beyond saying I tried and failed.
A: I do not know starteam, but usually you can export a list of labels/tags (or maybe all tags?) From your Source Versioning system. And then use svn_load_dirs.pl To "stack" them over each other.
This means you will not have the whole history, but at least most of your frozen project states.
You may or may not also export some time stamped versions and try to stack them as well.
I recently migrated some simple clearcase VOBs by just examining the checkin / commit history and exported for each checkin a full version of the project and used svn_load_dirs.pl to import them into a new svn repository.
A: https://netcodeman.blogspot.com/2011/01/converting-from-starteam-to-subversion.html?showComment=1506429228614#c7145074297097582572
https://stackoverflow.com/users/618865/quinn-bailey <= This guy has done conversions before and written some fixes. May be of help.
https://www.openmakesoftware.com/svn-importer-converting-from-borland-starteam/
has some interesting comments along these lines. I also know that the SVN Importer has issues importing revisions with more than one label. I've heard there was a version of SVN Importer that could get around this, but can't seem to find it yet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: android, andengine, pureMVC framework integration I want to use pureMVC framework for my android application.
I also want to use Android andengine in this application.
How can I integrate them? Is there any way to do that? If yes, can you send me link on some tutorials or sample, or template?
A: Is it compulsory to use PureMVC?
Yesterday I've answered similar question about MVC architecture on Android.
Don't reinvent the wheel, Android SDK offers excellent MVC/MVP/MVVM architecture for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Ruby Metaprogramming: creating a method by a method I just wondered about some metaprogramming.
Actually I need to create a method within a method, or just create a method in the root of a class by a block. example:
["method_a", "method_b"].each do |m|
Marshal.generate_a_method_called(m)
end
Does somebody know how this is possible? And where to place what the method does? I need one argument for my method.
Yours,
Joern.
A: You could use define_method:
[:method_a, :method_b].each do |m|
define_method(m) do
# your method stuff
end
end
A: I don't understand your example. Are you generating the source for the method as well?
So I will start with an example from the book Perrotta: Metaprogramming Ruby
class MyClass
define_method :my_method do |my_arg|
my_arg * 3
end
end
obj = MyClass.new
obj.my_method(2) # => 6
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Function with derived type parameter in a dictionary with the Type as the Key I want to be able to store a function in a dictionary with the Key being the object type. All functions will accept objects derived from the same base class. I want to be able to convert (based on a registered function) a class into a DbCommand. I've listed my code below in the form that seems correct but something is wrong with the syntax, etc. I think I'm missing something really simple... Any help will be greatly appreciated!
private Dictionary<object, Func<TrackingRecord, DbCommand>> conversionFunctions = new Dictionary<object, Func<TrackingRecord, DbCommand>>();
public void RegisterConversionFunction<T>(Func<T, DbCommand> conversionFunction) where T : TrackingRecord
{
conversionFunctions.Add(typeof(T), conversionFunction);
}
public DbCommand GetConverstion<T>(T trackingRecord) where T : TrackingRecord
{
DbCommand command = null;
if (conversionFunctions.ContainsKey(trackingRecord.GetType()))
{
Func<T, DbCommand> conversionFunction;
if (conversionFunctions.TryGetValue(trackingRecord.GetType(), out conversionFunction))
{
command = conversionFunction.Invoke(trackingRecord);
}
}
else
{
command = DefaultConversion(trackingRecord);
}
return command;
}
A: The problem with your original solution is that the method signature Func<T, DbCommand> doesn't match the expected value Func<TrackingRecord, DbCommand>. To fix this, because you know that T is constrained to inherit from TrackingRecord, you can create a wrapping function that matches the expected signature (Func<TrackingRecord, DbCommand>) and cast the argument to T.
Try this:
private Dictionary<object, Func<TrackingRecord, DbCommand>> conversionFunctions = new Dictionary<object, Func<TrackingRecord, DbCommand>>();
public void RegisterConversionFunction<T>(Func<T, DbCommand> conversionFunction) where T : TrackingRecord
{
conversionFunctions.Add(typeof(T), tr => conversionFunction((T)tr));
}
public DbCommand GetConverstion<T>(T trackingRecord) where T : TrackingRecord
{
DbCommand command = null;
Func<TrackingRecord, DbCommand> conversionFunction;
if (conversionFunctions.TryGetValue(typeof(T), out conversionFunction))
command = conversionFunction.Invoke(trackingRecord);
else
command = DefaultConversion(trackingRecord);
return command;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: two submissions for a form I have PHP code which creates a list with radio buttons for each list item.
$result = mysql_query("SELECT * FROM attitudes WHERE x_axis = '$famID'",$db);
$rowcheck = mysql_num_rows($result);
while ($row_user = mysql_fetch_assoc($result))
foreach ($row_user as $col=>$val) {
if ($col != $famID && $col != 'x_axis') {
list($famname) = mysql_fetch_row(mysql_query("SELECT familyname FROM families WHERE families_ID='$col'",$db));
echo "col $col famname $famname is val $val.";
echo "<input type = \"radio\" name = \"whichfam\" value = \"$col\" />";
echo "</br>";
}
}
Then I have a submit button at the bottom (and form tags for the whole thing)
I want to have two possible submissions. This code is intended to let the player raise or lower a value. They click on one of the radio buttons, and then select "Raise", or "Lower". It should then post to a backend and execute code to either raise or lower that value. I know how to do this in jquery, but I don't know how to have two SUBMIT buttons in PHP.
How can I do this?
(Specifically, how do I make two submission buttons work, the backend code should be relatively simple, $_POST or whatever)
A: Is this what you're looking for?
<button type="submit" name="submit1" value="submit1">submit1</button>
<button type="submit" name="submit2" value="submit2">submit2</button>
then
if(isset($_POST["submit1"])) {
} else if(isset($_POST["submit2"])) {
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: System.FormatException: Input string was not in a correct format private void ReadUnitPrice()
{
Console.Write("Enter the unit gross price: ");
unitPrice = double.Parse(Console.ReadLine());
}
This should work, but I'm missing something obvious. Whenever I input a double it gives me the error: System.FormatException: Input string was not in a correct format.
Note that 'unitPrice' is declared as a double.
A: It could be that you're using wrong comma separation symbol or even made an other error whilst specifying double value.
Anyway in such cases you must use Double.TryParse() method which is safe in terms of exception and allows specify format provider, basically culture to be used.
public static bool TryParse(
string s,
NumberStyles style,
IFormatProvider provider,
out double result
)
The TryParse method is like the Parse(String, NumberStyles,
IFormatProvider) method, except this method does not throw an
exception if the conversion fails. If the conversion succeeds, the
return value is true and the result parameter is set to the outcome of
the conversion. If the conversion fails, the return value is false and
the result parameter is set to zero.
EDIT: Answer to comment
if(!double.TryParse(Console.ReadLine(), out unitPrice))
{
// parse error
}else
{
// all is ok, unitPrice contains valid double value
}
Also you can try:
double.TryParse(Console.ReadLine(),
NumberStyle.Float,
CultureInfo.CurrentCulture,
out unitPrice))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Can a web app in UIWebView gain access to native storage If I have a web app running in a UIWebView can the javascript context in the web app get any sort of access to data in the native ipad app context? I'd like to store lots of images in the native app database, then access these from a web app running in a UIWebView within the native app.
A: Not directly, but if you can get some kind of "bridge" working with Javascript, you can use native code to pass back paths to files and such. Look into the the stringByEvaluatingJavaScriptFromString:@"SomeJSCommandHere". Check out this webpage for more information on that. It looks like they discuss it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When is it a good or bad idea to build a website with a CMS I'm about to begin a large scale web app project. The premise of this project is it will be a destination website that aggregates content (content is to be collected with a crawler/bot that runs independently and at set intervals to index data provided from partners that have approved our technique) and displays this content to users. Users can tailor what content the platform presents them with by ranking content, in an attempt to give the platform data to determine what content the user is likely to find favorable. (Yes, I know this sounds just like stumbleupon.com)
The creator of this idea is non-technical, and he has previous experience developing websites using wordpress. Because of this, his first instinct was to call for a CMS in creating this project. My instinct as a developer that has extensive web development experience building web apps with PHP/Codeigniter, is that a CMS was never intended to be used to create such a purpose-specific tailor-made app like this -- and attempting to use one would create a lot of unnecessary overhead/clutter in the project.
I'm thinking it might be better to build a back-end interface to view/add/edit/remove content that the spider collects, since I imagine this is the only type of access/control that non-technical partners will need in this project. (possible also ban users, remove inappropriate comments on content, etc)
But what do you guys think, is there some sort of value that a CMS could provide to a project like this? Are there situations where it's a generally accepted rule that a CMS is good/bad? I'm coming from years of PHP app building using frameworks like codeigniter, and recently I've had to do work on a wordpress site -- which to me seemed like a disgusting mess of global variables, endless 'hooks' to get code to execute when/where you need it to, etc.
---- EDIT ----
I should add that an intended feature to add to all of this is users will be able to add their own content to our collection of aggregated content. Just another feature that makes me think this app is too 'unique' to be properly developed on top of a CMS.
---- EDIT ----
Another thing to add is scalability is a big concern. We want to build this to be able to handle anywhere from 200,000 - 2,000,000 - 20,000,000 unique visitors per month. That means using everything at our disposal, load balancing, memcached-caching, worker processes/servers, high-availability mysql and mongodb databases (for different purposes in our web app), content-delivery-networks, hosting asset files independently of application server, etc. I'm uneasy about giving up direct control over all of the code because in the past I've used my ability to touch everything to fine-tune any performance issues/bottlenecks.
A: Well, most CMS out there are not only CMSs but also comprehensive PHP frameworks providing basic functionality. Having said that CMS are suitable more for websites that are content base like websites having a lot of articles. It is much easier to update and manage such sites by the users who aren't technical users. But when it comes to webApps they require much more interactions, e.g. a in a CRM application the inserts, reads, updates happen very frequently.
Others points that should be kept in mind are
1) would it be scale able if I use CMS for my app, If you think your app will grow in future, and you start building it from scratch, by the time your own piece of code would be transformed in a Framework for your app. Things will be much easy to update, adding some new functionality etc.
2) Flexibility, if you go with CMS you will have to constrained yourself in the CMS environment, What if you need a certain functionality in your website but you find nothing tailor made for that. In that case you will have to develop it your self which could take a long time than it would take otherwise.
3) Performance, CMS should be used for the purpose they are built for, a CMS will load everything it needs to function properly whereas much of these stuff you won't need for your app at all.
I would say to go with some Framework that is built to help the development process, like CakePHP, CodeIgniter, Yii etc.
A: This becomes really simple when you boil it down:
Do non-technical users need to have the ability to manage the content on the web site?
For pretty much any modern-day web site, the answer is "yes". The web is now mainstream and Facebook, Twitter, Wordpress, etc. have demonstrated that you don't need to be a programmer to create/maintain web content.
Your original question says as much. So, yes, you need a CMS (a system that makes content management possible by end-users).
So your real question is "Should I build my own CMS, or use an existing CMS?". Those custom interfaces you describe above, that's content management. You're describing building a basic CMS.
--
To that question, I'll say: Making "content management" accessible to end-users is a lot harder than most programmers seem to anticipate. Even implementing a Rich Text (WYSIWYG) editor that isn't completely fragile & buggy is a monumental task.
And that's just the tip of the iceberg: permissions, versioning, workflow, taxonomy, analytics, personalization, feeds, comments, moderation, error logging, etc., etc.
These may or may not be features you need at launch, but as the web site matures these opportunities often need addressed.
--
I work for a company that makes a CMS, so I'm biased but I consider the decision to create a CMS crazy. It's complicated from a technical perspective and even more complicated from a usability perspective. As a one-man-band (or even a ten-man-band) you don't have time to create all the features that are readily available with existing CMS packages. This means it's harder to evolve the web site to accommodate new ideas or modern practices. You'll be perpetually behind and playing catch up.
My advice, find a CMS platform that aligns with your client's needs, become involved with their community and build on this foundation. It might be harder in the short-term (comprising your PROGRAMMING ideals to accommodate a platform), but it better serves your client to not be dependent on some home-baked CMS that another developer will someday inherit (and hate).
A:
I'm thinking it might be better to build a back-end interface to
view/add/edit/remove content that the spider collects, since I imagine
this is the only type of access/control that non-technical partners
will need in this project. (possible also ban users, remove
inappropriate comments on content, etc)
Yes it would be a good idea, it will give you more control. Your non technical partner will only need these functions i guess. Or you can ask your partner that what kind/type of control he needs. I mean what specific use cases he will follow
But what do you guys think, is there some sort of value that a CMS
could provide to a project like this? Are there situations where it's
a generally accepted rule that a CMS is good/bad? I'm coming from
years of PHP app building using frameworks like codeigniter, and
recently I've had to do work on a wordpress site -- which to me seemed
like a disgusting mess of global variables, endless 'hooks' to get
code to execute when/where you need it to, etc.
I guess CMS can help you out also in this matter. What i recommend is DRUPAL in that case. DRUPAL is powerful enough to control this also you can create a custom list of actions (like add,edit or delete) in DRUPAL which your non-technical partner can easily access. DRUPAL has a lot of plugins (modules) , i'm sure you will find something like that or you can combine few plugins to get your job done. Using an existing CMS will give you confirmation that it is stable
A: The consideration is always "What are the business needs and how can software support that?" You have to consider what the core needs are, then assess what the best approach may be, be it using a CMS, rolling your own system, or adapting an existing product to fit the business needs.
Access control does not justify using a CMS - a CMS is great for user generated and maintained content, something that (from your description) you're not really doing. It sounds to me like you have User-specific preferences, which is a part of a CMS, but not really a major service of them.
WordPress isn't a good example of a CMS, at least at its core - it has some of the core functionality of a CMS (users, publishing, etc) but again, you're collecting content into a central location and then customizing the display of that data. It doesn't really fall into the area of a CMS in my opinion.
Edit: Ok, so your users are adding to/creating content, you should then consider a CMS. Your challenge would be to add the aggregated content to your CMS seamlessly. It isn't impossible, and as mentioned, one of the established CMS platforms would be a good starting point.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: What happens to existing gems when I install RVM? I currently have Ubuntu 10.04 Ruby 1.8 and Rails 2.3.8 with Apache2 and Phusion running on a machine where I've been developing this app. During development I have installed many other gems as required for the app. However I never had RVM installed from start.
Yesterday I tried to update rubygems from 1.3.5 to current version (because a gem wanted it) and because of ubuntu's specifics have completely mucked up my rubygems install. The app runs but I can't get script/console to work. The guys at rubygems.org suggested installing a new version of ruby using RVM to get round the problem.
My questions are :
*
*What happens to all the gems already installed on the system?
*How does the new version affect/interact with my app?
*Should I be uninstalling anything before installing RVM and a new ruby?
*Why does this happen towards the END of a project?
A: The gems installed on your system will still be installed on your system, but they won't be usable from your RVM ruby. One of the main advantages of RVM is that you avoid nasty interactions with your system ruby. It's not recommended, but you can optionally link or clone your system gems to an RVM environment if you really feel the need with
rvm gemdup system
A: they stay around in the system location , but won't be used by RVM.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Are Java random UUID's predictable? I would like to use a cryptographically secure primary key for sensitive data in a database - this cannot be guessable/predictable and it cannot be generated by the database (I need the key before the object is persisted).
I understand Java uses a type 4 UUID with a cryptographically secure random number generator, however I know the UUID isn't completely random so my question is how safe is it to assume that uuids cannot be predicted from a set of existing ones?
A: Well if you want to know how random a UUID is you have to look onto the source.
The following code section is taken from OpenJDK7 (and it is identical in OpenJDK6):
public static UUID randomUUID() {
SecureRandom ng = numberGenerator;
if (ng == null) {
numberGenerator = ng = new SecureRandom();
}
byte[] randomBytes = new byte[16];
ng.nextBytes(randomBytes);
randomBytes[6] &= 0x0f; /* clear version (set highest 4 bits to zero) */
randomBytes[6] |= 0x40; /* set to version 4 */
randomBytes[8] &= 0x3f; /* clear variant (set highest 2 bits to zero) */
randomBytes[8] |= 0x80; /* set to IETF variant */
return new UUID(randomBytes);
}
As you can see only 2 of 16 bytes are not completely random. In the sixth byte you lose 4 of 8 bits and on byte 8 you loose 2 bits of randomness.
Therefore you will get an 128 bit value with 122 bit randomness.
The only problem that may arise from the manipulation is that with a high chance your data can be identified as an UUID. Therefore if you want to hide it in other random data this will not work...
A: If you want to generate a secure random key, I suggest you use SecureRandom. This can generate a key of any number of bits you require. Its slower than Random, but much more secure.
A: I have always thought that the 'cryptographically secure random number generator', (actually 'cryptographically strong pseudo random number generator') Javadoc note answers this.
http://download.oracle.com/javase/1,5.0/docs/api/java/util/UUID.html#randomUUID()
From What Wikipedia says
http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator
such prediction would be a non-polynomial algorithm.
If you need something 'truely' not just 'pseudo' random, you need to use something external, a hardware noise generator, random points generated after moving a mouse,...
EntropyPool seems to be helping with that, have not tried it yet
http://random.hd.org/
The way I understand it, it let's you download some real world noise and use it in your Java app. It is not connected to java.util.UUID api, however, could probably be plugged in using the nameUUIDFromBytes (or other?) method.
Would be cool if you let us know which way you decided to go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: unable to pass array from jquery to php I need to pass an array to from jquery to php for processing.
i create an array object like this
function Bet(eventId,pick,odds,stake,profit,betType){
return {
eventId:eventId,
pick:pick,
odds:odds,
stake:stake,
profit:profit,
betType:betType
}
in my submit handler i have this piece of code
var bets = {};
$(".bet-selection").each(function() {
/**
some logic here
**/
}
});
bets.push(Bet(eventId,pick,odds,stake,profit,betType));
});
$.ajax({
url: 'testsubmit.php',
cache: false,
type: 'post',
data: bets
});
Nothing happens when i submit the form. I was hoping the an array will be submitted to php and i can use print_r to view the structure. Please guys what am i doing wrong and where?
Thank you.
A: AJAX is going to send the data to an external file, and you will not be able to see the output. That is why there is nothing visible happening when you submit the form. Maybe if you had the PHP script email you the data then you can check if it is passing it properly.
A: Fist of all, your code is syntactically and semantically incorrect. I marked the incorrect places with "<----"
function Bet(eventId,pick,odds,stake,profit,betType){
return ({
eventId:eventId,
pick:pick,
odds:odds,
stake:stake,
profit:profit,
betType:betType
});
} <------
var bets = {};
$(".bet-selection").each(function() {
/**
some logic here
**/
}
bets.push(Bet(eventId,pick,odds,stake,profit,betType)); <--- I guess this should be inside the loop, right?
});
Now you cannot just post Javascript objects like this. The best option is encoding them as JSON (JavaScript Object Notation), which actually encodes them ... as JS objects :)
Modern browsers include JSON parser/encoder, but older don't. So include the following library to make sure older browsers won't break: https://github.com/douglascrockford/JSON-js
Next, you'll need to modify a bit of your code:
$.ajax({
url: 'testsubmit.php',
cache: false,
type: 'post',
data: { bets : JSON.stringify(bets)}
});
On PHP side, use json_decode function to decode JSON string to a PHP array of objects.
<?php
$bets = json_decode($_POST['bets']);
var_dump($bets);
Nice day.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using a struct pointer as a @property I want to use a struct pointer as a @property but I'm not sure how should I free it.
This is what I have now:
.h:
@property (nonatomic, assign) InfoStruct * info;
.m:
@synthesize info;
- (id)init {
self = [super init];
if (self) {
self.info = (struct InfoStruct *) malloc(sizeof(struct InfoStruct));
}
return self;
}
-(void)dealloc {
free(info);
[super dealloc];
}
Could the code above cause any trouble? Is it correct? Seems to work fine, but I think I need a reassurance.
A: This should work just fine. @property's marked assign can handle regular C datatypes, whether they're numeric primitives or pointers. The fact that you're pointing at a struct doesn't change that.
Just be careful with your memory, because it looks like your property is read-write and anyone assigning to your property may not realize that your object "owns" it (e.g. calls free() in -dealloc, and requires free()-ing the old value of the property if you assign a new value to it). Unless you have a reason to want this property to be read-write, you may want to mark it readonly.
A: It depends on how you use instances of that class. For example:
SomeClass *obj = [SomeClass new];
// never assign an address to obj.info
[obj release];
will be okay.
However, since you’ve declared that property to be read-write, you need to take into account the ownership of the object pointed by that structure.
For example, in:
SomeClass *obj = [SomeClass new];
obj.info = someInfo;
[obj release];
the object you’ve allocated in -init doesn’t get freed (you’re leaking it), and the object pointed to by someInfo gets freed. You could change the property setter to something like:
- (void)setInfo:(InfoStruct *)newInfo {
if (newInfo != info) {
free(info); // free previous object
info = newInfo;
}
}
in which case an assignment will always free the previous object unless the value being assigned is the same as the previous value. This means that your class effectively owns the object whose address is being assigned to the property.
If you decide that the class shouldn’t be responsible for freeing objects other than the one created in -init, things get a tad more complicated. If info is assigned some address other than the address of the original info created in -init, the client code needs to free obj.info before assigning it a new value. For example:
SomeClass *obj = [SomeClass new];
free(obj.info);
obj.info = someInfo;
[obj release];
That’s problematic because you have code outside of the class deallocating memory used by an object of that class, which is quite intrusive. And, if the class isn’t responsible for freeing objects other than the one created in -init, you need to keep additional state indicating that so that -dealloc only frees info if info wasn’t changed after the object was initialised.
Also, as Jim noted, the correct method name is dealloc.
A: That method should be called dealloc, not destroy.
A: We know nothing about your InfoStruct. If it contains only primitive types, then calling free(info) is enough.
However, if it has pointers to other types you allocate memory for using malloc, then free(info) will not release these objects and you'll have a memory leak.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Insert Div before group of Divs in a parent Div jQuery I am trying to add a div as the first div in a group of child divs in a parent.
$('#activitytable:first-child').before('<div></div>');
The parent div's ID is activitytable. I have been trying to figure this out for a few hours and have tried multiple methods with no avail. I am trying to add the new div to the top of the others in activitytable.
Any help is greatly appreciated!!
- Chris
A: As you see here, your solution does not work overly well: http://jsfiddle.net/Yfhqr/2/
$('#activitytable').prepend('<div></div>');
does though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VB.net gridview showing more data than I want it to My gridview is showing more than one ProductName column and the ProductID column as well. All I want it to show is the Product Name clickable column. Can someone help me figure out what code to exclude?
<asp:Content ID="Content2" ContentPlaceHolderID="body" Runat="Server">
<br /><br /><br />
<asp:linkbutton id="btnAll" runat="server" text="ALL" onclick="btnAll_Click" />
<asp:repeater id="rptLetters" runat="server" datasourceid="dsLetters">
<headertemplate> | </headertemplate>
<itemtemplate>
<asp:linkbutton id="btnLetter" runat="server"
onclick="btnLetter_Click" text='<%#Eval("Letter")%>' />
</itemtemplate>
<separatortemplate> | </separatortemplate>
</asp:repeater>
<asp:sqldatasource id="dsLetters" runat="server" connectionstring="<%$ ConnectionStrings:ProductsConnectionString %>"
selectcommand="SELECT DISTINCT LEFT(ProductName, 1) AS [Letter] FROM [Product]">
</asp:sqldatasource>
<asp:gridview id="gvProducts" runat="server" datakeynames="ProductID"
datasourceid="dsProductLookup" style="margin-top: 12px;">
<Columns>
<asp:HyperLinkField DataNavigateUrlFields="ProductID"
DataNavigateUrlFormatString="Product/Default.aspx?ID={0}"
DataTextField="ProductName" HeaderText="Product Name"
SortExpression="ProductName" />
</Columns>
</asp:gridview>
<asp:sqldatasource id="dsProductLookup" runat="server"
connectionstring="<%$ ConnectionStrings:ProductsConnectionString %>"
selectcommand="SELECT ProductID, ProductName FROM [Product] ORDER BY [ProductName]">
</asp:sqldatasource>
</asp:Content>
CodeBehind:
Protected Sub btnAll_Click(sender As Object, e As EventArgs)
gvProducts.DataBind()
End Sub
Protected Sub btnLetter_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim btnLetter As LinkButton = TryCast(sender, LinkButton)
If btnLetter Is Nothing Then
Return
End If
dsProductLookup.SelectCommand = [String].Format("SELECT ProductID, ProductName
FROM [Product] WHERE ([ProductName] LIKE '{0}%') ORDER BY [ProductName]",
btnLetter.Text)
End Sub
A: Add the attribute AutoGenerateColumns="False". Otherwise the GridView looks at your data source and automatically adds columns to itself based on the properties of your data source objects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to switch on from one panel to another by hiding the first panel on netbeans IDE How do I switch from one panel to another by hiding the first panel in Netbeans IDE (ie: panel1.setVisible(false) and panel2.setVisible(true) as we click on a button belonging to first panel)? Please help me as Netbeans is strange to me.
A: Sounds like you want to use CardLayout to manage all the panels that you want to switch between, assuming that your panels will occupy the same space on the screen.
You'll need to create a component that uses the CardLayout layout manager and then add all the panels that you want to switch between to it. Then your various buttons that will switch panels can reference the layout manager and switch the panels accordingly - the CardLayout will manage calling the appropriate setVisible methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bugs in canvas pixel manipulation in Opera I'm learning HTML5 and when doing some basic things like canvas pixel manipulation, found out that Opera messes up the image completely when I want to change a color channel.
I've cooked up a small test page that should speak for itself: http://gda.0fees.net/tests/opera/canvas2.html (NB: the "expected result" images are dynamically loaded and the server is kind of slow).
The script takes the image and changes the red value for every pixel in a uniform manner. Here's the central point of my code (which you can see in full via the link above):
for (var i = 0, l = matrix.data.length; i < l; i += 4)
{
matrix.data[i] += delta;
if (matrix.data[i] > 255) matrix.data[i] = 255;
if (matrix.data[i] < 0 ) matrix.data[i] = 0;
}
In Chrome, Firefox, IE 9, and Safari it works like a charm. In Opera, however, I get this result for both transformations: http://gda.0fees.net/tests/opera/opera.jpg
Am I doing something wrong? Is this a known bug? Can it be suppressed?
A: If I had to guess I'd say the red channel value was wrapping round to some invalid value. Note (in the source image) that the bugged areas are all much brighter overall than the areas that are properly treated.
It might be that its doing some sort of limit check, zeroing the red value of pixels where the original red value + 128 would exceed the maximum value used to represent colour components (a uint 8 maybe?).
I've never used HTML5's canvas before, but if you can sample the colour of each pixel, you might be able to suppress it by guessing the maximum value and checking to make sure you don't exceed it when augmenting that particular pixel's colour component.
Try this:
// Apologies, my JavaScript is very rusty, and this isn't how I would do this.
for (var i = 0, l = matrix.data.length; i < l; i += 4)
{
var current_red = matrix.data[i];
var new_red = 0;
if((current_red + delta) > 255) new_red = 255;
else if((current_red - delta) < 0) new_red = 0;
else new_red = current_red + delta;
}
// What I would do is this:
for (var i = 0, l = matrix.data.length; i< l; i+=4)
{
// I don't know if JS has a clamp function :D
matrix.data[i] = clamp(matrix.data[i] + delta, 0, 255);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: merged html files - not removing head/body of each file can slow loading? I merged many html files (e-pub chapters) into one big html file. I did not remove anything. Loading is slow but, after loading, browser handle the huge web-page very well. I ask if it is possible that loading is slow because of not cutting head/body tags where not right.
A: An HTML document can only have a single <html> element, containing a single <head> and a single <body> element respectively.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dividing LBP into 6x6 matrixes Previously, i wrote a code for Local Binary Pattern(LBP) and Obtained a LBP image and histogram. Now i would like to divide the image into 6x6 matrixes and obtain the LBP image and histogram for each 6x6 matrix. I written the code below. But it doesnt work that well.
I2=imread('CropF.jpg');
m=size(I2,1);
n=size(I2,2);
counter = 1;
for i=2:6:m-1
for j=2:6:n-1
for k=i:i+6
for l=j:j+6
J0=I2(k,l);
I3(k-1,l-1)=I2(k-1,l-1)>J0;
I3(k-1,l)=I2(k-1,l)>J0;
I3(k-1,l+1)=I2(k-1,l+1)>J0;
I3(k,l+1)=I2(k,l+1)>J0;
I3(k+1,l+1)=I2(k+1,l+1)>J0;
I3(k+1,l)=I2(k+1,l)>J0;
I3(k+1,l-1)=I2(k+1,l-1)>J0;
I3(k,l-1)=I2(k,l-1)>J0;
LBP(k,l)=I3(k-1,l-1)*2^7+I3(k-1,l)*2^6+I3(k-1,l+1)*2^5+I3(k,l+1)*2^4+I3(k+1,l+1)*2^3+I3(k+1,l)*2^2+I3(k+1,l-1)*2^1+I3(k,l-1)*2^0;
end
end
LBP=uint8(LBP);
LBPv=reshape(LBP,1,size(LBP,1)*size(LBP,2));
Hist=hist(LBPv,0:255);
Hist1(counter,:)= Hist;
fname = sprintf('HistInf%03d.mat', counter);
save(fullfile(BASE_DIR,fname), 'Hist');
counter = counter + 1;
end
end
save('C:\Users\Lakshmen\Documents\MATLAB\HistInfMain','Hist1');
I have an error like this : ??? Index exceeds matrix dimensions.
Morever, the value for m and n I get is 394 and 330. Hence the value i should get for counter is 55 which is what i get but I get the error said above.
A: I guess you are still working on the problem from your previous questions.
I am assuming that m and n denote the size of the I2 matrix. If that is the case, then the issue here is with the two inner loops for the k and l variables. They go from the current values of i and j and go up to i+6 and j+6. But i and j themselves can reach m-1 and n-1 respectively thus you get "out of bound" errors.
If I am correct, you need to change the upper bounds of the i,j for-loops:
counter = 1;
Hist1 = []; %# you can probably pre-allocate a fixed size here
for i=2:6:m-1-6
for j=2:6:n-1-6
for k=i:i+6
for l=j:j+6
%#...
end
end
%# ...
end
end
%# ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Using MATLAB to process files in real-time after every instance a file is created by a separate program I am using MATLAB to process image files that are created by a camera and stored in a directory on Windows. I am trying to incorporate feedback into control of the camera and therefore require MATLAB to process an image every time a new image is created and appears in the directory. I have never created a MATLAB program that runs continuously and waits for an event to occur.
From what I've read online it appears my best option is to use a timer object and have the MATLAB program read the contents of the directory repeatedly. Is this a good approach or are there alternative approaches I can implement?
I'm wondering if there is a way the MATLAB program can be "triggered" by the appearance of a file in a directory as opposed to constantly surveying the contents of this directory. I hope there is because as the directory fills up I find that the "dir" command in MATLAB is really slow; slow enough that I may not be able to process images as fast as I require.
As a follow up. Are there any recommendations about how to deploy this program? An idea I like is a simple GUI with a "start" and "stop" button.
Thank you.
A: You could do the following:
Create timer object, which will check your directory every 10 seconds:
t = timer('TimerFcn', @mycallback, 'Period', 10.0, 'ExecutionMode', 'fixedSpacing');
your 'mycallback' function should look something like this:
DIR_TO_READ = 'C:\incoming-files';
DIR_TO_MOVE_PROCESSED = 'C:\processed-files';
% get list of files.
file_struct = dir(DIR_TO_READ)
% remove '.' and '..' directories
file_struct([file_struct.isdir]) = [];
for j = 1 : numel(file_struct)
current_file = file_struct(j).name;
full_filename = fullfile(DIR_TO_READ, current_file)
% add your processing of the file here
% e.g.
bla = imread(full_filename);
% now move the processed file to the processed file folder
movefile(full_filename, fullfile(DIR_TO_MOVE_PROCESSED, current_file))
end
Now you need to start the timer object
start(t);
You can stop the timer object with
stop(t);
A: The correct way to do this is to purchase the MATLAB Image Acquisition Toolbox (http://www.mathworks.com/products/imaq/). This functionality is intentionally not included in the base Matlab environment.
Alternatively, with some clever programming you could implement a work-around. The build-in MATLAB functions will likely be too slow. Your best bet would be to write the functionality you need in Java (See http://www.exampledepot.com/egs/java.io/GetFiles.html) and then calling your Java code directly from Matlab (see http://www.mathworks.com/help/techdoc/matlab_external/f44062.html).
Fundamentally, unless you are accessing the camera drivers or framegrabber directly, you will always need to implement some kind of directory polling.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can I stop two words from breaking onto separate lines and creating an orphan? I have a paragraph that ends with a link that contains the two word phrase "Read More". I'd like these two words to always be displayed on the same line. Right now, if the "More" can't fit on the same line, it gets bumped to the next line by itself.
Is there any CSS that will stop "Read More" from breaking onto separate lines?
A: <a href='#' class="my-readmore-css-class">Read more</a>
.my-readmore-css-class { white-space:nowrap; } // it should be style for your "Read more"
A: There's a <nobr> tag in HTML that will do this, but it's deprecated. This page suggests using white-space:nowrap instead.
white-space is defined in the CSS1 specification and should be supported by all major browers.
A: You can also place the non-breaking space between the two words:
Read More
although arguably this muddies HTML with presentation matters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Technical reasons to not allow using UI part of WinRT API in regular desktop applications WinRT API can be called from applications other than Metro style applications, except XAML classes. It might be beneficial to use some controls on desktop. What are the technical problems causing this restriction?
A: My guess is that it would be possible, but it would be too much work both from MS and the developers using this.
If you have some GUI library, I don't really see the benefit of using WinRT Button over the built-in button component.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Jquery UI slider tooltip class I'm having some trouble finding the css class linked to the tooltips in the Jquery ui slider... does anyone know what it's called, or another way I can adjust the tooltip width?
A: Can you post a JSFiddle with your code?
You can see an example JQueryUI Slider - Tooltip for the Current Position where the tooltip is set with an id of "tooltip"
I modified a bit here http://jsfiddle.net/YShtg/1/
Maybe this will help out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: dns.gethostbyname() i've been searching online about the Dns gethostbyname change to gethostentry, and modify the code accordingly, but why still not display the normal ipv4 address?
here my code:
string GetHostIP()
{
String myHostName = System.Net.Dns.GetHostName();
// Find host by name
System.Net.IPHostEntry myiphost = System.Net.Dns.GetHostEntry(myHostName);
String ipstring = "";
foreach(System.Net.IPAddress myipadd in myiphost.AddressList)
{
ipstring = myipadd.ToString();
return ipstring;
}
return ipstring;
}
A: They are trying to make you stop assuming the IP address is a dotted-decimal IPv4 address. They just can't get IPv6 off the ground and that's necessary. Completely out of free addresses as of a couple of months ago.
You can get the IPv4 address, you'll have to fish it out explicitly:
foreach (System.Net.IPAddress myipadd in myiphost.AddressList) {
if (myipadd.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) {
return myipadd.ToString();
}
}
throw new WhatTheHeckException();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: matrix losing class attribute in R Consider the following code:
A <- matrix(1:12, ncol=4)
colnames(A) <- letters[1:4]
class(A) <- c("foo", "matrix")
when A is subset, it loses the "foo" class label:
class(A[1:2,])
# [1] "matrix"
The same happens with vectors. Yet, the same doesn't happen with data.frames:
B <- as.data.frame(A)
class(B) <- c("foo", "data.frame")
class(B[1:2,])
# [1] "foo" "data.frame"
And usually, applying generic functions to objects preserves the class attribute. Not for matrix/numeric/integer objects. Why? And can this behavior be avoided?
A: data.frames have their own subset method [.data.frame, which takes care of the class for you. I'm not sure why the Primitive doesn't preserve the class, but it's pretty straight-forward to create your own subset method.
`[.foo` <- function(x, i, j, ...) {
y <- unclass(x)[i,j,...]
class(y) <- c("foo",class(y))
y
}
class(A[1:2,])
# [1] "foo" "matrix"
EDIT:
As others have mentioned, NextMethod should be used here.
`[.foo` <- `[.bar` <- function(x, i, j, ...) {
y <- NextMethod(.Generic)
class(y) <- .Class
y
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7532845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.