pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
4,596,433 | 0 | <p>You shouldn't need the html5shiv if you're using Modernizr, as Modernizr includes the same functionality itself.</p> <p>Quote from the Modernizr homepage:</p> <blockquote> <p>Lastly, Modernizr also adds support for styling and printing HTML5 elements. This allows you to use more semantic, forward-looking elements such as <code><section></code>, <code><header></code> and <code><dialog></code> without having to worry about them not working in Internet Explorer.</p> </blockquote> |
29,240,634 | 0 | <p>The simplest CGI app looks like this:</p> <pre><code>#include <iostream> using namespace std; int main () { cout << "Content-type:text/html\r\n\r\n"; cout << "<html>\n"; cout << "<head>\n"; cout << "<title>Hello World - First CGI Program</title>\n"; cout << "</head>\n"; cout << "<body>\n"; cout << "<h2>Hello World! This is my first CGI program</h2>\n"; cout << "</body>\n"; cout << "</html>\n"; return 0; } </code></pre> |
40,897,840 | 0 | How to % encode single quotes when making jQuery AJAX call? <p>I am using $.ajax to send a SQL query to my web server. The query string contains several single quotes ('). I encountered a very messy problem on encoding single quotes.</p> <p>My code like this, please note the single quotes in query string:</p> <pre><code>var query = "select SID, age from Students where Name=\'Jason\'" + String.fromCharCode(10) + "order by age asc"; $.ajax({ url: "http://mywebserver/query", data: { env: "dbserver1", endTime: "getUTCDate()", startTime: "dateadd(hour, -336, getUTCDate())", text: query }, type: "GET", dataType: "json" }).done(function (datum) { }); </code></pre> <p>If I don't explicitly call encodeURIComponent before make AJAX call, jQuery will encode it for me, however, the single quotes are not encoded to %27 by default, so query doesn't work;</p> <p>If I pass an encoded query string to jQuery, it will encode again, that messes up the query string.</p> <p>The only solution i can imagine is, i have to overwrite the behavior how jQuery encodes URL, and replace all (') with %27. But I don't know if jQuery supports that. Does anyone have a solution for this?</p> |
24,968,975 | 0 | <blockquote> <p>Is it safe if I use the same variable to create another subprocess if previous subprocess finishes?</p> </blockquote> <p>Yes. It would also be safe if the subprocess <em>weren't</em> finished, since you're completely replacing the value stored in <code>p</code> with a new value (a new object reference).</p> <hr> <p><s>In fact, <em>your</em> assignment in the loop you've shown isn't overwriting the previous value at all. By the time a new iteration starts, since you've declared your variable <em>inside</em> the block, it's either a new variable on each iteration or it's treated as though it were (you can look at it either way, probably; the bytecode probably reflects the latter but I think theory reflects the former). <em>Your</em> assignment is giving the (new) variable an initial value, not overwriting the previous iteration's value. If you moved your <code>Process p</code> declaration outside the loop, <em>then</em> you'd be overwriting it. Which would still be fine. :-)</s></p> <p>The strikeout text above may be or may not be true in theory (I'd have to dig through the JLS), but it would appear <em>not</em> to be true in pragmatic JVM/bytecode terms: Test: <a href="http://pastie.org/9422290" rel="nofollow">http://pastie.org/9422290</a> Bytecode: <a href="http://pastie.org/9422293" rel="nofollow">http://pastie.org/9422293</a> (pasted below). We can see that the <code>Date</code> reference is stored on instruction 20 of <code>main</code> in local variable 2 (<code>astore_2</code>). We only write to it on the first iteration. It isn't cleared when starting the next iteration, so pragmatically, you're using the same variable and overwriting it.</p> <p><code>Temp.java</code>:</p> <pre><code>import java.util.Date; public class Temp { public static final void main(String[] args) { int counter; for (counter = 0; counter < 10; ++counter) { Date dt; if (counter < 1) { dt = new Date(); System.out.println(dt); } System.out.println("loop end"); } } } </code></pre> <p>Output of <code>javap -c Temp</code>:</p> <pre><code>public class Temp { public Temp(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static final void main(java.lang.String[]); Code: 0: iconst_0 1: istore_1 2: iload_1 3: bipush 10 5: if_icmpge 42 8: iload_1 9: iconst_1 10: if_icmpge 28 13: new #2 // class java/util/Date 16: dup 17: invokespecial #3 // Method java/util/Date."<init>":()V 20: astore_2 21: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream; 24: aload_2 25: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V 28: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream; 31: ldc #6 // String loop end 33: invokevirtual #7 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 36: iinc 1, 1 39: goto 2 42: return } </code></pre> |
17,594,551 | 0 | <p>In the XAML you're setting the property to the default value which will not cause the <code>PropertyChanged</code> handler to fire. The boilerplate Get and Set methods will never be called unless you call them from code because properties set in XAML call <code>GetValue</code> and <code>SetValue</code> directly (as is the case with wrapper properties on a normal DP).</p> <p>To ensure the change handler is always called when a value is set you could use a <code>Nullable<HorizontalAlignment></code> instead and set the default to <code>null</code>.</p> |
20,109,023 | 0 | <p>The problem is that your <code>fscanf</code> will never read the newline at the end of the first line. So when it is called the second time, it will fail (returning 0, not EOF) and read nothing, leaving <code>buffer</code> unchanged.</p> <p>You could add a call to <code>fscanf("%*[\n]");</code> at the end of your while loop to skip the newline (and any blank lines that might occur). Or you could just use <code>fgets</code> instead, which also makes it easier to avoid the potential buffer overflow problem.</p> |
30,963,407 | 0 | Warning that "unknown addresses are found in partition table" <p>When using Hazelcast, I get warnings like:</p> <pre><code>Jun 21, 2015 11:10:15 AM com.hazelcast.partition.InternalPartitionService WARNING: [192.168.0.18]:5701 [5a11] [3.4.2] Following unknown addresses are found\ in partition table sent from master[Address[192.168.0.9]:5701]. (Probably they have recently joined or left the cluster.) { Address[192.168.0.13]:5701 } Jun 21, 2015 11:10:29 AM com.hazelcast.partition.InternalPartitionService WARNING: [192.168.0.18]:5701 [5a11] [3.4.2] Following unknown addresses are found\ in partition table sent from master[Address[192.168.0.20]:5701]. (Probably they have recently joined or left the cluster.) { Address[192.168.0.11]:5701 Address[192.168.0.17]:5701 } Warning: irregular exit, check log </code></pre> <p>What is the cause, and do I have to take actions to avoid these warnings?</p> <hr> <p>Details:</p> <p>These warning occur at the end of my distributed computations, and not for all instances. So it is very likely that some other instances have terminated and thus "recently left the cluster" when this warning occurs. </p> <p>But why does an instance leaving cause an unknown address? Does this mean the instance <code>x</code> giving the warning somehow found out that instance <code>y</code> has left, and the master hasn't yet found out and sends the address of <code>y</code> to <code>x</code>, causing this warning?</p> <p>Should I take actions to avoid this warning? Does it mean that <code>y</code> forgets some cleanup it is supposed to do at the end so that the master immediately finds out that <code>y</code> leaves the cluster? The only cleanup the instances are performing is <code>shutdown()</code> of their <code>HazelcastInstance</code>.</p> <p>Is the irregular exit at the end of my log messages caused by the inconsistency in the partition table?</p> |
23,913,310 | 0 | <p>If you have only one value for each key for each user:</p> <pre><code>select P.* from Table1 as t pivot ( max(Value) for [Key] in ([Address], [Number], [Sport], [Document]) ) as P </code></pre> <p>or</p> <pre><code>select t.Usr, max(case when t.[Key] = 'Address' then t.[Value] end) as Address, max(case when t.[Key] = 'Number' then t.[Value] end) as Number, max(case when t.[Key] = 'Sport' then t.[Value] end) as Sport, max(case when t.[Key] = 'Document' then t.[Value] end) as Document from Table1 as t group by t.Usr </code></pre> <p><strong><kbd><a href="http://sqlfiddle.com/#!3/cd68cc/4" rel="nofollow">sql fiddle demo</a></kbd></strong></p> |
28,614,566 | 0 | <p>The OS handles scheduling and dispatching of ready threads, (those that require CPU), onto cores, managing CPU execution in a similar fashion as it manages other resources. A cache-miss is no reason to swap out a thread. A page-fault, where the desired page is not loaded into RAM at all, may cause a thread to be blocked until the page gets loaded from disk. The memory-management hardware does that by generating a hardware interrupt to an OS driver that handles the page-fault.</p> |
18,300,412 | 0 | Why simply use PHP variables for dynamic stylesheets? <p>I've been reading about dynamic stylesheets and have stumbled across several options, including sass, and less. But my question is why not just turn my <code>stylesheet.css</code> into <code>stylesheet.css.php</code> and simply use php variables. Then, I avoid all the dependency issues associated with all these other approaches. </p> <p>Am I overlooking some serious problems by doing it this way?</p> |
12,009,827 | 0 | <p>Yes, this looks like VS2003 bug. Workaround is simple - use typedef, it works this way:</p> <pre><code>class A { public: int x; }; class B : public A { public: class A { public: int y; }; }; typedef B::A BA; class C: public BA {}; void f() { C cc; cc.y = 0; } </code></pre> |
36,410,229 | 0 | Pattern for moving javascript out of the markup <p><strong>tl;dr</strong> How do I refactor a typical .NET+KnockoutJS site using lots of server generated blocks (controllers) into one where all js is loaded separately from the markup?</p> <p>Up until now all my foray into front-end development has been new projects, built from the ground using modern tooling and workflows, such as React, Redux, isomorphic rendering, etc. Yesterday a legacy project (ok, made three years ago) landed on my lap, and it features "blocks" (an EPi Server term basically meaning templates) such as this:</p> <p><strong>MySuperSlider.ascx</strong></p> <pre><code><!-- ko foreach: products() --> <div class="my-super-slider"> <a data-bind="attr: { href: ProductUrl }"> <h1 data-bind="text: name"></h1> <img src="" data-bind="attr: { src : image.uri }" </a> </div> <!-- /ko --> <script type="text/javascript"> // Make a call to the back-end to retrieve the product data used // in the KO template above and apply it ko.applyBindings(new SliderBlock( '<%# ProductsController.GetServiceUrl(ProductsController.BlockUrl, Request.Url)%>', '<%# CurrentPage.PageLink.ID %>', '<%# GetBlockId() %>', '<%# (CurrentPage as SitePageDataBase) == null?string.Empty:(CurrentPage as SitePageDataBase).ProductPageUrl %>?id=', '<%# ContentLanguageCode %>', "<%# SliderContentBlock.ClientID %>"), document.getElementById("<%# SliderContentBlock.ClientID %>")); </script> </code></pre> <p>Blocks, such as this one, are being reused all over the site, but with different settings (ref <code>SliderContentBlock.ClientID</code> which would fetch data for that current block). The fact that the referenced variables are unique for each block instance and rendered at runtime makes it impossible/hard to split the js out. Except possibly using some <code>data</code> attributes that could later be picked up?</p> <p><strong>Problem: <code><script></code> tags cannot be moved out of <code><head></code></strong></p> <p>It is currently impossible to move <code><script></code> tags out of <code><head></code>, thus blocking the rendering pipeline. Neither moving after them after <code><body></code> or using <code>async</code> or <code>defer</code> attributes is possible as this would make any inline <code><script></code> blocks referring to the <code>ko</code> variable break.</p> <p>So what is a good strategy for refactoring the above code into something that will work regardless of whether the knockout library has been loaded or not?</p> <p><strong>Hacky solution</strong></p> <p>The fastest (and probably most brittle) solution would be to create an array to hold initialization functions that could then be executed later on. Something like</p> <pre><code><head> <script>window.initFuncs = [];</script> </head> <body> ... <!-- inline code pushing init code in the queue --> ... <script>initFuncs.forEach( fn => fn() );</script> </body> </code></pre> <p>Then all I would need to do to defer execution of the above javascript would be to wrap it in a <code>window.initFuncs.push( () => { ko.applyBindings(/* js goes here */) })</code></p> <p>This would work, but does not exactly seem like the way to go. But this problem must have been solved a million times before (?). How does other Knockout developers do this?</p> <p>I cannot simply move <em>all</em> of the javascript (as it is) out into separate files, as variables are being inserted into the markup during server rendering.</p> <p><strong>Attempt at better solution</strong></p> <p>I am not a .NET developer, but I feel the logic in the template with all the variable substitution would be better done in the backing code, instead of pushing all the details into the front-end. Not sure how that would be done, though.</p> |
6,448,456 | 0 | Move to eclipse Indigo? <p>Now that the new version of eclipse is out should I move to immediately? If my plug-ins work in Galileo will it work in the indigo?</p> |
15,871,512 | 0 | Three.js: vertexNormals of CircleGeometry looks inverse on r57 <p>VertexNormals of CircleGeometry looks inverse. If I use computeVertexNormals(), it is fixed. I'm using r57 and confirmed with Firefox19 and IE9+ChromeFrame26.</p> <p>If it is already reported, ignore it.</p> |
6,954,485 | 0 | <p>Here is a good SO question that i think addresses this:</p> <p><a href="http://stackoverflow.com/questions/2611350/intercept-paste-event-on-htmleditor-winforms">Intercept paste event on HtmlEditor WinForms</a></p> <p>You have to sub-class it and stop the paste message from getting farther down, by overriding WndPrc. Then, call your own function to handle the paste. </p> <p>I think there is an easier way to locate the paste message, though. Ignore his code for inserting the content, since that doesn't apply to an RTF.</p> |
27,642,754 | 0 | <p>Register a role resolver. See my example here: <a href="https://github.com/strongloop/loopback-example-access-control/blob/master/server/boot/create-role-resolver.js" rel="nofollow">https://github.com/strongloop/loopback-example-access-control/blob/master/server/boot/create-role-resolver.js</a></p> |
5,932,275 | 0 | <p>Because in one case its a pointer and in the other a reference:</p> <p>int a=&x means set a to the address of x - wrong</p> <p>int &p=fun() means set p to a reference to an int - ok</p> |
16,693,427 | 0 | <p>Please check the Last Lien of Code,</p> <pre><code> panel.add(btnInspector );// repalce btnInspector with btnToolBox </code></pre> |
21,425,966 | 0 | ObjectListView Column Reordering <p>I've got a <code>dataTreeListView</code> which has got afew column headers as added to it as follows:</p> <pre><code>oCol2.IsVisible = false; dataTreeListView.AllColumns.AddRange(new OLVColumn[] { oCol1, oCol2, oCol3, oCol4, oCol5}); dataTreeListView.KeyAspectName = id; dataTreeListView.ParentKeyAspectName = ParentId; dataTreeListView.DataSource = list; dataTreeListView.RootKeyValue = 0; </code></pre> <p>The list itself has got 7 properties (inclusive of <code>Id</code> and <code>ParentId</code>).</p> <p>What I'm trying to achieve is that, upon <code>selectedIndex</code> change of a combo box, the column header will change position.</p> <pre><code>From View (type1) (oCol2.IsVisible = false): oCol1 (expandable) | oCol2 (hidden) | oCol3 | oCol4 | oCol5 To View (type2) (oCol2.IsVisible = true): oCol2 | oCol1 (expandable) | oCol3 | oCol4 | oCol5 </code></pre> <p>What I got now is view (type1) is working correctly, but after switching to view type2, the expandable column is still at oCol1 instead of oCol2. It seems that I could not <code>switch</code> the primary column.</p> <p>Any help for this?</p> |
17,163,043 | 0 | Unable to WebKit Layout Tests on android <ul> <li>Compile the chromium for Android<br> Build every test: </li> </ul> <p><code>$ ninja -C out/Release</code></p> <ul> <li>Running the layout Tests </li> </ul> <p><code>$ webkit/tools/layout_tests/run_webkit_tests.sh</code></p> <p>I get following errors:</p> <blockquote> <p>Using port 'chromium-linux-x86_64' Test configuration: Placing test results in /host/chromium/src/webkit/Release/layout-test-results Baseline search path: chromium-linux -> chromium-win -> generic Using Release build Pixel tests enabled Regular timeout: 6000, slow test timeout: 30000 Command line: /host/chromium/src/third_party/WebKit/out/Release/DumpRenderTree -</p> <p>Found 29487 tests; running 28395, skipping 1092. Unable to find test driver at /host/chromium/src/third_party/WebKit/out/Release/DumpRenderTree</p> <p>For complete Linux build requirements, please see:</p> <p><a href="http://code.google.com/p/chromium/wiki/LinuxBuildInstructions" rel="nofollow">http://code.google.com/p/chromium/wiki/LinuxBuildInstructions</a><br> Build check failed</p> </blockquote> |
23,787,600 | 0 | <p>Here's a simple option, using <code>data.table</code> instead:</p> <pre><code>library(data.table) dt = as.data.table(your_df) setkey(dt, id, date) # in versions 1.9.3+ dt[CJ(unique(id), unique(date)), .N, by = .EACHI] # id date N # 1: Andrew13 2006-08-03 0 # 2: Andrew13 2007-09-11 1 # 3: Andrew13 2008-06-12 0 # 4: Andrew13 2008-10-11 0 # 5: Andrew13 2009-07-03 0 # 6: John12 2006-08-03 1 # 7: John12 2007-09-11 0 # 8: John12 2008-06-12 0 # 9: John12 2008-10-11 0 #10: John12 2009-07-03 0 #11: Lisa825 2006-08-03 0 #12: Lisa825 2007-09-11 0 #13: Lisa825 2008-06-12 0 #14: Lisa825 2008-10-11 0 #15: Lisa825 2009-07-03 1 #16: Tom2993 2006-08-03 0 #17: Tom2993 2007-09-11 0 #18: Tom2993 2008-06-12 1 #19: Tom2993 2008-10-11 1 #20: Tom2993 2009-07-03 0 </code></pre> <p>In versions 1.9.2 or before the equivalent expression omits the explicit <code>by</code>:</p> <pre><code>dt[CJ(unique(id), unique(date)), .N] </code></pre> <p>The idea is to create all possible pairs of <code>id</code> and <code>date</code> (which is what the <code>CJ</code> part does), and then merge it back, counting occurrences.</p> |
14,286,676 | 0 | Elegant way to iterate in C++ <p>Let's say I have a vector of Polygons, where each polygon contains a vector of Points. I have to iterate over all the points of all the polygons many times in my code, I end up having to write the same code over and over again:</p> <pre><code>for(std::vector<Polygon*>::const_iterator polygon = polygons.begin(); polygon != polygons.end(); polygon++) { for(std::vector<Point>::const_iterator point = (*polygon)->points.begin(); point != (*polygon)->points.end(); point++) { (*point).DoSomething(); } } </code></pre> <p>I really feel that is a lot of code for two simple iterations, and feel like it's clogging the code and interfering with the readability.</p> <p>Some options I thought are:</p> <ul> <li>using #defines - but it would make unportable (to use in other parts of the code). Furthermore, #defines are considered evil nowadays;</li> <li>iterate over vector->size() - it doesn't seem the most elegant way;</li> <li>calling a method with a function pointer - but in this case, the code that should be inside of the loop would be far from the loop.</li> </ul> <p>So, what would be the most clean and elegant way of doing this?</p> |
14,952,458 | 0 | <p>I guess you mean something like services running in the background and use GPS? So that you don't activate the GPS yourself but it's still running? In that case there's no way I know to get all Apps that are allowed to use GPS in background. You can go to your Settings->Apps and check the permissions which apps are allowed to use GPS.</p> <p>A typicall background GPS user is the facebook app (or google+ I guess). Hope this helps.</p> <p>Edit: Alternativly you could disable GPS when you don't need it so that no app has the possibility to use it in background.</p> |
33,356,273 | 0 | <blockquote> <p>The first parameter contains the name of the view file (in this example the file would be called blog_template.php), and the second parameter contains an associative array of data to be replaced in the template.</p> </blockquote> <pre><code>$data = array( 'blog_title' => 'My Blog Title', 'blog_heading' => 'My Blog Heading', 'blog_entries' => array( array('0' => 'Title 1', 'body' => 'Body 1'), array('1' => 'Title 2', 'body' => 'Body 2'), array('2' => 'Title 3', 'body' => 'Body 3'), array('3' => 'Title 4', 'body' => 'Body 4'), array('4' => 'Title 5', 'body' => 'Body 5') )); foreach ($data['blog_entries'] as &$arr) { foreach ($arr as $k => $v) { if (is_numeric($k)) { $arr['title'] = $v; unset($arr[$k]); } } $arr = array_reverse($arr); } echo '<pre>', var_dump($data);exit; </code></pre> <p>But you should be aware of eventual changes of structure of <code>$data</code> array. So if your api would export one more element with numeric key to that array, this code would be broken probably. You can check and test it though.</p> |
11,942,643 | 0 | How to handle slow network connection in Java/Android <p>I have an app that uses many, many calls to a MySQL database; it does this inside an <code>AsyncTask</code>. Below is a sample of what one may look like.</p> <p>My main question is this; sometimes, the host (Godaddy, ugh) decides to stall a connection and my <code>progressDialog</code> loads, and loads, and loads some more, until there is a force close and the app crashes. Especially if the user tries to interrupt it (most I have set to non-cancelable, however).</p> <p>Is there a better way to handle this than I am below? I am doing it in a <code>try</code>/<code>catch</code>, but not sure how to use that to my advantage.</p> <pre><code>class Task extends AsyncTask<String, String, Void> { private ProgressDialog progressDialog = new ProgressDialog( MasterCat.this); InputStream is = null; String result = ""; protected void onPreExecute() { progressDialog.setMessage("Loading..."); progressDialog.show(); progressDialog.setCancelable(false); } @Override protected Void doInBackground(String... params) { String url_select = "http://www.---.com/---/master.php"; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_select); ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); try { httpPost.setEntity(new UrlEncodedFormEntity(param)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); // read content is = httpEntity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader br = new BufferedReader( new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { // TODO: handle exception Log.e("log_tag", "Error converting result " + e.toString()); } return null; } protected void onPostExecute(Void v) { String cat; try { jArray = new JSONArray(result); JSONObject json_data = null; for (int i = 0; i < jArray.length(); i++) { json_data = jArray.getJSONObject(i); cat = json_data.getString("category"); cats.add(cat); } } catch (JSONException e1) { Toast.makeText(getBaseContext(), "No Categories Found", Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } ListView listView = getListView(); listView.setTextFilterEnabled(true); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) { Intent i = new Intent(getApplicationContext(), Items.class); i.putExtra("category", cats.get(arg2)); startActivity(i); } }); progressDialog.dismiss(); MasterCatAdapter adapter = new MasterCatAdapter(MasterCat.this, cats); setListAdapter(adapter); } } </code></pre> <p>Edit: Now I AM assuming the force close is because of the poor connection; but I will try to get alogcat up when I can recreate it.</p> <p>Edit2: here is LogCat:</p> <pre><code>08-13 14:57:00.580: E/WindowManager(2262): Activity com.---.---.MyFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@42b02cd0 that was originally added here 08-13 14:57:00.580: E/WindowManager(2262): android.view.WindowLeaked: Activity com.---.---.MyFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@42b02cd0 that was originally added here 08-13 14:57:00.580: E/WindowManager(2262): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374) 08-13 14:57:00.580: E/WindowManager(2262): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292) 08-13 14:57:00.580: E/WindowManager(2262): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224) 08-13 14:57:00.580: E/WindowManager(2262): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149) 08-13 14:57:00.580: E/WindowManager(2262): at android.view.Window$LocalWindowManager.addView(Window.java:547) 08-13 14:57:00.580: E/WindowManager(2262): at android.app.Dialog.show(Dialog.java:277) 08-13 14:57:00.580: E/WindowManager(2262): at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPreExecute(MyFragmentActivity.java:374) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.AsyncTask.execute(AsyncTask.java:534) 08-13 14:57:00.580: E/WindowManager(2262): at com.---.---.MyFragmentActivity$RateFragment$insertTask.onPostExecute(MyFragmentActivity.java:520) 08-13 14:57:00.580: E/WindowManager(2262): at com.---.---.MyFragmentActivity$RateFragment$insertTask.onPostExecute(MyFragmentActivity.java:1) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.AsyncTask.finish(AsyncTask.java:631) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.AsyncTask.access$600(AsyncTask.java:177) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.Handler.dispatchMessage(Handler.java:99) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.Looper.loop(Looper.java:137) 08-13 14:57:00.580: E/WindowManager(2262): at android.app.ActivityThread.main(ActivityThread.java:4745) 08-13 14:57:00.580: E/WindowManager(2262): at java.lang.reflect.Method.invokeNative(Native Method) 08-13 14:57:00.580: E/WindowManager(2262): at java.lang.reflect.Method.invoke(Method.java:511) 08-13 14:57:00.580: E/WindowManager(2262): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 08-13 14:57:00.580: E/WindowManager(2262): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 08-13 14:57:00.580: E/WindowManager(2262): at dalvik.system.NativeStart.main(Native Method) 08-13 14:57:00.588: D/AndroidRuntime(2262): Shutting down VM 08-13 14:57:00.588: W/dalvikvm(2262): threadid=1: thread exiting with uncaught exception (group=0x4200b300) 08-13 14:57:00.596: E/AndroidRuntime(2262): FATAL EXCEPTION: main 08-13 14:57:00.596: E/AndroidRuntime(2262): java.lang.NullPointerException 08-13 14:57:00.596: E/AndroidRuntime(2262): at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPostExecute(MyFragmentActivity.java:461) 08-13 14:57:00.596: E/AndroidRuntime(2262): at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPostExecute(MyFragmentActivity.java:1) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.os.AsyncTask.finish(AsyncTask.java:631) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.os.AsyncTask.access$600(AsyncTask.java:177) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.os.Handler.dispatchMessage(Handler.java:99) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.os.Looper.loop(Looper.java:137) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.app.ActivityThread.main(ActivityThread.java:4745) 08-13 14:57:00.596: E/AndroidRuntime(2262): at java.lang.reflect.Method.invokeNative(Native Method) 08-13 14:57:00.596: E/AndroidRuntime(2262): at java.lang.reflect.Method.invoke(Method.java:511) 08-13 14:57:00.596: E/AndroidRuntime(2262): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 08-13 14:57:00.596: E/AndroidRuntime(2262): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 08-13 14:57:00.596: E/AndroidRuntime(2262): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>Edit: Here is the Task that is in a different activity but being referenced in LogCat:</p> <pre><code>class RatingTask extends AsyncTask<String, String, Void> { private ProgressDialog progressDialog = new ProgressDialog( getActivity()); InputStream is = null; String result = ""; protected void onPreExecute() { progressDialog.setMessage("Loading..."); progressDialog.show(); progressDialog.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { RatingTask.this.cancel(true); } }); } @Override protected Void doInBackground(String... params) { String url_select = "http://www.---.com/---/get_ratings.php"; ArrayList<NameValuePair> param = new ArrayList<NameValuePair>(); param.add(new BasicNameValuePair("item", Item)); param.add(new BasicNameValuePair("category", Category)); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_select); try { httpPost.setEntity(new UrlEncodedFormEntity(param)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); // read content is = httpEntity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader br = new BufferedReader( new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } return null; } protected void onPostExecute(Void v) { String starTotal = null, starAvg = null; try { JSONArray jArray = new JSONArray(result); JSONObject json_data = null; for (int i = 0; i < jArray.length(); i++) { json_data = jArray.getJSONObject(i); starTotal = json_data.getString("TotalRating"); starAvg = json_data.getString("AverageRating"); } } catch (JSONException e1) { Log.e("log_tag", "Error in http connection " + e1.toString()); Toast.makeText(getActivity(), "JSONexception", Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } int total = 0; if (starTotal != null) { total = Integer.parseInt(starTotal); } else { starTotal = "0"; } if (total > 0) { total = Integer.parseInt(starTotal); } else { total = 0; } StarTotal = (TextView) getActivity().findViewById( R.id.tvStarTotal); StarTotal.setText("(" + String.valueOf(total) + (")")); float avg = 0.f; try { avg = Float.parseFloat(starAvg); } catch (NumberFormatException e) { avg = 0; } DecimalFormat myFormat = new DecimalFormat("0.00"); StarNumbers = (TextView) getActivity().findViewById( R.id.tvStarNumber); StarNumbers.setText(myFormat.format(avg)); ratingsBarTwo.setRating(Float.valueOf(avg)); progressDialog.dismiss(); } } </code></pre> |
23,275,948 | 0 | <p>I've seen such behavior before, it is probably tomcat and not ec2. Check the following:</p> <p>1- Your threading configuration (maxThreads and acceptCount). I've seen this behavior using the blocking connector when currentThreadsBusy > maxThreads. Check that you have enough threads or use the non-blocking (nio) connector.</p> <p>2- Check that your connection pool can reconnect lost connections automatically (autoReconnect=true in the jdbc url), your threads might be waiting db io on lost connections.</p> <p>Anyway, your ec2 instance is probably still working...</p> |
24,281,473 | 0 | How to disable the dropdownlist in DetailView depending on the date? <p>I'm using a <code>DropDownList</code> in the <code>DetailView</code> (EditMode) and I would like to disable it depending on the date of the system. For example : between the 18 June and the 20 June, make the dropdownlist <em>disabled</em> (gray).</p> <p>Any idea ?</p> |
15,200,646 | 0 | Get actual size of a gzip file in android <p>I am using GZIPInputStream to download pdf file I want to show the download progress of the file on a UI button. But, I am not getting the actual size of the file , what I am getting is compressed size due to which I am unable to show the correct download progress. This download progress is exceeding 100 as the actual file size is greater than the compressed size of file. Header content of file from server : - Following info I receive from server, from which I am using content-length which is giving compressed file size.</p> <p>1.Connection 2.Content-Encoding 3.Content-length 4.Content-Type 5.Keep-Alive 6.Server 7.Date</p> <p>Here is my code.</p> <pre><code> long fileLength = httpResponse.getEntity().getContentLength();// GZIPInputStream input = new GZIPInputStream(new BufferedInputStream(httpResponse.getEntity().getContent())); FileOutputStream output = new FileOutputStream(destinationFilePath); byte data[] = new byte[1024]; long total = 0; float percentage = 0; int count; currentDownloadingPercentage=0; while ((count = input.read(data)) != -1) { total += count; output.write(data, 0, count); // publishing the progress.... percentage = (float)total/(float)fileLength; percentage *= 100; if((int)percentage > (int)currentDownloadingPercentage) { currentDownloadingPercentage = percentage; Bundle resultData = new Bundle(); resultData.putBoolean(DOWNLOAD_FAILED, false); resultData.putInt(DOWNLOAD_PROGRESS ,(int)percentage); receiver.send(processID, resultData); resultData = null; } } </code></pre> |
16,994,894 | 0 | <p>try catching the array values in a reference:</p> <pre><code>MyClass &* item1 = *pointerArray + i; MyClass &* item2 = *pointerArray + i + 1; </code></pre> <p>then you shouldn't need to re-assign the values after the fact.</p> <p>EDIT: What you were doing is essentially making a copy to the pointers in item1, item2. Swapping them swapped the copies, but not the original. You could try omitting the copies and just doing something like this:</p> <pre><code>Swap(&(*pointerArray + i), &(*pointerArray + i + 1)); </code></pre> |
2,781,739 | 0 | Loading .eml files into javax.mail.Messages <p>I'm trying to unit test a method which processes <code>javax.mail.Message</code> instances.</p> <p>I am writing a converter to change emails which arrive in different formats and are then converted into a consistent internal format (<code>MyMessage</code>). This conversion will usually depend on the from-address or reply-address of the email, and the parts of the email, the subject, and the from- and reply-addresses will be required for creating the new <code>MyMessage</code>.</p> <p>I have a collection of raw emails which are saved locally as <code>.eml</code> files, and I'd like to make a unit test which loads the <code>.eml</code> files from the classpath and converts them to <code>javax.mail.Message</code> instances. Is this possible, and if so, how would it be done?</p> |
20,151,063 | 0 | Run app with a clean database everytime <p>I'm creating an app which uses a database.</p> <p>I'm refining the database, fixing errors and so on. But the <code>onCreate()</code> method of my helper is called only once. So, after the first test, the app's still using the old, and wrong database.</p> <p>I can implement the <code>onUpgrade()</code> method, but this seems odd to me, since I'm actually fixing errors and I'll find many of them. Is this the right way to do it? Playing with database version numbers?</p> <p>Is there any simpler method?</p> |
15,631,204 | 0 | Entity Framework Performance With Simple Insert is terrible <p>I am using EF 5 with code first against mySQL 5.5.25 with the 6.5.6 mySQL DotNet connector (However it is not the connector as the DevArt connector exhibits the same performance) and have an entity as follows:</p> <pre><code>public class SocialMediaEventEntity { public virtual int Id { get; set; } //PK public virtual DateTime Date{ get; set; } public virtual string ProvIdType{ get; set; } public virtual string ProviderId{ get; set; } public virtual int Rendered{ get; set; } public virtual int Sent{ get; set; } public virtual decimal UserId { get; set; } public virtual string UserName { get; set; } public virtual string UserScreenName { get; set; } public virtual string UserDescription { get; set; } public virtual ICollection<HistoryEntity> Messages { get; set; } } </code></pre> <p>It uses the following Code First to configure the keys etc.</p> <pre><code> HasKey(entity => entity.Id); Property(entity => entity.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired(); </code></pre> <p>Ultimately I am adding a single row to this table via:</p> <pre><code> var socialEvent = new SocialMediaEventEntity() { Date = ADate, ProviderId = AProviderId, ProvIdType = AProviderIdType, Rendered = ARendered, Sent = ASent, UserId = AUserId, UserName = AUserName ?? string.Empty, UserScreenName = AUserScreenName ?? string.Empty, UserDescription = AUserDescription ?? string.Empty, Messages = new List<HistoryEntity>() }; MyDBContext.SocialMediaEvents.Add(socialEvent); </code></pre> <p>Under the skin this generates the expected SQL of:</p> <pre><code>INSERT INTO tblSocialMediaEvents(`Date`, ProvIdType, ProviderId, Rendered, Sent, UserId, UserName, UserScreenName, UserDescription) VALUES ('2013-03-25 14:26:30', 'Twitter', '316028289447763968', 0, 0, 280310495, 'ChuBbyBhu', 'Komang Trinda Dewi', 'Always smile,,,but no crazy..:D\r All must be beautiful in its time' </code></pre> <p>Now the INSERT statement when profiled on my machine is very quick in the order of ~1ms, but the call to:</p> <pre><code>MyDBContext.SaveChanges(); </code></pre> <p>Takes anything from ~20 to ~40ms and occasionally > 100ms. </p> <p><img src="https://i.stack.imgur.com/cnDxf.png" alt="enter image description here"></p> <p>When I profile the code I see that its actually the transaction commit that is taking most of the time. However this is not the case when I do exactly the same SQL within a transaction into mySQL.</p> <p>So my questions are:</p> <ul> <li>How do I improve performance of this code? Aside from call SaveChanges() less often?</li> <li>Why is the transaction commit taking so much longer than when it is done executing the same code in a mySQL client tool like HeidiSQL?</li> </ul> <p>Appreciate any help and pointers.</p> <blockquote> <p>Edit: I have used the exact same code against SQL Server 2008 Express and performance is spectacular. Generally INSERTS are < ~1ms and the SaveChanges ~1ms. Naturally I would expect M$ products to be fast, but I am stuck with mySQL and cannot change. So is there anything I can do?</p> </blockquote> |
22,195,100 | 0 | Laravel 4 Migration has syntax error when adding Foreign Key <p>I'm trying to create a pivot table to hold some relationship data for some basic ACL functionality.</p> <p>The migration class:</p> <pre><code>Schema::create('group_user', function($table) { $table->increments('id'); $table->unsignedInteger('group_id'); $table->unsignedInteger('user_id'); $table->timestamps(); $table->softDeletes(); }); Schema::table('group_user', function($table) { $table->foreign('group_id') ->reference('id')->on('groups'); $table->foreign('user_id') ->reference('id')->on('users'); }); </code></pre> <p>After running the migration command, I get the following error:</p> <pre><code> [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at li ne 1 (SQL: alter table `group_user` add constraint group_user_group_id_foreign foreign key (`group_id`) references `groups` ()) </code></pre> <p>As you can see, the SQL syntax to add the foreign key constraint is missing the 'id' column name for the referenced table. Is this a bug in Laravel or is there something wrong with my schema code?</p> |
31,248,738 | 0 | <p>You may be running into <a href="https://bugs.php.net/bug.php?id=69874" rel="nofollow">Bug #69874 Can't set empty additional_headers for mail()</a> if you haven't done anything stupid (i.e. forgot to sanitize the headers).</p> <p>Test for the bug</p> <pre><code>$ php -d display_errors=1 -d display_startup_errors=1 -d error_reporting=30719 -r 'mail("[email protected]","Subject Here", "Message Here",NULL);' Warning: mail(): Multiple or malformed newlines found in additional_header in Command line code on line 1 </code></pre> <p>Alternately if you know your PHP version (hint: <code>php -v</code>) you can check <a href="http://php.net/ChangeLog-5.php" rel="nofollow">the changelog</a> for the bug number (69874) to see whether <a href="https://github.com/php/php-src/commit/dacea3f6fb3f84c79a3412b24547eb2c636754f6" rel="nofollow">the fix</a> has been applied for your version. </p> <p>A short-term fix is to replace calls to mail() like this</p> <pre><code> function fix_mail( $to , $subject , $message , $additional_headers =NULL, $additional_parameters=NULL ) { $to=filter_var($to, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES| FILTER_FLAG_STRIP_LOW| FILTER_FLAG_STRIP_HIGH); $subject=filter_var($subject, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES| FILTER_FLAG_STRIP_LOW| FILTER_FLAG_STRIP_HIGH); if (!$additional_headers) return mail( $to , $subject , $message ); if (!$additional_parameters) return mail( $to , $subject , $message , $additional_headers ); return mail( $to , $subject , $message , $additional_headers, $additional_parameters ); } </code></pre> |
8,031,029 | 0 | <p>To do this with multiple images you need to run though an <code>.each()</code> function. This works but I'm not sure how efficient it is.</p> <pre><code>$('img').hide(); $('img').each( function(){ $(this).on('load', function () { $(this).fadeIn(); }); }); </code></pre> |
16,622,087 | 0 | <p>In case someone is wondering what the complete solution looks like, here it is:</p> <pre><code><?php /** * in my case, the script was put in a subfolder of the project-root, called 'cron' * make sure you adjust this according to where you put it. */ chdir(dirname(__DIR__)); // Setup autoloading require 'init_autoloader.php'; Zend\Mvc\Application::init(require 'config/application.config.php'); /** * your code goes here */ echo date("d-m-Y H:i:s").": cron finished"; </code></pre> |
16,991,670 | 0 | <p>Or try to use the <strong>python-pexpect</strong> package instead of <strong>Subprocess</strong>. Much easier and friendly.</p> <pre><code>import pexpect mypassword='somepassword' child = pexpect.run('passwd guille') child.expect('Password:') child.sendline(mypassword) </code></pre> |
27,076,213 | 0 | <p>Each G-WAN script is compiled <em>separately</em>. As a result, all your variables are <em>static</em> (local to this module) - you cannot share them without using pointers and atomic operations.</p> <p>In order to ease the use of <em>global</em> variables, G-WAN provides persistent pointers (<code>US_HANDLER_DATA</code>, <code>US_VHOST_DATA</code>, or <code>US_REQUEST_DATA</code>):</p> <pre><code>void *pVhost_persistent_ptr = (void*)get_env(argv, US_VHOST_DATA); if(pVhost_persistent_ptr) printf("%.4s\n", pVhost_persistent_ptr); // get a pointer on a pointer (to CHANGE the pointer value) void **pVhost_persistent_ptr = (void*)get_env(argv, US_VHOST_DATA); if(pVhost_persistent_ptr) *pVhost_persistent_ptr = strdup("persistent data"); </code></pre> <p>Several examples, like <a href="http://gwan.ch/source/persistence.c" rel="nofollow">persistence.c</a> or <a href="http://gwan.ch/source/stream3.c" rel="nofollow">stream3.c</a> illustrate how to proceed with real-life programs.</p> |
30,809,773 | 0 | <p>You need to create a comparer that can compare tuples in such a way that the order of the items doens't matter:</p> <pre><code>public class UnorderedTupleComparer<T> : IEqualityComparer<Tuple<T, T>> { private IEqualityComparer<T> comparer; public UnorderedTupleComparer(IEqualityComparer<T> comparer = null) { this.comparer = comparer ?? EqualityComparer<T>.Default; } public bool Equals(Tuple<T, T> x, Tuple<T, T> y) { return comparer.Equals(x.Item1, y.Item1) && comparer.Equals(x.Item2, y.Item2) || comparer.Equals(x.Item1, y.Item2) && comparer.Equals(x.Item1, y.Item2); } public int GetHashCode(Tuple<T, T> obj) { return comparer.GetHashCode(obj.Item1) ^ comparer.GetHashCode(obj.Item2); } } </code></pre> <p>Note that an exclusive or of the hash codes is an operation that is going to have the same result regardless of the order of the operands, making it desirable here (but not in most hash code generating algorithms, as it's usually an <em>undesirable</em> property). As for <code>Equals</code>, one simply needs to check both possible pairings.</p> <p>Once you have that you can do:</p> <pre><code>var query = data.Distinct(new UnorderedTupleComparer<string>()); </code></pre> |
25,249,921 | 0 | <p>In the general case, you can redirect <code>stdout</code> to a file with the <code>></code> character:</p> <pre><code>your_program_name whatever arguments here > target.file ^^^^^^^^^^^^^ </code></pre> |
27,102,492 | 0 | <p>ASP.net 5 ( MVC 6) still available as preview edition. Also they have changed some major changes so Owin the way it support in ASP.net MVC 5 will not support same way. As they have changed basic interface that support that functionality but today I came across article they provide information how can we use old Owin and integrate in ASP.net MVC 6. </p> <p><a href="http://blogs.msdn.com/b/webdev/archive/2014/11/14/katana-asp-net-5-and-bridging-the-gap.aspx" rel="nofollow">http://blogs.msdn.com/b/webdev/archive/2014/11/14/katana-asp-net-5-and-bridging-the-gap.aspx</a></p> |
31,019,283 | 0 | <p>In your code <code>"pol1"</code> is called a <a href="https://en.wikipedia.org/wiki/String_literal" rel="nofollow"><em>string literal</em></a>. During compilation time, this data is stored into some memory area (<em>usually read-only memory, which cannot be altered, or atleast any attempt to alter the contents will result in <a href="https://en.wikipedia.org/wiki/Undefined_behavior" rel="nofollow">UB</a></em>) which is allocated by the compiler itself. </p> <p>When you use it, you essentially pass the base address of the string literal and collect it into a <code>char *</code> ( same as <code>char []</code> in case of usage in function parameter). There is no need for any allocation from your side.</p> |
31,731,212 | 0 | VS2013 Import Namespace "syntax error" <p>I am customizing a WSDL help file for a webservice. Currently on my .aspx I have a bunch of imports at the top:</p> <pre><code><%@ Import Namespace="System.Collections" %> <%@ Import Namespace="System.IO" %> <%@ Import Namespace="System.Xml.Serialization" %> <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.Xml.Schema" %> <%@ Import Namespace="System.Web.Services" %> </code></pre> <p>The error list current has 102 errors (the maximum it can display) and they all point to line 1 (see above, System.Collections) with many different errors like "syntax error", "end of statment expected" and "declaration expected". </p> <p>The service still works fine, and the namespaces are all being used properly. Should the namespaces be moved elsewhere? I want to handle this properly but couldn't find any information.</p> |
10,382,834 | 0 | <p><a href="http://developers.facebook.com/docs/reference/javascript/FB.login/" rel="nofollow"><code>FB.login</code></a> and <code>FB.api</code> doesn't provide you success/failure reporting just like you trying to implement it. There is no second argument for callbacks...</p> <p><code>FB.login</code> callback get one and only argument:</p> <blockquote> <p>response from <a href="http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/" rel="nofollow"><code>FB.getLoginStatus</code></a>, <a href="http://developers.facebook.com/docs/reference/javascript/FB.login/" rel="nofollow"><code>FB.login</code></a> or <a href="http://developers.facebook.com/docs/reference/javascript/FB.logout" rel="nofollow"><code>FB.logout</code></a>. This response object contains:</p> <p><strong>status</strong><br> The status of the User. One of connected, not_authorized or unknown.<br> <strong>authResponse</strong><br> The authResponse object.</p> </blockquote> <p><code>FB.api</code> callback get one and only arguments which is response from Graph API usually (but not always) containing <code>data</code> property, object fields, boolean false or <code>error</code> object (with <code>message</code>, <code>type</code> and <code>code</code> properties)</p> <hr> <p>You can modify your <code>loginHandler</code> by correction of response callbacks to take care of right arguments:</p> <pre><code>function loginHandler(loginResponse){ try{ if(loginResponse.authResponse){ alert('i am if'); FB.api('/me', function(response) { alert("first name == " + response.first_name + "\n ln === " + response.last_name); }); } }catch(error){} } </code></pre> |
27,485,859 | 0 | <p>It is not specific to Bootstrap.</p> <p>Here is a solution using jQuery (works for bootstrap or non-bootstrap login box) :</p> <pre><code>$('.dropdown').on('mouseover', function () { $('.dropdown-menu', this).show(); }).on('mouseout', function (e) { if (!$(e.target).is('input')) { $('.dropdown-menu', this).hide(); } }); </code></pre> <p>thanks to dtrunks for this solution : <a href="http://stackoverflow.com/questions/19727671/div-disappears-when-hovering-the-input-autocomplete-in-firefox">Div disappears when hovering the input autocomplete in Firefox</a></p> |
7,673,132 | 0 | <p>That's Helvetica Neue Light. You can find out this information using Firebug (Firefox) or Web Inspector (Chrome and Safari).</p> <p>Right-click the element on the page you are interested in and then click 'Inspect Element':</p> <p><img src="https://i.stack.imgur.com/5eJJl.png" alt="enter image description here"></p> <p>Then you will be able to see all of the attributes of that element:</p> <p><img src="https://i.stack.imgur.com/mdBtR.png" alt="enter image description here"></p> |
8,084,770 | 0 | <p>Both <a href="http://www.openssl.org/" rel="nofollow">OpenSSL</a> and <a href="http://www.gnu.org/software/gnutls/" rel="nofollow">GnuTLS</a> provide full X.509/SSL/TLS cryptographic functionality, while also supporting smart cards via the <a href="http://www.opensc-project.org/opensc" rel="nofollow">OpenSC</a> library.</p> <p>I am not sure what authenticating against an SSH server implies, but you may want to have a look at the <a href="http://www.openssh.com/" rel="nofollow">OpenSSH</a> project.</p> |
34,112,530 | 0 | <p>More elegant with shorter and more readable using <code>java.util.Random</code> and <code>IntStream</code></p> <pre><code>Random random = new Random(); random.ints(10, 0, 10000).boxed().forEach(randomIntegers::add); </code></pre> |
5,508,588 | 1 | Add and Compare Datetime in Python <p>How do I write this pseudocode in Python? With 'created_date' being a datetime object.</p> <pre><code>if (created_date + 30days) < now: print 'valid' else: print 'expired' </code></pre> |
8,516,141 | 0 | Best approach for implementing Backbone js and jQuery <p>Can some one help me to find the best approach? Its is documentcloud.</p> <p>References between Models and Views can be handled several ways. </p> <ol> <li>Direct pointers, where views correspond 1:1 with models (model.view and view.model). </li> <li>Intermediate "controller" objects that orchestrate the creation and organization of views into a hierarchy. </li> <li>Evented approach, which always fire events instead of calling methods directly. </li> </ol> <p>Thanks!</p> |
13,462,999 | 0 | <p>Dates in SQL are represented as #year/month/day#, eg. today's date would be #2012/11/19#, and to make DLookup work you have to use this syntax:</p> <pre><code>DLookup("HolidayDate", "Holidays", "HolidayDate=" & Format([EncDateTime],"\#yyyy/mm/dd\#")) </code></pre> <p>to check if today is holiday, you could use this:</p> <pre><code>DLookup("HolidayDate", "Holidays", "HolidayDate=" & Format(Date(),"\#yyyy/mm/dd\#")) </code></pre> <p>Yes, DLookup is slow, you should not use it in a query. To check if <code>EncDateTime</code> is a holiday, you should join <code>EncData</code> and <code>Holidays</code> togheter, with this SQL Code:</p> <pre><code>SELECT EncData.* FROM EncData INNER JOIN Holidays ON EncData.EncDateTime = Holidays.HolidayDate </code></pre> <p>This should return all EncData rows that are hoildays. It should, but it probably doesn't. Notice that EncDateTime contains not only the date, but also the time, so it doesn't match with HolidayDate that contains just the date. This works instead:</p> <pre><code>SELECT EncData.* FROM EncData INNER JOIN Holidays ON DateValue(EncData.EncDateTime) = Holidays.HolidayDate </code></pre> <p>And to extract all the rows in EncData, not just the holidays?</p> <pre><code>SELECT EncData.*, Holidays.HolidayDate FROM EncData LEFT JOIN Holidays ON DateValue(EncData.EncDateTime) = Holidays.HolidayDate </code></pre> <p>Notice that when HolidayDate contains a date only when that day is holiday, otherwise it will be NULL.</p> <p>These are just some basic ideas to start. But don't forget that you cans use wizards to make your query, then you can always see how your SQL code looks like.</p> |
28,321,897 | 0 | <p>Using <a href="http://stackoverflow.com/a/28315502/1499016">Alex's answer</a> I was able to move multiple issues from one sprint to another. Adding step by step incase it helps anyone else.</p> <ol> <li>Filter all the open, in progress, blocked and submitted issues with the following command: <code>Sprint: {oldSprint} State: Submitted State: Open State: {In Progress} State: Blocked</code></li> <li>On the issue list select all the issues - thanks Alex</li> <li>Click the command dialog button in the header, and select open command dialog.</li> <li>In the command dialog type <code>Sprint Unscheduled Sprint newSprint</code>. This'll first unassign the issue from the old sprint then assign it to the new sprint.</li> </ol> |
9,290,010 | 0 | Database query to JsonArray <p>I´m getting data from a database, the query works in the correct way, but I want to save that data in JsonArray.</p> <pre><code>while(rset.next()){ for(int i=0;i<numeroColumnas;i++){ json.addProperty(key[0], rset.getInt(key[0])); json.addProperty(key[1], rset.getString(key[1])); json.addProperty(key[2], rset.getString(key[2])); json.addProperty(key[3], rset.getInt(key[3])); json.addProperty(key[4], rset.getDouble(key[4])); json.addProperty(key[5], rset.getDouble(key[5])); } ajson.add(json); System.out.println("Cadena JSON:" +ajson.toString()); </code></pre> <p>}</p> <p>This code generates an incorrect output, I get repeat values:</p> <blockquote> <p>Cadena JSON:[{"IDCOORD":1,"HORA":"2012-02-13 07:58:06.146","FECHA":"2012-02-13 >07:58:03","COOR_IDEQUIPO":1,"LATITUD":28.56245,"LONGITUD":-16.7000555}]</p> <p>[{"IDCOORD":2,"HORA":"2012-02-13 07:59:41.881","FECHA":"2012-02-13 >07:59:39","COOR_IDEQUIPO":1,"LATITUD":-4.7152449,"LONGITUD":41.6514567}, {"IDCOORD":2,"HORA":"2012->02-13 07:59:41.881","FECHA":"2012-02-13 >07:59:39","COOR_IDEQUIPO":1,"LATITUD":->4.7152449,"LONGITUD":41.6514567}]</p> </blockquote> <p>I´m pretty sure that I´m doing something wrong on while. Thanks in advance!</p> |
1,191,936 | 1 | Is it possible to install SSL on Google app engine for iPhone application? <p>I am using python language for google app engine based iphone application .I want to install/access ssl on python. I am unable to find a way to install/enable it in python file. please guide me how can I make my application to connect to ssl As I want to Apple enable push notification services on my application Its urgent.</p> |
35,703,857 | 0 | Get files from remotePath that are not in localPath using C# <p>I am using WINSCP functionality with an SSIS script task to move files from a remotePath to a localPath. I am also setting these files to readonly using: </p> <pre><code>File.SetAttributes(LocalPath, FileAttributes.ReadOnly); </code></pre> <p>This works to set the attributes, it is just that since I have pulled some data from the remotePath that is already on the localPath, the readonly attribute gets set back to 0 and the archive attribute gets set to 1.</p> <p>Is there an easy way that I can just pull the files from the remotePath that aren't already in the localPath?</p> <p>This would eliminate any overwriting of files and also fix my readonly / archive attributes situation</p> |
27,365,231 | 1 | Write a program (or algorithm) in python which breaks up a string of texts into even and odd characters <pre><code>def breakString(str): i = 0 even = [] odd = [] for char in str if (i%2==0) even.push(char) else odd.push(char) </code></pre> <p>For some reason, this is not running in my python.</p> |
11,718,748 | 0 | <p>You can use generic tags on chunks:</p> <ol> <li>Set the tag on relevant chunks</li> <li>Create a class that extends <code>PdfPageEventHelper</code> and add it to the writer</li> <li>Write the code that makes the underlining job on the <code>onGenericTag</code> method </li> <li>In the <code>onGenericTag</code> method you have the surrounding rect of the chunk: you can draw a line directly on the PdfContentByte using a dashed style or whatever style you desire.</li> </ol> |
30,881,224 | 0 | <p>I would also add that transactional databases are meant to hold current state and oftentimes do so to be self-maintaining. You don't want transactional databases growing beyond their necessary means. When a workflow or transaction is complete then move that data out and into a Reporting database, which is much better designed to hold historical data.</p> |
23,845,558 | 0 | <p>If your program is a GUI then it is a good idea to run the serial port code in a separate worker thread. ReadFile can take a long time to get serial data and this would block the GUI message processing if it was done in the main thread. To provide notification events from the serial thread to the main (GUI) thread you can use PostMessage with a user-defined message. An example of doing this is at<br> <a href="http://vcfaq.mvps.org/mfc/12.htm" rel="nofollow">http://vcfaq.mvps.org/mfc/12.htm</a></p> |
10,924,433 | 0 | <pre><code>scala> val s = "<myapp><username>bill</username><password>secret123</password><background>#FFFFFF</background></myapp>" s: java.lang.String = <myapp><username>bill</username><password>secret123</password><background>#FFFFFF</background></myapp> scala> val e = xml.XML.loadString(s) e: scala.xml.Elem = <myapp><username>bill</username><password>secret123</password><background>#FFFFFF</background></myapp> scala> val sp = new sys.SystemProperties sp: scala.sys.SystemProperties = Map(env.emacs -> "", java.runtime.name -> Java(TM) SE Runtime Environment, ....) scala> sp ++= e.child.map(n => (e.label + "." + n.label, n.text)) res11: sp.type = Map(env.emacs -> "", java.runtime.name -> Java(TM) SE Runtime Environment, ...) </code></pre> <p>Sanity check:</p> <pre><code>scala> val p = java.lang.System.getProperties p: java.util.Properties = {env.emacs=, java.runtime.name=Java(TM) SE Runtime Environment,...} scala> import collection.JavaConversions._ import collection.JavaConversions._ scala> p filter { case (k, v) => k.startsWith("myapp") } \ foreach { case (k,v) => println(k + "=" + v) } myapp.password=secret123 myapp.background=#FFFFFF myapp.username=bill </code></pre> |
19,935,800 | 0 | <p>One of several places this topic has been discussed is <a href="http://stackoverflow.com/questions/19863952/xml-schema-maxoccurs-within-choice-element/19871075">this StackOverflow question</a>. </p> <p>You need a simple regular language over c1 and c2. The automaton you might write has two states: an initial state, in which no c2 has been encountered in the input, and in which c1 and c2 are accepted, and a second state in which c2 has been seen, and in which only c1 is accepted. This language can be described by the regular expression <code>(c1*c2c1*)</code>, or by the content model</p> <pre><code><xs:sequence> <xs:element ref="c1" minOccurs="0" maxOccurs="unbounded"/> <xs:element ref="c2"/> <xs:element ref="c1" minOccurs="0" maxOccurs="unbounded"/> </xs:sequence> </code></pre> <p>A more general form of the question (with two required elements) is described in <a href="http://stackoverflow.com/questions/2290360/xsd-how-to-allow-elements-in-any-order-any-number-of-times/12012599#12012599">this answer to a related SO question</a>. As the number of required elements rises, the content model experiences combinatorial explosion; in those cases, the all-groups of XSD 1.1 are much more convenient.</p> |
42,604 | 0 | <p>NHaml is my favorite for its terseness. People either love it or hate it, given that it looks very different from a traditional "HTML with inserted code" template system like ASPX or NVelocity.</p> <p><strong>Edit:</strong></p> <p>@Ben,</p> <p>There are other view engines which compile down (NHaml is one), so those do support custom HTML helpers. I wouldn't be surprised to see the currently interpreted view engines all eventually end up with a compilation model eventually.</p> |
29,124,053 | 0 | <p>Everytime a user selects a timerange, it creates a kind of <a href="http://fullcalendar.io/docs/selection/selectHelper/" rel="nofollow">placeholder</a> event for visual feedback to the user. This isn't actually an event yet, and it is removed when the user makes another selection.</p> <p>What you need to do, is add an actual event whenever a selection is made.</p> <p>Use the <a href="http://fullcalendar.io/docs/selection/select_callback/" rel="nofollow">select callback</a>.</p> <p>It's triggered every time the user selects (clicks and drags) a time slot. In it, call <a href="http://fullcalendar.io/docs/event_data/addEventSource/" rel="nofollow">addEventSource</a> to add it to the calendar as an actual event. And then call <a href="http://fullcalendar.io/docs/selection/unselect_callback/" rel="nofollow">unselect</a> to manually remove the placeholder.</p> <pre><code>select: function (start, end, jsEvent, view) { $("#calendar").fullCalendar('addEventSource', [{ start: start, end: end, }, ]); $("#calendar").fullCalendar("unselect"); } </code></pre> <p><a href="http://fiddle.jshell.net/slicedtoad/qp6Lxshp/3/" rel="nofollow">JSFiddle</a></p> |
27,083,155 | 0 | Does a HTTP resource that accepts range requests always specify content-length? <p>Before starting a range request, I first check if it is supported using a HEAD request. Normally I get back something like this:</p> <pre><code>curl -X HEAD -i http://bits.wikimedia.org/images/wikimedia-button.png HTTP/1.1 200 OK ... Content-Length: 2426 Accept-Ranges: bytes ... </code></pre> <p>Is the Content-Length guaranteed per the HTTP/1.1 specification in this case? I can't find a definitive answer but it seems like I would need to know the Content-Length before I do a Range request.</p> |
15,897,163 | 0 | <p>I made it! I found a nice tool for correct handling *.jpg files on Android platform with uncommon colorspaces like CMYK, YCCK and so on. Use <a href="https://github.com/puelocesar/android-lib-magick" rel="nofollow">https://github.com/puelocesar/android-lib-magick</a>, it's free and easy to configure android library. Here is a snippet for converting CMYK images to RGB colorspace:</p> <pre><code>ImageInfo info = new ImageInfo(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cmyk.jpg"); MagickImage imageCMYK = new MagickImage(info); Log.d(TAG, "ColorSpace BEFORE => " + imageCMYK.getColorspace()); boolean status = imageCMYK.transformRgbImage(ColorspaceType.CMYKColorspace); Log.d(TAG, "ColorSpace AFTER => " + imageCMYK.getColorspace() + ", success = " + status); imageCMYK.setFileName(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cmyk_new.jpg"); imageCMYK.writeImage(info); Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Docs/cmyk_new.jpg"); if (bitmap == null) { //if decoding fails, create empty image bitmap = Bitmap.createBitmap(imageCMYK.getWidth(), imageCMYK.getHeight(), Config.ARGB_8888); } ImageView imageView1 = (ImageView) findViewById(R.id.imageView1); imageView1.setImageBitmap(bitmap); </code></pre> |
29,157,138 | 0 | Android Eclipse application, compatible error <p>I'm developing Android app just for hobby, and I made an app, when I test on my phones works well, I tested on :</p> <ul> <li>Alcatel idol OneTouch 2S ( 6050y )</li> <li>Sony Xperia Tipo ( st21i )</li> <li>Samsung Galaxy Ace</li> <li>Asus Memo Pad HD7 (Tablet)</li> </ul> <p>Works great, and no error at all... but when I tested on Samsung Galaxy S4, and Samsung Galaxy S3.. no background music (on Galaxy S4 and no background pics are shown ), and what I click I see report error message so application crushes..</p> <p>Error Log:</p> <pre><code>03-20 16:55:07.366: D/skia(29417): --- allocation failed for scaled bitmap 03-20 16:55:07.376: D/AndroidRuntime(29417): Shutting down VM 03-20 16:55:07.376: W/dalvikvm(29417): threadid=1: thread exiting with uncaught exception (group=0x4206c700) 03-20 16:55:07.391: E/AndroidRuntime(29417): FATAL EXCEPTION: main 03-20 16:55:07.391: E/AndroidRuntime(29417): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.**********a/com.***********a.Info}: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown> 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.access$700(ActivityThread.java:159) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.os.Handler.dispatchMessage(Handler.java:99) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.os.Looper.loop(Looper.java:176) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.main(ActivityThread.java:5419) 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Method.invokeNative(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Method.invoke(Method.java:525) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) 03-20 16:55:07.391: E/AndroidRuntime(29417): at dalvik.system.NativeStart.main(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class <unknown> 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.createView(LayoutInflater.java:626) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.inflate(LayoutInflater.java:470) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.inflate(LayoutInflater.java:398) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.inflate(LayoutInflater.java:354) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:361) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.Activity.setContentView(Activity.java:1956) 03-20 16:55:07.391: E/AndroidRuntime(29417): at *********.Info.onCreate(Info.java:16) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.Activity.performCreate(Activity.java:5372) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257) 03-20 16:55:07.391: E/AndroidRuntime(29417): ... 11 more 03-20 16:55:07.391: E/AndroidRuntime(29417): Caused by: java.lang.reflect.InvocationTargetException 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Constructor.constructNative(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Constructor.newInstance(Constructor.java:417) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.createView(LayoutInflater.java:600) 03-20 16:55:07.391: E/AndroidRuntime(29417): ... 23 more 03-20 16:55:07.391: E/AndroidRuntime(29417): Caused by: java.lang.OutOfMemoryError 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:596) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:832) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.content.res.Resources.loadDrawable(Resources.java:2988) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.content.res.TypedArray.getDrawable(TypedArray.java:602) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.View.<init>(View.java:3563) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.ViewGroup.<init>(ViewGroup.java:475) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.widget.LinearLayout.<init>(LinearLayout.java:176) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.widget.LinearLayout.<init>(LinearLayout.java:172) 03-20 16:55:07.391: E/AndroidRuntime(29417): ... 26 more </code></pre> <p>Please any help ?</p> |
35,296,774 | 0 | <p>All commands from menu have a command-name callable via M-x COMMAND RET. In this case M-x <code>python-send-region</code> RET</p> |
2,487,243 | 0 | <p>You could just use wget's <code>-N</code> and <code>-c</code> options and remove the entire "if file exists" logic.</p> |
27,610,914 | 0 | <p>It does not just happen for ng-repeat, this seems to happen for any other directives that creates a scope like <code>ng-if</code> as well. And it seems like, this is because the directive's isolated scope gets overwritten by the ng-repeat's child scope. And because of <code>replace:true</code> option ng-repeat becomes a part of the directive source element i.e <code><foo></foo></code> and the child scope of ng-repeat is calculated from the ultimate parent scope <code>MainCtrl</code> (Which appears to be wrong) and this causes the entire directive template to be bound to the child scope of controller and any interpolations are evaluated against that scope. Hence you see main controller's scope being expanded in the directive. This seems like a bug.</p> |
17,196,396 | 0 | PEAR and absolute paths <p>In <a href="http://stackoverflow.com/questions/15516575/why-doesnt-pear-use-absolute-paths">why doesn't PEAR use absolute paths?</a> it's stated that PEAR doesn't use absolute paths so people can overwrite select PEAR libs with their own. Is that the only reason? And if so is there any evidence that people actually do that?</p> <p>I mean, it seems like using absolute paths would resolve a lot of issues people have with using PEAR libs and if the only reason for not using absolute paths is a use-case that no one actually utilizes it seems like PEAR would be better off using them.</p> <p>(I don't consider this question a duplicate but more as a followup; posting in the other question likely wouldn't get me any responses since that question's already been answered, so I post this new question)</p> |
36,494,038 | 0 | Is a variable declared under Grails(1.3.6) controller action and class variable thread safe? <p>Is a variable declared under Grails(1.3.6) controller action and class variable thread safe? i.e</p> <pre><code>class TestController { String y //Is y thread-safe? def testAction = { String x //Is x thread-safe? } } </code></pre> |
13,656,801 | 0 | <p>Create a recursive function:</p> <p>Semi-psuedo:</p> <pre><code>function dumpArr (arr){ foreach element in arr { if element is array/object{ dumpArr(element) }else{ echo element } } } </code></pre> <p>then, you can use CSS to adjust the padding, margin, etc</p> |
17,444,628 | 0 | <p>you can use <code>explode</code> to convert the string to an array using a delimeter.</p> <p>for example </p> <pre><code> $array = explode(",", $string); </code></pre> |
21,667,322 | 0 | <p><code>tapply</code> and <code>transform</code>?</p> <pre><code>> transform(df, volumen=unlist(tapply(cumVol, farm, function(x) c(0, diff(x))))) period farm cumVol other volumen A1 1 A 1 1 0 A2 2 A 5 2 4 A3 3 A 15 3 10 A4 4 A 31 4 16 B1 1 B 10 5 0 B2 2 B 12 6 2 B3 3 B 16 7 4 B4 4 B 24 8 8 </code></pre> <p><code>ave</code> is a better option, see @ thelatemail's comment</p> <pre><code>with(df, ave(cumVol,farm,FUN=function(x) c(0,diff(x))) ) </code></pre> |
12,623,852 | 0 | Drupal 7 date/text field issue <p>I have a content type in Drupal that is a text field that holds a date that the user types in. No, its not an actual date field unfortunately (ugghhh). What I need to do is make a view that has an exposed field that can pull content that is between 2 dates. For example I want to get all of the nodes who's date field is between 2012-09-01 and 2012-09-30. </p> <p>I'm guessing I could convert these fields using a computed field with <code>strtotime()</code>. But the problem I would run into is not being able to filter between 2 times (basically 2 strings of numbers) in an exposed filter. Is there a way to do that?</p> |
40,479,961 | 0 | <p>Here is the code for Swift3:</p> <pre><code>func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? { let infoWindow = Bundle.main.loadNibNamed("InfoWindow", owner: self, options: nil)?.first as! CustomInfoWindow infoWindow.name.text = ""Sydney Opera House" infoWindow.address.text = "Bennelong Point Sydney" infoWindow.photo.image = UIImage(named: "SydneyOperaHouseAtNight") return infoWindow } </code></pre> |
31,393,249 | 0 | <p>You can create custom commands for that: <a href="http://nightwatchjs.org/guide#writing-custom-commands">http://nightwatchjs.org/guide#writing-custom-commands</a></p> <ol> <li>in nightwatch.json specify the path to the folder that will contain your custom command file</li> <li>create a js file and name it how your custom command should be names (ie login.js)</li> <li>write the code you need:</li> </ol> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>exports.command = function(username, password) { this .waitForElementVisible('#password', 4000) .setValue('#password', password) .waitForElementVisible('#username', 1000) .setValue('#username', username) .waitForElementVisible('#sign_in', 1000) .click('#sign_in') .waitForElementVisible('h1.folder-title', 10000) return this; };</code></pre> </div> </div> </p> <ol start="4"> <li>use the custom command in your test:</li> </ol> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>.login("your_username", "your_password")</code></pre> </div> </div> </p> |
38,067,446 | 0 | <p><code>Enumerable#group_by</code> is a useful tool, but in this case it's not the best one.</p> <p>If we start with a Hash whose default value is <code>[0, 0]</code> we can do (almost) everything—look up the month (or get the default value of it's a new month) and add 1 to the appropriate index (<code>0</code> for false and <code>1</code> for true)—in a single step:</p> <pre><code>array = [["June", false], ["June", false], ["June", false], ["October", false]] hsh = Hash.new {|h,k| h[k] = [0,0] } array.each {|mo, bool| hsh[mo][bool ? 1 : 0] += 1 } p hsh.map(&:flatten) # => [["June", 3, 0], ["October", 1, 0]] </code></pre> |
29,603,764 | 0 | using shared peferences to save colors <p>I have an app that uses a color picking dialog to change the app background color, and the text color. The color picker works fine, but when the app closes for any reason it reverts back to default. </p> <p>I have checked: <a href="http://developer.android.com/guide/topics/data/data-storage.html#pref" rel="nofollow">http://developer.android.com/guide/topics/data/data-storage.html#pref</a> and <a href="http://stackoverflow.com/questions/23024831/android-shared-preferences-example">Android Shared preferences example</a></p> <p>the below code is the result of my research. The problem I'm having is all my text fields start off without text color, when i use the color dialog the colors change just fine, but are not saved. </p> <p>Any pointers on where I'm going wrong would be greatly appreciated.</p> <pre><code>public class TipCalculator extends ActionBarActivity implements ColorPickerDialog.OnColorChangedListener { //UI element objects to be manipulated. TextView tipper; TextView diner; /*few TextView items left out to save space*/ int color; RelativeLayout RLayout; private SharedPreferences preferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tip_calculator); preferences = getSharedPreferences("TipCalculator", MODE_PRIVATE); //color = preferences.getInt("TipCalculator", color); did not change anything color = preferences.getInt("bg_color", color); RLayout = (RelativeLayout) findViewById(R.id.RLayout);//layout object for background color manipulation bill = (EditText) findViewById(R.id.bill_amount_text);//UI elements placed in objects for text color manipulation billNtip = (TextView) findViewById(R.id.bill_tip_text); /*few TextView items left out to save space*/ bill.setSelection(bill.getText().length()); bill.addTextChangedListener(billWatcher); } @Override public void onPause(){// onStop does not seem to change how the app currently runs super.onPause(); /*preferences = getSharedPreferences("TipCalculator", MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); does not work*/ SharedPreferences.Editor editor = getSharedPreferences("TipCalculator", MODE_PRIVATE).edit(); //editor.putInt("TipCalculator", color); does not change anything editor.putInt("bg_color", color); editor.commit(); tipper.setTextColor(color); bill.setTextColor(color); /*few TextView items left out to save space*/ } @Override public void colorChanged(String key, int color) { color = newColor; if (decide.equals("font")) { tipper.setTextColor(color); bill.setTextColor(color); /*few TextView items left out to save space*/ } else if (decide.equals("background")) { RLayout.setBackgroundColor(color); } } </code></pre> |
39,483,265 | 0 | Mapping Error in Hibernate <p>I have prepared an application in Spring Boot</p> <p>I have implemented oneToOne mapping in hibernate between two tables :</p> <p>person and PersonDetail.</p> <p>Now, when I run the program, I get the <strong>following error</strong> :</p> <p>Neither binding result, nor model object available for 'person'.</p> <p>The error is in personform.html , on the fields address and age.</p> <p>//////////////////////////////Controller///////////////////////////////</p> <pre><code>package com.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.model.Person; //import com.model.PersonDetail; import com.service.PersonService; @Controller public class PersonController { Person person = new Person(); private PersonService personService; @Autowired public void setPersonService(PersonService personService) { this.personService = personService; } @RequestMapping(value = "/persons", method = RequestMethod.GET) public String list(Model model){ model.addAttribute("persons", personService.listAllPersons()); System.out.println("Returning Persons"); return "persons"; } @RequestMapping("person/{id}") public String showPerson(@PathVariable Integer id, Model model){ model.addAttribute("person", personService.getPersonById(id)); return "personshow"; } @RequestMapping("person/edit/{id}") public String edit(@PathVariable Integer id, Model model){ model.addAttribute("person", personService.getPersonById(id)); return "personform"; } @RequestMapping("person/new") public String newPerson(Model model){ model.addAttribute("person", new Person()); return "personform"; } @RequestMapping(value = "person", method = RequestMethod.POST) public String savePerson(Person person){ personService.savePerson(person); return "redirect:/persons/"; } @RequestMapping("person/delete/{id}") public String delete(@PathVariable Integer id){ personService.deletePerson(id); /*return "redirect:/products";*/ //return "persons"; return "redirect:/persons/"; } } </code></pre> <p>////////////////////////Person-Model///////////////////////////////</p> <pre><code>package com.model; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity //@Table(name = "person") public class Person{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id",unique=true,nullable=false) private Integer id; @Column(name = "name", unique = true, nullable = false, length = 10) private String name; @OneToOne(cascade= CascadeType.ALL) private PersonDetail personDetail; /* public Person(){} public Person(Integer id,String name) { this.id=id; this.name=name; }*/ public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public PersonDetail getPersonDetail() { return personDetail; } public void setPersonDetail(PersonDetail personDetail) { this.personDetail = personDetail; } } </code></pre> <p>////////////////////////////PersonDetail-Model//////////////////////</p> <pre><code>package com.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; @Entity public class PersonDetail{ @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @Column(name = "address", nullable = false, length = 20) private String address; @Column(name = "age", nullable = false,length=10) private Integer age; @OneToOne @PrimaryKeyJoinColumn private Person person; /* public PersonDetail() { } public PersonDetail(Integer id,String address,Integer age) { this.id=id; this.address=address; this.age=age; }*/ public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } } </code></pre> <p>/////////////////////////////PersonRepository//////////////////////</p> <pre><code>package com.repository; import javax.transaction.Transactional; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.model.Person; @Repository @Transactional public interface PersonRepository extends CrudRepository<Person, Integer>{ } </code></pre> <p>//////////////////////PersonDetailReppository/////////////////////</p> <pre><code>package com.repository; import javax.transaction.Transactional; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.model.PersonDetail; @Repository @Transactional public interface PersonDetailRepository extends CrudRepository<PersonDetail, Integer>{ } </code></pre> <p>/////////////////////////////////index.html/////////////////////</p> <pre><code><!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head lang="en"> <title>Spring Boot Example</title> <!-- <th:block th:include="fragments/headerinc :: head"></th:block> --> </head> <body> <div class="container"> <div th:fragment="header"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#" th:href="@{/}">Home</a> <ul class="nav navbar-nav"> <li><a href="#" th:href="@{/persons}">Persons</a></li> <li><a href="#" th:href="@{/person/new}">Create Person</a></li> </ul> </div> </div></nav></div> <!-- <div class="container"> --> <!-- <th:block th:include="fragments/header :: header"></th:block> --> </div> </body> </html> </code></pre> <p>/////////////////////////persons////////////////////////////</p> <pre><code><!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head lang="en"> <title>Persons</title> <th:block th:include="fragments/headerinc :: head"></th:block> </head> <body> <div class="container"> <!-- <th:block th:include="fragments/header :: header"></th:block> /*/ --> <div th:if="${not #lists.isEmpty(persons)}"> <h2>Person List</h2> <table class="table table-striped"> <tr> <th>Id</th> <th>Person Id</th> <th>Name</th> <th>Address</th> <th>Age</th> <th>View</th> <th>Edit</th> <th>Delete</th> </tr> <tr th:each="person : ${persons}"> <td th:text="${person.id}"><a href="/person/${person.id}">Id</a></td> <td th:text="${person.id}">Person Id</td> <td th:text="${person.name}">Name</td> <td th:text="${person.personDetail.address}">Address</td> <td th:text="${person.personDetail.age}">Age</td> <td><a th:href="${ '/person/' + person.id}">View</a></td> <td><a th:href="${'/person/edit/' + person.id}">Edit</a></td> <td><a th:href="${'/person/delete/' + person.id}">Delete</a></td> </tr> </table> </div> </div> </body> </html> </code></pre> <p>////////////////////////////////////personform/////////////////////</p> <pre><code><!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head lang="en"> <title>Spring Boot Example</title> <th:block th:include="fragments/headerinc :: head"></th:block> </head> <body> <div class="container"> <th:block th:include="fragments/header :: header"></th:block> <h2>Person Details</h2> <div> <!-- th:object="${person}" --> <form class="form-horizontal" th:action="@{/person}" method="post"> <input type="hidden" th:field="*{person.id}"/> <!-- <div class="form-group"> <label class="col-sm-2 control-label">Person Id:</label> <div class="col-sm-10"> <input type="text" class="form-control" th:field="*{id}"/> </div> </div> --> <div class="form-group"> <label class="col-sm-2 control-label">Name:</label> <div class="col-sm-10"> <input type="text" class="form-control" th:field="*{person.name}"/> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Address:</label> <div class="col-sm-10"> <input type="text" class="form-control" th:field="*{person.address}"/> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Age:</label> <div class="col-sm-10"> <input type="text" class="form-control" th:field="*{person.age}"/> </div> </div> <div class="row"> <button type="submit" class="btn btn-default">Submit</button> </div> </form> </div> </div> </body> </html> </code></pre> <p>///////////////////////////////////personshow///////////////////////</p> <pre><code><!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head lang="en"> <title>Person Details</title> <th:block th:include="fragments/headerinc :: head"></th:block> </head> <body> <div class="container"> <!--/*/ <th:block th:include="fragments/header :: header"></th:block> /*/--> <h2>Person Details</h2> <div> <form class="form-horizontal" th:action="@{/person}" th:object="${person}" method="get"> <div class="form-group"> <label class="col-sm-2 control-label">Person Id:</label> <div class="col-sm-10"> <p class="form-control-static" th:text="${id}">Person Id</p></div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Name:</label> <div class="col-sm-10"> <p class="form-control-static" th:text="${person.name}">name</p> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Address:</label> <div class="col-sm-10"> <p class="form-control-static" th:text="${person.personDetail.address}">address</p> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Age:</label> <div class="col-sm-10"> <p class="form-control-static" th:text="${person.personDetail.age}">age</p> </div> </div> </form> </div> </div> </body> </html> </code></pre> |
28,148,524 | 0 | Object directory in Makefile.am <p>My current Makefile.am looks something like this:</p> <pre><code>bin_PROGRAMS = MyProgram AM_CPPFLAGS = -I../shared MyProgram_SOURCES = main.cpp Source1.cpp ../shared/Source2.cpp clean : clean-am rm -f *~ rm -f DEADJOE distclean: distclean-am rm -f *~ rm -f DEADJOE rm -f Makefile rm -f *log </code></pre> <p>This creates all the .o files in the current directory. How can I specify a different object directory in a Makefile.am? I failed to find this in the GNU documentation, although I am sure it must be there somewhere.</p> |
5,230,607 | 0 | <p><code>translate_address</code> is not a Linux function. If you're referring to some kind of book or example code, it should explain where you're supposed to get this function from. If it doesn't, chances are it's not meant for Linux (or is a really, really bad reference/example).</p> <p>Furthermore, you should NOT modify the contents of <code>jmp_buf</code> or <code>sigjmp_buf</code> directly. These are architecture and platform-dependent structures, and only the C library is allowed to mess with them. Since the contents of the structures are OS-dependent, if you're using a reference intended for some other OS when modifying <code>sigjmp_buf</code>, Bad Things will happen.</p> <p>You should instead either use <a href="http://linux.die.net/man/2/setcontext" rel="nofollow"><code>setcontext</code>, <code>getcontext</code></a>, and <a href="http://linux.die.net/man/3/makecontext" rel="nofollow"><code>makecontext</code></a> for user threads (fibers) or <a href="http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_create.3.html" rel="nofollow"><code>pthread_create</code></a> for OS-level threads.</p> |
25,905,051 | 0 | <p>Assuming that all processing methods have no return value, one possible way is by creating a method that accept <a href="http://msdn.microsoft.com/en-us/library/system.action%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1" rel="nofollow"><code>Action Delegate</code></a> parameter. This method is responsible for setting <code>Processing</code> property and invoking the <code>Action</code> passed as the method parameter :</p> <pre><code>public bool Processing { get; set; } private void Process(Action process) { Processing = true; process(); Processing = false; } public void Load() { //Logic to load the data } public void Save() { //Logic to save the data } </code></pre> <p>Example usage :</p> <pre><code>//pass 'Load' method as parameter to load data : Process(Load); //pass 'Save' method as parameter to save data : Process(Save); </code></pre> <p>Though, I haven't verified my self whether <code>Action</code> delegate is supported in WP 8.1 universal apps, so it will be great to hear from you.</p> |
25,891,972 | 1 | Solve a ODE for arrays of parameters (Python) <p>*I am aware that this question is quite simple but I would like to know the best way to set up such a for loop in Python. </p> <p>I have written a program already to calculate and plot the solution to a 2nd order differential equation (this code is given below). </p> <p>I would like to know best methods for repeating this calculation for an array of f parameters (hence <code>f_array</code>). I.e. so that the plot shows <code>20</code> sets of data referring to solutions as a function of <code>t</code> each with a different value of <code>f</code>.</p> <p>Cheers for any ideas.</p> <pre><code>from pylab import * from scipy.integrate import odeint #Arrays. tmax = 100 t = linspace(0, tmax, 4000) fmax = 100 f_array = linspace(0.0, fmax, 20) #Parameters l = 2.5 w0 = 0.75 f = 5.0 gamma = w0 + 0.05 m = 1.0 alpha = 0.15 beta = 2.5 def rhs(c,t): c0dot = c[1] c1dot = -2*l*c[1] - w0*w0*c[0] + (f/m)*cos((gamma)*t)-alpha*c[0] - beta*c[0]*c[0]*c[0] return [c0dot, c1dot] init_x = 15.0 init_v = 0.0 init_cond = [init_x,init_v] ces = odeint(rhs, init_cond, t) s_no = 1 subplot(s_no,1,1) xlabel("Time, t") ylabel("Position, x") grid('on') plot(t,ces[:,0],'-b') title("Position x vs. time t for a Duffing oscillator.") show() </code></pre> <p>Here is a plot showing the solution to this equation regarding a single value of <code>f</code> for an array of <code>t</code> values. I would like a quick way to repeat this plot for an array of <code>f</code> values.</p> <p><img src="https://i.stack.imgur.com/evGl5.png" alt="http://i61.tinypic.com/28bgyzs.png"></p> |
12,807,015 | 0 | What RegEx would delimit a list which was copied and pasted from a web page? <p>I have a form which accepts a list of keywords. I then convert the list into an array using <code>mb_split</code> in PHP for entry into the database. However, I'm unable to find a RegEx that delimits the list successfully. Users will typically be pasting data that was copied from a list on a web page. Here's what I'm trying:</p> <pre><code>mb_split('/\s+/', $keywords) </code></pre> <p>And here's the result in the database:</p> <pre><code>keyword1¶keyword2¶keyword3 </code></pre> <p>I would have thought that the ¶ character would have been considered whitespace covered by <code>\s+</code>. I tried handling the ¶ character specifically, but it didn't work:</p> <pre><code>mb_split('/\s+\u00B6/', $keywords) </code></pre> <p>So what RegEx <em>would</em> work here?</p> <p><strong>SOLUTION</strong></p> <p>I ended up using this:</p> <pre><code>mb_split('\n|\r|¶', $keywords) </code></pre> <p>I needed to add the <code>|</code> (logical OR) and actually paste the ¶ symbol into the regex. I also switched to using <code>\n</code> and <code>\r</code> instead of <code>\s</code> to avoid losing multi-word entries which involve spaces.</p> |
15,779,017 | 0 | flip in pages in Wpf with add pages dynamically <p>I want to create application in which I want to give flip effect to each pages, I mean I want my application work and look like book. also I want to add pages dynamically when ever I want to add pages to application. suppose, I have 20 pages in application, now from admin panel want to add some pages to application,so that added pages also show in flip effect. <br>Is this possible?</p> |
11,699,705 | 0 | <p>To use it like regular HTML, you got to think in regular HTML!</p> <p><strong>Lets take your case as example :</strong></p> <pre><code><ui:style> .redborder { border: 1px solid red; } ... </ui:style> ... <div class="{style.redborder}"> <!--Notice I used class instead of styleName--> <g:Label>Hello,</g:Label> <g:Button ui:field="button" /> </div> .... </code></pre> <p>So just use "class" attribute instead of "styleName".</p> |
4,143,703 | 0 | <p>I had the same problem with Greek input, this <a href="http://bugs.launchpad.net/ipython/+bug/339642" rel="nofollow">patch from launchpad</a> works for me too.</p> <p>Thanks.</p> |
25,443,975 | 0 | <p>In the <code>noscript</code> section you could load a resource from your server. If the a visitor loads the resource, you know that he has JavaScript disabled.</p> |
16,020,661 | 0 | <p>I think that might have something to do that you haven't properly closed the files. I took the liberty to rewrite your code, without the chmod stuff (which I don't think is necessary)</p> <pre><code>filename = <your sourcefilename goes here> filename_gz = filename + ".gz" filepath = Rails.root + filename filepath_gz = Rails.root + filename_gz # gzip the file buffer = "" File.open(filepath) do |file| Zlib::GzipWriter.open(filepath_gz) do |gz| while file.read(4096, buffer) gz << buffer end end end # moves the filepath_gz to filepath (overwriting the original file in the process!) FileUtils.mv(filepath_gz, filepath) </code></pre> <p>As you can see I've used File.open(path) and passed a block. This has the effect that the files will be closed automatically when the block exits. I've also changed the delete/rename code to simply move the gziped file to the original path, which has the same effect.</p> <p>However, I strongly advice you to keep a backup of your original file.</p> |
16,060,372 | 0 | Rest web services - Synchronous or asynchrous <p>I have one doubt in my mind, What is the default behavior of REST web services-Synchronous or asynchronous. If synchronous then can we create asynchronous. </p> |
15,079,736 | 0 | <p>Example of a console application example/tutorial:</p> <pre><code>enum DurationType { [DisplayName("m")] Min = 1, [DisplayName("h")] Hours = 1 * 60, [DisplayName("d")] Days = 1 * 60 * 24 } internal class Program { private static void Main(string[] args) { string input1 = "10h"; string input2 = "1d10h3m"; var x = GetOffsetFromDate(DateTime.Now, input1); var y = GetOffsetFromDate(DateTime.Now, input2); } private static Dictionary<string, DurationType> suffixDictionary { get { return Enum .GetValues(typeof (DurationType)) .Cast<DurationType>() .ToDictionary(duration => duration.GetDisplayName(), duration => duration); } } public static DateTime GetOffsetFromDate(DateTime date, string input) { MatchCollection matches = Regex.Matches(input, @"(\d+)([a-zA-Z]+)"); foreach (Match match in matches) { int numberPart = Int32.Parse(match.Groups[1].Value); string suffix = match.Groups[2].Value; date = date.AddMinutes((int)suffixDictionary[suffix]); } return date; } } [AttributeUsage(AttributeTargets.Field)] public class DisplayNameAttribute : Attribute { public DisplayNameAttribute(String name) { this.name = name; } protected String name; public String Name { get { return this.name; } } } public static class ExtensionClass { public static string GetDisplayName<TValue>(this TValue value) where TValue : struct, IConvertible { FieldInfo fi = typeof(TValue).GetField(value.ToString()); DisplayNameAttribute attribute = (DisplayNameAttribute)fi.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault(); if (attribute != null) return attribute.Name; return value.ToString(); } } </code></pre> <p>Uses an attribute to define your suffix, uses the enum value to define your offset.</p> <p>Requires:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; </code></pre> <p>It may be considered a hack to use the enum integer value but this example will still let you parse out all the Enums (for any other use like switch case) with little tweaks.</p> |
19,845,769 | 0 | Smarty variable in array index <p>Have months array <code>$months('January', 'February', 'May')</code></p> <p>and want show this month in loop </p> <pre><code>{for $foo=1 to 3} {$months[$foo]} {/for} </code></pre> <p>I get white page, what is wrong with my code ?</p> |
40,697,589 | 0 | <p>Which padding and margin do you want remove?</p> |
30,961,517 | 0 | Can struts.xml and struts annotation be used at the same time <p>I am using two action classes in my application, i am using annotation in one action class and i want to use struts.xml for the other action class. Is it possible. When i am using annotation, this is working</p> <pre><code>@Namespace("/") @ResultPath("/") public class StartQuizAction extends ActionSupport { private static final long serialVersionUID = 953099491763814636L; private List qlist; public List getQlist() { return qlist; } public void setQlist(List qlist) { this.qlist = qlist; } public static long getSerialversionuid() { return serialVersionUID; } @Action(value="startQuiz" ,results={@Result(name="success" , location="User/pages/qData.jsp") }) public String execute(){ System.out.println("in 2nd action"); QuizDataInput qData= new QuizDataInput(); qlist=qData.getData(); System.out.println(qlist); return SUCCESS; } } </code></pre> <p>But when i use struts.xml, removing annotations, i am getting this error</p> <blockquote> <p>There is no Action mapped for namespace [/] and action name [] associated with context path [/quizcreator]. - [unknown location]</p> </blockquote> <p>Struts.xml</p> <pre><code><struts> <package name="default" namespace="/" extends="struts-default"> <action name="startQuiz" class="com.agc.onlinequiz.action.StartQuizAction"> <result name="success">User/pages/qData.jsp</result> </action> </package> </struts> </code></pre> |
22,104,734 | 0 | Android Google Maps, how to create navigation between 2 points <p>I want to create a Map activity (FragmentActivity) that displays a Google Map and shows navigation between 2 points.</p> <p>I have one made that shows one location but I've no idea on how to create navigation to another point, every link I saw gives their web api as the solution (<a href="https://maps.google.com/maps?saddr=X,Y&daddr=X,Y" rel="nofollow">https://maps.google.com/maps?saddr=X,Y&daddr=X,Y</a>)</p> <p>and I want to do exactly what it does just programmatically through the activity and not just link into their webpage</p> <p>my code so far:</p> <pre><code>try{ bndl = getIntent().getExtras(); COORDS = new LatLng(bndl.getDouble("lat"), bndl.getDouble("long")); if (map == null) { map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); if (map != null) { map.setMapType(GoogleMap.MAP_TYPE_HYBRID); map.addMarker(new MarkerOptions().position(COORDS).title("Your parking spot!")); CameraPosition cameraPosition = new CameraPosition.Builder() .target(COORDS) .zoom(20) .bearing(90) .tilt(0) .build(); map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } } } catch (Exception e){ Log.v("except", ""+e); } </code></pre> <p>now this only shows the one location (as it should do) but how to create another marker or something to navitage to? Is there a way to do this or do I HAVE to use their web api?</p> |
38,129,823 | 0 | Remove an association between two models <p>I have the following associations:</p> <pre><code>class a < ActiveRecord::Base has_many :bs class b < ActiveRecord::Base belongs_to :a </code></pre> <p>How do I now remove this association? I believe it requires a migration. What should this migration do?</p> |
20,153,175 | 0 | <p>These are 2 separate informations.</p> <pre><code>[[UIDevice currentDevice] name] // e.g. Raymonds iPhone </code></pre> <p>What you want is the following:</p> <pre><code>[[UIDevice currentDevice] model] // e.g. iPhone, iPod touch, iPad, iOS Simulator // or [[UIDevice currentDevice] localizedModel], e.g. Le iPod (j/k) </code></pre> <p>And for the device capacity, which there may be better examples, but this returns the space that is reported by the system:</p> <pre><code>- (NSString*)deviceCapacity { NSDictionary *attributesDict = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSTemporaryDirectory() error:NULL]; NSNumber *totalSize = [attributesDict objectForKey:NSFileSystemSize]; return [NSString stringWithFormat:@"%3.2f GB",[totalSize floatValue] /(1000*1000*1000)]; } </code></pre> <p><em>Note that the above example may return "14.37 GB" for a 16GB device (where 14.37 is the number the iOS reports, presumably the space after iOS is installed. So you can look at it as the <strong>user</strong> partition excluding the <strong>root</strong> partition.</em></p> <p>So to put it all together, use this:</p> <pre><code>[NSString stringWithFormat:@"%@ %@", [[UIDevice currentDevice] model], [self deviceCapacity]]; </code></pre> |
16,275,131 | 0 | <blockquote> <p>Am I missing something? How can I achieve the same thing in CodeIgniter?</p> <blockquote> <p><sub>if you want to learn how to truly approach MVC in PHP, you can learn it from Tom Butler <a href="http://r.je" rel="nofollow">articles</a></sub></p> </blockquote> </blockquote> <p>CodeIgniter implements Model-View-Presenter pattern, not MVC (even if it says so). If you want to implement a truly MVC-like application, you're on the wrong track.</p> <p>In MVP:</p> <ul> <li>View can be a class or a html template. View should never be aware of a Model.</li> <li>View should never contain business logic</li> <li>A Presenter is just a glue between a View and the Model. Its also responsible for generating output.</li> </ul> <blockquote> <blockquote> <p>Note: A model should never be <em>singular class</em>. Its a number of classes. I'll call it as "Model" just for demonstration.</p> </blockquote> </blockquote> <p>So it looks like as:</p> <pre><code>class Presenter { public function __construct(Model $model, View $view) { $this->model = $model; $this->view = $view; } public function indexAction() { $data = $this->model->fetchSomeData(); $this->view->setSomeData($data); echo $this->view->render(); } } </code></pre> <p>In MVC:</p> <ul> <li>Views are not HTML templates, but classes which are responsible for presentation logic</li> <li>A View has direct access to a Model</li> <li>A Controller should not generate a response, but change model variables (i.e assign vars from <code>$_GET</code> or <code>$_POST</code></li> <li>A controller should not be aware of a view</li> </ul> <p>For example,</p> <pre><code>class View { public function __construct(Model $model) { $this->model = $model; } public function render() { ob_start(); $vars = $this->model->fetchSomeStuff(); extract($vars); require('/template.phtml'); return ob_get_clean(); } } class Controller { public function __construct(Model $model) { $this->model = $model; } public function indexAction() { $this->model->setVars($_POST); // or something like that } } $model = new Model(); $view = new View($model); $controller = new Controller($model); $controller->indexAction(); echo $view->render(); </code></pre> |
1,298,071 | 0 | <p>You can do this easily in XeLaTeX:</p> <pre><code>\usepackage{fontspec} ... \fontspec[ItalicFont=*,ItalicFeatures=FakeSlant]{Minion Pro} </code></pre> <p>Highly undesirable, however, if there's any chance you can get a <a href="http://www.fonts.com/findfonts/detail.htm?pid=414411" rel="nofollow noreferrer">real italic</a>.</p> <p>Update: why undesirable? Because font outlines are not designed to be distorted! Any sort of transformation besides linear scaling in both directions will change the relationship between the inner/outer curves of the letters, effectively going against the wishes of the font designer.</p> <p>If you want to highlight something in a different font than the roman and not use italic, try something completely different like a harmonising sans serif, for example.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.