text
stringlengths
8
267k
meta
dict
Q: Get the correct url format to Facebook Sharer I need to format a url passed to Facebook Sharer via AS3 using navigateToURL(new URLRequest(request), "_blank");. The url that is passed has a lot of strange characters. What is the best way to get the correct output? This works: http://www.facebook.com/sharer.php?u=www.somesiteurlthatdoesnotexist.com?title=This works fine This does not work: http://www.facebook.com/sharer.php?u=www.somesiteurlthatdoesnotexist.com?title=Jag behöver fixa en url som funkar med åäl och & tecken A: Try this: escape("Jag behöver fixa en url som funkar med åäl och & tecken"); It should make it "URL encoded".
{ "language": "en", "url": "https://stackoverflow.com/questions/7633104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: recursive function and a breakpoint using F# Consider the following code: [<EntryPoint>] let main (args: string []) = let rec main time = let newTime = time + 2 // place a breakpoint at this line main newTime main 0 I am not able to place a breakpoint at the marked line. I meet such problems quite often when using recursive functions and it really makes me not to use them. Is there any simple solution for that? EDIT: I create a brand new solution and my build command looks like: '------ Build started: Project: ConsoleApplication4, Configuration: Debug x86 ------ C:\Program Files (x86)\Microsoft F#\v4.0\fsc.exe -o:obj\x86\Debug\ConsoleApplication4.exe -g --debug:full --noframework --define:DEBUG --define:TRACE --doc:bin\Debug\ConsoleApplication4.XML --optimize- --tailcalls- --platform:x86 -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\FSharp\2.0\Runtime\v4.0\FSharp.Core.dll" -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\mscorlib.dll" -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Core.dll" -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.dll" -r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\Profile\Client\System.Numerics.dll" --target:exe --warn:3 --warnaserror:76 --vserrors --LCID:1033 --utf8output --fullpaths --flaterrors "C:\Users\olsv\AppData\Local\Temp.NETFramework,Version=v4.0,Profile=Client.AssemblyAttributes.fs" Program.fs ConsoleApplication4 -> d:\olsv\documents\visual studio 2010\Projects\ConsoleApplication4\ConsoleApplication4\bin\Debug\ConsoleApplication4.exe ========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========' A: I tried debugging the code you posted and it seems to be working just fine (I'm using Visual Studio 2010 SP1). When I place the breakpoint and run the code (as a console application) it stops at the breakpoint repeatedly and I can step to the next expression and see the state of local variables. You could try checking compiler flags - the debugging works the best when you disable optimizations and tail-calls (this may be particularly relevant to recursive functions). When I build the project, the flags include the following:--debug:full --optimize- --tailcalls-. A: So it looks like, that it is a bug. I have already reported it to the F# team. So lets hope that they will fix it soon!
{ "language": "en", "url": "https://stackoverflow.com/questions/7633105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Which normal form does this table violate? Consider this table: +-------+-------+-------+-------+ | name |hobby1 |hobby2 |hobby3 | +-------+-------+-------+-------+ | kris | ball | swim | dance | | james | eat | sing | sleep | | amy | swim | eat | watch | +-------+-------+-------+-------+ There is no priority on the types of hobbies, thus all the hobbies belong to the same domain. That is, the hobbies in the table can be moved on any hobby# column. It doesn't matter on which column, a particular hobby can be in any column. Which database normalization rule does this table violate? Edit Q. Is "the list of hobbies [...] in an arbitrary order"? A. Yes. Q. Does the table have a primary key? A. Yes, suppose the key is an AUTO_INCREMENT column type named user_id. The question is if the columns hobby# are repeating groups or not. Sidenote: This is not a homework. It's kind of a debate, which started in the comments of the question SQL - match records from one table to another table based on several columns. I believe this question is a clear example of the 1NF violation. However, the other guy believes that I "have fallen fowl of one of the fallacies of 1NF." That argument is based on the section "The ambiguity of Repeating Groups" of the article Facts and Fallacies about First Normal Form. I am not writing this to humiliate him, me, or whomever. I am writing this, because I might be wrong, and there is something I am clearly missing and maybe this guy is not explaining it good enough to me. A: Your three-hobby table design probably violates what I usually call the spirit of the original 1NF (probably for the reasons given by dportas and others). It turns out however, that it is extremely difficult to find [a set of] formal and precise "measurable" criteria that accurately express that original "spirit". That's what your other guy was trying to explain talking about "the ambiguity of repeating groups". Stress "formal", "precise" and "measurable" here. Definitions for all other normal forms exist that satisfy "formal", "precise" and "measurable" (i.e. objectively observable). For 1NF it's just hard (/impossible ???) to do. If you want to see why, try this : You stated that the question was "whether those three hobby columns constitute a repeating group". Answer this question with "yes", and then provide a rigorous formal underpinning for your answer. You cannot just say "the column names are the same, except for the numbered suffix". Making a violation of such a rule objectively observable/measurable would require to enumerate all the possible ways of suffixing. You cannot just say "swim, tennis" could equally well be "tennis, swim", because getting to know that for sure requires inspecting the external predicate of the table. If that is just "person <name> has hobby <hobby1> and also has <hobby2>" , then indeed both are equally valid (aside : and due to the closed world assumption it would in fact require all possible permutations of the hobbies to be present in the table !!!). However, if that external predicate is "person <name> spends the most time on <hobby1> and the least on <hobby2>", then "swim, tennis" could NOT equally well be "tennis,swim". But how do you make such interpretations of the external predicate of the table objective (for ALL POSSIBLE PREDICATES) ??? etc. etc. A: This clearly "looks" like a design error. It's not not a design error when this data is simply stored and retrieved. You need only 3 of the hobbies and you don't intend to use this data in any other way than retrieve. Let's consider this relationship: * *Hobby1 is the main hobby at some point in a person's life (before 18 years of age for example) *Hobby2 is the hobby at another point (19-30) *Hobby3 is her hobby at a another one. Then this table seems definitely well designed and while the 1NF convention is respected the naming arguably "sucks". In the case of an indiscriminate storage of hobbies this is clearly wrong in most if not all cases I can think of right now. Your table has duplicate rows which goes against the 1NF principles. Let's not consider the reduced efficiency of SQL requests to access data from this table when you need to sort the results for paging or any other practical reason. Let's take into consideration the effort required to work with your data when your database will be used by another developer or team: * *The data here is "scattered". You have to look in multiple columns to aggregate related data. *You are limited to only 3 of the hobbies. *You can't use simple rules to establish unicity (same hobby only once per user). You basically create frustration, anger and hatred and the Force is disturbed. A: Well, The point is that, as long as all hobby1, hobby2 and hobby3 values are not null, AND names are unique, this table could be considered more or less as abbiding by 1NF rules (see here for example ...) But does everybody has 3 hobbies? Of course not! Do not forget that databases are basically supposed to hold data as a representation of reality! So, away of all theories, one cannot say that everybody has 3 hobbies, except if ... our table is done to hold data related to people that have three hobbies without any preference between them! This said, and supposing that we are in the general case, the correct model could be +------------+-------+ | id_person |name | +------------+-------+ for the persons (do not forget to unique key. I do not think 'name' is a good one +------------+-------+ | id_hobby |name | +------------+-------+ for the hobbies. id_hobby key is theoretically not mandatory, as hobby name can be the key ... +------------+-----------+ | id_person |id_hobby | +------------+-----------+ for the link between persons and hobbies, as the physical representation of the many-to-many link that exists between persons and their hobbies. My proposal is basic, and satisfies theory. It can be improved in many ways ... A: Without knowing what keys exist and what dependencies the table is supposed to satisfy it's impossible to determine for sure what Normal Form it satisfies. All we can do is make guesses based on your attribute names. Does the table have a key? Suppose for the sake of example that Name is a candidate key. If there is exactly one value permitted for each of the other attributes for each tuple (which means that no attribute can be null) then the table is in at least First Normal Form. A: If any of the columns in the table accept nulls then then the table violates first normal form. Assuming no nulls, @dportas has already provided the correct answer. A: You say that the hobbies belong to the same domain and that they can move around in the columns. If by this you mean that for any specific name the list of hobbies is in an arbitrary order and kriss could just as easily have dance, ball, swim as ball, swim, dance, then I would say you have a repeating group and the table violates 1NF. If, on the other hand, there is some fundamental semantic difference between a particular person's first and second hobbies, then there may be an argument for saying that the hobbies are not repeating groups and the table may be in 3NF (assuming that hobby columns are FK to a hobby table). I would suggest that this argument, if it exists, is weak. One other factor to consider is why there are precisely 3 hobbies and whether more or fewer hobbies are a potential concern. This factor is important not so much for normalization as for flexibility of design. This is one reason I would split the hobbies into rows, even if they are semantically different from one-another. A: The table does not violate first normal form. First normal form does not have any prohibition against multiple columns of the same type. As long as they have distinct column names, it is fine. The prohibition against "Repeating Groups" concerns nested records - a structure which is common in hierarchical databases, but typically not possible in relational databases. The table using repeating groups would look something like this: +-------+--------+ | name |hobbies | +-------+--------+ | kris |+-----+ | | ||ball | | | |+-----+ | | ||swim | | | |+-----+ | | ||dance| | | |+-----+ | +-------+--------+ | james |+-----+ | | ||eat | | | |+-----+ | | ||sing | | | |+-----+ | | ||sleep| | | |+-----+ | +-------+--------+ | amy |+-----+ | | ||swim | | | |+-----+ | | ||eat | | | |+-----+ | | ||watch| | | |+-----+ | +-------+--------+ In a table conforming to 1NF all values can be located though table name, primary key, and column name. But this is not possible with repeated groups, which require further navigation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Logical error in ternary operator Can somebody explain me why that ternary operetor return the second option instead of the first ? This is the code : $token_sid = ($user->data['user_id'] == ANONYMOUS && !empty($config['form_token_sid_guests'])) ? $user->session_id : ''; And here are the values for my actual testing $user->data['user_id'] = 36412 ANONYMOUS = 1 $config['form_token_sid_guests'] = 0 $user->session_id = 4c148b664b7284ecb776c0a932ddf008 $token_sid = '' Any idea why that return the empty value instead of the user session id ? A: $user->data['user_id'] = 36412 is not equal to ANONYMOUS = 1 (36412 != 1) So the first "AND"-Condition failes and your else-"Block" will be evaluated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633111", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Graphical front-end for references in Eclipse is there any graphical plugin/front-end for eclipse to handle/search for references like in Mendeley or Endnote. I know that the texClipse plugin comes with a bibtex editor but it takes quite a while to put all references together by hand. Regards, syrvn A: Sadly, I don't know about any such plug-in. Maybe Mendeley can export selected publications into a bib file that can be used with Texlipse (AFAIK Zotero, the manager I use can do this).
{ "language": "en", "url": "https://stackoverflow.com/questions/7633115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I concatenate array elements into a string? I have string whose value are like FirstName;LastName;Phone e.g. Tom;Hanks;12346789 I am populating a UIVewTable Label text is suposed to be FirstName,LastName e.g. Tom,Hanks Then I put the phone in details bit. I am splitting the String based on semiColumn ; then concatenating the first two elements of array and comma and third element in description. It is working fine but I think the concatenation of array elements is not probably the best or normal way seems like a hack. Can I please get somehelp getting it right. My code is below NSArray *title = [[dataArray objectAtIndex:indexPath.row] componentsSeparatedByString:@";"]; //This bit below does not look right. cell.textLabel.text = [[[title objectAtIndex:0] stringByAppendingString:@","] stringByAppendingString:[title objectAtIndex:1]]; cell.detailTextLabel.text = [title objectAtIndex:2]; A: Slightly better solution: cell.textLabel.text = [NSString stringWithFormat:@"%@,%@", [title objectAtIndex:0], [title objectAtIndex:1]];
{ "language": "en", "url": "https://stackoverflow.com/questions/7633124", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: In IE 8/9 - cant click image, inside anchor that is wrapped with span using display:block I've got a bit of a problem creating a navigation element - its working fine in firefox, but seems to be causing me a headache in IE8/IE9. The other odd thing is that it works fine in IE on when running under localhost, but not when run on a server. I've tried to narrow down the actual issue, and its seems to be caused by me wrapping a couple of elements (an img and some text), in a span that has display:block. When I do this the image no longer responds to the href javascript of the anchor tag. Its kind of difficult to explain so I've included a cut down example: <a title="My Link" href='javascript:alert(1);' style="display: block; height: 37px; text-decoration: none;"> <span style="display: block; height: 34px;"> <img title="My Icon" src="mypic.png" alt="ss" /> <span>Link Text</span> </span> </a> Any help would be great! Matt A: The other odd thing is that it works fine in IE on when running under localhost, but not when run on a server. In that case, the problem is to do with the rendering mode that IE is using. Hit F12 to bring up the Developer Tools to see which mode is being used. Adding this to your <head> should sort the problem out: <meta http-equiv="X-UA-Compatible" content="IE=edge">
{ "language": "en", "url": "https://stackoverflow.com/questions/7633127", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I get all values in a JIRA multi-checkbox customfield with SOAP? I'm developing a web application that uses SOAP to communicate with JIRA. I have a custom field that contains several checkboxes, and I can get this field through SOAP, but I can't get to the actual checkboxes it contains. Is there a way to do this? A: Since nobody has answered this so far, here is an old copy of some JavaScript I did for JIRA, reading customfields. var unitlist_val = $("#unitList_0").val(); var errorlist_val = $("#errorList_0").val(); var larmlist_val = $("#larmList_0").val(); var URL= ""+jira+"/sr/jira.issueviews:searchrequest-xml/temp/SearchRequest.xml jqlQuery=project+%3D+"+problem+ "+AND+%22Symptom+1+-+Component%22+~+%22+"+unitlist_val+"%22+AND+%22Symptom+2+-+State%22+~+%22"+errorlist_val+ "%22+AND+%22Symptom+3+-+alarm%22+~+%22"+larmlist_val+ "%22&tempMax=1000&field=title&field=link&field=customfield_10422&field=customfield_10423&field=customfield_10424&field=customfield_10420&field=resolution&field=customfield_10440"; $.ajax({ type: "GET", url: URL, dataType: "xml", cache: false, beforeSend: function(request) { request.setRequestHeader("Accept", "text/xml; charset=utf-8"); }, success: function(data){ $(data).find("item").each(function(){ // Make sure swedish chars, are handled properly. Append to page first, then get value. var unitList = $("<div/>").html($(this).find("#customfield_10422 customfieldvalue").text()).text().split(","); var errorList = $("<div/>").html($(this).find("#customfield_10423 customfieldvalue").text()).text().split(","); var alarmList = $("<div/>").html($(this).find("#customfield_10424 customfieldvalue").text()).text().split(","); var knownerror = $("<div/>").html($(this).find("#customfield_10420 customfieldvalue").text()).text() || "None"; var resolution = $("<div/>").html($(this).find("resolution").text()).text() || "None"; } }); You can probably do something similar in Java and use a simple GET request. I cut out quite a lot of code, so some parts might be syntax error on.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to delete a selected item from the listview? SORRY FOR THIS CONFUSION: UPDATED QUESTION: I'm trying to remove a list item from the listview. when the item is clicked, the alertdialog is shown. If i click OK, then the selected item must be removed from the listview. My Code goes below: case R.id.lvinc: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Delete Event "); builder.setMessage("Delete this Event ?"); builder.setPositiveButton("Ok, Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { ???? //What code to delete the selected list item? }catch(Exception e) { e.printStackTrace(); } } }); AlertDialog alert = builder.create(); alert.show(); displaylist(); break; Any help is really appreciated and thanks in advance... A: I don't know what kind of data you are using. I imagine Cursor, database or List, feel free to tell us, so it will be easier to help. This example is for a list: protected void onListItemClick(View v, int pos, long id) { Log.i(TAG, "onListItemClick id=" + id); //Display your Dialog (...) builder.setPositiveButton("Ok, Delete", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { myList.remove(pos); myAdapter.notifyDataChanged(); } }); } A: I tried to solve it and got one solution pls go through the code below: listview.java public class listview extends Activity implements OnItemClickListener{ ListView list; ListAdapter adapter; ArrayList<String> nameArray; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);//xml should have an ListView element nameArray = new ArrayList<String>(); nameArray.add("Item1"); nameArray.add("Item2"); nameArray.add("Item3"); nameArray.add("Item4"); nameArray.add("Item5"); list = (ListView) findViewById(R.id.listView); list.setOnItemClickListener(listview.this); adapter=new ListAdapter(listview.this, nameArray); list.setAdapter(adapter); } @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { showDialog(arg2); } @Override protected Dialog onCreateDialog(final int id) { Builder builder = new AlertDialog.Builder(this); builder.setMessage("Delete Event") .setCancelable(true) .setPositiveButton("Ok, Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { nameArray.remove(id); adapter=new ListAdapter(listview.this, nameArray); list.setAdapter(adapter); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = builder.create(); dialog.show(); return super.onCreateDialog(id); } } //Adapter Class ListAdapter.java public class ListAdapter extends BaseAdapter { private Activity activity; private ArrayList<String> name; private static LayoutInflater inflater=null; public ListAdapter(Activity a, ArrayList<String> nameArray) { activity = a; name = nameArray; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public int getCount() { return name.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public static class ViewHolder{ public TextView text; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; ViewHolder holder; if(convertView==null){ vi = inflater.inflate(R.layout.list_item, null); holder=new ViewHolder(); holder.text=(TextView)vi.findViewById(R.id.title); vi.setTag(holder); } else holder=(ViewHolder)vi.getTag(); holder.text.setText(name.get(position)); return vi; } } A: You propably have some kind of Adapter, that you have feed with some kind of data. Remove the item from that list, and notifyDataChanged to the ListView. And finally: dialog.dismiss(); A: itemLayout.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { indexClick = position; } } if ((indexClick) == (position)) { itemLayout.setBackgroundResource(R.drawable.tab_select); } otherwise put tab_unselected image.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remote exception through .NET Remoting? Possible Duplicate: .NET Remoting Exception not handled Client-Side I have a client-server applicaytion working with .NET Remoting. Server contains a class (RemoteClass) which contains a method throwing exception. But this exception crushes server instead of being handled by client try/catch block. My code looks like: //Common library public class RemoteClass : MarshalByRefObject { public void SomeMethod () { throw new NotSupportedException (); //Standart exception with Serializible attribute } } //Client-side code try { //remote is instance of remoteobject,the other its methods work fine remote.SomeMethod (); } catch(exception e) { //I want to handle exception here } But as I mentioned above my server-side is crushed...( Is there a way to do what I want via .NET Remoting?
{ "language": "en", "url": "https://stackoverflow.com/questions/7633136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Installing Perl/Tk on fedora I am having trouble trying to install perl Tk on my system(fedora,perl v5.8.8).I downloaded the tarred module from http://search.cpan.org/~srezic/Tk-804.029/pod/gencmd, untarred it.In the terminal,I gave "perl Makefile.PL" which worked fine and then "make" which could not complete.Here is what it gave: "make[1]: Entering directory `/work/harikal/Tk-804.029/pTk' gcc -c -I.. -I. -Ibitmaps -D_REENTRANT -D_GNU_SOURCE -fno-strict-aliasing -pipe -Wdeclaration-after-statement -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/usr/include/gdbm -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables -DVERSION=\"804.029\" -DXS_VERSION=\"804.029\" -fPIC "-I/usr/lib/perl5/5.8.8/i386-linux-thread-multi/CORE" -Wall -Wno-implicit-int -Wno-comment -Wno-unused -D__USE_FIXED_PROTOTYPES__ tkImgPhoto.c tkImgPhoto.c: In function ‘AllocateColors’: tkImgPhoto.c:3584: warning: implicit declaration of function ‘sazeof’ tkImgPhoto.c:3584: error: expected expression before ‘XColor’ make[1]: *** [tkImgPhoto.o] Error 1 make[1]: Leaving directory `/work/harikal/Tk-804.029/pTk' make: *** [pTk/libpTk.a] Error 2" and then it exits. What am I supposed to do?? Please Help Thanks. A: If you're using the system-installed Perl, then why not use the Fedora project's pre-built package for the module. $ sudo yum install perl-Tk A: I looked at http://cpansearch.perl.org/src/SREZIC/Tk-804.029/pTk/mTk/generic/tkImgPhoto.c - line 3584 and here says "sizeof" not "sazeof". Doublecheck your source/download.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633143", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Please return to the payment page and correct the address i have an problem with integration of paypal sandbox for Australia. in back end i enabled all tab except billing_phone number. when i click pay now i get following error Please return to the payment page and correct the address. here i am attaching my code. thanks in advance <iframe name="hss_iframe" width="600px" height="600px" style="margin-top:-5px"></iframe> <form style="display:none" target="hss_iframe" name="form_iframe" method="post" action="https://securepayments.sandbox.paypal.com/acquiringweb"> <input type="hidden" name="cmd" value="_hosted-payment"> <input type="hidden" name="currency_code" value="AUD"> <input type name="subtotal" value="71"> <input type="hidden" name="business" value="FK4PGWANVUF9C"> <input type="hidden" name="shipping" value="0"> <input type name="paymentaction" value="sale"> <input type="hidden" name="template" value="templateD"> <input type="hidden" name="invoice" value="12345"> <input type="hidden" name="billing_first_name" value="John"> <input type="hidden" name="billing_last_name" value="Due"> <input type="hidden" name="billing_address1" value="5 Cromwell St"> <input type="hidden" name="billing_address2" value="Glen Iris"> <input type="hidden" name="billing_city" value="Glen Iris"> <input type="hidden" name="billing_state" value="VIC"> <input type="hidden" name="billing_zip" value="3146"> <input type="hidden" name="buyer_email" value="[email protected]"> <input type="hidden" name="billing_country" value="AU"> <input type name="return" value="https://122.165.58.219/team2/wpp-hosted/receipt_page.html"> </form> <script type="text/javascript"> document.form_iframe.submit(); </script> A: My code wasn't working either, but I didn't have the billing fields which I have now added and it worked. I didn't have: <input type="hidden" name="currency_code" value="AUD"> <input type="hidden" name="shipping" value="0"> Hope this helps anyone A: I had the same problem. I resolved it by adding the same bunch of fields but without "billing_". In your case it will be: <input type="hidden" name="first_name" value="John"> <input type="hidden" name="last_name" value="Due"> <input type="hidden" name="address1" value="5 Cromwell St"> <input type="hidden" name="city" value="Glen Iris"> <input type="hidden" name="state" value="VIC"> <input type="hidden" name="zip" value="3146"> <input type="hidden" name="country" value="AU"> I don't know whether it's important or not but I also removed both "billing_address2" and "address2".
{ "language": "en", "url": "https://stackoverflow.com/questions/7633148", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# arraylist user input I have a problem with ArrayList in C#, I know how can I add my own input and run the program so the Array is filled with information. But I would like to fill an ArrayList based on user input. This is what I need: the user could enter his/hers name, birthdate and age. And all these theree information would be stored in one element. My goal is to be able to make an application which would allow the user to enter this kind of data for several people and then print the output. Here is my code: I have a class Person which handles the user information: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ArrayList_Siomple_Sorted_10 { class Person { private string personName; private DateTime birthDate; private double personAge; public Person(string name, DateTime bDate, double age) { personName = name; birthDate = bDate; personAge = age; } public string Name { get { return personName; } set { personName = value; } } public DateTime Birthdate { get { return birthDate; } set { birthDate = value; } } public double Grade { get { return personAge; } set { personAge = value; } } public void Show() { Console.WriteLine(personName + " " + birthDate.ToString("d.M.yyyy") + " " + personAge); } } } And this is the Main class with main method: using System; using System.Collections; using System.Text; namespace ArrayList_Siomple_Sorted_10 { class Program { static void Main(string[] args) { DateTime birthDateP3 = new DateTime(1980, 2, 25); Person p3 = new Person("Ann Person", birthDateP3, 8); DateTime birthDateP2 = new DateTime(1980, 2, 25); Person p2 = new Person("Ann Person", birthDateP2, 8); DateTime birthDateP1 = new DateTime(1980, 2, 25); Person p1 = new Person("Ann Person", birthDateP1, 8); ArrayList ar = new ArrayList(); ar.Add(p1); ar.Add(p2); ar.Add(p3); Console.WriteLine("Print the original Array"); foreach (Person pr in ar) pr.Show(); } } } Is the thing I am trying to achieve even possible? Thank you for your answers. V. A: Yes - it's possible. What is the exact issue that are you facing here? BTW, instead of ArrayList, you should be using generic collection List<Person>. From console program, you will use Console.ReadLine to get user input, validate/parse it and fill person instance and add to your list. For example, ... var ar = new List<Person>(); var name = Console.ReadLine(); // validate name (check if its not blank string etc) ... var dob = Console.ReadLine(); // validate date of birth (date/time format, past date etc) ... DateTime dateOfBirth = DateTime.Parse(dob); // compute age var age = (DateTime.Now - dateOfBirth).Years; var p = new Person(name, dateOfBirth, age); ar.Add(p); ... A: First of all, you should consider using List<T> instead of ArrayList. Secondly, off course, this is possible. You can do it in the following way. static void Main(string[] args) { DateTime birthDateP3 = new DateTime(1980, 2, 25); Person p3 = new Person("Ann Person", birthDateP3, 8); DateTime birthDateP2 = new DateTime(1980, 2, 25); Person p2 = new Person("Ann Person", birthDateP2, 8); DateTime birthDateP1 = new DateTime(1980, 2, 25); Person p1 = new Person("Ann Person", birthDateP1, 8); ArrayList ar = new ArrayList(); string name = Console.ReadLine(); ar.Add(name); Console.WriteLine("Print the original Array"); foreach (Person pr in ar) pr.Show(); } And you should be using Generic list instead of ArrayList like this: List<string> mylist = new List<string>(); string str = Console.ReadLine(); mylist.Add(str); A: Sure, you can read input data using Console.ReadLine() method or if you want a more sophisticated interface you can use Windows Form API.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Solr thinks a string field is a multivalued. Why? i'm trying to index a field in solr which is a string which may contain commas. Solr doesn't care about the type string, and gives me this exception http://pastie.org/2631085 (i'm running a custom plugin, that's why the unconventional error) As you can see, "Charlotte, NC" should be a string (like there are many similars around being indexed without error) but solr wants me to put a multivalued field for it. Why? I used CDATA on the xml and it fixes the problem, but i want to know why solr behaves like this. No manuals nor forum around seem to be any helpful! Ty in advance EDIT: this is the field definition in schema.xml <fieldType name="string" class="solr.StrField" sortMissingLast="true" omitNorms="true"/> <field name="location" type="string" indexed="true" stored="true" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7633153", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Coloring code disappeared Today I opened Eclipse Helios, and wanted to do some job. But when it opened I saw that there is no highlighted code, just class field are blue. I don't remember that I was changing configuration. How to set this to default? Here is screenshot: Now keywords like public, void, throws are just black and bold. A: try restore defaults under window-> Preferences.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jquery doesn't remove div always on mouseleave This is very annoying. After you rollover on image, if you rollout from left, top or right edges red box disappears. But if you rollout from bottom edge red box sometimes disappears sometimes not. Why is that? http://jsfiddle.net/f98r3/2/ Edit: Another weird thing is, when you check console log, mouseleave fires but doesn't remove div!!!. Edit 2: Ok both answers solved the problem but still I wonder how on earth console.log logs the mouseleave in the original code but doesn't trigger remove()? A: I think that the outer div creates some problem, this way it works: http://jsfiddle.net/f98r3/5/ $("img").bind("mouseenter", function () { $("#enlargemag").remove(); var imgobj = this; var w = $(imgobj).width(); var h = $(imgobj).height(); var p = $(imgobj).position(); $("<div id='enlargemag' style='border:none;cursor:pointer;position:absolute;top:" + p.top + "px;left:" + p.left + "px;width:" + w + "px;height:" + h + "px;background-color:#FF0000;'></div>").appendTo("body"); }); $("#enlargemag").live("mouseleave", function () { console.log("mouselave"); $("#enlargemag").remove(); }); A: display: block for image solves the problem
{ "language": "en", "url": "https://stackoverflow.com/questions/7633158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to set only the preferred width of Panel with flow layout? I have a panel with flow layout, and it can contain a variable number of items - from 1 to 2000. I want to put it inside a scroll pane, scrollable in vertical direction, and with fixed width. The problem is, when I set preferred size of panel to something like (800,600), some items are missing, and there is no scroll. If I set up preferred size of scroll pane, then all elements in flow pane are put on one very long line. Setting maximum size on any element seems to do nothing at all - layout managers ignore it. How can I fix this? A: I want to put it inside a scroll pane, scrollable in vertical direction, and with fixed width You can use the Wrap Layout for this. Don't set the preferred size of the panel. But you can set the preferred size of the scroll pane so the frame.pack() method will work. A: You could use BoxLayout to do this: JPanel verticalPane = new JPanel(); verticalPane.setLayout(new BoxLayout(verticalPane, BoxLayout.Y_AXIS)); JScrollPane pane = new JScrollPane(verticalPane); //add what you want to verticalPane verticalPane.add(new JButton("foo")); verticalPane.add(new JButton("bar")); This of course will use the preferred size of each component added. If you want to modify the preferred size for example of a JPanel, extend it and override getPreferredSize: class MyPanel extends JPanel(){ public Dimension getPreferredSize(){ return new Dimension(100,100); } } A note: BoxLayout will take in consideration getPreferredSize, other LayoutManager may not. Please criticize my answer, I'm not sure it's completely correct and I'm curious to hear objections in order to know if I understood the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633161", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: adding functions to injected elements Okay how can i add function to injected elements(which that element dosent exist on first browser load). Please read through my example carefully , i hope you can understand. For example: i go to www.website.com , when it loads it loads up "functions.js" and "other.js" , inside "functions.js" there's a code that injects a new div with ID when user click on a button. The injection code as shown below:(functions.js --jquery) $('a#button').click(function(){ $('a#button').after('<div id="new">New div<br><a href="#" id="newdivlink">Another link</a></div>'); }); However there's another on click functions loaded in another js file which is "other.js" (loaded same time as function.js load). Inside "other.js" has the code for the onclick function when the new div's link (#newdivlink) is clicked. other.js : $('a#newdivlink').click(function(){ alert('you clicked on new div's link yay?'); }); But the problem is , the onclick function for the new div's link(#newdivlink) cant be executed as the script can't find the div (as it is being injected after i loads). Or is there some problems ? P/S if you are asking why not combine both scripts , i don't want, as i want to try this technique out. A: use live() for jQuery version < 1.7 or on() for version >= 1.7 A: Try using 'live' instead of click: $('a#newdivlink').live('click', function(){ A: What you probably need is jQuery.live. $('a#newdivlink').live("click", function(){ alert('you clicked on new div's link yay?'); });
{ "language": "en", "url": "https://stackoverflow.com/questions/7633164", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: highlight a text in textview How can we highlight a text in textview like the imgage shown below,the user tap the select verse it hilight the verse in yellow color and a popup window apper for that verse for doing action.How to do this? Thanks in advance. A: It is only doable using CoreText, because it needs formatting attributes and NSAttributedString to display text with multiple font style and colors. You may be interested in my OHAttributedLabel class that is a subclass of UILabel to render NSAttributedString (obviously it uses CoreText for this). As setting the background color of a range of text is not directly possible/supported (no corresponding attribute in NSAttributedString), you may need to draw the yellow rectangles (before drawing the text) yourself, but I've done this in my class too to manage highlighted links (see drawActiveLinkHighlightForRect: method) so you may do a similar thing in your case.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633167", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deleting from SQLite Hy! I always get e sql error. I log the id of the choosen item and then i want to remove it from the ListView and from the db My code: public boolean onItemLongClick(final AdapterView<?> arg0, final View arg1, final int arg2, long arg3) { final Pizza pizza = (Pizza)arg0.getItemAtPosition(arg2); Log.e("xxx",String.valueOf(pizza.id)); AlertDialog.Builder builder = new AlertDialog.Builder(Main.this); builder.setMessage("Are you sure you to delete " + pizza.title + "?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { aa.notifyDataSetChanged(); list.remove(pizza); aa = new CustomAdapter(Main.this, R.layout.customlistitem,list); lv.setAdapter(aa); myDB = Main.this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null); myDB.execSQL("DELETE FROM "+MY_DB_TABLE+ " WHERE ID="+pizza.id); } Log: xxx is 1 so the id of the pizza is 1 10-03 09:23:13.135: ERROR/AndroidRuntime(640): android.database.sqlite.SQLiteException: no such column: ID: DELETE FROM Pizza WHERE ID=1 A: Preferred way to delete from SQLLite DB is with db.delete() Something like: db.delete(DBAdapter.TableName, "Id=?", new String[] { pizza.id }); A: You sure your pizza ID column named "ID"? android sqlite database already has a column nameed "_id" as the ID field. A: android.database.sqlite.SQLiteException: no such column: ID: DELETE FROM Pizza WHERE ID=1 Error indicates that there is No Column named ID, so ensure that the Name of Pizza id is ID or something else.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Suggestion for using php array? Let say i have 100k records in table, after fetching that records from table i am pushing it to an array with some calculations, and then send them to server for further processing. I have test the scenario with(1k) records, its working perfectly, but worrying about if there is performance issue, because the page which do calculation and fetching records from db run after each 2 mins. My Question is can I use array for more than 2 Millions records? A: There's no memory on how much data an array can hold, the limit is server memory/PHP memory limit. Why would you push 100k records into an array? You know databases have sorting and limiting for that reason! A: Let say i have 100k records in table, after fetching that records from table i am pushing it to an array with some filters. Filters? Can't you just write a query that implements those filters instead? A database (depending on vendor) isn't just a data store, it can do calculations and most of the time it's much quicker than transferring the data to PHP and doing the calculations there. If you have a database in, say, PostgreSQL, you can do pretty much everything you've ever wanted with plpgsql. A: My Question is can I use array for more than 2 Millions records? Yes you can, 2 Million array entries is not a limit in PHP for arrays. The array limit depends on the memory that is available to PHP. ini_set('memory_limit', '320M'); $moreThan2Million = 2000001; $array = range(0, $moreThan2Million); echo count($array); #$moreThan2Million You wrote: The page is scheduled and run after 2 min, so I am worrying about the performance issue. And: But I need to fetch all, not 100 at time, and send them to server for further processing. Performance for array operations is dependent on processing power. With a fast enough computer, you should not run into any problems. However, keep in mind that PHP is an interpreted language and therefore considerably slower than compiled binaries. If you need to run the same script every 2 minutes but the runtime of the script is larger than two minutes, you can distribute script execution over multiple computers, so one process is not eating the CPU and memory resources of the other and can finish the work in meantime another process runs on an additional box. Edit Good answer, but can you write your consideration, about how much time the script will need to complete, if the there is no issue with the server processor and RAM. That depends on the size of the array, the amount of processing each entry needs (in relation to the overall size of the array) and naturally the processor power and the amount of RAM. All these are unspecified with your question, so I can specifically say, that I would consider this unspecified. You'll need to test this on your own and building metrics for your application by profiling it. I have 10GB RAM and More than 8 Squad processor. For example you could do a rough metric for 1, 10, 100, 1000, 10000, 100000 and 1 million entries to see how your (unspecified) script scales on that computer. I am sending this array to another page for further processing. Metric as well the amount of data you send between computers and how much bandwidth you have available for inter-process communication over the wire.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android listview adapter show text from sqlite I need a little help with my custom list view adapter. I'm using the adapter example from vogella.de, but I need to find a way how to set text and image from sqlite database. Here is the adapter code which I am using : import android.app.Activity; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; public class MyArrayAdapter extends ArrayAdapter<String> { private final Activity context; private final String[] names; Cursor cursor; public MyArrayAdapter(Activity context, String[] names) { super(context, R.layout.main_listview, names); this.context = context; this.names = names; } // static to save the reference to the outer class and to avoid access to // any members of the containing class static class ViewHolder { public ImageView imageView; public TextView textView,textView2; } @Override public View getView(int position, View convertView, ViewGroup parent) { // ViewHolder will buffer the assess to the individual fields of the row // layout ViewHolder holder; // Recycle existing view if passed as parameter // This will save memory and time on Android // This only works if the base layout for all classes are the same View rowView = convertView; if (rowView == null) { LayoutInflater inflater = context.getLayoutInflater(); rowView = inflater.inflate(R.layout.main_listview, null, true); holder = new ViewHolder(); holder.textView = (TextView) rowView.findViewById(R.id.main_name); holder.textView2 = (TextView) rowView.findViewById(R.id.main_info); holder.imageView = (ImageView) rowView.findViewById(R.id.main_img); rowView.setTag(holder); } else { holder = (ViewHolder) rowView.getTag(); } final Bitmap b = BitmapFactory.decodeFile("/sdcard/52dde26940e0d3081f6a086d4b54cd1c.jpg", null); holder.textView.setText(""); holder.textView2.setText(""); holder.imageView.setImageBitmap(b); return rowView; } public String[] getNames() { return names; } } And I'm trying to set the text to a text view like this : String sql = "SELECT title FROM collections"; Cursor cursorTitle = userDbHelper.executeSQLQuery(sql); if(cursorTitle.getCount()==0){ Log.i("Cursor Null","CURSOR TITLE NULL"); } else if(cursorTitle.getCount()>0){ cursorTitle.moveToFirst(); String text = cursorTitle.getString(cursorTitle.getColumnIndex("title")); Log.i("title text","title text : "+text); String[] names = new String[] { text }; listView.setAdapter(new MyArrayAdapter(this, names)); } ,but when I run that code I don't get anything in my listview as a result. So can anyone suggest me how can I set the text and image in imageview and textview in my activity using this adapter. Thanks a lot! A: Check this out String text = cursorTitle.getString(cursorTitle.getColumnIndex("title")); Log.i("title text","title text : "+text); String[] names = new String[] { text }; What's the result of 'text' in LogCat? Any value stored in 'names' array? A: Where did you use the String array in adapter,you passed to it? i think,you set null in your both textviews. You need to use it like holder.textview.setText(names[position]) in your adapter. And second thing,you should use for loop for creating your string array from cursor.It seems like you will always get just the first result of your cursor data. A: Try to do something like this : MyAddapterClass : private final Activity context; private final String[] names; private final Bitmap image; private final String text; private final String text2; Cursor cursor; public MyArrayAdapter(Activity context, String[] names, Bitmap image, String text, String text2) { super(context, R.layout.main_listview, names); this.context = context; this.names = names; this.image = image; this.text = text; this.text2 = text2; } and set image, text and text2 to your holders : holder.textView.setText(text); holder.textView2.setText(text2); holder.imageView.setImageBitmap(image); and initialize it in your Activity.That's it. Hope it helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/7633175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jersey: how to use InjectableProvider with @Context annotation? I followed this post and created by first custom injectable provider, a LocaleProvider that scans the HTTP Request for the Accept-Language header. It works fine if I use it within a Jersey resource: @Path("test") @GET public Response getStatus(@Context Locale locale) { log.finer("Locale: "+ locale); Response response = Response .noContent() .build(); return response; } But when I want to use it in an ExceptionMapper I don't know how to inject the locale. I've tried to annotate it as a member variable: public class MyExceptionMapper implements ExceptionMapper<MyException> { @Context private Locale locale; @Override public Response toResponse(MyException ex) { ... } } but this fails at deployment: The following errors and warnings have been detected with resource and/or provider classes: SEVERE: Missing dependency for field: private java.util.Locale com.package.MyExceptionMapper.locale Other things like UriInfo or HttpServletRequest can be injected like that. How do I get access to my own LocaleProvider? FYI this is on Glassfish 3.1.1 using Jersey 1.8. A: There is a scope mismatch. ExceptionMapper is a singleton, while your injectable is per-request-scope. UriInfo works around it using ThreadLocals.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: link external stylesheet conflicting with script src loading jquery? Hi I was doing a simple expanding slider with jquery and somehow the slider would expand to the full-width of the window, then shrink to the desired width I assigned it to do .. (if you reload the page a few times, it comes up sometimes) the problem seems to disappear switch the loading order of the and between jquery and my external stylesheet but I am not sure why, I am wondering if anyone knows ???? here is the code that's causing the problem html: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript" src="jquery-1.6.1.min.js"></script> <link type="text/css" href="screen.css" rel="stylesheet" media="screen" /> <script> $(document).ready(function(){ $("#slider").animate({width:'100px'},1300); }); </script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>TEST</title> </head> <body> <div id="slider"> </div> </body> </html> css: #slider{ width:10px; height:20px; background:#09C; } after switch the order of and the expanding issue disappear: html: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <link type="text/css" href="screen.css" rel="stylesheet" media="screen" /> <script type="text/javascript" src="jquery-1.6.1.min.js"></script> <script> $(document).ready(function(){ $("#slider").animate({width:'100px'},1300); }); </script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>TEST</title> </head> <body> <div id="slider"> </div> </body> </html> css: #slider{ width:10px; height:20px; background:#09C; } A: Because scripts should always be loaded after static assets? Most browsers render line by line from top to bottom so a change made on one line can be changed again on the next line. If one loads the script first then the style will change the script.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Javascript Canvas Lat Lng Plotting I want to create a data visualization similar to this: ...but for the entire globe. The canvas size will be arbitrary but won't need to resize with the browser (I will set the width and height before I start plotting points). I need to figure out a way of converting latitude and longitude coordinates to points on the canvas. Does anyone know how to do it? A: First of all you need to choose projection. Then you can use proper formula. Or you can just use existent solution like proj4js for example. This is JS port of well-known proj utility for working with various projections. I would recommend to use Miller Projection for the visualizations on the whole globe. You can find formulas here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633183", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to remove spaces from pagination on CodeIgniter? I use the pagination helper from CodeIgniter and it works. But when I see the result in my browser, I can observ unwanted spaces. CodeIgniter seems to insert them in an automatic way. In my view: <div><?php echo $this->pagination->create_links(); ?></div> The code generated behind (html): <div> &nbsp; <a href="http://...example.../6">Previous</a> &nbsp; <a href="http://...example.../">1</a> &nbsp; <a href="http://...example.../6">2</a> &nbsp; <strong>3</strong> &nbsp; <a href="http://...example.../18">4</a> &nbsp; <a href="http://...example.../24">5</a> &nbsp; <a href="http://...example.../18">Next</a> &nbsp; &nbsp; <a href="http://...example.../30">Last</a> </div> So there is a space before my previous link and two spaces before my "Last" link. Same thing happens when it's reversed (two spaces after my "First" link). Why? It really blow my mind! Please do you know how to remove them? Any suggestions gratefully received. Solution (thanks to uzsolt's answer) : It works with first_tag_close and last_tag_open set to '' (see comments for more details). A: Maybe you can set num_tag_open and num_tag_close config variable. A: After trying all sorts of things by setting the config values from both within my controller and a application/config/pagination.php file. I managed to solve it by going into system/libraries/Pagination.php and reset the default values without any '&nbsp;'. Hope this helps someone else.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Firebird - update row's value in table basing on some condition As far as I remember I could do such update in MS SQL Server: UPDATE MyTable SET MyValue = (IF SomeCondition THEN 1 ELSE 0 END) or different way for update by using CASE: UPDATE MyTable SET MyValue = (CASE WHEN SomeCondition1 THEN 1 ELSE 0 END) Is any of this methods possible in Firebird? I've tried both ways but with no luck. Thanks for answers. A: Which version of FireBird are you using? I tested with 2.5 and the second one (using CASE) works as expected. FireBird doesn't support IF statement in DSQL but you can use IIF internal function, ie following works too: UPDATE MyTable SET MyValue = iif(SomeCondition, 1, 0)
{ "language": "en", "url": "https://stackoverflow.com/questions/7633195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Stripping characters from a Python string I have a string: v = "1 - 5 of 5" I would like only the part after 'of' (5 in the above) and strip everything before 'of', including 'of'? The problem is that the string is not fixed as in it could be '1-100 of 100', so I can't specify to strip everything off after the 10 or so characters. I need to search for 'of' then strip everything off. A: Using the partition method is most readable for these cases. string = "1 - 5 of 5" first_part, middle, last_part = string.partition('of') result = last_part.strip() A: str.partition() was built for exactly this kind of problem: In [2]: v = "1 - 5 of 5" In [3]: v.partition('of') Out[3]: ('1 - 5 ', 'of', ' 5') In [4]: v.partition('of')[-1] Out[4]: ' 5' A: In [19]: v[v.rfind('of')+2:] Out[19]: ' 5' A: p = find(v, "of") gives you the position of "of" in v
{ "language": "en", "url": "https://stackoverflow.com/questions/7633197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to cast void * to float (*)[3] in c++? This is the code snippet. typedef struct Lib3dsMesh { //.. float (*vertices)[3]; //.. } void* lib3ds_util_realloc_array(void *ptr, int old_size, int new_size, int element_size) { // Do something here. return ptr; } mesh->vertices = lib3ds_util_realloc_array(mesh->vertices, mesh->nvertices, nvertices, 3 * sizeof(float)); When I compile this code in visual c++ it returns error "Cannot convert from void* to float(*)[3]". I would like to know how to cast void * to float (*vertices)[3]; A: vertices is a pointer to a 3-element array of float. To do a cast from one pointer type to another, you generally use static_cast: void* result = lib3ds_util_realloc_array( mesh->vertices, mesh->nvertices, nvertices, 3 * sizeof(float)); mesh-vertices = static_cast<float (*)[3]>(result);
{ "language": "en", "url": "https://stackoverflow.com/questions/7633201", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UIImageView positioning problems? i wrote the following code: -(void)viewDidLoad{ JumpVelocity = 10; aStandRightArray = [[NSArray alloc] initWithObjects:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR1" ofType:@"png"]], [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR2" ofType:@"png"]], [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR3" ofType:@"png"]], [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aStandR2" ofType:@"png"]], nil]; aJumpRightArray = [[NSArray alloc] initWithObjects:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"aJumpR" ofType:@"png"]], nil]; aStandRight = [[UIImageView alloc] initWithFrame:CGRectMake(0, 242, 55, 65)]; aStandRight.animationImages = aStandRightArray; aStandRight.animationDuration = 0.5; [self.view addSubview:aStandRight]; aJumpRight = [[UIImageView alloc] initWithFrame:CGRectMake(0, 234, 69, 65)]; aJumpRight.animationImages = aJumpRightArray; [self.view addSubview:aJumpRight];} -(IBAction)buttonJumpRight:(id)sender{ [aStandRight stopAnimating]; [aStandRight removeFromSuperview]; [aJumpRight startAnimating]; jumpTimer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(playerJumpRight) userInfo:nil repeats:YES];} -(void)playerJumpRight{ [aJumpRight removeFromSuperview]; aJumpRight.center = CGPointMake(aJumpRight.center.x + JumpVelocity, 234); [self.view addSubview:aJumpRight]; if(aJumpRight.center.x >= 84.0) { [jumpTimer invalidate]; jumpTimer = nil; [aJumpRight stopAnimating]; aStandRight.center = CGPointMake(84, 242); [aStandRight startAnimating]; [self.view addSubview:aStandRight]; } } basically what i am trying to do here is load up a standing animation, then when the user presses the buttonJumpRight button i stop then unload the standing animation. after that i load up the jump animation and begin to move it across the screen with the playerJumpRight function. everything seems to work fine with two exception: * *the jump animation moves like expected along the x axis but for some reason does not keep its original y position which in the code above is "234". *when the jump animation x position meets the requirements for the if statement everything works like expected newly created position for the standing animation is way off of the desire position of (84, 242). i been searching for quite some time, trying out many different possible solutions but fail at every try. please excused my newbieism as i just start coding for ios/objective c. i greatly appreciate any help you can offer. A: If you remove a subview from its superview, then the center property becomes meaningless as it refers to the superview's coordinate system. Don't remove and re-add aJumpRight from the superview, just amend it's center property, this will move the view along which I think is what you are after. Note that you can also just animate the change to the center using block-based animation, see the UIView class reference here for details. Also, you may be confusing the center of a view with it's frame.origin. The latter is the top left of the view. I don't think setting the center for a view without a superview has any effect, though I'm not sure on that one. You can definitely set the frame origin in this situation.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Catching Flash URLLoader errors I'm trying to bullet proof a URLLoader and wondering where I need to capture things like 404s and more importantly, mid-session timeouts and connectivity failures. The app will be run in places where the connectivity is spotty and it is very possible that a connection will initiate correctly, but will die somewhere in the middle. I'm unable to recreate these scenarios in testing and am hoping someone can point me to a comprehensive list of error handling, so that I can anticipate most of the common network failures and handle them. TIA. A: You only need to handle the ioError and securityError events - that will catch all the errors. Timeouts will just eventually produce an ioError. You might also want to listen to the httpStatus event to get the HTTP code.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633206", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Remove page from Google Listings using robots.txt file Is this the correct way to do this - below is my txt file, would this prevent Google from indexing my admin directory as well as oldpage.php? User-agent: * Allow: / Disallow: /admin/ Disallow: http://www.mysite.com/oldpage.php A: Yes you are absolutely correct except single file restriction. User-agent: * : means for all crawler Allow: / : allow access of full site Disallow: /admin/ : restrict to admin directory Disallow: /oldpage.php : restrict to oldpage.php
{ "language": "en", "url": "https://stackoverflow.com/questions/7633207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Logoff after logonuser on C# I use advapi32.dll's logonuser method to access data over our network. I know it change the thread's user to the information i give it, but i was wondering if there's a way to reverse it. I want to access the data and then return to the local user credentials. A: Some time ago I created a small impersonator class. Basically you wrap your code to execute under another user simply inside a using block: using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) ) { ... <code that executes under the new context> ... } Worked very well for my projects. A: You can call RevertToSelf. That said, there is something to be said for spinning up a dedicated thread for the impersonation task, and terminating it when the impersonation work is complete. This will segregate the impersonation work so that if any callbacks or messages are processed on the main thread they will be performed in the context of the principal user rather than the impersonated user. In fact, the more I think about this the stronger I feel that a dedicated thread is the solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633208", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: shutdownReason : ConfigurationChange, but only static files changed? I'm on IIS 7.5 and ASP.NET 4 with latest official updates. I'm logging all application shutdown reasons. All is working ok, but since a week strange shutdown reasons are logged. This now happens when static files are updated on the server. Example log: shutDownMessage: Change Notification for critical directories. bin dir change or directory rename HostingEnvironment initiated shutdown HostingEnvironment caused shutdown Change Notification for critical directories. bin dir change or directory rename Change Notification for critical directories. bin dir change or directory rename ... (50 lines !) Change in X:\IISTemp\ASPNET4Compilation\root\c6474edd\e8b7124f\hash\hash.web Change Notification for critical directories. bin dir change or directory rename Change Notification for critical directories. bin dir change or directory rename ... (20x !) CONFIG change CONFIG change CONFIG change shutdownReason: BinDirChangeOrDirectoryRename shutDownStack: at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo) at System.Environment.get_StackTrace() at System.Web.Hosting.HostingEnvironment.InitiateShutdownInternal() at System.Web.HttpRuntime.ShutdownAppDomain(String stackTrace) at System.Web.HttpRuntime.OnCriticalDirectoryChange(Object sender, FileChangeEvent e) at System.Web.FileChangesMonitor.OnCriticaldirChange(Object sender, FileChangeEvent e) at System.Web.DirectoryMonitor.FireNotifications() at System.Web.Util.WorkItem.CallCallbackWithAssert(WorkItemCallback callback) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() at System.Threading.ThreadPoolWorkQueue.Dispatch() at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Any idea ? A: The problem has been fixed by updating time sync settings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633219", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Fluent NHibernate - Query over a derived class Lets say I have two classes: public class A { public virtual int Id { get; set; } public virtual Object1 Obj { get; set; } } public class B : A { public new virtual Object2 Obj { get; set; } } I use Fluent NHibernate and I have created two different mappings for the two classes. However, when I try to query class A in my repository, FNH finds both class B and A, which kind of makes sense since both are A. Example (this criteria will query over both A and B): public List<T> GetByName(string name) { return Session.CreateCriteriaOf<A>.Add(Restrictions...); } When writing CreateCriteriaOf<A>, I only want to query over A - not B. How can I solve my problem? A: I think you better make an inheritance tree where both A and B derive from a common (abstract) base type. Then NHibernate can make the distinction by a discriminator column. Of course, your data model should accommodate this, so I hope your model is not prescribed in any way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get public page statuses using Facebook Graph API without Access Token I'm trying to use the Facebook Graph API to get the latest status from a public page, let's say http://www.facebook.com/microsoft According to http://developers.facebook.com/tools/explorer/?method=GET&path=microsoft%2Fstatuses - I need an access token. As the Microsoft page is 'public', is this definitely the case? Is there no way for me to access these public status' without an access token? If this is the case, how is the correct method of creating an access token for my website? I have an App ID, however all of the examples at http://developers.facebook.com/docs/authentication/ describe handling user login. I simply want to get the latest status update on the Microsoft page and display it on my site. A: This is by design. Once it was possible to fetch the latest status from a public page without access token. That was changed in order to block unidentified anonymous access to the API. You can get an access token for the application (if you don't have a Facebook application set for your website - you should create it) with the following call using graph API: https://graph.facebook.com/oauth/access_token? client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET& grant_type=client_credentials This is called App Access Token. Then you proceed with the actual API call using the app access token from above. hope this helps A: It's no more possible to use Facebook Graph API without access token for reading public page statuses, what is called Page Public Content Access in Facebook API permissions. Access token even is not enough. You have to use appsecret_proof along with the access token in order to validate that you are the legitimate user. https://developers.facebook.com/blog/post/v2/2018/12/10/verification-for-individual-developers/. If you are individual developer, you have access to three pages of the data (limited), unless you own a business app. A: You can use AppID and Secret key to get the public posts/feed of any page. This way you don't need to get the access-token. Call it like below. https://graph.facebook.com/PAGE-ID/feed?access_token=APP-ID|APP-SECRET And to get posts. https://graph.facebook.com/PAGE-ID/posts?access_token=APP-ID|APP-SECRET A: You can get the posts by simply requesting the site that your browser would request and then extracting the posts from the HTML. In NodeJS you can do it like this: // npm i request cheerio request-promise-native const rp = require('request-promise-native'); // requires installation of `request` const cheerio = require('cheerio'); function GetFbPosts(pageUrl) { const requestOptions = { url: pageUrl, headers: { 'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0' } }; return rp.get(requestOptions).then( postsHtml => { const $ = cheerio.load(postsHtml); const timeLinePostEls = $('.userContent').map((i,el)=>$(el)).get(); const posts = timeLinePostEls.map(post=>{ return { message: post.html(), created_at: post.parents('.userContentWrapper').find('.timestampContent').html() } }); return posts; }); } GetFbPosts('https://www.facebook.com/pg/officialstackoverflow/posts/').then(posts=>{ // Log all posts for (const post of posts) { console.log(post.created_at, post.message); } }); For more information and an example of how to retrieve more than 20 posts see: https://stackoverflow.com/a/54267937/2879085 A: I had a similar use case for some weeks and I used this API: https://rapidapi.com/axesso/api/axesso-facebook-data-service/ I could fetch all posts and comments in some minutes, worked quite well for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633234", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "65" }
Q: What's the name of this methodology? Complete specification: I want to to this, this, and this Infinite iterations: 1. Design a task, module or little piece of software. 2. Implement. 3. Test. The design and implementation stages occurs practically at the same time. Does this methodology exist? A: I think we'd call it iterative or agile with a complete specification prior to starting iterations.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make url address like I want? I can't find information how to make url address like www.example.com/categories/id-category_name Could you give me example? Thank you A: This should be helpful. http://en.wikipedia.org/wiki/Rewrite_engine
{ "language": "en", "url": "https://stackoverflow.com/questions/7633238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assigning a directory thumbnail image for an MP4 in Android? I'm trying to assign a specific thumbnail image to represent the media file (mp4) within the android directory. By default, I believe android will use the first frame. I've tried metadata/tags to no avail. Please let me know if you have a solution, and I will be forever in your gratitude. Thank you! A: http://code.google.com/p/mp4parser/ This is part of the code I used: String filepath = "/yourFilePathHere/yourFileNameHere.ext"; File sourceFile = new File ( filepath ); IsoBufferWrapper isoBufferWrapper = new IsoBufferWrapperImpl( sourceFile ); IsoFile isoFile = new IsoFile(isoBufferWrapper); isoFile.parse(); AppleItemListBox appleItemListBox = (AppleItemListBox) IsoFileConvenienceHelper.get(isoFile, "moov/udta/meta/ilst"); AppleCoverBox coverBox = (AppleCoverBox) IsoFileConvenienceHelper.get (appleItemListBox, AppleCoverBox.TYPE); List<Box> dataBoxes = coverBox.getBoxes(); byte[] coverBoxByte = null; if (dataBoxes != null && dataBoxes.size() > 0) { AppleDataBox dataBox = (AppleDataBox)dataBoxes.get(0); coverBoxByte = dataBox.getContent(); } Bitmap icon = null; if (coverBoxByte != null){ icon = BitmapFactory.decodeByteArray(coverBoxByte, 0, coverBoxByte.length); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7633240", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Compress audio and video with VP8 and vorbis ogg into avi container I am developing a program to record movies. I grab video from the webcam and audio from the microphone. I want to use Webm VP8 DirectShow filter for video and Xiph Vorbis Ogg filter for audio recording. As far as I understood - the only way to mux these streams is to put it into Webm Muxer container and get an *.webm file as output. But I want to use AVI container also. Is it true that AVI doesn't work with VBR audio? What audio codec should I use along with VP8 to put everything into AVI container? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/7633247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Present or dismiss modal view controller in landscape orientation I have an iPad app with a view of a UIViewController with 3 subview (3 UIViewController). If i present or dismiss a modal view controller in portait orientation I get the view controller with the right frame. If I present or dismiss the modal view controller in landscape orientation i get a wrong frame ("{{0, -256}, {748, 1024}}"). A: I'm getting this same issue. I suspect it's because we're manually managing the view hierarchy and not properly accounting for orientation changes. I'll post any addition discovery, but so far I've found that you can correct the modal view controller after it's presented like so: // Display modal dialog view controller "detailNav" [self presentModalViewController:detailNav animated:YES]; // Create a custom frame for this view, optional, but needs to be set after presenting detailNav.view.superview.frame = customRect; // Recenter the view, for example to the center of your apps main window CGPoint center = myApp.window.center; detailNav.view.superview.center = center;
{ "language": "en", "url": "https://stackoverflow.com/questions/7633252", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ERROR: array value must start with "{" or dimension information This is my function: DECLARE f_ids integer[] := '{}'; BEGIN SELECT INTO f_ids "fileId" FROM "tbFiles" WHERE "size" <= $2 AND "size" >=$1 ; RETURN f_ids; END; This function should return bigint[], but when I try to run it I get this error: SELECT "GetFilesBySize"(0,888) ERROR: array value must start with "{" or dimension information CONTEXT: PL/pgSQL function "GetFilesBySize" line 4 at SQL statement It seems to me that the array is properly initialized, so where is the mistake? A: This will work: DECLARE f_ids integer[]; BEGIN SELECT INTO f_ids array_agg(fileId) FROM tbFiles WHERE size <= $2 AND size >=$1; RETURN f_ids; END But I think, you are better off using real set returning functions or use RETURN QUERY. Lookup the PostgreSQL manual for the both terms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: correlation computation with threshold in R I would like to compute correlations in R. However I have a lot of missing values. So, I would like to admit in the correlations matrix only correlations that were calculated from at least 10 pairs of values. How to proceed? Edit: please note that correlation matrix is generated from two big matrices X and Y having same individuals (rows). A: First we generate some example data: R> x = matrix(rnorm(100), ncol=5) ##Fill in some NA's R> x[3:15,1] = NA R> x[2:10,3] = NA Next we loop through the x matrix doing a comparsion to detect NA's: ##Create a matrix with where the elements are the ##maximum number of possible comparisons m = matrix(nrow(x), ncol=ncol(x),nrow=ncol(x)) ## This comparison can be made more efficient. ## We only need to do column i with i+1:ncol(x) ## Each list element for(i in 1:ncol(x)) { detect_na = is.na(x[,i]==x) c_sums = colSums(detect_na) m[i,] = m[i,] - c_sums } The matrix m now contains the number of comparison for each column pair. Now convert the m matrix in preparation of subsetting: m = ifelse(m>10, TRUE, NA) Next we work out the correlation for all column pairs and subset according to m: R> matrix(cor(x, use = "complete.obs")[ m], ncol=ncol(m), nrow=nrow(m)) [,1] [,2] [,3] [,4] [,5] [1,] NA NA NA NA NA [2,] NA 1.0000 -0.14302 0.35902 -0.3466 [3,] NA -0.1430 1.00000 0.03949 0.6172 [4,] NA 0.3590 0.03949 1.00000 0.1606 [5,] NA -0.3466 0.61720 0.16061 1.0000
{ "language": "en", "url": "https://stackoverflow.com/questions/7633256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: TypeDelegator equality inconsistency? Consider the following code: class MyType : TypeDelegator { public MyType(Type parent) : base(parent) { } } class Program { static void Main(string[] args) { Type t1 = typeof(string); Type t2 = new MyType(typeof(string)); Console.WriteLine(EqualityComparer<Type>.Default.Equals(t1, t2)); // <-- false Console.WriteLine(EqualityComparer<Type>.Default.Equals(t2, t1)); // <-- true Console.WriteLine(t1.Equals(t2)); // <-- true Console.WriteLine(t2.Equals(t1)); // <-- true Console.WriteLine(Object.Equals(t1, t2)); // <-- false Console.WriteLine(Object.Equals(t2, t1)); // <-- true } } How come the various versions of Equals return different results? The EqualityComparer.Default probably calls Object.Equals, so these results match, although inconsistent in themselves. And the normal instance version of Equals both return true. This obviously creates problems when having a method return a Type that actually inherits from TypeDelegator. Imagine for example placing these types as keys in a dictionary, which by default use the EqualityComparer.Default for comparisons. Is there any way to resolve this problem? I would like all the methods in the code above return true. A: The following code returns a System.RuntimeType Type t1 = typeof(string); If you look at the code for Type there is: public override bool Equals(Object o) { if (o == null) return false; return Equals(o as Type); } BUT, System.RuntimeType has: public override bool Equals(object obj) { // ComObjects are identified by the instance of the Type object and not the TypeHandle. return obj == (object)this; } And if you view the assembly it executes a: cmp rdx, rcx, so just a direct memory compare. You can reproduce it using the following: bool a = t1.Equals((object)t2); // False bool b = t1.Equals(t2); // True So it looks like RuntimeType is overriding the Type Equals method to do a direct comparison... It would appear there is no easy way around the issue (without supplying a comparer). EDITED TO ADD: Out of curiosity, I had a look at the .NET 1.0 & 1.1 implementation of RuntimeType. They don't have the override of Equals in RuntimeType, so the issue was introduced in .NET 2.0. A: Update The code from this answer has become a repository on GitHub: Undefault.NET on GitHub Steven gives a good explanation of why this works the way it does. I do not believe there is a solution for the Object.Equals case. However, I've found a way to fix the issue in the EqualityComparer<T>.Default case by configuring the default equality comparer with reflection. This little hack only needs to happen once per application life cycle. Startup would be a good time to do this. The line of code that will makes it work is: DefaultComparisonConfigurator.ConfigureEqualityComparer<Type>(new HackedTypeEqualityComparer()); After that code has been executed, EqualityComparer<Type>.Default.Equals(t2, t1)) will yield the same result as EqualityComparer<Type>.Default.Equals(t1,t2)) (in your example). The supporting infrastructure code includes: 1. a custom IEqualityComparer<Type> implementation This class handles equality comparison the way that you want it to behave. public class HackedTypeEqualityComparer : EqualityComparer<Type> { public override bool Equals(Type one, Type other){ return ReferenceEquals(one,null) ? ReferenceEquals(other,null) : !ReferenceEquals(other,null) && ( (one is TypeDelegator || !(other is TypeDelegator)) ? one.Equals(other) : other.Equals(one)); } public override int GetHashCode(Type type){ return type.GetHashCode(); } } 2. a Configurator class This class uses reflection to configure the underlying field for EqualityComparer<T>.Default. As a bonus, this class exposes a mechanism to manipulate the value of Comparer<T>.Default as well, and ensures that the results of configured implementations are compatible. There is also a method to revert configurations back to the Framework defaults. public class DefaultComparisonConfigurator { static DefaultComparisonConfigurator(){ Gate = new object(); ConfiguredEqualityComparerTypes = new HashSet<Type>(); } private static readonly object Gate; private static readonly ISet<Type> ConfiguredEqualityComparerTypes; public static void ConfigureEqualityComparer<T>(IEqualityComparer<T> equalityComparer){ if(equalityComparer == null) throw new ArgumentNullException("equalityComparer"); if(EqualityComparer<T>.Default == equalityComparer) return; lock(Gate){ ConfiguredEqualityComparerTypes.Add(typeof(T)); FieldFor<T>.EqualityComparer.SetValue(null,equalityComparer); FieldFor<T>.Comparer.SetValue(null,new EqualityComparerCompatibleComparerDecorator<T>(Comparer<T>.Default,equalityComparer)); } } public static void ConfigureComparer<T>(IComparer<T> comparer){ if(comparer == null) throw new ArgumentNullException("comparer"); if(Comparer<T>.Default == comparer) return; lock(Gate){ if(ConfiguredEqualityComparerTypes.Contains(typeof(T))) FieldFor<T>.Comparer.SetValue(null,new EqualityComparerCompatibleComparerDecorator<T>(comparer,EqualityComparer<T>.Default)); else FieldFor<T>.Comparer.SetValue(null,comparer); } } public static void RevertConfigurationFor<T>(){ lock(Gate){ FieldFor<T>.EqualityComparer.SetValue(null,null); FieldFor<T>.Comparer.SetValue(null,null); ConfiguredEqualityComparerTypes.Remove(typeof(T)); } } private static class FieldFor<T> { private const string FieldName = "defaultComparer"; private const BindingFlags FieldBindingFlags = BindingFlags.NonPublic|BindingFlags.Static; static FieldInfo comparer, equalityComparer; public static FieldInfo Comparer { get { return comparer ?? (comparer = typeof(Comparer<T>).GetField(FieldName,FieldBindingFlags)); } } public static FieldInfo EqualityComparer { get { return equalityComparer ?? (equalityComparer = typeof(EqualityComparer<T>).GetField(FieldName,FieldBindingFlags)); } } } } 3. a compatible IComparer<T> implementation This is basically a decorator for IComparer<T> that ensures compatibility between Comparer<T> and EqualityComparer<T> when EqualityComparer<T> is injected. It makes sure that any two values that the configured IEqualityComparer<T> implementation thinks are equal will always have a comparison result of 0. public class EqualityComparerCompatibleComparerDecorator<T> : Comparer<T> { public EqualityComparerCompatibleComparerDecorator(IComparer<T> comparer, IEqualityComparer<T> equalityComparer){ if(comparer == null) throw new ArgumentNullException("comparer"); if(equalityComparer == null) throw new ArgumentNullException("equalityComparer"); this.comparer = comparer; this.equalityComparer = equalityComparer; } private readonly IComparer<T> comparer; private readonly IEqualityComparer<T> equalityComparer; public override int Compare(T left, T right){ return this.equalityComparer.Equals(left,right) ? 0 : comparer.Compare(left,right); } } A: Fascinating q. The middle Equals both being true are because Type.Equals returns the value of ReferenceEquals as invoked on the UnderlyingSystemType property for both sides - and TypeDelegator overrides UnderlyingSystemType to return the Type you constructed it with! How you can persuade a non-Type-ish equality operation to understand this, I don't know. I suspect you can't, and you'll need to always supplier a suitably aware EqualityComparer. A: EqualityComparer<T> defauls to the object.Equals method, so the 1) and 2) cases are equivalent to 5) and 6). I don't see why these comparison should be consistent by default. The true cases happen because System.Type equality implementation is based on the UnderlyingSystemType property. So, you could override Equals(object) and Equals(Type) - BTW, virtual only on Framework 4 -, but that wouldn't fix case 3). So, what you can do to make sure it is consistent is this: class MyType : TypeDelegator { public MyType(Type parent) : base(parent) { } public override Type UnderlyingSystemType { get { return this; } } } With this implementation, all cases will report false, which is consistent, but I'm unsure about the side effects... I suppose it depends on what your code does eventually.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: matching urls with query string I need a piece of code that basically does task of matching URL. I have listed 2 scenarios below to clear how I need the things. Match URL may/may not contain sub-directory, so there are 2 scenarios. http://example.com/?pgid=1 http://example.com/?pgid=1&opt2=2 http://example.com/?opt2=2&pgid=1 http://example.com/?pgid=1&opt2=2&opt3=3 http://example.com/?opt2=2&pgid=1&opt3=3 http://example.com/?opt2=2&opt3=3&pgid=1 should match => http://example.com/?pgid=1 and http://example.com/sub-dir/?pgid=1 http://example.com/sub-dir/?pgid=1&opt2=2 http://example.com/sub-dir/?opt2=2&pgid=1 http://example.com/sub-dir/?pgid=1&opt2=2&opt3=3 http://example.com/sub-dir/?opt2=2&pgid=1&opt3=3 http://example.com/sub-dir/?opt2=2&opt3=3&pgid=1 should match => http://example.com/sub-dir/?pgid=1 How can I achieve above thing, help appreciated. Thanks. A: The regex to mach that url is: \?pgid=1$ As i understand you don't want any other query string parameters in your url. A: I suppose you mean something like this: $input = array('http://example.com/?pgid=1', 'http://example.com/?pgid=1&opt2=2', 'http://example.com/?opt2=2&opt3=3&pgid=1', 'http://example.com/sub-dir/?opt2=2&opt3=3&pgid=1'); foreach($input as $i){ $url = parse_url($i); echo $url['scheme'].'://'.$url['host'].$url['path']; parse_str($url['query'],$query); echo 'pgid='.$query['pgid']; echo '<br/>'; } Obviously you should adjust this to your personal needs, but this shows how you can extract pgid and rebuild the url with just that parameter. Afterwards you can do the matching, probably by just using $query['pgid'] or maybe by using the whole new url. A: you can use parse_url and parse_str: $url = parse_url('http://example.com/?pgid=1&opt2=2&opt3=3'); $against = parse_url('http://example.com/?pgid=1'); $folder = $url['path']; $query = parse_str($url['query']); $pgidout = $pgid; $query = parse_str($against['query']); if(($url['path'] == $against['path']) && ($pgid == $pgidout)){ echo "matched"; } else { echo "not matched"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7633262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Causing VS2010 debugger to break when Debug.Assert fails Is there any way to cause Visual Studio 2010 to break while debugging when the argument of Debug.Assert evaluates to false? Example: in my code I have lines like this: Debug.Assert(!double.IsInfinity(x)); If I am not debugging, a window pops up when the assertion fails. But when I am debugging, the assertion is logged to the "Output" pane, which is easy to miss; there is not popup window and the debugger does not stop. Therefore: is there any way to force the Visual Studio debugger to break when Debug.Assert fails? (BTW: I am developing a WPF based desktop application. In a Windows Forms application, the behavior seems to be differnt: here, the debugger stops on Debug.Assert.) EDIT: Please let me clarify: I am not looking for an alternative to Debug.Assert(), because my code and external code I use is full of Debug.Assert() statements. I am looking for a way to cause the Visual Studio debugger to break when Debugg.Assert fails. (I think earlier VS versions did that, and that the behavior changed in VS2010). A: If by debugging you mean using "Step Into" feature, see this MS's answer to the problem. http://connect.microsoft.com/VisualStudio/feedback/details/522995/system-diagnostics-debug-assert-doesnt-pop-up-messagebox-correctly-when-step-into-it-in-vs-2010-and-2008 Using "Step Over" at the Assert statement does solve the issue too (for me). A: You can use condition breakpoint for this sort of behavior, just set a breakpoint on a line on which you want to break and then right click on the point at the left and choose condition, in popup enter desired condition (in your case is double.IsInfinity(x)) A: Use the Debugger.Break method (in the System.Diagnostics namespace). This will break execution if you are running in a debugger. A: It seems to work as expected for me in a console application at least: in debug builds, a dialog pops up that allows you to break into the application using the debugger, but in release builds, nothing happens. Admittedly, I just used a simplistic Debug.Assert(false);, but I don't see why that should make much of a difference. I'm running Visual Studio 2010 SP1 Ultimate. I'd suggest that you take a close look at your build settings. Here's the code I used: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace ConsoleApplication { class Program { static void Main(string[] args) { System.Diagnostics.Debug.Assert(false); Console.ReadLine(); } } } A: Can't you just throw an exception when !double.IsInfinity(x) instead of using an assertion? A: It appears that your app removed the default TraceListener from the Debug class, and replaced it with a custom one that implements the Fail(string) method differently. You may be able to track it down by searching your code for Debug.Listeners and see if somewhere the default one is cleared out or modified, or see if you've got a trace section in your app.config. By default, from what I've read, you should definitely get the popup window. A: If using the DefaultTraceListener you can add the following section to your app.config file which enables breaking on Debug.Assert(false): <configuration> <system.diagnostics> <assert assertuienabled="false"/> </system.diagnostics> </configuration> For details see assert element and DefaultTraceListener.AssertUiEnabled Property.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633265", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: when i use bundle , Could not reach rubygems repository http://rubygems.org/ aoople@aoople:~/projects/jobs$ bundle Fetching source index for http://rubygems.org/ Could not reach rubygems repository http://rubygems.org/ Could not find hoptoad_notifier-2.4.11 in any of the sources somebody help me !
{ "language": "en", "url": "https://stackoverflow.com/questions/7633268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: java error stackoverflow I want to generate random numbers within a range and the generated numbers should not collide within some range. i used following code but im getting Stackoverflow error.. Any better solution? static int [] xPositions=new int[10]; int WIDTH=700 public static void main(String args[])throws IOException { if(generateRandomXPositions(10)){ for(int i=0;i<10;i++){ System.out.println(" Random Numbers "+i+" :"+xPositions[i]); } } } private static boolean generateRandomXPositions(int n) { for(int i=0;i<10;i++){ int temp=((int)0 + (int)(Math.random() * ((WIDTH - 0) + 1))); for(int j=0;j<xPositions.length;j++){ if(xPositions[j]>temp-50 && xPositions[j]<temp+50){ // IF GENERATED NUMBER IS IN THIS RANGE IT SHOULD REGENERATE THE NUMBERS generateRandomXPositions(10); } } xPositions[i]=temp; } return true; } I know problem is here if(xPositions[j]>temp-50 && xPositions[j]<temp+50). Below one works fine `if(xPositions[j]==temp)`. But I need that random numbers should follow that range! . Many are wondering about the exit condition of recursive loop. But I believe if random number is not in that range, then there is no point of entering in to the recursive loop. UPDATE 1: And I believe compiler is tired to find the number between this range! Now I found that it is impossible fit 10 images having width of 100px each in to the 700px width container without colliding X positions! Please see the image below. Lets imagine i want to place this boxes randomly without colliding... how can i do that? A: Since I think this is homework and your question is pretty vague, try to fill in these methods yourself and combine them intelligent. public int generateRandom(); public boolean isAccepted(int number); public void generate(); For generate(), use some loop like: int temp = generateRandom(); while (!isAccepted(temp)) temp = generateRandom(); A: You're getting a StackOverflowError because the chances of xPositions[j]>temp-50 && xPositions[j]<temp+50 not passing is very low when there's a range of 50. The chances of this function terminating is even lower due to the inner for-loop. Thus, this will keep recursing.. However, it doesn't seem like you're doing what you actually want to accomplish. If you want to generate numbers that are all within a set range, you don't want to compare xPositions[j] to temp-50 and temp+50. That's going to regenerate numbers when xPositions[j] isn't within some random range. If you really just want to generate numbers that are within a certain range, then you'll want to get rid of the inner for-loop and instead do something like this: for every number in xPositions: a = random number if a is within an unwanted range, regenerate numbers else set xPositions[i] = a or without recursion: for every number in xPositions: a = random number while a is within an unwanted range: a = random number set xPositions[i] = a On the other hand, if you want to randomize the order of some images along the x-axis, you can do something like this: bag = [0 1 2 ... n-1] shuffle bag for every number in xPositions: xPositions[i] = bag.pop * IMAGE_WIDTH A: You've committed the classic error when writing recursive methods: no stopping condition. Your method has to have one condition that returns false. A: Instead of calling generateRandomXPositions() again you should use a loop for creating a number and checking if it already exists or not. The stackOverFlowError occurs because you recursively call the function from within itself. A: You called generateRandomXPositions(10); inside a loop? This is inifinite loop, man. And you never use the param from the method.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633271", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Trouble with WCF configuration in asp .net I have a 5 layer application (Entity, Data Access, Business, UI and Exception) in my Visual Web developer express 2010. My Data Access Layer being a WCF Service and UI being asp .net web application. I added service reference to the Business Layer and dragged the app config file to the UI Layer. When I run the app, I get the following error Could not find default endpoint element that references contract 'ExcelService.IExcelReader' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element. A: The content of the app.config will need to be merged with the web.config file that's already present. Specifically, you'll find a <system.serviceModel> section in the app.config file. Take this whole section and copy it into web.config - your UI layer should then see the WCF configuration. Your web.config will then look a little like this: <configuration> <appSettings> <!-- application settings --> </appSettings> <system.web> <!-- configuration for Web application --> </system.web> <system.serviceModel> <!-- configuration for WCF --> </system.serviceModel> </configuration>
{ "language": "en", "url": "https://stackoverflow.com/questions/7633272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extracting words from a string, removing punctuation and returning a list with separated words I was wondering how to implement a function get_words() that returns the words in a string in a list, stripping away the punctuation. How I would like to have it implemented is replace non string.ascii_letters with '' and return a .split(). def get_words(text): '''The function should take one argument which is a string''' returns text.split() For example: >>>get_words('Hello world, my name is...James!') returns: >>>['Hello', 'world', 'my', 'name', 'is', 'James'] A: This has nothing to do with splitting and punctuation; you just care about the letters (and numbers), and just want a regular expression: import re def getWords(text): return re.compile('\w+').findall(text) Demo: >>> re.compile('\w+').findall('Hello world, my name is...James the 2nd!') ['Hello', 'world', 'my', 'name', 'is', 'James', 'the', '2nd'] If you don't care about numbers, replace \w with [A-Za-z] for just letters, or [A-Za-z'] to include contractions, etc. There are probably fancier ways to include alphabetic-non-numeric character classes (e.g. letters with accents) with other regex. I almost answered this question here: Split Strings with Multiple Delimiters? But your question is actually under-specified: Do you want 'this is: an example' to be split into: * *['this', 'is', 'an', 'example'] *or ['this', 'is', 'an', '', 'example']? I assumed it was the first case. [this', 'is', 'an', example'] is what i want. is there a method without importing regex? If we can just replace the non ascii_letters with '', then splitting the string into words in a list, would that work? – James Smith 2 mins ago The regexp is the most elegant, but yes, you could this as follows: def getWords(text): """ Returns a list of words, where a word is defined as a maximally connected substring of uppercase or lowercase alphabetic letters, as defined by "a".isalpha() >>> get_words('Hello world, my name is... Élise!') # works in python3 ['Hello', 'world', 'my', 'name', 'is', 'Élise'] """ return ''.join((c if c.isalnum() else ' ') for c in text).split() or .isalpha() Sidenote: You could also do the following, though it requires importing another standard library: from itertools import * # groupby is generally always overkill and makes for unreadable code # ... but is fun def getWords(text): return [ ''.join(chars) for isWord,chars in groupby(' My name, is test!', lambda c:c.isalnum()) if isWord ] If this is homework, they're probably looking for an imperative thing like a two-state Finite State Machine where the state is "was the last character a letter" and if the state changes from letter -> non-letter then you output a word. Don't do that; it's not a good way to program (though sometimes the abstraction is useful). A: All you need is a tokenizer. Have a look at nltk and especially at WordPunctTokenizer. A: Try to use re: >>> [w for w in re.split('\W', 'Hello world, my name is...James!') if w] ['Hello', 'world', 'my', 'name', 'is', 'James'] Although I'm not sure that it will catch all your use cases. If you want to solve it in another way, you may specify characters that you want to be in result: >>> re.findall('[%s]+' % string.ascii_letters, 'Hello world, my name is...James!') ['Hello', 'world', 'my', 'name', 'is', 'James']
{ "language": "en", "url": "https://stackoverflow.com/questions/7633274", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: JSF 2 : Why my first bean is called during an ajax action to a second bean? I have two backbeans, one to retrieve datas in a ui:repeat and one to perform an action. When my page is rendered, if I perform an action with the second backbean, the first is called (initialized) even if I use an ajax action with Richfaces 4. It is not the case if I don't use a repeat component. It's annoying that the first bean is called with a repeat element. Here my code : <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:a4j="http://richfaces.org/a4j" xmlns:rich="http://richfaces.org/rich"> <h:head> </h:head> <h:body> <h:form> <ui:repeat var="currentValue" value="#{test_form_backBean_1.testSimpleModels}"> #{currentValue.name} <br /> </ui:repeat> <a4j:commandButton value="Tester" actionListener="#{test_form_backBean_2.test}" execute="@this" render="@this"> </a4j:commandButton> </h:form> </h:body> </html> My first bean : @Named("test_form_backBean_1") @RequestScoped public class Test_form_backBean_1 { private static final Logger logger = Logger.getLogger(Test_form_backBean_1.class); private List<Test_Simple_Model> testSimpleModels; @PostConstruct public void init() { if (logger.isTraceEnabled()) logger.trace("Initialisation de Test_form_backBean_1."); testSimpleModels = new ArrayList<Test_Simple_Model>(); testSimpleModels.add(new Test_Simple_Model(1L, "name_1")); testSimpleModels.add(new Test_Simple_Model(2L, "name_2")); testSimpleModels.add(new Test_Simple_Model(3L, "name_3")); testSimpleModels.add(new Test_Simple_Model(4L, "name_4")); } public List<Test_Simple_Model> getTestSimpleModels() { logger.trace("getTestSimpleModels() : appel."); return testSimpleModels; } public void setTestSimpleModels(List<Test_Simple_Model> testSimpleModels) { logger.trace("setTestSimpleModels() : appel."); this.testSimpleModels = testSimpleModels; } } The second : @Named("test_form_backBean_2") @RequestScoped public class Test_form_backBean_2 { private static final Logger logger = Logger.getLogger(Test_form_backBean_2.class); @PostConstruct public void init() { logger.trace("Initialisation de Test_form_backBean_2."); } public void test() { logger.trace("test() : appel de la fonction de test."); } } Thanks in advance for your help. A: The problem is that your beans are request scoped, meaning they go out of scope as soon as a request-response lifecycle has completed, be that the result of a non-faces request (full page) or an AJAX post-back request. You need to use view scoped beans instead. Since you are using CDI, you could either stop using that and switch to using JSF 2 managed beans which has a @ViewScoped annotation, or you could continue to use CDI with Seam Faces 3 which apparently also supports @ViewScoped. (I don't know by what magic it does that, but apparently it just works.) Please also try to use generally accepted naming conventions for Java such as TestFormBackBean1 instead of Test_form_backBean_1.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633277", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android add undo feature to finger paint example in api demo hi i am trying to add undo feature to finger paint example given in API demo. but i am not able to achieve it. So far i have added all the path that are drawn in a list and redrawing it to the canvas except the last path. But it is not working. Any clue where i am going wrong. Edit #1: My Undo Method is this private void undo(){ if (MyPathList.size()>0) { mCanvas.drawColor(0xFFFFFFFF); for (int i = 0; i < MyPathList.size()-1; i++) { Path p=(Path)MyPathList.get(i); mCanvas.drawLine(0, 0, 20, 20, mPaint); mCanvas.drawLine(0, 0, 80, 20, mPaint); mCanvas.drawPath(p, mPaint); p.reset(); } invalidate(); } } Thanks in Advance. A: Maybe this tutorial is what your looking for: http://www.tutorialforandroid.com/p/drawing-with-canvas-series.html A: When you drawing line for the current process like at now use drawing the like using it finger now store this points into temp_array list. now add this temp_array list into the main array list which will draw all sub array list point like wise here. List<List<Point> main_Points = new ArrayList<List<Point>>(); List<Point> temp_point; // this one is for the current drawing like onTouch() onTouch(MotionEvent event){ int x = (int) event.getX(); int y = (int) event.getY(); if(event.getAction==MotionEvent.DOWN){ temp_point = new ArrayList<Point>(); temp_point.add(new Point(x,y); }else if(event.getAction==MotionEvent.MOVE){ if(temp_point!=null) temp_point.add(new Point(x,y); }else if(event.getAction==MotionEvent.UP){ mainPoint.add(temp_point); temp_point = null; } return true; } always re-initialize into onTouch() method in down event and get all the point at move time get the point and store into this list now at up event time store this array list into main list. now if you want to undo last or more you can just remove last add temp_point list from the mainPoint array List A: There is another way of achieving undo , you can use porterduff mode.clear to draw over the particular path which need to be undone 1. Store your paths to array of Paths during onTouch event. 2. check the size of stored path array, and get the last drawn path using size() method. i.e patharray.size()-1; 3. Store that to a separate path. 4. Call invalidate() method 5. Set your paint xfermode property to Mode.clear 6. Draw on canvas using the retrieved path and the newly set paint. Public Path unDonePath,drawpath; Public Boolean undo=false; Paint paintForUndo= new Paint(); Public ArrayList<Path>unDonePathArray= new ArrayList<Path>(); Public ArrayList<Path>patharray= new ArrayList<Path>(); public boolean onTouchEvent(MotionEvent event) { Switch(MotionEven.getAction()) { case MotionEvent.ACTION_UP: pathArray.add(drawpath); pathToDraw = new Path(); //drawpath contains touchx and touch y co-ordinates. } } Protected void undo() { if(pathArray.size()>0) { unDonePath=new Path(); unDonePathArray.add(pathArray.remove(pathArray.size()-1)); unDonePath=unDonePathArray.get(unDonePathArray.size()-1); unDonePathArray.clear(); invalidate(); } } public void onDraw(Canvas canvas) { if(undo) { paintForUndo.setStrokeWidth(12.0f); /*stroke width have to be set more than or equal to your painted stroke width, if ignored border of the painted region will be left uncleared. */ paintForUndo.setXfermode(newPorterDuffXfermode(PorterDuff.Mode.CLEAR)); drawOnCanvas.drawPath(unDonePath,paintForUndo); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7633282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to create play heroku procfile? I am following the directions here http://blog.heroku.com/archives/2011/8/29/play/ but I do play run and then git push heroku master but a procfile is not found. -----> No Procfile found. Will use process: play run --http.port=$PORT $PLAY_OPTS * *How do I explicitly create a procfile? *The instructions seem to indicate that I should push to heroku master while the app is running. Am I reading that wrong? *Where can I specify $PORT and $PLAY_OPTS for mydomain.herokuapp.com? *Is it better to just modify the values for %prod in application.conf? A: It will considerably depend on the play version you're using. I checked the docs and found the following Procfiles for each of the given versions: * *1.x web: play run --http.port=$PORT $PLAY_OPTS *2.0 web: target/start -Dhttp.port=${PORT} ${JAVA_OPTS} *2.2.0 web: bin/<your-appname> -Dhttp.port=${PORT} ${JAVA_OPTS} -DapplyEvolutions.default=true *2.2.1 web: target/universal/stage/bin/<your-appname> -Dhttp.port=${PORT} -DapplyEvolutions.default=true For more information for the specific version check this URL: http://www.playframework.com/documentation/2.2.1/ProductionHeroku Make sure you replace 2.2.1 with whatever version you're using. A: You need to create a file named Procfile in the root of your project and for Play it should contain web: play run --http.port=$PORT $PLAY_OPTS When you then deploy your application the $PORT and $PLAY_OPTS will be set by heroku when the application is started. A: * *Creating a Procfile is as simple as it sounds. Just create a file called Procfile and declare your process types and commands. More information is here: http://devcenter.heroku.com/articles/procfile In this case, you didn't provide a Procfile so Heroku just used the standard Play process. It's best practice to explitly provide a Procfile in case this default changes in the future. *No, you are not reading that wrong. To upload a new version of your app you perform a git push to heroku. *The $PORT variable is set internally by Heroku. No need to set it. The $PLAY_OPTS variable is set in your app space when you first push your Play app to Heroku. You can see it using the heroku command line. More information on that command line is here: http://devcenter.heroku.com/articles/heroku-command To view your app configuration: $ heroku config To change $PLAY_OPTS: $ heroku config:remove PLAY_OPTS $ heroku config:add PLAY_OPTS=... By default, heroku will run Play apps under the prod framework id. You can change this in your Procfile or in the $PLAY_OPTS variable. The only important thing here is that your app run in PROD mode on heroku (note that mode is different from framework id). Heroku cannot run Play apps in DEV mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: Plotting surfaces with contour map in 3D over triangles The example code here for rgl does almost what I want. However my (x,y) are not in a rectangle but in a triangle that is half of the rectangle (x=0..1, y=0..1 and z is missing if x+y>1). My input dataset is in the following format: x1 x2 x3 x4 x5 x6 z and I would like to visualize (x4, x5, z) and (x2, x3, x6), etc. Any help is appreciated how to do this in R, I am beginner. Can export the final plot into PDF, EPS or SVG? UPDATE: OK, I see I can export to EPS. UPDATE 2: Thanks to Carl I almost got what I want. The only problem is that one of the edges of the surface is saw-toothed. Between the teeth, where x+y<=4 the surface should be kept so the saw-toothed edge becomes like the other edges. How can I do this? The R code is below, the input data is here library(rgl) mat = matrix(scan("bpexamp.out"),ncol=9,byrow=T) N <- 4 x <- c(0:N) y <- c(0:N) z <- mat[,9] zlim <- range(y) zlen <- zlim[2] - zlim[1] + 1 colorlut <- terrain.colors(zlen,alpha=0) # height color lookup table col <- colorlut[ z-zlim[1]+1 ] # assign colors to heights for each point open3d() aspect3d(1,1,0.1) surface3d(x, y, z, col) axes3d() A: This is a comment - but I don't know howto put an image into a comment, so formatted as an answer. I ran yr stuff and got this chart: I ran yr stuff and got this chart: So, what is missing or inaccurate here? We can probably 'fix' it for you...
{ "language": "en", "url": "https://stackoverflow.com/questions/7633288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Deploying App in iOS device - .sql file is zero bytes I am attempting to test my app on an iPad and iPhone. The app includes a small SQLite database file, which locally on my Mac is 8 bytes, but when I deploy and run the app on my iOS device, the .sql file is zero bytes. I initially read the SQL file (database) and discovered that the file is empty, i.e zero bytes. Has anyone else come across this issue? Thanks. A: Are you trying to update/edit the database file. Then you need to copy it in the document folder. NSBundle elements are not editable. That may be the reason. A: In that first of all you create database which is put into the resource folder but that data is not copy into the document folder for that you need to following code to copy .rsd file into document folder. NSString *local=[[NSBundle mainBundle] pathForResource:@"Stock" ofType:@"rsd"]; more detail about that database Download the example here.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633289", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I change never notify in 'user account control settings'? Possible Duplicate: Disabling UAC programmatically How can I change never notify in 'user account control settings' by c#? by manual : User Accounts -> user account control settings -> change by scall bar to 'never notify'. (I need it for automated integration tests ) A: As an Administrator you could change the appropriate registry key using C#: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System Have a look at this answer: https://superuser.com/questions/83677/disabling-uac-on-windows-7/83678#83678 A: This should do the trick. using Microsoft.Win32; RegistryKey key = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"); key.SetValue("EnableLUA", "0"); key.Close();
{ "language": "en", "url": "https://stackoverflow.com/questions/7633291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Change subview with binding Possible Duplicate: Changing the View for a ViewModel I have a view: <UserControl ...> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition /> <ColumnDefinition /> </Grid.ColumnDefinitions> <ComboBox ItemSource="{Binding Items}" /> **<???>** </Grid> </UserControl> I have ViewModel: public class VM { // ... public List<Entities> Items { get; set;} public String Title { get; set; } } and I have a few subview's like this: <UserControl ...> <TextBlock Text="{Binding Title}" /> </UserControl> When user selecta some value from ComboBox in main View, I need to place in second column of main View some of subViews. If user selects other value in ComboBox, another subView sould replace existing subView. How can it be done? A: I usually just use a ContentControl and let it figure out which view to draw based on DataTemplates <ContentControl Content="{Binding SelectedView}"> <ContentControl.Resources> <DataTemplate DataType="{x:Type local:ViewModelA}"> <local:ViewA /> </DataTemplate> <DataTemplate DataType="{x:Type local:ViewModelB}"> <local:ViewB /> </DataTemplate> <DataTemplate DataType="{x:Type local:ViewModelC}"> <local:ViewC /> </DataTemplate> </ContentControl.Resources> </ContentControl> A: You could bind to the SelectedItem of the ComboBox, e.g. <ComboBox x:Name="cb" ItemSource="{Binding Items}" /> <ContentControl Content="{Binding SelectedItem, ElementName=cb}" Grid.Column="1"> <ContentControl.ContentTemplate> <DataTemplate> <v:SubView /> <!-- Bind properties as appropriate --> <DataTemplate> <ContentControl.ContentTemplate> <ContentControl> If you have differnt views use the ContentTemplateSelector instead of hardcoding one template.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I make the image move in a random position? I have an image inside the panel and it moves in a clockwise direction. Now, I want it to move in a random direction and that is my problem. Could someone give me an idea how to do it? Here's what I've tried : private int xVelocity = 1; private int yVelocity = 1; private int x, y; private static final int RIGHT_WALL = 400; private static final int UP_WALL = 1; private static final int DOWN_WALL = 400; private static final int LEFT_WALL = 1; public void cycle() { x += xVelocity; if (x >= RIGHT_WALL) { x = RIGHT_WALL; if (y >= UP_WALL) { y += yVelocity; } } if (y > DOWN_WALL) { y = DOWN_WALL; if (x >= LEFT_WALL) { xVelocity *= -1; } } if (x <= LEFT_WALL) { x = LEFT_WALL; if (y <= DOWN_WALL) { y -= yVelocity; } } if (y < UP_WALL) { y = UP_WALL; if (x <= RIGHT_WALL) { xVelocity *= -1; } } } A: Change y -= yVelocity; To if (y>0) { y = -1*Random.nextInt(3); } else { y = Random.nextInt(3); } A: Call a method like this to set a random direction: public void setRandomDirection() { double direction = Math.random()*2.0*Math.PI; double speed = 10.0; xVelocity = (int) (speed*Math.cos(direction)); yVelocity = (int) (speed*Math.sin(direction)); } Just noticed that you're cycle method will need a little fixing for this to work. public void cycle() { x += xVelocity; y += yVelocity; //added if (x >= RIGHT_WALL) { x = RIGHT_WALL; setRandomDirection();//bounce off in a random direction } if (x <= LEFT_WALL) { x = LEFT_WALL; setRandomDirection(); } if (y >= DOWN_WALL) { y = DOWN_WALL; setRandomDirection(); } if (y <= UP_WALL) { y = UP_WALL; setRandomDirection(); } } (It works, but this is not the most efficient/elegant way to do it) And if you want some sort of 'random walk' try something like this: public void cycle() { //move forward x += xVelocity; y += yVelocity; if (Math.random() < 0.1) {//sometimes.. setRandomDirection(); //..change course to a random direction } } You can increase 0.1 (max 1.0) to make it move more shaky.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633295", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Simple git post-commit hook to copy committed files to a certain folder I would like to automatically copy the committed files to a certain folder so they can be viewed in a browser, but I would like to do this without having to create a bare repository that mirrors the main repository (as shown here) and I would like this to happen on commit. Is there any simple way to create a hook that reads which files have been committed and copies them/updates them on a live webserver? For example: I have a folder named /example.com and a git repository. I want that when I commit index.html in the repository, the corresponding index.html file from /example.com to be updated with the contents of the committed file A: A good way of doing this is to create a post-commit that runs git checkout -f with the work tree set to the directory that is exposed by your web server and the git directory set to the .git directory in your development repository. For example, you could create a .git/hooks/post-commit file that did: #!/bin/sh unset GIT_INDEX_FILE export GIT_WORK_TREE=/example.com/ export GIT_DIR=/home/whoever/development/web-project/.git/ git checkout -f Be careful with this, however - the -f means that git may remove or overwrite files to make /example.com/ match the tree in your most recent commit. (Remember to make the .git/hooks/post-commit file executable as well.)
{ "language": "en", "url": "https://stackoverflow.com/questions/7633299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Android table row image How do I make an image occupy the entire row of a table and not be bigger than the screen ? TableLayout tableView = (TableLayout) findViewById(R.id.tblVW); TableRow row = new TableRow(this); ImageView im = new ImageView(this); bmp=getbmp(img); im.setImageBitmap(bmp); row.addView(im); tableView.addView(row, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); If I use this code , the image is bigger than the screen . I want the image to fill the whole row , regardless the view ( landscape or portrait) or the device's screen size.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to perform scp between 2 remote unix boxes using Jsch? I am writing a Java code using Jsch in which I need to perform scp between 2 remote UNIX boxes. I tried to execute the scp command in the same way as to execute a normal command from my java code like this : JSch jsch=new JSch(); Session session=jsch.getSession("user", "host", 22); UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.setPassword("pwd"); session.connect(); Channel channel=session.openChannel("exec"); ((ChannelExec)channel).setCommand("scp [email protected]:/home/user/demo.csv /home/user/demo.csv"); channel.setInputStream(null); ((ChannelExec)channel).setErrStream(System.err); InputStream in=channel.getInputStream(); channel.connect(); //Printing operations channel.disconnect(); session.disconnect(); Instead of prompting password for [email protected] as I expected. I get only errors : Permission denied, please try again. Permission denied, please try again. Permission denied (publickey,gssapi-with-mic,password). exit-status: 1 From executing the command on the UNIX box directly, I have found this : scp asks for password to connect to the remote machine.. however using this code, it is not prompting for any password. So it is trying to perform scp without the password and trying thrice(NumberoOFAttempts flag) and gives the error messages... I want to know how to make scp atleast prompt to enter something instead of just not taking password ... I have used the default implementation of MyUserInfo class given in jsch examples for my code... Or Is there any way to provide the password along with the scp command ?? I am trying to avoid using private/public key combinations as much as possible.. EDIT : From Paulo's post.. Now I have added channel.setPty(true) to get a pseudo terminal for the command and it is asking for me to enter Password than failing automatically.. How should I specify the password now... I tried typing it in the console but it is not accepting and keeps on waiting for user input.... I tried setting it using channel.setInputStream(pwdbytes); but it keeps waiting at the command and not taking the input .. Thanks for any help regarding this... A: The scp command on your first Unix box tries to read the password from the console/terminal. But this will only work when there is a terminal associated with the process - and it is not, by default. The easiest way to solve this would be to use channel.setPty(true) before connecting the channel, and then provide the password via the input/output streams.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633305", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ExtJS 4 Application Login & Authentification & Rights I'm developing an web application on Ext JS 4 using the new recommended application structure. Therefore I need to implement a authentification & rights system. The idea so far: * *The server is responsible to ensure the user role and rights. *ExtJS frontend has to change according to the permissions and role *I use a card layout. The first tab is the login screen, the second the application *In my controller I check if the user is logged in. If he has a valid identity I switch to tab 2. If not he is thrown back to tab 1. My problem now is that I'm unsure about part 2 and part 4? How would you implement these two? A: * *Once the user is authenticated bring the config options over from the server into a store. For example: Ext.StoreManager.get('ConfigOptionStore').loadData(/* config data returned from server */); *Use the beforeRender event to add components to your current view (do this in the controller), like so: init: function() { this.control({ 'myPanel': { beforerender: function(cmp, eOpts){ //place the store in a var for easy access var myConfigStore = Ext.StoreManager.get('ActiveUserStore').getAt(0); //from here you can use add() to add stuff like so: if (myConfigStore.get('hasMyButton')) { cmp.add({ xtype: 'button', text: 'My Button', action: 'doSomething' }); } //etc... } }); } *Make sure that at any given time, you update the first record of the store with the current config options (when you loadData, load just one record). *This should get you started in the right direction. Just be sure to create your initial views with the only the most basic components, and then add the custom components based on the user's config. A: You could send unique user "config" file from server depending on user id, so every user has its own config set up the way he wants, also you could use StateManager to save user config after has been changed. This way frontend will change according to the permission and role. For the part 4. i dont see any problem, if you decide to go with card layout... setActiveTab( String/Number/Ext.Component card ) EDIT: You can use getState(); from the Ext.AbstractComponent to retrive the "states", and save, so on the next load this state is initialized.This is not depending on Cookie or Local storage, so it will not expire. You can give user a chance to save state after he is finished with customizing Views.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633309", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: colorbox - enable clicks outside of it I'm using colorbox, and I want to be able to click on the webpage behind the colorbox while it is open. Is it possible? A: The idea of lightbox-like "windows" is that they shadow the website while they are open. But you can add the following to your CSS to hide the overlay: #cboxOverlay { display: none !important; } This will allow you to click on the site even with the colorbox being shown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633311", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Will we leak the android service connection if the client's process is killed by android? Condition: I have a client activity "X" of a remote service (with AIDL) that calls the bindService() in the onCreate() and unbindService() in the onDestroy(). Assume that this activity has been started but not in the foreground (onStop() has happened). It is said that when android system needs more memory elsewhere it might kill the process of another activity with less priority (possibly "X"). If, says, the android system decides to kill "X"'s process, according to the activity-lifecycle diagram the onDestroy() will not be called if the process is killed when more memory is needed. http://developer.android.com/guide/topics/fundamentals/activities.html Question: Will this cause it to leak the service connection? Is it safer then to bind and unbind service in onStart() and onStop()? Thanks in advance! A: Question: Will this cause it to leak the service connection? The ServiceConnection object would be in the process of "X" and therefore will go away when that process is terminated.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633317", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get Facebook wall data to web portal I have web portal. I need to somehow get all Facebook wall posts from just one specific user or group( that represents my web portal). I need to have wall posts available on my web portal for further processing. I will be also needing an option for posting messages from web portal to FB user/group wall. I haven`t worked with FB API until now, so any materials, tutorials that can lead me in right direction would be of great help. Can this be done without creating Facebook application? Thank you A: No, Facebook just like that does not share its user information. you will have to create an app on facebook to authorize urself,and on your web portal you will have to sek users permission before getting any user info. craete facebook app here https://developers.facebook.com/apps You can choose between javascript sdk and graph api on how you want to get user data. You can use publish_stream permisiion to get the post on user wall. A: Can this be done without creating Facebook application? NO Tutorials and materials: * *Graph API *Samples & How-Tos *Google, but I would be careful here. Try to search for updated tutorials (written or updated on 2011) A: I used this http://neosmart.de/social-media/facebook-wall its fb.wall plugin into jQuery .js library. It easy and can be edited symply via CSS
{ "language": "en", "url": "https://stackoverflow.com/questions/7633322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: MSBuild backup files (with time stamp) before replacing I currently use a web deployment project to update an existing web site through various MSBuild tasks Taking site offline: <Target Name="BeforeBuild" Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <CreateItem Include="..\website\App_Code\override\App_Offline.htm"> <Output TaskParameter="Include" ItemName="AppOffline" /> </CreateItem> <Copy SourceFiles="@(AppOffline)" DestinationFiles="@(AppOffline->'\\servername\f$\web\example.com\wwwroot\%(RecursiveDir)%(Filename)%(Extension)')" /> <RemoveDir Directories="\\servername\f$\web\example.com\wwwroot\bin\" /> </Target> Update files: <Target Name="AfterBuild" Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <CreateItem Include=".\Release\**\*"> <Output TaskParameter="Include" ItemName="ReleaseFiles" /> </CreateItem> <Copy SourceFiles="@(ReleaseFiles)" ContinueOnError="true" SkipUnchangedFiles="true" DestinationFiles="@(ReleaseFiles->'\\servername\f$\web\example.com\wwwroot\%(RecursiveDir)%(Filename)%(Extension)')" /> <Delete Files="\\servername\f$\web\example.com\wwwroot\App_Offline.htm" /> </Target> However, what I also want to do is backup the existing site before overwriting anything, into a timestamped zip (or 7zip) file, e.g. if done on 3rd October 2011 at 10:35 file would be named \\servername\f$\web\example.com\backup201110031035.7z containing the contents of the wwwroot folder (before taking the site offline and deleting the bin directory) A: The MSBuild Community Tasks provide support for both, zipping and getting the (formatted) current time through the Zip and Time tasks respectively. Once the MSBuild community tasks are installed and imported to your project, you can create a backup zip file by adding the following to the beginning of your BeforeBuild target. <ItemGroup> <FilesToZip Include="\\servername\f$\web\example.com\wwwroot\**\*.*" /> </ItemGroup> <Time Format="yyyyMMddhhmm"> <Output TaskParameter="FormattedTime" PropertyName="Timestamp" /> </Time> <Zip Files="@(FilesToZip)" ZipFileName="\\servername\f$\web\example.com\backup$(Timestamp).zip" WorkingDirectory="\\servername\f$\web\example.com\wwwroot" />
{ "language": "en", "url": "https://stackoverflow.com/questions/7633324", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL: Eliminate chains of duplicate in a GROUP_CONCAT I'm running a query to analyse variations in Group_member_ID for some users. What I would like to identify is the key variations in group_member_ids (eg Group1 on 01/08/2011, Group5 on 05/08/2011). I came up with this command: select id, CAST(group_concat(concat('[',group_member_id,'-',from_unixtime(obs_time),']') order by obs_time) as CHAR(10000) CHARACTER SET utf8) from Table1 where id=1 RESULT: imei group/date 1[178-2011-06-13 18:58:31],[0-2011-06-13 19:20:56],[0-2011-06-17 17:21:57],[0-2011-06-19 16:53:29],[0-2011-06-22 16:41:11],[178-2011-09-30 16:43:11],[179-2011-10-01 18:43:11] How can I eliminate the Group/date [0-2011-06-17 17:21:57],[0-2011-06-19 16:53:29],[0-2011-06-22 16:41:11] from this query as I already identified the first record for group_member_id=0 and the others do not matter for me... In other words, I would like my final result to look like: imei group/date 1[178-2011-06-13 18:58:31],[0-2011-06-13 19:20:56],[178-2011-09-30 16:43:11],[179-2011-10-01 18:43:11] I'm stuck. I was thinking of using LIMIT in my group_concat but apparently it's not possible. Or is it? Thanks for your answers. A: TRY with GROUP BY SELECT id, CAST( GROUP_CONCAT ( CONCAT('[',group_member_id,'-',from_unixtime(obs_time),']') ORDER BY obs_time ) as CHAR(10000) CHARACTER SET utf8) AS group_set FROM table1 WHERE id=1 GROUP BY group_member_id
{ "language": "en", "url": "https://stackoverflow.com/questions/7633328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error converting from MySQL to SQLite It hasn't been too much trouble but there's an error I keep getting from an update from user clicking a button. Originally in MySQL this was an enum('Y','N') value, but as SQLite doesnt use enums or booleans, I've decided to use an int with 1 and 0 respectively. How can this be solved? if(e.getSource()==boughtB){ String cigName; cigName = Habanos2.selection; String humiString; int humino; Connection con = null; System.out.println(cigName); try{ ResultSet humiRS1 = HabMenu.getGenericRS("select * from cigar where name = '"+cigName+"'"); if(humiRS1.next()){ humiString = humiRS1.getString("humi_no"); humino = Integer.parseInt(humiString); System.out.println("humino"+humino); Class.forName("org.sqlite.JDBC").newInstance(); con = DriverManager.getConnection("jdbc:sqlite:cigardb.db"); Statement s = con.createStatement(); humino++; String humiNoS = Integer.toString(humino); s.executeUpdate("update cigar set humi = 1 where name ='"+cigName+"'" ); s.executeUpdate("update cigar set humi_no = "+humiNoS+"where name ='"+cigName+"'"); Habanos2Frame.myHumi.setText(""); ResultSet humiii = HabMenu.getGenericRS("select * from cigar where humi = 1"); It produces this error: java.sql.SQLException: database locked at org.sqlite.DB.execute(DB.java:270) at org.sqlite.DB.executeUpdate(DB.java:281) mysql humi error humiNoS = at org.sqlite.Stmt.executeUpdate(Stmt.java:103) at cigarDiary.buttonBar$ButtonHandler.actionPerformed(buttonBar.java:207) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) A: Ok the way I solved this was by closing each ResultSet (rs.close) and Connection (con.close) after I was finished using it. This is something that MySql doesnt seem to mind but SQLite does. It wont allow you to perform an update while a resultset and its connection are stilll open.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: P4 - change workspace for client I want to change the workspace client using the p4 command line but i don't know if its possible. You can create, delete or edit workspace using the p4 workspace command, but i want to change the current workspace with a .bat method. Exemple : p4 -c MyClient changeworkspace myNewWorkspace If you know in first step if it's possible. Thanks. A: Either set the P4CLIENT environment variable to the name of the workspace you want to be your current workspace, or consistently pass that workspace name as the value of the -c flag on your p4 commands: http://www.perforce.com/perforce/doc.current/manuals/cmdref/env.P4CLIENT.html#1040647 See also these other ways to set the environment variable (many people find P4CONFIG files helpful): http://www.perforce.com/perforce/doc.current/manuals/p4guide/02_config.html#1069873
{ "language": "en", "url": "https://stackoverflow.com/questions/7633332", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: Android dialog number picker Is there any tested and usable component we can use to show "Count selector" like this? Our target is to get it working from API v7 . (Taken from DatePickerDialog) A: After some deep testing and using, this is a list of usable Picker widget libraries * *Android Wheel http://code.google.com/p/android-wheel/ *Number Picker from Michael Novak https://github.com/mrn/numberpicker *Date Slider (which can be easily adjusted) http://code.google.com/p/android-dateslider/ *Horizontal slider widget http://blog.sephiroth.it/2012/01/28/android-wheel-widget/ *Backport of Android 4.2 NumberPicker https://github.com/SimonVT/android-numberpicker When kindly omitted the solution in accepted answer, these widget libraries are very usable if you need alter the design, and you like the way iOS does the wheel slider picker. A: I think this one is better: https://github.com/SimonVT/android-numberpicker it has the same look of android 4.2 number picker: another alternative is using the HoloEverywhere library, which has plenty of native look&feel of android jelly bean
{ "language": "en", "url": "https://stackoverflow.com/questions/7633343", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: How to see "alternatives" for properties in PowerShell? Using Get-ChildItem | Get-Member I can see the methods and properties for an object. But how can I see the different possible values for e.g. properties? I can use Get-ChildItem | Where-Object {$_.Attributes -ne "Directory"} to extract objects which are not directory objects, but how can I see the other alternatives for .Attributes? A: The provider property PSIsContainer is true for folders and false for files, so you can get files only with one of the following: Get-ChildItem | Where-Object {$_.PSIsContainer -ne $true} Get-ChildItem | Where-Object {!$_.PSIsContainer} Get-ChildItem | Where-Object {-not $_.PSIsContainer} As for the Attributes property, the output of Get-Member shows its type name (System.IO.FileAttributes), which is an Enum object: PS> dir | gm attr* TypeName: System.IO.DirectoryInfo Name MemberType Definition ---- ---------- ---------- Attributes Property System.IO.FileAttributes Attributes {get;set;} You can get its possible values with: PS> [enum]::GetNames('System.IO.FileAttributes') ReadOnly Hidden System Directory Archive Device Normal Temporary SparseFile ReparsePoint Compressed Offline NotContentIndexed Encrypted
{ "language": "en", "url": "https://stackoverflow.com/questions/7633344", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Jmeter issue while recording and executing windows based authentication scripts In one of my application during the initial login I need to give the windows authentication as the user name and password to login into the application. In Jmeter I was unable to proceed if i play back the captured step. Also I was unable to parametrise and create new values by executing the steps once again. Application is developed in Sharepoint with windows based authentication. Do any one have an idea about how to resolve this issue? A: This should do the trick for you: http://jmeter.apache.org/usermanual/component_reference.html#Login_Config_Element
{ "language": "en", "url": "https://stackoverflow.com/questions/7633345", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to transition an existing DB Schema without AUTO_INCREMENT primary key to a key with AUTO_INCREMENT? I have an application which was developed with HSQL DB and the problem is that we are migrating it to MySQL with JPA/Hibernate. The problem is that the old schema doesn't have an AUTO_INCREMENT primary key : how can I use JPA to use such an incrementing key feature without modifying the schema ? Is there a mechanism to tell hibernate to take the last INSERTED_ID + 1 for the next insertion ? thanks a lot, A: The safest is to use the mysql AUTO_INCREMENT when creating the table and if you want to start with an AUTO_INCREMENT value other than 1, you can set that value with CREATE TABLE or ALTER TABLE, like this: mysql> ALTER TABLE tbl AUTO_INCREMENT = 100; If you dont want to add this little modification to the schema while migrating to mysql. You can use the hibernate id generator increment that is constructed by counting from the maximum primary key value at startup. Really important !!! Increment is not safe for use in a cluster compared to mysql AUTO_INCREMENT. IncrementGenerator An IdentifierGenerator that returns a long, constructed by counting from the maximum primary key value at startup. Not safe for use in a cluster! Mapping parameters supported, but not usually needed: tables, column. (The tables parameter specified a comma-separated list of table names.) increment generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: maven assembly create jar with dependency and class path I have a maven project with a lot of dependencies. I want to pack all in a jar with dependency using assembly plugin, but I don't won't all the dependencies jars unpacked in a big mess. I want all of them do go into lib folder, but I don't know how to add the class path. my pom: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>test.com</groupId> <artifactId>simple-weather</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>simple-weather</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.14</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>velocity</groupId> <artifactId>velocity</artifactId> <version>1.5</version> </dependency> <dependency> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <classpathPrefix>lib/</classpathPrefix> <mainClass>adi.com.weather.Main</mainClass> </manifest> </archive> </configuration> </plugin> <plugin> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>attached</goal> </goals> </execution> </executions> <configuration> <descriptors> <descriptor>package.xml</descriptor> </descriptors> </configuration> </plugin> </plugins> </build> </project> my assembly file <?xml version="1.0" encoding="UTF-8"?> <assembly> <id>test5</id> <formats> <format>jar</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <dependencySets> <dependencySet> <unpack>false</unpack> <scope>runtime</scope> <outputDirectory>lib</outputDirectory> </dependencySet> </dependencySets> <fileSets> <fileSet> <directory>${project.build.outputDirectory}</directory> <outputDirectory>/</outputDirectory> </fileSet> </fileSets> </assembly> A: He was probably reconfiguring his maven dependency plugin: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.10</version> <executions> <execution> <id>copy</id> <phase>package</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory>${distDirectory}/lib</outputDirectory> <includeScope>runtime</includeScope> </configuration> </execution> </executions> </plugin> Now, when your run mvn package, all your dependency jars will go to target/lib (or whatever your distDirectory is). HTH A: If maven-jar-plugin is not generating the entry Class-Path in the manifest file although you have set <addClasspath>true</addClasspath>, make sure you are using version 2.2 or newer of the plugin. It seems that the bug MJAR-83 in version 2.1 was preventing the plugin from listing the dependencies in Class-Path.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633347", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: best way to make this list in css Basically I would like to know the best way to create a simple list in CSS that: instead of bullets has a circle with a number inside of it, and the text next to it... I know how to create circles in css3, but how do you replace the bullet that comes with ul, with the circle? Should I not use lists at all to create this? I just need circles with numbers inside of it, and text next to each circle saying xyz... ex: circle(with 1 inside) xyz circle(with 2 inside) zzz circle (with 3 inside) aaa Thanks for any help :). A: @Ryan; yes you can do this with css counter-increment property like this: ul { counter-reset: item; margin-left: 0; padding-left: 0; } li { display: block; margin-bottom: .5em; margin-left: 2em; } li:before { display: inline-block; content: "("counter(item) ") "; counter-increment: item; width: 2em; margin-left: -2em; } check the fiddle http://jsfiddle.net/sandeep/ndBZk/ EDIT: list with circle css: li:before { display:block; content: counter(item); counter-increment: item; width:20px; height:18px; border-radius:10px; -moz-border-radius:10px; -webkit-border-radius:10px; background:red; text-align:center; position:absolute; top:2px; left:-30px; padding-top:2px; } http://jsfiddle.net/sandeep/XuHNF/3/
{ "language": "en", "url": "https://stackoverflow.com/questions/7633348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JSON generation in ASP.NET MVC 3 I've got the sample code below from an article written by Scott Mitchell on using Google Maps with ASP.NET MVC: @{ var locations = new List<string>(); var infoWindowContents = new List<string>(); foreach (var store in Model) { locations.Add(string.Format( @"{{ title: ""Store #{0}"", position: new google.maps.LatLng({1}, {2}) }}", store.StoreNumber, store.Latitude, store.Longitude)); infoWindowContents.Add(string.Format( @"{{ content: ""<div class=\""infoWindow\""><b>Store #{0}</b><br />{1}<br />{2}, {3} {4}</div>"" }}", store.StoreNumber, store.Address, store.City, store.Region, store.PostalCode) ); } } However, when the page renders the following is showing (I added a space between "&" and "quot;" { title: & quot;Store #893& quot;, position: new google.maps.LatLng(32.7178080, -117.1611020) } Most probably related to JSON encoding, but I'm still a beginner in ASP.NET MVC. A: try use @: so it doesn't HTML-encode output A: You should try wrapping the JSON you wish to output in a MvcHtmlString A: When outputting the location, don't just use the variable, but wrap it in @Html.Raw(i). This way the render engine knows that it doesn't have to escape possibly dangerous characters, like quotes. In code it should look something like @for(var location in locations) { Html.Raw(location); } Also look at JsonResult. Is is far easier and cleaner to use than creating your own json strings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633349", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting an error in W3C Markup Validation when trying to get a whole element as a link in a page I am trying to get whole <figure> element as a link so i wrote these line of code :- <figure> <a href="#"> <img src="images/product-image.jpg" alt="image " /> <span class="label"><span class="rotate">40%</span></span> <span class="curle-label_bg"></span> <figcaption><span class="product-brand">Brand of product</span> Main Caption here <span class="save-money">Save 395.05</span> <span class="product-price">€169.30</span> </figcaption> </a> </figure> I am getting an error "Element figcaption not allowed as child of element a in this context. (Suppressing further errors from this subtree.)" in http://validator.w3.org/ ,I have changed my Document Type in to HTML5 (experimental) in "More option", Can anybody tell me why i am getting this error or where i am going wrong? A: From the spec: Contexts in which this element can be used: As the first or last child of a figure element. You are trying to use it as a child element of an <a> not a <figure> A: Better to do this: <a href="#"> <figure> <img src="images/product-image.jpg" alt="image " /> <span class="label"><span class="rotate">40%</span></span> <span class="curle-label_bg"></span> <figcaption><span class="product-brand">Brand of product</span> Main Caption here <span class="save-money">Save 395.05</span> <span class="product-price">€169.30</span> </figcaption> </figure> </a> Now the figure is enclosed within the a tag, and the figcaption is a child of the figure, not the <a>
{ "language": "en", "url": "https://stackoverflow.com/questions/7633350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Geting the last entry on join So, I have these 2 tables. One contains, lets call them, bugs, and another contains solutions. One bug may have more than one solution (or state, if you may), and I'd like to get the last one. Right now, I'm doing it like this: Select b.*, ap.approveMistakeId from bugs_table as b LEFT JOIN (select approveId, approveCause, approveDate, approveInfo, approveUsername, mistakeId as approveMistakeId from approve_table order by approveDate desc) AS ap ON m.mistakeId = ap.approveMistakeId GROUP BY b.bugId This is not a complete query, it is just to show the how I'm approaching it. The real query joins more than 10 tables. The problem with this is, that with this subselect, the query runs for about 3.3s and returns ~2.4K records. Without this query, it runs for 0.4s, which is more acceptable. I have created and index on approveDate, but that didn't seem to solve the problem. Could the solution be a view, that was created from this query, and then joined to this query? Or is there a way to do this in some other manner? Thanks! A: For joining two tables, you essentially should have some join condition. If I take m.mistakeId = ap.approveMistakeId to be b.mistakeId = ap.approveMistakeId, then also you can go for a simpler join like: Select b.*, ap.approveMistakeId, ap.approveDate from bugs_table as b INNER JOIN approve_table as ap ON b.mistakeId = ap.approveMistakeId order by ap.approveDate desc A: The problem was the sub-select. The solution - de-normalization. Yes, I know, that isn't the best solution, but definitely the fastest. Tried aggregate self-sorting, but that only added time. Same with joining with a view.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633352", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to hide the arrow buttons in a JScrollBar I need to hide the arrow buttons of java.awt.Scrollbar(VERTICAL) in an AWT application. Does anyone know how this can be achieved? I saw an example here, but the code just hides the buttons. The vacant space for the buttons still remains; it is not occupied by the scroll bar. To be more exact, here is the screenshot of what I should achieve. I am not sure which direction to go about it. Update : I was looking for a solution in AWT. But now I am open to suggestions in Swing as well. A: Using Nimbus Look and Feel you can use this to remove the arrow buttons: UIManager.getLookAndFeelDefaults().put( "ScrollBar:\"ScrollBar.button\".size", 0); UIManager.getLookAndFeelDefaults().put( "ScrollBar.decrementButtonGap", 0); UIManager.getLookAndFeelDefaults().put( "ScrollBar.incrementButtonGap", 0); Here is a full example: public class ScrollDemo extends JFrame { public ScrollDemo() { String[] columnNames = {"Column"}; Object[][] data = { {"A"},{"B"},{"C"},{"D"},{"E"},{"F"}, {"A"},{"B"},{"C"},{"D"},{"E"},{"F"}, {"A"},{"B"},{"C"},{"D"},{"E"},{"F"}, {"A"},{"B"},{"C"},{"D"},{"E"},{"F"}, {"A"},{"B"},{"C"},{"D"},{"E"},{"F"}, }; add(new JScrollPane(new JTable(data, columnNames))); pack(); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (Exception e) { // No Nimbus } UIManager.getLookAndFeelDefaults().put( "ScrollBar:ScrollBarThumb[Enabled].backgroundPainter", new FillPainter(new Color(127, 169, 191))); UIManager.getLookAndFeelDefaults().put( "ScrollBar:ScrollBarThumb[MouseOver].backgroundPainter", new FillPainter(new Color(127, 169, 191))); UIManager.getLookAndFeelDefaults().put( "ScrollBar:ScrollBarTrack[Enabled].backgroundPainter", new FillPainter(new Color(190, 212, 223))); UIManager.getLookAndFeelDefaults().put( "ScrollBar:\"ScrollBar.button\".size", 0); UIManager.getLookAndFeelDefaults().put( "ScrollBar.decrementButtonGap", 0); UIManager.getLookAndFeelDefaults().put( "ScrollBar.incrementButtonGap", 0); new ScrollDemo(); } }); } } Code for the Painter used: public class FillPainter implements Painter<JComponent> { private final Color color; public FillPainter(Color c) { color = c; } @Override public void paint(Graphics2D g, JComponent object, int width, int height) { g.setColor(color); g.fillRect(0, 0, width-1, height-1); } } A: Try this.. it replaces the regular buttons on the Vertical ScrollBar with buttons that are 0x0 in size. It does limit your look and feel though :( JScrollPane scroller = new JScrollPane(mainPane); scroller.setPreferredSize(new Dimension(200,200)); // ... etc scroller.getVerticalScrollBar().setUI(new BasicScrollBarUI() { @Override protected JButton createDecreaseButton(int orientation) { return createZeroButton(); } @Override protected JButton createIncreaseButton(int orientation) { return createZeroButton(); } private JButton createZeroButton() { JButton jbutton = new JButton(); jbutton.setPreferredSize(new Dimension(0, 0)); jbutton.setMinimumSize(new Dimension(0, 0)); jbutton.setMaximumSize(new Dimension(0, 0)); return jbutton; } }); Update: sorry, this is a swing solution
{ "language": "en", "url": "https://stackoverflow.com/questions/7633354", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Javascript Regular Expression Match Try <script type="text/javascript"> var str=">1 people>9 people>1u people"; document.write(str.match(/>.*people/img).length); </script> at http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_regexp_dot. This code should return an array of size 3 but it return array of size 1. Where is the problem? A: The .* part of your regexp is being "greedy" and taking as many characters as it can, in this case returning the entire string as a single match. Write it like this instead, with a trailing ?: str.match(/>.*?people/img) See the section describing "?" in the Mozilla Developer Network JS Reference.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: jquery.cookie and internet explorer cookie issue I am building an asp.net website using jquery cookie. I have the jquery image slider on that page. In order to retain the scroll position of the slider, I store them in the jquery cookie (I use the jquery.cookie plugin by carhartl). for example I use the function as below to create the cookie and write the scroll position in it afterEnd:function(e){$.cookie('scrollposition', e.first().index(), {Path: "/", expires: 0});} this is how read from the cookie start: parseInt($.cookie('scrollposition'),10) || 0, The above steps works perfectly on firefox. chrome and Opera. But it is not working on Internet Explorer and Safari. While investigating this issue I found out that changing the cookie management settings on IE and Safari helps. For example on IE, Tools->Internet options->privacy->Click Advanced-> Enable Override automatic cookie handling and safari->preference->privacy->Block cookies->never. Is there any alternative to the cookie? Because most of the people use IE, this cookie approach doesnt seem to help me. Many Thanks in advance for example, my site say www.y.com points to a folder on www.x.com/folder-x. so when you access the site www.y.com through the url www.x.com/folder-x jquery cookie works perfectly. but if you access it from www.y.com, jquery cookie's doesn't seem to work as folder-x is created as a virtual directory on www.x.com. it would be better to use sessions in that case. hope this helps some one.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633374", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to integrate Wordpress CMS with a telephone system such as Asterisk? At the moment, I am dealing with a Web project and would like to know what are the possibilities to develop a Website with Wordpress CMS and integrate it with a Telephone system such as Asterisk. The main purpose is to build a portal where visitors can make calls to others. Any idea on this? All your opinions/responses are welcome! I will appreciate it! A: If you are looking for a paid product then check out Twilio also check out Asterix PHP API. A: Your question is -very- vague. If you mean "I click / you call" service, then yes. Essentially Asterisk PBX support API calls via HTTP/REST as well as "AGI", which is the same as a website CGI, only for Asterisk. Really, the limit is pretty much what you can imagine. If you ask a more specific question, I can provide a more specific answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to set this Layout that fit to Any Screen height? I have Some layout Problem regarding my Application. This is My Application Layout: <?xml version="1.0" encoding="utf-8"?> <ImageView android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/tax_calculator_logo"/> <LinearLayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_gravity="center" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <Button android:id="@+id/contactUs" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Contact Us" android:textSize="20dp"/> <Button android:id="@+id/contactUs" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Contact Us" android:textSize="20dp"/> <Button android:id="@+id/contactUs" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Contact Us" android:textSize="20dp"/> <Button android:id="@+id/contactUs" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Contact Us" android:textSize="20dp"/> </LinearLayout> Here, I want to set this all button to be complete fit with the height of the Screen of any device. Yes i can show all the Button. but i want them all to be have equat space between them and they must be fit complete to the Screen height. So what should i have to do for that ?? Edited: And there is, My tax_calculator_logo is of 600x239 resolution and i have set the ImageView height as wrap_content and width with fill_parent then why the Image is croping from bottom and top ??? A: To do this we have to get he display(screen) width and height.Then through java code assign the height. For exmple The xml file is like this <ImageView android:layout_width="fill_parent" android:layout_height="wrap_content" android:src="@drawable/tax_calculator_logo"/> <LinearLayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_gravity="center" android:layout_marginTop="10dp" android:layout_marginBottom="10dp"> <Button android:id="@+id/contactUs" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Contact Us" android:textSize="20dp"/> <Button android:id="@+id/contactUs" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Contact Us" android:textSize="20dp"/> <Button android:id="@+id/contactUs" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Contact Us" android:textSize="20dp"/> <Button android:id="@+id/contactUs" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Contact Us" android:textSize="20dp"/> In the Activity class Display display = ((WindowManager)context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight()/5; after setContentView(..); imageview.getLayoutParams().height=height; button1.getLayoutParams().height=height; button2.getLayoutParams().height=height; button3.getLayoutParams().height=height; button4.getLayoutParams().height=height; I think this may help you... A: Give equal weight to each of your buttons, they will share height automatically. <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" android:layout_marginBottom="10dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="10dp" android:orientation="vertical" > <Button android:id="@+id/contactUs" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="Contact Us" android:textSize="20dp" /> <Button android:id="@+id/contactUs" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="Contact Us" android:textSize="20dp" /> <Button android:id="@+id/contactUs" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="Contact Us" android:textSize="20dp" /> <Button android:id="@+id/contactUs" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="Contact Us" android:textSize="20dp" /> </LinearLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/7633382", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Will this allow for mysql_real_escape_string to work globally? $_POST = mysql_real_escape_string($_POST); By executing this statement, does each post value now get escaped via mysql_real_escape_string? A: No. That won't work at all: $_POST is an array: mysql_real_escape_string needs a string as its first argument. You can, however, achieve what you want with array_map: $_POST = array_map('mysql_real_escape_string', $_POST); Or array_walk_recursive as array_map does not work on array post values: array_walk_recursive($_POST, function(&$v, $k) {$v = mysql_real_escape_string($v);}); Better, however, would be to use paramaterised queries: this is by far the most secure way to avoid SQL injection. Not only does the above option do needless escaping (for instance, members of the $_POST array that don't need to be inserted into the database), it also makes it harder to use the data in other contexts, e.g. returning them to the browser in some way. A: No, but you can use array_walk()Docs or array_walk_recursive()Docs to achieve that, as mysql_real_escape_string()Docs requires a string (go figure...) as input, and you're passing it an array instead. With this, you pass each array element the same callback function: array_walk_recursive($_POST, 'escape'); escape($k,$v) { return mysql_real_escape_string($v); } But it's better to treat each value accordingly, for ex. casting an INT to INT, etc., or better yet, use parametrized queries. A: Since $_POST is an array, this will going to give you an error. link: http://php.net/manual/en/function.mysql-real-escape-string.php A: $escapedPost = array_map(array($this, 'recursive_escape'), $_POST); /** * recursively escape an array containing strings and/or arrays */ function recursive_escape($value) { if (is_array($value)) { array_map(array($this, 'recursive_escape'), $value); } else { $value = mysql_real_escape_string($value); } return $value; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7633385", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find out 3rd party libraries version? In my project I want to find what is the version of 3rd party libraries. I only have the jar file and some of them contains manifest file with version number in but others don't. Is there a way other than manifest? A: The general technique is to find a place which has multiple versions of the jars, and compare the jars with your version, using file size and checksums. So, go to Maven Search (a good place to start) and search for your library. Then look through the versions that you find there and compare the file sizes with the one you have. Finally, compare the checksums with your jar, or just using a binary compare. If it's not on maven, then searching on the web is a last resort. This is quite tedious to do, but most of the time it works. But, it isn't always possible to find out the version for a given jar, because it may not exist any more. A: No. You would have to look at the compilation dates of the .class files and relate that manually to release dates as per whatever they publish about that. A: The only semi-standard mechanism would be including version information in MANIFEST.MF, as you note. And, of course, many project JARs have a version in the file name. There is otherwise no other general way to define or determine the "version" of a library.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fix border in UITableView for the UITableViewStyleGrouped For a UITableViewStyleGrouped UITableView a small extra line is drawn below the tableview How do I fix this? I have tried my best. No luck so far. Thank's in advance. My Code -(void)myTableView { // if(mytableView != nil) // [mytableView release]; if (mytableView == nil) { mytableView = [[UITableView alloc]initWithFrame:myFrame style:UITableViewStyleGrouped]; } mytableView.delegate=self; mytableView.dataSource=self; mytableView.backgroundView=nil; mytableView.scrollEnabled = FALSE; [self.view addSubview:mytableView]; [self myPortraitMode]; } Background of the table is fixed is an image. A: I think what you are referring to is the Bevel color of the table view. The answer is in this post. Basically, you need to set the table separatorStyle to UITableViewCellSeparatorStyleNone or to UITableViewCellSeparatorStyleSingleLine. A: You need to set a background view: UIView *backgroundView = [[UIView alloc] init]; backgroundView.backgroundColor = [UIColor yourColor]; tableview.backgroundView = backgroundView; [backgroundView release]; You don't need to set the properties every time. -(void)myTableView { if (mytableView == nil) { mytableView = [[UITableView alloc]initWithFrame:myFrame style:UITableViewStyleGrouped]; mytableView.delegate=self; mytableView.dataSource=self; mytableView.backgroundView=nil; mytableView.scrollEnabled = NO; [self.view addSubview:mytableView]; [self myPortraitMode]; } } I don't really see what the problem is though.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633390", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Only scrolling inside one div, while website stays positioned I'm trying to create a website with the following. On top there's just a basic horizontal menu. Below that, on the left side, is another subcategory. The content will be on the right of the subcategory and can be very long. Now what I would like is that when you scroll anywhere on the page, it only scrolls the content div while everything else stays at its original position. I have been thinking about it for some hours now but I cannot really come up with a solution on how to do this. <html> <head> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <div class="container"> <div class="left_side"></div> <div class="right_side"></div> </div> </body> </html> .container { width:1000px; } .left_side { float:left; width:250px; height:500px; background:green; } .right_side { float:right; width:750px; height:1500px; background:yellow; } Any idea on how to do this? Thanks in advance. A: Answer was given by @jao's comment. Setting all divs, except for the content one, to position: fixed. A: Add the overflow:auto style to its class. Full explanation: http://www.w3schools.com/cssref/pr_pos_overflow.asp
{ "language": "en", "url": "https://stackoverflow.com/questions/7633392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do you perform a delayed loop in Opa? What construct exists in Opa to perform a delayed loop; for instance, executing a function every 10 seconds. Take the chatroom tutorial - if I wanted a bot in there then how would I have it write a statement every 10 seconds to the other users? A: What you are looking for is the Scheduler module. In particular the: Scheduler.timer function, or Scheduler.make_timer if you need more control over your timer (like stopping or changing the interval).
{ "language": "en", "url": "https://stackoverflow.com/questions/7633395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Print list of ALL environment variables I would like to print a list of all environment variables and their values. I searched the Stackoverflow and the following questions come close but don't answer me: * *How to discover what is available in lua environment? (it's about Lua environment not the system environment variables) *Print all local variables accessible to the current scope in Lua (again about _G not the os environment variables) *http://www.lua.org/manual/5.1/manual.html#pdf-os.getenv (this is a good function but I have to know the name of the environment variable in order to call it) Unlike C, Lua doesn't have envp** parameter that's passed to main() so I couldn't find a way to get a list of all environment variables. Does anybody know how I can get the list of the name and value of all environment variables? A: Standard Lua functions are based on C-standard functions, and there is no C-standard function to get all the environment variables. Therefore, there is no Lua standard function to do it either. You will have to use a module like luaex, which provides this functionality. A: This code was extracted from an old POSIX binding. static int Pgetenv(lua_State *L) /** getenv([name]) */ { if (lua_isnone(L, 1)) { extern char **environ; char **e; if (*environ==NULL) lua_pushnil(L); else lua_newtable(L); for (e=environ; *e!=NULL; e++) { char *s=*e; char *eq=strchr(s, '='); if (eq==NULL) /* will this ever happen? */ { lua_pushstring(L,s); lua_pushboolean(L,0); } else { lua_pushlstring(L,s,eq-s); lua_pushstring(L,eq+1); } lua_settable(L,-3); } } else lua_pushstring(L, getenv(luaL_checkstring(L, 1))); return 1; } A: You can install the lua-posix module. Alternatively, RedHat installations have POSIX routines built-in, but to enable them, you have to do a trick: cd /usr/lib64/lua/5.1/ # (replace 5.1 with your version) ln -s ../../librpmio.so.1 posix.so # (replace the "1" as needed) lua -lposix > for i, s in pairs(posix.getenv()) do print(i,s,"\n") end The trick is in creating a soft-link to the RPM's "io" directory and to naming the soft-link the same name of the library LUA will attempt to open. If you don't do this, you get: ./librpmio.so: undefined symbol: luaopen_librpmio or similar. A: local osEnv = {} for line in io.popen("set"):lines() do envName = line:match("^[^=]+") osEnv[envName] = os.getenv(envName) end this would not work in some cases, like "no valid shell for the user running your app" A: An easy 2 liner: buf = io.popen("env", '*r') output = buf:read('*a') print(output) -- or do whatever
{ "language": "en", "url": "https://stackoverflow.com/questions/7633397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Rhomobile back function I'm having a problem getting the back button function to work in Rhomobile. I've tried various methods of url_for(:index, :back => ....) etc etc and nothing seems to work. The problem with this method is (even if it worked) that it only allows navigation to a set place, rather than a dynamic history/back navigation. The closest I've come to a working solution is by using this in the application_helper: def page_back WebView.navigate_back end and then <a href="page_back">Back</a> in the view. This works, and i can navigate across views and even controllers. However, it generates a "Error loading page" error, even though it does actually render the right page... Does anybody have any ideas? A: Ok this is what I did in the end. I've decided against using rhodes now but here is what I came up with for this problem: Added data-add-back-btn="true" to: <div data-role="page" data-add-back-btn="true"> Then: <div data-role="header" data-position="inline"> <h1>Title</h1> <a href="page_back" class="ui-btn-left" data-theme="a" data-icon="arrow-l" data-rel="back" data-direction="reverse">Back</a> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/7633399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: whole link created using attribute passing, not working. Trying to create a link dynamically for some purpose $('', { text: 'Click here!', href: 'http://www.example.com', title: 'Click to win' }).appendTo('body'); But this is not working ... anything wrong ? http://jsfiddle.net/QJy6P/ A: you have not selected the jquery option in the fiddle, also specify what are you creating <a/> $(function(){ $('<a/>', { text: 'Click here!', href: 'http://www.example.com', title: 'Click to win' }).appendTo('body'); }) DEMO A: You need the initial parameter to dynamically create your A link element: $('<a/>', { text: 'Click here!', href: 'http://www.example.com', title: 'Click to win' }).appendTo('body'); A: you should do: $('<a/>', { text: 'Click here!', href: 'http://www.example.com', title: 'Click to win' }).appendTo('body');
{ "language": "en", "url": "https://stackoverflow.com/questions/7633402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Can Google analytics be used for an old web app? I have heard about google analytics ad currently reading up and researching it. My company has a really old web app that's being retired but before it does I would like to pull some statistical information on it. The application was developed on a struts 1.1 framework with a hibernate persistence layer (around 2007ish I think). Since it's not a customer serving site per se and there's no advertising involved. I'd just like to track the busiest functional part(s) of the web app. Is this possible? Thanks A: Yes. Enabling google analytics is just a question of adding a piece of javascript to all the pages. Hopefully your web app has some template that you can put this piece of javascript into, so that it is emitted on all pages.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633404", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Synced animated tiles in a 2d web game I'm building a strategy game in the browser since 2 years back. Its already actively played by a small crowed of people so it is a working game. Our problem is that its resource hungry. Basically you want opera or chrome. IE9 is more or less unplayable and firefox can be quite slow on some maps. The game is a tile based top down game using 64x64pixel DIVs for the map. We are currently in the end phase and we are focusing on optimizations. One of the things that eat resources is our animated water. We have 32 different tiles of water split into 15 frames each. So 480 64x64 images in one .gif file that is 1.1 mb. Here is a link to the water: http://www.warbarons.com/beta5/terrain/water/water2.gif Our game uses Fog of War to hide enemy units and castles that you cant see just like any RTS game. So on top of the .gif there is usually a layer with a transparent PNG. It seems like this solution is quite demanding on the browser. When I scroll the map to show water in FireFox CPU goes up to 25% while its around 4-5% when no water is in sight. I've been googling for a few days now trying to get an idea of a better technique. I've found two other way of doing this, either with a canvas tag which is iterating over a spreadsheet or using CSS to loop over a spreadsheet. The problem I see with those two options is that all water tiles must remain in sync. If one starts playing before another one the waves wont be in sync which will break the seamless look. I wonder if anyone have an idea to solve this? I know that having multiple gif animations will result in the out of sync problem. Is there some cleaver way to use canvas to do this? Is it even possible to mix canvas with divs or would that require that we change the whole map engine? Any help would be greatly appreciated. A: Bit of a novice work around and a longshot, but: For preparation, make a sprite-sheet of all of the different types of water tiles, with the first frame on the left, with a new row for each type, descending down. * *Create a <div> with an 'overflow' attribute of 'hidden' behind the canvas *Make the background of the canvas transparent *Inside of the div, you can use <div>s for the water tiles and adjust their 'margin' attributes to match the position of the map *Give them all a class designation 'water', as well as a class to match the type of water tile (like 'dockleft', 'beachtop', etc.) *In your <style> element, make a class rule '.water' *Give the rule the 'background-image' attribute, linking to whatever and wherever your sprite-sheet is *For each type of water tile, create a class rule that corresponds to each tile-type and give them a matching y position for the sprite-sheet *Create a new <style> element with an id, one that will contain the background-position of all of the frames *Create a javascript variable to conatin the x position of all of the backgrounds *Inside your game loop, decrement the variable by 64 for whenever you want the sprite to change (until it equals 960, then set it 0) *When the variable changes, set the contents of the new <style> element to the new CSS rule for its 'background-position-x' using the variable Meh. A little much, I know, but better than looping through an array and gobbling up system resources, changing each element individually (at least I assume so). Here's a simplified code sample: <script type="text/javascript"> var pos = 0; // background-position-x variable function loop() { document.getElementById('changeMe').innerHTML = ".water{background-position-x:" + pos + "px;}"; //changes the contents of the <style> with the id 'changeMe' //changes the <style> with id 'Change' pos -= (pos == 960) ? -960 : 64; //assuming your sprite-sheet is oriented horizontally setTimeout('loop();', 100); } </script> <style type="text/css"> /* Remains unchanged */ .water { width: 64px; height: 64px; background-image: url('spriteSheet.png'); } .dockleft{ background-position-y: 420px; /* If all of your sprites are on one sheet, you can set the 'background-position-y' attribute for each type of water tile and give the 'water' class one sprite-sheet url for all of the types */ } </style> <style id="changeMe" type="text/css"> /* Changed by 'loop()' */ </style> <body onload="loop();"> <div class="water dockleft"></div> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/7633406", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Mapping elements of a data frame by looping through another data frame I have two R data frame with differing dimensions. However but data frames have an id column df1: nrow(df1)=22308 c1 c2 c3 pattern1.match ENSMUSG00000000001_at 10.175115 10.175423 10.109524 0 ENSMUSG00000000003_at 2.133651 2.144733 2.106649 0 ENSMUSG00000000028_at 5.713781 5.714827 5.701983 0 df2: Genes Pattern.Count ENSMUSG00000000276 ENSMUSG00000000276_at 1 ENSMUSG00000000876 ENSMUSG00000000876_at 1 ENSMUSG00000001065 ENSMUSG00000001065_at 1 ENSMUSG00000001098 ENSMUSG00000001098_at 1 nrow(df2)=425 I would like to loop through df2, and find all genes that have pattern.count=1 and check it in df1$pattern1.match column. Basically I would like to overwrite the fields GENES AND pattern1.match with the df2$Genes and df2$Pattern.Count. All the elements from df2$Pattern.Count are equal to one. I wrote this function, but R freezes while looping through all these rows. idcol <- ncol(df1) return.frame.matches <- function(df1, df2, idcol) { for (i in 1:nrow(df1)) { for (j in 1:nrow(df2)) if(df1[i, 1] == df2[j, 1]) { df1[i, idcol] = 1 break } } return (df1) } Is there another way of doing that without almost killing the computer? A: I'm not sure I get exactly what you are doing, but the following should at least get you closer. The first column of df1 doesn't seem to have a name, are they rownames? If so, df1$Genes <- rownames(df1) Then you could then do a merge to create a new dataframe with the genes you require: merge(df1,subset(df2,Pattern.Count==1)) Note they are matching on the common column Genes. I'm not sure what you want to do with the pattern1.match column, but a subset on the df1 part of merge can incorporate conditions on that. Edit Going by the extra information in the comments, df1$pattern1.match <- as.numeric(df1$Genes %in% df2$Genes) should achieve what you are looking for. A: Your sample data is not enough to play around with, but here is what I would start with: dfm <- merge( df1, df2, by = idcol, all = TRUE ) dfm_pc <- subset( dfm, Pattern.Count == 1 ) I took the "idcol" from your code, don't see it in the data.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to know whether a class method was called internally or remotely in .NET Remoting? I have a class which needs to behave differently when being called remotely via .Net remoting. How can I determine, inside the class, if this is the case? class RemoteClass : MarshalByRefObject { public void SomeMethod () { if (ConditionWhatINeed) //If this method was called internally/remotely { //Do one stuff } else { //Do another suff } } A: you may want to have a look at the RemotingServices.IsObjectOutOfContext Method. it also has an example you may find useful. of course, because you'll be calling this method server-side on 'this' it will never be seen as a remoting object but if you add a parameter to your method than that parameter will be in local context if not remoting and out of context when remoting (PS this is an unverified assumption on my account). Another useful helper may be the RemotingServices.IsTransparentProxy Method. A: There may be a way using one of the *Services objects under the System.Runtime.Remoting hierarchy, as mtijn indicated. However, you have deep problems in your object model. Having dual responsibility on objects is bad practice, difficult to maintain and difficult to understand. Why not rather expose a dedicated 'remote' object; the following sample demonstrates it: class Program { static void Main(string[] args) { InitializeRemoting(); var remote = GetRemotingObject("localhost"); var local = new LocalClass(); remote.SomeMethod(); local.SomeMethod(); Console.ReadLine(); } static void InitializeRemoting() { var c = new TcpServerChannel(9000); ChannelServices.RegisterChannel(c, false); WellKnownServiceTypeEntry entry = new WellKnownServiceTypeEntry ( typeof(RemoteClass), "LocalClass", // Lie about the object name. WellKnownObjectMode.Singleton ); RemotingConfiguration.RegisterWellKnownServiceType(entry); } static LocalClass GetRemotingObject(string serverName) { TcpClientChannel channel = new TcpClientChannel("tcp-client", new BinaryClientFormatterSinkProvider()); ChannelServices.RegisterChannel(channel, false); return (LocalClass)Activator.GetObject ( typeof(LocalClass), // Remoting will happily cast it to a type we have access to. string.Format("tcp://{0}:9000/LocalClass", serverName) ); } } public class LocalClass : MarshalByRefObject { public void SomeMethod() { OnSomeMethod(); } protected virtual void OnSomeMethod() { // Method called locally. Console.WriteLine("Local!"); } } // Note that we don't need to (and probably shouldn't) expose the remoting type publicly. class RemoteClass : LocalClass { protected override void OnSomeMethod() { // Method called remotely. Console.WriteLine("Remote!"); } } // Output: // Remote! // Local! Edit: To answer your question directly, even though what you are trying to achieve is bad practice, duplicate my code and simply provide a virtual bool IsLocal { get { return true; } } on the local class and override it on the remote class. You can then use the property in your if statements. Edit: If you server and your clients needs to share the exact same instance of the class you should use the Facade Pattern. For example: class CommonImplementation { public static readonly CommonImplementation Instance = new CommonImplementation(); private CommonImplementation() { } public void SomeMethod(string someArg, bool isServerCall) { if (isServerCall) { Console.WriteLine("Remote! {0}", someArg); } else { Console.WriteLine("Local! {0}", someArg); } } } // These two classes are the facade. public class LocalClass : MarshalByRefObject { public virtual void SomeMethod(string someArg) { CommonImplementation.Instance.SomeMethod(someArg, false); } } class RemoteClass : LocalClass { public override void SomeMethod(string someArg) { CommonImplementation.Instance.SomeMethod(someArg, true); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7633412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Passing value between NSTabView I try to do a simple program in cocoa, a NSTabVew with 2 items, in the first item I set a content to a string var, in the second tab I display this value. I create two Object class (Prima and Seconda), than I add 2 object in IB setting like Prima and Seconda Prima.m - (IBAction) salva:(id) sender{ nome = [field stringValue]; NSLog(@"%@",nome); } Seconda.m - (IBAction) visualizza:(id) sender{ NSString *dato; Prima *prima = [[Prima alloc] init]; dato = prima.nome; [label setStringValue:dato]; } when I run the program I get this error: 2011-10-03 11:42:43.511 Prova[44622:707] *** Assertion failure in -[NSTextFieldCell _objectValue:forString:errorDescription:], /SourceCache/AppKit/AppKit-1138/AppKit.subproj/NSCell.m:1564 2011-10-03 11:42:43.511 Prova[44622:707] Invalid parameter not satisfying: aString != nil 2011-10-03 11:42:43.513 Prova[44622:707] ( 0 CoreFoundation 0x00007fff8d497986 __exceptionPreprocess + 198 1 libobjc.A.dylib 0x00007fff90ed9d5e objc_exception_throw + 43 2 CoreFoundation 0x00007fff8d4977ba +[NSException raise:format:arguments:] + 106 3 Foundation 0x00007fff8cce914f -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 169 4 AppKit 0x00007fff88957685 -[NSCell _objectValue:forString:errorDescription:] + 160 5 AppKit 0x00007fff889575df -[NSCell _objectValue:forString:] + 19 6 AppKit 0x00007fff88957545 -[NSCell setStringValue:] + 41 7 AppKit 0x00007fff88a58039 -[NSControl setStringValue:] + 115 8 Prova 0x0000000100001365 -[Seconda visualizza:] + 133 9 CoreFoundation 0x00007fff8d48711d -[NSObject performSelector:withObject:] + 61 10 AppKit 0x00007fff88a3f852 -[NSApplication sendAction:to:from:] + 139 11 AppKit 0x00007fff88a3f784 -[NSControl sendAction:to:] + 88 12 AppKit 0x00007fff88a3f6af -[NSCell _sendActionFrom:] + 137 13 AppKit 0x00007fff88a3eb7a -[NSCell trackMouse:inRect:ofView:untilMouseUp:] + 2014 14 AppKit 0x00007fff88abe57c -[NSButtonCell trackMouse:inRect:ofView:untilMouseUp:] + 489 15 AppKit 0x00007fff88a3d786 -[NSControl mouseDown:] + 786 16 AppKit 0x00007fff88a0866e -[NSWindow sendEvent:] + 6280 17 AppKit 0x00007fff889a0f19 -[NSApplication sendEvent:] + 5665 18 AppKit 0x00007fff8893742b -[NSApplication run] + 548 19 AppKit 0x00007fff88bb552a NSApplicationMain + 867 20 Prova 0x0000000100000f92 main + 34 21 Prova 0x0000000100000f64 start + 52 22 ??? 0x0000000000000001 0x0 + 1 ) where is the error for you? A: It seems that dato is nil, which (based on what you've given us) is probably because things aren't hooked up right in the XIB. Without more information I can't say more.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633413", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using JNA or similar to shutdown and restart computer in linux and mac I am trying to write a function in java that will shutdown, force shutdown, restart and force restart the computer and it should work on Windows, Linux and Mac. Windows is not a problem, but I am unable to run commands to shutdown on Linux due to the sudo privileges. I was therefore thinking of using JNA to shut down the computer (i know you can use JNA to do this on windows), but I can't find any examples online for linux or mac. Can anyone help me out? It will be much appreciated! Even if it's not through JNA, it would help me a lot as long as I can find some way to accomplish this. A: If you could simply override system protections just by using Java, that would be a big security flaw! I'm surprised you can do this on Windows. Anyway, it can only be done if you have administrative access to your machine to set the program in a certain group which has the rights to shutdown/restart. Otherwise, you can't just do that. I think you could give directly these rights to your JVM, but that could be dangerous if other java programs try to do shutdown.
{ "language": "en", "url": "https://stackoverflow.com/questions/7633433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Getting logcat from a tester's android device We are having trouble reproducing some bugs in an application we are developing, and so I would like to retrieve logcat logs from a tester's android device. He isn't testing plugged into a computer, and we don't have regular physical access to his machine as he is testing in another location. What is the simplest way for him to send us logcat logs after he has experienced a bug? Please bear in mind he is not a technical professional but he does seem to have a knack for inducing bugs :) A: The best way to do AFAIK is to install a Log application, such as: LogCollector: http://www.appbrain.com/app/log-collector/com.xtralogic.android.logcollector By this way, tester can send log data to your email or message. A: A useful tool to collect log messages remotely is www.remotelogcat.com - it can be used to store strings, or the logcat for the current application. You need to add the permission: <uses-permission android:name="android.permission.READ_LOGS" /> In order to read logs. A: You could try using PhoneHome. Will work >= 4.1 without root, essentially inserting a layer between your log calls and logcat... A: Try this: * *Download Logger app to your device: Logger - Offline Local Debugging https://play.google.com/store/apps/details?id=sk.rogansky.logger.app *Download Logger library to your project and initialize library Download and intialize library: * *Download Loger library via dependencies compile 'sk.rogansky.logger:logger:+' *If you want to automatically send fatal exceptions to Logger app, initialize Logger library in onCreate in App class (don't forget add class to manifest) public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); Log.initialize(getApplicationContext()); // to send fatal exceptions in RELEASE mode too, initialize Logger with unique string channel Log.initialize(context, channel); } } Add class to manifest <application android:name=".MyApp".... *If you want to receive details about network, add permission to manifest <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> Logger library has the same interface as java logger, but has some nice features. After initialization will library automatically send fatal exceptions to Logger app. You can send your message too. Just add action to call method. import sk.rogansky.logger.Log; Log.d(Log.Action.SHOW_NOTIFICATION, "TAG", "Message"); Log.d(Log.Action.SAVE, "TAG", "Message"); // it will save locally in Logger app Everything works local and offline, but testers can share logs via Logger app. A: I've found a way to collect logs without libraries or Log Applications. You gonna need to create a Process object by executing Runtime command and specifying arguments as: new String[]{"logcat", "-v", "threadtime"} Then, you could use InputStream from Process to read logs. See this article for example code and more details: https://medium.com/@danileron/collect-testers-devices-logs-without-libraries-or-third-party-applications-9e6a7e609a2c
{ "language": "en", "url": "https://stackoverflow.com/questions/7633434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Map different function to first and last element in list I have a function where I want to transform a list of floats into another one, where for each element I want to have x percent of element i spill over into element i + 1 example: let p3 = [0.1; 0.2; 0.4; 0.2; 0.1] then p3_s should be: [0.05; 0.15; 0.3; 0.3; 0.2] To do this I took half of each element and added it to the next element. * *0.1 became 0.05 because it gave 0.05 to the next, there is no previous element *0.2 became 0.15 because it gave 0.1 to the next and got 0.05 from the first *etc *and finally 0.1 became 0.2 because it .01 from the previous. There is no next element. Now I came up with this which works but only for list of size 5: // create list let p3 = [0.1; 0.2; 0.4; 0.2; 0.1] let shiftList orgList shift = // chop list up in tuples of what stays and what moves let ms = orgList |> List.map (fun p-> (p * shift, p * (1.0-shift))) // map new list ms |> List.mapi (fun i (move, stay) -> match i with | 0 -> stay | 4 -> stay + fst ms.[i-1] + move // note hardcoded 4 | _ -> stay + fst ms.[i-1]) // get shifted list shiftList p3 0.5 Now for the questions: 1) How do I make it match on any length list? Now I hardcoded the 4 in the match expression but I'd like to be able to accept any lenght list. I tried this: let shiftList orgList shift = // chop list up in tuples of what stays and what moves let ms = orgList |> List.map (fun p-> (p * shift, p * (1.0-shift))) // find length let last = orgList.Length - 1 // map new list ms |> List.mapi (fun i (move, stay) -> match i with | 0 -> stay | last -> stay + fst ms.[i-1] + move | _ -> stay + fst ms.[i-1]) // now this one will never be matched But this will not treat last as the number 4, instead it becomes a variable for i even though last is already declared above. So how could I match on a variable, so that I can treat the last elmement differently? Finding the first one is easy because it's at 0. 2) How would you do this? I'm still pretty fresh to F# there are many things I don't know about yet. Guess the general case here is: how do I map a different function to the first and last element of a list, and a general one to the others? Thanks in advance, Gert-Jan A: Here is a more functional solution let func (input:float list) = let rec middle_end input_ = match input_ with |h::t::[] -> ((h/2.0)+t)::[] |h::t::tt ->((h+t)/2.0)::(middle_end (t::tt)) | _ -> [] //fix short lists let fst = input.Head/2.0 fst::middle_end(input) Also, this only requires a single pass through the list, rather than the 3 in Ramon's solution, as well as less temporary storage. A: As an alternative to writing your own recursive function, you can also use built-in functions. The problem can be solved quite easily using Seq.windowed. You still need a special case for the last element though: let p3 = [0.1; 0.2; 0.4; 0.2; 0.1] // Prefix zero before the list, pre-calculate the length let p3' = (0.0 :: p3) let l = p3.Length // Perform the transformation p3' |> Seq.windowed 2 |> Seq.mapi (fun i ar -> (if i = l - 1 then ar.[1] else ar.[1] / 2.0) + ar.[0] / 2.0) |> List.ofSeq A: You want to do: let shiftList orgList shift = // chop list up in tuples of what stays and what moves let ms = orgList |> List.map (fun p-> (p * shift, p * (1.0-shift))) // find length let last = orgList.Length - 1 // map new list ms |> List.mapi (fun i (move, stay) -> match i with | 0 -> stay | last' when last' = last -> stay + fst ms.[i-1] + move | _ -> stay + fst ms.[i-1]) // now this one will never be matched A: Using List.scan: let lst = [0.1; 0.2; 0.4; 0.2; 0.1] let len = (lst.Length-1) lst |> List.mapi (fun i e -> (i,e)) |> List.scan (fun (c,_) (i,e) -> if i = len then (0.0,e+c) else ((e/2.0),(e/2.0)+c)) (0.0,0.0) |> List.tail |> List.map snd A: Just another idea, let bleh p3 = match Seq.fold (fun (give,acc) i -> i*0.5,((i*0.5 + give) :: acc)) (0.0,[]) p3 with |(give,h::t) -> give+h :: t |> List.rev |(_,[]) -> []
{ "language": "en", "url": "https://stackoverflow.com/questions/7633441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: how to save instance the activity without refreshing? i switch to next screen and then comes back to the original and wants to pick up where i left off , save and restore data.In Activity 1:i have more than 10 buttons i can select and unselect button,if go to next screen and if i come back it should not reload,it should show me where i leftoff, up1 = (Button) findViewById(R.id.adultup1); up1.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (upt1 == 0) { up1.setBackgroundResource(R.drawable.adultup1); upt1 = 1; } else { up1.setBackgroundResource(R.drawable.adultup1_pressed); upt1 = 0; } } }); submit = (ImageButton) findViewById(R.id.next); submit.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { TabFunctionality.setFirstTabFunctionality(TabFunctionality.FIRST_TAB, 1); Intent intent = new Intent(AdultTeeth.this, MainScreen.class); intent.putExtra("TEXT", view); startActivity(intent); finish(); } }); } A: I am not sure the whole picture of your activities as you just post a part of the code. I can tell you now is you could use startActivityForResult() instead of startActivity(). StartActivity() and finish() will close Activity 1. And you could get anything result of Activity 2 from onActivityResult() in Activity 1. A: override protected void onSaveInstanceState(Bundle outState){} and save all button states here and put it in the bundle. and while creating or resuming Activity get these values and restore your state..
{ "language": "en", "url": "https://stackoverflow.com/questions/7633442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }