text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: In Scala, why does getInstance fail to work with GregorianCalendar? java.util.GregorianCalendar.getInstance();
Works in Java
java.util.Calendar.getInstance();
Works in Scala
java.util.GregorianCalendar.getInstance();
Fails in Scala. getInstance is not a member of object java.util.GregorianCalendar
A: There are no static in scala, rather there are in singleton objects and methods in them, and so they are not considered inherited, even when defined in java. getInstance is defined on Calendar. In java, calling it on GregorianCalendar does call the exact same method as calling it on Calendar. In scala, you have to call it on Calendar. (BTW, calling it on GregorianCalendar in java is rather misleading)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Solving linear equations during inverse iteration I am using OpenCL to calculate the eigenvectors of a matrix. AMD has an example of eigenvalue calculation so I decided to use inverse iteration to get the eigenvectors.
I was following the algorithm described here and I noticed that in order to solve step 4 I need to solve a system of linear equations (or calculate the inverse of a matrix).
What is the best way to do this on a GPU using OpenCL? Are there any examples/references that I should look into?
EDIT: I'm sorry, I should have mentioned that my matrix is symmetric tridiagonal. From what I have been reading this could be important and maybe simplifies the whole process a lot
A: The fact that the matrix is tridiagonal is VERY important - that reduces the complexity of the problem from O(N^3) to O(N). You can probably get some speedup from the fact that it's symmetric too, but that won't be as dramatic.
The method for solving a tridiagonal system is here: http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm.
Also note that you don't need to store all N^2 elements of the matrix, since almost all of them will be zeroes. You just need one vector of length N (for the diagonal) and two of length N-1 for the sub- and superdiagonals. And since your matrix is symmetric, the sub- and superdiagonals are the same.
Hope that's helpful...
A: I suggest using LU decomposition.
Here's example.
It's written in CUDA, but I think, it's not so hard to rewrite it in OpenCL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to add phone logs programmatically in Android? I want to add phone logs programmatically from my custom application.
Using the following code for adding phone logs, I get a new phone log in phone log list,
but it only adds the phone number in the list, not "call type", "duration", and "Date".
What did I miss?
ContentValues values = null;
for (int i = 0; i < length; i++) {
Info info = (Info) Variables.elementAt(i);
int index = info.getIndex();
String value = info.getValue();
values = new ContentValues();
if (value != null) {
if (index == Constants.NUMBER_TYPE) {
values.put(CallLog.Calls.CACHED_NUMBER_TYPE, value);
} else if (index == Constants.CALL_TYPE) {
values.put(CallLog.Calls.TYPE, value);
} else if (index == Constants.DATE) {
values.put(CallLog.Calls.DATE, value);
} else if (index == Constants.DURATION) {
values.put(CallLog.Calls.DURATION, value);
}
}
}
values.put(CallLog.Calls.NUMBER, phoneNumber);
activity.getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);
A: I tried this in my LG P350.
Its surely works with the android.permission.WRITE_CONTACTS permission.
ContentValues values = new ContentValues();
values.put(CallLog.Calls.CACHED_NUMBER_TYPE, 0);
values.put(CallLog.Calls.TYPE, CallLog.Calls.INCOMING_TYPE);
values.put(CallLog.Calls.DATE, System.currentTimeMillis());
values.put(CallLog.Calls.DURATION, 50);
values.put(CallLog.Calls.NUMBER, "1234567890");
getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problem with Custom Button added to numpad Hi I am trying to dismiss a numpad-keyboard which has a custom DOne Button implemented. When I try to dismiss it the app it crashes giving the following error
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton key]: unrecognized selector sent to instance 0x7399b40'
Here is the code snippet
// Snippet
- (void)keyboardWillShow:(NSNotification *)notification {
// create custom button
doneButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
doneButton.frame = CGRectMake(0, 163, 106, 53);
doneButton.adjustsImageWhenHighlighted = NO;
[doneButton setImage:[UIImage imageNamed:@"DoneUp.png"] forState:UIControlStateNormal];
[doneButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateHighlighted];
[doneButton addTarget:self action:@selector(doneButton:) forControlEvents:UIControlEventTouchUpInside];
// locate keyboard view
UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
UIView* keyboard;
UITextField * tempTextField = (UITextField*)self.currentResponder; //Current responder is the textfield which is clicked
for(int i=0; i<[tempWindow.subviews count]; i++) {
keyboard = [tempWindow.subviews objectAtIndex:i];
if([[[keyboard class]description] hasPrefix:@"UIPeripheralHostView"])
{
if(tempTextField.keyboardType == UIKeyboardTypeNumberPad)
{
UIView *viewToInsertButtonInto = [[[[[[[[keyboard subviews] objectAtIndex:0] subviews]objectAtIndex:0]subviews]objectAtIndex:0]subviews]objectAtIndex:0];
[viewToInsertButtonInto addSubview:self.doneButton];
}
}
}
}
- (void)doneButton:(id)sender
{
NSLog(@"%@,%@ _________ %s",self.faxTextField,self.currentResponder,__FUNCTION__);
UITextField * tempTextField = (UITextField*)self.currentResponder;
if ([tempTextField isFirstResponder]) {
NSLog(@"It is the first responder");
}
[tempTextField resignFirstResponder];
}
The App Crashes when [tempTextField resignFirstResponder]; is executed.
Can someone please help.
Thanks
Nachiket
A: NSLog(@"%@,%@ _________ %s",self.faxTextField,self.currentResponder,__FUNCTION__);
why are u using this log?.
I think u should use NSLog(@"%@,self.faxTextField.text);
or use
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];
return NO;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSPredicate filter for many-to-many-to-many relationships I'm still fairly new to using NSPredicate, but I've got a somewhat complicated issue and I'm not quite sure the best way to go about a solution.
I'm attempting to build a filter for an entity called Instrument, which can be used with many Procedures. Procedures, in turn, are related to one or more Diseases. Diseases are related to many Procedures, and Instruments can be used in more than one Procedure. In other words, I have the following many-to-many-to-many relationship:
Instruments <-> Procedures <-> Diseases
What I would like to do is filter Instruments using Disease.title. In a simple and magical world, this would be as simple as
//where predicate is used on the Instruments array
[NSPredicate predicateWithFormat:@"(procedures.diseases.title == %@)", diseaseTitleString];
Stepping through this piece by piece (with a few typos and misnamings), I found that the filter knows the fields of Procedures and Diseases enough to tell me that "diseaseTypes" is not a field on procedures, and "name" is not a field on diseases. Naivety led me to hoping that this simple predicate would work.
I get nothing.
I've also tried using (ALL procedures.diseases.title == %@), but that doesn't work either.
I've seen some things about sub-predicates, but nothing that really sticks out to me as something that works or makes a lot of sense to me.
Basically I want to get the list:
NSArray *instruments = [[NSArray alloc] init];
for (Disease *disease in Diseases) {
if ([disease.title isEqualToString:titleString]) {
for (Procedure *procedure in disease.procedures) {
for (Instrument *instrument in procedure.instruments) {
if (![instruments containsObject:instrument]) {
[instruments addObject:instrument];
}
}
}
}
}
Right now, I'm using this method to get an array that I can filter based on other predicates, and it's working fine, but it's ugly and I feel like there is a better, cleaner way do filter this. Can anyone help educate me on the finer uses of NSPredicate design?
A: On the predicate you have above, replace the double equals with a single equals. Also add an "ANY" clause. Finally, remove the parentheses. So you will have:
[NSPredicate predicateWithFormat:@"ANY procedures.diseases.title = %@", diseaseTitleString];
In general, I find a good way to handle complex predicates is to build them up using sub-predicates.
So, you start with:
NSMutableArray *subpredicates = [NSMutableArray array];
Then bit by bit you add your subpredicates:
[subpredicates addObject:
[NSPredicate predicateWithFormat:@"ANY procedures.diseases.title = %@",
diseaseTitleString]]
[subpredicates addObject:anotherPredicate etc];
Finally, create your "and" or "or" predicate, for example:
NSPredicate *andPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Oracle SQL Developer and PostgreSQL I'm trying to connect to a PostgreSQL 9.1 database using Oracle SQL Developer 3.0.04, but I'm not having any success so far.
First, if I add a third party driver on preferences, when adding a new connection there's no tab for PostgreSQL (it works fine for MySQL though). I'm using a JDBC4 version 9.1 driver, but I tried a JDBC3 of the same version and still get the same thing.
Second, there's nothing like manual configuration tab when adding a new connection. The closest is the Advanced option on Oracle tab, where I can provide a custom URL, but it fails because complains about the selected Driver (of course).
Finally, I got connected importing a connection from an XML file (contents below), but it displays only my schemas and doesn't show my tables inside them.
So, my question is: does Orable SQL Developer support PostgreSQL connections? Is there any other way to have my tables being displayed in the ObjectViewer?
<?xml version = '1.0' encoding = 'UTF-8'?>
<References xmlns="http://xmlns.oracle.com/adf/jndi">
<Reference name="Lumea" className="oracle.jdeveloper.db.adapter.DatabaseProvider" credentialStoreKey="Lumea" xmlns="">
<Factory className="oracle.jdeveloper.db.adapter.DatabaseProviderFactory"/>
<RefAddresses>
<StringRefAddr addrType="user">
<Contents>lumea</Contents>
</StringRefAddr>
<StringRefAddr addrType="subtype">
<Contents>thirdParty</Contents>
</StringRefAddr>
<StringRefAddr addrType="customUrl">
<Contents>jdbc:postgresql://localhost:5432/versates</Contents>
</StringRefAddr>
<StringRefAddr addrType="SavePassword">
<Contents>true</Contents>
</StringRefAddr>
<StringRefAddr addrType="password">
<Contents>myencryptedpass</Contents>
</StringRefAddr>
<StringRefAddr addrType="driver">
<Contents>org.postgresql.Driver</Contents>
</StringRefAddr>
<StringRefAddr addrType="DeployPassword">
<Contents>true</Contents>
</StringRefAddr>
</RefAddresses>
</Reference>
</References>
A: Oracle SQL Developer doesn't support connections to PostgreSQL. Use pgAdmin to connect to PostgreSQL instead, you can get it from the following URL
http://www.pgadmin.org/download/windows.php
A: I managed to connect to postgres with SQL Developer.
I downloaded postgres jdbc driver and saved it in a folder.
I run SQL Developer -> Tools -> Preferences -> Search -> JDBC
I defined postgres jdbc driver for the Database and Data Modeler (optional).
This is the trick.
When creating new connection define Hostname like localhost/crm? where crm is the database name. Test the connection, works fine.
A: If there is no database with the same name as the username, then clicking "Choose Database" will fail with an error like "Status : Failure -FATAL: database "your_username" does not exist"
To work around this, put 5432/database_name? in the Port field, where 5432 is the port of your Postgres instance and database_name is the name of at an existing database that your_username has access to. Then click "Choose Database" again and it should work. Now you can choose the database you want and remove the extra /database_name? from the Port field.
A: I think this question needs an updated answer, because both PostgreSQL and SQLDeveloper have been updated several times since it was originally asked.
I've got a PostgreSQL instance running in Azure, with SSLMODE=Require.
While I've been using DBeaverCE to access that instance and generate an ER Diagram, I've gotten really familiar with SQLDeveloper, which is now at v19.4.
The instructions about downloading the latest PostgreSQL JDBC driver and where to place it are correct. What has changed, though, is where to configure your DB access.
You'll find a file $HOME/.sqldeveloper/system19.4.0.354.1759/o.jdeveloper.db.connection.19.3.0.354.1759/connections.json:
{
"connections": [
{
"name": "connection-name-goes-here",
"type": "jdbc",
"info": {
"customUrl": "jdbc:postgresql://your-postgresql-host:5432/DBNAME?sslmode=require",
"hostname": "your-postgresql-host",
"driver": "org.postgresql.Driver",
"subtype": "SDPostgreSQL",
"port": "5432",
"SavePassword": "false",
"RaptorConnectionType": "SDPostgreSQL",
"user": "your_admin_user",
"sslmode": "require"
}
}
]
}
You can use this connection with both Data Modeller and the admin functionality of SQLDeveloper. Specifying all the port, dbname and sslmode in the customUrl are required because SQLDeveloper isn't including the sslmode in what it sends via JDBC, so you have to construct it by hand.
A: Oracle SQL Developer 4.0.1.14 surely does support connections to PostgreSQL.
*
*download JDBC driver for Postgres (http://jdbc.postgresql.org/download.html)
*in SQL Developer go to Tools β Preferences, Database β Third Party JDBC Drivers and add the jar file (see http://www.oracle.com/technetwork/products/migration/jdbc-migration-1923524.html for step by step example)
*now just make a new Database Connection and instead of Oracle, select PostgreSQL tab
Edit:
If you have different user name and database name, one should specify in hostname: hostname/database? (do not forget ?) or hostname:port/database?.
(thanks to @kinkajou and @Kloe2378231; more details on https://stackoverflow.com/a/28671213/565525).
A: I've just downloaded SQL Developer 4.0 for OS X (10.9), it just got out of beta. I also downloaded the latest Postgres JDBC jar. On a lark I decided to install it (same method as other third party db drivers in SQL Dev), and it accepted it. Whenever I click "new connection", there is a tab now for Postgres... and clicking it shows a panel that asks for the database connection details.
The answer to this question has changed, whether or not it is supported, it seems to work. There is a "choose database" button, that if clicked, gives you a dropdown list filled with available postgres databases. You create the connection, open it, and it lists the schemas in that database. Most postgres commands seem to work, though no psql commands (\list, etc).
Those who need a single tool to connect to multiple database engines can now use SQL Developer.
A: I got the list of databases to populate by putting my username in the Username field (no password) and clicking "Choose Database". Doesn't work with a blank Username field, I can only connect to my user database that way.
(This was with SQL Developer 4.0.0.13, Postgres.app 9.3.0.0, and postgresql-9.3-1100.jdbc41.jar, FWIW.)
A: Oracle SQL Developer 2020-02 support PostgreSQL, but it is just the basics by adding postgreSQL driver under jdbc dir and configure by adding as a 3rd party driver.
The supported functionality:
*
*multiple databases which can be selected at connection definition
*CRUD operations like query tables
*scheme operations
*basic modelling support: show tables without pk, fk, connections
Not supported functionalities:
*
*no table or field completion
*no indexes are shown in a tab
*no constraints are shown in a tab like: fk, pk-s, unique, or others
*no table or field completions in the editor
*no functions, packages,triggers, views are shown
The sad thing is Oracle should only change the queries behind this view in case of PostgreSql connections. For example for indexes they need to use this query: select * from pg_catalog.pg_indexes;
A:
Except that it will not work if your user name and database name are differents. It sounds like an SQLDeveloper bug and i can't find any workaroud
Maybe there are some bugs in Oracle SQL Developer when it connect to the postgresql.However I connect postgresql with navicat successfully.(My postgresql username and database name are different
A: host= localhost/postgres? worked for me if you need a schema/database use:
localhost/postgres?currentSchema=myschema
ex: localhost/postgres?currentSchema=public
once connected, you can also use the
[Choose Database] button and pull down
sql developer postgres jdbc url for the rest of us
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "75"
}
|
Q: Can a UITableViewCell know that it should be in grouped mode? Is there a way for a cell, if used in a grouped table view, detect that fact and modify its appearance as ro not overlap the rounded rect borders?
A: In a grouped table view, such a cell will always be the 1st or last of the section. You can easily identify it in cellForRowAtIndexPath:, by looking at the indexPath parameter.
A: There are two ways to do this. If you are making a custom cell you can just add a boolean property to the cell and set it when you create the cell. Or, you can do this:
UITableView *parentTable = (UITableView *)self.superview;
if (parentTable.style == UITableViewstyleGrouped {
//Do what you need to do for a grouped cell
}
else {
//Do what you need to do for a plain cell
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Extra and misaligned rows when importing data in SAS I am trying to import data in SAS like:
A B C D E
x y z h i
s1 s2 s3 s4 s5
where A B C D and E are column names.
I have 240 columns in my dataset and the code I am using is:
data INFO;
infile Attdata notab dlm='09'x dsd missover LRECL = 100000000;
length A B C D E $200; (I am importing 240 columns)
input A B C D E;
run;
Whenever I import data, some of the rows of column B, C etc, gets stacked below rows of A:
A B C D E
x h i
s1 s2 s3 s5
y s4
z
Is there a way to fix this? Do I need to do something with lrecl one? My data gets all weird after running this code. Might there be problem with length one?
A: It may be something to do with missover (rather than LRECL). I have found this site to be useful in the past: http://www2.sas.com/proceedings/sugi26/p009-26.pdf
Are you saying in your question that data from line 1 is appearing on lines 3 and 4 and some data from line 2 is on line 3? I've never seen SAS do this before.
You may want to check your delimiter/end of line characters.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSNumberFormatter Problem IN my App i have to share the amount among the event people for Example i have 3 people names like RAM, RAJ, RAGHU ,if RAM put amount of 10.00 in event than i am dividing the among three people like 10.00/3=3.333333, Then,
RAJ has to pay to RAM-------------3.33
RAGHU has to pay to RAM -------3.33
over all he getting From other 2 people in the event 6.66
here 0.1 missing how can i solve this problem
i am using NumberStyle:NSNumberFormatterCurrencyStyle like below
NSNumberFormatter *numberFormater = [[NSNumberFormatter alloc] init];
[numberFormater setLocale:[NSLocale currentLocale]];
[numberFormater setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *str_num = [numberFormater stringFromNumber:[NSNumber numberWithDouble:3.333333]];
[numberFormater release];
A: Why don't you subtract RAM's share from 10? 10 - 3.33 = 6.67.
A: float invoice= 10.15;
int num_people = 3; // sample people
float num_to_add;
float piece_pie;
// now just add num_to_add to your invoice then divide by num_people
num_to_add=num_people*.01;
invoice=invoice+num_to_add;
piece_pie = invoice/num_people;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problem with "Click Sound" on button click in iPhone i am working in the project in which i face the problem of playing the clicking sound on button click, i have done the following code on TouchDown Event of Buttons on every page
-(IBAction)ClickButtonSound:(id)sender
{
SystemSoundID theSound;
NSString *pathToSound;
pathToSound = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"buttonsound" ofType:@"wav"] isDirectory:NO];
OSStatus error = AudioServicesCreateSystemSoundID((CFURLRef)pathToSound,&theSound);
NSLog(@"error=%@",error);
AudioServicesPlaySystemSound (theSound);
//[pathToSound release];
}
this code is working well on simulator but when i test it on iphone device it gives humming sound,but not plays clicking sound so can anyone plese point out the reason why it is so?
thanks
A: Are you sure you stop the sound from playing when you get the TouchUpEvent?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Silverlight 4.0: Safari and XMLHttpRequest function releaseUser(user) {
if (user != null) {
var requestParams = "", url = "", number = 0, type = "";
/* Configure Parameters */
url = readCookie("endpointaddress");
requestParams = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
requestParams = requestParams + "<soap:Body><ReleaseUser xmlns=\"http://Test.Test.CaseHistory/\">";
requestParams = requestParams + "<credentials>" + user + "</credentials></ReleaseUser></soap:Body></soap:Envelope>";
/* Send XML/SOAP Request To Web Service Using Browser's Javascript DOM */
try {
releaseUserRequest = new XMLHttpRequest();
}
catch (trymicrosoft)
{
try {
releaseUserRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (othermicrosoft) {
try {
releaseUserRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (failed) {
releaseUserRequest = false;
}
}
}
releaseUserRequest.open("POST", url, true);
releaseUserRequest.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
releaseUserRequest.onreadystatechange = releaseUserState;
releaseUserRequest.send(requestParams);
**alert(releaseUserRequest.responseText);**
}
}
function releaseUserState() {
if (releaseUserRequest.readyState == 4) {
if (releaseUserRequest.status == 200) {
**alert(releaseUserRequest.responseText);**
}**alert(releaseUserRequest.responseText);**
}
}
The code above is my Silverlight server page and is working in Firefox and IE but NOT in Safari. releaseUser function calls the web service method when the user click browser close.
OS: Windows 7
Is their anything that I've missed in Safari configuration? Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails simple_form attribute required mark (*) I am using Simple Form in my app and I'd like to remove the * to indicate an attribute is required on all of my forms (existing and those yet to be created).
I have tried to set in simple_form.rb:
# Whether attributes are required by default (or not). Default is true.
config.required_by_default = false
And I've tried to modify simple_form.en.yml:
required:
text: 'required'
mark: '' # <------ tried setting this to blank.
I know I can set :required => false on each field, but I want to clean up the views & set it once.
A: on Rails 4 just remove the "required" word
config.label_text = lambda { |label, required, explicit_label| "#{required} #{label}" }
so it should be
config.label_text = lambda { |label, required, explicit_label| "#{} #{label}" }
Validation still works!
A: Setting the simple_form.required.mask to '' should work if you restarted the server.
But you can remove it changing the the configuration:
# config.label_text = proc { |label, required| "#{required} #{label}" }
to
config.label_text = proc { |label, required| "#{label}" }
A: You can also do
simple_form_for @model, :defaults => {:required => false}
A: just
# Whether attributes are required by default (or not). Default is true.
config.required_by_default = false
and restart your rails server. Then it works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: How to open a file name that looks like a URL after require open-uri? How to open a file name that seems like a URL after require 'open-uri'
require 'open-uri'
open("http://google.com")
in folder
- http://google.com
A: According to ruby-doc.org, open-uri creates an alias to the original open called open_uri_original_open. You can use that method for enforcing opening local files.
But then, I'm not sure if you can really have filenames like http://google.com in your OS/filesystem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Executing SQL statement in ASEISQL with UNIX scripts Since I am new to unix scripting. I am running a SQL statement in ASE ISQL, and if SQL statement gives some result then I need to mail that result to a particular users. And if SQL is not returning any result then mail should not be sent.
The Sample Script I have wriiten is:
#!/bin/ksh
isql -U$DBO -S$DSQUERY -D$DBNAME -P$PASSWORD << END
go
select * from 'Table'
go
if (@@rowcount !=0)
mailx -s "Hello" XYZ@gmail.com
END
Please let me know where I am going wrong?
A: I think you need to capture the output of the SQL into a shell variable, and then test the result before sending the email, roughly like:
#!/bin/ksh
num=$(isql -U$DBO -S$DSQUERY -D$DBNAME -P$PASSWORD << END
select count(*) from 'Table'
go
END
)
if [ "$num" -gt 0 ]
then mailx -s "Hello" XYZ@gmail.com < /dev/null
fi
I am assuming that the isql program will only print the number and not any headings or other information. If it is more verbose, then you have to do a more sensitive test.
Note, too, that COUNT(*) is quicker and more accurately what you're after than your 'select everything and count how many rows there were' version.
Actually my problem is if my SQL statement is returning any result then only that resultset should be sent in a mail.
Then I'd use:
#!/bin/ksh
tmp=${TMPDIR:-/tmp}/results.$$
trap "rm -f $tmp; exit 1" 0 1 2 3 13 15
isql -U$DBO -S$DSQUERY -D$DBNAME -P$PASSWORD << END > $tmp
select * from 'Table'
go
END
if [ -s $tmp ]
then mailx -s "Hello" XYZ@gmail.com < $tmp || exit 1
fi
rm -f $tmp
trap 0
exit 0
This captures the results in a file. If the file is not empty (-s) then it sends the file as the body of an email. Please change the subject to something more meaningful. Also, are you sure it is a good idea to send corporate email to a Gmail account?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ribbon menu in IPad application I want to use ribbon menu(as on Microsoft Word 2007 or 10) in my IPad application. Anyone have any suggestions? If it impossible to implement, may be anyone have other ideas how to implement similar functionality? In IOS development i am newbie, so i can not imagine how to modulate Ribbon menu with Xcode tools. May be using of Ribbon menu in tablet Apps is not good idea, if so, what alternative i can use? Ribbon menu need because application is very large, and it's have many tools and options. Thanks!:)
A: I would avoid the Ribbon. I am pretty sure it wasn't designed for touch and users will reject the idea of such a distinctive Windows control on iOS. There are other options for complicated options than a Ribbon. Google iPad menu.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you use the JSON data pulled from an external php file in your javascript/html? I was able to pull the JSON data and put it into my HTML file as a script in my head. How do I gain access to this data? (put it into usable variables)
external json.php file (populated with mySQL data):
names:
[
{"firstName":"Kevin","lastName":"Guo"},
{"firstName":"Jun Sung","lastName":"Wong"},
{"firstName":"Anton","lastName":"Ansalmar"},
{"firstName":"Linda","lastName":"Wong"},
{"firstName":"George","lastName":"Costanza"}
]
my javascript code that pulls in the external json data:
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://totallyExternalURL.php";
elm.id="jsonTest";
console.log(elm);
document.getElementsByTagName('head')[0].appendChild(elm);
The entire json data is put as a script in my head, how can I pull all the firstnames/lastnames for display?
A: What you're doing is actually known as jsonp. Normally what you'd do is have the script return a script calling a function on your page with the data. You might find it easier to work with jQuery either using jsonp or, if calling a script on your own server, regular `json'.
function callback(data) {
... do something with the returned data
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://totallyExternalURL.php?callback=callback";
elm.id="jsonTest";
console.log(elm);
document.getElementsByTagName('head')[0].appendChild(elm);
Then have your external script return (note, your script should detect the value of the callback parameter and use that as the name of the function to invoke). The name of the function and the value of the callback parameter need to be the same.
callback( { "names" :
[
{"firstName":"Kevin","lastName":"Guo"},
{"firstName":"Jun Sung","lastName":"Wong"},
{"firstName":"Anton","lastName":"Ansalmar"},
{"firstName":"Linda","lastName":"Wong"},
{"firstName":"George","lastName":"Costanza"}
] });
Or with jQuery
$.getJSON( 'http://totallyExternalURL.php?callback=?', function(data) {
... do something with the data ...
});
A: Make the js returned as a function that returns the a javascript object that is the array and then you can make a call to that function and assign the return value to a variable.
So wrap the JSON in a function call.
Look up jsonp.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: pre-populate associative array keys in awk? I've written a munin plugin that uses slurm's sacct to monitor job states on a HPC cluster. I've written it in sh + awk (rather than my usual tool of choice, perl).
The script works, but it took me ages to figure out how to pre-populate the associative array of possible states (some/most may not be present in sacct output, and i want them to default to zero). Google wasn't much help, and the best I could come up with was to use split on a string to produce a temporary array, which I then iterated over.
I came up with this:
BEGIN {
num = split("cancelled completed completing failed nodefail pending running suspended timeout",statenames," ");
for (i=1;i<=num;i++) {
states[statenames[i]] = 0
}
}
This works, but seems clumsy compared to how i'd do it in perl, like this:
foreach (qw(cancelled completed completing failed nodefail pending running suspended timeout)) {
$states{$_} = 0;
}
or this
%states = map {$_ => 0} qw(cancelled completed completing failed nodefail pending running suspended timeout);
my question is: is there a way of doing this in awk that is similar to either of the perl versions?
[ edited ]
to clarify, here's a sample of the sacct output i'm piping into awk. Note that the only states in this output are RUNNING, COMPLETED, and CANCELLED - the others don't exist (because they haven't occurred today), but i want them in my script's output anyway (in a form usable by munin as "statename.value 0").
# sacct -X -P -o 'state' -n
RUNNING
RUNNING
RUNNING
RUNNING
COMPLETED
RUNNING
COMPLETED
RUNNING
COMPLETED
COMPLETED
CANCELLED by 1000
COMPLETED
[ edited again ]
and here's sample output from my munin plugin:
# ./slurm-sacct
suspended.value 0
pending.value 0
nodefail.value 0
failed.value 0
running.value 6
completing.value 0
completed.value 5
timeout.value 0
cancelled.value 1
The script runs and does what I want, I just wanted to know if there was a better way to initialise the associative array.
A: You probably don't need to do it at all. Variables in awk are dynamic, which means they're automatically initialized when they are first used (either assigned to or accessed), and this applies to array elements as well.
A variable will be initialized to 0 if it's accessed in a numeric context, or to the empty string otherwise. (At least gawk does this, though I'm not sure if it's implementation-dependent) So if you're doing something like counting the number of jobs that are in each state, the entire program is as simple as something like
{ states[$1]++ }
END {
for (state in states) print state, states[state]
}
Each time the expression states[$1]++ is executed, it will check for the existence of states[$1] and initialize it to 0 if it doesn't already exist.
EDIT: From your comment I'm guessing you want to print out a line for each possible state, regardless of whether there are any jobs in that state or not. In that case, you need to include all the possible state names, and there is no shortcut notation for doing so as there is in Perl. As far as I know, what you've already found is about as clean as it gets. (Awk is not really designed with that usage in mind)
I'd suggest the following:
{ states[$1]++ }
END {
split("cancelled completed completing failed nodefail pending running suspended timeout",statenames," ");
for (state in statenames) print state, states[state]+0
}
A: Perhaps Craig can use instead of :
print "Timeout states ",states[timeout],".";
this:
print "Timeout states ",int(states[timeout]),".";
In my case if there is no timeout state in awk input, the first print will give:
Timeout states .
While the second will give:
Timeout states 0.
A: I think a more natural approach in awk would be to have a separate file of keys. Consider a file keys.txt with one key per line. You could then do something like this:
printf "key1\nkey2\nkey2\nkey5" |
awk '
FILENAME == "keys.txt" {
counts[$0] = 0
next
}
{
counts[$0]++
}
END {
for (key in counts) {
print key, counts[key]
}
}' keys.txt -
With five keys in keys.txt, this produces:
key1 1
key2 2
key3 0
key4 0
key5 1
Although the keys are shown in order here, that's just incidental and shouldn't be relied upon.
For the specific example, you could also skip the associative array altogether. Instead, you could minimally process the lines with awk and use sort | uniq -c to tabulate the counts. The presence of all keys could be ensured using join against a file of keys.
A: awk is somewhat clumsier (I would say "less terse") than Perl.
You could write this (similar to @Michael's answer):
pipeline of data |
awk '
NR == FNR {statenames[$1]=0; next}
{ usual processing }
END { usual output }
' <(printf "%s\n" cancelled completed completing failed nodefail pending running suspended timeout) -
A: One tweak to @DavidZaslavsky's answer might be to print the states in the order you specified them on the split() line. That would be:
{ states[tolower($1)]++ }
END {
n = split("cancelled completed completing failed nodefail pending running suspended timeout",statenames)
for (i=1; i<=n; i++) {
state = statenames[i]
print state, states[state]+0
}
}
I also converted the input to lower case so it matches your hard-coded values, got rid of the unnecessary 3rd arg to split() and the subsequent null statement (trailing semi-colon).
In case you want to account for finding state names in your input that weren't in your hard-coded set, you could tweak it to:
{ states[tolower($1)]++ }
END {
n = split("cancelled completed completing failed nodefail pending running suspended timeout",statenames)
for (i=1; i<=n; i++) {
state = statenames[i]
print state, states[state]+0
delete states[state]
}
for (state in states) {
print "WARNING: found new state name %s\n",state | "cat>&2"
print state, states[state]+0
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How do I get my JavaScript to tile this table properly? var intervalID;
function autoUpdateFeed()
{
if( document.autoupdatefeedform.autoupdatefeed.checked == true )
{
intervalID = setInterval(updateFeed, 1000);
} else {
clearInterval(intervalID);
}
}
function updateFeed()
{
var oRequest;
try {
oRequest=new XMLHttpRequest();
} catch (e) {
try {
oRequest=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
oRequest=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
oRequest.onreadystatechange=function()
{
if(oRequest.readyState==4)
{
//Start of problem.
var newfeedstable = document.getElementById("newfeeditems");
var newcontent = document.createElement('tr');
newcontent.innerHTML = oRequest.responseText;
while (newcontent.firstChild)
{
newfeedstable.insertBefore(newcontent.firstChild, newfeedstable.firstChild);
}
//End of problem.
}
}
oRequest.open("GET","back/newsfeedlatest.php",true);
oRequest.send(null);
}
Here is the JavaScript code I and my friend are currently using to add new status updates to a table for new status updates on our work-in-process social networking site, the problem is when the new elements are added to the table, they tile to the side, instead of tiling downwards, so I need to know why this is happening and how to fix it, any ideas? For more information, look at the website, you may have to make an account but feel free to use a fake email until we start using email activation again. http://friendgrid.com/
Here's a screenshot of the problem for further reference: http://dl.dropbox.com/u/2281426/Newsfeed%20Error.bmp
A: Try next:
oRequest.onreadystatechange=function() {
if(oRequest.readyState===4) {
if(oRequest.status===200) { // HTTP OK
//Start of problem.
var newfeedstable = document.getElementById("newfeeditems");
var newcontent = document.createElement('tr');
newcontent.innerHTML = oRequest.responseText;
// next lines removed: it's a problem: you download a <td> and next code insert its into table directly, without <tr>
//while (newcontent.firstChild)
//{
// newfeedstable.insertBefore(newcontent.firstChild,newfeedstable.firstChild);
//}
// 1) next line added, try next:
newfeedstable.insertBefore(newcontent,newfeedstable.firstChild)
// 2) OR IF RESPONSE CAN CONTAIN MORE THAN ONE <TD> try next (not checked code)
while (newcontent.cells.length) {
var td=newcontent.cells[0];
newcontent.removeChild(td);
var tr=document.createElement('tr');
tr.appendChild(td);
newfeedstable.insertBefore(tr,newfeedstable.firstChild);
}
//End of problem.
}
}
}
A: The issue would be at the line inside the While:
newfeedstable.insertBefore(newcontent.firstChild, newfeedstable.firstChild);
There the first parameter should be only newcontent without the .firstChild, the firstChild would be inserting only that element and not the newly created <TR>
Altough i suggest you to use DOM methods to modify tables, something easier like:
TableElement.insertRow( 0).innerHTML = oRequest.responseText;
TableElement in your case would be newfeedstable, which if you don't need it later you could reduce to:
document.getElementById("newfeeditems").insertRow( 0).innerHTML = oRequest.responseText;
The 0 as parameter would make the insert always as first row, use a -1 to insert always as last row.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Difference between cleaned_data and cleaned_data.get in Django I've seen some samples codes like:
def clean_message(self):
message = self.cleaned_data['message']
num_words = len(message.split())
if num_words < 4:
raise forms.ValidationError("Not enough words!")
return message
and some examples like:
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
...
self.check_for_test_cookie()
return self.cleaned_data
What's the difference between the two?
A: cleaned_data is a Python dictionary, you can access its values by:
Specifying the key between [ ]:
self.cleaned_data[βfieldβ]
Using get() method:
self.cleaned_data.get(βfieldβ)
Difference between cleaned_data and cleaned_data.get in Django is that if the key does not exist in the dictionary, self.cleaned_data[βfieldβ] will raise a KeyError, while self.cleaned_data.get(βfieldβ) will return None.
A: .get() is basically a shortcut for getting an element out of a dictionary. I usually use .get() when I'm not certain if the entry in the dictionary will be there. For example:
>>> cleaned_data = {'username': "bob", 'password': "secret"}
>>> cleaned_data['username']
'bob'
>>> cleaned_data.get('username')
'bob'
>>> cleaned_data['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'foo'
>>> cleaned_data.get('foo') # No exception, just get nothing back.
>>> cleaned_data.get('foo', "Sane Default")
'Sane Default'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: how to bind the same event to checkboxes, dropdown select and multiple select components? there are checkboxes, dropdown select and multiple select components in my webform, I want that they bind the same event that will be triggered when items are check(unchecked) or selectd(unselected), show should do that? Is there a clever and neat way?
A: you can use the :input to target all the inputs, select, buttons on your site. and then bind the .change() event.
$(":input").bind("change", function() {
//What you want to happen
});
you can even bind more events like click depending on what oyu want to do:
$(":input").bind("change click", function() {
//What you want to happen
});
or if you want specific inputs:
$("input.special, select.myFormSelect, #username").bind("change click", function() {
//What you want to happen
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Enterprise library 5.0 logging block in asp.net? I have download the Enterprise library 5.0 in my PC from microsoft. i installed it. now i want to use only logging application block with asp.net application. ao what steps i need to follow? Or do i need to add reference of logging dll from installation location (programe files..\Enterprise Library 5.0) and directly use it ?
A: There are many steps to get it working, you have to add a configuration section to your web.config, you should check the enterprise library labs found here http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=6932, it is a walkthroughtfor configuring each of the enterprise library components
A: Look the these articles, they should answer your question.
*
*Get Logging with the Enterprise Library (this is one is a bit old)
*Logging via the Microsoft Enterprise Library
*How to use Logging Application Block in Enterprise Library 5.0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Interactive "screen" for WCF hosted in service I have a WCF Service that I already mention in another question here. As I have read here host WCF in Windows service is the best solution for all reasons. So that's why I select this option. But windows service hosting doesn't allow any visual process communication (before we used self-hosted service, that have hosted in console application and report any problems just into console). How can I get similar way for hosting service? My thoughts is about using another named pipes binding for visual "communication" between service and human.
I would be very nice for me if somebody recommend me something useful.
Thanks very much in advance guys!
A: In case you need the "Screen" just so that the service can report the problems, the I would suggest that you use windows event to log such events from the service and then you can create any UI/back ground process that can look for such events in window event log and report them appropriately (ex: sending email etc)
A: I tend to agree with @Ankur's answer, but figured I'd give you an alternative option. You could consider using WMI provide visual feedback to a running service. I attended an interesting ALT.NET talk on the subject (not WCF specific) a while back (full video is available here) and it should be relatively straightforward to instrument your application with WMI to allow you system state to be queried
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I add limits to a custom scrolling element? I have a pretty huge image being displayed in a container, the image stretches with the view port as it gets resized, but as the image is so big I have added scroller buttons to the side of the page, up and down, the only problem I have now is that when I press up or down there is no limit, the user can keep going until the image is completely out of sight, how can I stop that from happening?
Here is the code I have thus far,
HTML:
<body>
<div id="wrapper">
<div class="scroll top"></div>
<div id="content">
<div id="zoom_container">
<img id="image" src="8052x2000px" />
</div>
</div>
<div class="scroll bot"></div>
</div>
</body>
CSS:
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#wrapper {
overflow: hidden;
height: 100%;
max-height: 100%;
}
#content {
min-height: 100% !important;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#image {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
jQuery:
//side scroller bar
$('.scroll').live('click', function(){
var direction = $(this).hasClass('top');
var img_pos_top = $("#zoom_container img").position().top;
var inc = 0;
inc = $("#zoom_container img").height() / 10;
if(direction)
{
inc = $("#zoom_container img").position().top + inc;
}
else
{
inc = $("#zoom_container img").position().top - inc;
}
$("#zoom_container img").css({ position: 'relative',top: inc });
});
so as you can see I am incrementing or decrementing the top positioning of the image by 10% of it's height each click, how can I make sure the top of the image will never go further down than the top of the viewport and the bottom of the image never further up than the bottom of the viewport?
Is there a better more efficient way of achieving the same result?
A: Have a try this one.
<html>
<head>
<title>Canvas Sizing</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var canvasContext;
resizeCanvas();
$(window).resize(function() { resizeCanvas() });
function resizeCanvas()
{
var w = window.innerWidth - 40;
var h = window.innerHeight - 40;
var canvasString = '<canvas id="mainCanvas" width="' + w + '" height="' + h + '">Canvas is not supported</canvas>';
$('#contentholder').empty();
$(canvasString).appendTo('#contentholder');
canvasContext = $('#mainCanvas').get(0).getContext('2d');
drawOnCanvas();
}
function drawOnCanvas()
{
var x = 15;
var y = 35;
canvasContext.font = "30pt serif";
canvasContext.fillStyle="#0f0";
canvasContext.fillText("Hello World!", x, y);
}
});
</script>
<style>
#mainCanvas
{
background-color: #000;
border: solid 3px #0F0;
}
body
{
background: #000;
}
#contentholder
{
width: 99%;
height: 99%;
margin: auto;
}
</style
</head>
<body>
<div id="contentholder"></div>
</body>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: regex pattern not matching at start of the line I have this pattern:
/([^>'"])(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/
when using this as a subject:
http://www.google.com <a href="http://www.google.com">http://www.google.com</a> http://www.google.com
It matches the last http://www.google.com but not the first one at the start of the line. How can I get it to match the first one at the start of the line too? (and continue to not match inside the anchor tag)
A: It's because [^'">] means any one character that isn' ', " or >. There is no one character before the http at the start of the line, which is why it's not matching.
One possibility (not necessarily the best), is to use something like:
(([^'">])(http))|(^http)
(either of two possible patterns). This basically means to give me all those you currently specify as well as "http" at the start of the line.
I don't doubt there are trickier ways to do this with the more advanced regex features like look-ahead, negative look-behind or the little known surreptitious look-under (a), but I prefer simplicity most of the time.
(a) Some features alluded to in this answer may not, in fact, exist :-)
A: /(^|[^>'"])(http|ftp)+(s)?:(\/\/)((\w|\.)+)(\/)?(\S+)?/ will do it for you. ^ inside [] will negate the rest of the characters. You have to keep ^ at the starting of the regex and outside of [] to match the start of the line
A: try ([^'">])?(http) (untested)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: uncaught error NOT_FOUND_ERR DOM Exception 8 So I am deleting all the contents under a particular div and adding a message content. However, javascript throw the following error after the finish:
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
Here is the code where it is executed
new Ajax.Request("profileThis.php",
{
method:'post',
parameters:{title:title, review:review, userId:userId, category:category, categoryId:categoryId},
onSuccess:function(ajax)
{
alert(ajax.responseText); // this is just for debugging purposes
var message=ajax.responseText;
var divMessage=document.createElement("div");
divMessage.style.color="rgb:(105,105,105)";
divMessage.innerHTML=message;
while($("reviewSheet").hasChildNodes)
{
$("reviewSheet").removeChild($("reviewSheet").lastChild);
}
$("reviewSheet").adopt(divMessage);
},
onFailure:ajaxFailure,
onException:ajaxFailure
});
People commented that the problem was with how I assigned divMessage to reviewSheet. I tried both adopt and appendChild but none works.
A little help would be appreciated.
A: divMessage.style.color="rgb:(105,105,105)";
should be
divMessage.style.color="rgb(105,105,105)";
A: Is the problem that you are calling the method hasChildNodes() on a jQuery object? I'm not sure what $("reviewSheet") is supposed to be, but wrapping a string in $() makes it a jQuery object which I don't believe will work with regular javascript methods. If "reviewSheet" is the id of an element you could do something like
node = document.getElementById('reviewSheet');
then you could go into your while loop.
while (node.hasChildNodes()) {
//the rest of your code here
}
Oh also you need to put the parenthesis after hasChildNodes() to return a boolean value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: condition check for enter number would be betwen 0 to 9 0r decimal "." i have a edit text box in which i can enter alphanumeric charracter but when i click the summit button then a checking would be perform for either edit text contains values 0 to 9 and also it can contain "." and in other case it will show a message that "pls enter numeric values" so how to achive it?
means validate 0123456789 and "." in edit textbox
public void onClick(View arg0) {
String Ammount =
((EditText) findViewById(R.id.price))
.getText().toString();
double db = Math.ceil(Integer.parseInt(Ammount)*100)/100;
ammount = Double.toString(db);
}};
A: Why to go hard just don't allow to enter string in your xml add:
<EditText
....
android:inputType="numberDecimal"
...
/>
A: add this tag in its xml android:numeric = "decimal"
A: One of the option would be use regex. Show the error message when validate return false.
boolean validate(String s )
{
return s.matches("[0-9\\.]*");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When embedding CPython in Java, why does this hang? I'm embedding CPython into a JVM using Jepp, but when I run
import numpy; numpy.finfo(float)
the process hangs. gdb says something's blocking a semaphore/lock acquisition, and the stack trace suggests something floating point-related:
$ LD_PRELOAD=/usr/lib/libpython2.6.so gdb --args java -jar jepp.jar -i /tmp/go.py
GNU gdb (GDB) 7.1-ubuntu
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
Reading symbols from /usr/bin/java...(no debugging symbols found)...done.
(gdb) r
Starting program: /usr/bin/java -jar jepp.jar -i /tmp/go.py
[Thread debugging using libthread_db enabled]
process 20736 is executing new program: /usr/lib/jvm/java-6-sun-1.6.0.26/jre/bin/java
[Thread debugging using libthread_db enabled]
[New Thread 0x7ffff58fd700 (LWP 20739)]
[New Thread 0x7ffff16ca700 (LWP 20740)]
[New Thread 0x7ffff15c9700 (LWP 20741)]
[New Thread 0x7ffff14c8700 (LWP 20742)]
[New Thread 0x7ffff13c7700 (LWP 20743)]
[New Thread 0x7ffff0bf5700 (LWP 20744)]
[New Thread 0x7ffff0af4700 (LWP 20745)]
[New Thread 0x7ffff09f3700 (LWP 20746)]
[New Thread 0x7ffff08b3700 (LWP 20747)]
[New Thread 0x7ffff07b2700 (LWP 20748)]
[New Thread 0x7ffff06b1700 (LWP 20749)]
[New Thread 0x7ffff05b0700 (LWP 20750)]
[New Thread 0x7ffff04af700 (LWP 20751)]
>>> import numpy; numpy.finfo(float)
^C
Program received signal SIGINT, Interrupt.
0x00007ffff771703d in pthread_join () from /lib/libpthread.so.0
(gdb) bt
#0 0x00007ffff771703d in pthread_join () from /lib/libpthread.so.0
#1 0x000000004000591c in ContinueInNewThread ()
#2 0x0000000040001ef4 in main ()
(gdb) i threads
14 Thread 0x7ffff04af700 (LWP 20751) 0x00007ffff771abc9 in pthread_cond_timedwait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
13 Thread 0x7ffff05b0700 (LWP 20750) 0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
12 Thread 0x7ffff06b1700 (LWP 20749) 0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
11 Thread 0x7ffff07b2700 (LWP 20748) 0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
10 Thread 0x7ffff08b3700 (LWP 20747) 0x00007ffff771cb50 in sem_wait ()
from /lib/libpthread.so.0
9 Thread 0x7ffff09f3700 (LWP 20746) 0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
8 Thread 0x7ffff0af4700 (LWP 20745) 0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
7 Thread 0x7ffff0bf5700 (LWP 20744) 0x00007ffff771abc9 in pthread_cond_timedwait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
6 Thread 0x7ffff13c7700 (LWP 20743) 0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
5 Thread 0x7ffff14c8700 (LWP 20742) 0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
4 Thread 0x7ffff15c9700 (LWP 20741) 0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
3 Thread 0x7ffff16ca700 (LWP 20740) 0x00007ffff771a85c in pthread_cond_wait@@GLIBC_2.3.2 () from /lib/libpthread.so.0
2 Thread 0x7ffff58fd700 (LWP 20739) 0x00007ffff771cb50 in sem_wait ()
from /lib/libpthread.so.0
* 1 Thread 0x7ffff7ed8700 (LWP 20736) 0x00007ffff771703d in pthread_join ()
from /lib/libpthread.so.0
(gdb) thread 2
[Switching to thread 2 (Thread 0x7ffff58fd700 (LWP 20739))]#0 0x00007ffff771cb50 in sem_wait () from /lib/libpthread.so.0
(gdb) bt
#0 0x00007ffff771cb50 in sem_wait () from /lib/libpthread.so.0
#1 0x00007ffff7a4db28 in PyThread_acquire_lock ()
from /usr/lib/libpython2.6.so
#2 0x00007ffff7a1cbb4 in PyEval_RestoreThread () from /usr/lib/libpython2.6.so
#3 0x00007ffff7a41008 in PyGILState_Ensure () from /usr/lib/libpython2.6.so
#4 0x00007fffeb1e1ff6 in _error_handler (method=-334489136, errobj=0x80,
errtype=0x0, retstatus=-1, first=0x0)
at numpy/core/src/umath/ufunc_object.c:95
#5 0x00007fffeb1e2379 in PyUFunc_handlefperr (errmask=521,
errobj=0x7fffec502950, retstatus=4, first=0x7ffff58fa5fc)
at numpy/core/src/umath/ufunc_object.c:189
#6 0x00007fffeb1e7cd1 in PyUFunc_GenericFunction (self=<value optimized out>,
args=<value optimized out>, kwds=<value optimized out>, op=0x7ffff58faaa0)
at numpy/core/src/umath/ufunc_object.c:2734
#7 0x00007fffeb1e7ff0 in ufunc_generic_call (self=0x7fffec1df790,
args=<value optimized out>, kwds=<value optimized out>)
at numpy/core/src/umath/ufunc_object.c:4180
#8 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#9 0x00007ffff797ed9f in _PyObject_CallFunction_SizeT ()
from /usr/lib/libpython2.6.so
#10 0x00007ffff797c9aa in ?? () from /usr/lib/libpython2.6.so
#11 0x00007ffff797d698 in PyNumber_Multiply () from /usr/lib/libpython2.6.so
#12 0x00007ffff7a1f2bc in PyEval_EvalFrameEx () from /usr/lib/libpython2.6.so
#13 0x00007ffff7a22928 in PyEval_EvalFrameEx () from /usr/lib/libpython2.6.so
#14 0x00007ffff7a23d60 in PyEval_EvalCodeEx () from /usr/lib/libpython2.6.so
#15 0x00007ffff79a9d60 in ?? () from /usr/lib/libpython2.6.so
#16 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#17 0x00007ffff798dcef in ?? () from /usr/lib/libpython2.6.so
#18 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#19 0x00007ffff79e2cd0 in ?? () from /usr/lib/libpython2.6.so
#20 0x00007ffff79d8f98 in ?? () from /usr/lib/libpython2.6.so
#21 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#22 0x00007ffff7a21771 in PyEval_EvalFrameEx () from /usr/lib/libpython2.6.so
#23 0x00007ffff7a23d60 in PyEval_EvalCodeEx () from /usr/lib/libpython2.6.so
#24 0x00007ffff7a220ab in PyEval_EvalFrameEx () from /usr/lib/libpython2.6.so
#25 0x00007ffff7a23d60 in PyEval_EvalCodeEx () from /usr/lib/libpython2.6.so
#26 0x00007ffff79a9d60 in ?? () from /usr/lib/libpython2.6.so
#27 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#28 0x00007ffff79d928d in ?? () from /usr/lib/libpython2.6.so
#29 0x00007ffff79d8f53 in ?? () from /usr/lib/libpython2.6.so
#30 0x00007ffff797c2e3 in PyObject_Call () from /usr/lib/libpython2.6.so
#31 0x00007ffff7a21771 in PyEval_EvalFrameEx () from /usr/lib/libpython2.6.so
#32 0x00007ffff7a23d60 in PyEval_EvalCodeEx () from /usr/lib/libpython2.6.so
#33 0x00007ffff7a23e32 in PyEval_EvalCode () from /usr/lib/libpython2.6.so
#34 0x00007ffff7a41d1c in PyRun_StringFlags () from /usr/lib/libpython2.6.so
#35 0x00007ffff019d1e7 in pyembed_eval (env=0x401121d0,
_jepThread=140737154335376,
str=0x7fffec117390 "import numpy; numpy.finfo(float)") at pyembed.c:929
#36 0x00007ffff019c29a in Java_jep_Jep_eval (env=0x401121d0,
---Type <return> to continue, or q <return> to quit---
obj=<value optimized out>, tstate=140737154335376, jstr=0x7ffff58fbdf8)
at jep.c:137
#37 0x00007ffff1a67d6e in ?? ()
#38 0x0000000000000000 in ?? ()
(gdb) thr 10
[Switching to thread 10 (Thread 0x7ffff08b3700 (LWP 20747))]#0 0x00007ffff771cb50 in sem_wait () from /lib/libpthread.so.0
(gdb) bt
#0 0x00007ffff771cb50 in sem_wait () from /lib/libpthread.so.0
#1 0x00007ffff600eea5 in check_pending_signals(bool) ()
from /usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib/amd64/server/libjvm.so
#2 0x00007ffff600745c in signal_thread_entry(JavaThread*, Thread*) ()
from /usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib/amd64/server/libjvm.so
#3 0x00007ffff61170f1 in JavaThread::run() ()
from /usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib/amd64/server/libjvm.so
#4 0x00007ffff600eadf in java_start(Thread*) ()
from /usr/lib/jvm/java-6-sun-1.6.0.26/jre/lib/amd64/server/libjvm.so
#5 0x00007ffff77159ca in start_thread () from /lib/libpthread.so.0
#6 0x00007ffff726e70d in clone () from /lib/libc.so.6
#7 0x0000000000000000 in ?? ()
From delta debugging, it appears the following loop runs 9 times (should run max_iterN=10000 times), and then things halt on the temp = z*t line:
for _ in xrange(max_iterN):
y = z
z = y*y
a = z*one # Check here for underflow
temp = z*t
if any(a+a == zero) or any(abs(z)>=y):
break
temp1 = temp * betain
if any(temp1*beta == z):
break
i = i + 1
k = k + k
else:
print 'baz'
raise RuntimeError, msg % (_, one.dtype)
Any ideas? To fully reproduce:
mkdir /tmp/test/
cd /tmp/test/
wget 'http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/numpy-1.6.1.tar.gz'
tar xzf numpy-1.6.1.tar.gz
cd numpy-1.6.1/
python setup.py install --prefix=/tmp/test/env
cd
git clone https://github.com/mrj0/jepp.git
cd jepp/jep/
export JAVA_HOME=/usr/lib/jvm/java-6-sun/
./configure --prefix=/tmp/jepp && make && make install
touch /tmp/go.py
PYTHONPATH=/tmp/test/env/lib/python2.6/site-packages/
LD_PRELOAD=/usr/lib/libpython2.6.so java -jar jepp.jar -i /tmp/go.py
>>> import numpy
>>> numpy.finfo(float)
I've been able to reproduce this on my machines, which are Ubuntu x86_64 boxes. It's been a while but IIRC I don't experience this with the Ubuntu numpy package, only with a from-source build as instructed above.
Thanks in advance. This has been driving me up the wall.
A: See this post by John Wright who ran into the same problem: http://mail.scipy.org/pipermail/numpy-discussion/2009-July/044046.html
Basically, numpy is using the Python C api in a way that's incompatible with Jep. Jep uses sub interpreters to allow multiple interpreter environments. It could be possible to change Jep so that it uses the GIL state functions, but that would really limit Jep's functionality in Java.
A: Is there any particular reason you cant use Jython ? My understand is that is pretty much a real subsitute for the real thing.
A: If you have more than one thread calling into CPython, and one of those threads is "busy", then the global lock will probably be locked, and CPython has no choice except to hang until that lock is released.
What threads do you have calling into python - additionally - what is python doing in those threads?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Qt C++ QTouchEvent & TouchPoint Confusion Just trying to wrap my head around QTouchEvent. Any help/advice is appreciated.
Specifically I'm a bit confused when a touch event is fired (for e.g. TouchBegin); does this represent only one unique touch point? If so why is there a list of touch points inside QTouchEvent?
If not, is it the case that Qt will group together several TouchBegin instances that happen in a given time fraction and deliver it as one event, with the list of points encapsulated in the event? Likewise a QTouchUpdate event will contain information about several touch points that are being updated at that time?
Also I assume that;
QTouchEvent::TouchPoint::id
will remain consistent throughout TouchBegin, TouchUpdate and TouchEnd. Meaning that in different touch events if I see a point with the same id, it is the same touch point that both events are referring to. Is this assumption correct?
FYI: I've been working with TUIO for sometime, so if someone is familiar with both Qt and TUIO a comparative explanation would be much easier for me to understand. I've read through Qt documentation as well, but wasn't able to find an answer to my question.
Still I'd really appreciate any help at all.
Thank you.
A: How exactly the events are reported seem to differ in different platforms. If you press it with two fingers, it can start with a single touch point (TouchBegin), and immediately follow that with a new QTouchEvent with two TouchUpdate points. But it can also group two touch points into the TouchBegin QTouchEvent. But I have also witnessed two TouchBegin events, event though this is kind of forbidden (see "Touch Point Grouping" in the QTouchEvent doc).
After the begin, there are again differences in the TouchUpdates. Sometimes you always get two points (or the amount you have fingers down) even if you lift one finger. In this case the pressure is 0 for the lifted finger "id". Alternatively you'll get the amount of touchpoint ids that are actually down.
The best way to understand how these are generated is to install an eventfilter and observe the events while you press them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to fetch the current Location in every 1 min of interval? I have implemented the Demo to show the current lat-long of the User.
Now I am able to see the lat-long of the current Position.
but I want to Set it to to be displayed in every 1 min of interval.
The code is as below:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener lListener = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, lListener);
}
private class mylocationlistener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
Toast.makeText(MainActivity.this,
"My current location:\nLatitude:"+location.getLatitude() + "\nLogitude:" + location.getLongitude(),Toast.LENGTH_LONG).show();
}
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
So, What should I have to do to make it to display the current lat-long in every 1 min of interval?
I think I have to use the thread to implement it. How to make it possible?
A: lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, lListener);
The argument in the method signify - provider, time, distance and the location listener.
Therefore to request an update from the Location listener you need to set the second parameter to 1000*60, because the time is recorded in milliseconds.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why there are 2 () in a sub signature? Recently I asked a question and got a working answer. The code below is the working code. I have problem understand the Sub signature. Why there are two ()() for the sub. I mean I don't understand the first one (Of Algorithm As SymmetricAlgorithm). Obviously the second one is for the paramater. Can you point to me where I can read more about it?
Public Shared Sub DecryptTo(Of Algorithm As SymmetricAlgorithm)(sourceStream As Stream, stream As Stream, password As String)
Dim pdb = GetPassword(password)
Using alg = Activator.CreateInstance(Of Algorithm)()
Using trans = alg.CreateDecryptor(pdb.GetBytes(alg.KeySize / 8), pdb.GetBytes(16))
Using cStream = New CryptoStream(sourceStream, trans, CryptoStreamMode.Read)
cStream.CopyTo(stream)
End Using
End Using
End Using
End Sub
A: At http://msdn.microsoft.com/en-us/library/w256ka79(v=vs.80).aspx
one can find a description of Generics (which is the reason for the first set of parentheses).
It starts:
A generic type is a single programming element that adapts to perform
the same functionality for a variety of data types. When you define a
generic class or procedure, you do not have to define a separate
version for each data type for which you might want to perform that
functionality.
An analogy is a screwdriver set with removable heads. You inspect the
screw you need to turn and select the correct head for that screw
(slotted, crossed, starred). Once you insert the correct head in the
screwdriver handle, you perform the exact same function with the
screwdriver, namely turning the screw.
Screwdriver set as a generic tool
When you define a generic type, you parameterize it with one or more
data types. This allows the using code to tailor the data types to its
requirements. Your code can declare several different programming
elements from the generic element, each one acting on a different set
of data types. But the declared elements all perform the identical
logic, no matter what data types they are using.
For example, you might want to create and use a queue class that
operates on a specific data type such as String. You can declare such
a class from System.Collections.Generic.Queue, as the following
example shows.
VB Public stringQ As New System.Collections.Generic.Queue(Of String)
You can now use stringQ to work exclusively with String values.
Because stringQ is specific for String instead of being generalized
for Object values, you do not have late binding or type conversion.
This saves execution time and reduces run-time errors.
A: VB.NET uses parenthesis in several different ways:
*
*parameter section of method declaration or method calls (same as C#)
*declaring generics (equivalent of <> in C#)
*declaring and indexing arrays (equivalent of [] in C#)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Var vs IEnumerable when it comes to Entity Framework If I were to use IEnumerable instead of var in the code example below, will the SQL be generated only during the execution of the foreach statement? Or will it execute as an when the Linq statements are evaluated?
var query = db.Customers.Where (c => c.Age > 18);
query = query.Where (c => c.State == "CO");
var result = query.Select (c => c.Name);
foreach (string name in result) // Only now is the query executed!
Console.WriteLine (name);
Another example:
IEnumerable<Order> query = db.Orders.Where(o => o.Amount > 1000);
int orderCount = query.Count();
Would it be better to use var (or IQueryable) as it would be executed a select count(*)... when .Count() is executed or would it be exactly same with the IEnumerable code shown above?
A: It would make no difference. var is just syntactic sugar. If you hover over var, you will see what type C# thinks your query is.
From http://msdn.microsoft.com/en-us/library/bb383973.aspx
Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:
var i = 10; // implicitly typed
int i = 10; //explicitly typed
If you want to perform actions on your query that SQL wouldn't know what to do with, such as a method defined in your class, then you could use AsEnumerable().
For example:
var query = db.Customers
.Where(c => c.Age > 18)
.AsEnumerable()
.Select(c => GetCustomerViewModel());
//put definition of GetCustomerViewModel() somewhere in the same class
Update
As Omar mentioned, if you want your query to be executed immediately (rather than deferred), use ToList(). This will immediately enumerate the IQueryable/IEnumerable and fill the list with the actual data from the database.
A: Linq queries return IQueryable<> or IEnumerable<>, the execution of both is deferred.
As DanM stated, whether or not you use var or IEnumerable<> it all depends on the return value of the method you're calling: if it's an IEnumerable<> or IQuerable<> it'll be deferred, if you use .ToList(), it'll be executed right away.
When to use var comes down to personal choice/style. I generally use var when the return value is understood from the line of code and variable name or if I'm instantiating a generic with a long declartion, e.g. Dictionary<string, Func<Order, object>>.
From your code, it's clear that a collection of Customers/Orders is returned, so I would use the var keyword. Again, this is a matter of personal preference.
A: In general, the SQL is generated when GetEnumerator is called on the IQueryable.
In your example, there is a subtle difference that you may want to consider. Let's take your original example:
var query = db.Customers.Where (c => c.Age > 18);
query = query.Where (c => c.State == "CO");
var result = query.Select (c => c.Name);
In this case if you change your first query to IEnumerable query = ..., then the second line would use the IEnumerable version of the Where extension (LINQ to Objects) rather than the IQueryable one (LINQ to SQL/EF). As a result, when we start iterating, the first where clause is passed to the database, but the second where clause is performed on the client side (because it has already been converted to an IEnumerable).
Another subtle item you want to be aware of is the following type of code:
var query = db.OrderBy(c => c.State);
query = query.Customers.Where(c => c.Age > 18); // Fails: Widening
In this case, since your original query returns IOrderedQueryable rather than IQueryable. If you try to then assign query to the result of the .Where operation, you're trying to widen the scope of the return type and the compiler will refuse to perform that widening. As a result, you have to explicitly specify the baseline type rather than using var:
IQueryable<Customer> query = db.OrderBy(c => c.State); // Is narrowing rather than widening.
query = query.Customers.Where(c => c.Age > 18);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get a total count when also grouping in sql? I am attempting to get a COUNT for a mysql query. Its pretty simple:
SELECT COUNT(id) FROM table WHERE [insert rule here] GROUP BY grouper
The problem is because of that group by at the end, I end up getting a count of rows for each group, when I simply want a total.
Currently to do this I'll put the results in an array from a query that looks more like this:
$res = mysql_query(SELECT * FROM table WHERE [insert rule here] GROUP BY grouper)
$count = mysql_num_rows($res);
This works ok, but I'd just like to use COUNT.
How is this accomplished?
A: Add WITH ROLLUP after your group by statement: SELECT COUNT(id) FROM table WHERE [insert rule here] GROUP BY id WITH ROLLUP
A: at the risk of sounding stupid (or misinterpreting your question):
remove the group by clause?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Tool that will remove duplicate lines from a file? Is there a mac file comparison tool that can detect duplicates within a file? This is very close to what I'm looking for except it is for Windows: http://www.rlvision.com/dupli/about.asp. Also, I need to compare duplicate content across two files. If nothing else, I can just append file2 content to the bottom of file1.
A: I don't know of a GUI app to do it, but it's fairly easy at the terminal:
cat file1.txt file2.txt | sort | uniq -d
The -d will make it show only duplicate lines. If you just want the output without duplicates, just leave off the -d.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How do I escape CoffeeScript reserved words? I'm trying to run some unit tests using QUnit written in CoffeeScript but there seems to be some reserved words that are causing problems, most notably "not". Is there a way to escape a CoffeeScript reserved word? Here's a simple test that demonstrates the problem:
module "Sad face test"
test "will not compile", ->
not false, "holy crap this creates a syntax error :-("
The error this generates is "Parse error on line 3: Unexpected ','"
A: The best answer I have been able to find is to escape into JavaScript and alias the function:
notEqual = `not`
module "Sad face test"
test "will not compile", ->
notEqual false, "holy crap this creates a syntax error :-("
Although it looks like not isn't a function within the latest version of QUnit, so in this specific instance you may not need to to escape a CoffeeScript reserved word.
A: The not function is global, so it's actually attached to window, right? Instead of backtick escapes, then, you can just write
window.not
instead of not; or
notEqual = window.not
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Setting a value to a dictionary's dictionary value The code:
>>> mydict = {}
>>> keylist = ['a','b','c']
>>> mydict=dict.fromkeys(keylist,{})
>>> mydict['a']['sample'] = 1
>>> mydict
{'a': {'sample': 1}, 'c': {'sample': 1}, 'b': {'sample': 1}}
I was expecting mydict['a']['sample'] = 1 would set the value just for a's dictionary value and would get this: {'a': {'sample': 1}, 'c': {}, 'b': {}}.
What am I missing here? What should I have to do to get the expected output?
A: The problem is that you added the same dictionary to mydict for every key. You want to add different dictionaries, like so:
mydict = dict((key, {}) for key in keylist)
In the above code, you create a new dictionary to pair with each key. In your original code, the function fromkeys took the argument (the empty dictionary you provided) and added that exact argument - that single empty dictionary you created to pass in to the function - to each of the keys. When that one dictionary was changed, then, that change showed up everywhere.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: grails fails to build war Anyone has seen this issue before? What's the cause here?
Error executing script War: loader constraint violation in interface
itable initialization: when resolving method
"groovy.util.XmlParser.setDocumentLocator(Lorg/xml/sax/Locator;)V"
the class loader (instance of
org/codehaus/groovy/grails/cli/support/GrailsRootLoader) of the
current class, groovy/util/XmlParser, and the class loader (instance
of ) for interface org/xml/sax/ContentHandler have
different Class objects for the type org/xml/sax/Locator used in the
signature
at java.lang.Class.forName0(Native Method) at
java.lang.Class.forName(Class.java:169) at
_GrailsWar_groovy$_run_closure4.class$(_GrailsWar_groovy) at
_GrailsWar_groovy$_run_closure4.$get$$class$groovy$util$XmlParser(_GrailsWar_groovy)
at _GrailsWar_groovy$_run_closure4.doCall(_GrailsWar_groovy:186) at
War$_run_closure1.doCall(War.groovy:38) at
gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381) at
gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415) at
gant.Gant$_dispatch_closure7.doCall(Gant.groovy) at
gant.Gant.withBuildListeners(Gant.groovy:427) at
gant.Gant.this$2$withBuildListeners(Gant.groovy) at
gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source) at
gant.Gant.dispatch(Gant.groovy:415) at
gant.Gant.this$2$dispatch(Gant.groovy) at
gant.Gant.invokeMethod(Gant.groovy) at
gant.Gant.executeTargets(Gant.groovy:590) at
gant.Gant.executeTargets(Gant.groovy:589)
EDIT: As answered by Tim and Peter below this issue is a typical xml-api lib getting in the way of classloader. After removing it from the ivy cache dir i was able to run the dependency-report and clearly see it being pulled in by hibernate->dom4j->xml-api . I ran the same report on another machine with the same code base and did not see this dependency being pulled in. So I am still trying to figure out what caused this issue in the first place. The quick fix for me was to add the following in the BuildConfig
inherits("global") {
excludes ( "xml-apis", "commons-digester")
}
A: Sounds like something has pulled the xml-apis module into your classpath.
GroovyWS is sometimes the culprit. Have you added anything to the dependencies recently?
I assume the project used to work...so it must be something someone has added recently
Looking back through your source control might help you see what it is...
Or it could be something someone stuck in JAVA_HOME/lib/ext?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: if statement should print string values How do I print result from if statements in Java? This result should be assigned to some variable, that variable should print result in string. Currently, my code is like this. I want to store simple & extended into a single variable, so that i should able to call this variable anywhere in the program. There it should print "simple" or "extended".
if(loc[i]==1) {
System.out.println("simple");
}
else if(loc[i]>1) {
System.out.println("extended");
}
A: You mean like this:
String mode;
if(loc[i]==1)
mode = "simple";
else if(loc[i]>1)
mode = "extended";
else
mode = "error";
System.out.println(mode);
A: String type;
if( loc[i] == 1 )
{
type = "simple";
}
else if( loc[i] > 1)
{
type = "extended";
}
else
{
type = null;
}
// variable 'type' can now be used in the same block of code
System.out.println( type );
If you want to use this variable anywhere in your program, you will have to either declare the variable at a higher scope to be accessible or return this variable from this code block.
A: If I understood you correctly you need following
private static final SIMPLE_STRING = "simple";
private static final EXTENDED_STRING = "extended";
if(loc[i]==1) {
System.out.println(SIMPLE_STRING );
}
else if(loc[i]>1) {
System.out.println(EXTENDED_STRING );
}
A: How about
String s = (loc[i]==1 ? "simple" : (loc[i]>1 ? "extended" : null));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Exporting sounds as WAV files I never worked too much with sounds in Mma.
I have
t = Sound[List["Violin",SoundNote[-6]]]
How could I Export t as a .WAV file?
When I try the obvious
Export["c:\\test.wav",t]
I get
In this old thread Szabolcs said that it can't be done. Perhaps things have improved since 2007!
A: I think that it still can't be done. Mathematica supports creating and modifying MIDI objects, but leaves the sound generation from the midi to the underlying operating system. For now, you'll have to export to midi then use the midi interface on your system or an online service to convert to a sampled sound format.
For example (from the documentation)
t = Sound[SoundNote[DeleteCases[3 Range[31] Reverse[#], 0] - 48, .1] & /@
Transpose[CellularAutomaton[90, {{1}, 0}, 30]]]
Export["test.mid", t]
Uploaded to http://free-midi-converter.com/Midi/Create gives the link.
It can also be converted with TiMidity which is available on all major operating systems with the command (assuming you've run the above)
Run["timidity test.mid -Ow -o test.wav"]
which can be imported back into Mathematica using Import["test.wav"].
This conversion can be automated if need be...
Apparently VLC can also convert midi to wav, which might be an easier option for some propriety operating systems! See also the options given here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to validate edittext with integers in android? I want to have an edittext that only accepts numbers as input and when a button is clicked I want to check that the edittext has got a number inside and is not empty. Thanks.
A: try this in layout.xml
<EditText android:numeric="integer" ..../>
in Code
EditText mNumber = (EditText)findViewById(R.id....);
onButtonClick
if(mNumber.getText().toString().length()>0)
//logic
else
//empty Editext
A: Call EditText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
This will make sure that numeric virtual keypad will appear, and special filtering will be applied to only allow only numbers to be entered.
To check empty text, call
EditText.getText().length() != 0
A: Instead of validating you can add a (inpuType = "number") attribute in your xml file (Under the editText) after which you'll be able to add only numbers in your editText.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Objective C: Returning Objects from Methods I'm learning how to program, and starting off with Objective C. I'm trying to understand exactly what happens when an object is allocated from within a method.
-(Fraction *) add: (Fraction *) f
{ //'result' will store the result of the addition
Fraction *result = [[Fraction alloc]init];
result.numerator = (numerator*f.denominator + denominator*f.numerator);
result.denominator = denominator*f.denominator;
[result reduce];
return result;
}
I understand that I can create an object to store 'result' in when it is returned,
tempStorageObject = [aFraction add: bFraction];
and that i am then responsible for releasing it, but what happens when I don't store it, as in:
[aFraction add: bFraction];
NSLog(@"%i/%i", result.numerator, result.denominator); //result object not declared in main
I am told that I have an undeclared identifier. I get that, but what exactly happens to 'result' after using my 'add' method. Where does it go? Shouldn't I be able to access its variables since it was created and returned in the method? Obviously not, but I'm not clear on why. I've tried re-reading my book and searching this forum but I can't find a clear answer. Thanks. (First post)
A: Four different things:
*
*Properties
*Local variables
*Function return values
*Heap storage
"I get that, but what exactly happens to 'result' after using my 'add' method. Where does it go?"
It's a local variable. It's gone.
"Shouldn't I be able to access its variables"
Seeing your comment, it looks like you mean access by dot notation. No, dot notation is for properties.
"since it was created"
Dot notation does not give you access to local variables.
"and returned in the method?"
Dot notation does not give you access to function return values.
All of the first three things are pointers, when they refer to objects. The fourth thing is what they point to. When you do alloc, you create an object in heap storage. You then have instance variables, properties, local variables, and function return values refer to the heap storage. In a way you think of them as being the same thing as the object in heap storage. Syntactic sugar like dot notation helps you do that. Your object will last, but in this case the different variables that refer to it are limited in scope and come and go.
*
*When you call alloc, an object is created on the heap.
*When you assign it to result, result now has the same object.
*When you return result, the local variable result no longer exists, the return value temporarily holds the same object, and the object still exists in the heap.
4a. When you assign the function result to tempStorageObject, another local variable (I guess), the function result goes away. It existed only temporarily to pass a value from inside the function to out. tempStorageObject now holds the object, and the object still exists in the heap.
4b. Instead if you don't assign the function result to anything, then the function result still goes away. But the object still exists on the heap. You have a problem. You have an object on the heap, but you can't refer to it directly there (unless you are good at guessing its address). Without being able to refer to it, you can't get it off the heap, which will be a major problem if you do that kind of thing over and over. The heap will start to get full with objects you can't get rid of and you'll run out of memory. That's what's called a leak.
The correct thing to do in this case is to return [result autorelease]. When you call [something autorelease], it adds "something" to an "autorelease pool" and then returns the same something.
*
*You call alloc and create an object on the heap. Its retain count starts at 1.
*You assign it to result, a local variable. Result has the object and it's on the heap.
*[result autorelease]. result has the object, it's in an autorelease pool, and it's on the heap.
*return that. result is gone, the return value has the object, it's in the autorelease pool, and it's on the heap.
5a. Assign the return value to tempStorageObject. The return value is gone, tempStorageObject has the object, it's in an autorelease pool, and it's on the heap.
6a. You leave the scope of tempStorageObject. tempStorage object is gone. The object is in an autorelease pool and on the heap.
5b. You don't assign the function result to anything. The function result is gone. The object is in an autorelease pool and on the heap.
7ab. The autorelease pool is drained. That is usually done from code in the main run loop provided by the system library, but you can do it yourself if you know how. All the objects in the autorelease pool, including the one we're paying attention to, are sent a release message. The object's retain count goes to 0.
8ab. With a retain count of 0, the object is removed from the heap. The object is in the autorelease pool.
9ab. The second thing drain does is remove all the objects from the pool. Now the object doesn't exist anywhere anymore.
A: You said you are familiar with release, so I just say you should use autorelease keyword, which releases the allocated object when no more code blocks need it, check document below, from Apple:
Memory Management Programming
A: The scope of alloc is global: once you have allocated an object, there is room for it in memory and that memory will remain allocated until the release count hits zero (or the app is terminated). Until then, the object will still exist.
The scope of a variable is much shorter. In your example 'result' goes out of scope right at the end of the method 'add'. But that variable is just a name, a reference to an object. So whoever is calling add, should make sure to do something with the returned object. Otherwise there is no more variable referring to the object and so it can not be released.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Tab Page Error: The requested method GET is not allowed I have just set up a custom tab on my page for the first time. I have thoroughly followed the setup guide and seem to have everything on the Facebook side setup correctly.
However when I view my page it throws the following error:
Method Not Allowed The requested method GET is not allowed for the
URL /Facebook/index.html. Additionally, a 404 Not Found error was
encountered while trying to use an ErrorDocument to handle the
request. Apache/1.3.41 Server at feebnaturals.com.au Port 80
I believe it may be some kind of Apache server config issue, however I'm not that Apache savvy, so not sure where to start.
A: I had the same problem, but instead of GET, it was POST method which was not allowed. This is a setting on your server. Not server savvy myself, but it seems that my provider didn't allow this method on html-page, but makes no problem on doing the same for php-pages. So all I did was rename my page from .html to .php, updated the app settings in facebook and all works fine now.
A: This is definitely an error on your side, check your server logs and see what they say - it looks like you've configured the page to only work via a POST request and it's being requested in a GET request
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the proper DateTime format to get "both" date and time in MySQL and C# In a MySQL table, I need to have two fields "StartTime" and "EndTime". My requirements are:
*
*If I do StartTime - EndTime, I need to get the time elapsed (when I subtract them I need to get time in seconds or minutes or whatever).
*From "StartTime" I need to get the date (the date when my object was started).
So my question is in what format (or what type) should the fields "StartTime" and "EndTime" be in my MySQL table to meet the above two conditions? Also to which format in C# should I be retrieving the value from MySQL table?
A: Generally in MySql the DateTime will be in 'YYYY-MM-DD HH:MM:SS' format. Refer to this to get the Required.
A: MySQL offers two very similar data types DATETIME and TIMESTAMP. For many applications, either will work, but in some cases, one works better than the other...
http://dev.mysql.com/doc/refman/5.0/en/timestamp.html
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
in general if you can use TIMESTAMP you should, as it is more
space-efficient than DATETIME (it takes half the size of DATETIME).
here is a link to all the possible operations on the date type
http://dev.mysql.com/doc/refman/4.1/en/date-and-time-functions.html
A: In c# you should use DateTime. I believe the mySQL equivalent is TimeStamp.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is pass-by-value a reasonable default in C++11? In traditional C++, passing by value into functions and methods is slow for large objects, and is generally frowned upon. Instead, C++ programmers tend to pass references around, which is faster, but which introduces all sorts of complicated questions around ownership and especially around memory management (in the event that the object is heap-allocated)
Now, in C++11, we have Rvalue references and move constructors, which mean that it's possible to implement a large object (like an std::vector) that's cheap to pass by value into and out of a function.
So, does this mean that the default should be to pass by value for instances of types such as std::vector and std::string? What about for custom objects? What's the new best practice?
A: In almost all cases, your semantics should be either:
bar(foo f); // want to obtain a copy of f
bar(const foo& f); // want to read f
bar(foo& f); // want to modify f
All other signatures should be used only sparingly, and with good justification. The compiler will now pretty much always work these out in the most efficient way. You can just get on with writing your code!
A: It's a reasonable default if you need to make a copy inside the body. This is what Dave Abrahams is advocating:
Guideline: Donβt copy your function arguments. Instead, pass them by value and let the compiler do the copying.
In code this means don't do this:
void foo(T const& t)
{
auto copy = t;
// ...
}
but do this:
void foo(T t)
{
// ...
}
which has the advantage that the caller can use foo like so:
T lval;
foo(lval); // copy from lvalue
foo(T {}); // (potential) move from prvalue
foo(std::move(lval)); // (potential) move from xvalue
and only minimal work is done. You'd need two overloads to do the same with references, void foo(T const&); and void foo(T&&);.
With that in mind, I now wrote my valued constructors as such:
class T {
U u;
V v;
public:
T(U u, V v)
: u(std::move(u))
, v(std::move(v))
{}
};
Otherwise, passing by reference to const still is reasonable.
A: Pass parameters by value if inside the function body you need a copy of the object or only need to move the object. Pass by const& if you only need non-mutating access to the object.
Object copy example:
void copy_antipattern(T const& t) { // (Don't do this.)
auto copy = t;
t.some_mutating_function();
}
void copy_pattern(T t) { // (Do this instead.)
t.some_mutating_function();
}
Object move example:
std::vector<T> v;
void move_antipattern(T const& t) {
v.push_back(t);
}
void move_pattern(T t) {
v.push_back(std::move(t));
}
Non-mutating access example:
void read_pattern(T const& t) {
t.some_const_function();
}
For rationale, see these blog posts by Dave Abrahams and Xiang Fan.
A: The signature of a function should reflect it's intended use. Readability is important, also for the optimizer.
This is the best precondition for an optimizer to create fastest code - in theory at least and if not in reality then in a few years reality.
Performance considerations are very often overrated in the context of parameter passing. Perfect forwarding is an example. Functions like emplace_back are mostly very short and inlined anyway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "145"
}
|
Q: Make jqZoom Evolution's zoom box follow my mouse cursor I am using jqZoom Evolution to implement zoom functionality on my site, the problem is that it does not have the functionality for the zoom box to follow my mouse pointer around as I hover over a image, I have tried using mousemove to make it follow the cursor around, but every time I resize the browser the box moves further away from the cursor,
$("#single_main_container").mousemove(function(e){
$(".zoomWindow").css({
top: e.pageY,
left: e.pageX
});
});
so basically I just need the zoom box to follow my mouse cursor around when I hover over the image.
A: its not following your cursor?
but the 1st demo is showing zoom as you move your mouse
http://www.mind-projects.it/projects/jqzoom/demos.php#demo1
Edit
not exactly a solution but an alternative plugin which provides mouseover zoom out-of-box
http://redeyeoperations.com/plugins/zoomy/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Issue converting JSON to HashMap in Android I have JSONArray and when I decode JSON to HashMap at that time HashMap take last value of JSONArray.
here my code:
QjArray = new JSONArray(Questionresult);
JSONObject json_data = new JSONObject();
for (int i = 0; i<QjArray.length(); i++) {
objJMap = new HashMap<String, String>();
json_data = QjArray.getJSONObject(i);
jQuestionName =json_data.getString("QuestionName");
objJMap.put("QuestionName",jQuestionName);
jQuestiontypeid = json_data.getInt("Questiontypeid");
String Qid = jQuestiontypeid.toString();
objJMap.put("Questiontypeid", Qid);
jAnswertypeid = json_data.getInt("Answertypeid");
String Aid = jAnswertypeid.toString();
objJMap.put("Answertypeid", Aid);
}
My JSONArray:
This is question list[{"QuestionID":"1","QuestionName":"when you come","Questiontypeid":"1","Answertypeid":"1"},{"QuestionID":"2","QuestionName":"about your words","Questiontypeid":"1","Answertypeid":"2"},{"QuestionID":"3","QuestionName":"you want extra service?","Questiontypeid":"1","Answertypeid":"3"},{"QuestionID":"4","QuestionName":"performance of quality ?","Questiontypeid":"1","Answertypeid":"4"},{"QuestionID":"5","QuestionName":"performance of staff?","Questiontypeid":"1","Answertypeid":"5"},{"QuestionID":"6","QuestionName":"when you left room ?","Questiontypeid":"2","Answertypeid":"1"},{"QuestionID":"7","QuestionName":"your words about roomservice ?","Questiontypeid":"2","Answertypeid":"2"},{"QuestionID":"8","QuestionName":"you like roomservice ?","Questiontypeid":"2","Answertypeid":"3"},{"QuestionID":"9","QuestionName":"performance room service ?","Questiontypeid":"2","Answertypeid":"4"},{"QuestionID":"10","QuestionName":"performance room service staff?","Questiontypeid":"2","Answertypeid":"5"}]
A: This is because your code re initializes the HashMap after every loop.
for (int i = 0; i<QjArray.length(); i++) {
objJMap = new HashMap<String, String>();
....
}
Place the HashMap outside the loop and it will work fine.
objJMap = new HashMap<String, String>();
for (int i = 0; i<QjArray.length(); i++) {
....
}
A: I think there are certain problems in your logic. For every JSON object u are creating new HashMap object inside for loop, so u will loose any previous data. Also HashMap will override new Data, so you will have only final data. What u can do is that create an arrayList of Hashmap....
ArrayList<HashMap<String, String>> data = new ArrayList<HashMap<STring, String>>();
for (int i = 0; i<QjArray.length(); i++) {
objJMap = new HashMap<String, String>();
........
data.add(objJMap);
...}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to find all objects with ids from one number to another in Rails? What query should I use to find all the objects with an id from one number to another. For example, let's say I wanted to find all objects with a primary key from 10 to 20 (between 9 and 21). How would I do this in Rails?
Would this work? Object.where(:id => (10)..(20))
A: Use a range:
MyModel.where(:id => (10..20))
A: This would also work:
Model.limit(11).offset(9)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can having many files in a folder affect performances? I've got an application that's going to generate about 20,000 files. To keep it simple, I'm thinking about putting all these files in the same folder. Am I likely to run into some performance issues doing so? My software is for Windows XP, Vista, Seven and Mac OS X.
Any idea?
A: I know that Doxygen has a feature to break the generated files up into multiple directories because of slowness in access files in large directories under Windows. I don't know if this is just FAT or NTFS or both.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery Form Validation - Cross Browser Compatibility So I have built this form validation using jQuery and it works perfectly in Chrome, and fails miserably in IE and FF. The page just continues to load upon submission in IE and FF.
I can't find a worthy explanation as to why, or how to fix it.
Any suggestions would be much appreciated....
I'd also like to know how to validate the checkbox field using jQuery rules & messages, if this is possible. Cannot find any info on this in the jQuery documentation.
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script type="text/javascript">
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#successForm").validate({
rules: {
firstName: {
required: true,
minlength: 2,
},
lastName: {
required: true,
minlength: 2,
},
phoneNumber: {
required: true,
minlength: 10,
},
emailAddress: {
required: true,
email: true,
},
attachOne: {
required: true,
accept: "png|jpg|gif|jpeg|tif",
},
attachTwo: {
required: true,
accept: "png|jpg|gif|jpeg|tif",
},
termsAgree: {
required: true,
minlength: 1,
},
},
messages: {
firstName: {
required: "Please enter your First Name.",
minlength: jQuery.format("You need to use at least {0} characters for your first name."),
},
lastName: {
required: "Please enter your Last Name.",
minlength: jQuery.format("You need to use at least {0} characters for your last name"),
},
phoneNumber: {
required: "Please enter your Phone Number.",
minlength: jQuery.format("Please enter a valid phone number."),
},
emailAddress: {
required: "Please enter your Email Address.",
minlength: jQuery.format("Please enter a valid email address."),
},
dateOfBirth: {
required: "Please enter your Date of Birth.",
minlength: jQuery.format("Please enter the date in the format DD-MM-YYYY."),
},
termsAgree: "You must agree to the Terms and Conditions.",
}
});
});
</script>
<style type="text/css">
input.error { border: 1px solid red; }
label.error {background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/unchecked.gif') no-repeat;
padding-left: 16px;
margin-left: .3em;
}
label.valid {background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
display: block;
width: 16px;
height: 16px;
}
</style>
<form action="<?=$_SERVER['PHP_SELF'];?>" enctype="multipart/form-data" id="successForm"><table style="padding: 6px;">
<tr>
<td><label for="firstName">First Name</label></td>
<td><input type="text" id="firstName" name="firstName" class="InputSuccess" value="<?=stripslashes(htmlspecialchars($firstName));?>" /></td>
</tr>
<tr>
<td><label for="lastName">Last Name</label></td>
<td><input type="text" id="lastName" name="lastName" class="InputSuccess" value="<?=stripslashes(htmlspecialchars($lastName));?>" /></td>
</tr>
<tr>
<td><label for="phoneNumber">Phone Number</label></td>
<td><input type="text" id="phoneNumber" name="phoneNumber" class="InputSuccess" value="<?=stripslashes(htmlspecialchars($phoneNumber));?>" /></td>
</tr>
<tr>
<td><label for="emailAddress">Email Address</label></td>
<td><input type="text" id="emailAddress" name="emailAddress" class="InputSuccess" value="<?=stripslashes(htmlspecialchars($emailAddress));?>" /></td>
</tr>
<tr>
<td><label for="dateOfBirth">Date of Birth</label></td>
<td><input type="text" id="dateOfBirth" name="dateOfBirth" class="InputSuccess" value="<?=stripslashes(htmlspecialchars($dateOfBirth));?>" /></td>
</tr>
<tr>
<td><label for="successStory">Your Success Story</label></td>
<td><textarea id="successStory" name="successStory" cols="50" rows="6"></textarea></td>
</tr>
<tr>
<td colspan="2" style="margin-top:20px; margin-bottom: 5px; border: 1px solid #666; color:#666; width:300px;"><b>Please attach some photos of your success.</b><br /><span style="font-size:8pt;">Accepted File Types: jpg, jpeg, gif, png, tif<br />Maximum File Size: 2 megabytes</span>
<table style="border: 0px;">
<tr>
<td style="width:150px;"><label for="attachOne">Attachment 1</label></td>
<td><input type="file" id="attach[0]" name="attachOne" /></td>
</tr>
<tr>
<td style="width:150px;"><label for="attachOne">Attachment 2</label></td>
<td><input type="file" id="attach[1]" name="attachOne" /></td>
</tr>
</table>
</td>
</tr>
<tr>
<td><label for="termsConditions">Terms & Conditions</label></td>
<td><textarea id="termsConditions" name="termsConditions" cols="50" rows="6">Terms and Conditions...</textarea></td>
</tr>
<tr>
<td><label for="termsAgree"> </label></td>
<td><input type="checkbox" id="termsAgree" name="termsAgree" />I have read and agree to the Terms and Conditions.</td>
</tr>
<tr>
<td colspan="2" style="text-align: center;"><input type="submit" value="Validate!" /><input type="reset" value="Reset!" /></td>
</tr>
</table>
</form>
Thanks for your help. Unfortunately though, that did not work. I might be misinterpreting your code, but here's what I've got.
<script type="text/javascript">
function validateForm() {
if ($(".required").valid() == 0) {
alert("failed!");
return false;
}
else {
alert("success!");
return true;
}
}
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$(document).ready(function(){
$("#successForm").validate({
rules: {
firstName: {
required: true,
minlength: 2,
},
lastName: {
required: true,
minlength: 2,
},
phoneNumber: {
required: true,
minlength: 10,
},
emailAddress: {
required: true,
email: true,
},
attachOne: {
required: true,
accept: "png|jpg|gif|jpeg|tif",
},
attachTwo: {
required: true,
accept: "png|jpg|gif|jpeg|tif",
},
termsAgree: {
required: true,
minlength: 1,
},
},
messages: {
firstName: {
required: "Please enter your First Name.",
minlength: jQuery.format("You need to use at least {0} characters for your first name."),
},
lastName: {
required: "Please enter your Last Name.",
minlength: jQuery.format("You need to use at least {0} characters for your last name"),
},
phoneNumber: {
required: "Please enter your Phone Number.",
minlength: jQuery.format("Please enter a valid phone number."),
},
emailAddress: {
required: "Please enter your Email Address.",
minlength: jQuery.format("Please enter a valid email address."),
},
dateOfBirth: {
required: "Please enter your Date of Birth.",
minlength: jQuery.format("Please enter the date in the format DD-MM-YYYY."),
},
termsAgree: "You must agree to the Terms and Conditions.",
}
});
});
</script>
I don't appear to get an alert showing up in Chrome, FF or IE. I have tried onsubmit= from and onclick= from . Neither worked.
A: i had the same issue the other day
jQuery Validation always returns true
i solved by doing something like this;
function validateForm() {
if ($(".required").valid() == 0)
return false;
else
return true;
}
I call validateForm from my submit button.
onclick="return validateForm()"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iPhone:Add & Delete Row in UITableview with editing mode What I want to do is:
*
*Setting editing mode on NavigationBar in UITableView adds an edit button on the left side of the UINavigationBar. When I click this button, I'd like an add button to appear on the right side of the NavigationBar.
*When I click on the add button, add a row to the NSMutableArray and update the table.
So please give me ideas, code, or links to develop this functionality.
A: - (IBAction)DeleteButtonAction:(id)sender
{
[arry removeLastObject];
[Table reloadData];
}
- (IBAction) EditTable:(id)sender
{
if(self.editing)
{
[super setEditing:NO animated:NO];
[Table setEditing:NO animated:NO];
[Table reloadData];
[self.navigationItem.leftBarButtonItem setTitle:@"Edit"];
[self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStylePlain];
}
else
{
[super setEditing:YES animated:YES];
[Table setEditing:YES animated:YES];
[Table reloadData];
[self.navigationItem.leftBarButtonItem setTitle:@"Done"];
[self.navigationItem.leftBarButtonItem setStyle:UIBarButtonItemStyleDone];
}
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)aTableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (self.editing == NO || !indexPath) return UITableViewCellEditingStyleNone;
if (self.editing && indexPath.row == ([arry count]))
{
return UITableViewCellEditingStyleInsert;
} else
{
return UITableViewCellEditingStyleDelete;
}
return UITableViewCellEditingStyleNone;
}
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[arry removeObjectAtIndex:indexPath.row];
[Table reloadData];
} else if (editingStyle == UITableViewCellEditingStyleInsert)
{
[arry insertObject:@"Tutorial" atIndex:[arry count]];
[Table reloadData];
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath
{
NSString *item = [[arry objectAtIndex:fromIndexPath.row] retain];
[arry removeObject:item];
[arry insertObject:item atIndex:toIndexPath.row];
[item release];
}
}
A: Create a private property to have a reference to the Edit button:
@property (nonatomic) UIBarButtonItem *editButton;
In viewDidLoad:, init the button and assign it to the right button of the navigationItem:
self.editButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Edit", nil) style:UIBarButtonItemStylePlain target:self action:@selector(toggleEdit:)];
self.navigationItem.rightBarButtonItem = self.editButton;
Create a method to invoke when the Edit button is tapped. Will change the table's editing mode and update the Edit button title:
- (IBAction)toggleEdit:(id)sender {
[self.myTableView setEditing:!self.myTableView.editing animated: YES];
[self.editButton setTitle:self.myTableView.editing ? NSLocalizedString(@"Done", nil) : NSLocalizedString(@"Edit", nil)];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Entity CRUD w/ OneToMany and orphanRemoval I am building some CRUD forms for a web application. I have one entity, lets say Part, that has its own fields (sku, price, etc) as well as a link to other entities via @OneToMany. The way I have laid out my CRUD interface is that the part data points are edited on one form, and the related data points are edited in a separate form (on a different tab).
When I submit the Part form it will POST the part ID, price, sku, etc, but none of the related data. When Spring does its data binding, it will call the no-argument constructor on my Part class, then call setPrice, setId, setSku, etc. Nothing is posted for the related entities since they are on a separate form. The part object provided to me by Spring is then merged using JPA.
The problem is that I use cascade = ALL, orphanRemoval = true on the OneToMany relationships. All these relationships are deleted because they are blank in the data-binder-generated part object. Possible solutions:
*
*Can I have Spring somehow pull the Part from JPA instead of calling the no-arg constructor?
*Take the data-binder-generated object and copy all of the part attributes to an object pulled from the database
*Do not use data binding; pull parameters out of the servlet request
Obviously the first one is the most preferred; is there a way to accomplish this? How have you dealed with similar situations?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: android problem with thread I am working with a drawing application. ON A CANVAS i able to draw something as free hand.
What i am doing here, i just store the paths in a List<path> and drawing on canvas synchronized by a thread.
when i am starting to draw for 1st time it is so smooth and speed also, but as paths are increased List<Path> size also increased so it becomes so slow , so terrible.
if i clear the List then again it becomes smoother.
But i want for every time it should be smoother. How can i do it?
IS there any way?
Thank you
A: I think if you are using invalidate to refresh the screen on a View, only invalidate the area where you drew the new line. So the system will not keep drawing everything. Other option is you handle the event and you keep one list for your undo redo purposes and another smaller detailed list for actual drawing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make the JS function get the data from the database everytime I call it? I am using a code look like this:
<script>
function getdata()
{
var employee =
<?php
//connect to database and get employee name
echo "'" . $row['empnm'] "'";
?>;
}
</script>
<a href="#" onclick="getdata();">print them</a>
It works, but the function is running the PHP code only on the page loading and not every time I call the function. So, if the target employee name is changed the JS function will show the old name untill the page is reloaded. How to make the JS function get the data from the database everytime I call it?
A: look into a library like jQuery
Then using the following code
function getdata(){
$.post("path/to/file.php", function(data) {
var employee = data;
// do whatever with the data.
});
}
and you can still use your same html
<a href="#" onclick="getdata();">print them</a>
and file.php
<?php
// connect to your db, get your results, echo them back
echo $row['empnm'];
?>
A: When you first request the page, PHP renders out a whole string of html, then your browser executes that generated HTML, not the original PHP. i.e. your server is going to send something like
<script>
function getdata()
{
var employee =
"hello world";
}
</script>
<a href="#" onclick="getdata();">print them</a>
So, as far as the web browser knows, "hello world" is just hardcoded there.
You'll need to look into AJAX for how to make it work. Check out this beginners' tutorial on using jQuery for ajax: http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
A: Define a global variable
<script>
var employee = <?php echo "'" . $row['empnm'] "'";?>;
function getdata(){
return employee;
}
</script>
Now keep on changing variable employee whenever it is changed
<a href="#" onclick="getdata();">print them</a>
A: If you're in a PHP loop -- it does looks like you are, since -- you can use PHP to define the parameter to be passed into getdata() in your loop; e.g.
<script type="text/javascript">
function getdata(employee) {
// connect to database and get employee name
}
</script>
<?php
foreach ($loopData as $row) {
print '<a href="#" onclick="getdata(' . $row['empnm'] . ');">print them</a>';
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Custom ReferenceID property for buttons and menu classes For ASP controls - let us say we are using button, is it possible to derive from BUTTON, a derived control and create new property called, say , ReferenceID (type say integer) and use that property.
I would like to have a unique id for the control other than the ID we are having
A: Yes, it is possible and the way you are thinking about it will work but keep in mind that you will have to keep track of the values assigned to this property in ViewState. What I mean is this (untested code):
public class CustomButtom : Button
{
public int ReferenceID {
get {
if(ViewState["ReferenceID"]!=null)
return int.Parse(ViewState["ReferenceID"].ToString());
return -1;
}
set {
ViewState["ReferenceID"]=value;
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android - How to finish button if using setVisibility I have buttons and they all finish to go to the next activity.
But I'm trying to finish an button that has setVisibility like example code below.
Button failfiveButton = (Button)findViewById(R.id.failfive);
failfiveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Button button = (Button) v;
button.setVisibility(View.INVISIBLE);
mSoundManager.playSound(2);
finish();
}
});
Button failsixButton = (Button)findViewById(R.id.failsix);
failsixButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Button button = (Button) v;
button.setVisibility(View.INVISIBLE);
mSoundManager.playSound(2);
finish();
}
});
Because I have about six buttons of the code above and if I add finish();
under mSoundManager.playSound(2); it goes back to the first .main screen. Instead of letting me continue and make the rest of the buttons invisible.
If I don't finish(); the application lags from too much memory leaking.
Thanks
Wahid
A: Its happening because this method gets called when ever a button is clicked. it does't care how many buttons you click. here you are finishing your Activity for each button click, so this is happening. a silly solution could be this
private static int count = 0;
private static int count1 = 0;
failfiveButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
count++
Button button = (Button) v;
button.setVisibility(View.INVISIBLE);
mSoundManager.playSound(2);
if(count == 6)
finish();
}
});
Button failsixButton = (Button)findViewById(R.id.failsix);
failsixButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
count1++
Button button = (Button) v;
button.setVisibility(View.INVISIBLE);
mSoundManager.playSound(2);
if(count1==6)
finish();
}
});
Edit: there could be other better ways to do it. but i gave you this solution since i don't know what exactly is your purpose.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to reduce many similar correlated subqueries? This is part of a larger statement, but I'm wondering if CTE or another method would help make this more efficient or cleaner. I could write it as a table-valued function and include it in my from clause, but I'd like to avoid extra objects if there is another solution.
The SELECT TOP 1 ... sub-queries here simply catch when I have a rate with an earlier effective date than the base table, but I'm not fond of repeating them for each column I need to access. Is there a better way to accomplish this, or is this a normal looking statement?
SELECT j.EmployeeId
,j.CompanyId
,j.JobCode
,COALESCE(j.CustomWageRate, r.WageRate, (SELECT TOP 1 WageRate
FROM ContractLabor.CompanyJobRates
WHERE CompanyId = j.CompanyId
AND JobCode = j.JobCode
AND EffectiveDate < j.EffectiveDate
ORDER BY EffectiveDate DESC), 0) AS EffectiveRate
,COALESCE(r.CustomBurdenRateReg, (SELECT TOP 1 CustomBurdenRateReg
FROM ContractLabor.CompanyJobRates
WHERE CompanyId = j.CompanyId
AND JobCode = j.JobCode
AND EffectiveDate < j.EffectiveDate
ORDER BY EffectiveDate DESC)) AS CustomBurdenRateReg
,COALESCE(r.CustomBurdenRateOvt, (SELECT TOP 1 CustomBurdenRateOvt
FROM ContractLabor.CompanyJobRates
WHERE CompanyId = j.CompanyId
AND JobCode = j.JobCode
AND EffectiveDate < j.EffectiveDate
ORDER BY EffectiveDate DESC)) AS CustomBurdenRateOvt
,COALESCE(r.CustomBurdenRateDbl, (SELECT TOP 1 CustomBurdenRateDbl
FROM ContractLabor.CompanyJobRates
WHERE CompanyId = j.CompanyId
AND JobCode = j.JobCode
AND EffectiveDate < j.EffectiveDate
ORDER BY EffectiveDate DESC)) AS CustomBurdenRateDbl
,j.EffectiveDate
FROM ContractLabor.EmployeeJobDetails j
LEFT JOIN ContractLabor.CompanyJobRates r
ON j.CompanyId = r.CompanyId
AND j.JobCode = r.JobCode
AND j.EffectiveDate = r.EffectiveDate
A: SELECT j.EmployeeId
,j.CompanyId
,j.JobCode
,COALESCE(j.CustomWageRate, r.WageRate, ca.WageRate, 0) AS EffectiveRate
,COALESCE(r.CustomBurdenRateReg, ca.CustomBurdenRateReg) AS CustomBurdenRateReg
,COALESCE(r.CustomBurdenRateOvt, ca.CustomBurdenRateOvt) AS CustomBurdenRateOvt
,COALESCE(r.CustomBurdenRateDbl, ca.CustomBurdenRateDbl) AS CustomBurdenRateDbl
,j.EffectiveDate
FROM ContractLabor.EmployeeJobDetails j
LEFT JOIN ContractLabor.CompanyJobRates r
ON j.CompanyId = r.CompanyId
AND j.JobCode = r.JobCode
AND j.EffectiveDate = r.EffectiveDate
OUTER APPLY --or CROSS APPLY
(
SELECT TOP 1 WageRate
,CustomBurdenRateReg
,CustomBurdenRateOvt
,CustomBurdenRateDbl
FROM ContractLabor.CompanyJobRates
WHERE CompanyId = j.CompanyId
AND JobCode = j.JobCode
AND EffectiveDate < j.EffectiveDate
ORDER BY EffectiveDate DESC
) ca
A: You could join on a derived table expression in your outer query using cross apply / top 1 and select the relevant columns all at once.
Your query could then look like:
SELECT ..., ISNULL(x, defaultValues.x)
FROM ...
CROSS APPLY (SELECT TOP(1) x, y, z FROM ... WHERE ... ORDER BY ...) defaultValues
It will be more efficient because there are fewer joins in the query (each of your original correlated subqueries turns into an outer join).
You can also use OUTER APPLY for outer join like functionality.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make 3.2 APDI slider emulator Hey i am making a app in which i want to make emulator that should be 320 X 480 i.e. APDI emulator .Can anyone help me out ...
Thanks.
A: The HVGA emulator is 320 X 480 only
A: HVGA emulator is one You are looking for ..
A: The HvGA is the emulator whose ewsolution is 320X480
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Count folder inside the folder Can you help me how to count the folders inside the folder.
How can i count the sub folders after the FolderBrowserDialog is popup and choose that main folder consist of 3 folders.
I'm using
FolderBrowserDialog fbdialog = new FolderBrowswerDialog();
A: Use System.IO.DirectoryInfo() class and its methods.
A: Refer to the Recursive File and Directory Method to all the list of folders including Count of sub folders in a folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: UISlider's value is not shown by UILabel In my app, I have a Settings view, where the user can use UISlider to set value from 50 to 1000. The selected value is then shown in a UILabel.
The problem is that the label does not display at all. The Action and the IBOutlets are connected in IB. The NSLog displays the value correctly on the console.
I can't figure out what is going on....help is needed :)
I have the following:
IBOutlet UILabel *sliderLabel;
IBOutlet UISlider *slider;
...
@property (nonatomic, retain) UILabel *sliderLabel;
@property (nonatomic, retain) UISlider *slider;
-(IBAction) sliderValueChanged:(id) sender;
and
@synthesize sliderlabel, slider;
- (IBAction) sliderValueChanged:(UISlider *) sender {
NSString *sliderValue = [NSString stringWithFormat:@"%d feet",(int)[sender value]];
NSLog(@"%@", sliderValue);
[[self sliderLabel] setText: sliderValue];
}
Thanks, and regards.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you deep clone a persistent entity in ColdFusion ORM? I have a persistent entity that I'm using as a template:
Company
Locations
Departments
Employees
In other words, a Company contains many Locations, which contains many Departments, which contains many Employees. I have one Company set up as a template that should be copied when a new company is created. However, this template is persistent in the database. I tried using the following code to deep clone it:
var template = EntityLoadByPK("Company", 13);
var company = Duplicate(template);
EntitySave(company);
But I receive an error says that the entity is not attached to the session. So then I tried to assign 0 to all the IDs before saving:
company.setId(0);
for (location in company.getLocations())
{
location.setId(0);
// more nested for loops
}
But I receive a similar error. Finally, I tried to do a direct 1:1 copy of the properties:
var newCompany = EntityNew("Company");
newCompany.setName(company.getName());
newCompany.setCEO(company.getCEO());
// etc...
But this gets more and more cumbersome the deeper the object graph goes. Is there an easier way of deep cloning a persistent entity so that you get a brand new transient entity, including all of its child collections?
A: last time I encountered the same situation, I just wrote a clone-like method in the root CFC. Cannot call it clone btw, 'cause it's reserved I believe.
A: Have you tried using EntityMerge? You should be able to duplicate an ORM object, NULL out the IDs, and then Merge it back into the session.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Converting a string to a defined constant in PHP Let's say I have defined the constant ERROR_0 as follows:
define("ERROR_0","An error occurred.")
Now, let's say I have the string "ERROR_0" but I want to convert that into the constant ERROR_0 such that I can get the string "An Error occurred." How can I do that?
Thanks!
A: Use constant function
echo constant("ERROR_0");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: 2d array in C. Fixed width but unknown height? Is it possible to make an array with an unknown height but a set width?
So that It can be something like:
|----------8-----------|
[0][0][0][0][0][0][0][0] |
[1][1][1][1][1][1][1][1] |
[2][2][2][2][2][2][2][2] |
[3][3][3][3][3][3][3][3] \|/
So that it can be as big as it needs but stays 8 floats wide.
I have a feeling that the declaration will look somewhat like:
float *array[8] // maybe???
or
float array[8][] // idk???
Im not used to multiple pointers on a var (I get confused still). I use apple's cocoa framework a lot so I would normally use NSArray but the thing I'm building requires a C-based array not a class.
A: Try this:
float (*array)[8];
...which declares array as a pointer to 8-element arrays of float.
You can then allocate space for the whole thing as follows:
array = malloc(sizeof(*array) * num_elements);
Then, array[3][0], for example, would access the first float in the 4th array of 8 floats.
A: float *array[8];
Now you have an array of 8 float pointers.
For each one of these, you would then need to allocate space when you know how large it needs to be:
array[0] = calloc(numMembers, sizeof(float));
If you later decided you needed a specific second dimension to be larger, you would need to reallocate.
A: Yes It definatly is:
float *p2DArray[8];
for (int i = 0; i < HEIGHT; ++i) {
p2DArray[i] = (float*)malloc(sizeof(float)*WIDTH);
}
taken from Multi-Dimensional Arrays
A: As an argument to a function, you can require a 2d array of unknown height, as so
void foo(int arr[][8])
{
//...do stuff with arr...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: use the toggle function to show hide a table row I would like to use the toggle function to show hide a table row BELOW
a dynamic row, so the table would look like this
row from database with data
row I want to show hide (defaults to hide)
I know how to do this when the table is static but how do I do it when
the rows are being built based on the numbers of rows from the
database?
A: It should not be any different if its build dynamic from .NET, you can still bind them because .NET generates the markup for you. But if its a response from an AJAX call or something you may want to look at .delegate() method or the .live() method.
A: Try the following .
Specify a class for the row which will be created from database. Say the class is 'RowFromDB', then if you specify $('.RowFromDB').next() you can get the next element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: non void method for binary tree inorder traversal I'm wondering if its possible to have an inorder tree traversal method in java actually RETURN something... I'm trying to traverse through the tree given a node and a value, return the node that matches the value:
/**
* Variable for storing found node from inorder search
*/
private Node returnNode;
/**
* Perform an inorder search through tree.
* If a value is matched, the node is saved to returnNode, otherwise return null.
* @param node The given node
* @param value The value of the node to be found.
*/
public void inorder(Node node, Object value){
if(node != null){
inorder(node.leftChild, value);
if(node.value.equals(value)){
System.out.println(value + " was found at " + node);
returnNode = node;
}
inorder(node.rightChild, value);
}
}
Right now, I've tried declaring a public node to store the value, but I find that that doesn't work when I run:
assertEquals(newNode3, BT.contains("3"));
assertEquals(null, BT.contains("abcd"));
Where returnNode takes on newNode3's values and messes up my tests for null.
Can anyone point me in the right direction?
A: I would have thought you'd want something like this:
/**
* Perform an inorder search through tree.
* The first node in order that matches the value is returned, otherwise return null.
* @param node The given node
* @param value The value of the node to be found.
* @return The first node that matches the value, or null
*/
public Node inorder(Node node, Object value){
Node result = null;
if(node != null){
result = inorder(node.leftChild, value);
if( result != null) return result;
if(node.value.equals(value)){
System.out.println(value + " was found at " + node);
return node;
}
result = inorder(node.rightChild, value);
}
return result;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Picasa Web Service in android Is it possible to get Picasa Album photos using gdata API ( Google Data API)
my imports :
"import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.PhotoEntry;"
my service creation :
PicasawebService service = new PicasawebService("exampleClient");
If I use that in my Android activity it compiles fine when I run the app I get no class found excetion. Any Help will be greatly appreciated
09-29 01:01:41.160: ERROR/AndroidRuntime(30113): java.lang.NoClassDefFoundError: com.google.gdata.client.photos.PicasawebService
09-29 01:01:41.160: ERROR/AndroidRuntime(30113): at com.chandu.examples.picassa.PicassaAlbumsActivity.loadAlbum(PicassaAlbumsActivity.java:48)
09-29 01:01:41.160: ERROR/AndroidRuntime(30113): at com.chandu.examples.picassa.PicassaAlbumsActivity.onCreate(PicassaAlbumsActivity.java:31)
A: Your GData client JAR should be be in the war/WEB-INF/lib directory
From the documentation:
To use this library in your App Engine application, you must first copy the JARs listed below from the lib directory of the gdata-java-client package to your project's war/WEB-INF/lib directory:
gdata-client-1.0.jar
gdata-client-meta-1.0.jar
gdata-core-1.0.jar
gdata-docs-3.0.jar
gdata-docs-meta-3.0.jar
gdata-media-1.0.jar
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ruby on Rails Relational Drop Downs Second dependant on the First I have three different models that will be involved with this. I am trying to create a user who will belong to an owner. The owner has many partners and the partner has many clients. The problem with this and how it varies from other questions asked here, is that I do not want someone to view source of the page and see the entire list of clients. This is currently in devel/testing phase right now. I will eventually restrict the owner_id to be hard coded to the @current_user's owner_id. This owner user can only see their own partners and those partner's clients. I would not want them to see the partners of another owner.
<%= f.input :owner_id, :as => :select, :collection => Owner.find(:all) %>
<%= f.input :partner_id, :as => :select, :collection => Partner.find(params[:owner_id]) %>
<%= f.input :client_id, :as => :select, :collection => Client.find(params[:partner_id]) %>
The issue that I have above is that the find params is generating an error since the :owner_id has no value and is not going to find any partners. So how do I go about having the client selection populate the list of clients when a partner is selected. Likewise, how to figure out how to populate the Partners once the owner is selected. Keep in mind, that the owner line will change once I figure this piece out. There's no point in moving forward until this is figured out.
If this were a City based on the State chosen, I've found several options but haven't found the right one with this yet. Thanks guys!
A: I don't think you're understanding (or taking advantage of) the model associations. Since I don't fully understand your model or business domain, I'm doing a lot of hand-waving here... it sounds like you want to restrict the number of options in the select box to just those that the current user should be able to see.
Let's say you had a Tumblr-style app. You have many users, and many blogs. The current logged in user can post a new item to any one of the blogs they have access to. When creating a new post and selecting which blog to publish it in, it would not be appropriate to let me post to your blog, or even know it exists. Instead of Blog.all, we'd use @current_user.blogs.
<%= semantic_form_for @post do |f| %>
<%= f.input :blog, :label => "Which blog?", :as => :select, :collection => @current_user.blogs %>
...
<% end %>
I would see my list of blogs to choose from, you'd see yours. I think this partially answers your question.
The other part of the question seems to be around dynamically altering the contents of the select box based on the selections made in other select boxes in the form. This is something that would need to be handled with Javascript/AJAX, and kind of out-of-scope for Formtastic and a simple answer on Stack Overflow :)
I'd recommend keeping this as simple as possible for a first version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When should I set a custom class override default UIViewController for a xib file? When should I set a custom class to override default UIViewController for a xib file?
For example, I have a UIViewController subclass named SettingViewController, and a xib file namedSettingViewDetail.xib.
I found whether I set a custom class for the xib or not(default is UIViewController), my following code will work normal, it will create a controller for me
SettingViewController *oneView = [[SettingViewController alloc] initWithNibName: @"SettingViewDetail" bundle:nil];
and I can use it to control view navigation:
[[[[UIApplication sharedApplication] delegate ] naviController] pushViewController: oneView animated:TRUE];
I want to know when should I set a custom class for xib, and what reason for this?
A: If you want to set outlets (references to your subviews in this .xib) and have simple (without using tags) access to that subviews in your SettingViewController then you should set appropriate class of File's Owner and then that IBOutlet's will appear.
In similar way you can easily set methods (IBAction's) that will be called when user click the button, for example.
So, in the general case, you can just reduce amount of your code.
A: As far as the xib file goes, I think you are talking about the class identifier for the file's owner? That only needs to be your custom subclass if you have specific actions or outlets that you are connecting in interface builder that only exist in your subclass.
If there are no subclass specific features you are using in the xib, the you can use UIViewController instead. This would allow you to reuse the same xib file for several different view controller subclasses if you liked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to generate MD5 fingerprint hi i have to generate signing cartificate fingerprint so my first task is to generate keystore file using command.
C:\Program Files\Java\jdk1.7.0\bin>keytool -genkey -v -keystore myrelease.keystore -alias alias_name.
now i have to generate the finger prints(MD5) using this command:
C:\Program Files\Java\jdk1.7.0\bin>keytool -genkey -v -keystore helloworld7.keys
tore -alias alias_name -validity 10000.
but its giving output in
Certificate fingerprint (SHA1):my finger print.
its giving finger print using SHA1 algorithm.can any one please tell what modification i have to do in my commands so that i can get MD5 finger prints
A: add -v after keytool and you will get all fingerprints
A: JDK1.6 by default generates MD5 fingerprint but jdk1.7 generates SHA1. But you can get MD5 fingerprint by using keytool -v -list -keystore your_key in the keytool commandAs you are using jdk1.7, so you can get MD5 finger print by placing -v -list in the command.
Example:
C:\Program Files\Java\jdk1.7.0\bin>keytool -v -list -keystore helloworld7.keystore
A: Being confronted with the same problem, I have found some posts on the site saying that this happens because of the jdk1.7, it generates SHA1 instead of MD5. I have uninstalled jdk1.7 and installed jdk1.6 and following the Abhi's link(jdk 1.6 is used there also) I was able to get a MD5 fingerprint. I registered it on http://code.google.com/android/maps-api-signup.html and I got an API Key.
A: Here is a link to another post on here with the exact same problem:
How can I get the MD5 fingerprint from Java's keytool, not only SHA-1?
This solution actually works for JDK1.7. I tested it before I posted this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android convert the ArrayList> mylist to stringarray I have create an android application program..I dont know how to convert the ArrayList<HashMap<String,String>> mylist to string array..pls tell some idea.Thanks in advance
A: Create a new ArrayList<String>, traverse the "mylist", append one after one element into newly created list and finally use toArray(T[]) method of newly created list to obtain a string array.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Has the response from FB.ui requests changed? It used to be that the response from a request gave us an array of request ids (as described here http://developers.facebook.com/docs/reference/dialogs/requests/) but it seems now the response variable returns two items insead 'to' and 'request'. To being a comma delimited string of user ids and request being a request id. Is this correct? I have seen nothing about this anywhere but it is the behavior I am seeing currently.
Update
Here is a super simplified version of my call:
FB.ui({method: 'apprequests', message: 'My Great Request'}, requestCallback);
function requestCallback(response) {
for(var key in response){
console.log(key);
console.log(response[key]);
}
}
When I make a request to one person the variable response has two keys: request and to. Request is a request id, to is the id of the person I'm sending the request to. If I make a call to the graph api using the provided request id, however, I find that the user under both 'to' and 'from' are equal to the sender's name and fbid.
Alternatively, if I request to multiple people request is equal to a single request id and to is an array containing all the fbids of the users that had requests sent to them. When I make a call to the graph api, however, I once more find that both 'to' and 'from' contain the user id and name of the requesting user.
A: As in the documentation, the new callback will receive an object (response) that contains an array (request_ids) of request ids:
{
"request_ids": [
0: [request_id]
1: [request_id]
...
]
}
So I suppose you can loop using this modified code:
function requestCallback(response) {
for( var k in response.request_ids ) {
console.log(k);
console.log(response.request_ids[k]);
}
}
A: There is already a bug filed here
http://developers.facebook.com/bugs/129565473812085
There is no clear information yet whether the response is really changed or its a bug.
A: I faced similar issue yesterday. Had to fix my code. But today request_ids were back in the response. So I updated the code again. But this time to work with both type of objects.
I found the documentation here (move down to the "Performance improvements" section)
http://developers.facebook.com/blog/post/569/
But it still doesn't explains why they reverted the change today. Or was it accidently released yesterday.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Technology behind the Facebook Search If you just start typing a person name in the Facebook search box(displayed in blue upper bar on your profile) then suddenly within a fraction of a second search results appear and they comes much more faster if that person already exist in your profile.
so i just want to know that what is behind this search.i mean to say that which software tool and algorithm they are using for it.
i know that no one other than Facebook can explain exactly about it thats why i am just asking to give me an idea about that.
i am sure that they are using something which is open source.
A: I assume the underlying technology is AJAX, with some caching mechanism that increases performance for profiles in your friends list.
A: The response is an autocomplete Ajax form, but this is not really the question. The key question here is how fast can you search in a text field. Facebook splits this into 2 parts. First they search in the list of your friend which is a cached and relatively rarely changed file containing 100 to a 1000 entries. This is quite fast. The other thing is to search for a name in ALL Facebook, which means I guess 1 billion names. This is a little more tricky, but I guess they have them splitted and indexed by letters or letters combinations. For example:
// search query Alice Cooper
A ... they give you a list of A like names Alina, Ana, Alice...
Al .... they limit it to Alicia, Alice, Alina ...
// and so on
Probably after a 3 letters they are starting to do a search, but not in the 1 billion rows, but in a limited subset of your 3rd level friends and probably increasing it each time.
Probably your query is never compared with the whole table, and there are definitely cached levels or recalculated queries for most of the common names.
This is in terms of technique. In terms of technology take a look at Solandra, a search engine build on top of Cassandra which Facebook is using, though I cannot confirm that this is what they are using, but just to give you a research direction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: How to deploy Excel 2010 add-in for Office 2007 .NET 3.5 target environment? Installing Excel 2010 add-in on the target machine with Office 2010 + .Net framework 4.0 is absolutely fine. However, I am not sure whether or not Excel 2010 add-in is compatible with Excel 2007 and .Net 3.5.
Would someone give me some basic ideas about deploying Excel 2010 add-in for that target environment?
Also, in the Prerequisites of setup project, I have currently got .NET 4 client profile , VS2010 tools for office runtime, Windows Installer 3.1 checked. Do I need to check any other options?
A: Do you have the primary interop assemblies for Excel 2007 installed?
See this for detailed documentation on how to deploy VSTO 2010 add-in.
A: (Posted solution on behalf of the question author).
Managed to install Excel 2010 Add-in onto target machine that runs Office 2007. Mostly the steps have been covered by this tutorial but there are a few tricks that we need to be aware of.
Main project
*
*Be sure to check the target framework of your application in your main project
Setup project
*
*In registry editor, create following new keys in additional to those suggested in the above tutorial, if you are deploying automation add-in (e.g. HKCR \ CLSID \ {your custom class id} \ Programmable)
*Set Programmable key to AlwaysCreate = True ( The UDF will not appear in the automation server list if you don't create this Key and set it properly )
*In launch conditions editor, Add Windows Installer Search, and rename it Search for Office 2007 Shared PIA
*Set ComponentId to {1ABEAF09-435F-47D6-9FEB-0AD05D4EF3EA} ( This is Excel 2007 Component ID )
*(For Excel 2010, use {EA7564AC-C67D-4868-BE5C-26E4FC2223FF})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how to remove namespace and retain only some of the elements from the original XML document using XSL? Below is my XML. I wanted to parse this using XSL. What I want to achieve is to remove the namespace (xmlns) then just retain some of the elements and their attributes. I found a way to remove the namespace but when I put it together with the code to retain some of the elements, it doesn't work. I already tried the identity but still didn't work.
I hope someone out there could share something. Thank you very much in advance.
XML Input:
<Transaction xmlns="http://www.test.com/rdc.xsd">
<Transaction>
<StoreName id="aa">STORE A</StoreName>
<TransNo>TXN0001</TransNo>
<RegisterNo>REG001</RegisterNo>
<Items>
<Item id="1">
<ItemID>A001</ItemID>
<ItemDesc>Keychain</ItemDesc>
</Item>
<Item id="2">
<ItemID>A002</ItemID>
<ItemDesc>Wallet</ItemDesc>
</Item>
</Items>
<IDONTLIKETHIS_1>
<STOREXXX>XXX-</STOREXXX>
<TRANSXXX>YYY</TRANSXXX>
</IDONTLIKETHIS_1>
<IDONTLIKETHIS_2>
<STOREXXX>XXX-</STOREXXX>
<TRANSXXX>YYY</TRANSXXX>
</IDONTLIKETHIS_2>
</Transaction>
<Transaction>
Expected XML Output:
<Transaction>
<Transaction>
<StoreName id="aa">STORE A</StoreName>
<TransNo>TXN0001</TransNo>
<RegisterNo>REG001</RegisterNo>
<Items>
<Item id="1">
<ItemID>A001</ItemID>
<ItemDesc>Keychain</ItemDesc>
</Item>
<Item id="2">
<ItemID>A002</ItemID>
<ItemDesc>Wallet</ItemDesc>
</Item>
</Items>
</Transaction>
<Transaction>
Code used to remove the namespace (xmlns):
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
A: <xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:x="http://invia.fujitsu.com/RetailDATACenter/rdc.xsd">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:template match="*">
<xsl:element name="{name()}">
<xsl:copy-of select="@*"/>
<xsl:apply-templates select="node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="node()[not(self::*)]">
<xsl:copy-of select="."/>
</xsl:template>
<xsl:template match="x:IDONTLIKETHIS_1 | x:IDONTLIKETHIS_2"/>
</xsl:stylesheet>
Explanation:
*
*The template matching "*" matches any element and recreates it (<xsl:element>) with the same name, but doesn't copy any namespace nodes. It also copies all attributes of this element. Then it applies templates (including itself -- recursively) on all of this element's children nodes -- not only elements but all types of children nodes: elements, text nodes, processing-instructions and comments.
*The last template matches any node we don't like to copy to the output and does exactly this (no copying ) with an empty template body.
*The second template matches and copies to the output all nodes that aren't elements, excluding the document node /
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Override text property of textbox How do I override the text property in a textbox in WPF?
I want this code in WPF:
public override string Text
{
get { return Text.Replace(",", ""); }
set { Text = value; }
}
A: If you are data binding against the TextBox.Text property then another possible approach is to move the logic away from the control itself and place it in a converter. Your converter would look something like this...
public class CommaReplaceConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return value.ToString().Replace(",", "");
}
}
And data binding something like this...
<TextBox Text="{Binding XXX, Converter={StaticResource CRC}" />
...where the static resource is defined as...
<Window.Resources>
<CommaReplaceConverter x:Key="CRC"/>
</Windows.Resources>
A: Text is a dependency property. If you have derived a class from TextBox then you need to override the metadata and provide your validation callbacks
See
*
*http://blog.ningzhang.org/2008/11/dependencyproperty-validation-coercion.html
*http://msdn.microsoft.com/en-us/library/ms745795.aspx#Validation_Callbacks
A: While the upvoted answers are correct, there is a much simpler approach: as the Text property of TextBox is bound to a property of an underlying class (usually in the Viewmodel) simply take care to provide the replacement in the underlying class.
A: You were just missing the text argument?
public override string Text
{
get { return Text.Replace(",", Text); }
set { Text = value; }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Simple Xml - order of elements not preserved?β I am using SimpleXml 2.6.1 in my android app. Eventhough the documentation (http://simple.sourceforge.net/download/stream/doc/javadoc/index.html?org/simpleframework/xml/Order.html) says the order of the elements in the xml are same as the way they have defined in the class file, I am always getting the order to be random in the xml. If I add few more variables, the order of the elements again changes.
Adding @Order notation works, but since the class is complex with 100s of variables, I do not want to add order. Is this a known bug for android versions? It works fine in java console programs.
p.s: I opened the .class file disassembled and found the variables declared in the same order as java file, so I don't think it's a class file issue.
A: import org.simpleframework.xml.Element;
import org.simpleframework.xml.Order;
@Order(elements = {"name", "isTrue"})
public class SimpleXml {
public static final String NAME = "$NAME$";
public static final String IS_TRUE = "$IS_TRUE$";
@Element
private String name;
@Element
private Boolean isTrue;
...
A: Since there is no answer, I'll try to save precious time to anyone who gets here.
I found no cause, and since I don't have time to analyze Simple libraries, I came up with a "workaroud". It's more of an advice, actually - don't use it for (marshaling)creating xml if you have a large xml definition and the order matters(a rule more than an exception). The order is mostly used for marshaling anyway so just save yourself some time and do it manually.
The template:
<document>
<name>$NAME$</name>
<isTrue>$IS_TRUE$</isTrue>
</document>
The class:
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
/**
* User: ksaric
*/
public class SimpleXml {
public static final String NAME = "$NAME$";
public static final String IS_TRUE = "$IS_TRUE$";
private String name;
private Boolean isTrue;
public SimpleXml() {
}
public Boolean getTrue() {
return isTrue;
}
public void setTrue(Boolean aTrue) {
isTrue = aTrue;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
String template = null;
try {
template = getTemplate();
} catch (IOException e) {
e.printStackTrace();
}
/* GUAVA - checkNotNull() */
if (null == template) return null;
template = template.replace(NAME, getName());
/* OR CONVERT IN THE GETTER METHOD */
template = template.replace(IS_TRUE, getTrue().toString());
return template;
}
/* SINGLETON? Performance(IO) loss... */
public String getTemplate() throws IOException {
InputStream templateStream = getClass().getResourceAsStream("/template.xml");
/* APACHE IO COMMONS */
/*
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
*/
final String stringTemplate = IOUtils.toString(templateStream);
return stringTemplate;
}
}
The test:
import org.junit.Test;
import static junit.framework.Assert.*;
/**
* User: ksaric
*/
public class SimpleXmlTest {
@Test
public void test() throws Exception {
//Before
/* Use standard instantiation, factory method recommended for immutability */
SimpleXml simpleXml = new SimpleXml();
simpleXml.setName("This is a name");
simpleXml.setTrue(false);
//When
String result = simpleXml.toString();
//Then
assertNotNull(result);
System.out.println(result);
}
}
Not really an answer, but save yourself some time and don't use Simple(which is a great library) on Android...
A: Simple Xml doesn't preserve Order on Android. Based on pfh's answer, here is my recommendation:
I would prefer to use JAXB in the case where you want the order to be preserved than manual string/template parsing. JAXB is slightly complex to use than SimpleXml but comes with similar set of annotations based xml serialization and deserialization.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to configure log4j for package level logging? I want to log in to multiple log files(flume and console). How to set log4j as package level?ie com.mypackage.myclass into flume and other packages into console..
A: First of all you need to configure log4j to have two named loggers, one that sends to the Console appender, and one that sends to Flume. You can then write use a proxy class for making your logging calls that routes the log4j calls to the different loggers depending on the package the caller is in. You can do this by accessing the stack of the current thread, like so:
public class Logger
{
public static org.apache.log4j.Logger getLogger()
{
// this will get the calling frame, 0=Thread, 1=this, 2=caller
StackTraceElement stackElement = Thread.currentThread().getStackTrace()[2];
if(stackElement.getClassName().startsWith("the.package.that.goes.to.flume"))
{
return org.apache.log4j.Logger.getLogger("Flume");
}
else
{
return org.apache.log4j.Logger.getLogger("Console");
}
}
}
}
The code above is assuming you have named your two loggers 'Flume' and 'Console'.
When ever you make a logging call in your app, use Logger.getLogger() rather than going to log4j directly.
A: Check this blog post
http://veerasundar.com/blog/2009/07/log4j-tutorial-adding-log4j-logging-to-your-project/
It has a complete PDF for download on how to add log4j to project.
You need to define categories for different packages.Everything is explained in above PDF.
Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Anyone have a skeletonizer library or psuedo code I am already using the SkeletonFilter from jhlabs.com but it has a few issues. For example it seems to remove small details that are perpedicular to the longer line. An example is the serifs from a capital A when skeletonized are removed.
I have looked at some tracers such as Autotracer and potrace but they do slightly more than just plain skeletonization.
Are there any other java alternatives ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to convert java arraylist to javascript array? How do we convert java array list of String objects to java script array?
This is what I am doing but I am looking for a better way to do it. I dont want to iterate over the array list.
var myArray = [
<c:forEach items="${myList}" var="item">
{itemName: "${item.name}"},
</c:forEach>
];
Thanks.
A: There is no direct way to convert the Java ArrayList to the Javascript Array.
You have to do one of the following step
1. Convert the Java ArrayList to the JSON String and then convert it to Javascript Array by parsing the String.
2. Directly write the ArrayList (using scriptlet) to the Javascript String and then split/parse it the the array.
3. Send a string by calling ArrayList.toString() as a response and then follow the Step 2.
A: var myArray2 = new Array();
myArray2= new Array('<s:property value="%{Listclassaveragelist}"/>');
var carter = myArray2.toString();
carter = carter.replace("[","");
carter = carter.replace("]","");
carter = carter.split(",");
A: You can use java libraries such as gson or Jackson to convert the arraylist object in java to JSON and then transfer it over to the client side where you can extract it from the JSON using javascript. Here you can avoid looping on the client side because gson converts java ArrayList to a javascript array when it creates JSON.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there a sqlldr api for java I want to use sqlldr from a java program, but I dont want to invoke it using "Runtime.exec".
is there such api for sqlldr in java.
A: No, there is no native API to call SQL*Loader functionality from Java.
The only option you have is to use Runtime.exec() (or a ProcessBuilder).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592764",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Problem with setting Project Facets As said in the following IBM tutorial, http://public.dhe.ibm.com/software/dw/xml/x-springandroid/x-springandroid-pdf.pdf I have tried to create a JAX RS web services.
But I am not able to set the Project facets to JAX - RS as I don't get any such options. Also, I wanted to know hoew do i set the class path of server to the respective jars.
I am using Eclipse Ganymade IDE
Thanks
Sneha
A: we have to use Helios version of eclipse to get those options for JAX RS. I was using ganymade version. Also,To set the class path i just nedd to copy the jars to lib folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: UISwitch performing action on value change-iphone sdk I have a UISwitch and I need to load the value in a string into an array when change the switch state change to OFF to ON. I have used the following code, but not working.
-(IBAction)toggleSwitch1:(id)sender {
if (addSwitch.on) {
[addSwitch addTarget:self action:@selector(addName:) forControlEvents:UIControlEventValueChanged];
NSLog(@"%@",userName);
}else {
NSLog(@"No");
}
}
-(void)addName:(UIControl*)sender {
[alertList addObject:userName];
NSLog(@"AlertList: %@", alertList);
}
And if once the state changed to ON, how can I remain the same state, if I reload the page?
Please share your thoughts.
Thanks
A: In viewDidLoad use this one:
-(void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
if([userdefault boolForKey:@"yes"]) {
addSwitch.on=YES;
} else {
addSwitch.on=NO;
}
}
-(IBAction)toggleSwitch1:(id)sender
{
NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
if (addSwitch.on) {
[self performSelector:@selector(addName:) withObject:userName];
NSLog(@"%@",userName);
[userdefault setBool:YES forKey:@"yes"];
} else {
[userdefault setBool:NO forKey:@"no"];
NSLog(@"No");
}
}
-(void)addName:(UIControl*)sender
{
[alertList addObject:sender];
NSLog(@"AlertList: %@", alertList);
}
A: Looks like the issue you're having is that the toggleSwitch method is called when the state changes and then it starts listening for the change using the addTarget: method. You should choose one or the other to handle the change.
-(IBAction)toggleSwitch1:(id)sender{
if (addSwitch.on) {
[self addName:userName];
} else {
//do something else
}
}
-(void)addName:(UIControl*)sender{
[alertList addObject:userName];
}
To save the switch state just have another variable that stores the switch state and call the setOn:animated: method in viewDidLoad.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In C, Save one char at a time I am processing a string in which each word is separated by spaces. The < indicates it is a input redirection, and > indicates it is a output redirection.
Ex:
< Hello > World
I want to save the words in different variables (char *in, char *out )
How can I do that? I've looked through the string library and none seems to be able to do the job.
Here's what I have so far concerning this question.
char buff[MAXARGS];
char *str;
char *in;
char *out;
if( strchr(buff, '<') != NULL )
{
str = strchr(buff, '<');
str++;
if( *str == ' ' || *str == '\0' || *str == '\n' || *str == '\t' )
{
fprintf( stdout, "User did not specify file name!\n" );
}
else
in = str; // This will save Hello > World all together. I don't want that.
}
Thanks much.
A: u can use this..
char filename[max_path]
str1 = strchr(buff, '<');
str2 = strchr(buff, '>');
memcpy( filename , str1+1 , str2-str1-1 );
so the path between < and > will be in filename.
and
output = str2 + 1;
A: supposing your input patter is fixed as < input_name > output_name and you want to be able to extract input_name and output_name respectively.
One solution is to split the str using " <>". Following code will print out Hello , World consecutively. Saving them to in and out is left for you as an exercise :)
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="< Hello > World";
char *in;
char *out;
char *pch;
char *del=" <>";
pch = strtok (str,del);
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, del);
}
return 0;
}
A: To get you started, here's how you could do it assuming you are allowed to modify buff, and assuming a simple case (at most one < and at most one >).
First, get the position of the < and >
in = strchr(buff, '<');
out = strchr(buff, '>');
Then you artificially split the string:
if (in) {
*in = 0;
in++;
}
if (out) {
*out = 0;
out++;
}
At this point, buff points to a C-terminated string that has no < or >. in is either null, or points to a string that follows < and contains no >. Same for out.
Then you need to "strip" all these strings (remove whitespace), and check that after that they still contain meaningful data.
You'll need a whole lot more logic to get all the cases right, including rejecting invalid input.
A: You need to decide where the storage for the two filenames is allocated, and how you will know how much storage is provided.
static void find_filename(const char *str, char *name)
{
char c;
while ((c = *str++) != '\0' && isspace((unsigned char)c))
;
if (c != '\0')
{
*name++ = c;
while ((c = *str++) != '\0' && !isspace((unsigned char)c))
*name++ = c;
}
}
int find_io_redirection(const char *str, char *in, char *out)
{
const char *lt = strchr(str, '<');
const char *gt = strchr(str, '>');
if (lt != 0)
find_filename(lt+1, in);
if (gt != 0)
find_filename(gt+1, out);
return(lt != 0 && gt != 0);
}
This code simply assumes that you provide big enough strings for in and out. If you want to be safer, then you tell the function(s) how big each target string is. You can compress that code. You might decide you want to return the number of redirections. You might decide you should know about double output redirections, or double input redirections. You might decide you should return a bit mask indicating which redirections were present. With a considerably more complex interface, you might be able to indicate which parts of the input line represented the I/O redirection; this would help in the calling function to decide which parts of the line should now be ignored.
You'd use the code above like this:
char buffer[MAXCMDLEN];
char in[MAXFILENAMELEN];
char out[MAXFILENAMELEN];
if (fgets(buffer, sizeof(buffer), stdin) != 0)
{
if (find_io_redirection(buffer, in, out))
...process buffer know that I/O redirection is present...
else
...witter about missing I/O redirection...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Valums qq.FileUploader doesn't work when it's initialized after loading button by ajax I use Valums qq.FileUploader(ex-AjaxUpload) plugin for uploading in my Asp.net mvc 3 application...
I have some button in my page add-newimage, and by clicking in it I get modal window, and I load data into that window by loading Partial View.
And in that partial view I have button upload-image , in which I want to initilaize my qq.FileUploader, but it doesn't work anywhere...
Here is code
$("#add-newimage").click(function () {
$("#add-image").load('/Design/AddImage/', function () {
$("#add-image").dialog('open');
var uploader= new qq.FileUploader({
element: document.getElementById("upload-image"),
action: '/Design/UploadImage',
allowedExtensions: ['jpg'],
onComplete: function (id, fileName, responseJSON) {
$("#hidden-path input").html("/Img/Temp/@User.Identity.Name/" + file);
alert($("#hidden-path input").html());
}
});
});
});
How can I make it work?
A: I would try to put the uploader code in the open event of your dialog.
$("#add-image").dialog({
open : function(event, ui) {
var uploader= new qq.FileUploader({
element: document.getElementById("upload-image"),
action: '/Design/UploadImage',
allowedExtensions: ['jpg'],
onComplete: function (id, fileName, responseJSON) {
$("#hidden-path input").html("/Img/Temp/@User.Identity.Name/" + file);
alert($("#hidden-path input").html());
}
}
});
..
$("#add-newimage").click(function () {
$("#add-image").load('/Design/AddImage/', function () {
$("#add-image").dialog('open');
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android How to use and create temporary folder I develop an app which collects some data from internet. Then save it to a temporary folder. To build this app I need to create and access a folder ( just for the purpose of app, not for the user). How can I do it?
A: this code is to create folder:
File direct = new File(Environment.getExternalStorageDirectory() + "/New Folder");
if(!direct.exists())
{
(direct.mkdir()) //directory is created;
}
try it may help you
A: File mFile;
onCreate()
mFile= new File(Environment.getExternalStorageDirectory()+"/temp/";
mFile.mkdir();
onDestroy();
mFile.delete();
A: try out this...
private void makeFolder(){
File root = new File(Environment.getExternalStorageDirectory()
+ File.separator + getString(R.string.folder_name));
boolean mainfolderexist = root.exists();
if (!mainfolderexist) {
try {
if (Environment.getExternalStorageDirectory().canWrite()) {
root.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
All The best
A: You should really check this other SO answer: https://stackoverflow.com/a/6485850/65716
Aside from the fact that you have to completely manage your use of the space, etc, caching on external storage requires more permission for your app.
See http://developer.android.com/reference/android/content/Context.html#getCacheDir()
"Apps require no extra permissions to read or write to the returned path, since this path lives in their private storage."
A: For app use only, I would recommend to use Context.getDir() for retrieving the directory if the files is used by our app only and don`t want to be visible to users by file browsers.
// No need to check if exist, created automatically.
File tempRoot = context.getDir("temp", Context.MODE_PRIVATE);
// do something
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Different Focus on Dual Monitors I have installed dual monitor on my system. I am running a process which continuously takes focus of browser. This way, I am unable to work on some other application as other application loses focus again and again.
Is there any way by which i can set different focus for different monitors?
A: I say "no" because focus can be only one.
Otherwise what would happen when you click "Ctrl+C" or "Alt+F4" or every other key combination that assumes you have 1 focused application/element?
Your solution is to deal with that application stealing your focus.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: compatibility Android 3.* with android 4 I want to build Android application. My target devices is tablets (not smartphones). Today exist only 3.* version of android OS, aimed for tablets. Is it normal if i begin build application for tablets in 3.* API? The tablets which will be release with android 4.0 (ice cream sandwich) can to run my application built on 3.0 API? Or me better to wait for 4.0 API if my target devices is tablets?
Generally, in which version of API to develop my app for tablets?
Thanks.
A: I'm pretty sure that the applications which run on Android 3.* will run on Android 4.* too, because there is no point of making and OS if the old application will not run and all the developers have to build their applications for the next version. So I suggest to build your application for Android 3.* if your target devices are tablets.
A: Android documentation says that all their SDK releases are forward friendly and that seems to be the case when using an emulator. I have an application that was written in 2.0, recently upgraded to 2.1 and we have some people in the office that have XOOM tablets (3.0) and we cant get it installed.
After some modifications to the manifest (suggested steps from droid dev portal) it still wont install on the XOOM at all.
If you are targeting tablets then i would start with 3.0. If there are features in 3.1 that you can't live without then have fun.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get all unchecked radio buttons Ok, so I've got a jQuery code which constructs my radio inputs from XML data, like this:
var items = xml.children('item');
if (items.length > 0)
{
var ul = $('<ul/>',{
class: 'priceList'
});
items.each(function(){
var $this = $(this);
var li = $('<li/>');
var img = $('<img/>',{
src: 'products/' + $this.children('image').text(),
});
var input = $('<input/>',{
type: 'radio',
id: $this.children('id').text(),
name: 'products'
});
var span = $('<span/>',{
text: $this.children('price').text() + ' USD'
});
var label = $('<label/>',{
for: $this.children('id').text()
});
label.append(img);
label.append("</br>");
label.append(span);
li.append(input);
li.append(label);
ul.hide().append(li).fadeIn('slow');
});
return ul;
}
return null;
Now I need a nice way to find all unchecked radio labels and do something with them, e.g. fade them out or change a css property. Since the XML list consists of nearly 40 items, writing an if-else construction is a no-go. Need a good solution. Thanks in advance!
EDIT: See my answer below.
A: Try this (also see my jsfiddle):
$('input').not(':checked')
A: Found it myself. None of the above answers worked for me, which is strange, because most of them should be totally legit.
What I found to be working is actually
$('input[type="radio"]:not(:checked)')
And in my case I needed
$('li input[type="radio"]:not(:checked) + label')
And the whole code is:
//we'll need m for detecting a click outside of element with our radio buttons...
var m = false;
$(document).ready(function(){
$.ajax({
type: "GET", url: 'xml.xml', dataType: 'xml',
success: function(data){
var xml = $(data);
$('#windowList').append( ItemToUl(xml.children()) );
}
});
$('.calc').hover(function(){
m=true;
}, function(){
m=false;
});
$("body").mousedown(function(){
if(! m) {
//...and unchecking a checked radio. I heard that .attr() was deprecated but couldn't get .prop() to work
$('li input[type="radio"]:checked').attr('checked', false);
$('li input[type="radio"]:not(:checked) + label').fadeTo('slow', 1);
}
});
$("li input").live("change", function(){
$('li input[type="radio"]:checked + label').fadeTo('slow', 1);
$('li input[type="radio"]:not(:checked) + label').fadeTo('slow', 0.45);
});
});
//constructing function, etc...
A: i think this sould work
$("input:!checked");
You may want to put a class selector in there as well.
Then do an .each to do something with the elements
A: $('form input[type="radio"]').not(':checked').each(function() {
$(this).addClass('unchecked');
// or
$(this).slideUp('slow');
});
Obviously the element you use is up to you but the :unchecked selector is what you're after.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Serial Number (Record Count) in Razor? Could some one point out how to include a Serial Number while populating from a table on a Razor page view.
Here's my view
@foreach (var item in Model) {
<tr>
<td>
---- ??? HOW TO INCLUDE SERIAL NUMBER HERE ??? ----
</td>
<td>
@Html.DisplayFor(modelItem => item.studentName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.studentID }) |
@Html.ActionLink("Details", "Details", new { id = item.studentID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.studentID })
</td>
</tr>
}
(Im using EF 4.1 scaffolding to autogenerate the contexts and models)
A: @foreach (var item in Model )
{
<tr>
<td> @( ((Int32) 1) + @Model.IndexOf(item) ) </td>
</tr>
}
A: @{int index = 1;}
@foreach (var item in Model)
{
<tr>
<td>
@index
</td>
</tr>
index++;
}
A: @item.Serial
If you don't want to show it in an html control. You don't need to do anything special.
EDIT: It seems you just want a counter
change the loop in your code to
@foreach (var item in Model.Select((x, i) => new { Data = x, Index = i }))
{
<tr>
<td>
@item.Index
</td>
<td>
@Html.DisplayFor(modelItem => item.Data.studentName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Data.studentID }) |
@Html.ActionLink("Details", "Details", new { id = item.Data.studentID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Data.studentID })
</td>
</tr>
}
A: <tbody>
@{
int sno = 0;
}
@foreach (var item in Model)
{
<tr>
<td>
@{ sno++; }
@sno
</td>
</tr>
}
</tbody>
A: @{ int i = 1; }
@foreach (var item in Model) {
<tr>
<td>
@i
</td>
@{ i++; }
<td>
@Html.DisplayFor(modelItem => item.studentName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.studentID }) |
@Html.ActionLink("Details", "Details", new { id = item.studentID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.studentID })
</td>
</tr>
A: @foreach (var item in Model) {
<tr>
<td>
@(Model.ToList().IndexOf(item) + 1)
</td>
<td>
@Html.DisplayFor(modelItem => item.studentName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.studentID }) |
@Html.ActionLink("Details", "Details", new { id = item.studentID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.studentID })
</td>
</tr>
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: .NET windows WPF LOCALIZATION I am new to localization ... ..I initially created a resource file(.resx file) then used resgen command to generate corresponding .resource file.. it got created.. then I used al.exe to generate corresponding satellite assembly.. it also got created .. but further when I tried to access .resx file from codebehind using Resource manager class it threw error something like--
Assembly Manifest exception ..
I am not understanding where I am wrong.. plz let me know if there is any further process to be done (plz don't suggest LOCBAML tool).. I want the solution using resource files only..
A: Your start was pretty good. Using LocBaml was too complicated for me too. So I had to figure out something easier for me. Here's solution: first, you have to create resource .resx file (this step is already done in your); Simple way to get all strings from resource file is to store it in dictionary. You can do it using this method:
public Dictionary<string, string> ApplicationStrings(string locale)
{
Dictionary<string, string> result = new Dictionary<string, string>();
ResourceManager manager = null;
// Here is two locales (custom and english locale), but you can use more than two if there's a need
if (locale == "Your locale")
{
manager = new ResourceManager(typeof(your_locale_resource_file));
}
else
{
manager = new ResourceManager(typeof(ApplicationStrings_en));
}
ResourceSet resources = manager.GetResourceSet(CultureInfo.CurrentCulture, true, true);
IDictionaryEnumerator enumerator = resources.GetEnumerator();
while (enumerator.MoveNext())
{
result.Add((string)enumerator.Key, (string)enumerator.Value);
}
return result;
}
You have to set DataContext of MainWindow as this method result and bind all you strings to the dictionary.
Binding example:
Text="{Binding [YourKey]}"
You can call this method and then change DataContext whenever and wherever you want. Thanks to Data Binding it works in runtime very well.
I am guaranteed that this solution is not the best but it's working in a simple way.
I hope it helps.
A: Have a look at these articles having details about using Resx files for localization in WPF -
Localizing a WPF Application with ResX Files
WPF Localization
I would also suggest you to go through these -
WPF Globalization and Localization Overview
WPF Localization Guidance - Whitepaper
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sending parameters in Jquery Ajax call with quotes, double or single I am unable to send data through my ajax call if the user put quotes in the textarea. Is there a way to send text with quotes? I dont want to get rid of the quotes. I guess this is usually not a big problem, i found very little online about this situation.
var description = $('#Description').val();
var title = $('#Title').val();
var parameters = '{content:' + $('#ContentCheck').is(':checked') +
',title: "' + title + '",desciption:"' + description + '"}';
A: Checkout JSON.stringify(object) which is built into javascript.
The jist is, you create a javascript object, and call stringify to create a JSON string. With your information given above, you might do:
var jsonText = JSON.stringify({
'content': $('$('#ContentCheck').is(':checked'),
'title': title,
'description': description
});
Here we define a javascript hash using the curly braces, and then pass it to stringify.
A: same problem was with me.I tried this and completely working
xmlhttp.open("POST","test_test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+encodeURIComponent(name)+"&details="+encodeURIComponent(details)+"&r_price="+r_price+"&o_price="+o_price+"&id="+id);
and use urldecode($_REQUEST['details'])` when inserting.
A: You can convert parameters into a map -- basically an associative array -- instead of a string. That way, you can do string manipulation in the backend .NET without any changes in your frontend js; e.g.
var url = 'http://path/to/your/backend/script';
var parameters = {
contentCheck: $('#ContentCheck').is(':checked'),
title: title,
description: description
};
$.post(url, parameters);
A: You can encode quotes using js and decode it server side to get the original string
//js
function totalEncode(s){
str= s.replace(/\&/g,'&');
str= str.replace(/</g,'<');
str= str.replace(/>/g,'>');
str= str.replace(/\"/g,'"');
str= str.replace(/\'/g,''');
return(str);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Stack versus Integer I've created a program to solve Cryptarithmetics for a class on Data Structures. The professor recommended that we utilize a stack consisting of linked nodes to keep track of which letters we replaced with which numbers, but I realized an integer could do the same trick. Instead of a stack {A, 1, B, 2, C, 3, D, 4} I could hold the same info in 1234.
My program, though, seems to run much more slowly than the estimation he gave us. Could someone explain why a stack would behave much more efficiently? I had assumed that, since I wouldn't be calling methods over and over again (push, pop, top, etc) and instead just add one to the 'solution' that mine would be faster.
This is not an open ended question, so do not close it. Although you can implement things different ways, I want to know why, at the heart of C++, accessing data via a Stack has performance benefits over storing in ints and extracting by moding.
Although this is homework, I don't actually need help, just very intrigued and curious.
Thanks and can't wait to learn something new!
EDIT (Adding some code)
letterAssignments is an int array of size 26. for a problem like SEND + MORE = MONEY, A isn't used so letterAssignments[0] is set to 11. All chars that are used are initialized to 10.
answerNum is a number with as many digits as there are unique characters (in this case, 8 digits).
int Cryptarithmetic::solve(){
while(!solved()){
for(size_t z = 0; z < 26; z++){
if(letterAssignments[z] != 11) letterAssignments[z] = 10;
}
if(answerNum < 1) return NULL;
size_t curAns = answerNum;
for(int i = 0; i < numDigits; i++){
if(nextUnassigned() != '$') {
size_t nextAssign = curAns % 10;
if(isAssigned(nextAssign)){
answerNum--;
continue;
}
assign(nextUnassigned(), nextAssign);
curAns /= 10;
}
}
answerNum--;
}
return answerNum;
}
Two helper methods in case you'd like to see them:
char Cryptarithmetic::nextUnassigned(){
char nextUnassigned = '$';
for(int i = 0; i < 26; i++) {
if(letterAssignments[i] == 10) return ('A' + i);
}
}
void Cryptarithmetic::assign(char letter, size_t val){
assert('A' <= letter && letter <= 'Z'); // valid letter
assert(letterAssignments[letter-'A'] != 11); // has this letter
assert(!isAssigned(val)); // not already assigned.
letterAssignments[letter-'A'] = val;
}
A: From the looks of things the way you are doing things here is quite inefficiant.
As a general rule try to have the least amount of for loops possible since each one will slow down your implementation greatly.
for instance if we strip all other code away, your program looks like
while(thing) {
for(z < 26) {
}
for(i < numDigits) {
for(i < 26) {
}
for(i < 26) {
}
}
}
this means that for each while loop you are doing ((26+26)*numDigits)+26 loop operations. Thats assuming isAssigned() does not use a loop.
Idealy you want:
while(thing) {
for(i < numDigits) {
}
}
which i'm sure is possible with changes to your code.
This is why your implementation with the integer array is much slower than an implementation using the stack which does not use the for(i < 26) loops (I assume).
In Answer to your original question however, storing an array of integers will always be faster than any struct you can come up with simply because there are more overheads involved in assigning the memory, calling functions, etc.
But as with everything, implementation is the key difference between a slow program and a fast program.
A: The div instruction used by the mod function is quite expensive. Using it for your purpose can easily be less efficient than a good stack implementation. Here is an instruction timings table: http://gmplib.org/~tege/x86-timing.pdf
You should also write unit tests for your int-based stack to make sure that it works as intended.
A: The problem is that by counting you are considering also repetitions, when may be the problem asks to assign a different number to each different letter so that the numeric equation holds.
For example for four letters you are testing 10*10*10*10=10000 letter->number mappings instead of 10*9*8*7=5040 of them (the bigger is the number of letters and bigger becomes the ratio between the two numbers...).
A: Programming is actually trading memory for time and vice versa.
Here you are packing data into integer. You spare memory but loose time.
Speed of course depends on the implementation of stack. C++ is C with classes. If you are not using classes it's basically C(as fast as C).
const int stack_size = 26;
struct Stack
{
int _data[stack_size];
int _stack_p;
Stack()
:_stack_size(0)
{}
inline void push(int val)
{
assert(_stack_p < stack_size); // this won't be overhead
// unless you compile debug version(-DNDEBUG)
_data[_stack_p] = val;
}
inline int pop()
{
assert(_stack_p > 0); // same thing. assert is very useful for tracing bugs
return _data[--_stack_p]; // good hint for RVO
}
inline int size()
{
return _stack_p;
}
inline int val(int i)
{
assert(i > 0 && i < _stack_p);
return _data[i];
}
}
There is no overhead like vtbp. Also pop() and push() are very simple so they will be inlined, so no overhead of function call. Using int as stack element also good for speed because int is guaranteed to be of best suitable size for processor(no need for alignment etc).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What are the advantages of pwrite and pread over fwrite and fread? Hey please don't mind if I am asking trivial question, but, please can somebody help me with this..
A: Current file position doesn't change after a call to pread/pwrite.
Also because you don't need to call lseek to change the current file position pread/pwrite avoid potential race conditions when multiple threads are involved.
A: There are two parts:
*
*Difference between pread/pwrite and read/write:
They are both at the same level, namely system calls. There are two differences:
*
*The "p" variants take offset to read from, so they are independent of the current file pointer. That makes it easier to read/write from multiple threads concurrently.
*The "p" variants only work on seekable files (i.e. real files, not pipes, sockets or devices).
*Difference between read/pread/write/pwrite and fread/fwrite:
The "f" variants are standard runtime wrappers of the former (using the basic variants). They support in-process buffering. That can significantly improve performance for simple code, but it makes use of other features of the system-call level impractical.
Only use the "p" variants if you have good use for reading at random offsets (avoiding seeks and allowing concurrent access via one file handle), which often the case with some kind of database files (record-oriented with records at known offsets) and rarely in other applications.
A: It's useful when you do a lot of random read/write operations. There is even an option for SQLite3 that replaces seek() + read() and seek()+ write() with pread()/pwrite().
The advantage: seek()+ read() and seek() + write() both are the pairs of system calls while pread() and pwrite() are single system calls. It's usually an universal truth that the less system calls program issues the more efficient it is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: JPA (hibernate) relation OneToMany with date I need to create hibernate relation one to many between Department and Person (one Department has many persons).
The problem is that I want to maintain time validity. Without ORM (hibernate) it is easy to select persons of particular department at specified date:
select * from Person where department_id = ? and ? between validFrom and validTill
How can I do it with JPA hibernate?
class Department {
Long id;
String code;
String name;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "departmentId")
@OnDelete(action = OnDeleteAction.CASCADE)
private Set<Person> persons = new HashSet<Person>();
}
class Person {
Long id;
String name;
String surname;
Date validFrom;
Date validTill;
}
And how to do it if Department is time valid too?
select P.* from Person P, Deparment d
where d.code = ? and
p.department_id = d.department_id and
? between d.validFrom and d.validTill and
? between p.validFrom and p.validTill
All records with same deparment.code is one department.
A: You do it in JPA the same way that you're doing it with SQL. Just make it a JPQL query rather that a SQL query:
select p from Person p
inner join p.department d
where d.code = :departmentCode
and :today between d.validFrom and d.validTill
and :today between p.validFrom and p.validTill
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cron not working with minutes (Update: apparently there are no seconds in cron jobs. However, my question now becomes: what explains the cron behaving this way? Thank you)
I have two cron triggers, one is supposed to come in just moments before the other one.
First I had task 1 come in every 59 seconds
*/59 * * * * ?
And task 2 come in every 59 seconds, but offset by 15 seconds.
15/59 * * * * ?
This worked fine. No complaints. Now I want to just move this values over to the minutes column. This time, there is only a minute offset, which is negligible since the task repeats every 59 minutes.
Task 1
* */59 * * * ?
Task 2
* 1/59 * * * ?
Suddenly, task 1 is constantly firing and task 2 doesn't fire at all. The change described above seems to be the only thing affecting this.
A: * */59 * * * means run every minute (the first * is minutes) in the current hour, and then wait 59 hours to run again.
* 1/59 * * * means run every minute in the first hour (which you are not in, hence task 2 never fires) and then run every minute in the hour 50 hours later.
I think the problem is still the seconds/minutes confusion.
EDIT: Note some versions of Cron will not accept a number preceding a '/'... it must be a range. So for your use case I would use */59 * * * * and 1-59/59 * * * *
A: Because there are no seconds
* * * * * command to be executed
β¬ β¬ β¬ β¬ β¬
β β β β β
β β β β β
β β β β ββββββ day of week (0 - 7) (Sunday=0 or 7)
β β β βββββββββββ month (1 - 12)
β β ββββββββββββββββ day of month (1 - 31)
β βββββββββββββββββββββ hour (0 - 23)
ββββββββββββββββββββββββββ min (0 - 59)
http://en.wikipedia.org/wiki/Cron
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to Insert JSON data object to Spring MVC application (via controller) with Jquery I want to Insert JSON data object (User) to my Spring MVC application (via controller) with Jquery. if code is like follow how can I accomplish this? Thanks.
User Object
public class User {
private Integer usId;
private String usName;
private Boolean usActive;
}
Spring Controller
@Controller
@RequestMapping(value="/user")
public class UserController {
@Autowired
UserService userService;
private Validator validator;
@RequestMapping(method=RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> create(@RequestBody User user, HttpServletResponse response) {
Set<ConstraintViolation<User>> failures = validator.validate(user);
userService.insert(user);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
return Collections.singletonMap("id", user.getUsId());
}
}
}
A: $.post("/user", { usName: "John", usActive: "true" } );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Replace previous files in windows setup I have created a setup using VS2008 setup wizard. It works fine and installs my application well. But the problem is that when a user installs a new version of the app, the setup doesn't overwrite the previous Database.
For example in v1.1 I have a db with 2 tables but in 1.2 I added 1 more table so when a user with v1.1 installs v1.2 the setup doesn't remove the 1.1 db. Hence the user uses an old db with 2 tables and the app fails to work properly.
I am using c#
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Correct way to get beans from applicationContext Spring I have a factory that creates instances:
public class myFactory {
public static getInstace() {
switch(someInt) {
case 1:
return new MySpringBean();
case 2:
return new MyOtherSpringBean();
}
}
}
I need to return a new instance of the beans that are "managed" by Spring bc they have Transactional business logic methods. I have read in many posts here that I should not use getBean method to get a singleton or a new instance from the applicationContext. But I cannot find the proper way to do it for my case. I have used @Resource and it seems to work but it doesn't support static fields.
Thanx
A: There are many ways to achieve this in spring, the most obvious way given the factory class that you have is to use JavaConfig. If you used the spring enabled JavaConfig annotations you could do the following to construct your beans and add them to the application context:
@Configuration
public class myFactory {
@Bean
public static getInstance() {
switch(someInt) {
case 1:
return new MySpringBean();
case 2:
return new MyOtherSpringBean();
}
}
}
A: One way is create a factory class and store the instances of the beans (each implementing a common interface MyBean) as values under some key in a map (beans):
public class MyBeanFactory {
private Map<Integer, MyBean> beans;
public MyBean create(Integer which) {
if (which != null)
return beans.get(which);
else
throw new IllegalArgumentException("Unknown bean");
}
public void setBeans(Map<Integer, MyBean> beans) {
this.beans = beans;
}
}
In your Spring applicationContext.xml now create bean a of the factory and set the beans:
<beans...>
<bean id="myBeanFactory" class="foo.bar.MyBeanFactory">
<property name="beans">
<map>
<entry key="1">
<bean class="foo.bar.MyBeanA" />
</entry>
<entry key="2">
<bean class="foo.bar.MyBeanB" />
</entry>
</map>
</property>
</bean>
</beans>
Finally you can inject your bean factory as usual and get instances from like e.g. this:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext.xml" })
public class MyBeanFactoryTest {
@Autowired
private MyBeanFactory myBeanFactory;
@Test
public void test() {
Assert.assertTrue(myBeanFactory.create(1) instanceof MyBeanA);
Assert.assertTrue(myBeanFactory.create(2) instanceof MyBeanB);
}
}
A: You implement the org.springframework.beans.factory.FactoryBean interface for objects that are themselves factories.
The FactoryBean interface is a point of pluggability into the Spring IoC container's instantiation logic. If you have complex initialization code that is better expressed in Java as opposed to a (potentially) verbose amount of XML, you can create your own FactoryBean, write the complex initialization inside that class, and then plug your custom FactoryBean into the container.
The FactoryBean interface provides three methods:
*
*Object getObject(): returns an instance of the object this factory creates. The instance can possibly be shared, depending on whether this factory returns singletons or prototypes.
*boolean isSingleton(): returns true if this FactoryBean returns singletons, false otherwise.
*Class getObjectType(): returns the object type returned by the getObject() method or null if the type is not known in advance
Take a look at Spring Docs
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Generating second graph in different window - VPython If I have a graph like this in VPython: graphX = gcurve(color = color.cyan), how can I make another graph (graphY = gcurve(color = color.red)) in a different window (different set of axes)?
A: use gdisplay() to create graph window:
from visual.graph import *
graphX = gcurve(color = color.cyan)
gdisplay()
graphY = gcurve(color = color.red)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there any API that tells whether an Android device is dual-core or not? I am doing dual core optimization by multi-threading, and it works like this:
If the device has dual-core processor, two threads are created to do the computation, and if the device has only one-core processor, only one thread is created to do the computation.
My question is: how does my program know whether a device is dual-core or not?
I just want to have one program that can run on both dual-core and one-core devices, so it has to be able to know that information.
code like this:
if( xxx_API_is_device_dual_core() ) // Inside if() is the expected API
{
saveThread = new SaveThread[2];
}
else
{
saveThread = new SaveThread[1];
}
Thank you very much for any help!
A: The Runtime.availableProcessors() doesn't seem to work correctly for all Android devices (for example, it only returns "1" on my dual-core Galaxy S II). There may be some confusion between physical CPUs, and virtual CPUs, aka Cores.
The most reliable method I've found is described in this forum post. Basically, you have to count the virtual CPU devices in /sys/devices/system/cpu/. This will work with dual-core and quad-core devices with no modifications.
I've tested this method on my Galaxy S II (2 cores) and Asus Transformer Prime (4 cores) and it reports correctly. Here's some sample code (taken from my answer to this question):
/**
* Gets the number of cores available in this device, across all processors.
* Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
* @return The number of cores, or 1 if failed to get result
*/
private int getNumCores() {
//Private Class to display only CPU devices in the directory listing
class CpuFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
//Check if filename is "cpu", followed by a single digit number
if(Pattern.matches("cpu[0-9]", pathname.getName())) {
return true;
}
return false;
}
}
try {
//Get directory containing CPU info
File dir = new File("/sys/devices/system/cpu/");
//Filter to only list the devices we care about
File[] files = dir.listFiles(new CpuFilter());
//Return the number of cores (virtual CPU devices)
return files.length;
} catch(Exception e) {
//Default to return 1 core
return 1;
}
}
A: Is Runtime.availableProcessors() fails to report correctly on the 2-core device?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: asp.net mvc keep object alive, information i have this code
[HttpPost]
public ActionResult Index(LoginModel loginModel)
{
if (ModelState.IsValid)
{
// some lines of code . bla bla bla
TempData["loginModel"] = loginModel;
return RedirectToAction("index", "premium");
}
...
}
and this controller here
public ActionResult Index()
{
var loginModel = TempData["loginModel"] as LoginModel;
...
}
now, when the page loads, everything seems to work fine. but when i refresh, everything messes up, it says that the loginModel is like null. the question is, how can i like keep track of the current login users. i have forms authentication enabled. tnx
error is as below
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 22:
Line 23: var loginModel = TempData["loginModel"] as LoginModel;
Line 24: string username = loginModel.username;
Line 25: string password = loginModel.password;
Line 26: premiumModel.username = username;
A: Confusion
but when i refresh, everything messes up, it says that the loginModel
is like null
Answer
This is due to the fact that you have read the TempData key and Once it is read, data will be lost for that particular key.
var Value = TempData["keyName"] //Once read, data will be lost
Question
how can i like keep track of the current login users
Answer
So to persist the data even after the data is read you can Alive it like below
var Value = TempData["keyName"];
TempData.Keep(); //Data will not be lost for all Keys
TempData.Keep("keyName"); //Data will not be lost for this Key
TempData works in new Tabs/Windows also, like Session variable does.
You could use Session Variable also, Only major problem is that Session Variable are very heavy comparing with TempData. Finally you are able to keep the data across Controllers/Area also.
Hope this post will help you alot.
A: You only need to store the user's identity (username) once the user is authenticated - password is not needed. As such ASP.NET authentication already supports storing user's identity in the authentication cookie and you don't have to re-invent the wheel. You can get the identity using Controller.User property.
EDIT: I am assuming that you have set up your application correctly for Forms Authentication. Regardless, here are few how-to/tutorial links that start you on it:
*
*http://www.apexa.net/Blog/web_design_Blog_20100319.aspx
*http://www.asp.net/mvc/tutorials/authenticating-users-with-forms-authentication-cs
*Explain solution so that you don't have to apply Authorize attribute on every action - http://blogs.msdn.com/b/rickandy/archive/2011/05/02/securing-your-asp-net-mvc-3-application.aspx
A: TempData does only live for one request. Therefore it's empty when you make the second request. If you'd want to do it like this you should use Session instead or you can have a look at forms authentication.
You should also consider VinayC advice and not store any password information in any state, especially not in clear text format.
A: I suggest you create a new MVC 3 project in Visual Studio via File > New. It will set up forms authentication for you, so you can see the best practices for the login and registration pages, signing the user in/out with the session cookie, and displaying user info like username.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Wordpress Theme Got 502 proxy error -The proxy server could not handle the request GET /check I just finished create my own wordpress theme. But when I checked the html validation through validator.w3.com, it got:
502 Proxy Error
The proxy server received an invalid response from an upstream server.
The proxy server could not handle the request GET /check.
Reason: Error reading from remote server.
Apache/2 Server at validator.w3.org Port 80
What does it mean? As far as I know, I don't play around using any proxy server.
----- EDIT: -----
Looks like the problem is in functions.php:
if(isset($_GET['page']) && $_GET['page']=='admin-functions.php'){
**codes here***
}
If I remove the if(isset($_GET['page']) && $_GET['page']=='admin-functions.php'), it returns no 502 proxy error. How should I fix this code to get through the w3 validator?
Many thanks!
----- EDIT: -----
oh well, apparently it's not the problem. Even if I remove the if(isset($_GET['page']) && $_GET['page']=='admin-functions.php'), it sometimes returns 502 error, but sometimes not. I really don't get the idea.
-----FOUND THE SOLUTION!-----
call me stupid!
I found the problem:
I use these DOCTYPEs:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
then I erased all of them and change to :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Works fine now
A: I found the problem:
I use these DOCTYPEs:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
then I erased all of them and change to :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Works fine now
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.