text
stringlengths
8
267k
meta
dict
Q: Jquery, after cloning and changing id of a div, cannot access the element through that id After I clone my (div) container and change the id, I cannot seem to get at it using the id-selector, am I doing something wrong? I know the clone is correct, I know the id changed good, but I can no longer use the default Jquery selector to get at that element. var clone = $('#test').clone(); clone.attr('id', 'abc'); alert(clone.attr('id')); // gives 'abc' alert($("#abc").html()); // gives null <------------ WHY? alert(clone.html()); // gives correct html A: You haven't inserted the clone into the DOM yet. This $("#abc") looks in the current document for that ID and it isn't in there yet. This works: var clone = $('#test').clone(); clone.attr('id', 'abc'); alert(clone.attr('id')); // gives 'abc' $(document.body).append(clone); // <==== Put the clone into the document alert($("#abc").html()); // gives correct html
{ "language": "en", "url": "https://stackoverflow.com/questions/7518786", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Selecting every Nth row per user in Postgres I was using this SQL statement: SELECT "dateId", "userId", "Salary" FROM ( SELECT *, (row_number() OVER (ORDER BY "userId", "dateId"))%2 AS rn FROM user_table ) sa WHERE sa.rn=1 AND "userId" = 789 AND "Salary" > 0; But every time the table gets new rows the result of the query is different. Am I missing something? A: Assuming that ("dateId", "userId") is unique and new rows always have a bigger (later) dateId. After some comments: What I think you need: SELECT "dateId", "userId", "Salary" FROM ( SELECT "dateId", "userId", "Salary" ,(row_number() OVER (PARTITION BY "userId" -- either this ORDER BY "dateId")) % 2 AS rn FROM user_table WHERE "userId" = 789 -- ... or that ) sub WHERE sub.rn = 1 AND "Salary" > 0; Notice the PARTITION BY. This way you skip every second dateId for each userId, and additional (later) rows don't change the selection so far. Also, as long as you are selecting rows for a single userId (WHERE "userId" = 789), pull the predicate into the subquery, achieving the same effect (stable selection for a single user). You don't need both. The WHERE clause in the subquery only works for a single user, PARTITION BY works for any number of users in one query. Is that it? Is it? They should give me "detective" badge for this. Seriously. A: No that seems to be OK. You have new rows, those rows change the old rows to appear on different position after sorting. A: If someone insert a new row with a userId below 789 the order will change. For example, if you have: userId rn 1 1 4 0 5 1 6 0 and you insert a row with userId = 2, the rn will change: userId rn 1 1 2 0 4 1 5 0 6 1 In order to select every Nth row you need a column with a sequence or a timestamp.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518788", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Searching for certain triples in a list Let’s assume we have a list of elements of the type {x,y,z} for x, y and z integers. And, if needed x < y < z. We also assume that the list contains at least 3 such triples. Can Mathematica easily solve the following problem? To detect at least one triple of the type {a,b,.}, {b,c,.} and {a,c,.}? I am more intereseted in an elegant 1-liner than computational efficient solutions. A: If I understood the problem, you want to detect triples not necessarily following one another, but generally present somewhere in the list. Here is one way to detect all such triples. First, some test list: In[71]:= tst = RandomInteger[5,{10,3}] Out[71]= {{1,1,0},{1,3,5},{3,3,4},{1,2,1},{2,0,3},{2,5,1},{4,2,2}, {4,3,4},{1,4,2},{4,4,3}} Here is the code: In[73]:= Apply[Join,ReplaceList[tst,{___,#1,___,#2,___,#3,___}:>{fst,sec,th}]&@@@ Permutations[{fst:{a_,b_,_},sec:{b_,c_,_},th:{a_,c_,_}}]] Out[73]= {{{1,4,2},{4,3,4},{1,3,5}},{{1,4,2},{4,2,2},{1,2,1}}} This may perhaps satisfy your "one-liner" requirement, but is not very efficient. If you need only triples following one another, then, as an alternative to solution given by @Chris, you can do ReplaceList[list, {___, seq : PatternSequence[{a_, b_, _}, {b_, c_, _}, {a_,c_, _}], ___} :> {seq}] A: I don't know if I interpreted your question correctly but suppose your list is something like list = Sort /@ RandomInteger[10, {20, 3}] (* {{3, 9, 9}, {0, 5, 6}, {3, 4, 8}, {4, 6, 10}, {3, 6, 9}, {1, 4, 8}, {0, 6, 10}, {2, 9, 10}, {3, 5, 9}, {6, 7, 9}, {0, 9, 10}, {1, 7, 10}, {4, 5, 10}, {0, 2, 5}, {0, 6, 7}, {1, 8, 10}, {1, 8, 10}} *) then you could do something like ReplaceList[Sort[list], {___, p:{a_, b_, _}, ___, q:{a_, c_, _}, ___, r:{b_, c_, _}, ___} :> {p, q, r}] (* Output: {{{0, 2, 5}, {0, 9, 10}, {2, 9, 10}}, {{3, 4, 8}, {3, 5, 9}, {4, 5, 10}}, {{3, 4, 8}, {3, 6, 9}, {4, 6, 10}}} *) Note that this works since it is given that for any element {x,y,z} in the original list we have x<=y. Therefore, for a triple {{a,b,_}, {a,c,_}, {b,c,_}} \[Subset] list we know that a<=b<=c. This means that the three elements {a,b,_}, {a,c,_}, and {b,c,_} will appear in that order in Sort[list]. A: To match triples "of the type {a,b,.}, {b,c,.} and {a,c,.}": list = {{34, 37, 8}, {74, 32, 65}, {48, 77, 18}, {77, 100, 30}, {48, 100, 13}, {100, 94, 55}, {48, 94, 73}, {77, 28, 12}, {90, 91, 51}, {34, 5, 32}}; Cases[Partition[list, 3, 1], {{a_, b_, _}, {b_, c_, _}, {a_, c_, _}}] A: (Edited) (Tuples was not the way to go) Do you require something like: list = RandomInteger[10, {50, 3}]; Cases[Permutations[ list, {3}], {{a_, b_, _}, {b_, c_, _}, {a_, c_, _}} /; a < b < c] giving {{{0, 1, 2}, {1, 5, 2}, {0, 5, 4}}, {{2, 3, 5},{3, 4, 10}, {2, 4, 5}}, {{6, 8, 10}, {8, 10, 10},{6, 10, 0}}, {{2, 4, 5}, {4, 8, 2}, {2, 8, 5}}, {{2, 4, 5}, {4, 7, 7}, {2, 7, 3}}, {{0, 2, 2}, {2, 7, 3}, {0, 7, 2}}, {{0, 2, 1}, {2, 7, 3}, {0, 7, 2}}} or perhaps (as other have interpreted the question): Cases[Permutations[ list, {3}], {{a_, b_, _}, {b_, c_, _}, {a_, c_, _}}];
{ "language": "en", "url": "https://stackoverflow.com/questions/7518790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Flash, ActionScript 3.0 Tiles map I want to build a Flash game using tiles (32x32) For a few years ago I used http://www.tonypa.pri.ee/tbw/start.html but I'm quite sure that is pretty outdated these days. I want to have scrolling as well (a big map). Could someone provide me with some links that I can start off with? I have problem finding something useful. A: No sense in re-inventing the wheel. For my two cents, I recommend using a game engine. Here is a list of the most popular ones: http://www.flashrealtime.com/flash-game-library-engine-list/ It seems that http://flixel.org/ would fit your purpose. Have a look at their examples to get an idea on where to begin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to modify sql Data Source parameters on event? here is my scenario: Iv linked a parameter of my sqlds to a dropDownList (dropDownList.selectedValue), but i want it so that when the selected item is "" (an item with no text is added on pageload, to let the user select a null value, sort of), i want the sqlds to pass null. Here is what i tried, but it doesnt work (gave the error saying no such parameter existed: protected void sqldsNewItem_Inserting(object sender, SqlDataSourceCommandEventArgs e) { DropDownList ddl = dwNewItem.FindControl("ddlEffects") as DropDownList; if (ddl.SelectedItem.Text == "") { e.Command.Parameters["effect"].Value = null; e.Command.Parameters["numberOfTurns"].Value = null; } } (I used FindControl because the dropDownList in question is in a template.) And here is how i bound it to the sqlds in the first place: <asp:ControlParameter ControlID="dwNewItem$ddlEffects" Name="effect" PropertyName="SelectedValue" DbType="int64" /> Thanks guys!
{ "language": "en", "url": "https://stackoverflow.com/questions/7518793", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Instapaper API & Javascript XAuth I've spent most of today try to implement Instapaper's XAuth API. I haven't even been able to get an oauth token, yet. Any ideas what I'm doing wrong? I'm using node.js and the oauth module. It's my understanding that I need to pass the username, password, amd mode as extra parameters. And the oauth module should take care of all of the oauth parameters. But it's not. Here's the code: var OAuth = require('oauth').OAuth; var oauth = new OAuth(  '',  'https://www.instapaper.com/api/1/oauth/access_token',  'CONSUMER_KEY',  'CONSUMER_SECRET',  '1.0',  null,  'HMAC-SHA1',  null ); var extra = {  'x_auth_username': 'USERNAME',  'x_auth_password': 'PASSWORD',  'x_auth_mode': 'client_auth' }; var hello = oauth._prepareParameters('', '', 'POST', 'https://www.instapaper.com/api/1/oauth/access_token', null); var url = 'https://www.instapaper.com/api/1/oauth/access_token'; var f = true; for (var i in hello) {  if (f) {    url += '?';    f = false;  } else {    url += '&';  }  url += hello[i][0] + '=' + hello[i][1]; } console.log(url+'&x_auth_mode=client_auth&x_auth_username=&x_auth_password=') oauth._performSecureRequest('', '', "POST", url+'&x_auth_mode=client_auth&x_auth_username=&x_auth_password=', null, null, null, function(error, data, response) {  console.log(error, data) }); And it returns this: { statusCode: 401, data: 'oauth_signature [pWRf4W9k9nogID/O90Ng29bR2K0=] does not match expected value [eqJ8zD1bKeUa3InpDyegGDAbSnM=]' } 'oauth_signature [pWRf4W9k9nogID/O90Ng29bR2K0=] does not match expected value [eqJ8zD1bKeUa3InpDyegGDAbSnM=]'} A: So I am not sure whether this is an error with the oauth module or if Instapaper's API is too strict in parsing the Authorization headers, but I had to add a space after the comma for the header delimiter. At any rate this seems to be causing all the issues (400 errors). oauth currently builds up headers as: oauth_consumer_key=SomeKey,oauth_consumer_secret=SomeSecret... needed to be oauth_consumer_key=SomeKey, oauth_consumer_secret=SomeSecret... I modified the oauth.js file to reflect this. https://github.com/ciaranj/node-oauth/blob/master/lib/oauth.js#L121 added a space after the comma towards the end of the line authHeader+= "" + this._encodeData(orderedParameters[i][0])+"=\""+ this._encodeData(orderedParameters[i][1])+"\", "; Here is my working client sample: var OAuth = require('oauth').OAuth; var consumerKey = 'chill'; var consumerSecret = 'duck'; var oa = new OAuth( null, 'https://www.instapaper.com/api/1/oauth/access_token', consumerKey, consumerSecret, '1.0', null, 'HMAC-SHA1' ); var x_auth_params = { 'x_auth_mode': 'client_auth', 'x_auth_password': 'yourpass', 'x_auth_username': 'yourusername@whatever.com' }; oa.getOAuthAccessToken(null, null, null, x_auth_params, function (err, token, tokenSecret, results) { // CAN HAZ TOKENS! console.log(token); console.log(tokenSecret); // ZOMG DATA!!! oa.get("https://www.instapaper.com/api/1/bookmarks/list", token, tokenSecret, function (err, data, response) { console.log(data); }); }); Hope this helps! A: Derek's answer is right about the missing space as being the problem, but you don't need to edit oauth.js. After creating the OAuth client, just set the separator string: var OAuth = require('oauth').OAuth; var oa = new OAuth({...}); oa._oauthParameterSeperator = ', '; (yes, "sepErator", there's a typo in the module's code)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Wait for threads to complete before continuing When the user launches my Android App, I fire up 2 threads to do some processing in the background. thread_1 does some calculations on the client, and thread_2 fetches some data from the server. That all works fine. None of the threads modify the UI. I have two follow up questions. new Thread(new Runnable(){ @Override public void run(){ MyClass.someStaticVariable = doSomeCalculations(); } }).start(); * *What is the best practice to retrieve the data from the run() method of a thread? I currently have a static variable, and I assign the relavent calculated data/ fetched data to it. Or is it recommended to use the Handler class to get data out of threads? I imagined one only uses the handler if they wish to update the UI. while(true) { if (!thread1.isAlive() && !thread2.isAlive()) { startActivity(intent) } } *I need to wait until both threads are finished before I can pass the data from both threads via an Intent. How can I achieve that? I can do it using the code shown above, but that just seems wrong. A: Using callable / Future / ExecutorService would be the cleanest way of doing this in a reqular java app (should be same for android as well) ExecutorService executor = Executors.newFixedThreadPool(2); Future<Integer> firstThreadResult = executor.submit(new Callable<Integer>() { Integer call() { } }); Future<Integer> secondThreadResult = executor.submit(new Callable<Integer>() { Integer call() { } }); executor.shutdown(); executor.awaitTermination(Integer.MAX_VALUE,TimeUnit.SECONDS); // or specify smaller timeout // after this you can extract the two results firstThreadResult.get(); secondThreadResult.get(); More detailed example. A: You could use a Future. It will block on get until the data is available: http://developer.android.com/reference/java/util/concurrent/Future.html An alternative is to pass a CountDownLatch into the threads and call countDown() when exiting the run method: http://developer.android.com/reference/java/util/concurrent/CountDownLatch.html final CountDownLatch latch = new CountDownLatch(2); new Thread(new Runnable(){ @Override public void run(){ // Do something latch.countDown() } }).start(); new Thread(new Runnable(){ @Override public void run(){ // Do something latch.countDown() } }).start(); latch.await() startActivity(intent) A: * *You can use a shared object (via static field pointing to it or any other way), but you must be aware of two things. First there are synchronization issues with objects accessed by two threads. Use immutable objects to aleviate that. Second, how to notify the other thread that new shared data is available - this depends on what your other thread is doing. *Set common flag that both threads check or set when they finish. This way thread can check if other flag finished before it. A: For query 1: What is the best practice to retrieve the data from the run() method of a thread? In addition to Future, you can use Callback mechanism from your thread run() method. In this run() method, pass the value to caller object or set the relevant values in an object. Implementing callbacks in Java with Runnable For query 2: I need to wait until both threads are finished before I can pass the data from both threads via an Intent You can achieve it in multiple ways in addition basic join() API. 1.ExecutorService invokeAll() API Executes the given tasks, returning a list of Futures holding their status and results when all complete. 2.CountDownLatch A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. 3.ForkJoinPool or newWorkStealingPool() in Executors Refer to this related SE question: wait until all threads finish their work in java
{ "language": "en", "url": "https://stackoverflow.com/questions/7518803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Function Pointer - Automatic Dereferencing Possible Duplicate: How does dereferencing of a function pointer happen? void myprint(char* x) { printf("%s\n", x); } int main() { char* s = "hello"; void (*test)(char*); void (*test2)(char*); test = myprint; test2 = &myprint; test(s); (*test)(s); test2(s); (*test2)(s); } Can anyone explain to me why all of the above code is valid? "hello" is printed four times. By applying the function pointer, is it implicitly derefenced? Basically I want to know how function pointers are actually stored, because the above is kind of confusing. A: This is just a quirk of C. There's no other reason but the C standard just says that dereferencing or taking the address of a function just evaluates to a pointer to that function, and dereferencing a function pointer just evaluates back to the function pointer. This behavior is (thus obviously) very different from how the unary & and * operators works for normal variables. So, test2 = myprint; test2 = &myprint; test2 = *myprint; test2 = **********myprint; All just do exactly the same, gives you a function pointer to myprint Similarly, test2(s); (*test2)(s); (***********test2)(s); Does the same, call the function pointer stored in test2. Because C says it does.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "33" }
Q: Probability computation and algorithm for subsequences Here is a game where cards 1-50 are distributed to two players each having 10 cards which are in random order. Aim is to sort all the cards and whoever does it first is the winner. Every time a person can pick up the card from the deck and he has to replace an existing card. A player can't exchange his cards. i.e only he can replace his card with the card from the deck.A card discarded will go back to deck in random order. Now I need to write a program which does this efficiently. I have thought of following solution 1) find all the subsequences which are in ascending order in a given set of cards 2) for each subsequence compute a weight based on the probability of the no of ways which can solve the problem. for ex: If I have a subsequence 48,49,50 at index 2,3,4 probability of completing the problem with this subsequnce is 0. So weight is multiplied by 0 . Similarly if I have a sequence 18,20,30 at index 3,4,5 then no of possible ways completing the game is 20 possible cards to chose for 6-10 and 17 possible cards to chose for first 2 position , 3) for each card from the deck, I'll scan through the list and recalculate the weight of the subsequnces to find a better fit. Well, this solution may have lot of flaws but I wanted to know 1) Given a subsequence , how to find the probability of possible ways to complete the game? 2) What are the best algorithm to find all the subsequences? A: So if I understand correctly, the goal is to obtain an ordered hand by exchanging as few cards as possible, right? Have you tried the following approach? It is very simplistic, yet I would guess it has a pretty good performance. N=50 I=10 while hand is not ordered: get a card from the deck v = value of the card put card in position round(v/N*I)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518818", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "9" }
Q: Remote service does not Bind / asInterface returns "null" I created a Remote Service after the example in this book and try to bind it with in this activity: public class TuCanMobileActivity extends Activity { /** Called when the activity is first created. */ //private HTTPSbrowser mBrowserService; private HTTPBrowserRemote mBrowserRemoteService; private Boolean mbound=false; private ServiceConnection mBrowserRemoteServiceConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { try { mBrowserRemoteService.unregister_course_callback(courseCallback); } catch (RemoteException e) {} } @Override public void onServiceConnected(ComponentName name, IBinder service) { mBrowserRemoteService=HTTPBrowserRemote.Stub.asInterface(service); mbound=true; try { mBrowserRemoteService.register_course_callback(courseCallback); } catch (RemoteException e) { // TODO: handle exception } } }; private final IClassesCallback courseCallback = new IClassesCallback.Stub() { @Override public void expressClassesdata(HTTPSResponse ClassesResponse) throws RemoteException { Toast.makeText(TuCanMobileActivity.this, "Just works??", Toast.LENGTH_SHORT).show(); final TextView txtLoginName = (TextView) findViewById(R.id.textView1); txtLoginName.setText(ClassesResponse.HTMLResponse); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void onClickSendLogin (final View sfNormal) { final Intent browserIntent = new Intent(TuCanMobileActivity.this,HTTPBrowserRemoteImpl.class); this.bindService(browserIntent, mBrowserRemoteServiceConnection, Context.BIND_AUTO_CREATE); if(mbound==true){ Toast.makeText(TuCanMobileActivity.this, "Service Bound", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(TuCanMobileActivity.this, "Service NOT Bound", Toast.LENGTH_SHORT).show(); } try { mBrowserRemoteService.call_course_overview(); } catch (RemoteException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*final Intent i = new Intent(this,MainMenu.class); startActivity(i);*/ unbindService(mBrowserRemoteServiceConnection); } } But the mBrowsserRemoteService is null (in the method onClickSendLogin) and returns a NullPointerException and I don't know why? It also seems that the onBind method in the service is never called. Where is my problem. Thanks in advance Tyde A: The reason you are getting a NullPointerException is because you are executing mBrowserRemoteService.call_course_overview(); regardless of mbound; mbound may be true or false at that point. I suspect a bigger problem is that you are unable to bind to this service most likely because your AndroidManifest.xml is not configured correctly. If you're still having issues, please post your AndroidManifest file.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518823", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Identifying Files in Plone BlobStorage Files in var/blobstorage can be listed and sorted by their sizes via Unix commands. This way shows big files on top list. How can I identify these files belongs to which IDs/paths in a Plone site? A: There is no 'supported' way to do this. You could probably write a script to inspect the ZODB storage, but it'd be complicated. If you want to find the biggest files in your Plone site, you're probably better off writing a script that runs in Plone and using it to search (using portal_catalog) for all File objects (or whatever content type is most likely to have big files) and calling get_size() on it. That should return the (cached) size, and you can delete what you want to clean up.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518824", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Where do you whitelist your domain on Facebook for video embeds? Do you still need to get your domain whitelisted by Facebook to allow embedding of your own Flash videos into feeds? If so, where do you go to do so? The old page was: http://www.facebook.com/help/contact.php?show_form=video_embed_whitelist This, however, now redirects and I'm unable to find any information on this at all. Thanks! A: You don't need to whitelist your domain for videos anymore. You can utilize opengraph and og:video tags to share videos on the user/page walls. more info: https://developers.facebook.com/docs/opengraph/ scroll to og:video hope this helps
{ "language": "en", "url": "https://stackoverflow.com/questions/7518833", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How are URI's handled in a REST api? I'm creating a hobby iOS app, and I'm a bit confused about how to create a REST backend for it. I've read the resources available on the internet and I understand the theories behind REST. However, I'm confused about how the URI's get handled. For instance, is there a file handling rest functions at /resource/ or /resource/{id} or are these files sitting at root, and somehow the URI calls are getting routed to them? Excuse my ignorance at web design. A: That depends on the server architecture. It’s perfectly legal to have only separate CGI files sitting in appropriate folders and handling the requests, maybe in conjuction with some URL rewriting to have nice URLs. On the other hand most modern web frameworks have some kind of URL dispatcher. That’s a core component of the framework, and it takes care of dispatching (= mapping) requests to various pieces of code (usually classes and methods). There’s for example a modern Perl framework called Mojolicious. Even without knowing any Perl you might find its documentation about routing interesting, for it answers your question quite well.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: While loop keeps repeating I setup a while loop where i want to choose r or h, i dont want to use forloops but i want to use a switch why is it when i enter r or h it keeps repeating a million times the cout for that case? I cant get it to just say it once.. while (chooseMove == 'r' or 'h') { switch (chooseMove) { case 'r': cout << "you chose r"; break; case 'h': cout << "you chose h"; break; } } I also tried it with forloops and had the same problem i cant figure it out A: What you mean is while (chooseMove == 'r' or chooseMove == 'h'). What you've currently written is equivalent to ((chooseMove == 'r') or ('h')), and 'h' evaluates as true. Maybe you were also asking for help with the input logic: char c; bool success = false; while (std::in >> c) { switch(c) { case 'r': /* ... */ success = true; break; case 'h': /* ... */ success = true; break; } if (success) break; } This will also terminate if the input stream is closed, and you can use success to inspect the success of the operation. A: Because that's what you programmed it to do. If you want the loop to stop or pause (and say, wait for input), you should add that code into the loop. while (chooseMove == 'r' or chooseMove == 'h') { switch (chooseMove) { case 'r': cout << "you chose r"; break; case 'h': cout << "you chose h"; break; } std::cin >> chooseMove; //stop and wait for more input } A: This is a problem: while (chooseMove == 'r' or 'h') Try this instead: while ((chooseMove == 'r') || (chooseMove == 'h')) When you write (how did this even compile? or isn't C++): chooseMove == 'r' or 'h' It is interpreted as: (chooseMove == 'r') or ('h') The statement 'h' is always true, so the while loop runs forever. A: What does chooseMove == 'r' or 'h' mean? According to the C++ standard, this is grouped as (chooseMove == 'r') or ('h'); the implicit conversion of 'h' to bool then results in (chooseMove == 'r') or ('h' != 0). The second condition will always be true. A: while (chooseMove == 'r' or 'h') which is equivalent to this: while ( (chooseMove == 'r') or true) //same as while ( (chooseMove == 'r') || true) So this is infinite loop. Note that or and || are same thing. What you want is this: while ( (chooseMove == 'r') or (chooseMove == 'h')) //same as while ( (chooseMove == 'r') || (chooseMove == 'h'))
{ "language": "en", "url": "https://stackoverflow.com/questions/7518837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java: NullPointerException when trying to add object to BlockingQueue? I found a similar question about a PriorityQueue, the error with that one was that it wasn't initialized correctly. I might have the same problem, but i can't figure out how to initialize it correctly! As of now i just do: BlockingQueue myQueue = null; but that throws an exception as soon as i try to add something to the list. How do i correctly initialize a BlockingQueue? A: BlockingQueue<E> is an interface. You need to pick a specific implementation of that interface, such as ArrayBlockingQueue<E>, and invoke one of its constructors like so: BlockingQueue<E> myQueue = new ArrayBlockingQueue<E>(20); If you're unsure what different types of blocking queues exist in the JDK, look under "All Known Implementing Classes". A: If you call any method on null you will get a null pointer exception. Try making a new ArrayBlockingQueue, which implements the interface. A: Please read the javadocs which also has examples http://download.oracle.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html BlockingQueue blockingQueue = new ArrayBlockingQueue(100); // there are other implementations as well, in particular that uses a linked list and scales better than the array one. A: * *Make BlockingQueue hold a certain type, for example BlockingQueue<String> or something similar. *You need to initialize the variable with an implementation of BlockingQueue, for example ArrayBlockingQueue<E>. So do something like: BlockingQueue<MyObject> = new ArrayBlockingQueue<MyObject>(); and you'll be fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Making an Android App (Java) 'Wait' Until Something Finishes I have this app that originally has you take a picture, shows you a progress bar, and uploads it to a website. What I want to add is something so that before the progress bar shows, an Intent starts an activity that loads a layout with a dropdown menu that allows you to choose a descriptor for the picture. Following this, once you hit the 'OK' button on this new layout, the program should return back to where it had left off and display the progress bar. Does anyone have any ideas on how to achieve this? It seems that all I really want is some way to tell the program to stall for a while to call an intent, and when the user hits 'OK', the code may resume. A: You should be using OnActivityResult().. More information on the link below http://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518842", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sharing SQL Server Between Multiple System I have three computer in a office and I have installed my C#-2005 Project on all three computers. But Problem is that Boss wants Sql-server-2000 on One PC out of three and other would share the same. I don’t know how to share Sql-server-2000 between three PC?. How to do?. Confusion:- Thanks for your co-operation but here I have a confusion on majority people said to check TCP/IP address and consider the Connection string as per main server from client PC. Suppose I have financial project and there would be thousand of connection string in a project. As per above I have to change thousand of connection string as per main pc. Now think it is a one customer's need If I have ten cutomer having same offer than think How much time I have to waste on it?. I have to modify thousand of connection string ten time more?. If it is true than it will take lots of time on installation to each customer. I don’t know if it is only way?. The Connection string I have utilized on my each winform is as below: string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah"; SqlConnection conn = new SqlConnection(connstr); conn.Open(); Here suggested about Config File and same I don't know if some body give me idea about how to consider it with my C#2005 project than it will save my lots time. A: When you connect to the database in your code, you'll a database connection string of some sort somewhere in there. Figure out the connection string for the Database server and set your code to point to that database server's connection info; I'd bet you currently you have it pointed at localhost If you're using SQL Server you may need to enable remote connections on the database server. added: you may need to modify firewall settings as well to allow SQL Server traffic (thanks Jared) . Edit: For putting the configuration string into a central location. Your posted code string connstr = "server=.;initial catalog=maa;uid=mah;pwd=mah"; SqlConnection conn = new SqlConnection(connstr); conn.Open(); Change to Assuming your application has a App.Config file then you'd add an entry in there like <add key="DBConnectionString" value="server=.;initial catalog=maa;uid=mah;pwd=mah"/> And change your C# code to be like string connstr = ConfigurationManager.AppSettings["DBConnectionString"]; SqlConnection conn = new SqlConnection(connstr); conn.Open(); Putting the ConfigManager call into a class might be a good idea if you have a lot of settings to retrieve and/or believe the configuration storage methodology might change down the road. Going with the above example is WAY better than having the string literal scattered throughout your code. A: Enable theTCP/IP connection in SQL Server. So that you can connect remotely from any pc within the network check here A: If your problem is that you embedded your connection string in the code, then you are going to have to do some refactoring. These would be the general steps, you will have to tailor them a bit to your situation. * *Add your connection string to the app.config file. *Create a static/shared method that will read the connection string from the config file. *Do a find and replace in your solution to replace all of the hard coded connection strings in your code with the (class and) name of the method that gets the connection string. This is probably going to be easier than rewriting all of your data calls to use something like enterprise library or EF. A: You will need to do as the others suggested, such as changing the connection string and enabling TCP/IP within SQL Server, but you will also likely need to configure your firewall to allow requests to SQL Server (default port of 1433) through.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518847", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Dynamic video playback speed on iOS? Does anyone know how to play a video on an iOS device, then change the playback speed smoothly to a faster or slower framerate?
{ "language": "en", "url": "https://stackoverflow.com/questions/7518849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EWS: How to upload attachment first before sending an email? I use Exchange Web Service API to do sending email. It is very easy to add attachments by just writing message.Attachments.AddFileAttachment(attachmentname); The problem is attaching process happens in sending process. I found that yahoo, gmail and hotmail they all uploading attachmetns first before you sending the mail. How to do so? A: It's the EWS Managed API which does this uploading and sending in one process. But in the background, multiple requests are made to the Exchange server: * *Create the message in the Drafts folder of your mailbox *Upload the attachments *Send the items. If you want to, you can do this yourself. But I don't see the point in doing that. What do you want to accomplish? A: If you notice, GMail for example does not use the same manner of attachment. For instance, when you attach something, I am guessing the files get uploaded to some server and then they just provide you with a Link for the download. So I think you can upload the file to some server (be it FTP, or just a database) and then just add the links to the download of the files in the body of the email. Good luck. I will be looking into the thread to see if there is in fact a way to do this. Hanlet
{ "language": "en", "url": "https://stackoverflow.com/questions/7518850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JavaScript and 'this' inside immediately executed functions I have been reading up on the intricacies of 'this' in JavaScript. Given this code: $(document).ready(function() { console.dir(this); (function foo() { console.dir(this); })(); }); In Chrome, the console shows the first 'this' as an 'HTMLDocument' (as I expected), but the second 'this' is 'undefined'. Can someone point me to a good explanation of why? A: They way in which a javascript function is invoked changes the meaning of this inside of it. Here you've invoked a method which isn't associated with any object hence it has no this value to bind to. In the first case the callback is being invoked via JQuery and they are manipulating the callback such that this points to the document DOM element. It's easy to visualize this as your callback being invoked with apply yourCallback.apply(document, null); You can fix the second version like so $(document).ready(function() { console.dir(this); var that = this; (function foo() { console.dir(that); })(); }); Or another way using apply $(document).ready(function() { console.dir(this); (function foo() { console.dir(this); }).apply(this, null); }); A: this is the context with which the current function has been called. * *When calling a function with the object.method() syntax, object become the context. *When calling a function with the function() syntax, there is no context: it's null. jQuery calls your ready function with document as the context. And you call your immediately executed function without context, which is why it's null. You can do this: // assign `this` to that so you can access `this` through `that` var that = this; (function foo() { console.log(that); }()); Or this: // bind the function to `this` and then call it $.proxy(function() { console.log(this); }, this)(); See jQuery.proxy. Or even this: // call the function with `this` as context (function() { console.log(this); }).call(this); See Function.call. A: If that code is put into the console of a page with jQuery loaded, the second "this" is DOMWindow, which is the global "this". It is not undefined. There must be something else on your page. A: The second this is in an anonymous function which has no context. this is always an implicit variable at the function level, so your inner functions this is shadowing the outer this
{ "language": "en", "url": "https://stackoverflow.com/questions/7518858", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: slightly complex linq for C# I asked a question before on retrieving the count of data server side and was provided a solution on the site. The suggestion was to use linq which worked perfectly however since i'm relatively new to it I need a little in depth help. Using John's solution: class Guy { public int age; public string name; public Guy( int age, string name ) { this.age = age; this.name = name; } } class Program { static void Main( string[] args ) { var GuyArray = new Guy[] { new Guy(22,"John"),new Guy(25,"John"),new Guy(27,"John"),new Guy(29,"John"),new Guy(12,"Jack"),new Guy(32,"Jack"),new Guy(52,"Jack"),new Guy(100,"Abe")}; var peeps = from f in GuyArray group f by f.name into g select new { name = g.Key, count = g.Count() }; foreach ( var record in peeps ) { Console.WriteLine( record.name + " : " + record.count ); } } } I can get the count of occurrences of John, Jake and Abe using the above as suggested by John. However what if the problem was a little more complicated for instance var GuyArray = new Guy[] { new Guy(22,"John", "happy"),new Guy(25,"John", "sad"),new Guy(27,"John", "ok"), new Guy(29,"John", "happy"),new Guy(12,"Jack", "happy"),new Guy(32,"Jack", "happy"), new Guy(52,"Jack", "happy"),new Guy(100,"Abe", "ok")}; The above code works great to retrieve the number of occurrences of the different names but what if I need the number of occurences of the names and also the number of occurrences of each person who is happy, sad or ok as well. ie output is : Name, count of names, count of names that are happy, count of names that are sad, count of names that are ok. If linq isn't the best solution for this, I am prepared to listen to all alternatives. Your help is much appreciated. A: Frankly, it's not clear if you want the total number of people that are happy, or the total number of people that are happy by name (also for sad, ok). I'll give you a solution that can give you both. var nameGroups = from guy in GuyArray group guy by guy.name into g select new { name = g.Key, count = g.Count(), happy = g.Count(x => x.status == "happy"), sad = g.Count(x => x.status == "sad"), ok = g.Count(x => x.status == "ok") }; Then: foreach(nameGroup in nameGroups) { Console.WriteLine("Name = {0}, Count = {1}, Happy count = {2}, Sad count = {3}, Okay count = {4}", nameGroup.name, nameGroup.count, nameGroup.happy, nameGroup.sad, nameGroup.ok); } If you want the total happy, sad, ok counts you can say: Console.WriteLine(nameGroups.Sum(nameGroup => nameGroup.happy)); etc. Additionally, you should make an enum public enum Mood { Happy, Sad, Okay } and then class Guy { public int Age { get; set; } public string Name { get; set; } public Mood Mood { get; set; } } so that you can instead write: var people = from guy in guyArray group guy by guy.Name into g select new { Name = g.Key, Count = g.Count(), HappyCount = g.Count(x => x.Mood == Mood.Happy), SadCount = g.Count(x => x.Mood == Mood.Sad), OkayCount = g.Count(x => x.Mood == Mood.Okay) }; A: To do so: class Guy { public int age; public string name; string mood; public Guy( int age, string name,string mood ) { this.age = age; this.name = name; this.mood = mood; } } class Program { static void Main( string[] args ) { var GuyArray = new Guy[] { new Guy(22,"John", "happy"),new Guy(25,"John", "sad"),new Guy(27,"John", "ok"), new Guy(29,"John", "happy"),new Guy(12,"Jack", "happy"),new Guy(32,"Jack", "happy"), new Guy(52,"Jack", "happy"),new Guy(100,"Abe", "ok")}; var peepsSad = from f in GuyArray where f.mood=="sad" group f by f.name into g select new { name = g.Key, count = g.Count() }; var peepsHappy = from f in GuyArray where f.mood=="happy" group f by f.name into g select new { name = g.Key, count = g.Count() }; var peepsOk = from f in GuyArray where f.mood=="ok" group f by f.name into g select new { name = g.Key, count = g.Count() }; foreach ( var record in peepsSad ) { Console.WriteLine( record.name + " : " + record.count ); } foreach ( var record in peepsHappy ) { Console.WriteLine( record.name + " : " + record.count ); } foreach ( var record in peepsOk ) { Console.WriteLine( record.name + " : " + record.count ); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to findByAll with a Domain hasMany member? I have: static hasMany = [ services:String, tags:String ] I need to search the database for services. This is the JSON for services "services":["tid.2","tid.3"] If services was a String (service) and not a hasMany String then tbis works def inUse = ServiceTemplate.findAllByName(serviceTemplateInstance.service).size() > 1 How can I do this with services? I've tried def c = ServiceTemplate.createCriteria() def results = c.list { eq('services', 'tid.2') } but no luck... A: You can use HQL instead. For example: ServiceTemplate.findAll("from ServiceTemplate st where :service in elements(st.services)", [service:'a'])
{ "language": "en", "url": "https://stackoverflow.com/questions/7518865", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Javascript value lost across scope This has been driving me mad for weeks.I have a variable data that I would like accessed at different parts of my program. Like such, var data = []; SomeNamespace.module.method(function(){ data.push(['some data']); }); // data is undefined here But, it seems to be lost, possibly something to do with scope. How can I get around this? Thanks in advance! A: That function is a callback, so data is not filled until that callback is ran. So this: var data = []; (function(){ data.push(['some data']); })(); data; // ['some data'] sets data, but: var data = []; var func = function() { data.push('values'); } data; // [] - empty array
{ "language": "en", "url": "https://stackoverflow.com/questions/7518872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: disable scrolling when selecting text in richTextBox (C#) I have a rich text box that contains (a lot of) text. I've added a search option for it, and when the user presses the search button, the program marks all the matches in yellow (by performing selectionBackColor on each selection) and then selects the first match. The result is that the program looks like it "scans" the text and then selects the first match. I don't want this to happen so I need to disable the autoscrolling (that occurs when performing Select()) for a specific code segment. I searched this problem before posting and the main topics I found involved appending text, and that's not my case. Any idea of how to solve my problem? I'm using .NET framework 4 (visual studio 2010) and I write in C#. Thanks in advance, Guy A: Well it seems that I'll answer my own question - all I had to do was to put these two lines among with the other class's properties: [DllImport("user32.dll", EntryPoint = "LockWindowUpdate", SetLastError = true, CharSet = CharSet.Auto)] private static extern IntPtr LockWindow(IntPtr Handle); and surround the desired code segment with this at the start: LockWindow(this.Handle); and this at the end: LockWindow(IntPtr.Zero);
{ "language": "en", "url": "https://stackoverflow.com/questions/7518876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to add indexes in mongoDB project with Morphia framework i'm working on a gwt project, that uses mongoDB as database, and morphia framework to work with mongodb. I already finished the basic dao of my classes and now i want to insert indexes in my classes to speedup the mongo searches. I looked the morphia documentation, and i saw that haves a @Indexed that makes this, but i don't know how to really use the index in a search. The morphia will automatically use the index? Does anyone have a good example of index in a real project ? (the hello world examples of mongodb site doesn't help to much) == EDIT == Is recommended insert index only in embed fields ? A: Mongodb will automatically use indexes so that isn't handled by morphia. You should index fields that you would commonly use for queries, for example: Post: { title : "My title", // indexed content : "My long long long long loooooong content" // Not indexed } In the simple post document shown above you see that the title field is indexed because a blog engine commonly searches over titles instead of contents plus the content will use a lot of your RAM so it might not fit in memory. That might no be the best example but it shows the main idea. I suggest you to read the indexes link.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you extend the Java Exception class with a custom exception that takes a String parameter? So I see you can extend the Exception class like so: public FooException(Exception e) { this.initCause(e); } But what if you want to pass not an exception to FooException's constructor - but a String: public FooException(String message) { // what do i do here? } What would the body of the Constructor look like in that case? A: Exception also has a String constructor. class FooException extends Exception { public FooException(String message) { super(message); } } A: Erm ... that's not how you extend an exception. Create your own subclass which already takes a string as the argument. A: To extend a class you should do something like this: public class FooException extends Exception { FooException(String message) { super(message); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Utf8ToString and older Delphi versions I want to use some units in both older and newer versions of Delphi. Since a recent Delphi version, Utf8Decode throws a deprecated warning which advises to switch to Utf8ToString. Problem is older versions of Delphi don't declare this function, so which {$IFDEF}label should I use to define a wrapper around Utf8Decode named Utf8String (or perhaps Utf8ToWideString)? Or in other words: which version was Utf8ToString introduced? A: I think I would implement it with an $IF so that calling code can use either the new RTL function, or fall back on the older deprecated version. Since the new UTF8ToString returns a UnicodeString I think it is safe to assume that it was introduced in Delphi 2009. {$IF not Declared(UTF8ToString)} function UTF8ToString(const s: UTF8String): WideString; begin Result := UTF8Decode(s); end; {$IFEND} A: As far as I remember: * *UTF8String and associated UTF8Encode / UTF8Decode were introduced in Delphi 6; *UTF8ToWideString and UTF8ToString were introduced in Delphi 2009 (i.e. Unicode version), as such: function UTF8Decode(const S: RawByteString): WideString; deprecated 'Use UTF8ToWideString or UTF8ToString'; In order to get rid of this compatibility issue, you can either define your own UTF8ToString function (as David propose), or either use your own implementation. I rewrote some (perhaps) faster version for our framework, which works also with Delphi 5 (I wanted to add UTF-8 support for some legacy Delphi 5 code, some 3,000,000 source code lines with third party components which stops easy upgrade - at least for the manager's decision). See all corresponding RawUTF8 type in SynCommons.pas: {$ifdef UNICODE} function UTF8DecodeToString(P: PUTF8Char; L: integer): string; begin result := UTF8DecodeToUnicodeString(P,L); end; {$else} function UTF8DecodeToString(P: PUTF8Char; L: integer): string; var Dest: RawUnicode; begin if GetACP=CODEPAGE_US then begin if (P=nil) or (L=0) then result := '' else begin SetLength(Dest,L); // faster than Windows API / Delphi RTL SetString(result,PAnsiChar(pointer(Dest)),UTF8ToWinPChar(pointer(Dest),P,L)); end; exit; end; result := ''; if (P=nil) or (L=0) then exit; SetLength(Dest,L*2); L := UTF8ToWideChar(pointer(Dest),P,L) shr 1; SetLength(result,WideCharToMultiByte(GetACP,0,pointer(Dest),L,nil,0,nil,nil)); WideCharToMultiByte(GetACP,0,pointer(Dest),L,pointer(result),length(result),nil,nil); end; {$endif}
{ "language": "en", "url": "https://stackoverflow.com/questions/7518885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dynamic Strings and Xml I'm new to Android (and surely I'm not an expert Java developer), so I'm sorry for the dumb question I would like to "capture" the id of a textView and to set its text value dynamically, here is how I'm trying to do this: public class AndStringTestActivity extends Activity { /** Called when the activity is first created. */ String abc = "abcabc"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TextView tv = (TextView)findViewById(R.id.test); tv.setText(abc); setContentView(R.layout.main); } } and here is the Xml from which i'm reading the id of the textview i would like to write inside // main.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:id="@+id/test" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> the error i receive is the usual Application stopped unexpectedly Thanks. A: Call setContentView before trying to find the TextView. The TextView does not exist before you have called setContentView (which will inflate your XML layout) A: Call setContentView(R.layout.main) before you call findViewById().
{ "language": "en", "url": "https://stackoverflow.com/questions/7518891", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android: Growing backstack problem, how to conserve memory? our app is designed using fragments and fragment transactions in a way where the user can keep going forward and "grow" our backstack indefinately. Now, besides the "dont design the app that way" answer, what options do I have to conserve memory. Eventually we run out and crash. Is there a way to onSaveInstanceState, save most of the state, release all the views (which hopefully releases memory associated with them), and then reload the views? Or is there a way to remove some transactions from the bottom of the stack? We are ok with loosing some of the user's backstack history if it comes from the bottom of the stack. Meaning: we would only keep the last 5 transactions in memory or something like that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518893", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SendMessage() doesn't work in one project I tried to use this Watermark it does work correctly on my test project, but it doesn't work in our main project. How can I debug this? I checked lastwin32error it returns a 0 which I guess is good. EDIT: It does work in the designer but when I run the project it doesn't. I created a connect bug report Link I'm still waiting for some response there... I uploaded there the project that makes the problem. If I could upload it here too I'll do it. EDIT: I found that if I set this 2 check boxes then it'll work... is there a way around it, I don't want to set the 'enable application framework' because it requires a form as the start-up form. A: The Windows cue banner, if it's what you're using, has some limitation and requirements. You cannot set a cue banner on a multiline edit control or on a rich edit control. To use this API, you must provide a manifest specifying Comclt32.dll version 6.0. See here for the official details: EM_SETCUEBANNER message EDIT: The Comctl32 issue means in .NET, you mist ensure there is a Application.EnableVisualStyles() line in your program start code, before Application.Run().
{ "language": "en", "url": "https://stackoverflow.com/questions/7518894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL query for SQL Server I have 3 tables students, class and grades. I need to make a query that will count how many specific grades are for specific class. And also calculate average grade for specific class where grade 1 is not included (grades are 1,2,3,4,5). Columns for the query should look like this: Class | Grade 1 | Grade 2 | Grade 3 | Grade 4 | Grade 5 | Average (except 1) I know how to get result for one specific grade: select C.ClassName, count(G.Grade) from Classes C, Grades G where G.ClassesID = C.ClassesID and G.Grade = 1 group by C.ClassName but how do I make a query to get all columns at once? A: If your SQL Server is new enough (2005 or newer), PIVOT can save you a lot of trouble here. SELECT ClassName, [1], [2], [3], [4], [5], ([1] + [2] + [3] + [4] + [5])/5 as [Average Count] FROM ( select C.ClassName, G.Grade from Classes C join Grades G on G.ClassesID = C.ClassesID ) AS source PIVOT ( count(G.Grade) FOR Grade IN ([1], [2], [3], [4], [5]) ) as pvt A: I would try SUBQUERY. If you use MSSQL you can try this: SELECT C.ClassName, --Grade 1 (SELECT COUNT(G1.Grade) FROM Classes C1, Grades G1 WHERE G1.ClassesID = C1.ClassesID and G1.Grade = 1 and C1.ClassName = C.ClassName), --Grade 2 (SELECT COUNT(G2.Grade) FROM Classes C2, Grades G2 WHERE G2.ClassesID = C2.ClassesID and G2.Grade = 2 and C2.ClassName = C.ClassName), -- Grade 3 (SELECT COUNT(G3.Grade) FROM Classes C3, Grades G3 WHERE G3.ClassesID = C3.ClassesID and G3.Grade = 3 and C3.ClassName = C.ClassName), --Grade 4 (SELECT COUNT(G4.Grade) FROM Classes C4, Grades G4 WHERE G4.ClassesID = C4.ClassesID and G4.Grade = 4 and C4.ClassName = C.ClassName), --Grade 5 (SELECT COUNT(G5.Grade) FROM Classes C5, Grades G5 WHERE G5.ClassesID = C5.ClassesID and G5.Grade = 5 and C5.ClassName = C.ClassName) -- Average (except 1) (SELECT SUM(GA.Grade) / COUNT(GA.Grade) FROM Classes CA, Grades GA WHERE GA.ClassesID = CA.ClassesID and GA.Grade NOT IN (1) and CA.ClassName = C.ClassName) FROM Classes C, Grades G WHERE G.ClassesID = C.ClassesID GROUP BY C.ClassName Aliases for the tables are not necessary. -- Means comment.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: select data from last 2 rows sql Im using an odbc-jdbc bridge in my project and I need select 2 pieces of data from the database and save the data to 2 variables on the java side of my application. Here is an example of my table. SITE_ID ------- DEV_ID ------- SCHEDULE_TIME ------- VALUE_ENUM ------- IDX --------------------------------------------------------------------------- 1 3000 09:30:00 1 1 1 3000 11:30:00 0 2 1 3000 12:00:00 1 3 1 3000 14:00:00 0 4 1 3000 18:30:00 1 5 1 3000 20:30:00 0 6 1 4000 05:00:00 1 1 1 4000 13:30:00 0 2 1 4000 16:30:00 1 3 1 4000 18:30:00 0 4 What I want to do is select SCHEDULE_TIME for the last 2 IDX's where DEV_ID is 3000, so I would like to save 18:30:00 and 20:30:00 in a variables, some examples of statements Ive tried are: select SCHEDULE_TIME from ARRAY_BAC_SCH_Schedule order by IDX desc limit 1 where DEV_ID = 3000 select SCHEDULE_TIME from ARRAY_BAC_SCH_Schedule order by IDX desc limit (1,1) where DEV_ID = 3000 SELECT TOP 1 SCHEDULE_TIME FROM ARRAY_BAC_SCH_Schedule WHERE DEV_ID = 3000 ORDER BY IDX DESC Right now Im just worrying about how to get the select statement to work in Query tool before I implement it in the java side. Thanks, Beef. A: Maybe I'm missing something. Is there a reason you wouldn't just run: select SCHEDULE_TIME from ARRAY_BAC_SCH_Schedule order by IDX desc limit 2 where DEV_ID = 3000 This should return 2 rows, containing 20:30:00 and 18:30:00. A: if it is mysql then select SCHEDULE_TIME from ARRAY_BAC_SCH_Schedule where DEV_ID = 3000 order by IDX desc limit 2 A: I think SELECT TOP 2 * from (select SCHEDULE_TIME FROM ARRAY_BAC_SCH_Schedule WHERE DEV_ID = 3000 ORDER BY IDX DESC) as inner A: The specifics will vary a little based on your DB, but your query should look something like this: SELECT TOP 2 SCHEDULE_TIME FROM ARRAY_BAC_SCH_Schedule WHERE DEV_ID = 3000 ORDER BY IDX Desc Or, on one line: SELECT TOP 2 SCHEDULE_TIME FROM ARRAY_BAC_SCH_Schedule WHERE DEV_ID = 3000 ORDER BY IDX Desc A: For SQL Server you should use SELECT TOP 2 SCHEDULE_TIME from (select SCHEDULE_TIME FROM ARRAY_BAC_SCH_Schedule WHERE DEV_ID = 3000 ORDER BY IDX DESC) as inner like Hemal told you. Be careful with queries like select TOP 2 SCHEDULE_TIME FROM ARRAY_BAC_SCH_Schedule WHERE DEV_ID = 3000 ORDER BY IDX DESC because that is wrong. SQL Server does the top and then the order. In PostgreSQL or MySQL you should use limit and the end of the query. The limit is after the where part. In Oracle you should use rownum inside the where part. A: You can do that with subquerys: select * from array_bac_sch_schedule where (value_enum,idx) in (select value_enum,idx from array_bac_sch_schedule where dev_id=3000) order by schedule_time desc limit 2; I took value_enum and idx as primary key.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518904", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generic Type XAML 2009 I have a litte problems with these class public class MyClass : MyGenericClass<String, Int32> { } // XAML Class public class MyGenericClass<T, U> : MyGenericClassBase<T, U> where U : class where T : class { public MyGenericClass() { InitializeComponent(); } } public class MyGenericClassBase<T, U> where U : class, new() where T : class, new() { T _t; U _u; public MyGenericClassBase() { } } I want to did the class "MyGenericClass" in XAML but I can't ! I try it : <MyGenericClassBase x:Class="MyGenericClass" x:TypeArguments="class,class" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > ... How can i pass the argument type at my "MyGenericClass" and the inherit class "MyGenericClassBase " Thanks a lot Nico A: XAML 2006: You can't use generic types in xaml 2006. The easiest solution is to use MyClass directly. Check out this question for other workarounds: Can I specify a generic type in XAML (pre .NET 4 Framework)? XAML 2009: Generic types are supported natively: <MyGenericClass x:TypeArguments="x:Int32, x:String"> ... </MyGenericClass>
{ "language": "en", "url": "https://stackoverflow.com/questions/7518911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: NSOutlineView outlineViewSelectionDidChange my NSOutlineView outlineViewSelectionDidChange method will not be called. I set set the NSOutlineViews delegate to the class where the other methods such as - (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item exist. But outlineViewSelectionDidChange will not be called on selecting an item. Does anybody has an idea? A: This notification is a bit odd, in that it is not automatically forwarded to delegates. Try adding an explicit registration to your initialization code, like this example: - (void)windowControllerDidLoadNib:(NSWindowController *)aController; { [super windowControllerDidLoadNib:aController]; NSNotificationCenter * center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(outlineViewSelectionDidChange:) name:@"NSOutlineViewSelectionDidChangeNotification" object:outlineView]; } A: Okay, meanwhile i figured out that the "NSOutlineViewSelectionDidChangeNotification" will be thrown only within the notification object. So i had to subclass my NSOutlineView to catch the notification and pass it to the object where i need it. A: Your own view needs to conform to the NSOutlineViewDelegate protocol like so.. @interface MyOutlineViewController : NSView <NSOutlineViewDataSource,NSOutlineViewDelegate> { IBOutlet NSOutlineView *myoutlineview; } @end you will have this methods in your implementation -(NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item; -(BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item; -(id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item; -(id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item; where you setup your outlineview. When loading this view -(void)viewDidLoad gets called and your predefined nib/xib file or your manual call will set your datasource to fill it depending on your logic. Now in your -(void)viewDidLoad your myoutlineview needs to set its own delegate with [myoutlineview setDelegate:self]; so your own View may know where to call its notification methods triggerd from selections and so on. So you can place your notification logic inside the same View class conforming to this protocol. -(void)outlineViewSelectionDidChange:(NSNotification *)notification { NSLog(@"selection did change"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to stop renamed .inc to .asp includes files to be browseable from the internet So, I have a ASP classic website. I had many includes files that were mostly static html, but still some script code. When they have a .inc extension Visual studio 2010 shows them as plain text. They do not show any syntax highlighting or intellisense. So I renamed them to .asp extensions. Now I've realized that the public and search bots can browse to those files and execute them directly. Is there a way to stop this without needing to rename the files back to *.inc? I don't want to name them back for several reasons. * *The syntax highlighting makes code so much more readable *I don't want to risk any issues with version control from renaming, which I've had in the past *I just plain don't want to have to change 100+ pages that reference the includes A: It's not entirely clear which way round you want the files to be named so I will try and cover both options. If they are .asp and they are showing the code, it means IIS is not executing the ASP properly, check your file handlers (let me know which IIS version you are using and i'll get you instructions). VS 2010 doesn't support classic ASP very well, the colouring is poor and there is no code completion. Use VS 2008 if you have it or you can get an Eclipse plugin, or I recently found Sublime Text that supports Classic ASP and does a much better job of colouring the text that VS2010 does (or there's good ol' Dreamweaver if you have money to burn). If all your files are .inc, you will need to tell IIS to execute *.inc with the ASP handler. This way if someone did browse to the files, they would be executed first and not show any asp code back to the browser (they'll probably error, but that's a different matter). Your IDEs won't recognise .inc as a Classic ASP extension, so you will have to add .inc as being VBScript to your IDE. Again, VS 2010 isn't great for Classic ASP, so when you've picked an IDE that is, let me know and I'll set some instructions on changing file associations within it.! File Associations: VS2010 Tools > Options > Text Editor > File Extension A: Use a different editor like Notepad++ that allows you to manually set the language encoding.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ios ASIFormDataRequest reporting invalid file from PHP upload Somebody please... #$%^ please take a look at this. days walking through the debugger, using setData with a jpeg representation. set file using ios4 asset library, trying a new PHP script, deleting the asiHTTPrequest files and making damn sure I have the new ones. Still nothing... Half the code has been put together from examples here or elsewhere on the web. The goal here, is to simply pick a photo from the camera roll, and upload it, seems pretty easy, I had a different PHP script that was working fine from the desktop and nabbed one from here because it's much more concise and it works from the desktop as well. so the override for finishing image picking - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType]; UIImage *originalImage, *editedImage, *imageToSave; // dealing with a still image if(CFStringCompare((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo){ editedImage = (UIImage *) [info objectForKey:UIImagePickerControllerEditedImage]; originalImage = (UIImage*) [info objectForKey:UIImagePickerControllerOriginalImage]; /* if(editedImage){ imageToSave = editedImage; } else { imageToSave = originalImage; } */ chosenImage.image = [info objectForKey:UIImagePickerControllerOriginalImage]; [[picker parentViewController] dismissModalViewControllerAnimated:YES]; //_imageData = [[NSData alloc] initWithData:UIImageJPEGRepresentation(originalImage, 0.0)]; //_imageData = [[NSData alloc] initWithData:UIImageJPEGRepresentation(chosenImage.image, 0.0)]; UIImage *im = [info objectForKey:@"UIImagePickerControllerOriginalImage"] ; UIGraphicsBeginImageContext(CGSizeMake(320,480)); [im drawInRect:CGRectMake(0, 0,320,480)]; _resizedImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); _imageData = [[NSData alloc] initWithData:UIImageJPEGRepresentation(_resizedImage, 0.0)]; } [picker release]; } then the upload method. -(void)uploadPhoto { //NSLog(@"image path inside uploadPhoto --> %@", _imagePath); NSLog(@"uploadPhoto"); //NSLog(@"%@", imageData); //_imageData = _imageData; NSString *unescapedURL = @"http://dev.xxxx.com/upload.php"; NSString * escapedURL = (NSString *)CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)unescapedURL, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 ); NSURL *url = [NSURL URLWithString:unescapedURL]; //NSURL *url = [NSURL URLWithString:unescapedURL]; ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; [request setDelegate:self]; [request setRequestMethod:@"POST"]; //[request setStringEncoding:NSUTF8StringEncoding]; //[request addPostValue:@"submit" forKey:@"Submit"]; //[request setPostValue:@"Submit" forKey:@"Submit"]; [request setData:_imageData withFileName:@"image4.jpg" andContentType:@"image/jpeg" forKey:@"photo"]; //[request setFile:_imagePath forKey:@"photo"]; //[request setFile:_imagePath withFileName:@"image5.png" andContentType:@"image/png" forKey:@"photo"]; [request setDidFailSelector:@selector(requestFailed:)]; [request setDidFinishSelector:@selector(requestFinished:)]; [request setTimeOutSeconds:500]; [request startAsynchronous]; NSError *error = nil; NSString *theString = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error]; if( theString ) { NSLog(@"Text=%@", theString); } else { NSLog(@"Error = %@", error); NSString *localized = [error localizedDescription]; NSString *localizedFail = [error localizedFailureReason] ? [error localizedFailureReason] : NSLocalizedString(@"not it", nil); NSLog(@"localized error--> %@", localized); NSLog(@"localizedFail--> %@", localizedFail); } [escapedURL release]; } then the finish/fail selectors -(void)requestFinished:(ASIFormDataRequest *)request { NSLog(@"requestFinished"); NSString *respondingString = [request responseString]; NSLog(@"response string--> %@", respondingString); NSData *responseData = [request responseData]; NSLog(@"%@", responseData); } -(void)requestFailed:(ASIFormDataRequest *)request { NSLog(@"requestFailed"); //NSError *error = [request error]; //NSLog(@"%@", [error description]); } Help! Drowning... A: It was a problem with the PHP. move_uploaded_file($_FILES["file"]["tmp_name"] was the issue. if you look at this [request setData:_imageData withFileName:@"image4.jpg" andContentType:@"image/jpeg" forKey:@"photo"]; It's changing the POST so the standard... move_uploaded_file($_FILES["file"]["tmp_name"] needs to be move_uploaded_file($_FILES["photo"]["tmp_name"] adding error_reporting(E_ALL); ini_set("display_errors", 1); print_r($_FILES); to the PHP allowed me to see.. response string--> Array ( [photo] => Array ( [name] => image4.jpg [type] => image/jpeg [tmp_name] => /tmp/phpCSXJgl [error] => 0 [size] => 150854 ) ) in the selector defined by... [request setDidFinishSelector:@selector(requestFinished:)]; What I'll do from here is revert the PHP to where it was before move_uploaded_file($_FILES["file"]["tmp_name"] and change the setFile call to [request setData:_imageData withFileName:@"image4.jpg" andContentType:@"image/jpeg" forKey:@"file"]; all will be well with the world and I'm going to get some food. cheers!
{ "language": "en", "url": "https://stackoverflow.com/questions/7518923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: JQuery Multiple Group Sort I need to sort a table of users alphabetically based upon a value in a td element. I can do basic sort fine but I have 3 tbodies per user and I need them all to stick together rather then just a single one of those tbodies being sorted. This is an example of my table: <tbody1> <tr><td>The Value To Base Sort On(username)</td></tr> <tr></tr> </tbody> <tbody2> <tr><td>some other stuff</td></tr> <tr></tr> </tbody> <tbody1> <tr><td>other stuff</td></tr> <tr></tr> </tbody> I need these 3 tbodies to remain linked next to each other when the table is sorted, however all 3 should be sorted based upon a value in the first tbody if that makes sense. A: Here is the jQuery plugin you are looking for: http://james.padolsey.com/javascript/sorting-elements-with-jquery/ $('#someId>li').sortElements( function(a, b){ return $(a).text() > $(b).text() ? 1 : -1; } );
{ "language": "en", "url": "https://stackoverflow.com/questions/7518925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Anyone tried using MySQL DataController to setup a Federated table with MSSQL Server? I found this: http://en.wikipedia.org/wiki/MySQL_DataController which lead me to this: https://launchpad.net/datacontroller It looks like a plug in to let you created federated tables in MySQL to connect to MSSQL Server, but the only example they give it with Oracle. It would be neat if this was possible, as it would solve a few problems for me. If anyone has any experience and can point me in the right direction, that would be awesome. A: The datacontroller plugin actually works with mssql. You simply use mssql:// instead of oracle
{ "language": "en", "url": "https://stackoverflow.com/questions/7518928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SSRS 2008: How to create parameter based on another parameter I know others have asked similar questions, but I have tried their solutions and it still is not working for me. I have one parameter called "Region" which uses the "region" dataset and another report parameter called "Office" which uses the "office" dataset. Now I want "Office" list of values to filter based on "Region" selection. Here is what I did so far. For the region dataset, it returns "regions_id" and "region_description". Then for "Region" report parameter, I selected "Text" datatype and allow Null values. This may be a mistake to select "text" since this is a uniqueidentifier value. For available values, I selected the region dataset and regions_id for value, region_description for label. I went to Advanced tab and selected "Always refresh". And on Default tab, I entered "(Null)", for when they want to see all regions. NExt, I created a report parameter called "regions_id2", allow null values, and I set available values = region dataset. For values and label both, I specified the regions_id. For default value, I again entered "(Null)". And I again selected "Always refresh". Finally, I added this "regions_id2" parameter to the "office" dataset. And then the office report parameter uses the "office" dataset with available values. Value field = "group_profile_id" and label field = "name_and_license". Default values = "(Null)". Advanced "Always refresh". And I ordered these report parameters in this same order: Regions, regions_id2, and Office. But now when I run this report I get no errors, however, the list of offices includes all of the offices regardless of what I choose for regions. Here is my T-SQL for these datasets: CREATE Procedure [dbo].[rpt_rd_Lookup_Regions] ( @IncludeAllOption bit = 0, ) As SET NOCOUNT ON If @IncludeAllOption = 1 BEGIN Select Distinct NULL AS [regions_id], '-All-' AS [region_description] UNION ALL SELECT Distinct [regions_id], [region_description] FROM [evolv_cs].[dbo].[regions] Where [region_description] not in ('NA','N/A') Order By [region_description] END Else BEGIN SELECT Distinct [regions_id], [region_description] FROM [evolv_cs].[dbo].[regions] Where [region_description] not in ('NA','N/A') Order By [region_description] END CREATE Procedure [dbo].[rpt_rd_Lookup_Facilities] ( @IncludeAllOption bit = 0, @regions_id uniqueidentifier = NULL ) As SET NOCOUNT ON If @IncludeAllOption = 1 BEGIN Select Null As [group_profile_id], Null As [profile_name], Null As [license_number], Null As [other_id], --Null As [Regions_id], '-All-' As [name_and_license] UNION ALL SELECT [group_profile_id], [profile_name], [license_number], [other_id], --[regions_id], [profile_name] + ' (' + LTRIM(RTRIM([license_number])) + ')' As [name_and_license] FROM [evolv_cs].[dbo].[facility_view] With (NoLock) Where [is_active] = 1 and (@regions_id is NULL or @regions_id = [regions_id]) Order By [profile_name] END Else BEGIN SELECT [group_profile_id], [profile_name], [license_number], [other_id], [regions_id], [profile_name] + ' (' + LTRIM(RTRIM([license_number])) + ')' As [name_and_license] FROM [evolv_cs].[dbo].[facility_view] With (NoLock) Where [is_active] = 1 and (@regions_id is NULL or @regions_id = [regions_id]) Order By [profile_name] END What could I possibly be doing wrong? A: I fixed this by selecting the region parameter value from region dataset for the office dataset
{ "language": "en", "url": "https://stackoverflow.com/questions/7518929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: setting scalar value on collection using introspection I am doing something like the answer on: Set object property using reflection Dynamically setting the value of a object property. I have a function wrapping this sort of functionality and it works great. However, I want to make it so that it looks at the property type to see if it is some sort of collection and add the value/object to the collection. I tried to do something like: if (object is ICollection) The problem is that VS2010 wants me to type the collection which I dont know how to do programatically. So what I want to do is something like the following given subject is the target object and value is value to be set: public void setPropertyOnObject(object subject, string Name, object value) { var property = subject.GetType().GetProperty(Name) // -- if property is collection ?? var collection = property.GetValue(subject, null); collection.add(value) // -- if propert is not a collection property.SetValue(subject, value, null); } A: You can dynamically check a typed collection (and add an item to it) thusly: using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Object subject = new HasList(); Object value = "Woop"; PropertyInfo property = subject.GetType().GetProperty("MyList", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public); var genericType = typeof (ICollection<>).MakeGenericType(new[] {value.GetType()}); if (genericType.IsAssignableFrom(property.PropertyType)) genericType.GetMethod("Add").Invoke(property.GetValue(subject, null), new[] { value }); } } internal class HasList { public List<String> MyList { get; private set; } public HasList() { MyList = new List<string>(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7518931", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Applet and JSF Integration - example Is there a tutorial or a simple applet example with JSF? How do I perform a request to a Managed Bean from an applet? A: Don't use a JSF managed bean. It is not suitable for this job. Use a servlet or a webservice. To exchange data, use the session scope with an unique autogenerated key which you pass as parameter to the applet beforehand. This way the data will be available to JSF as well. A: JSF (and hence managed beans) executes on the server to produce HTML; An applet executes on the client's machine - so you can't just pass a reference to a managed bean to an applet. If you just need to pass a value from a managed bean to an Applet at start time, you can use the <param> sub-element of the tag to pass this value. If you need some kind of dynamic access to the managed bean, it's going to be a lot harder - basically, you'll need to build some kind of web service that's backed by the managed bean so that the applet can make http requests back to the server to get the values it needs.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518933", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: delete the from the textarea? I am trying to do a line break after the message "Original message", I have tried with this but It keeps showing me the ---Original message---<br /> message <textarea id="txtMessage" rows="10" cols="50"><?php echo nl2br(str_replace('<br/>', " ","---Original message---\n".$array['message']));?></textarea> I want something likes this: ---Original message--- message any advise? A: This should do what you want it to: <?php echo str_replace('<br />', " ","---Original message---\n".$array['message']);?> nl2br — Inserts HTML line breaks before all newlines in a string (from php.net) Example: echo "<textarea>HI! \nThis is some String, \nit works fine</textarea>"; Result: But if you try this: echo nl2br("<textarea>HI! \nThis is some String, \nit works fine</textarea>"); you will get this: Therefore you should not use nl2br before saving it to database, otherwise you have to get rid of <br /> every time you try to edit text! Just use it when you print it out as text. A: echo nl2br(str_replace('<br/>', " ", ... )); should be echo str_replace('<br />', ' ', ... ); A: The php function "nl2br" takes newlines, and converts them into br tags. If you don't want that, you should probably remove it :). Heh, beaten by Ryan. A: You're trying to replace <br/>, but the original text has <br /> (note the space). A: You are removing the HTML breaks, then adding them back! Look at your code: nl2br(str_replace('<br/>', " ","---Original message---\n".$array['message'])) First, str_replace replaces '<br/>' with a space. Then, nl2br adds a <br> for every newline (\n) it finds. Remove nl2br call and it's done. A: If you want to do nl2br on all of the text except for what's inside the textarea you could do this: function clean_textarea_of_br($data) { return str_replace(array("<br>", "<br/>", "<br />"), "", $data[0]); } $message = preg_replace_callback('#<textarea[^>]*>(.*?)</textarea>#is',clean_textarea_of_br,$message);
{ "language": "en", "url": "https://stackoverflow.com/questions/7518944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: want to use Xcode 4 for everything, how to add folder in project navigator? I'd like to move my web dev editing to Xcode 4 (currently using textmate). I have a couple of simple questions that are clearly a lack of experience on my end. * *In Xcode's Project Navigator, how do I add a folder to the shown directory tree? Currently, I add via terminal and do File -> Add Files Is there any way to tell Xcode to see the file system as the file system and not as references? a less likely thing: * *Is there any way to bring up a console within the context of a folder in project navigator (would like to be able to run grep again small portion or something)? thx A: I can answer the first question. Adding a folder of files to a project is the same as adding individual files. Choose File > Add Files in Xcode. When you add a folder of files to a project, you should see something like the following screenshot: Create groups if you need to access the files in Xcode, such as adding a folder of source code files. Create folder references if you don't need to access the files in Xcode, such as adding a folder of audio files. You can also add folders to the project navigator by selecting a file or folder in the project navigator, right-clicking, and choosing New Group. A: As far as I know, Xcode won't mirror the filesystem as an Xcode tree (anyone correct me id I'm wrong). Wanting to have an identical structure is quite some work. I use to first place the files hierarchically in the file-system, then I mimic the same structure in Xcode. This requires some attention since Xcode 4.1 not always writes new classes to the place you told him to - they may prefer to land in the highest level of the Xcode project. I had similar thoughts and started a thread, might be helpful for further reading Your second question: sorry, can't help you there.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Regular Expression in Splunk I need regular expression which will provide me error msg in following format: [2011-09-21 17:53:24:446 GMT][75DABF9052639D387C4E2F8EF7DC516C.http-8080-18] [com.abc.resolver.rest.CommComponent] ERROR Cannot get payload while processing error message [2011-09-21 17:53:24:446 GMT][75DABF9052639D387C4E2F8EF7DC516C.http-8080-18][com.pqr.chktest.Client] ERROR Error connecting to http://beta.com/api/1 with response code: 401 [2011-09-21 17:53:24:446 GMT][75DABF9052639D387C4E2F8EF7DC516C.http-8080-18][com.pqr.chktest.Client] ERROR upload error: java.lang.Exception: Error connecting to beta server at http address http://beta.com Cannot get payload while processing Error connecting to http://beta.com/api/1 with upload error: Error connecting to Basically, I want to get only first 5 words after word "ERROR" (in capital letter) "ERROR (?[^[]+)" is returning me the whole words. But I'm not able to get it working for just first 5 words. Also, if the first 5 words after ERROR contains java.lang.Exception, I don;t want to include it in my result, instead I need the next matching words. Any help is much appreciated. Thanks! A: Try the regular expression "ERROR(\s+[^\s]+){5}" to get five words after "ERROR". For the second part (exclude java.lang.Exception) I would not do it in a single regex but test the first match and if it includes these words start another search on the string, now like "java.lang.Exception:(\s+[^\s]+){5}"
{ "language": "en", "url": "https://stackoverflow.com/questions/7518947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Share a paragraph (or part of a text) on facebook I just saw a new feature for sharing a part of text on facebook. c.f. http://www.metrolyrics.com/someone-like-you-lyrics-adele.html This should be done by javascript and probably with aid of jQuery. Is there a developed plugin for this purpose? What is the pathway to develop this idea? A: You can use the Facebook Javascript SDK to call the feed dialog. You put the text you want, in their case the lyrics, in the caption and description properties of the feed dialog.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518949", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I compare two generic types in C++? I need to determine whether an element is the same as the one I'm passing by reference. In the function Belongs I need to compare equality between d is and an element of a stored in a dynamic list: struct Nodo{ Dominio dominio; Rando rango; Nodo* next; }; typedef Nodo* ptrNodo; ptrNodo pri; template<class Dominio, class Rango> bool DicListas<Dominio,Rango>::Belongs(const Dominio &d) { bool retorno = false; if(!EsVacia()) { ptrNodo aux=pri; while(aux!=NULL) { if(aux->dominio==d)//-------> THIS CLASS DOESN'T KNOW HOW TO COMPARE THE TYPE DOMINIO. { retorno = aux->isDef; } aux = aux->sig; } } return retorno; } A: Whatever type argument you provide for the type parameter Dominio, you've to overload operator== for that type. Suppose, you write this: DicListas<A,B> obj; obj.Belongs(A()); then you've to overload operator== for the type A as: class A { public: bool operator == (const A &a) const { //compare this and a.. and return true or false } }; Also note that it should be public if it's a member function, and better make it const function as well, so that you can compare const objects of type A. Instead of making it member function, you can make operator== a non-member function as well: bool operator == (const A &left, const A & right) { //compare left and right.. and return true or false } I would prefer the latter. A: It reduces to defining an overload of operator== for the user-defined type: bool operator==(const WhateverType &a, const WhateverType &b) { return whatever; } or maybe as a member of WhateverType. A: If you want to compare something about two, possibly distinct, types, you probably want to look at either Boost type traits or the versions of type traits that made it into TR1 and C++11 (if you're using a compiler that supports either TR1 or C++11). However, that doesn't seem to be the case that you're running into. In your case, you know that the two objects are of the same type. In C++, you will get compiler errors if a class you pass as a type parameter to a template does not support all the methods or operators that the template needs. That's what you're running into. That's also the problem that concepts are meant to solve (well, concepts are meant to advertise "if you want to use your type with this template, then your type must support ..."). But, unfortunately we didn't get concepts in C++11, so the requirements are implicit. In your case, as already mentioned, you simply need to make sure that whatever class you pass in as Dominio supports operator==. You may also want to look at Boost concept check to advertise that whatever type is passed in as Dominio must support operator==.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518954", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Virtualizing Stack Panel Returning Null Selected Item I was using a stack panel to display listbox items, but when I decided to change it to a virtualizing one the selected item was null sometimes. Here is part of the DataTemplate I was using to invoke the selected item command: <i:Interaction.Triggers> <ei:DataTrigger Binding="{Binding IsSelected}" Value="True"> <i:InvokeCommandAction CommandParameter="{Binding}" Command="{Binding DataContext.SelectItemCommand, RelativeSource={RelativeSource AncestorType={x:Type ListBox}, Mode=FindAncestor}}" /> </ei:DataTrigger> </i:Interaction.Triggers> Here is the ListBox: <ListBox x:Name="_itemsListBox" Grid.Row="1" ScrollViewer.CanContentScroll="true" ItemsSource="{Binding Items}" IsSynchronizedWithCurrentItem="True" SelectionMode="Single" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemTemplate="{StaticResource ListItemTemplate}"> <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}"> <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" /> </Style> </ListBox.ItemContainerStyle> </ListBox> If I turn off virtualization, this issue doesn't happen. How can I prevent it from returning a null item? A: Maybe you can define a FallBackValue inside your Binding, to get back the FallBackValue instead of null. A: My best guess would be that your selected item is null when it is out of view in the listbox. It makes sense I guess because of the virtualization though it is an odd one. Your solution is likely to be that when your selected item changes you make sure you bring it in to view. Take a look at this question to sort that out. Good luck & HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/7518956", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to fire Java method using bash Suppose I launch a Java application: java -cp whatever.jar com.example.Start Process launches ok and keeps running with PID 1314. Now I would like the system to fire a method by users request. How can I use bash to signal the running PID and have it fire a method? A: My thought is to have bash echo data to the Java processes via a named pipe, which I'm pretty sure Java has support for. A: To communicate with a Java process, you would normally use RMI from another process (this could be in the same JAR) However, if you want a pure bash/unix utilities solution, you could have the application listen on a port for commands and send back responses. This means you could use plain telnet to send commands and get output. One example of this is to use a http server with wget or you could have a simple socket based solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL QUERY - Time comparison (SQLite) I would like to ask if someone would be able to help with sql query. I have table with times in format: HH:MM:SS. I want to write a query that returns me the closest time (to the future) to the current time. For example: Table contains 3 rows: 12:00:00, 12:01:00, 12:02:00. If: 1) Current time is: 12:00:30. The query returns: 12:01:00., etc. BUT! 2) Current time is: 12:02:30. The query returns: 12:00:00. I write this query, whitch solves me 1), but not 2). select time(myColumn) from myTable where time(myColumn) >= time(current_timestamp, 'localtime') order by myColumn limit 1 I would appreciate if someone could help. PS: Database is in SQLite (must be) and is not possible to calculate with dates eg: 2011-01-01 12:00:00...) Thank you Tom. A: You could do this: select min( time(yourtimecolumn) ) from foo where time(current_timestamp, 'localtime') < time(yourtimecolumn) Edited by Tom A: EDIT: if you need to get the NEXT closest time, try: SELECT time(myColumn) FROM myTable ORDER BY CASE WHEN myColumn - time(current_timestamp, 'localtime') > 0, THEN myColumn - time(current_timestamp, 'localtime') ELSE myColumn - time(current_timestamp, '24 hours', 'localtime') END CASE LIMIT 1 It sorts by the amount of time to the next timestamp in the database, attempting to add 24 hours if necessary to get a positive number (an upcoming time) as a result. A: I solved it! This is the query: select case when (select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') < time(myColumn)) is null then (select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') > time(myColumn)) else (select min(time(myColumn)) from myTable where time(current_timestamp, 'localtime') < time(myColumn)) end Thx Tim & Dave who showed me the way.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery hero slider logic, not(:first) isn't working for me I have the following function: $('#btn-homeheroleft').click( function() { if ( $('#homehero-btns a.on:not(:first)')) { $('#homehero-btns a.on').prev('a').trigger('click'); } else { //$('#homehero-btns a.on').prev('a').trigger('click'); $('#homehero-btns a').last('a').trigger('click'); } //return false; }); It works fine to rotate the hero banner until it gets to the first one, in which it should return to the last looping around, however it never makes it to the else, and always evaluate true on the if for some reason. I've executed $('#homehero-btns a').last('a').trigger('click') in the console and it works just fine there. UPDATE: Here was the solution to my issue if anyone is interested, thank you everyone for your help. $('#btn-homeheroleft').click( function(e) { if ( $('#homehero-btns a:first').hasClass('on') ) { $('#homehero-btns a:last').trigger('click'); } else { $('#homehero-btns a.on').prev('a').trigger('click'); } e.preventDefault(); }); $('#btn-homeheroright').click( function(e) { if ($('#homehero-btns a:last').hasClass('on')) { $('#homehero-btns a:first').trigger('click'); } else { $('#homehero-btns a.on').next('a').trigger('click'); } e.preventDefault(); }); } A: As you asked about the hero slider logic, I will address the structure and method part, ignoring your current code (might work, but could be better.) For the case, where the rotation have to unlimited. You can use a very simple trick. Each time you rotate it to the next image (or slide, with whatever content)..you want to move the last image to the front and vice versa. I once made a very simple slider rotator to some question over here. This is a very good example on how easy it is to make the rotator dynamic: http://jsfiddle.net/PmXr2/1/ You can use that code however you want. A: try adding .length to ur selector $('#btn-homeheroleft').click( function() { if ( $('#homehero-btns a.on:not(:first)').length) { $('#homehero-btns a.on').prev('a').trigger('click'); } else { //$('#homehero-btns a.on').prev('a').trigger('click'); $('#homehero-btns a').last('a').trigger('click'); } //return false; });
{ "language": "en", "url": "https://stackoverflow.com/questions/7518963", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: jQuery: how to get position of mouse relative to the top/left corner of an element taking into account scrollbars I'm doing some work with the canvas element and need to track the mouse around highlighting parts of it. I would like to be able get the position relative to the elements top left, 0 , 0. I have this - using jQuery: ... var pos = $(this).position(); var left = e.clientX - position.left; var top = e.clientY - position.top; ... First is there an jQuery api that will do the above for me and secondly it fails miserably when the window has been scrolled up/down as the canvas is a lot bigger than the actual browser window so is there an api that takes that into account also. TIA. A: You should, depending on the browser, use offsetX/offsetY or layerX/layerY attributes of the Event Object to track the mouse relative to the element which you've bound the mousemove event to. I made this small plugin which normalizes the above values and adds mouseX and mouseY to the Event Object. (function($){ var org = $.event, _super = { fix: org.fix }; $.extend($.event, { fix: function(event) { var self = _super.fix.apply(this, [event]); // Normalize offsetY/X and layerX/Y self.mouseX = (self.offsetX || self.layerX); self.mouseY = (self.offsetY || self.layerY); return self; } }); })(jQuery); See test case on jsFiddle A: managed to kinda fix it, after a fashion: var left = 0; var top = 0; if(e.offsetX) { left = e.offsetX; top = e.offsetY; } else { var offset = $(element).offset(); left = e.layerX - offset.left; top = e.layerY - offset.top; } moz needs the offset taken into account. Although i'm sure there must be a "proper" jquery api that hides this detail from me. Also There's something "funny" going on with jsfiddle that the above example works ok - it didn't in a browser. Of course I may just be speaking nonsense.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: JQuery Loupe Tool with Image Protextion I work for a company that wants to use a loupe tool on larger images on our website, but also wants to incorporate some image protection (realizing that no amount of work will stop someone from snagging the image). I came across two really great opensource scripts that do these individually, but don't want to work together. Image Loupe Script: http://jdbartlett.com/loupe/ Image Protect Script: http://davidwalsh.name/image-protector-plugin-for-jquery The loupe tool works by linking a larger image to a smaller 'thumbnail' and modifying the CSS via javascript to create a 'zoom' effect inside of a square. The image protect tool works by overlaying a blank .gif on top of an image via absolute positioning. My question is, is there any way to incorporate the two? I'm scratching my head because I don't think with this loupe tool it is possible to overlay at .gif and still allow for interactivity with the Loupe tool. Any help would be greatly appreciated! A: I'd just use the loupe js and make the directory (containing the large image) inaccessible to all but the host. As for the image protect script you've linked, I wouldn't bother with it. All it took was a quick resize of the browser window to obtain the file. FAIL! A: As an update, I ended up using a combination of two other methods to basically deter most people from taking the image (again, I know it's impossible to completely inhibit people). The first thing that I did was disallow dragging on the webpages by using: <body ondragstart="return false"> Then, I used a snipped of javascript to disallow right-clicking on images: $('img').bind("contextmenu",function(){ return false; }); This is a simple fix, and will probably prevent a vast percentage of people from stealing my precious images! :-)
{ "language": "en", "url": "https://stackoverflow.com/questions/7518968", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using bundler, how do you unpack a gem installed via a git repository? How can I unpack a gem specified in bundler by a :git => url? My Gemfile has gem 'my_gem', :git => 'git@github.com:xxxxx/xxxxx.git' $ bundle correctly reports the gem as available, and my code works. $ bundle which my_gem even tells me where my gem is stored. However: $ gem unpack my_gem ERROR: Gem 'my_gem' not installed nor fetchable. $ bundle exec gem unpack my_gem ERROR: Gem 'my_gem' not installed nor fetchable. Is it possible to unpack a gem installed like this? A: Why the need to unpack it? You already have the sourcecode. The point of specifying a git repository is that you don't have a bundled gem, but the source to generate it. Simply use git clone git://github.com/xxxx/yyy.git and the source will be in the yyy folder of the current directory. A: Also, you can open any gem in your Gemfile using: bundle open my_gem A: Not exactly answering the question but supposing you had the gem file to hand, it's a bunch of gzip files tarred up (opposite to the usual) $ tar xzf mygem.gem $ ls mygem.gem checksums.yaml.gz data.tar.gz metadata.gz metaddata.gz is the gemspec, and data.tar.gz is all the files (lib/my/stuff.rb etc).
{ "language": "en", "url": "https://stackoverflow.com/questions/7518970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Applet and JSF Integration - example Can we implement javascript into applet/swing?If yes how? please give some basic/small example. A: You can't "implement" it as in manipulating its components, you can however use JavaScript to dynamically change the <param> tags of the <applet> element, and define the applet to respond to that.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518974", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I test performance of my .NET application and optimize it? I have been developing an application that runs on a client computer and extracts data from a central SQL Server server. Before the application was quite fast and running good. As a little data grew in size up to some thousands of records now the program is being too slow on client computers. How do I check the performance of my .NET application? A: I am planning to check the performance of my .net app Get a profiler. It will tell you where your app is spending a majority of its time so that you can find the bottlenecks. These are the areas to focus on to improve your performance. I have been developing an application that runs in client computer and extracts data from central SQL Server. Before the application was quite fast and running good. As few data grew in size upto some thousands of records now the program is being too slow in client computers. Sounds like a database problem (indexing, select n + 1, select fetches instead of join fetches, etc.). The profiler will tell you if your app is spending too much time waiting for the database to return results. If that is where the bottleneck is, work on that. Work on indexing your tables appropriately, and optimizing your queries (are you pulling back more columns than you need, do you have select n + 1 problem, etc.) The salient point is this is: don't guess. Don't waste your time optimizing loops that aren't performance bottlenecks, etc. You're are observing performance that is consistent with the database being a bottleneck. Get a tool that will confirm that guess for you. Use that tool to focus your efforts.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518983", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ActiveMQ, why not use BytesMessage with properties? using ActiveMQ I want to serialize my objects with protocol buffers (*). Then I have an byte array. Now I read that ByteMessage should not be used with properties: http://activemq.apache.org/nms/msdoc/1.5.0/vs2005/html/T_Apache_NMS_IBytesMessage.htm (They have the same text in the java documentation, too) Where is the problem, and when will the problems occur? (*) We use this format internally, if possible I want to use is as message body, too. A: There shouldn't be any problem with using message properties in BytesMessage object with ActiveMQ. The NMS docs just have some similar warnings as the JMS spec as its meant to be generic per provider so in other providers this might not be the case but should work without any issue in ActiveMQ.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518984", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get correctly content and avoid breaking html tags using strip_tags with substr? In my page I have some post previews from RSS feeds. Every post preview shows about 300 characters. When a user clicks on expanding button, then the #post-preview is replaced with the #post. The #post shows the rest of the post. Everything fine with this but the format of the #post is not good, not readable. So I thought of allowing <br><b><p> tags, it will make it ok to be read. Because I don't want the user to be distracted, I want the tags to be allowed after the 300 chars. With the following method, it is possible to break some tags where the $start ends and $rest starts. This means no good readable output. $start = strip_tags(substr($entry->description, 0, 300)); $rest = strip_tags(substr($entry->description, 300), '<b><p><br>'); $start . $rest; My question is how can I keep $start and $rest the same (no tags) until the 300 char, and after that $rest will show the formatted post? Are there any other ways of doing this? Here is an example of a RSS feed structure (from view page source). <item><guid isPermaLink="false"></guid><pubDate></pubDate><atom:updated></atom:updated><category domain=""></category><title></title><description></description><link></link><author></author></item> I am looking for a way that does not kill performance. A: Something like: $start = substr($entry->description, 0, 300); if(($pos = stripos($start, "<")) !== false) { $start = strip_tags(substr($start, 0, $pos)); $rest = substr($entry->description, $pos); } else { $start = strip_tags($start); $rest = substr($entry->description, 300); } Ok, it's just a concept. Gets first 300 chars and checks for broken tag. If broken cut before it and get $rest from this point. If not broken just strip and get rest. There is at least 1 problem: * *you never now the length of the $start(after strip_tags could be nothing left), could use loop with length checking but eeee... efficiency EDIT Ok, get it: $start = ""; $chars = 400; while(strlen($start) < 300) { $start = strip_tags(substr($rss, 0, $chars)); $chars += 50; } $pos = stripos($rss, substr($start, strlen($start) - 50)); $rest = substr($rss, $pos+50); Ok, little nasty and there are some cases on which it fails(with repetable text probably:D), tested on Ideone
{ "language": "en", "url": "https://stackoverflow.com/questions/7518985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle Trigger Subquery problem CREATE OR REPLACE TRIGGER "DISC_CLIENT" BEFORE INSERT ON "PURCHASE" FOR EACH ROW DECLARE checkclient PURCHASE.CLIENTNO%TYPE; BEGIN SELECT Clientno INTO checkclient FROM PURCHASE GROUP BY ClientNo HAVING SUM(Amount)=(SELECT MAX(SUM(Amount)) FROM PURCHASE GROUP BY Clientno); IF :new.ClientNo = checkclient new.Amount := (:old.Amount * 0.90); END IF; END; / Seem to be having a problem with this trigger. I know there I cant use the WHEN() clause for subqueries so im hoping this would work but it doesnt! Ideas anyone? :/ Basically im trying to get this trigger to apply a discount to the amount value before inserting if the client matches the top client! : ) A: There's a non-pretty but easy way round this, create a view and update that. You can then explicitly state all the columns in your trigger and put them in the table. You'd also be much better off creating a 1 row 2 column table, max_amount and then inserting the maximum amount and clientno into that each time. You should also really have a discounted amount column in the purchase table, as you ought to know who you've given discounts to. The amount charged is then amount - discount. This get's around both the mutating table and being unable to update :new.amount as well as making your queries much, much faster. As it stands you don't actually apply a discount if the current transaction is the highest, only if the client has placed the previous highest, so I've written it like that. create or replace view purchase_view as select * from purchase; CREATE OR REPLACE TRIGGER TR_PURCHASE_INSERT BEFORE INSERT ON PURCHASE_VIEW FOR EACH ROW DECLARE checkclient max_amount.clientno%type; checkamount max_amount.amount%type; discount purchase.discount%type; BEGIN SELECT clientno, amount INTO checkclient, checkamount FROM max_amount; IF :new.clientno = checkclient then discount := 0.1 * :new.amount; ELSIF :new.amount > checkamount then update max_amount set clientno = :new.clientno , maxamount = :new.amount ; END IF; -- Don-t specify columns so it breaks if you change -- the table and not the trigger insert into purchase values ( :new.clientno , :new.amount , discount , :new.other_column ); END TR_PURCHASE_INSERT; / A: As I remember a trigger can't select from a table it's fired for. Otherwise you'll get ORA-04091: table XXXX is mutating, trigger/function may not see it. Tom advises us not to put too much logic into triggers. And if I understand your query, it should be like this: SELECT Clientno INTO checkclient FROM PURCHASE GROUP BY ClientNo HAVING SUM(Amount)=(select max (sum_amount) from (SELECT SUM(Amount) as sum_amount FROM PURCHASE GROUP BY Clientno)); This way it will return the client who spent the most money. But I think it's better to do it this way: select ClientNo from ( select ClientNo, sum (Amount) as sum_amount from PURCHASE group by ClientNo) order by sum_amount where rownum
{ "language": "en", "url": "https://stackoverflow.com/questions/7518988", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to rewrite SQL query that has subquery with joins I have a SQL query that has a subquery that has joins. I would like to rewrite the query without the subquery so that I can create a view. MySQL does not allow SELECT statements where the FROM is a subquery. Is this possible? I've tried removing the outer select and moving the group by inside the subs query. This partially works but some of the data is incorrect. select * from (SELECT r.id, r.dateAdded, r.listingId, r.rating, r.username, r.valid, tbl_data.nameShort, tbl_data.desk, d.model, d.hardware, d.serial, l.appVersion, r.photoUrl, r.comment FROM tbl_ratings r JOIN tbl_data on r.listingId = vi_data.id JOIN tbl_devices d on r.serial = d.serial JOIN tbl_log l on l.serial = d.serial ORDER BY d.serial, l.dateAdded DESC) x group by id order by dateAdded DESC Thanks in advance! A: Is it as simple as: SELECT r.id, r.dateAdded, r.listingId, r.rating, r.username, r.valid, tbl_data.nameShort, tbl_data.desk, d.model, d.hardware, d.serial, l.appVersion, r.photoUrl, r.comment FROM tbl_ratings r JOIN tbl_data on r.listingId = vi_data.id JOIN tbl_devices d on r.serial = d.serial JOIN tbl_log l on l.serial = d.serial GROUP BY r.id ORDER BY r.dateAdded DESC Also, you have a reference to "vi_data" that isn't anywhere else in the query A: Change your group by clause to be group by r.id. Since you're selecting from a derived table (the subquery), the db can't tell that there's only one "id" field in that derived table - it only sees the column headers as specified in the subquery, which is r.id.
{ "language": "en", "url": "https://stackoverflow.com/questions/7518997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: C# how can I run cygwin scp and put in password using Process and StandardInputWriter? With this code I see the login window prompting for a password but I can't seem to write the password to the shell window. Process scp = new Process(); scp.StartInfo.FileName = @"c:\cygwin\bin\scp"; scp.StartInfo.Arguments = "/cygdrive/c" + path + " " + username + "@" + ServerName + ":/cygdrive/c/Temp/."; scp.StartInfo.UseShellExecute = false; scp.StartInfo.RedirectStandardOutput = true; scp.StartInfo.RedirectStandardError = true; scp.StartInfo.RedirectStandardInput = true; scp.Start(); //I've tried this with no success: using (StreamWriter sw = scp.StandardInput) { if (sw.BaseStream.CanWrite) { sw.WriteLine(pass); } } // Another failed attempt: scp.StandardInput.Write(pass + Environment.NewLine); scp.StandardInput.Flush(); Thread.Sleep(1000); I know I can get this to work with cygwin expect but would rather use c# to interact with the windows input / output. A: Try this: [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr hWnd); Process scp = new Process(); scp.StartInfo.FileName = @"c:\cygwin\bin\scp"; scp.StartInfo.Arguments = "/cygdrive/c" + path + " " + username + "@" + ServerName + ":/cygdrive/c/Temp/."; scp.StartInfo.UseShellExecute = false; scp.StartInfo.RedirectStandardOutput = true; scp.StartInfo.RedirectStandardError = true; scp.StartInfo.RedirectStandardInput = true; scp.Start(); Process[] p = Process.GetProcessesByName("cmd"); SetForegroundWindow(p[0].MainWindowHandle); SendKeys.SendWait(pass); scp.WaitForExit(); EDIT: Be sure to include \n at the end of pass. A: this code works fine as expected and with no need to call Flush or Sleep: Process p = new Process(); ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.UseShellExecute = false; p.StartInfo = info; p.Start(); using (StreamWriter sw = p.StandardInput) { if (sw.BaseStream.CanWrite) { sw.WriteLine("dir"); } } are you 100% sure that your cygwin is just waiting for the pwd?
{ "language": "en", "url": "https://stackoverflow.com/questions/7519001", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mvc3 Problem passing data from View to Controller I am using mvcContrib to generate a grid to allow users to filter data by keying in search data. There are several partial views that are rendered in my Index View: Here is the partial view that handles the searching: @model CRMNPS.Models.PagedViewModel<CRMNPS.Models.NPSProcessed> @using (Html.BeginForm("Index", "Home", FormMethod.Get)) { <label> Model Number:&nbsp;&nbsp; @Html.TextBox("searchWord" ) <br /><br />From Date:&nbsp;&nbsp;&nbsp; @Html.EditorFor(m => m.FromDate) </label> <label> <Br /><br />To Date:&nbsp;&nbsp;&nbsp; @Html.EditorFor(m => m.ToDate) </label> <label> <br /><br />&nbsp;&nbsp;<input class="button" value="Search" type="submit" /> <br /> </label> } Here is my Index view: @model PagedViewModel <CRMNPS.Models.NPSProcessed> @{ ViewBag.Title = "CRM Processed List"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Processed List</h2> @{Html.RenderPartial("SearchBox");} @{Html.RenderPartial("Pager", Model.PagedList);} @Html.Grid(Model.PagedList).AutoGenerateColumns().Columns(column =>{ column.For(x => Html.ActionQueryLink(x.ModelNumber, "Edit", new { id = x.Id })).Named("Id").InsertAt(1); }).Sort(Model.GridSortOptions).Attributes(@class => "grid-style") @using (Html.BeginForm("Index", "Home", FormMethod.Post, new { FromDate = Model.FromDate, ToDate = Model.ToDate, SearchWord = Model.SearchWord })) { <p> <input class="button" value="Export to Excel" type="submit" /> </p> } At the bottom of the Index View I have another submit within the Html.BeginForm with a Formmethod.Post. The Index ActionResult that calls this view passes a viewmodel with the search criteria and a IQueryable object that the mvcContrib uses. When the user presses the Export to Excel push button I would like to pass the selected values back to the Index actionresult HttpPost controller. (FromDate, ToDate and SearchWord) The FromDate, ToDate and SearchWord values always come back null. I am fairly new to MVC so any constructive comments are welcome. Thanks Joe A: Since they are not in the form that you are posting - (Export to Excel is in a separate form). The inputs FromDate, ToDate and SearchWord Are in the first form (in the partial view). So those values don't show up in the controller (since they are not part of the http post). If you want to see all these values being passed back to the controller, they should be under one Html.BeginForm A: One way is to put'em all in the same form as MoXplod suggested or you can use some javascript to send search values as query string by hooking the submit event of second form like $('#excel-form').live('click', function(){ var action = this.action; var searchString = $('#SearchWord').val(); var toDateString = $('#ToDate').val(); var fromDateString = $('#FromDate').val(); if(action.indexOf('?')<0) { action = action+"?SearchWord="+searchString; } else { action = action+"&SearchWord="+searchString; } action = action + "&ToDate="+toDateString + "&FromDate=" + fromDateString; $(this).attr('action', action); return true; }); it will put these values in querystring and make them available in action method. Alternatively, you can use ajax to post these values to controller rather than full regular post back.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519004", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: reading text file lines into asp.net contentplaceholder I am new to ASP.Net and am trying to set up some content pages to work with my master page. I currently have the following text hardcoded into an asp:contentplaceholder and it works just fine. I want to read lines in from a text file to produce those headlines and retain the current formatting. I tried using the tag i need each line as a separate tag. Below is the code in the content place holder. Id like to have this done in the Page_Load or the pre Init. <p class="text1">--- We recently completed an evaluation for a large Ocean Tug fleet showing 70% particulate reduction, 11% NOx reduction and an 8% fuel economy improvement.</p> <p class="text1">--- Our Product was added to the Grainger catalog as its primary emissions and fuel efficiency Catalyst.</p> <p class="text1">--- Our Product is recommended by Mann-Hummel to promote better performance in Diesel Particulate Filters.</p> A: The IO.File.ReadAllLines() method will read a text file and return to you an array of strings; one for each line of text. You can then loop through that, building up the HTML string to place into the ContentPlaceHolder A: Try the following: Dim Lines() As String = IO.File.ReadAllLines(Path) For Each f As String In Lines Response.Write("<p class='text1'>" & f & "</p>") Next Edit: I noticed you want it inside a ContentPlaceHolder, therefore can't use Response.Write. If that's the case you can try using a Literal control and then append the previous code using LiteralName.Text &= f Hopefully it helps! Edit: Adding more code, supporting what @Brian M. has said: Dim Content As String = String.Empty Dim Lines() As String = IO.File.ReadAllLines(Path) For Each TxtFromFile As String In Lines Content &= "<p class='text1'>" & TxtFromFile & "<p>" Next Me.ContentPlaceHolder1.Controls.Add(New LiteralControl(Content)) I hope it helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519016", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: self.view.backgroundColor = [UIColor greenColor]; does not work in pushed view I want to draw something in drawRect of pushed view. Also, I want to change back ground color of view. I can change background color by self.view.backgroundColor = [UIColor greenColor]; in viewDidLoad, if view is main view. I used that in viewDidLoad of pushed view controller, but it is still black. MyViewController *myViewController = [MyViewController alloc]init]; [self.navigationContoller pushViewController:myViewContoller animated:YES]; // I want to change background color of this view. [myViewController release]; A: Setting the myViewController's background color before pushing it should work. myViewController.view.backgroundColor = [UIColor greenColor]; // push myViewController. Or you can go to the viewWillAppear of that view and set the backgroundColor there. A: In Apple Swift, We can use: self.view.backgroundColor = UIColor(red: 0, green: 1, blue: 0, alpha: 1) Background will change to Green A: You actually should customize your view in viewDidLoad of your pushed view. Thats what it is made for.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: MATLAB Parallel Computing Toolbox - Parallelization vs GPU? I'm working with someone who has some MATLAB code that they want to be sped up. They are currently trying to convert all of this code into CUDA to get it to run on a CPU. I think it would be faster to use MATLAB's parallel computing toolbox to speed this up, and run it on a cluster that has MATLAB's Distributed Computing Toolbox, allowing me to run this across several different worker nodes. Now, as part of the parallel computing toolbox, you can use things like GPUArray. However, I'm confused as to how this would work. Are using things like parfor (parallelization) and gpuarray (gpu programming) compatible with each other? Can I use both? Can something be split across different worker nodes (parallelization) while also making use of whatever GPUs are available on each worker? They think its still worth exploring the time it takes to convert all of your matlab code to cuda code to run on a machine with multiple GPUs...but I think the right approach would be to use the features already built into MATLAB. Any help, advice, direction would be really appreciated! Thanks! A: If you are mainly interested in simulations, GPU processing is the perfect choice. However, if you want to analyse (big) data, go with Parallization. The reason for this is, that GPU processing is only faster than cpu processing if you don't have to copy data back and forth. In case of a simulation, you can generate most of the data on the GPU and only need to copy the result back. If you try to work with bigger data on the GPU you will very often run into out of memory problems. Parallization is great if you have big data structures and more than 2 cores in your computer CPU. A: When you use parfor, you are effectively dividing your for loop into tasks, with one task per loop iteration, and splitting up those tasks to be computed in parallel by several workers where each worker can be thought of as a MATLAB session without an interactive GUI. You configure your cluster to run a specified number of workers on each node of the cluster (generally, you would choose to run a number of workers equal to the number of available processor cores on that node). On the other hand, gpuarray indicates to MATLAB that you want to make a matrix available for processing by the GPU. Underneath the hood, MATLAB is marshalling the data from main memory to the graphics board's internal memory. Certain MATLAB functions (there's a list of them in the documentation) can operate on gpuarrays and the computation happens on the GPU. The key differences between the two techniques are that parfor computations happen on the CPUs of nodes of the cluster with direct access to main memory. CPU cores typically have a high clock rate, but there are typically fewer of them in a CPU cluster than there are GPU cores. Individually, GPU cores are slower than a typical CPU core and their use requires that data be transferred from main memory to video memory and back again, but there are many more of them in a cluster. As far as I know, hybrid approaches are supposed to be possible, in which you have a cluster of PCs and each PC has one or more Nvidia Tesla boards and you use both parfor loops and gpuarrays. However, I haven't had occasion to try this yet. A: If you write it in CUDA it is guaranteed to run in parallel at the chip-level versus going with MATLAB's best guess for a non-parallel architecture and your best effort to get it to run in parallel. Kind of like drinking fresh mountain water run-off versus buying filtered water. Go with the purist solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519019", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Issue displaying pdf on android using html tag I am trying to display a PDF to a web page using the html [object] tag. This works fine on all the web browsers on PC's as well as iPhone/iPad. But when I load the same page on an Android it asks me if I want to download the file which is the backup when the PDF isn't displayed. Does anyone know why this wouldn't work or another html control I could use rather than forcefully calling the local PDF program on the phone. Below is how my html is rendered. <object data="../myFile.pdf" type="application/pdf" width="100%" height="100%"> <p>Missing PDF plugin for this browser.<a href="../myFile.pdf">Click here to download the PDF file.</a></p> </object> I have also seen examples on stackoverflow suggesting the below code but I am unsure of how to leverage it on my site and was hoping there was a possible html fix. WebView webview = new WebView(this); setContentView(webview); webview.getSettings().setJavaScriptEnabled(true); webview.loadUrl("URL/Demo_PDF.pdf"); The phone I am using is a Thunderbolt. Thanks for the help. A: Does anyone know why this wouldn't work Because that is not supported on Android. or another html control I could use rather than forcefully calling the local PDF program on the phone. There may not even be a "local PDF program on the phone". Many phones ship with one, many users install one, but there is no guarantee. But, beyond that, there is no way to display PDFs natively inline in the stock Android browser. A third party one might support it (e.g., Firefox). Converting the PDF to a Flash animation might work with the stock Android browser, though that will only work on Android 2.2 and higher. but I am unsure of how to leverage it on my site You wouldn't. That is Java code, for an Android application.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519023", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Does f(int) in base class inherited in derived derived class D which have f(double)? Possible Duplicate: Why does an overridden function in the derived class hide other overloads of the base class? Does f(int) in base class inherited in derived derived class D? if yes then why overloading is not working here. and if no then why f(int) is not inherited as class d is publicly derived. I am confused. class B { public: int f(int i) { cout << "f(int): "; return i+1; } // ... }; class D : public B { public: double f(double d) { cout << "f(double): "; return d+1.3; } // ... }; int main() { D* pd = new D; cout << pd->f(2) << '\n'; cout << pd->f(2.3) << '\n'; } A: This is the Classical example for Function Hiding. The overload resolution in C++ does not work across classes, A function in derived class Hides all the functions with identical name in the Base class. Compiler only sees the function in derived class for an derived class object. You can Unhide all the base class functions for your derived class by using the using Declaration. in your derive class. Adding, using B::f; in your derived class will enable your derived class object to access all the functions with the name f() int the Base class as if they were overloaded functions in Derived class. This should be a good read: What's the meaning of, Warning: Derived::f(char) hides Base::f(double)? A: I think if you give a derived class a function with the same name as functions existing in a base class, the derived class' function will hide the base class' functions. If you merely wanted to overload, use the using keyword. class B { public: int f(int i) { cout << "f(int): "; return i+1; } // ... }; class D : public B { public: using B::f; //brings in all of B's "f" functions //making them equals of D's "f" functions. double f(double d) { cout << "f(double): "; return d+1.3; } // ... }; int main() { D* pd = new D; cout << pd->f(2) << '\n'; cout << pd->f(2.3) << '\n'; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7519028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: iOS: How to obtain ZipKit without using Mercurial? I installed Mercurial, but true to its name it is failing to run when I try to download ZipKit. I get this message: abort: couldn't find mercurial libraries in .... /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python26.zip /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6 /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-old /System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload /Library/Python/2.6/site-packages /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/PyObjC /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/wx-2.8-mac-unicode] (check your install and PYTHONPATH) A: Turns out that Mercurial can only be run from the account under which it was installed, at least on OS/X. Therefore I merely had to switch bad to my main account and fetch zipkit.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling another script file in MATLAB I am having a problem with calling another script from within a script. I run a script "a.m" and it uses a function detailed in another script "b.m", and within "b.m" there is an if clause which is supposed to rerun "a.m" given a certain condition is fulfilled. However, when trying to write this if clause and calling "a.m", i get this error: Undefined variable "a" or class "a.m". % My "if" clause in b.m looks like this: if numel(xyz) == 0 a.m; end Why am I getting this error, considering it's "a.m" that I initially run? A: The syntax is wrong. You call it as a not a.m.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make this simple 301 redirect in .htaccess? I've looked to some already asked questions, but wasn't able to solve it. How do I make a simple 301 redirect FROM: www.mydomain.cz/something/somethingelse/ TO www.mydomain.cz/sometext I've came up with this, but it didn't work and I don't really know the difference between RedirectMatch and RewriteRule, could anyone tell? Thanks. RewriteEngine on RewriteBase / RedirectMatch 301 something/somethingelse(/)?$ sometext I get an "Internal Server Error" when using this. A: nice easy one.. Redirect 301 /oldfolder/oldfile.html http://www.domain.com/Content/newfile.html http://www.techieshelp.com/how-to-redirect-a-web-page/
{ "language": "en", "url": "https://stackoverflow.com/questions/7519034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how does this game load its modules? This game uses ig.module('impact.font').requires('impact.image') for impact/font.js but when i see source code via Google Developer Tools i dont see <script> for impact/font.js (in http://playbiolab.com page) Why? how do they load them? A: All the code is in biolab.js. The 'modules' aren't external files (at least not by the time the code is delivered to the browser). A: The variables are defined at http://playbiolab.com/biolab.js. Instead of starting with the developer tools, you can also view the source of the page, then search for <script (without closing >). If you cannot understand the code, because it's packed, use http://jsbeautifier.org.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519036", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Real-time keyboard input to console (in Windows)? I have a doubly-linked list class, where I want to add characters to the list as the user types them, or removes the last node in the list each time the user presses backspace, whilst displaying the results in console in real-time. What functions would I use to intercept individual keyboard input, and display it in real-time to the console? So the following results: User starts typing: Typ_ User stops typing: Typing this on screen_ User presses backspace 5 times: Typing this on s_ Particular OS is windows (vista, more specifically). As a side-note GetAsyncKeyState under windows.h appears to perhaps be for keyboard input, however the issue of real-time display of the console remains. A: C++ has no notion of a "keyboard". It only has an opaque FILE called "stdin" from which you can read. However, the content of that "file" is populated by your environment, specifically by your terminal. Most terminals buffer the input line before sending it to the attached process, so you never get to see the existence of backspaces. What you really need is to take control of the terminal directly. This is a very platform-dependent procedure, and you have to specify your platform if you like specific advice. On Linux, try ncurses or termios. A: You will be surprised, but this code will do what you want: /* getchar example : typewriter */ #include <stdio.h> int main () { char c; puts ("Enter text. Include a dot ('.') in a sentence to exit:"); do { c=getchar(); putchar (c); } while (c != '.'); return 0; } A: You could use ReadConsoleInput, adding incoming caracters to your list, look for the backspace keys (INPUT_RECORD->KEY_EVENT_RECORD.wVirtualScanCode == VK_BACKSPACE) and removing the last caracter from your list for all of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: close pop-up window using shdocvw? I used to close pop-up windows in VBA using the following code: Dim k As New shdocvw.ShellWindows ' close menu window Dim c As WebBrowser For Each c In k If c.LocationURL = "http://specificsite.com/x.html" Then c.Quit() Next You can see I have to check if the pop-up was opened and then close it. I've migrated to VB.NET e2010 and it doesn't work. I've found how to handle events and use the NewWindow to cancel the opening of the pop-up. Unfortunately by cancelling instead of closing after it was opened, it causes a script error by JavaScript on the main page. How can this be solved? A: I was working on similar kind of project that i used shdocvw you can find it here You could also find this one helpful this is using c# but you can convert it into VB Click Here
{ "language": "en", "url": "https://stackoverflow.com/questions/7519043", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to dynamically use TG_TABLE_NAME in PostgreSQL 8.2? I am trying to write a trigger function in PostgreSQL 8.2 that will dynamically use TG_TABLE_NAME to generate and execute a SQL statement. I can find all kinds of examples for later versions of PostgreSQL, but I am stuck on 8.2 because of some requirements. Here is my function as it stands which works, but is hardly dynamic: CREATE OR REPLACE FUNCTION cdc_TABLENAME_function() RETURNS trigger AS $cdc_function$ DECLARE op cdc_operation_enum; BEGIN op = TG_OP; IF (TG_WHEN = 'BEFORE') THEN IF (TG_OP = 'UPDATE') THEN op = 'UPDATE_BEFORE'; END IF; INSERT INTO cdc_test VALUES (DEFAULT,DEFAULT,op,DEFAULT,DEFAULT,OLD.*); ELSE IF (TG_OP = 'UPDATE') THEN op = 'UPDATE_AFTER'; END IF; INSERT INTO cdc_test VALUES (DEFAULT,DEFAULT,op,DEFAULT,DEFAULT,NEW.*); END IF; IF (TG_OP = 'DELETE') THEN RETURN OLD; ELSE RETURN NEW; END IF; END; The way this is currently written, I would have to write a separate trigger function for every table. I would like to use TG_TABLE_NAME to dynamically build my INSERT statement and just prefix it with 'cdc_' since all of the tables follow the same naming convention. Then I can have every trigger for every table call just one function. A: I was looking for the exact same thing a couple of years back. One trigger function to rule them all! I asked on usenet lists, tried various approaches, to no avail. The consensus on the matter was this could not be done. A shortcoming of PostgreSQL 8.3 or older. Since PostgreSQL 8.4 you can just: EXECUTE 'INSERT INTO ' || TG_RELID::regclass::text || ' SELECT ($1).*' USING NEW; With pg 8.2 you have a problem: * *cannot dynamically access columns of NEW / OLD. You need to know column names at the time of writing the trigger function. *NEW / OLD are not visible inside EXECUTE. *EXECUTE .. USING not born yet. There is a trick, however. Every table name in the system can serve as composite type of the same name. Therefore you can create a function that takes NEW / OLD as parameter and execute that. You can dynamically create and destroy that function on every trigger event: Trigger function: CREATE OR REPLACE FUNCTION trg_cdc() RETURNS trigger AS $func$ DECLARE op text := TG_OP || '_' || TG_WHEN; tbl text := quote_ident(TG_TABLE_SCHEMA) || '.' || quote_ident(TG_TABLE_NAME); cdc_tbl text := quote_ident(TG_TABLE_SCHEMA) || '.' || quote_ident('cdc_' || TG_TABLE_NAME); BEGIN EXECUTE 'CREATE FUNCTION f_cdc(n ' || tbl || ', op text) RETURNS void AS $x$ BEGIN INSERT INTO ' || cdc_tbl || ' SELECT op, (n).*; END $x$ LANGUAGE plpgsql'; CASE TG_OP WHEN 'INSERT', 'UPDATE' THEN PERFORM f_cdc(NEW, op); WHEN 'DELETE' THEN PERFORM f_cdc(OLD, op); ELSE RAISE EXCEPTION 'Unknown TG_OP: "%". Should not occur!', TG_OP; END CASE; EXECUTE 'DROP FUNCTION f_cdc(' || tbl || ', text)'; IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF; END $func$ LANGUAGE plpgsql; Trigger: CREATE TRIGGER cdc BEFORE INSERT OR UPDATE OR DELETE ON my_tbl FOR EACH ROW EXECUTE PROCEDURE trg_cdc(); Table names have to be treated like user input. Use quote_ident() to defend against SQL injection. However, this way you create and drop a function for every single trigger event. Quite an overhead, I would not go for that. You will have to vacuum some catalog tables a lot. Middle ground PostgreSQL supports function overloading. Therefore, one function per table of the same base name (but different parameter type) can coexist. You could take the middle ground and dramatically reduce the noise by creating f_cdc(..) once per table at the same time you create the trigger. That's one tiny function per table. You have to observe changes of table definitions, but tables shouldn't change that often. Remove CREATE and DROP FUNCTION from the trigger function, arriving at a small, fast and elegant trigger. I could see myself doing that in pg 8.2. Except that I cannot see myself doing anything in pg 8.2 anymore. It has reached end of life in December 2011. Maybe you can upgrade somehow after all. A: I also asked a similar question a couple of years ago. Have a look at that question and see if it gives you any useful ideas: Inserting NEW.* from a generic trigger using EXECUTE in PL/pgsql
{ "language": "en", "url": "https://stackoverflow.com/questions/7519044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to leave TODOs for yourself as part of Xcode4? The one thing i like about Eclipse is that it lets one leave annotations like //TODO:, which IDE highlights and draws your attention to. Is there anything like this available for Xcode? Ultimately, i'd like to mark things as to be completed without fear of forgetting to revisit this code later. Searching for this is fine, but i can't help but think there has got to be something better. Please let me know. A: // FIXME: foo // TODO: bar Works the same. In addition, these show up in the drop-down list of method names, so you can see and jump right to the areas that need more work.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519045", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can you determine if a radio button was set checked=true by 3rd party JavaScript? Setting a radio button to checked=true programatically doesn't fire a change event. How can I know if a radio button was checked by a script? See this example: http://jsfiddle.net/wykEx/7/ In Firebug, no change events are logged to the console unless you manually click on the radio buttons. A: One way to do it would be to set up a timer and poll for changes. Of course it may not be the most elegant solution but it should be good enough and should work in all browsers. The biggest caveat with doing it this way is that you may loose some transitions if code changes the checked attribute of your input element too often. window.setInterval(function(){ var elem = $('twoRadioBtn'); if(elem.checked != elem.lastchecked) { console.log('TWO changed!'); elem.lastchecked = elem.checked; } }, 100); // poll every 100 ms.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WSDL generated in WCF consumed by Delphi client I have a WCF (.net 3.5) service that implements security through ws-security. I have generated a WSDL file for consumption by a client created in Delhi v7.0. I have been having a number of issues with the SOAP message that is received from the Delhi client: 1) The SOAP message is different from the SOAP message generated by a .NET web form using the same WSDL file. for eg. SOAP message sent by Delhi client doesn't contain <Header> element 2) The <Body> element is missing from the SOAP message. etc. In summary the integration has not been smooth. I see this as some incompatibility issue. I want to understand how to resolve such issues. What precautions should be taken so that any client using the same WSDL can send SOAP message which is similar to the SOAP message sent by .NET client. A: You can inject the tags by using a stringreplace on the XML string right before it goes out the door "onto the wire". You need a RIO_BeforeExecute handler, and you can then deal with the SOAPRequest directly.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can you Interupt a function from a GUI callback without adding an interupt-check to the function? (MATLAB) So, I've a GUI that basically allows the user to iteratively process data. Thus, there is a start/stop button and a display that shows the current state of the data. When you click the start button, the callback function calls the data processing function shown below: function result = process_data(data) result = 0; for big_loop=big_start:big_end for small_loop=small_start:small_end result = result+data; %in reality just some fancier matrix ops end end My problem is how to implement the stop button's callback so that it returns from process_data after the current iteration of the small loop. Right now I do this by modifying the process_data code to be as follows: function result = process_data_new(data) result = 0; for big_loop=big_start:big_end for small_loop=small_start:small_end result = result+data; %in reality just some fancier matrix ops %new code start ----------------- if interrupt_flag return; end %new code end -------------------- end end However, I really want the interruption to be handled from the GUI's end so my code isn't littered with interrupt checks (My real code would involve this kind of thing very often, and the user would sometimes need to change the process_data function). Is this possible? I imagine it would involve making all of the looping variables 'observable' properties, and then waiting for small_loop to change, but I can't figure out details of how to go about implementing the callback. A: may be this helps: have a button 'stop', in its callback, set a flag to true. in the smaller loop (i.e. the other callback which busy in a loop), it will check this flag at the top (or bottom) of its (small) loop. If the flag is set true, it makes it false right away and terminate the overall loop and returns. (add a check in your loop to check if this flag is set) So, the most the user has to wait after hitting STOP is for one smaller iteration to complete if the hit happened just after the last check. callbacks interrupt each others, so the above works. The flag is set in userData buffer and read from there by the other callback each time. This snippets code from one example I have the small loop example function status= output(t,x,~,data) %called by ode45 after each step. Plot the current %pendulum position for simulation userData = get(data.handles.figure1, 'UserData'); if userData.stop status=true; g_status =true; else status = false; .... do real work end end the 'run' button callback % --- Executes on button press in run_btn. function run_btn_Callback(hObject, eventdata, handles) % hObject handle to run_btn (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) [data,status] = parse_input(handles); if not(status) return; end ..... userData.stop = false; set(handles.figure1, 'UserData',userData); ... stop button callback % --- Executes on button press in reset_tag. function reset_tag_Callback(hObject, eventdata, handles) % hObject handle to reset_tag (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) data = get(handles.figure1, 'UserData'); data.stop = true; set(handles.figure1, 'UserData',data); ..... A: If you have the parallel computing toolbox, then you can create a Task. Otherwise, I don't think it's possible without adding the control flow you suggest since there's no other way of creating a processing thread and stopping it from your UI. A: what you basically want is to kill the process_data once the user presses the 'stop' button. Unfortunately, this is not possible because there are no real threads in matlab. Therefore, your only solution is the one you've implemented yourself.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519049", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Separating body I have hundreds of divs, each of which have their own style properties in it. Just a few minutes ago, I discovered that I have to change a lot of things just to change some background of the page. I want the background of the body, starting from 0px to 200px, to have a black background, the background of the body from 200px to 500px to have a gray background and from 500px to 700px to have a black background again. Finally, 700px to ...px should have a white background. To be precise, body { background-color:#ADADAD; } makes all of the page, including the bottom of the page (which I wanted to be white) gray. Is there anyway to separate the body px to px? A: As Daniel pointed out, the best approach (as I'm sure you're trying to avoid having to add even more divs, is by creating a picture 1px in height and 700px in width. Use the following style to implement your image on your background: body{background: url(your-image-here.jpg) repeat-y;} This will repeat your image vertically, recreating your color seperation without having to create more divs. EDIT: as you mentionned, depending on the category, you could implement a unique class on your body tag in your css file. In this case, for each different categories, you could have a different image to load. Since the image is very small in size (a few kB at the most), it wouldn't be very heavy on the server or the users to download images for each category. (this is better than trying to stretch your images to fit your needed dimensions).
{ "language": "en", "url": "https://stackoverflow.com/questions/7519055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Joda - remove seconds, milliseconds from PeriodFormat.getDefault().print()? I have a method like this: public static String getFormattedDateDifference(DateTime startDate, DateTime endDate) { Period p = new Period(startDate, endDate); return PeriodFormat.getDefault().print(p); } I'd like to chop off the seconds and milliseconds from printing. How can I do that? A: If you only want it down to minutes, why not just specify the right period type to start with? private static final PeriodType PERIOD_TO_MINUTES = PeriodType.standard().withSecondsRemoved().withMillisRemoved(); public static String getFormattedDateDifference(DateTime startDate, DateTime endDate) { Period p = new Period(startDate, endDate, PERIOD_TO_MINUTES); return PeriodFormat.getDefault().print(p); } I expect that to format in the way you want. Note that if these are really meant to be dates, you should probably use PeriodType.yearMonthDay() and specify the values as LocalDate. DateTime should be used for date and time values, not just dates.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How can I display a lot of app icons on a desktop in a UI friendly way? Imagine I have 100 icons, 200 icons... It is kind of the same problem Apple addressed with the dock How can I best display them and are there any existing tools/libraries for doing so?
{ "language": "en", "url": "https://stackoverflow.com/questions/7519059", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Multiple NSURLConnection Problem This is my code: - (void)saveData:(NSString *)url withName:(NSString *)name{ NSString *URLString=[NSString stringWithFormat:@"http://www.google.com/reader/atom/%@?n=%d&xt=user/-/state/com.google/read", url, 50 ]; NSLog(@"------>In attesa di %@",URLString); NSURL *requestURL = [NSURL URLWithString:URLString]; NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init]; [theRequest setHTTPMethod:@"GET"]; [theRequest setTimeoutInterval:30.0]; //[theRequest addValue:[NSString stringWithFormat:@"GoogleLogin auth=%@", auth] forHTTPHeaderField:@"Authorization"]; [theRequest setURL:requestURL]; [self.oauthAuthentication authorizeRequest:theRequest]; OrignalNSURLConnection *conn = [[OrignalNSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:NO]; conn.originalURL=name; conn.stato=@"store"; [conn start]; NSLog(@"-------------------------- connection: %@", conn); self.web = conn; [conn release]; //NSLog(@"########## get response: %d", [response statusCode]); [theRequest release]; } -(void) storeData{ for(SubscriptionArray *element in subscriptions){ [self saveData:element.htmlUrl withName:element.title]; } } If I call storeData only the 1st was written correctly for the others connection I received 0 data maybe because I do a lot of request... How can stop storeData cycle until the data will received? (in the didFinishLoading method)? thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/7519060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Add bindings after calling ko.applyBindings In KnockoutJS, is there any way to add bindings after calling ko.applyBindings? A: Turns out the answer to my question is the same as this one: Can you call ko.applyBindings to bind a partial view? ko.applyBindings accepts a second parameter, limiting the scope of binding to a specific element within the DOM. So as long as we know where the new bindings are located in the DOM, we can apply them separately afterwards.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519061", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Cropping a QRegion for setMask I am setMask()'ing a QRegion I've a Big QRect of that I am making a Circle //config->rectangle = QRect(0,0 275x275) QRegion circleRegion(config->rectangle, QRegion::Ellipse) and now I've a small widgetRect QRect(43,0 93x110) that area I need to crop from the previous region and use for setMasking. What I am doing circleRegion.intersected(widgetRect) which is not giving me the proper result. I am expecting a Pie Region. Where am I missing ?
{ "language": "en", "url": "https://stackoverflow.com/questions/7519069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Write an Intent to an NFC tag? Is it possible to write an intent object to an NFC tag? For example, if I could write the following intent to an NFC tag: String phoneNumber = "5555555555"; Uri uri = Uri.parse("sms:" + phoneNumber); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.putExtra("address", phoneNumber); intent.setType("vnd.android-dir/mms-sms"); String intentAsUri = intent.toUri(0); // = #Intent;action=android.intent.action.VIEW;type=vnd.android-dir/mms-sms;S.address=5555555555;end then I could write the output uri as a url data to an NFC tag. When a user taps my tag, android interprets as the above intent, and launches an sms messenger? It doesn't seem to work, and I don't know that there's a way to serialize an intent object itself onto an NFC tag (or that android would know to interpret one) Thanks A: You can write a special URL to invoke SMS app: sms:+tel_no. There are some issues with adding a body text: see here. A: There are multiple types of 'NDEF' defined - most are under the type 'U' URI actions, including subtype 0 (no action) which will allow you to fill the space with whatever and act accordingly in your app. However there is also type 'T' for text actions (but have to work with international codepages as a result). http://members.nfc-forum.org/specs/spec_list/ as a starting point, but you probably already know this.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Web Development - Entirely "scalable" website without flash, possible? I'm an aspirant web developer, and I've been wondering if it's possible to make fully "scalable" websites without using flash. Maybe a JQuery plugin that scales every object inside the body according to the body itself, so if its width is 100% of the window everything inside it gets scaled according. Personally, I think this is needed because both resolution and pixel density of displays are getting discrepant, you can't assume a specific resolution and a median is very bad for the extremes, which are an enormous part of the users. And the in-browser scaling is not a good solution. My idea is to make everything super-dimensioned, e.g.: an image that displays at 50x50px in a XGA screen, displays at 100x100px in a QXGA screen, and the image itself could be a 120x120px JPEG. Of course it's not possible to apply fancy effects for resizing like bicubic interpolation, possibly only nearest neighbor, but it's better than using a magnifying glass :). IMHO, There should be a CSS unit that is a percentage of the browser window, for example, wx and wy, so the property fontsize:0.3wx; will always scale the font to 0.3% of the window x size. Nowadays pixel density ranges from <100 to >200ppi, not counting the different resolutions. A site that has a fixed width developed for XGA screens gets horrible in a high resolution screen, specially if there's no fancy background. Monitors are becoming bigger and with higher ppi, and there are also portable devices that has low resolution. Of course this was not necessary when you only had to support SVGA and XGA resolutions, but that was the last millennium, nowadays the resolutions ranges from WVGA(tablets) to WQXGA(modern monitors/macs), for smartphones and pocket devices i think it's okay to make a separate template, but not for tablets, notebooks, low-end desktops, high-end desktops. So if anyone knows how to do something like this, please lemme know! Otherwise I think it's impossible to avoid flash, more and more portable devices are supporting it, and it allows you to make fully scalable websites that looks exactly the same on all displays and platforms. Thank you. PS: (2013) It turned out that I gave up on web development. Nowadays things are getting more standardized, but even though it's a real nightmare to support all the different browsers and systems. Certainly not the thing for me. A: Well-designed style sheets will do most of this... not per the browser size but the text size (using ems) which most browsers allow you to change with a key combination. (like ctrl + "+"). Putting a lot of effort into making things scale exactly sounds like a lot of effort for not a lot of reward. A: You might want to look into responsive web design. This article walks you through a process of making a webpage respond to different screen resolutions. It is not so much about scaling, but adapting. Hope it helps. A: One of the methods is using the CSS transform property. Old browsers do not support this CSS feature though. /*Basic syntax:*/ transform: scale(2); /*width and height times two*/ transform: scale(2, 3); /*width times 2, height times three*/ transform: scaleX(2) scaleY(3); /*Same as above*/ To support as much browsers as possible, you have to define -moz-transform, -webkit-transform, -o-transform, -ms-transform and just transform names: -moz-transform: scale(2); -webkit-transform: scale(2); -o-transform: scale(2); -ms-transform: scale(2); transform: scale(2); EDIT, The transform feature can easily be implemented: var scale = 2; //Dynamic calculations resulted 2 var scaleCSS = ["-moz-", "-webkit-", "-o-", "-ms-", "", ""] .join("transform: scale("+scale+");"); /*Less error-sensitive*/ document.body.style.cssText += ";" + scaleCSS; /*The RE below is similar to this one: /;\s*((?!text-)[a-z-])*transform:/i This RE is needed to prevent "text-transform" from matching */ if(!/(;\s*(-moz-|-webkit-|-o-|-ms-|)transform:)/i.test(document.body.style.cssText)) { /*the browser doesn't recognise any of the CSS features Go to another, probably CPU-consuming JavaScript method *Or redirect the user to one of the pre-styled pages */ } A: well there is percentages that scale to your browser...check out 960 Grid and Using percentages Personally I would stay away from flash
{ "language": "en", "url": "https://stackoverflow.com/questions/7519071", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Error trying to convert char to number I have an information, which I assume to be char type, since I have the following (dbms_output.put_line is a function like "print" and the returned value is after --> ): dbms_output.put_line( table_record.column_1 ); --> 0.6 dbms_output.put_line( UPPER(table_record.column_1) ); --> 0.6 dbms_output.put_line( LOWER(table_record.column_1) ); --> 0.6 But I don't want that. I want to convert this column to FLOAT type. When I try: dbms_output.put_line( to_number(crate_record.column_1) ); I have ORA-06502: PL/SQL: numeric or value error: character to number conversion error. Why the to_number is not working? A: Kindly try alter session and format mask alter session set NLS_NUMERIC_CHARACTERS=".," dbms_output.put_line( to_number(crate_record.column_1,999999999.99) ); and if you want the same decimal and group separater for the whole application then change NLS_NUMERIC_CHARACTERS in DB for which below link might be helpful https://forums.oracle.com/forums/thread.jspa?threadID=899739
{ "language": "en", "url": "https://stackoverflow.com/questions/7519073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In Vim's NERDTree, is there a way to open a file/dir using the space key or tab key? Currently the only way to open the file or directory currently underneath your cursor is to type o. Is there a way to also map this to space or tab? A: let NERDTreeMapActivateNode='<space>' should work fine. For more information see :h NERDTreeMappings.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519074", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Image auto width in CSS for all browsers? I have my img tag defined with some CSS as: img { width: auto !important; height: auto !important; max-width: 100%; } It works just fine in some of the Mobile Browsers I have tried, as well as Google Chrome on a desktop. However, it does not seem to work in IE or FireFox. By that, I mean, as you resize the window. Take a look at a sandbox site I am working on: http://terraninstitute.com. I have the image on the home page intentionally set to be a huge picture. Also navigate to the Information (main menu) then Newcomers (side menu) and notice the map image at the bottom. On my Droid (and a few other devices I can get my hands on) as well as in Google Chrome this looks pretty good. In IE and FireFox, not so much. Am I missing something? Conflicting style definitions? I am not finding them as of yet if it is. TIA A: Bootstrap solution for responsive images: img { /* Responsive images (ensure images don't scale beyond their parents) */ /* Part 1: Set a maxium relative to the parent */ max-width: 100%; /* IE7-8 need help adjusting responsive images */ width: auto\9; /* Part 2: Scale the height according to the width, otherwise you get stretching */ height: auto; vertical-align: middle; border: 0; -ms-interpolation-mode: bicubic; } A: Don't use !important Make your CSS more speficic: body img { width: auto; height: auto; max-width: 100%; } A: You're declaring the width of your images multiple times in your document unnecessarily and declaring a max-width the wrong way. Max-width is supposed to define a max size/boundary for your images (600px, for example), if you declare max-width:100% in conjunction with width:100%, you're not really doing anything with that declaration as the images will expand 100% as it is. Remove the width declarations from your CSS in the following lines: line 116: delete the img declaration all together, it is not needed. line 365: remove the max-width:100% and height:auto; attribute as they are not needed (and if you can delete the declaration all together as you can declare that elsewhere) line 121: Now just stick with this one and just add the following: img { height: auto; width:100%; } A: in style.css line line 116, 212 and in inuit.css line 365. Remove all those. img{ height: auto; max-width: 100%; } Thats all you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to convert binary to hexadecimal string in C/glib? Is there a common way or good public domain code for converting binary (i.e. byte array or memory block) to hexadecimal string? I have a several applications that handle encryption keys and checksums and I need to use this function a lot. I written my own "quick and dirty" solution for this but it only works with binary objects of fixed size and I'm looking for something more universal. It seems pretty mundane task and I'm sure there should be some code or libraries for this. Could someone point me in the right direction, please? A: Something like this? void print_hex(const char * buffer, size_t size) { for (size_t i = 0; i < size; i++) printf("%02x", buffer[i]); } A: Thanks everybody for your help. Here is how final code turned out in glib notation: gchar * print_to_hex (gpointer buffer, gsize buffer_length) { gpointer ret = g_malloc (buffer_length * 2 + 1); gsize i; for (i = 0; i < buffer_length; i++) { g_snprintf ((gchar *) (ret + i * 2), 3, "%02x", (guint) (*((guint8 *) (buffer + i)))); } return ret; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7519084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: file reference with slash If I am referenceing a file (lets say an image file for it to display on a webpage) which is a few folders above, I can write "folder1/folder2/file.jpg". What does it mean if the reference starts with a slash like "/folder1/folder2/file.jpg"? A: Leading slash means that the reference is starting from the root directory (absolute reference) vs. the current location (relative reference).
{ "language": "en", "url": "https://stackoverflow.com/questions/7519086", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Overriding global htpasswd password protection I am testing a Drupal site on a development server that runs bunch of other development sites. All of the sites are password protected globally by htpasswd. However, I need to not have password protection on my testing site because I am testing another authentication method using Apache directive "AuthType Shibboleth" in my .htaccess, which seems in conflict with Apache password. How do I turn off htpasswd protection for my site only with global htpasswd in effect for other sites? A: The following line in an .htaccess in the root of the site you DON'T want protected always works for me: satisfy any
{ "language": "en", "url": "https://stackoverflow.com/questions/7519088", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: debug TcpClient and TcpListener on the same machine New to network programming here. I have a two piece application. I am trying to debug it locally. Service listens for connections on new IPEndPoint(IPAddress.Any, 3000). Calling tcpClient.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3000)) throws No connection could be made because the target machine actively refused it 127.0.0.1:3000. Windows firewall is off. Am I doing something fundamentally stupid? A: you should call the Start method on the TcpListener to get it working, or it will not accept any connection. I have tested and this snippet works :) using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { int port = 5124; var myListener = new TcpListener(new IPEndPoint(IPAddress.Any, port)); myListener.Start(); var tcpClient = new TcpClient(); tcpClient.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port)); tcpClient.Close(); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/7519091", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to change selectedNode in a treeView during AfterLabelEdit I'm having an issue with the selected node in a treeview. Here is are two scenario. (# 2 is causing my problem) 1 - If I select the node "level", press F2, change the label and press enter. The selectedNode inside the AfterLabelEdit will change. The selectedNode will change from "Level1" to "Root". 2 - If I select the node "level", press F2, change the label but click somewhere on the treeview, the selectedNode will never change. Is an event firing that is causing the issue? I've created a small test project to show the issue at hand. public partial class Form1 : Form { public Form1() { InitializeComponent(); this.Load += new EventHandler(Form1_Load); this.treeView1.KeyDown += new KeyEventHandler(Form1_KeyDown); this.treeView1.AfterLabelEdit += new NodeLabelEditEventHandler(treeView1_AfterLabelEdit); } void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) { Console.WriteLine(this.treeView1.SelectedNode); this.treeView1.SelectedNode = this.treeView1.SelectedNode.Parent; Console.WriteLine(this.treeView1.SelectedNode); TreeNode test = this.treeView1.SelectedNode; } void Form1_KeyDown(object sender, KeyEventArgs e) { if (this.treeView1.SelectedNode != null) { if (e.KeyData == Keys.F2) { this.treeView1.SelectedNode.BeginEdit(); } } base.OnKeyDown(e); } void Form1_Load(object sender, EventArgs e) { this.treeView1.Nodes.Add(new TreeNode("root")); this.treeView1.Nodes[0].Nodes.Add(new TreeNode("level1")); this.treeView1.Nodes[0].Nodes[0].Nodes.Add(new TreeNode("level2")); this.treeView1.SelectedNode = this.treeView1.Nodes[0]; this.treeView1.SelectedNode.ExpandAll(); this.treeView1.SelectedNode = this.treeView1.Nodes[0].Nodes[0]; } } A: It is an event order problem, the mouse click fires after AfterLabelEdit so it wins. The typical BeginInvoke trick doesn't work, you'll need a Timer to select the node: void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) { TreeNode nextnode = this.treeView1.SelectedNode.Parent; var timer = new Timer() { Enabled = true, Interval = 50 }; timer.Tick += delegate { this.treeView1.SelectedNode = nextnode; timer.Dispose(); }; } That works, kinda ugly. This only happens when the user clicks a specific node, maybe you should not override the choice. Kudos for the repro code btw. A: Kinda a hack, but this will select the root node when the user clicks somewhere else in the treeview, except for the level2 node: private bool SelectParent = false; void treeView1_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) { this.treeView1.SelectedNode = e.Node.Parent; SelectParent = true; } private void treeView1_MouseDown(object sender, MouseEventArgs e) { if (SelectParent) { this.treeView1.SelectedNode = this.treeView1.SelectedNode.Parent; SelectParent = false; } } put this in your form1 constructor: this.treeView1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.treeView1_MouseDown);
{ "language": "en", "url": "https://stackoverflow.com/questions/7519093", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pass array from c++ library to a C# program I'm making a dll in c++ and I want to pass an array to a c# program. I already managed to do this with single variables and structures. Is it possible to pass an array too? I'm asking because I know arrays are designed in a different way in those two languages and I have no idea how to 'translate' them. In c++ I do it like that: extern "C" __declspec(dllexport) int func(){return 1}; And in c# like that: [DllImport("myDLL.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "func")] public extern static int func(); A: Using C++/CLI would be the best and easier way to do this. If your C array is say of integers, you would do it like this: #using <System.dll> // optional here, you could also specify this in the project settings. int _tmain(int argc, _TCHAR* argv[]) { const int count = 10; int* myInts = new int[count]; for (int i = 0; i < count; i++) { myInts[i] = i; } // using a basic .NET array array<int>^ dnInts = gcnew array<int>(count); for (int i = 0; i < count; i++) { dnInts[i] = myInts[i]; } // using a List // PreAllocate memory for the list. System::Collections::Generic::List<int> mylist = gcnew System::Collections::Generic::List<int>(count); for (int i = 0; i < count; i++) { mylist.Add( myInts[i] ); } // Otherwise just append as you go... System::Collections::Generic::List<int> anotherlist = gcnew System::Collections::Generic::List<int>(); for (int i = 0; i < count; i++) { anotherlist.Add(myInts[i]); } return 0; } Note I had to iteratively copy the contents of the array from the native to the managed container. Then you can use the array or the list however you like in your C# code. A: * *You can write simple C++/CLI wrapper for the native C++ library. Tutorial. *You could use Platform Invoke. This will definitely be simpler if you have only one array to pass. Doing something more complicated might be impossible though (such as passing nontrivial objects). Documentation. A: In order to pass the array from C++ to C# use CoTaskMemAlloc family of functions on the C++ side. You can find information about this on http://msdn.microsoft.com/en-us/library/ms692727 I think this will be suffice for your job.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519094", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Monitoring webapp deployed in Glassfish From a webapp deployed in a Glassfish app server, I have to find some metrics to allow monitoring. Inside the webapp, is there others tools/libraries which allow me to gather such metrics ? I know I can connect to JMX/AMX, but is there others solutions ? A: JavaMelody can monitor a lot of things inside the webapp (used memory, %cpu, http sessions, ...), and if you want that you could use it to access metrics and JMX values over just http. A: dpending on your client there is variety of options - first comming to my mind is JSON or CSV provided through HTTP URL you can pull A: There is the Codahale Metrics library which provides you a conevient way to collect many different metrics. Furthermore it provides different reporters as JMX, CSV, JSON, fileoutput.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519098", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Change focus list of textboxes WPF I have a listbox where the Items are Textboxes. I need to set a key to change the focus to the next textbox and begin the editing of its content. I have cheated a solution sending Key strokes to achieve what I want, for example: ((TextBox)listBox1.Items[0]).KeyDown += (object x, KeyEventArgs y) => { if (y.Key == Key.Enter) { InputSimulator.SimulateKeyDown(VirtualKeyCode.TAB); InputSimulator.SimulateKeyPress(VirtualKeyCode.DOWN); InputSimulator.SimulateKeyDown(VirtualKeyCode.TAB); } }; I use the library InputSimulator found here http://inputsimulator.codeplex.com/ for that approach. I know that this is not the correct way to do it so I'm ask how can i achieve the same using the focus methods. I try with the following code but i get "out of range" error that I don't understand: private void Window_Loaded(object sender, RoutedEventArgs e) { for (int i = 0; i < 3; i++) { listBox1.Items.Add(new TextBox() { TabIndex=i }); } for (int i = 0; i < listBox1.Items.Count-1; i++) { ((TextBox)listBox1.Items[i]).KeyDown += (object x, KeyEventArgs y) => { if (y.Key == Key.Tab) { Keyboard.Focus((TextBox)listBox1.Items[i+1]); } }; } ((TextBox)listBox1.Items[listBox1.Items.Count - 1]).KeyDown += (object x, KeyEventArgs y) => { if (y.Key == Key.Tab) { Keyboard.Focus((TextBox)listBox1.Items[0]); }}; } A: Here is a really short answer for you. In XAML you can use a style to define a common handler for your listboxes... <Window x:Class="Interface.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <Style TargetType="{x:Type TextBox}"> <EventSetter Event="KeyDown" Handler="TextBox_KeyDown"/> <Setter Property="Width" Value="100"/> </Style> </Window.Resources> <ListBox Name="lstBoxList"> <TextBox>ABC</TextBox> <TextBox>DEF</TextBox> <TextBox>GHI</TextBox> </ListBox> </Window> So you can see all of the text boxes in the list. The actual handler code will look like this... private void TextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { // Locate current item. int current = lstBoxList.Items.IndexOf(sender); // Find the next item, or give up if we are at the end. int next = current + 1; if (next > lstBoxList.Items.Count - 1) { return; } // Focus the item. (lstBoxList.Items[next] as TextBox).Focus(); } } So the basic concept is that you will locate the current text box in the list. Then you will find the next one somehow (tags, names, etc.) and focus it explicitly. Of course you will have to tweak depending on your exact need.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: mod_mono on windows I am trying mod_mono on apache 2.2.x running on a win7 box – followed the steps described here. The module loads Ok, but I can't run my ASP.net application (404). Does anybody have any suggestions or an example configuration that works? Thanks. A: My working config: <VirtualHost *:80> ServerAlias localhost DocumentRoot "c:\web\mysite" MonoServerPath mysite "c:\mono\usr\bin\mod-mono-server2.exe" MonoApplications mysite "/:c:\web\mysite" <Directory "c:\web\mysite"> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny Allow from all MonoSetServerAlias mysite SetHandler mono DirectoryIndex default.aspx index.html </Directory> </VirtualHost> A: I found a good tutorial for you. Example mono configuration: MonoServerPath default /usr/bin/mod-mono_server2 Alias [D] “[P]” AddMonoApplications default “[D]:[P]” <Location [D]> SetHandler mono </Location> Another example: MonoServerPath default /usr/bin/mod-mono_server2 Alias /MySite “/srv/www/htdocs/MySite” AddMonoApplications default “/MySite:/srv/www/htdocs/MySite” <Location /MySite> SetHandler mono </Location>
{ "language": "en", "url": "https://stackoverflow.com/questions/7519104", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Regular Expression Commas and Columns I have an issue while parsing my Solr Queries that I pass on the querystring: The values I end up having to work with look like this: ed_deliveryMethod:Face to Face,ed_location:Alexandria,VA,ed_delivery:Onsite I need a regex that would parse a key value pair: * *ed_deliveryMethod:Face to Face *ed_location:Alexandria,VA *ed_delivery:Onsite So I need a regex to parse FacetName:FacetValue I was doing a split by commas but the comma on the location is throwing things off. The last comma is optional since there might be just one filter. I did try a lot of things before asking this question but no success. I'm not good at regex as you can see. ((?<Facet>.+):(?<FacetValue>.+),)+ A: Try the following: (?<Facet>\w+):(?<FacetValue>.+?)(?=,\w+:|$) Maybe you need to adjust \w to contain all allowed charactes of your keys. A: Use QueryString.GetValues(key), it returns an array of values. E.g. if you have &filter=category:car&filter=category:motorcycle as you mentioned in a comment, and you call QueryString.GetValues("filter") you get an array with elements "category:car" and "category:motorcycle". Then split each element by :, etc. No regex needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: JSON says it's null? My server side code: returns an array: return array('success'=>true, 'client_id' => $_GET['id']); which is then echo'd echo htmlspecialchars(json_encode($result), ENT_NOQUOTES); JSON looks like this when outputting; {"success":true,"client_id":"db7A8"} But when I run onComplete: function(id, fileName, responseJSON){ var newBucket = $.parseJSON(responseJSON); alert(newBucket.client_id); } it says that it's null (it's a function of AJAX upload), any idea what's wrong here? A: Have you specified proper ContentType header while returning JSON data from php? IE and Chrome doesn't like to receive JSON under the wrong ContentType header. If that doesn't solve your problem try using this http://code.google.com/p/jquery-json/ var encoded = $.toJSON(responseJSON); var newBucket = $.evalJSON(encoded); alert(newBucket.client_id); Edit : the code above is using the mentioned jquery plugin to serialize the responseJSON before parsing it. You may use other alternative methods to do the same if you don't want to use that jquery plugin.
{ "language": "en", "url": "https://stackoverflow.com/questions/7519106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Convert url encoded string into python unicode string I have strings encoded in the following form: La+Cit%C3%A9+De+la+West that I stored in a SQLite VARCHAR field in python. These are apparently UTF-8 encoded binary strings converted to urlencoded strings. The question is how to convert it back to a unicode string. s = 'La+Cit%C3%A9+De+la+West' I used the urllib.unquote_plus( s ) python function but it doesn't convert the %C3%A9 into a unicode char. I see this 'La Cité De la West' instead of the expected 'La Cité De la West'. I'm running my code on Ubuntu, not windows and encoding is UTF-8. A: As we discussed, it looks like the problem was that you were starting with a unicode object, not a string. You want a string: >>> import urllib >>> s1 = u'La+Cit%C3%A9+De+la+West' >>> type(s1) <type 'unicode'> >>> print urllib.unquote_plus(s1) La Cité De la West >>> s2 = str(s1) >>> type(s2) <type 'str'> >>> print urllib.unquote_plus(s2) La Cité De la West >>> import sys >>> sys.stdout.encoding 'UTF-8'
{ "language": "en", "url": "https://stackoverflow.com/questions/7519109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }