text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Message Passing In C/Printing a char array from a struct in C I created this program to pass a message to a parent process. I want the parent process to print out the message it receives. I'm not sure if this is an issue with reading the char array or message passing as I am quite new to programming in c. Here is my attempt:
struct msg {
long int mtype; /* message type */
char mtext[1028]; /* message text */
} msg;
int pid, len;
int msgflg = 0;
int msqid;
char *mymsg[1028];
size_t msgsz;
long int msgtyp;
switch(pid=fork()) //fork child process
{//Child process
case 0:
mymsg[1] = "serving for sender\n";
len = strlen(mymsg[1]);
msgsnd(msqid,mymsg[1],len,msgflg);
break;
case -1:
printf("fork failed");
exit(-1);
break;
default:
msg.mtype = 0;
msqid = msgget(IPC_PRIVATE,msgflg);
wait((int *) 0);
msgrcv(msqid,&msg,msgsz,msgtyp,IPC_NOWAIT);
printf("%s",msg.mtext);
msgctl(msqid, IPC_RMID, NULL);
exit(0);
}
My question is, why is the message serving for sending not being displayed when this code is compiled and executed?
A: You haven't really asked a question, but a couple of issues I can see with the code are:
char *mymsg[1028];
...
mymsg[1] = "serving for sender\n";
Here you have mymsg which is an array of 1028 pointers to char, which is intended to be treated as a string. (By the way, why 1028? Not that it matters, but just so you know 2^10 is 1024). However, this array contains pointers that are not initialized and are pointing to random locations. Important thing is, there is no space allocated for the possible message you want to put in them.
Second issue is that arrays in C start with index 0, so you probably meant to write
mymsg[0] = "serving for sender\n";
That doesn't matter however.
More importantly, you can't copy strings in C using =, you should use strcpy and copy to a memory location that you have already allocated. Here are two ways to do it:
char mymsg[1028][1028]; // if you are sure your messages fit in 1028 chars
...
mymsg[1] = malloc(strlen("serving for sender)*sizeof(char)); // sizeof(char) not really needed
strcpy(mymsg[1], "serving for sender\n");
msgsnd(msqid,mymsg[1],len,msgflg);
free(mymsg[1]);
or
char *mymsg[1028];
...
char str_to_be_printed[] = "serving for sender\n";
mymsg[1] = malloc(strlen(str_to_be_printed)*sizeof(char)); // sizeof(char) not really needed
strcpy(mymsg[1], str_to_be_printed);
msgsnd(msqid,mymsg[1],len,msgflg);
free(mymsg[1]);
Edit: In the second case where you already have the string somewhere (and not in the form of "this is a string"), assigning the pointers is enough and you don't to copy or allocate memory. However, if your situation is more complex than this, and between assignment of mymsg[1] = ... and msgsnd there are other code, you have to make sure the original string stays alive until msgsnd is done. Otherwise, you have a dangling pointer which will cause you problems. Here's the idea:
+-+-+-+-+-+-+-+-+--+
str_to_be_printed ----->|A| |s|t|r|i|n|g|\0|
+-+-+-+-+-+-+-+-+--+
^
mymsg[1]---------------/
If you free the memory of str_to_be_printed, access to mymsg[1] would cause segmentation fault/access violation.
Note that, the code I wrote is just to give you a guideline, don't copy-paste it.
A: There are few observation related to your code.
*
*When you use system calls (any function which returns any error code) check the return value of the function. In the case of system calls you have used will set errno i.e. error number which can be used to check for error. You can use perror or strerror to see the message (Pointed out by Jonathan Leffler already)
*You need to create message queue before using it (Again pointed out by Jonathan Leffler already).
*You are sending char * in msgsnd & receiving struct msg type in msgrcv.
*You have set the size to be passed in the message queue send & receive calls, for which you are using msgsz but uninitialized. Set value of msgsz to the size you want to send/receive. While sending you seem to sending 17 bytes but while receiving it is not set.
*mtype should have a value greater than 0.
*Type for pid should be pid_t, which seems do you little good in this case anyway.
Some code sections for your reference:
#include <stdio.h> /*For perror*/
...
/* Create message queue */
msqid = msgget(IPC_PRIVATE, IPC_CREAT);
if( 0 > msqid )
{
perror("msgget");
/* Handle error as per your requirement */
}
...
/* Sending & receiving messages */
...
struct msg {
long int mtype; /* message type */
char mtext[1028]; /* message text */
} sender_msg, receiver_msg;
...
size_t msgsz = 10; /* Send & receive 10 bytes, this can vary as per need. You can receive less than what was sent */
...
switch(fork())
{
case 0: /* Child */
sender_msg.mtype = 1;
strncpy(sender_msg.mtext,"01234567890123", 1027);
/* Sending the whole text size */
if ( 0 > msgsnd(msqid, &sender_msg, strlen(sender_msg.mtext),msgflg))
{
perror("msgsnd");
/* Handle error as per your requirement */
}
break;
case -1:
perror("fork");
exit(-1);
break;
default:
wait((int *) 0);
receiver_msg.mtype = 1;
/* Receive only 10 bytes as set in msgsz */
if( 0 > msgrcv(msqid,&receiver_msg,msgsz,msgtyp,IPC_NOWAIT))
{
perror("msgrcv");
/* Error handling */
}
printf("%s",receiver_msg.mtext);
if (0 > msgctl(msqid, IPC_RMID, NULL))
{
perror("msgctl");
/* Handle error as per your requirement */
}
break;
}
You seem to be using System V message queues APIs here, you can look into the POSIX message queue APIs like mq_open, mq_close, mq_send, mq_receive etc.
For message queue overview see the man pages (man mq_overview)
Use man pages for information about APIs as well.
Hope this helps!
A: You have several problems:
*
*You need to create the message queue before you call fork(), so that both the parent and child have access to it;
*The permissions of the message queue are set from the low-order bits of the second parameter of msgget(), so you need to specify at least read and write permissions for the owner of the message queue. You can use the constant S_IRWXU from <sys/stat.h> here;
*You are passing msgsnd() a pointer to a string, but it actually wants a pointer to a message struct like your struct msg.
*You should check for msgrcv() failing.
With these issues fixed, the corrected code looks like:
int pid;
int msqid;
msqid = msgget(IPC_PRIVATE, S_IRWXU);
if (msgid < 0) {
perror("msgget");
exit(1);
}
switch(pid=fork()) //fork child process
{//Child process
case 0:
msg.mtype = 1; /* Must be a positive value */
strcpy(msg.mtext, "serving for sender\n");
msgsnd(msqid, &msg, strlen(msg.mtext) + 1, 0);
break;
case -1:
printf("fork failed");
exit(2);
break;
default:
wait(NULL);
if (msgrcv(msqid, &msg, sizeof msg.mtext, 0, IPC_NOWAIT) >= 0)
printf("%s",msg.mtext);
else
perror("msgrcv");
msgctl(msqid, IPC_RMID, NULL);
exit(0);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: php function to list months for dropdown I have this function
function bookingMonthField() {
$str="";
for($i = 0; $i < 16; $i++) {
$time = mktime(0, 0, 0, date('n') + $i);
$str .="<option value=" . date('Yn', $time) . ">" . date('M Y', $time) . "</option>";
}
return $str;
}
Which works (almost) as it should, except it is returning no Feb and 2x March:
<option value="20119">Sep 2011</option>
<option value="201110">Oct 2011</option>
<option value="201111">Nov 2011</option>
<option value="201112">Dec 2011</option>
<option value="20121">Jan 2012</option>
<option value="20123">Mar 2012</option>
<option value="20123">Mar 2012</option>
<option value="20124">Apr 2012</option>
<option value="20125">May 2012</option>
<option value="20126">Jun 2012</option>
<option value="20127">Jul 2012</option>
<option value="20128">Aug 2012</option>
<option value="20129">Sep 2012</option>
<option value="201210">Oct 2012</option>
<option value="201211">Nov 2012</option>
<option value="201212">Dec 2012</option>
ANy ideas why this is happening?
A: Just tell your script, you want the first of the month:
$time = mktime(0, 0, 0, date('n') + $i, 1);
Or wait another day, then your website is automatically fixed :)
A: mktime will use the current day if none is provided. Today is the 29th, so February is skipped. Instead, specify "1" for the day.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Adding a best fit normal on top of a histogram in R
Possible Duplicate:
Fitting a density curve to a histogram in R
I'm trying to add a best fit normal over a histogram in R. Right now, I have the following:
x<-table[table$position==1,]$rt
hist(x,breaks=length(x))
And now I'd like to plot a normal curve over this plot which allows for skew and for kurtosis. How can I do this? This is what my curve looks like:
A: I would suggest not using the terms "skew" and "kurtosis" in the same sentence with "Normal curve", since Normal curves have neither. Perhaps you are looking for one or two parameter continuous density distribution that might be comparable to a function that was bounded at zero and had right skewing? If so then you should think about a) posting the data, b) consider plotting a Poisson, a log-Normal, or a gamma density on top of a histogram.
set.seed(123)
xpois <- trunc(rpois(100, 4))
hist(xpois)
lines(seq(0,10), 100*dpois(seq(0,10), 4))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bing Maps Multiple Pushin Infoboxes I have a map where I have multiple pushpins, and would like the infobox to support HTML content. I'm using the native infobox class, and while I have used a custom infobox, as many have suggested, I'd like to figure this one out.
The code is at: http://brickenandassociates.com/bm.php
Its not compressed or encoded, so you can just view the source.
at line 84, the options for the Infobox are set. In the description, I've tried setting a var , but am missing the syntax somewhere. Something like this :
var ibDescription = document.getElementById('ibDescription');
ibDescription.innerHTML = e.target.description;
Any guidance would be most appreciated !
A: Looks like you've figured this out already:
pinInfobox.setOptions({title: e.target.Title, description: e.target.Description, visible:true, offset: new Microsoft.Maps.Point(0,25)});
pinInfobox.setLocation(e.target.getLocation());
One thing I noted was that you are only using one InfoBox. I use one info box per pushpin, so I set the infobox detail at the time it is created and then only have to hide or show it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Create unique form fields based on database query in Symfony 1.4/Doctrine 1.2 I have this wild project happening at work, and we happen to use Symfony 1.4 so I was hoping, ideally, to keep this project within the framework's capabilities as much as possible. Unfortunately, despite quite a bit of research and searching, I haven't yet found a way to generate sfWidgetForm elements based on queries to the database.
I'll outline what the purpose of this is by explaining the flow of the project.
*
*The user submits a form which contains most of the data our advertisers need.
*Based on this data, rows from a database can be called. Perhaps this form was filled, and in it, the user claims to be interested in gardening. Based on that relevance this will yield a row (or several rows, but whatever) of form fields related to gardening.
*Here in lies the important part. This gardening related content is essentially an outline of form fields required to a complete a submission for someone who is interested in gardening. We will get form element types, names, labels, requirement status, enablement status, etc. Based on the ids of these elements, we can see if any of them are dependent on each other from another table. If that's the case, they are treated with javascript. That's another story.
*At this point, I can either create forms using custom built components in Symfony (Which would be alright). These would output forms which worked fine, but they wouldn't be supported by sfValidator widgets, which is unfortunate. What I'd like to do is somehow tell some magical form class to build a form based on X criterion, widgets and validators all.
*Once the form is complete and outputted, the user fills in the remaining fields, the second form gets validated and the whole whack of data from both forms is sent to the advertiser.
What I'm most interested in here is data on dynamically building forms within Symfony. I can build using a component easily, but I don't really want to. Especially since I plan to quit soon, and keeping something within the framework would be ideal for my team mates.
Thanks for any ideas! This is a pretty exciting project, despite being boring from the outside - I've never dynamically generated forms before, let alone within Symfony. Should be cool.
A: You can certainly build selection lists / radio buttons / check boxes based on query - im not sure if this is exactly what you want to do ?
See http://www.symfony-project.org/api/1_4/sfWidgetFormDoctrineChoice and the query parameter - I use this a lot and it works fine.
To build a whole form dynamically is going to be difficult IMO - I think you need to define at least some rules so that you can display / hide certain form elements.
A: A functioning example of how I solved this problem can be found here: http://pastebin.com/NrJeADAk
It works well. If your database describe your forms properly and consistently, you can even create new forms by submitting their descriptions via a form. I've done this for my team at work, and with very heavy validation on the fields, so far they haven't managed to create a single form that causes issues. I'm a frequent SO user, so if you stumble across this and would like to know more, feel free to message me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to put a single column item into a single row? I have a file like this:
a
b
c
d
e
f
g
h
and so on, with a single word/number on each line. and after 4/5 lines a couple of ( or three ) space. what I want to do is put them like this
a,b,c,d
e,f,g,h
I was working with sed, but sed is oneliner and seems to helpless for the addition of multiple lines. Can anybody help me with a shell script? I know this must be done easily via Perl, Python or at most C.
A: This can be done a wide variety of ways without anything even as complicated as sed, much less Perl or Python. My weapon of choice would be tr:
cat inFile.txt | tr "\n" "," | tr ",,,," " " > outFile.txt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does \b work when using regular expressions? If I have a sentence and I wish to display a word or all words after a particular word has been matched ahead of it, for example I would like to display the word fox after brown The quick brown fox jumps over the lazy dog, I know I can look positive look behinds e.g. (?<=brown\s)(\w+) however I don't quite understand the use of \b in the instance (?<=\bbrown\s)(\w+). I am using http://gskinner.com/RegExr/ as my tester.
A: The \b token is kind of special. It doesn't actually match a character. What it does is it matches any position that lies at the boundary of a word (where "word" in this case is anything that matches \w). So the pattern (?<=brown\s)(\w+) would match "bbbbrown fox", but (?<=\bbrown\s)(\w+) wouldn't, since the position between "bb" and "brown" is in the middle of a word, not at its boundary.
A: \b is a zero width assertion. That means it does not match a character, it matches a position with one thing on the left side and another thing on the right side.
The word boundary \b matches on a change from a \w (a word character) to a \W a non word character, or from \W to \w
Which characters are included in \w depends on your language. At least there are all ASCII letters, all ASCII numbers and the underscore. If your regex engine supports unicode, it could be that there are all letters and numbers in \w that have the unicode property letter or number.
\W are all characters, that are NOT in \w.
\bbrown\s
will match here
The quick brown fox
^^
but not here
The quick bbbbrown fox
because between b and brown is no word boundary, i.e. no change from a non word character to a word character, both characters are included in \w.
If your regex comes to a \b it goes on to the next char, thats the b from brown. Now the \b know's whats on the right side, a word char ==> the b. But now it needs to look back, to let the \b become TRUE, there needs to be a non word character before the b. If there is a space (thats not in \w) then the \b before the b is true. BUT if there is another b then its false and then \bbrown does not match "bbrown"
The regex brown would match both strings "quick brown" and "bbrown", where the regex \bbrown matches only "quick brown" AND NOT "bbrown"
For more details see here on www.regular-expressions.info
A: \b is a "word boundary" and is the position between the start or end of a word and then "non-word" characters.
Its main use is to simplify the selection of a whole word to \bbrown\s will match:
^brown
brown
99brown
_brown
Its more or less equivalent to "\W*" except when "capturing" strings as "\b" matches the start of the word rather than the non-word character preceding or following the word.
A: \b is a zero width match of a word boundary.
(Either start of end of a word, where "word" is defined as \w+)
Note: "zero width" means if the \b is within a regex that matches, it does not add any characters to the text captured by that match. ie the regex \bfoo\b when matched will capture just "foo" - although the \b contributed to the way that foo was matched (ie as a whole word), it didn't contribute any characters.
A: A word boundary is a position that is either preceded by a word character and not followed by one, or followed by a word character and not preceded by one. It's equivalent to this:
(?<=\w)(?!\w)|(?=\w)(?<!\w)
...or it's supposed to be. See this question for everything you ever wanted to know about word boundaries. ;)
A: \b guarantees that brown is on a word boundary effectively excluding patterns like
blackandbrown
A: You don't need a look behind, you can simply use:
(\bbrown\s)(\w+)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: Python: counting unique instance of words across several lines I have a text file with several observations. Each observation is in one line. I would like to detect unique occurrence of each word in a line. In other words, if same word occurs twice or more on the same line, it is still counted as once. However, I would like to count the frequency of occurrence of each words across all observations. This means that if a word occurs in two or more lines,I would like to count the number of lines it occurred in. Here is the program I wrote and it is really slow in processing large number of file. I also remove certain words in the file by referencing another file. Please offer suggestions on how to improve speed. Thank you.
import re, string
from itertools import chain, tee, izip
from collections import defaultdict
def count_words(in_file="",del_file="",out_file=""):
d_list = re.split('\n', file(del_file).read().lower())
d_list = [x.strip(' ') for x in d_list]
dict2={}
f1 = open(in_file,'r')
lines = map(string.strip,map(str.lower,f1.readlines()))
for line in lines:
dict1={}
new_list = []
for char in line:
new_list.append(re.sub(r'[0-9#$?*_><@\(\)&;:,.!-+%=\[\]\-\/\^]', "_", char))
s=''.join(new_list)
for word in d_list:
s = s.replace(word,"")
for word in s.split():
try:
dict1[word]=1
except:
dict1[word]=1
for word in dict1.keys():
try:
dict2[word] += 1
except:
dict2[word] = 1
freq_list = dict2.items()
freq_list.sort()
f1.close()
word_count_handle = open(out_file,'w+')
for word, freq in freq_list:
print>>word_count_handle,word, freq
word_count_handle.close()
return dict2
dict = count_words("in_file.txt","delete_words.txt","out_file.txt")
A: You're running re.sub on each character of the line, one at a time. That's slow. Do it on the whole line:
s = re.sub(r'[0-9#$?*_><@\(\)&;:,.!-+%=\[\]\-\/\^]', "_", line)
Also, have a look at sets and the Counter class in the collections module. It may be faster if you just count and then discard those you don't want afterwards.
A: Without having done any performance testing, the following come to mind:
1) you're using regexes -- why? Are you just trying to get rid of certain characters?
2) you're using exceptions for flow control -- although it can be pythonic (better to ask forgiveness than permission), throwing exceptions can often be slow. As seen here:
for word in dict1.keys():
try:
dict2[word] += 1
except:
dict2[word] = 1
3) turn d_list into a set, and use python's in to test for membership, and simultaneously ...
4) avoid heavy use of replace method on strings -- I believe you're using this to filter out the words that appear in d_list. This could be accomplished instead by avoiding replace, and just filtering the words in the line, either with a list comprehension:
[word for word words if not word in del_words]
or with a filter (not very pythonic):
filter(lambda word: not word in del_words, words)
A: import re
u_words = set()
u_words_in_lns = []
wordcount = {}
words = []
# get unique words per line
for line in buff.split('\n'):
u_words_in_lns.append(set(line.split(' ')))
# create a set of all unique words
map( u_words.update, u_words_in_lns )
# flatten the sets into a single list of words again
map( words.extend, u_words_in_lns)
# count everything up
for word in u_words:
wordcount[word] = len(re.findall(word,str(words)))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenCV polar transform selective region I want to restrict the operating region of the polar transform in OpenCV's cvLogPolar function. I would consider rewriting the function from scratch. I am unwrapping a fisheye lens image to yield a panorama, and I want to make it as efficient as possible. Much of the image is cropped away after the transform, giving a donut-shaped region of interest in the input image:
This means much processing is wasted on black pixels.
This should be pretty simple, right? The function should take two additional arguments for clipping extents, radius1 and radius2. Here is the relevant pol-to-cart portion of the cvLogPolar function from imgwarp.cpp:
cvLogPolar( const CvArr* srcarr, CvArr* dstarr,
CvPoint2D32f center, double M, int flags )
{
cv::Ptr<CvMat> mapx, mapy;
CvMat srcstub, *src = cvGetMat(srcarr, &srcstub);
CvMat dststub, *dst = cvGetMat(dstarr, &dststub);
CvSize ssize, dsize;
if( !CV_ARE_TYPES_EQ( src, dst ))
CV_Error( CV_StsUnmatchedFormats, "" );
if( M <= 0 )
CV_Error( CV_StsOutOfRange, "M should be >0" );
ssize = cvGetMatSize(src);
dsize = cvGetMatSize(dst);
mapx = cvCreateMat( dsize.height, dsize.width, CV_32F );
mapy = cvCreateMat( dsize.height, dsize.width, CV_32F );
if( !(flags & CV_WARP_INVERSE_MAP) )
//---snip---
else
{
int x, y;
CvMat bufx, bufy, bufp, bufa;
double ascale = ssize.height/(2*CV_PI);
cv::AutoBuffer<float> _buf(4*dsize.width);
float* buf = _buf;
bufx = cvMat( 1, dsize.width, CV_32F, buf );
bufy = cvMat( 1, dsize.width, CV_32F, buf + dsize.width );
bufp = cvMat( 1, dsize.width, CV_32F, buf + dsize.width*2 );
bufa = cvMat( 1, dsize.width, CV_32F, buf + dsize.width*3 );
for( x = 0; x < dsize.width; x++ )
bufx.data.fl[x] = (float)x - center.x;
for( y = 0; y < dsize.height; y++ )
{
float* mx = (float*)(mapx->data.ptr + y*mapx->step);
float* my = (float*)(mapy->data.ptr + y*mapy->step);
for( x = 0; x < dsize.width; x++ )
bufy.data.fl[x] = (float)y - center.y;
#if 1
cvCartToPolar( &bufx, &bufy, &bufp, &bufa );
for( x = 0; x < dsize.width; x++ )
bufp.data.fl[x] += 1.f;
cvLog( &bufp, &bufp );
for( x = 0; x < dsize.width; x++ )
{
double rho = bufp.data.fl[x]*M;
double phi = bufa.data.fl[x]*ascale;
mx[x] = (float)rho;
my[x] = (float)phi;
}
#else
//---snip---
#endif
}
}
cvRemap( src, dst, mapx, mapy, flags, cvScalarAll(0) );
}
Since the routine works by iterating through pixels in the destination image, the r1 and r2 clipping region would just need to be translated to y1 and y2 row region. Then we just change the for loop: for( y = 0; y < dsize.height; y++ ) becomes for( y = y1; y < y2; y++ ).
Correct?
What about constraining cvRemap? I am hoping it ignores unmoved pixels or it is a negligible computational cost.
A: I ended up doing a different optimization: I store the result of the polar transform operation in persistent remapping matrices. This helps a LOT. If you're doing polar unwrap on full motion video using the same polar transform mapping at all times, you don't want to recalculate the transform with a million sin/cos operations every single frame. So this just required some small modification on the logPolar/linearPolar operations in the OpenCV source to save the remap result somewhere outside.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jquery failed updating image attribute on firefox I have the following code
var first = $jq("<div></div>");
first.append("<td><img id='smile' src='/Images/smile.png' style='width: 120px; height: 120px; display: none; padding-top: 5px; padding-right: 5px;' alt='image' /></td>");
// some logic ...
var img = $jq('#smile');
img[0].style.display = 'inline';
The code works perfectly fine on IE (9), but not on FF (tried on 7.0). Any reasons? And if possible, work around?
A: Try:
img.css("display", "inline");
http://api.jquery.com/css/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails partial template using a custom handler is escaping html I'm working on a Rails 3.1 app using JavascriptMVC and ejs templates within the client to do some complicated features on my application. Unfortunately ejs syntax is very similar to erb syntax, to the point where I can't keep the code in the same file (although if someone knows of a good way to do this, I'd be ecstatic). Ultimately I want to be able to apply some rails code within the ejs template (say for I18n) but at this point I will just settle for getting this to work
Following the example from this question I have created a custom template handler that looks like this:
module CommonModel
class Handler < ActionView::Template::Handler
include ActionView::Template::Handlers::Compilable
def compile(template)
template.source.inspect
end
end
end
ActionView::Template.register_template_handler :ejs, CommonModel::Handler
Then I created a partial template that has my ejs code in it:
_jmvc_templates.html.ejs
<script type="text/ejs" id="my_ejs_template">
<div>Some ejs here</div>
</script>
Within my existing template, I attempt to include my partial:
<%= render 'path/to/my/ejs/templates/jmvc_templates' %>
At this point, the file is included and my handler is used, but everything is escaped, so my div in my template gets rendered to the page like this:
<div%gt;
I'm sure I'm missing something obvious here, but I don't know what it could be... How can I get this template handler to just include my ejs based template without escaping all of the html in it?
Edit:
I've found that calling render with html_safe works:
<%= render('path/to/my/ejs/templates/jmvc_templates').html_safe %>
This seems like a kludge though - there has to be a way to get the erb renderer to treat text from my handler as html safe text.
A: Maybee you should be using raw. Check this
def compile(template)
raw template.source.inspect
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Having an issue with setting up MySQLdb on Mac OS X Lion in order to support Django So I am pretty sure that I have managed to dork up my MySQLdb installation. I have all of the following installed correctly on a fresh install of OS X Lion:
*
*phpMyAdmin
*MySQL 5.5.16
*Django 1.3.1
And yet when I try to run "from django.db import connection" in a django console, I get the following:
from django.db import connection Traceback (most recent call
last): File "", line 1, in File
"/Library/Python/2.7/site-packages/Django-1.3.1-py2.7.egg/django/db/init.py",
line 78, in
connection = connections[DEFAULT_DB_ALIAS] File
"/Library/Python/2.7/site-packages/Django-1.3.1-py2.7.egg/django/db/utils.py",
line 93, in getitem
backend = load_backend(db['ENGINE']) File
"/Library/Python/2.7/site-packages/Django-1.3.1-py2.7.egg/django/db/utils.py",
line 33, in load_backend
return import_module('.base', backend_name) File
"/Library/Python/2.7/site-packages/Django-1.3.1-py2.7.egg/django/utils/importlib.py",
line 35, in import_module
import(name) File
"/Library/Python/2.7/site-packages/Django-1.3.1-py2.7.egg/django/db/backends/mysql/base.py",
line 14, in
raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/[my
username]/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg-tmp/_mysql.so,
2): Library not loaded: libmysqlclient.18.dylib Referenced from:
/Users/[my
username]/.python-eggs/MySQL_python-1.2.3-py2.7-macosx-10.7-intel.egg-tmp/_mysql.so
Reason: image not found
I have no idea why this is happening, could somebody help walk me through this?
A: I found the following solution for this issue. It worked for me. I have encountered this problem when I was running python console from PyCharm.
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
A: Easy,
edit your .bash_profile (vi ~/.bash_profile) somewhere in that add the following line:
export DYLD_LIBRARY_PATH="/usr/local/mysql/lib"
This line assumes your mysql install directory is in /usr/local/mysql/.
This will solve executing via python interrupter launched in shell (the .bash_profile exports the path needed by the MySQLdb module to load the ' libmysqlclient.18.dylib').
If you are having this issue with a Python IDE like PyCharm add the DYLD_LIBRARY_PATH variable to the launching module configuration.
I hope this helps :)
Also,
To fully understand this problem, read the following section:
http://mysql-python.sourceforge.net/FAQ.html#importerror
This explains this error in detail
A: Install pip if you haven't already, and run
pip install MySQL-Python
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why is my jQuery .click() callback not handling input properly? I'm creating this cool HTML Jeopardy game and I need a little coding help.
Right now im working just on the first question. Which pops up in an FancyBox.
I'm using an if to Identify the correct answer but it is not working.
I have the code:
$(document).ready(function() {
var tag_100_input = $('#tag_100_ans').val();
$('#tag_100_button').click(function() {
if (tag_100_input == 'strong' || tag_100_input == 'b' || tag_100_input == '<strong>' || tag_100_input == '<b>') {
$('.tag_100_correct').fadeIn(500);
setTimeout("$.fancybox.close()", 3000);
score += 100;
$('#tag_100_not').css('display', 'none');
$('#tag_100').css('display', 'none');
}
else {
$('.tag_100_wrong').fadeIn(500);
setTimeout("$.fancybox.close()", 3500);
$('#tag_100_not').css('display', 'none');
$('#tag_100').css('display', 'none');
}
$('.score').html(score);
});
});
The jeopardy question is:
What tag can make text Bold?
Even when I enter one of the awnsers: b, strong, <b>, or <strong>
It shows me the wrong <span> instead of the correct one. Why is that?
A: $(document).ready(function() {
var tag_100_input = $('#tag_100_ans').val();
$('#tag_100_button').click(function() {
You're retrieving the input with .val() as soon as the document loads. You don't look at the input again later, so your code will only act on the default input values, not what you've actually entered.
You just need get the input value inside of your .click() callback instead, by swapping the second and third lines:
$(document).ready(function() {
$('#tag_100_button').click(function() {
var tag_100_input = $('#tag_100_ans').val();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Disadvantages to release Flash application which was compiled in debug mode I want to release my flash application not in release mode but in debug mode
to see result of trace() after releasing the app.
I don't care that debug mode makes processing speed little slow.
Except for processing speed, are there disadvantages to release flash application which was compiled in debug mode?
Is it possible that the app throws exception or Flash Players of the app's users crash due to debug mode?
A: Here a few disadvantages. I made some simple tests that don't really prove anything as they don't tell if it's caused by the different players and whether the additional memory/file size values increase linear or stay at that level. They just show there are differences.
*
*Increased file size
*
*Tested (mxmlc 4.5.1) empty document class in a single line:
*
*-debug=false: 550 Bytes
*-debug=true: 667 Bytes
*Adds an additional line number instruction for each line of code (maybe even for each declaration/statement/expression)
*Contains your project structure: full paths to .as files.
*
*possible privacy concern (could show local username)
*shows internal project name, maybe internal version if used in path
*probably indicates used OS and/or IDE
*Increased memory consumption
*
*Very simple test watching the task manager: for loop creating local objects
*
*debug: ~ 6300k - 7400k
*release: ~ 5800k - 6900k
*Slower (as already mentioned in the question)
I'm not sure if security is an issue here, since trace statements don't reveal anything that couldn't be extracted from memory or reconstructed by decompilation. Maybe the presence of a trace would indicate that it could be a critical part of the application, but in general even non-debug bytecode still contains those trace instructions. Line numbers could be used by a decompiler to create prettier code though.
A: @kapep 's answer is right about the things debug mode does to your swf.
but it's not neccessary to use debug mode for traces - compile in release mode and use a different debugging tool like
*
*monster debugger
*alcon logger
*...
and maybe use a logging framework to also use normal trace statements as well as the ones that are catched by the external logger.
i can recommend this one here: parsley+spicelib
here's a short manual: http://www.spicefactory.org/parsley/docs/2.0/manual/logging.php#intro
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Java's MessageDigest SHA1-algorithm returns different result than SHA1-function of php I have a SQL table with usernames and passwords. The passwords are encoded using MessageDigest's digest() method. If I encode a password - let's say "abcdef12" - with MessageDigest's digest() method and then convert it to hexadecimal values, the String is different than if I do the same using PHP's SHA1-method. I'd expect these values to be exactly the same though.
Code that is used to encode the passwords:
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] passbyte;
passbyte = "abcdef12".getBytes("UTF-8");
passbyte = md.digest(passbyte);
The conversion of the String to hexadecimal is done using this method:
public static String convertStringToHex(String str) {
char[] chars = str.toCharArray();
StringBuffer hex = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
hex.append(Integer.toHexString((int) chars[i]));
}
return hex.toString();
}
Password: abcdef12
Here's the password as returned by a lot of SHA1-hash online generators and PHP SHA1()-function: d253e3bd69ce1e7ce6074345fd5faa1a3c2e89ef
Here's the password as encoded by MessageDigest: d253e3bd69ce1e7ce674345fd5faa1a3c2e2030ef
Am I forgetting something?
Igor.
Edit: I've found someone with a similar problem: C# SHA-1 vs. PHP SHA-1...Different Results? . The solution was to change encodings.. but I can't change encodings on the server-side since the passwords in that SQL-table are not created by my application.
I use client-side SHA1-encoding using a JavaScript SHA1-class (more precisely: a Google Web Toolkit-class). It works and encodes the string as expected, but apparently using ASCII characters?..
A: I have the same digest as PHP with my Java SHA-1 hashing function:
public static String computeSha1OfString(final String message)
throws UnsupportedOperationException, NullPointerException {
try {
return computeSha1OfByteArray(message.getBytes(("UTF-8")));
} catch (UnsupportedEncodingException ex) {
throw new UnsupportedOperationException(ex);
}
}
private static String computeSha1OfByteArray(final byte[] message)
throws UnsupportedOperationException {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(message);
byte[] res = md.digest();
return toHexString(res);
} catch (NoSuchAlgorithmException ex) {
throw new UnsupportedOperationException(ex);
}
}
I've added to my unit tests:
String sha1Hash = StringHelper.computeSha1OfString("abcdef12");
assertEquals("d253e3bd69ce1e7ce6074345fd5faa1a3c2e89ef", sha1Hash);
Full source code for the class is on github.
A: Try this - it is working for me:
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(original.getBytes());
byte[] digest = md.digest();
StringBuffer sb = new StringBuffer();
for (byte b : digest) {
sb.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
Regards,
Konki
A: It has nothing to do with the encodings. The output would be entirely different.
For starters, your function convertStringToHex() doesn't output leading zeros, that is, 07 becomes just 7.
The rest (changing 89 to 2030) is also likely to have something to do with that function. Try looking at the value of passbyte after passbyte = md.digest(passbyte);.
A: Or try this:
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(clearPassword.getBytes("UTF-8"));
return new BigInteger(1 ,md.digest()).toString(16));
Cheers Roy
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: input/output lzw issue Sup dudes,
I need your help on something. I'm writing a lzw compressor in C, and I'm having a spot o trouble with encode and decode. Here is what I have so far:
fixed it, thanks.
$> ./encode < input.txt
code 1
code 2
code 3
code 4
code 1
$> ./decode < output.txt (this contains the codes, but as a stream of bits)
read 1
read 2
read 3
read 4
It appears to always skip the last code. When I GDB, I see that after C gets 258, it then gets EOF (-1), and I have no idea why the last code is skipped. Any tips?
A: I don't seem to completely understand your question, but here is my 2 cents.
try flushing out the stdout at the end
fflush(stdout);
This might help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When to use "$" in javascript/jQuery Ive been starting to do javascript and jQuery recently and one thing I constantly find myself wondering is when to use "$" I know that indicates jQuery but it just doesn't always seem to be that way. I'll give some examples:
These are two scripts I've written:
First:
$(function() {
var newHTML = '<span style="font-size: 1.7em; text-align:center; line-height:50px;">Login</span>';
var oldHTML = '<span style="font-size: 32px; line-height: 18px;">+</span><span style="font-size: 14px; float: left;">Add to watchlist</span>';
// on mouse over
$("a.bid-addwatchlist").hover(
function () {
(this).innerHTML = newHTML;
},
// on mouse out
function () {
(this).innerHTML = oldHTML;
});
});
Second:
(function(){
$("#container a").click(function(){
if ($(this).html() == "Stop Listening")
{
$(this).html("Listen");
}
else if ($(this).html() == "Listen")
{
$(this).html("Stop Listening");
}
});
});
Why is it that in the first script it wouldn't work if I had a $ before "this" but the second script needed it?
Note: I did already look here: When to use $ and when not to
But that answer was not nearly comprehensive enough.
A: You use $ when you NEED a jQuery object or method in order to solve your problem. If you have a DOM element already and a direct DOM property will give you everything you need, then there's no reason to use jQuery. On the other hand, if you want to use a jQuery method that is unique to jQuery, then, of course, you create a jQuery object and call a method on it.
Example:
$("#myButton").blur(function() {
if (!this.value) {
this.value = "Enter name";
}
});
So, in the first line of this script, we use a jQuery object because it's easier to find an object in the page and assign an event handler.
Inside the handler, I'm using plain javascript and direct properties because there's no advantage to using jQuery. This could have been written this way:
$("#myButton").blur(function() {
if (!$(this).val()) {
$(this).val("Enter name");
}
});
But, there's no advantage to using jQuery inside this handler. It's just more code and more function calls.
So ... use it when you need it or it makes more readable or more reliable code. If none of those apply, don't use jQuery for that particular operation.
A: JQuery objects are meant to represent a DOM element. In the second example, you are using "$(this)" followed by a function call. This means that you can use only the interfaces support by the JQuery object.
In the first example, you are just using "this", which is a reference to the DOM element that owns the current execution context. DOM elements do not implement the JQuery interface (or else you wouldn't need to use JQuery at all!)
In other words, JQuery maintains enough information about a DOM element to be able to find it and perform manipulations on it. However, that does not mean that JQuery exposes an interface identical to a DOM elements.
EDIT: DOM stands for Document Object Model. Essentially, this is a model where all elements in the document are represented as objects (DOM elements). For example, you could use document.getElementById("anId") to retrieve a "DOM element" by the value of its ID attribute. This Document Object Model gives us the ability to manipulate and alter various parts of the document via scripting languages. Basically, the DOM is just a bunch of hierarchical objects that represent the elements on your page. These objects expose interfaces like "innerHTML"--Since JQuery objects are not DOM objects, they do not
A: $(function(){
// ...
});
is equivalent to:
$(document).ready(function () {
// ...
});
This is because jQuery itself will execute the function on the ready event.
On the other hand the below creates an anonymous function that isn't executed:
(function(){
// ...
});
What you'd need instead is:
(function(){
// ...
})();
and that would execute the function immediately.
The first script doesn't actually need the $(this) unless you want to use jQuery functions as the second function one does.
Although it is good to note that the second function isn't executed as stated above unless you have other code that isn't shown here.
A: look at jquery source code
jQuery.fn = jQuery.prototype = {
....
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
....
}
$(handler) the handler will execute when DOM is loaded, if DOM already loaded, handler will execute immediately.
(handler) just declare an anonymous function, if you want to execute it you should use (handler)() as James Khoury's answer;
A: In the first case, this is a DOM element on which the function is called. You're using the innerHtml property directly.
In the second case, you're wrapping the DOM element in a jQuery wrapper and using jQuery methods such as .html() and you're therefore manipulating the element's innerHtml indirectly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: rails best practice for a multistep form? I want to create a mutlistep form in Rails 3. I've watched the railscasts episode on it, but I did not feel like he was using the best practice when creating the form. I felt like it was a sloppy way to accomplish the task. What is the best way to create a multistep form using the best practices in rails?
A: Your question is a little hard to answer without more information, and a true answer would be a detailed tutorial (like a Railscast) rather than a SO answer, but here's some thoughts to get you on your way.
There are two major approaches to multistep forms:
*
*Use Javascript to display the form bit by bit
*Create separate views and use create/update or similar to route the user from one to the next.
There are advantages to each method, depending on whether you want to support javascript, and what your requirements are about saving data in between sections.
Advantages of 1
*
*Faster for the user to navigate from section to section (javascript hide/show is instantaneous)
*Data is easily accessible is the user wants to refer to an earlier section
*Simpler controller actions
Disadvantages of 1
*
*Will not work for users who are not running javascript (and no progressive enhancement is really possible here other than displaying the form as a huge chunk).
*Will require you to provide javascript-based navigation to move from section to section (only a disadvantage if you're new to .js)
*Will require AJAX if you want to save the user's information between steps.
*Without AJAX and javascript, the user is at the risk of losing a lot of entry if the user accidentally pressing the back button, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use Eclipselink @Multitenant in JSF/EJB? The @Multitenant support in Eclipselink 2.3 looks really interesting, but I'm having a hard time understanding how to use it in a JSF or EJB which injects an EntityManager with @PersistenceContext. The EclipseLink docs are pretty clear that @PersistenceContext injection doesn't work in this case, but you could inject an EntityManagerFactory via @PersistenceUunit instead.
Still, what I'm not seeing is how to manage the lifecycle of an EntityManager you might create via injected EntityManagerFactory.createEntityManager() - in particular, when to close the resulting EntityManager, and how to participate in transactions.
Has anyone gotten this to work? Or am I missing something obvious?
See also: http://wiki.eclipse.org/EclipseLink/Examples/JPA/Multitenant
UPDATE
I had some success with @PersistenceContext (EntityManager) injection and then passing parameters to EclipseLink via session listener. I'm not 100% sure this is the right answer and would appreciate confirmation that it isn't creating a non-obvious race condition or thread-safety issue.
For example:
public static class TenantListener extends SessionEventAdapter {
@Override
public void postAcquireClientSession(SessionEvent event) {
long tenantId = **business logic**;
event.getSession().setProperty("eclipselink.tenant-id", tenantId);
}
}
A: Using events is fine.
You could also inject the EntityManager and set the property, or inject the EntityManagerFactory and use joinTransaction() to join the active JTA transaction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: mysql_insert_id and mysql_pconnect I've been using mysql_pconnect to establish all DB connections on my PHP site, with the theory that it's more efficient (debatable, I know).
I went to use mysql_insert_id to get the ID from a recent INSERT and it occurred to me that given the multi-threaded nature of web requests, I can't guarantee that another PHP script using the same pconnection has made a DB INSERT before my call to mysql_insert_id.
This is kind of a huge deal as I see no other way to guarantee atomicity of the INSERT and ID retrieval, as the ID is not returned by the INSERT query (or I don't know how to get it).
So basically I can never use mysql_pconnect if I want to have thread-safe INSERTS and ID retrieval?
A: mysql_insert_id() returns the last id within context of the current connection session. Thus avoiding race-condition problems. There's a bunch of notes/comments regarding this on the php.net manual for mysql_insert_id()
More Info:
*
*PHP/MySQL insert row then get 'id'
*How bad is using SELECT MAX(id) in MYSQL instead of mysql_insert_id() in PHP?
*get id of last inserted record without using mysql_insert_id()
This should be easy to test:
<?php
// connection already established
mysql_query("INSERT INTO table VALUES('foo', 'bar')");
sleep(15);
echo mysql_insert_id();
Then see if you can fool it by slamming it with requests during the sleep period.. and check the insert_id results.
A: mysql_pconnect means that the connection won't be closed from the php module to the mysql.As there is an overhead of creating a new connection so it can be beneficial if you are creating a lot of connections.
As php executes a request in a single thread.And most probably you will be using 1 connection to the database a call to INSERT and subsequent call to ID retrieval is gonna be ATOMIC.
The MYSQL connection taken by 1 php thread can't be used by another php thread while it is still being in used which ensure atomicity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Select next event from 2 arrays I have 2 tables
table 'events'
id event_name date
1 buy milk 1319074920 // 10-20-2011
2 lunch 1321753320 // 11-20-2011
table 'people'
id user birthday
1 Jack 16508520 // 7-11-1970
2 Bill 180409320 // 9-20-1975
What I am trying to do is:
[1] create an array with the event closest to current date/time >> SOLVED
My query generates an array like this
Array ( [0] =>
Array (
[date] => 1319074920
[event_name] => buy milk
)
)
[2] create an array with the birthday closest to current date/time
Not sure how to do this. I could query the database and retrieve users and birthdays and loop through the results, but would need to change the birthday year to the current year, keeping month and day unchanged.
[3] compare the 2 arrays and pick one entry that is closest to current date/time: birthday or event.
Any suggestions?
QUERY CODE
$query = $this->db->query("
SELECT *
FROM events
WHERE UTC_1 >= UNIX_TIMESTAMP()
ORDER BY UTC_1
LIMIT 1
;");
A: If you've got a query that gives you the closest event, then just use the same query for birthdays, since your tables are the same structure.
Once you have the closest event and closest birthday, you can do a simple compare in php to find which one to display.
if (abs(bday[0]['date'] - time()) < abs(event[0]['date'] - time())) {
// Show birthday
} else {
// Show event
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Clojure priority-map I have the following,
(let [t (priority-map-by (comparator (fn [[f1 _] [f2 _]]
(< f1 f2)))
:b [8 [2 1]])]
(assoc t :c [8 [2 3]]))
for some reason the associated item :c is modified after it is added to the map what I get is,
{:c [8 [2 1]], :b [8 [2 1]]}
what I expect is,
{:c [8 [2 3]], :b [8 [2 1]]}
am I missing something obvious why is the items value is modified? or is this a bug?
A: I got what I wanted by not using a comparator and returning -1 0 1 depending on the cond,
(let [t (priority-map-by (fn [x y]
(if (= x y)
0
(let [[f1 _] x
[f2 _] y]
(if (< f1 f2) -1 1))))
:b [8 [2 1]])]
(assoc t :c [8 [2 3]]))
that gives me what I want,
{:b [8 [2 1]], :c [8 [2 3]]}
A: Looking at the implementation for priority-map-by, it appears to be based on sorted-map-by, which holds that keys that compare the same are the same. For example:
(sorted-map-by (fn [[a] [b]] (< a b)) [1 2] :foo [1 3] :bar)
=> {[1 2] :bar}
This also holds true for sorted-set-by:
(sorted-set-by (fn [[a] [b]] (< a b)) [1 2] [1 3] [3 4])
=> #{[1 2] [3 4]}
Whether that's intended behavior for priority-map-by, you'd have to ask the author. I think it's reasonable.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: jQuery tmpl clear Does anyone know how to clear a jQuery tmpl() so I can re-populate it? I cant use empty() because i need the rest of the content in the parent. I can use remove, but I need to know how many... wait, i might have just figured it out :)
The template looks like this
<table id="lvList" class="grid1">
<tr id="itemtemplatePlaceHolder">
<th>Reference</th>
<th>Address</th>
<th>Country</th>
<th>Postcode</th>
<th>Tel</th>
<th>Fax</th>
<th style="width:50px;">Billing</th>
<th style="width:50px;">Shipping</th>
</tr>
<script id="itemtemplate" type="text/x-jquery-tmpl">
<tr>
<td><a id="${id}" href="address.aspx?id=${id}" oncontextmenu="ContextMenu.Show(this,event); return false;">${reference}</a></td>
<td>${$item.nobreak("address", ", ")}</td>
<td>${country}</td>
<td>${postcode}</td>
<td>${tel}</td>
<td>${fax}</td>
<td>${$item.bool("defaultbilling", "X", "")}</td>
<td>${$item.bool("defaultshipping", "X", "")}</td>
</tr>
</script>
<tr id="footertemplate">
<td colspan="8"> </td>
</tr>
</table>
A: Answered my own query :) but just in case anyone else has the same problem, he's what i did
Kept a track of how many items there were in the data list this.itemcount = data.Count();, then removed all siblings past the placeholder with an index less than the item count $("#itemtemplatePlaceHolder ~ :lt(" + this.itemcount + ")").remove()
this.Populate = function () {
try {
if (this.itemcount > 0) {
$("#itemtemplatePlaceHolder ~ :lt(" + this.itemcount + ")").remove();
}
var data = this.GetData();
this.itemcount = data.Count();
$("#itemtemplate").tmpl(data).insertAfter("#itemtemplatePlaceHolder");
}
catch (ex) { this.HandleError(ex); }
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: make an Setup exe file of c++ VS2010 I've done app by c++ . It's serial port programming/win app.
It's got many files and I would like to make an exe file(setup file to install on client's pc) for delivering thru customers.
I did many research and as far as i see i couldnt.
Any way to do that ?
Would be appreciated.
A: You need to create a setup project and add it to your solution.
EDIT
You may also like to check this and this links.
A: So after the comments, I'm pretty sure what you really want is to build an installer for your application which will package up your built executables with all it necessary libraries and what not, so that you can deliver a single file to your customers and have them install it.
A basic way is the way a lot of open source/free software projects do it - supply an archive/zip/whatever file that the user downloads and unzips on their own machine. I don't really recommend this way unless your users are all technical.
At a previous company we InnoSetup, which is really nice, easy to learn, and free.
A: nsis is another option. http://nsis.sourceforge.net/Main_Page . It can create windows installers and is script based.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Objective C - Cannot read file in Directory of Document or Cache in Iphone In my work, I just want to read a downloaded PDF in iphone device
At first, I tried to use the "bundleRoot" directory, it is work in simulator but not on device. Now, I just test in simulator for Directory of Document or Cache.
How can I get a writable path on the iPhone?
After I read the above topic,
I have tried using Directory of Document or Cache.
Here is my code in finding the writable path
/******************************************************************************/
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDir] && isDir == NO) {
[[NSFileManager defaultManager] createDirectoryAtPath:cachePath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *path_to_file = [cachePath stringByAppendingPathComponent:@"testing6.pdf"];
/******************************************************************************/
I can find the downloaded file and get the size in this directory,but I cannot read the file by using the following code :
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
page = CGPDFDocumentGetPage(pdf, 1);
CGPDFPageRetain(page);
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
The return pageRect.size.width is 0
After I print out the download and retrieve file path also are :
/Users/ITDEV/Library/Application Support/iPhone Simulator/4.3.2/Applications/806ED359-70F8-4C07-996F-6AFC959B3FC7/Library/Caches/testing6.pdf
Anyone can help me pls?
A: You can read the file in UIWebView.
And By using below code you can open the file.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDir] && isDir == NO) {
[[NSFileManager defaultManager] createDirectoryAtPath:cachePath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *path_to_file = [cachePath stringByAppendingPathComponent:@"testing6.pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path_to_file];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[YourWebViewName loadRequest:request];
Don't Forget to connect the IBOutlet of your webview with nib file's UIWebview.
A: If all other answers won't work then try using NSBundle as below:
NSString *path = [[NSBundle mainBundle] pathForResource:@"myfilename" ofType:@"pdf"];
NSLog("path : %@",path);
Same problem i faced and i found that my plist file was not in Documents directory but instead it shows me path to my app and then it shows MYAppName.app/myPlist.plist file. This means that the app file includes my plist file in its own bundle i.e. MainBundle.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery assignment fails when inside a for loop I have a jquery which works correctly when I do this:
var slide = [];
slide[1] =
{
hide: function() {
$("#slide-1").hide();
},
show: function() {
$("#slide-1").show(2000);
}
};
slide[1].show(); <<< works fine
But if I try it in a loop in fails:
for (var i=1; i <= totalSlides; i++) {
slide[i] =
{
hide: function() {
$("#slide-" + i).hide();
},
show: function() {
$("#slide-" + i).show(2000);
}
};
};
slide[1].show(); << unassigned
any idea?
A: Well, you're saying that it is "unassigned" but I'm guessing that the function is just not doing what you want.
This is a common issue. All the functions you're creating in the loop are referencing the same i variable. This means that when the function runs, it is getting the value of i where it was left after the loop finished.
You need to scope the variable that your functions reference in a new variable environment to retain the value from the loop. To do that, you need to invoke a function, and have that function reference the current i value.
Like this:
function generate_functions( j ) {
// v----- DO NOT place the opening brace on the next line, after the
return { // return statement, or your code will break!!!
hide: function() {
$("#slide-" + j).hide();
},
show: function() {
$("#slide-" + j).show(2000);
}
};
}
var slide = [];
for (var i=1; i <= totalSlides; i++) {
slide[i] = generate_functions( i );
};
slide[1].show(); // should work
I created a function called generate_functions(), and invoked it in each iteration, passing i as an argument.
You'll notice that generate_functions() received the value as the j parameter. You could call it i as well, but changing the name makes it a little clearer IMO.
So now your functions are referencing the local j. Because a new variable environment is created with each invocation of generate_functions(), the functions inside that you create will be referencing the j value of that specific variable environment.
So the generate_functions() returns the object that contains the functions that were created in each new variable environment, and that object is assigned to slide[i].
A: Is the $("slide-1" + i).show(2000) a typo, or the error?
A: Add var slide = []; above the for loop.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605250",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Java java.nio writes line of []s I am using java.nio to copy a file, it copies fine except for the fact that there is a line of []s at the end of the file.
Here is my code:
source (the source channel)
source.read(buffer);
buffer.flip();
mbb.put(buffer)
mbb is MappedByteBuffer
Source Channel:
source = new FileInputStream(original(this is a File)).getChannel();
MappedByteBuffer:
source.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
A: You are assuming the file is 1024 bytes long instead of using the actual file size. I suspect the junk is in the MappedByteBuffer rather than the file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: wxPython Button Background Image Can I create a button with text with a background image? In wxPython, there are certain functions which create buttons such as wx.lib.buttons.GenBitmapTextButton and other functions like that. I'm wondering if I can create a button with a fancy background image, as well as label text.
A: There is no built-in button that allows a background image underneath the text. You can probably look at one of the generic button widgets though and use them as a template. Basically you just need to draw the bitmap on and then draw text on top, probably by using wx.DC or wx.GCDC or similar. The generic buttons include such things as wx.lib.buttons, wx.lib.agw.aquabutton and wx.lib.platebtn among others.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ACM Programming Question I'm trying to solve a programming problem to practice for a competition tomorrow, and I thought maybe this would be a good place to ask how to approach it. The problem is the first one on this site: http://www.cs.rit.edu/~icpc/questions/2010/Oswego_2010.pdf
The FAQ on this site mentions Algorithm and data structure concepts, and Design patterns, so I guess asking how to approach this problem isn't off topic. Here is what I have so far (not much). I don't understand how to solve this.
public class Ape
{
public void computeOutput(int weight, int[] capacities, int[] snackLosses)
{
//not sure what to do
}
public static void main(String [] args) throws FileNotFoundException
{
Ape ape = new Ape();
File file = new File(args[0]);
Scanner in = new Scanner(file);
int totalWeight = in.nextInt();
int n = in.nextInt();
int[] capacities = new int[n];
int[] snackLosses = new int[n];
for (int i = 0; i < n; i++)
{
capacities[i] = in.nextInt();
snackLosses[i] = in.nextInt();
}
ape.computeOutput(totalWeight, capacities, snackLosses);
}
}
A: This looks like a dynamic programming problem at first glance.
Basically, we have a function f(N,K) = the number of bannas brought home given K available bannas and the first N monkeys.
Clearly f(0,K) = 0 and f(N,0) = 0
Then all you have to do is figure out the value of f(n,k). You should do so by taking the maximum over two case:
*
*The monkey doesn't take a bannana f(n,k) = f(n-1,k), since the monkey does nothing it is just like he isn't there
*The monkey takes the bannana f(n,k) = f(n-1, k - Strength) + strength - stuff monkey eats
Fill a table our use memoization with this logic and then determine f(N,K) and you've got your answer.
A: this question can be reduced to a 0/1 knapsack which is itself a well known DP algorithm. But here instead of value you have Capacities - Snacks.
A: #include <iostream>
using namespace std;
main(){
int totalwight,numberapes;
//cout<<"Enter The total weight of bananas available to lug home : ";
cin>>totalwight;
//cout<<"Enter The number of apes : ";
cin>>numberapes;
int *capacity = new int [numberapes];
int *tcapacity = new int [numberapes];
int *snackloss = new int [numberapes];
int *pos = new int [numberapes];
int *tpos = new int [numberapes];
for (int i=0 ; i<numberapes ; i++){
pos[i]=i+1;
tpos[i]=0;
}
for (int i=0 ; i<numberapes ; i++){
// cout<<"Enter How many monkey # "<<i+1<<" carrying capacity : ";
cin>>capacity[i];
tcapacity[i]=capacity[i];
//cout<<"Enter How many snack loss of monkey # "<<i+1<<" : ";
cin>>snackloss[i];
}
int *arr = new int [numberapes];
for (int i=0 ; i<numberapes ; i++)
arr[i] = capacity[i] - snackloss[i];
int temp;
for (int i=0 ; i<numberapes ; i++)
for (int j=0 ; j<i ; j++)
if (arr[i] > arr[j]){
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
temp = tcapacity[i];
tcapacity[i] = tcapacity[j];
tcapacity[j] = temp;
temp = pos[i];
pos[i] = pos[j];
pos[j] = temp;
}
int *tarr = new int [numberapes];
int j=0;
for (int i=0 ; i<numberapes ; i++)
tarr[i]=0;
for (int i=0 ; i<numberapes ; i++){
if (arr[i] <= totalwight && tcapacity[i] <= totalwight){
totalwight -= tcapacity[i];
tpos[j] = pos[i];
j++;
}
}
for (int i=0 ; i<numberapes ; i++)
for (int j=0 ; j<numberapes ; j++)
if (tpos[j] > tpos[i] && tpos[i]!=0 && tpos[j]!=0){
temp = tpos[i];
tpos[i] = tpos[j];
tpos[j] = temp;
}
int t1=1,t2=0;
while (t1<=numberapes){
if (t1 == tpos[t2]){
cout<<"1 ";
t2++;
}
else
cout<<"0 ";
t1++;
}
}
A: Please see my answer:
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
namespace monkey
{
class Program
{
static int getTotalCapacity(int[] ki, int[] indexes)
{
int result = 0;
foreach (int i in indexes)
{
result += ki[i];
}
return result;
}
static int[] computeOutput(int k, int n, int[] ki, int[] wi)
{
// #1: Sort the input by ki - wi
Dictionary<int, int> vi = new Dictionary<int, int>();
for (int i = 0; i < n; i++)
{
vi.Add(i, ki[i] - wi[i]);
}
Dictionary<int, int> sorted_vi = (from entry in vi orderby entry.Value descending select entry).ToDictionary(x => x.Key, x => x.Value);
// #2: Take elements in sequence in order to fulfill the minimum total k
Dictionary<int, int> result = new Dictionary<int, int>();
foreach (KeyValuePair<int, int> kv in sorted_vi)
{
if (ki[kv.Key] + getTotalCapacity(ki, result.Select(x=>x.Key).ToArray()) <= k)
{
result.Add(kv.Key,kv.Value);
}
}
// #3 Transform to output format
int[] output = new int[n];
foreach(KeyValuePair<int,int> kv in result){
output[kv.Key] = 1;
}
return output;
}
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("Usage: <prog>.exe <filepath>");
return;
}
try
{
int k;
int n;
int[] ki;
int[] wi;
// Reading file input
using (StreamReader fs = new StreamReader(args[0]))
{
k = Convert.ToInt32(fs.ReadLine());
n = Convert.ToInt32(fs.ReadLine());
ki = new int[n];
wi = new int[n];
for (int i = 0; i < n; i++)
{
string[] line = fs.ReadLine().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
ki[i] = Convert.ToInt32(line[0]);
wi[i] = Convert.ToInt32(line[1]);
}
}
int[] output = computeOutput(k, n, ki, wi);
Console.WriteLine(string.Join(" ", output));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to change title of NSPanel at runtime? Maybe I'm missing something really simple here (I hope so), but is there a trick to changing the title of an NSPanel at runtime? The obvious [panel setTitle:@"New title"] doesn't seem to be working.
I'm trying to display a regular panel which contains a WebView, and I want to the title of the panel to reflect the title of the HTML content.
I subclassed NSWindowController and called initWithWindowNibName. I changed the class in the nib from NSWindow to NSPanel, and everything seems to be working okay. In my window controller, I did this:
- (void)windowDidLoad {
[super windowDidLoad];
[[self window] setTitle:@"My New Title"];
}
(I will actually be setting the title in a webView:didReceiveTitle:forFrame delegate, but this is simpler to show).
I verified that the code is getting called, and there are no errors reported, but the title never changes. Any ideas?
A: In the nib file that contains the panel, make sure that the File’s Owner’s class has been set to your NSWindowController subclass and that the window outlet from File’s Owner has been connected to the panel. Otherwise, the window controller won’t know which window it should be managing and [self window] returns nil.
A: You're setting the title, but you're not telling the window to display itself again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: passing a return statement into another function in a class I have the following code that I am using to send a message from a gmail account to another gmail account:
import smtplib
class GmailSmpt:
global server
server = smtplib.SMTP('smtp.gmail.com','587')
def __init__(self,sendfrom,sendto,usrname,pswd):
self.sendfrom = sendfrom
self.sendto = sendto
self.usrname = usrname
self.pswd = pswd
def connect(self):
msg = 'this is a test message'
server.starttls()
server.login(self.usrname,self.pswd)
server.sendmail(self.sendfrom,self.sendto,msg)
print ("your email has been sent")
def quit(self):
server.quit()
first = GmailSmpt('sendfrom','sendto',
'usrname','pswd')
first.connect()
first.quit()
Instead of having a global variable server, I would like to use "return server" in the "connect" function and then pass server on to the "quit" function. How would I put that into the parameter of def quit(self, ?)? What I would normally do in a non object oriented program is "def quit(self,connect), but in this case I want to be able to call def connect() and def quit() separately.
Thanks!
A: How about make server an attribute of each instance of GmailSmpt:
class GmailSmpt:
def __init__(self,sendfrom,sendto,usrname,pswd):
self.server = smtplib.SMTP('smtp.gmail.com','587')
...
After all, server.login uses self.usrname, and self.pswd, so server's domain of relevance is bound to one instance of GmailSmpt, so it makes sense to make server an attribute of that instance also.
PS. If you make server an attribute of self, then you'll also have to change server --> self.server in the other methods.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to prevent the Application Error MessageBox show in Windows XP I need to execute a console application periodly in windows XP. So I use the following python code:
import subprocess
import time
while True:
subprocess.call("test.exe")
time.sleep(1.0)
the problem is that test.exe crashs occasionally, and an error report messagebox pops-up, unless I close the messagebox manually, the python program will be paused at subprocess.call().
After some search, I disabled the error report messagebox as the following link:
http://www.howtogeek.com/howto/windows/disable-those-annoying-x-application-has-encountered-a-problem-and-must-be-shut-down-messages-in-windows-xp/
the error report messagebox gone, but another application error messagebox pops-up (sorry the messagebox is in Japanese):
it will also cause the python program pause. I just want the test.exe crashes silently, and let the python program calls it again in next period. How can I prevent the Application Error messagebox shows up?
I can't fix the bugs in test.exe, because I have not source code of it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What should I use as a server to meet the following requirements? I am trying to develop a system that involves a:
*
*server with a database that will handle the system's logic and manipulate data
*an android app that will interact with that server (pull and push data into the server)
*a website that will do the same as the android app, but from a website with slightly different data.
What I thought of is to use SQLite with Apache Tomcat installed on the server and deploy a Grails war file on it. That will take care of the 'website' side of the system. But what about the android app? Can it communicate with Tomcat as well?
A: If you have an API that is web accessible, an Android can access it.
A: Android shouldn't have any problems communicating with Tomcat.
Look at http://grails.org/doc/latest/guide/13.%20Web%20Services.html for more information.
A RESTful web service is most likely what you'll need. Android can consume SOAP web services but it requires more work for less overall functionality.
A: Tomcat will suit your needs. I would look at hosting options though. Are you hosting your own server, or do you have a hosting provider? Do you have experience hosting a tomcat server etc. Do you have experience with java web applications, or other web frameworks? All of the above, and probably more should lead you to your decision on what type of framework/language to use on the server. This in turn will lead you to your options for hosting, and web-container to use.
Once that is determined all major web frameworks will allow you to publish web-services Rest, Soap, etc. that can be consumed by an android application.
Also, if you are planning on providing a web interface and service at the server level, my guess is you are going to be storing a fair amount of data, I would look into a more robust and scalable database such as mysql or postgres. This post contains some insights into this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook canvas app "redirect_uri" breaks out of iframe after authorization & authentication I'm upgrading my existing FB apps, and going absolutely bonkers trying to get a simple PHP iframe canvas app to authorize and authenticate (as well as use SSL). Never looked through so many examples...
Here's where I'm stuck: After the user authorizes the app, and the app authenticates the user (I am able to make a graph request with the token OK), the redirect_uri happens, and the whole page refreshes, leaving Facebook and thenjust shows me the contents of my "Canvas URL" page (with my server's domain), rather than iframed on Facebook.
I currently have this as a crude two step process...
Here's what my code looks like on the first page (index.php):
<?php
require('src/facebook.php');
$app_id = '123456789';
$app_secret = '1234secrets1234';
$canvas_page = "https://apps.facebook.com/123456789/";
$canvas_url = "https://myserver.com/apptest/";
$code = $_REQUEST['code'];
if(!$code){
$display= 'page';
$scope= 'manage_pages, offline_access, read_insights, publish_stream, user_about_me, user_likes, email';
$redirect_url = 'https://myserver.com/apptest/step2.php';
$oauth_url = 'https://www.facebook.com/dialog/oauth?canvas=1&client_id='.$app_id.'&display='.$display.'&redirect_uri='.urlencode($redirect_url).'&scope='.$scope;
$config = array('appId' => $app_id,'secret' => $app_secret,'cookie' => true,'domain' => true);
$facebook_client = new Facebook($config);
echo "<script type=\"text/javascript\">top.location.href = \"".$oauth_url."\";</script>";
}
?>
and the second page (step2.php):
<?php
require('src/facebook.php');
$app_id = '123456789';
$app_secret = '1234secrets1234';
$canvas_page = "https://apps.facebook.com/123456789/";
$canvas_url = "https://myserver.com/apptest/";
if($_REQUEST['code']){
$code=$_REQUEST['code'];
$redirect_url = 'https://myserver.com/apptest/step2.php';
$link="https://graph.facebook.com/oauth/access_token?canvas=1&client_id=".$app_id."&redirect_uri=".urlencode($redirect_url)."&client_secret=".$app_secret."&code=".$code;
$string = file_get_contents($link);
$auth_token=substr($string, 13, 150);
$graph_url = "https://graph.facebook.com/me?access_token=".$auth_token;
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
Again, once the user has authorized the app, and the app has authenticated the user, the graph call works.
Any ideas?
A: When navigating to the OAuth dialog the web page (not the frame your app is in) is navigated to the OAuth URL. To get back into the Facebook iframe after authentication you need to set the OAuth redirect URL to the canvas_page URL. The code shown above is navigating to the URL of myserver when redirected so your app takes up the entire page (because you left the Facebook iframe when navigating to the OAuth dialog). Your code at canvas_url needs to determine if it is being entered from authorization (success or failure) or if it is being entered with a valid access token after authentication.
Also your canvas_page URL appears to be comprised of the facebook apps host and your application ID. It should be the facebook apps host and your application name (the redirect URL should be the same as the "Canvas Page" URL on your app's developer page).
A: Well I did get this working. On the app > settings > basic I hadn't set a namespace, so the URL it gave me for the app on facebook was like this: https://apps.facebook.com/123456789/ and now with the namespace they changed it to: https://apps.facebook.com/myappname. So that may have been it. I tried to carefully follow the simple PHP autorization demo on this page: https://developers.facebook.com/docs/appsonfacebook/tutorial/ and it seems to work ok now.
Thanks for the help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Improving "shuffle" efficiency Right now, I am using the following code to create a Shuffle extension:
public static class SiteItemExtensions
{
public static void Shuffle<T>(this IList<T> list)
{
var rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}
}
I am looking for a way more faster and efficient way to do this. Right now, using the Stopwatch class, it is taking about 20 seconds to shuffle 100,000,000 items. Does anyone have any ideas to make this faster?
A: This highlights an aspect of modern computer design that's often overlooked. It can be made over 3 times faster by a silly change:
int k = 0; rng.Next(n + 1); // silly change
There are now more statements in the inner loop but it is much faster. What you are seeing is the effect of the CPU cache. This algorithm has very poor cache locality, the odds that the next element to be read from the array is already in the cache is very low. Which takes an expensive trip to the slower outer caches and the dead-slow memory bus. The odds that elements from the array needed later are loaded into the cache is very high. But the odds that they are still there when needed is very low, your list is simply too large the fit the cache.
Nothing can be done to fix this, it is inherent in the algorithm design. Using realistic list sizes is however an obvious solution. Running it 100,000 times on a list with a 1000 elements is 3 times as fast.
A: You have exceeded the capabilities of your CPU's cache and are spending most of the time waiting for RAM.
By progressively lowering the number of elements, I get the following results (on List<int>):
count time (s) slowdown
100000000 16.0429005 11.99215276436421
10000000 01.3377832 20.37312930505406
1000000 00.0656641 13.36837069158574
100000 00.0049119
Notice the big slowdown between between 10^6 and 10^7. I increased the number of elements by factor of 10, but the time increased by factor of 20. This is probably where my CPU no longer can fit most of the array into the 2nd (and last on my CPU) level of cache.
BTW, you can gain a second or two (but lose generality), by replacing IList<T> with List<T> in the method signature and avoiding the interface call penalty on []:
IList<T>: 16.0429005 s
List<T>: 14.3529349 s
For the record, under Visual C++ 2010, std::random_shuffle on std::vector<int> with 100000000 elements takes...
17.947 s
...so you are probably already as fast as you can be.
(NOTE: Both C# and C++ benchmarks were done under respective Release configurations, outside of the debugger.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to make links to dynamic content work from outside a GWT page I have a webapp example.com written in pure GWT. Obviously the webapp
has dynamic links, like example.com/#/link1.
I want example.com/#/link1 to be accesible from outside my website. For example. I would like to post the example.com/#/link1 link in facebook.com so my friends can see it. However, when someone clicks on the link, it will take him to example.com, NOT example.com/#/link1, even though I have a valueChangeHandler in my EntryPoint.
So my question is, how to make dynamic links accesible from outside my GWT page.
EDIT: found out answer:
In EntryPoint do the following
public void onModuleLoad() {
String initState = History.getToken();
//This is your initial token for your gwt ap
System.out.println(initState);
//Do any stuff you want to here, like init some stuff in your app, and finally:
History.newItem(initState);
//That las line calls the initial state of your app. This worked for me because I
//changed the history state in between, so I had to save initialState, do stuff and then
//fire inistial state.
}
A: It seems to me like you need to work with Activities and Places to handle browser history. This creates a link between a place/state/page in your application and the URL in the browser by inserting/parsing URL place tokens. Have a look at the content of this Google Dev page.
You should be able to do what you want with history handling. You define a set of tokens which describe places/pages/whatever state in your application. Your app parses tokens in the URL and redirects to the appropriate page/view.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting text field data from different page to display in jquery? I have a page with the following code:
<div data-role="page" id="personaldetails">
<div data-role="header">
<h1>ENTER PERSONAL DETAILS</h1>
</div><!-- /header -->
<div data-role="content">
<div data-role="fieldcontain">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" />
<label for="name">Phone Number:</label>
<input type="text" name="phone" id="phone" value="" />
<label for="address">Address:</label>
<textarea cols="40" rows="10" name="address" id="address"></textarea>
</div>
<p><a href="#confirmscreen" data-role="button">Input Incident Details</a> </p>
</div><!-- /content -->
<div data-role="footer">
<h4></h4>
</div><!-- /footer -->
</div><!-- /page -->
And I try to do this in another page:
<div data-role="page" id="confirmscreen">
<div data-role="header">
<h1>DETAILS TO SEND</h1>
</div><!-- /header -->
<div data-role="content">
<div data-role="fieldcontain">
<script type="text/javascript">
$('<p>').html($('#phone').val()).appendTo('body');
</script>
</div>
<p><a href="http://google.com/" data-role="button">Fin</a> </p>
</div><!-- /content -->
<div data-role="footer">
<h4></h4>
</div><!-- /footer -->
</div><!-- /page -->
I'm trying to output the phone text area but I'm getting a blank space instead of the phone number I entered.
Do I need to maybe submitt he form or something to get it to work? If so how would I do it?
A: I don't know if it will do any good, but the first thing i would do is to wrap the jquery code inside a
$( window ).load( function() {
});
A: You need to perform a PHP Post. A PHP Post() is a method used in PHP to pass info from one page to another. This is how I would set it up
Assuming you have your Original Page, I am going to call it index.php. You probably have it as index.html right now. Change the ending to .php, and re-open your document. Now, follow along
You have right now this:
<div data-role="page" id="personaldetails">
<div data-role="header">
<h1>ENTER PERSONAL DETAILS</h1>
</div><!-- /header -->
<div data-role="content">
<div data-role="fieldcontain">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" />
<label for="name">Phone Number:</label>
<input type="text" name="phone" id="phone" value="" />
<label for="address">Address:</label>
<textarea cols="40" rows="10" name="address" id="address"></textarea>
</div>
<p><a href="#confirmscreen" data-role="button">Input Incident Details</a> </p>
</div><!-- /content -->
<div data-role="footer">
<h4></h4>
</div><!-- /footer -->
</div><!-- /page -->
Now where you have this:
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" />
<label for="name">Phone Number:</label>
<input type="text" name="phone" id="phone" value="" />
<label for="address">Address:</label>
<textarea cols="40" rows="10" name="address" id="address"></textarea>
You are going to want to enclose it in a form, and make it look like this
<form action="page2.php" method="post">
<label for="name">Name:</label>
<input type="text" name="name" id="name" value="" />
<label for="name">Phone Number:</label>
<input type="text" name="phone" id="phone" value="" />
<label for="address">Address:</label>
<textarea cols="40" rows="10" name="address" id="address"></textarea>
<input type="submit" value="Report Incident Details" />
</form>
If you notices, I enclosed the inputs in a Form tag and added action="page2.php" method="post" to the tag's attributes. This means when the form is submitted, the data will be sent to the second page you want it to be on. We also included the Submit Button within the form area.
Now the second page should look like this
<div data-role="page" id="confirmscreen">
<div data-role="header">
<h1>DETAILS TO SEND</h1>
</div><!-- /header -->
<div data-role="content">
<div data-role="fieldcontain">
<?php echo $_POST["name"]; ?><br />
<?php echo $_POST["phone"]; ?><br />
<?php echo $_POST["address"]; ?><br />
</div>
<p><a href="http://google.com/" data-role="button">Fin</a> </p>
</div><!-- /content -->
<div data-role="footer">
<h4></h4>
</div><!-- /footer -->
</div><!-- /page -->
That should do that trick. Have fun!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tell sage where to find libjpeg I have installed Sage on Mac OS X. It looks like it has PIL. The following code gives me an IOError..
import Image
a = Image.open("pic.jpg")
a.thumbnail((int(100), int(100)))
This is the error I get.
IOError Traceback (most recent call last)
<ipython console> in <module>()
/sage/local/lib/python2.6/site-packages/PIL/Image.pyc in thumbnail(self, size, resample)
1520 self.draft(None, size)
1521
-> 1522 self.load()
1523
1524 try:
/sage/local/lib/python2.6/site-packages/PIL/ImageFile.pyc in load(self)
178
179 for d, e, o, a in self.tile:
--> 180 d = Image._getdecoder(self.mode, d, a, self.decoderconfig)
181 seek(o)
182 try:
/sage/local/lib/python2.6/site-packages/PIL/Image.pyc in _getdecoder(mode, decoder_name, args, extra)
373 return apply(decoder, (mode,) + args + extra)
374 except AttributeError:
--> 375 raise IOError("decoder %s not available" % decoder_name)
376
377 def _getencoder(mode, encoder_name, args, extra=()):
IOError: decoder jpeg not available
It seems, to me, that it can't find libjpeg. I checked MacPorts on my machine, & it looks like the jpeg package has been installed. I also found libjpeg in /opt/local/lib. I tried manipulating LD_LIBRARY_PATH, both in the sage script & while in Sage, using the os library, but haven't been able to get rid of this error. I searched on the Internet for how to get PIL to find libjpeg, but what I found involves modifying setup.py rebuilding PIL. sage doesn't seem to include PIL's setup.py.
Has anyone else encountered this problem & solved it? Perhaps someone familiar w/ PIL?
A: The answer is to just reinstall PIL.
sage.misc.package.install_package("pil", force=True)
It was that simple & it just took a minute. Reinstalling it on my machine probably allowed it to find the location of the libraries on my machine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Accessing RequestContextHolder and HttpServletRequest.getUserPrincipal() from AuthenticationSuccessHandler I have a Spring-MVC application (i.e. I am using the Spring's dispatcher servlet). I am also using Spring Security to authenticate users. Since I use the Spring's dispatcher servlet, I do NOT have to declare
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
in my web.xml in order to be able to use RequestContextHolder (if I understand correctly the documentation).
My question refers to my implementation of the interface org.springframework.security.web.authentication.AuthenticationSuccessHandler:
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
int timeout = 60*60;
//does work
request.getSession().setMaxInactiveInterval(timeout); //60 minutes
System.out.println("Session timeout of user: " + authentication.getName() + " has been set to: " + timeout + " seconds.");
/*
//does not work
session().setMaxInactiveInterval(timeout); //60 minutes
System.out.println("Session timeout of user: " + request.getUserPrincipal().getName() + " has been set to: " + timeout + " seconds.");
*/
//now restore the default work flow (SavedRequestAwareAuthenticationSuccessHandler is the default AuthenticationSuccessHandler that Spring uses,
// see: http://static.springsource.org/spring-security/site/docs/3.0.x/reference/core-web-filters.html#form-login-flow-handling )
(new SavedRequestAwareAuthenticationSuccessHandler()).onAuthenticationSuccess(request, response, authentication);
}
public static HttpSession session() {
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
return attr.getRequest().getSession(true); // true == allow create
}
}
Could you explain why in the above mentioned code, RequestContextHolder.currentRequestAttributes() and HttpServletRequest.getUserPrincipal() do not work (they do work inside a Controller)?
Thanks!
A: Spring security is filter-based. That is why you need the RequestContextListener defined since the DispatcherServlet will not have been invoked yet when the spring-security stuff happens and the spring request context will not have been set up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to have the C preprocessor execute code during compilation? I'm currently working on a code project that requires me to replace certain strings with hashes of those strings. Seeing as these strings will not change at runtime, it would be advantageous, efficiency wise, to have the c preprocessor run my hash function on each string that I declare to be hashed at compile time.
Is there any way to get the C preprocessor to run my hash function at compile time?
I know this doesn't work the way I described above, but just to get an idea of where I'm going, here's some pseudocode that uses a macro. Imagine that instead of simply expanding the macro, the preprocessor ran the hash function and expanded it to the return value of that hash function:
#include <iostream>
#include <string>
#define U64_HASH(inputString) getU64HashCode(inputString)
//my hash function
unsigned long long getU64HashCode (string inputString)
{
/*code*/
}
int main()
{
cout << U64_HASH("thanks for helping me") << endl;
return 0;
}
Again, ideally the cout << U64_HASH("thanks for helping me") << endl; would expand to cout << 12223622566970860302 << endl;
I wrote a header file generator, and that works fine for this project.
Final Solution
I have decided to use John Purdy's perl script for this project, as it is simply awesome,and allows me to feed the output I want directly to my compiler. Thanks very much, John.
A: One way to accomplish this is to put all your strings into a header file, and name them:
// StringHeader.h
#define helloWorld "Hello World"
#define error_invalid_input "Error: Invalid Input"
#define this_could_get_tedious "this could get tedious"
Then you can use those strings:
#include "StringHeader.h"
std::cout << this_could_get_tedious << std::endl;
Then you can run a program on your StringHeader.h to hash each string, and generate a replacement header file:
// Generated StringHeader.h
#define helloWorld 097148937421
#define error_invalid_input 014782672317
#define this_could_get_tedious 894792738384
That looks very manual and tedious, at first, but there's ways to automate it.
For example, you could write something to parse your source code, looking for "quoted strings". Then it could name each string, write it to a single StringHeader.h, and replace the inline quoted string with the new named string constant. As an additional step when you create the file, you could hash each string - or you could has the file in one go after you've created it. This could let you create a hashed and non-hashed version of the file (which could be nice to create a non-hashed Debug version, and a hashed Release version).
If you do try that, your initial parser to look for strings will have to handle edge cases (comments, #include lines, duplicated strings, etc).
A: If a compiler ever supports this, C++11 has user defined literals:
constexpr unsigned long long operator "" U64_HASH_(
const char *literal_string) { ... }
#define U64_HASH(inputString) inputString U64_HASH_
or with constexpr:
constexpr unsigned long long operator "" U64_HASH(
const char *literal_string) { ... }
A: If you can't get the pre-processor to do this for you, you may be able to write your own pre-processor to do this step first.
A: There's no way to force it, but if your compiler is good enough, it can do it. Play with its optimization options and study the disassembly of the code in the debugger to see if any one of them lets you achieve what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: What effect does compiling to LLVM bytecode, then to machine code have on speed, etc? I ask because, with the increasing popularity of mobile computing on ARM devices, the continued need for backwards-compatible X86 devices, and newer technologies like quantum computing, which will have completely different architectures, an intermediate language seems like the best choice for a compiler developer. How does the double-compilation affect the quality of the generated machine code?
A: All compilers use low-level internal representation (LIR) to carry out low-level optimizations. In GCC it is called "GIMPLE"; in LLVM it is called "LLVM IR". In other words, LLVM approach is no different to other compilers with respect to this point.
In fact, most front-end further use some high-level internal representation (HIR) to carry out some optimizations (esp. on loops) which are much more cumbersome to apply at the LIR level (or impossible due to loss of information).
So usually a program goes through not 2 but 3 steps of "compilation": C -> HIR -> LIR -> ASM.
Regarding the remaining of your question, as other people already mentioned, the LIR is not meant to be portable among different architectures, but among different instances of the same (or similar) architectures. Their are many reasons for that:
*
*C code is inherently not portable anymore after steps like preprocessing or the evaluation of the various sizeof.
*depending on the target applications, different optimizations are required, some of them being carried out at the HIR level (e.g. inside Clang); it would be too late to roll back after conversion to LLVM IR.
*anyway, when you have optimized C code, it is usually highly target-dependent.
Anyway, if you're interested about portability, you should also take a look at NVidia's PTX ISA. It is a virtual ISA common all NVIdia's GPU, to be compiled by the GPU driver at install time into machine code.
A: LLVM is designed to generate high-performance code from LLVM IR; if you're writing a new compiler, you'll get much better performance with much less effort by using IR as opposed to writing your own code generator. In some sense, you could say that the "double-compilation" actually improves the generated code, since LLVM has powerful optimizers for LLVM IR.
http://www.aosabook.org/en/llvm.html might be of interest.
A: LLVM is just as platform independent as your language, i.e. it can be platform independent, but is not high enough level to represent the C language independently.
So, as long as you don't have types, etc that depend on things like "pointer size" then you're probably OK. The "double compilation" is just fine because it means you can compile to the exact hardware at the time of execution/shipping/etc for exactly the processor you want. The downside is that your language needs to be platform independent or you need bitcode for the various different platforms.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Android java change drawable image Alright so how when i click a button? it will change the a image to a different image
my xml of the image i want to change when button press:
<ImageView
android:id="@+id/bluebtn1"
android:src="@drawable/buttonblue"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginLeft="33dp"
android:layout_marginTop="140dp"></ImageView>
and here is my java code ill be doing when you press the button
case R.id.redbtn1:
if (lvl1.getText().equals("1")) {
lvl1.setText("2");
// Here is where the code goes to change the image
} else {
Toast.makeText(main.this, "YOU LOSE!", Toast.LENGTH_SHORT).show();
}
break;
A: Put this in your click listener.
ImageView blueBtn = (ImageView)findViewById(R.id.bluebtn1);
blueBtn.setImageResource(R.drawable.YOUR_NEWIMAGE);
This should work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: ObjectName incompatible with String FindBug error For my production code resembling the following:
public something xyz(String name) {
return getSomething(abc.get(name));
}
Where the method "get" expects javax.management.ObjectName to be passed to it, I am getting the following high priority warning from the Findbugs tool:
Bug: String is incompatible with expected argument type javax.management.ObjectName
Pattern id: GC_UNRELATED_TYPES, type: GC, category: CORRECTNESS
However, according to javax API docs, I see that one can have ObjectName as a String, as shown on: http://download.oracle.com/javase/6/docs/api/javax/management/ObjectName.html
Is this a problem with Findbugs or am I missing something?
A: public something xyz(String name) {
return getSomething(abc.get(new ObjectName(name)));
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Relative references to images inside a webview I have hundreds of HTML files in my assets/content1/htmls/ folder. Image sources referred to inside the HTML files are in the folder assets/content1/images/. In the HTML files, relative paths to the images are used (e.g. <img src="../images/1274.jpg" width="547" height="290" border="0"/>). But the images don't show up in the HTML files.
After researching other SO posts, I tried setting the BaseUrl to file:///android_asset/content1/ and replacing all the src="../images/" with src="images/ in the loadDataWithBaseUrl method. Even then, the images did not show up. Can anyone tell me why this is not working? How should relative URLs should be used in webview?
A: if you put your images on content1 folder then write like this in html file
<img src="file:///android_asset/content1/1.jpg" alt="" title="";"/>
if it is in images folder then
<img src="file:///android_asset/images/1274.jpg" alt="" title="";"/>
and it is working coz i have tried out this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How does the Spring know where to get the proxy object needs to get injected? To my impression, RmiProxyFactoryBean is supposed to produce a proxy object instance that is of type AccountService that will be injected to accountService property of SimpleObject instance in the following code.
What I do not understand is why does the XML file seem to instruct Spring to inject an object of RmiProxyFactoryBean type to accountService property of SimpleObject object instance? I'm expecting an explicit instruction from the XML file that tells the Spring how to get an AccountService instance from RmiProxyFactoryBean instance instead of injecting an RmiProxyFactoryBean instance. I find this confusing.
public class SimpleObject {
private AccountService accountService;
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
}
<bean class="example.SimpleObject">
<property name="accountService" ref="accountService"/>
</bean>
<bean id="accountService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl" value="rmi://HOST:1199/AccountService"/>
<property name="serviceInterface" value="example.AccountService"/>
</bean>
Source:
http://static.springsource.org/spring/docs/2.5.x/reference/remoting.html
(see 17.2.2.)
Thanks
A: Because Proxy Beans wrap the object in question, they pretend to be the interface that is being called (and then later actually call that interface).
The RmiProxyFactoryBean returns a proxy object so that when your code thinks it is calling a method on your example.AccountService class, it's actually being called on a bean with the same interface as your example.AccountService interface as specified here:
<bean id="accountService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
...
<property name="serviceInterface" value="example.AccountService"/>
</bean>
Say there was a method on the interface called example.AccountService.reconcile(Long amount) (just for sake of example)...
If you called this normally the method calling it would just push it into the stack. But if the example.AccountService object is returned from the RmiProxyFactoryBean as it is above, it will be wrapped in a proxy bean. This proxy bean has a method inside of it that is also named reconcile and also has an argument of Long amount, which makes it indistinguishable from the original example.AccountService bean which it wraps. This way the proxy bean can have code that it runs, before, after, or instead of the code that is in the actual example.AccountService.reconcile(Long amount) method.
Proxy beans come from a whole different way of programming called Aspect Oriented Programming (AOP) which deals with cross-cutting-concerns; i.e. code that doesn't clearly seem to fit within the confines of normal OOP separation of concerns. Some of these concerns are For instance, transaction demarcation, security, and logging.
It appears that you are doing this rather manually above, but it's sometimes easier to weave these in at runtime using SpringAOP which has a language for selecting and applying proxy beans to existing code.
However, take note to program to interfaces rather than to program to just classes.
A: A more succinct way of putting it is that the RmiProxyFactoryBean implements the FactoryBean interface. Implementing that interface instructs the Spring bean factory that this class is a factory itself, causing Spring to invoke the getObject() method on that class and return the result as the bean, rather than creating an instance of the class itself and returning.
So, short answer, it's a built-in mechanic of Spring.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How can I smooth my density curve so it has fewer peaks? How can I limit the number of "humps" I allow in my density curve. I just want a nice looking skewed bell curve type thing. But right now, my density almost just looks like a line graph of my data.
A: Look at the help for density. There are a variety of parameters you can try changing, like the bw argument.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: May I restrict zoom levels of MKMapView?
Possible Duplicate:
Is there way to limit MKMapView maximum zoom level?
May I restrict zoom levels of MKMapView, i.e., set max and min zoom levels of MKMapView?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Datetime picker transparent background out of the box? This is out of the box mvc3 stock grade plain vanilla jquery behavior? Is this default styling behavior? How do I make it NOT transparent? Thx!
<script src="../../Scripts/jquery-1.5.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.11.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.date').datepicker({ dateFormat: "dd/mm/yy" });
});
</script>
@Html.TextBox("xxx", "", new { @class = "date" })
A: I was using a custom theme, so the above suggestion wasnt ideal...
The fix was to add background color to this section
/* DatePicker Container */
.ui-datepicker {
width: 216px;
height: auto;
margin: 5px auto 0;
font: 9pt Arial, sans-serif;
-webkit-box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);
-moz-box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);
box-shadow: 0px 0px 10px 0px rgba(0, 0, 0, .5);
background-color: #FFF;
}
A: This will just work
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
A: My guess is you are indeed missing either the stylesheet or the images.
try adding CSS link to
http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/base/jquery-ui.css
A: I found that the files were there, but the BundleConfig.cs file had the file name wrong. The file name was "~/Content/themes/base/datepicker.css" but BundleConfig.cs had the file listed as "~/Content/themes/base/jquery.ui.datepicker.css".
A: Just Give the z-index style value for the input field a higher value and also make the position relative, i.e.,
position: relative; z-index: 10000;
It will work smoothly.
A: Add this code in style tab
.ui-datepicker { background: white; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: Git replication across several live servers I have a question about git repository replication across several live http servers
My goal was to create replication from my test server to the live http servers. So when I'd commit my changes on test, the changes should automatically appear also on server
I had a look at gerrit2 and it looks ok but I tried to do it with git, but since git uses post-commit hook I’m sure I’d be able to do it with that
So I tried doing multiple pushes in the hook after commit ( since overwriting seems to be only option because if I merged there’d a chance of conflicts and last thing I want to have on my live server are messed up files...) from test to live and firstly I got some odd errors, but then I added the force parameter and push succeeded but unfortunately the changes did not appear on remote server.
I was using ssh protocol to exchange data.
How to do it so it will be good and reliable? What is the set of commands I must execute?
A: As @Jefromi points out, it is not a good idea to push.
Instead, you can try to pull from the production server, by using a script that runs at regular interval (like each hour or each multiple of 5min). That way you will know when the servers will be updated.
But if you do any modifications on the server, the pull may fail because it will refuse to update a modified file. You can make the script to check if the working copy is dirty before doing the pull and send an e-mail to have someone to look at the server.
A: Alternatively you could setup a bare repo
(git init --bare)
and use a post receive hook to check it out and copy it into the published directory (hooks/post-receive)
GIT_REPO=$HOME/blah
TMP_GIT_CLONE=$HOME/tmp/tmpblah
PUBLIC_WWW=/srv/public_folder/
git clone $GIT_REPO $TMP_GIT_CLONE
mv $TMP_GIT_CLONE $PUBLIC_WWW
exit
This is how i manage the sites on my server i push to both my code repo (gitosis setup) and to a repo that checks out and deploys the changes to production
A simple feature improvement would be to add an incrementing value into your deploy script and deploy into a new folder each time and simply update a symlink to point to it
so a push today would go to 2011102900 the next to etc and a symlink would link current to whichever folder is newest (and be updated by the post_receive script)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Are files in the /public directory served via the rails stack? I'm using nginx + phusion, I believe in the rails docs it says that if I put page caching on, then a html file is created and put the /public folder.
Does this mean that the phusion service won't have to put the request through the rails stack?
How is the file served then, just by nginx alone?
A: Static assets are served directly by nginx, this includes page caches.
See bottom of: http://www.modrails.com/documentation.html
A: From the Rails Guides:
config.serve_static_assets configures Rails itself to serve static assets. Defaults to true, but in the production environment is turned off as the server software (e.g. Nginx or Apache) used to run the application should serve static assets instead.
The recommendation is not to turn this setting on in production. Let nginx serve it directly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Batch how to set FINDSTR result to a variable and disable findstr print to console My batch program
FINDSTR /C:"Result Comparison failure" %tmp_result_file%
I want to do the folloiwng , set the result of the above command to a variable.
If found, set the first line to varible or set the all found line to a varible is OK for me.
also the above commmand will print the findstr command to console even @echo off. is there any method to disable the print.
thanks a lot
part of my script, what i do is run command on every line in sourcefile and put the run result into a tmp file, then use find str to find the failed string to check the run result.
for /f %%a in (%source_file%) do (
echo run %%a >> %output_file%
call %run_script_command% %%a > %tmp_result_file% 2>&1
::notepad %tmp_result_file%
for /f %%i in ('FINDSTR /C:"Result Comparison failure" %tmp_result_file%') do echo %%ixxx
echo xx
)
very strange , the result is:
xx
Resultxxx
xx
the background is that i have two items in %source_file%, so the out for run 2 times.
for the first one, the FINDSTR can not find anything, so print xxx
for the second one, it find one in findstr , but only print "Result" instead of "Result Comparison failure", also the xx is print before it in result. Very Strange!
A: The first problem is because you just take the first token from FOR. To solve it, you have two solutions, either to echo the complete line where the string is found...
for /f "tokens=*" %%i in ('FINDSTR /C:"Result Comparison Failure" %tmp_result_file%') do echo %%i
or echo the three tokens found
for /f %%i in ('FINDSTR /C:"Result Comparison Failure" %tmp_result_file%') do echo %%i %%j %%k
the second problem, the xx echoed two times is because you run two times the command. The first xx is the one from the first run, the second one is from the second run. If you want to prevent the second one, you need to use some additional logic. For example, setting a variable and then checking it. Warning, setting a variable in a loop requires enabling delayed expansion and using the !xx! syntax (see HELP SET for a detailed explanation)
setlocal enabledelayedexpansion
...
set result=
for /f "tokens=*" %%i in ('FINDSTR /C:"Result Comparison Failure" %tmp_result_file%') do (
set result=%%i
)
if "!result!"=="" (
echo !result!
) else (
echo xx
)
A: Check out the FOR /F command.
for /f %i in ('FINDSTR /C:"Result Comparison failure" %tmp_result_file%') do ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: JSF2.0, How to load external resource bundle files? I currently have my properties files put inside my project folder, so if I change the content of those files while my web app is deployed, the JSF pages that use these resource bundle won't be able to get updated automatically unless the server is restarted. This is quite troublesome when you only make small changes yet resulting the whole server to restart in order for it to be updated.
As I understand when the project is deployed, my JSF pages will refer to those properties files that are on the web server(Weblogic 11 in this case). But there is another thing, I am unable to find the deployment folder of Weblogic, therefore I cannot locate my WAR file.
Btw, I am using Eclipse Helios to deploy my project.
Any help would be appreciated, many thanks in advance.
A: The resource bundles are being cached by JSF in order not to hit the disk, so even if you would know the actual deployment path, you would still need to redeploy the whole web application.
For this reason I use jrebel (yes, it's a commercial product) that is actually able to change the resource bundle implementation itself, so it rereads the file whenever it changes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to auto-stretch UISegmented Control horizontally to fill full UITableViewCell? How to auto-stretch UISegmented Control horizontally to fill full UITableViewCell? In a manner in which it will auto-resize after an orientation change too.
I have tried the following however this still doesn't work. The segmented control appears in the cell on the left, but does not stretch itself across horizontally.
NSArray *itemArray = [NSArray arrayWithObjects: @"Feet", @"Metric", nil];
UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:itemArray];
segmentedControl.selectedSegmentIndex = [self.config.isMetric boolValue] ? 1 : 0;
segmentedControl.contentMode = UIViewContentModeScaleToFill;
[cell.contentView addSubview:segmentedControl];
cell.contentView.contentMode = UIViewContentModeScaleToFill;
[segmentedControl release];
A: You would need to set the frame for the UISegmentedControl which in your case would be the same as the cell's frame.
segmentedControl.frame = cell.frame;
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Got the PHP include path blues. Quick and easy bootstrap? I am fairly far into a project, and am having trouble having everything included properly.
I have several files in different directories that need to include the same files, but since some are called via ajax or via includes in different situations, there path varies. I had a php_include path set up via .htaccess, but the testing server I need things set up doesn't run with php commands in the .htaccess! I am trying to figure out a quick way of roping everything together.
I have multiple files all including the same 'project' file that in turn includes functions, etc. I have a $ROOT variable set-up to store the absolute path of my directories, but that's not usable in includes without mucking with the php.ini, which I can't do easily, and it's included afterwards anyway.
I know a little bit about bootstrapping, and I would love to route everything through htaccess, but I don't really have a concept of how to implement something like that really quickly and easily (and would that work for files called through ajax?)
I can't rely on server_document_root because it may need to reside in a subdirectory.
This is not class based, but has value objects for database stuff.. there's the main home.php, view.php etc in the root directory, then a program/ directory with the main scripts and value objects, then utilities and components folders that contain miniature view type classes.
I would redo everything if I had time, but right now I'm trying to figure out a way to have everything just work (preferably without dumping everything into one folder :p)
A: In home.php, or view.php include your "main" file, this will include the rest of your app.
require 'base.php';
Its ok if home.php or view.php are in some other directory, just do whatever you need to do in that file to load base.php something like this will work the same:
require '../base.php';
Then in base.php
$root = dirname(__FILE__);
require $root.'/lib/mylib1.php';
require $root.'/lib/mylib2.php';
The __FILE__ is the full path to the current file, dirname gets its directory, then you can write all of your includes/requires relative to the location of base.php.
I hope this helps point you in a helpful direction.
A: A simple solution for this could be to use a variable set before the file is included. You can then check if this variable is defined, and if it isn't use the path for ajax, instead of the include path.
$included = true;
include("ajax_inc.php");
Assuming your main files are in / and your ajax files are in /ajax:
if (isset($included)) {
$path = "/";
} else $path = "../";
You could also do some checks with getcwd() and chdir()
http://php.net/manual/en/function.getcwd.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VB.Net application can't connect to local MySQL but I can connect from command We have a VB.Net application which works fine in our tests in different Windows XP SP3 machines. However there is one machine in which is displaying this error:
Unable to connect to any of the specified MySQL hosts
Using the mysql command, we can successfully connect to the database. We already checked for any other application or firewall that could be blocking the connection but it seems fine. We also reinstalled the system (no errors during the installation) but the MySQL error message doesn't change.
The system settings are exactly the same as in the other computers. We are using "localhost" as server in the connection string. The "hosts" file has its default values (nothing strange in there).
Does anyone have a similar experience and can point me in the right direction?
A: It took me more than an hour to figure it out... I was trying to see if there was something wrong in the network configuration. So I issue:
netstat -na
And it gave me some clues: Comparing it with the other computers (that work fine), I found a difference:
NOT WORKING:
Proto Local Address Foreign Address State
TCP [::]:3306 [::]:0 LISTENING 0
WORKING:
Proto Local Address Foreign Address State
TCP 127.0.0.1:3306 127.0.0.1:0 LISTENING
So, what is "[::]" and why is that zero to the right?
ANSWER:
I found out that "[::]" means 127.0.0.1 in IPv6 (about the zero, I have no idea).
So I checked the TCP/IP settings in the computer that was not working and "TCP/IP IPv6" was installed (which the working ones didn't have). I uninstalled it, restarted and voila! It worked! :)
Perhaps some network card installers add IPv6 automatically? Whatever the reason was, that was the problem.
To prevent it in the future, and for simplification, we can issue the command:
> ipv6 uninstall
and it will remove it automatically.
A more elegant way to solve the problem will be to implement the IPv6 support within the VB.net system (which I think it is explained here) but that will be done later.
My guess is that MySQL 5.5 is IPv6 aware by default? I didn't find any way to change that in the settings nor any report of this kind of problem.
I hope this helps to other people with the same problem.
Now I can go to rest...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: dotted line span between word and image html problem Below i have hardcoded dotted lines on my menu between the name and image, I cant figure out how to get dotted lines that adjust to the width between where i have them now.
This is the code below that i have. I basically want to remove the hardcoded ..... and make it better somehow with a repeated image inside or just something easier, how can i approach this? I have been boggled with this problem for some time now...
<script type="text/javascript">
$(document).ready(function(){
$('.serviceDesc').hide();
$('.serviceName:first').addClass('active').next().show();
$('.serviceName').click(function(){
if( $(this).next().is(':hidden') ) {
$('.serviceName').removeClass('active').next().slideUp();
$(this).toggleClass('active').next().slideDown();
}
return false;
});
});
</script>
<style>
#servicesContainer {
width: 485px;
height: 400px;
margin: 0 auto;
margin-top: 20px;
}
h2.serviceName {
margin: 0;
margin-bottom: 5px;
margin-top: 5px;
background-image: url(http://i.imgur.com/IcnZl.png);
background-position: right top;
background-repeat:no-repeat;
height: 29px;
line-height: 24px;
width: 480px;
font-size: 18px;
font-weight: bold;
float: left;
color:#000;
}
h2.serviceName a {
color: #000;
text-decoration: none;
display: block;
}
h2.active {
background-position: right bottom;
}
.serviceDesc {
margin: 0 0 10px;
padding: 0;
overflow: hidden;
width: 480px;
clear: both;
}
.serviceDesc .block {
}
.serviceDesc .block p {
color: #413f44;
margin: 0;
font-size:18px;
}
</style>
<div id="servicesContainer">
<h2 class="serviceName"><a href="#">Text...............................................................................</a></h2>
<div class="serviceDesc">
<div class="block">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. </p>
</div>
</div>
<h2 class="serviceName"><a href="#">Text...............................................................................</a></h2>
<div class="serviceDesc">
<div class="block">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.</p>
</div>
</div>
<h2 class="serviceName"><a href="#">Text...............................................................................</a></h2>
<div class="serviceDesc">
<div class="block">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.<br />
<br />
</p>
</div>
</div>
<h2 class="serviceName"><a href="#">Text...............................................................................</a></h2>
<div class="serviceDesc">
<div class="block">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.</p>
</div>
</div>
<h2 class="serviceName"><a href="#">Text...............................................................................</a></h2>
<div class="serviceDesc">
<div class="block">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. </p>
</div>
</div>
<h2 class="serviceName"><a href="#">Text...............................................................................<br />
</a></h2>
<div class="serviceDesc">
<div class="block">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud. </p>
</div>
</div>
<h2 class="serviceName"><a href="#">Text...............................................................................</a></h2>
<div class="serviceDesc">
<div class="block">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.</p>
</div>
</div>
<h2 class="serviceName"><a href="#">Text...............................................................................</a></h2>
<div class="serviceDesc">
<div class="block">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud.</p>
</div>
</div>
</div>
You can view an example here:
http://jsfiddle.net/K7MHK/
A: creating a with a repeated by x background image of a dot would be the easiest way.
However you would need to set the element it is in to width:100% or whichever width you want it at.
eg.
<html>
<head>
<style>
.filler{
background: url(dot.png) bottom left repeat-x;
float:left;
width:80%;
}
.floating_text {
float:left;
}
</style>
</head>
<body>
<h2 class="serviceName"><a href="#">
<span class="floating_text">Text</span>
<span class="filler"> </span>
</a></h2>
</body>
</html>
The span appears to hook into the <h2></h2> height and not the <a></a> height, this is what is causing the problem with it appearing on two lines.
The reason the dots appear to be in the middle of the span in your example is because of your image, remove the white at the bottom and it will appear as normal.
A: I feel as though there is a better way to do this, but it is escaping me. Hopefully this helps someone on to a robust answer though. I only did it for the first list item.
http://jsfiddle.net/K7MHK/1/
I use the css border-bottom property to create the dotted line on an element. The question then was - how do you get two elements side-by-side. One to contain the text and the other to contain the dots. The caveat being the dots need to take up the rest of the space. I couldn't figure out a good way.
So instead I made the dots go all the way across, but put the text in a absolutely positioned div. This allows it to float over and hide the dots.
/* set h2 to relative so that we can absolutely position an element inside of it */
/* Give it padding so that dots don't intersect the image*/
h2.serviceName {
padding-right: 50px;
position: relative;
/* absolutely position div to cover dots and give it bg that matches */
div#a { position: absolute; top: 0; left: 0; background: white; }
/* modify the height property here to adjust the location of the dots*/
div#b {
width: 100%;
border-bottom: 1px dotted red;
height: 18px;
}
So things that could make this better:
*
*Don't rely on absolutely positioned div
*Perhaps use line-height? to position text so that you don't have to manually adjust dots location.
A: Okay - another answer after I learned asker can't have elements actually on top of each other. This is because he has a background that needs to show through. After quite a bit of research on SO I found that two dynamically side-by-side divs cannot be made to fill a fixed width. So instead you need to rely on a table.
http://jsfiddle.net/K7MHK/6/
//html
<h2 class="serviceName"><a href="#">
<table>
<tr>
<td>Text of Variable Length</td>
<td><div></div></td>
</tr>
</table>
</a>
</h2>
So instead we use a table which is good at this. The right hand cell autoexpands. Inside we place a div that takes the dotted css border property. We then adjust the position of the dots through the divs height.
table { width: 440px; }
table td { white-space: nowrap; }
table td:last-child { width: 100%; }
table td:last-child div { width: 100%; border-bottom: 2px dotted black; height: 15px; }
A: I would set the css of the a-tag to
h2.serviceName a {
color: #000;
text-decoration: none;
display: block;
overflow: hidden;
margin-right: 45px;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can call Activity from JavascriptInterface in Android? I am new to phonegap and my project, I need to call an activity from
the javascript in the html page, is it possible?
public void capturePhoto() {
JavascriptInterface.this.runOnUiThread(new Runnable() {
@Override
public void run() {
try{
Intent i = new Intent(JavascriptInterface.this, GetPicture.class);
startActivity(i);
}catch(Exception e){
Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
A: I'm not that familiar with web programming on android or with the javascript interfaces, so I don't know if it's possible to launch an arbitrary intent with those.
However, I assume that you have some way to simply open a link. And if you find out that it's not possible to launch an activity otherwise, you can still get something working, using a custom URI scheme.
Basically, the idea is that you add an intent filter to the activity that you want to launch that registers a custom URI scheme for that activity. And then when you try to open a link using that scheme, Android will map that to an android.intent.action.VIEW intent for your activity.
For example, If you have the following in the intent filter for the activity that you want to launch:
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="penroser"/>
</intent-filter>
You could then launch a URL like penroser:BLAH, and it should actually launch your activity.
However, the above assumes that you are able to add an intent filter to the activity that you want to launch. However, if you want to launch a more general intent, or launch an activity that you don't control, it makes things a bit more complicated.
In this case, you could define a "spring-board" activity, whose purpose is to receive the custom URI intents, and then decode some intent information using some format that you define, and then launch an intent based on that decoded information.
For example, let's say that you register the custom URI scheme launchactivity:, and then you could launch a link like: launchactivity://activity?component=com.example.MyActivity, and then have some parsing logic in the spring-board Activity that parses out the component name from the URI and launches an intent for that component.
Depending on exactly what you needed, you should be able to pass any intent data you need in a launchactivity: URL
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to move a textview up so the keyboard doesn't block it I have several text views within a scroll view. I need some help with having the scroll view move up so the keyboard doesn't block the text view.
A: You can scroll the view to based on the textview rect so that it will be visible if the the keyboard pops up.
Try this when textview is ready for editing
-(void) textViewDidBeginEditing:(UITextView *)textView {
CGPoint pt;
CGRect rc = [textView bounds];
rc = [textView convertRect:rc toView:scrollView];
pt = rc.origin;
pt.x = 0;
pt.y -= 60;
[scrollView setContentOffset:pt animated:YES];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parsing a tab delimited file into separate lists or strings I am trying to take a tab delimited file with two columns, Name and Age, which reads in as this:
'Name\tAge\nMark\t32\nMatt\t29\nJohn\t67\nJason\t45\nMatt\t12\nFrank\t11\nFrank\t34\nFrank\t65\nFrank\t78\n'
And simply create two lists, one with names (called names, without heading) and one with the ages (called ages, but without ages in the list).
A: I would use the split and splitlines methods of strings:
names = []
ages = []
for name_age in input.splitlines():
name, age = name_age.strip().split("\t")
names.append(name)
ages.append(age)
If you were parsing a more complex format, I would suggest using the csv module, which can also handle tsv… But it seems like it would be a bit overkill here.
A: Using the csv module, you might do something like this:
import csv
names=[]
ages=[]
with open('data.csv','r') as f:
next(f) # skip headings
reader=csv.reader(f,delimiter='\t')
for name,age in reader:
names.append(name)
ages.append(age)
print(names)
# ('Mark', 'Matt', 'John', 'Jason', 'Matt', 'Frank', 'Frank', 'Frank', 'Frank')
print(ages)
# ('32', '29', '67', '45', '12', '11', '34', '65', '78')
A: Unutbu's answer compressed using a list comprehension:
names = [x[0] for x in csv.reader(open(filename,'r'),delimiter='\t')]
ages = [x[1] for x in csv.reader(open(filename,'r'),delimiter='\t')]
A: tab delimited data is within the domain of the csv module:
>>> corpus = 'Name\tAge\nMark\t32\nMatt\t29\nJohn\t67\nJason\t45\nMatt\t12\nFrank\t11\nFrank\t34\nFrank\t65\nFrank\t78\n'
>>> import StringIO
>>> infile = StringIO.StringIO(corpus)
pretend infile was just a regular file...
>>> import csv
>>> r = csv.DictReader(infile,
... dialect=csv.Sniffer().sniff(infile.read(1000)))
>>> infile.seek(0)
you don't even have to tell the csv module about the headings and the delimiter format, it'll figure it out on its own
>>> names, ages = [],[]
>>> for row in r:
... names.append(row['Name'])
... ages.append(row['Age'])
...
>>> names
['Mark', 'Matt', 'John', 'Jason', 'Matt', 'Frank', 'Frank', 'Frank', 'Frank']
>>> ages
['32', '29', '67', '45', '12', '11', '34', '65', '78']
>>>
A: marvin's answer but without reading the entire file twice
data = [ (x[0],x[1]) for x in csv.reader(open(filename,'r'),delimiter='\t')]
If you are ok with it being of tuples, instead of two lists
you could still read data into two lists in a single pass and that would be unubtu's answer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Are there compiler options to minimize file size of binary for Opa web (or "cloud") apps? I have the simplest "Hello, web" web app written in Opa (see one line of code below):
server = one_page_server("Hello", -> <>Hello, web!</>)
I then compile this file (in my case named hello.opa) like so:
opa hello.opa
This generates a file hello.exe which is ~35Mb in size. I realize Opa packages a big punch in the binary, but is there anyway to get the size of the resulting binary file down if our app isn't utilizing all the its neat features? If so, how? I reviewed the options printed on opa --help, but did not see anything that appeared pertinent to this query.
Information about my environment:
*
*Operating system: OS X/10.7 (Lion)
*Opa version: S3.5 -- build 652
Appreciate any input.
Updated: @Bill mentioned using strip. I ran strip on the hello.exe binary file and it brought it down to 25Mb. Excellent suggestion (I had forgotten about strip) though I was hoping for something still smaller.
A: You should try upx and compare the result size with the one produced by strip. 7.3M on my Mac for this hello.opa.
You can use MacPort on your Mac to install it: sudo port install upx
Note that we have made a big website ( http://jetleague.com/ ) with OPA. I've checked on the server, and the binary is only 13M (upx-ed).
Don't forget that their is everything inside this binary. You can run it on any fresh server without any extra-installation (like Apache, Mysql, PHP modules...).
If you need to update your server, you can use rsync for fast updates.
A: Not specific to opa, but did you try plain old strip?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mathematica integral evaluation just shows up as nicely formatted text? Attempting the following exponential integral:
Integrate[ Exp[-2 A Sqrt[x^2 + a^2] + I ( x Subscript[k, x] + b )],
{x, 0, Infinity}
]
I get back something that is pretty printed, but not evaluated? Does this mean that Mathematica could not perform the integral and gave up? I don't see any messages saying that's what happened.
To provide context for this question, this is a stripped down to one dimension version of the integral I'd done with paper and pencil:
\int d^3 r e^{ i \vec{k} \cdot \vec{r} } e^{ - 2 Z r/ a_0 }
The point of trying mathematica was to see if I could verify my result:
16 \pi Z a_0^3/(4 Z^2 + k^2 a_0^2)^2
A: Correct, when Mathematica spits the integral back out it usually means it doesn't know how to do it. Sometimes, it can only do the integral under certain assumptions (such as `a > 0' and real), but it will usually give the answer as a gigantic if-statement with those.
This particular integral you have is not trivial at all. And it doesn't fit the form of any of the special functions that I'm familiar with. So it's possible that it can't be expressed in closed form in terms of the special functions that Mathematica has.
Also, what's the point of the Subscript[k, x]? I tried removing it and Mathematica still can't do the integral.
A: With a simple change of variables the 'simple' case Exp[-2 A Sqrt[a^2 + x^2] yields besselfunctions:
Integrate[Exp[-2*A*Sqrt[a^2 + x^2]]*Dt[x] /. x -> Sqrt[t^2 - a^2] /. Dt -> (1 & ), {t, a, Infinity}, Assumptions -> a > 0 < A]
to get
a*(-BesselK[0, 2*a*A] + BesselK[1, 2*a*A])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Rails3 - Need route to a method that increments a counter Ok, I have a simple question. I am new to RoR and I created a scaffold for an item. I then wanted to add a link that, when pressed, incremented a counter. What I am having trouble with is routing. I modeled this functionality after the destroy/delete link and method. Here is my code:
index.html.erb:
...
<td><%= link_to 'Destroy', post, method: :delete %></td>
<td><%= link_to 'increment', post, method: :increment%></td>
...
post_controller.rb:
def vote
@post = Post.find(params[:id])
@post.counts = @post.counts + 1
@post.save
respond_to do |format|
format.html { redirect_to post_url }
format.json { head :ok }
end
end
When I try and click on the link, I get a routing error:
Routing Error
No route matches [POST] "/posts/25"
is there a step I am missing? Do I have to add some routing stuff to get this working?
A: Ok, hang in here with me, there's a few fixes needed:
The :method param in the link_to function is not referring to the controller method, it is referring to the HTTP method. So acceptable values would be ':post', ':delete' etc.
More info: http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
In this case we probably want to set :method to :post for the increment link, which we will need to match with the route we will create now.
To access the vote action you have created, we need to add it to the routes file. You probably have something like this:
resources :posts
We need to add an action (vote), that will apply to a member of the posts resource, so we change that to this:
resources :posts do
member do
post 'vote'
end
end
Now that we have the correct route, we can use the route helper method in the link_to helper (to see a full list of routes run rake routes at the command line). So in your link_to replace post with vote_post_path(post). If we include our earlier change about the :method we get:
<%= link_to 'increment', vote_post_path(post), method: :post %>
Hope this helps to fill in some blanks for you!
A: I am going to assume that you haven't added posts as a resource to your config/routes.rb file. Try adding this line:
map.resources :posts
You might have to restart the server after you make the change.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What part of the computer renders text? Hardware or Software? For example, if i make a very simple bootloader that runs a "hello world" program (as the operating system), where is the graphical representation of the text processed. The the GPU render the text, or the the hardware. Is basic text input and output hard-coded in either the BIOS or processor, or is it integrated in assembly/programming langauge?
A: In PC land, there's a character generator in the video subsystem. Takes the 8-bit character values out of video RAM, uses the character definition matrices (which can either be in ROM, or pointed to ones in RAM for custom character sets) and generates the display. This only applies to pure text mode. Graphical mode is a completely different animal in regards to video RAM layout (and also starts to involve the GPU, etc).
A: The GPU can be in the processor or in the discrete card or even the motherboard. Basic I/O is done via the framebuffer in whatever handles it and is memory mapped by the BIOS usually to 0xb8000. To get simple I/O you just write the ascii characters to the framebuffer and the card will just output them to the screen (in a basic OS like you said).
It can be accomplished in any low level language that allows you to directly address memory values and can be compiled into native code.
For text you see on your screen (like this text) that's typically software's job as there are fonts, styles and other things to deal with. This is usually handled via basic API's exported by the operating system that allow screen drawing or by the drivers themselves.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Named pipes and can they stream data? I asked a previous question here:
Stream video from ffmpeg and capture with OpenCV
and I want to know more about named pipes in general. Can I use named pipes to stream data? For example, can I continuously add data to the pipe (via ffmpeg) in conjunction with reading data with another application? Or is there another method to do this?
A: you can check this stackoverflow link and have a look at ffmpeg documentation on pipe section
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Split specific string by regular expression i am trying to get an array that contain of aaaaa,bbbbb,ccccc as split output below.
a_string = "aaaaa[x]bbbbb,ccccc";
split_output a_string.split.split(%r{[,|........]+})
what supposed i put as replacement of ........ ?
A: No need for a regex when it's just a literal:
irb(main):001:0> a_string = "aaaaa[x]bbbbb"
irb(main):002:0> a_string.split "[x]"
=> ["aaaaa", "bbbbb"]
If you want to split by "open bracket...anything...close bracket" then:
irb(main):003:0> a_string.split /\[.+?\]/
=> ["aaaaa", "bbbbb"]
Edit: I'm still not sure what your criteria is, but let's guess that what you are really doing is looking for runs of 2-or-more of the same character:
irb(main):001:0> a_string = "aaaaa[x]bbbbb,ccccc"
=> "aaaaa[x]bbbbb,ccccc"
irb(main):002:0> a_string.scan(/((.)\2+)/).map(&:first)
=> ["aaaaa", "bbbbb", "ccccc"]
Edit 2: If you want to split by either the of the literal strings "," or "[x]" then:
irb(main):003:0> a_string.split /,|\[x\]/
=> ["aaaaa", "bbbbb", "ccccc"]
The | part of the regular expression allows expressions on either side to match, and the backslashes are needed since otherwise the characters [ and ] have special meaning. (If you tried to split by /,|[x]/ then it would split on either a comma or an x character.)
A: no regex needed, just use "[x]"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Joomla 1.6 Auto Hyperlink Image to full Article I'm trying to have the first image on an article automatically link to the full article (similar to how wordpress 3.x works). This should work on Frontpage as well as Blog layout.
Basically I'm looking for a plugin like http://extensions.joomla.org/extensions/news-display/articles-summary/7233 but is compatible with Joomla 1.6. Any help would be much appreciated thanks.
A: Have you tried to use CM Auto Read More for Joomla 1.6/1.7?
Here is a link to the developer's demo page:
http://demo.masterswebsitedesign.com/cmautoreadmore/
Here is the JED entry link:
http://extensions.joomla.org/extensions/news-display/articles-summary/17979
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get current object in function? I'm trying to code a simple UITextField and I have a simple question:
Im using this to 'empty' the UITextField:
-(IBAction)editbegin{
campo1.text="";
}
The problem is: want to use this function in more than one TextField. So, how can I 'grab' the object, so I can get the 'text'? Already tried 'self.text', but it returns the view.
Thanks.
A: Check out the UITextField documentation. It looks like you are trying to "reinvent" the wheel.
If all you want to do is clear the textfield once a user begins editing, there is a function for that.
When creating your text field, just set:
textField.clearsOnBeginEditing = YES;
The same option is also available on Interface Builder if that's what you are using.
Specific documentation link here http://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UITextField_Class/Reference/UITextField.html#//apple_ref/occ/instp/UITextField/clearsOnBeginEditing
A: Include the "sender" property.
-(IBAction)editbegin:(id)sender{
sender.text=@"";
}
Edit: Apparently you need to cast it? I thought you could send any message to id. I guess this is better code, anyway.
-(IBAction)editbegin:(id)sender{
UITextField *field = (UITextField *)sender;
field.text=@"";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Debugging native/managed C++ in VS 2010 with NUnit Is there a way to set breakpoints and step through them using NUnit with a mixed project of native C++ and managed C++?
I have my SUT (Software Under Test) configured as a static library (native C++)
I have my unit test suite as a separate project configured as a dll that depends on my previously stated library. I also added said library as a reference to my unit test project.
My tests run fine in NUnit, breakpoints just don't work.
Again, is there a way to get the breakpoints to work with NUnit with Native/Managed C++?
A: The most convenient way to do this is to set up a custom tool entry specifying the path to NUnit as the command. For a VS2003 C# project, you can use $(TargetPath) for the arguments and $(TargetDir) for the initial directory.
With Visual Studio VS2005 this becomes a bit harder, because that release changed the meaning of the 'Target' macros so they now point to the intermediate 'obj' directories rather than the final output in one of the 'bin' directories. Here are some alternatives that work in both versions:
$(ProjectDir)$(ProjectFileName) to open the VS Project rather than the assembly. If you use this approach, be sure to rename your config file accordingly and put it in the same directory as the VS project file.
$(ProjectDir)bin/Debug/$(TargetName)$(TargetExt) to run the assembly directly. Note that this requires hard-coding part of the path, including the configuration.
If you would like to debug your tests, use the Visual Studio Debug | Processes… menu item to attach to NUnit after starting it and set breakpoints in your test code as desired before running the tests.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Trying to Add Resource in Visual Studio 2010 Pro SP1 results in "The operation could not be completed. Unspecified error" message with C++ project I'm using Windows XP Professional SP3 and recently switched to Visual Studio 2010 Professional SP1 to work on a C++ project.
If I try to right-click on a project inside Solution Explorer and select "Add" >> "Resource...", I get this error popup window:
"The operation could not be completed. Unspecified error"
And then the only option is to click "OK".
Anyone else encountered this?
A: I had this same problem.
Right clicking on the project, selecting Unload Project, then right clicking again and clicking Reload Project fixed it.
A: So I'm not 100% sure of the exact reason for this, but it had something to do with the Code Browsing Info DB that I had disabled to speed up VS2010. Seems VS won't allow entering the Add Resource wizard if the Code Browsing Info DB is disabled.
Still with the DB re-enabled I got the hanging "Please wait while 'Resource Script Wizard' prepares to start. Click Cancel to end 'Resource Script Wizard'" prompt. Not sure how it finally disappeared, but I had to do a reboot and did close my Outlook mail client after the reboot while doing a couple more trials. Not sure if it has anything to do, but after that I was able to enter the Add Resource Wizard.
Maybe the good old Microsoft-style troubleshooting reboots still works after all these years.
A: In my case, it was cause by Google Recaptcha control.
I'd generate ressource after my page was completed so he catch my recaptcha Control but added a weird tag in his XML document.
Here is what I propose to you, open your resources file using XML editor and check out if there is not a weird tags which is widely different than other one. Maybe for me it's recatpcha, but maybe for you it's another third party.
Check out mine what it looks like :
<!-- OTHER TAGS --->
<data name="aControlResource1.ToolTip" xml:space="preserve">
<value />
</data>
<!--
THIS IS THE NASTY TAGS ... REMOVING IT MAKE IT WORKS PERFECTLY.
-->
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="recaptchaResource1.ErrorMessage" type="System.Resources.ResXNullRef, System.Windows.Forms">
<value />
</data>
<data name="anotherControlResource1.ToolTip" xml:space="preserve">
<value />
</data>
<!-- OTHER TAGS -->
A: Yes i had same problem, the solution its simple, you should close resource file then u can insert another image resource, Visual Studio cant add ids to bitmap while the file steel open "resource.h"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can't cast char array into int value in C# I am making a caesar cipher and am trying to convert the char value of each letter into an int so the shift value can change it.
for (int i = 0; i < plainTextInput.Length; ++i)
{
chars[i] = ((int)chars[i]) + shiftAmount;
}
It says it cannot convert int into char. How do i fix this problem?
A: You have to explicitly cast it back:
for (int i = 0; i < plainTextInput.Length; ++i)
{
chars[i] = (char)(((int)chars[i]) + shiftAmount);
}
However, you're going to run into trouble pretty quickly once you shift past z.
A: By explicitly casting:
chars[i] = (char)(((int)chars[i]) + shiftAmount);
I'd rewrite your loop:
var enciphered = chars.Select(c => (char)((int)c + shiftAmount)).ToArray();
What are you planning to do if you shift to a non-printable character? Standard Caesar cipher wraps around. You should incorporate that.
A: When I compile that code, I get the following error message:
Cannot implicitly convert type 'int' to 'char'. An explicit conversion
exists (are you missing a cast?)
Why yes, you are missing a cast:
chars[i] = (char)(((int)chars[i]) + shiftAmount);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Whats the point of the ObjectDataSource Given that every grid, combobox, checkboxlist and in general multi row control supports binding directly to any IEnumerable what is the point of the ObjectDataSource?
Why would one use it as opposed to binding directly to your collection? Particularly if you already have reasonable separation of concerns in your business, presentation and data layers?
I also feel this is an even more relevant question since the introduction of LINQ. I have often found that when binding I would like to perform some further ordering, exclusion and so forth using LINQ and I believe this is not possible when using the ObjectDataSource without creating a specific method for your (potentially single use case)?
So when is it appropriate to use an ObjectDataSource and what are the advantages compared to direct binding to IEnumerable?
A: First, ObjectDataSource is usually used in ASP.NET WebForms (aspx). ObjectDataSource is located in System.Web.UI.WebControls, as you can see this link on MSDN Library:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.objectdatasource.aspx
Using ObjectDataSource to bind your data means you bind you'll have datasource as an object, can be in form of DataSet or any other .NET object that implements IEnumerable. Using ObjectDataSource means you have to perform your own Select, Update, Insert and Delete method that usually found in SqlDataSource.
There's this nice walkthrough in MSDN Library: Walkthrough: Data Binding to a Custom Business Object
But binding to a simple IEnumerable without implementing IListSource (like DataTable has) means you won't have nice feature such as data bindings to a complex data control such as GridView. And you'll lose other feature too, because a simple IEnumerable alone can't be bound in two ways to other list control such as ListView and GridView.
To have your data to be bindable two way, your object must also implement INotifyPropertyChanged interface before added into the IListSource as data item.
Samples:
public class Employee : BusinessObjectBase
{
private string _id;
private string _name;
private Decimal parkingId;
public Employee() : this(string.Empty, 0) {}
public Employee(string name) : this(name, 0) {}
public Employee(string name, Decimal parkingId) : base()
{
this._id = System.Guid.NewGuid().ToString();
// Set values
this.Name = name;
this.ParkingID = parkingId;
}
public string ID
{
get { return _id; }
}
const string NAME = "Name";
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
// Raise the PropertyChanged event.
OnPropertyChanged(NAME);
}
}
}
const string PARKING_ID = "Salary";
public Decimal ParkingID
{
get { return parkingId; }
set
{
if (parkingId != value)
{
parkingId = value;
// Raise the PropertyChanged event.
OnPropertyChanged(PARKING_ID);
}
}
}
}
This is the implementation of INotifyPropertyChanged:
public class BusinessObjectBase : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
private void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (null != PropertyChanged)
{
PropertyChanged(this, e);
}
}
#endregion
}
A: You can bind to an enum with it if you dont want codebehind.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Magento: Single Quotes in Translation Files Void Translation I am trying to translate some strings from a Magento 1.5.x install and it works fine when there is a double quote, but I cannot properly escape single quotes.
"Hello, <strong>\'.Mage::getSingleton(\'customer/session\')->getCustomer()->getName().\'!</strong>","Hello, <strong>\'.Mage::getSingleton(\'customer/session\')->getCustomer()->getName().\'!</strong>","Olá, <strong>\'.Mage::getSingleton(\'customer/session\')->getCustomer()->getName().\'!</strong>"
"<button class=""form-button"" onclick=""setLocation(\'%s\')"" type=""button""><span>Login or Register</span></button>","<button class=""form-button"" onclick=""setLocation(\'%s\')"" type=""button""><span>Login ou Cadastro</span></button>"
I've tried the original string as is, and escaped with a backslash. I've tried the translated string escaped with a backslash and double single quotes.
I tried searching the magento forum, but the only two people that posted about this problem got no replies.
A: Try this
Other option is that you can put error message in double quotes as
__("Please specify the product's option(s).");
and in translation file you make it by simple this
Colum ONE | Colum Two
Please specify the product's option(s). | TRANSLATION OF that FILE
remove \ from Translation file and from code make it DOUBLE QUOTES in stead of single quote.
A: When you escape a single-quote with a backslash in the .phtml file, you need to remove the backslash from the translation string in the .csv file.
Example:
<?php echo $this->__('Click <a href="%s" onclick="this.target=\'_blank\'">here to print</a> a copy of your order confirmation.', $this->getPrintUrl())
Should be in .csv file:
"Click <a href=""%s"" onclick=""this.target='_blank'"">here to print</a> a copy of your order confirmation.", "Click <a href=""%s"" onclick=""this.target='_blank'"">here to print</a> a copy of your order confirmation."
without the backslashes, otherwise the string won't get translated. As usual double-quotes in the .csv have to be escaped with another double-quotes.
Some .csv translation files in Magento 1.7.0.2 still have these backslashes before single-quotes, which is a minor bug that needs to be fixed.
A: It turns out that the way the strings were being output in PHP were not compatible with Magento's translation engine. The fix comprised changes in the PHP file, not in the syntax of the translation files. The PHP files now read:
echo $this->__('Hello') . ', <strong>'.Mage::getSingleton('customer/session')->getCustomer()->getName().'!</strong>';
echo ('<button class="form-button" onclick="setLocation(\'' . $this->getUrl('customer/account/login') . '\')" type="button"><span>') . $this->__('Login or Register') . '</span></button>';
as opposed to having everything inside one echo $this->__('String to be translated . phpcode. String to be translated . phpcode . etc . etc')
A: You should never put html in a translated string. Magento uses vsprintf (http://php.net/manual/en/function.vsprintf.php) so it's easy to add a variable to a translation like this:
echo '<strong>'.$this->__('Hello %s!',Mage::getSingleton('customer/session')->getCustomer()->getName()).'</strong>';
In this way you can then translate easily in a csv: "Hello %s","Hola %s"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: [ios develop]Why does ipad2 camera not full screen? I am using UIImagePickerController to take photo.The process is :
*
*start a view with some controls.
*addsubview on current view:
self.claim.view.frame = CGRectMake(0, 0, 1024, 50);
[self.view addSubview self.claim.view];
3.there is a Button in self.claim.view to start camera and it does start, but the problem is:the vision is only shows in the view area( 0, 0, 1024, 50 ),I can't see anything clear through the camera,why doesn't it fill the screen ?I try several ways but doesn't work.
My tries:
1. set property cameraOverlayView(manual said this property set a view to overlay the preview view.)
2. when press the button add another subview with frame(0,0,1024,768), and in new view delegate method*(void)viewDidAppear:(BOOL)animated**start the camera.
neither of them is helpful.Is there any possible way to make the camera full screen?
A: I had a similar issue before. It could be the view controller that you're doing your
[self presentViewController:imagePicker animated:YES completion:nil];
instead try to instantiate the imagePicker in another view controller and dismiss the current view controller. Hope this help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Everyday GC is running on same time In my server everyday 3:00AM GC is running and Heapspace is filling in a flash.
This causing site outage. ANY inputs?
following are my JVM settings.I am using JBOSS server.
-Dprogram.name=run.sh -server -Xms1524m -Xmx1524m -Dsun.rmi.dgc.client.gcInterval=3600000 -Dsun.rmi.dgc.server.gcInterval=3600000 -XX:NewSize=512m -XX:MaxNewSize=512m -Djava.net.preferIPv4Stack=true -XX:MaxPermSize=512m -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -Djavax.net.ssl.trustStorePassword=changeit -Dcom.sun.management.jmxremote.port=8888 -Djava.rmi.server.hostname=192.168.100.140 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote
Any suggestions really helpful..
A: (This turned out somewhat long; there is an actual suggestion for a fix at the end.)
Very very briefly, garbage collection when you use -XX:+UseConcMarkSweepGC works like this:
All objects are allocated in the so-called young generation. This is typically a couple of hundred megs up to a gig in size, depending om VM settings, number of CPU:s and total heap size. The young generation is collected in a stop-the-world pause, followed by a parallel (multiple CPU) compacting (moving objects) collection. The young generation is sized so as to make this pause reasonably large.
When objects have survived (are still reachable) young gen they get promoted to "old-gen" (old generation).
The old generation is where -XX:+UseConcMarkSweepGC kicks in. In the default mode (without -XX:+UseConcMarkSweepGC) when the old generation becomes full the entire heap is collected and compacted (moving around, eliminating fragmentation) at once in a stop-the-world copy. That pause will typically be longer than young-gen pauses because the entire heap is involved, which is bigger.
With CMS (-XX:+UseConcMarkSweepGC) the work to compact the old generation is mostly concurrent (meaning, running in the background with the application not paused). This work is also not compacting; it works more like malloc()/free() and you are subject to fragmentation.
The main upside of CMS is that when things work well, you avoid long pause times that are linear in the size of the heap, because the main work is cone concurrently (there are some stop-the-world steps involved but they are supposed to usually be short).
The two primary downsides are that:
*
*You are subject to fragmentation because old-gen is not compacted.
*If you don't finish a concurrent collection cycle before old-gen fills up, or if fragmentation prevents allocation, the resulting full collection of the entire heap is not parallel as it is with the default collector. I..e, only one CPU is used. That means that when/if you do hit a full garbage collection, the pause will be longer than it would have been with the default collector.
Now... your logs. "Concurrent mode failure" is intended to convey that the concurrent mark/sweep work did not complete in time for another young-gen GC that needs to promote surviving objects into the old generation. The "promotion failed" is rather that during promotion from young-gen to old-gen, an object was unable to be allocated in old-gen due to fragmentation.
Unless you are hitting a true bug in the JVM, the sudden increase in heap usage is almost certainly from your application, JBoss, or some external entity acting on your application. So I can't really help with that. However, what is likely happening is a combination of two things:
*
*The spike in activity is causing an increase in heap usage too quick for the concurrent collection to complete in time.
*Old-gen is too fragmented, causing problems especially when the old-gen is almost full.
I should also point out now that the default behavior of CMS is to try to postpone concurrent collections as long as possible (yet not too long) for performance reasons. The later it happens, the more efficient (in terms of CPU usage) the collection is. However, a trade-off is that you're increasing the risk of not finishing in time (which again, will trigger a full GC and a long pause). It should also (I have not made empirical tests here, but it stands to reason) result in fragmentation being a greater concern; basically the more full old-gen is when an object is promoted, the greater is the likelyhood that the object's promotion will worsen fragmentation concerns (too long to go into details here).
In your case, I would do two things:
*
*Keep figuring out what is causing the activity. I would say it's fairly unlikely that it is a GC/JVM bug.
*Re-configure the JVM to trigger concurrent collection cycles earlier in order to avoid the heap every becoming so full that fragmentation becomes a particularly huge concern, and giving it more time to complete in time even during your sudden spikes of activity.
You can accomplish (2) most easily be using the JVM options
*
*-XX:CMSInitiatingOccupancyFraction=75
*-XX:+UseCMSInitiatingOccupancyOnly
in order to explicitly force the JVM to kick start a CMS cycle at a certain level of heap usage (in this example 75% - you may need to change that; the lower the percentage, the earlier it will kick in).
Note that depending on what your live size is (the number of bytes that are in fact live and reachable) in your application, forcing an earlier CMS cycle may also require that you increase your heap size to avoid CMS running constantly (not a good use of CPU).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: write a sql statement to update data for below query in sybase we have table 1 :
TABLE 1
(col1,col2) values(A,2)
(col1,col2) values(A,3)
(col1,col2) values(A,5)
(col1,col2) values(B,6)
(col1,col2) values(B,1)
(col1,col2) values(C,2)
now, we have table 2 :
TABLE :2
(col1,col2) values(A,null)
(col1,col2) values(B,null)
(col1,col2) values(C,null)
write a query to update sum of indivisual of col1 from only 1 statement. Do not use a temp table .
OUTPUT: table 2:
(col1,col2) values(A,9)
(col1,col2) values(B,7)
(col1,col2) values(C,2)
A: Oracle variant (I hope that it is working on Sybase too):
create table TABLE1 (col1 varchar(1), col2 integer);
create table TABLE2 (col1 varchar(1), col2 integer);
insert into TABLE1 (col1,col2) values('A',2);
insert into TABLE1 (col1,col2) values('A',3);
insert into TABLE1 (col1,col2) values('A',5);
insert into TABLE1 (col1,col2) values('B',6);
insert into TABLE1 (col1,col2) values('B',1);
insert into TABLE1 (col1,col2) values('C',2);
insert into TABLE2 (col1,col2) values('A',null);
insert into TABLE2 (col1,col2) values('B',null);
insert into TABLE2 (col1,col2) values('C',null);
update TABLE2 t2 set COL2 = (select sum(t1.col2) from TABLE1 t1 where t1.col1 = t2.col1);
select * from TABLE2;
As can I remember, Sybase has own update syntax (can't check myself):
update TABLE2
set col2 = sum(t2.col1)
from TABLE1 t1, TABLE2 t2
where t1.col1 = t2.col2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: The right way? Automated Synchronization between 2 mysql DB I already read a few threads here and I also went through the MySQL Replication Documentation (incl. Cluster Replication), but I think it's not what I really want and propably too complicated, too.
I got a local and a remote DB that might get both accessed/manipulated by 2 different persons at the same time. What I'd like to do is to sync them as soon as possible (means instantly or as soon the local machine goes online). Both DB's only get manipulated from my own PHP Scripts.
My approach is the following:
If local machine is online:
*
*Let my PHP Script on the loal machine always send the SQL Query to the remote DB too
*Let my PHP Script on the remote machine always store its queries and...
*...let the local machine ask the remote DB every x minutes for new queries and apply them locally.
If local machine is offline:
Do step 2. also for both machines and send the stored queries to the remote DB as soon as
local machine goes online again. Also pull the queries from the remote machine for sure.
My questions are:
*
*Did I just misunderstand Replication or am I right that my way would be easier in my case? Or is there any other good solution for what I'm trying to accomplish?
*Any idea how I could check whether my local machine is online/offline? I guess I'd have to use JavaScript, but I don't know how. The browser/my script would always be running on the local machine.
A: What you're describing is master-master or multi-master replication. There are plenty of tutorials on how to set this up across the web. Definitely do your research before putting a solution like this into production as replication in MySQL isn't exactly elegant -- you need to know how to recover if (when?) something goes wrong.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What fonts are supported by Salesforce PDF generation? I'm generating a pdf using a VisualForce page with the renderAs param set to pdf. I'm wishing for more fonts even though others have complained there are few. Does anyone know of additional fonts that work with Salesforce pdf generation?
So far I've only found five fonts that work (serif, sans-serif, monospace, courier, and arial unicode ms) by testing with a simple VisualForce page like this:
<apex:page renderAs="pdf">
<h2>Standard Font Families</h2>
<p style="font-family: serif;">Serif</p>
<p style="font-family: sans-serif;">Sans-serif</p>
<p style="font-family: monospace;">Monospace</p>
<h2>Additional Fonts (wishing for more)</h2>
<p style="font-family: Courier;">Courier!</p>
<p style="font-family: Arial Unicode MS;">Arial Unicode MS!</p>
<h2>Missing Fonts</h2>
<p style="font-family: Arial;">Arial</p>
<p style="font-family: Helvetica;">Helvetica</p>
<p style="font-family: Verdana;">Verdana</p>
<p style="font-family: Georgia;">Georgia</p>
<p style="font-family: Times;">Times</p>
<p style="font-family: Times New Roman;">Times New Roman</p>
<p style="font-family: Consolas;">Consolas</p>
</apex:page>
A: Looks like this is it for now:
*
*Serif
*Sans-serif
*Monospace
*Courier
*Arial Unicode MS
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Spring security XML SCHEMA I get PARSE exception for the following XML file..
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http pattern="/static/**" secured="false" />
<http use-expressions="true">
<intercept-url pattern="/jsp/**" access="isAuthenticated()"/>
<form-login />
<logout />
</http>
</beans:beans>
Full exception was
"cvc-complex-type.3.2.2: Attribute 'secured' is not allowed to appear in element 'http'."
I looked up spring-security-3.1.xsd and it it seemed perfectly alright to have "secured" attribute for http. Does anyone else have this issue?
I
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Emacs inside of gedit? After years of experimentation with editors, the fact is I prefer them as minimal as possible. I never use fancy features and the full-feature IDE's become bloated, heavy, and slow. Of course, when I do something that pretty much requires a specific IDE (like Android dev and Eclipse) I have no problems using it. But most of the time, I use gedit for programming.
However, I like many Emacs commands, and I want to use them occasionally. Is there a way to embed Emacs inside of gedit? For instance, I envision pressing alt-q (or whatever combo) and Emacs mode is enabled, and from then on all my key presses in the current tab do Emacs commands. I press alt-q again, and it turns off. This would allow me the best of both worlds. Anything like this exist, or do I need to write this plugin myself?
A: No.
I've seen discussion of embedding of Emacs in other applications in the past, and the consensus is that even that's not feasible, let alone what you're suggesting.
You'd be better off identifying what gedit does that makes you want to use it instead of Emacs, and extending Emacs to make it do that, too. (There can't be that much --- gedit doesn't do much.) The extra features can just sit there and wait for you, and you'll find it easier to locate and use them if you're comfortable in Emacs-mode already.
(On top of all the other advantages of Emacs, you gain the ability to use the same editor you use in a windowed environment on the terminal --- a huge advantage.)
Or maybe yes . . .
You can use the External Tools plugin of gedit (look for it in Preferences). Add a new command, bind it to the key you want, and use this script:
#!/bin/sh
FILE_NAME=$GEDIT_CURRENT_DOCUMENT_PATH
emacs $FILE_NAME
If you want it to open in the currently-running Emacs, replace emacs with emacsclient, and add the following to your .emacs:
(server-start)
A: This is kind of backward. Why don't you just use Emacs and stay away from all the extra bells and whistles? It'd probably be easier to coax emacs to emulate gedit than the other way around.
A: If gedit (a) can be scripted to launch another application with the current file as an argument, and (b) will notice if the file is modified on disk and offer to reload it, then you would have a workaround.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ERROR MESSAGES DOES NOT DISPLAY i have a php file that process my registration form however it does not display the error messages if the form has discrepancies (blank fields, etc.). Also, the captcha validation is not working.
This is the php code that process the form.
<?php
//Start session
session_start();
//Include database connection details
require_once('connect.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$username = clean($_POST['username']);
$password = clean($_POST['password']);
$cpassword = clean($_POST['cpassword']);
$nickname = clean($_POST['nickname']);
$email = clean($_POST['email']);
$code = clean($_POST['code']);
//Input Validations
if($username == '') {
$errmsg_arr[] = 'Username missing';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
if($cpassword == '') {
$errmsg_arr[] = 'Confirm Password missing';
$errflag = true;
}
if($nickname == '') {
$errmsg_arr[] = 'nickname missing';
$errflag = true;
}
if($email == '') {
$errmsg_arr[] = 'Email Address missing';
$errflag = true;
}
if( strcmp($password, $cpassword) != 0 ) {
echo "Password Do not match";
$errmsg_arr[] = 'Passwords do not match';
$errflag = true;
}
include("../captcha/securimage.php");
$img = new Securimage();
$valid = $img->check($_POST['code']);
if($valid == true) {
echo "<center>Thanks, you entered the correct code.</center>";
} else {
echo "<center>Sorry, the code you entered was invalid.";
}
//Check for duplicate login ID
if($login != '') {
$qry = "SELECT * FROM employee_login WHERE username='$username'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$errmsg_arr[] = 'Username already in use';
$errflag = true;
}
@mysql_free_result($result);
}
else {
die("Query failed");
}
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: ../register.php");
exit();
}
//Create INSERT query
$qry = "INSERT INTO employee_login(username, password, email, nickname) VALUES('$username','".md5($_POST['password'])."','$email','$nickname')";
$result = @mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: ../registergood.php");
exit();
}else {
die("Query failed");
}
?>
What might be wrong?
A: Well, it's not displaying your error messages because at no point in the code you've provided do you output those messages to the user. You store them in an array and later a session variable, but that's it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Retrieving a URL though an authenticating proxy using PHP I am attempting to script the retrieval of an secure (password protected + https) URL trough a proxy server that requires authentication. I found many examples of how to use the 'proxy' option and how to send credentials with stream_context_create.
$url = "https://$server/$uri";
$cred = sprintf('Authorization: Basic %s\r\n', base64_encode("$user:$pass"));
$options['header']=$cred;
$options['proxy']="tcp://10.1.1.1:3128";
$params = array('http' => $options);
$ctx = stream_context_create($params);
$fp = @fopen($url, 'rb', false, $ctx);
However I did not find any where a uid/password was provided to the proxy server. I attempted to add a header manually:
$prox_cred = sprintf('Proxy-Connection: Keep-Alive\r\nProxy-Authorization: Basic %s\r\n', base64_encode("$proxy_user:$proxy_pass"));
$options['header'] .= $prox_cred;
I have root access to the proxy server and I can see my request hitting it, but when I look into the traffic I don't see my headers. I guess they are being added to the portion that gets encrypted and sent to the end server.
A: For some reason I didn't want to complicate things by using the cURL modules for the first time. However based on the responses I tried it and it took about 6 minutes to get things working.
if ($proxy_server != '') {
curl_setopt($ch,CURLOPT_PROXYAUTH,CURLAUTH_BASIC);
curl_setopt($ch,CURLOPT_PROXY,"$proxy_server");
if ($proxy_user != '') {
curl_setopt($ch,CURLOPT_PROXYAUTH,CURLAUTH_BASIC);
curl_setopt($ch,CURLOPT_PROXYUSERPWD,"$proxy_user:$proxy_pass");
}
}
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XmlSerialize - Desrialize external XML I have many files, with the format of:
<?xml version="1.0" encoding="utf-8"?>
<Words>
<word>
<Eng>chain</Eng>
<EngEnd>chained</EngEnd>
<PartOfSpeechEng>verb</PartOfSpeechEng>
<Heb>לקשור עם שרשרת</Heb>
<EngInHeb>צֵ'ין</EngInHeb>
<PartOfSpeechHeb>פועל</PartOfSpeechHeb>
<DicNumber>27</DicNumber>
<Arb>سلسلة</Arb>
<EngInArb>
</EngInArb>
</word>
<word>
<Eng>growl</Eng>
<EngEnd>growls</EngEnd>
<PartOfSpeechEng>verb</PartOfSpeechEng>
<Heb>לנהום</Heb>
<EngInHeb>גְרַאוּל</EngInHeb>
<PartOfSpeechHeb>פועל</PartOfSpeechHeb>
<DicNumber>3</DicNumber>
<Arb>دمدمة/تذمـُّر</Arb>
<EngInArb>
</EngInArb>
</word>
</Words>
I failed to deserialize it into array, can someone help me deserialize it
Thanks
A: Generated using xsd.exe using schema created by this online tool.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class Words {
private WordsWord[] wordField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("word")]
public WordsWord[] word {
get {
return this.wordField;
}
set {
this.wordField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
public partial class WordsWord {
private string engField;
private string engEndField;
private string partOfSpeechEngField;
private string hebField;
private string engInHebField;
private string partOfSpeechHebField;
private int dicNumberField;
private string arbField;
private string engInArbField;
/// <remarks/>
public string Eng {
get {
return this.engField;
}
set {
this.engField = value;
}
}
/// <remarks/>
public string EngEnd {
get {
return this.engEndField;
}
set {
this.engEndField = value;
}
}
/// <remarks/>
public string PartOfSpeechEng {
get {
return this.partOfSpeechEngField;
}
set {
this.partOfSpeechEngField = value;
}
}
/// <remarks/>
public string Heb {
get {
return this.hebField;
}
set {
this.hebField = value;
}
}
/// <remarks/>
public string EngInHeb {
get {
return this.engInHebField;
}
set {
this.engInHebField = value;
}
}
/// <remarks/>
public string PartOfSpeechHeb {
get {
return this.partOfSpeechHebField;
}
set {
this.partOfSpeechHebField = value;
}
}
/// <remarks/>
public int DicNumber {
get {
return this.dicNumberField;
}
set {
this.dicNumberField = value;
}
}
/// <remarks/>
public string Arb {
get {
return this.arbField;
}
set {
this.arbField = value;
}
}
/// <remarks/>
public string EngInArb {
get {
return this.engInArbField;
}
set {
this.engInArbField = value;
}
}
}
and you can use it like this
XmlSerializer mySerializer = new XmlSerializer(typeof(Words));
FileStream myFileStream = new FileStream("path_to_xml",FileMode.Open);
Words words = (Words)mySerializer.Deserialize(myFileStream);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails 3.1 and selecting out across three tables I have the following and am trying to figure out how to select the User info (sql at end of question).
# only global_id and list_id
class GlobalList < ActiveRecord::Base
set_table_name :globals_lists
belongs_to :list
end
# user_id
class List < ActiveRecord::Base
has_many :global_lists
belongs_to :user
end
# email
class User < ActiveRecord::Base
has_many :lists
end
How would I select out the emails of the user list assuming I have a global_id (ie assuming a global_id of 256,
select u.* from users u, lists l, globals_lists gl where gl.global_id=256 and gl.list_id=l.id and l.user_id=u.id)
A: Try this:
User.includes({:lists => :global_lists}).where(['global_lists.global_id = ?', 256])
That will return User objects, which seems to be what you are looking for from your query. You can then get their email from their .email attribute, in a loop, or however you need it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Database Design about Date/Time Column Brief Description:
I have a table that stores articles. Articles are listed on table and sorted - DESC - by dateCreated.
dateCreated column represents the date and time user has posted/created the article. It is fixed and must not be changed.
Problem:
By the days, old articles usually ends up in far pages. However, the user has the chance of bumping his article back to the top of the table on first page. Since i'm ordering the articles by dateCreated, which mustn't be changed, how can i bump the article without changing dateCreated?
My Solution - I'm not sure if its a good one or not (i need suggestions):
Create another column called bumpDate. When user posts an article, date/time will be inserted into dateCreated and bumpDate. The articles on the gridview will be sorted by bumpDate. When user bumps his article, i only update bumpDate. Therefore, user's article ,regardless of dateCreated date, will be on top. Gradually, the article will go down by the days depending how many new articles posted by other users.
Do you see any glitches in this design/solution?
A: What you have outlined is how those things are typically done. While BumpDate might not be the best name (does this truly represent the action of "bumping", or did they do something else like modifying it?), that's what you should use.
A: I don't see any real issues with what you are proposing, only possible thing would be to try and utilize an INT value instead of a DateTime (4 bytes vs 8 bytes) if you are going to have a LOT of data, otherwise I would do the same thing you are proposing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Manipulating a histogram plot in R I have a histogram, and I want to move it over by 10 units on the x axis.
h1 <- hist(t1,breaks=15)
plot(h1,xlim=c(0,200),col="red")
how can I do this?
A: If your original is:
h1 <- hist(t1,breaks=15)
plot(h1,xlim=c(0,200),col="red")
then does this do it?
h1 <- hist(t1,breaks=15)
plot(h1,xlim=c(-10,190),col="red")
Not having your t1 data, I can't tell. But is that what you are trying to do?
A: You can specify your brakes
eg:
b<-seq(range(t1)[1],range(t1)[2],length.out=15)
which you can then manipulate
b<-seq(range(t1)[1],range(t1)[2],length.out=15)-10
h1<-hist(t1, breaks=b)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Get script name in OCaml? Does OCaml have a way to get the current file/module/script name? Something like:
*
*C/C++'s argv[0]
*Python's sys.argv[0]
*Perl/Ruby's $0
*Erlang's ?FILE
*C#'s ProgramName.Environment.CommandLine
*Factor's scriptname/script
*Go's os.Args[0]
*Haskell's System/getProgName
*Java's System.getProperty("sun.java.command").split(" ")[0]
*Node.js's __filename
*etc.
A: I presume you are scripting in OCaml. Then Sys.argv.(0) is the easiest way to get the script name. Sys module also provides Sys.executable_name, but its semantics is slightly different:
let _ = prerr_endline Sys.executable_name; Array.iter prerr_endline Sys.argv;;
If I run the above line, putting the line in test.ml, by ocaml test.ml hello world, I have:
/usr/local/bin/ocaml - executable_name
test.ml - argv.(0)
hello - argv.(1)
world - argv.(2)
So OCaml toplevel does something fancy against argv for you.
In general, obtaining the current module name in OCaml is not easy, from several reasons:
*
*ML modules are so flexible that they can be aliased, included into other modules, and applied to module functors.
*OCaml does not embed the module name into its object file.
One probably possible workaround is to add a variable for the module name by yourself, like:
let ml_source_name = "foobar.ml"
This definition can be probably auto inserted by some pre-processing. However, I am not sure CamlP4 can have the file name of the currently processing source file.
If your main purpose is simple scripting, then of course this pre-processing is too complicated, I am afraid.
A: I don't know anything about OCaml but some googling turned up
Sys.argv.(0)
See http://caml.inria.fr/pub/docs/manual-ocaml/manual003.html#toc12
A: let _ =
let program = Sys.argv.(0) in
print_endline ("Program: " ^ program)
And posted to RosettaCode.
A: In OCaml >= 4.02.0, you can also use __FILE__ to get the filename of the current file, which is similar to Node's __filename and not the same as Sys.argv.(0).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I remove parent opacity in CSS? In my CSS I have the following:
.Thing {
filter: alpha(opacity=40);
opacity:0.4;
-moz-opacity:0.4;
}
.Thing button {
filter: alpha(opacity=100);
opacity:1;
-moz-opacity:1.0;
}
However, the button is still .4 opacity. I then try opacity: 2 and such and it looks like I can give it less opacity but not more. Is there a way I can remove it or do I have to write multiple rules to get everything but the button?
I am testing with Firefox and Chrome.
A: use rgba with a rgb fallback.
background-color: rgb(0,0,0);
background-color: rgba(0,0,0, 0.5); /*ie6 will ignore this*/
rgba will only apply opacity to the target element.
What i've recently been doing is using the rgbapng sass/compass plugin which generates a png image to use as a fallback for browsers without rgba support.
Note: you'll still need to use an ie6 png fix for this to work.
A: Not a fix for the opacity issue but a possible workaround.
How about removing the button from the normal document flow and then placing back inside the .Thing
Something like this: http://jsfiddle.net/CqgkM/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: C# CompileAssemblyFromSource, add referenced assemblies it needs? I have the CompileAssemblyFromSource working for code that only references assemblies that my program (that compiles it) uses. It works beautifully.
However, if I need to compile code that has a "using blah;" statement, it won't be able to find blah and say it is missing a resource.
So if it is "System.Windows.Forms", and I say "compilerparams.ReferencedAssemblies.Add("System.Windows.Forms.dll")", it works.
So I can parse the code file and get all the "using" parameters, but how do I know that those are supposed to be "*.dll" adding, or they are namespaces elsewhere or whatnot? Is there a way for .NET to take in "System.Windows.Forms" and spit back out "System.Windows.Forms.dll" because that's what it needs and so on?
A: *
*Read the article How the Runtime Locates Assemblies
*Before compiling the code load all the assemblies found in the locations mentioned in point 1
*Load all the types in all the assemblies and keep a dictionary of namespace, type pair
*When a using is encountered in the source try adding reference of assemblies from the dictionary in 3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What is a good UML or ReverseEngineering Language for Visual C++ 6.0? What is a good UML or ReverseEngineering Language for Visual C++ 6.0 ?
I have to build upon another guys code that is greater than 50K lines and tons of classes.
He has little to no documentation. I need to produce a map and see how everything intertwines.
I am looking for software package to read in the project code and produce a map of the classes and showing how things relate.
Thanks
A: Hey I'm interested in this topic too, so did a little search:
http://msdn.microsoft.com/en-us/library/aa140255(v=office.10).aspx
A: I have use Poseidon UML (http://www.visual-paradigm.com/solution/freeumltool/?src=google&kw=UML&mt=b&net=g&plc=&gclid=CNnmsMr9w6sCFQhrgwod9GFy5w). I also like Rational (http://www.ibm.com/developerworks/rational/library/769.html)
Your attempt to document the C++ may fail as UML has trouble with specific implementations. You may get an approximation.
I also like LePus3 (http://www.lepus.org.uk/) which is not UML but it seems to reverse engineer better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Play Framework: Run single selenium test on the command line (headless browser) I can run a single selenium test in play's browser UI, however, is it possible to execute a play selenium test on the command line?
Obviously if I run play auto-test it will execute all my selenium tests (as well as my junit tests). Is there a way that I could tell Play to execute just a single selenium test on the command line to check whether it works using the headless browser?
A: I don't think it's possible to do so with the current play framework,
but see how auto-test works on
https://github.com/playframework/play/blob/master/modules/testrunner/src/play/modules/testrunner/FirePhoque.java .
It get the play test lists on /@tests.list , maybe you could try to override it providing what you want to test.
Anyway, I don't see the usecase of testing only one test in a headless browser.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Git Submodules. Pulling into a new clone of the super-project OK. So I thought I had this licked ... but now ....
I have a project which includes one small library from GitHub as a submodule. In the original version of that super-project the submodule is working as expected.
However, I just cloned the superproject, did what I thought I should : "git submodule init", got the directory of the submodule to appear, but it's empty.
If I now try to do
git submodule update
I get
fatal: Needed a single revision
Unable to find current revision in submodule path 'external_libraries/BEACHhtml'
If I try
git submodule foreach git pull
I get
Entering 'external_libraries/BEACHhtml'
fatal: Where do you want to fetch from today?
Stopping at 'external_libraries/BEACHhtml'; script returned non-zero status.
In my .git/config, I have this :
[submodule "external_libraries/BEACHhtml"]
url = git@github.com:interstar/BEACHhtml.git
In my .gitmodules I have this :
[submodule "external_libraries/BEACHhtml"]
path = external_libraries/BEACHhtml
url = git@github.com:interstar/BEACHhtml.git
Anyone got an idea what's missing?
A: Solved by deleting 2 directories and refetching submodule:
*
*Go to external_libraries/BEACHhtml and look into .git file. It's content should be something like gitdir: ../../.git/modules/external_libraries/BEACHhtml
*Delete both external_libraries/BEACHhtml and .git/modules/external_libraries/BEACHhtml directories.
From now on git submodule update runs without errors.
A: I had this problem (flaky network so I got dropped submodule checkout like this) and I solved it by making this script (named it git-submodule-fix so I could run it as git submodule-fix)
#!/bin/bash
for arg
do
echo $arg
find . -name "`basename $arg`" | grep "$arg\$" | xargs rm -fr
done
If you get this i.e. from a git submodule update
fatal: Needed a single revision
Unable to find current revision in submodule path 'some/submodule/path'
do
git submodule-fix some/submodule/path
git submodule update
A: It seems that now (in 2019) installing latest GIT client could solve the problem according to comments below. This should be the best solution for now.
I have the same problem as you. This is a bug in git: http://git.661346.n2.nabble.com/BUG-git-submodule-update-is-not-fail-safe-td7574168.html
In short, for your problem, try:
# rm -rf external_libraries/BEACHhtml
# git submodule update
It seems there is something wrong with the previous checkout folder, remove it, and update again solves the problem.
A: If you are reading in 2019 or later, just update the git client. Worked for me.
A: I ran into this in 2021 when I got into a detached HEAD state between commits from the sub-module repo's source and it's version in the 'calling' main repo.
this answer helped --> How do I fix a Git detached head?
And I verified this strategy with new changes to the sub-module repo
*
*$ cd <into the sub-module dir within the calling/main repo>
*$ git pull --> the sub-module repo brings in any changes from it's source
*$ cd <back into the calling/main repo>
*$ git status --> should show new changes to be committed for the sub-module repo
A: use a diff tool to compare the original clone that's working and this one. Also, what does git submodule output. Ensure you are pointing to the same branch in each repo before you do.
I'm suspecting that you've switched to a branch or older revision where the submodule was not defined.
hope this helps
A: I had the same issue with a submodule on a project. When I tried to clone the submodule separately it worked well.
I've tried all of the answers above, but without success (git submodule update, ..., removing the submodule folders, ...).
The issue disappeared after update of git (from Git-1.7.11-preview20120710) to latest version (to Git-1.8.1.2-preview20130201) at the time. Strangely my colleagues had even older version, worked without any issues, but they were on Mac. I'm on Win7 64bit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
}
|
Q: CSS for only iPhone and only regular browsers? I have a website that looks horrible on the iPhone but fine in regular browsers. I want to be able to only load css for the iPhone and only load the other stylesheet for regular browsers. I would rather not use PHP but it is an available option, I'd like to use the standard way to call css:
<link rel="stylesheet" href="index.css"/>
A: This can be done with CSS media queries. This will serve a mobile stylesheet to devices with a screen no wider than 768 pixels, and a desktop screenshot to the others.
<link rel="stylesheet" type="text/css" media="screen and (max-device-width: 768px)" href="mobile.css" />
<link rel="stylesheet" type="text/css" media="screen and (min-device-width: 768px)" href="desktop.css" />
A: What you're looking for is CSS media queries. The let you specify which css rules to use based on different browser resolutions / screen dpi. You can read more about them at http://www.alistapart.com/articles/responsive-web-design/
A: If php is an option one thing you can do is install user agent processing tool to find from which device the request has come and you can tailor your website accordingly.
WURLF works well for me.
There is open source MYSQL-PHP library for that:
TERA-WURFL
If you don't want that and looking for a single solution you can use something like this in your css:
// target small screens (mobile devices or small desktop windows)
@media only screen and (max-width: 480px) {
/* CSS goes here */
}
/* high resolution screens */
@media (-webkit-min-device-pixel-ratio: 2),
(min--moz-device-pixel-ratio: 2),
(min-resolution: 300dpi) {
header { background-image: url(header-highres.png); }
}
/* low resolution screens */
@media (-webkit-max-device-pixel-ratio: 1.5),
(max--moz-device-pixel-ratio: 1.5),
(max-resolution: 299dpi) {
header { background-image: url(header-lowres.png); }
}
You can read more about this at this good blog post:
http://davidbcalhoun.com/2010/using-mobile-specific-html-css-javascript
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GoogleMap with KML zooming and Polygon highlighting This is the code for generating map with a kml file
var myLatlng = new google.maps.LatLng(47.711516,-117.395075);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("mapdiv"), myOptions);
var geoLayer = new google.maps.KmlLayer(
'http://some.kml.url/kmllayer.kml',
{suppressInfoWindows: true,map: map});
geoLayer.setMap(map);
My problem is its always getting at max distance, zoom settings not working even if i try to map.setCenter() call, its still same.
Another question is when i draw polygons on map, is there any way to highlight inside color of it when someone mouse overs it.
A: 2nd question. Draw an initial polygon with a fill opacity of 0 but stroke opacity of 1. Have two event listeners attached to the polygon, for mouseover and mouseout.
google.maps.event.addListener(polygon, 'mouseover', function() {
polygon.setOptions({fillOpacity:0.5});
}
google.maps.event.addListener(polygon, 'mouseout', function() {
polygon.setOptions({fillOpacity:0.0});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Open Graph Beta: Add Data to Profile URL In the new Open Graph Beta Auth Dialog does the "Add Data to Profile URL" essentially serve as the callback URL where Facebook will send the user after they click the "Add to My Timeline" button?
In a related question, will clicking the "Add to My Timeline" button in the new auth process in itself generate posting an item to the new Timeline page for the user?
Since these new features are in beta, we're not sure what to expect.
A: Have a look at:
https://developers.facebook.com/docs/beta/authentication/#add-data
If configured, Reports and stories on Timeline will have a menu option that lets the friends of your app's users click "add to my timeline" to install your app. Note that the screenshots in the docs are somewhat out of date and should say "Add to Timeline".
A: When a user clicks on "Add To My Timeline", whenever your app post an Open Graph Action for the user (e.g. Bill listened to Nirvana), it will add it to the timeline if you have Aggregation for that action (e.g. Music I Listen To).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can I create a virtual webcam and stream data to it? I am looking to stream a video from ffmpeg to OpenCV (a video manipulation library) and I am stumped. My idea is to create a virtual webcam device and then stream a video from ffmpeg to this device and the device will in turn stream like a regular webcam. My motivation is for OpenCV. OpenCV can read in a video stream from a webcam and go along its merry way.
But is this possible? I know there is software to create a virtual webcam, but can it accept a video stream (like from ffmpeg) and can it stream this video like a normal webcam? (I am working in a cygwin environment , if that is important)
A: You don't need to fool OpenCV into thinking the file is a webcam. You just need to add a delay between each frame. This code will do that:
#include <iostream>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
int main(int argc, const char * argv[]) {
VideoCapture cap;
cap.open("/Users/steve/Development/opencv2/opencv_extra/testdata/python/videos/bmp24.avi");
if (!cap.isOpened()) {
printf("Unable to open video file\n");
return -1;
}
Mat frame;
namedWindow("video", 1);
for(;;) {
cap >> frame;
if(!frame.data)
break;
imshow("video", frame);
if(waitKey(30) >= 0) //Show each frame for 30ms
break;
}
return 0;
}
Edit: trying to read from a file being created by ffmpeg:
for(;;) {
cap >> frame;
if(frame.data)
imshow("video", frame); //show frame if successfully loaded
if(waitKey(30) == 27) //Wait 30 ms. Quit if user presses escape
break;
}
I'm not sure how it will handle getting a partial frame at the end of the file while ffmpeg is still creating it.
A: Sounds like what you want is VideoCapture::Open, which can open both video devices and files.
If you're using C, the equivalents are cvCaptureFromFile and cvCaptureFromCAM.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Str_replace for multiple items I remember doing this before, but can't find the code. I use str_replace to replace one character like this: str_replace(':', ' ', $string); but I want to replace all the following characters \/:*?"<>|, without doing a str_replace for each.
A: For example, if you want to replace search1 with replace1 and search2 with replace2 then following code will work:
print str_replace(
array("search1","search2"),
array("replace1", "replace2"),
"search1 search2"
);
// Output: replace1 replace2
A: If you're only replacing single characters, you should use strtr()
A: str_replace(
array("search","items"),
array("replace", "items"),
$string
);
A: You could use preg_replace(). The following example can be run using command line php:
<?php
$s1 = "the string \\/:*?\"<>|";
$s2 = preg_replace("^[\\\\/:\*\?\"<>\|]^", " ", $s1) ;
echo "\n\$s2: \"" . $s2 . "\"\n";
?>
Output:
$s2: "the string "
A: Like this:
str_replace(array(':', '\\', '/', '*'), ' ', $string);
Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:
str_replace([':', '\\', '/', '*'], ' ', $string);
A: str_replace() can take an array, so you could do:
$new_str = str_replace(str_split('\\/:*?"<>|'), ' ', $string);
Alternatively you could use preg_replace():
$new_str = preg_replace('~[\\\\/:*?"<>|]~', ' ', $string);
A: I had a situation whereby I had to replace the HTML tags with two different replacement results.
$trades = "<li>Sprinkler and Fire Protection Installer</li>
<li>Steamfitter </li>
<li>Terrazzo, Tile and Marble Setter</li>";
$s1 = str_replace('<li>', '"', $trades);
$s2 = str_replace('</li>', '",', $s1);
echo $s2;
result
"Sprinkler and Fire Protection Installer", "Steamfitter ", "Terrazzo, Tile and Marble Setter",
A: I guess you are looking after this:
// example
private const TEMPLATE = __DIR__.'/Resources/{type}_{language}.json';
...
public function templateFor(string $type, string $language): string
{
return \str_replace(['{type}', '{language}'], [$type, $language], self::TEMPLATE);
}
A: In my use case, I parameterized some fields in an HTML document, and once I load these fields I match and replace them using the str_replace method.
<?php echo str_replace(array("{{client_name}}", "{{client_testing}}"), array('client_company_name', 'test'), 'html_document'); ?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "141"
}
|
Q: SQL Server XML local-name() anomaly Is anyone able to explain why the two results are different, even though the node XML representation is exactly the same?
declare @t varchar(max) set @t = '<a><b><c/></b><d>eeee</d></a>'
declare @x xml set @x = cast(@t as xml)
select N.query('.'), N.value('local-name(.)','varchar(max)')+'.' from @x.nodes('//*') T(N)
select N.query('.'), N.value('local-name(.)','varchar(max)')+'.' from @x.nodes('/') T(N)
Result1:
Col1 Col2
<a><b><c /></b><d>eeee</d></a> a.
<b><c /></b> b.
<c /> c.
<d>eeee</d> d.
Result2:
Col1 Col2
<a><b><c /></b><d>eeee</d></a> .
Answer: (with the help from accepted answer from Mitch)
This query more clearly (relatively speaking) shows what is happening:
declare @t varchar(max) set @t = '<a><b><c/></b><d>eeee</d></a><x />'
declare @x xml set @x = cast(@t as xml)
select N.query('.'), N.value('local-name(.)','varchar(max)')+'.' from @x.nodes('//*') T(N)
select N.query('.'), N.value('local-name(.)','varchar(max)')+'.' from @x.nodes('/*') T(N)
select N.query('.'), N.value('local-name(.)','varchar(max)')+'.' from @x.nodes('/') T(N)
Result1:
Col1 Col2
<a><b><c /></b><d>eeee</d></a> a.
<b><c /></b> b.
<c /> c.
<d>eeee</d> d.
Result2:
Col1 Col2
<a><b><c /></b><d>eeee</d></a> a.
<x /> x.
Result3:
Col1 Col2
<a><b><c /></b><d>eeee</d></a><x /> .
So in the original question, even though the XML in the results 1 and 2 are identical visually, they are "different".
*
*The first one is the XML-node starting at taking the (virtual) position of "root"
*The second one has a "virtual root" that is a "document" element that is not visually displayed.
A: '/' Selects from the root node
'//' Selects nodes in the document from the current node that match the selection no matter where they are.
Query 1 matches all root elements.
Query 2 matches the single element at the document root. The document root does not have a name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to center text in a background div baloon image? I am having a difficulty on how to center a text in a div with background image. This is my fiddle
http://jsfiddle.net/VnqeY/12/
Thank you.
A: jsFiddle
Just declare line-height and set the <a> to be vertical-align: middle
.balloon{
background:url('http://i.imgur.com/B19Zb.jpg');
background-repeat: no-repeat;
text-align: center;
color:#fff;
font-size:1.1em;
height:140px;
width:140px;
line-height: 118px;
}
.balloon a{
vertical-align: middle;
color:yellow;
text-align:center
}
<div class="balloon">
<a href="#">Advertise with us</a>
</div>
A: display: table-cell;
text-align: center;
vertical-align: middle;
one option is to you display:table-cell The image and size and such needs fixed though.
A: http://jsfiddle.net/VnqeY/16/
Read up on CSS relative positioning.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Suppressing "X rows affected" in SQL Server using sqlcmd and Java In my Java program, I am trying to execute a bunch of SQL scripts using sqlcmd via getRuntime.exec().
Earlier, I had been using osql this way -
osql -n -S SERVER -U sa -P PASSWORD -q "SET NOCOUNT ON" -i "INPUTSCRIPT.sql"
However, in the case of sqlcmd, the -i and -q switches are mutually exclusive. How do I do this in sqlcmd?
Note:
*
*I'd rather not modify the SQL scripts to include SET NOCOUNT ON in
each file.
*There's already been a very similar question here. That solution discusses setting environment variables. Is that possible using Java?
A: You can specify multiple scripts for the i switch so you can do this:
sqlcmd ... -i SetNoCountOn.sql,MyScript1.sql,MyScript2.sql
That is, create a an extra script that just has SET NOCOUNT ON
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: php code "=" in js format This JavaScript code was in a PHP file, and I need to put this JS code into a .js file.
<script>
$j(".fresh").click(function(){
$j(this).html('<span><?php echo $this->lang_arr['my_new_func']; ?></span>');
$j.post( "<?= site_url('website/func_resh') ?>",
{ id : "<?= $webfun_one_arr[id] ?>",
website_id : "<?= $web_one_arr[id] ?>"
}
);
})
</script>
I know this code <?php echo $this->lang_arr['my_new_func']; ?> in the JavaScript format is {$this->lang_arr['my_new_func'];}
But I don't know how I change <?= site_url('website/func_resh') ?> and <?= $webfun_one_arr[id] ?> into JS format.
Thanks for any answer.
A: Don't. Make it a .js.php file that returns a content type of text/javascript, and includes the other relevant PHP scripts.
A: Interpolating PHP and JavaScript is a big can of worms that you should avoid opening. IMO the best way to deal with this is to use PHP to output a JSON object, which it has built-in support for, and then use the object in your JavaScript. This way you only have to put one tiny snippet of PHP in a <script> tag and you don't have to try to make the server parse .js files as PHP. Something like this:
In your PHP:
<?php $my_vals = array(
'myNewFunc' => $this->lang_arr['my_new_func'],
'postUrl' => site_url('website/func_resh'),
'postId' => $webfun_one_arr['id'],
'postWebsiteId' => $web_one_arr['id']
);
?>
<script>
$j.getScript('/path/to/your_script.js', function() {
myFunc(<%= json_encode($my_vals); %>); // turns your PHP array into a
}); // JavaScript object automatically
</script>
Then, in your_script.js:
// Look, Ma, no PHP!
function myFunc(someJson) {
$j(".fresh").click(function(){
$j(this).html('<span>' + someJson.myNewFunc + '</span>');
$j.post( someJson.postUrl,
{ id : someJson.postId,
website_id : someJson.postWebsiteId
}
);
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7605505",
"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.