text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How to write in two fields at a time in objective-c? I have two UITextFields one field is RISK and other is WIN. Now when user start writing in RISK field then it should accordingly calculate the value of WIN and should be filled in WIN field. Formula is this
if (a<0) {
WIN = RISK/(-a/100)
}
else {
WIN = RISK*(a/100)
}
and if value is entered in WIN then it should populate the value in RISK, formula is
if (a<0) {
RISK = WIN*(-a/100)
}
else {
RISK= WIN*(100/a)
}
so please guys guide me how can i populate the fields without pressing any button and how can i calculate the values?
Thanx in advance
A: You should implement the UITextFieldDelegate. Set a class, perhaps your view controller to the delegate of the WIN textfield, then implement this method.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
Inside the method, convert the string to a number, run your formula, change the value of the RISK textfield and return YES.
A: Assuming you have a property for each field:
@property (nonatomic, retain) IBOutlet UITextField win;
@property (nonatomic, retain) IBOutlet UITextField risk;
and IBAction methods:
- (IBAction) winDidChange: (id) sender;
- (IBAction) riskDidChange: (id) sender;
Hook these up in interface builder to the Editing Changed event:
Your method will look something like:
- (IBAction) winDidChange: (id) sender
{
float winValue = [self.win.text floatValue];
float riskValue = <your calculation here>
self.risk.text = [NSString stringWithFormat: @"%f", riskValue];
}
.. and similarly for riskDidChange:
If you hook up the Editing Changed event of the win field to the winDidChange: IBAction in interface builder (and the same for risk), the method will be called every time a character is typed into the field.
You should read The Target-Action Mechanism section in http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html
A: You can implement the delegate method (UITextFieldDelegate) to make use of the following methods....
*
*textFieldShouldBeginEditing:
*textFieldDidBeginEditing:
*textFieldShouldEndEditing:
*textfieldDidEndEditing:
*textField:shouldChangeCharactersInRange:replacementString:
When a value changes, you can use these delegate methods to update your other value.
A: all you need to do is
[myTextField addTarget:self action:@selector(myFunction:) forControlEvents:UIControlEventEditingChanged];
and then
- (void)myFunction:(id)sender {
//calculate and show in WIN field
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: check if value changed upon change() trigger I noticed that change() can be triggered for a <select> even if the option was not changed.
See my jsfiddle example.
Changing the selection will change the text input displayed. However (and I do know it's a bit of stretch) if you:
*
*select the drop down by clicking on its label Selection:
*press down on the keyboard (assuming Show A was selected)
*then select Show A with the mouse pointer it will trigger change().
Is there an easy workaround for this (right now I'm thinking of using a variable to keep track what the last selection was upon change())?
EDIT:
It seems it is a Chrome-specific problem. I was able to fix the problem by using a variable to keep track of what the last selected item was. I guess this a bug left for the jQuery/Chrome developers.
A: I would store the current value as data on the element (rather than a variable) like this:
$('#variable').data('currentval', $('#variable').val()).change(function() {
var t = $(this);
if (t.data('currentval') != t.val()) {
$(this).data('currentval', $(this).val());
$('#listA').toggle('fast');
$('#listB').toggle('fast');
}
});
http://jsfiddle.net/emMx6/2/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Programmatically start crawling a given content source in Sharepoint 2010 Is it possible to programmatically start crawling a given content source (say a file share) through Sharepoint API or any other means?
A: Based on Rob's comment above I found this to be helpful. Following is the C# code I did.
The code in the link throws an error on SPServiceContext.Current if you're building a console app. So the first step and the GetContext() method are specific to that situation.
SPSite mySite = new SPSite("http://localhost");
SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy(SPServiceContext.GetContext(mySite)); Guid appId = proxy.GetSearchServiceApplicationInfo().SearchServiceApplicationId;
//Console.WriteLine("AppID : " + appId.ToString());
SearchServiceApplication app = SearchService.Service.SearchApplications.GetValue<SearchServiceApplication>(appId);
Content content = new Content(app);
ContentSourceCollection cs = content.ContentSources;
Console.WriteLine("Name\tId\tCrawlCompleted");
foreach (ContentSource csi in cs)
{
Console.WriteLine(csi.Name + "\t" + csi.Id + "\t" + csi.CrawlCompleted);
}
Console.WriteLine("Starting full crawl....");
ContentSource css = content.ContentSources["source name"]; //csi.Name within square brackets
css.StartFullCrawl();
Console.WriteLine("Full crawl on source name started...");
Be sure to adjust the build target platform in the Project Properties with the Sharepoint installation. Otherwise SpSite will not be created.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook - Canvas HTTPS Security Migration I can't seem to find anything definitive, with the HTTPS migration, what will happen to existing apps that are just on HTTP? Will they cease to work? Or is it just a case that any new apps will need to be on HTTPS and the old ones will be fine?
If I read rightly I think it's a case that all existing apps will need to be converted.
Cheers guys
A: From what I understand, any existing apps that haven't entered a secure url will be disabled. My guess is they'll be stuck in sandbox mode until you enter that url.
A: I just set up a test app today that embeds into the canvas. I found that while it requires it to be HTTPS, it doesn't care if you use a self-signed certificate, so they're not insisting that users spend money to keep using their canvas apps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android table creation Failure (near "autoincrement": syntax error)? public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final String MYDATABASE_TABLE2 = "MY_TABLE2";
public static final int MYDATABASE_VERSION = 1;
public static final String KEY_ID = "_id";
public static final String KEY_ID2 = "_id2";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
//create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE = "create table " + MYDATABASE_TABLE + " ("
+KEY_ID + " integer primary key autoincrement, "
+ KEY_CONTENT1 + " text not null);";
private static final String SCRIPT_CREATE_DATABASE2 = "create table " + MYDATABASE_TABLE2 + " ("
+ KEY_ID2 + " integer autoincrement, "
+ KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + " text not null, "
+ " FOREIGN KEY ("+KEY_ID2+") REFERENCES "+MYDATABASE_TABLE+" ("+KEY_ID+"));";
I can not find out what gives the following error, please help me out thank you.
09-29 13:41:19.760: ERROR/Database(334): Failure 1 (near
"autoincrement": syntax error) on 0x218df0 when preparing 'create
table MY_TABLE2 (_id2 integer autoincrement, Content2 text not null,
Content3 text not null, FOREIGN KEY (_id2) REFERENCES MY_TABLE
(_id));'.
09-29 13:41:19.770: DEBUG/AndroidRuntime(334): Shutting down VM
09-29 13:41:19.770: WARN/dalvikvm(334): threadid=1: thread exiting
with uncaught exception (group=0x4001d800)
09-29 13:41:19.791: ERROR/AndroidRuntime(334): FATAL EXCEPTION: main
09-29 13:41:19.791: ERROR/AndroidRuntime(334):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{sep.com/sep.com.SepActivity}:
android.database.sqlite.SQLiteException: near "autoincrement": syntax
error: create table MY_TABLE2 (_id2 integer autoincrement, Content2
text not null, Content3 text not null, FOREIGN KEY (_id2) REFERENCES
MY_TABLE (_id));
A: This:
+ KEY_ID2 + " integer autoincrement, "
should be this:
+ KEY_ID2 + " integer primary key autoincrement, "
If you follow the syntax diagrams for CREATE TABLE you'll see that autoincrement should only come after primary key.
If you want _id2 to be a foreign key then you don't want it to be auto increment at all though.
A: An above answer says that 'There is no autoincrement keyword in SQLite.' This is incorrect. There is a keyword called 'autoincrement' and I used it in the primary key.
For example:
static final String CREATE_LOCATION_TABLE="CREATE TABLE Location"+
"( LocationID INTEGER PRIMARY KEY AUTOINCREMENT," +
" RestuarantID int not null," +
" Latitude float not null," +
" Longitude float not null)";
Also make sure when you enter data to this table use the keyword 'null' in the place of the primary key.
Like this:
static final String INSERT_LOCATION= "Insert into Location values" +
"(null,1002,6.905369,79.851514)";
A: In short: In SQLite a column declared INTEGER PRIMARY KEY will autoincrement. There is no autoincrement keyword in SQLite, that is why you are getting an error.
You can find out more on SQLite FAQ.
EDIT: just writing integer primary key it is enough. SQLite will automatically increment your ids.
EDIT2: Your onUpgrade() method should look like this :
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
Log.w("MyAppTag","Updating database from version " + oldVersion + " to "
+ newVersion + " .Existing data will be lost.");
db.execSQL("DROP TABLE IF EXISTS " + MY_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + MY_TABLE2);
onCreate(db);
}
A: Three things:
*
*Remove the trailing ; from the statements.
*Add "primary key" constraint to the autoincrement column
*Remove autoincrement from PK columns - it will happen automatically.
A: sqlite> CREATE TABLE app (a INTEGER PRIMARY KEY NOT NULL, B VARCHAR);
sqlite> insert into app (b) values ('');
sqlite> insert into app (b) values ('a');
sqlite>
sqlite> insert into app (b) values ('b');
sqlite> insert into app (b) values ('c');
sqlite> insert into app (b) values ('d');
sqlite> select * from app;
1|
2|a
3|b
4|c
5|d
sqlite> exit;
NOTE: IN SQLite there in no AUTOINCREMENT keyword. So, you have to just use INTEGER PRIMARY KEY NOT NULL. It will automatically insert the incremented value for the attribute.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: RES != CODE + DATA in the output information of the top command,why? what 'man top' said is: RES = CODE + DATA
q: RES -- Resident size (kb)
The non-swapped physical memory a task has used.
RES = CODE + DATA.
r: CODE -- Code size (kb)
The amount of physical memory devoted to executable code, also known as the 'text resident set' size or TRS.
s: DATA -- Data+Stack size (kb)
The amount of physical memory devoted to other than executable code, also known as the 'data >resident set' size or DRS.
what when i run 'top -p 4258',i get the following:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ CODE DATA COMMAND
258 root 16 0 3160 1796 1328 S 0.0 0.3 0:00.10 476 416 bash
1796 != 476+416
why?
ps:
linux distribution:
linux-iguu:~ # lsb_release -a
LSB Version: core-2.0-noarch:core-3.0-noarch:core-2.0-ia32:core-3.0-ia32:desktop-3.1-ia32:desktop-3.1-noarch:graphics-2.0-ia32:graphics-2.0-noarch:graphics-3.1-ia32:graphics-3.1-noarch
Distributor ID: SUSE LINUX
Description: SUSE Linux Enterprise Server 9 (i586)
Release: 9
Codename: n/a
kernel version:
linux-iguu:~ # uname -a
Linux linux-iguu 2.6.16.60-0.21-default #1 Tue May 6 12:41:02 UTC 2008 i686 i686 i386 GNU/Linux
A: I'll explain this with the help of an example of what happens when a program allocates and uses memory. Specifically, this program:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(){
int *data, size, count, i;
printf( "fyi: your ints are %d bytes large\n", sizeof(int) );
printf( "Enter number of ints to malloc: " );
scanf( "%d", &size );
data = malloc( sizeof(int) * size );
if( !data ){
perror( "failed to malloc" );
exit( EXIT_FAILURE );
}
printf( "Enter number of ints to initialize: " );
scanf( "%d", &count );
for( i = 0; i < count; i++ ){
data[i] = 1337;
}
printf( "I'm going to hang out here until you hit <enter>" );
while( getchar() != '\n' );
while( getchar() != '\n' );
exit( EXIT_SUCCESS );
}
This is a simple program that asks you how many integers to allocate, allocates them, asks how many of those integers to initialize, and then initializes them. For a run where I allocate 1250000 integers and initialize 500000 of them:
$ ./a.out
fyi: your ints are 4 bytes large
Enter number of ints to malloc: 1250000
Enter number of ints to initialize: 500000
Top reports the following information:
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ SWAP CODE DATA COMMAND
<program start>
11129 xxxxxxx 16 0 3628 408 336 S 0 0.0 0:00.00 3220 4 124 a.out
<allocate 1250000 ints>
11129 xxxxxxx 16 0 8512 476 392 S 0 0.0 0:00.00 8036 4 5008 a.out
<initialize 500000 ints>
11129 xxxxxxx 15 0 8512 2432 396 S 0 0.0 0:00.00 6080 4 5008 a.out
The relevant information is:
DATA CODE RES VIRT
before allocation: 124 4 408 3628
after 5MB allocation: 5008 4 476 8512
after 2MB initialization: 5008 4 2432 8512
After I malloc'd 5MB of data, both VIRT and DATA increased by ~5MB, but RES did not. RES did increase after I touched 2MB of the integers I allocated, but DATA and VIRT stayed the same.
VIRT is the total amount of virtual memory used by the process, including what is shared and what is over-committed. DATA is the amount of virtual memory used that isn't shared and that isn't code-text. I.e., it is the virtual stack and heap of the process. RES is not virtual: it is a measurment of how much memory the process is actually using at that specific time.
So in your case, the large inequality CODE+DATA < RES is likely the shared libraries included by the process. In my example (and yours), SHR+CODE+DATA is a closer approximation to RES.
Hope this helps.
There's a lot of hand-waving and voodoo associated with top and ps. There are many articles (rants?) online about the descrepancies. E.g., this and this.
A: This explanation is terrific to resolve my some queries. Thanks!
And meanwhile, trying to add something got during my understanding of linux memory management knowledge. If any misunderstand, please correct me!
*
*Modern OS process concepts are based on virtual memory. Virtual memory system includes the RAM+SWAP;
So I think most of the memory concepts related with processes refer to the virtual memory, except that there are some supplement notes.
*Any virtual address(page) allocated to a process is in below state:
a) allocated, but no mapping to any physical memory(something like COW)
b) allocated, already mapped to physical memory
c) allocated, already mapped to swapped memory.
*The fields ouput of top command:
a) VIRT -- it refers to all virtual memory that the process have the right
to access, no matter it is already mapped to physical memory or swapped
memory, or even has no any mapping.
b) RES -- it refers to the virtual address already mapped to physical address and it still in RAM.
c) SWAP -- refers to the virtual address already mapped to physical address and it is swapped into SWAP space.
d) SHR -- it refers to the shared memory available to a process(VM?)
e) CODE + DATA -- CODE could be in a state of 2.b/2.c, and DATA could be in any of 3 state 2.a/2.b/3.c, and 3.b/3.c also have a fields name called "USED".
4) So the calculation maybe look like:
a) VIRT(VM) = RES(VM in memory) + SWAP(VM in swap) + VM unmapped(DATA, SHR?).
b) USED = RES + SWAP
c) SWAP = CODE(vm in memory) + DATA(vm in memory) + SHR(vm in memory?)
d) RES = CODE(vm in memory) + DATA(vm in memory) + SHR(vm in memory?)
At least DATA segment still have a "DATA(VM unmapped)", this could be observed from above malloc example. That's a little different from the manpage of top command which says "DATA: The amount of physical memory devoted to other than executable code, also known as the Data Resident Set size or DRS". Thanks again.
So amount of (CODE + DATA + SHR) usually larger than RES, because at least DATA(vm unmapped) actually calculated in "DATA", not like the manpge claiming.
Regards,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: use jquery to remove element from parent i have a form with multiple div elements like this
<div>
<label for="id">text</label>
<input type="text" name="id" id="id" value="">
</div>
<div>
<label for="id1">text</label>
<input type="text" name="id1" id="id1" value="">
</div>
i use .post to validate some fields before submit
if the input failed validation i add a span element to the parent div
$('#id').parent('div:first').append('<span class="error">error message</span>');
<div>
<label for="id">text</label>
<input type="text" name="id" id="id" value="">
<span class="error">error message</span>
</div>
else i want to remove the span from the div and i tried
$('#id').parent('div:first').remove('.error');
$('#id').parent('div:first').remove('span');
but doesn't work
any ideas ?
A: You could do:
$('#id').nextAll('span.error').remove();
This would remove all the with class error following the input
fiddle here: http://jsfiddle.net/H5sDC/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java Garbage Collection Defragmentation I am getting a OutOfMemoryError java heap exception when just allocating and deallocating a byte array, even though there is enough free memory for the allocation.
There is a short log below. I know from running on a different JVM, that the problem is due to fragmented memory and that the largest free block is only about 6MB. I thought that the java (oracle) JVM should take care of fragmented memory.
This is my test:
*
*Set up the java JVM with params -Xms10M -Xmx10M
*I allocate a byte array of say 90percent of the JVM Memory.
*Set this byte array then to null, then try to re-allocate the byte array of 90percent of the JVM memory.
*We see from the logs that JVM memory has reset to the full amount, yet we cant allocate the same amount of memory.
*Hence the memory must be fragmented?
Here are my details:
Total Free Memory: 9881728
Attempting to Allocate Array of size: 6917209
Freeing Allocated Array of size: 6917209
Total Free Memory: 9881728
Attempting to Allocate Array of size: 6917209
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
The other JVM that I am running is CEE-J by Skelmir, I am running on a low memory device so I cannot set the MaxPermSize. It is interesting that the java heap is split into different areas, can these areas change size after garbage collection ?I have run another tests where I,
First create a byte array for about 95 percent of the memory,
then release the array again,
then I create a load of arrays of objects which contain hashmaps, each with one entry,
i clear the array and maps, then reallocate the same arrays again.
I check the memory each time i allocate and free. After doing this say 10 times,
i free the memory for the last time,
Then I check the memory, see that I have the full JVM allocation,
I then try to allocate the 95% of the JVM allocation again and get the same JVM out of memory exception, even though it says I have enough memory to allocate?
public static void main(String[] args) throws InterruptedException {
Runtime s_runtime = Runtime.getRuntime ();
long used_memory = s_runtime.totalMemory () - s_runtime.freeMemory ();
long start_memory = used_memory;
long freeMemory = s_runtime.freeMemory();
Integer numSubMemories = 1;
Integer numMapEntries = 1;
Integer numIterations = 1;
float percentMem = (float) 1.0;
if(args.length>0){
if(args[0]!=null){
String subEntries = args[0];
if(subEntries.length()>0){
numSubMemories = Integer.parseInt(subEntries);
}
}
if(args[1]!=null){
String mapEntries = args[1];
if(mapEntries.length()>0){
numMapEntries = Integer.parseInt(mapEntries);
}
}
if(args[2]!=null){
String numIts = args[2];
if(numIts.length()>0){
numIterations = Integer.parseInt(numIts);
}
}
if(args[3]!=null){
String percentMemArg = args[3];
if(percentMemArg.length()>0){
percentMem = Float.parseFloat(percentMemArg);
}
}
}
System.out.println("Total Free Memory: " + freeMemory);
int numBytes = (int) (freeMemory * percentMem);
System.out.println("Attempting to Allocate Array of size: " + numBytes);
byte[] mbyteArray = new byte[numBytes];
System.out.println("Freeing Allocated Array of size: " + numBytes);
mbyteArray = null;
TestMemory myMemory = new TestMemory(numSubMemories,numMapEntries);
used_memory = s_runtime.totalMemory () - s_runtime.freeMemory ();
System.out.println("Used Memory: " + used_memory);
long after_allocation_memory = used_memory;
for(int i=0;i<numIterations;i++){
System.out.println("\t\t--Iteration: "+ i + " about to release Memory");
myMemory.releaseMemoryArray(numSubMemories);
System.out.println("\t\t--Iteration: "+ i + " about to reallocate Memory");
myMemory.reAllocateMemoryArray(numSubMemories,numMapEntries);
used_memory = s_runtime.totalMemory () - s_runtime.freeMemory ();
System.out.println("\t\t--Used Memory: " + used_memory);
System.out.println("\t\t--Max Memory: " + s_runtime.maxMemory());
System.out.println("\t\t--Free Memory: " + s_runtime.freeMemory());
System.gc();
System.out.flush();
}
System.out.println("Releasing the Arrays for the last time");
myMemory.releaseMemoryArray(numSubMemories);
System.gc();
freeMemory = s_runtime.freeMemory();
//numBytes = (int)(freeMemory*0.95);
System.out.println("Attempting to Allocate Array of size: " + numBytes);
System.out.println("Total Free Memory: " + freeMemory);
mbyteArray = new byte[numBytes];
long end_memory = used_memory;
//System.gc();
Thread.sleep(6000);
used_memory = s_runtime.totalMemory () - s_runtime.freeMemory ();
System.out.println("------Results---------");
System.out.println(" Start Memory: " + start_memory);
System.out.println(" After Memory: " + after_allocation_memory);
System.out.println(" End Memory: " + end_memory);
System.out.println("End Release Memory: " + used_memory);
}
Output Log from the second test.
Total Free Memory: 9881728
Attempting to Allocate Array of size: 6917209
Freeing Allocated Array of size: 6917209
Used Memory: 7519744
-Iteration: 0 about to release Memory
-Iteration: 0 about to reallocate Memory
-Used Memory: 7890928
-Max Memory: 10092544
-Free Memory: 2147808
-Iteration: 1 about to release Memory
-Iteration: 1 about to reallocate Memory
-Used Memory: 930952
-Max Memory: 10092544
-Free Memory: 9107792
-Iteration: 2 about to release Memory
-Iteration: 2 about to reallocate Memory
-Used Memory: 1181832
-Max Memory: 10092544
-Free Memory: 8856912
-Iteration: 3 about to release Memory
-Iteration: 3 about to reallocate Memory
-Used Memory: 1190552
-Max Memory: 10092544
-Free Memory: 8848192
-Iteration: 4 about to release Memory
-Iteration: 4 about to reallocate Memory
-Used Memory: 902408
-Max Memory: 10092544
-Free Memory: 9190136
-Iteration: 5 about to release Memory
-Iteration: 5 about to reallocate Memory
-Used Memory: 902408
-Max Memory: 10092544
-Free Memory: 9190136
-Iteration: 6 about to release Memory
-Iteration: 6 about to reallocate Memory
-Used Memory: 902408
-Max Memory: 10092544
-Free Memory: 9190136
-Iteration: 7 about to release Memory
-Iteration: 7 about to reallocate Memory
-Used Memory: 902408
-Max Memory: 10092544
-Free Memory: 9190136
-Iteration: 8 about to release Memory
-Iteration: 8 about to reallocate Memory
-Used Memory: 902408
-Max Memory: 10092544
-Free Memory: 9190136
-Iteration: 9 about to release Memory
-Iteration: 9 about to reallocate Memory
-Used Memory: 902408
-Max Memory: 10092544
-Free Memory: 9190136
Releasing the Arrays for the last time
Attempting to Allocate Array of size: 6917209
Total Free Memory: 9956688
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
A: The Java heap is split into a number of areas. A single allocation cannot span areas. There are various -XX options in the Oracle JRE [I'll let some one else point to the details] that allow configuration of allocations. You could set the eden and survivor areas to be very small. Another issue if insufficient memory is available after a collection, you might still get an OOME to prevent thrashing (again more -XX options to control that).
A: Add -XX:MaxPermSize argument to provide adequate space to Heap.
-XX:MaxPermSize=512m
A: In which other JVM you successfully ran your program. If you are talking about IBM jdk there heap management is totally different from Sun(Oracle)jvm heap management. http://download.boulder.ibm.com/ibmdl/pub/software/dw/jdk/diagnosis/GCandMemory-042005.pdf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Calculate height of a HTML-Table generated by HtmlTextWriter (C#) I generate a HTML-Page from C#. In the HTML-Page there are a lot of elements. All of them have a absolute position.
One of these elements is a table. This table represents a object that keeps a double[]. Every double value is a new cell in a new row.
I iterate over double[] and create my table:
for (int i = 0; i < dbl.Length; i++)
{
htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Tr);
htmlTextWriter.RenderBeginTag(HtmlTextWriterTag.Td);
htmlTextWriter.Write(dbl[i]);
htmlTextWriter.RenderEndTag(); // td
htmlTextWriter.RenderEndTag(); // tr
}
If the table has so much elements, that it cross an element that is below this table, I have to be responsive to this issue.
This means, I need to know how many pixels this table is long.
Of course I do know how many cells I generate and I also know BorderSize, Padding, Margin, etc.
But there are two problems. First although I know FontSize, FontFamily, FontWeight, I do not know how to include these information into a mathematical calculation.
Second I think in every browser the actual size is also different. I created a dummy table and recognized, that in one screen height I already have one cell difference between Opera and Firefox.
So I think in C# I am only able to approximate the actual height?!
The next idea I have is to include a JavaScript into my HTML. I've no experience with JavaScript, but my approach would be to find my tables and read out size. Then iterate over all elements and find all overlappings.
My questions are:
*
*Are my consideration true or do I miss some aspects?
*Are my approaches the right way (in C# I only will get an
approximated result?!, JavaScript I do not know if it is really
possible what I want to do)
*Are there other possibilities I do not see right now?
Hint: Other script languages than JavaSript are not applicable for my solution. JavaScript I only use if really necessary.
A: I think javascript is the answer, not c#.
http://api.jquery.com/height/
A: You cannot calculate the height in C#. Please use javascript to do this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.NET MVC subproperty's deserialization I have two identical dropdownlists for identical subproperties of my item TaskViewModel.
@Html.DropDownListFor(x => x.AssignedTo.ID, TaskHelper.GetUsersSelect(Model.AssignedTo), new { @class = "select" })
@Html.DropDownListFor(x => x.Controller.ID, TaskHelper.GetUsersSelect(Model.Controller), new { @class = "select" })
Both values sending on posting form (...&AssignedTo.ID=1&Controller.ID=1...), but I always get only task.AssignedTo deserialized
public ActionResult SaveTask(TaskViewModel task)
{
task.AssignedTo.ID //value here
task.Controller.ID //null reference exception
}
public class TaskViewModel
{
public UserViewModel Controller { get; set; }
public UserViewModel AssignedTo{ get; set; }
}
public class UserViewModel
{
public long ID { get; set; }
public string Title { get; set; }
}
What may be a reason for that strange behaviour?
A: It looks like Controller is a reserved keyword and the default model binder doesn't like it. Try renaming the property:
public class TaskViewModel
{
public UserViewModel TaskController { get; set; }
public UserViewModel AssignedTo { get; set; }
}
The whole problem comes from the ValueProvider that the default model binder uses. When it encounters the Controller navigation property it does this:
var value = ValueProvider.GetValue("Controller");
which unfortunately first looks at route data and after that in query string. So this returns "Home" or whatever the name of the controller is and obviously trying to assign the string "Home" to a class of type UserViewModel cannot result in success.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How To Get Silverlight To Play A .WMA File on IIS 6 When The .WMA Extn. Is Mapped To Asp.Net I seem to have hit a bit of a wall on this one - although everything works fine on XP Pro IIS5.1, on IIS 6 I have tried everything over the last few days to get silverlight to simply play a .wma file when the .wma file extension is mapped to .Net in IIS (via Home Directory > configuration, map the extension to c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll. ) - without success !! The file plays ok so long as the .wma file-type isn't mapped to .net, but as soon as it is, I keep getting a generic "System.Exception - 3137" error message - which I believe is a file not found/file inaccessible message.
The .wma file that won't play is not compiled as a resource into the silverlight .xap - I am attempting to access it with it just being a normal part of the folder/file structure on the server. I have tried many different combinations of path, but presumably the path is correct as the file plays ok when the .wma extension isn't mapped to .net. The code within the SL app setting the source is :
mediaPlayer.Source = new Uri("http://www.thedomainname.org.uk/radio/featuredartistsplaylists/poprock.wma", UriKind.Absolute);
- although I have also tried relative paths from the .xap file (with and without a leading '/'), the absolute path using the ip address rather than the domain name (which gave a network error) and relative file system path in back\slash format (which gave a network error).
- for authentication, anonymous access is enabled on IIS for windows user account IUSR_HOST-7418 and as well as not setting the mode in web.config at all I have tried setting it to mode="none" and mode="windows"
My web-hosting set-up is a VPS running Windows Server 2003 Standard. I don't really know what I am doing, but I have tried the following to no effect :
- In the IIS configuration mapping dialogue, trying with the 'verify that file exists' checkbox checked and unchecked
- adding a <httpHandlers> entry for .wma in the <system.web> tag of web.config as follows :
<path "*.wma" verb="*" type="System.Web.UI.PageHandlerFactory" validate="false" />
(and tried it with validate="true")
- running the request with and without a global.asax and with a code-free Application_BeginRequest event - in case my code in global.asax was blocking access to the .wma
- granted Read & Execute rights on the folder containing the .wma to both the Internet Guest Account(HOST-7418\IUSR_HOST-7418) and Users(HOST-7418/Users) Account.
At this point, beyond suspecting that it is some sort of file/folder access issue rather than a path issue, I am pretty much out of ideas - not least because I encountered an identical problem on a Windows Server 2008 (IIS 7) VPS set-up - with .wma files again only playing when not mapped to .net (using compiled handlers/modules), otherwise refusing to play due to "System.Exception : 2210 AG_E_INVALID_ARGUMENT" error code.
Any help would be very much appreciated.
A: Couple things - first off, WMA shouldn't need to be mapped to the .NET handler. It's just a static file being served off a web server, so don't worry about any of the handler or web.config stuff. A plain vanilla IIS web site should do you just fine.
First, test your server configuration.
If your file is at http://www.mywebserver.com/SampleFile.wma, open up Windows Media Player, go to File > Open URL, and put that full URL in and make sure it plays. If it doesn't, Silverlight isn't going to work.
Once that's working, the Silverlight MediaElement can use 2 methods of Windows Media streaming - Progressive Download or Streaming. Progressive Download is your current scenario, streaming requires Windows Media Services and can be done over the RTSP protocol (MMS) or HTTP.
To help with your testing and for comparison, I've put a sample WMA out for you to test with using these 3 scenarios:
Progressive Download (plain ol' web server): http://static.x9tech.com/StackOverflow/WithoutASoundSample.wma
Streaming (WMS over MMS): mms://xstream5.x9tech.com/Static/StackOverflow/WithoutASoundSample.wma
Streaming (WMS over HTTP): http://xstream5.x9tech.com/Static/StackOverflow/WithoutASoundSample.wma
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android integration AdWhirl and AdMob I'm trying to integrate AdWhirl and AdMob in my Android Application and I have some question:
*
*I have many activities and I want put advertisement in most of them. In which activity should I put the following code?
//***ADWHIRL CODE
// These are density-independent pixel units, as defined in
// http://developer.android.com/guide/practices/screens_support.html
int width = 320;
int height = 52;
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float density = displayMetrics.density;
width = (int) (width * density);
height = (int) (height * density);
// Optional, will fetch new config if necessary after five minutes.
AdWhirlManager.setConfigExpireTimeout(1000 * 60 * 5);
// References AdWhirlLayout defined in the layout XML.
AdWhirlLayout adWhirlLayout = (AdWhirlLayout) findViewById(R.id.adwhirl_layout);
adWhirlLayout.setAdWhirlInterface(this);
adWhirlLayout.setMaxWidth(width);
adWhirlLayout.setMaxHeight(height);
//*******ADWHIRL CODE END
I already put also this code in AndroidManifest:
<!-- AdWhirl Key -->
<meta-data android:value="7e*********************5a6"
android:name="ADWHIRL_KEY" />
<!-- AdMob integration -->
<activity android:name="com.google.ads.AdActivity"
android:configChanges="orientation|keyboard|keyboardHidden" />
*
*Is it possible show the ads always in the foreground, in a indipendent way from the height of the content?
Does anyone have any advice? Any help is appreciated. Sorry for my English.
A: While the code at the top is nice to make sure your AdWhirlLayout doesn't extend upon the dimensions of the screen, you shouldn't need to include that at all. You could get away with wrapping the content of the AdWhirlLayout you define in XML. You will need to have an AdWhirlLayout in each activity that you want to display ads in, however.
To show your ads in the same place regardless of content, consider using a RelativeLayout and using the
android:layout_alignParentBottom="true" property in your AdWhirlLayout to assign the ad to the bottom of the screen, for example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How I can make a table in database having variable columns in Java? I have a Java web application. I have to create a table, and I am using JDBC.
I don't know in my list tag how many values will be there, so for each value tag, I need a corresponding column in my table. These values are fetched from some other application.
So I can create a table having n number of columns where n can be different every time.
<list>
<value>Name</value>
<value>Address</value>
<value>Contact No</value>
..
.
.
</list >
How can I achieve this?
A: You should use n rows to store the values, not n columns. Columns are somehow 'fixed' in a database, while it is easy to add/delete/modify rows.
A: You need to deal with your table structure dynamically. Several solutions exist.
With JDBC, simply query Oracle and retrieve the columns of your table.
String myTable = "FOO_TABLE";
String query = "Select COLUMN_NAME from USER_TAB_COLUMNS where TABLE_NAME=?";
PreparedStatement ps = conn.prepareStatement(query);
ps.setString(1, myTable);
//
Set<String> existingColumns = new HashSet<String>();
ResultSet rs = ps.executeQuery();
while (rs.next())
{
existingColumns.add(rs.getString(1));
}
Now you know which column exists or not and you can ALTER your table as you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java is not working in my PC I had installed Java in my PC and it was working perfectly. Suddenly something went wrong and now I m not able to open swing applications and its showing the error 'Java not found'. But I can run the Eclipse IDE which also needed Java to run. So I decide to reinstall the Java, but when I tried to uninstall the Java it shows the Error 1723 - There is a problem with this Windows Installer Package. So I have installed a new JDK in another location and set the PATH. Still I am not able to run the Swing application.
Can anybody help me on this?
A: How are you running your swing application?
If it's from the command line like java mySwingApp and you're getting java not found then your PATH isn't set properly. Make sure that the java/bin directory is on your PATH not just the top level directory. You can test your PATH by just typing java in a console window - it should print the java help page.
If you're not running from a terminal like above, then you may need to set a JAVA_HOME environment variable which points to your java installation folder. Here's a tutorial on setting JAVA_HOME
Setting JAVA_HOME
Hope this helps,
Will
A: This is close to jakob's answer, about trying to get your Java install setup correctly again, just with a little more detail.
I had a similar problem on my Windows 7 box where I was trying to uninstall Java and do a clean install of a newer version. Something got messed up and I would get the 1723 error message during the uninstall and attempted reinstall. Here's information about how I was able to fix the problem, and maybe this will help you:
Look at the log files for the uninstall/reinstall. On Windows 7 they can be found at c:\users\username\AppData\Local\Temp\
The java_install.logdidn't show any extra information, but I had several MSI##### log files that contained error messages about the failed uninstall. The message was: Error 1723.There is a problem with this Windows Installer package. A DLL required for this install to complete could not be run. Contact your support personnel or package vendor. Action UninstallJRE, entry: MSIUninstallJRE, library: C:\Program Files\Java\jre6\bin\regutils.dll
There was indeed no regutils.dll file, and not even the bindirectory was there. So I copied over a regutils.dll file from another computer, ran the uninstaller, and it worked. Then the new clean install of Java also worked.
So take a look at your logfiles and hopefully that will give you more detailed information about the 1723 error.
A: This usally happens when you delete Java files manually.
If you try to uninstall Java and it fails, it generates a log file.
Should be in C:\Users[Username]\AppData\Local\Temp
Almost at the end the missing file(s) can be found.
Try to copy that file(s) from a working installation to your computer.
Then you should be able to uninstall your Java and install a new version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python nested list within a nested list without looping I want to add a dictionary to a nested list within a nested list.
so;
['master_list 1', ['list 1', ['sub_list 1']], ['list 2'], ['list 3']]
would end up like;
['master_list_1', ['list_1', ['sub_list_1',{key_1:value_1}]], ['list_2'], ['list_3']]
I know the exact position within the lists that I want to add the dictionary, so can I add the dictionary without looping through other lists?
I have got as far as
master_list[0].append(list_1)
but I can't find out how to call the lower lists.
A: master_list[1][1].append({key_1:value_1})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Annotation attributes with type parameters When you define a Java interface, it's possible to declare a method with type parameters, for example like this:
public interface ExampleInterface {
<E extends Enum<E>> Class<E> options();
}
The same thing does not work in an annotation. This, for example, is illegal:
public @interface ExampleAnnotation {
<E extends Enum<E>> Class<E> options();
}
I can get what I'm after by using the raw type Enum:
public @interface ExampleAnnotation {
@SuppressWarnings("rawtypes")
Class<? extends Enum> options();
}
What exactly is the reason why it is not possible to declare annotation attributes with type parameters?
A: Section 9.6 of the Java Language Specification describes annotations. One of the sentences there reads:
It is a compile-time error if the return type of a method declared in an annotation type is any type other than one of the following: one of the primitive types, String, Class and any invocation of Class, an enum type (§8.9), an annotation type, or an array (§10) of one of the preceding types. It is also a compile-time error if any method declared in an annotation type has a signature that is override-equivalent to that of any public or protected method declared in class Object or in the interface annotation.Annotation.
And then it says the following, which is I think the key to this problem:
Note that this does not conflict with the prohibition on generic methods, as wildcards eliminate the need for an explicit type parameter.
So it suggests that I should use wildcards and that type parameters are not necessary. To get rid of the raw type Enum, I just have to use Enum<?> as irreputable suggested in his answer:
public @interface ExampleAnnotation {
Class<? extends Enum<?>> options();
}
Probably allowing type parameters would have opened up a can of worms, so that the language designers decided to simply disallow them, since you can get what you need with wildcards.
A: They wanted to introduce annotations in order for people only to use them as ,,,well annotations. And prevent developers from putting logic in them.
i.e. start programming stuff using annotations, which might have an effect of making Java look like a very different language in my opinion.
Hence the context free syntax note in Java Language Specification.
The following restrictions are imposed on annotation type declarations
by virtue of their context free syntax:
Annotation type declarations cannot be generic.
No extends clause is permitted. (Annotation types implicitly extend annotation.Annotation.)
Methods cannot have any parameters
Methods cannot have any type parameters
(http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html)
To better understand what I mean, look at what this JVM hacker does:
http://ricken.us/research/xajavac/
He creates And, Or annotations as instructions and processes other annotations using them. Priceless!
A: I'm admittedly late to the party here, but having struggled with this exact question for a good while myself, I wanted to add a slightly different take on it.
NOTE: this is a pretty long answer, and you probably don't need to read it unless you are interested in low-level details of the JVM or if you are in the business of implementing new programming languages on top of the JVM.
First of all, there is a difference between Java the language and the Java Virtual Machine as its underlying platform. Java, the language, is governed by the Java Language Specification that several folks already cited in their answers. The JVM is governed by the Java Virtual Machine Specification, and, besides Java, it supports several other programming languages such as Scala, Ceylon, Xtend and Kotlin. The JVM acts as a common denominator for all these languages, and, as a result, it has to be a lot more permissive than the languages that are based on it.
The restrictions that were cited in existing answers are restrictions of the Java language, not of the JVM. For the most part, these restrictions do not exist at the JVM level.
For example, let's say you wanted to define something like the following (explanation as to why one would want to do this follows at the end):
@Retention(RUNTIME)
public @interface before
{
class<? extends Runnable> code() default @class(Initializer.class);
}
public @interface class<T>
{
Class<T> value();
}
public class Initializer extends Runnable
{
@Override
public void run()
{
// initialization code
}
}
It is clearly not possible to write this code in Java, because (a) it involves an annotation that has a type parameter, and (b) because that annotation is called class (with lower-case c), which is a reserved keyword in Java.
However, using code generation frameworks like ByteBuddy, it is indeed possible to create the corresponding JVM bytecode programmatically:
import java.lang.annotation.Annotation
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import net.bytebuddy.ByteBuddy
import net.bytebuddy.description.annotation.AnnotationDescription
import net.bytebuddy.description.annotation.AnnotationValue
import net.bytebuddy.description.modifier.Visibility
import net.bytebuddy.description.type.TypeDefinition
import net.bytebuddy.description.type.TypeDescription
import net.bytebuddy.description.type.TypeDescription.Generic
import net.bytebuddy.dynamic.DynamicType.Unloaded
import net.bytebuddy.dynamic.scaffold.TypeValidation
import net.bytebuddy.implementation.StubMethod
import static java.lang.annotation.RetentionPolicy.RUNTIME
import static net.bytebuddy.description.type.TypeDescription.Generic.Builder.parameterizedType
import static net.bytebuddy.description.type.TypeDescription.Generic.OfWildcardType.Latent.boundedAbove
import static net.bytebuddy.description.type.TypeDescription.CLASS
import static net.bytebuddy.matcher.ElementMatchers.named
class AnnotationWithTypeParameter
{
def void createAnnotationWithTypeParameter()
{
val ByteBuddy codeGenerator = new ByteBuddy().with(TypeValidation.DISABLED)
val TypeDefinition T = TypeDescription.Generic.Builder.typeVariable("T").build
val TypeDefinition classT = TypeDescription.Generic.Builder.parameterizedType(CLASS, T).build
val Unloaded<? extends Annotation> unloadedAnnotation = codeGenerator
.makeAnnotation
.merge(Visibility.PUBLIC)
.name("class")
.typeVariable("T")
.defineMethod("value", classT, Visibility.PUBLIC)
.withoutCode
.make
val TypeDescription classAnnotation = unloadedAnnotation.typeDescription
val Unloaded<Runnable> unloadedRunnable = codeGenerator
.subclass(Runnable).merge(Visibility.PUBLIC).name("Initializer")
.method(named("run")).intercept(StubMethod.INSTANCE)
.make
val TypeDescription typeInitializer = unloadedRunnable.typeDescription
val AnnotationDescription.Builder a = AnnotationDescription.Builder.ofType(classAnnotation)
.define("value", typeInitializer)
val AnnotationValue<?, ?> annotationValue = new AnnotationValue.ForAnnotationDescription(a.build)
val TypeDescription classRunnable = new TypeDescription.ForLoadedType(Runnable)
val Generic.Builder classExtendsRunnable = parameterizedType(classAnnotation, boundedAbove(classRunnable.asGenericType, classRunnable.asGenericType))
val Retention runtimeRetention = new Retention()
{
override Class<Retention> annotationType() {Retention}
override RetentionPolicy value() {RUNTIME}
}
val Unloaded<? extends Annotation> unloadedBefore = codeGenerator
.makeAnnotation
.merge(Visibility.PUBLIC)
.name("before")
.annotateType(runtimeRetention)
.defineMethod("code", classExtendsRunnable.build, Visibility.PUBLIC)
.defaultValue(annotationValue)
.make
#[unloadedBefore, unloadedAnnotation, unloadedRunnable].forEach[load(class.classLoader).loaded]
// ...or alternatively something like: .forEach[saveIn(new File("/tmp"))]
}
}
(the above code is written in Xtend syntax, but can easily be transformed into regular Java)
In a nutshell, this code will create a parameterized annotation (@class<T>) and use it as an attribute of another annotation (@before), where the type parameter is bound to ? extends Runnable. The validity of the generated code can be easily verified by replacing the forEach[load(...)] with a forEach[saveIn(...)] (to generate actual class files) and compiling a small Java test program in the same folder:
import java.lang.reflect.Method;
import java.lang.annotation.Annotation;
public class TestAnnotation
{
@before
public static void main(String[] arg) throws Exception
{
Method main = TestAnnotation.class.getDeclaredMethod("main", String[].class);
@SuppressWarnings("unchecked")
Class<? extends Annotation> beforeAnnotation = (Class<? extends Annotation>)Class.forName("before");
Annotation before = main.getAnnotation(beforeAnnotation);
Method code = before.getClass().getDeclaredMethod("code");
Object classAnnotation = code.invoke(before);
System.err.println(classAnnotation);
}
}
The test program will show the expected initializer class wrapped in an @class annotation:
@class(value=class Initializer)
To get a better understanding what this achieves (and doesn't achieve) it's useful to disassemble some of the generated class files via javap -c -v:
Classfile /private/tmp/class.class
Last modified Feb 28, 2020; size 265 bytes
MD5 checksum f57e09ce9d174a6943f7b09704cbdea3
public interface class<T extends java.lang.Object> extends java.lang.annotation.Annotation
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_INTERFACE, ACC_ABSTRACT, ACC_ANNOTATION
Constant pool:
#1 = Utf8 class
#2 = Class #1 // class
#3 = Utf8 <T:Ljava/lang/Object;>Ljava/lang/Object;Ljava/lang/annotation/Annotation;
#4 = Utf8 java/lang/Object
#5 = Class #4 // java/lang/Object
#6 = Utf8 java/lang/annotation/Annotation
#7 = Class #6 // java/lang/annotation/Annotation
#8 = Utf8 value
#9 = Utf8 ()Ljava/lang/Class;
#10 = Utf8 ()Ljava/lang/Class<TT;>;
#11 = Utf8 Signature
{
public abstract java.lang.Class<T> value();
descriptor: ()Ljava/lang/Class;
flags: ACC_PUBLIC, ACC_ABSTRACT
Signature: #10 // ()Ljava/lang/Class<TT;>;
}
Signature: #3 // <T:Ljava/lang/Object;>Ljava/lang/Object;Ljava/lang/annotation/Annotation;
The above code shows that the type parameter T is properly reflected at the class and the method level and that is also shows up correctly in the value attribute's signature.
Classfile /private/tmp/before.class
Last modified Feb 28, 2020; size 382 bytes
MD5 checksum d2166167cf2adb8989a77dd320f9f44b
public interface before extends java.lang.annotation.Annotation
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_INTERFACE, ACC_ABSTRACT, ACC_ANNOTATION
Constant pool:
#1 = Utf8 before
#2 = Class #1 // before
#3 = Utf8 java/lang/Object
#4 = Class #3 // java/lang/Object
#5 = Utf8 java/lang/annotation/Annotation
#6 = Class #5 // java/lang/annotation/Annotation
#7 = Utf8 Ljava/lang/annotation/Retention;
#8 = Utf8 value
#9 = Utf8 Ljava/lang/annotation/RetentionPolicy;
#10 = Utf8 RUNTIME
#11 = Utf8 code
#12 = Utf8 ()Lclass;
#13 = Utf8 ()Lclass<+Ljava/lang/Runnable;>;
#14 = Utf8 Lclass;
#15 = Utf8 LInitializer;
#16 = Utf8 Signature
#17 = Utf8 AnnotationDefault
#18 = Utf8 RuntimeVisibleAnnotations
{
public abstract class<? extends java.lang.Runnable> code();
descriptor: ()Lclass;
flags: ACC_PUBLIC, ACC_ABSTRACT
Signature: #13 // ()Lclass<+Ljava/lang/Runnable;>;
AnnotationDefault:
default_value: @#14(#8=c#15)}
RuntimeVisibleAnnotations:
0: #7(#8=e#9.#10)
The disassembly for the @before annotation again shows that the concrete type argument (? extends Runnable) is properly recorded in both the actual method signature as well as the Signature attribute.
So, if you have a language that is capable of parameterized annotations, then the bytecode preserves all the information that you would need to guarantee type safety at compile time. That being said (i.e. type safety being mainly enforced at compile time in Java), I do not believe that there is anything at the JVM level that would prevent a class that does not extend Runnable from being assigned as a default value to the code attribute of the @before annotation (but again, it's the compiler's job to detect and prevent that).
Finally, the big question in the room is: why would anybody want to do all this?
I didn't actually write all this code from scratch, just to provide an obscure answer to an already answered question. The code that I pasted above comes from (slightly redacted) test cases for a JVM-based programming language. Annotations in this language frequently need to carry code with them (in the form of references to classes that contain the code). This is a necessity for implementing language features similar to the active annotations feature in the Xtend programming language. Now, since java.lang.Class is a valid annotation attribute type this could just be achieved by using class literals directly. However, that would directly expose Java API, which is not desirable because it would create a tight coupling. If the class literal is to be wrapped in some other attribute type it has to be another annotation, and if we don't want to lose the type information in the process then this annotation needs to have a type parameter to carry that information.
So, long story short, parameterized annotations are possible (on the JVM, not in Java), and there are use cases where you need them, but in practice this will only be of interest for JVM language implementors.
BTW, another poster talked about how "programming stuff using annotations" is not really an intended feature in Java, but I highly recommend a look at Xtend's active annotation feature. It's exactly that, i.e. "programming stuff using annotations", and once you get the hang of it it is a very powerful language feature.
A: I think it is possible, but it requires lots of additions to language spec, which is not justified.
First, for you enum example, you could use Class<? extends Enum<?>> options.
There is another problem in Class<? extends Enum> options: since Enum.class is a Class<Enum> which is a Class<? extends Enum>, it's legal to options=Enum.class
That can't happen with Class<? extends Enum<?>> options, because Enum is not a subtype of Enum<?>, a rather accidental fact in the messy raw type treatments.
Back to the general problem. Since among limited attribute types, Class is the only one with a type parameter, and wildcard usually is expressive enough, your concern isn't very much worth addressing.
Let's generalize the problem even further, suppose there are more attribute types, and wildcard isn't powerful enough in many cases. For example, let's say Map is allowed, e.g.
Map<String,Integer> options();
options={"a":1, "b":2} // suppose we have "map literal"
Suppose we want an attrbite type to be Map<x,x> for any type x. That can't be expressed with wildcards - Map<?,?> means rather Map<x,y> for any x,y.
One approach is to allow type parameters for a type: <X>Map<X,X>. This is actually quite useful in general. But it's a major change to type system.
Another approach is to reinterpret type parameters for methods in an annotation type.
<X> Map<X,X> options();
options={ "a":"a", "b":"b" } // infer X=String
this doesn't work at all in the current understanding of method type parameters, inference rules, inheritance rules etc. We need to change/add a lot of things to make it work.
In either approaches, it's a problem how to deliver X to annotation processors. We'll have to invent some additional mechanism to carry type arguments with instances.
A: The The Java™ Language Specification Third Edition says:
The following restrictions are imposed on annotation type declarations by virtue of their
context free syntax:
*
*Annotation type declarations cannot be generic.
*No extends clause is permitted. (Annotation types implicitly extend annotation.Annotation.)
*Methods cannot have any parameters
*Methods cannot have any type parameters
*Method declarations cannot have a throws clause
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
}
|
Q: Have PDF-Creator suppress warning dialog not to halt build process I have a msbuild script that includes creation of a few PDF's using PDF creator. It's the Convert2PDF.vbs that's being used, converting doc's to PDF's, and a while ago it stopped working and none seemed to take the time to fix it. So I looked into it and by debugging the script I found that it was in fact a document for which Word presented a dialog with information about contents being larger than the margins. This halted the entire thing since none could press this dialog during the auto-build.
So what I wonder is if there is a way to tell the PDF Creator script, via cmd line arguments or by altering the script, to suppress these kinds of warnings and just continue with conversion?
A: I solved this by creating a script in word that suppressed warnings if the given document resided within the build folder specified.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Navigate back in visual webgui I'm a newbie of ASP.NET world. I'm developing an app with asp.net and insiede of an aspx page i'm using a window form developed with visual webgui.
I've this problem: inside my form, i have a button wich has to rise an event equals to the page back button of the browser.
I tried to search informations about this, but i can't find anything unfortunately.
I think that i've to do something with the HttpContext. I tried with the Redirect function but my "previous page" is open always in a new browser window.
Can someone tell me a way on how to do this thing please?
Thank's
Marco
EDIT SOLVED
button.RegisterClientAction("history.go( -1 )", "");
A: Cant you do this:
Response.Redirect(Request.UrlReferrer.ToString());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Node.js: How to install NPM I have cygwin and node.exe (0.5.7) installed on my window XP.
When I git clone npm(1.0.30), cd npm, then "make install", there are lots of node_modules cloning.
But it stopped when execute "node cli.js install git+https://github.com/isaac/ronnjs.git".
The following is my npm-debug.log.
info it worked if it ends with ok
verbose cli [ 'E:\node\node.exe', verbose cli
'e:\github\npm\cli.js', verbose cli 'cache', verbose cli
'clean' ] info using npm@1.0.30 info using node@v0.5.7
verbose config file C:\Documents and Settings\zhangchiqing.npmrc
verbose config file E:\etc\npmrc ERR! prefix directory not
found ERR! Error: ENOENT, �����ɹ����ɡ� ERR! 'E:' ERR!
Report this entire log at: ERR!
http://github.com/isaacs/npm/issues ERR! or email it to: ERR!
npm-@googlegroups.com ERR! ERR! System Windows_NT
5.1.2600 ERR! command "E:\node\node.exe" "e:\github\npm\cli.js" "cache" "clean" ERR! cwd E:\github\npm ERR! node -v v0.5.7
ERR! npm -v 1.0.30 verbose exit [ 1, true ]
A: This works in Ubuntu. You have to use older version of node.
sudo apt-get install -y g++ libssl-dev apache2-utils curl git-core
git clone git://github.com/joyent/node.git
cd node
git checkout v0.4.11
./configure
make
sudo make install
node -v
curl https://npmjs.org/install.sh | sudo sh
npm -v
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Resolving of vptr class base {
public:
virtual void fn(){}
};
class der : public base {};
I know that compiler provides a member call VPTR in class which is initialised with the exact VTABLE at run time by constructor. I have 2 questions
1) Which class holds the VPTR. or all the class is having seperate VPTR.
2) When executing statement der d; how VPTR is being resolved at run time?
A: vtable is created for the class that contains virtual function and for the classes derived from it.It means in your program vtable will be created for base class and der class.Each of these vtables would contain the address of virtual function void fn().Now note that der class doesn't contain the definition of void fn(),hence its vtable contains the address of base class's void fn() function.Thus if u make a call like d.fn(); the void fn() function of base class would get executed.
A: Note: a virtual table and a virtual pointer are implementation details, though all the C++ compilers I know use them, they are not mandated by the Standard, only the results are.
To answer your specific question: each instance of a class with virtual methods (either its own, or inherited ones) or a class with (somewhere) a virtual inheritance relationship will need at least one virtual-pointer.
There can be several (when virtual inheritance or multi-inheritance are involved).
In your example, a single virtual pointer is sufficient. However it does not make sense to speak of it as being part of a class. The virtual pointer is part of the instance (object), and lives outsides the classes rules because those apply to the language, and the virtual pointer is an implementation mechanism.
A:
1) which class holds the VPTR. or all the class is having seperate VPTR.
Every class object has its own vptr if the class is polymorphic (i.e. contains virtual function or has virtual inheritance.) In this case both the classes has virtual function.
2) when executing statement der d; how VPTR is resolve at run time?
You are just declaring the object of der. But even if you call a function then in this case the call to any function is resolved at compile time. Virtual function resolution comes into picture only when the function is called with pointer/reference.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cache.NoSlidingExpiration in ASP - when is it reset? I have found an answer to a similar question (System.Web.Caching.Cache.NoSlidingExpiration in asp.net c#) and followed the links, but I need more specific information I cannot find.
NoSlidingExpiration does not reset when you 'access' it. But, does that mean when you read it? Or also when you write it?
For example, if I do
Cache.Insert("mykey", 42, null, DateTime.Now.AddMinutes(20), System.Web.Caching.Cache.NoSlidingExpiration);
and then 10 minutes later, I do:
Cache.Insert("mykey", 42, null, DateTime.Now.AddMinutes(20), System.Web.Caching.Cache.NoSlidingExpiration);
again, will the expiry be adjusted?
Thanks!
A: According to the MSDN doc on Cache.NoSlidingExpiration
When used, this field sets the slidingExpiration parameter to the
TimeSpan.Zero field, which has a constant value of zero. The cached
item expires in accordance with the absoluteExpiration parameter
associated with the Insert or Add method call.
That means when you call Add or Insert, whatever the absoluteExpiration value you have given in that call will be used to expire that item. So in your example:
DateTime.Now.AddMinutes(20)
means the item will be reset after 20 minutes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Ruby: Why is 1.025.round(2) rounded to 1.02? As far as I understand the .round()-functionality in ruby rounds decimals upwards where the last significant number is 5?
For example 1.5.round(0) # => 2 (OK)
but why does 1.025.round(2) # => 1.02, and not 1.03 as I would expect?
irb(main):037:0> 1.025.round(2)
=> 1.02
What can I do to go around this?
A: I think this is due to the nature of floating point numbers. They're not exact representations of a number:
printf("%f", 1.025) # rounded to 6 decimal places
=> 1.025000
printf("%.16f", 1.025) # rounded to 16 decimal places
=> 1.0249999999999999
So when you enter "1.025" it's represented in the computer as a number that is fractionally less than the value you really wanted. Most of the time it's not a problem but it can throw up the occasional bit of strangeness.
Just to be clear: this isn't a problem with Ruby, it's a problem with floating point numbers in all languages. If it's causing you trouble have a look at BigDecimal.
A: This has nothing to do with the last digit being 5 and everything to do with conversion of a decimal value to a double precision floating point value.
http://en.wikipedia.org/wiki/Double_precision_floating-point_format
Basically, the decimal number has to be represented in limited binary format which can only approximate certain decimal values, leading to loss of precision. This can cause some weird behavior, as you have seen.
Best to explain this by showing you... Marshal.dump(1.025) dumps the Float value and shows the value a bit closer to what it really is: 1.0249999999999999. 1.025.to_r will provide you with the fraction which represents the binary value. You can use the arbitrarily precise decimal library, BigDecimal to convert this:
ruby-1.9.2-p180 :060 > (BigDecimal.new("2308094809027379.0") / BigDecimal.new("2251799813685248.0")).to_s('F')
=> "1.024999999999999911182158029987476766"
When certain decimals are converted to this "approximate" binary number format they will be represented differently, possibly more precisely. So, you might have noticed that 1.085.round(2) results in 1.09 as you'd expect.
This lack of precision with floating point math means it's never, ever appropiate to use floating point values for currency calculations, or even as temporary containers for money values. Arbitrary precision data types should be used at all times for anything involving money.
As a former developer for an extremely large financial company I was constantly shocked by how rarely this advice is heeded and how common the use of floats or doubles is in financial software. Most programmers in that industry I have talked to are not aware that floats and doubles should never store money values. So, don't feel like you are too behind the curve ;-)
tl;dr
Use BigDecimal: BigDecimal.new("1.025").round(2) => "1.03"
A: Using Pry you can look at the underlying code for Float#round
So in Pry type:
show-method Float#round
which show's the underlying C code:
From: numeric.c in Ruby Core (C Method):
Number of lines: 36
static VALUE
flo_round(int argc, VALUE *argv, VALUE num)
{
VALUE nd;
double number, f;
int ndigits = 0, i;
long val;
if (argc > 0 && rb_scan_args(argc, argv, "01", &nd) == 1) {
ndigits = NUM2INT(nd);
}
number = RFLOAT_VALUE(num);
f = 1.0;
i = abs(ndigits);
while (--i >= 0)
f = f*10.0;
if (isinf(f)) {
if (ndigits < 0) number = 0;
}
else {
if (ndigits < 0) number /= f;
else number *= f;
number = round(number);
if (ndigits < 0) number *= f;
else number /= f;
}
if (ndigits > 0) return DBL2NUM(number);
if (!FIXABLE(number)) {
return rb_dbl2big(number);
}
val = (long)number;
return LONG2FIX(val);
}
Which show's it's using the C round function. Which is complying to IEEE-754.
Unless you have a very strange edge-case I would recommend that you keep with this type of rounding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: CSS for Nested Lists I am currently trying to create some nested lists to display the following...
A...R...X
B...S...Y
C...T...Z
(where the letters will eventually be replaced by words) and have made this work perfectly in chrome and firefox, however when I use Internet Explorer I get something resembling the following...
A
B...R
C...S...X
......T...Y
...........Z
I assume it's probably to do with the css, but please can someone help me with this problem, the html and css are shown below, thanks in advance for any help.
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<link rel=stylesheet href="lists in IE.css" type="text/css">
</head>
<body>
<div id="container">
<ul id="links-nav">
<li>
<ul>
<li><a href="#">A</a></li>
<li><a href="#">B</a></li>
<li><a href="#">C</a></li>
</ul>
</li>
<li>
<ul>
<li><a href="#">L</a></li>
<li><a href="#">M</a></li>
<li><a href="#">N</a></li>
</ul>
</li>
<li>
<ul>
<li><a href="#">X</a></li>
<li><a href="#">Y</a></li>
<li><a href="#">Z</a></li>
</ul>
</li>
</ul>
<div class="clear"></div>
</div>
</body>
</html>
CSS
#container{
width:940px;
margin:0px auto;
border: 1px solid #000;
padding: 20px 10px;
height:auto;
font-family: Arial, sans-serif;
font-size:11px;
}
.clear {
clear: both;
height: 0;
overflow: hidden;
}
a{
text-decoration:none;
color:#555;
}
#links-nav li, li ul li{
list-style:none;
}
#links-nav{
list-style-type: none;
margin:0px;
padding:0px;
}
#links-nav li ul{
float:left;
width:168px;
padding: 0px 10px;
list-style-type: none;
}
A: add in your css
#links-nav > li {
width:168px;
float:left;
}
Demo: http://jsfiddle.net/qUJuy/2/
or
#links-nav > li {
width:168px;
display:inline;
}
Demo: http://jsfiddle.net/qUJuy/3/
The above will fix the error in ie7 (in ie8 it was already correct).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Shell script that continuously checks a text file for log data and then runs a program I have a java program that stops often due to errors which is logged in a .log file. What can be a simple shell script to detect a particular text in the last/latest line say
[INFO] Stream closed
and then run the following command
java -jar xyz.jar
This should keep on happening forever(possibly after every two minutes or so) because xyz.jar writes the log file.
The text stream closed can arrive a lot of times in the log file. I just want it to take an action when it comes in the last line.
A: How about
while [[ true ]];
do
sleep 120
tail -1 logfile | grep -q "[INFO] Stream Closed"
if [[ $? -eq 1 ]]
then
java -jar xyz.jar &
fi
done
A: There may be condition where the tailed last log "Stream Closed" is not the real last log and the process is still logging the messages. We can avoid this condition by checking if the process is alive or not. If the process exited and the last log is "Stream Closed" then we need to restart the application.
#!/bin/bash
java -jar xyz.jar &
PID=$1
while [ true ]
do
tail -1 logfile | grep -q "Stream Closed" && kill -0 $PID && sleep 20 && continue
java -jar xyz.jar &
PID=$1
done
A: I would prefer checking whether the corresponding process is still running and restart the program on that event. There might be other errors that cause the process to stop. You can use a cronjob to periodically (like every minute) perform such a check.
Also, you might want to improve your java code so that it does not crash that often (if you have access to the code).
A: i solved this using a watchdog script that checks directly (grep) if program(s) is(are) running. by calling watchdog every minute (from cron under ubuntu), i basically guarantee (programs and environment are VERY stable) that no program will stay offline for more than 59 seconds.
this script will check a list of programs using the name in an array and see if each one is running, and, in case not, start it.
#!/bin/bash
#
# watchdog
#
# Run as a cron job to keep an eye on what_to_monitor which should always
# be running. Restart what_to_monitor and send notification as needed.
#
# This needs to be run as root or a user that can start system services.
#
# Revisions: 0.1 (20100506), 0.2 (20100507)
# first prog to check
NAME[0]=soc_gt2
# 2nd
NAME[1]=soc_gt0
# 3rd, etc etc
NAME[2]=soc_gp00
# START=/usr/sbin/$NAME
NOTIFY=you@gmail.com
NOTIFYCC=you2@mail.com
GREP=/bin/grep
PS=/bin/ps
NOP=/bin/true
DATE=/bin/date
MAIL=/bin/mail
RM=/bin/rm
for nameTemp in "${NAME[@]}"; do
$PS -ef|$GREP -v grep|$GREP $nameTemp >/dev/null 2>&1
case "$?" in
0)
# It is running in this case so we do nothing.
echo "$nameTemp is RUNNING OK. Relax."
$NOP
;;
1)
echo "$nameTemp is NOT RUNNING. Starting $nameTemp and sending notices."
START=/usr/sbin/$nameTemp
$START 2>&1 >/dev/null &
NOTICE=/tmp/watchdog.txt
echo "$NAME was not running and was started on `$DATE`" > $NOTICE
# $MAIL -n -s "watchdog notice" -c $NOTIFYCC $NOTIFY < $NOTICE
$RM -f $NOTICE
;;
esac
done
exit
i do not use the log verification, though you could easily incorporate that into your own version (just change grep for log check, for example).
if you run it from command line (or putty, if you are remotely connected), you will see what was working and what wasnt. have been using it for months now without a hiccup. just call it whenever you want to see what's working (regardless of it running under cron).
you could also place all your critical programs in one folder, do a directory list and check if every file in that folder has a program running under the same name. or read a txt file line by line, with every line correspoding to a program that is supposed to be running. etcetcetc
A: A good way is to use the awk command:
tail -f somelog.log | awk '/.*[INFO] Stream Closed.*/ { system("java -jar xyz.jar") }'
This continually monitors the log stream and when the regular expression matches its fires off whatever system command you have set, which is anything you would type into a shell.
If you really wanna be good you can put that line into a .sh file and run that .sh file from a process monitoring daemon like upstart to ensure that it never dies.
Nice and clean =D
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Frame Busting buster not completely working for IE I've been working on a Frame busting buster (what's in a name, hehe), which kept my users on my page and open a new window with the target URL. I'm using a Lightbox script to display iframes, this is what I'm doing:
1) Added an event for all .lightbox clicks, f.e:
$('.lightbox').live("click", function(e) {
e.preventDefault();
$('#redirectURL').val($(this).attr('href'));
$(this).lightbox();
}
2) Added a frame busting buster:
<script type="text/javascript">
var prevent_bust = 0
window.onbeforeunload = function() { prevent_bust++ }
setInterval(function() {
if (prevent_bust > 0) {
prevent_bust -= 2
window.top.location = 'http://server-which-responds-with-204.com'
}
}, 1)
</script>
3) Modified the frame busting buster code to fit my needs, which are:
*
*detect if an iframe wants to change the window.top.location
*if so, prevent this from happening using the 204 server respond
*open a new page: window.open( $('#redirectURL', '_blank' );
*close lightbox: $('.jquery-lightbox-button-close').click();
So far, this is what I've come up with:
var prevent_bust = 0
window.onbeforeunload = function() { prevent_bust++ }
setInterval(function() {
if (prevent_bust > 0) {
prevent_bust -= 2;
redirectURL = $('#redirectURL').val();
if(redirectURL != "") {
window.top.location = 'http://www.****.com/ajax/nocontent.php';
window.open(redirectURL, "_blank");
$('.jquery-lightbox-button-close').click();
$('#redirectURL').val('');
} else {
window.top.location = 'http://www.****.com/ajax/nocontent.php';
}
}
}, 1);
// EDIT: Before I forget, 'nocontent.php' is a file that returns a 204 header
For Firefox it acts as I programmed it, if there's a change detected in the window.top.location it opens a new frame/page and prevents the iframe from reloading the top location and to round it up, it closes the jQuery lightbox.
Safari/Chrome act similar, they open a new browser screen (not sure if theres an option to say target="_newtab" or something?). Only bad thing is they do not really display a message of the popup is blocked, but I can work around that by displaying a popup balloon on my website with a link to the page.
Internet Explorer is, what a shocker, the only black sheep left.. IE does not open a new popup, nor blocks the window.top.location reset by the iFrame and simply continues refreshing the complete page to the '#targetURL'. It does the same with the default busting code.. so it's not because of some of my edits.
Anyone who is able to spot a mistake in my code?
Also, I would need a little modification that sees if the request has been made by an iframe or by the user itself, because now there is really NO option for a user to leave my page by changing the address in the toolbar or by clicking a link, which is not really needed LOL.
Thanks in advance.
A: PENDO, I tried to simulate the whole process you described, ligthbox-jquery, javascript their own codes and controls opening pages via lightbox. I could not simulate at all, and as time is running out I'm sending a suggestion to broaden the range of possibilities and solutions.
I suggest replacing the redirect page:
...
redirectUrl = $ ('# redirectUrl'). val ();
...
window.top.location = 'http://www .****. with / ajax / nocontent.php';
window.open (redirectUrl, "_blank");
Replaced with a DIV container that simulates a page, using ajax calls and taking the content and overwritten the contents of the DIV.
...
$.post(redirectoURL /* or desired URL */, function(data) {
$('DIV.simulateContent').html(data);
});
...
or
...
$('DIV.simulateContent').load(redirectoURL);
...
This approach also avoids the problem of preventing the user from even leaving your page using the address bar (as you yourself mentioned).
Sorry, let me give you a complete solution, but time prevented me.
PENDO, a little more work on alternatives to the problem, I found a customizable jQuery lightbox plugin for working with custom windows yet (iframe, html, inline ajax etc.). Maybe it will help. The following link:
http://jacklmoore.com/colorbox/
A: If you don't need javascript running in your iframe in IE, you can set the iframe security attribute :
<iframe security="restricted" src="http://domain.com" />
http://msdn.microsoft.com/en-us/library/ms534622(v=VS.85).aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: file default editor is changed `Eclipse` I have an opened project in Eclipse. I have some special extensions like *.VW,*.RW and many.
If I double click those files in Eclipse, it will automatically open in default eclipse text editor.
Problem: Unfortunately, I have opened *.RW file with Notepad (via
file system).
Now, if I double click those files in Eclipse, it is getting opened in Notepad only :(. How do I reset the default editor?
Thanks
A: Right click and Open with ... should the opening behaviour in eclipse. Furthermore you can set the behaviour in Preferences -> General -> Editors -> File Associations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Error when using jcaptcha plugin with grails 1.3.7 Hi I am facing following error when trying to use jcaptcha plugin with grails 1.3.7.
org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object '{}' with class 'groovy.util.ConfigObject' to class 'com.octo.captcha.service.CaptchaService' due to:
groovy.lang.GroovyRuntimeException: Could not find matching constructor for: com.octo.captcha.service.CaptchaService(groovy.util.ConfigObject)
at org.grails.plugin.jcaptcha.JcaptchaService.getCaptchaService(JcaptchaService.groovy:42)
at org.grails.plugin.jcaptcha.JcaptchaService$$FastClassByCGLIB$$98874858.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149)
at org.grails.plugin.jcaptcha.JcaptchaService$$EnhancerByCGLIB$$468f85f9.getCaptchaService(<generated>)
at org.grails.plugin.jcaptcha.JcaptchaService$getCaptchaService.call(Unknown Source)
at org.grails.plugin.jcaptcha.JcaptchaController$_closure1.doCall(JcaptchaController.groovy:29)
at org.grails.plugin.jcaptcha.JcaptchaController$_closure1.doCall(JcaptchaController.groovy)
at java.lang.Thread.run(Thread.java:619)
Any pointers on same will be really helpful.
Thanks in advance.
A:
A String like "captcha1" (if you named your captcha in the Config.groovy like that) is expected by the jcaptchaService.validateResponse as first argument to identify which captcha-instance to use.
Config.groovy Exmpl.:
...
captchas {
captcha1 = new GenericManageableCaptchaService(...)
}
...
for the view use the captcha like that:
<jcaptcha:jpeg name="captcha1" /> ...
<g:textField name="user_typed_captcha" value="" />
and in the controller something like that:
if(jcaptchaService.validateResponse("captcha1", session.id, params.user_typed_captcha)) {
log.info("CAPTCHA WAS VALID!")
} else {
log.info("CAPTCHA WAS NOT VALID!")
}
This should fix your issue using the jcaptcha in controllers.
For me using the jcaptchaService in CommandObjects did not worked out. I think the reason was that validation method was for some reasons called twice, which made the capture invalid . I used Grails 1.3.7.
A: When using JCaptcha with Grails, you need to "define captchas" : that means you must specify the rules according to which Jcaptchas are generated.
Your captchas are defined in your conf/Config.groovy file :
jcaptchas {
captcha1 = …
captcha2 = …
}
More info on how to create these @ http://www.grails.org/JCaptcha+Plugin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Scrolling Button On Scroll View with Middle Button Selected Please guide me on how can I create a dynamic button a scroll view that will be scrollable, with the middle button always selected.
like this
b1 b2 b3 b4 b5(selected) b6 b7 b8 b9
if user select b4 it should seems like that
b1 b2 b3 b4(selected) b5 b6 b7 b8
b2 b3 b4 b5 b6(selected) b7 b8 b9
the way should like that. Please guide.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Output datetime value to StaticTextField in SmartGWT I have a field in my dataset defined as:
DataSourceDateTimeField dateField = new DataSourceDateTimeField("date");
and a StaticTextItem in DynamicForm defined as
StaticTextItem dateItem = new StaticTextItem("date", "Date");
I played a lot with different combinations of setDateFormatter, but datetime values are still rendered as something like 2011-08-23T20:00:00 (datasource receives it in json as a yyyy-MM-dd'T'HH:mm:ss.SSSZ field).
Is there some easy way to output datetime values to StaticTextItem? I assume using DynamicForm.fetchData().
UPD1. Data example.
Table row in PgSQL:
1 | "2011-09-29 12:10:05.010276+04" | "Europe"
Data sent by REST service:
{
"location":"Europe",
"id":1,
"date":"2011-09-29T08:10:05.010+0000"
}
Data fetched by SGWT from REST service (I dumped it with JSON.encode(XMLTools.selectObjects(data, "/").getJavaScriptObject()) in my implementation of transformResponse()) :
{
"location":"Europe",
"id":1,
"date":"2011-09-29T08:10:05"
}
Value as rendered in StaticTextField:
2011-09-29T08:10:05
So datetime values returned by server seem to conform the standard and also I have no warnings in Developer Console.
UPD2. May be I'm doing something wrong in my transformResponse() ?
protected void transformResponse(DSResponse response, DSRequest request, Object data) {
String json = JSON.encode(XMLTools.selectObjects(data, "/").getJavaScriptObject());
SC.logWarn("Response received");
SC.logWarn(json);
Record[] records = jsonToRecords(json);
//safe HTML text values
for (Record rec: records) {
for (DataSourceField field: getFields()) {
if (field.getType() == FieldType.TEXT) {
String textVal = rec.getAttribute(field.getName());
if (textVal != null) {
textVal = SafeHtmlUtils.htmlEscape(textVal);
}
rec.setAttribute(field.getName(), textVal);
}
}
}
response.setData(records);
response.setStartRow(0);
response.setEndRow(records.length);
response.setTotalRows(records.length);
}
/**
* Converts JS-array into SmartGWT records
*/
public static native ListGridRecord[] jsonToRecords(String jsonString) /*-{
var json = eval(jsonString);
return @com.smartgwt.client.widgets.grid.ListGrid::convertToListGridRecordArray(Lcom/google/gwt/core/client/JavaScriptObject;)(json);
}-*/;
A: Your problem is most likely that your date value is still a String, not an instance of Date. It should have been parsed into a Date when the JSON response was received - if it was not, there will be a warning in the SmartGWT Developer Console tell you so.
The format expected for date values in documented under DataSource.dataFormat - XML Schema date/datetime format is expected by default, and you can provide a FieldValueParser if you are unable to make your server produce this format.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use the mouse joint in Android? I want to use the MouseJoint in Java for Android. I am new in box2d and cocos2d. I don't know how to use the mouse joint.
A: i recomend you to see this tutorial example. Copy from it (sorry i don't like broken links :) ) ...
you drag your body with the help of the MouseJoint, it will collide with the other bodys in the world and apply force to them.
Box2d - Manual - http://www.box2d.org/manual.html#_Toc258082974
8.10 Mouse Joint
The mouse joint is used in the testbed to manipulate bodies with the mouse. It attempts to drive a point on a body towards the current position of the cursor. There is no restriction on rotation.
The mouse joint definition has a target point, maximum force, frequency, and damping ratio. The target point initially coincides with the body’s anchor point. The maximum force is used to prevent violent reactions when multiple dynamic bodies interact. You can make this as large as you like. The frequency and damping ratio are used to create a spring/damper effect similar to the distance joint.
Many users have tried to adapt the mouse joint for game play. Users often want to achieve precise positioning and instantaneous response. The mouse joint doesn’t work very well in that context. You may wish to consider using kinematic bodies instead.
So let's start..
*
*You have to create your PhysicWorld and at least one body in it. ( Checkout the PhysicExample how to.. )
- MouseJoint method
public MouseJoint createMouseJoint(AnimatedSprite box , float x, float y)
{
final Body boxBody =
this.mPhysicsWorld.getPhysicsConnectorManager().findBodyByShape(box);
Vector2 v = boxBody.getWorldPoint(
new Vector2(x/pixelToMeteRatio, y/pixelToMeteRatio)
);
MouseJointDef mjd = new MouseJointDef();
mjd.bodyA = groundBody;
mjd.bodyB = boxBody;
mjd.dampingRatio = 0.2f;
mjd.frequencyHz = 30;
mjd.maxForce = (float) (200.0f * boxBody.getMass());
mjd.collideConnected = true;
mjd.target.set(v);
return (MouseJoint) this.mPhysicsWorld.createJoint(mjd);
}
- Touching Body
we have to override our onAreaTouched method to create an MouseJoint anchor-point on the touch position.
MouseJoint mjActive = null;
private float pixelToMeteRatio = PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
@Override
public boolean onAreaTouched(
final TouchEvent pSceneTouchEvent,
final ITouchArea pTouchArea ,
final float pTouchAreaLocalX,
final float pTouchAreaLocalY )
{
if(pSceneTouchEvent.getAction() == MotionEvent.ACTION_DOWN) {
this.runOnUpdateThread(new Runnable() {
@Override
public void run() {
final AnimatedSprite face = (AnimatedSprite)pTouchArea; //The touched body
//If we have a active MouseJoint, we are just moving arround don't create an 2nd one.
if( mjActive == null)
{
Vector2 vector = new Vector2(pTouchAreaLocalX/pixelToMeteRatio,pTouchAreaLocalY/pixelToMeteRatio);
//=====================================
// GROUNDBODY - Used for the MouseJoint
//=====================================
BodyDef groundBodyDef = new BodyDef();
groundBodyDef.position.set(vector);
groundBody = mPhysicsWorld.createBody(groundBodyDef);
//====================================
// CREATE THE MOUSEJOINT
//====================================
mjActive = PhysicsJumpExample.this.createMouseJoint(face, pTouchAreaLocalX, pTouchAreaLocalY);
}
}});
return true;
}
return false;
}
- Moving the body
We are moving our finger over the scene, so we have to move the MouseJoint too.
If we release the finger.. we must destroy the MouseJoint..
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if(this.mPhysicsWorld != null) {
if(pSceneTouchEvent.getAction() == MotionEvent.ACTION_MOVE) {
this.runOnUpdateThread(new Runnable() {
@Override
public void run() {
if( mjActive != null ){ //If the MJ is active move it ..
// =========================================
// MOVE THE MOUSEJOINT WITH THE FINGER..
// =========================================
Vecotr2 vec = new Vector2(pSceneTouchEvent.getX()/pixelToMeteRatio, pSceneTouchEvent.getY()/pixelToMeteRatio);
mjActive.setTarget(vec);
}
}});
return true;
}
//===========================================
// RELEASE THE FINGER FROM THE SCENE..
//===========================================
if( pSceneTouchEvent.getAction() == MotionEvent.ACTION_UP ||
pSceneTouchEvent.getAction() == MotionEvent.ACTION_CANCEL
) {
this.runOnUpdateThread(new Runnable() {
@Override
public void run() {
if( mjActive != null )
{
//======================================
// DESTROY OUR MOUSEJOINT
//======================================
PhysicsJumpExample.this.mPhysicsWorld.destroyJoint(mjActive);
PhysicsJumpExample.this.mPhysicsWorld.destroyBody(groundBody);
mjActive = null;
}
}});
return true;
}
return false;
}
FYI:
To fit your needs, you have to play with this settings ( in the createMouseJoint method )
mjd.dampingRatio = 0.2f;
mjd.frequencyHz = 30;
mjd.maxForce = (float) (200.0f * boxBody.getMass());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the best way to optimize a big jquery POST? My problem is that after breaking the KB size on a jquery POST, the sending time is mostly bigger than 1 sec.
Is there a good way to optimize that?
And why it takes so long to send, so less data?
A: I had a similar problem, but in PHP. The thing is when you're sending POST requests with a lot of (or large) parameter values (larger than 1Kb if I remember correctly), HTTP tries to optimize the requests by sending "Expect: 100" header directive.
Meaning: wait for code 100 before sending the second part (those large parameters). In my case this was exactly 2 seconds. I solved this by sending the "Expect: " header directive.
If you look in the Net tab of your FireBug, is there by and chance the an Expect parameter in the Request Header?
You can manually add the header like this (if you're using the ajax jQuery function):
$.ajax
(
{
url: "return.php",
headers:
{
'Expect': ''
}
}
);
I might be completely wrong, but this sounded too familiar for me to stay silent...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: android meaning of @null in xml attribute I found the following attribute in one xml layout:
android:background="@null"
What is the meaning of @null? What is the difference between specifying background="@null" and omitting background attribute?
A: If I remember correctly, omitting the background attribute sets a default background. However, explicitly setting background to "@null" removes the background, causing whatever is below the element to be shown. In particular, if you for instance set the background of a Button to null, the border of the button will also be gone (and the button effectively will not really look like a button at all).
A: What i have observed if i do android:background="@null"or android:background="@android:color/transparent" both have same effect, they just remove the background of the view, so you will see the background colour of the view which is beneath this view.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "82"
}
|
Q: Objective c - CCCryptorStatus without CCOptions I would like to know, how can I define a CCCryptorStatus without using CCOptions. The documentation said, if I don't set the kCCOptionECBMode, the default is CBC mode, which is good for me. But I don't need for kCCOptionPKCS7Padding too, so how can I set this?
I try:
CCCryptorStatus cryptStatus = CCCrypt(opMode, /* Defines the basic operation: kCCEncrypt or kCCDecrypt */
kCCAlgorithmAES128, /* Defines the encryption algorithm */
0,...
but this is the correct way? Because if I want to use this method, I get an NSData object with full of 0, but with the correct size. So I don't think this value is good...
Thanks for any reply, madik
A: When I encountered this problem, I had to use kCCOptionPKCS7Padding. As far as I can see it's the only solution.
Please note, that using of the padding increases the security.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Totalise row in pivot table - Excel 2007 I have a spreadsheet I used to calculate time spend on projects. I take the weekly timesheets sent to me and I pick out and log the hours spent on a task for a specific person on a specific project.
I then want to totalise the time spent on each task, by each person, then the total time spent on the project by each person. Finally, a total time spent on the project my everyone.
I have created a pivot table to handle most of this, however I can not get the pivot table to totalise rows and columns. (Columns totalise fine) I could just manually SUM the rows, however I have to recreate / move the SUM each time I add a new task.
I hope the demo, downloadable from the link below shows what I want to achieve. Surely there has to be a way and I just can't see the wood for the trees.
Thanks
www.xserv.co.uk/MASTER Project Time_DEMO.xlsx
A: Excel 2010: In the pivot-table-options (e.g. from pivot table context menu / right click) select the first two check boxes in the sums and filters tab. This gives you sums (or whatever you select in the other options) of each row and column.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP - floatval cuts of position after decimal point? I have this PHP code:
<?php
$float = "1,99";
echo "<p>$float<br>";
$float = floatval($float); // Without this line number_format throws a notice "A non well formed numeric value encountered" / (float) $float leads to the same output
$val = number_format($float, 2,'.', ',');
echo "$float</p>";
?>
Why does it return 1? Don't get that.
And: yes, there is a sense in converting 1,99 to 1,99 ;-)
Thanks for advise...
A: The problem is, that PHP does not recognize the , in 1,99 as a decimal separator. The float type is defined as having the following formal definition:
LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})
That means it'll only accept . as a decimal separator. That's in fact the same reason why number_format throws a warning on an invalid datatype because it cannot convert 1,99 to a float internally.
The following should work:
$float = "1,99";
echo "<p>$float<br>";
$val = number_format(str_replace(',', '.', $float), 2,'.', ',');
echo "$float</p>";
A: floatval recognizes the comma (,) as a character and not as a number, so it cuts off everything that comes after it. In this case, that's the 99. Please use a dot (.) instead of a comma (,) and it will probably work.
Example floatval (source: http://php.net/manual/en/function.floatval.php):
<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>
A: 1,99 is not a valid php float. The issue is your comma (,). In PHP you have to use dot (.) as floating point separator.
<?php
$float = "1.99";
echo "<p>$float<br>";
$float = (float)$float;
$val = number_format($float, 2,'.', ',');
echo "$float</p>";
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: how to identity if button submit has opened a new browser window or new tab in watin I have the same problem, my site opens a new tab whenever I click on the submit form button.
Is there any way to check whether i have opened a new tab or new windows in watin
I have tried myself with ie.internetexplorers to get the new url, it worked in some cases but in most cases it failed.
does any one have any better idea
A: Browser.AttachTo() should find you the new window:
string expectedUrl = "http://mysite.com/expected-url/";
using (var newWindow = Browser.AttachTo<IE>(
Find.ByTitle("Expected title")))
{
Assert.AreEqual(expectedUrl, newWindow.Url);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Alarm Clock application source code Is there a way to get the Alarm Application source code for customizing the existing default source code availble in Android 2.3.
A: This is the version that's made and maintained by Google now in a move to keep the apps unbundled from the system so as to provide the apps and updates to everyone even if the OEMs don't provide system update.
Hence It's the one that's available from the Play store to download too. The one that's shared previously is the stock App which is quite old.
https://android.googlesource.com/platform/packages/apps/DeskClock/
As the site of the source may keep changing, best way for you to figure it out is by visiting Android Open Source Project (AOSP) page and searching for the URL of the code.
A: You can download the app from the Android github mirror.
https://github.com/android/platform_packages_apps_alarmclock
Or on the cyanogen mirror
https://github.com/CyanogenMod/android_packages_apps_DeskClock
And because, you are a nice guy, you are wondering: What is the license of that code?
Glad you asked, because according to the Android documentation and cyanogen's wikipedia page, it's the Apache Software License 2.0
And as we all know, the Apache license 2.0 is a nice license for the all hackers. Even those who intend to make a buck or two. (you little capitalist scoundrels)
Please note that, I didn't come up with that nice cheat sheet. Someone else did.
A: You can download whole android source tree including alarm app from here:
http://source.android.com/source/downloading.html
A: Cyanogenmod is dead. So, here's the latest Lineage DeskClock (Apache License 2.0) repository:
https://github.com/LineageOS/android_packages_apps_DeskClock
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594637",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Javascript widget works fine on my own domain, but not on anyone elses? Created javascript widget. Testing on my own domain and its working fine. However when posting on a 3rd party site it looks like it's not connecting to the database and getting the data.
Here is the part of the js file where I get the data:
/******* Load HTML *******/
var jsonp_url = "http://www.example.com/widget/data.php";
$.getJSON(jsonp_url, function(data) {
When I test on example.com everything is fine. I set the permissions on data.php to 777 and it still isn't working. Please help!
A: you cannot make an ajax call across different domains:
let's say your domain is 'example.com', and the third party site has 'thirdparty.com'. you install the widget on thirdparty.com. The widget code on thirdparty.com will try to make an ajax request to 'example.com'. Which is forbidden by the browser.
You can always replace the ajax call with a straight < script > tag. This doesn't have any restriction.
Hope it helps
A: You have a variable called jsonp_url, but the URL you use doesn't include the string callback=? which the documentation says triggers jsonp mode.
You need to include that in the URL and make sure that your server side script is outputting JSONP (using $_GET['callback'] (with suitable sanitisation) to determine the function name you wrap the JSON in).
A: they need to enable cross orgin resource sharing. http://enable-cors.org/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL shortest query without results I'm looking for a query with the lowest possible resource usage which gives no result. For example (this won't work):
SELECT 1 WHERE 0
Edit:
The goal would be to be used in an EXISTS subquery in special cases where I want no matches. (I know this is not the only possible solution, but in my environment I chose to use this one).
A: select '1' from tableName where 0
A: SELECT 1 FROM DUAL WHERE 0
will do the job; you will not even need a USE-statement before.
A: SELECT 1; would work but it gives a result set
You could try SELECT NULL from <any table>
A USE <database name> statement gives no result and takes up minimal resources.
What is this for exactly?
A: Perhaps you could do
select 1 where 1=0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: operator '-' cannot be applied to operands of type 'decimal' and 'Systems.Collections.Generic.IEnumerable I have this error that I am tying to solve.
Visual Studio 2010 gives the error as:
operator '-' cannot be applied to operands of type 'decimal' and 'Systems.Collections.Generic.IEnumerable<decimal>
My Code:
// Step 5: Retrieve MPR amount and deduct form Gross Tax Dictionary Per-Employee
//Query database
var taxtable = taxTableService.GetAllTaxTables();
var mprAmount = (from tt in taxtable select tt.U_MPR_amount).Distinct();
Dictionary<int, decimal> paye = new Dictionary<int, decimal>();
grossTaxDictionary.ToList().ForEach(x =>
{
var totalPAYE = x.Value - mprAmount;
paye.Add(x.Key, totalPAYE);
});
In my database, the field U_MPR_amount is a decimal and so is x.Value.
Error shows up on the line x.Value - mprAmount;
What could be the problem? Any help appreciated.
A: According to your code, mprAmount is a list, you cannot subtract it from a single value.
If you are certain that the list contains just a single element then you can retrieve it using the Single method:
var totalPAYE = x.Value - mprAmount.Single();
Or, more likely:
var mprAmount = (from tt in taxtable select tt.U_MPR_amount).Single();
Notice that I’ve changed Distinct for Single. Using both makes no real sense.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Password Displayed on inputSecret too long I Use JSF 1.2 and i want to display a password as six characters for the user, and since i use an md5 encryption, so the password is displayed too long.
This is my code
<h:inputSecret id="password"
redisplay="true"
value="{userHome.instance.password"
style="FONT-SIZE: medium;" title="Password">
</h:inputSecret>
Thks a lot
A: You should only apply MD5 hashing at the point the data is to be saved in the DB, not before.
You should not obtain the password from the DB whenever you present an edit form to the enduser. You should keep the field empty.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Registration timer expired, but client is still registering? my app program use coremotionmanager and locationmanager too.when i start the program, i found this error.
ERROR,Time,338977575.221,Function,"void CLClientHandleRegistrationTimerExpiry(__CFRunLoopTimer*, void*)",Registration timer expired, but client is still registering!
the error is'nt matter to my program ever. but recently i found my opengles view stopped unexpectedly when i move the ipod touch4 (use gyro). i checked my project, can't found any error except this.
anyone know how to slove this error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: invalid multibyte char (US-ASCII) MAC OSX RUBY on Rails Without magic enconding? On ruby 1.8.7 I had no problems with swedish chars ÅÄÖ but now on ruby 1.9.2 this exception comes up. Strangley enough it does not appear on my Ubuntu machine.
Can it be fixed without Magic encoding or putting #encoding utf-8 on top of every ruby file with Swedish chars?
A: Looks like there is no solution to avoid this Error without adding encoding line
Add "# coding: utf-8" to all files
A: Hmm, try to add this
export LC_ALL="en_US.UTF-8"
to your ~/.profile, ~/.bash_profile or equivalent. It worked here!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get dir of a file I think I have a simple question, but I cant figure it out. I would like to get the directory of a file.
Example:
path = /mnt/sdcard/music/music.mp3
Should return 'music'
public String getDir(String pathAudioFile)
{
File f = new File(pathAudioFile);
return f.???
}
A: f.getParent(); // returns directory String
f.getParentFile(); // returns File directory object
A: f.getParentFile().getName()
will return just "music", stripping off the leading path elements.
A: Here you go
File file = new File(pathAudioFile);
String parent = file.getParent();
System.out.println("Parent directory is : " + parent);
A: public String getDir(String pathAudioFile)
..
return f.getParent();
But the code should not be return a String that represents a File. It should return a File. 1
public File getDir(String pathAudioFile)
..
return f.getParentFile();
1 IMO all methods in the J2SE that are designed to accept a String that represents a File should be deprecated. If a method needs a File, give it a File!
Extending that philosophy..
@deprecated Use getDir(java.io.File) instead.
public File getDir(String pathAudioFile)
{
return getDir(new File(pathAudioFile));
}
public File getDir(File audioFile)
{
return audioFile.getParentFile();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to determine when DST starts or ends in a specific location in Python? I'm looking for a method of determining when DST starts or ends for a given timezone in a Python script I'm working on.
I know pytz can convert the UTC dates I'm working into localtime, and will take DST into account, however for this particular application I need to know the point of the changeover.
Any suggestions?
A: You could have a look to the _utc_transition_times memberof the timezone you're using.
>>> from pytz import timezone
>>> tz = timezone("Europe/Paris")
>>> print tz._utc_transition_times
[datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1911, 3, 10, 23, 51, 39), datetime.datetime(1916, 6, 14, 23, 0), datetime.datetime(1916, 10, 1, 23, 0), date
....
datetime.datetime(2037, 3, 29, 1, 0), datetime.datetime(2037, 10, 25, 1, 0)]
It will give you the list of the DST change dates (start and end of DST).
According to the code of tzinfo.py
class DstTzInfo(BaseTzInfo):
'''A timezone that has a variable offset from UTC
The offset might change if daylight savings time comes into effect,
or at a point in history when the region decides to change their
timezone definition.
'''
# Overridden in subclass
_utc_transition_times = None # Sorted list of DST transition times in UTC
_transition_info = None # [(utcoffset, dstoffset, tzname)] corresponding
# to _utc_transition_times entries
So if you mix the _utc_transition_times with _transition_info you will grab all your needed informations, date, time and offset to apply ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Get content between comments Hopefully not too tricky this one...
I am trying to get just the context between the <!-- itemtemplate --> comments using javascript (with the jQuery plugin). The result must exclude the comments though. In this case the parent is a table, but it can be anything such as a div
Table
<table id="lvList" class="grid1">
<tr>
<th>Name </th>
<th>Number </th>
<th>Type </th>
<th>Account Manager </th>
</tr>
<!-- itemtemplate -->
<tr>
<td><boundfield output="hyperlink" datafield="name" dataurlfields="id" dataurlformat="details/?id={0}" /></td>
<td><boundfield output="string" datafield="id" /></td>
<td><boundfield output="string" datafield="type" /></td>
<td><boundfield output="string" datafield="accmgr" /></td>
</tr>
<!-- itemtemplate -->
</table>
Div
<div id="lvList">
<!-- itemtemplate -->
something something something
<boundfield output="string" datafield="id" />
<!-- itemtemplate -->
</div>
Thanks to Felix for the idea
function GetTemplate(root, name) {
var output = "";
var record = false;
function iterate(node) {
var children = node.childNodes;
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child.nodeType === 3 && child.nodeValue.trim() === "") continue;
if (child.nodeType === 8 && child.nodeValue.trim() === name) {
if (!record) { record = true; continue; }
else { break; }
}
if (record)
output += outerHTML(child);
else {
if (child.hasChildNodes)
iterate(child);
}
}
}
iterate(root);
return output;
};
function ClearTemplate (root, name) {
var record = false;
function iterate(node) {
var children = node.childNodes;
for (var i = children.length - 1; i >= 0; i--) {
var child = children[i];
if (child.nodeType === 8 && child.nodeValue.trim() === name) {
if (!record) { record = true; continue; }
else { break; }
}
if (record)
node.removeChild(child);
else {
if (child.hasChildNodes)
iterate(child);
}
}
}
iterate(root);
};
function InsertInto (root, name, items) {
function iterate(node) {
var children = node.childNodes;
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child.nodeType === 3 && child.nodeValue.trim() === "") continue;
if (child.nodeType === 8 && child.nodeValue.trim() === name) {
for (var n = items.length - 1; n >= 0; n--)
child.parentNode.insertBefore(items[n], child.nextSibling);
break;
}
if (child.hasChildNodes)
iterate(child);
}
}
iterate(root);
};
String.prototype.trim = function () {
return this.replace(/^(\s| |\u00A0)+|(\s| |\u00A0)+$/g, "");
};
function outerHTML(node) {
return node.outerHTML ||
(function (n) {
var div = document.createElement('div');
div.appendChild(n.cloneNode(true));
return div.innerHTML;
})(node);
};
A: Neither regex nor jQuery: The idea is to iterate over all child nodes and check whether the node is a comment node and if yes, whether it contains a certain string, e.g. itemtemplate.
function extract(node, needle) {
var children = node.childNodes,
record = false,
container = document.createDocumentFragment();
for(var i = 0, l = children.length; i < l; i++) {
var child = children[i];
if(child.nodeType === 8 && child.nodeValue === needle) {
record = !record;
continue;
}
if(record) {
container.appendChild(child.cloneNode(true));
}
}
return container;
}
Usage:
var nodes = extract(someParent, ' itemtemplate ');
DEMO
I don't know whether this is the best solution for you situation, you don't give any information about the context.
A: Parsing XML data (as HTML is a type of) using regular expressions is bound to fail.
I suggest you use a tool specifically designed for parsing XML. In javascript, DOMParser can be used for this.
Link to w3schools for using this.
A: You can try this
var result = '<div id="lvList"><!-- itemtemplate -->something something something<boundfield output="string" datafield="id" /><!-- itemtemplate --></div>'.split(/<!--\s*itemtemplate\s*-->/)
result[1] will have the desired text you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Rewrite url: serve both query string and block urls my journey of learning MVC continues and as hard as it is, I'm learning a lot of things I could never learn otherwise. Now I have faced the problem in routing. Currently I'm taking the $_SERVER["REQUEST_URI"] and get the controller and method and any args. When url is in format http://mysite.com/forum/thread/12/1123 there is no problem but I need to catch also requests like http://mysite.com/index.php?forum=12&&thread=1123.
I have read links in threads below but cannot get my head on QSA and I though I would better ask.
Thanks
mod_rewrite: Check for Custom query string in URL?
Rewrite url with query string in htaccess
A: I ended up writing something like before:
I redirect using htaccess
//No Controller specified in url (The current url is base url like http://example.com/hosanna_framework/)
if(!isset($_GET['base_url'])){
$url = $config["router"]["default_controller"];
}
//Controller is specified in url
else{
$url = $_GET['base_url'];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making a HTTPS Post request using XML in Java I'm trying to use the API from Web Of Knowledge(WoK) to obtain some data. The documentation explain that you have to do POST Requests through HTTPS, sending a XML which contains the queries. But I only get the error 400 form server. (Bad Request)
Here is my code, I found it in Google and I make some fixes for my case.
public static void main(String[] args) throws Exception {
// Get target URL
String strURL = /*Here the Server URL*/;
// Get file to be posted
String strXMLFilename = "src/main/resources/xml/wosdata.xml";
File input = new File(strXMLFilename);
// Prepare HTTP post
PostMethod post = new PostMethod(strURL);
// Request content will be retrieved directly
// from the input stream
// Per default, the request content needs to be buffered
// in order to determine its length.
// Request body buffering can be avoided when
// content length is explicitly specified
post.setRequestEntity(new InputStreamRequestEntity(
new FileInputStream(input), input.length()));
// Specify content type and encoding
// If content encoding is not explicitly specified
// ISO-8859-1 is assumed
post.setRequestHeader(
"Content-type", "text/xml; charset=ISO-8859-1");
// Get HTTP client
HttpClient httpclient = new HttpClient();
// Execute request
try {
int result = httpclient.executeMethod(post);
// Display status code
System.out.println("Response status code: " + result);
// Display response
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
}catch (Exception e) {
e.printStackTrace();
} finally {
// Release current connection to the connection pool
// once you are done
post.releaseConnection();
}
}
A: There is something wrong with the XML you are sending. You will have to look at server logs to find out exactly what, as 400 deliberately tells you as little as possible.
A: You should do it like this. First read the contents of the xml to String and do post using a StringRequestEntity.
// Get file to be posted
String strXMLFilename = "src/main/resources/xml/wosdata.xml";
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(new File(strXMLFilename)));
try {
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
StringEntity requestEntity = new StringEntity(contents.toString());
post.setEntity(requestEntity);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Treeview with checkbox bind by different lists I have a class like this :
public class Project
{
List<Object> list1;
List<Object> list2;
}
I want to show this in a treeview control like as follows :
Checkbox + "Listing1"
--> Checkbox + Object 1 of list1
--> Checkbox + Object 2 of list1
Checkbox + "Listing2"
--> Checkbox + Object 1 of list2
-->Checkbox + Object 2 of list2
My biggest problem is making the difference between the 2 lists + some extra : if list2 does not contain any objects, the "Listing2" header may not be shown.
Does anybody have any good idea how I can do this ?
A: This can be solved without TreeView - Just 2 CheckBoxes and 2 ItemsControl with specific ItemTemplate.
I prefer this way of solving this problem:
<StackPanel>
<StackPanel.Resources>
<DataTemplate x:Key="MyTemplate">
<StackPanel Orientation="Horizontal">
<CheckBox Content="{Binding SomeProperty}" IsChecked="{Binding SomeBooleanProperty}" />
</StackPanel>
</DataTemplate>
</StackPanel.Resources>
<CheckBox Content="List number 1" />
<ItemsControl ItemsSource="{Binding list1}" ItemTemplate="{StaticResource MyTemplate}" />
<CheckBox Content="List number 2" />
<ItemsControl ItemsSource="{Binding list2}" ItemTemplate="{StaticResource MyTemplate}" />
</StackPanel>
As for your extra: you can bind Visibility to the property in your Project class, which will be looks like:
public class Project
{
public List<Object> list1;
public List<Object> list2;
public Visibility Visuality
{
get
{
return this.list2.Any() ? Visibility.Visible : Visibility.Colapsed;
}
}
}
and than in the code:
<ItemsControl Visibility="{Binding Visuality}" ... />
<CheckBox Visibility="{Binding Visuality}" ... />
...if I understand you right...
A: You can create one class TreeViewItemWithCheckbox by extending TreeViewItem class like below :
public class TreeViewItemWithCheckbox : TreeViewItem
{
#region Variable Declaration
CheckBox chkBox = new CheckBox();
StackPanel stpContent = new StackPanel();
#endregion
#region Properties
public string HeaderText
{
get { return chkBox.Content.ToString(); }
set { chkBox.Content = value; }
}
public bool IsChecked
{
get { return chkBox.IsChecked.Value; }
set { chkBox.IsChecked = value; }
}
#endregion
#region Constructor
public TreeViewItemWithCheckbox()
{
stpContent.Orientation = Orientation.Horizontal;
chkBox = new CheckBox();
chkBox.VerticalAlignment = VerticalAlignment.Center;
chkBox.Click += new RoutedEventHandler(SetCheckboxes);
chkBox.Margin = new Thickness(0, 0, 0, 0);
stpContent.Children.Add(chkBox);
Header = stpContent;
}
#endregion
#region Event Handlers
private void SetCheckboxes(object sender, RoutedEventArgs e)
{
TreeViewItemWithCheckbox selectedItem = ((TreeViewItemWithCheckbox)((StackPanel)((CheckBox)sender).Parent).Parent);
if (selectedItem != null)
{
/* Set checkboxes for all child items */
if (selectedItem.Items.Count > 0)
{
SetChildItemCheckboxes(selectedItem, selectedItem.IsChecked);
}
/* Check if all childs checked then check/uncheck parent accoringly */
if (selectedItem.Parent.GetType() == typeof(TreeViewItemWithCheckbox))
{
TreeViewItemWithCheckbox parentItem = (TreeViewItemWithCheckbox)selectedItem.Parent;
bool bIsAllChecked = true;
foreach (TreeViewItemWithCheckbox item in parentItem.Items)
{
if (!item.IsChecked)
{
bIsAllChecked = false;
break;
}
}
parentItem.IsChecked = bIsAllChecked;
}
}
}
private void SetChildItemCheckboxes(TreeViewItemWithCheckbox item, bool IsChecked)
{
if (item.Items.Count > 0)
{
foreach (TreeViewItemWithCheckbox childItem in item.Items)
{
SetChildItemCheckboxes(childItem, IsChecked);
item.IsChecked = IsChecked;
}
}
else
item.IsChecked = IsChecked;
}
#endregion
}
Then you need to add treeview nodes from 2 list like below :
trvTest.Items.Clear();
//Add default root element
TreeViewItemWithCheckbox rootNode = new TreeViewItemWithCheckbox();
rootNode.HeaderText = "Root";
rootNode.IsExpanded = true;
trvTest.Items.Add(rootNode);
if (_project.list1.Count > 0)
{
TreeViewItemWithCheckbox nodeHead1 = new TreeViewItemWithCheckbox();
nodeHead1.HeaderText = "Listing 1";
rootNode.Items.Add(nodeHead1);
TreeViewItemWithCheckbox node1;
for (int i = 0; i < _project.list1.Count; i++)
{
node1 = new TreeViewItemWithCheckbox();
node1.HeaderText = _project.list1[i].Name;
nodeHead1.Items.Add(node1);
}
}
if (_project.list2.Count > 0)
{
TreeViewItemWithCheckbox nodeHead2 = new TreeViewItemWithCheckbox();
nodeHead2.HeaderText = "Listing 2";
rootNode.Items.Add(nodeHead2);
TreeViewItemWithCheckbox node2 = new TreeViewItemWithCheckbox();
for (int i = 0; i < _project.list2.Count; i++)
{
node2 = new TreeViewItemWithCheckbox();
node2.HeaderText = _project.list2[i].Name;
nodeHead2.Items.Add(node2);
}
}
A: If your first "Listing" items are static, you can do something like this
<TreeView x:Name="tv">
<TreeViewItem Header="Listing 1" ItemsSource="{Binding list1}"/>
<TreeViewItem Header="Listing 2" ItemsSource="{Binding list2}"/>
</TreeView>
To hide elements without children you need a bit of code.
var view = CollectionViewSource.GetDefaultView(_project.list1);
view.Filter = myFilter;
view.Refresh();
tv.DataContext = _project;
For both lists of course.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Blackberry screen renew with new data I am developing a Blackberry Application. I have a map in a screen. I want to refresh map's data with new data which i am getting from my web service. I am using BlockingSenderDestination in a Thread. When i request "get data" its return new data. no problem. I am using invokelater function to call my maprefresh function with passing arguments but i got illegalargumentexception.
Any suggestion to solve my problem or any better way to do this?
Here is my code:
public class MyMainScreen extends MainScreen {
RichMapField map;
MyClassList _myclassList;
private String _result2t;
public MyMainScreen(JSONArray jarray)
{
map = MapFactory.getInstance().generateRichMapField();
MapDataModel mapDataModel = map.getModel();
JSONObject json = null;
boolean getdata=false;
for (int i=0;i<jarray.length();i++)
{
try
{
json=jarray.getJSONObject(i);
getdata=true;
}
catch(Exception e)
{
}
if(getdata)
{
try
{
double lat = Double.valueOf(json.getString("LATITUDE")).doubleValue();
double lng = Double.valueOf(json.getString("LONGITUDE")).doubleValue();
String myclassdata= json.getString("myclassdata").toString();
MyClass ben = new MyClass(myclassdata);
_myclassList.addElement(ben);
MapLocation termimapitem = new MapLocation( lat, lng, "","");
mapDataModel.add((Mappable)termimapitem,"1");
}
catch(Exception e)
{
//mesajGoster("Hatalı Veri");
}
}
else
{
//mesajGoster("Listeye Eklenemedi");
}
}
}
private void GetTerminals(String companyNo){
final String companyNoR= companyNo;
Thread t = new Thread(new Runnable()
{
public void run()
{
Message response = null;
String uriStr = "http://webservice";
BlockingSenderDestination bsd = null;
try
{
bsd = (BlockingSenderDestination)
DestinationFactory.getSenderDestination
("o", URI.create(uriStr));
if(bsd == null)
{
bsd =
DestinationFactory.createBlockingSenderDestination
(new Context("o"),
URI.create(uriStr)
);
}
response = bsd.sendReceive();
if(response != null)
{
BSDResponse(response,companyNoR);
}
}
catch(Exception e)
{
}
finally
{
if(bsd != null)
{
bsd.release();
}
}
}
});
t.start();
}
private void BSDResponse(Message msg,final String companyNo)
{
if (msg instanceof ByteMessage)
{
ByteMessage reply = (ByteMessage) msg;
_result2t = (String) reply.getStringPayload();
} else if(msg instanceof StreamMessage)
{
StreamMessage reply = (StreamMessage) msg;
InputStream is = reply.getStreamPayload();
byte[] data = null;
try {
data = net.rim.device.api.io.IOUtilities.streamToBytes(is);
} catch (IOException e) {
// process the error
}
if(data != null)
{
_result2t = new String(data);
}
}
try {
final JSONArray jarray= new JSONArray(_result2t);
final String username=_userName;
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("The Toolbar i");
Yenile(jarray);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void Yenile(JSONArray jarray){
MapDataModel mapDataModel = map.getModel();
mapDataModel.remove("1");
map.getMapField().update(true);
_terminalList = new TerminalList();
map= MapFactory.getInstance().generateRichMapField();
MapDataModel mapDataModel = map.getModel();
JSONObject json = null;
boolean getdata=false;
for (int i=0;i<jarray.length();i++)
{
try
{
json=jarray_terminaller.getJSONObject(i);
getdata=true;
}
catch(Exception e)
{
}
if(getdata)
{
try
{
double lat = Double.valueOf(json.getString("LATITUDE")).doubleValue();
double lng = Double.valueOf(json.getString("LONGITUDE")).doubleValue();
String myclassdata= json.getString("myclassdata").toString();
MyClass ben = new MyClass(myclassdata);
_myclassList.addElement(ben);
MapLocation termimapitem = new MapLocation( lat, lng, "","");
mapDataModel.add((Mappable)termimapitem,"1");
}
catch(Exception e)
{
//mesajGoster("Hatalı Veri");
}
}
else
{
//mesajGoster("Listeye Eklenemedi");
}
}
}
}
A: To refresh the screen: do like this:
public class LoadingScreen extends MainScreen{
LoadingScreen()
{
createGUI();
}
public void createGUI()
{
//Here you write the code that display on screen;
}}
we know that this is the actual way of creating a screen;
Now if you want to refresh the screen write like below:
deleteAll();
invalidate();
createGUI();//here it creates the screen with new data.
Instead of writing in InvokeLater method better to write the above three lines in run method after Thread.sleep(10000);
If you have any doubts come on stackOverFlow chat room name "Life for Blackberry" for clarify your and our doubts.
A: I found a solution to my question.
After getting the data i was sending it via new run method:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
MyFunction(jarray);
}});
But i was need to synchronize with main thread. So the solution:
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
synchronized(Application.getEventLock()) {
Yenile(jarray);
}
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Will a client side MVC framework suit building UI controls Lately i have been thinking of developing UI controls suite similar to Extjs or YUI but using a MVC framework like Backbone or Spine. Am i wrong in taking this decision? Will a mvc framework suit the purpose of such development? What would the significance, cost of maintaining such a project would be.
A: Technically, I don't see why you can't do this. You would forgo the "router" portion of Backbone and stick with Models, Collections and Views. You would probably also forgo all of the backend syncing capabilities of the Collections and Models in favor of your own interface with the client application. You would also have to come up with a way to apply the Backbone render pattern generically to allow the client app to host your widgets. You would get some separation of concerns still and your widget kit would work.
But, I don't know if I would recommend it. By building a widget kit around Backbone, you are requiring that your users be bound to Backbone, Underscore and probably jQuery as well. You'd be doing this but throwing out many of the features that Backbone has to offer (like routing and syncing). If the client application is also using Backbone, you might also get into version incompatibility issues, so you'd have to deal with that by using noConflict.
In all, it would feel to me like you are shoehorning a whole suite of tools into your widget kit for minimal gain. Your widget kit would be fat and bloated right off the bat. Instead, I would try to make my widget kit more lightweight. Use the patterns you've learned in Backbone but don't use backbone itself. Even consider ripping some of the Backbone code out to base your infrastructure off of, but modify it to eliminate the features that you won't be using and make it your own.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Collapsed methods expands after IDE restart I fold (collapse) some method in Android project in IntelliJ IDEA either via plus sign or via "right click->Folding->Collapse". I close IntelliJ. After I reopen the IDE, the methods are unfolded (expanded) again.
Is there a way to solve this? It this IDE's bug or I can fix this in IDE's properties?
A: Folding of individual methods is not saved. The folding settings can be found here: File --> Settings --> Editor --> Code Folding
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Should I use Global ID's or find another solution to my Notification system? So I have nearly finished my notification system, and just before I am about to implement reCAPTCHA, I test what happens if I spam the notifications.
To give you some background on my notification system. I determine the newest content, by its timestamp. I retrieve the rows from the database ORDER BY timestamp. The timestamp value is an integer formatted to Unix Time. When notifications are shown, they are hyperlinks, that follow this URL format -
http://test.com/article/id
Where id is the id for the table, each time a new article is submitted, the id increments. I noticed after spamming my notifications, that the URL's of the spammed notifications are in reverse order. After further investigation, I find that if I spam quick enough, the timestamp variable is not accurate enough, and records multiple submissions with the same timestamp.
Since my website is low traffic now, and there aren't many submissions, this is currently not an issue, but if, a very small chance, but if a piece of content is submitted at the same time as another, the notifications will rank when they were submitted wrongly, a small, but annoying bug.
So I'm wondering what I should do. Should I fix the issue, or is this an extremely minute chance of this happening. Due to the implementation of reCAPTCHA, spamming is not an issue, but there is still a chance this could happen by accident.
I have come up with 3 possible solutions. My question is which would be the most efficient
*
*Create a global id for all 4 types of content, which increments every time a comment, article or update is created.
*Use a more accurate PHP time function, such as microtime
*Add some sort of secondary ranking variable
A: Given that there can be multiple threads and even multiple nodes in a cluster inserting data in different tables there is always a possibility that any clock based value you use will get duplicated in multiple, or even the same, table.
So my first thought is to use a global id table. You could use a common content table with an auto-incrementing primary key that all other tables foreign key into and use that for ordering.
On the other hand, by the same logic, how well can you ensure some fixed order between submissions? It is quite possible that two submissions will be committed to the database in the reverse order of receiving at the server. The only way to solve that problem I think is to a have a global gatekeeper that all requests have to pass through. If you are using such a gatekeeper, that is also the best place to assign the ordering value.
All in all, I think you should not insist on complete ordering because it does not exist unless it is a highly ordering sensitive system such as Trading or Betting. Otherwise microsecond should be good enough, as long as the notification for a comment on a article does not come before the article itself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: htaccess rewrite rule, old URL to new A bit of help fellow SO people.
What I have at the moment (based on some code I used for a different type of URL).
I want the first URL to redirect to the second, with no query string included afterwards
This is what I have to so far.
RewriteRule ^(page.php?id=missionstatement+)/?$ http://example.com/why/mission-statement [R=301,L]
RewriteRule ^(page.php?id=ofsted+)/?$ http://example.com/how/ofsted-report [R=301,L]
RewriteRule ^(page.php?id=governingbody+)/?$ http://example.com/governors [R=301,L]
A: Here is the rule (will redirect 1 URL):
RewriteCond %{QUERY_STRING} ^id=whatever
RewriteRule ^page\.php$ http://%{HTTP_HOST}/how/somehow? [R=301,L]
*
*This rule intended to be placed in .htaccess in website root folder. If placed elsewhere some small tweaking may be required.
*I have used %{HTTP_HOST} -- this will redirect to the same domain as requested URL. If domain name has to be different, replace it by exact domain name.
*The ? at the end of new URL will get rid of existing query string.
A: Ahoy!
Give this a whirl:
#check mod_rewrite is enabled
<IfModule mod_rewrite.c>
#enable mod rewrite
RewriteEngine On
#set working directory
RewriteBase /
#force trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [R=301,L]
#bootstrap index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^page.php\?id=(.*)$ http://www.willans.com/page.php/$1 [R=310,L]
#end mod rewrite check
</IfModule>
It's been a while since i've done any web dev, but that should be a push in the right direction at least ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to optimize the updating of values in an ArrayList I want to store all values of a certain variable in a dataset and the frequency for each of these values. To do so, I use an ArrayList<String> to store the values and an ArrayList<Integer> to store the frequencies (since I can't use int). The number of different values is unknown, that's why I use ArrayList and not Array.
Example (simplified) dataset:
a,b,c,d,b,d,a,c,b
The ArrayList<String> with values looks like: {a,b,c,d} and the ArrayList<Integer> with frequencies looks like: {2,3,2,2}.
To fill these ArrayLists I iterate over each record in the dataset, using the following code.
public void addObservation(String obs){
if(values.size() == 0){// first value
values.add(obs);
frequencies.add(new Integer(1));
return;//added
}else{
for(int i = 0; i<values.size();i++){
if(values.get(i).equals(obs)){
frequencies.set(i, new Integer((int)frequencies.get(i)+1));
return;//added
}
}
// only gets here if value of obs is not found
values.add(obs);
frequencies.add(new Integer(1));
}
}
However, since the datasets I will use this for can be very big, I want to optimize my code, and using frequencies.set(i, new Integer((int)frequencies.get(i)+1)); does not seem very efficient.
That brings me to my question; how can I optimize the updating of the Integer values in the ArrayList?
A: Use a HashMap<String,Integer>
Create the HashMap like so
HashMap<String,Integer> hm = new HashMap<String,Integer>();
Then your addObservation method will look like
public void addObservation(String obs) {
if( hm.contains(obs) )
hm.put( obs, hm.get(obs)+1 );
else
hm.put( obs, 1 );
}
A: I would use a HashMap or a Hashtable as tskzzy suggested. Depending on your needs I would also create an object that has the name, count as well as other metadata that you might need.
So the code would be something like:
Hashtable<String, FrequencyStatistics> statHash = new Hashtable<String, FrequencyStatistics>();
for (String value : values) {
if (statHash.get(value) == null) {
FrequencyStatistics newStat = new FrequencyStatistics(value);
statHash.set(value, newStat);
} else {
statHash.get(value).incrementCount();
}
}
Now, your FrequencyStatistics objects constructor would automatically set its inital count to 1, while the incrementCound() method would increment the count, and perform any other statistical calculations that you might require. This should also be more extensible in the future than storing a hash of the String with only its corresponding Integer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Excel having columns with dot(.) I am working in c# windows forms product.
I am exporting some data to an excel.these data are inputted by the user.the rows in he dataset are made columns in the excel.these column names has 'dot'. While exporting,these columns remain the same.But while trying to import back the data,the column names which are having dot will have # in the dataset
eg..initially it was A.B,now in dataset it is A#B.
on the client side i cannot simply convert # to dot as the user can also give input with #.Please help me to solve this problem.I am not able to find a solution.
Thanks
Neethu
A: On your connectionString, set HDR=No. Now DataSet treats column names as rows and you will get the data as it is there in the excel.
string cnnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"C:\\Untitled 1.xls\";Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\"";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Add behaviour to TextBlock silverlight 3 I want to add a behaviour to a TextBlock in silverlight 3.
I have a behaviour class in a c# file in a different project than my xaml file within my solution.
public class FooBehavior : Behavior<TextBlock>
{
...
}
How do I attach this behaviour to my TextBlock? Would be nice to do without involving c# code.
A: Include the following lines in the definition of your UserControl:
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:myBehaviors="clr-namespace:MyNamespace.Behaviors;assembly=MyAssembly"
Then on the TextBlock have this code:
<TextBlock .....>
<i:Interaction.Behaviors>
<myBehaviors:FooBehaviour/>
</i:Interaction.Behaviors>
</TextBlock>
A: ChrisF has the correct answer for how to write the Xaml to add the behavior. However, if you have Blend it is even simpler.
*
*Open your project in Blend
*On the tools toolbar click the >> button
*Click on Behaviors
*Find your Behavior and Drag it over your TextBlock and drop it
Blend will add all the proper namespaces for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: CSS3 @font-face. Get width of imported font This is how i import the TTF font:
@font-face {
font-family: bt;
src: url('Monospace 821 BT.ttf');
}
body {
font: normal 21px bt;
}
And this is how i calculate the Width of font characters:
window.onload = function() {
var k = document.createElement('div');
k.innerHTML = 'M';
k.style.position = 'absolute';
document.body.appendChild(k);
var size = [
k.offsetWidth,
k.offsetHeight
];
document.body.removeChild(k);
alert(size[0]+' '+size[1]);
};
Using this method i am able to calculate the width & height successfully of the system's fixed-width fonts like "Monospace", "Monaco" etc.
But as for the imported font the results I get vary every time i change the character 'M' to something else. Also, YES, i am able to write on-screen with the imported font, so indeed it is successfully loaded in the <body>.
How can this behavior get fixed?
A: Browsers handle things like kerning differently, so the spacing between letters (even if it's a monospace font) isn't guaranteed to be uniform. Particularly so if the font has varied metrics; the appearance of the characters might be the same, but the actual metrics assigned to each glyph could be wider or thinner. What you see isn't always what you get as far as digital typography is concerned.
If the application you're using requires setting some arbitrary dimensions based on the font size, I'd suggest using a relative CSS unit instead like ch, which pertains to the width of the character "0" as rendered in the element's current typeface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: implement scrollView events in Android [RE-EDIT]
I am trying to implement these events in the scrollView:
*
*OnSingleTap
*OnDoubleTap
*PaningStart
*OnPanning
*PanningEnd
*PinchingStart
*OnPinching
*PinchingEnd
*RotatingStart
*OnRotating
*RotatingEnd
*OnLongPress
The application is a collection of UI parts that function as one UI part. I have categorized them under a relative layout which I've placed in the scrollView.
I am completely new at this and I would appreciate any help offered. Thanks.
[RE-EDIT]
code sample:
public class Mobclassname extends ScrollView {
private Object[] children;
private ArrayList<Object> uiParts = null;
private Context context;
public MobGadgetFile(Context context, NSDictionary dict) {
super(context);
this.context = context;
setProperties(dict);
uiParts = ObjectMgr.createUIParts(context, children);
RelativeLayout rl = new RelativeLayout(context);
MobUtils.addUIparts(uiParts, rl);
HorizontalScrollView hscroll = new HorizontalScrollView(context);
hscroll.addView(rl);
this.addView(hscroll);
}
I am doing everything in code therefore I don't have any xml layout file. This is my specification.
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Centering thumbnail gallery with captions without fixed image size I've tried unsuccessfully to implement the layout in the attached image. When apllied div with table setting IE brokes, if elements are floated when captions are more than one line the layout is broken again. Any suggestion will be greatly appreciated.!
Layout image:
Here is the CSS
.thumbsHolder {clear:both;float:left;width:100%;overflow:hidden;}
.thumbsHolder ul#prodThumbs {padding-top:20px;margin:0 auto;list-style-type:none;text-align:center;}
.thumbsHolder ul#prodThumbs li {float:left;padding:0 7px;min-height:150px;}
.thumbsHolder ul#prodThumbs li a {font-family:Arial, Helvetica, sans-serif;font-weight:normal;text-decoration:none;font-size:70%;}
HTML
<div class="thumbsHolder">
<ul id="prodThumbs">
<li><a href="link1.htm"><img src="thumb1.jpg" /></a> <!-- image width and height may differ -->
<p><a href="link1.htm">Caption</a></p></li>
<li><a href="link2.htm"><img src="thumb2.jpg" /></a>
<p><a href="link2.htm">Longer caption</a></p>
</li>
<li><a href="link3.htm"><img src="thumb3.jpg" /></a>
<p><a href="link3.htm">Even longer caption</a></p>
</li>
<li><a href="link4.htm"><img src="thumb4.jpg" /></a>
<p><a href="link4.htm">Longer caption</a></p>
</li>
<li><a href="link5.htm"><img src="thumb5.jpg" /></a>
<p><a href="link5.htm">Caption this time is a sentence that goes three rows</a></p>
</li>
<li><a href="link6.htm"><img src="thumb6.jpg" /></a>
<p><a href="link6.htm">Caption this time is a sentence that goes three rows</a></p>
</li>
<li><a href="link7.htm"><img src="thumb7.jpg" /></a>
<p><a href="link7.htm">Caption this time is a sentence that goes three rows</a></p>
</li>
<li><a href="link8.htm"><img src="thumb8.jpg" /></a>
<p><a href="link8.htm">Caption this time is a sentence that goes three rows</a></p>
</li>
<li><a href="link9.htm"><img src="thumb9.jpg" /></a>
<p><a href="link9.htm">Since we have a wider image at first row, this row must be centered</a></p>
</li>
<li><a href="link10.htm"><img src="thumb10.jpg" /></a>
<p><a href="link10.htm">Longer caption</a></p>
</li>
<li><a href="link11.htm"><img src="thumb11.jpg" /></a>
<p><a href="link11.htm">Here text also goes down, so if we float layout breaks</a></p>
</li>
<li><a href="link12.htm"><img src="thumb12.jpg" /></a>
<p><a href="link12.htm">Caption</a></p>
</li>
<li><a href="link13.htm"><img src="thumb13.jpg" /></a>
<p><a href="link13.htm">Longer caption</a></p>
</li>
<li><a href="link14.htm"><img src="thumb14.jpg" /></a>
<p><a href="link14.htm">This is a centered image</a></p>
</li>
<li><a href="link15.htm"><img src="thumb15.jpg" /></a>
<p><a href="link15.htm">This is out last image</a></p>
</li>
</ul>
</div>
A: You should know what the maximum size of a thumbnail will be when generated on your site, there must be some limit. Why not wrap your tag into a div set that divs height to the max of a thumbnail. Then align the img in the div. Then you have your p tag below for captions
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to keep my data in a array-iphone sdk I'm trying to create an application, and in that I'm receiving some contents from net and loading into and array, if I quit and run the app again i'm losing the data. How can I store the data in the app itself. Should I use some kind of database? If so which one and how can I implement that? I need to store only some string variables.
EDIT:
My app is tabbar based app, and have two tabs. Loading the arrays in one tab and loading that array in a table in the other VC. once I load the array and move to the second tab, the table is loaded with the array. If i go back and add few more values and then if i check, the added datas is not displayed in the table. And also, when I quit the app the table lose all the values, I need to keep the values in the table, even after i quit the app. How can I do that?
here is my code:
in viewdidload:
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
[simplePlistDb setBool:YES forKey:@"isItWorking"];
[simplePlistDb setObject:alertList forKey:@"myArray"];
[simplePlistDb synchronize];
in cellforrowatindexpath:-
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
BOOL flag = [simplePlistDb boolForKey:@"isItWorking"];
if (flag)
{
NSArray *myArray = [simplePlistDb objectForKey:@"myArray"];
for (NSString *str in myArray){
NSLog(@"Str:%@", str);
[loadArray addObject:str];
}
cell.textLabel.text = [loadArray objectAtIndex:indexPath.row];
}
Thank you.
A: You will want to look into Core Data if you want to save a decent amount of data to the iPhone. However, if not, you can just load the items in the array into a plist and load them from there at launch.
Plist Writing: How to create a new custom property list in iPhone Applications
CoreData: http://www.raywenderlich.com/934/core-data-tutorial-getting-started
Edit--->
As Nekto said, you can also use NSUserDefaults, but I advise mainly using NSUserDefaults for simple NSStrings and integers.
A: I think for your purposes NSUserDefaults will be enough : NSUserDefaults Class Reference.
Examples:
// save
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
[simplePlistDb setBool:YES forKey:@"isItWorking"];
[simplePlistDb setObject:[NSArray arrayWithObjects:@"very", @"cool", nil]];
[simplePlistDb synchronize];
// restore
NSUserDefaults *simplePlistDb = [NSUserDefaults standardUserDefaults];
BOOL flag = [simplePlistDb boolForKey:@"isItWorking"];
if (flag)
{
NSArray *myArray = [simplePlistDb objectForKey:@"myArray"];
for (NSString *str in myArray)
NSLog(@"%@", str);
}
A: You can use NSUserDefaults in order to store your data till the time your app is installed in your device.
How to write in NSuserDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"yourObject1" forKey:@"correspopndingKey1"];
[defaults setObject:@"yourObject2" forKey:@"correspopndingKey2"];
[defaults synchronize];
How to read from NSuserDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *temp1 = [defaults objectForKey:@"correspopndingKey1"];
NSString *temp2 = [defaults objectForKey:@"correspopndingKey2"];
You can store NSArray in a similar way.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:objArray forKey:@"correspopndingKey"];
[defaults synchronize];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: using oembed - json responses (in client side javascript) If an oembed provider is only outputting json and xml, does that mean it is impossible to use this via client side javascript? ($.ajax request to the provider)?
Can we only use oembed providers that allow for a jsonp callback in javascript?
Thanks,
Wesley
A: you cannot use ajax across different domains.
Jsonp is an option, other option is to have a server side script which will fetch the data from the provider and then make an ajax call to that script to return the fetched data
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: lot of records in html5 local storage? 1) is it possible to store lot of records in html5 storage?
2) what is the maximum size of local storage of HTML5?
3) can we access local storage using RDBMS Concept?
A: 1 - Yes
2 -
Disk space
User agents should limit the total amount of space allowed for storage
areas.
User agents should guard against sites storing data under the origins
other affiliated sites, e.g. storing up to the limit in
a1.example.com, a2.example.com, a3.example.com, etc, circumventing the
main example.com storage limit.
User agents may prompt the user when quotas are reached, allowing the
user to grant a site more space. This enables sites to store many
user-created documents on the user's computer, for instance.
User agents should allow users to see how much space each domain is
using.
A mostly arbitrary limit of five megabytes per origin is recommended.
Implementation feedback is welcome and will be used to update this
suggestion in the future.
http://dev.w3.org/html5/webstorage/#disk-space
3 -
http://www.w3schools.com/html5/html5_webstorage.asp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the SQL Query To Find in MySQL DB Table without considering the accented letters? Like the Title.
What is the SQL Query To Find in MySQL DB Table without considering the accented letters?
So, if I search "abcdè" I find "abcde"
A: By default utf8 strings ignore accents as they use the utf8_general_ci collation.
If you're not using utf8 (and why not?) Then you probably want to use the COLLATE command:
http://dev.mysql.com/doc/refman/5.0/en/charset-collate.html
SELECT *
FROM t1
WHERE _latin1 'Müller' COLLATE latin1_german2_ci = k;
SELECT *
FROM t1
WHERE k LIKE _latin1 'Müller' COLLATE latin1_german2_ci;
Also, you can apparently use the 'SET NAMES' command to alter the comparisons:
MySQL diacritic insensitive search (spanish accents)
A: Collation is the set of rules your DB is using to compare values. "all" you have to do is choose the right collation for your application. That said, @Danack57 above already gave you that piece of information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jsp with javascript parameter inside javascript onclick I would like to insert a call to a function to get a parameter for my JavaScript onclick function. What I would like to do is something like:
<input class="refreshbutton"
type="button"
id="searchUfficiPopup"
onClick="javascript:postColorbox('/DeliDete/searchUfficiPopupBySettoreId', **'&settoreIdKey=${javascript:getSettoriId()}'**, 'tabUfficiForm', 'initScriptUffici')"
value="<fmt:message key="navigation.searchUffici"/>" />
This way Eclipse tells me the function javascript:getSettoriId() is undefined. I defined this function in an external .js file, loaded at runtime with jQuery's .getScript, so I would not like to insert it into the jsp (anyway I tried to insert it into the jsp but the IDE still says that the function is not defined).
The function postColorbox is defined as:
function postColorbox(url, parameters, formName, initScript)
The function getSettoriId() returns the value of a previously entered form element, Settori, which I need to perform a restricted query (I need to obtain all Uffici entities related to the selected Settori entity)
Told this, I would like to ask you experts:
*
*Is it even possible to use a JavaScript function as a parameter of an onclick JavaScript function?
*If I put this function to be called in an external .js file will the jsp be able to see it and call it?
Thank you all for your help!
Andrea
A: Calling functions from inside the HTML element is not a preferred way. If you can - just assign the element an id or class, and then add a listener to it using javascript on page load.
This way you don't have your data and operations mixed. It will be also easier to modify the code, as your code will be located in js files.
A: Remove the onClick on your <input> and do it with a jQuery event handler instead:
$('#searchUfficiPopup').click(function() {
var settoriId = getSettoriId();
postColorbox('/DeliDete/searchUfficiPopupBySettoreId',
'&settoreIdKey=' + settoriId,
'tabUfficiForm',
'initScriptUffici');
return false;
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSURL getting value from string I have the following string that I am passing into [NSURL URLWithString:] and getting nil back.
I do not see anything wrong with the string??
/Users/danny/Library/Application Support/iPhone Simulator/4.3.2/Applications/A7C18F62-6ED3-4193-993B-D724ADA4D292/fantasy.app/common/files/file1/movies/demo1.mov
Am I mistaken?
Thanks
A: Try the +fileURLWithPath: method, it should do what you want.
A: use this
NSURL *url = [NSURL fileURLWithPath:yourString]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Slide Background with AnythingSlider I need to slide a background when clicking the "next" arrow, and the "previous" arrow - right now the background is in the #container element - However, that doesnt work - I've tried putting the background on the ul#slider element - But that doesnt work either...
What i need is that the background will be slider as much as the liinside the slider...
Any suggestions on how to do that ?
You can see the project here: http://www.i-creative.dk/Slider/
thx
A: I've built something like what you're asking for, and it's a total pain.
The problem is, you're talking about having a different background image, the size of the page, for EVERY slide.
2 options are:
1: Have one BIG background image, with all the background aligned horizontally, and animate the css background-position when you change a div, to keep things matching. This ahs the advanatage that only one image needs to be downloaded, but it will be big.
Problems are: you see all the other images if you jump multiple steps at once;
it requires that you use a fixed width;
it's a pain if you want to change the background for just one slide;
*
*Preload the background for the next slide on a div which is a sibling of container but has a higher z-index. Use jquery to slide this over the existing background, from the appropriate side.
The good thing about this method is that you can use css to make the background image always take up the full-width of the screen, or use a bigger imager and have it centred. See here: http://cksk.com for an example.
Long story short, you won't get this working with an off-the-shelf solution, you'll need to get your hands dirty.
Also, you'll need to spend a hell of a lot of time on optimisation.
A: Try this css...
#slider {
width: 472px; /* divided the width of the background image by 4 (# of panels) */
height: 570px;
list-style: none;
/* start background after the initial cloned panel: 472px to match panel width */
background: transparent url(../images/background.png) 472px 0 repeat-x;
}
/* This makes sure the last cloned panel background matches the first panel */
ul#slider li.clone {
background: transparent url(../images/background.png) 0 0 repeat-x !important;
}
/* Make the background visible */
div.anythingSlider .anythingWindow {
overflow: visible !important;
}
The only problem is that the width of the UL is limited, so when you get to the last panel, the background ends, but reappears once you hit the right arrow.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to match ets:match against a record in Erlang? I have heard that specifying records through tuples in the code is a bad practice: I should always use record fields (#record_name{record_field = something}) instead of plain tuples {record_name, value1, value2, something}.
But how do I match the record against an ETS table? If I have a table with records, I can only match with the following:
ets:match(Table, {$1,$2,$3,something}
It is obvious that once I add some new fields to the record definition this pattern match will stop working.
Instead, I would like to use something like this:
ets:match(Table, #record_name{record_field=something})
Unfortunately, it returns an empty list.
A: Format you are looking for is #record_name{record_field=something, _ = '_'}
http://www.erlang.org/doc/man/ets.html#match-2
http://www.erlang.org/doc/programming_examples/records.html (see 1.3 Creating a record)
A: The cause of your problem is what the unspecified fields are set to when you do a #record_name{record_field=something}. This is the syntax for creating a record, here you are creating a record/tuple which ETS will interpret as a pattern. When you create a record then all the unspecified fields will get their default values, either ones defined in the record definition or the default default value undefined.
So if you want to give fields specific values then you must explicitly do this in the record, for example #record_name{f1='$1',f2='$2',record_field=something}. Often when using records and ets you want to set all the unspecified fields to '_', the "don't care variable" for ets matching. There is a special syntax for this using the special, and otherwise illegal, field name _. For example #record_name{record_field=something,_='_'}.
Note that in your example you have set the the record name element in the tuple to '$1'. The tuple representing a record always has the record name as the first element. This means that when you create the ets table you should set the key position with {keypos,Pos} to something other than the default 1 otherwise there won't be any indexing and worse if you have a table of type 'set' or 'ordered_set' you will only get 1 element in the table. To get the index of a record field you can use the syntax #Record.Field, in your example #record_name.record_field.
A: Try using
ets:match(Table, #record_name{record_field=something, _='_'})
See this for explanation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: convert objects to JSON and send via jquery ajax I've 1 object:
var myobject = {first: 1, second: {test: 90}, third: [10, 20]};
and I want to send it as JSON string via jQuery ajax.
How can I do it? (i test JSON.stringify(), but it doesn't work in IE)
Thanks.
A: If you specify your myobject as the data parameter to the jQuery .ajax() method, it will automatically convert it to a query string, which I believe is what you want.
e.g.
$.ajax({
url: /* ... */,
data: myobject,
/* other settings/callbacks */
})
From the docs:
data
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs.
A: You should be able to pass your object to the 'data' parameter of the ajax function -
$.ajax({
type: "POST",
url: "some.php",
data: myobject ,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery change textbox values dynamically on Change after table row clone I have a sort of complex php,html script that I am using to create an interactive design. I am using a repeat table and i am basically cloning the contents of a particular table row and appending it to the end of the table. When I select a certain option in the select menu, the corresponding textfields get updated with the correct values. However cloned rows misbehave
What I'm asking is if there is a way to make this fields also change values. Here is the various code
Code for adding/cloning a row. Please note the id details is the id of a table row
$("#addrow1").click(function(){
//alert("It works");
//$('#description tr:last').after('<tr>...</tr>');
$('#details').clone().appendTo('#dailyexpense');
});
Code for changing the textfield and textbox values
$("#cities").live('change',function(){
var cityrates = $("#cities :selected").val();
var brkfstrates = (0.2 * cityrates).toFixed(1);
$("#brkfasttxt").val(brkfstrates);
$("#brkfastchk").val(brkfstrates);
var lunchrates = (0.3 * cityrates).toFixed(1);
$("#lunchtxt").val(lunchrates);
$("#lunchchk").val(lunchrates);
var dinnerrates = (0.3 * cityrates).toFixed(1);
$("#dinnertxt").val(dinnerrates);
$("#dinnerchk").val(dinnerrates);
var incdntlrates = (0.2 * cityrates).toFixed(1);
$("#incidentltxt").val(incdntlrates);
$("#incidentlchk").val(incdntlrates);
});
My table row code for the one that gets loaded by the browser
<tr id="details">
<td><label for="date"></label>
<input style="background-color:#CCC;" type="text" name="date" id="date" /></td>
<td><label for="cities"></label>
<select name="cities" id="cities" style="background-color:#CCC; width:220px;">
<?php
foreach($country as $makassi1){
$selectcities = "SELECT City, Country, Rate FROM perdiem_rates WHERE Country = '$makassi1'";
$checkcity = mysql_query($selectcities)or die(mysql_error());
$countcities = mysql_num_rows($checkcity);
while($row=mysql_fetch_assoc($checkcity))
{
$countries = ($row['Country']);
$names =($row['City']) ;
$rate =($row['Rate']) ;
$ratess=$countries."-".$names
?>
<option id="cityoptrates" value="<?php echo $rate; ?>">
<?php echo $ratess; ?>
</option>
<?php
}
}
?>
</select></td>
<td><input name="brkfastchk" type="checkbox" class="chkbox" id="brkfastchk" />
<label for="brkfasttxt"></label>
<input style="background-color:#CCC;" name="brkfasttxt" type="text" id="brkfasttxt" size="5" readonly="readonly" />
<label for="brkfastchk"></label></td>
<td><input type="checkbox" name="lunchchk" id="lunchchk" class="chkbox" />
<label for="lunchtxt"></label>
<input style="background-color:#CCC;" name="lunchtxt" type="text" id="lunchtxt" size="5" readonly="readonly" />
<label for="lunchchk"></label></td>
<td><input type="checkbox" name="dinnerchk" id="dinnerchk" class="chkbox" />
<label for="dinnertxt"></label>
<input style="background-color:#CCC;" name="dinnertxt" type="text" id="dinnertxt" size="5" readonly="readonly" />
<label for="dinnerchk"></label></td>
<td><input type="checkbox" name="incidentlchk" id="incidentlchk" class="chkbox" />
<label for="incidentltxt"></label>
<input style="background-color:#CCC;" name="incidentltxt" type="text" id="incidentltxt" size="5" readonly="readonly" />
<label for="incdntchk"></label></td>
<td colspan="2"><label for="daily_totals"></label>
<input style="background-color:#CCC;" name="daily_totals" type="text" id="daily_totals" size="5" /></td>
</tr>
As per the above my textfield value changing code works perfectly with the first initial row. The cloned rows don't work. The only one which works on the cloned rows is the select menu for selecting the cities. Help needed. Open to suggestions and improvements.
link to actual code in jsfiddle http://jsfiddle.net/NAafu/10/
A: In your case maybe you should also clone the events:
$('#details').clone(true).appendTo('#dailyexpense');
as stated in the documentation of clone()
EDIT - The problem perhaps is that you are using an id selector ($("#cities").live) which returns only one element. Ids should be unique on the page you should use a class instead
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Managed analogue for SendMessage API function or How to send a message to window from C#? I want to send a window message from one application (console) to the wondow of another application. I can use WinAPI functions SendMessage or PostMessage, but may be there is managed way to do it?
A: There is no managed alternative to that but you can easily P/Invoke with:
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
private void button1_Click(object sender, EventArgs e)
{
SendMessage(this.Handle, COMMAND_HERE, PARAM_HERE, 0);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Shift a whole range of keys I am working on time series data, for which the key column is a timestamp : Time.
There are also many "value" columns for each row.
I am about to shift a whole range of my data by several hours (due to a daylight saving time issue).
For that, I will update the key of several rows, and it might result in some duplicate keys. I would like the duplicate keys on the edge of the date range to be ignore. I want the shifted range to override the old one.
I plan to do something like :
UPDATE IGNORE time_series_table
SET time=time-<some_shift>
WHERE <time in a date-range>
Here is the output of describe <table> for the time key :
Field Type Null Key Default Extra
TimeMeas datetime NO PRI NULL
My question is : Will it shift all the keys at once, or will it try to shift each row one by one, resulting in massive duplicate keys wihthin the shifted range itself ?
Do you have a better way of doing this in mind ?
Thanks in advance
A:
Will it shift all the keys at once, or will it try to shift each row one by one
It will shift all the keys at once.
resulting in massive duplicate keys wihthin the shifted range itself ?
It just failed if any of primary key is duplicated.
With update ignore, it just skip silently.
This is my approach to fix this
/* create a temporary table to store matches records*/
create table tmp_table select time-<some_shift>, etc_cols....
from time_series_table
where <time in a date-range>;
then
/* delete the matches in the original table */
delete from time_series_table where <time in a date-range>;
delete from time_series_table where <time in a date-range - some_shift>;
finally
/* at this point, there won't be any duplicate data */
/* so, insert back into original table */
insert into time_series_table select * from tmp_table;
optmize table time_series_table;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Submitting a book app so that it can download and read in iBooks? Could you please let me know how an app needs to be submitted so that it can be downloaded in iBooks and user can read from the same.
Any step by step procedure or Tutorials will be appreciated!!
A: iBooks lets people read PDF files or ebooks, which must be in the EPUB format. An EPUB file is ZIP file that contains mainly HTML for the content and some XML files for the table of contents etc. It has nothing to do with native iOS apps.
To publish a book on the iBooks store so that people can buy it, you don't go through Apple's App Store submission process. Apple has its own iBooks submission process or you go to a third party service provider that has a contract with Apple to publish ebooks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: HTML5 File API - slicing or not? There are some nice examples about file uploading at HTML5 Rocks but there are something that isn't clear enough for me.
As far as i see, the example code about file slicing is getting a specific part from file then reading it. As the note says, this is helpful when we are dealing with large files.
The example about monitoring uploads also notes this is useful when we're uploading large files.
Am I safe without slicing the file? I meaning server-side problems, memory, etc. Chrome doesn't support File.slice() currently and i don't want to use a bloated jQuery plugin if possible.
A: Both Chrome and FF support File.slice() but it has been prefixed as File.webkitSlice() File.mozSlice() when its semantics changed some time ago. There's another example of using it here to read part of a .zip file. The new semantics are:
Blob.webkitSlice(
in long long start,
in long long end,
in DOMString contentType
);
Are you safe without slicing it? Sure, but remember you're reading the file into memory. The HTML5Rocks tutorial offers chunking the upload as a potential performance improvement. With some decent server logic, you could also do things like recovering from a failed upload more easily. The user wouldn't have to re-try an entire 500MB file if it failed at 99% :)
A: This is the way to slice the file to pass as blobs:
function readBlob() {
var files = document.getElementById('files').files;
var file = files[0];
var ONEMEGABYTE = 1048576;
var start = 0;
var stop = ONEMEGABYTE;
var remainder = file.size % ONEMEGABYTE;
var blkcount = Math.floor(file.size / ONEMEGABYTE);
if (remainder != 0) blkcount = blkcount + 1;
for (var i = 0; i < blkcount; i++) {
var reader = new FileReader();
if (i == (blkcount - 1) && remainder != 0) {
stop = start + remainder;
}
if (i == blkcount) {
stop = start;
}
//Slicing the file
var blob = file.webkitSlice(start, stop);
reader.readAsBinaryString(blob);
start = stop;
stop = stop + ONEMEGABYTE;
} //End of loop
} //End of readblob
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: accessing mic and earphone of android cellphone hey can anybody please tel me that can i access a mic and earphone of my android cell,as we can access camera hardware of cellphone so is there any way to access them as i want to make a walky-talky app.And im a very beginner so please help me out thanks evry1.
A: You can use AudioRecord to record the audio.
Check some Android audio chat (SIP) projects to how they have done it:
http://code.google.com/p/csipsimple/
http://code.google.com/p/sipdroid/
A: Well that would be android.media.AudioRecord for the mic and android.media.AudioTrack for the sound. But what you want to do won't be something for beginner. You should at least be able to find this in the android api.
I suggest you to start with a less complex program. On the android developer site, you will find a good start for this.
http://developer.android.com/guide/index.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: git - merge difference of branches I have three branches A, B and C.
B is regularly merged into C.
o---o---o A
/
--------o---o---o---o---o---o B
\ \ \ \
o---o---o---o---o---o C
Now I want to merge the changes I did in C, but without the merges from B, on top of A.
What is the easiest way to do this in git?
A: Use the git rebase.
First, rebase your C on top of B:
git checkout C
git checkout -b rebasedC #Let's do a new branch for it also, just in case
git rebase B
it will place all C commits on to of B.
Now we want transplant branch rebasedC from B to A:
git rebase --onto A B rebasedC
So, now you have your C-commits on top of A in the rebasedC branch. Now you can fast-forward your A to it:
git checkout A
git merge rebasedC
git branch -d rebasedC# I don't think you would need it.
That's all, I hope.
A: If i understand correctly, you want to take some commits from C into A.
If that´s the case, why don´t you "cherry-pick" them? It can lead to conflicts, but i think its your best chance :)
http://schacon.github.com/git/git-cherry-pick.html
http://schacon.github.com/git/user-manual.html#reordering-patch-series
A: You can try cherry-picking C's non-merge patches. Be prepared to handle merge conflicts. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to project a list with QUeryOver in NHibernate I am a little mystified(or stupid more likely) when it comes to QueryOver in NHibernate.
I am trying something like this:
_session.QueryOver<Task>()
.Where(x => x.Category == category)
.Fetch(x => x.SubTasks).Eager
.Select(
x => x.Id,
x => x.DisplayName,
x => x.SubTasks)
.List<object[]>();
Which I would expect would return me a list of arrays of objects with my Id, DisplayName and a collection of some kind of eagerly loaded subtasks.
Instead I get the following exception:
NHibernate.Exceptions.GenericADOException: could not execute query
[ SELECT this_.Id as y0_, this_.DisplayName as y1_, this_.Id as y2_ FROM [Task] this_ WHERE this_.Category = @p0 ]
Positional parameters: #0>Internal
[SQL: SELECT this_.Id as y0_, this_.DisplayName as y1_, this_.Id as y2_ FROM [Task] this_ WHERE this_.Category = @p0] ---> System.IndexOutOfRangeException: Index was outside the bounds of the array.
at NHibernate.Loader.Criteria.CriteriaLoader.GetResultColumnOrRow(Object[] row, IResultTransformer resultTransformer, IDataReader rs, ISessionImplementor session) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Criteria\CriteriaLoader.cs:line 111
at NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 479
at NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 243
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1694
--- End of inner exception stack trace ---
at NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1711
at NHibernate.Loader.Loader.ListIgnoreQueryCache(ISessionImplementor session, QueryParameters queryParameters) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Loader.cs:line 1601
at NHibernate.Loader.Criteria.CriteriaLoader.List(ISessionImplementor session) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Loader\Criteria\CriteriaLoader.cs:line 74
at NHibernate.Impl.SessionImpl.List(CriteriaImpl criteria, IList results) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\SessionImpl.cs:line 1928
at NHibernate.Impl.CriteriaImpl.List(IList results) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 265
at NHibernate.Impl.CriteriaImpl.List[T]() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Impl\CriteriaImpl.cs:line 277
at Codehouse.TimeRegistration.Web.Controllers.TimeRegistrationAjax.TimeRegistrationGetTasksController.Execute(String category) in E:\TfsSource\Codehouse Time Registration Beetle\Main\Source\Codehouse.TimeRegistration.Web.Controllers\TimeRegistrationAjax\TimeRegistrationGetTasksControllers.cs:line 26
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
I have spent a good hour looking on google but to no avail - so any kind of help/pointer would be much appreciated.
A: Try
_session.QueryOver<Task>()
.Where(x => x.Category == category)
.Fetch(x => x.SubTasks).Eager
.List<Task>()
.Select(
x => x.Id,
x => x.DisplayName,
x => x.SubTasks)
.ToList();
I found this to work by creating a List then doing the select after.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Windows Service in C# Express I am trying to create a service with Visual Express for C#. But cannot find the template. I want to create a simple service which reads every X hours or day an XML files containing date and time and attributes.
Then the services will send a syslog message to a remote host containing the task attribute in message.
Any suggestion?
A: Use Windows Scheduler, and call a normal C# program to handle the XML file.
A: AFAIK you cannot create windows services with Visual Studio Express.
EDIT: Here a service is created in VS 2005 Express, so it is still possible.
EDIT1: How to: Write Services Programmatically in VS 2010
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cufon doesn't work inside javascript I have the following problem.
I have some text within a javascript. I want the text to look nice, so I wrapped it with "h3" which carries a cufon canvas javascript modifier, so it will look different from the normal font.
However, text within Javascript doesn't seem to be affected by cufon.
I've tried a few things to make it work, but nothing seems to work.
This is the code:
jQuery.noConflict();
jQuery(document).ready(function($) {
var author = $('#author').val();
if( author !='' && $('#email').val() !='' ) {
$('#authorData').hide();
$('#authorData').before('<div id="welcome"> <h3>Welcome back, <strong>' + author + '</strong>! <a href="#">Edit »</a></h3></div>')
$('#welcome a').toggle(
function() {
$('#authorData').show(300);
$(this).html('Minimize »');
return false;
},
function() {
$('#authorData').hide(300);
$(this).html('Edit »');
return false;
}
);
}
});
My idea is to get the whole "weclome div" into the actual php and out of the javascript code and just leave a "redirector" in the javascript, but I'm not sure if that's possible at all.
Any ideas how to make this work?
My cufon script looks like this:
Cufon.replace('h1',{hover: true})('h2')('h3')('.stepcarousel .panel .caption .title');
P.S.: It kind of works in Internet Explorer, but not in Firefox. Very weird!
Thanks a lot for any advice and suggestions! :)
A: cufon doesn't work if element or parent is display: none ( you are using hide() ). Use visibility hidden instead.
A: You appear to be appending the content after the DOM is ready. You haven't shown in your code where you actually call the Cufon.now() method, but I'm assuming it's called before your elements are appended to the DOM.
If you check the Cufon API you will see the refresh method, which can be called to do precisely that:
Cufon.refresh();
You need to call the refresh method if new text is added to the document, or even if existing text changes (e.g. font size is increased).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Do PHP files with multiple extensions gets parsed? I have a habit of making file backups by adding the .bak extension (file.ext.bak).
Imagine if I have a config in PHP, config.php and I want to backup that file by adding the .bak extension, will the file get parsed or will you see the source code if a client accidentally end up at that url? Is it server dependent?
I've tried some tests on a MAMP server but it seems to be parsing
A:
will the file get parsed or will you see the source code if a client accidentally end up at that url?
Usually, you will see the source code because the .bak extension is not registered to be parsed with PHP. Needless to say, this is very dangerous!
Is it server dependent?
Yes. It is possible to configure the server to parse those files, but it's not part of any default configuration I know.
The better solution is to do it the other way round: filename.bak.php
A: It depends on the server configuration. It is a bad habit to keep those files accessible by browsers anyway, but should you want to, check your httpd.conf for these lines:
<IfModule mod_php5.c>
AddType application/x-httpd-php .php .phtml .php3
AddType application/x-httpd-php-source .phps
</IfModule>
This will tell the webserver that .php files actually contain code to be executed.
*
*You could add the .bak file there (but it remains a bad habit).
*Another workaround would be to just rename the file to file.bak.ext
instead).
*The best solution remains moving the files to somewhere where the
browser can't access them, out of the document root and other
mappings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: iphone URL Scheme image upload app I have developed an application to upload image captured from camera to server. I registered this app to URL Scheme so that i can access camera from web app.
I can able to launch the app from web app but do not know how to go back to the web page from where i launched the app.
Please help me
A: What you need to do is send the URL of the webapp to your app via your app URL sheme:
myapp://callback=www.someurl.com
Then when your app is done just open the URL again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does loading an object with session.get doesn't persist object modifications at the end of session? Maybe I misunderstood the semantics of get and merge in hibernate, but if I do this (in a Spring method controller, so using service and dao layers):
ClassMy a = service.get(234, ClassMy.class) (this loads the object using session.get)
a.setPropertyX("test");
this will not result in a automatic update. Instead, if I already had "a" in memory I would do:
a = (ClassMy) service.merge(a);
a.setPropertyX("test");
this results in a update.
Do I have to merge the object after loading it with get? Sounds so strange...
A: You have something wrong.
The first snippet should work, provided it's executed in the same transaction as the service.get call (i.e. the transaction should be started by the method containing this snippet, and not by the service.get method).
In the second snippet, if it runs in a transaction, then it should work: it loads the entity from the session, then copy the state of the detached a to the attached entity, then modifies the property of the attched entity. If it doesn't run in a transaction, (i.e. if it's service.merge which starts the transaction), the merge will work, but the change of the property will be done on a detached entity, and the new value of the property won't be persisted.
A: You have to make sure a transaction is there. Starting a transaction, call "Save" and then commit the transaction is mandatory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: eclipse api's to get current project's repository url i am working on developing a eclipse plugin which takes code from repository and builds the code in hudson.
for that i need to get the repository url of pom.xml
are there any eclipse api's to get repository url of current project.
for example i have got the workspace of current project using this api.
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IWorkspaceRoot root = workspace.getRoot();
IPath location = root.getLocation();
A: I think you should try to "stand on the shoulders of giants". Eclipse has now integrated m2e from Sonatype (formally m2eclipse), and I found the following in an XML file
M2E provides both a framework for building Maven-centric Eclipse
tools and set of tools and user interface elements directly
consumable by Eclipse Users.
As a framework, M2E provides facilities to import and configure
Maven projects in Eclipse workspace as well as APIs that allow
m2e extensions to access Maven project metadata and participate in
Maven project configuration and workspace build.
So you should look into m2e and check if the API allows what you want to do. I would start with plugin org.eclipse.m2e.core and study how to get access to the maven project ...
A: I think eclipse may not know the repository url in pom.xml,the eclipse maven plugin can tell you about them,but why not manually analyze the pom.xml as resource file?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript + printing values from select box I have a select box call 'ToLB' which takes in value items from another select box. I need to extract those selected values from 'ToLB' and print it on a label, this is how I do it but apparently it's not working as in no error message but nothing was printed to the label, please kindly advice, thanks! :
The Select box:
<select multiple size="8" name="ToLB" style="width: 135px" onblur="javascript:dropValue6(this)">
</select>
The label:
QMType: <asp:Label ID="destinationQualMemType" runat="server" ></asp:Label >
Javascript function:
function dropValue6(source) {
while (source.selectedIndex != -1)
{
if (source.selectedIndex != 0) arSelected.push(source.options[source.selectedIndex].value);
source.options[source.selectedIndex].selected = false;
var i;
for (i = 0; i < arSelected; i++) {
document.getElementById('<%= destinationSpendingType.ClientID %>').innerHTML =
+ "\n" + document.getElementById('<%= destinationSpendingType.ClientID %>').innerHTML = arSelected[i].value;
}
}
}
A: You might look at the lines marked //***
function dropValue6(source) {
var arSelected = []; // ***
while (source.selectedIndex != -1)
{
if (source.selectedIndex != 0) arSelected.push(source.options[source.selectedIndex].value);
source.options[source.selectedIndex].selected = false;
var i;
for (i = 0; i < arSelected.length; i++) { // ***
document.getElementById('<%= destinationSpendingType.ClientID %>').innerHTML = arSelected[i]; // ***
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Closest equivalent of 'facebook connect' for google, is it OpenId,OAuth, or google friend connect? I would want to implement a user authentication + accesing his/her data in google account.
OAuth seems to be the best choice, but openId and google friend connect also seem to confuse me.
Here are my requirements :
*
*Ask the user only ONE TIME to grant scope permissions for my app ( as done by facebook apps )
*Based on permissions , fetch the user data, and create his/her account for my website.
Here I would want to map his UNIQUE GOOGLE ID to UNIQUE MYWEBSITE ID, and store the pair.
How can I fetch UNIQUE_GOOGLE_ID ?
eg. for facebook it is profile id :
so I map 111100xxxx -> MY_WEBSITE_ACCOUNT_ID
What is the numeric unique id for google accounts apart from email ?
*
*When the user logins the second time, he should not be asked for permission,
and logged in using his UNIQUE_GOOGLE_ID store in step 2.
Can OAuth do all this, primarily step #1 , asking for permissions only once, unless revoked in google account settings.
A: oauth is the way to go since it is now a sort of industry standard and works similar to facebook's implementation of oauth, take a look:
http://code.google.com/apis/accounts/docs/OAuth2.html
especially "OAuth 2.0 for client-side web applications" will be the closest equivalent of "facebook connect":
http://code.google.com/apis/accounts/docs/OAuth2.html#CS
hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to track down errors when Azure web role starts up? I habe a web role in azure. It is running fine locally in development app fabric, but fails silently when deployed to Azure (simply no response at all for any request).
I assume it's some problem with the web.config, but that is happening so early that it occurs already before I can set up the diagnostic stuff in global asax. As said, it's working fine locally, but there is simply no response at all from the azure system.
How can I find out what specifically is wrong to be able to solve it like get the exception text, stack trace, IIS application system error log or anything that could hint me to the real problem?
A: The absolute first thing that is run in a Web role is not your application but the OnStart() method in WebRole.cs in your Azure project. This is the place to add code to monitor your Web site.
The standard technique is to copy your application trace logs and the Windows event logs to Azure table storage, together (if appropriate) with instrumentation for CPU usage, IIS statistics and what-have-you.
A good introduction to this is here: http://blog.bareweb.eu/2011/01/beginning-azure-diagnostics/
and a good followup with details on the specifics you'll need in your application is here: http://blog.bareweb.eu/2011/03/implementing-azure-diagnostics-with-sdk-v1-4/
which remains applicable for the Azure SDK 1.5.
Once you are capturing diagnostics, you can either use Visual Studio to view them directly, or you can use a tool like the Cerebrata Azure Diagnostics Manager to graph and filter them automatically. This tool is a little rough around the edges (especially for larger systems with multiple instances: the graphs aren't really useful) but is as good as it gets at the moment.
An alternative approach is to use Remote Desktop to connect to the remote instance and do some spelunking in the Windows event logs and suchlike. You can also use the Internet Explorer browser that's on the remote instance to directly connect locally to the application and see any errors etc. that may otherwise be hidden.
Personally I'd only do this if the diagnostic storage mechanism isn't working: production servers really should have remote desktop access turned off altogether to reduce the possible surface area for external attack.
A: Setting up diagnostics is the best long term solution to dealing with tracking errors in your application. If you want something a little more ad-hoc you can either catch the errors and write them to blob storage or use your own light weight trace listener.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: What use cases necessitate #define without a token-string? I have encountered the #define pre-processor directive before while learning C, and then also encountered it in some code I read. But apart from using it to definite substitutions for constants and to define macros, I've not really understook the special case where it is used without a "body" or token-string.
Take for example this line:
#define OCSTR(X)
Just like that! What could be the use of this or better, when is this use of #define necessary?
A: This is used in two cases. The first and most frequent involves
conditional compilation:
#ifndef XYZ
#define XYZ
// ...
#endif
You've surely used this yourself for include guards, but it can also be
used for things like system dependencies:
#ifdef WIN32
// Windows specific code here...
#endif
(In this case, WIN32 is more likely defined on the command line, but it
could also be defined in a "config.hpp" file.) This would normally
only involve object-like macros (without an argument list or
parentheses).
The second would be a result of conditional compilation. Something
like:
#ifdef DEBUG
#define TEST(X) text(X)
#else
#define TEST(X)
#endif
That allows writing things like:
TEST(X);
which will call the function if DEBUG is defined, and do nothing if it
isn't.
A: Such macro usually appears in pair and inside conditional #ifdef as:
#ifdef _DEBUG
#define OCSTR(X)
#else
#define OCSTR(X) SOME_TOKENS_HERE
#endif
Another example,
#ifdef __cplusplus
#define NAMESPACE_BEGIN(X) namespace X {
#define NAMESPACE_END }
#else
#define NAMESPACE_BEGIN(X)
#define NAMESPACE_END
#endif
A: One odd case that I recently dug up to answer a question turned out to be simply commentary in nature. The code in question looked like:
void CLASS functionName(){
//
//
//
}
I discovered it was just an empty #define, which the author had chosen to document that the function accessed global variables in the project:
C++ syntax: void CLASS functionName()?
So not really that different from if it said /* CLASS */, except not allowing typos like /* CLAAS */...some other small benefits perhaps (?)
A: I agree with every answer, but I'd like to point out a small trivial thing.
Being a C purist I've grown up with the assertion that EACH AND EVERY #define should be an expression, so, even if it's common practice using:
#define WHATEVER
and test it with
#ifdef WHATEVER
I think it's always better writing:
#define WHATEVER (1)
also #debug macros shall be expressions:
#define DEBUG (xxx) (whatever you want for debugging, value)
In this way, you are completely safe from misuse of #macros and prevents nasty problems (especially in a 10 million line C project)
A: This can be used when you may want to silent some function. For example in debug mode you want to print some debug statements and in production code you want to omit them:
#ifdef DEBUG
#define PRINT(X) printf("%s", X)
#else
#define PRINT(X) // <----- silently removed
#endif
Usage:
void foo ()
{
PRINT("foo() starts\n");
...
}
A: #define macros are simply replaced, literally, by their replacement text during preprocessing. If there is no replacement text, then ... they're replaced by nothing! So this source code:
#define FOO(x)
print(FOO(hello world));
will be preprocessed into just this:
print();
This can be useful to get rid of things you don't want, like, say, assert(). It's mainly useful in conditional situations, where under some conditions there's a non-empty body, though.
A: As you can see in the above responses, it can be useful when debugging your code.
#ifdef DEBUG
#define debug(msg) fputs(__FILE__ ":" (__LINE__) " - " msg, stderr)
#else
#define debug(msg)
#endif
So, when you are debugging, the function will print the line number and file name so you know if there is an error. And if you are not debugging, it will just produce no output
A: There are many uses for such a thing.
For example, one is for the macro to have different behavior in different builds. For example, if you want debug messages, you could have something like this:
#ifdef _DEBUG
#define DEBUG_LOG(X, ...) however_you_want_to_print_it
#else
#define DEBUG_LOG(X, ...) // nothing
#endif
Another use could be to customize your header file based on your system. This is from my mesa-implemented OpenGL header in linux:
#if !defined(OPENSTEP) && (defined(__WIN32__) && !defined(__CYGWIN__))
# if defined(__MINGW32__) && defined(GL_NO_STDCALL) || defined(UNDER_CE) /* The generated DLLs by MingW with STDCALL are not compatible with the ones done by Microsoft's compilers */
# define GLAPIENTRY
# else
# define GLAPIENTRY __stdcall
# endif
#elif defined(__CYGWIN__) && defined(USE_OPENGL32) /* use native windows opengl32 */
# define GLAPIENTRY __stdcall
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 303
# define GLAPIENTRY
#endif /* WIN32 && !CYGWIN */
#ifndef GLAPIENTRY
#define GLAPIENTRY
#endif
And used in header declarations like:
GLAPI void GLAPIENTRY glClearIndex( GLfloat c );
GLAPI void GLAPIENTRY glClearColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha );
GLAPI void GLAPIENTRY glClear( GLbitfield mask );
...
(I removed the part for GLAPI)
So you get the picture, a macro that is used in some cases and not used in other cases could be defined to something on those cases and nothing to those other cases.
Other cases could be as follows:
If the macro doesn't take parameters, it could be just to declare some case. A famous example is to guard header files. Another example would be something like this
#define USING_SOME_LIB
and later could be used like this:
#ifdef USING_SOME_LIB
...
#else
...
#endif
Could be that the macro was used at some stage to do something (for example log), but then on release the owner decided the log is not useful anymore and simply removed the contents of the macro so it becomes empty. This is not recommended though, use the method I mentioned in the very beginning of the answer.
Finally, it could be there just for more explanation, for example you can say
#define DONT_CALL_IF_LIB_NOT_INITIALIZED
and you write functions like:
void init(void);
void do_something(int x) DONT_CALL_IF_LIB_NOT_INITIALIZED;
Although this last case is a bit absurd, but it would make sense in such a case:
#define IN
#define OUT
void function(IN char *a, OUT char *b);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: ClassCastException error ( Object and Vector ) I am working with LWUIT List. Here is how the List is created :
db = new ClientDB();
listclient = db.listClient();
tModel = new ListSource(listclient);
renderer = new CListCell(true, new String[]{"", "", "Encours : ", "Impayés : "});
tList = new CList(tModel, renderer);
public Vector listClient()
{
try
{
filter = new Filter("");
comparator = new Comparator();
enumRec = this.enumerateRecords(filter, comparator);
while(enumRec.hasNextElement())
{
id = enumRec.nextRecordId();
recIDs.addElement(new Integer(id));
bData = this.getRecord(id);
client = new Client(bData);
if (!innerResultat.isEmpty())
{
innerResultat.removeAllElements();
}
innerResultat.addElement(new String(client.getIdclient()));
innerResultat.addElement(new String(client.getCin()));
innerResultat.addElement(new String(client.getNoms()));
innerResultat.addElement(new String(client.getEncours()));
innerResultat.addElement(new String(client.getImpayes()));
resultat.addElement(innerResultat);
}
}
catch (Exception ex) {
ex.printStackTrace();
}
return resultat;
}
public class ListSource extends DefaultListModel {
public ListSource(Vector valeur)
{
super(valeur);
}
public int getListIDs(int ligneSelected)
{
return ligneSelected;
}
}
public class CListCell extends Container implements ListCellRenderer {
private boolean isPhotoDisplayed;
private BorderLayout photoLayout = new BorderLayout();
private BoxLayout yLayout = new BoxLayout(BoxLayout.Y_AXIS);
private Vector vLabels = new Vector();
private Label pic = new Label("");
private Container cnt;
private Font fontLibelle = (MenuPrincipalForm.r).getFont("FontTextFieldBold");
private Label focus = new Label("");
public CListCell(boolean displayPhoto, String[] libelles)
{
isPhotoDisplayed = displayPhoto;
this.getSelectedStyle().setPadding(0, 0, 0, 0);
this.getUnselectedStyle().setPadding(0, 0, 0, 0);
if (displayPhoto)
{
setLayout(photoLayout);
addComponent(BorderLayout.WEST, pic);
}
else
{
setLayout(yLayout);
}
cnt = new Container(yLayout);
for (int i=0;i<libelles.length;i++)
{
vLabels.addElement(new Label(libelles[i]));
((Label)vLabels.elementAt(i)).getStyle().setBgTransparency(0);
((Label)vLabels.elementAt(i)).getStyle().setFont(fontLibelle);
cnt.addComponent(((Label)vLabels.elementAt(i)));
}
addComponent(BorderLayout.CENTER, cnt);
focus.getStyle().setBgTransparency(100);
}
public Component getListCellRendererComponent(List list, Object value, int index, boolean isSelected)
{
Vector reelData = new Vector();
if (value != null && (value instanceof Vector))
{
if (((Vector)value).isEmpty())
{
if (isPhotoDisplayed)
pic.setIcon(null);
for (int i=0; i<vLabels.size(); i++)
((Label)vLabels.elementAt(i)).setText(((Label)vLabels.elementAt(i)).getText().concat("-"));
}
else
{
reelData = (Vector)((Vector)value).elementAt(index);
for (int i=0; i<vLabels.size(); i++)
((Label)vLabels.elementAt(i)).setText(((Label)vLabels.elementAt(i)).getText().concat(String.valueOf(reelData.elementAt(i+1))));
pic.setIcon(null);
}
}
return this;
}
public Component getListFocusComponent(List list)
{
return focus;
}
}
public class CList extends List {
public CList(ListSource model, CListCell renderer)
{
setModel(model);
setListCellRenderer(renderer);
setItemGap(0);
setFixedSelection(List.FIXED_NONE_CYCLIC);
}
}
And in the getListCellRendererComponent method of the ListCellRenderer the value parameter causes me the problem. Its type is Object in the Javadoc , and the real datatype of it in my application is Vector, it is a Vector of Vector ( a Vector whose elements are Vector).
My problem is that I get the ClassCastException error in runtime , and the stack error shows that the getListCellRendererComponent method caused the error.
So how to work with Object and Vector ?
Stack error is :
java.lang.ClassCastException: 0
- view.CListCell.getListCellRendererComponent(), bci=112
- com.sun.lwuit.plaf.DefaultLookAndFeel.getListPreferredSize(), bci=218
- com.sun.lwuit.List.calcPreferredSize(), bci=7
- com.sun.lwuit.Component.preferredSize(), bci=28
- com.sun.lwuit.Component.getPreferredSize(), bci=1
- com.sun.lwuit.Component.getPreferredH(), bci=1
- com.sun.lwuit.layouts.FlowLayout.getPreferredSize(), bci=70
- com.sun.lwuit.Container.calcPreferredSize(), bci=5
- com.sun.lwuit.Component.preferredSize(), bci=28
- com.sun.lwuit.Component.getPreferredSize(), bci=1
- com.sun.lwuit.Component.getPreferredH(), bci=1
- com.sun.lwuit.layouts.BoxLayout.getPreferredSize(), bci=38
- com.sun.lwuit.Container.calcPreferredSize(), bci=5
- com.sun.lwuit.Component.preferredSize(), bci=28
- com.sun.lwuit.Component.getPreferredSize(), bci=1
- com.sun.lwuit.Component.getPreferredH(), bci=1
- com.sun.lwuit.layouts.FlowLayout.getPreferredSize(), bci=70
- com.sun.lwuit.Container.calcPreferredSize(), bci=5
- com.sun.lwuit.Component.calcScrollSize(), bci=1
- com.sun.lwuit.Component.getScrollDimension(), bci=23
- com.sun.lwuit.Container.isScrollableY(), bci=8
- com.sun.lwuit.Component.getSideGap(), bci=1
- com.sun.lwuit.layouts.FlowLayout.layoutContainer(), bci=18
- com.sun.lwuit.Container.doLayout(), bci=5
- com.sun.lwuit.Container.layoutContainer(), bci=13
- com.sun.lwuit.Container.doLayout(), bci=37
- com.sun.lwuit.Container.layoutContainer(), bci=13
- com.sun.lwuit.Form.initFocused(), bci=20
- com.sun.lwuit.Form.show(), bci=25
- com.sun.lwuit.Form.show(), bci=2
- controler.SmartPhoneBanking.displayScreen(), bci=19
- view.MenuPrincipalForm.actionPerformed(), bci=56
- com.sun.lwuit.util.EventDispatcher.fireActionSync(), bci=19
- com.sun.lwuit.util.EventDispatcher.fireActionEvent(), bci=89
- com.sun.lwuit.Button.fireActionEvent(), bci=70
- com.sun.lwuit.Button.released(), bci=17
- com.sun.lwuit.Button.pointerReleased(), bci=1
- com.sun.lwuit.Form.pointerReleased(), bci=93
- com.sun.lwuit.Component.pointerReleased(), bci=7
- com.sun.lwuit.Display.handleEvent(), bci=125
- com.sun.lwuit.Display.edtLoopImpl(), bci=115
- com.sun.lwuit.Display.mainEDTLoop(), bci=198
- com.sun.lwuit.RunnableWrapper.run(), bci=242
- java.lang.Thread.run(), bci=11
A: In general it's a good idea to check whether cast are possible or not. In your case you seem to get some object which is not a Vector.
if (value != null && value instanceof Vector) {
Vector vector = (Vector) value;
... your body with vector instead of value
} else {
throw new IllegalArgumentException("Man I didn't get a Vector!");
}
Did you consider using generic types?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hibernate relation OneToMany with non unique key I am not able to describe my problem, I try it again with example:
I have two entities (tables): Department and Person. Both tables have a field CODE which is not unique.
How can I define manyToMany bidirectional relations between these tables?
*
*Departmen has collection Persons which returns all entities with Person.CODE eq Department.CODE
*Partner has collection Departments which returns all entities with Department.CODE eq Partner.CODE
I need the relation definition - no sql or hpql query.
--------- Original question -------
I need to create hibernate relation one to many between Department and Person (one Department has many persons). Department and persons has time validity (validFrom, validTill)
class Department {
Long id;
String code;
String name;
Date validFrom;
Date validTill;
@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;
}
Without ORM (hibernate) it is easy to select persons of particular department at specified date:
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
The relation has to use non unique key (CODE) instead of department ID.
Is it possible to do something similar with hibernate?
I don't need separated objects and construct queries myself.
I want use all feature which ORM offers (lazy loading, cascase persist ...)
A: You can define a Filter. It allows you to add that check to every query you do, or disable it if you like.
Example:
<class name="Department" ...>
...
<many-to-one name="person" column="person_id" class="Person"/>
<property name="validFrom" type="date" column="validFrom"/>
<property name="validTill" type="date" column="validTill"/>
<property name="code" type="string" column="code"/>
...
<!--
Note that this assumes non-terminal records have an eff_end_dt set to
a max db date for simplicity-sake
-->
<filter name="effectiveDate"
condition="code = :code and :asOfDate BETWEEN validFrom and validTill"/>
</class>
Regards.
A: UPDATED
First off, you mention that you want to use all features which ORM offers. If this is the case then you need to use a schema that Hibernate is friendly toward. There are annotations available in both the JPA persistence API and with Hibernate-specific API that allow you to more easily work with 'legacy' databases. But if you want full and correct Hibernate use, then you have to design your schema according to what Hibernate expects.
You can do what you are asking in this case by using a join formula instead of a join column for your relationships. The join formula is a valid SQL fragment (which may reduce portability). I've left the actual SQL out in the example below.
public class Person {
...
@OneToMany
@JoinFormula("sql fragment")
private List<Department> departments;
...
}
public class Department {
...
@OneToMany
@JoinFormula("sql fragment")
private List<Person> people;
...
}
You should also consider treating code as a Hibernate object:
@Embeddable
public class Code {
...
@Column(nullable = false, length = 20)
private String code;
...
}
Rather than just a string so that the use of a code in entity relationships is more effectively managed by the Hibernate persistence context and the row mapping process.
Lastly, consider actually mapping the relationship between Person and Department as a join table in your schema. You'd then be able to take advantage of the @ManyToMany and @JoinTable annotations to do actual schema-based relationships in your entities.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to query data in data table? I used the following code to insert two row in data table:
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI).withValue(
RawContacts.ACCOUNT_TYPE, null).withValue(RawContacts.ACCOUNT_NAME,
null).build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(
Data.RAW_CONTACT_ID, rawContactInsertIndex).withValue(Data.MIMETYPE,
StructuredName.CONTENT_ITEM_TYPE).withValue(StructuredName.DISPLAY_NAME,
"a").build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI).withValueBackReference(
Data.RAW_CONTACT_ID, rawContactInsertIndex).withValue(Data.MIMETYPE,
GroupMembership.CONTENT_ITEM_TYPE).withValue(CommonDataKinds.GroupMembership.GROUP_ROW_ID,
"groupa").build());
So i got two new line in data table.But when i want to get a contact's groupId which display_name is a, i don`t know how to do.
thanks
A: I feel more than content providers SQLite3 is a better option to work with.
A: I have found the answer myself. RawContactsEntity can solve the problem properly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery remove() callback? Is there an official way to hook in to jQuery.remove() so that a function can be called before/after?
I have a system whereby certain handlers are attached to elements, and sometimes these elements are removed (eg. a UI widget whose primary element is removed by some other action on the page). If handlers could be notified that their primary element was removed, I can run cleanup routines a little easier.
A: Use a custom event, attach handlers to the custom event that fire before/after the remove. For example,
$( document ).bind( 'remove', function( event, dom ){
$( document ).trigger( 'beforeRemove', [ dom ] );
$( dom ).remove();
$( document ).trigger( 'afterRemove', [ dom ] );
});
$( document ).trigger( 'remove', 'p' ); //Remove all p's
A: Here's a nifty hack - you might wanna give it a try.
$('div').hide(1, function(){
// callback
$(this).remove();
});
A: you can use jQuery.when():
$.when($('div').remove()).then( console.log('div removed') );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: jQuery .clone() refreshes the page in safari When I call
var newElement = $(someElement).clone();
It refreshes the page immediately in Safari. I use jQuery v1.6.4. and Safari v5.1. In Chrome and Firefox the above call works perfectly.
Here is the code that refreshes the page in safari.
function resetAllAudioPieces()
{
var audioPieces = $(".audio-piece");
audioPieces.each(function(index){
var newElement = $(audioPieces[index]).clone();
$(audioPieces[index]).replaceWith(newElement);
$(audioPieces[index]).removeClass("playing");
$(audioPieces[index]).disableSelection();
});
return;
}
$("a#stop").live('click', function(e){
resetAllAudioPieces();
e.preventDefault();
});
When I click the "#stop" link, the page refreshes. Is this a bug in jQuery clone() ? Please help.
A: Can you try without the "return;" and switch the preventDefault position ?
function resetAllAudioPieces()
{
var audioPieces = $(".audio-piece");
audioPieces.each(function(index){
var newElement = $(audioPieces[index]).clone();
$(audioPieces[index]).replaceWith(newElement);
$(audioPieces[index]).removeClass("playing");
$(audioPieces[index]).disableSelection();
});
// return;
}
$("a#stop").live('click', function(e){
e.preventDefault();
resetAllAudioPieces();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I just want to have dofferentcolor iTems on my UITabbar How I can make my colored UITabBar Please help me I want to make a colored UITabBar for Each Items I need differentColor.
A: As explained in this post on Stack Overflow, subclass UITabBarController, then override the -(void)viewDidLoad method. Here's an example:
- (void)viewDidLoad {
[super viewDidLoad];
// Alternate between red and blue. Obviously this is a pretty terrible example,
// since the number of items shouldn't be a fixed integer. Replace this
// with whatever you want to do with your UITabBarItems.
int colorIndex = 0;
NSArray *colorArray = [NSArray arrayWithObjects:[UIColor redColor], [UIColor blueColor], nil];
for (int itemIndex = 0; itemIndex < 3; itemIndex++) {
// Create a frame for a subview which will overlap over the UITabBarItem.
CGRect frame = CGRectMake((self.tabBar.bounds.size.width/2.0)*itemIndex,
0.0,
self.tabBar.bounds.size.width/2.0,
self.tabBar.bounds.size.height);
// Initialize a UIView using the above frame.
UIView *v = [[UIView alloc] initWithFrame:frame];
// Cycle through the colors.
if (++colorIndex >= [colorArray count]) {
colorIndex = 0; // Keep colorIndex from going out of bounds.
}
// Set alpha to 0.5 so OP can see the view overlaps over the original UITabBarItem.
[v setAlpha:0.5];
[v setBackgroundColor:[colorArray objectAtIndex:colorIndex]];
// Add subview to UITabBarController view.
[[self tabBar] addSubview:v];
// v is retained by the parent view, so release it.
[v release];
}
}
Also, you should know that it's good practice to search the answers here on Stack Overflow before asking a new question. You could have made a lot of progress on your own using the link above. You should also post code detailing what you've tried so far--people will be more inclined to help you if you do.
I posted my code because I am still a beginner myself and I enjoyed the challenge presented by your question. If anyone has any suggestions for my code, please comment!
Anyway, hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to find current zoom level of MKMapView? I want to know the current zoom level of MKMapView in iphone programming, how can I do that?
Actually I have one app, that is taking few arguments(Radius from center to corner of MKMapView) are returning the store details in that are, when I am on MKMapView, the radius is very high and it changes when Radius is smaller, so I want to know the zoom level and setup my webservice according to that, How can I get zoom level of current MKMapView visible area?
A: I created very simple helper subclass for it:
#define MERCATOR_RADIUS 85445659.44705395
#define MAX_GOOGLE_LEVELS 20
@interface MKMapView (ZoomLevel)
- (double)getZoomLevel;
@end
@implementation MKMapView (ZoomLevel)
- (double)getZoomLevel
{
CLLocationDegrees longitudeDelta = self.region.span.longitudeDelta;
CGFloat mapWidthInPixels = self.bounds.size.width;
double zoomScale = longitudeDelta * MERCATOR_RADIUS * M_PI / (180.0 * mapWidthInPixels);
double zoomer = MAX_GOOGLE_LEVELS - log2( zoomScale );
if ( zoomer < 0 ) zoomer = 0;
// zoomer = round(zoomer);
return zoomer;
}
@end
A: You can use span inside the region property of the MKMapView. It is defined like this:
typedef struct {
CLLocationDegrees latitudeDelta;
CLLocationDegrees longitudeDelta;
} MKCoordinateSpan;
Take a look at the documentation. It is well explained there.
A: All the previous answers do not take into consideration current map rotation. MKMapView's longitudeDelta differs for non-rotated map and rotated map.
Here is a great function for straight map zoom calculation: https://stackoverflow.com/a/15020534/4923516
And here is my improvement in Swift, that takes into consideration map rotation and returns current zoom level:
class MyMapView : MKMapView {
func getZoom() -> Double {
// function returns current zoom of the map
var angleCamera = self.camera.heading
if angleCamera > 270 {
angleCamera = 360 - angleCamera
} else if angleCamera > 90 {
angleCamera = fabs(angleCamera - 180)
}
let angleRad = M_PI * angleCamera / 180 // camera heading in radians
let width = Double(self.frame.size.width)
let height = Double(self.frame.size.height)
let heightOffset : Double = 20 // the offset (status bar height) which is taken by MapKit into consideration to calculate visible area height
// calculating Longitude span corresponding to normal (non-rotated) width
let spanStraight = width * self.region.span.longitudeDelta / (width * cos(angleRad) + (height - heightOffset) * sin(angleRad))
return log2(360 * ((width / 256) / spanStraight)) + 1;
}
}
You can download sample project in my repo: https://github.com/d-babych/mapkit-wrap
A: The easiest way to get an Integer of the current zoom level, is by using the MapView function: regionDidChangeAnimated. This function recognizes every change in zoom and will give you the basis for the calculation of the zoom factor.
Just insert this function into your MapView class (works for Swift 3.0):
var mapView: MKMapView! = nil
...
func mapView(_ mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
let zoomWidth = mapView.visibleMapRect.size.width
let zoomFactor = Int(log2(zoomWidth)) - 9
print("...REGION DID CHANGE: ZOOM FACTOR \(zoomFactor)")
}
And you will get a zoomFactor value out of it, where 0 is the most near point you can zoom into the map and every higher value is a far far away zoom... :-)
A: If it helps you can also use mapView.camera.altitude to get the current altitude of the currently displayed map region.
This is what helped me when I searched how to get the map zoom level.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: divide a web page to two pages I know how to divide a web page using <div>s
, but I want each divided section to have its own back and forward and address bar. Is it possible? How can I do that?
A: You can't do it using one physical web page and have 2 sets of the browser's default controls, no.
You could create two HTML pages, each representing half the original page and then display them in two browser windows, sized identically and positioned adjacent to each other.
Otherwise use - ugh - iframes!
EDIT: If you really want a browser in a browser, then open Firefox and visit
chrome://browser/content/browser.xul
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: regenerate prestashop category tree I imported prestashop categories in 2500 from a CSV file. I respected the ties of parentage, everything works in the navigation or in the backoffice.
However, the category tree (which can be seen when we created a new product or you want to put a scene in a category) is not "update". I see all my categories ... in bulk.
How can regenerate this tree?
A: The bug was in prestashop. It has been fixed. They changed the categories tree in AdminScenes. The change is available on the SVN and in the future 1.4.5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Determining URL or String PHP I'm making a link and text service, but I have a problem, which is: there is only 1 input text form, and the user could paste something like this:
http:// asdf .com - which would register as a link, or 'asdf http:// test .com' because of the http://, it would register as a url, or
asdf - which would register as a string, because it doesn't contain http://
BUT my problem arises when the user writes something like:
asdf http://asdf.com, which in my current program outputs a "url" value. I've been experimenting for about an hour now, and I've got 3 bits of code (they were all in the same document being commented, so forgive me if they give errors!)
<?
$str = $_POST['paste'];
if(stristr($str, "http://")) {
$type = "url";
}
if(stristr($str, "https://")) {
$type = "url";
}
if($type!="url") {
$type = "string";
}
?>
Next:
<?
$type = "url";
if($type=="url"){
$t = substr($str, 8);
if(stristr($t, "https://")==$t){
$type = "url";}
if(stristr($t, "https://")==$t){
$type = "url";}
if(stristr($t, "http://")!=$t){
$type = "string";}
if(stristr($t, "https://")!=$t){
$type = "string";}
}
echo $type;
?>
Next:
<?
$url = "hasttp://cake.com";
if(stristr($url, "http://")=="") {
$type = "string"; } else {
$type = "url";
$sus = 1;}
if(stristr($url, "http://")==$url) {
$type = "url"; }
if($sus==1) {
$r = substr($url, 7);
if(stristr($r,"http://")!="http://") {
$type = "url"; }
if($r=="") {
$type = "string";
}
}
echo $type;
?>
I have no clue how I could go about classifying a string like 'asdf http://asdf.com' as a string, whilst classifying 'asdf' as a string, and classifying 'http://asdf.com' as a url.. Another idea I haven't tried yet is strpos, but that's what I'm working on now.
Any ideas?
Thanks alot! :)
Some parts of this question are getting cut off for some reason, apologies!
A: $type = '';
if (preg_match('%^https?://[^\s]+$%', $url)) {
$type = 'url';
} else {
$type = 'string';
}
This will match any value which starts with http:// or https://, and does not contain any space in it as type url. If the value does not start with http:// or https://, or it contains a space in it, it will be type string.
A: PHP parse_url is your function:
On seriously malformed URLs, parse_url() may return FALSE.
If the component parameter is omitted, an associative array is returned. At least one element will be present within the array. Potential keys within this array are:
*
*scheme - e.g. http
*host
*port
*user
*pass
*path
*query - after the question mark ?
*fragment - after the hashmark #
If the component parameter is specified, parse_url() returns a string (or an integer, in the case of PHP_URL_PORT) instead of an array. If the requested component doesn't exist within the given URL, NULL will be returned.
A: If I'm understanding the problem correctly you want to detect when the user inputs both a string and a url and parse each of them correspondingly.
Try using explode(" ", $userInput);, this will return an array containing all strings separated by a space. Than you can check that for each element in the array and set the type.
A: You should use a regular expression to check if the string starts with http
if(preg_match('/^http/',$string_to_check)){
//this is a url
}
A: $type = strpos($str, 'http') === 0 ? 'url' : 'string':
The strpos function returns the position of a match within a string or FALSE if no match. The tripple equals checks that the result does not only translates to 0 (as FALSE would have done), but that it is in fact integer as well (i.e., the string begins with http).
You could also use something like
switch (true) {
case strpos(trim($str), 'http://') === 0:
case strpos(trim($str), 'https://') === 0:
$type = 'url';
break;
default:
$type = 'string';
break; // I know this is not needed, but it is pretty :-)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Http requests from external and internal IP I have web server with Internet domain name. That server has 2 IP: Internal and External.
My web application receives HTTP requests from Internet (external IP). If that web app makes HTTP request to other web server inside our Intranet network, but which also has 2 IP (external and internal), which IP will be used by first server?
And if I receive request from Internet at external IP how can I change IP to internal for doing HTTP requests to other server inside Intranet?
A: This will depend on your environment. For example,
*
*Are you using the same host header (e.g. www.mysite.com) for accessing the second web server from internal and external network? If no then use the internal host header while accessing the web server.
*If its same host header, to which IP it get resolved? You can have DNS configuration that so that the same host address will be resolved to internal IP if accessed from the internal site.
*You can always use IP based addressing - you have make sure that on 2 web server that if host header is IP address then it should get mapped to the web site. I would not recommend this approach because it brittle and depends upon binding the ip address to particular site.
*Finally, you can always use local hosts file on the first web server to register the second web server internal IP address under configured host header. Then requests using that host header on first web server will always use internal IP.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add event for image I want to add and event on image. That is, when I click on the image, it should be replaced with another image.
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class RadioButtonLoader extends Canvas{
private static final long serialVersionUID = 1L;
BufferedImage image = null;
public RadioButtonLoader(){
try {
this.image = ImageIO.read(new File("res/rb1.gif"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public RadioButtonLoader(String checked){
try {
this.image = ImageIO.read(new File("res/rb2.gif"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Override
public void setSize(Dimension d) {
super.setSize(new Dimension(15,22));
}
@Override
public void paint(Graphics g) {
setSize(new Dimension(15,22));
g.drawImage(image, 0, 0, null);
}
}
How can I do it?
A: Simply you add mouselistner in your image in mouselister onclick method add your code...............
http://www.anyexample.com/programming/java/java_full_screen_image_viewer.xml
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to pass image id to alarm service? I use alarm service to start notifications. I want to have different image in notification based on which pendingIntent has called it. I tried passing this id via intent, but the app crashes
Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);
//pass something to intent
myIntent.putExtra("param", 999);
pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);
And in service class, I catch it via
int test = intent.getExtras().getInt("param", -1);
Toast.makeText(this, test, Toast.LENGTH_SHORT).show();//the app crashes here!
However, the app crashes in the marked line.
How should I pass image id to the service so that I can use this ID to set image in the norifications?
EDIT
Here is the logcat when error happens
09-29 12:04:45.087: ERROR/AndroidRuntime(12973): FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start service com.exercise.AndroidAlarmService.MyAlarmService@2f9768a0 with Intent { flg=0x4 cmp=com.exercise.AndroidAlarmService/.MyAlarmService (has extras) }: android.content.res.Resources$NotFoundException: String resource ID #0x3e7
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3063)
at android.app.ActivityThread.access$3600(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2096)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String resource ID #0x3e7
at android.content.res.Resources.getText(Resources.java:208)
at android.widget.Toast.makeText(Toast.java:258)
at com.exercise.AndroidAlarmService.MyAlarmService.onStart(MyAlarmService.java:53)
at android.app.Service.onStartCommand(Service.java:420)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3053)
... 10 more
A: Toast.makeText(this, test, Toast.LENGTH_SHORT).show();//the app crashes here!
Means you are sending an int as the message. This in turn means that you're telling Android to look for a String with resource id 999.
Change it to:
Toast.makeText(this, String.valueOf(test), Toast.LENGTH_SHORT).show();//the app won't crash here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594846",
"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.