id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
4,518,933
How to make a textbox of multiple line type in html?
<pre><code>&lt;input class="FormElement" name="term" id="term" type="text"&gt; </code></pre> <p>What modifications should I do to this textbox to make it multiple line, without the need to modify anything else in the code, like reading its value.</p> <p>I used to read the input by javascript like that, what should be changed in that as well?</p> <pre><code>var $term = $("textarea#term").val(); </code></pre>
4,518,968
1
0
null
2010-12-23 12:57:04.643 UTC
null
2010-12-23 14:07:55.247 UTC
2010-12-23 13:12:29.79 UTC
null
132,640
null
132,640
null
1
12
php|html
62,147
<p>You need a <a href="https://developer.mozilla.org/en/DOM/HTMLTextareaElement" rel="noreferrer"><code>&lt;textarea&gt;</code></a> with the same <code>name</code>, so replace this:</p> <pre><code>&lt;input class="FormElement" name="term" id="term" type="text"&gt; </code></pre> <p>With this:</p> <pre><code>&lt;textarea class="FormElement" name="term" id="term" cols="40" rows="4"&gt;&lt;/textarea&gt; </code></pre> <p>The <code>rows</code> and <code>cols</code> arguments are the width/height respectively...or use CSS styling to specify the size, like this:</p> <pre><code>&lt;textarea class="FormElement" name="term" id="term" style="width: 200px; height: 40px;"&gt;&lt;/textarea&gt; </code></pre>
39,258,979
How can I view hidden characters in Notepad++?
<p>I have a string that has been giving some of my code fits of rage and its got "extra" characters in it that I only stumbled upon by using the arrow keys to go through it. I noticed that the cursor stayed in place in certain areas for an extra keystroke of the arrow key. Using View >Show Symbols > Show All Characters still didnt seem to indicate anything there. What kind of character could be there and is there a plugin for it?</p>
39,259,048
4
3
null
2016-08-31 21:04:08.017 UTC
null
2022-06-10 05:57:29.23 UTC
2020-09-04 15:24:59.927 UTC
null
2,756,409
null
3,206,983
null
1
21
notepad++
66,434
<p>If you really want to get a raw look, check out the <a href="https://sourceforge.net/projects/npp-plugins/files/Hex%20Editor/" rel="noreferrer">HEX-Editor Plugin</a> (Check the Plugin Manager for it). You'll see the character codes for everything; even non-printable characters.</p> <p>I use it, and have no issues on the newer versions of Notepad++.</p>
26,530,551
Is it possible to use a static library only when testing with device and not simulator?
<p>I have external closed library that can compile with armv7s (etc) only. when I try to compile against simulator obviously its not running and display some errors. I don't want to insert this library to my code unless I can configure Xcode to use this library only when i test with a device. unfortunately, i tried to do it with cocoapods with no success and i wonder if there any way to do it?</p>
26,531,614
4
1
null
2014-10-23 14:33:19.17 UTC
8
2020-07-29 07:15:49.067 UTC
null
null
null
null
3,083,605
null
1
10
ios|iphone|xcode|static
2,445
<p>Yes, this can be done. I had a similar problem with a framework that caused linker errors only in the simulator so I setup up my project to only use the framework when building for a device.</p> <p>The following assumes you are not using cocoa pods to link the library. I'm not sure what would need to be changed if you are.</p> <ol> <li>Select your target and go to the Build Phases tab.</li> <li>Under the &quot;Link Binary With Libraries&quot; section, remove the static library from the list but make sure the library file still exists in your project files under Frameworks folder. If the library file name is missing the leading &quot;lib&quot; in its name you might need to rename the file in the project navigator and add the leading &quot;lib&quot; to the file name.</li> <li>Go to the Build Settings tab.</li> <li>Find the &quot;Other Linker Flags&quot; setting.</li> <li>Double-click on the Debug value. Tap the + and enter &quot;-l&quot;</li> <li>In place of enter the actual name of your library minus the leading &quot;lib&quot;. Do not include the extension. The &quot;libMyLibrary.a&quot; should be entered as &quot;-lMyLibrary&quot;</li> <li>Select the Debug value and notice a little circled +. Click the +.</li> <li>Click on the new &quot;Any Architecture | Any SDK&quot; part and change it to &quot;Any iOS Simulator SDK&quot;.</li> <li>Now double click on the value to the right of &quot;Any iOS Simulator SDK&quot; and remove the -lsomeLibrary entry you added.</li> </ol> <p>Now do a debug build.</p> <p>The above change basically means that the library is linked in for all builds except for iOS Simulator builds.</p> <p>You will probably also need to make some code changes. Any code making any reference to header files or other symbols from the library should be wrapped as follows:</p> <pre><code>#if !TARGET_IPHONE_SIMULATOR #import &quot;someLibrary.h&quot; #endif #if !TARGET_IPHONE_SIMULATOR // Use stuff from the library #endif </code></pre>
6,398,418
Setting DatePicker Value
<p>I currently have a program that takes the value from a datePicker and have the date saved as a string. I only needed the date not the time so i used the following code to save the date value:</p> <pre><code>DateTime StartDate; String inMyString; savedDate = datePicker1.SelectedDate.Value.Date; inMyString = savedDate.Date.ToShortDateString() </code></pre> <p>I have the <code>inMyString</code> pushedBack into my list and now i want to place it back into the datePicker.</p> <p>On MSDN is shows me the following example to set the date.</p> <pre><code>dateTimePicker1.Value = new DateTime(2001, 10, 20); </code></pre> <p>the problem is that having .Value after my date picker is not an option (it doesn't show in Intellisense.)</p> <p>I have also tried </p> <pre><code>datePicker1.SelectedDate.Value= new DateTime(inMyString) </code></pre> <p>and also converting the <code>inMyString</code> to type <code>DateTime</code> but it still does not work.</p> <p>Any thoughts on how to do this?<br> Any Suggestions and comments are appreciated.</p> <p>Thanks!</p>
6,398,434
2
0
null
2011-06-18 19:34:33.853 UTC
1
2017-04-27 04:35:04.39 UTC
2011-06-20 17:00:23.873 UTC
null
732,945
null
507,518
null
1
19
c#|.net|wpf|datepicker
66,203
<p>Try this:</p> <pre><code>datePicker1.SelectedDate = new DateTime(2001, 10, 20); </code></pre> <p>If you need to take datetime from string:</p> <pre><code>datePicker1.SelectedDate = DateTime.Parse(inMyString); </code></pre> <hr> <p>Side note:</p> <p>You can replace those 3 lines:</p> <pre><code>String inMyString; savedDate = datePicker1.SelectedDate.Value.Date; inMyString = savedDate.Date.ToShortDateString(); </code></pre> <p>with one:</p> <pre><code>var inMyString = datePicker1.SelectedDate.Value.ToShortDateString(); </code></pre> <hr> <p>Another side note: don't know if there is a reason to it, but you might consider storing datetime as dattime, not as a string.</p>
7,131,925
How to enable and disable javascript functions?
<pre><code> if(tmpStr == tmp+value) { i=1; action = null; action2 = null; } if(tmpStr1 == tmp+value) { i=0; action();//not working action2();//not working } for(i;i&lt;=14; i++) { if(tmp!="movie"+i) { document.getElementById("movie"+i).sndToAS("resume"); } } } function action() { document.getElementById("movie0").sndToAS("pause"); } function action2() { if(tmp != "movie0") { document.getElementById("movie0").sndToAS("pause"); } } </code></pre>
7,132,103
3
6
null
2011-08-20 13:09:41.98 UTC
1
2021-11-06 06:44:03.25 UTC
2011-08-20 15:06:01.143 UTC
null
624,094
null
624,094
null
1
4
javascript
41,456
<p>Do something like this</p> <pre><code>function actionFunc(){ document.getElementById("movie0").sndToAS("pause"); } function action2Func() { if(tmp != "movie0"){ document.getElementById("movie0").sndToAS("pause"); } } window.action = actionFunc; window.action2 = action2Func; if(tmpStr == tmp+value) { id=1; window.action = null; window.action2 = null; } if(tmpStr1 == tmp+value) { id=0; window.action = actionFunc; window.action2 = action2Func; } </code></pre> <p>Then when you want to call your functions all you have to do is</p> <pre><code>action(); action2(); </code></pre> <p>but your going to want to check if the are set before calling them</p> <p>I believe thats what your after</p> <p>or do something like this</p> <pre><code>function action(){ if (window.actionEnabled) { document.getElementById("movie0").sndToAS("pause"); } } function action2() { if (window.action2Enabled) { if(tmp != "movie0"){ document.getElementById("movie0").sndToAS("pause"); } } } window.actionEnabled = true; window.action2Enabled = true; if(tmpStr == tmp+value) { id=1; window.actionEnabled = false; window.action2Enabled = false; } if(tmpStr1 == tmp+value) { id=0; window.actionEnabled = true; window.action2Enabled = true; } </code></pre> <p>then you don't have to check if the are enabled just call them and they will work or want depending on if they are enabled</p>
1,658,887
functional programming: immutable data structure efficiency
<p>I don't understand, how FP compilers make the code dealing with immutable data structures fast, not blow up stack, etc.</p> <p>For example, insert operation in tree, it has to copy the whole tree before adding the new node and return the copied tree, versus the imperative couterpart that only needs to add a pointer to the new node. If the insert operation is run millions times, it would take a load of memory, and copying will be slower and slower when the tree is bigger. How do FP compilers actually optimize this ?</p>
1,658,905
4
0
null
2009-11-02 00:21:44.917 UTC
11
2009-11-06 21:37:16.977 UTC
null
null
null
null
187,915
null
1
16
functional-programming
2,308
<p>You don't have to copy the whole tree to make a change; you can share most of the structure. See e.g. the diagrams in <a href="http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!248.entry" rel="noreferrer">this blog</a>, or <a href="http://www.infoq.com/presentations/Value-Identity-State-Rich-Hickey" rel="noreferrer">this talk</a> by Rich Hickey on Clojure (see discussion of hash tries about halfway through).</p>
49,752,149
How do I convert 2018-04-10T04:00:00.000Z string to DateTime?
<p>I get a date from a JSON API which looks like this "2018-04-10T04:00:00.000Z". I want to convert it in order to obtain a Date or String object and get something like "01-04-2018" that its "dd-MM-YYYY". How can I do it?</p>
49,752,361
2
4
null
2018-04-10 11:11:44.973 UTC
16
2018-04-10 11:33:30.987 UTC
null
null
null
null
9,605,869
null
1
55
java|android-studio|datetime|datetime-format
435,624
<h3>Update: Using <code>DateTimeFormat</code>, introduced in java 8:</h3> <p>The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.</p> <p>Your input format looks quite standard, except the trailing <code>Z</code>. Anyway, let's deal with this: <code>"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"</code>. The trailing <code>'Z'</code> is the interesting part. Usually there's time zone data here, like <code>-0700</code>. So the pattern would be <code>...Z</code>, i.e. without apostrophes.</p> <p>The output format is way more simple: <code>"dd-MM-yyyy"</code>. Mind the small <code>y</code> -s.</p> <p>Here is the example code:</p> <pre><code>DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH); DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH); LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter); String formattedDate = outputFormatter.format(date); System.out.println(formattedDate); // prints 10-04-2018 </code></pre> <h3>Original answer - with old API <code>SimpleDateFormat</code></h3> <pre><code>SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy"); Date date = inputFormat.parse("2018-04-10T04:00:00.000Z"); String formattedDate = outputFormat.format(date); System.out.println(formattedDate); // prints 10-04-2018 </code></pre>
49,510,176
Android Studio: Gradle sync failed: Could not HEAD '...'. Received status code 502 from server: Bad Gateway
<p>After update Android Studio to latest version (3.1) and gradle version in my project I get an error (the link is always different):</p> <pre><code>12:54 Gradle sync started 12:56 Gradle sync failed: Could not HEAD 'https://jcenter.bintray.com/com/android/tools/analytics-library/shared/26.1.0/shared-26.1.0.jar'. Received status code 502 from server: Bad Gateway Consult IDE log for more details (Help | Show Log) (1m 56s 602ms) 12:56 Gradle sync started 12:57 Gradle sync failed: Could not HEAD 'https://jcenter.bintray.com/org/codehaus/mojo/animal-sniffer-parent/1.14/animal-sniffer-parent-1.14.pom'. Received status code 502 from server: Bad Gateway Consult IDE log for more details (Help | Show Log) (1m 4s 266ms) 12:58 Gradle sync started 12:59 Gradle sync failed: Could not HEAD 'https://jcenter.bintray.com/com/sun/activation/all/1.2.0/all-1.2.0.pom'. Received status code 502 from server: Bad Gateway Consult IDE log for more details (Help | Show Log) (1m 29s 985ms) 13:01 Gradle sync started 13:02 Gradle sync failed: Could not HEAD 'https://jcenter.bintray.com/com/sun/activation/javax.activation/1.2.0/javax.activation-1.2.0.pom'. Received status code 502 from server: Bad Gateway Consult IDE log for more details (Help | Show Log) (4s 976ms) </code></pre> <p>Android Studio version:</p> <pre><code>Android Studio 3.1 Build #AI-173.4670197, built on March 22, 2018 JRE: 1.8.0_152-release-1024-b02 amd64 JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o Windows 10 10.0 </code></pre> <p>I already tried clean rebuild and update gradle, restart Android Studio and PC, but without success. Any ideas?</p> <p>PS: of course I have internet. Also, if you open a link in the browser - the file is downloaded.</p>
49,511,097
9
6
null
2018-03-27 10:13:29.28 UTC
11
2022-01-13 09:40:07.787 UTC
null
null
null
null
4,866,667
null
1
97
android|android-studio|gradle|android-gradle-plugin
76,051
<p>jcenter is having issues at the moment, please check <a href="http://status.bintray.com/" rel="nofollow noreferrer">http://status.bintray.com/</a></p> <p><strong>EDIT</strong>: it looks like the link above was <a href="https://stackoverflow.com/a/70687500/1401164">sunset</a>, new link at: <a href="https://status.gradle.com/" rel="nofollow noreferrer">https://status.gradle.com/</a></p>
10,660,291
Highlight elements in WebDriver during runtime
<p>Can someone please help!</p> <p>How can I highlight all web elements in following class during test execution in WebDriver? With Selenium RC, it was quite straight forward but with WebDriver I am struggling.</p> <p>I would be grateful if someone can please provide me with some code that I can try, also where would that code fit into the class below — sorry my Java skills aren't all that great.</p> <pre><code>package hisScripts; import java.util.concurrent.TimeUnit; import org.testng.annotations.*; import org.testng.Assert; import static org.testng.Assert.fail; import org.openqa.selenium.*; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.interactions.Actions; public class R_LHAS_Only_Account_Verification extends HIS_Login_Logout{ public WebDriver driver; public String baseUrl; public int exeMonth; private StringBuffer verificationErrors = new StringBuffer(); @BeforeClass @Parameters ({"browser1", "url", "executionMonth"}) public void setUp(String browser1, String url, int executionMonth) throws Exception { exeMonth = executionMonth; baseUrl = url; if (browser1.equals("FF")) { driver = new FirefoxDriver(); } else if (browser1.equals("IE")){ driver = new InternetExplorerDriver(); } driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void R_LHAS_Reports() throws Exception { R_LHAS_Only_Login(baseUrl, driver); Assert.assertEquals("Kingston upon Thames (RB)", driver.findElement(By.xpath("//html/body/div[9]/div/div[3]/div/div/div")).getText()); Assert.assertEquals("Average price", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr/td")).getText()); Assert.assertEquals("% price change", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[2]/td")).getText()); Assert.assertEquals("Lower quartile price", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[3]/td")).getText()); Assert.assertEquals("Time to sell (weeks)", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[4]/td")).getText()); Assert.assertEquals("% asking price achieved", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[5]/td")).getText()); Assert.assertEquals("House price to earnings ratio", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[6]/td")).getText()); Assert.assertEquals("Cost of buying outright - LQ 2 bed £pw", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[7]/td")).getText()); Assert.assertEquals("Private rent 2 bed £pw", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[8]/td")).getText()); Assert.assertEquals("80% private rent 2 bed £pw", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[9]/td")).getText()); Assert.assertEquals("Social rent 2 bed £pw", driver.findElement(By.xpath("//table[@id='tableId']/tbody/tr[10]/td")).getText()); R_LHAS_Only_Logout(baseUrl,driver); } @AfterClass(alwaysRun=true) public void tearDown() throws Exception { driver.quit(); String verificationErrorString = verificationErrors.toString(); if (! "".equals(verificationErrorString)) { fail(verificationErrorString); } } } </code></pre>
10,660,734
11
2
null
2012-05-18 22:05:00.143 UTC
14
2022-07-13 18:16:22.143 UTC
2014-06-25 14:38:27.927 UTC
null
31,493
null
929,258
null
1
24
java|selenium|webdriver
78,654
<p>There is no way to do this in <a href="http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebDriver.html"><code>WebDriver</code></a> (as of v2.21.0). You can try replacing the usual <a href="http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebDriver.html#findElement%28org.openqa.selenium.By%29"><code>findElement(By)</code></a> method with an adjusted one that uses JavaScript to highlight the found element:</p> <pre><code>// Draws a red border around the found element. Does not set it back anyhow. public WebElement findElement(By by) { WebElement elem = driver.findElement(by); // draw a border around the found element if (driver instanceof JavascriptExecutor) { ((JavascriptExecutor)driver).executeScript("arguments[0].style.border='3px solid red'", elem); } return elem; } </code></pre> <p>Now that you got the idea, there's an improved version that restores the original <code>border</code> of the last element when a new one is found and highlighted:</p> <pre><code>// assuming JS is enabled private JavascriptExecutor js = (JavascriptExecutor)driver; private WebElement lastElem = null; private String lastBorder = null; private static final String SCRIPT_GET_ELEMENT_BORDER; private static final String SCRIPT_UNHIGHLIGHT_ELEMENT; void highlightElement(WebElement elem) { unhighlightLast(); // remember the new element lastElem = elem; lastBorder = (String)(js.executeScript(SCRIPT_GET_ELEMENT_BORDER, elem)); } void unhighlightLast() { if (lastElem != null) { try { // if there already is a highlighted element, unhighlight it js.executeScript(SCRIPT_UNHIGHLIGHT_ELEMENT, lastElem, lastBorder); } catch (StaleElementReferenceException ignored) { // the page got reloaded, the element isn't there } finally { // element either restored or wasn't valid, nullify in both cases lastElem = null; } } } </code></pre> <p>And the scripts! I load them from a file using <a href="http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#readFileToString%28java.io.File%29"><code>FileUtils.readFileToString()</code></a>.</p> <p>SCRIPT_GET_ELEMENT_BORDER (<a href="http://www.quirksmode.org/dom/getstyles.html">IE friendly version taken from this site</a>), it would be way shorter if it used highlighting via changing the background color, say, only the bottom border. But this is the nicest one :).</p> <pre><code>/* * Returns all border properties of the specified element as String, * in order of "width style color" delimited by ';' (semicolon) in the form of: * * "2px inset #000000;2px inset #000000;2px inset #000000;2px inset #000000" * "medium none #ccc;medium none #ccc;1px solid #e5e5e5;medium none #ccc" * etc. */ var elem = arguments[0]; if (elem.currentStyle) { // Branch for IE 6,7,8. No idea how this works on IE9, but the script // should take care of it. var style = elem.currentStyle; var border = style['borderTopWidth'] + ' ' + style['borderTopStyle'] + ' ' + style['borderTopColor'] + ';' + style['borderRightWidth'] + ' ' + style['borderRightStyle'] + ' ' + style['borderRightColor'] + ';' + style['borderBottomWidth'] + ' ' + style['borderBottomStyle'] + ' ' + style['borderBottomColor'] + ';' + style['borderLeftWidth'] + ' ' + style['borderLeftStyle'] + ' ' + style['borderLeftColor']; } else if (window.getComputedStyle) { // Branch for FF, Chrome, Opera var style = document.defaultView.getComputedStyle(elem); var border = style.getPropertyValue('border-top-width') + ' ' + style.getPropertyValue('border-top-style') + ' ' + style.getPropertyValue('border-top-color') + ';' + style.getPropertyValue('border-right-width') + ' ' + style.getPropertyValue('border-right-style') + ' ' + style.getPropertyValue('border-right-color') + ';' + style.getPropertyValue('border-bottom-width') + ' ' + style.getPropertyValue('border-bottom-style') + ' ' + style.getPropertyValue('border-bottom-color') + ';' + style.getPropertyValue('border-left-width') + ' ' + style.getPropertyValue('border-left-style') + ' ' + style.getPropertyValue('border-left-color'); } // highlight the element elem.style.border = '2px solid red'; return border; </code></pre> <p>SCRIPT_UNHIGHLIGHT_ELEMENT</p> <pre><code>var elem = arguments[0]; var borders = arguments[1].split(';'); elem.style.borderTop = borders[0]; elem.style.borderRight = borders[1]; elem.style.borderBottom = borders[2]; elem.style.borderLeft = borders[3]; </code></pre> <p>Any questions, notes, requests and improvements are welcome!</p>
28,683,327
How to check if Gradle dependency has new version?
<p>In Android Studio when I use a <code>+</code> in the version number like:<br /> <code>com.android.support:recyclerview-v7:21.+</code><br /> I get a &quot;Avoid using + in version numbers&quot; warning.</p> <p>But when I use a specific version number I can't always use the latest version. I have a lot of dependencies in my project.</p> <p>How do I check if a dependency has a newer version?</p> <p>Is there an Android Studio plugin (or something like that) to notify me when there is a newer version of a dependency?</p> <p><strong>Edit:</strong><br /> Android Studio highlights the outdated Android Support Libraries and Google play services. But this is not available for other custom libraries.</p> <p><img src="https://i.stack.imgur.com/yZ2DO.png" alt="Android Studio highlights" /></p>
35,371,234
10
4
null
2015-02-23 20:59:16.32 UTC
66
2022-03-08 13:17:01.227 UTC
2022-03-08 13:17:01.227 UTC
null
10,749,567
null
1,120,126
null
1
270
android-studio|gradle|version
113,929
<p>This is now built-in to Android Studio as a Lint check. You can enable it here:</p> <blockquote> <p>Settings > Editor > Inspections > "Newer Library Versions Available"</p> </blockquote> <p>The description for this inspection:</p> <blockquote> <p>Newer Library Versions Available </p> <p>This detector checks with a central repository to see if there are newer versions available for the dependencies used by this project. This is similar to the GradleDependency check, which checks for newer versions available in the Android SDK tools and libraries, but this works with any MavenCentral dependency, and connects to the library every time, which makes it more flexible but also <strong>much</strong> slower.</p> </blockquote> <p>Because of the slowdown this can introduce I'd recommend running it manually periodically, rather than having it always on. You can do this by:</p> <blockquote> <p>Analyze > "Run Inspection By Name"</p> </blockquote> <p>Then search for "Newer Library Versions Available", and run it on your module.</p> <p><strong>Edit</strong>: The above should just work as of Android Studio 2.3. If you're on an old version (you should update) the following may help:</p> <p>Note that it appears you must have the inspection enabled in order to run it manually - so (as of Android Studio 2.0 Beta 2) you need to find the inspection in settings, enable it, then run it by name, then disable it again (to regain previous performance).</p>
7,229,885
What are the differences between .gitignore and .gitkeep?
<p>What are the differences between <code>.gitignore</code> and <code>.gitkeep</code>? Are they the same thing with a different name, or do they both serve a different function?</p> <p>I don't seem to be able to find much documentation on <code>.gitkeep</code>.</p>
7,229,996
5
0
null
2011-08-29 12:11:05.037 UTC
323
2022-02-28 17:39:08.26 UTC
2019-10-06 14:06:07.98 UTC
user456814
63,550
null
509,271
null
1
2,458
git|gitignore
546,008
<p><code>.gitkeep</code> isn’t documented, because it’s not a feature of Git.</p> <p>Git <a href="https://git.wiki.kernel.org/index.php/Git_FAQ#Can_I_add_empty_directories.3F" rel="noreferrer">cannot add a completely empty directory</a>. People who want to track empty directories in Git have created the convention of putting files called <code>.gitkeep</code> in these directories. The file could be called anything; Git assigns no special significance to this name.</p> <p>There is a competing convention of adding a <code>.gitignore</code> file to the empty directories to get them tracked, but some people see this as confusing since the goal is to keep the empty directories, not ignore them; <code>.gitignore</code> is also used to list files that should be ignored by Git when looking for untracked files.</p>
7,607,502
sizeof(long) in 64-bit C++
<p>I have downloaded MinGW-64, so I can now compile 64-bit programs for Windows 7, using g++ 4.7.0 (experimental). But the following line:</p> <pre><code>cout &lt;&lt; sizeof(long) &lt;&lt; " " &lt;&lt; sizeof(void*) &lt;&lt; endl ; </code></pre> <p>prints <code>4 8</code>, not <code>8 8</code>. The documentation for g++ 4.6.0 says:</p> <blockquote> <p>The 64-bit environment sets int to 32 bits and long and pointer to 64 bits</p> </blockquote> <p>Does anybody know why <code>sizeof(long)</code> is not 8?</p> <p><strong>Edited to add:</strong> The source of my confusion was that g++ 4.7.0 for 64-bit Windows is not (yet) an official part of the GNU Compiler Collection. And it's the first 64-bit version with a 32-bit <code>long</code>, so the documentation simply doesn't apply to it. Indeed, if you go to the <a href="http://gcc.gnu.org/gcc-4.7/changes.html" rel="noreferrer">relevant web page</a>, the full entry for <strong>IA-32/x86-64</strong> consists of this:</p> <blockquote> <p>...</p> </blockquote>
7,607,557
6
3
null
2011-09-30 07:53:58.607 UTC
5
2019-07-16 14:37:44.18 UTC
2011-09-30 08:23:49.17 UTC
null
428,857
null
428,857
null
1
25
c++|64-bit
50,711
<p>Because it doesn't have to be. The C++ standard only requires that it is (if memory serves) at least 32 bits wide, and at least as big as <code>int</code>.</p> <p>MSVC (and the ABI used by Windows) defines <code>long</code> to be 32 bits wide, and MingW follows suit because well, the compiler is a lot more useful when it agrees with the host OS</p>
13,909,295
Check for slow internet connection iOS
<p>I have added Reachability classes provided by apple and it is working fine for checking internet connection. MY app is displaying message if internet goes off.</p> <p>But if internet is very slow it just keep loading.......</p> <p>I am using wi-fi and I face this problem when there is only a dot visible in iPhone notification bar for wifi signal.</p> <p>So I want to know how can I check for slow internet connection.</p>
13,910,178
1
4
null
2012-12-17 06:25:39.083 UTC
10
2012-12-17 07:48:48.523 UTC
null
null
null
null
1,365,821
null
1
16
ios
7,695
<p>You can send a request to your server and given that it's about 5-10 KB of data you expect to be returned, then create a timer callback that is scheduled for say 20 seconds.</p> <p>If you don't get a response within 20 seconds, then let's consider that a slow connection.</p> <p>Example:</p> <pre><code>// make POST request to server, the POST request should have a callback method assigned [self testSpeed]; // schedule a method to be called after 20 seconds myTimer = [NSTimer scheduledTimerWithInterval:20.0 selector:@selector(stopSpeedTest) .... ]; // your POST request callback method -(void)speedTestCallback { [myTimer invalidate]; myTimer = nil; [self alertGoodSpeed]; } // your stopSpeedTest method to identify app didn't receive response within 20 seconds -(void)stopSpeedTest { [self alertTooSlow]; } </code></pre> <p>I think that's what H2CO3 was trying to ask:</p> <p>"How many bytes per second do you consider slow?"</p> <p>You need to decided on long you think the user is willing to wait for the amount of data expected to be returned.</p> <p>If you're telling the user you're downloading 50 MB of data, then yes, getting them all back in 20 second is fast.</p> <p>However, if you're expecting only 5-10 KB of data and it's taking longer than 10 seconds, let alone 20 seconds, then connection is very slow. </p>
14,007,075
Google Maps not working on iPhone simulator
<p>I've implemented the "Getting the Google Maps SDK for iOS" step by step</p> <p>finally the simulator running ok no errors found but the map has no details except the marker.</p> <p>As showing in the picture: </p> <p><img src="https://i.stack.imgur.com/KG5kt.jpg" alt="Screnshot of simulator"></p> <p>Also the output on the bottom has this message:</p> <blockquote> <p>2012-12-23 01:06:59.869 GogleMap[3680:c07] GMSZoomTableQuadTree lacks root zoom table for >tile type (mapType: 10) 2012-12-23 01:07:00.042 GogleMap[3680:1b03] Google Maps SDK for iOS version: 1.0.1.1154 2012-12-23 01:07:00.375 GogleMap[3680:c07] ClientParametersRequest failed, 3 attempts >remaining. Error Domain=DASHConnectionError Code=100 "The operation couldn’t be completed. (DASHConnectionError error 100.)"</p> </blockquote> <p>Help please and thanks in advance.</p>
14,013,422
20
4
null
2012-12-22 22:26:39.593 UTC
7
2020-12-11 12:06:52.157 UTC
2013-12-26 06:52:22.687 UTC
null
368,070
null
1,924,208
null
1
28
iphone|google-maps|sdk|ios-simulator|google-maps-sdk-ios
35,940
<p>@user1924208 I am having the same issue. I have searched the internet tirelessly for the answer and unfortunately I think we are out of luck. The Google API Console is probably showing you the API key for Google Maps v.3 which is NOT the Google Maps iOS API key. Therefore when you use that as your API key, the validation request will always fail.</p> <p>It seems as if they haven't issued many API keys for the iOS version for whatever reason. As frustrating as it is, you will just need to wait until you receive an email from them (not really sure when that will be...).</p> <p>You can confirm this because replacing the current API key with any random string will produce the same results. By the way, this also produces the same results both on simulator and on a real device, which I have tested.</p> <p><strong>Update</strong></p> <p>I just got an email from Google Maps that my API key is now available. I switched out the MKMapKit with GMSServices and things are working. It seems like they are a little more comfortable with releasing API keys now so hopefully you will get yours very soon. </p>
13,872,049
Print empty line?
<p>I am following a beginners tutorial on Python, there is a small exercise where I have to add an extra function call and print a line between verses, this works fine if I print an empty line in between function calls but if I add an empty print line to the end of my <code>happyBirthday()</code> I get an indent error, without the added print line all works fine though, any suggestions as to why?</p> <p>Here is the code:</p> <pre><code>def happyBirthday(person): print("Happy Birthday to you!") print("Happy Birthday to you!") print("Happy Birthday, dear " + person + ".") print("Happy Birthday to you!") print("\n") #error line happyBirthday('Emily') happyBirthday('Andre') happyBirthday('Maria') </code></pre>
13,872,126
7
14
null
2012-12-14 03:03:33.293 UTC
9
2020-05-22 18:36:40.087 UTC
2016-10-22 15:22:21.137 UTC
null
3,885,376
null
823,119
null
1
32
python|python-3.x|newline
234,775
<p>You will always only get an indent error if there is actually an indent error. Double check that your final line is indented the same was as the other lines -- either with spaces or with tabs. Most likely, some of the lines had spaces (or tabs) and the other line had tabs (or spaces).</p> <p>Trust in the error message -- if it says something specific, assume it to be true and figure out why. </p>
14,207,414
How to show changed file name only with 'git log'
<p>Is it able to show changed <strong>file name</strong> only with <code>git log</code>?</p>
14,227,496
6
1
null
2013-01-08 02:40:29.623 UTC
34
2021-07-04 19:51:29.397 UTC
2021-07-04 19:43:43.073 UTC
null
63,550
null
380,774
null
1
167
git
138,685
<p>I use</p> <pre><code>git log --name-only </code></pre> <p>or</p> <pre><code>git log --name-only --oneline </code></pre> <p>for short.</p>
43,258,461
Convert png to jpeg using Pillow
<p>I am trying to convert png to jpeg using pillow. I've tried several scrips without success. These 2 seemed to work on small png images like this one.</p> <p><a href="https://i.stack.imgur.com/m2GGn.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/m2GGn.jpg" alt="enter image description here"></a></p> <p>First code:</p> <pre><code>from PIL import Image import os, sys im = Image.open("Ba_b_do8mag_c6_big.png") bg = Image.new("RGB", im.size, (255,255,255)) bg.paste(im,im) bg.save("colors.jpg") </code></pre> <p>Second code: </p> <pre><code>image = Image.open('Ba_b_do8mag_c6_big.png') bg = Image.new('RGBA',image.size,(255,255,255)) bg.paste(image,(0,0),image) bg.save("test.jpg", quality=95) </code></pre> <p>But if I try to convert a bigger image like this one</p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/9/92/Ba_b_do8mag_c6_big.png" alt=""> </p> <p>I'm getting</p> <pre><code>Traceback (most recent call last): File "png_converter.py", line 14, in &lt;module&gt; bg.paste(image,(0,0),image) File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1328, in paste self.im.paste(im, box, mask.im) ValueError: bad transparency mask </code></pre> <p>What am i doing wrong?</p>
43,258,974
4
2
null
2017-04-06 14:44:00.123 UTC
17
2021-11-07 15:54:31.01 UTC
2019-08-08 14:46:11.06 UTC
null
355,230
null
7,161,215
null
1
80
python|python-3.x|image|python-imaging-library
129,701
<p>You should use convert() method:</p> <pre><code>from PIL import Image im = Image.open("Ba_b_do8mag_c6_big.png") rgb_im = im.convert('RGB') rgb_im.save('colors.jpg') </code></pre> <p>more info: <a href="http://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.convert" rel="noreferrer">http://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.Image.convert</a></p>
32,656,888
Recursive use of Stream.flatMap()
<p>Consider the following class:</p> <pre><code>public class Order { private String id; private List&lt;Order&gt; orders = new ArrayList&lt;&gt;(); @Override public String toString() { return this.id; } // getters &amp; setters } </code></pre> <p>NOTE: <em>It is important to note that I <strong>cannot modify</strong> this class</em>, because I'm consuming it from an external API.</p> <p>Also consider the following hierarchy of orders:</p> <pre><code>Order o1 = new Order(); o1.setId("1"); Order o11 = new Order(); o11.setId("1.1"); Order o111 = new Order(); o111.setId("1.1.1"); List&lt;Order&gt; o11Children = new ArrayList&lt;&gt;(Arrays.asList(o111)); o11.setOrders(o11Children); Order o12 = new Order(); o12.setId("1.2"); List&lt;Order&gt; o1Children = new ArrayList&lt;&gt;(Arrays.asList(o11, o12)); o1.setOrders(o1Children); Order o2 = new Order(); o2.setId("2"); Order o21 = new Order(); o21.setId("2.1"); Order o22 = new Order(); o22.setId("2.2"); Order o23 = new Order(); o23.setId("2.3"); List&lt;Order&gt; o2Children = new ArrayList&lt;&gt;(Arrays.asList(o21, o22, o23)); o2.setOrders(o2Children); List&lt;Order&gt; orders = new ArrayList&lt;&gt;(Arrays.asList(o1, o2)); </code></pre> <p>Which could be visually represented this way:</p> <pre><code>1 1.1 1.1.1 1.2 2 2.1 2.2 2.3 </code></pre> <p>Now, I want to flatten this hierarchy of orders into a <code>List</code>, so that I get the following:</p> <pre><code>[1, 1.1, 1.1.1, 1.2, 2, 2.1, 2.2, 2.3] </code></pre> <p>I've managed to do it by recursively using <code>flatMap()</code> (along with a helper class), as follows:</p> <pre><code>List&lt;Order&gt; flattened = orders.stream() .flatMap(Helper::flatten) .collect(Collectors.toList()); </code></pre> <p>This is the helper class:</p> <pre><code>public final class Helper { private Helper() { } public static Stream&lt;Order&gt; flatten(Order order) { return Stream.concat( Stream.of(order), order.getOrders().stream().flatMap(Helper::flatten)); // recursion here } } </code></pre> <p>The following line:</p> <pre><code>System.out.println(flattened); </code></pre> <p>Produces the following output:</p> <pre><code>[1, 1.1, 1.1.1, 1.2, 2, 2.1, 2.2, 2.3] </code></pre> <p>So far so good. The result is absolutely correct.</p> <p>However, <a href="https://stackoverflow.com/questions/29229373/why-filter-after-flatmap-is-not-completely-lazy-in-java-streams"><strong>after reading this question</strong></a>, I had some concerns regarding the usage of <code>flatMap()</code> within a recursive method. Particularly, I wanted to know how the stream was being expanded (if that's the term). So I modified the <code>Helper</code> class and used <code>peek(System.out::println)</code> to check this:</p> <pre><code>public static final class Helper { private Helper() { } public static Stream&lt;Order&gt; flatten(Order order) { return Stream.concat( Stream.of(order), order.getOrders().stream().flatMap(Helper::flatten)) .peek(System.out::println); } } </code></pre> <p>And the output was:</p> <pre><code>1 1.1 1.1 1.1.1 1.1.1 1.1.1 1.2 1.2 2 2.1 2.1 2.2 2.2 2.3 2.3 </code></pre> <p>I'm not sure if this is the output that should be printed.</p> <p>So, I wonder if it's OK to let intermediate streams contain repeated elements. Furthermore, what are the pros and cons of this approach? Is it correct, after all, to use <code>flatMap()</code> this way? Is there a better way to achieve the same?</p>
32,657,824
2
4
null
2015-09-18 16:30:45.37 UTC
7
2015-09-19 01:13:33.3 UTC
2017-05-23 12:02:13.08 UTC
null
-1
null
1,876,620
null
1
43
java|java-8|java-stream
26,386
<p>Well, I used the same pattern with a generic <code>Tree</code> class and didn’t have a wrong feeling with it. The only difference is, that the <code>Tree</code> class itself offered a <code>children()</code> and <code>allDescendants()</code> methods, both returning a <code>Stream</code> and the latter building on the former. This is related to <a href="https://stackoverflow.com/q/24676877/2711488">“Should I return a Collection or a Stream?”</a> and <a href="https://stackoverflow.com/q/28805077/2711488">“Naming java methods that return streams”</a>.</p> <p>From a <code>Stream</code>s perspective, there is no difference between a <code>flatMap</code> to children of a different type (i.e. when traversing a property) and a <code>flatMap</code> to children of the same type. There is also no problem if the returned stream contains the same element again, as there is no relationship between the elements of the streams. In principle, you can use <code>flatMap</code> as a <code>filter</code> operation, using the pattern <code>flatMap(x -&gt; condition? Stream.of(x): Stream.empty())</code>. It’s also possible to use it to duplicate elements like in <a href="https://stackoverflow.com/a/32520472/2711488">this answer</a>.</p>
519,107
jQuery autocomplete tagging plug-in like StackOverflow's input tags?
<p>What solutions accomplish the same auto-completion that SO uses for entering tags?</p> <p>There are plugins that can handle one word but I haven't seen any that handle multiple words.</p>
2,674,466
6
7
null
2009-02-06 04:27:57.913 UTC
374
2022-03-02 21:49:35.747 UTC
2015-05-21 14:06:17.453 UTC
d03boy
20,471
d03boy
20,471
null
1
532
jquery|autocomplete|tags
210,711
<p>In order of activity, demos/examples available, and simplicity:</p> <ul> <li>(<a href="https://github.com/yairEO/tagify#demo-page" rel="noreferrer">demo</a>) <a href="https://github.com/yairEO/tagify" rel="noreferrer">https://github.com/yairEO/tagify</a></li> <li>(<a href="https://aehlke.github.io/tag-it/examples.html" rel="noreferrer">demo</a>) <a href="https://github.com/aehlke/tag-it" rel="noreferrer">https://github.com/aehlke/tag-it</a></li> <li>(<a href="http://xoxco.com/projects/code/tagsinput/" rel="noreferrer">demo</a>) <a href="https://ioncache.github.io/Tag-Handler/" rel="noreferrer">https://ioncache.github.io/Tag-Handler/</a></li> <li>(<a href="http://textextjs.com/" rel="noreferrer">demo</a>) <a href="http://textextjs.com/" rel="noreferrer">http://textextjs.com/</a></li> <li>(<a href="http://tagedit.webwork-albrecht.de/playground.html" rel="noreferrer">demo</a>) <a href="https://github.com/webworka/Tagedit" rel="noreferrer">https://github.com/webworka/Tagedit</a></li> <li>(<a href="http://documentcloud.github.com/visualsearch/#demo" rel="noreferrer">demo</a>) <a href="https://github.com/documentcloud/visualsearch/" rel="noreferrer">https://github.com/documentcloud/visualsearch/</a></li> <li>(<a href="http://harvesthq.github.io/chosen/#multiple-select" rel="noreferrer">demo</a>) <a href="http://harvesthq.github.io/chosen/" rel="noreferrer">http://harvesthq.github.io/chosen/</a> (this isn't really a tagging plugin)</li> <li>(demo?) <a href="http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/" rel="noreferrer">http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples/</a></li> <li>(demo?) <a href="http://jcesar.artelogico.com/jquery-tagselector/" rel="noreferrer">http://jcesar.artelogico.com/jquery-tagselector/</a></li> <li>(demo?) <a href="http://remysharp.com/wp-content/uploads/2007/12/tagging.php" rel="noreferrer">http://remysharp.com/wp-content/uploads/2007/12/tagging.php</a></li> <li>(demo?) <a href="http://pietschsoft.com/post/2011/09/09/Tag-Editor-Field-using-jQuery-similar-to-StackOverflow.aspx" rel="noreferrer">http://pietschsoft.com/post/2011/09/09/Tag-Editor-Field-using-jQuery-similar-to-StackOverflow.aspx</a></li> </ul> <p>Related:</p> <ul> <li><a href="https://meta.stackexchange.com/questions/100669/feedback-wanted-improved-tag-editor">https://meta.stackexchange.com/questions/100669/feedback-wanted-improved-tag-editor</a></li> </ul>
1,275,484
Good plotting library for C?
<p>My question is very similar in spirit to this question: <a href="https://stackoverflow.com/questions/1120542/what-is-the-best-plotting-library-for-python">What is the best plotting library for Python?</a></p> <p><strong>What is my best bet for plotting data in C?</strong> Am I better off forgoing a library and just generating data that I can feed directly into <a href="http://en.wikipedia.org/wiki/Gnuplot" rel="noreferrer">gnuplot</a>?</p> <p>My impetus for this question is being able to visualize DSP transformations while studying the excellent resources found in an <a href="https://stackoverflow.com/questions/1253116/learning-digital-signal-processing">earlier question of mine</a>. So the focus is really just 2D plots, histograms, etc.; 3D isn't as important right now.</p>
1,275,498
6
1
null
2009-08-14 00:47:46.873 UTC
15
2018-05-24 02:09:14.12 UTC
2017-05-23 12:10:17.723 UTC
null
-1
null
103,058
null
1
38
c|plot|gnuplot
53,379
<p>I think you are on the right track with gnuplot. For what you want, it's very powerful and flexible.</p> <p>However, you may want to consider writing to gnuplot directly from your application instead of creating data and feeding it. There is an <a href="http://ndevilla.free.fr/gnuplot/" rel="noreferrer">ANSI C API to gnuplot</a> available.</p>
544,474
Can you help me understand this? "Common REST Mistakes: Sessions are irrelevant"
<p>Disclaimer: I'm new to the REST school of thought, and I'm trying to wrap my mind around it.</p> <p>So, I'm reading this page, <a href="http://prescod.net/rest/mistakes/" rel="noreferrer">Common REST Mistakes</a>, and I've found I'm completely baffled by the section on sessions being irrelevant. This is what the page says:</p> <blockquote> <p>There should be no need for a client to "login" or "start a connection." HTTP authentication is done automatically on every message. Client applications are consumers of resources, not services. Therefore there is nothing to log in to! Let's say that you are booking a flight on a REST web service. You don't create a new "session" connection to the service. Rather you ask the "itinerary creator object" to create you a new itinerary. You can start filling in the blanks but then get some totally different component elsewhere on the web to fill in some other blanks. There is no session so there is no problem of migrating session state between clients. There is also no issue of "session affinity" in the server (though there are still load balancing issues to continue).</p> </blockquote> <p>Okay, I get that HTTP authentication is done automatically on every message - but how? Is the username/password sent with every request? Doesn't that just increase attack surface area? I feel like I'm missing part of the puzzle.</p> <p>Would it be bad to have a REST service, say, <code>/session</code>, that accepts a GET request, where you'd pass in a username/password as part of the request, and returns a session token if the authentication was successful, that could be then passed along with subsequent requests? Does that make sense from a REST point of view, or is that missing the point?</p>
544,548
6
1
null
2009-02-13 02:07:55.917 UTC
87
2014-02-12 20:45:11.3 UTC
2011-07-05 22:28:38.917 UTC
null
446,591
unforgiven3
18,505
null
1
162
session|rest
40,465
<p>To be RESTful, each HTTP request should carry enough information by itself for its recipient to process it to be in complete harmony with the stateless nature of HTTP.</p> <blockquote> <p>Okay, I get that HTTP authentication is done automatically on every message - but how?</p> </blockquote> <p>Yes, the username and password is sent with every request. The common methods to do so are <strong>basic access authentication</strong> and <strong>digest access authentication</strong>. And yes, an eavesdropper can capture the user's credentials. One would thus encrypt all data sent and received using <strong>Transport Layer Security (TLS)</strong>.</p> <blockquote> <p>Would it be bad to have a REST service, say, /session, that accepts a GET request, where you'd pass in a username/password as part of the request, and returns a session token if the authentication was successful, that could be then passed along with subsequent requests? Does that make sense from a REST point of view, or is that missing the point?</p> </blockquote> <p>This would not be <strong>RESTful</strong> since it carries state but it is however quite common since it's a convenience for users; a user does not have to login each time. </p> <p>What you describe in a "session token" is commonly referred to as a <strong>login cookie</strong>. For instance, if you try to login to your Yahoo! account there's a checkbox that says "keep me logged in for 2 weeks". This is essentially saying (in your words) "keep my session token alive for 2 weeks if I login successfully." Web browsers will send such login cookies (and possibly others) with each HTTP request you ask it to make for you.</p>
69,448,131
Kubernetes: what's the difference between Deployment and Replica set?
<p>Both replica set and deployment have the attribute <code>replica: 3</code>, what's the difference between deployment and replica set? Does deployment work via replica set under the hood?</p> <p>configuration of deployment</p> <pre><code>apiVersion: apps/v1 kind: Deployment metadata: name: my-deployment labels: my-label: my-value spec: replicas: 3 selector: matchLabels: my-label: my-value template: metadata: labels: my-label: my-value spec: containers: - name: app-container image: my-image:latest </code></pre> <p>configuration of replica set</p> <pre><code>apiVersion: apps/v1 kind: ReplicaSet metadata: name: my-replicaset labels: my-label: my-value spec: replicas: 3 selector: matchLabels: my-label: my-value template: metadata: labels: my-label: my-value spec: containers: - name: app-container image: my-image:latest </code></pre> <blockquote> <p><a href="https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/#when-to-use-a-replicaset" rel="noreferrer">Kubernetes Documentation</a></p> <p>When to use a ReplicaSet</p> <p>A ReplicaSet ensures that a specified number of pod replicas are running at any given time. However, Deployment is a higher-level concept that manages ReplicaSets and provides declarative updates to Pods along with a lot of other useful features. Therefore, we recommend using Deployments instead of directly using ReplicaSets, unless you require custom update orchestration or don't require updates at all.</p> <p>This actually means that you may never need to manipulate ReplicaSet objects: use a Deployment instead, and define your application in the spec section.</p> </blockquote>
69,448,162
3
4
null
2021-10-05 09:38:29.343 UTC
9
2022-05-31 13:41:48.297 UTC
2021-10-05 10:08:16 UTC
null
5,117,552
null
5,117,552
null
1
43
kubernetes
20,300
<p>A ReplicaSet ensures that a number of Pods is created in a cluster. The pods are called replicas and are the mechanism of availability in Kubernetes. But changing the ReplicaSet will not take effect on existing Pods, so it is not possible easily change, for example, the image version.</p> <p>A deployment is a higher abstraction that manages one or more ReplicaSets to provide controlled rollout of a new version. When the image version is changed in the Deployment, a new ReplicaSet for this version will be created with initially zero replicas. Then it will be scaled to one replica, after that is running, the old ReplicaSet will be scaled down. (The number of newly created pods, the step size so to speak, can be tuned.)</p> <p>As long as you don't have a rollout in progress a deployment will result in a single replicaset with the replication factor managed by the deployment.</p> <p>I would recommend to always use a Deployment and not a bare ReplicaSet.</p>
37,607,911
When to use TaskCreationOptions.LongRunning?
<p>I've wondered this for quite a while, but never really found the answer. </p> <p>I understand that it's a hint for the task scheduler where the task will run on, and that the task scheduler can (or nowadays will?) decide to instantiate a non-thread-pool thread for that task.</p> <p>What I don't know (and surprisingly can't find nowhere on the internet) is some "rule of thumb" when to specify a task as long-running. Is one second long? 30 seconds? A minute? 5 minutes? Does it have a relation with the amount of tasks the application uses? Should I as programmer do some calculation with the #threads in the thread pool, how many Tasks I create, how many will be long-running at the same time, and based on that make a decision whether to use a long running task? </p> <p>Hope to learn something here.</p>
37,611,613
4
4
null
2016-06-03 06:59:23.237 UTC
15
2016-06-06 16:40:43.173 UTC
2016-06-06 16:40:43.173 UTC
null
41,071
null
1,470,327
null
1
76
c#|multithreading|task-parallel-library|task
29,880
<p>It can be quantified, the threadpool manager adds an <em>extra</em> thread beyond the optimum when the existing tp threads don't complete soon enough. It does this twice a second, up to the maximum set by SetMaxThreads(). Which has a <em>very</em> high default value. The optimum is the number of processor cores the machine has available, 4 is typical. Running more threads than available cores can be detrimental due to the context switching overhead.</p> <p>It does this based on the <em>assumption</em> that these existing threads don't make progress because they are not executing enough code. In other words, they block on I/O or a lock too much. Such threads therefore don't use the cores efficiently enough and allowing an extra thread to execute is entirely appropriate to drive up processor usage and get more work done.</p> <p>So it is "long running" when the thread takes more than half a second. Keep in mind that this is a very long time, it equals roughly 4 billion processor instructions on a modern desktop class machine. Unless you are running computationally heavy code like calculating the value of pi to a gazillion digits, thus actually executing those 4 billion instructions, a practical thread can only take this long when it <em>does</em> block too often. Which is very common, something like a dbase query is often slow and executed on a worker thread and consumes little cpu.</p> <p>It is otherwise up to you to verify that the assumption that the threadpool manager will make is accurate. The task should take a long time because it isn't using the processor efficiently. Task Manager is a simple way to see what the processor cores are doing in your program, albeit that it won't tell you exactly what code they are executing. You'll need a unit test to see the thread executing in isolation. The ultimate and only completely accurate way to tell you that using LongRunning was an appropriate choice is to verify that your app indeed gets more work done.</p>
21,196,077
Sublime text 3 - compile program and run in terminal
<p>I am using Ubuntu 12.04, and I was wondering, is it possible to automatically run c++ program from terminal? It really sucks when you have to use build in console because sometimes I make infinite loops by accident and have to restart sublime text to work again. I am using Sublime text 3.</p>
21,196,509
8
4
null
2014-01-17 21:19:50.097 UTC
10
2019-11-12 10:30:57.687 UTC
null
null
null
null
2,648,841
null
1
12
c++|ubuntu|compiler-construction|sublimetext3
58,289
<p>Sublime Text 3 includes two build systems you might be interested in: C++ and Make. The <code>C++.sublime-build</code> file is as follows:</p> <pre class="lang-json prettyprint-override"><code>{ "shell_cmd": "g++ \"${file}\" -o \"${file_path}/${file_base_name}\"", "file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$", "working_dir": "${file_path}", "selector": "source.c, source.c++", "variants": [ { "name": "Run", "shell_cmd": "g++ \"${file}\" -o \"${file_path}/${file_base_name}\" &amp;&amp; \"${file_path}/${file_base_name}\"" } ] } </code></pre> <p>To use it, go to <code>Tools -&gt; Build System</code> and select <code>C++</code>. You can now use <kbd>Ctrl</kbd><kbd>B</kbd> to run the build (top command), or <kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>B</kbd> to run the <code>Run</code> variant.</p>
44,114,463
Stratified Sampling in Pandas
<p>I've looked at the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html" rel="noreferrer">Sklearn stratified sampling docs</a> as well as the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="noreferrer">pandas docs</a> and also <a href="https://stackoverflow.com/questions/41035187/stratified-samples-from-pandas">Stratified samples from Pandas</a> and <a href="https://stackoverflow.com/questions/36997619/sklearn-stratified-sampling-based-on-a-column">sklearn stratified sampling based on a column</a> but they do not address this issue.</p> <p>Im looking for a fast pandas/sklearn/numpy way to generate stratified samples of size n from a dataset. However, for rows with less than the specified sampling number, it should take all of the entries.</p> <p>Concrete example:</p> <p><a href="https://i.stack.imgur.com/Y1EsP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Y1EsP.png" alt="enter image description here"></a></p> <p>Thank you! :)</p>
44,115,314
4
2
null
2017-05-22 13:41:51.287 UTC
24
2022-04-21 03:42:16.303 UTC
null
null
null
null
5,766,416
null
1
61
python|pandas|numpy|scikit-learn
71,650
<p>Use <code>min</code> when passing the number to sample. Consider the dataframe <code>df</code></p> <pre><code>df = pd.DataFrame(dict( A=[1, 1, 1, 2, 2, 2, 2, 3, 4, 4], B=range(10) )) df.groupby('A', group_keys=False).apply(lambda x: x.sample(min(len(x), 2))) A B 1 1 1 2 1 2 3 2 3 6 2 6 7 3 7 9 4 9 8 4 8 </code></pre>
18,138,166
What is a top-level statement in Python?
<p>In the Python Guide's chapter on <a href="http://docs.python-guide.org/en/latest/writing/structure.html" rel="noreferrer">project structure</a>, the term "top-level statement" is brought up a few times. I'm not sure exactly what this refers to. My guess is it's any variable declarations that happen outside of any functions or class methods that fire as soon as a module is loaded. Is this correct? Does it also include a module's <code>import</code> statements?</p>
18,138,250
3
1
null
2013-08-08 23:54:29.21 UTC
8
2020-01-01 14:32:11.07 UTC
null
null
null
null
155,175
null
1
17
python
20,819
<p>It's not just variable declarations (and there aren't any variable declarations anyway). It's pretty much anything that starts at indentation level 0.</p> <pre><code>import sys # top-level 3 + 4 # top-level x = 0 # top-level def f(): # top-level import os # not top-level! return 3 # not top-level if x: # top-level print 3 # not top-level else: print 4 # not top-level, but executes as part of an if statement # that is top-level class TopLevel(object): # top-level x = 3 # not top-level, but executes as part of the class statement def foo(self): # not top-level, but executes as part of the class statement print 5 # not top-level </code></pre>
17,879,735
There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key
<p>In SQL Server , I got this error -> </p> <blockquote> <p>"There are no primary or candidate keys in the referenced table 'BookTitle' that match the referencing column list in the foreign key 'FK_<em>BookCopy</em>_Title__2F10007B'."</p> </blockquote> <p>I first created a relation called the <code>BookTitle</code> relation.</p> <pre><code>CREATE TABLE BookTitle ( ISBN CHAR(17) NOT NULL, Title VARCHAR(100) NOT NULL, Author_Name VARCHAR(30) NOT NULL, Publisher VARCHAR(30) NOT NULL, Genre VARCHAR(20) NOT NULL, Language CHAR(3) NOT NULL, PRIMARY KEY (ISBN, Title)) </code></pre> <p>Then I created a relation called the <code>BookCopy</code> relation. This relation needs to reference to the <code>BookTitle</code> relation's primary key, <code>Title</code>.</p> <pre><code>CREATE TABLE BookCopy ( CopyNumber CHAR(10) NOT NULL, Title VARCHAR(100) NOT NULL, Date_Purchased DATE NOT NULL, Amount DECIMAL(5, 2) NOT NULL, PRIMARY KEY (CopyNumber), FOREIGN KEY (Title) REFERENCES BookTitle(Title)) </code></pre> <p>But I can't create the <code>BookCopy</code> relation because the error stated above appeared. </p> <p>I really appreciate some useful help. </p>
17,879,897
4
0
null
2013-07-26 11:04:57.803 UTC
8
2022-07-14 02:00:45.65 UTC
2013-07-26 11:26:40.847 UTC
null
13,302
null
2,622,438
null
1
56
sql|sql-server|key|candidate
133,928
<p>Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index.</p> <p>At the moment, the only unique index you have is a compound one on <code>ISBN, Title</code> which is your primary key.</p> <p>There are a number of options open to you, depending on exactly what BookTitle holds and the relationship of the data within it.</p> <p>I would hazard a guess that the ISBN is unique for each row in BookTitle. ON the assumption this is the case, then change your primary key to be only on ISBN, and change BookCopy so that instead of Title you have ISBN and join on that.</p> <p>If you need to keep your primary key as <code>ISBN, Title</code> then you either need to store the ISBN in BookCopy as well as the Title, and foreign key on both columns, OR you need to create a unique index on BookTitle(Title) as a distinct index.</p> <p>More generally, you need to make sure that the column or columns you have in your <code>REFERENCES</code> clause match exactly a unique index in the parent table: in your case it fails because you do not have a single unique index on <code>Title</code> alone.</p>
47,038,400
Firebase Authentication via OpenID Connect
<p>I would like to authenticate users against Firebase Authentication via OpenID Connect. In other words:</p> <ul> <li>create a Firebase project</li> <li>add users under authentication</li> <li>get an issuer URL for my project that implements OIDC Discovery</li> <li>get a clientID</li> <li>use the issuer URL and the clientID in my app that acts as an OIDC client to retrieve information / id_token for users in the Firebase Project</li> </ul> <p>The documentation does not mention this possibility, so I'd understand if this was not possible.</p> <p>However:</p> <ul> <li>using OIDC is quite the standard way to do these things</li> <li>there is <a href="https://stackoverflow.com/questions/43989039/using-firebase-openid-connect-provider-as-aws-iam-identity-provider">this</a> and <a href="https://stackoverflow.com/questions/45143700/unable-to-authenticate-using-firebase-open-id-connect-as-amazon-cognito-authenti">this</a> post that actually tell me this is/was possible</li> <li>the OIDC discovery document they mention is actually available my project too, although it is incomplete (missing the endpoint URLs)</li> <li>digging in the GC dev console it seems like OAuth2 is used internally in the Firebase SDK - newly created service accounts inherit some callback URLs that belong to my Firebase project</li> </ul> <p>Implementing my own IDP using Firebase Auth seems to be an overkill, especially that it might already be available.</p> <p>Any hints anyone? </p>
66,388,466
1
3
null
2017-10-31 14:56:42.77 UTC
5
2021-02-26 15:24:51.877 UTC
2017-10-31 15:16:17.027 UTC
null
5,996,134
null
1,824,548
null
1
31
firebase|firebase-authentication|openid-connect
5,044
<p>Old question but I'm surprised no one has answered this.</p> <p>With Firebase you have the choice of using the simpler Firebase Auth or the more comprehensive <a href="https://cloud.google.com/identity-platform" rel="noreferrer">Identity Platform</a> to authenticate your users and <a href="https://cloud.google.com/identity-platform/docs/web/oidc" rel="noreferrer">Identity Platform does support OIDC</a> authentication.</p> <p><a href="https://cloud.google.com/identity-platform/docs/product-comparison" rel="noreferrer">Here's a comparison of the differences.</a></p> <p>Identity Platform just simply needs to be enabled for your project and it will begin authenticating users without changing a line of code. Both services utilize the same Firebase JS SDK for authentication making the transition easy.</p> <p>The only &quot;downside&quot; is that the Identity Platform isn't free, but does have a very generous free tier.</p>
61,412,000
Do I need to use the "import type" feature of TypeScript 3.8 if all of my imports are from my own file?
<p>I have a simple file <code>types.ts</code> that defines some types:</p> <pre><code>export interface MyInterface { // ... } export const enum MyEnum { // ... } export type MyType = { // ... } </code></pre> <p>I have read about the new feature <code>import type</code> for the latest typescript <a href="https://devblogs.microsoft.com/typescript/announcing-typescript-3-8-beta/#type-only-imports-exports" rel="noreferrer">here</a>. As far as I understand it is meant to fix specific problems which seems mostly to happen when importing from .js files.</p> <p>I can import my types with both <code>import</code> and <code>import type</code> statements. Both seems to work equally fine. The question is should I prefer <code>import type</code> for being more explicit and helping me to avoid some theoretical edge-case problems or can I just use <code>import</code> for simplicity and rely on <code>import elision</code> to remove these from compiled code?</p> <p>In other words: is there any benefit of using <code>import type</code> here or it should rather be used for specific cases to work around <code>import elision</code> shortcomings?</p>
64,243,357
1
1
null
2020-04-24 15:33:04.737 UTC
9
2020-10-07 11:47:18.82 UTC
2020-04-26 13:48:52.77 UTC
null
1,671,558
null
1,671,558
null
1
74
typescript|import|module|elision|typescript3.8
46,896
<p><em>Short answer:</em> Being more explicit by using <code>import type</code> and <code>export type</code> statements seem to yield explicable benefits by <strong>safeguarding against edge-case problems</strong>, as well as <strong>giving current and upcoming tooling better ground for improving processing performance and reliability with type definition analysis</strong>.</p> <p><em>Long answer:</em></p> <p>As <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-8.html" rel="noreferrer">TypeScript 3.8 release notes</a> say:</p> <blockquote> <p><code>import type</code> only imports declarations to be used for type annotations and declarations. <strong>It always gets fully erased, so there’s no remnant of it at runtime.</strong> Similarly, export type only provides an export that can be used for type contexts, and is also erased from TypeScript’s output.</p> </blockquote> <p>Here are two practical examples how these remnant imports can cause errors in build or runtime:</p> <ul> <li>Strange type-related Webpack error fixed by <code>import type</code> statement, a blog post: <a href="https://medium.com/javascript-in-plain-english/leveraging-type-only-imports-and-exports-with-typescript-3-8-5c1be8bd17fb" rel="noreferrer">Leveraging Type-Only imports and exports with TypeScript 3.8</a></li> <li>An SO question about <a href="https://stackoverflow.com/questions/40982927/using-import-type-statement-to-fix-circular-dependency-reference-error/40984510">remnant imports causing circular dependency reference errors</a></li> </ul> <p>Another benefit relates to tooling that is analyzing type definitions. Currently there are details about benefits with bundler setups using Babel, but may currently or later benefit other tooling as well (like IDE performance).</p> <p>For Babel users manually configuring their setup: If you are using Babel 7.9=&gt; in your bundler setup with TS 3.8=&gt;, then you can possibly remove the previously needed <code>@babel/plugin-transform-typescript</code> plugin.</p> <p>For those setups that are using pre-built Babel presets: Babel's team is recommending of configuring Babel presets so that explicit type-only imports are to be used.</p> <p>Read more in a blog post: <a href="https://www.infoq.com/news/2020/03/babel-79-bundles-typescript/" rel="noreferrer">Babel 7.9 Reduces Bundle Sizes, Adds TypeScript 3.8 Support</a>.</p> <p>More of relevant info about <a href="https://www.typescriptlang.org/docs/handbook/babel-with-typescript.html" rel="noreferrer">Using Babel with TypeScript</a> in TS docs.</p> <p>Detailed look into benefits using and how <code>isolatedModules</code> TS compiler option works <a href="https://levelup.gitconnected.com/improving-babel-support-for-typescript-with-type-only-imports-28cb209d9460" rel="noreferrer">type-only imports — A new TypeScript feature that benefits Babel users</a></p>
21,328,055
How to target the href to div
<p>Here i am trying to open and get the contents of one div to target div on-click on a href. Here i have table where i have hrefs which has the link to div ids, and i have an target div which is empty.</p> <p>when i click the href links, the linked div contents should open in the target div.</p> <p>for ex: for link <code>fea1</code> i have linked id <code>#m1</code>, when i click the <code>fea1</code>, the <code>#m1</code> contents should appear in target div.</p> <p>How can i do this???</p> <p>here is my code:</p> <p>HTML:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; Example &lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="css/style.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;table border="0"&gt; &lt;tr&gt; &lt;td&gt; &lt;hr&gt; &lt;a href="#m1"&gt; fea1 &lt;/a&gt; &lt;br&gt; &lt;hr&gt; &lt;a href="#m2"&gt; fea2 &lt;/a&gt; &lt;br&gt; &lt;hr&gt; &lt;a href="#m3"&gt; fea3 &lt;/a&gt; &lt;br&gt; &lt;hr&gt; &lt;a href="#m4"&gt; fea4 &lt;/a&gt; &lt;br&gt; &lt;hr&gt; &lt;a href="#m5"&gt; fea5 &lt;/a&gt; &lt;br&gt; &lt;hr&gt; &lt;a href="#m6"&gt; fea6 &lt;/a&gt; &lt;br&gt; &lt;hr&gt; &lt;a href="#m7"&gt; fea7 &lt;/a&gt; &lt;br&gt; &lt;hr&gt; &lt;a href="#m8"&gt; fea8 &lt;/a&gt; &lt;br&gt; &lt;hr&gt; &lt;a href="#m9"&gt; fea9 &lt;/a&gt; &lt;hr&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div class="target"&gt; &lt;/div&gt; &lt;div id="m1"&gt; dasdasdasd &lt;/div&gt; &lt;div id="m2"&gt; dadasdasdasd &lt;/div&gt; &lt;div id="m3"&gt; sdasdasds &lt;/div&gt; &lt;div id="m4"&gt; dasdasdsad &lt;/div&gt; &lt;div id="m5"&gt; dasdasd &lt;/div&gt; &lt;div id="m6"&gt; asdasdad &lt;/div&gt; &lt;div id="m7"&gt; asdasda &lt;/div&gt; &lt;div id="m8"&gt; dasdasd &lt;/div&gt; &lt;div id="m9"&gt; dasdasdsgaswa &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>css:</p> <pre><code>a{ text-decoration:none; color:black; } .target{ width:50%; height:200px; border:solid black 1px; } #m1, #m2, #m3, #m4, #m5, #m6, #m7, #m8, #m9{ display:none; } </code></pre>
21,328,501
7
14
null
2014-01-24 08:42:11.943 UTC
8
2018-10-04 05:17:13.643 UTC
2014-01-24 08:46:18.097 UTC
null
2,590,090
null
2,590,090
null
1
19
html|css
161,789
<p>You can put all your <code>#m1</code>...<code>#m9</code> divs into <code>.target</code> and display them based on fragment identifier (hash) using <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/%3atarget"><code>:target</code></a> pseudo-class. It doesn't move the contents between divs, but I think the effect is close to what you wanted to achieve.</p> <p><strong><a href="http://jsfiddle.net/hn3U7/1/">Fiddle</a></strong></p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="target"&gt; &lt;div id="m1"&gt; dasdasdasd m1 &lt;/div&gt; &lt;!-- etc... --&gt; &lt;div id="m9"&gt; dasdasdsgaswa m9 &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.target { width:50%; height:200px; border:solid black 1px; } .target &gt; div { display:none; } .target &gt; div:target{ display:block; } </code></pre>
2,173,356
How to switch to a different buffer from a terminal buffer
<p>I've been using emacs for few weeks and it's been great so far - coming from <code>vim</code> was easier than I expected (actually - emacs' keyboard shortcuts feel more... natural).</p> <p>I have added few customizations like moving between buffers using <code>M-Left/Right/Up/Down</code> because <code>C-x o</code> felt a little bit too slow when I had four files opened at once.</p> <p>So far - so good :-)</p> <p>One thing bugs me though:</p> <ol> <li>I open some splits using <code>C-x 3</code> and <code>C-x 2</code></li> <li>I open the terminal in one of them using <code>M-x term ENT</code></li> <li>How do I switch to different split using keyboard? </li> </ol> <p>Usual shortcuts obviously don't work - terminal is intercepting every emacs command, and I have to click on different buffer to activate it.</p>
2,173,749
5
7
null
2010-01-31 21:12:45.177 UTC
21
2011-11-11 06:41:26.793 UTC
2010-02-01 09:47:19.877 UTC
null
130,896
null
130,896
null
1
68
emacs|emacs23
15,456
<p>In term-mode, any regular <code>C-x whatever</code> keybinding becomes <code>C-c whatever</code> instead.</p>
2,165,078
A reference can not be NULL or it can be NULL?
<p>I have read from the Wikipedia that:</p> <blockquote> <p>“References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.”</p> </blockquote> <p>But I don’t believe because of following code, look at it, compiler gives no error:</p> <pre><code>class person { public: virtual void setage()=0; }; int main() { person *object=NULL; person &amp;object1=*object; } </code></pre> <p>Please elaborate this point.</p>
2,165,109
7
9
null
2010-01-29 20:52:23.55 UTC
10
2019-06-17 09:04:44.177 UTC
2019-06-17 09:04:44.177 UTC
null
9,254,404
null
238,919
null
1
13
c++|oop
14,387
<p>Saying <code>person &amp;object1=*object</code> is not the same thing as saying <code>person &amp;object1=NULL</code>. Probably the compiler is just not smart enough to find out that you are dereferencing null pointer, but you'll get a runtime error anyway. So they are kind of true still ;)</p>
1,726,391
Matplotlib: draw grid lines behind other graph elements
<p>In Matplotlib, I make dashed grid lines as follows:</p> <pre><code>fig = pylab.figure() ax = fig.add_subplot(1,1,1) ax.yaxis.grid(color='gray', linestyle='dashed') </code></pre> <p>however, I can't find out how (or even if it is possible) to make the grid lines be drawn behind other graph elements, such as bars. Changing the order of adding the grid versus adding other elements makes no difference. </p> <p>Is it possible to make it so that the grid lines appear behind everything else?</p>
1,726,527
7
2
null
2009-11-13 00:30:55.11 UTC
32
2021-11-27 14:39:49.5 UTC
2015-07-03 21:37:18.533 UTC
null
832,621
null
110,793
null
1
178
python|matplotlib|grid
137,963
<p>According to this - <a href="http://matplotlib.1069221.n5.nabble.com/axis-elements-and-zorder-td5346.html" rel="noreferrer">http://matplotlib.1069221.n5.nabble.com/axis-elements-and-zorder-td5346.html</a> - you can use <code>Axis.set_axisbelow(True)</code></p> <p>(I am currently installing matplotlib for the first time, so have no idea if that's correct - I just found it by googling "matplotlib z order grid" - "z order" is typically used to describe this kind of thing (z being the axis "out of the page"))</p>
1,568,288
escaping the .each { } iteration early in Ruby
<p>code: </p> <pre><code> c = 0 items.each { |i| puts i.to_s # if c &gt; 9 escape the each iteration early - and do not repeat c++ } </code></pre> <p>I want to grab the first 10 items then leave the "each" loop. </p> <p>What do I replace the commented line with? is there a better approach? something more Ruby idiomatic?</p>
1,568,445
8
1
null
2009-10-14 18:56:37.783 UTC
3
2017-01-21 14:27:55.06 UTC
null
null
null
null
36,590
null
1
42
ruby|loops|iterator|enumerator
63,541
<p>While the <code>break</code> solution works, I think a more functional approach really suits this problem. You want to <code>take</code> the first 10 elements and print them so try</p> <pre><code>items.take(10).each { |i| puts i.to_s } </code></pre>
2,080,150
When should I use static methods in a class and what are the benefits?
<p>I have concept of static variables but what are the benefits of static methods in a class. I have worked on some projects but I did not make a method static. Whenever I need to call a method of a class, I create an object of that class and call the desired method. </p> <p><strong>Q:</strong> Static variable in a method holds it's value even when method is executed but accessible only in its containing method but what is the best definition of static method? </p> <p><strong>Q:</strong> Is calling the static method without creating object of that class is the only benefit of static method? </p> <p><strong>Q:</strong> What is the accessible range for static method? </p> <p>Thanks</p>
2,080,166
10
1
null
2010-01-17 06:10:45.45 UTC
24
2015-07-11 19:03:34.053 UTC
2010-09-20 05:47:06.067 UTC
null
149,206
null
149,206
null
1
68
oop|static-methods|static-variables
60,617
<p>Your description of a static variable is more fitting to that found in C. The concept of a static variable in Object Oriented terms is conceptually different. I'm drawing from Java experience here. Static methods and fields are useful when they conceptually don't belong to an instance of something. </p> <p>Consider a Math class that contains some common values like Pi or e, and some useful functions like sin and cos. It really does not make sense to create separate instances to use this kind of functionality, thus they are better as statics:</p> <pre><code>// This makes little sense Math m = new Math(); float answer = m.sin(45); // This would make more sense float answer = Math.sin(45); </code></pre> <p>In OO languages (again, from a Java perspective) functions, or better known as methods, cannot have static local variables. Only classes can have static members, which as I've said, resemble little compared to the idea of static in C. </p>
1,932,150
Can Android do peer-to-peer ad-hoc networking?
<p>Is it possible to set up Android in ad-hoc peer-to-peer wifi mode? For example, I would like to have one phone broadcast a message, and have all peers in the network receive the broadcast, without having a server. I would like to use wifi since bluetooth range is more limited.</p>
1,932,171
11
2
null
2009-12-19 06:17:06.63 UTC
42
2015-07-10 13:33:56.683 UTC
2012-04-11 23:49:52.83 UTC
null
-1
null
234,933
null
1
98
android|networking|wifi|p2p|adhoc
140,412
<p>Here's a bug report on the feature you're requesting.</p> <p>It's status is "reviewed" but I don't believe it's been implemented yet.</p> <p><a href="http://code.google.com/p/android/issues/detail?id=82" rel="noreferrer">http://code.google.com/p/android/issues/detail?id=82</a></p>
2,322,234
How to find serial number of Android device?
<p>I need to use a unique ID for an Android app and I thought the serial number for the device would be a good candidate. How do I retrieve the serial number of an Android device in my app ?</p>
2,322,494
18
3
null
2010-02-23 22:26:39.053 UTC
77
2021-02-22 01:39:41.77 UTC
2012-09-10 09:10:46.523 UTC
null
648,313
null
246,793
null
1
115
android|serial-number
242,278
<pre><code>TelephonyManager tManager = (TelephonyManager)myActivity.getSystemService(Context.TELEPHONY_SERVICE); String uid = tManager.getDeviceId(); </code></pre> <p>getSystemService is a method from the Activity class. getDeviceID() will return the MDN or MEID of the device depending on which radio the phone uses (GSM or CDMA). </p> <p>Each device MUST return a unique value here (assuming it's a phone). This should work for any Android device with a sim slot or CDMA radio. You're on your own with that Android powered microwave ;-)</p>
1,878,001
How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?
<p>How do I implement the following (Python pseudocode) in C++?</p> <pre><code>if argv[1].startswith('--foo='): foo_value = int(argv[1][len('--foo='):]) </code></pre> <p>(For example, if <code>argv[1]</code> is <code>--foo=98</code>, then <code>foo_value</code> is <code>98</code>.)</p> <p><strong>Update:</strong> I'm hesitant to look into Boost, since I'm just looking at making a very small change to a simple little command-line tool (I'd rather not have to learn how to link in and use Boost for a minor change).</p>
40,441,240
23
3
null
2009-12-10 00:57:26.82 UTC
49
2021-07-22 15:59:38.33 UTC
2018-11-16 16:11:03.64 UTC
null
2,074,605
null
4,766
null
1
374
c++|string|parsing|substring|startswith
442,923
<p>Use <a href="http://www.cplusplus.com/reference/string/string/rfind/" rel="noreferrer"><code>rfind</code></a> overload that takes the search position <code>pos</code> parameter, and pass zero for it:</p> <pre><code>std::string s = &quot;tititoto&quot;; if (s.rfind(&quot;titi&quot;, 0) == 0) { // pos=0 limits the search to the prefix // s starts with prefix } </code></pre> <p>Who needs anything else? Pure STL!</p> <p>Many have misread this to mean &quot;search backwards through the whole string looking for the prefix&quot;. That would give the wrong result (e.g. <code>string(&quot;tititito&quot;).rfind(&quot;titi&quot;)</code> returns 2 so when compared against <code>== 0</code> would return false) and it would be inefficient (looking through the whole string instead of just the start). But it does not do that because it passes the <code>pos</code> parameter as <code>0</code>, which limits the search to only match at that position <em>or earlier</em>. For example:</p> <pre><code>std::string test = &quot;0123123&quot;; size_t match1 = test.rfind(&quot;123&quot;); // returns 4 (rightmost match) size_t match2 = test.rfind(&quot;123&quot;, 2); // returns 1 (skipped over later match) size_t match3 = test.rfind(&quot;123&quot;, 0); // returns std::string::npos (i.e. not found) </code></pre>
33,854,795
Does a Python-like virtualenv exist in Julia?
<p>Is there a Python-like virtualenv environment simulator for Julia where one can do development in a local, virtual environment?</p>
33,857,601
3
3
null
2015-11-22 12:31:53.28 UTC
5
2019-11-23 13:55:25.703 UTC
null
null
null
null
4,993,513
null
1
38
julia
9,245
<p>Currently (julia 1.2) is able to manage virual environments via it's builtin <code>Pkg</code> standard library module:</p> <ul> <li><a href="https://docs.julialang.org/en/v1/stdlib/Pkg" rel="noreferrer">https://docs.julialang.org/en/v1/stdlib/Pkg</a></li> </ul> <pre><code>julia&gt; ] (v1.2) pkg&gt; activate tutorial [ Info: activating new environment at `/tmp/tutorial/Project.toml`. (tutorial) pkg&gt; (tutorial) pkg&gt; status Status `/tmp/tutorial/Project.toml` (empty environment) (tutorial) pkg&gt; add Example ... (tutorial) pkg&gt; status Status `/tmp/tutorial/Project.toml` [7876af07] Example v0.5.1 </code></pre> <p><s>There is <a href="https://github.com/Rory-Finnegan/Playground.jl" rel="noreferrer"><code>Playground.jl</code></a></s></p> <blockquote> <p><s> A package for managing julia sandboxes like python's virtualenv (with a little influence from pyenv and virtualenvwrapper)</s></p> </blockquote>
33,784,369
RecyclerView - Get view at particular position
<p>I have an activity with a <code>RecyclerView</code> and an <code>ImageView</code>. I am using the <code>RecyclerView</code> to show a list of images horizontally. When I click on an image in the <code>RecyclerView</code> the <code>ImageView</code> in the activity should show a bigger picture of the image. So far everything works fine.</p> <p>Now there are two more <code>ImageButtons</code> in the activity: <code>imageButton_left</code> and <code>imageButton_right</code>. When I click on <code>imageButton_left</code>, the image in the <code>ImageView</code> should turn left and also, the thumbnail in the <code>RecyclerView</code> should reflect this change. Similar is the case with <code>imageButton_right</code>.</p> <p>I am able to rotate the <code>ImageView</code>. But, how can I rotate the thumbnail in the <code>RecyclerView</code>? How can I get the <code>ViewHolder</code>'s <code>ImageView</code>? </p> <p>Code:</p> <p>Activity XML:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;android.support.v7.widget.RecyclerView android:id="@+id/recyclerview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" /&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:orientation="vertical"&gt; &lt;ImageView android:id="@+id/original_image" android:layout_width="200dp" android:layout_height="200dp" android:scaleType="fitXY" android:src="@drawable/image_not_available_2" /&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:gravity="center_horizontal" android:orientation="horizontal"&gt; &lt;ImageButton android:id="@+id/imageButton_left" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="20dp" android:background="@drawable/rotate_left_icon" /&gt; &lt;ImageButton android:id="@+id/imageButton_right" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/rotate_right_icon" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>My Activity Code:</p> <pre><code>public class SecondActivity extends AppCompatActivity implements IRecyclerViewClickListener { RecyclerView mRecyclerView; LinearLayoutManager mLayoutManager; RecyclerViewAdapter mRecyclerViewAdapter; List&lt;String&gt; urls = new ArrayList&lt;String&gt;(); ImageView mOriginalImageView; ImageButton mLeftRotate, mRightRotate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); urls.clear(); mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview); mLayoutManager = new LinearLayoutManager(this, android.support.v7.widget.LinearLayoutManager.HORIZONTAL, false); mLayoutManager.setOrientation(android.support.v7.widget.LinearLayoutManager.HORIZONTAL); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerViewAdapter = new RecyclerViewAdapter(this, urls); mRecyclerView.setAdapter(mRecyclerViewAdapter); mOriginalImageView = (ImageView) findViewById(R.id.original_image); mLeftRotate = (ImageButton) findViewById(R.id.imageButton_left); mLeftRotate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mOriginalImageView.setRotation(mOriginalImageView.getRotation() - 90); } }); mRightRotate = (ImageButton) findViewById(R.id.imageButton_right); mRightRotate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mOriginalImageView.setRotation(mOriginalImageView.getRotation() + 90); } }); Intent intent = getIntent(); if (intent != null) { String portfolio = intent.getStringExtra("portfolio"); try { JSONArray jsonArray = new JSONArray(portfolio); for (int i = 0; i &lt; jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); String url = jsonObject.getString("url"); urls.add(url); } Log.d(Const.DEBUG, "URLs: " + urls.toString()); mRecyclerViewAdapter.notifyDataSetChanged(); } catch (Exception e) { e.printStackTrace(); } } } @Override public void onItemClick(int position) { Picasso.with(this).load(urls.get(position)).into(mOriginalImageView); } } </code></pre> <p>My Custom Adapter for RecyclerView:</p> <pre><code>public class RecyclerViewAdapter extends RecyclerView.Adapter&lt;RecyclerViewAdapter.ViewHolder&gt; { Context context; List&lt;String&gt; mUrls = new ArrayList&lt;String&gt;(); IRecyclerViewClickListener mIRecyclerViewClickListener; public int position; public int getPosition() { return position; } public void setPosition(int position) { this.position = position; } public RecyclerViewAdapter(Context context, List&lt;String&gt; urls) { this.context = context; this.mUrls.clear(); this.mUrls = urls; Log.d(Const.DEBUG, "Urls Size: " + urls.size()); Log.d(Const.DEBUG, urls.toString()); if (context instanceof IRecyclerViewClickListener) mIRecyclerViewClickListener = (IRecyclerViewClickListener) context; else Log.d(Const.DEBUG, "Implement IRecyclerViewClickListener in Activity"); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_horizontal_recyclerview, parent, false); ViewHolder holder = new ViewHolder(view); return holder; } @Override public void onBindViewHolder(ViewHolder holder, int position) { Picasso.with(context).load(mUrls.get(position)).into(holder.mImageView); } @Override public int getItemCount() { return mUrls.size(); } public void rotateThumbnail() { } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public ImageView mImageView; public View v; public ViewHolder(View v) { super(v); v.setTag(getAdapterPosition()); v.setOnClickListener(this); this.mImageView = (ImageView) v.findViewById(R.id.image); } @Override public void onClick(View v) { this.v = v; mIRecyclerViewClickListener.onItemClick(getAdapterPosition()); } } } </code></pre>
33,798,938
16
4
null
2015-11-18 15:43:25.12 UTC
51
2022-04-14 08:20:43.91 UTC
2017-11-15 16:04:15.467 UTC
null
7,609,347
null
1,777,523
null
1
173
java|android|android-recyclerview|widget|position
229,218
<p>I suppose you are using a <a href="http://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html" rel="noreferrer"><code>LinearLayoutManager</code></a> to show the list. It has a nice method called <a href="http://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html#findViewByPosition%28int%29" rel="noreferrer"><code>findViewByPosition</code></a> that</p> <blockquote> <p>Finds the view which represents the given adapter position.</p> </blockquote> <p>All you need is the adapter position of the item you are interested in.</p> <p><strong>edit</strong>: as noted by <em>Paul Woitaschek</em> in the comments, <code>findViewByPosition</code> is a method of <code>LayoutManager</code> so it would work with all LayoutManagers (i.e. <code>StaggeredGridLayoutManager</code>, etc.)</p>
8,398,030
chomsky hierarchy in plain english
<p>I'm trying to find a plain (i.e. non-formal) explanation of the 4 levels of formal grammars (unrestricted, context-sensitive, context-free, regular) as set out by Chomsky.</p> <p>It's been an age since I studied formal grammars, and the various definitions are now confusing for me to visualize. To be clear, I'm <strong>not</strong> looking for the formal definitions you'll find everywhere (e.g. <a href="http://en.wikipedia.org/wiki/Chomsky_hierarchy">here</a> and <a href="http://en.wikibooks.org/wiki/Computability_and_Complexity/Formal_Languages/Chomsky_Hierarchy">here</a> -- I can google as well as anyone else), or really even formal definitions of any sort. Instead, what I was hoping to find was clean and simple explanations that don't sacrifice clarity for the sake of completeness.</p>
8,398,208
3
2
null
2011-12-06 09:57:18.307 UTC
10
2019-03-05 02:38:54.983 UTC
null
null
null
null
86,060
null
1
34
grammar|context-free-grammar|regular-language|context-sensitive-grammar
7,596
<p>Maybe you get a better understanding if you remember the automata generating these languages.</p> <p><strong>Regular languages</strong> are generated by regular automata. They have only have a finit knowledge of the past (their compute memory has limits) so everytime you have a language with suffixes depending on prefixes (palindrome language) this can not be done with regular languages.</p> <p><strong>Context-free languages</strong> are generated by nondeterministic pushdown automata. They have a kind of knowledge of the past (the stack, which is not limited in contrast to regular automata) but a stack can only be viewed from top so you don't have complete knowledge of the past.</p> <p><strong>Context-sensitive languages</strong> are generated by linear-bound non-deterministic turing machines. They know the past and can deal with different contexts because they are non-deterministic and can access all the past at every time.</p> <p><strong>Unrestricted languages</strong> are generated by Turing machines. According to the Church-Turing-Thesis turing machines are able to calculate everything you can imagine (which means everything decidable).</p>
46,448,682
cmake error 'the source does not appear to contain CMakeLists.txt'
<p>I'm installing opencv in ubuntu 16.04. After installing the necessary prerequisites I used the following command:-</p> <pre><code>kvs@Hunter:~/opencv_contrib$ mkdir build kvs@Hunter:~/opencv_contrib$ cd build kvs@Hunter:~/opencv_contrib/build$ kvs@Hunter:~/opencv_contrib/build$ cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX+/usr/local -D INSTALL_C_EXAMPLES=ON -D INSTALL_PYTHON_EXAMPLES=ON -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules -D BUILD_EXAMPLES=ON .. </code></pre> <p>but it produced an error:-</p> <pre><code>CMake Error: The source directory "/home/kvs/opencv_contrib" does not appear to contain CMakeLists.txt. Specify --help for usage, or press the help button on the CMake GUI. </code></pre> <p>I used the command provided in the folder 'module' documentation. How do I solve it? I tried the answers here at <a href="https://stackoverflow.com/questions/24153845/opencv-ubuntu-12-04-cmake-error-source-directory-does-not-appear-to-contain-cm">stack-overflow</a> and a few other question but still can't figure it out.</p> <p>Project Git repository <a href="https://github.com/opencv/opencv_contrib" rel="noreferrer">here</a>. </p>
46,448,980
4
6
null
2017-09-27 13:05:16.76 UTC
9
2022-08-16 12:18:57.317 UTC
2017-09-27 13:11:21.137 UTC
null
6,534,684
null
6,534,684
null
1
34
python|opencv
174,213
<p>You should do <code>mkdir build</code> and <code>cd build</code> while inside <code>opencv</code> folder, not the <code>opencv-contrib</code> folder. The <code>CMakeLists.txt</code> is there. </p>
18,144,016
Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"
<p>Hope you can help me with a problem trying to execute a script block with alternate credentials on a local computer. I've been thoroughly searching on forums and doing some googling and found two possible approach to solve my problem:</p> <ol> <li>Use Invoke-Command</li> <li>Use Start-Job</li> </ol> <p>Using approach #1 I had this code:</p> <pre><code>$res = Invoke-Command -Credential $migratorCreds -ScriptBlock {param($one, $two) Get-LocalUsers -parentNodeXML $one -migratorUser $two } -ArgumentList $xmlPRE,$migratorCreds </code></pre> <p>where <code>Get-LocalUsers</code> is a custom function stored in a custom module (*.psm1).</p> <p>My problem is that every time I run this code I get following error:</p> <blockquote> <p>Parameter set cannot be resolved using the specified named parameters</p> </blockquote> <p>So it's obvious that I must be missing something, could you help me on this topic?</p> <p>Thanks in advance...</p>
18,145,769
4
0
null
2013-08-09 09:51:12.69 UTC
2
2019-10-29 15:30:42.757 UTC
2019-10-18 14:51:08.56 UTC
null
5,415,234
null
655,056
null
1
26
powershell
129,211
<p>The error you have is because <code>-credential</code> without <code>-computername</code> can't exist.</p> <p>You can try this way:</p> <pre><code>Invoke-Command -Credential $migratorCreds -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME </code></pre>
6,322,524
How do you view a sample of the call stack in ruby?
<p>I'm investigating different optimization techniques, and I came across this post <a href="https://stackoverflow.com/questions/890222/analyzing-code-for-efficiency/893272#893272">Analyzing Code for Efficiency?</a> by someone who believes that sampling the call stack is more effective than using a profiler. The basic idea is that if you take a view of the call stack, you see where your application is most likely to be spending most of its time, and then optimize there. </p> <p>It is certainly interesting, and he is obviously an expert on this, but I don't know how to view the call stack in ruby. In debugger I can say "info stack" but only seems to show one line.</p> <p>EDIT: I saw this comment by Mike Dunlavey: "I would just like to point out that if you run under the debugger, interrupt it manually, and display the call stack..."</p> <p>I'm just not sure how to interrupt it manually and dipslay the call stack.</p>
6,322,788
3
1
null
2011-06-12 14:39:04.713 UTC
7
2014-10-05 02:47:22.843 UTC
2017-05-23 12:02:13.08 UTC
null
-1
null
636,892
null
1
52
ruby-on-rails|ruby|optimization|profiling
26,747
<p>Just put</p> <pre><code>puts caller </code></pre> <p>anywhere in the code. If you don't like its format, it's an array of strings, so you can do some regex manipulation for a desired output.</p>
6,507,687
should a db connection be a singleton?
<p>What is the best way in Java to create a singleton? Should a DB connection be a singleton (being a singleton it's automatically thread-safe)? Because theoretical the DB can't be accessed by many users in the same time.</p>
6,507,820
4
3
null
2011-06-28 14:02:30.063 UTC
15
2013-03-28 16:03:53.813 UTC
null
null
null
null
818,703
null
1
27
java|design-patterns|singleton
58,469
<p>A DB connection should not normally be a Singleton.</p> <p>Two reasons:</p> <ol> <li>many DB drivers are not thread safe. Using a singleton means that if you have many threads, they will all share the same connection. The singleton pattern does not give you thread saftey. It merely allows many threads to easily share a "global" instance.</li> <li>Personally, I think Singleton often leads to bad design: See this post (by somebody else) <a href="http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/" rel="noreferrer">http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/</a></li> </ol> <p>Instead of doing this consider a database pool. The pool is shared (and could be a singleton if you wanted). When you need to do database work your code does this:</p> <pre><code>getConnectioFromPool(); doWork() closeConnection() // releases back to pool </code></pre> <p>Sample Pool Libraries:</p> <ul> <li><a href="http://commons.apache.org/dbcp/" rel="noreferrer">http://commons.apache.org/dbcp/</a></li> <li><a href="http://jolbox.com/" rel="noreferrer">http://jolbox.com/</a></li> </ul>
6,520,293
What are the advantages of using the fieldset tag?
<p>What are the advantages of using the <code>&lt;fieldset&gt;</code> tag?</p> <p>I don't really get what it is used for.</p>
6,520,332
4
1
null
2011-06-29 12:00:49.673 UTC
3
2015-10-09 14:03:41.973 UTC
2011-06-29 12:11:35.307 UTC
null
398,242
null
310,276
null
1
32
html|fieldset
13,708
<p>Forms are often broken up into various sets of fields.</p> <p>The fieldset tag allows you to logically group sets of fields in order that your forms be more descriptive.</p> <p>You'll also note that you can use the fieldset to style your forms and display those logical associations between fields.</p> <p>Just like forms you find in the "real" world.</p> <p>The "advantages" of using a fieldset are that they allow you to mark up your data (in this case a form) in the most semantic way available. Consider that placing your fields in a fieldset is more descriptive than placing your fields in a div. The div tells you nothing about the relationship between the fields, a fieldset tells you there is a relationship.</p> <p>It's a similar principle to many of the new HTML5 tagsets. <code>&lt;footer&gt;</code> for example tells you more about the meaning of the data inside it compared to an ambiguous <code>&lt;div&gt;</code>.</p>
52,187,362
How to deploy python script?
<p>This might sound like a very open ended question, but I am a python enthusiast, and pretty new to this world of development. I have developed a python script which takes in an input and gives an output based on the algorithm I have put in place in the script. I want to use this script and package it in a way that it can be used by end users having no technical mindset and are only concerned with input they give and the output they get. </p> <p>I have used Jupyter Notebook to develop this complex code and I want to know a way about how I can package or deploy this code so that the end user can use it without seeing how it works as it might be overwhelming for them. </p> <p>Can anyone help me with the idea on how to do it? Something which is Opensource would be preferred. </p> <p>Thanks</p>
57,563,511
5
10
null
2018-09-05 14:17:29.577 UTC
26
2021-12-22 19:01:43.357 UTC
null
null
null
null
10,214,220
null
1
37
python|windows|deployment|package|jupyter
46,917
<p>I want to round up this question by suggesting a couple of ways to deploy Python Script or Models:</p> <ul> <li><strong>Docker</strong>: This is one of the most popular ways of hosting scripts and deploying Machine Learning Models online. You can use Docker to containerize the code and host it as a microservice using different apps.</li> <li><strong>PEX</strong>: <a href="https://www.youtube.com/watch?v=NmpnGhRwsu0" rel="noreferrer">PEX</a> is a clever tool being developed at Twitter that allows Python code to be shipped as executable zip files.</li> <li><strong>AWS</strong>: Using AWS, you can create a free account and get started with hosting/deployment. A lot of resources are available online.</li> <li><strong>PYSimple, Pyinstaller, and Sparrow</strong>: As mentioned in the answers above, we can use these packages also to do the task. Please read above.</li> <li><strong>Flask App</strong>: If you don't want to use Docker, using a simple flask app, you will be able to host your script online. But there will be a lot of issues as it is not containerized. Best to use Docker.</li> <li><strong>py2exe</strong>: If you are looking to convert the Python file into windows executable, <a href="http://www.py2exe.org/" rel="noreferrer">Click here</a></li> <li><strong><a href="https://cx-freeze.readthedocs.io/en/latest/" rel="noreferrer">cx_Freeze</a></strong>: Similar to the py2exe, you can use this also</li> </ul> <p>I will keep adding more content as I find them, but I think the best way to do it using Docker. Hope this helps.</p>
23,934,905
Pandas - conditionally select source column of data for a new column based on row value
<p>Is there a pandas function that allows selection from different columns based on a condition? This is analogous to a CASE statement in a SQL Select clause. For example, say I have the following DataFrame:</p> <pre><code>foo = DataFrame( [['USA',1,2], ['Canada',3,4], ['Canada',5,6]], columns = ('Country', 'x', 'y') ) </code></pre> <p>I want to select from column 'x' when Country=='USA', and from column 'y' when Country=='Canada', resulting in something like the following:</p> <pre><code> Country x y z 0 USA 1 2 1 1 Canada 3 4 4 2 Canada 5 6 6 [3 rows x 4 columns] </code></pre>
23,935,823
5
2
null
2014-05-29 13:46:42.757 UTC
4
2020-07-13 13:37:06.233 UTC
2017-12-11 19:17:03.817 UTC
null
3,604,745
null
1,459,601
null
1
21
python|pandas
40,694
<p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.where.html?highlight=where#pandas.DataFrame.where" rel="noreferrer"><code>DataFrame.where</code></a>'s <code>other</code> argument and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="noreferrer"><code>pandas.concat</code></a>:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; &gt;&gt;&gt; foo = pd.DataFrame([ ... ['USA',1,2], ... ['Canada',3,4], ... ['Canada',5,6] ... ], columns=('Country', 'x', 'y')) &gt;&gt;&gt; &gt;&gt;&gt; z = foo['x'].where(foo['Country'] == 'USA', foo['y']) &gt;&gt;&gt; pd.concat([foo['Country'], z], axis=1) Country x 0 USA 1 1 Canada 4 2 Canada 6 </code></pre> <p>If you want <code>z</code> as column name, specify <code>keys</code>:</p> <pre><code>&gt;&gt;&gt; pd.concat([foo['Country'], z], keys=['Country', 'z'], axis=1) Country z 0 USA 1 1 Canada 4 2 Canada 6 </code></pre>
18,584,520
Reason for - ORDER BY items must appear in the select list if SELECT DISTINCT is specified
<p>I know that the query below causes the error - ORDER BY items must appear in the select list if SELECT DISTINCT is specified.</p> <pre><code>SELECT DISTINCT city FROM HR.Employees WHERE country = N'USA' AND region = N'WA' ORDER BY birthdate; </code></pre> <p>What is the reason for this ? What is actually happening ? If I don't use DISTINCT or just add birthdate in SELECT or ORDER BY city only, it gives me some output, but not an error. Is it because <code>SELECT DISTINCT city</code> only gives a result set with cities and nothing else ?</p> <p><strong>EDIT -(I think this may be an answer to my question)</strong> </p> <pre><code>SELECT city FROM HR.Employees WHERE country = N'USA' AND region = N'WA' </code></pre> <p>Consider the above query. Not sure, but I think this is how it works - Behind the scenes, SQL Server probably has a result set with all columns, but we are only shown the city column which I will call the "displayed set" . So, ordering by city or any other column is valid. </p> <p>What happens to the result set when we use SELECT DISTINCT city instead ? SQL server does not have only the rows with DISTINCT cities in its result set. It has the entire result set, like the one generated by a SELECT * query. But, it shows only distinct rows based on city. Now can this displayed set be sorted based on birthdate ? No.</p> <p>In a city with many employees, ie many birthdates, SQL server cannot tell which birthdate should be used for ordering the displayed set. That is why it displays an error message.</p>
18,585,057
2
3
null
2013-09-03 05:12:54.623 UTC
4
2013-09-03 06:14:09.917 UTC
2013-09-03 06:05:50.293 UTC
null
2,643,274
null
2,643,274
null
1
7
sql|sql-server
51,251
<p>A query with <code>SELECT DISTINCT</code> can be rewritten using <code>GROUP BY</code>. So the query:</p> <pre><code>SELECT DISTINCT city FROM HR.Employees WHERE country = N'USA' AND region = N'WA' ; </code></pre> <p>is equivalent to:</p> <pre><code>SELECT city FROM HR.Employees WHERE country = N'USA' AND region = N'WA' GROUP BY city ; </code></pre> <p>and you can't use <code>ORDER BY birthdate</code> here either. The reason is the same for both queries. There may be many (more than one) rows with same <code>city</code> but different <code>birthdate</code>. Which one should be used for the ordering (if it was allowed?)</p> <p>You can however use aggregate functions with a <code>GROUP BY</code> query:</p> <pre><code>SELECT city FROM HR.Employees WHERE country = N'USA' AND region = N'WA' GROUP BY city ORDER BY MIN(birthdate) ; -- or MAX(birthdate) </code></pre>
18,776,288
Snapshot of MKMapView in iOS7
<p>I am trying to create a snapshot of a MKMapView in iOS7 application the same way it's recommended everywhere for previous iOS versions:</p> <pre><code>- (UIImage*) renderMapViewToImage { UIGraphicsBeginImageContextWithOptions(mapView.frame.size, NO, 0.0); [mapView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image; } </code></pre> <p>However, the image returned is a black rectangle with a blue current location dot on top of it. I've tried using different sublayers of the mapView as well, but the result is always the same.</p> <p>Does anyone know how to take MKMapView snapshots in iOS7 ?</p>
18,776,723
3
2
null
2013-09-13 00:19:46.277 UTC
35
2018-07-14 13:46:12.653 UTC
2015-05-13 15:14:48.677 UTC
null
165,050
null
369,891
null
1
43
ios|ios7|mkmapview|mapkit|mkmapsnapshotter
20,890
<p>You can use <code>MKMapSnapshotter</code> and grab the <code>image</code> from the resulting <code>MKMapSnapshot</code>. See the discussion of it WWDC 2013 session video, <a href="https://developer.apple.com/videos/play/wwdc2013/309/">Putting Map Kit in Perspective</a>.</p> <p>For example:</p> <pre><code>MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init]; options.region = self.mapView.region; options.scale = [UIScreen mainScreen].scale; options.size = self.mapView.frame.size; MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options]; [snapshotter startWithCompletionHandler:^(MKMapSnapshot *snapshot, NSError *error) { UIImage *image = snapshot.image; NSData *data = UIImagePNGRepresentation(image); [data writeToFile:[self snapshotFilename] atomically:YES]; }]; </code></pre> <p>Having said that, the <code>renderInContext</code> solution still works for me. There are notes about only doing that in the main queue in iOS7, but it still seems to work. But <code>MKMapSnapshotter</code> seems like the more appropriate solution for iOS7.</p> <hr> <p>If you want to include some annotations in the snapshot, you have to draw them manually (!). This is discussed in some detail at the end of the <a href="https://developer.apple.com/videos/play/wwdc2013/309/">Putting Map Kit in Perspective</a> video. I have to say that this is one of the least elegant implementations that I've ever seen Apple advise. Anyway, in iOS, it might look like:</p> <pre><code>MKMapSnapshotOptions *options = [[MKMapSnapshotOptions alloc] init]; options.region = self.mapView.region; options.scale = [UIScreen mainScreen].scale; options.size = self.mapView.frame.size; MKMapSnapshotter *snapshotter = [[MKMapSnapshotter alloc] initWithOptions:options]; [snapshotter startWithQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) completionHandler:^(MKMapSnapshot *snapshot, NSError *error) { // get the image associated with the snapshot UIImage *image = snapshot.image; // Get the size of the final image CGRect finalImageRect = CGRectMake(0, 0, image.size.width, image.size.height); // Get a standard annotation view pin. Clearly, Apple assumes that we'll only want to draw standard annotation pins! MKAnnotationView *pin = [[MKPinAnnotationView alloc] initWithAnnotation:nil reuseIdentifier:@""]; UIImage *pinImage = pin.image; // ok, let's start to create our final image UIGraphicsBeginImageContextWithOptions(image.size, YES, image.scale); // first, draw the image from the snapshotter [image drawAtPoint:CGPointMake(0, 0)]; // now, let's iterate through the annotations and draw them, too for (id&lt;MKAnnotation&gt;annotation in self.mapView.annotations) { CGPoint point = [snapshot pointForCoordinate:annotation.coordinate]; if (CGRectContainsPoint(finalImageRect, point)) // this is too conservative, but you get the idea { CGPoint pinCenterOffset = pin.centerOffset; point.x -= pin.bounds.size.width / 2.0; point.y -= pin.bounds.size.height / 2.0; point.x += pinCenterOffset.x; point.y += pinCenterOffset.y; [pinImage drawAtPoint:point]; } } // grab the final image UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // and save it NSData *data = UIImagePNGRepresentation(finalImage); [data writeToFile:[self snapshotFilename] atomically:YES]; }]; </code></pre> <p>For MacOS implementation, see that video for more information, but the technique is basically the same (the mechanism for creating the images is slightly different).</p>
27,467,730
Is there a way to copy only the structure (not the data) of a Pandas DataFrame?
<p>I received a DataFrame from somewhere and want to create another DataFrame with the same number and names of columns and rows (indexes). For example, suppose that the original data frame was created as</p> <pre><code>import pandas as pd df1 = pd.DataFrame([[11,12],[21,22]], columns=['c1','c2'], index=['i1','i2']) </code></pre> <p>I copied the structure by explicitly defining the columns and names:</p> <pre><code>df2 = pd.DataFrame(columns=df1.columns, index=df1.index) </code></pre> <p>I don't want to copy the data, otherwise I could just write <code>df2 = df1.copy()</code>. In other words, after df2 being created it must contain only NaN elements:</p> <pre><code>In [1]: df1 Out[1]: c1 c2 i1 11 12 i2 21 22 In [2]: df2 Out[2]: c1 c2 i1 NaN NaN i2 NaN NaN </code></pre> <p>Is there a more idiomatic way of doing it?</p>
47,961,242
10
3
null
2014-12-14 08:49:35.527 UTC
13
2022-02-28 16:16:51.66 UTC
2017-11-05 12:32:31.867 UTC
null
243,392
null
3,482,418
null
1
90
python|pandas|dataframe
68,175
<p>That's a job for <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex_like.html" rel="noreferrer"><code>reindex_like</code></a>. Start with the original:</p> <pre><code>df1 = pd.DataFrame([[11, 12], [21, 22]], columns=['c1', 'c2'], index=['i1', 'i2']) </code></pre> <p>Construct an empty DataFrame and reindex it like df1:</p> <pre><code>pd.DataFrame().reindex_like(df1) Out: c1 c2 i1 NaN NaN i2 NaN NaN </code></pre>
41,183,845
Error with $http.get in angularJS -- Success not a Function
<p>Getting this error: </p> <blockquote> <p>angular.min.js:122 TypeError: $http.get(...).success is not a function at getUserInfo (app.js:7) at new (app.js:12) at Object.invoke (angular.min.js:43) at Q.instance (angular.min.js:93) at p (angular.min.js:68) at g (angular.min.js:60) at g (angular.min.js:61) at g (angular.min.js:61) at angular.min.js:60 at angular.min.js:21</p> </blockquote> <p>Here is my code:</p> <pre><code>var gitHub = angular.module('gitHub', []); gitHub.controller('mainController', ['$scope', '$http', function($scope, $http) { var $scope.user = ''; function getUserInfo($scope, $http){ $http.get('https://api.github.com/users') .success(function (result) { $scope.user = result; console.log(result); }); }; getUserInfo($scope, $http); }]); </code></pre> <p>and here is the html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html ng-app="gitHub"&gt; &lt;head&gt; &lt;title&gt;Github Users Directory&lt;/title&gt; &lt;script src="angular.min.js"&gt;&lt;/script&gt; &lt;script src="app.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div ng-controller="mainController"&gt; &lt;div&gt; &lt;h1&gt;GitHub Users&lt;/h1&gt; Who do you want to search for?&lt;input type="text" name="FindHim" ng-model="queryName" /&gt; &lt;button ng-click="getUserInfo()"&gt;Search&lt;/button&gt; &lt;/div&gt; &lt;div&gt; {{ user }} &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
41,187,435
9
3
null
2016-12-16 11:55:15.3 UTC
6
2018-11-10 22:25:03.45 UTC
2017-01-25 12:58:16.477 UTC
null
4,927,984
null
6,883,002
null
1
27
angularjs|angularjs-http|angularjs-1.6
60,972
<p>The <code>.success</code> and <code>.error</code> methods are deprecated and have been <a href="https://docs.angularjs.org/guide/migration#migrate1.5to1.6-ng-services-$http" rel="noreferrer">removed from AngularJS 1.6</a>. Use the standard <code>.then</code> method instead.</p> <pre><code>$http.get('https://api.github.com/users') .then(function (response) { var data = response.data; var status = response.status; var statusText = response.statusText; var headers = response.headers; var config = response.config; $scope.user = data; console.log(data); }); </code></pre> <blockquote> <h2>Deprecation Notice</h2> <p>The <code>$http</code> legacy promise methods <code>.success</code> and <code>.error</code> have been deprecated and will be removed in v1.6.0. Use the standard <code>.then</code> method instead.</p> <p><a href="https://code.angularjs.org/1.5.10/docs/api/ng/service/$http#deprecation-notice" rel="noreferrer">&#8212; AngularJS (v1.5) $http Service API Reference -- Deprecation Notice</a>.</p> </blockquote> <p>Also see <a href="https://stackoverflow.com/a/35331339/5535245">SO: Why are angular $http success/error methods deprecated?</a>.</p>
1,134,085
Rendering a value as text instead of field inside a Django Form
<p>Is there a simple way to make Django render <code>{{myform.name}}</code> as </p> <pre><code>John Smith </code></pre> <p>instead of </p> <pre><code>&lt;input id="id_name" name="name" value="John Smith" /&gt; </code></pre> <p>inside <code>&lt;form&gt;</code> tags? Or am I going about this the wrong way?</p>
1,134,167
7
0
null
2009-07-15 21:05:10.9 UTC
10
2019-10-29 18:39:52.553 UTC
null
null
null
null
4,965
null
1
18
django|django-templates|django-forms
18,880
<pre><code>&lt;form&gt; {% for field in form %} {{ field.label }}: {{ field.value }} {% endfor %} &lt;/form&gt; </code></pre> <p>Take a look here <a href="http://docs.djangoproject.com/en/dev/ref/forms/fields/#initial" rel="noreferrer">Form fields</a> and <a href="http://docs.djangoproject.com/en/dev/topics/forms/" rel="noreferrer">Working with forms</a></p>
690,436
Is there a way to drag & drop to copy files between two visual studio 2008 instances?
<p>Is there a way to copy files between two Visual Studio 2008 instances ? A plugin, setting, or something else ? Currently, dragging a file from one instances to another does nothing (mouse shows that it's invalid operation).</p> <p>Right-clicking a file and selecting "Copy" from instance 1, and pasting in instance 2 results in the following error:</p> <blockquote> <p>The source files for this operation cannot be found in this solution.</p> </blockquote> <p>Any ideas or solutions ?</p>
43,974,656
7
0
null
2009-03-27 16:22:37.33 UTC
2
2021-12-17 20:40:55.737 UTC
2013-07-15 12:11:46.56 UTC
null
880,367
Initri
27,472
null
1
35
visual-studio-2008
14,192
<p>Got me the Visual Studio extension <a href="https://marketplace.visualstudio.com/items?itemName=tux.OpenInExplorer" rel="noreferrer">Open In Explorer</a> that provides a context menu option "copy files". This way you don't have to go over a windows explorer window.</p> <p><a href="https://i.stack.imgur.com/ct7aQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ct7aQ.png" alt="copy files"></a></p>
51,526
Changing the value of an element in a list of structs
<p>I have a list of structs and I want to change one element. For example :</p> <pre><code>MyList.Add(new MyStruct("john"); MyList.Add(new MyStruct("peter"); </code></pre> <p>Now I want to change one element:</p> <pre><code>MyList[1].Name = "bob" </code></pre> <p>However, whenever I try and do this I get the following error:</p> <blockquote> <p>Cannot modify the return value of System.Collections.Generic.List.this[int]‘ because it is not a variable</p> </blockquote> <p>If I use a list of classes, the problem doesn't occur.</p> <p>I guess the answer has to do with structs being a value type.</p> <p>So, if I have a list of structs should I treat them as <em>read-only</em>? If I need to change elements in a list then I should use classes and not structs?</p>
51,537
7
0
null
2008-09-09 10:23:29.503 UTC
10
2022-06-05 14:01:54.073 UTC
2015-06-02 10:31:15.14 UTC
Motti
1,155,650
Darren Jackson
3,989
null
1
76
c#|struct|value-type
105,819
<pre><code>MyList[1] = new MyStruct("bob"); </code></pre> <p>structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created).</p> <p>In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single property or field.</p>
1,220,423
Directly convert .aspx to .pdf
<p>A project I am working on requires me to build a report that is output in both HTML (.aspx) and as a PDF. Is there a solution available that allows me to feed the output of an .aspx page to a PDF generation utility? Full support of HTML and CSS would be ideal.</p> <p>Thanks!</p>
1,220,451
8
1
null
2009-08-03 01:58:03.337 UTC
10
2015-10-06 08:55:09.887 UTC
2009-08-03 02:59:16.36 UTC
null
3,043
null
149,461
null
1
11
asp.net|pdf|pdf-generation
42,040
<p><a href="http://wkhtmltopdf.org/" rel="nofollow noreferrer">wkhtmltopdf</a> will do it.... USAGE:</p> <pre><code>wkhtmltopdf http://www.google.com google.pdf </code></pre> <p>That is it. You can go to any web page... even aspx. css is supported better than any other utility as it uses the webkit html rendering engine (Safari, Chrome). Enjoy</p> <p>There is a single .exe (7 mb) that can be used from .Net simply by using Process.Start Make sure that you copy the exe into your project directory or you have to specify the full path. ex:</p> <pre><code>static void HtmlToPdf(string website,string destinationFile) { ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = "wkhtmltopdf.exe"; startInfo.Arguments = website+" "+destinationFile; Process.Start(startInfo); } </code></pre> <p>I think SSL is supported but I do not think that 2-way SSL would work at the moment. It is hands down the best single stop HTML -> PDF tool I have seen.</p>
342,189
How do I apply gravity to my bouncing ball application?
<p>I've written a fairly simple java application that allows you to drag your mouse and based on the length of the mouse drag you did, it will shoot a ball in that direction, bouncing off walls as it goes.</p> <p>Here is a quick screenshot:<br> <a href="http://img222.imageshack.us/img222/3179/ballbouncemf9.png">alt text http://img222.imageshack.us/img222/3179/ballbouncemf9.png</a></p> <p>Each one of the circles on the screen is a Ball object. The balls movement is broken down into an x and y vector;</p> <pre><code>public class Ball { public int xPos; public int yPos; public int xVector; public int yVector; public Ball(int xPos, int yPos, int xVector, int yVector) { this.xPos = xPos; this.yPos = yPos; this.xVector = xVector; this.yVector = yVector; } public void step() { posX += xVector; posY += yVector; checkCollisions(); } public void checkCollisions() { // Check if we have collided with a wall // If we have, take the negative of the appropriate vector // Depending on which wall you hit } public void draw() { // draw our circle at it's position } } </code></pre> <p>This works great. All the balls bounce around and around from wall to wall. </p> <p>However, I have decided that I want to be able to include the effects of gravity. I know that objects accelerate toward the earth at 9.8m/s but I don't directly know how this should translate into code. I realize that the yVector will be affected but my experimentation with this didn't have the desired effect I wanted.</p> <p>Ideally, <strong><em>I would like to be able to add some gravity effect to this program and also allow the balls to bounce a few times before settling to the "ground."</em></strong> </p> <p>How can I create this bouncing-elastic, gravity effect? How must I manipulate the speed vectors of the ball on each step? What must be done when it hits the "ground" so that I can allow it to bounce up again, but somewhat shorter then the previous time?</p> <p>Any help is appreciated in pointing me in the right direction.</p> <hr> <p>Thanks you for the comments everyone! It already is working great!</p> <p>In my step() I am adding a gravity constant to my yVector like people suggested and this is my checkCollision():</p> <pre><code>public void checkCollision() { if (posX - radius &lt; 0) // Left Wall? { posX = radius; // Place ball against edge xVector = -(xVector * friction); } else if (posX + radius &gt; rightBound) // Right Wall? { posX = rightBound - radius; // Place ball against edge xVector = -(xVector * friction); } // Same for posY and yVector here. } </code></pre> <p>However, the balls will continue to slide around/roll on the floor. I assume this is because I am simply taking a percentage (90%) of their vectors each bounce and it is never truly zero. Should I add in a check that if the xVector becomes a certain absolute value I should just change it to zero?</p>
342,205
9
4
null
2008-12-04 21:42:31.933 UTC
9
2011-11-28 03:52:45.803 UTC
2011-11-28 03:52:45.803 UTC
Simucal
214,668
anon
null
null
1
11
language-agnostic|physics|gravity
15,553
<p>What you have to do is constantly subtract a small constant (something that represents your 9.8 m/s) from your yVector. When the ball is going down (yVector is already negative), this would make it go faster. When it's going up (yVector is positive) it would slow it down.</p> <p>This would not account for friction, so the things should bounce pretty much for ever.</p> <p>edit1: To account for friction, whenever it reverses (and you reverse the sign), lower the absolute number a little. Like if it hits at yVector=-500, when you reverse the sign, make it +480 instead of +500. You should probably do the same thing to xVector to stop it from bouncing side-to-side.</p> <p>edit2: Also, if you want it to react to "air friction", reduce both vectors by a very small amount every adjustment.</p> <p>edit3: About the thing rolling around on the bottom forever--Depending on how high your numbers are, it could be one of two things. Either your numbers are large and it just seems to take forever to finish, or you are rounding and your Vectors are always 5 or something. (90% of 5 is 4.5, so it may round up to 5).</p> <p>I'd print out a debug statement and see what the Vector numbers are like. If they go to somewhere around 5 and just stay there, then you can use a function that truncates your fraction to 4 instead of rounding back to 5. If it keeps on going down and eventually stops, then you might have to raise your friction coefficient.</p> <p>If you can't find an easy "rounding" function, you could use (0.9 * Vector) - 1, subtracting 1 from your existing equation should do the same thing.</p>
40,632
I just don't get continuations!
<p>What are they and what are they good for?</p> <p>I do not have a CS degree and my background is VB6 -> ASP -> ASP.NET/C#. Can anyone explain it in a clear and concise manner?</p>
40,643
9
0
null
2008-09-02 20:55:13.353 UTC
15
2008-12-29 05:59:17.64 UTC
2008-09-02 21:33:57.55 UTC
Kyle
658
Oded
1,583
null
1
34
functional-programming|continuations|callcc
3,144
<p>Imagine if every single line in your program was a separate function. Each accepts, as a parameter, the next line/function to execute. </p> <p>Using this model, you can "pause" execution at any line and continue it later. You can also do inventive things like temporarily hop up the execution stack to retrieve a value, or save the current execution state to a database to retrieve later.</p>
638,761
GetHashCode override of object containing generic array
<p>I have a class that contains the following two properties:</p> <pre><code>public int Id { get; private set; } public T[] Values { get; private set; } </code></pre> <p>I have made it <code>IEquatable&lt;T&gt;</code> and overriden the <code>object.Equals</code> like this:</p> <pre><code>public override bool Equals(object obj) { return Equals(obj as SimpleTableRow&lt;T&gt;); } public bool Equals(SimpleTableRow&lt;T&gt; other) { // Check for null if(ReferenceEquals(other, null)) return false; // Check for same reference if(ReferenceEquals(this, other)) return true; // Check for same Id and same Values return Id == other.Id &amp;&amp; Values.SequenceEqual(other.Values); } </code></pre> <p>When having override <code>object.Equals</code> I must also override <code>GetHashCode</code> of course. But what code should I implement? How do I create a hashcode out of a generic array? And how do I combine it with the <code>Id</code> integer?</p> <pre><code>public override int GetHashCode() { return // What? } </code></pre>
639,098
9
0
null
2009-03-12 14:08:06.823 UTC
52
2017-03-03 13:31:53.183 UTC
2016-04-12 20:02:25.387 UTC
null
3,159,635
Svish
39,321
null
1
61
c#|arrays|generics|hashcode
51,072
<p>Because of the problems raised in this thread, I'm posting another reply showing what happens if you get it wrong... mainly, that you can't use the array's <code>GetHashCode()</code>; the correct behaviour is that no warnings are printed when you run it... switch the comments to fix it:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; static class Program { static void Main() { // first and second are logically equivalent SimpleTableRow&lt;int&gt; first = new SimpleTableRow&lt;int&gt;(1, 2, 3, 4, 5, 6), second = new SimpleTableRow&lt;int&gt;(1, 2, 3, 4, 5, 6); if (first.Equals(second) &amp;&amp; first.GetHashCode() != second.GetHashCode()) { // proven Equals, but GetHashCode() disagrees Console.WriteLine("We have a problem"); } HashSet&lt;SimpleTableRow&lt;int&gt;&gt; set = new HashSet&lt;SimpleTableRow&lt;int&gt;&gt;(); set.Add(first); set.Add(second); // which confuses anything that uses hash algorithms if (set.Count != 1) Console.WriteLine("Yup, very bad indeed"); } } class SimpleTableRow&lt;T&gt; : IEquatable&lt;SimpleTableRow&lt;T&gt;&gt; { public SimpleTableRow(int id, params T[] values) { this.Id = id; this.Values = values; } public int Id { get; private set; } public T[] Values { get; private set; } public override int GetHashCode() // wrong { return Id.GetHashCode() ^ Values.GetHashCode(); } /* public override int GetHashCode() // right { int hash = Id; if (Values != null) { hash = (hash * 17) + Values.Length; foreach (T t in Values) { hash *= 17; if (t != null) hash = hash + t.GetHashCode(); } } return hash; } */ public override bool Equals(object obj) { return Equals(obj as SimpleTableRow&lt;T&gt;); } public bool Equals(SimpleTableRow&lt;T&gt; other) { // Check for null if (ReferenceEquals(other, null)) return false; // Check for same reference if (ReferenceEquals(this, other)) return true; // Check for same Id and same Values return Id == other.Id &amp;&amp; Values.SequenceEqual(other.Values); } } </code></pre>
435,890
Find Java classes implementing an interface
<p>Some time ago, I came across a piece of code, that used some piece of standard Java functionality to locate the classes that implemented a given interface. I know the functions were hidden in some non-logical place, but they could be used for other classes as the package name implied. Back then I did not need it, so I forgot about it, but now I do, and I can't seem to find the functions again. Where can these functions be found?</p> <p>Edit: I'm not looking for any IDE functions or anything, but rather something that can be executed within the Java application.</p>
435,930
9
3
null
2009-01-12 16:05:54.473 UTC
47
2021-08-30 16:27:46.523 UTC
2011-03-31 16:01:51.31 UTC
Linor
63,550
Linor
3,197
null
1
134
java|interface
207,222
<p>Awhile ago, I put together a package for doing what you want, and more. (I needed it for a utility I was writing). It uses the <a href="http://asm.objectweb.org/" rel="noreferrer">ASM</a> library. You can use reflection, but ASM turned out to perform better.</p> <p>I put my package in an open source library I have on my web site. The library is here: <a href="http://software.clapper.org/javautil/" rel="noreferrer">http://software.clapper.org/javautil/</a>. You want to start with the with <a href="http://software.clapper.org/javautil/api/org/clapper/util/classutil/ClassFinder.html" rel="noreferrer">ClassFinder</a> class.</p> <p>The utility I wrote it for is an RSS reader that I still use every day, so the code does tend to get exercised. I use ClassFinder to support a plug-in API in the RSS reader; on startup, it looks in a couple directory trees for jars and class files containing classes that implement a certain interface. It's a lot faster than you might expect.</p> <p>The library is BSD-licensed, so you can safely bundle it with your code. Source is available.</p> <p>If that's useful to you, help yourself.</p> <p>Update: If you're using Scala, you might find <a href="http://software.clapper.org/classutil/" rel="noreferrer">this library</a> to be more Scala-friendly.</p>
722,922
Best way to handle memory allocation in C?
<p>I think I've got a good grasp on how to handle memory in C++ but doing it in C is different I'm a bit off.</p> <p>In C++ I've got constructors and destructors, I've got the pretty straightforward new and delete and I know how to encapsulate it using RAII, using with smart pointers and within classes.</p> <p>However in C I can't handle malloc and free the same way. I don't know how to hide them and how to automate things. All I can figure is using functions for initiating and destroying my pointers. But how should I structure my memory handling?</p> <p>While writing this I've realized this is more a question about me understanding the flow of C than anything else, but one question at a time.</p> <p><strong>Edit</strong>: Thanks for the answers but I need to rephrase myself.</p> <p>When I say that I use RAII and smart pointers for C++ I don't want the same for C, I know it's not the same. But how I handle memory allocation in C++ is connected to these techniques.</p> <p>For example in my classes I dynamically add and destroy the memory my class uses. This way I can achieve a sort of encapsulation, I don't need to know when/how/why the class handles it's memory, it just does. This means I can "hide" the lower memory handling and just focus on a few "bigger" classes.</p> <p>What I want to know is what's the best-practice in handling memory in C? There are no classes with constructors/destructors to handle this for me. Is it good to allocate memory in the beginning of a function or use a function that creates it for me? And how should I free them again?</p> <p>These are broad questions and they differ from situation to situation but how do you prefer to handle it? What tips and lessons can you give?</p>
722,993
12
0
null
2009-04-06 19:54:30.443 UTC
13
2015-01-28 00:48:50.69 UTC
2009-04-07 15:09:16.52 UTC
null
75,073
null
75,073
null
1
14
c|memory-management
12,747
<p>Part of the confusion is that it is inherently more difficult in C. <code>malloc</code> and <code>free</code> are similar to <code>new</code> and <code>delete</code>: <code>malloc</code> allocates new memory, and returns a pointer to that memory. <code>free</code> makes that memory available again, <strong>so long as it's memory that was allocated using malloc</strong>. Otherwise, it just makes hash of some chunk of memory. It doesn't care.</p> <p>The important thing with malloc/free is to decide on and consistently maintain a disciplined use. Here are some hints:</p> <p>ALWAYS check the returned pointer from malloc for NULL</p> <pre><code>if((p = (char *) malloc(BUFSIZ)) == NULL { /* then malloc failed do some error processing. */ } </code></pre> <p>For belt and suspenders safety, set a pointer to NULL after freeing it.</p> <pre><code>free(p); p = NULL ; </code></pre> <p>try to malloc and free a chunk of memory within the same scope if possible: </p> <pre><code> { char * p ; if((p = malloc(BUFSIZ)) == NULL { /* then malloc failed do some error processing. */ } /* do your work. */ /* now you're done, free the memory */ free(p); p = NULL ; /* belt-and suspenders */ } </code></pre> <p>When you can't, make it clear that what you're returning is <code>malloc</code>'ed memory, so the caller can free it.</p> <pre><code> /* foo: do something good, returning ptr to malloc memory */ char * foo(int bar) { return (char *) malloc(bar); } </code></pre>
496,896
How to delete an element from an array in C#
<p>Lets say I have this array,</p> <pre><code>int[] numbers = {1, 3, 4, 9, 2}; </code></pre> <p>How can I delete an element by "name"? , lets say number 4?</p> <p>Even <code>ArrayList</code> didn't help to delete?</p> <pre><code>string strNumbers = " 1, 3, 4, 9, 2"; ArrayList numbers = new ArrayList(strNumbers.Split(new char[] { ',' })); numbers.RemoveAt(numbers.IndexOf(4)); foreach (var n in numbers) { Response.Write(n); } </code></pre>
497,005
12
5
null
2009-01-30 19:33:29.62 UTC
56
2021-03-19 21:38:02.18 UTC
2015-07-01 07:32:41.55 UTC
ahmed
1,080,354
ahmed
459,737
null
1
191
c#|.net|arrays
648,262
<p><strong><em>If you want to remove all instances of 4 without needing to know the index:</em></strong></p> <p><strong><em>LINQ:</em></strong> (.NET Framework 3.5)</p> <pre><code>int[] numbers = { 1, 3, 4, 9, 2 }; int numToRemove = 4; numbers = numbers.Where(val =&gt; val != numToRemove).ToArray(); </code></pre> <p><strong><em>Non-LINQ:</em></strong> (.NET Framework 2.0)</p> <pre><code>static bool isNotFour(int n) { return n != 4; } int[] numbers = { 1, 3, 4, 9, 2 }; numbers = Array.FindAll(numbers, isNotFour).ToArray(); </code></pre> <p><strong><em>If you want to remove just the first instance:</em></strong></p> <p><strong><em>LINQ:</em></strong> (.NET Framework 3.5)</p> <pre><code>int[] numbers = { 1, 3, 4, 9, 2, 4 }; int numToRemove = 4; int numIndex = Array.IndexOf(numbers, numToRemove); numbers = numbers.Where((val, idx) =&gt; idx != numIndex).ToArray(); </code></pre> <p><strong><em>Non-LINQ:</em></strong> (.NET Framework 2.0)</p> <pre><code>int[] numbers = { 1, 3, 4, 9, 2, 4 }; int numToRemove = 4; int numIdx = Array.IndexOf(numbers, numToRemove); List&lt;int&gt; tmp = new List&lt;int&gt;(numbers); tmp.RemoveAt(numIdx); numbers = tmp.ToArray(); </code></pre> <p><strong><em>Edit:</em></strong> Just in case you hadn't already figured it out, as Malfist pointed out, you need to be targetting the .NET Framework 3.5 in order for the LINQ code examples to work. If you're targetting 2.0 you need to reference the Non-LINQ examples.</p>
226,144
Overload a C++ function according to the return value
<p>We all know that you can overload a function according to the parameters:</p> <pre><code>int mul(int i, int j) { return i*j; } std::string mul(char c, int n) { return std::string(n, c); } </code></pre> <p>Can you overload a function according to the return value? Define a function that returns different things according to how the return value is used:</p> <pre><code>int n = mul(6, 3); // n = 18 std::string s = mul(6, 3); // s = "666" // Note that both invocations take the exact same parameters (same types) </code></pre> <p>You can assume the first parameter is between 0-9, no need to verify the input or have any error handling.</p>
226,251
16
7
null
2008-10-22 15:02:00.823 UTC
30
2014-04-17 01:51:32.427 UTC
2013-02-17 18:44:43.907 UTC
RoBorg
560,648
Motti
3,848
null
1
41
c++|function|puzzle|overloading
25,840
<pre><code>class mul { public: mul(int p1, int p2) { param1 = p1; param2 = p2; } operator int () { return param1 * param2; } operator std::string () { return std::string(param2, param1 + '0'); } private: int param1; int param2; }; </code></pre> <p>Not that I would use that.</p>
840,162
Should each and every table have a primary key?
<p>I'm creating a database table and I don't have a logical primary key assigned to it. Should each and every table have a primary key?</p>
840,182
16
2
null
2009-05-08 14:49:14.963 UTC
114
2022-01-26 17:35:13.563 UTC
2021-09-18 11:25:00.347 UTC
null
6,458,245
null
1,100
null
1
397
database|database-design
314,614
<p>Short answer: <strong>yes</strong>.</p> <p>Long answer:</p> <ul> <li>You need your table to be joinable on something</li> <li>If you want your table to be clustered, you need some kind of a primary key.</li> <li>If your table design does not need a primary key, rethink your design: most probably, you are missing something. Why keep identical records?</li> </ul> <p>In MySQL, the InnoDB storage engine always creates a primary key if you didn't specify it explicitly, thus making an extra column you don't have access to.</p> <p>Note that a primary key can be composite.</p> <p>If you have a many-to-many link table, you create the primary key on all fields involved in the link. Thus you ensure that you don't have two or more records describing one link.</p> <p>Besides the logical consistency issues, most RDBMS engines will benefit from including these fields in a unique index.</p> <p>And since any primary key involves creating a unique index, you should declare it and get both logical consistency and performance.</p> <p>See this article in my blog for why you should always create a unique index on unique data:</p> <ul> <li><a href="http://explainextended.com/2009/04/23/making-an-index-unique/" rel="noreferrer"><strong>Making an index UNIQUE</strong></a></li> </ul> <p><strong>P.S.</strong> There are some <em>very, very</em> special cases where you don't need a primary key.</p> <p>Mostly they include log tables which don't have <em>any</em> indexes for performance reasons.</p>
867,518
How to make an Android Spinner with initial text "Select One"?
<p>I want to use a Spinner that initially (when the user has not made a selection yet) displays the text "Select One". When the user clicks the spinner, the list of items is displayed and the user selects one of the options. After the user has made a selection, the selected item is displayed in the Spinner instead of "Select One".</p> <p>I have the following code to create a Spinner: </p> <pre><code>String[] items = new String[] {"One", "Two", "Three"}; Spinner spinner = (Spinner) findViewById(R.id.mySpinner); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, items); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); </code></pre> <p>With this code, initially the item "One" is displayed. I could just add a new item "Select One" to the items, but then "Select One" would also be displayed in the dropdown list as first item, which is not what I want.</p> <p>How can I fix this problem?</p>
3,427,058
36
6
null
2009-05-15 08:09:23.52 UTC
259
2022-07-22 21:14:12.783 UTC
2019-05-02 06:48:15.99 UTC
null
10,607,772
null
51,034
null
1
603
android|android-spinner
617,565
<p>Here's a general solution that overrides the <code>Spinner</code> view. It overrides <code>setAdapter()</code> to set the initial position to -1, and proxies the supplied <code>SpinnerAdapter</code> to display the prompt string for position less than 0.</p> <p>This has been tested on Android 1.5 through 4.2, but buyer beware! Because this solution relies on reflection to call the private <code>AdapterView.setNextSelectedPositionInt()</code> and <code>AdapterView.setSelectedPositionInt()</code>, it's not guaranteed to work in future OS updates. It seems likely that it will, but it is by no means guaranteed.</p> <p>Normally I wouldn't condone something like this, but this question has been asked enough times and it seems like a reasonable enough request that I thought I would post my solution.</p> <pre><code>/** * A modified Spinner that doesn't automatically select the first entry in the list. * * Shows the prompt if nothing is selected. * * Limitations: does not display prompt if the entry list is empty. */ public class NoDefaultSpinner extends Spinner { public NoDefaultSpinner(Context context) { super(context); } public NoDefaultSpinner(Context context, AttributeSet attrs) { super(context, attrs); } public NoDefaultSpinner(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setAdapter(SpinnerAdapter orig ) { final SpinnerAdapter adapter = newProxy(orig); super.setAdapter(adapter); try { final Method m = AdapterView.class.getDeclaredMethod( "setNextSelectedPositionInt",int.class); m.setAccessible(true); m.invoke(this,-1); final Method n = AdapterView.class.getDeclaredMethod( "setSelectedPositionInt",int.class); n.setAccessible(true); n.invoke(this,-1); } catch( Exception e ) { throw new RuntimeException(e); } } protected SpinnerAdapter newProxy(SpinnerAdapter obj) { return (SpinnerAdapter) java.lang.reflect.Proxy.newProxyInstance( obj.getClass().getClassLoader(), new Class[]{SpinnerAdapter.class}, new SpinnerAdapterProxy(obj)); } /** * Intercepts getView() to display the prompt if position &lt; 0 */ protected class SpinnerAdapterProxy implements InvocationHandler { protected SpinnerAdapter obj; protected Method getView; protected SpinnerAdapterProxy(SpinnerAdapter obj) { this.obj = obj; try { this.getView = SpinnerAdapter.class.getMethod( "getView",int.class,View.class,ViewGroup.class); } catch( Exception e ) { throw new RuntimeException(e); } } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { try { return m.equals(getView) &amp;&amp; (Integer)(args[0])&lt;0 ? getView((Integer)args[0],(View)args[1],(ViewGroup)args[2]) : m.invoke(obj, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (Exception e) { throw new RuntimeException(e); } } protected View getView(int position, View convertView, ViewGroup parent) throws IllegalAccessException { if( position&lt;0 ) { final TextView v = (TextView) ((LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE)).inflate( android.R.layout.simple_spinner_item,parent,false); v.setText(getPrompt()); return v; } return obj.getView(position,convertView,parent); } } } </code></pre>
6,958,780
Quitting node.js gracefully
<p>I'm reading through the excellent online book <a href="http://nodebeginner.org/">http://nodebeginner.org/</a> and trying out the simple code </p> <pre><code>var http = require("http"); function onRequest(request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8888); </code></pre> <p>Now I didn't know (and I still don't know!) how to shut down node.js gracefully, so I just went <code>ctrl+z</code>. Now each time I try to run <code>node server.js</code> I get the following error messages.</p> <pre><code>node.js:134 throw e; // process.nextTick error, or 'error' event on first tick ^ Error: EADDRINUSE, Address already in use at Server._doListen (net.js:1100:5) at net.js:1071:14 at Object.lookup (dns.js:153:45) at Server.listen (net.js:1065:20) at Object.&lt;anonymous&gt; (/Users/Bob/server.js:7:4) at Module._compile (module.js:402:26) at Object..js (module.js:408:10) at Module.load (module.js:334:31) at Function._load (module.js:293:12) at Array.&lt;anonymous&gt; (module.js:421:10) </code></pre> <p>So, two questions:</p> <p>1) How do I shut down node.js gracefully?</p> <p>2) How do I repair the mess I've created?</p>
6,958,964
5
4
null
2011-08-05 15:29:01.073 UTC
28
2015-08-05 22:25:06.377 UTC
null
null
null
null
707,381
null
1
80
node.js
61,015
<ol> <li><p>Use <kbd>Ctrl</kbd>+<kbd>C</kbd> to exit the node process gracefully</p></li> <li><p>To clean up the mess depends on your platform, but basically you need to find the remains of the process in which node was running and kill it. </p> <p>For example, on Unix: <code>ps -ax | grep node</code> will give you an entry like:</p> <pre><code>1039 ttys000 0:00.11 node index.js </code></pre> <p>where <code>index.js</code> is the name of your node file.</p> <p>In this example, 1039 is the process id (yours will be different), so <code>kill -9 1039</code> will end it, and you'll be able to bind to the port again.</p></li> </ol>
6,427,531
How to program hardware?
<p>I am an adept Visual Basic programmer. I wish to learn about how people program hardware. For example I have seen people create an LED watches, boxes etc. How do you achieve this? Can it be done using VB or Java? I have some experience in reading C, C++ code. I am only aware of IO in the C and C++ language. </p>
6,427,621
6
1
null
2011-06-21 15:07:07.253 UTC
12
2015-12-11 21:33:40.003 UTC
2012-03-10 03:14:16.187 UTC
null
3,043
null
790,971
null
1
12
embedded|hardware
42,929
<p>Probably you are looking for a programmable microcontroller. If you have experience in C/C++/Java, checkout <a href="http://www.arduino.cc/" rel="noreferrer">Arduino</a>. Its chip is programmed using a <a href="http://arduino.cc/en/Reference/HomePage" rel="noreferrer">C like language</a>. This "<a href="http://sheepdogguides.com/arduino/ahttoc.htm" rel="noreferrer">How tos</a>" page might help you get started. There are also some good books that will help you move forward:</p> <ol> <li><a href="https://rads.stackoverflow.com/amzn/click/com/0596154143" rel="noreferrer" rel="nofollow noreferrer">Programming Interactivity</a>.</li> <li><a href="http://www.makingthingsmove.com/about-the-book/" rel="noreferrer">Making Things Move DIY Mechanisms for Inventors, Hobbyists, and Artists</a> </li> </ol> <p><a href="http://wiring.org.co/" rel="noreferrer">Wiring</a> is a platform similar to Arduino.</p> <p>Also have a look at the <a href="http://en.wikipedia.org/wiki/Forth_%28programming_language%29" rel="noreferrer">Forth</a> programming language. There are lot of interesting "<a href="http://www.ultratechnology.com/" rel="noreferrer">tiny computers</a>" that you can program with this rather unusual language. Here is a partial list:</p> <ol> <li><a href="http://www.forth.com/" rel="noreferrer">Forth Inc</a></li> <li><a href="http://greenarraychips.com/" rel="noreferrer">Greenarrays</a></li> <li><a href="http://maptools.home.comcast.net/~maptools/Z8/" rel="noreferrer">Zilog Z8</a></li> <li><a href="http://pic18forth.sourceforge.net/" rel="noreferrer">PIC18Fxx2</a></li> </ol> <p>Two famous Forth books:</p> <ol> <li><a href="http://www.forth.com/starting-forth/index.html" rel="noreferrer">Starting Forth</a></li> <li><a href="http://thinking-forth.sourceforge.net/" rel="noreferrer">Thinking Forth</a> (A classic in Software Engineering literature.)</li> </ol>
6,409,372
Committing the code on Subversion (first time)
<p>I am new on Subversion. I have to commit a code on subversion and this is the first time that I am doing this. So my mentor told me to put username on his server using SSH. I did this by following code:</p> <p><code>amit@&lt;URL&gt;</code> and it works fine.</p> <p>Now he asked to commit the code and he give me url, but he said me to create a folder first by username which you have got at the time of SSH i.e. amit. </p> <p>How I create a folder on svn link and then how to commit the project.</p>
6,409,393
7
2
null
2011-06-20 09:41:48.513 UTC
1
2019-02-28 06:46:04.507 UTC
2018-09-02 18:06:40.153 UTC
null
472,495
user478489
null
null
1
12
svn|ssh|commit|svn-checkout
57,099
<p>First checkout that repository by</p> <pre><code>svn checkout &lt;Your URL&gt; svn </code></pre> <p>Now <code>cd</code> to <strong>svn</strong> folder, create username folder(amit) in <strong>svn</strong> folder and commit:</p> <pre><code>svn commit -m"username folder is created." </code></pre> <p>Now copy your files in that folder(<strong>amit</strong> in your case). Now you have to add each new file or new folder:</p> <pre><code>svn add filename svn add foldername </code></pre> <p>Now you can commit these files to server:</p> <pre><code>svn commit -m"Some new files are added." </code></pre> <p><strong>Note:</strong> <em>Text after <code>-m</code> are comments and you can change it according to your needs.</em></p>
6,646,405
How do you add Boost libraries in CMakeLists.txt?
<p>I need to add Boost libraries into my CMakeLists.txt. How do you do it or how do you add it?</p>
6,646,518
8
1
null
2011-07-11 06:14:46.323 UTC
68
2022-09-17 05:58:41.467 UTC
2018-09-05 00:43:47.397 UTC
null
63,550
null
800,821
null
1
157
boost|cmake
188,290
<p>Put this in your <code>CMakeLists.txt</code> file (change any options from OFF to ON if you want):</p> <pre><code>set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME OFF) find_package(Boost 1.45.0 COMPONENTS *boost libraries here*) if(Boost_FOUND) include_directories(${Boost_INCLUDE_DIRS}) add_executable(progname file1.cxx file2.cxx) target_link_libraries(progname ${Boost_LIBRARIES}) endif() </code></pre> <p>Obviously you need to put the libraries you want where I put <code>*boost libraries here*</code>. For example, if you're using the <code>filesystem</code> and <code>regex</code> library you'd write:</p> <pre><code>find_package(Boost 1.45.0 COMPONENTS filesystem regex) </code></pre>
45,632,920
Why should one use Objects.requireNonNull()?
<p>I have noted that many Java 8 methods in Oracle JDK use <code>Objects.requireNonNull()</code>, which internally throws <code>NullPointerException</code> if the given object (argument) is <code>null</code>.</p> <pre><code>public static &lt;T&gt; T requireNonNull(T obj) { if (obj == null) throw new NullPointerException(); return obj; } </code></pre> <p>But <code>NullPointerException</code> will be thrown anyway if a <code>null</code> object is dereferenced. So, why should one do this extra null check and throw <code>NullPointerException</code>?</p> <p>One obvious answer (or benefit) is that it makes code more readable and I agree. I'm keen to know any other reasons for using <code>Objects.requireNonNull()</code> in the beginning of the method.</p>
45,632,962
12
6
null
2017-08-11 10:26:19.197 UTC
74
2022-08-10 05:01:59.08 UTC
2019-03-29 14:25:39.623 UTC
null
5,506,167
null
4,686,046
null
1
368
java|java-8|nullpointerexception
164,152
<p>Because you can make things <strong>explicit</strong> by doing so. Like:</p> <pre><code>public class Foo { private final Bar bar; public Foo(Bar bar) { Objects.requireNonNull(bar, "bar must not be null"); this.bar = bar; } </code></pre> <p>Or shorter:</p> <pre><code> this.bar = Objects.requireNonNull(bar, "bar must not be null"); </code></pre> <p>Now you <strong>know</strong>: </p> <ul> <li><em>when</em> a Foo object was successfully created using <code>new()</code> </li> <li><em>then</em> its <em>bar</em> field is <strong>guaranteed</strong> be non-null.</li> </ul> <p>Compare that to: you create a Foo object today, and <strong>tomorrow</strong> you invoke a method that uses that field and throws. Most likely, you will not know tomorrow why that reference was null <em>yesterday</em> when it got passed to the constructor!</p> <p>In other words: by explicitly using this method to check <em>incoming</em> references you can <strong>control</strong> the point in time when the exception will be thrown. And most of the time, you want to <em>fail as fast as possible</em>!</p> <p>The major advantages are:</p> <ul> <li>as said, <em>controlled</em> behavior</li> <li>easier debugging - because you throw up in the context of the object creation. At a point in time where you have a certain chance that your logs/traces tell you what went wrong!</li> <li>and as shown above: the true power of this idea unfolds in conjunction with <em>final</em> fields. Because now <em>any other code</em> in your class can safely assume that <code>bar</code> isn't null - and thus you do not need any <code>if (bar == null)</code> checks in other places!</li> </ul>
16,000,548
Google Play Services in emulator, implementing Google Plus login button etc
<p>When integrating a Google Plus login button in an Android app, I'm observing some differences in how the button appears on an actual device and in the emulator. I am aware of the fact that the Google Plus services APKs are not installed in the emulator, but this can be worked around by pulling the APKs from a device and installing them into the emulator using APK.</p> <p>My current "implementation" simply includes the login button in a layout, by referring to the button with the following XML code:</p> <pre><code>&lt;com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; </code></pre> <p>When I test my app on the device, the button appears all red and shiny, according to the guidelines mentioned here <a href="https://developers.google.com/+/mobile/android/sign-in" rel="noreferrer">https://developers.google.com/+/mobile/android/sign-in</a> . But when running on the emulator, it's just a normal button (grey background with black text) saying "Sign in with Google".</p> <p>Any idea why the results are different? I've made sure I'm running the same API level, and the resource does seem to get pulled in correctly also on the emulator since it shows the actual login button (but with a different look).</p> <p><b>Update:</b> Found a clue in logcat; the message "Sign in button not found, using placeholder instead." pretty much explains why I'm seeing the grey dull button on the emulator. Still need to figure out why; could be the "copy google plus apk's from device" hack isn't working properly.</p>
17,245,326
4
2
null
2013-04-14 15:09:01.683 UTC
13
2016-04-07 07:17:20.977 UTC
2013-04-15 09:55:42.07 UTC
null
116,879
null
116,879
null
1
17
android|google-plus|google-play|google-play-services
66,456
<p>Google Play services works on the 4.2.2 versions of the Android Emulator and is officially supported as described in the <a href="http://developer.android.com/google/play-services/setup.html" rel="noreferrer">Android documentation: Setup Google Play Services</a>.</p> <p><strong>Update</strong></p> <p>You now can use the Intel/x86 images (HAXM-compatible) for API 19 and newer and for ARM, Google Play Services is available on most images.</p> <p><strong>Setting up the image</strong></p> <p>To get the right image for your virtual device manager:</p> <ul> <li>Open the Android SDK Manager</li> <li>Open the group Android 4.2.2 (API 17)</li> <li>Check Google APIs</li> <li>Check ARM EABI v7a System Image</li> </ul> <p><img src="https://i.stack.imgur.com/Yv4Tw.png" alt="enter image description here"></p> <p>To create the Virtual Device:</p> <ul> <li>Open the Android Virtual Device Manager </li> <li>Create a New device </li> <li>Enter an AVD name</li> <li>Set the target to <em>Google APIs (Google Inc.) - API Level 17</em></li> <li>Save your Virtual device and start it...</li> </ul> <p><strong>Note</strong> <em>CPU/ABI will be fixed as ARM</em></p> <p><img src="https://i.stack.imgur.com/x6zI2.png" alt="enter image description here"></p> <p>Now you should be able to use the Google Play Services in the emulator. Of note, you need to set your target appropriately in your Android project to the Google APIs in order for Google Play Services to work.</p>
15,786,618
Per Process disk read/write statistics in Mac OS X
<p>How do I get programatically per process disk i/o statistics in Mac OS X. In 'Activity Monitor' application or in 'top' command we can only get whole system disk i/o statistics.<br> For reference <a href="https://stackoverflow.com/questions/1639903/programmatically-getting-per-process-disk-io-statistics-on-windows">Similar question asked for PC.</a></p>
16,451,377
5
1
null
2013-04-03 11:53:10.43 UTC
10
2019-07-10 08:50:17.627 UTC
2017-05-23 12:32:11.663 UTC
null
-1
null
42,078
null
1
27
performance|macos|statistics|disk
16,410
<p>Use <code>iotop</code> (as root), for example:</p> <pre><code>iotop -C 3 10 </code></pre> <p>But the best way (for me) is:</p> <pre><code>sudo fs_usage -f filesys </code></pre>
10,681,101
Git Bash doesn't see my PATH
<p>When I use Git Bash (on Windows), I cannot run any executable without specifying its full path, although it is located in a folder which is in my PATH variable. Looks like bash doesn't recognize it. Why? Can I fix it?</p>
10,764,080
21
4
null
2012-05-21 07:33:25.16 UTC
23
2021-05-11 03:21:35.387 UTC
null
null
null
null
112,757
null
1
129
windows|bash|git-bash
224,139
<p>Got it. As a Windows user, I'm used to type executable names without extensions. In my case, I wanted to execute a file called <code>cup.bat</code>. In a Windows shell, typing <code>cup</code> would be enough. Bash doesn't work this way, it wants the full name. Typing <code>cup.bat</code> solved the problem. (I wasn't able to run the file though, since apparently bash couldn't understand its contents)</p> <p>One more reason to switch to posh-git..</p> <p>Thanks @Tom for pointing me to the right direction.</p>
10,473,823
Android get image from gallery into ImageView
<p>I'm trying to add a photo from galery to a <code>ImageView</code> but I get this error:</p> <blockquote> <p>java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/1 }} to activity {hotMetter.pack/hotMetter.pack.GetPhoto}: java.lang.NullPointerException</p> </blockquote> <p>This is my code:</p> <pre class="lang-java prettyprint-override"><code> Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE); } Bitmap bitmap=null; public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == Activity.RESULT_OK) { if (requestCode == SELECT_PICTURE) { Uri selectedImageUri = data.getData(); selectedImagePath = getPath(selectedImageUri); tv.setText(selectedImagePath); img.setImageURI(selectedImageUri); } } public String getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); if (cursor == null) return null; int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); String s=cursor.getString(column_index); cursor.close(); return s; } </code></pre> <p>I get the <code>selectedImagePath="mnt/sdcard/DCIM/myimage"</code> but on <code>img.setImageURI(selectedImageUri);</code> i get the error.</p> <p>I've also used a <code>Bitmap</code> and tried to set the image from <code>SetImageBitmap</code> but i get the same error.</p> <p>LogCat:</p> <pre><code>05-06 19:41:34.191: E/AndroidRuntime(8466): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/1 }} to activity {hotMetter.pack/hotMetter.pack.GetPhoto}: java.lang.NullPointerException 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.deliverResults(ActivityThread.java:2532) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.handleSendResult(ActivityThread.java:2574) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.access$2000(ActivityThread.java:117) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:961) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.os.Handler.dispatchMessage(Handler.java:99) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.os.Looper.loop(Looper.java:123) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.main(ActivityThread.java:3683) 05-06 19:41:34.191: E/AndroidRuntime(8466): at java.lang.reflect.Method.invokeNative(Native Method) 05-06 19:41:34.191: E/AndroidRuntime(8466): at java.lang.reflect.Method.invoke(Method.java:507) 05-06 19:41:34.191: E/AndroidRuntime(8466): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 05-06 19:41:34.191: E/AndroidRuntime(8466): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 05-06 19:41:34.191: E/AndroidRuntime(8466): at dalvik.system.NativeStart.main(Native Method) 05-06 19:41:34.191: E/AndroidRuntime(8466): Caused by: java.lang.NullPointerException 05-06 19:41:34.191: E/AndroidRuntime(8466): at hotMetter.pack.GetPhoto.onActivityResult(GetPhoto.java:55) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.Activity.dispatchActivityResult(Activity.java:3908) 05-06 19:41:34.191: E/AndroidRuntime(8466): at android.app.ActivityThread.deliverResults(ActivityThread.java:2528) </code></pre> <p>Advice please.Thanks!</p>
10,474,092
13
5
null
2012-05-06 20:03:27.693 UTC
22
2021-05-07 17:40:49.28 UTC
2016-09-18 18:19:51.16 UTC
null
4,908,802
null
1,378,505
null
1
56
android|imageview|gallery|image-gallery|getimagedata
173,945
<p>Run the app in debug mode and set a breakpoint on if <code>(requestCode == SELECT_PICTURE)</code> and inspect each variable as you step through to ensure it is being set as expected. If you are getting a NPE on <code>img.setImageURI(selectedImageUri);</code> then either <code>img</code> or <code>selectedImageUri</code> are not set. </p>
10,606,328
Why isn't there an asynchronous file delete in .net?
<p>You have the asynchronous versions of read and write (begin/end functions), but not of delete (that I can tell). Is there any reason for this? Isn't there as much reason to do delete asynchronously as read/write? </p> <p>Using threading to simulate asynchronous behavior is not the same as asynchronous functions. Big difference, sure you get the perceived parallel processing, but it's not really preventing blocking, that other thread is still blocked waiting for the file i/o to complete. The real asynchronous functions (begin/end functions) operate at a system level, they queue up file i/o, let the application proceed, and let the application know when it is ready to proceed with the file i/o (allowing you to do other things while you wait for the file i/o to come available).</p>
10,607,467
6
7
null
2012-05-15 18:02:26.263 UTC
8
2020-08-01 04:25:06.237 UTC
2012-05-15 20:31:07.577 UTC
null
212,313
null
212,313
null
1
58
.net|file-io|asynchronous
23,993
<p>This would be useful. DeleteFile could take up to 30s if deleting on a disconnected network share.</p> <p>The reason is likely to be that there is no native function to delete a file asynchronously. The managed APIs generally are wrappers around the unmanaged ones.</p> <hr> <p>Now why is there no native asynchronous file delete API? Native async deletion is hard to implement on Windows as it is. <code>DeleteFile</code> does in pseudocode <code>CreateFile</code> plus <code>NtSetInformationFile(Disposition, Delete)</code> plus <code>CloseHandle</code>. There is no async <code>CreateFile</code> (in my opinion a design bug in Windows). <code>NtSetInformationFile</code> just sets a flag on the file data structure in the kernel. It can't be asynchronous. The actual deletion happens when the last handle is closed. I think this might make <code>CloseHandle</code> blocking which is another design issue in Windows. There is no async <code>CloseHandle</code>.</p>
4,409,019
How to redirect users using HTTP response
<p>I have a scenario where the user clicks on a 'restaurant' link (for searching restaurants in a particular locality). I have to check whether the location is set or not. If it is not set, I want to redirect him to a page that allows him to set the location, and, then, go back to search results filtered by the set location. I'm using <code>response.sendRedirect(url)</code> to redirect the user to the setting location page. But, how can I send the redirect back URL (i.e., the URL where I want to send the user after the location is set)?</p> <p>I tried this:</p> <pre><code>response.sendRedirect("/location/set.html?action=asklocation&amp;redirectUrl="+ request.getRequestUri()+request.getQueryString()); </code></pre> <p>but this isn't working and 404 error is shown; also, the url formed in the browser doesn't look good.</p> <p>Please, if anyone could solve the problem ...</p>
4,409,157
2
1
null
2010-12-10 12:57:12.813 UTC
1
2017-01-15 21:40:05.8 UTC
2016-04-05 16:20:07.657 UTC
null
5,759,943
null
390,230
null
1
3
java|struts
42,497
<p>Looks like you're missing at least a "?" between <code>request.getRequestUri()</code> and <code>request.getQueryString()</code>. You should url-encode the parameter as well, which you can use <code>java.net.URLEncoder</code> for.</p> <p>Also, when doing redirects you need to prepend the context path: <code>request.getContextPath()</code>.</p> <p>Something like</p> <pre><code>String secondRedirectUrl = request.getRequestUri()+"?"+request.getQueryString(); String encodedSecondRedirectUrl = URLEncoder.encode(secondRedirectUrl, serverUrlEncodingPreferablyUTF8); String firstRedirectUrl = request.getContextPath()+"/location/set.html?action=asklocation&amp;redirectUrl="+encodedSecondRedirectUrl; response.sendRedirect(firstRedirectUrl); </code></pre> <p>Personally, i'd rather solve the problem by storing a <code>RequestDispatcher</code> in the session and forwarding to it after the location has been set.</p>
37,677,750
Pdf file size too big created using jspdf
<p>I am using jspdf for creating PDF inside browser. I am having multiple charts having svg as chart Data. For adding data to pdf I am converting svg to png using canvas and then Base64 Data using <code>canvas.toDataURL</code> method. After all this conversions size of the file created by jspdf is huge (about 50 MB). Below is the code for div of chart data and canvas.</p> <pre><code>newdiv = document.createElement("div"); newdiv.className = "big_Con_graph big_Con_graph0"; newdiv.style.height = "0px"; newdiv.id = "big_Con_graph" + id; </code></pre> <p></p> <p>below is the dimensions for SVG chart load.</p> <pre><code>document.getElementById("big_Con_graph" + id).style.display = "block"; var big_chartReference = FusionCharts("big_myChartId"+id); if(big_chartReference != null){ big_chartReference.dispose(); } var big_width = "1088"; var big_height = "604"; </code></pre> <p>now below is the code for conversion of above graph SVG data and adding to PDF.</p> <pre><code>var elem_graph = $($('.big_Con_graph,big_Con_graph0')[count]).clone(true); svgString = $(elem_graph).find("span").html(); var img = document.createElement('img'); var DOMURL = self.URL || self.webkitURL || self; var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"}); var url = DOMURL.createObjectURL(svg); img.onload = pdfAfterImageLoad(img,pdf,imgLoadSequence,DOMURL,totalReports,reportName); img.src = url; </code></pre> <p>this is the code for PDFAfterImageLoad function:</p> <pre><code>var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); var png = canvas.toDataURL("image/png"); pdf.addImage(png, 'PNG', leftmargin, 120, 485, 270); </code></pre> <p>I am using png, so imagequality parameter can not be used.</p> <p>Can anyone help me decrease the file size?</p>
37,915,636
6
8
null
2016-06-07 11:10:04.14 UTC
19
2021-07-16 12:56:35.933 UTC
2016-06-16 05:52:21.873 UTC
null
1,420,197
null
970,785
null
1
39
javascript|html5-canvas|base64|jspdf|fusioncharts
46,212
<p>You need to compress the images in the PDF's that you are generating. Try using Deflate.js and adler32cs.js and use the compress parameter in both jsPDF and addImage functions that you are using. For eg : </p> <pre><code>var doc = new jsPDF('p', 'pt','a4',true); </code></pre> <p>make sure you set the last parameter as 'true' refer to : <a href="https://github.com/MrRio/jsPDF/blob/ddbfc0f0250ca908f8061a72fa057116b7613e78/jspdf.js#L146" rel="noreferrer">https://github.com/MrRio/jsPDF/blob/ddbfc0f0250ca908f8061a72fa057116b7613e78/jspdf.js#L146</a></p> <p>Go through it and you can clearly see that the last parameter is for enabling compression.</p> <p>Also use :</p> <pre><code>pdf.addImage(png, 'PNG', leftmargin, 120, 485, 270,'','FAST'); </code></pre> <p>instead of</p> <pre><code>pdf.addImage(png, 'PNG', leftmargin, 120, 485, 270); </code></pre> <p>you can choose between NONE, FAST, MEDIUM and SLOW, whichever suits you best.</p>
35,713,244
Circular (round) UIView resizing with AutoLayout... how to animate cornerRadius during the resize animation?
<p>I have a subclassed UIView that we can call <code>CircleView</code>. CircleView automatically sets a corner radius to half of its width in order for it to be a circle.</p> <p>The problem is that when "CircleView" is resized by an AutoLayout constraint... for example <strong>on a device rotation</strong>... it distorts badly until the resize takes place because the "cornerRadius" property has to catch up, and the OS only sends a single "bounds" change to the view's frame.</p> <p>I was wondering if anyone had a good, clear strategy for implementing "CircleView" in a way that won't distort in such instances, <strong>but will still mask its contents to the shape of a circle and allow for a border to exist around said UIView.</strong></p>
35,714,554
5
9
null
2016-03-01 01:47:23.093 UTC
13
2018-01-12 20:58:41.23 UTC
2016-04-29 16:02:31.523 UTC
null
77,567
null
963,901
null
1
13
ios|uiview
6,723
<h2>UPDATE: If your deployment target is iOS 11 or later:</h2> <p>Starting in iOS 11, UIKit will animate <code>cornerRadius</code> if you update it inside an animation block. Just set your view's <code>layer.cornerRadius</code> in a <code>UIView</code> animation block, or (to handle interface orientation changes), set it in <code>layoutSubviews</code> or <code>viewDidLayoutSubviews</code>.</p> <h2>ORIGINAL: If your deployment target is older than iOS 11:</h2> <p>So you want this:</p> <p><a href="https://i.stack.imgur.com/UN498.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/UN498.gif" alt="smoothly resizing circle view"></a></p> <p>(I turned on Debug > Slow Animations to make the smoothness easier to see.)</p> <p><strong>Side rant,</strong> feel free to skip this paragraph: This turns out to be a lot harder than it should be, because the iOS SDK doesn't make the parameters (duration, timing curve) of the autorotation animation available in a convenient way. You can (I think) get at them by overriding <code>-viewWillTransitionToSize:withTransitionCoordinator:</code> on your view controller to call <code>-animateAlongsideTransition:completion:</code> on the transition coordinator, and in the callback you pass, get the <code>transitionDuration</code> and <code>completionCurve</code> from the <code>UIViewControllerTransitionCoordinatorContext</code>. And then you need to pass that information down to your <code>CircleView</code>, which has to save it (because it hasn't been resized yet!) and later when it receives <code>layoutSubviews</code>, it can use it to create a <code>CABasicAnimation</code> for <code>cornerRadius</code> with those saved animation parameters. And don't accidentally create an animation when it's <strong>not</strong> an animated resize… <strong>End of side rant.</strong></p> <p>Wow, that sounds like a ton of work, and you have to involve the view controller. Here's another approach that's entirely implemented inside <code>CircleView</code>. It works now (in iOS 9) but I can't guarantee it'll always work in the future, because it makes two assumptions that could theoretically be wrong in the future.</p> <p>Here's the approach: override <code>-actionForLayer:forKey:</code> in <code>CircleView</code> to return an action that, when run, installs an animation for <code>cornerRadius</code>.</p> <p>These are the two assumptions:</p> <ul> <li><code>bounds.origin</code> and <code>bounds.size</code> get separate animations. (This is true now but presumably a future iOS could use a single animation for <code>bounds</code>. It would be easy enough to check for a <code>bounds</code> animation if no <code>bounds.size</code> animation were found.)</li> <li>The <code>bounds.size</code> animation is added to the layer before Core Animation asks for the <code>cornerRadius</code> action.</li> </ul> <p>Given these assumptions, when Core Animation asks for the <code>cornerRadius</code> action, we can get the <code>bounds.size</code> animation from the layer, copy it, and modify the copy to animate <code>cornerRadius</code> instead. The copy has the same animation parameters as the original (unless we modify them), so it has the correct duration and timing curve.</p> <p>Here's the start of <code>CircleView</code>:</p> <pre><code>class CircleView: UIView { override func layoutSubviews() { super.layoutSubviews() updateCornerRadius() } private func updateCornerRadius() { layer.cornerRadius = min(bounds.width, bounds.height) / 2 } </code></pre> <p>Note that the view's bounds are set before the view receives <code>layoutSubviews</code>, and therefore before we update <code>cornerRadius</code>. This is why the <code>bounds.size</code> animation is installed before the <code>cornerRadius</code> animation is requested. Each property's animations are installed inside the property's setter.</p> <p>When we set <code>cornerRadius</code>, Core Animation asks us for a <code>CAAction</code> to run for it:</p> <pre><code> override func action(for layer: CALayer, forKey event: String) -&gt; CAAction? { if event == "cornerRadius" { if let boundsAnimation = layer.animation(forKey: "bounds.size") as? CABasicAnimation { let animation = boundsAnimation.copy() as! CABasicAnimation animation.keyPath = "cornerRadius" let action = Action() action.pendingAnimation = animation action.priorCornerRadius = layer.cornerRadius return action } } return super.action(for: layer, forKey: event) } </code></pre> <p>In the code above, if we're asked for an action for <code>cornerRadius</code>, we look for a <code>CABasicAnimation</code> on <code>bounds.size</code>. If we find one, we copy it, change the key path to <code>cornerRadius</code>, and save it away in a custom <code>CAAction</code> (of class <code>Action</code>, which I will show below). We also save the current value of the <code>cornerRadius</code> property, because Core Animation calls <code>actionForLayer:forKey:</code> <strong>before</strong> updating the property.</p> <p>After <code>actionForLayer:forKey:</code> returns, Core Animation updates the <code>cornerRadius</code> property of the layer. Then it runs the action by sending it <code>runActionForKey:object:arguments:</code>. The job of the action is to install whatever animations are appropriate. Here's the custom subclass of <code>CAAction</code>, which I've nested inside <code>CircleView</code>:</p> <pre><code> private class Action: NSObject, CAAction { var pendingAnimation: CABasicAnimation? var priorCornerRadius: CGFloat = 0 public func run(forKey event: String, object anObject: Any, arguments dict: [AnyHashable : Any]?) { if let layer = anObject as? CALayer, let pendingAnimation = pendingAnimation { if pendingAnimation.isAdditive { pendingAnimation.fromValue = priorCornerRadius - layer.cornerRadius pendingAnimation.toValue = 0 } else { pendingAnimation.fromValue = priorCornerRadius pendingAnimation.toValue = layer.cornerRadius } layer.add(pendingAnimation, forKey: "cornerRadius") } } } } // end of CircleView </code></pre> <p>The <code>runActionForKey:object:arguments:</code> method sets the <code>fromValue</code> and <code>toValue</code> properties of the animation and then adds the animation to the layer. There's a complication: UIKit uses “additive” animations, because they work better if you start another animation on a property while an earlier animation is still running. So our action checks for that.</p> <p>If the animation is additive, it sets <code>fromValue</code> to the difference between the old and new corner radii, and sets <code>toValue</code> to zero. Since the layer's <code>cornerRadius</code> property has already been updated by the time the animation is running, adding that <code>fromValue</code> at the start of the animation makes it look like the old corner radius, and adding the <code>toValue</code> of zero at the end of the animation makes it look like the new corner radius.</p> <p>If the animation is not additive (which doesn't happen if UIKit created the animation, as far as I know), then it just sets the <code>fromValue</code> and <code>toValue</code> in the obvious way.</p> <p>Here's the whole file for your convenience:</p> <pre><code>import UIKit class CircleView: UIView { override func layoutSubviews() { super.layoutSubviews() updateCornerRadius() } private func updateCornerRadius() { layer.cornerRadius = min(bounds.width, bounds.height) / 2 } override func action(for layer: CALayer, forKey event: String) -&gt; CAAction? { if event == "cornerRadius" { if let boundsAnimation = layer.animation(forKey: "bounds.size") as? CABasicAnimation { let animation = boundsAnimation.copy() as! CABasicAnimation animation.keyPath = "cornerRadius" let action = Action() action.pendingAnimation = animation action.priorCornerRadius = layer.cornerRadius return action } } return super.action(for: layer, forKey: event) } private class Action: NSObject, CAAction { var pendingAnimation: CABasicAnimation? var priorCornerRadius: CGFloat = 0 public func run(forKey event: String, object anObject: Any, arguments dict: [AnyHashable : Any]?) { if let layer = anObject as? CALayer, let pendingAnimation = pendingAnimation { if pendingAnimation.isAdditive { pendingAnimation.fromValue = priorCornerRadius - layer.cornerRadius pendingAnimation.toValue = 0 } else { pendingAnimation.fromValue = priorCornerRadius pendingAnimation.toValue = layer.cornerRadius } layer.add(pendingAnimation, forKey: "cornerRadius") } } } } // end of CircleView </code></pre> <p>My answer was inspired by <a href="https://stackoverflow.com/a/10902063/77567">this answer by Simon</a>.</p>
40,914,108
Bash: Python3: command not found (Windows, discord.py)
<p>I've been trying to configure the discord API discord.py and for the purpose of running the Red-MusicBot on my server. I've installed Python 3.5, and added the PATH variables (I clicked the "add Python to PATH" option in install). Here's what my path variables currently look like:</p> <pre class="lang-none prettyprint-override"><code>C:\Users\Corey Rigney\AppData\Local\Programs\Python\Python35\Scripts\ C:\Users\Corey Rigney\AppData\Local\Programs\Python\Python35\ </code></pre> <p>Those are the only ones related to Python. Now, as part of discord.py's install process, it wants me to run this command in Git Bash:</p> <pre class="lang-none prettyprint-override"><code>$ git clone https://github.com/Rapptz/discord.py $ cd discord.py $ python3 -m pip install -U .[voice] </code></pre> <p>The first two lines work perfectly, but the third line returns:</p> <pre class="lang-none prettyprint-override"><code>bash: python3: command not found </code></pre> <p>I also cloned pip from GitHub as an attempted fix, although the python install site says it comes packaged with 3.5.</p> <p>I'm running windows 10, 64-bit.</p> <p>The overall goal of this is to install a discord music bot, if it would help I can post the errors I get when trying to run that.</p>
40,931,434
7
15
null
2016-12-01 15:12:34.433 UTC
12
2021-05-17 13:13:58.387 UTC
2016-12-01 18:20:13.947 UTC
null
2,747,593
null
5,353,600
null
1
24
pip|python-3.5|git-bash|discord
116,850
<p>On Windows the normal name for the python executable is <code>python.exe</code> (console program) or <code>pythonw.exe</code> (for GUI programs). </p> <p>The python executable is sometimes called <code>python3</code> on some platforms, where the default (<code>python</code>) is the old python 2. On many UNIX-based (inc. Linux and OS X) systems, python 2 is used by system utilities, changing it could have bad consequences on those platforms, hence the name "python3". </p> <p>On Windows you should be fine - there are other issues on Windows but you won't get those unless you try to use more than one python version.</p>
13,407,006
Android: "Class loader may fail for processes that host multiple applications"
<p>What does this message in Eclipse's logcat for Android mean?</p> <pre><code>W/ActivityThread: ClassLoader.getResources: The class loader returned by Thread.getContextClassLoader() may fail for processes that host multiple applications. You should explicitly specify a context class loader. For example: Thread.setContextClassLoader(getClass().getClassLoader()); </code></pre> <p>Unfortunately, there is no context given as to this warning, so I don't know what causes this problem and how I can resolve it.</p>
13,455,154
2
2
null
2012-11-15 22:01:46.533 UTC
12
2016-08-30 11:08:50.473 UTC
null
null
null
null
89,818
null
1
21
android|multithreading|classloader
13,413
<h2>Background information</h2> <p>The message means that Android has setup a dummy <code>ClassLoader</code> with <code>Thread.currentThread().setContextClassLoader()</code>, and something tries to use that dummy class loader. The <em>something</em> can be a lot of things, it's hard to tell exactly what from the information given. There is a trick you can try though, see below. Anyway, Android sets up the dummy class loader when there is a risk that the process might contain code from more than one APK. More specifically, Android looks in your manifest if you have used <code>android:sharedUserId</code>:</p> <pre><code>&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" ... android:sharedUserId="triggers.dummy.loader" &gt; </code></pre> <p>or if you run in a non-standard <code>android:process</code></p> <pre><code> &lt;application android:process="triggers.dummy.loader"&gt; </code></pre> <h2>How to get rid of the warning</h2> <p>There are two things you can do to get rid of the warning:</p> <ol> <li>Don't use <code>android:sharedUserId</code> or <code>android:process</code></li> <li>Explicitly set what APK <code>ClassLoader</code> to use before running any other code</li> </ol> <p>To go with solution 2, there are some key insights you need. First, for any class <code>AnyClass</code> in an APK, <code>AnyClass.class.getClassLoader()</code> will return the same <code>ClassLoader</code>. Second,</p> <pre><code>AnyClass obj = new AnyClass(); Thread.currentThread().setContextClassLoader(obj.getClass().getClassLoader()) </code></pre> <p>is the same as</p> <pre><code>Thread.currentThread().setContextClassLoader(AnyClass.class.getClassLoader()) </code></pre> <p>Third, you need to call <code>Thread.currentThread().setContextClassLoader(getClass().getClassLoader())</code> before the code that calls <code>Thread.currentThread().getContextClassLoader()</code>. Fourth, When many APKs are involved, you need to call <code>Thread.setContextClassLoader(getClass().getClassLoader())</code> <em>after</em> the last APK has been loaded (otherwise loading the last APK will overwrite what you have set manually). Because of that, it would be a good idea to find out who is using the context class loader in you case by using the below debug trick. Then, right before that, you call <code>Thread.setContextClassLoader(getClass().getClassLoader())</code> for a class from the desired APK, typically the APK that is loaded first (or, in the case when only one APK is involved, that APK ;). Fifth, the context class loader is <em>per thread</em>, which you need to keep in mind if your application is multi-threaded.</p> <h2>Debug trick</h2> <p>If you want to find out what code that calls ClassLoader.getResources(), this should work:</p> <pre><code>Thread.currentThread().setContextClassLoader(new ClassLoader() { @Override public Enumeration&lt;URL&gt; getResources(String resName) throws IOException { Log.i("Debug", "Stack trace of who uses " + "Thread.currentThread().getContextClassLoader()." + "getResources(String resName):", new Exception()); return super.getResources(resName); } }); </code></pre> <p>if you do this early enough, you should see in the logcat a stack trace that goes back to whoever calls <code>getResources()</code> on the dummy class loader.</p>
13,638,896
TFS and Scrum - Best Practice configuration for Areas, Iterations, backlog iteration, sprint iteration
<p><em>This set of questions tries to elicit a best practice answer on how to setup TFS 2012 Areas and Iterations with Scrum 2.</em></p> <p><strong>Context:</strong> We've been using Team System since TFS 2005 and had initially created a Team Project for each product we have and then used MSF 4.2 process template which we eventually tweaked slightly (only added a few fields to some work item types).</p> <p>Roll forward to present day and we now run TFS 2012 and VS 2012. Taking into account past experiences and community feedback we will move to a single Team Project and Scrum 2.1 and then use areas to separate products and teams. The following links make good reading for this approach:</p> <ul> <li><a href="http://blog.hinshelwood.com/when-should-i-use-areas-in-tfs-instead-of-team-projects-in-team-foundation-server-2010/" rel="nofollow noreferrer">http://blog.hinshelwood.com/when-should-i-use-areas-in-tfs-instead-of-team-projects-in-team-foundation-server-2010/</a></li> <li><a href="https://stackoverflow.com/questions/8582557/tfs-areas-optimal-definition-and-configuration">TFS Areas, Optimal Definition and Configuration</a></li> <li><a href="https://stackoverflow.com/questions/5106557/team-foundation-server-area-iteration">Team Foundation Server - Area / Iteration</a></li> </ul> <p>A typical layout we plan to applying for areas would be along these lines:</p> <pre><code>-&gt; Team Project (Area root) |--&gt; Client A (This is also out team boundary - ie. we have a TFS Team for Client A) |---&gt; Product A | |---&gt; Feature Area 1 | |---&gt; Feature Area 2 | |---&gt; Feature Area 3 | |---&gt; Product B | |---&gt; Feature Area 1 | |---&gt; Feature Area 2 | | (ETC) |--&gt; Client B (This is also out team boundary - ie. we have another TFS Team for Client B) |---&gt; Product C | |---&gt; Feature Area 1 | |---&gt; Feature Area 2 | | (ETC) </code></pre> <p>Conceptually we are pretty happy with the above as it is logical to our environment. According to the above we would have teams as follows: * "Client A Team" * "Client B Team"</p> <p><strong>Question 1)</strong> We figured that because our teams aren't that big and to make administration more manageable, that we didn't want to define teams per product since we physically have teams per client and they oversee all the products for that client. Is this a mistake, or is this OK?</p> <p><strong>Question 2)</strong> Asuming that the above team configuration is OK, are we then correct to "map" each of the areas above to each team i.e. For team "Client A Team" specify area "Client A" (and all sub-areas) as the areas to be owned by that team. What about the default area, is it ok to set the root of the "Client A" area as the default for the team?</p> <p>As for the iterations layout we plan for something similar, like this:</p> <pre><code>-&gt; Team Project (iteration root) |--&gt; Client A (This is also out team boundary - ie. we have a TFS Team for Client A) |---&gt; Product A | |---&gt; Release 1 | | |---&gt; Sprint 1 | | |---&gt; Sprint 2 | | |---&gt; Sprint 3 | | | |---&gt; Release 2 | | |---&gt; Sprint 1 | | |---&gt; Sprint 2 | | |---&gt; Sprint 3 | | | |---&gt; Release 3 | |---&gt; Product B | |---&gt; Release 1 | | |---&gt; Sprint 1 | | |---&gt; Sprint 2 | | | |---&gt; Release 2 | | |---&gt; Sprint 1 | | |---&gt; Sprint 2 | | (ETC) |--&gt; Client B (This is also out team boundary - ie. we have another TFS Team for Client B) |---&gt; Product C | |---&gt; Release 1 | | |---&gt; Sprint 1 | | |---&gt; Sprint 2 | | | |---&gt; Release 2 | | |---&gt; Sprint 1 | | |---&gt; Sprint 2 | | (ETC) </code></pre> <p><strong>Question 3)</strong> This seems to be trickier to get the iterations right, especially when it comes to TFS showing the backlog. Specifically, for the TFS Scrum 2 Iteration setup, it seems that I should be selecting (check box) only those leaf level iterations that are for planning and subsequent development. So extending the above example, we might have that the "Client A Team" will be available to start work on a new Product B for the next 4 weeks (assume 2 week sprints). Would we then <em>only</em> select (check box) "Sprint 1" and "Sprint 2" from Release 1? Am I understanding/using it correctly?</p> <p><strong>Question 4)</strong> Team Backlog Iteration selection - This might be problematic due to our concept of having teams per client and not teams per product, but maybe I just understand it wrong. In TFS Areas setup, you specify which iterationis the "Backlog iteration for the team". My problem is that our PBI (Product Backlog Items) will be product specific and do not wish to mix them with PBIs from another product. So what I'm unable to understand yet is what the impact will be if we select area "Client A" as the "Backlog iteration for the team" instead of perhaps "Product B". I think I'm confusing myself here - what would be a sensible choice?</p> <p>The questions above stem my lack of understanding what the impact these selections for iterations, areas, team backlog iterations, and default areas will have for each TFS 2012 team defined. Some issues I'm having with this setup is for TFS to correctly identity the product backlog and sprint backlog for a team.</p> <p>I don't know whether have one team project and multiple areas for products (as is generally recommended) is complicating the issue.</p> <p><strong>Question 5)</strong> TFS Web Access website - For any given team under "WORK | work items | Shared Queries" there is predefined queries under a folder called "Current Sprint" (Blocked Tasks; Sprint Backlog; etc), but it seems that these queries are hardcoded against "Root Project\Release 1\Sprint 1" - should these not automatically discover which is the current sprint given the dates defined against iterations? If not, then what is the best practice for maintaining these queries?</p> <p>Do you know of some quality TFS 2012 and Scrum 2 specific training / tutorials that might help address these questions, or give some guidance for a successful Scrum 2 TFS setup?</p>
13,731,157
2
0
null
2012-11-30 04:12:50.737 UTC
16
2017-10-11 13:37:16.337 UTC
2017-10-11 13:37:16.337 UTC
null
1,000,551
null
351,511
null
1
26
tfs|scrum|backlog|sprint
29,826
<p>I hope you found use of my post, and I would also recommend that you take a look at <a href="http://blog.hinshelwood.com/one-team-project/" rel="noreferrer">One Team Project to rule them all</a> and <a href="http://blogs.msdn.com/b/greggboer/archive/2012/01/27/tfs-vnext-configuring-your-project-to-have-a-master-backlog-and-sub-teams.aspx" rel="noreferrer">TFS vNext: Configuring your project to have a master backlog and sub-teams</a>. </p> <p>Here is my best effort to answer your questions:</p> <blockquote> <blockquote> <p>Question 1) We figured that because our teams aren't that big and to make administration more manageable, that we didn't want to define teams per product since we physically have teams per client and they oversee all the products for that client. Is this a mistake, or is this OK?</p> </blockquote> </blockquote> <p>This is just fine and will allow you to grow as your teams do. If your team members work across multiple Clients you may run into prioritisation and context switching issues that you can minimise by pushing your team up a level, or having a single unified backlog and separate sub teams but still focusing on client work and not product work. I would indeed recommend this approach for the layout that you have.</p> <blockquote> <blockquote> <p>Question 2) Assuming that the above team configuration is OK, are we then correct to "map" each of the areas above to each team i.e. For team "Client A Team" specify area "Client A" (and all sub-areas) as the areas to be owned by that team. What about the default area, is it ok to set the root of the "Client A" area as the default for the team?</p> </blockquote> </blockquote> <p>That is indeed correct and should result in all of your work items being created when that team is selected with those defaults. Many organisations also create a parent or master backlog where misc items are created, ordered and then divided up into the appropriate team backlog as Greg Boer, Product Owner for the TFS Agile Planning Tools blogged about in his post <a href="http://blogs.msdn.com/b/greggboer/archive/2012/01/27/tfs-vnext-configuring-your-project-to-have-a-master-backlog-and-sub-teams.aspx" rel="noreferrer">TFS vNext: Configuring your project to have a master backlog and sub-teams</a>. </p> <p>You layout for iterations is indeed looking good as long as your Teams don’t cross the boundary between clients or you will start getting into difficultly mapping Areas and Iterations to Teams. If you think that you may need to have a single Team or group of teams map to more than one client then you may need something more like:</p> <pre><code>-&gt; Team Project (Iteration root) |—&gt; Team Boundary (This could be one or more teams) |--&gt; Client A (This is also out team boundary - ie. we have a TFS Team for Client A) |---&gt; Product A | |---&gt; Release 1 | |---&gt; Release 2 | |---&gt; Release 3 | |---&gt; Product B | |---&gt; Release 1 | |---&gt; Release 2 | | (ETC) |--&gt; Client B (This is also out team boundary - ie. we have another TFS Team for Client B) |---&gt; Product C | |---&gt; Release 1 | |---&gt; Release 2 | | (ETC) </code></pre> <p>While still not dynamic this would enable that scenario. I would however still retain my $\TeamProject\Client A\ProductA source control structure and not filter this down. It is simply a compartmentalisation of the planning process and should not nessesarily spill over into the other parts of your ALM Solution.</p> <blockquote> <blockquote> <p>Question 3) This seems to be trickier to get the iterations right, especially when it comes to TFS showing the backlog. Specifically, for the TFS Scrum 2 Iteration setup, it seems that I should be selecting (check box) only those leaf level iterations that are for planning and subsequent development. So extending the above example, we might have that the "Client A Team" will be available to start work on a new Product B for the next 4 weeks (assume 2 week sprints). Would we then only select (check box) "Sprint 1" and "Sprint 2" from Release 1? Am I understanding/using it correctly?</p> </blockquote> </blockquote> <p>You are, but you are really looking at 3 Sprints out to have an actionable backlog as part of the Scrum process. I would recommend sequentially numbering your sprints consecutively so that in the UI you will not get confused on Sprint 2 when you also tick Sprint 4 if it is called Sprint 1. It is also nice to keep a tally of the experience level of the current team.</p> <pre><code>-&gt; Team Project (Iteration root) |—&gt; Team Boundary (This could be one or more teams) |--&gt; Client A (This is also out team boundary - ie. we have a TFS Team for Client A) |---&gt; Product A | |---&gt; Release 1 | | |---&gt; Sprint 1 | | |---&gt; Sprint 2 | | |---&gt; Sprint 3 | |---&gt; Release 2 | | |---&gt; Sprint 4 | | |---&gt; Sprint 5 | | |---&gt; Sprint 6 | |---&gt; Release 3 | | |---&gt; Sprint 7 | | |---&gt; Sprint 8 | | |---&gt; Sprint 9 | | (ETC) </code></pre> <p>But you are fundamentally correct on the technical process involved and the result it will achieve.</p> <blockquote> <blockquote> <p>Question 4) Team Backlog Iteration selection - This might be problematic due to our concept of having teams per client and not teams per product, but maybe I just understand it wrong. In TFS Areas setup, you specify which iterations the "Backlog iteration for the team". My problem is that our PBI (Product Backlog Items) will be product specific and do not wish to mix them with PBIs from another product. So what I'm unable to understand yet is what the impact will be if we select area "Client A" as the "Backlog iteration for the team" instead of perhaps "Product B". I think I'm confusing myself here - what would be a sensible choice?</p> </blockquote> </blockquote> <p>You are not confusing yourself and the person entering something into the backlog of the team will need to change the default to be the iteration/area of the product that they want the change in. At least by default you are getting the correct Team and this should be an easy thing for either the person entering the item, the Product Owner or a Team Member to categories this correctly.</p> <p>Anything under the area that you specify as the Team Default is by default included in the items that you see. You can “right click” on your default Area for a team and de-select “Include sub-areas” so that you only see the top level and this is the technic that is used for Greg's Master Backlog. I would however suggest that you want to maintain a setting of “Include sub-areas” for visibility and transparency within your team.</p> <blockquote> <blockquote> <p>I don't know whether have one team project and multiple areas for products (as is generally recommended) is complicating the issue.</p> </blockquote> </blockquote> <p>It can. Some organisations prefer to add a drop-down list for “Team” to their work items (like the Conchango/EMC template) and use that as their team designation which can be configured in the Agile Planning Tools configuration as a default. That way you don’t need a Team designation in Area or Iteration if you are hitting up against that. I have no recommendation either way without more information of how your organisation is configured.</p> <blockquote> <blockquote> <p>Question 5) TFS Web Access website - For any given team under "WORK | work items | Shared Queries" there is predefined queries under a folder called "Current Sprint" (Blocked Tasks; Sprint Backlog; etc), but it seems that these queries are hardcoded against "Root Project\Release 1\Sprint 1" - should these not automatically discover which is the current sprint given the dates defined against iterations? If not, then what is the best practice for maintaining these queries?</p> </blockquote> </blockquote> <p>Option 1: Each Sprint spend the 2 minutes it takes to change the queries</p> <p>Option 2: Create a tool to do that for you</p> <p>Option 3: Have an additional “Current” iteration node within your Release and move the currently active iteration to below that node. Then set the queries to point to “Under” that “Client A\Product A \Release 1\Current”. Then it is quicker to change the nested iteration once and all the queries work. You then only need to change the Current but once per Release.</p> <blockquote> <blockquote> <p>Do you know of some quality TFS 2012 and Scrum 2 specific training / tutorials that might help address these questions, or give some guidance for a successful Scrum 2 TFS setup?</p> </blockquote> </blockquote> <p>I would recommend the Professional Scrum Developer training from Scrum.org or / and engaging with an ALM Consultant.</p>
13,566,688
How to integrate MEF with ASP.NET MVC 4 and ASP.NET Web API
<p>How does one integrate <a href="http://mef.codeplex.com/">Managed Extensibility Framework</a> (MEF) with ASP.NET MVC 4 and ASP.NET Web API in the same project?</p> <p>Consider an example application, with an MVC controller <code>HomeController</code> and a Web API controller <code>ContactController</code>. Both have a property of type <code>IContactRepository</code>, which they rely on MEF to resolve. The problem is how to plug MEF into MVC and Web API, so that instances are created via MEF.</p> <p><strong>HomeController:</strong></p> <pre><code>/// &lt;summary&gt; /// Home controller. Instruct MEF to create one instance of this class per importer, /// since this is what MVC expects. /// &lt;/summary&gt; [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class HomeController : Controller { [Import] private IContactRepository _contactRepository = null; public ActionResult Index() { return View(_contactRepository.GetAllContacts()); } } </code></pre> <p><strong>ContactController:</strong></p> <pre><code>/// &lt;summary&gt; /// Contact API controller. Instruct MEF to create one instance of this class per importer, /// since this is what Web API expects. /// &lt;/summary&gt; [Export] [PartCreationPolicy(CreationPolicy.NonShared)] public class ContactController : ApiController { [Import] private IContactRepository _contactRepo = null; public Contact[] Get() { return _contactRepo.GetAllContacts(); } } </code></pre> <p><strong>IContactRepository and ContactRepository:</strong></p> <pre><code>public interface IContactRepository { Contact[] GetAllContacts(); } [Export(typeof(IContactRepository))] public class ContactRepository : IContactRepository { public Contact[] GetAllContacts() { return new Contact[] { new Contact { Id = 1, Name = "Glenn Beck"}, new Contact { Id = 2, Name = "Bill O'Riley"} }; } } </code></pre> <p><strong>Contact:</strong></p> <pre><code>public class Contact { public int Id { get; set; } public string Name { get; set; } } </code></pre>
13,566,690
6
0
null
2012-11-26 14:17:57.07 UTC
13
2019-03-21 08:25:15.257 UTC
2014-01-19 23:27:06.123 UTC
null
749,172
null
265,261
null
1
29
asp.net-mvc|asp.net-mvc-4|asp.net-web-api|mef
20,200
<p>The solution is to implement <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.idependencyresolver%28v=vs.98%29.aspx">System.Web.Mvc.IDependencyResolver</a> and <a href="http://msdn.microsoft.com/en-us/library/system.web.http.dependencies.idependencyresolver%28v=vs.108%29.aspx">System.Web.Http.Dependencies.IDependencyResolver</a> and register your implementation with ASP.NET MVC and ASP.NET Web API respectively, in your <code>Application_Start</code> method.</p> <p>In this example we'll create a class <code>MefConfig</code>, which implements a method <code>RegisterMef</code> that gets called from <code>Application_Start</code> in order to install our dependency resolver. The class <code>MefDependencyResolver</code> implements both <code>System.Web.Mvc.IDependencyResolver</code> and <code>System.Web.Http.Dependencies.IDependencyResolver</code> and, as such, handles dependency resolution duties for both MVC and Web API.</p> <p><strong>Application_Start, Put This in Your Global.asax.cs:</strong></p> <pre><code>public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { [...] MefConfig.RegisterMef(); } } </code></pre> <p><strong>MefDependencyResolver and MefConfig:</strong></p> <pre><code>/// &lt;summary&gt; /// Resolve dependencies for MVC / Web API using MEF. /// &lt;/summary&gt; public class MefDependencyResolver : System.Web.Http.Dependencies.IDependencyResolver, System.Web.Mvc.IDependencyResolver { private readonly CompositionContainer _container; public MefDependencyResolver(CompositionContainer container) { _container = container; } public IDependencyScope BeginScope() { return this; } /// &lt;summary&gt; /// Called to request a service implementation. /// /// Here we call upon MEF to instantiate implementations of dependencies. /// &lt;/summary&gt; /// &lt;param name="serviceType"&gt;Type of service requested.&lt;/param&gt; /// &lt;returns&gt;Service implementation or null.&lt;/returns&gt; public object GetService(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); var name = AttributedModelServices.GetContractName(serviceType); var export = _container.GetExportedValueOrDefault&lt;object&gt;(name); return export; } /// &lt;summary&gt; /// Called to request service implementations. /// /// Here we call upon MEF to instantiate implementations of dependencies. /// &lt;/summary&gt; /// &lt;param name="serviceType"&gt;Type of service requested.&lt;/param&gt; /// &lt;returns&gt;Service implementations.&lt;/returns&gt; public IEnumerable&lt;object&gt; GetServices(Type serviceType) { if (serviceType == null) throw new ArgumentNullException("serviceType"); var exports = _container.GetExportedValues&lt;object&gt;(AttributedModelServices.GetContractName(serviceType)); return exports; } public void Dispose() { } } public static class MefConfig { public static void RegisterMef() { var asmCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); var container = new CompositionContainer(asmCatalog); var resolver = new MefDependencyResolver(container); // Install MEF dependency resolver for MVC DependencyResolver.SetResolver(resolver); // Install MEF dependency resolver for Web API System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = resolver; } } </code></pre>
13,626,756
How can I get onBackPressed() while SearchView is activated?
<p>How can I handle <code>onBackPressed()</code> at search mode? I have implemented the search at the <code>ActionBar</code>, and I want to handle <code>onBackPressed()</code>.</p> <h2>Edit:</h2> <p>At <code>MainActivity</code> I have added this, but it only gets notified when search is closed</p> <pre><code>@Override public void onBackPressed() { mMenu.findItem(R.id.menu_eye).setVisible(true); mMenu.findItem(R.id.menu_layers).setVisible(true); super.onBackPressed(); }; </code></pre> <p>and my listener for search action looks like this:</p> <pre><code>import com.cyrilmottier.polaris.PolarisMapView; import android.app.SearchManager.OnCancelListener; import android.content.Context; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.SearchView; public class SearchListener implements SearchView.OnQueryTextListener, SearchView.OnCloseListener, SearchView.OnSuggestionListener, OnClickListener, OnCancelListener{ private Context mContext; private PolarisMapView mMapView; private Menu mMenu; private SearchView mSearchView; public SearchListener(Context c, PolarisMapView mMapView, Menu mMenu, SearchView mSearchView){ this.setmContext(c); this.setmMapView(mMapView); this.setmMenu(mMenu); this.mSearchView = mSearchView; } @Override public boolean onQueryTextChange(String newText) { return false; } @Override public boolean onQueryTextSubmit(String query) { if (Constants.searchPlaceNavigate(query, mContext, mMapView)) return this.onClose(); return false; } public Context getmContext() { return mContext; } public void setmContext(Context mContext) { this.mContext = mContext; } public PolarisMapView getmMapView() { return mMapView; } public void setmMapView(PolarisMapView mMapView) { this.mMapView = mMapView; } @Override public boolean onSuggestionClick(int position) { String p = mSearchView.getSuggestionsAdapter().getCursor().getString(position); if(position== 0) p = mSearchView.getSuggestionsAdapter().getCursor().getString(position*4+1); if(p != null) if(position== 0) Constants.searchPlaceNavigate(mSearchView.getSuggestionsAdapter().getCursor().getString(position*4+1), mContext, mMapView); else Constants.searchPlaceNavigate(mSearchView.getSuggestionsAdapter().getCursor().getString(position), mContext, mMapView); return this.onClose(); } @Override public boolean onSuggestionSelect(int position) { return false; } @Override public boolean onClose() { mMenu.findItem(R.id.menu_eye).setVisible(true); mMenu.findItem(R.id.menu_layers).setVisible(true); mMenu.findItem(R.id.menu_search).collapseActionView(); return true; } public Menu getmMenu() { return mMenu; } public void setmMenu(Menu mMenu) { this.mMenu = mMenu; } public SearchView getmSearchView() { return mSearchView; } public void setmSearchView(SearchView mSearchView) { this.mSearchView = mSearchView; } @Override public void onClick(View v) { this.onClose(); } @Override public void onCancel() { this.onClose(); } } </code></pre>
22,730,635
9
1
null
2012-11-29 13:19:26.193 UTC
3
2021-08-06 14:42:32.66 UTC
2014-08-06 06:18:14.42 UTC
null
1,276,636
null
573,925
null
1
30
android|searchview
19,400
<p>another way is to listen on the MenuItem for the ActionExpand/Collapse :</p> <pre><code> MenuItem searchMenuItem = menu.findItem(R.id.menu_search); searchMenuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() { @Override public boolean onMenuItemActionExpand(MenuItem item) { // Do whatever you need return true; // KEEP IT TO TRUE OR IT DOESN'T OPEN !! } @Override public boolean onMenuItemActionCollapse(MenuItem item) { // Do whatever you need return true; // OR FALSE IF YOU DIDN'T WANT IT TO CLOSE! } }); SearchView searchView = (SearchView) searchMenuItem.getActionView(); ... // Keep doing as you do </code></pre> <p>I think this way is cleaner, as you listen directly on what you want</p> <p>Thanks to <a href="https://groups.google.com/d/msg/actionbarsherlock/l6Xp4UTx5kQ/f8Ly1rgJuGcJ" rel="noreferrer">this thread</a></p>
39,510,821
How to remove all element from array except the first one in javascript
<p>I want to remove all element from array except the element of array at 0th index</p> <pre><code>["a", "b", "c", "d", "e", "f"] </code></pre> <p>Output should be <code>a</code></p>
39,510,882
8
6
null
2016-09-15 12:17:01.903 UTC
4
2020-05-15 08:04:24.377 UTC
2016-09-15 12:27:13.45 UTC
null
5,104,748
null
6,734,038
null
1
34
javascript|arrays|slice|array-splice
64,039
<p>You can set the <code>length</code> property of the array.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var input = ['a','b','c','d','e','f']; input.length = 1; console.log(input);</code></pre> </div> </div> </p> <p>OR, Use <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" rel="noreferrer"><code>splice(startIndex)</code></a> method</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var input = ['a','b','c','d','e','f']; input.splice(1); console.log(input);</code></pre> </div> </div> </p> <p>OR use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice" rel="noreferrer">Array.slice</a> method</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var input = ['a','b','c','d','e','f']; var output = input.slice(0, 1) // 0-startIndex, 1 - endIndex console.log(output); </code></pre> </div> </div> </p>
3,922,628
Jquery Validation: Call Valid without displaying errors?
<p>Using JQuery Validation plugin, I am trying to call the .valid() method without the side-effects of displaying error messages on screen. I have tried a number of scenarios with no success, my latest being:</p> <pre><code>$('#signup').validate({ showErrors: function() { return; }, errorElement: "", errorClass: "", errorPlacement: function() { }, invalidHandler: function() { }, highlight: function(element, errorClass) { }, unhighlight: function(element, errorClass) { } }); $('#displayPurposes').text("Valid: " + $("#EMailAddress_EmailAddress").valid()); </code></pre> <p>Whilst the .valid() call is working correctly it is still causing side-effects of displaying error messages.</p> <p>I don't want this to happen, help please.</p>
8,049,157
2
0
null
2010-10-13 10:18:16.257 UTC
9
2018-01-24 19:03:10.207 UTC
2018-01-24 19:03:10.207 UTC
null
594,235
null
193,127
null
1
21
jquery|jquery-validate
10,932
<p>Well instead of trying to disable any error placement made by the plugin you could use CSS to 'force' hiding the create error messages elements. Something like:</p> <pre><code>label.myvalidationclass { display: none !important; } </code></pre> <p>Where <code>myvalidationclass</code> is either the default error class name or your own.</p> <p>I'm aware it is not a very nice solution but in my opinion, displaying error messages is one of the core feature of the plugin.</p> <p>d.</p>
3,921,736
Parsing json into java objects in spring-mvc
<p>I'm familiar with how to return json from my <code>@Controller</code> methods using the <code>@ResponseBody</code> annotation.</p> <p>Now I'm trying to read some json arguments into my controller, but haven't had luck so far. Here's my controller's signature:</p> <pre><code>@RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestParam("json") @RequestBody SearchRequest json) { </code></pre> <p>But when I try to invoke this method, spring complains that: <code>Failed to convert value of type 'java.lang.String' to required type 'com.foo.SearchRequest'</code></p> <p>Removing the <code>@RequestBody</code> annotation doesn't seem to make a difference.</p> <p>Manually parsing the json works, so Jackson must be in the classpath:</p> <pre><code>// This works @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestParam("json") String json) { SearchRequest request; try { request = objectMapper.readValue(json, SearchRequest.class); } catch (IOException e) { throw new IllegalArgumentException("Couldn't parse json into a search request", e); } </code></pre> <p>Any ideas? Am I trying to do something that's not supported?</p>
3,921,780
2
0
null
2010-10-13 07:59:19.587 UTC
15
2012-08-12 13:40:02.81 UTC
null
null
null
null
372,860
null
1
30
java|json|spring-mvc|jackson
63,294
<p>Your parameter should either be a <code>@RequestParam</code>, <em>or</em> a <code>@RequestBody</code>, not both. </p> <p><code>@RequestBody</code> is for use with POST and PUT requests, where the body of the request is what you want to parse. <code>@RequestParam</code> is for named parameters, either on the URL or as a multipart form submission.</p> <p>So you need to decide which one you need. Do you really want to have your JSON as a request parameter? This isn't normally how AJAX works, it's normally sent as the request body.</p> <p>Try removing the <code>@RequestParam</code> and see if that works. If not, and you really are posting the JSON as a request parameter, then Spring won't help you process that without additional plumbing (see <a href="http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-webdatabinder" rel="noreferrer">Customizing WebDataBinder initialization</a>).</p>
45,532,808
Why does GCC move variables to a temporary location before assigning them?
<p>When looking at some decompiled C code I saw this:</p> <pre><code>movl -0xc(%rbp), %esi movl %esi, -0x8(%rbp) </code></pre> <p>This corresponds to this C code:</p> <pre><code>x = y; </code></pre> <p>This got me thinking: how come gcc moves <code>y</code> to <code>%esi</code> and then move <code>%esi</code> to <code>x</code> instead of just moving <code>y</code> to <code>x</code> directly?</p> <hr> <p>This is the entire C and decompiled code, if it matters:</p> <h2>C</h2> <pre><code>int main(void) { int x, y, z; while(1) { x = 0; y = 1; do { printf("%d\n", x); z = x + y; x = y; y = z; } while(x &lt; 255); } } </code></pre> <h2>Decompiled</h2> <pre><code>pushq %rbp movq %rsp, %rbp subq $0x20, %rsp movl $0x0, -0x4(%rbp) movl $0x0, -0x8(%rbp) ; x = 0 movl $0x1, -0xc(%rbp) ; y = 1 ; printf leaq 0x56(%rip), %rdi movl -0x8(%rbp), %esi movb $0x0, %al callq 0x100000f78 ; z = x + y movl -0x8(%rbp), %esi ; x -&gt; esi addl -0xc(%rbp), %esi ; y + esi movl %esi, -0x10(%rbp) ; z = esi ; x = y movl -0xc(%rbp), %esi movl %esi, -0x8(%rbp) ; y = z movl -0x10(%rbp), %esi movl %esi, -0xc(%rbp) movl %eax, -0x14(%rbp) ; not sure... I believe printf return value? cmpl $0xff, -0x8(%rbp) ; x &lt; 255 jl 0x100000f3d ; do...while(x &lt; 255) jmp 0x100000f2f ; while(1) </code></pre>
45,532,844
1
13
null
2017-08-06 14:05:58.75 UTC
3
2017-08-08 07:29:52.213 UTC
2017-08-08 07:29:52.213 UTC
null
5,615,635
null
5,615,635
null
1
37
c|assembly|x86|decompiling
3,164
<p>Most x86 instructions (other than some specialized instructions such as <code>movsb</code>) can only access one memory location. Therefore a move from memory to memory requires going through a register with two <code>mov</code> instructions.</p> <p>The <code>mov</code> instruction can be used in the following ways:</p> <pre><code>mov mem, reg mov reg, mem mov reg, reg mov reg, imm mov mem, imm </code></pre> <p>There is no <code>mov mem, mem</code>.</p> <p>Note that if you had compiled with optimizations, the variables would be placed in registers so this wouldn't be an issue.</p>
9,472,488
Differences between Agda and Idris
<p>I'm starting to dive into dependently-typed programming and have found that the Agda and Idris languages are the closest to Haskell, so I started there.</p> <p>My question is: which are the main differences between them? Are the type systems equally expresive in both of them? It would be great to have a comprehensive comparative and a discussion about benefits.</p> <p>I've been able to spot some:</p> <ul> <li>Idris has type classes à la Haskell, whereas Agda goes with instance arguments</li> <li>Idris includes monadic and applicative notation</li> <li>Both of them seem to have some sort of rebindable syntax, although not really sure if they are the same.</li> </ul> <hr> <p><em>Edit</em>: there are some more answers in the Reddit page of this question: <a href="http://www.reddit.com/r/dependent_types/comments/q8n2q/agda_vs_idris/" rel="noreferrer">http://www.reddit.com/r/dependent_types/comments/q8n2q/agda_vs_idris/</a></p>
9,474,117
2
2
null
2012-02-27 21:22:39.75 UTC
65
2022-06-29 12:19:40.323 UTC
2017-08-02 11:25:36.43 UTC
null
3,924,118
null
1,236,540
null
1
184
agda|type-theory|idris
24,570
<p>I may not be the best person to answer this, as having implemented Idris I'm probably a bit biased! The FAQ - <a href="http://docs.idris-lang.org/en/latest/faq/faq.html" rel="nofollow noreferrer">http://docs.idris-lang.org/en/latest/faq/faq.html</a> - has something to say on it, but to expand on that a bit:</p> <p>Idris has been designed from the ground up to support general purpose programming ahead of theorem proving, and as such has high level features such as type classes, do notation, idiom brackets, list comprehensions, overloading and so on. Idris puts high level programming ahead of interactive proof, although because Idris is built on a tactic-based elaborator, there is an interface to a tactic based interactive theorem prover (a bit like Coq, but not as advanced, at least not yet).</p> <p>Another thing Idris aims to support well is Embedded DSL implementation. With Haskell you can get a long way with do notation, and you can with Idris too, but you can also rebind other constructs such as application and variable binding if you need to. You can find more details on this in the tutorial, or full details in this paper: <a href="http://eb.host.cs.st-andrews.ac.uk/drafts/dsl-idris.pdf" rel="nofollow noreferrer">http://eb.host.cs.st-andrews.ac.uk/drafts/dsl-idris.pdf</a></p> <p>Another difference is in compilation. Agda goes primarily via Haskell, Idris via C. There is an experimental back end for Agda which uses the same back end as Idris, via C. I don't know how well maintained it is. A primary goal of Idris will always be to generate efficient code - we can do a lot better than we currently do, but we're working on it.</p> <p>The type systems in Agda and Idris are pretty similar in many important respects. I think the main difference is in the handling of universes. Agda has universe polymorphism, Idris has <a href="https://ncatlab.org/nlab/show/type+universe#cumulativity" rel="nofollow noreferrer">cumulativity</a> (and you can have <code>Set : Set</code> in both if you find this too restrictive and don't mind that your proofs might be unsound).</p>
16,547,996
how to automatically restart a node server?
<p>We are finishing development of a project, the client is already using it but occasionally some errors occur - crashing the server.</p> <p>I know I could register a service as 'upstart' script on linux, in order to have my node service restart when it crashes. </p> <p>But our server is running other stuff, so we can't restart it. Well, actually, while writing, I realize I have two questions then:</p> <ul> <li>Will 'upstart' work without having to reboot? Something is just whispering yes to me :)</li> <li>If not, what other option would I have to 'respawn' my node server when it crashes?</li> </ul>
16,548,045
4
0
null
2013-05-14 16:12:34.45 UTC
3
2022-07-06 17:11:29.913 UTC
2021-10-10 04:57:00.127 UTC
null
7,446,770
null
169,252
null
1
40
node.js|server|restart|upstart
76,817
<p>Yes, upstart will restart your process without a reboot.</p> <p>Also, you should look into <a href="https://npmjs.org/package/forever" rel="noreferrer">forever</a>.</p>
16,481,379
How can I delete using INNER JOIN with SQL Server?
<p>I want to <strong>delete</strong> using <code>INNER JOIN</code> in <strong>SQL Server 2008</strong>.</p> <p>But I get this error:</p> <blockquote> <p>Msg 156, Level 15, State 1, Line 15<br /> <strong>Incorrect</strong> syntax near the <strong>keyword</strong> 'INNER'.</p> </blockquote> <p>My code:</p> <pre><code>DELETE FROM WorkRecord2 INNER JOIN Employee ON EmployeeRun=EmployeeNo WHERE Company = '1' AND Date = '2013-05-06' </code></pre>
16,481,475
14
3
null
2013-05-10 11:38:21.043 UTC
222
2021-10-03 14:07:39.16 UTC
2021-10-02 07:17:40.507 UTC
null
16,364,625
null
1,556,907
null
1
1,629
sql|sql-server|sql-server-2008|inner-join|sql-delete
1,916,686
<p>You need to specify what table you are deleting from. Here is a version with an alias:</p> <pre><code>DELETE w FROM WorkRecord2 w INNER JOIN Employee e ON EmployeeRun=EmployeeNo WHERE Company = '1' AND Date = '2013-05-06' </code></pre>
16,232,833
How to respond with an HTTP 400 error in a Spring MVC @ResponseBody method returning String
<p>I'm using Spring MVC for a simple JSON API, with <code>@ResponseBody</code> based approach like the following. (I already have a service layer producing JSON directly.)</p> <pre><code>@RequestMapping(value = &quot;/matches/{matchId}&quot;, produces = &quot;application/json&quot;) @ResponseBody public String match(@PathVariable String matchId) { String json = matchService.getMatchJson(matchId); if (json == null) { // TODO: how to respond with e.g. 400 &quot;bad request&quot;? } return json; } </code></pre> <p>In the given scenario, what is the simplest, cleanest way to respond with a HTTP 400 error?</p> <p>I did come across approaches like:</p> <pre><code>return new ResponseEntity(HttpStatus.BAD_REQUEST); </code></pre> <p>...but I can't use it here since my method's return type is String, not ResponseEntity.</p>
16,250,729
13
0
null
2013-04-26 09:16:16.04 UTC
117
2022-07-06 15:22:38.823 UTC
2022-06-19 12:03:31.273 UTC
null
63,550
null
56,285
null
1
445
java|spring|spring-mvc|http-error
484,080
<p>Change your return type to <code>ResponseEntity&lt;&gt;</code>, and then you can use the below for 400:</p> <pre class="lang-java prettyprint-override"><code>return new ResponseEntity&lt;&gt;(HttpStatus.BAD_REQUEST); </code></pre> <p>And for a correct request:</p> <pre><code>return new ResponseEntity&lt;&gt;(json,HttpStatus.OK); </code></pre> <p>After Spring 4.1 there are helper methods in ResponseEntity which could be used as:</p> <pre><code>return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null); </code></pre> <p>and</p> <pre><code>return ResponseEntity.ok(json); </code></pre>
17,645,620
ng-selected not working in select element
<p>I have a bound select </p> <pre><code>&lt;select ng-model="collegeSelection" ng-options="c as c.CollegeName for c in colleges" ng-selected="c.CollegeName == collegeSelection.CollegeName" name="selectCollege" id="selectCollege"&gt;&lt;/select&gt; </code></pre> <p>but when both c.CollegeName == collegeSelection.CollegeName match the item still isn't selected. Documentation doesn't seem to help. Any ideas? </p>
17,646,636
4
0
null
2013-07-15 01:45:12.977 UTC
2
2017-12-29 21:30:29.303 UTC
null
null
null
null
256,357
null
1
7
javascript|angularjs|angularjs-directive
46,528
<p><code>ng-selected</code> should be used in the <code>&lt;option&gt;</code> tag, not in the <code>&lt;select&gt;</code> tag. Take a closer look at its <a href="http://docs.angularjs.org/api/ng.directive:ngSelected" rel="noreferrer">doc</a> and the example.</p> <p>Because the <code>select</code> directive's determination of the selected option is based on <code>ngModel</code>. Therefore, once you remove <code>ng-selected="c.CollegeName == collegeSelection.CollegeName"</code>, your code should work.</p> <p>I created a very simple <a href="http://plnkr.co/edit/cmAe0QWODQys1PQYaKGv" rel="noreferrer">plunk</a> to demonstrate the "selected" feature in <code>select</code> directive.</p> <h2>More details:</h2> <p>AngularJS uses <code>ngModel</code> directive to enable "two-way data binding" between your model and UI elements.</p> <p>In the case of "select", the model <code>collegeSelection</code> you specified as <code>&lt;select ng-model="collegeSelection" ...&gt;</code> is the <em>selected</em> item. Which means if an user selects an item from the dropdown on the page, <code>collegeSelection</code> will be set to that item; <strong>and</strong>, if you set <code>collegeSelection</code> to an item in your javascript code, AngularJS will make sure that the corresponded <code>&lt;option&gt;</code> is selected.</p> <p>Say you have the following code in your controller:</p> <pre><code>$scope.colleges = [ {id: 0, name: 'a'}, {id: 1, name: 'b'}, {id: 2, name: 'c'} ]; $scope.collegeSelection = $scope.colleges[0]; </code></pre> <p>And the HTML looks like:</p> <pre><code>&lt;select ng-model="collegeSelection" ng-options="c as c.name for c in colleges"&gt;&lt;/select&gt; </code></pre> <p>That's it! The first college in the colleges array <em>will be selected</em> if you run the code.</p> <p>Just remember <code>collegeSelection</code> <strong>is</strong> the selected option, no matter it's because user selected an item on the UI, or you selected an item in javascript.</p> <p>That's how two-way data binding works.</p>
27,084,617
Detect strings with non English characters in Python
<p>I have some strings that have a mix of English and none English letters. For example:</p> <pre><code>w='_1991_اف_جي2' </code></pre> <p>How can I recognize these types of string using Regex or any other fast method in Python?</p> <p>I prefer not to compare letters of the string one by one with a list of letters, but to do this in one shot and quickly.</p>
27,084,708
6
4
null
2014-11-23 01:31:48.267 UTC
17
2020-03-14 21:35:41.5 UTC
2014-11-23 01:53:25.127 UTC
null
1,090,562
null
755,000
null
1
61
python|regex|non-english
74,138
<p>You can just check whether the string can be encoded only with ASCII characters (which are Latin alphabet + some other characters). If it can not be encoded, then it has the characters from some other alphabet.</p> <p>Note the comment <code># -*- coding: ....</code>. It should be there at the top of the python file (otherwise you would receive some error about encoding)</p> <pre><code># -*- coding: utf-8 -*- def isEnglish(s): try: s.encode(encoding='utf-8').decode('ascii') except UnicodeDecodeError: return False else: return True assert not isEnglish('slabiky, ale liší se podle významu') assert isEnglish('English') assert not isEnglish('ގެ ފުރަތަމަ ދެ އަކުރު ކަ') assert not isEnglish('how about this one : 通 asfަ') assert isEnglish('?fd4))45s&amp;') </code></pre>
17,174,707
Can model views in Flask-Admin hyperlink to other model views?
<p>Let's suppose we have a model, <code>Foo</code>, that references another model, <code>User</code> - and there are Flask-Admin's <code>ModelView</code> for both.</p> <p>On the <code>Foo</code> admin view page</p> <p><a href="https://i.stack.imgur.com/uNwrP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uNwrP.png" alt="enter image description here" /></a></p> <p>I would like the entries in the <code>User</code> column to be linked to the corresponding <code>User</code> model view.</p> <p>Do I need to modify one of Flask-Admin's templates to achieve this?</p> <p>(This is possible in the Django admin interface by simply outputting HTML for a given field and setting <code>allow_tags</code> <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.list_display" rel="nofollow noreferrer">(ref)</a> True to bypass Django's HTML tag filter)</p>
17,184,281
4
0
null
2013-06-18 16:59:30.787 UTC
13
2022-08-10 15:42:08.39 UTC
2022-08-10 15:42:08.39 UTC
null
3,705,840
null
167,806
null
1
24
python|flask
7,851
<p>Use <code>column_formatters</code> for this: <a href="https://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.column_formatters" rel="noreferrer">https://flask-admin.readthedocs.org/en/latest/api/mod_model/#flask.ext.admin.model.BaseModelView.column_formatters</a></p> <p>Idea is pretty simple: for a field that you want to display as hyperlink, either generate a HTML string and wrap it with Jinja2 <code>Markup</code> class (so it won't be escaped in templates) or use <code>macro</code> helper: <a href="https://github.com/mrjoes/flask-admin/blob/master/flask_admin/model/template.py" rel="noreferrer">https://github.com/mrjoes/flask-admin/blob/master/flask_admin/model/template.py</a></p> <p>Macro helper allows you to use custom Jinja2 macros in overridden template, which moves presentational logic to templates.</p> <p>As far as URL is concerned, all you need is to find endpoint name generated (or provided) for the <code>User</code> model and do <code>url_for('userview.edit_view', id=model.id)</code> to generate the link.</p>
17,190,755
Why sbt runs dependency resolution every time after clean?
<p>SBT runs dependency resolution every time after <code>clean</code> even if project dependency management configuration hasn't changed. This is time consuming when running on CI server.</p> <p>But documentation <a href="http://www.scala-sbt.org/0.12.3/docs/Detailed-Topics/Dependency-Management-Flow.html" rel="noreferrer">says</a>:</p> <blockquote> <ol> <li>Normally, if no dependency management configuration has changed since the last successful resolution and the retrieved files are still present, sbt does not ask Ivy to perform resolution.</li> </ol> </blockquote> <p>How can I stop sbt from doing dependency resolution every time I build project with <code>sbt clean publish-local</code> ?</p> <p><strong>Update</strong></p> <p>I've discovered that sbt also runs resolution when I enter in interactive mode with <code>sbt</code>.</p> <p><strong>Update2</strong></p> <p>As <code>@Ezhik</code> pointed if I can preserve <code>target/resolution-cache</code> then sbt will not resolve dependencies after clean. So I tried to move <code>resolution-cache</code> out from target dir:</p> <pre><code>ivyConfiguration &lt;&lt;= (externalResolvers, ivyPaths, offline, checksums, appConfiguration, target, streams) map { (rs, paths, off, check, app, t, s) =&gt; val resCacheDir = t / ".." / "resolution-cache" new InlineIvyConfiguration(paths, rs, Nil, Nil, off, Option(lock(app)), check, Some(resCacheDir), s.log) } </code></pre> <p>Now with this code in <code>Build.scala</code> resolution cache is placed in project root and is therefore preserved after <code>clean</code>, but resolution is being done anyway. So I assume this approach is wrong or insufficient.</p>
17,207,597
4
0
null
2013-06-19 12:06:11.827 UTC
11
2014-03-24 04:39:06.217 UTC
2013-06-20 08:45:49.513 UTC
null
1,743,253
null
1,743,253
null
1
25
scala|sbt|ivy
8,574
<p>Because of directory <code>target/resolution-cache</code> that contains Ivy reports. It is obviously that you remove all <code>target</code> content while <code>clean</code> operation.</p> <p>IMHO You must point it in your project to somewhere out from <code>target</code> if you want to preserve resolution state.</p> <p><em>Updated.</em></p> <p>vs SBT.0.12.4.RC1</p> <ol> <li>Find where <code>resolution-cache</code> is used - in IvyConfiguration</li> <li><p>Inspect where IvyConfiguration located - in project scope</p> <pre><code>&gt; inspect ivy-configuration [info] Task: sbt.IvyConfiguration [info] Description: [info] General dependency management (Ivy) settings, such as the resolvers and paths to use. [info] Provided by: [info] {file:/home/ezh/projects/sbt/}xsbt/*:ivy-configuration [info] Dependencies: [info] xsbt/*:offline </code></pre></li> <li><p>Fix it in build.sbt.</p> <pre><code>ivyConfiguration &lt;&lt;= (ivyConfiguration, baseDirectory) map { case (c: InlineIvyConfiguration, b) =&gt; import c._ new InlineIvyConfiguration(paths, resolvers, otherResolvers, moduleConfigurations, localOnly, lock, checksums, resolutionCacheDir.map(_ =&gt; b / "123"), log) case (other, _) =&gt; other // something unknown } </code></pre></li> </ol> <p>4 Test... Ups... resolution is still active... Investigate. -></p> <p><code>target/scala-2.10/cache/default-920e5d/global/update/output</code> cache contain pointers to <code>resolution-cache</code> :)</p> <ol> <li><p>Fix it.</p> <pre><code>cacheDirectory &lt;&lt;= baseDirectory / "234" </code></pre></li> </ol> <p>Test. Got it. Resolution is skipped.</p> <p>Summary changes for required configuration:</p> <pre><code>ivyConfiguration &lt;&lt;= (ivyConfiguration, baseDirectory) map { case (c: InlineIvyConfiguration, b) =&gt; import c._ new InlineIvyConfiguration(paths, resolvers, otherResolvers, moduleConfigurations, localOnly, lock, checksums, resolutionCacheDir.map(_ =&gt; b / "123"), log) case (other, _) =&gt; other // something unknown } cacheDirectory &lt;&lt;= baseDirectory / "234" </code></pre> <hr> <p>vs SBT.0.13.x</p> <pre><code>@deprecated("Use the cacheDirectory provided by streams.", "0.13.0") </code></pre> <p><a href="https://github.com/sbt/sbt/issues/1208">https://github.com/sbt/sbt/issues/1208</a></p>
5,242,866
how to loop 7 times in the django templates
<p>this is my code :</p> <pre><code>{% for i in range(7)%} &lt;option value={{i+1}}&gt; {{i+1}}&lt;/option&gt; {% endfor %} </code></pre> <p>but it show error ,</p> <p>what can i do ,</p> <p>thanks</p>
5,243,044
3
1
null
2011-03-09 07:57:46.25 UTC
6
2015-05-21 18:55:52.657 UTC
null
null
null
null
420,840
null
1
20
django|templates
44,500
<p>views.py:</p> <pre><code>context['loop_times'] = range(1, 8) </code></pre> <p>html:</p> <pre><code>{% for i in loop_times %} &lt;option value={{ i }}&gt;{{ i }}&lt;/option&gt; {% endfor %} </code></pre>
43,198,273
Which files in .idea folder should be tracked by Git?
<p>Unlike Netbeans, in Jetbrains IDEs, the setting files related to user and team are mixed in the same folder that makes it tricky when you need to push them to git.</p> <p>There is a number of sample git ignore files for these IDEs and <a href="https://intellij-support.jetbrains.com/hc/articles/206544839" rel="noreferrer">https://intellij-support.jetbrains.com/hc/articles/206544839</a> page on git site.</p> <p>However, after using them for a months we figure out that it is safer and actually more convenient to do the reverse. I mean ignoring all <code>.idea</code> files and adding only team-related settings explicitly. (instead of adding all and ignoring some).</p> <p>The main thing that can be shared among developers is code style configs. So, by using IDE auto-reformatting option all the team will follow a consistent style.</p> <p>Besides that, the question is which other files are recommended to be included and not ignored? Why?</p> <p>Answer: I came across with this: <a href="https://github.com/salarmehr/idea-gitignore" rel="noreferrer">https://github.com/salarmehr/idea-gitignore</a></p>
44,690,814
5
6
null
2017-04-04 04:29:33.637 UTC
11
2021-09-22 03:12:59.303 UTC
2020-07-18 04:46:56.933 UTC
null
1,383,227
null
752,603
null
1
66
git|intellij-idea|phpstorm|ignore
26,192
<p>After some investigation, I came up with <a href="https://github.com/salarmehr/idea-gitignore" rel="nofollow noreferrer">https://github.com/salarmehr/idea-gitignore</a></p> <pre><code>#### ignore all .idea files ... * #### except # Version Control configuration for your project !vcs.xml # how IDEA should treat the text files in your project !encodings.xml # automatic code formatting !codeStyleSettings.xml # project specific words !dictionaries !copyrights !misc.xml !sqldialects.xml </code></pre> <p>Above files should practically be identical for all team members.</p>
61,655,199
Proper way to use react-hook-form Controller with Material-UI Autocomplete
<p>I am trying to use a custom <code>Material-UI Autocomplete</code> component and connect it to <code>react-hook-form</code>.</p> <blockquote> <p>TLDR: Need to use MUI Autocomplete with react-hook-form Controller without <code>defaultValue</code></p> </blockquote> <p>My custom <code>Autocomplete</code> component takes an object with the structure <code>{_id:'', name: ''}</code> it displays the name and returns the <code>_id</code> when an option is selected. The <code>Autocomplete</code> works just fine. </p> <pre class="lang-js prettyprint-override"><code>&lt;Autocomplete options={options} getOptionLabel={option =&gt; option.name} getOptionSelected={(option, value) =&gt; option._id === value._id} onChange={(event, newValue, reason) =&gt; { handler(name, reason === 'clear' ? null : newValue._id); }} renderInput={params =&gt; &lt;TextField {...params} {...inputProps} /&gt;} /&gt; </code></pre> <p>In order to make it work with <code>react-hook-form</code> I've set the <code>setValues</code> to be the handler for <code>onChange</code> in the <code>Autocomplete</code> and manually register the component in an <code>useEffect</code> as follows</p> <pre class="lang-js prettyprint-override"><code>useEffect(() =&gt; { register({ name: "country1" }); },[]); </code></pre> <p>This works fine but I would like to not have the <code>useEffect</code> hook and just make use of the register somehow directly. </p> <p>Next I tried to use the <code>Controller</code> component from <code>react-hook-form</code> to proper register the field in the form and not to use the <code>useEffect</code> hook </p> <pre class="lang-js prettyprint-override"><code>&lt;Controller name="country2" as={ &lt;Autocomplete options={options} getOptionLabel={option =&gt; option.name} getOptionSelected={(option, value) =&gt; option._id === value._id} onChange={(event, newValue, reason) =&gt; reason === "clear" ? null : newValue._id } renderInput={params =&gt; ( &lt;TextField {...params} label="Country" /&gt; )} /&gt; } control={control} /&gt; </code></pre> <p>I've changed the <code>onChange</code> in the <code>Autocomplete</code> component to return the value directly but it doesn't seem to work. </p> <p>Using <code>inputRef={register}</code> on the <code>&lt;TextField/&gt;</code> would not cut it for me because I want to save the <code>_id</code> and not the <code>name</code></p> <p><a href="http://codesandbox.io/s/vigilant-feather-6nvf6" rel="noreferrer">HERE</a> is a working sandbox with the two cases. The first with <code>useEffect</code> and <code>setValue</code> in the <code>Autocomplete</code> that works. The second my attempt in using <code>Controller</code> component</p> <p>Any help is appreciated.</p> <blockquote> <p>LE</p> </blockquote> <p>After the comment from Bill with the working sandbox of MUI Autocomplete, I Managed to get a functional result</p> <pre class="lang-js prettyprint-override"><code>&lt;Controller name="country" as={ &lt;Autocomplete options={options} getOptionLabel={option =&gt; option.name} getOptionSelected={(option, value) =&gt; option._id === value._id} renderInput={params =&gt; &lt;TextField {...params} label="Country" /&gt;} /&gt; } onChange={([, { _id }]) =&gt; _id} control={control} /&gt; </code></pre> <p>The only problem is that I get an <code>MUI Error</code> in the console </p> <p><em>Material-UI: A component is changing the uncontrolled value state of Autocomplete to be controlled.</em></p> <p>I've tried to set an <code>defaultValue</code> for it but it still behaves like that. Also I would not want to set a default value from the options array due to the fact that these fields in the form are not required.</p> <p>The updated sandbox <a href="http://codesandbox.io/s/wizardly-platform-i7fwc" rel="noreferrer">HERE</a></p> <p>Any help is still very much appreciated</p>
61,721,952
6
4
null
2020-05-07 10:10:47.75 UTC
6
2022-09-07 10:37:28.617 UTC
2020-05-11 07:39:53.703 UTC
null
4,440,646
null
4,440,646
null
1
32
reactjs|material-ui|react-hook-form
43,283
<p>So, I fixed this. But it revealed what I believe to be an error in Autocomplete.</p> <p>First... specifically to your issue, you can eliminate the <code>MUI Error</code> by adding a <em>defaultValue</em> to the <code>&lt;Controller&gt;</code>. But that was only the beginning of another round or problems.</p> <p>The problem is that functions for <code>getOptionLabel</code>, <code>getOptionSelected</code>, and <code>onChange</code> are sometimes passed the value (i.e. the <code>_id</code> in this case) and sometimes passed the option structure - as you would expect.</p> <p>Here's the code I finally came up with:</p> <pre><code>import React from "react"; import { useForm, Controller } from "react-hook-form"; import { TextField } from "@material-ui/core"; import { Autocomplete } from "@material-ui/lab"; import { Button } from "@material-ui/core"; export default function FormTwo({ options }) { const { register, handleSubmit, control } = useForm(); const getOpObj = option =&gt; { if (!option._id) option = options.find(op =&gt; op._id === option); return option; }; return ( &lt;form onSubmit={handleSubmit(data =&gt; console.log(data))}&gt; &lt;Controller name="country" as={ &lt;Autocomplete options={options} getOptionLabel={option =&gt; getOpObj(option).name} getOptionSelected={(option, value) =&gt; { return option._id === getOpObj(value)._id; }} renderInput={params =&gt; &lt;TextField {...params} label="Country" /&gt;} /&gt; } onChange={([, obj]) =&gt; getOpObj(obj)._id} control={control} defaultValue={options[0]} /&gt; &lt;Button type="submit"&gt;Submit&lt;/Button&gt; &lt;/form&gt; ); } </code></pre>
27,658,409
downloading error using nltk.download()
<p>I am experimenting NLTK package using Python. I tried to downloaded NLTK using <code>nltk.download()</code>. I got this kind of error message. How to solve this problem? Thanks.</p> <p>The system I used is Ubuntu installed under VMware. The IDE is Spyder.</p> <p><img src="https://i.stack.imgur.com/JF6RT.png" alt="enter image description here"></p> <p>After using <code>nltk.download('all')</code>, it can download some packages, but it gets error message when downloading <code>oanc_masc</code></p> <p><img src="https://i.stack.imgur.com/Aagi0.png" alt="enter image description here"></p>
27,660,379
4
6
null
2014-12-26 14:35:06.2 UTC
6
2020-02-10 22:22:43.93 UTC
2016-12-16 18:18:24.497 UTC
null
1,454,176
null
288,609
null
1
21
python|python-2.7|ubuntu|nltk|spyder
60,722
<p>To download a particular dataset/models, use the <code>nltk.download()</code> function, e.g. if you are looking to download the <code>punkt</code> sentence tokenizer, use:</p> <pre><code>$ python3 &gt;&gt;&gt; import nltk &gt;&gt;&gt; nltk.download('punkt') </code></pre> <p>If you're unsure of which data/model you need, you can start out with the basic list of data + models with:</p> <pre><code>&gt;&gt;&gt; import nltk &gt;&gt;&gt; nltk.download('popular') </code></pre> <p>It will download a list of "popular" resources.</p> <p>Ensure that you've the latest version of <code>NLTK</code> because it's always improving and constantly maintain:</p> <pre><code>$ pip install --upgrade nltk </code></pre> <hr> <h1>EDITED</h1> <p>In case anyone is avoiding errors from downloading larger datasets from <code>nltk</code>, from <a href="https://stackoverflow.com/a/38135306/610569">https://stackoverflow.com/a/38135306/610569</a></p> <pre><code>$ rm /Users/&lt;your_username&gt;/nltk_data/corpora/panlex_lite.zip $ rm -r /Users/&lt;your_username&gt;/nltk_data/corpora/panlex_lite $ python &gt;&gt;&gt; import nltk &gt;&gt;&gt; dler = nltk.downloader.Downloader() &gt;&gt;&gt; dler._update_index() &gt;&gt;&gt; dler._status_cache['panlex_lite'] = 'installed' # Trick the index to treat panlex_lite as it's already installed. &gt;&gt;&gt; dler.download('popular') </code></pre> <p>And if anyone wants to find <code>nltk_data</code> directory, see <a href="https://stackoverflow.com/a/36383314/610569">https://stackoverflow.com/a/36383314/610569</a> </p> <p>And to config <code>nltk_data</code> path, see <a href="https://stackoverflow.com/a/22987374/610569">https://stackoverflow.com/a/22987374/610569</a></p>
15,350,603
How to trigger mouseover function on an element when not really mouseovered
<p>In jQuery, is it possible for an element to act like it is mouseovered automatically when the page is loading, when it is not really mouseovered? I mean, I won't put my pointer on the desired element for it to do what it would do if I put.</p>
15,350,636
3
0
null
2013-03-11 23:30:42.02 UTC
0
2016-07-15 13:14:05.963 UTC
2016-07-15 13:14:05.963 UTC
null
24,875
null
2,114,455
null
1
10
jquery|mouseover
41,062
<p>Use <a href="http://api.jquery.com/trigger/">.trigger()</a> to trigger an event.</p> <pre><code>$('#foo').trigger('mouseover'); </code></pre>