Dataset Viewer
Auto-converted to Parquet
id
stringlengths
34
39
dataset
stringclasses
1 value
prompt
stringlengths
21
60.3k
chosen
stringlengths
21
41k
rejected
stringlengths
21
29.8k
stack-exchange-preferences_train_0
stack-exchange-preferences
<p>For example, here is the shape of intended spiral (and each step of the iteration)</p> <pre><code> y | | 16 15 14 13 12 17 4 3 2 11 -- 18 5 0 1 10 --- x 19 6 7 8 9 20 21 22 23 24 | | </code></pre> <p>Where the lines are the x and y axes.</p> <p>Here would be the actual values the algorithm would "return" with each iteration (the coordinates of the points):</p> <pre><code>[0,0], [1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1], [0,-1], [1,-1], [2,-1], [2,0], [2,1], [2,2], [1,2], [0,2], [-1,2], [-2,2], [-2,1], [-2,0].. </code></pre> <p>etc.</p> <p>I've tried searching, but I'm not exactly sure what to search for exactly, and what searches I've tried have come up with dead ends.</p> <p>I'm not even sure where to start, other than something messy and inelegant and ad-hoc, like creating/coding a new spiral for each layer.</p> <p>Can anyone help me get started?</p> <p>Also, is there a way that can easily switch between clockwise and counter-clockwise (the orientation), and which direction to "start" the spiral from? (the rotation)</p> <p>Also, is there a way to do this recursively?</p> <hr> <p><strong>My application</strong></p> <p>I have a sparse grid filled with data points, and I want to add a new data point to the grid, and have it be "as close as possible" to a given other point.</p> <p>To do that, I'll call <code>grid.find_closest_available_point_to(point)</code>, which will iterate over the spiral given above and return the first position that is empty and available.</p> <p>So first, it'll check <code>point+[0,0]</code> (just for completeness's sake). Then it'll check <code>point+[1,0]</code>. Then it'll check <code>point+[1,1]</code>. Then <code>point+[0,1]</code>, etc. And return the first one for which the position in the grid is empty (or not occupied already by a data point).</p> <p>There is no upper bound to grid size.</p>
<p>There's nothing wrong with direct, &quot;ad-hoc&quot; solution. It can be clean enough too.<br /> Just notice that spiral is built from segments. And you can get next segment from current one rotating it by 90 degrees. And each two rotations, length of segment grows by 1.</p> <p><strong>edit</strong> Illustration, those segments numbered</p> <pre><code> ... 11 10 7 7 7 7 6 10 8 3 3 2 6 10 8 4 . 1 6 10 8 4 5 5 5 10 8 9 9 9 9 9 </code></pre> <pre class="lang-java prettyprint-override"><code> // (di, dj) is a vector - direction in which we move right now int di = 1; int dj = 0; // length of current segment int segment_length = 1; // current position (i, j) and how much of current segment we passed int i = 0; int j = 0; int segment_passed = 0; for (int k = 0; k &lt; NUMBER_OF_POINTS; ++k) { // make a step, add 'direction' vector (di, dj) to current position (i, j) i += di; j += dj; ++segment_passed; System.out.println(i + &quot; &quot; + j); if (segment_passed == segment_length) { // done with current segment segment_passed = 0; // 'rotate' directions int buffer = di; di = -dj; dj = buffer; // increase segment length if necessary if (dj == 0) { ++segment_length; } } } </code></pre> <p>To change original direction, look at original values of <code>di</code> and <code>dj</code>. To switch rotation to clockwise, see how those values are modified.</p>
<p>Try searching for either parametric or polar equations. Both are suitable to plotting spirally things. <a href="http://www.mathematische-basteleien.de/spiral.htm" rel="nofollow noreferrer">Here's a page</a> that has plenty of examples, with pictures (and equations). It should give you some more ideas of what to look for. </p>
stack-exchange-preferences_train_1
stack-exchange-preferences
<p>I found DDD being natural if I am working on a operational/transactional type of application. However I am always stucked in a reasonable way to handle reporting type of functions.</p> <p>The reporting I am talking on is not bound to report generation, but also functions that perform comparatively complicated queries. (like, giving the summary of all orders that a trader did, or display the account summary for trading accounts having certain stock, etc). They can be simply some query or supporting function that is used together with those operational function.</p> <p>For such functions, it is quite natural if we can perform join in SQL (or whatever query language), get the columns we are interested, and return the massaged result set. However, it seems such way not going that well with DDD: we need a extra special repository or having existing most-related repository returning a special "entity/value object" (which is the specialized resultset). These kind of special "entities" is not having any domain meaning in fact.</p> <p>If we want to make use of the meaningful domain layer, that may creates a lot of extra lookups from different repository, plus a lot of aggregation work in the domain or service layer, which will easily cause horrible performance degrade.</p> <p>I have also thought of having another "path" for these kind of function, which doesn't go through the "DDD path", having its own way to get the report data from DB, compose the results for display. However it is going to make the application unnecessarily complicated, and even worse, we provided an extra path so that developers that is more used to traditional DB-oriented development may tends to use this path even it is not appropriate.</p> <p>I thought such situation is quite common (normally a big system will not contains operational but also reporting and enquiry functions), I would want to know how people is dealing with it?</p>
<p>In terms of DDD Reporting in most cases is a separate Bounded Context and a supporting subdomain where domain-driven design would be overkill. Remember the most important concept of DDD: Focus your modelling efforts on the Core Domain and implement everything else using the simplest possible solution.</p>
<p>One approach would be to have a separate reporting system which ran data feeds from your app's data store to store another copy of the data in a more relational format.</p> <p>A shortcut I've used is to create a view or stored procedure to return the joined data into a simple dumb object.</p>
stack-exchange-preferences_train_2
stack-exchange-preferences
<p>Currently I have a program which goes through a list of vector coordinates and performs a simple math function on the two vectors, but I want to make a loop inside of a loop to be able to have more control on what happens, this is my program so far:</p> <pre><code>import operator import numpy as np b = 0 a = 1 for a in range(0,56): vector1 = (int(l[b][0]),int(l[b][1]),int(l[b][2])) vector2 = (int(l[a][0]),int(l[a][1]),int(l[a][2])) #print vector1 #print vector2 x = vector1 y = vector2 vector3 = list(np.array(x) - np.array(y)) #print vector3 dotProduct = reduce( operator.add, map( operator.mul, vector3, vector3)) print dotProduct a += 1 </code></pre> <p>But what I want is that once a hits 56 and does its final run through, I want B to add 1 and a to reset back to zero, and redo the loop of operations until b goes up to 55.</p> <p>Desired output: example of coordiantes:</p> <p>Cu 46.7176 27.1121 27.1121</p> <p>Cu 43.2505 36.0618 32.4879</p> <p>Cu 43.3392 36.0964 28.9236</p> <p>Cu 43.2509 37.8362 27.1091</p> <p>Cu 34.4872 14.1794 16.5767</p> <p>Cu 34.4103 16.0364 14.3521</p> <p>Cu 32.7006 14.069 14.412 </p> <p>and I want the first coordinate to perform the dot product with everything under it, and go back and then start with the second coordinate and perform dot product with everything under it, and so on..</p>
<p>Run this and see what you get (before you ask another question)</p> <pre><code>for b in range(56): for a in range(57): print "a:", a, "b:", b </code></pre> <hr> <p>Answer to question in comment:</p> <p>You can use <code>b</code> as argument in inner loop</p> <pre><code>for b in range(56): for a in range(b+1, 57): print "a:", a, "b:", b </code></pre> <p>you could try with smaller range to see all results on one screen</p> <pre><code>for b in range(6): for a in range(b+1, 7): print "a:", a, "b:", b </code></pre> <p>result:</p> <pre><code>a: 1 b: 0 a: 2 b: 0 a: 3 b: 0 a: 4 b: 0 a: 5 b: 0 a: 6 b: 0 a: 2 b: 1 a: 3 b: 1 a: 4 b: 1 a: 5 b: 1 a: 6 b: 1 a: 3 b: 2 a: 4 b: 2 a: 5 b: 2 a: 6 b: 2 a: 4 b: 3 a: 5 b: 3 a: 6 b: 3 a: 5 b: 4 a: 6 b: 4 a: 6 b: 5 </code></pre>
<p>You can use while loop instead of for loop :</p> <pre><code>b = 0 a = 0 while a &lt;= 56 : import operator import numpy as np vector1 = (int(l[b][0]), int(l[b][1]), int(l[b][2])) vector2 = (int(l[a][0]),int(l[a][1]),int(l[a][2])) #print vector1 #print vector2 x = vector1 y = vector2 vector3 = list(np.array(x) - np.array(y)) #print vector3 dotProduct = reduce( operator.add, map( operator.mul, vector3, vector3)) print dotProduct if a == 56 : b += 1 a = 0 else: a += 1 if b == 55: break </code></pre>
stack-exchange-preferences_train_3
stack-exchange-preferences
<p>I need to check a date before downloading / manipulate some data from a server. Let's say I need to do that only if 24 hours or more are gone by. this code seems to work, but I'm not sure about it, no way to do it with less lines of code? it seems to be too long to me. i checked <a href="https://stackoverflow.com/questions/24755558/measure-elapsed-time-in-swift">this</a> but solutions are quite different from mine.</p> <pre><code>import UIKit //standard day formatter let dateFormatter = DateFormatter() //let's say this is the date I saved last time i updated data from online server: let previousDate: String = "2019-03-19 06:40 PM" dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a" let old = dateFormatter.date(from: previousDate) //today I try to download data let today = Date() //this simply tests if "moment before" is greater than "moment after" if today &gt; old! { print("update data") } else { print("do not update") } //here I create a measure let minute:TimeInterval = 60.0 let hour:TimeInterval = 60.0 * minute let day:TimeInterval = 24 * hour //here I measure if the old date added of 24h is greater than now, in that case a day or more is passed and I can update let theOldDateMore24h = Date(timeInterval: day, since: old!) if theOldDateMore24h &lt; today { print("passed more than a day: Update!") } else { print("less than a day, do not update") } </code></pre>
<p>Consider storing your fruit information as data and using some common shared functions to render.</p> <p>Can you tell us where the 3D data is coming from and we can add that functionality.</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>let fruits = [{ name: "apple", description: "An apple is a sweet, edible fruit produced by an apple tree (Malus pumila). Apple trees are cultivated worldwide and are the most widely grown species in the genus Malus. The tree originated in Central Asia, where its wild ancestor, Malus sieversii, is still found today. Apples have been grown for thousands of years in Asia and Europe and were brought to North America by European colonists.", color: "green" }, { name: "banana", description: "A banana is an edible fruit – botanically a berry – produced by several kinds of large herbaceous flowering plants in the genus Musa. In some countries, bananas used for cooking may be called 'plantains.' Musa species are native to tropical Indomalaya and Australia, and are likely to have been first domesticated in Papua New Guinea. They are grown in 135 countries and the world's largest producers of bananas are India and China", color: "gold" }, { name: "strawberry", description: "The garden strawberry is a widely grown hybrid species of the genus Fragaria, collectively known as the strawberries. It is cultivated worldwide for its fruit. The fruit is widely appreciated for its characteristic aroma, bright red color, juicy texture, and sweetness.", color: "red" }, { name: "orange", description: "The orange is the fruit of the citrus species Citrus × sinensis in the family Rutaceae. It is known as the 'Sweet Orange.' It originated in ancient China and the earliest mention of the sweet orange was in Chinese literature in 314 BC. As of 1987, orange trees were found to be the most cultivated fruit tree in the world. In 2014, 70.9 million tonnes of oranges were grown worldwide, with Brazil producing 24% of the world total followed by China and India. Oranges are infertile and reproduce asexually.", color: "peru" }, { name: "pineapple", description: "The word 'pineapple' in English was first recorded to describe the reproductive organs of conifer trees (now termed pine cones). When European explorers encountered this tropical fruit in the Americas, they called them 'pineapples' (first referenced in 1664, for resemblance to pine cones). The plant is indigenous to South America and is said to originate from the area between southern Brazil and Paraguay. Columbus encountered the pineapple in 1493 on the leeward island of Guadeloupe. He called it piña de Indes, meaning 'pine of the Indians', and brought it back with him to Spain.", color: "yellow" }, { name: "blueberry", description: "Blueberries are perennial flowering plants with blue– or purple–colored berries. They are classified in the section Cyanococcus within the genus Vaccinium. Commercial 'blueberries' are all native to North America. They are covered in a protective coating of powdery epicuticular wax, colloquially known as the 'bloom'. They have a sweet taste when mature, with variable acidity.", color: "blue" }, { name: "grape", description: "A grape is a fruit, botanically a berry, of the deciduous woody vines of the flowering plant genus Vitis. Grapes are a non-climacteric type of fruit, generally occurring in clusters. The cultivation of the domesticated grape began 6,000–8,000 years ago in the Near East.[1] Yeast, one of the earliest domesticated microorganisms, occurs naturally on the skins of grapes, leading to the discovery of alcoholic drinks such as wine. The earliest archeological evidence for a dominant position of wine-making in human culture dates from 8,000 years ago in Georgia.", color: "purple" }, { name: "lemon", description: "The lemon, Citrus limon Osbeck, is a species of small evergreen tree in the flowering plant family Rutaceae, native to South Asia, primarily North eastern India. The juice of the lemon is about 5% to 6% citric acid, with a pH of around 2.2, giving it a sour taste. The distinctive sour taste of lemon juice makes it a key ingredient in drinks and foods such as lemonade and lemon meringue pie.", color: "yellow" }, { name: "kiwi", description: "Kiwi is the edible berry of several species of woody vines in the genus Actinidia. It has a fibrous, dull greenish-brown skin and bright green or golden flesh with rows of tiny, black, edible seeds. Kiwifruit is native to north-central and eastern China. The first recorded description of the kiwifruit dates to 12th century China during the Song dynasty. China produced 56% of the world total of kiwifruit in 2016.", color: "green" }, { name: "watermelon", description: "Citrullus lanatus is a plant species in the family Cucurbitaceae, a vine-like flowering plant originating in West Africa. It is cultivated for its fruit. There is evidence from seeds in Pharaoh tombs of watermelon cultivation in Ancient Egypt. Watermelon is grown in tropical and subtropical areas worldwide for its large edible fruit, also known as a watermelon, which is a special kind of berry with a hard rind and no internal division, botanically called a pepo.", color: "crimson" }, { name: "peach", description: "The peach (Prunus persica) is a deciduous tree native to the region of Northwest China between the Tarim Basin and the north slopes of the Kunlun Mountains, where it was first domesticated and cultivated. The specific name persica refers to its widespread cultivation in Persia (modern-day Iran), from where it was transplanted to Europe. China alone produced 58% of the world's total for peaches and nectarines in 2016.", color: "peru" } ]; function resetStyle() { document.querySelectorAll('li').forEach(x =&gt; x.style.color = 'hotpink'); } function setFruit(fruit) { console.log(`loading ${fruit.name}`); let elem = document.getElementById(fruit.name); elem.style.color = fruit.color; fruitName = document.getElementById('fruitName'); fruitName.innerText = fruit.name; fruitDesc = document.getElementById('fruitDesc'); fruitDesc.innerText = fruit.description; //activate 3d view window var x = document.getElementById('x'); x.innerHTML = 1; } document.addEventListener('click', (e) =&gt; { if (e.target.matches('li')) { resetStyle(); setFruit(fruits.find(f =&gt; f.name === e.target.id)); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { margin: 0px; padding: 0px; border: 0px; } .container { background-color: beige; width: 600px; min-height: 550px; border-radius: 30px; margin: 40px auto; } .title { font-family: sans-serif; margin: 20px 20px 20px 20px; color: indianred; display: inline-block; float: left; } .box3d { float: right; height: 225px; width: 280px; background-color: slategray; display: inline-block; margin: 25px 50px 0px 0px; } .desc { float: right; height: 225px; width: 350px; background-color: white; display: inline-block; margin: 25px 50px 0px 0px; overflow: auto; } .fruitlist { padding-left: 20px; margin: 20px 0px 0px 30px; list-style: none; display: inline-block; float: left; } li { margin-bottom: 12px; font-family: sans-serif; color: purple; font-size: 18px; } li:hover { font-size: 20px; color: hotpink; } #fruitName { color: blue; margin: 10px 10px 10px 10px; border-bottom: solid 3px blue; font-family: sans-serif; } #fruitDesc { margin: 10px 10px 0px 10px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt; &lt;title&gt;FruityView&lt;/title&gt; &lt;link rel="stylesheet" href="fruitstyle.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;h1 class="title"&gt;FruityView&lt;/h1&gt; &lt;!--3D MODEL VIEW WINDOW--&gt; &lt;div class="box3d" id="box3d"&gt; &lt;p id='x'&gt;0&lt;/p&gt; &lt;script&gt; //this doesn't work - maybe I could do some sort of for loop that could retest it? var x = document.getElementById('x'); console.log(x); function view3d() { console.log("view function activated"); } if (x == 1) { view3d(); } //this doesn't work - I know it would if it came after the list but I don't want to do that /*var peach = document.getElementById('peach').onclick = peach; peach() { console.log("successful activation"); } */ &lt;/script&gt; &lt;/div&gt; &lt;br&gt; &lt;!--SELECTION LIST--&gt; &lt;ul class="fruitlist"&gt; &lt;li id="apple"&gt;Apple&lt;/li&gt; &lt;li id="banana"&gt;Banana&lt;/li&gt; &lt;li id="strawberry"&gt;Strawberry&lt;/li&gt; &lt;li id="orange"&gt;Orange&lt;/li&gt; &lt;li id="pineapple"&gt;Pineapple&lt;/li&gt; &lt;li id="blueberry"&gt;Blueberry&lt;/li&gt; &lt;li id="grape"&gt;Grape&lt;/li&gt; &lt;li id="lemon"&gt;Lemon&lt;/li&gt; &lt;li id="kiwi"&gt;Kiwi&lt;/li&gt; &lt;li id="watermelon"&gt;Watermelon&lt;/li&gt; &lt;li id="peach"&gt;Peach&lt;/li&gt; &lt;/ul&gt; &lt;!--NAME AND DESCRIPTION--&gt; &lt;div class="desc"&gt; &lt;h3 id="fruitName"&gt;Welcome to FruityView&lt;/h3&gt; &lt;p id="fruitDesc"&gt;Please pick a fruit&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<p>It seems to me that there's a misunderstanding of what <code>&lt;script&gt;</code> does and why you cannot use <code>document.getElementById</code> before the list. So I'll try to explain.</p> <p>Anything you put directly in <code>&lt;script&gt;</code> will be executed right away when the browser reads it.</p> <p>That means any elements in the DOM following that script don't exist yet, which is the reason why <code>document.getElementById()</code> will not find such an element.</p> <p>So the reason it fails is not that "JavaScript isn't active", it's that the element with the ID is not existing yet.</p> <p>If you want to declare code in a script element, and call it only later, you would just wrap it in a function, like so:</p> <pre><code>&lt;script&gt; function callMeLater() { var x = document.getElementById('x'); } &lt;/script&gt; … &lt;script&gt; /* now all above elements exist */ callMeLater(); &lt;/script&gt; </code></pre> <p>Further, it is not necessary to put a script inside the <code>&lt;div&gt;</code> which will contain the model. You can inject HTML into an element by means of <a href="https://developer.mozilla.org/de/docs/Web/API/Element/innerHTML" rel="nofollow noreferrer"><code>innerHTML</code></a> any time (once it exists in the DOM).</p> <pre><code>document.getElementById('box3d').innerHTML = 3dModelHtml; </code></pre> <p>Last, I would like to mention that you have a lot of duplicate code, which you should avoid by all means. Replace them with functions and objects where you store data.</p> <p>For example, use an object to store fruitIds together with their descriptions:</p> <pre><code>var fruitDescriptions = { 'apple': "An apple is a sweet, edible fruit produced by an apple tree (Malus pumila). Apple trees are cultivated worldwide and are the most widely grown species in the genus Malus. The tree originated in Central Asia, where its wild ancestor, Malus sieversii, is still found today. Apples have been grown for thousands of years in Asia and Europe and were brought to North America by European colonists.", 'banana': "…", } </code></pre> <p>Then, you can iterate over the fruits with <a href="https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for...in" rel="nofollow noreferrer">for…in</a> to bind the event handlers to each fruit and reset it's styles:</p> <pre><code>for(fruitId in fruitDescriptions) { var fruit = document.getElementById(fruitId); fruit.click = function() { fruit(fruitId); } fruit.style.color = "hotpink"; } </code></pre> <p>(You need another function for the event handler, to pass the parameter <code>fruitId</code> to the actual handler)</p> <p>Finally, refactor your duplicate functions to use the fruit as a parameter:</p> <pre><code>function fruit(fruitId){ console.log("loading " + fruitId); styleReset(); var fruit = document.getElementById(fruitId); fruit.style.color = "red"; fruitName = document.getElementById('fruitName'); fruitName.innerText = fruitId; fruitDesc = document.getElementById('fruitDesc'); fruitDesc.innerText = fruitDescriptions[fruitId]; } </code></pre>
stack-exchange-preferences_train_4
stack-exchange-preferences
<p>I don't want user to give the back date or time. </p> <p>How can I compare if the entered date and time is LESS then the current time?</p> <p>If the current date and Time is 17-Jun-2010 , 12:25 PM , I want user cannot give date before 17 Jun -2010 and time before 12:25 PM.</p> <p>Like my function return false if the time entered by user is 16-Jun-2010 and time 12:24 PM</p>
<p>MSDN: <a href="http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx" rel="noreferrer">DateTime.Compare</a></p> <pre><code>DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0); DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0); int result = DateTime.Compare(date1, date2); string relationship; if (result &lt; 0) relationship = "is earlier than"; else if (result == 0) relationship = "is the same time as"; else relationship = "is later than"; Console.WriteLine("{0} {1} {2}", date1, relationship, date2); // The example displays the following output: // 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM </code></pre>
<pre><code>public static bool CompareDateTimes(this DateTime firstDate, DateTime secondDate) { return firstDate.Day == secondDate.Day &amp;&amp; firstDate.Month == secondDate.Month &amp;&amp; firstDate.Year == secondDate.Year; } </code></pre>
stack-exchange-preferences_train_5
stack-exchange-preferences
<p>First, apologies if this has been asked before - I searched for a while through the existing posts, but could not find support.</p> <p>I am interested in a solution for Fedora to OCR a multipage non-searchable PDF and to turn this PDF into a new PDF file that contains the text layer on top of the image. On Mac OSX or Windows we could use Adobe Acrobat, but is there a solution on Linux, specifically on Fedora?</p> <p><a href="https://web.archive.org/web/20190807064639/https://snippets.webaware.com.au/howto/pdf-ocr-linux/" rel="noreferrer">This</a> seems to describe a solution - but unfortunately I am already lost when retrieving exact-image.</p>
<p><a href="https://pypi.org/project/ocrmypdf/" rel="noreferrer"><code>ocrmypdf</code></a> does a good job and can be used like this:</p> <pre><code>ocrmypdf in.pdf out.pdf </code></pre> <p>To install:</p> <pre><code>pip install ocrmypdf </code></pre> <p>or</p> <pre><code>sudo apt install ocrmypdf # ubuntu sudo dnf -y install ocrmypdf # fedora </code></pre>
<p>An easy tool available in Ubuntu is 'ocrfeeder' it allows the generation of PDFs with OCR text overlaid on the original documents. It makes use of Tesseract plus other OCR engines (not sure which) and provides for image rotation/'unpaper', etc, as well.</p> <ul> <li><a href="http://live.gnome.org/OCRFeeder" rel="noreferrer">http://live.gnome.org/OCRFeeder</a></li> <li><a href="https://github.com/GNOME/ocrfeeder" rel="noreferrer">https://github.com/GNOME/ocrfeeder</a></li> </ul>
stack-exchange-preferences_train_6
stack-exchange-preferences
<p>I have the optimization problem in <span class="math-container">$u := \left(u_{1},u_{2}\right)$</span></p> <p><span class="math-container">$$\begin{array}{ll} \text{minimize} &amp; \frac{1}{2}u^{\top}\Sigma u-au^{\top}\beta\\ \text{subject to} &amp; u_{1}u_{2}\le0\end{array}$$</span></p> <p>where matrix <span class="math-container">$\Sigma$</span> is positive definite and <span class="math-container">$a&gt;0$</span>. </p> <p>The first-order condition is</p> <p><span class="math-container">\begin{equation} \nabla f=\Sigma u-\beta a=0\Rightarrow u^{*}=a\Sigma^{-1}\beta=\left(\begin{array}{c} u_{1}^{*}\\ u_{2}^{*} \end{array}\right) \end{equation}</span></p> <p>If <span class="math-container">$u_{1}^{*}u_{2}^{*}&gt;0$</span> and we assume <span class="math-container">$f\left(u\right)$</span> attain minimum at <span class="math-container">$u^{\#}=\left(\begin{array}{c} u_{1}^{\#}\\ u_{2}^{\#} \end{array}\right)$</span>, do we have <span class="math-container">$u_{1}^{\#}u_{2}^{\#}=0$</span>?</p> <p>Does anyone know how to show it in a rigorous proof?</p>
<p>No, given <span class="math-container">$\epsilon&gt;0$</span>, <span class="math-container">$(a,a+\epsilon )=\emptyset$</span> is not true. In fact <span class="math-container">$x_{0}&lt;a+\epsilon$</span> does not imply that <span class="math-container">$x_0\leq a$</span>. </p> <p>Instead if <span class="math-container">$a&lt;x_0&lt;b$</span> there exists <span class="math-container">$\epsilon&gt;0$</span> such that <span class="math-container">$a+\epsilon&lt;x_0&lt;b-\epsilon$</span> (take for example <span class="math-container">$\epsilon=\frac{\min(x_0-a,b-x_0)}{2}$</span>). In this way, we show that <span class="math-container">$$(a,b)=\bigcup_{\epsilon&gt;0}(a+\epsilon ,b-\epsilon ).$$</span></p> <p>This means that if <span class="math-container">$x_0\in (a,b)$</span> then there is <span class="math-container">$\epsilon&gt;0$</span> such that <span class="math-container">$x_0\in (a+\epsilon ,b-\epsilon)$</span> and therefore if <span class="math-container">$f$</span> is continuous in <span class="math-container">$(a+\epsilon ,b-\epsilon )$</span> for all <span class="math-container">$\epsilon &gt;0$</span> then we may conclude that <span class="math-container">$f$</span> is continuous in <span class="math-container">$(a,b)$</span></p>
<p>You need to be careful in applying the "for all" quantifier. The logical statement </p> <p><span class="math-container">$$\forall\epsilon\gt0\,\,\,(x_0\lt a+\epsilon\implies x_0\le a)$$</span> </p> <p>does not hold. What does hold is the logical statement </p> <p><span class="math-container">$$(\forall\epsilon\gt0\,\,\, x_0\lt a+\epsilon)\implies x_0\le a$$</span></p> <p>In other words, it's not true that <span class="math-container">$(a,a+\epsilon)=(b-\epsilon,b)=\emptyset$</span>, but, rather</p> <p><span class="math-container">$$\bigcap_{\epsilon\gt0}(a,a+\epsilon)=\bigcap_{\epsilon\gt0}(b-\epsilon,b)=\emptyset$$</span></p>
stack-exchange-preferences_train_7
stack-exchange-preferences
<p>The definition of a reversible thermodynamic process requires in any instant the <strong>mechanical equilibrium</strong> (equal pressures) and <strong>thermal equilibrium</strong> (equal temperatures) of the system in a quasi-static processr.</p> <p>But there are cases of processes in which one of the two kinds of equilibrium cannot be reached. </p> <p><strong>Can these processes be considered "reversible" anyway?</strong></p> <p>I'll make two examples</p> <hr> <ol> <li>Quasi-static process in a completely adiabatic tank with two different gases at different temperatures: <strong>mechanical</strong> equilibrium always present, but <strong>thermal</strong> equilibrium (between the two gases) not necessarily reached. <a href="https://i.stack.imgur.com/EcSwA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EcSwA.png" alt="enter image description here"></a></li> </ol> <hr> <ol start="2"> <li>Isochoric quasi-static process of a gas in rigid and diatermic tank: <strong>thermal</strong> equilibrium always present, but <strong>mechanical</strong> equilibrium (between the gas and the environment) not necessarily reached.</li> </ol> <p><a href="https://i.stack.imgur.com/XCOym.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XCOym.png" alt="enter image description here"></a></p>
<p>This is an exact value. Meter is defined by the speed of light.</p> <p>Meter is a distance that the light travels during $\frac{1}{299792458}$ of a second.</p>
<p>The BIPM (Bureau International de Poids et Mesures) defines the meter as the distance traveled by light in $\frac{1}{299792458}$ seconds.</p> <blockquote> <p>The metre is the length of the path travelled by light in vacuum during a time interval of 1/299 792 458 of a second.</p> </blockquote> <p>The speed of light as $299792458$ m/s is therefore exact and not a measured value.</p> <p>Similarily, the vaccuum permeability $\mu_0$ also has a defined value of $$\mu_0 = 4\pi \times 10^{-7} N/A^2$$</p> <p>This is also used to calculate the vaccuum permittivity $$\varepsilon_0 = \frac{1}{\mu_0 c^2} = 8.854\ 187\ 817\ \cdots\times 10^{−12} F/m$$</p> <p>Sources:</p> <ul> <li><a href="http://www.bipm.org/en/publications/si-brochure/metre.html" rel="nofollow">http://www.bipm.org/en/publications/si-brochure/metre.html</a></li> <li><a href="https://www.wikiwand.com/en/Vacuum_permeability" rel="nofollow">https://www.wikiwand.com/en/Vacuum_permeability</a></li> <li><a href="https://www.wikiwand.com/en/Vacuum_permittivity" rel="nofollow">https://www.wikiwand.com/en/Vacuum_permittivity</a></li> </ul>
stack-exchange-preferences_train_8
stack-exchange-preferences
<p>My understanding of vigilantism is that it constitutes any act motivated by a desire to seek justice outside of the state-enforced judicial system. As such, can one be considered a vigilante if one's personal conception of justice doesn't match up with what the majority generally considers to be justice?</p> <p>In Edgar Wright's <em>Hot Fuzz</em>, for example, the Neighbourhood Watch Alliance murder those that they feel ruin their village's chances of winning village of the year. They're the villains of the film, but they claim to do what they do "for the greater good", so presumably from their point of view they've been punishing those that break the rules they've established for the town. The rules are bizarre, but they're rules nonetheless, and so, from a warped perspective, punishing those who break them could be considered a kind of justice. </p> <p>With this in mind, could the Neighbourhood Watch Alliance be considered 'vigilantes', albeit villainous ones?</p> <p>Edit: I think its worth clarifying - I mean more to ask whether the justice that an individual seeks has to be the one advocated by the state (as in nation-state, rather than US state), or could it be their own personal idea of justice? Does a vigilante have to uphold existing laws, or can they uphold their own?</p>
<p><em>vigilante</em> implies going outside the law; the law applies to everyone and isn't a matter of choice or preference. But neighborhood watch groups, which often exist, aren't an example of vigilantism. It's not a question, however, of one's view that the current administration of justice may be inadequate or inappropriate; it's a question of what one does.</p> <p><a href="https://www.merriam-webster.com/dictionary/vigilante" rel="nofollow noreferrer">MW on vigilante</a>:</p> <blockquote> <h2>Definition of vigilante</h2> <p>a member of a volunteer committee organized to suppress and punish crime summarily (as when the processes of law are viewed as inadequate); <em>broadly</em> : a self-appointed doer of justice</p> <h3>The Meaning and Origin of vigilante</h3> <p>Vigilante entered English in the 19th century, borrowed from the Spanish word of the same spelling which meant “watchman, guard” in that language. The Spanish word can be traced back to the Latin vigilare, meaning “to keep awake.” The earliest use of the word in English was to refer to a member of a vigilance committee, a committee organized to suppress and punish crime summarily, as when the processes of law appear inadequate. The word may often be found in an attributive role, as in the phrases “vigilante justice,” or “vigilante group.” In this slightly broadened sense it carries the suggestion of the enforcement of laws without regard to due process or the general rule of law.</p> </blockquote> <p>Note, however, that citizens may have the power to make an arrest: <a href="http://criminal.findlaw.com/criminal-procedure/citizen-s-arrest.html" rel="nofollow noreferrer">Citizen's Arrest</a></p> <blockquote> <p>In certain situations, private individuals have the power to make an arrest without a warrant. These types of arrests, known as citizens arrests, occur when ordinary people either detain criminals themselves or direct police officers to detain a criminal.</p> </blockquote> <p><strong>Fictional heros, superheros, detectives, and commandos</strong> may have a vigilante aspect--they may violate the law in order to bring justice. For example:</p> <p>Batman</p> <p>Jack Reacher (Lee Child's books)</p> <p>Pike Logan (Brad Taylor)</p> <p>Mitch Rabb (Vince Flynn)</p>
<p>A <strong><em>vigilante</em></strong> is simply (from Spanish) a <strong><em>night watchman</em></strong>, from <strong><em>vigilant</em></strong>, meaning (per OED), </p> <blockquote> <p>Wakeful and watchful; keeping steadily on the alert; attentively or closely observant.</p> </blockquote> <p>Most uses of the term are connected with guarding against the illegal and criminal, but it is difficult always to be clear exactly what that is. Opinions differ as to what is legally proper. I did find this example of <em>vigilant</em>, at least suggesting that the officers of the law were not always beyond a need to be watched. </p> <blockquote> <p>1845 H. H. Wilson Hist. Brit. India 1805–35 I. vii. 400 It was impossible for him to exercise a vigilant personal supervision over the officers of the police.</p> </blockquote>
stack-exchange-preferences_train_9
stack-exchange-preferences
<p>I have 2 views login and usermodule.I want to switch to usermodule if login is success.I have made datatemplates in mainwindow and a content control which gets bind by currentviewmodel.I made a switchview method in MainWindowViewModel which is called after successful login.As the login is successful the currentviewmodel gets changed to usermoduleviewmodel bur the view is not changing.</p> <p>I have done like this: MainWinodow.xaml</p> <pre><code> &lt;Window.Resources&gt; &lt;DataTemplate DataType="{x:Type VM:LoginViewModel}"&gt; &lt;local:LoginView&gt;&lt;/local:LoginView&gt; &lt;/DataTemplate&gt; &lt;DataTemplate DataType="{x:Type VM:MenuViewModel}"&gt; &lt;local:MenuWindow /&gt; &lt;/DataTemplate&gt; &lt;DataTemplate DataType="{x:Type VM:UserModuleMapViewModel}"&gt; &lt;local:UserModuleMapView /&gt; &lt;/DataTemplate&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;ContentPresenter x:Name="Pages" Content="{Binding CurrentViewModel}" Grid.Row="1"/&gt; &lt;/Grid&gt; </code></pre> <p><strong>MainWindow.cs</strong></p> <pre><code> MainWindowViewModel mainVM = new MainWindowViewModel(); public MainWindow() { InitializeComponent(); this.DataContext = mainVM; } </code></pre> <p><strong>MainWindowViewModel.cs</strong></p> <pre><code>public class MainWindowViewModel : ViewModelBase { readonly LoginViewModel _loginViewModel = new LoginViewModel(); readonly MenuViewModel _menuViewModel = new MenuViewModel(); readonly UserModuleMapViewModel _usermodmapViewModel = new UserModuleMapViewModel(); public MainWindowViewModel() { CurrentViewModel = _loginViewModel; } private ViewModelBase _currentViewModel; public ViewModelBase CurrentViewModel { get { return _currentViewModel; } set { if (_currentViewModel == value) return; _currentViewModel = value; OnPropertyChanged("CurrentViewModel"); } } public void switchView() { if (CurrentViewModel == _loginViewModel) { CurrentViewModel = _usermodmapViewModel; } else { CurrentViewModel = _loginViewModel; } } } </code></pre> <p>LoginViewModel.cs</p> <pre><code>public LoginModel objmodel { get; set; } public ICommand LoginCommand { get; set; } public LoginModel _selectedItem { get; set; } public LoginModel SelectedItem { get { return _selectedItem; } set { _selectedItem = value; OnPropertyChanged("comboBoxItems");//need to check now its working properly } } readonly UserModuleMapViewModel _usermodmapViewModel = new UserModuleMapViewModel(); public LoginViewModel() { getjobkeycodeCombobox(); objmodel = new LoginModel(); LoginCommand = new RelayCommand(() =&gt; Login()); } public void Login() { try { UserIdInfo info = new UserIdInfo(); { objmodel.job_Code_Key = SelectedItem.job_Code_Key; info.EMP_NO = objmodel.EMP_NO; info.Password = objmodel.Password; info.Job_Code_Key = objmodel.job_Code_Key; if (objmodel.EMP_NO == null || objmodel.EMP_NO == "" || objmodel.Password == null || objmodel.Password == "") { MessageBox.Show("Please Enter the inputs of all the fields..!!"); } else { UserIdBL uidBL = new UserIdBL(); if (uidBL.isvalid(info)) { MessageBox.Show("Success..!!"); MainWindowViewModel mwvm = new MainWindowViewModel(); mwvm.CurrentViewModel = _usermodmapViewModel; //Messenger.Default.Send(new NotificationMessage("LoginSuccess")); } else { } } } } } </code></pre> <p>What mistake is done?Am I missing something > </p>
<p>For completeness, <code>\a</code> is an escape character and that is causing issue for you. Using raw string as mentioned in the comments solve this issue.</p> <p>You can see this clearly if you do <code>repr(file_path)</code> . This is one of the gotchas with Windows. I would suggest using forward slashes for accessing files even in Windows to avoid running into these issues.</p>
<p>Answer was to add the 's' at the end of the file name and to use the \ in the file path. </p>
stack-exchange-preferences_train_10
stack-exchange-preferences
<p>I've created a Java RESTful web service using NetBeans 8.0 and GlassFish server 4.0, using my database(local). When I click the "Test RESTful web services" my default web browser opens with an alert saying:</p> <blockquote> <p>Cannot access WADL: Please restart your RESTful application, and refresh this page.</p> </blockquote> <p>Note: Using the default sample database everything works fine.</p> <hr> <p><strong>Update</strong>: I'm following this tutorial <a href="https://netbeans.org/kb/docs/websvc/rest.html" rel="nofollow noreferrer">https://netbeans.org/kb/docs/websvc/rest.html</a></p>
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow noreferrer"><code>reindex</code></a> by columns from <code>df</code>:</p> <pre><code>df = pd.DataFrame(columns = ['a','b','c']) d = {'a': [1, 2], 'b': [3, 4]} df1 = pd.DataFrame(data=d).reindex(columns=df.columns) print (df1) a b c 0 1 3 NaN 1 2 4 NaN </code></pre> <p>Difference betwen soluions - if columns are not sorted get different output:</p> <pre><code>#different order df = pd.DataFrame(columns = ['c','a','b']) d = {'a': [1, 2], 'b': [3, 4]} df1 = pd.DataFrame(data=d) print (df1.reindex(columns=df.columns)) c a b 0 NaN 1 3 1 NaN 2 4 print (df1.merge(df,how='left')) a b c 0 1 3 NaN 1 2 4 NaN </code></pre>
<blockquote> <blockquote> <p>How can I join them</p> </blockquote> </blockquote> <p>If you have the dataframe existing somewhere(not creating a new), do :</p> <pre><code>df1.merge(df,how='left') a b c 0 1 3 NaN 1 2 4 NaN </code></pre> <p><strong>Note:</strong> This produces sorted columns. So if order of columns are already sorted, this will work fine , else not.</p>
stack-exchange-preferences_train_11
stack-exchange-preferences
<p>I am having trouble fingering this passage. It is fast, quarter note = 140 or so. I was thinking: </p> <p>3432 -- 3454 -- 3423 -- 1213</p> <p>the start is fine but as it descends the 1213 stumbles me. Any suggestions?</p> <p><a href="https://i.stack.imgur.com/WAGCm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WAGCm.jpg" alt="enter image description here"></a></p>
<p>When you learn a scale shape on guitar, the whole lot of it is moveable, provided there are enough frets above or below to accomodate all the notes.</p> <p>For example, A pent min. basically goes 6 string - 5,8. 5th string - 5-7. 4th string 5-7. 3rd string 5-7. 2nd string 5-8. top string 5 (and 8 if you like). This pattern can be moved up and down, let's start on 6th string 3rd fret. Copy the exact fingering, (take 2 away from each fret number) and you have G pent min. Start at fret 8 (add 3 to each fret number) and you have C pent min.</p> <p>This works for each and every scale you can play. Learn, say, C harmonic min. starting on fret 8 on bottom string. Start instead on 6th fret, and you'll be playing Bb harmonic minor, assuming you use the same finger pattern, relatively.</p> <p>Be aware that there are two common pentatonic scales - minor and major, so just calling something 'pentatonic' is a bit open, although I guess a lot of guitarists, beginners in particular, will be meaning pent. minor.</p>
<p>Thanks for your question. Tim's answer is 100% correct. </p> <p>Another way to answer would be <strong>yes</strong> - all of the patterns remain the same for a given type scale - regardless of where you start the pattern on the neck (which will determine the key of the scale you are playing). </p> <p>If you have studied the CAGED system, you may have learned that the pattern shapes are based on the open position chord shapes for major chords in standard tuning. You have the C shape, the A shape, the G shape, the E shape and D shape. Those are the 5 chords that can be played as open chords. Any other major chord is played as a barre chord using one of those 5 shapes. For example an F Major chord is an E shaped chord with either a full bar or a mini bar playing only the top four strings and a B flat in first position is an A shaped Barre chord (which can also be played using only the top four strings). </p> <p>By using a barre, you can play <strong>any</strong> chord using <strong>any one</strong> of these 5 shapes <strong>somewhere</strong> on the neck. </p> <p>When you move a barre chord up and down the neck, the shape stays exactly the same. For example if you play an E shaped barre chord on the third fret to play a G - the shape stays exactly the same if you move it up to the fifth fret to play an A. </p> <p>The same concept applies to scale shapes. The shapes stay exactly the same no matter where you start. Works that way on guitar but not on keyboard. </p> <p>Hope that helps you understand the concept of movable scale patterns and movable barre chords. Keep up your interest in learning to play your instrument better and better as you go by increasing your understanding of the theory and concepts that will make it easier to expand your capabilities. </p>
stack-exchange-preferences_train_12
stack-exchange-preferences
<p>I am not entirely sure if I am going on the right pass here in solving the following logical puzzle:</p> <p>There are 3 people.<br> <strong>$X$ says only one person is lying. $Y$ says exactly two people are lying. $Z$ says all of us are lying.</strong></p> <p>This is how I tried to solve it, I used the negation for lying and normal form for truth.</p> <p>$Z: \lnot X\wedge \lnot Y\wedge \lnot Z$ so, </p> <p>$\lnot Z: X \vee Y\vee Z$ , which forms a contradiction as Z can't be a truth teller</p> <p>So, $Y: (\lnot X\wedge\lnot Y\wedge Z)\vee(\lnot X\wedge\lnot Z\wedge Y)\vee(\lnot Z\wedge\lnot Y\wedge X)$ </p> <p>But the first brackets form a contradiction as Z is a liar, so that can be canceled out</p> <p>so,$Y:(\lnot X\wedge\lnot Z\wedge Y)\vee(\lnot Z\wedge\lnot Y\wedge X)$ Here I think I can't go any further because, both could be correct.</p> <p>Thus, I move to the X,</p> <p>$X:(\lnot X\wedge Y\wedge Z)\vee(\lnot Y\wedge Z\wedge X)\vee(\lnot Z\wedge Y\wedge X)$ Here again we cancel out two of them for the same reason like $Y$.</p> <p>so, $X:(\lnot Z\wedge Y\wedge X)$</p> <p>And here I just tried if $X$ is true then, $Y$ and $x$ are true which shows contradiction in $Y$ so $X$ is a liar as well and thus $Y$ is the truth teller?</p> <p>Now, my question is whether this was correct, and if anyone can show me an alternative shorter/faster way to solve this? Thanks in advance.</p>
<p>If X says the truth, then Y and Z lie. Contradiction.</p> <p>If Z says the truth, then X, Y and Z lie. Since this implies that X, Y and Z say the truth (because the number of liars can not be $1$, $2$ or $3$) and what they say can not happen at once, this is a contradiction.</p> <p>So only Y can say the truth. I can not find any contradiction in this case.</p>
<p>I like both the answers posted before mine, but if you want an algebraic approach to this kind of puzzles--one that requires almost no thinking--you proceed as follows. </p> <p>"If $Z$ is truthful, $X$, $Y$, and $Z$ lie" is translated into</p> <p>$$ Z \leftrightarrow (\neg X \wedge \neg Y \wedge \neg Z) \enspace. $$</p> <p>Simplifying, we get $\neg Z \wedge (X \vee Y)$. Then, "If $X$ is truthful, one of $X$, $Y$, $Z$ lies" simplifies to</p> <p>$$ X \leftrightarrow (X \wedge Y) $$</p> <p>when taking $\neg Z$ into account. Further manipulation yields $\neg X \vee Y$, which combined with $\neg Z \wedge (X \vee Y)$ gives $\neg X \wedge Y \wedge \neg Z$, which implies $Y$'s statement.</p> <p>The puzzle is well-posed because it has exactly one solution. </p>
stack-exchange-preferences_train_13
stack-exchange-preferences
<p>So I bought this keyboard. Armaggeddon Black Hornet MKA-3 mechanical gaming keyboard. Here's the link to it.</p> <p><a href="http://armaggeddon.net/gaming-keyboards/black-hornet-black/" rel="nofollow">http://armaggeddon.net/gaming-keyboards/black-hornet-black/</a></p> <p>They provide Windows drivers so my it works nice on my PC. I use both Linux and Mac OS at my workplace, it works great with my Linux without any configuration but surprisingly not functioning well with my Mac. Although I don't use mac very, I still want to be able to use my keyboard when I have to use Mac sometimes.</p> <p>Here's what happened, I plugged in the USB, reboot to Mac, can't type password at the login screen, I plugged in my apple keyboard, and logged in. The system detected my new keyboard, asked me to press the key right to the left shift key, after I pressed it for several times, it says the keyboard is not recognised and I have to choose one manually. </p> <p>So I chose US standard layout, but the key mappings are all messed up. I mean you have 8 when you type 1, and you see 's' when you press space.</p> <p>All my other keyboards are working fine, I want to ask is there anyway in mac you can manually 'program' the key mappings, or what should I do to make it work. </p> <p>Here's some a list of wrong key mappings.</p> <pre><code>1 = 8 2 = 9 3 = 0 4 = 'Enter' 5 = 'Not Sure' 6 = 'Back space' 'Backspace' = \ ' = q , = 4 . = n p = f a = d i = b </code></pre> <p>Thanks for any help.</p>
<p>From the <a href="http://growl.info/documentation/faq-new.php" rel="nofollow">Growl FAQ</a> page:</p> <blockquote> <p><strong>How do I disable the update checker in 1.2.2 and below?</strong></p> <p>The update checker in Growl 1.2.2 and below will run automatically every 24 hours. The update checker in 1.2.2 admittedly is not great, and is one of the reasons that Growl is now in the App Store. </p> <p>For those who wish to continue to run Growl 1.2.2, you can do so but will likely benefit from disabling the update checker. </p> <p>To disable the update checker, follow these steps:<br> - Open System Preferences<br> - Click on Growl<br> - Click on the About tab at the top<br> - Please make sure that you are using 1.2.2. If you are not, please update to 1.2.2 available <a href="http://growl.info/downloads" rel="nofollow">here</a><br> - Uncheck "Check for updates automatically"<br> - Close System Preferences, you are done</p> </blockquote> <p>Since the older version is going to become less compatible over time I would honestly suggest just paying the $4 and upgrading to the latest version that integrates all Growl notifications into message centre, even for apps that don't support message centre.</p>
<p>I just met this issue too. I downloaded and built version 2.1.1 using Xcode 4.6.3; this took a while as I needed to download/install a number of applications first (Xcode, command-line tools, Mercurial etc) and follow the build instructions carefully. Being a software developer it wasn't too hard, but it took me much more than $3.99 worth of time to do it. It was interesting though. If it is compatible with the licence terms, I would consider distributing my build for free: does anyone know if that is legitimate?</p>
stack-exchange-preferences_train_14
stack-exchange-preferences
<pre><code>String date = jsonobject.getString("needbydate"); DateFormat df = new SimpleDateFormat("MMM/dd/yyyy"); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ"); Date startDate = sdf.parse(date); String needbydate = df.format(startDate).toString()+""; </code></pre> <h2>What is happening::</h2> <ul> <li><strong>At the start</strong></li> </ul> <p><code>date</code>=<code>2014-12-17T21:37:00+00:00</code></p> <ul> <li><strong>At the end</strong></li> </ul> <p><code>needbydate</code>= Dec/18/2014</p> <p><code>17</code> is changed to <code>18</code> .... What wrong am i doing in conversion</p> <hr> <h2>EDIT:</h2> <pre><code> String date=jsonobject.getString("needbydate"); DateFormat df = new SimpleDateFormat("MMM/dd/yyyy",Locale.ENGLISH); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss",Locale.ENGLISH); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); Date startDate; startDate = sdf.parse(date); needbydate = df.format(startDate).toString()+""; </code></pre>
<p>Your date formats are using the system default time zone. That's okay for your input, because it specifies the UTC offset explicitly - but for your output, you've just got a date. So it's showing you the date that that point in time occurred in your system time zone.</p> <p>You need to think about what time zone you <em>want</em> it to be - and whether that's affected by a non-zero offset in your input. You can use <a href="http://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html#setTimeZone-java.util.TimeZone-"><code>DateFormat.setTimeZone</code></a> to set the time zone to be used on output. (For example, should 2014-12-17T21:37:00-05:00 show as December 18th (UTC) or December 17th (source time zone)?)</p> <p>You should also be using <code>HH</code> in your input format instead of <code>hh</code>, as it's clearly a 24-hour value rather than a 12-hour value.</p>
<h2>With the help of JonSkeet resolved this ... Complete solution ...here</h2> <pre><code> String date=jsonobject.getString("needbydate"); DateFormat df = new SimpleDateFormat("MMM/dd/yyyy",Locale.ENGLISH); df.setTimeZone(TimeZone.getTimeZone("UTC")); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss",Locale.ENGLISH); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); Date startDate; startDate = sdf.parse(date); needbydate = df.format(startDate).toString(); </code></pre>
stack-exchange-preferences_train_15
stack-exchange-preferences
<p>I have a folder with an ever growing list of .log files. Whats a quick way to remove all *.log files from a folder using PHP?</p> <p>thankyou</p>
<p>Just use the built-in function <code>zip</code> - </p> <p>like in</p> <pre><code>for letters in zip('hello', 'apple', 'green', 'paint', 'sting'): print letters </code></pre> <p>zip is a built-in that does just that: combine one element of each iterable in a tuple, for each iteration.</p> <p>Running the above example, you have:</p> <pre><code>&gt;&gt;&gt; for letters in zip('hello', 'apple', 'green', 'paint', 'sting'): ... print letters ... ('h', 'a', 'g', 'p', 's') ('e', 'p', 'r', 'a', 't') ('l', 'p', 'e', 'i', 'i') ('l', 'l', 'e', 'n', 'n') ('o', 'e', 'n', 't', 'g') </code></pre>
<p>Use the <code>zip</code> function that takes several lists (iterables) and yields tuples of corresponding items:</p> <pre><code>zip(*string_list) </code></pre> <p>yields (successively)</p> <pre><code>[('h', 'a', 'g', 'p', 's'), ('e', 'p', 'r', 'a', 't'), ('l', 'p', 'e', 'i', 'i'), ('l', 'l', 'e', 'n', 'n'), ('o', 'e', 'n', 't', 'g')] </code></pre>
stack-exchange-preferences_train_16
stack-exchange-preferences
<p>I have 251 images that are 128x128 in size; I need to create one big image that includes them all tiled together.</p> <p>The image will be 32128x32128 in size if all goes well (Paint.NET says it will be 3.8GB in size, fun times)</p> <p>I need to do this systematically, with a tool or a script since I might have to do this a few times - it's very tiresome to do by hand. I have programming skills, so if the solution requires that, then no problem.</p> <p>If your idea does not work for such a big image but would work with a part of the images, then I'd like to hear about it anyway.</p>
<p>Try <a href="http://www.imagemagick.org" rel="noreferrer">ImageMagick</a>, a command-line image editor. Its <strong>montage</strong> command can help you tile your images together. For more info about <code>montage</code>:</p> <ul> <li><a href="http://www.imagemagick.org/Usage/montage/" rel="noreferrer">http://www.imagemagick.org/Usage/montage/</a></li> <li><a href="http://www.imagemagick.org/script/montage.php" rel="noreferrer">http://www.imagemagick.org/script/montage.php</a></li> </ul> <p>Here's an example that tiles 100 PNG files in a folder together (10 images down, 10 images across). </p> <pre><code>montage *.png -geometry +0+0 -tile 10x10 all.png </code></pre> <p>where</p> <p><strong>all.png</strong> is the output file name</p> <p><code>-geometry +horizontalSpacing+verticalSpacing</code><br> <code>-tile COLSxROWS</code> </p> <p>Result: <img src="https://i.stack.imgur.com/RxEWB.png" alt="enter image description here"></p>
<p>There are a few programs that will do this for you. The smallest one that comes to mind is John's Background Switcher. </p>
stack-exchange-preferences_train_17
stack-exchange-preferences
<p>I have an issue with filling blank cells of a column.</p> <p>I have 4 Column headings in A, B, C, D.</p> <p>I am trying to create macro to fill blank cells for dynamic data as per attached Data able wherein cell value in Column D is randomly filled and blanked.. Blank cell value needs to filled based on value mentioned in Column A..</p> <p>I have created the macro but it's working to fill the blank with above value only and not getting the exact result..</p> <p>Can someone please help...</p> <p><a href="https://i.stack.imgur.com/Yk0dR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yk0dR.png" alt="Data" /></a></p> <p>Below result is expected from coding...</p> <p><a href="https://i.stack.imgur.com/uSEQE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uSEQE.png" alt="Result" /></a></p> <p>Below is the macro which I have created</p> <pre><code>Sub FillblankCells() lr = Cells.Find(&quot;*&quot;, Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row With Range(&quot;D2:D&quot; &amp; lr) .SpecialCells(xlBlanks).FormulaR1C1 = &quot;=R[-1]C&quot; .Value = .Value End With End Sub </code></pre>
<p>A dictionary is probably overkill, but this should work.</p> <pre><code>Sub x() Dim lr As Long, r As Range Dim oDic As Object lr = Cells.Find(&quot;*&quot;, Cells(1, 1), xlFormulas, xlPart, xlByRows, xlPrevious, False).Row Set oDic = CreateObject(&quot;Scripting.Dictionary&quot;) 'store column A for each entry in D For Each r In Range(&quot;D2:D&quot; &amp; lr).SpecialCells(xlCellTypeConstants) oDic(r.Offset(, -3).Value) = r.Value Next r 'retrieve each column A for blanks in D For Each r In Range(&quot;D2:D&quot; &amp; lr).SpecialCells(xlCellTypeBlanks) r.Value = oDic(r.Offset(, -3).Value) Next r End Sub </code></pre>
<p>You can sort the list before using your formula. Something like this might work:</p> <pre><code>Sub FillblankCells() 'Declarations. Dim RngList As Range Dim DblColumnQuote As Double Dim DblColumnBuyerName As Double 'Setting. Set RngList = Range(&quot;A1:D1&quot;) DblColumnQuote = 1 DblColumnBuyerName = 4 'Resetting RngList. Set RngList = Range(RngList, RngList.End(xlDown)) 'Sorting RngList. With RngList.Parent.Sort .SortFields.Clear .SortFields.Add Key:=RngList.Columns(DblColumnQuote), _ SortOn:=xlSortOnValues, _ Order:=xlDescending, _ DataOption:=xlSortNormal .SortFields.Add Key:=RngList.Columns(DblColumnBuyerName), _ SortOn:=xlSortOnValues, _ Order:=xlAscending, _ DataOption:=xlSortNormal .SetRange RngList .Header = xlYes .MatchCase = False .Orientation = xlTopToBottom .SortMethod = xlPinYin .Apply .SortFields.Clear End With 'Filling the blank cells of the Buyer Name column in RngList. With RngList.Columns(DblColumnBuyerName) .SpecialCells(xlBlanks).FormulaR1C1 = &quot;=R[-1]C&quot; .Value = .Value End With End Sub </code></pre>
stack-exchange-preferences_train_18
stack-exchange-preferences
<p><strong>Does Promise.all() run in sequential or parallel in Javascript?</strong></p> <p>For Example:</p> <pre class="lang-js prettyprint-override"><code> const promises = [promise1(), promise2(), promise3()] Promise.all(promises) .then(data =&gt; { // whatever }); </code></pre> <p>Does <code>promise1()</code> execute and resolve before moving onto promise2() or does <code>promise1()</code>, <code>promise2()</code>, and <code>promise 3()</code> all run in parallel at the same time? I would assume like Node, Javascript in the browser to be single threaded thus they don't run in parallel?</p>
<p>Javascript is a single threaded application. However, asynchronous calls allow you to not be blocked by that call. This is particularly useful when making REST API calls. For example your <code>promise1()</code> can make a REST API call and before it waits for the results, another REST API call can be made from <code>promise2()</code>. This pseudo-parallelism is thus achieved by not waiting on API servers to do the tasks and fire multiple such calls to either same or different API endpoints in parallel. This allows your code to continue executing that parts that are not dependent on resolution of the promises.</p> <p>So yes, <code>promise1()</code>, <code>promise2()</code> and <code>promise3()</code> can be said to be running in parallel in that respect. And there is a chance that <code>promise2()</code> gets resolved before <code>promise1()</code> and so on. The function <code>Promise.all()</code> waits for all the promises provided to it to fulfill or at least one of them to fail.</p> <p>Learn more about Javascript event loops in this <a href="https://www.youtube.com/watch?v=cCOL7MC4Pl0" rel="noreferrer">video</a> by Jake Archibald.</p>
<p><code>Promise.all</code> does not make your promises run in parallel.<br /> <code>Promise.all</code> does not make your promises run at all.<br /> What <code>Promise.all</code> does, is just waiting for all the promises to complete.</p> <p>The line of code that actually executes things is this one:</p> <pre class="lang-js prettyprint-override"><code>const promises = [promise1(), promise2(), promise3()] </code></pre> <p>Assuming that your promises make HTTP calls:</p> <p><code>promise1()</code> is executed -&gt; 1 HTTP call going on<br /> <code>promise2()</code> is executed -&gt; 2 HTTP calls going on<br /> <code>promise3()</code> is executed -&gt; 3 HTTP calls going on</p> <p>then after a while, in undetermined order, these promises complete.</p> <p>These 3 HTTP calls could complete in the same time, but in your code, you will have 3 sequential completition. For this reason, you can use <code>Promise.all</code> to assure that your callback is executed only when all of your promises complete.</p> <p>Remember that there's a limit on the amount of parallel HTTP connections you can have inyour environment, look at this: <a href="https://stackoverflow.com/a/985704/7327715">https://stackoverflow.com/a/985704/7327715</a></p>
stack-exchange-preferences_train_19
stack-exchange-preferences
<p>I feel as if this question must have been asked before, but I simply cannot find a similar question.</p> <p>I have a very simple file format:</p> <pre><code>Header 1: &lt;multiline text&gt; Header 2: &lt;multiline text&gt; Header 3: &lt;multiline text&gt; </code></pre> <p>where the (arbitrarily-named) headers each end with a colon, followed by text that is indented with spaces.</p> <p>I'd like to, for example, pick out the text under a particular header, e.g. "Header 2". The most obvious thing to try is <code>grep</code>, but I can only match certain lines and output a fixed number of context lines with that. I also looked at using <code>sed</code>, like so:</p> <pre><code>sed -ne '/Header 2:/,$p' </code></pre> <p>but of course this prints out everything up to the end of the file. </p> <p>EDIT: In an actual use-case, I won't necessarily know what header follows "Header 2", if there even is one (it could be the last one in the file).</p>
<p>With awk:</p> <pre><code>awk '!/^ /&amp;&amp;/:$/{p=0}p;/^Header 2:$/{p=1}' file </code></pre> <p>How does it work:</p> <ul> <li>This block <code>!/^ /&amp;&amp;/:$/{p=0}</code> means: If you find a line that does not begin with a space and ends with a colon ":", then set the flag <code>p</code> to zero</li> <li>This block <code>p;</code> means: if the flag has a non-zero value, then print the current line</li> <li>This block <code>/^Header 2:$/{p=1}</code> means: If you find a line that matches <code>Header 2</code>, then set the flag <code>p</code> to <code>1</code>.</li> </ul> <p>This works, because variables that are not initialized have a zero value.</p>
<p>Or with <code>sed</code></p> <pre><code>sed -n '/Header 2:/,/Header/{/Header/!p}' file </code></pre>
stack-exchange-preferences_train_20
stack-exchange-preferences
<p>Like I said, this code works in PowerShell version 2, but not in PowerShell version 5.</p> <pre><code>function wait { $compte = 0 Write-Host "To continue installation and ignore configuration warnings type [y], type any key to abort" While(-not $Host.UI.RawUI.KeyAvailable -and ($compte -le 20)) { $compte++ Start-Sleep -s 1 } if ($compte -ge 20) { Write-Host "Installation aborted..." break } else { $key = $host.ui.rawui.readkey("NoEcho,IncludeKeyup") } if ($key.character -eq "y") {Write-Host "Ignoring configuration warnings..."} else {Write-Host "Installation aborted..." }} </code></pre>
<p>The <a href="https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/read-host" rel="nofollow noreferrer">official</a> documentation or <code>Read-Host -?</code> will tell that it's not possible to use <code>Read-Host</code> in that manner. There is no possible parameter to tell it to run with some kind of timeout.</p> <p>But there are <a href="https://stackoverflow.com/questions/150161/waiting-for-user-input-with-a-timeout">various</a> other <a href="https://stackoverflow.com/questions/16964542/powershell-wait-input-for-10-seconds">questions</a> detailing how to do this in PowerShell (usually utilizing C#).</p> <p>The idea seems to be to check whenever the user pressed a key using <code>$Host.UI.RawUI.KeyAvailable</code> and check that for the duration of your timeout.</p> <p>A simple working example could be the following:</p> <pre><code>$secondsRunning = 0; Write-Output "Press any key to abort the following wait time." while( (-not $Host.UI.RawUI.KeyAvailable) -and ($secondsRunning -lt 5) ){ Write-Host ("Waiting for: " + (5-$secondsRunning)) Start-Sleep -Seconds 1 $secondsRunning++ } </code></pre> <p>You could use <code>$host.UI.RawUI.ReadKey</code> to get the key that was pressed. This solution probably would not be acceptable if you need more complex input than a simple button press. See also:</p> <ul> <li><a href="https://technet.microsoft.com/en-us/library/ff730938.aspx" rel="nofollow noreferrer">Windows PowerShell Tip of the Week - Pausing a Script Until the User Presses a Key</a></li> <li><a href="https://blogs.technet.microsoft.com/heyscriptingguy/2013/09/14/powertip-use-powershell-to-wait-for-a-key-press/" rel="nofollow noreferrer">PowerTip: Use PowerShell to Wait for a Key Press (Hey, Scripting Guy!)</a></li> </ul>
<p>Seth, thank you for your solution. I expanded on the example you provided and wanted to give that back to the community.</p> <p>The use case is a bit different here - I have a loop checking if an array of VMs can be migrated and if there are any failures to that check the operator can either remediate those until the checks clear or they can opt to "GO" and have those failing VMs excluded from the operation. If something other than GO is typed state remains within the loop.</p> <p>One downside to this is if the operator inadvertently presses a key the script will be blocked by Read-Host and may not be immediately noticed. If that's a problem for anyone I'm sure they can hack around that ;-)</p> <pre><code>Write-Host "Verifying all VMs have RelocateVM_Task enabled..." Do { $vms_pivoting = $ph_vms | Where-Object{'RelocateVM_Task' -in $_.ExtensionData.DisabledMethod} if ($vms_pivoting){ Write-Host -ForegroundColor:Red ("Some VMs in phase have method RelocateVM_Task disabled.") $vms_pivoting | Select-Object Name, PowerState | Format-Table -AutoSize Write-Host -ForegroundColor:Yellow "Waiting until this is resolved -or- type GO to continue without these VMs:" -NoNewline $secs = 0 While ((-not $Host.UI.RawUI.KeyAvailable) -and ($secs -lt 15)){ Start-Sleep -Seconds 1 $secs++ } if ($Host.UI.RawUI.KeyAvailable){ $input = Read-Host Write-Host "" if ($input -eq 'GO'){ Write-Host -ForegroundColor:Yellow "NOTICE: User prompted to continue migration without the blocked VM(s)" Write-Host -ForegroundColor:Yellow "Removing the following VMs from the migration list" $ph_vms = $ph_vms | ?{$_ -notin $vms_pivoting} | Sort-Object -Property Name } } } else { Write-Host -ForegroundColor:Green "Verified all VMs have RelocateVM_Task method enabled." } } Until(($vms_pivoting).Count -eq 0) </code></pre>
stack-exchange-preferences_train_21
stack-exchange-preferences
<p>I'm trying to install Slim on my local LAMP server on Ubuntu only I get stuck at second base. From my tutorial and various documentation found online:</p> <p>You now have access to the composer command. Sure enough if I go to the terminal and enter:</p> <pre><code>$ composer Composer version b474944155429eb4cce186c746d55287ee6bb3f4 Usage: [options] command [arguments] </code></pre> <p>The next step is to specify Slim as a required package for your app. This can be accomplished, via a composer.json file within the root of your project.</p> <p>Where is the root of my project? I thought it would be</p> <pre><code>/var/www/slim </code></pre> <p>I've tried adding composer.json to:</p> <pre><code>/var/www/slim </code></pre> <p>and stood in /slim define an index.php script with:</p> <pre><code>&lt;?php require 'vendor/autoload.php'; $app = new \Slim\Slim(); $app-&gt;get('/hello/:name', function ($name) { echo "Hello, $name"; }); ?&gt; </code></pre> <p>Go to </p> <pre><code>http://localhost/var/www/slim </code></pre> <p>and the browser returns:</p> <p>Warning: require(vendor/autoload.php): failed to open stream: No such file or directory in /var/www/slim/index.php on line 2</p> <p>Fatal error: require(): Failed opening required 'vendor/autoload.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/slim/index.php on line 2</p>
<p>Well, there seems to be more then one question in your post, but regardless ...</p> <ol> <li>"Where is the root of my project?"</li> </ol> <p>The root of your project should be in <code>/var/www</code> if you haven't changed your hosts / Apache settings.</p> <p>Then on to your 2nd question, which I will take the liberty to rephrase :)</p> <ol start="2"> <li><p>"How to create your web App, and include the composer-installed packages inside?" go to your respective web-root directory, likely in your case <code>/var/www</code> and in it create <code>"index.php"</code>. Then, there, in the console, run the command:</p> <pre><code>composer install </code></pre></li> </ol> <p>This should install the packages defined in your composer.json, which should in the same web root dir.<br> If everything went OO, you will have in the following a new directory: <code>/var/www/vendor</code></p> <p>Now, go to your web-root directory and create your <code>index.php</code> <em>and in it, in the beginning add the following lines</em>:</p> <pre><code>require 'vendor/autoload.php'; // to load all the packages installed with composer, not only slim. If //composer was run in the right directory and w/o problems of course :) $app = new \Slim\Slim(); // to instantiate Slim script instance and assign it to the pointer $app $app-&gt;get('/hello/:name', function ($name) { echo "Hello, $name"; }) //to create your 1st route ... </code></pre>
<p>you need to run </p> <pre><code>composer install </code></pre> <p>from terminal. After that, add</p> <pre><code>$app-&gt;run(); </code></pre> <p>in index.php.</p>
stack-exchange-preferences_train_22
stack-exchange-preferences
<p>Lithium has most negative electrode potential still its reaction with water is less vigorous than that of sodium </p>
<p>You can't just take the electrode potential as if that's going to correspond to the rate in which something is going to react. For example, why do you think that aluminum is so stable in atmospheric conditions versus iron? Aluminum forms a stable oxide layer that serves to protect it against further reaction, while iron oxide is weak, adheres poorly and is and porous. There are numerous factors which affect a rate of reaction, and they vary in different situations.</p> <p>Calculating rates of reaction is a very complicated thing, and it's usually easier / more accurate to just determine the Arrhenius parameters experimentally and use those.</p>
<p>Reactivity with water in the sequence Li (mp=180.5C), Na (mp=98C), K (mp=63.5 C) is dictated by melting point of the metal. Electrode potential dictates the equilibrium constant between M and M+. With voltages >1 the reverse reaction can be ignored. </p> <p>Here is what happens when alkali metal reacts with water from phisical perspective. It contacts water, temperature rises to 100C (boiling point of water). Lithium remains solid, whereas Na and K turn into a liquid. This liquid spreads on the surface of water creating a large area of contact. Lithium remains solid. LiOH forms on it's surface and prevents further reaction. LiOH does dissolve in water (that is why Li react with water and Al doesn't), but it takes time. At the same time both sodium and potassium leak out of the protective shell of oxides/hydroxides.</p>
stack-exchange-preferences_train_23
stack-exchange-preferences
<p>I would like to find an object. There is only one object with the variable x=10. Is it possible? I hope you get what I try to explain... :)</p> <pre><code>if (any object of the class X .getValue() == 10) ... </code></pre> <p>Class X</p> <pre><code> public int getValue(){ return x; } </code></pre>
<p>This can partially work, until you try to do much with the array. There's a very good chance the subarrays will be fully read into memory if you subset, or you'll get an error.</p> <p>An important consideration here is that the underlying code is written assuming the arrays are typical in-memory numpy arrays. Cost of random access is very different for mmapped arrays and in memory arrays. In fact, much of the code here is (at time of writing) in Cython, which may not be able to work with more exotic array types.</p> <p>Also most of this code can change at any time, as long as the behaviour is the same for in-memory arrays. This has personally bitten me when some I learned some code I worked with was doing this, but with <code>h5py.Dataset</code>s for the underlying arrays. It worked surprisingly well, until a bug fix release of <code>scipy</code> completely broke it.</p>
<p>This works without any problems.</p>
stack-exchange-preferences_train_24
stack-exchange-preferences
<p>im noob using react query and react with typesript, i don't know how to solve this: <em>React Hook &quot;useQuery&quot; is called in function &quot;onSubmit&quot; that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter</em>.</p> <pre><code>export const LoginForm = () =&gt; { const { handleSubmit, control } = useForm&lt;IFormInput&gt;({defaultValues: defaultValues, resolver: yupResolver(schema)}); const onSubmit = ({email, password}: IFormInput) =&gt; { const {data, isLoading, error} = useQuery('loginUser', () =&gt; startLogin({email, password})); console.log(data); console.log(error); }; ... ... ... } </code></pre> <pre><code> export const startLogin = ({email, password}: IFormInput) =&gt; ( axios.post(loginEndpoint, {email, password}).then(res =&gt; res.data) ); </code></pre>
<p>I’d like to add that for logging in a user, you probably don’t want a query but a mutation. Logging someone in is likely not a GET request and it has side effects (it makes the user be logged in), so <code>useMutation</code> is for that. You can define <code>useMutation</code> on the top of your functional component (in accordance with the rules of hooks) and invoke the returned <code>mutate</code> function in the callback:</p> <pre><code>export const LoginForm = () =&gt; { const { mutate, isLoading } = useMutation(variables =&gt; startLogin(variables)) const onSubmit = ({email, password}: IFormInput) =&gt; { mutate({ email, password }) }; </code></pre>
<p>Your <code>onSubmit()</code> doesn't look like being <strong>executed</strong> inside a React Component, and you also need to rename your component to a PascalCase.</p> <p>In most cases, rename your component to PascalCase will fix the issue.</p>
stack-exchange-preferences_train_25
stack-exchange-preferences
<p>I'm working on this code that iterates over a string--that is actually a string representing an integer in this case--and fills an array with each "digit" of the string. So string <code>"350"</code> would result in an array with elements <code>{3,5,0}</code>. Here is the code:</p> <pre><code> #include &lt;stdlib.h&gt; #include &lt;iostream&gt; using namespace std; int main() { int arr[5]; string test = "10000"; for(unsigned int i = 0; i&lt;test.length(); i++) { char c = test[i]; cout &lt;&lt; c &lt;&lt; endl; arr[i] = c; } //printing the array for testing for (int i = 5 - 1; i &gt;= 0; i--) cout &lt;&lt; arr[i]; return 0; } char c = test[i]; arr[i] = c; } return 0; } </code></pre> <p>The issue is that array that results from this is <code>{49,48,48,48,48}</code>. I have no idea why its doing that and where I have gone wrong with the code. Why is it adding the numbers 49 and 48, and how can I fix this?</p> <p>Also if it helps anyone, here is a link to a stepper running through the code: <a href="http://pythontutor.com/visualize.html#code=%0A%23include%20%3Cstdlib.h%3E%0A%23include%20%3Ciostream%3E%0A%0A%0Ausing%20namespace%20std%3B%0A%0A%0A%0Aint%20main%28%29%20%7B%0A%20%20int%20arr%5B5%5D%3B%0A%09string%20test%20%3D%20%2210000%22%3B%0A%20%20for%28unsigned%20int%20i%20%3D%200%3B%20i%3Ctest.length%28%29%3B%20i%2B%2B%29%20%7B%0A%20%20%20%20char%20c%20%3D%20test%5Bi%5D%3B%20//this%20is%20your%20character%0A%20%20%20%20arr%5Bi%5D%20%3D%20c%3B%0A%7D%0A%09return%200%3B%0A%7D%0A%0A%0A&amp;cumulative=false&amp;curInstr=19&amp;heapPrimitives=false&amp;mode=display&amp;origin=opt-frontend.js&amp;py=cpp&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false" rel="nofollow noreferrer">http://pythontutor.com/visualize.html#code=%0A%23include%20%3Cstdlib.h%3E%0A%23include%20%3Ciostream%3E%0A%0A%0Ausing%20namespace%20std%3B%0A%0A%0A%0Aint%20main%28%29%20%7B%0A%20%20int%20arr%5B5%5D%3B%0A%09string%20test%20%3D%20%2210000%22%3B%0A%20%20for%28unsigned%20int%20i%20%3D%200%3B%20i%3Ctest.length%28%29%3B%20i%2B%2B%29%20%7B%0A%20%20%20%20char%20c%20%3D%20test%5Bi%5D%3B%20//this%20is%20your%20character%0A%20%20%20%20arr%5Bi%5D%20%3D%20c%3B%0A%7D%0A%09return%200%3B%0A%7D%0A%0A%0A&amp;cumulative=false&amp;curInstr=19&amp;heapPrimitives=false&amp;mode=display&amp;origin=opt-frontend.js&amp;py=cpp&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false</a></p>
<p>What you see in your array are the ascii for the characters your insert. Here is what you should do to convert your character to an integer: <code>arr[i] = atoi(&amp;c);</code></p>
<p>You created <code>arr</code> as an array of integers, thus by assigning character elements to it you implicitly cast them to an integer. When you do this, the ASCII value of the characters is printed, instead of the characters themselves. You should use an array of characters instead. </p> <pre><code>char arr[5]; </code></pre>
stack-exchange-preferences_train_26
stack-exchange-preferences
<p>I am learning open CV and for the same i was trying few programs. I am referring to this link. <a href="http://docs.opencv.org/modules/contrib/doc/facerec/tutorial/facerec_gender_classification.html" rel="nofollow">http://docs.opencv.org/modules/contrib/doc/facerec/tutorial/facerec_gender_classification.html</a></p> <p>I am using visual studio 10 to run the same, and i think somewhere i have messed up with some configuration. I am facing the same problem in couple of more programs (picked from same source) , </p> <p>The error which i get is as follows:- </p> <blockquote> <p>1>main.obj : error LNK2019: unresolved external symbol "int __cdecl cv::waitKey(int)" (?waitKey@cv@@YAHH@Z) referenced in function __catch$_main$0</p> <p>1>main.obj : error LNK2019: unresolved external symbol "class cv::Mat __cdecl cv::subspaceReconstruct(class cv::_InputArray const &amp;,class cv::_InputArray const &amp;,class cv::_InputArray const &amp;)" (?subspaceReconstruct@cv@@YA?AVMat@1@ABV_InputArray@1@00@Z) referenced in function __catch$_main$0</p> </blockquote> <p>..... (more such unresolved external symbol error)</p> <blockquote> <p>1>main.obj : error LNK2001: unresolved external symbol "public: virtual bool __thiscall cv::_InputArray::empty(void)const " (?empty@_InputArray@cv@@UBE_NXZ)</p> <p>1>c:\users\isenses\documents\visual studio 2010\Projects\gender_classification\Debug\gender_classification.exe : fatal error LNK1120: 37 unresolved externals</p> <p>1></p> <p>1>Build FAILED.</p> <p>1>Time Elapsed 00:00:00.36</p> <p>========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========</p> </blockquote> <p>My Project Properties are as follows:-</p> <p>Properties->Configuration Properties ->Debugging->command arguments->C:\Users\isenses\Documents\Visual Studio 2010\Projects\gender_classification\csv.txt</p> <p>Properties->Configuration Properties ->VC++ directories->Include directories->(added C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib &amp;<br> C:\openCV_2.4\opencv\build\x86\vc10\lib)</p> <p>C/C++->general->additional include directories (added include path of openCV ie:- C:\openCV_2.4\opencv\build</p> <p>Linker->General--- Enable incremental linking=no</p> <p>Additional Library directories=C:\Program Files %28x86%29\Microsoft Visual Studio 10.0\VC\lib</p> <p>C:\openCV_2.4\opencv\build\x86\vc10</p> <p>linker->System---SubSystem= /SUBSYSTEM:CONSOLE</p> <p>Linker->Input--- additional dependencies= wsock32.lib opencv_contrib2411d.lib</p> <p>opencv_calib3d2411d.lib</p> <p>opencv_ml2411d.lib</p> <p>opencv_objdetect2411d.lib</p> <p>Thank you.</p>
<p>Thanks to @miki i was able to build the file successfully. The solution to my problem was:-</p> <ol> <li>adding proper additional Dependencies in properties->linker->input.</li> <li>Adding libraries path in windows environment variables.</li> <li>I had not used proper additional dependencies as pointed by @miki and as quoted by him "well you also have to link opencv_coreXXX,opencv_highguiXXX, opencv_imgprocXXX etc... (with trailing "d" if in debug) in your Linker->Input--- additional dependencies"</li> </ol> <p>Thanks again</p>
<p>I want to add an answer to this because I feel the documentation on the opencv site needs to be updated. I followed the tutorial and could not get the library to link. After many permutations I decided to look at the .lib files. My problem was quite simple. The lib files in the opencv tutorial are not complete. Specifically my lib directory includes three more lib files. I added three extra lib files to visual studio linker and the external symbol problem was solved. I am unsure why this is the case because I was only trying to use functions contained within the core module. Anyway, hopefully this will help someone.</p> <p>I am using opencv 3 and visual studio 2017.</p>
stack-exchange-preferences_train_27
stack-exchange-preferences
<p>At the beginning of the episode, the Silence didn't want the Doctor to speak his name (like all of the other aliens in the sky). So why did they help get rid of those aliens (particularly the Daleks) at the end of the episode?</p>
<p>It is true that the Silence did not want the Doctor to speak his name. However, the Silents in this episode were associated with the Papal Mainframe, which was revealed to be an intergalactic peacekeeping force. By assisting the Doctor in his efforts to stave off the enemy forces, they also managed to keep him from saying his name - as long as the forces were being held back (which they were, as it was stated that all of the races besides the Daleks either burned or fled), the Doctor would not have had to have risked the planet's destruction by releasing the Time Lords and inviting an assault by the alien forces, who would have attacked as soon as he spoke his name.</p>
<p>The Silent's only concern was the safety of Trenzalore. Once Tasha Lem was certain of The Doctor's intentions, she would command the Silents to assist The Doctor in any way they could.</p>
stack-exchange-preferences_train_28
stack-exchange-preferences
<p>Without brackets, seems it is not possible to have haproxy select use_backend based on <code>true and (a or b)</code></p> <p>For example, I want to <code>use_backend ClusterA if allowed_src and (method_a or path_b)</code>. Regardless if I invert the conditions before/after <code>and</code>, I am left with a way to hit the backend with a single true value instead of requiring <code>allowed_src</code> and one of either <code>method_a</code> or <code>path_b</code>.</p> <p>*updated example such that all three ACL are distinct.</p>
<p>The answer Vadim wrote achieves what you asked initially. To match your updated question, you could use the following logic:</p> <pre><code>acl allowedsrc src 123.123.123.123 acl mypath path_beg /path_a use_backend ClusterA if allowedsrc mypath || allowedsrc METH_POST </code></pre> <p>Since you didn't mention what you were trying to match with <strong>allowedsrc</strong> ACL, I'll assume you wanted to match certain IP address.</p> <p>Let me break down the whole logic to plain english.</p> <p>acl allowedsrc matches source IP 123.123.123.123</p> <p>acl mypath matches URLs that begins with <strong>/path_a</strong></p> <p>The last line means that request will be poined to <strong>ClusterA</strong> backend <strong>if</strong> source IP address was 123.123.123.123 <strong>and</strong> if URL was beginning with /path_a <strong>or</strong> if source IP address was 123.123.123.123 and HTTP method was POST.</p> <p>Instead of METH_POST, you can use different pre-defined ACLs. Check out <a href="https://cbonte.github.io/haproxy-dconv/1.8/configuration.html#7.4" rel="nofollow noreferrer">HAProxy's documentation</a> to see the complete list.</p>
<pre><code>acl allowedsrc ....... acl mypath path_beg /path_a /path_b use_backend ClusterA if allowedsrc mypath </code></pre>
stack-exchange-preferences_train_29
stack-exchange-preferences
<p>I plan on hiking the St-Jacques-de-Compostelle trail, starting in France and ending in Spain. To lower the costs, I would like to camp on my own outside.</p> <p><strong>Is it legal to camp outside in a small tent or bivy bag?</strong></p>
<p>As a french hiker often going camping, here is what I know. </p> <p>In France, camping is regulated by the law named « Camping, aménagement des parcs résidentiels de loisirs, implantation des habitations légères de loisirs et installation des résidences mobiles de loisirs et des caravanes » from the « décret n° 2015-1783 du 28 décembre 2015 relatif à la partie réglementaire du livre Ier du code de l'urbanisme et à la modernisation du contenu du plan local d'urbanisme ».</p> <p>Here is a link summarizing what you can / cannot do: <a href="https://www.lecampingsauvage.fr/legislation-et-reglementation/camping-sauvage-bivouac">https://www.lecampingsauvage.fr/legislation-et-reglementation/camping-sauvage-bivouac</a> (in French, but you can translate).</p> <p>This law makes the difference between a "bivouac" and "wild camping". "Bivouac" is the term employed to nominated hikers that put a small tent for the night, as they may be too far from civilization. "Wild camping" however is more associated with people owning cars and putting a tent closer to the city, avoid hotel costs. </p> <p>Camping is especially forbidden in some protected areas such as in some National Parks, but each park has its own regulation. If you go to the Pyrénées, there are the National N03, Regional park R43 and R46 (see the map in the previous link).</p> <p>In N03, "wild camping" is forbidden, and "bivouac" is authorized between 7PM to 9AM the next day, if you are at more than one hour walk to the park limits, or road access.</p> <p>In R43 (Parc naturel régional des Pyrénées catalanes), "wild camping" is forbidden, but "bivouac" is okay close to the refuges or along the GRs (the hiking ways). </p> <p>In R46 (Parc naturel régional des Pyrénées ariégeoises), there are no specific legislation, so you have to follow the national regulation.</p> <p>It is in general forbidden close to the roads, and you should know that any bit of land belongs to someone. The law says that you need the approval of the owner to put your tent there, who may live miles away. </p> <p>That is the official legislation, but as a camper myself, I can tell you that no one will put you in jail for putting a tent for the night in a forest, just avoid the places where it is explicitly written on a sign. However, you should not leave any trace of your camp when you leave, so remember to take your garbage with you, and organize yourself for the "restrooms". </p> <p>Have a safe trip!</p>
<p>As for France,</p> <p>You are not -in theory- allowed to stay on private property without the owner's consent. /!\ forests might be private...</p> <p>That's the theory, in practice if you set up a tent in the woods for a night (but don't step in homes' garden though ^^), don't set the forest on fire and leave it as clean as when you arrived, nobody would care.</p>
stack-exchange-preferences_train_30
stack-exchange-preferences
<p>We are using AVPlayer to play an HLS stream, but we have a new requirement that we need to supply a custom HTTP header field to identify the client from the backend team. Is it possible to add custom HTTP header field to AVPlayer requests without resorting to hacking HLS playlist file to use a custom protocol?</p>
<p>I found this answer somewhere from the web. I am using it in my test app, but since this is an undocumented feature, there is a risk that apple may reject. But technically, this is an option.</p> <pre><code>NSMutableDictionary* headers = [NSMutableDictionary dictionary]; [headers setObject:@"SOF" forKey:@"X-REQ-HEADER-TEST"]; AVURLAsset* asset = [AVURLAsset URLAssetWithURL:myUrl options:@{@"AVURLAssetHTTPHeaderFieldsKey": headers}]; AVPlayerItem* item = [AVPlayerItem playerItemWithAsset:asset]; [avPlayerObj replaceCurrentItemWithPlayerItem:item]; </code></pre> <p>Usage of AVURLAssetHTTPHeaderFieldsKey is the one in question.</p>
<p>I spent weeks looking for a way to do this officially. For anyone else looking for an approach that would work for both requests and responses for the playlist and chunk requests, the only way I was able to find that worked was by passing the playback request through a reverse proxy on the device itself, which allows you to intercept the request, add headers, send it to the real server, and then extract the headers from the response before returning it to the AVPlayer. </p> <p>I made a simple example project (with lots of comments and documentation) here: <a href="https://github.com/kevinjameshunt/AVPlayer-HTTP-Headers-Example" rel="nofollow noreferrer">https://github.com/kevinjameshunt/AVPlayer-HTTP-Headers-Example</a></p>
stack-exchange-preferences_train_31
stack-exchange-preferences
<p>I try to compile a basic code with buildozer. At first run it installs depencies and fail. Later runs it just fails.</p> <p>any help needed desperately.</p> <p>Thanks in advance.</p> <pre><code>BUILD FAILED /home/mbp/.buildozer/android/platform/android-sdk-21/tools/ant/build.xml:645: The following error occurred while executing this line: /home/mbp/.buildozer/android/platform/android-sdk-21/tools/ant/build.xml:651: null returned: 127 Total time: 1 second form/python-for-android/dist/sozluk/private/lib/python2.7/site-packages/kivy/modules/inspector.pyo ... ..... ... assets/private.mp3: /home/mbp/build/.buildozer/android/platform/python-for-android/dist/sozluk/private/lib/python2.7/lib-dynload/_io.so assets/private.mp3: /home/mbp/build/.buildozer/android/app/sitecustomize.pyo assets/private.mp3: /home/mbp/build/.buildozer/android/app/main.pyo assets/private.mp3: /home/mbp/build/.buildozer/android/app/sozluk.kv Traceback (most recent call last): File "build.py", line 412, in &lt;module&gt; make_package(args) File "build.py", line 336, in make_package subprocess.check_call([ANT, arg]) File "/usr/lib64/python2.7/subprocess.py", line 542, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['ant', 'debug']' returned non-zero exit status 1 # Command failed: /usr/bin/python build.py --name DenemeSozluk --version 1.2.0 --package bs.sozluk.sozluk --private /home/mbp/build/.buildozer/android/app --sdk 14 --minsdk 8 --orientation sensor debug </code></pre> <p>Fedora release 20 (Heisenbug) I found following question about very similar problem on ubuntu. It might not be distro specific. <a href="https://stackoverflow.com/questions/22145721/build-error-while-converting-python-file-into-apk-using-buildozer">Build Error while converting python file into apk using buildozer</a></p> <pre><code>Linux localhost.localdomain 3.12.9-301.fc20.x86_64 #1 SMP Wed Jan 29 15:56:22 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux </code></pre> <p>Full output: <a href="http://paste.fedoraproject.org/82968/41173791/" rel="nofollow noreferrer">http://paste.fedoraproject.org/82968/41173791/</a></p>
<p><a href="http://jsfiddle.net/rhLvV/" rel="nofollow"><strong><em>DEMO</em></strong></a></p> <pre><code>.timeline-panel { background-color:red!important; } .timeline &gt; li &gt; .timeline-panel:after { border-left:14px solid red!important; border-right: 0 solid red!important; } .timeline &gt; li.timeline-inverted &gt; .timeline-panel:after { border-left:14px solid #fff!important; border-right-width: 14px!important; border-left-width: 0!important; } </code></pre> <p><em>You don't need <code>!important</code> if you ordered your rules properly and/or modified the values accordingly, but it's there so the rule is shown at the top of the page.</em></p>
<p>Are you sure that CSS is getting used. I know that some versions of IE doesn't like/understand the parent/child operator ">"</p> <p><a href="http://forums.techguy.org/web-design-development/596886-css-operator-question.html" rel="nofollow">http://forums.techguy.org/web-design-development/596886-css-operator-question.html</a></p> <p>Even Windows Explorer preview can't handle them</p> <p>Change it to:</p> <p>.timeline li .timeline-panel { ... }</p> <p>and see if it is used.</p>
stack-exchange-preferences_train_32
stack-exchange-preferences
<p>Suppose you have a bunch of tea bags in a box, initially in pairs, like these:</p> <p><a href="https://i.stack.imgur.com/ZT9Zzm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZT9Zzm.jpg" alt="enter image description here"></a></p> <p>Let us suppose the box initially contains only joined pairs of tea bags, say $N_0$ of them (thus making for a total of $2N_0$ tea bags).</p> <p>Every time you want to make yourself a tea, you put a hand in the box and randomly extract a tea bag. Sometimes you will find yourself with a joined pair, in which case you split it, take one for your tea, and put the other back into the box. If you instead extract a single tea bag (which was already split before), you just take it.</p> <p>Now if you ever happened to be in a similar situation, you will probably have noticed that after a while you will almost always extract single tea bags and seldolmly find doubles (which is not surprising of course). The question is, <strong>what exactly is the probability $p_k$ of extracting a single tea bag, after $k$ tea bags have already been picked?</strong></p> <p>Suppose for this problem that each time there is an equal probability of extracting <em>any</em> of the tea bags, regardless of them being joined with another or not, so that after the first step (in which we necessarily extract and split a double) the probability of extracting a single bag is $p_1=\frac{1}{2N_0-1}$.</p> <p>It is relatively easy, just by computing the values of $p_k$ for the first $k$s, to see that the answer to the problem is quite nice: $$p_k = \frac{k}{2N_0 -1}.$$ How can we prove this?</p> <hr> <p>An interesting variation of the problem is asking what happens if we instead consider the picking of a pair as a single event (instead that as two, as in the above considered case). With this assumption the previous formula does not hold, as computing the first values of $p_k$ shows: $$ p_1 = \frac{1}{N_0}, \\ p_2 = \frac{2(N_0-1)}{N_0^2} .$$</p>
<p>Say you select tea bag $i$. Your question, then, is what is the probability that teabag $\hat i$ has previously been selected. (where $\forall i$, teabag $i$ was initially paired with $\hat i$). thus we are asked to compute the probability that a given teabag survived the selection process conditioned on the fact that we know some other specified teabag did survive. the conditioning just requires us to start with a sample of $2N_0-1$ and then the probability that a given teabag survived $k$ selections is $$\frac {2N_0-2}{2N_0-1}\times \frac {2N_0-3}{2N_0-2}\times \cdots\times \frac {2N_0-(k+1)}{2N_0-k}=\frac {2N_0-(k+1)}{2N_0-1}$$</p> <p>The answer you seek is the compliment of this, hence $$1-\frac {2N_0-(k+1)}{2N_0-1}=\frac k{2N_0-1}$$</p>
<p>I found a simple way to deal with this. I get Barry's Tea, which does come in paired bags. Furthermore, each bag is $3$ grams of tea, where the vast majority of teabags one sees are $2$ grams each. I get the Gold Blend and the Irish Breakfast. </p> <p>I take both teabags and put them in the mug and then pour boiling water on them. And wait five minutes. More flavor. Oh, I do separate the two teabags, because I later pull them out with tweezers and squeeze them with teabag tongs to get most of the liquid out. That would be clumsy with joined bags. </p> <p><a href="http://www.barrystea.ie/" rel="nofollow">http://www.barrystea.ie/</a> </p> <p><a href="http://www.englishteastore.com/tea-bag-squeezer.html" rel="nofollow">http://www.englishteastore.com/tea-bag-squeezer.html</a> </p> <p>Afterthought: Barry's is the first tea that I have regularly purchased that comes with no string. It is entirely possible that teabags with strings are typically two grams and teabags without them are typically three grams. Oh, and I sometimes get a very nice pu-erh, loose leaves, from a nearby shop called Far Leaves. </p> <p><a href="http://www.farleaves.com/" rel="nofollow">http://www.farleaves.com/</a> </p> <p><a href="http://www.farleaves.com/collections/puer-teas" rel="nofollow">http://www.farleaves.com/collections/puer-teas</a></p>
stack-exchange-preferences_train_33
stack-exchange-preferences
<p>I am using MaterializeCSS to create a select 'dropdown' menu. On a Mac laptop the dropdown is working fine (tested in Safari and FireFox, and in IE and Chrome through browserling.com). However, when I browse the website from a Windows computer (IE and Chrome) I always have to double click to toggle the dropdown. I don't understand why this issue happens. I would appreciate if anyone can point to a specific issue with the code as set out below:</p> <pre><code> &lt;div class="dropdown-div"&gt; &lt;div class="input-field"&gt; &lt;select&gt; &lt;option value="1" class="dropdown-text"&gt;&lt;a class="dropdown-text-default" data-url="#General"&gt;General&lt;/a&gt;&lt;/option&gt; &lt;option value="2"&gt;&lt;a class="dropdown-text" data-url="#Option1"&gt;Option1&lt;/a&gt;&lt;/option&gt; &lt;option value="3"&gt;&lt;a class="dropdown-text" data-url="#Option2"&gt;Option2&lt;/a&gt;&lt;/option&gt; &lt;option value="4"&gt;&lt;a class="dropdown-text" data-url="#Option3"&gt;Option3&lt;/a&gt;&lt;/option&gt; &lt;option value="5"&gt;&lt;a class="dropdown-text" data-url="#Option4"&gt;Option4&lt;/a&gt;&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/js/materialize.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $('select').material_select(); }); &lt;/script&gt; </code></pre> <p>Please find the documentation from MaterializeCSS <a href="https://materializecss.com/select.html" rel="nofollow noreferrer">here</a>.</p>
<p>This is a regression bug in Chrome 73. To solve the problem use following code: (This is the only solution I could find.)</p> <pre><code>$('select').material_select(); document.querySelectorAll('.select-wrapper').forEach(t =&gt; t.addEventListener('click', e=&gt;e.stopPropagation())) </code></pre>
<p>Here's a hack, using jQuery</p> <pre><code>$('.select-dropdown').trigger("click"); </code></pre> <p>I've had the same issue on materialize selects, I couldn't find a patch anywhere.</p> <p>So the theory is, If it works with a double click, then trigger another click on this instance.</p> <p>Here's the context I applied it for my application</p> <p>I have a select drop down like:</p> <pre><code>&lt;div class="input-field ingredient-unit"&gt; &lt;select name="" id="ingredient-unit"&gt; &lt;option value="gr" selected&gt;gr&lt;/option&gt; &lt;option value="kg" &gt;kg&lt;/option&gt; &lt;option value="cups" &gt;cups&lt;/option&gt; &lt;option value="ml" &gt;ml&lt;/option&gt; &lt;option value="L" &gt;L&lt;/option&gt; &lt;option value="tsp" &gt;tsp&lt;/option&gt; &lt;option value="Tbsp" &gt;Tbsp&lt;/option&gt; &lt;option value="pcs" &gt;pcs&lt;/option&gt; &lt;/select&gt; &lt;label for="ingredient-unit"&gt;&lt;/label&gt; &lt;/div&gt; </code></pre> <p>To get the value of this select, I have a javascript function like:</p> <pre><code>$('.add-ingredient-button').click(function(){ // due to a materialize css bug with chrome, take two clicks to activate the given selection // we hack this by triggering another click on the #ingredient-unit instance here $('.select-dropdown').trigger("click"); //then we get the dropdown instance, everything else can be done with jQuery const ingredientUnit = M.FormSelect.getInstance($('#ingredient-unit')); // we need to grab information from all those boxes const name = $('#ingredient-name').val(); const value = $('#ingredient-value').val(); const unit = ingredientUnit.getSelectedValues(); console.log(name,value,unit); }); </code></pre> <p>When the button with class .add-ingredient-button is pressed, we want to get the ingredient name, value and unit. The unit is in a materialize select instance.</p> <p>So the function is triggered when we click on .add-ingredient-button, and we 'manually' trigger another click on the select instance, which effectively picks the unit that the user had already selected.</p> <p>I'm not sure why this error occurred, and I can't really tell you why this is working. But it works.</p> <p>I hope it helps!</p>
stack-exchange-preferences_train_34
stack-exchange-preferences
<p>In Web Forms for Marketers, I have a few fields that I am using to pass values to the pipeline processors and to append CSS code to the form. </p> <p>I don't want these fields to appear on the form. How can I mark a field to be invisible? Right now I am doing this via CSS, but I am quite sure there must be a better way to do so. </p> <p>Thanks! </p>
<p>You can extend the Single Line Text field class and change the container CSS class to your own CSS class that hides the field and label. You can also add value to that field when the form is loaded through the querystring.</p>
<p>I believe there is a Hidden Field type in WFFM. Could you use that?</p>
stack-exchange-preferences_train_35
stack-exchange-preferences
<p>I have a Trek 7200 (Alpha aluminum frame) and it has two water bottle holder mountings, the top braze-on on the seat tube seems to have broken from over-tightening and has sunk into the frame. These braze-ons are recessed into the body of the frame tubes, as if they were somehow attached from the inside. </p> <p>Is it possible to repair this braze-on? Is it something some super-glue could help with, or am I looking at a permanent wound?</p>
<p>Bosses in aluminum frames are typically <a href="http://www.parktool.com/blog/repair-help/water-bottle-fittings">rivet nuts</a>, aka "pem nuts", which have a head that should be too large to slip back into the frame.</p> <p>For your frame, it sounds like the <a href="http://www.parktool.com/blog/calvins-corner/fishing-for-the-boss">Park Tool directions for securing bosses on carbon frames</a> should work equally well. The top mount on the seat-tube is also the easiest to repair using this method, so you're in luck.</p>
<p>No matter what you do: if you have loose metal parts hanging around inside your tubes, then your first priority is to get them out. </p> <p>The Park Tools link in the other answer has some good ideas. My first thought would be to get a metal nut or threaded sleeve and epoxy it in place. </p> <p>But the simplest option is to not fix it at all, and just use a clamp to secure the bottle cage. Your bike shop might have clamps specifically for bottle cages, otherwise use a hose clamp from a hardware or auto parts store.</p>
stack-exchange-preferences_train_36
stack-exchange-preferences
<p>Is it possible to convert byte* to Array^ in C++/CX?</p> <p>Currently I accomplish this by copying each value, which I know is <strong>not</strong> space/performance efficient.</p> <p>My current implementation is :</p> <pre><code>Array&lt;byte&gt;^ arr = ref new Array&lt;byte&gt;(byteCount); for (int i = 0; i &lt; byteCount; i++) { arr[i] = *(bytes + i); } </code></pre>
<p>There's an array constructor for that (<a href="http://msdn.microsoft.com/en-us/windows/apps/hh441578">MSDN</a>): <code>Array(T* data, unsigned int size);</code></p> <p>So in your case, simply do: <code>Array&lt;byte&gt;^ arr = ref new Array&lt;byte&gt;(bytes, byteCount);</code></p> <p><a href="http://msdn.microsoft.com/en-us/windows/apps/hh700131">This</a> is a great article on C++/CX and WinRT array patterns.</p>
<p>Yes you can also use</p> <pre><code>Array&lt;byte&gt;^ t = ref new Platform::Array&lt;byte&gt;(byteReaded); CopyMemory(t-&gt;Data, buff, byteReaded); </code></pre> <p>for copy or for access using </p> <pre><code>t-&gt;Data </code></pre>
stack-exchange-preferences_train_37
stack-exchange-preferences
<p>Hi guys i follow this <a href="https://raspberrypi.stackexchange.com/questions/499/how-can-i-resize-my-root-partition">How can I resize my / (root) partition?</a> and work .</p> <p>But it's possible to make an automate bash script?</p> <p>I have to pass 501760 when ask for start number.</p> <p>Thank you</p>
<p>Make sure python modules python-smbus and i2c-tools are installed.</p> <p>Try checking that /etc/modules file contains the i2c related kernel modules (i2c-bcm2708 &amp; i2c-dev)</p> <p>Also check the bus you are using. Adafruits i2c use default bus but it may differ in some cases so try to edit Adafruit_CharLCDPlate class and replace the busnum parameter at line 425 with the one you are using. To check your bus use command: sudo i2cdetect -y 1 (bus format is like 0x00) (For old Rasp. Pi Model B 256MB command is sudo i2cdetect -y 0)</p>
<p>Yes. I have had that working, using a 2 line and a 4 line LCD display.</p> <p>I don't have a write-up available yet, the Raspberry Pi Spy article explains how to configure I2C and I have some source code on github (for the 4 line version) <a href="https://github.com/penguintutor/learnelectronics/tree/master/quiz" rel="nofollow">https://github.com/penguintutor/learnelectronics/tree/master/quiz</a> </p>
stack-exchange-preferences_train_38
stack-exchange-preferences
<p>My xampp in ubuntu was working just fine until suddenly it stopped working and when I reinstall it and start it through the command line, it is showing me this error "opt/lampp/bin/mysql.server: 260: kill: No such process" after starting. </p> <p>I am also facing this error on my localhost/phpmyadmin</p> <pre><code>MySQL said: Documentation Cannot connect: invalid settings. mysqli_real_connect(): (HY000/2002): No such file or directory Connection for controluser as defined in your configuration failed. mysqli_real_connect(): (HY000/2002): No such file or directory phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server. </code></pre>
<p>The error is most likely permission issue, there is no error log from mysql, even though <code>sudo chmod -R /opt/lampp</code> worked but I don't think making <code>/opt/lampp/</code> 777 is a good idea, so I made some improvements to the original answer:</p> <ol> <li><code>sudo chmod 777 /opt/lampp/var/</code></li> <li><code>sudo chown -R mysql:mysql /opt/lampp/var/mysql/</code></li> <li><code>sudo lampp restart</code></li> </ol>
<p>I fixed by (<code>ERROR : opt/lampp/bin/mysql.server: 260: kill: No such process</code>)</p> <pre><code>sudo chmod -R 777 /opt/lampp sudo service mysql stop sudo /opt/lampp/lampp restart </code></pre>
stack-exchange-preferences_train_39
stack-exchange-preferences
<p><a href="https://en.wikipedia.org/wiki/Vulkan_(API)">From the wiki</a>: "the Vulkan API was initially referred to as the 'next generation OpenGL initiative' by Khrono", <a href="https://en.wikipedia.org/wiki/OpenGL#Vulkan">and that it is</a> "a grounds-up redesign effort to unify OpenGL and OpenGL ES into one common API that will not be backwards compatible with existing OpenGL versions".</p> <p>So should those now getting into graphics programming be better served to learn Vulkan instead of OpenGL? It seem they will serve the same purpose.</p>
<p>If you're getting started now, and you want to do GPU work (as opposed to always using a game engine such as Unity), you should definitely start by learning Vulkan. Maybe you should learn GL later too, but there are a couple of reasons to think Vulkan-first.</p> <ol> <li><p>GL and GLES were designed many years ago, when GPUs worked quite differently. (The most obvious difference being immediate-mode draw calls vs tiling and command queues.) GL encourages you to think in an immediate-mode style, and has a lot of legacy cruft. Vulkan offers programming models that are much closer to how contemporary GPUs work, so if you learn Vulkan, you'll have a better understanding of how the technology really works, and of what is efficient and what is inefficient. I see lots of people who've started with GL or GLES and immediately get into bad habits like issuing separate draw calls per-object instead of using VBOs, or even worse, using display lists. It's hard for GL programmers to find out what is no longer encouraged.</p></li> <li><p>It's much easier to move from Vulkan to GL or GLES than vice-versa. Vulkan makes explicit a lot of things that were hidden or unpredictable in GL, such as concurrency control, sharing, and rendering state. It pushes a lot of complexity up from the driver to the application: but by doing so, it gives control to the application, and makes it simpler to get predictable performance and compatibility between different GPU vendors. If you have some code that works in Vulkan, it's quite easy to port that to GL or GLES instead, and you end up with something that uses good GL/GLES habits. If you have code that works in GL or GLES, you almost have to start again to make it work efficiently in Vulkan: especially if it was written in a legacy style (see point 1).</p></li> </ol> <p>I was concerned at first that Vulkan is much harder to program against, and that while it would be OK for the experienced developers at larger companies, it would be a huge barrier to indies and hobbyists. I posed this question to some members of the Working Group, and they said they have some data points from people they've spoken to who've already moved to Vulkan. These people range from developers at Epic working on UE4 integration to hobbyist game developers. Their experience was that getting started (i.e. getting to having one triangle on the screen) involved learning more concepts and having longer boilerplate code, but it wasn't too complex, even for the indies. But after getting to that stage, they found it much easier to build up to a real, shippable application, because (a) the behaviour is a lot more predictable between different vendors' implementations, and (b) getting to something that performed well with all the effects turned on didn't involve as much trial-and-error. With these experiences from real developers, they convinced me that programming against Vulkan is viable even for a beginner in graphics, and that the overall complexity is less once you get past the tutorial and starting building demos or applications you can give to other people.</p> <p>As others have said: GL is available on many platforms, WebGL is a nice delivery mechanism, there's a lot of existing software that uses GL, and there are many employers hiring for that skill. It's going to be around for the next few years while Vulkan ramps up and develops an ecosystem. For these reasons, you'd be foolish to rule out learning GL entirely. Even so, you'll have a much easier time with it, and become a better GL programmer (and a better GPU programmer in general), if you start off with something that helps you to understand the GPU, instead of understanding how they worked 20 years ago.</p> <p>Of course, there's one option more. I don't know whether this is relevant to you in particular, but I feel I should say it for the other visitors anyway.</p> <p>To be an indie games developer, or a game designer, or to make VR experiences, you don't need to learn Vulkan or GL. Many people get started with a games engine (Unity or UE4 are popular at the moment). Using an engine like that will let you focus on the experience you want to create, instead of the technology behind it. It will hide the differences between GL and Vulkan from you, and you don't need to worry about which is supported on your platform. It'll let you learn about 3D co-ordinates, transforms, lighting, and animation without having to deal with all the gritty details at once. Some game or VR studios only work in an engine, and they don't have a full-time GL expert at all. Even in larger studios which write their own engines, the people who do the graphics programming are a minority, and most of the developers work on higher-level code.</p> <p>Learning about the details of how to interact with a GPU is certainly a useful skill, and one that many employers will value, but you shouldn't feel like you have to learn that to get into 3D programming; and even if you know it, it won't necessarily be something you use every day.</p>
<p>You should be learning OpenGL first, as that is the standard for Graphics, across so many platforms.</p> <p>Even if there is a newer library, understanding the basics, and working with a language that is used all over the industry, is very important... Especially since Vulkan wont be used in Big Companies for awhile, since.</p> <ol> <li><p>No one wants to adapt right away and end up screwing themselves over with a non-stable Framework/Library.</p></li> <li><p>They would need to hire / re-train their current Open-GL programmers, and there is no need to.</p></li> </ol> <hr> <p>Also, I've heard that OpenGL, and Vulkan, aren't exactly the same. I hear Vulkan is a lower level API, and closer to machine code, than OpenGL.</p> <p>This answer I just found seems to have a lot of great info</p> <p><a href="https://gamedev.stackexchange.com/questions/96014/what-is-vulkan-and-how-does-it-differ-from-opengl">https://gamedev.stackexchange.com/questions/96014/what-is-vulkan-and-how-does-it-differ-from-opengl</a></p> <hr> <p>Another thing that is something to consider is the issue that happened back with OpenGL 1.</p> <p>OpenGL 1 to OpenGL 2 had MAJOR changes, and since many people were using OpenGL1, and hardware supported it, there is heavy backwards compatibility needed to be implemented in some applications/engines, and that sometimes is really painful for the devs to keep supporting it.</p> <p>Besides the support, the language shifted so much, that you had to learn new stuff.</p> <p>This has happened with frameworks such as JavaFX (from 1.x to 2.x) and Play! Framework (Also 1.x to 2.x). Complete changes to the framework, meaning we have to relearn... everything...</p> <hr> <p>So essentially what you should do is wait until Vulkan is STABLE. That means wait until Probably the 2.0 patch. IT doesn't mean you cannot learn about the basics of Vulkan, but just know this might change. I would assume that a group like Kronos would provide a very stable API from the start, especially since there are multiple Nvidia and AMD engineers working on Vulkan, including a high up Nvidia person overseeing the project apparently, as well as The base of Mantle; however, like any software, we the coders will see how well it works from the start, but many are wary and waiting to see what happens.</p>
stack-exchange-preferences_train_40
stack-exchange-preferences
<p>I've been trying several implementations for sending events using the Google Analytics library v2 but none are sending data to my Analytics dashboard.</p> <p>The simplest implementation that should be working is</p> <pre><code>EasyTracker.getTracker().sendEvent("Social", "Opened Share App", "Clicked", (long) 1); EasyTracker.getInstance().dispatch(); </code></pre> <p>Other things like activities and screens get tracked just fine.</p> <p>I've also tried by using:</p> <pre><code>mGaInstance = GoogleAnalytics.getInstance(this); mGaTracker = mGaInstance.getTracker("UA-XXXXXX-X"); </code></pre> <p>And then using that tracker to send events, but this doesn't send data either. I've also read about events needing over 24 hours to register. This really seems weird since everything else in analytics is basically instant, is this true though? I'm not finding any confirmation of this.</p> <p>With debugging turned on in analytics.xml the following appears in logcat</p> <pre><code>putHit called Sending hit to store PowerSaveMode terminated. Thread[GAThread,5,main]: dispatch running... User-Agent: GoogleAnalytics/2.0 (Linux; U; Android 4.1.1; nl-nl; HTC One X Build/JRO03C) Host: ssl.google-analytics.com GET /collect?ul=nl-nl&amp;ev=1&amp;ht=1370875183876&amp;sr=720x1280&amp;a=72697680&amp;aid=com.package.android&amp;ea=Opened+Share+App&amp;cid=8e7dc0b4-d03c-4ccb-8bed-f549f16a1b1d&amp;ec=Social&amp;av=0.1.1&amp;v=1&amp;t=event&amp;el=Clicked&amp;an=My+App&amp;tid=UA-XXXXXX-X&amp;_u=.C&amp;_v=ma1b5&amp;cd=com.package.android.ActivityAbout&amp;qt=39&amp;z=103 HTTP/1.1 </code></pre> <p>So it seems to be dispatching just fine right?</p>
<p>Ok, so the answer was quite silly. I went back to fixing this around 23:45 and was still struggling to find an answer. Then the clock turned 00:07 and I refreshed... Tadaa, 73 events popped up for the previous day... </p> <p><img src="https://i.stack.imgur.com/FrMDF.png" alt="Events in analytics"></p> <p>So yea, if other people have the same issue. The first snippet of code in my question works just fine.</p> <pre><code>EasyTracker.getTracker().sendEvent("Social", "Opened Share App", "Clicked", (long) 1); EasyTracker.getInstance().dispatch(); </code></pre> <p>Calling the dispatch method isn't really needed, nor does it help with showing up anything earlier either. Just use the default value or you can read about it more <a href="https://developers.google.com/analytics/devguides/collection/android/v2/dispatch" rel="nofollow noreferrer">here</a>.</p>
<p><strong>Use Google Analytics Social Interaction API</strong> </p> <pre><code>Tracker tracker = EasyTracker.getInstance(getActivity() .getApplicationContext()); tracker.send(MapBuilder.createSocial("Twitter", "Tweet", "https://developers.google.com/analytics").build()); </code></pre> <p><a href="https://developers.google.com/analytics/devguides/collection/android/v2/social" rel="nofollow">Google Analtyics Social Interactions - Android SDK</a></p>
stack-exchange-preferences_train_41
stack-exchange-preferences
<p>My app crashes when I use fragments and its obviously related to the <code>GoogleMap</code> inside one of the fragments.</p> <p>I already changed the map fragment from <code>MapFragment</code> to <code>SupportMapFragment</code> but it didnt help.</p> <p>this is the Main page where all the fragments are (the <code>FragmentActivity</code>):</p> <pre><code>import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.view.View; public class Fragments extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_fragments); MainActivity fragment = new MainActivity(); FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction(); transaction.add(R.id.fragment_place, fragment); transaction.commit(); } public void onSelectFragment(View view) { Fragment newFragment; if (view == findViewById(R.id.add)) { newFragment = new Add(); } else if (view == findViewById(R.id.map)) { newFragment = new MainActivity(); } else { newFragment = new MainActivity(); } FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction(); transaction.replace(R.id.fragment_place, newFragment); transaction.addToBackStack(null); transaction.commit(); } } </code></pre> <p>the logcat:</p> <pre><code>09-30 15:03:19.257: W/dalvikvm(12895): threadid=1: thread exiting with uncaught exception (group=0x40ed5300) 09-30 15:03:19.265: E/AndroidRuntime(12895): FATAL EXCEPTION: main 09-30 15:03:19.265: E/AndroidRuntime(12895): java.lang.NoClassDefFoundError: com.google.android.gms.R$styleable 09-30 15:03:19.265: E/AndroidRuntime(12895): at com.google.android.gms.maps.GoogleMapOptions.createFromAttributes(Unknown Source) 09-30 15:03:19.265: E/AndroidRuntime(12895): at com.google.android.gms.maps.SupportMapFragment.onInflate(Unknown Source) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:284) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 09-30 15:03:19.265: E/AndroidRuntime(12895): at com.example.free.MainActivity.onCreateView(MainActivity.java:122) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:556) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1163) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.app.Activity.performStart(Activity.java:5018) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2210) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.app.ActivityThread.access$600(ActivityThread.java:142) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1208) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.os.Handler.dispatchMessage(Handler.java:99) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.os.Looper.loop(Looper.java:137) 09-30 15:03:19.265: E/AndroidRuntime(12895): at android.app.ActivityThread.main(ActivityThread.java:4931) 09-30 15:03:19.265: E/AndroidRuntime(12895): at java.lang.reflect.Method.invokeNative(Native Method) 09-30 15:03:19.265: E/AndroidRuntime(12895): at java.lang.reflect.Method.invoke(Method.java:511) 09-30 15:03:19.265: E/AndroidRuntime(12895): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 09-30 15:03:19.265: E/AndroidRuntime(12895): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:558) 09-30 15:03:19.265: E/AndroidRuntime(12895): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>and the fragment is kinda large so Ive pasted it on pastebin:</p> <p><a href="http://pastebin.com/G9MekK1Z" rel="nofollow">http://pastebin.com/G9MekK1Z</a></p> <p>Thanks for your assistance!</p>
<p>Closest gets the parent of your selector, this is already table tr, try this : </p> <pre><code> if ($(this).hasClass("selected_row")) { $(this).removeClass("selected_row"); } else { $(this).addClass("selected_row"); $(this).siblings().removeClass('selected_row'); } </code></pre>
<p>There is no need to add an onclick handler to every table row. Use event bubbling to your advantage. Use siblings to get the one that has the class if it exists. </p> <pre><code>$("table tbody").on("click", "tr", function() { var row = $(this); row.toggleClass("selected_row"); row.siblings("selected_row").removeClass("selected_row"); }); </code></pre>
stack-exchange-preferences_train_42
stack-exchange-preferences
<p>My (trekking) bike has 9 gears (9 sprocket wheels at the rear wheel / Shimano Acera). I just wanted to replace sprocket and chain. I correctly bought a 9-speed chain but the length is wrong. My old chain has 118 links and the newly bought chain 114 links.</p> <p>There are two reasons why I'm wondering whether I can still use the 114 link chain on my bike:</p> <ol> <li>because I have it already</li> <li>because 118 link 9-speed chains seem to be in short supply</li> </ol> <p>So, what happens if I just put the 114-link chain on the bike? I assume this will make it necessary to readjust the gearing. Or is this not possible at all?</p> <p>What are my options?</p> <hr /> <p>Bonus question: is there a qualitative difference between 114 and 118 links? Or is it just a different length and that's it?</p>
<p>Chainstay length, size of cogs, and drivetrain type, are the factors that dictate chain length.</p> <p>The type of drivetrain affects chain length because different group sets have different methods for measuring the correct length. It’s not necessarily as simple as putting the chain over the largest cogs and adding two links, anymore. If you were installing a whole new drivetrain, (or just chainring the size of either the cassette or chainrings) it would be best to look up the service instructions for how to properly measure chains on your system.</p> <p>Chainstay length is self explanatory- a bike with a longer distance between the rear axle and the bottom bracket will need a longer chain, all else being equal. On full suspension bikes, the chainstay is often longest in position of full travel, so that’s usually required to determine the appropriate chain length.</p> <p>Cog size also determines chain length. As you can tell from the traditional method, an improperly sized chain will have problems when you try to use certain gear combinations. On many modern drivetrains, the rear derailleur guide pulley is not concentric with the RD cage pivot, so chain length also affects the derailleur’s ability to track the curvature of the cassette. A major problem with running too short of a chain, is that shifting to larger cogs can damage the system. In theory, you can avoid damage by determining which rear cogs (if 1x) or which sprocket combinations are safe before riding (turning the cranks in a work stand, and watching the derailleur cage while carefully shifting from smaller cogs to larger ones) but that damage can happen quickly when you’re not thinking about it. I wouldn’t recommend riding like that unless you can eliminate that risk by locking out the larger cogs with the derailleur limit screws.</p> <p>My recommendation for you is to get the links necessary to run your chain at the correct length. It’s not uncommon in bike shops to need more than one packaged chain for a bike, because tandems, and recumbents, and many hybrids and beach cruisers, require longer chains than what comes in a single box. When we open two chains for one bike, we hold on to the remainder of the second one, so we don’t waste two complete chains on every such bike- we just cut the extra links from the extra 9 (or 8, etc) speed chain in the drawer, and connect them using a connecting pin or quick link as appropriate. If I were in your position, I would ask around at your local bike shops for a few links from a spare 9 speed chain, or, consider buying a second chain, taking the needed links from it, and keeping it around for the next time you need a few extra links of 9 speed chain.</p>
<blockquote> <p>My (trekking) bike has 9 gears (9 sprocket wheels at the rear wheel / Shimano Acera). I just wanted to replace sprocket and chain. I correctly bought a 9-speed chain but the length is wrong. My old chain has 118 links and the newly bought chain 114 links</p> </blockquote> <p>Most likely the new chain is way too short.</p> <p>A trekking bike sounds like a bike that:</p> <ul> <li>Has a triple crankset with 48-tooth big ring as opposed to tiny &quot;big&quot; rings typical of MTBs</li> <li>Has decent length chainstays as opposed to road bikes that often have ridiculously short chainstays</li> <li>Has a rear cassette where the big sprocket is perhaps 32, perhaps 34 teeth.</li> </ul> <p>For example, I have a touring bike with 48-tooth big ring, 11-30 cassette and 47 cm chainstays. The <a href="http://www.machinehead-software.co.uk/bike/chain_length/chainlengthcalc.html" rel="nofollow noreferrer">chain length calculator</a> tells that it requires 116-link chain. I could have put a 11-32 cassette or 50-tooth big ring there but either choice would necessitate a 118-link chain and finding such a 8-speed chain with low shipping costs from an online store that has something else I may want to order at the same time is hard, especially if I limit myself to only Shimano chains as those have the superior reinforced pin based connecting system. Of course there are 138-link chains but such chains are so expensive I am unwilling to pay the price. In contrast, 116-link 8-speed chains can be easily bought from many different online stores. So that's why I limit my big ring and big sprocket sizes.</p> <p>Unfortunately, we live in a world where those with the money buy predominantly bikes from either the &quot;MTB&quot; category (where the biggest chainring is so small that it's wonder why the bikes make any forward progress at all) and &quot;road&quot; category (where the chainstay is so short that anything larger than 23 mm tire will jam as it touches the seat tube). Those with the money won't purchase bikes from the &quot;reasonable&quot; category. So we are in a world where it's all too easy to buy a chain that is too short, but very hard to buy a chain that's the right size for a decent bike.</p>
stack-exchange-preferences_train_43
stack-exchange-preferences
<blockquote> <p>I'm going to be as forthcoming as I can be, Mr. Anderson.</p> </blockquote> <p>from The Matrix.</p>
<p>It means "willing to share information" about something. </p> <p>From NOAD:</p> <blockquote> <p><strong>forthcoming</strong> 2 • (of a person) willing to divulge information : <em>their daughter had never been forthcoming about her time in Europe</em>.</p> </blockquote>
<p>Definitions of <a href="http://dictionary.reference.com/browse/forthcoming" rel="nofollow">Forthcoming</a></p> <p>I would think that the meaning here is either </p> <blockquote> <p>"frank and cooperative; candid "In his testimony, the senator could have been more forthcoming."</p> </blockquote> <p>Or </p> <blockquote> <p>"friendly and outgoing; sociable."</p> </blockquote> <p>Depending on the context.</p>
stack-exchange-preferences_train_44
stack-exchange-preferences
<p>I've had the Huntsman for a while, and it's still confused me. The projectiles seem to be affected by gravity, most definitely. But sometimes, when I stretch out the bow, the arrow seems to barely make an arc (meaning straight line), while other times, it seems to just make an arc.</p> <p>There's also a bar that's shown as you pull the string back on the bow, what is this used for?</p>
<p>You need to pull back for 1 second to get a Full Length arrow off. If you pull back for more than 5 seconds, your hand starts to wobble and you will lose accuracy (I'm guessing this is what you are experiencing when you say that sometimes it doesn't go in a straight line)</p> <p>So in order to get a good shot off, you need to charge it for 1 second (which is what the charging bar shown is) and fire the arrow before it starts wobbling (which occurs 5 seconds after being fully charged)</p> <p>If you find yourself with a charged shot longer than 5 seconds for whatever reason, you can switch out your weapon to reset it, or better yet, press right click again to 'unload' the shot (does not waste ammo)</p> <p>No matter how you shoot it, the arrow is always affected by gravity, but even more so if you do not fully charge the shot (from memory the shot does less damage for shorter charge as well) so make sure you always charge for at least 1 second</p>
<p>The two things you have mentioned (variable arrow arc, bar shown as you pull string) are connected. The bar you see is the charge bar, same as with any sniper rifle. Pulling back the string by holding down <code>primary-fire</code> is your charge method, as opposed to rifles where you click once to zoom in. At no charge, arrows arc significantly and move rather slowly. At max charge, arrows fly almost straight much faster and do 2.4x damage. Arrows will headshot at any charge unless you let your aim get wobbly; you can reset the wobble with <code>alt-fire</code>.</p>
stack-exchange-preferences_train_45
stack-exchange-preferences
<p>Self-invoking anonymous function should be like</p> <pre><code>(function() { //.... })() </code></pre> <p>or</p> <pre><code>(function() { //.... }()) </code></pre> <p>But what is the difference between</p> <pre><code>(function() { //.... }) </code></pre> <p>What parameters will missing in the wrong one?</p> <pre><code>(function() { console.log('test'); $(".dropdown-menu").dropdown(); }) </code></pre>
<p>Check <a href="https://github.com/rails/rails/tree/master/activemodel" rel="nofollow">https://github.com/rails/rails/tree/master/activemodel</a> for more info:</p> <pre><code>require 'active_model' class TestValidator &lt; ActiveModel::Validator def validate(record) record.errors[:base] = "First and last can't be the same" if record.first.presence == record.last.presence end end class Person include ActiveModel::Model attr_accessor :first, :last validates_presence_of :first, :last validates_with TestValidator end p = Person.new(first: "Nick", last: "Nick") puts p.valid? # =&gt; false puts p.errors.full_messages # =&gt; First and last can't be the same p = Person.new(first: "Nick", last: "Doe") puts p.valid? # =&gt; true </code></pre>
<p>I came up with my own solution to this, what I was looking for was:</p> <pre><code>require 'active_model' class Person include ActiveModel::Validations attr_accessor :first, :last validate :first_does_not_equal_last def first_does_not_equal_last if @first == @last self.errors[:base] &lt;&lt; "First cannot be the same as Last" end end def initialize(first, last) @first = first @last = last end end </code></pre>
stack-exchange-preferences_train_46
stack-exchange-preferences
<p>I'm developping an android app using Zxing qr code But i have a probleme to make a rederction of the web search button to my database i'm make a modification in this ligne </p> <pre><code>final void openProductSearch(String upc) { Uri uri = Uri.parse("http://www.google." + LocaleManager.getProductSearchCountryTLD(activity) +"/m/products?q=" + upc + "&amp;source=zxing"); launchIntent(new Intent(Intent.ACTION_VIEW, uri)); } </code></pre> <p>But nothing it's happen </p>
<pre><code>Uri uri = Uri.parse("http://www.google." + LocaleManager.getProductSearchCountryTLD(activity) + "/m/products?q=" + upc + "&amp;source=zxing"); </code></pre> <p>change localhost by you IP address</p>
<p>if you have the zxing code inside your app , remove that part of the intent and do whatever you need to do with the data . you don't have to use the intents part .</p> <p>zxing has apache licence , so you are free to change the code, as long as you (always , even if you don't touch the code) leave the upper header of the code (with the disclaimer and such) .</p>
stack-exchange-preferences_train_47
stack-exchange-preferences
<p>I have run into a problem, I did solve it but I feel that it is pretty inefficient, which involves traversing through a Core Data (for iOS) entity hierachy of parent/children references to count the amount of items attached to certain entities.</p> <p>Let me be more specific. I have 2 types of entities: <code>Category</code> and <code>Attachment</code>.</p> <p>The <code>Category</code> entities are linked via parent/children references. The attachments are linked to <code>Categories</code> as a many-to-one (many attachments to one category).</p> <p>If I would like to count the amount of attachments that fall within the hierarchy of a given <code>Category</code>, is there a <code>NSFetchRequest</code> that I can do that is more efficient than this?</p> <pre class="lang-c prettyprint-override"><code>NSInteger count = 0; NSMutableArray *stack = [[NSMutableArray alloc] init]; [stack addObject:targetCategory]; while([stack count] &gt; 0) { Category *current = [stack lastObject]; [stack removeLastObject]; count += current.attachments.count; for (Category *cat in current.children) { [stack addObject:cat]; } } </code></pre> <p><code>targetCategory</code> is the root Category chosen.</p> <p>Thanks in advance.</p>
<p>If you need only to count objects, use <code>countForFetchRequest:error:</code> like the following:</p> <pre><code>NSError *err = nil; NSUInteger count = [moc countForFetchRequest:request error:&amp;err]; if(count == NSNotFound) { // Handle error } </code></pre> <p>Obviously, @MartinR's advice remains valid.</p>
<p><em>(It is risky to answer with "that is not possible", but)</em> I am quite sure that there is no fetch request that fetches or counts objects recursively. You have to traverse the hierarchy, either with a recursive method or as you did.</p>
stack-exchange-preferences_train_48
stack-exchange-preferences
<p>If you have a property:</p> <pre><code>public class Fred { public string UserName { set { userName=value; } } } </code></pre> <p>how do you use Rhino Mocks to check that</p> <pre><code>fred= new Fred(); fred.UserName="Jim"; </code></pre> <p>is called.</p> <pre><code>Expect.Call(mockFred.UserName).SetPropertyWithArgument("Jim"); </code></pre> <p>does not compile.</p>
<pre><code>public interface IFred { string UserName { set; } } [Test] public void TestMethod1() { IFred fred = MockRepository.GenerateMock&lt;IFred&gt;(); fred.UserName = "Jim"; fred.AssertWasCalled(x =&gt; x.UserName = "Jim"); } </code></pre>
<p>You should just be able to do a verify all on the property set</p> <pre><code>[TestClass] public class FredTests { [TestMethod] public void TestFred() { var mocker = new MockRepository(); var fredMock = mocker.DynamicMock&lt;IFred&gt;(); fredMock.UserName = "Name"; // the last call is actually to the set method of username LastCall.IgnoreArguments(); mocker.ReplayAll(); fredMock.UserName = "Some Test that does this."; mocker.VerifyAll(); } } public interface IFred { string UserName { set; } } </code></pre>
stack-exchange-preferences_train_49
stack-exchange-preferences
<p>I'm looking to pass data from a form into an iFrame, but I have a slight problem.</p> <ul> <li>The form page I can edit with no restrictions </li> <li>The page I send the data to <strong>I cannot edit</strong> unless its html or JavaScript </li> <li>The data needs to end up in an iframe within this page, which I can edit with no restrictions</li> </ul> <p>I'm incorporating a search function into a CMS system which is why I cannot edit the iframe's parent page, and why I am using iframes at all. </p> <p>At the moment the data sends to the parent page but is not picked up within the iframe, I am sending via the POST method.</p>
<pre><code>com.sun.lwuit.io.Storage.init("MobileApplication1"); if(com.sun.lwuit.io.Storage.isInitialized()) { com.sun.lwuit.io.Storage.getInstance().writeObject("MobileApplication1","My first string"); String myStr = (String)com.sun.lwuit.io.Storage.getInstance().readObject("MobileApplication1"); System.out.println(myStr); } else { System.out.println("Storage not initialized"); } </code></pre> <p>The above code will create a storage of name 'MobileApplication1', add an object 'My first string' and reads the string.</p>
<p>You can use J2ME record store as well and your record store will always have only 1 record.</p>
stack-exchange-preferences_train_50
stack-exchange-preferences
<p>Say I have a rotating disk #1, that is connected via an axle to disk #2 with a person on it. Disk #1 has a torque about the axle from the person via the applied force at the edge and it rotates CCW. The person &amp; Disk #2 would revolve around the axis with a CW direction.</p> <p>But how does the person move or get any torque to do so? The reaction of the applied force on the person would be cancelled by the friction force from Disk #2. Since they are at equal radi, the torques would cancel. The friction force on disk #2 would be cancelled from the axle force. However, there would be a net torque on disk #2. The total force x-direction of the system(disk #1, Disk #2 and person) would cancel as it is internal. The only torque would be to disk #2, yet the person revolves with the disk?</p> <p>What am I confusing or missing?</p> <p><a href="https://i.stack.imgur.com/T1aeH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T1aeH.jpg" alt="enter image description here" /></a></p>
<blockquote> <p>The reaction of the applied force on the person would be cancelled by the friction force from Disk #2</p> </blockquote> <p>That doesn't happen. We can consider the friction between the person and disk2 to be sufficient so that they don't slide. Therefore the person and disk2 can be considered a single solid object.</p> <p>When the person pushes on disk1, there is a force couple created. Disk 1 has a force in one direction (which create a torque), and the disk2/person object has a force in the other direction (which creates a torque in the other direction).</p> <p>Friction here couples the person to disk2, it does not cancel or eliminate the torque.</p> <blockquote> <p>But when i break them down, wouldn't friction and the reaction force from disk #1 cancel out on the person?</p> </blockquote> <p>No, the friction force must be smaller, so they don't cancel. Let's look closely at the friction force. It forms another couple, one part of the force is &quot;forward&quot; on the person (same direction the person is pushing disk 1), and the other part is &quot;backward&quot; on disk 2.</p> <p>This second part of the friction force has nothing to oppose it. We can show it to be <span class="math-container">$F=ma$</span>, where the friction force accelerates disk2. Since the person is attached to the disk, the person accelerates as well.</p> <p>If you want to look at the person and the disks as 3 elements, then there is no cancelling the force on disk1, and there is no cancelling the friction on disk2. Both will cause accelerations and motions.</p> <blockquote> <p>I am not understanding. If i sit on a chair, i cannot push myself. In this example, the person is essentially pushing on disk 1, which pushes into the axle, which cancels out the reaction force.</p> </blockquote> <p>No. If the person pushes disk1 toward the axle, that would happen. But then there would be zero motion and the problem is boring. But we assume the person is trying to turn the wheel. In that case there is a component of the force that is tangential, and the axle doesn't cancel. disk1 goes one way and the person/disk2 goes the other way.</p> <p>And yes, because the person's mass is not aligned with the axis, as the person moves, the axle will move to keep the center of mass in the same position (assuming the axle isn't fixed to some object).</p>
<p>You are right that the torques applied to disk <span class="math-container">$1$</span> and disk <span class="math-container">$2$</span> are equal and opposite. But disk <span class="math-container">$1$</span> is smaller than disk <span class="math-container">$2$</span> so it presumably has a smaller moment of inertia than disk <span class="math-container">$2$</span>. So disk <span class="math-container">$1$</span> will rotate more quickly counter clockwise than disk <span class="math-container">$2$</span> rotates clockwise.</p>
stack-exchange-preferences_train_51
stack-exchange-preferences
<p>I have been looking around and would like to know what everyone uses to resize images in case I am missing out.</p> <p>I am using php imageGD library imagejpeg() ect.</p> <p>I have continually updated my class to try and "Solve" this one situation:</p> <p>If an image a user uploads is say 469x358 and the display end picture needs to be or is designed to fit within a 120x80 box for instance. If i resize based upon width the resulting resized image will be 120x92, i could just then fix the height but that will pixelate or squash the image, i could also crop the end off with either imageGD or css overflow hidden.</p> <p>I have had a quick look and seen that there are algorithms(bicubic ect) that you can use to shrink an image which sharpens it so it doesnt look squashed, which is the continual effect i seem to get with imageGD. Has anyone used this algorithm?</p> <p>I have also seen ImageMagick has anyone used this software? Does it shrink an image better?</p> <p>I am currently cropping the end off with overflow hidden, but is there a better way?</p>
<blockquote> <p>If an image a user uploads is say 469x358 and the display end picture needs to be or is designed to fit within a 120x80 box for instance. If i resize based upon width the resulting resized image will be 120x92, i could just then fix the height but that will pixelate or squash the image, i could also crop the end off with either imageGD or css overflow hidden.</p> </blockquote> <p>If your image was 358x469 (portrait) and you want to resize it to 120x80 so that the image does not look distorted, here is the math:</p> <pre><code>358/469 = width/80 =&gt; width = 358*80/469 = 61px (approx) </code></pre> <p>We had a taller image we'll use maximum height and constrained width. A desired width of 120px means the image is stretched horizontally; with a better algorithm you can only achieve smoothness but you cannot make a squashed/stretched image look normal with a better algorithm.</p> <p>If fitting is required, I suggest that you crop-to-fit of resize-to-fit. You can do this on the server side via GD library/ImageMagick or on the client side using CSS background positioning. If you're using GD, cropping is as simple as resizing the image with negative offsets (somewhat similar to CSS background positioning with negative background-position).</p> <h1>Edit 1</h1> <p>If it is a question of whether to use GD or IM, I'd suggest IM. I am not sure about the quality of output but as far as performance is concerned, IM will outperform GD, specially when you are dealing with high resolution images. In case you prefer GD, the GD library function <code>imagecopyresampled</code> will give you better results compared to <code>imagecopyresized</code> but higher CPU and/or memory usage.</p> <h1>Edit 2</h1> <p>I forgot to mention, I stopped using GD long time ago and switched to <a href="http://phpthumb.sourceforge.net/" rel="nofollow">phpThumb</a>. Takes care of most of the chores. Internally it uses GD and/or IM -- built-in intelligence lets it select the best available method for a given operation.</p>
<p>A few points that might help you decide.</p> <ul> <li><p>The resampled output from ImageMagick and gd2 were largely similar. I'm not sure what sort of resampling gd2 performs, and I'm fairly certain that ImageMagick uses bicubic interpolation, but either way, for most cases, bicubic and bilinear resampling generate outputs that are virtually identical while downsizing. Upscaling a small image is where bicubic interpolation really stands apart. (Even so, there are some pathological cases where the difference between bicubic and bilinear interpolation might be striking -- check out <a href="http://en.wikipedia.org/wiki/Aliasing" rel="nofollow">http://en.wikipedia.org/wiki/Aliasing</a>)</p></li> <li><p>I haven't had much chance to use the ImageMagick module in PHP, though the CLI version was blazing fast for resampling images. Assuming the <code>Imagick</code> module is similarly fast, you should see quick performance. However, in the case of gd2, speed has been a bit of an issue -- I've frequently used it for generating 50-odd thumbnails per page, and the lag is noticeable.</p></li> <li><p>gd2 is a part of most PHP installations, and the API is fairly simple to use. <code>Imagick</code> seems to be a PECL extension. Depending on your hosting provider, that may or may not be an issue.</p></li> </ul> <p>That said, let me point out that it's <strong>almost always</strong> a better idea to cache resized images -- especially if you are sure that the same image will be resized frequently. For instance, if you were creating, say, some online shop and wanted to display image thumbnails, it'd particularly suck if you ran the same set of images through the resizer again and again. OTOH for applications where the images are more variable, on-the-fly resizing might be the better option.</p>
stack-exchange-preferences_train_52
stack-exchange-preferences
<p>I'm testing an API and get all data from the DB. I save the response as </p> <pre><code>MvcResult result = mockMvc.perform(..some code..).andReturn(); </code></pre> <p>I get a json as response. I want to get the length of json array. So, if I have 2 rows in DB, I want to get 2 as a result.</p> <p>Or is there maybe another way to count number of rows which are present in the DB.</p>
<p>if you want to get json array length this is the way,</p> <p>1.if you import <code>org.json.simple.JSONArray</code> you can use <code>JSONArray.size()</code></p> <p>2.if you import <code>org.json.JSONArray</code> you can use <code>JSONArray.length()</code></p>
<p>Try:</p> <pre><code>String content = result.getResponse().getContentAsString(); </code></pre> <p>and then try this <a href="https://stackoverflow.com/questions/15609306/convert-string-to-json-array">one</a> </p>
stack-exchange-preferences_train_53
stack-exchange-preferences
<p>I created this class for a project when I wanted to have <code>List&lt;T&gt;</code> properties on a class and also listen for items being added and removed. </p> <p>I looked at using <a href="https://msdn.microsoft.com/en-us/library/ms132679(v=vs.110).aspx"><code>BindingList&lt;T&gt;</code></a> or <a href="https://msdn.microsoft.com/en-us/library/ms668604(v=vs.110).aspx"><code>ObservableCollection&lt;T&gt;</code></a> but I felt that their collection changed events are too complicated. I simply wanted to know when items are added and removed.</p> <pre><code>public class EventList&lt;T&gt; : IList&lt;T&gt; { private readonly List&lt;T&gt; _list; public EventList() { _list = new List&lt;T&gt;(); } public EventList(IEnumerable&lt;T&gt; collection) { _list = new List&lt;T&gt;(collection); } public EventList(int capacity) { _list = new List&lt;T&gt;(capacity); } public event EventHandler&lt;EventListArgs&lt;T&gt;&gt; ItemAdded; public event EventHandler&lt;EventListArgs&lt;T&gt;&gt; ItemRemoved; private void RaiseEvent(EventHandler&lt;EventListArgs&lt;T&gt;&gt; eventHandler, T item, int index) { var eh = eventHandler; eh?.Invoke(this, new EventListArgs&lt;T&gt;(item, index)); } public IEnumerator&lt;T&gt; GetEnumerator() { return _list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(T item) { var index = _list.Count; _list.Add(item); RaiseEvent(ItemAdded, item, index); } public void Clear() { for (var index = 0; index &lt; _list.Count; index++) { var item = _list[index]; RaiseEvent(ItemRemoved, item, index); } _list.Clear(); } public bool Contains(T item) { return _list.Contains(item); } public void CopyTo(T[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } public bool Remove(T item) { var index = _list.IndexOf(item); if (_list.Remove(item)) { RaiseEvent(ItemRemoved, item, index); return true; } return false; } public int Count =&gt; _list.Count; public bool IsReadOnly =&gt; false; public int IndexOf(T item) { return _list.IndexOf(item); } public void Insert(int index, T item) { _list.Insert(index, item); RaiseEvent(ItemRemoved, item, index); } public void RemoveAt(int index) { var item = _list[index]; _list.RemoveAt(index); RaiseEvent(ItemRemoved, item, index); } public T this[int index] { get { return _list[index]; } set { _list[index] = value; } } } public class EventListArgs&lt;T&gt; : EventArgs { public EventListArgs(T item, int index) { Item = item; Index = index; } public T Item { get; } public int Index { get; } } </code></pre> <p>The typical use case would be something like this:</p> <pre><code>public class MyClass { public MyClass() { MyItems = new EventList&lt;string&gt;(); MyItems.ItemAdded += (sender, args) =&gt; { // do something when items are added }; MyItems.ItemRemoved += (sender, args) =&gt; { // do something when items are removed }; } public EventList&lt;string&gt; MyItems { get; } } </code></pre> <p>I'm posting this here for code review for general feedback, but also to ask if I've missed something obvious, like an alternative class in the .NET framework or a 3rd party library that might do the same sort of thing?</p>
<p><strong>Bug</strong> </p> <blockquote> <pre><code>public void Insert(int index, T item) { _list.Insert(index, item); RaiseEvent(ItemRemoved, item, index); } </code></pre> </blockquote> <p>I don't think that you want to raise an <code>ItemRemoved</code> event in the case of inserting an item. </p> <hr> <p>In general I like your implementation. It is leightweight and is doing exactly what it should. </p> <p>But for sure I have something to critizise: </p> <ul> <li><p>The name <code>EventList&lt;T&gt;</code> which reads like a list <strong>of</strong> events instead of a list <strong>with</strong> events. Because there is already a <code>ObservableCollection&lt;T&gt;</code> maybe an <code>ObservableList&lt;T&gt;</code> would be a better name. </p></li> <li><p>You implement <code>IList&lt;T&gt;</code> but have the underlaying list as a <code>List&lt;T&gt;</code> instead of an <code>IList&lt;T&gt;</code> like <code>private readonly IList&lt;T&gt; _list;</code>. </p></li> <li><p><s>The <code>RemoveAt()</code> could be simplified by calling the <code>Remove()</code> method like so </p> <pre><code>public void RemoveAt(int index) { Remove(_list[index]); } </code></pre> <p></s> See <a href="https://codereview.stackexchange.com/users/46715/roman-reiner">@RomanReiner</a>'s answer <a href="https://codereview.stackexchange.com/a/111578/29371">here</a></p></li> <li>IMO the raising of multiple <code>ItemRemoved</code> events inside the <code>Clear()</code> method isn't that good because you are raising the event before the item is removed. You should either have an additional event <code>ItemsCleared</code> or you should raise the <code>ItemRemoved</code> events after the clearing of that list. </li> </ul>
<pre><code>private void RaiseEvent(EventHandler&lt;EventListArgs&lt;T&gt;&gt; eventHandler, T item, int index) { var eh = eventHandler; eh?.Invoke(this, new EventListArgs&lt;T&gt;(item, index)); } </code></pre> <p>The conditial invocation will be compiled to something like</p> <pre><code>if (eh != null) { eh.Invoke(this, new EventListArgs&lt;T&gt;(item, index)); } </code></pre> <p>So there is no reason/advantage in having another copy of the <code>eventHandler</code> variable in this case. The only reason for using a local copy of the event handler is to avoid the original event handler being set to <code>null</code> before the invocation, but the method's parameter won't change. Just use</p> <pre><code>private void RaiseEvent(EventHandler&lt;EventListArgs&lt;T&gt;&gt; eventHandler, T item, int index) { eventHandler?.Invoke(this, new EventListArgs&lt;T&gt;(item, index)); } </code></pre>
stack-exchange-preferences_train_54
stack-exchange-preferences
<p>Alright, so this is something really basic, and I know that when someone tells me the answer I'm going to feel really silly, but I can't for the life of me figure out why the following code isn't working:</p> <p>index.php:</p> <pre><code>&lt;?php include('config.php'); //this works fine. variables in this file are reached correctly - $_MYSQL is defined there ?&gt; &lt;?php include($_MYSQL); ?&gt; &lt;?php echo ($fruit);?&gt; </code></pre> <p>db_config.php (which is what $_MYSQL links to, this works no problem):</p> <pre><code>&lt;?php $fruit = "apple"; echo($fruit); ?&gt; </code></pre> <p>for completeness config.php looks like:</p> <pre><code>&lt;?php $_MYSQL = 'http://'.$_SERVER['HTTP_HOST'].'/public_html/db_config.php'; $BASE_URL = 'http://'.$_SERVER['HTTP_HOST'].'/public_html/Opto10/'; ?&gt; </code></pre> <p>So as the names imply the code is meant to contact this db_config.php that then connects to the database, but for some reason the variables in the db_config file don't seem to carry across to index.php. The weird thing is that include('config.php'); works perfectly fine, but in the code I've shown above in the index.php "echo($fruit);" doesn't print out anything. The same line in db_config.php does though (so I guess that it does mean it's included). Somehow the variables aren't passed along. Just so you know, in case this makes a difference, the db_config.php file is located in the parent of the current directory.</p> <p>I'm thoroughly puzzled, any help is extremely welcome. Thanks in advance,</p> <p>Simon</p> <p>What you have abovev is literally all my php code. </p>
<p>You can't inlcude across HTTP like that</p> <p>From <a href="http://us3.php.net/manual/en/function.include.php" rel="noreferrer">the manual</a></p> <blockquote> <p>If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see List of Supported Protocols/Wrappers for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. <strong>This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.</strong></p> </blockquote>
<p>if the connection to DB fails, you have false in the variable, so echo false; is like echo ''; --> you'll see nothing.</p> <p>Try the var_dump($variable); on $fruit, as Manzoo Ahmed suggested to you.</p>
stack-exchange-preferences_train_55
stack-exchange-preferences
<p>I thought that the function <a href="http://php.net/manual/en/function.array-multisort.php" rel="nofollow">array_multisort</a> can sort multidimensional array, but this code does not work.</p> <p>Code:</p> <pre><code>$values = array(0, 2, 1, array(0, 2, 1)); array_multisort($values, SORT_ASC); var_dump($values); </code></pre> <p>Return:</p> <pre><code>array(4) [ 0 =&gt; 0 1 =&gt; 1 2 =&gt; 2 3 =&gt; array(3) [ 0 =&gt; 0 1 =&gt; 2 //should be 1 2 =&gt; 1 //should be 2 ] ] </code></pre> <p>Why the array in array is not sorted? Thanks</p>
<p>You can try</p> <pre><code>sort_recursive($values); var_dump($values); </code></pre> <p>Output </p> <pre><code>array (size=4) 0 =&gt; int 0 1 =&gt; int 1 2 =&gt; int 2 3 =&gt; array (size=3) 0 =&gt; int 0 1 =&gt; int 1 2 =&gt; int 2 </code></pre> <p>Function Used </p> <pre><code>function sort_recursive(&amp;$array) { sort($array); foreach ( $array as &amp;$v ) { is_array($v) and sort_recursive($v); } } </code></pre>
<p>is because the <code>array()</code> is in a multidimentional form</p> <p>try this link to see how to sort multidimensional array <a href="https://stackoverflow.com/questions/2699086/sort-multidimensional-array-by-value-2">click here</a></p>
stack-exchange-preferences_train_56
stack-exchange-preferences
<p>I have VC++, VC# and VB Express 2008 installed on my computer. I have registered VC# and VC++ products but when I try to register VB Express 2008, there is no registration box appear. In fact, when I click Help -> Register Product, it opens a MS Registration web page in the browser instead of opening the registration box, asks me to enter my EMail info and after a while web page says thanks to mine instead of registration number as if I have already register the product. I installed VC++ and VC# by the web installer and installed VB from the DVD-ISO image of VS Express 2008 SP1.</p> <p>Any suggestion would be worth!</p>
<p>Or even simpler:</p> <pre><code>SELECT TOP 15 * FROM MyTable WHERE reference LIKE '123%' OR first_name LIKE 'Pa%' ORDER BY reference LIKE '123%' DESC; </code></pre> <p><code>true</code> naturally orders after <code>false</code>, so just order by the match you want + DESC</p>
<pre><code> SELECT TOP 15 * FROM MyTable WHERE reference LIKE '123%' OR first_name LIKE 'Pa%' ORDER BY CASE WHEN reference LIKE '123%' THEN 1 WHEN first_name LIKE 'Pa%' THEN 2 END ASC </code></pre>
stack-exchange-preferences_train_57
stack-exchange-preferences
<p>Why I am getting Spring @Autowired field as null :</p> <pre><code>Exception : java.lang.NullPointerException at com.elastic.controller.MainController.getUsers(MainController.java:38) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) </code></pre> <hr> <p>MainController.java</p> <pre><code>package com.elastic.controller; @Component() @Path("/user") public class MainController { @Autowired private ElasticSearchRepository elasticSearchRepository; @GET @Path("/getAllUsers") @Produces(MediaType.APPLICATION_JSON) public Response getUsers() throws Exception{ List&lt;User&gt; userlist =new ArrayList&lt;User&gt;(); Iterator&lt;User&gt; users = elasticSearchRepository.getAllUsers(); while (users.hasNext()) { userlist.add(users.next()); } return Response.ok(userlist).build(); } } </code></pre> <hr> <p>ElasticSearchRepository.java</p> <pre><code>package com.elastic.repository; @Configuration @EnableElasticsearchRepositories(basePackages = "com.elastic.repository") public class ElasticSearchRepository { public Iterator&lt;User&gt; getAllUsers() { Iterator&lt;User&gt; users = userRepository.findAll().iterator(); return users; } } </code></pre> <hr> <p>mvc-dispatcher-servlet.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch" xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"&gt; &lt;context:annotation-config /&gt; &lt;mvc:annotation-driven /&gt; &lt;context:component-scan base-package="com.elastic" /&gt; &lt;elasticsearch:repositories base-package="com.elastic.repository" /&gt; &lt;elasticsearch:repositories base-package="com.elastic.entity" /&gt; &lt;/beans&gt; </code></pre> <p>for Controller i have kept @component Annotation and for repository i have kept @Configuration but still getting this exception . Pls help on this .</p>
<p>Based on the problem statement, I am able to find two problems and solution is below:</p> <p>Please try this</p> <ol> <li><p>Please try with in the class ElasticSearchRepository.java <code>@ComponentScan(basePackages = { "com.elastic" })</code></p></li> <li><p><code>@Component()</code> rename with <code>@Controller</code> in the MainController.java class</p></li> </ol>
<p>This could be due to the way you are using <code>MainController</code>, If your main controller is not initialized and provisioned by spring context i.e. you have created an instance of <code>MainController</code> using <code>new</code> keyword.</p> <p>Secondly I do not see <code>getAllUsers()</code> method in the ElasticSearchRepository, Just wondering how does your code compile ?</p>
stack-exchange-preferences_train_58
stack-exchange-preferences
<p>Let $X$ be a random variable having expected value $\mu$ and variance $\sigma^2$. Find the Expected Value and Variance of $Y = \frac{X−\mu}{\sigma}$.</p> <p>I would like to show some progress I've made so far, but honestly I've been thinking about this problem for the past few days but just have no idea where to start. Any hint or insight on a starting point would be much appreciated.</p> <p>Thanks!</p>
<p>Given a random variable $X$, a location scale transformation of $X$ is a new random variable $Y=aX+b$ where $a$ and $b$ are constants with $a&gt;0$. </p> <p>The location scale transformation $aX+b$ horizontally scales the distribution of $X$ by the factor $a$, and then <em>shifts</em> the distribution so obtained by the factor $b$ on the real line $\mathbb{R}$. </p> <ul> <li>In an intuitive sense, the expected value $\mathbb{E}[X]$ of a random variable is the center of mass of the distribution of $X$. Shifting the distribution of $X$ by a factor $b$, shifts the center of mass by the factor $b$. Scaling the distribution of $X$ by a factor $a$, scales the center of mass by $a$. In other words, $$\mathbb{E}[aX+b]=a\mathbb{E}[X]+b$$</li> <li>Similarly, the variance of $X$ is a measure of the horizontal spread of the distribution of $X$, but the $\text{Var}[X]$ is defined as <em>squared-distance</em>. Thus scaling the distribution of $X$ by a factor $a$, scales the $\text{Var}[X]$ by the factor $a^2$. Shifting the distribution of $X$ by any factor will not affect the spread of distribution, $\text{Var}[X]$, but only affects center of mass. In other words, $$\text{Var}[aX+b]=\text{Var}[aX]=a^2\text{Var}[X]$$</li> </ul> <p>Now, here is an hint to your problem: $Y=\dfrac{X-\mu}{\sigma}=\dfrac{1}{\sigma}X-\dfrac{\mu}{\sigma}$, which can be written as $aX+b$. Find $a$ and $b$, and then use the location-scale transformation.</p>
<p>Have you seen the following basic properties of expectation and variance?</p> <p>(I'd be very surprised if some version of these hadn't been discussed)</p> <p>$\text{E}(aX+b) = a\text{E}(X)+b$</p> <p>$\text{Var}(aX+b) = a^2\text{Var}(X)$</p> <p><a href="http://en.wikipedia.org/wiki/Expected_value#Linearity" rel="nofollow">http://en.wikipedia.org/wiki/Expected_value#Linearity</a></p> <p><a href="http://en.wikipedia.org/wiki/Variance#Basic_properties" rel="nofollow">http://en.wikipedia.org/wiki/Variance#Basic_properties</a></p> <p>If you apply these properties, or better, the versions you'll already have been given, the problem is trivial.</p> <p>If you still can't see it, try finding $\text{E}(X-\mu)$ first and work from there.</p>
stack-exchange-preferences_train_59
stack-exchange-preferences
<p>After installing windows update, my IE version updated to 11.0.9600.18059 (Update Version: 11.0.24), and I found that its consuming too much memory, when I open 3-4 tabs and surfing 10-15 mins, memory raise up to 1300-1500 MB and I have to restart it.</p> <p>So is there any solution or patch available for this?</p>
<p>If you're a developer landing here because your page is blowing up since the IE build on October 13th. Try adding this attribute to your HTML body tag like so: <code>&lt;body spellcheck='false'&gt;&lt;/body&gt;</code></p>
<p>Yes, I also confirm that disabling spellchecker solved the high memory usage in our case too.</p>
stack-exchange-preferences_train_60
stack-exchange-preferences
<p>I'm playing around with Monogame and can't add a font. When adding a font with the MonoGame Pipeline tool i can't build my project anymore.</p> <p>Visual studio stopps with the following error:</p> <blockquote> <p>Der Befehl ""C:\Program Files (x86)\MSBuild\MonoGame\v3.0\Tools\MGCB.exe" /@:"C:\dev\Mini\Mini\Content\Content.mgcb" /platform:Windows /outputDir:"C:\dev\Mini\Mini\Content\bin\Windows" /intermediateDir:"C:\dev\Mini\Mini\Content\obj\Windows" /quiet" wurde mit dem Code 1 beendet. 'FontDescriptionProcessor' had unexpected</p> </blockquote> <p>(sorry, its German, but i think you can understand the problem ; ) )</p> <p>When i execute the error throwing command i get a more helping error:</p> <blockquote> <p>C:\dev\Mini\Mini\Content>"C:\Program Files (x86)\MSBuild\MonoGame\v3.0\Tools\MGCB.exe" /@:"C:\dev\Mini\Mini\Content\Content.mgcb" /platform:Windows /outputDir:"C:\dev\Mini\Mini\Content\bin\Windows" /intermediateDir:"C:\dev\Mini\Mini\Content\obj\Windows" Build started 07.08.2015 23:15:43</p> <p>Skipping C:/dev/Mini/Mini/Content/Game/Character.PNG Skipping C:/dev/Mini/Mini/Content/SplashScreen/splashScreenGame.png Skipping C:/dev/Mini/Mini/Content/Game/Background.PNG C:/dev/Mini/Mini/Content/fonts/default.spritefont C:/dev/Mini/Mini/Content/fonts/default.spritefont: error: Processor 'FontDescriptionProcessor' had unexpected failure! System.ArgumentException: Illegales Zeichen im Pfad. bei System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional) bei System.IO.Path.IsPathRooted(String path)<br> bei Microsoft.Xna.Framework.Content.Pipeline.Processors.FontDescriptionProcessor.FindFontFileFromFontName(String fontName, String fontDirectory) bei Microsoft.Xna.Framework.Content.Pipeline.Processors.FontDescriptionProcessor.Process(FontDescription input, ContentProcessorContext context) bei Microsoft.Xna.Framework.Content.Pipeline.ContentProcessor`2.Microsoft.Xna.Framework.Content.Pipeline.IContentProcessor.Process(Object input, ContentProcessorContext context) bei MonoGame.Framework.Content.Pipeline.Builder.PipelineManager.ProcessContent(PipelineBuildEvent pipelineEvent)Skipping C:/dev/Mini/Mini/Content/SplashScreen/SplashScreen.xml Skipping C:/dev/Mini/Mini/Content/Game/Game.xml</p> <p>Build 3 succeeded, 1 failed.</p> <p>Time elapsed 00:00:00.19.</p> </blockquote> <p>I understand, that the path <code>C:/dev/Mini/Mini/Content/fonts/default.spritefont</code> is invalid, but i don't see any invalid characters. The .spritefont file is generated with the MonoGame tool and not imported. Did i miss something?</p> <p>I am on a Windows 10, the MonoGame Pipeline Tool is on version 3.5.0.465 and MGCB.exe has the version 3.5.0.465, too.</p> <p>Edit: When checking the path myself, everything looks ok and moving the whole project to an other harddrive doesn't help at all.</p> <p>Edit2: Okey. it looks like it is not my font path. It is the path loaded from the registry. The line <code>registryKey.GetValue(current).ToString();</code> inside the <code>FindFontFileFromFontName</code> method returns <code>ARIAL.TTF\00\0\0\0\0\0</code>. I will look into it and update this question or make an answer.</p>
<p>After testing around i came to an solution (or i found the problem...): Some font paths in my registry are corrupted. Fonts with an uppercase Date value are throwing errors. When you encounter a similar problem take a look in your registry under <code>"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts"</code>l, check your chosen font or change it to a different one. I hope this solution will help you, too. (And when somebody know, why my registry data got corrupted, please let me know.)</p> <p><a href="https://i.stack.imgur.com/ZJywv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZJywv.png" alt="enter image description here"></a></p>
<p>I had this error and because the spritefont file is just a font meta-data definition file and not the actual font I still had manually install the TTF font files in Windows, then the build succeeded since the font could then be found to compress into the binary.</p>
stack-exchange-preferences_train_61
stack-exchange-preferences
<p>In my home page(.xhtml),I'm having 4 h:inputText box and one serach button(h:commandButton)in JSF page</p> <pre><code>&lt;h:inputText id="stlID" value="#{searchSettlementTransRequest.stlmtTransId}" name='stlmt'&gt; &lt;h:inputText id="pmtID" value="#{searchSettlementTransRequest.pmtTransId}" name='pmt'&gt; &lt;h:inputText id="AgentID" value="#{searchSettlementTransRequest.AgentId}" name='agnt'&gt; &lt;h:inputText id="AgencyID" value="#{searchSettlementTransRequest.AgencyId}" name='agncy'&gt; &lt;h:commandButton id="tranSearchBtn" styleClass="valign first button-search sSearch" action="stlmtSubmit"/&gt; </code></pre> <p>My requirement is:</p> <ol> <li>on entered data in 1st input field the other input fields should be disabled(ie. 2,3,4).</li> <li>on entered data in 2nd input field the other input fields should be disabled(ie. 1,3,4). and so on.. Note: at the sametime if user entered data in 1st or 2nd or 3rd or 4th (user dynamic)field and delete the same before leaving out the input field in such case all field should be enabled. When i get response back(empty or non-empty data response) after clicking "search" button now all the input fields should be enabled for another search(now user may input data in any of the 4 fields)</li> </ol>
<p>S3 does not support stream compression nor is it possible to compress the uploaded file remotely.</p> <p>If this is a one-time process I suggest downloading it to a EC2 machine in the same region, compress it there, then upload to your destination.</p> <p><a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html" rel="noreferrer">http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html</a></p> <p>If you need this more frequently</p> <p><a href="https://stackoverflow.com/questions/5442011/serving-gzipped-css-and-javascript-from-amazon-cloudfront-via-s3">Serving gzipped CSS and JavaScript from Amazon CloudFront via S3</a></p>
<p>There are now pre-built apps in Lambda that you could use to compress images and files in S3 buckets. So just create a new Lambda function and select a pre-built app of your choice and complete the configuration.</p> <ol> <li>Step 1 - Create a new Lambda function</li> <li>Step 2 - Search for prebuilt app <a href="https://i.stack.imgur.com/b8ZAf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b8ZAf.jpg" alt="enter image description here" /></a></li> <li>Step 3 - Select the app that suits your need and complete the configuration process by providing the S3 bucket names. <a href="https://i.stack.imgur.com/j1Qby.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j1Qby.jpg" alt="enter image description here" /></a></li> </ol>
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
65