id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
5,128,711
Styling <a> without href attribute
<p>Is it possible to match all links without <code>href</code> specified via CSS?</p> <p>Example:</p> <pre><code>&lt;a&gt;Invalid link&lt;/a&gt; </code></pre> <p>I know its possible to match all links with href but I'm just looking for the opposite.</p>
5,128,720
1
1
null
2011-02-26 17:57:49.08 UTC
8
2016-04-13 11:57:33.23 UTC
2012-05-14 18:35:45.303 UTC
null
106,224
null
62,368
null
1
72
html|css|css-selectors
41,204
<p>Either use CSS3's <code>:not()</code>:</p> <pre class="lang-css prettyprint-override"><code>a:not([href]) { /* Styles for anchors without href */ } </code></pre> <p>Or specify a general style for all <code>a</code>, and one for <code>a[href]</code> to override it for those with the attribute.</p> <pre class="lang-css prettyprint-override"><code>a { /* Styles for anchors with and without href */ } a[href] { /* Styles for anchors with href, will override the above */ } </code></pre> <p>For the <strong>best</strong> browser support (includes ancient but not quite forgotten browsers), use the <a href="http://www.w3.org/TR/selectors/#the-link-pseudo-classes-link-and-visited" rel="noreferrer"><code>:link</code> and <code>:visited</code> pseudo-classes</a> instead of the attribute selector (combining both will match the same as <code>a[href]</code>):</p> <pre class="lang-css prettyprint-override"><code>a {} /* All anchors */ a:link, a:visited {} /* Override */ </code></pre> <p>Also see <a href="https://stackoverflow.com/questions/10587245/is-there-a-reason-to-use-a-instead-of-alink-or-avisited-in-my-stylesheet/10589840#10589840">this answer</a> for an in-depth explanation of <code>a[href]</code> versus <code>a:link, a:visited</code>.</p>
44,698,437
Map JSON To List<Map<<String, Object>>
<p>I have a JSON of the format</p> <pre><code>[{ "id" : "a01", "name" : "random1", "val" : "random2" }, { "id" : "a03", "name" : "random3", "val" : "random4" }] </code></pre> <p>I need to map it to a <code>List</code> holding various <code>Map</code> objects. How do I achieve it?</p> <p>Even if I am able to convert this JSON to a <code>List</code> of <code>String</code> of the form</p> <pre><code>{ "id" : "a01", "name" : "random1", "val" : "random2" } </code></pre> <p>then I have a method to convert each individual <code>String</code> to a <code>Map</code>.</p>
44,698,844
3
2
null
2017-06-22 11:42:47.363 UTC
8
2020-10-30 21:33:53.773 UTC
2020-03-28 07:17:20.133 UTC
null
745,828
null
6,135,078
null
1
26
java|json|jackson|objectmapper
42,306
<p>You will need to pass a <code>TypeReference</code> to <code>readValue</code> with the desired result type:</p> <pre><code>ObjectMapper mapper = new ObjectMapper(); List&lt;Map&lt;String, Object&gt;&gt; data = mapper.readValue(json, new TypeReference&lt;List&lt;Map&lt;String, Object&gt;&gt;&gt;(){}); </code></pre>
21,609,040
what are the differences (and when to use) selenium-webdriver over webdriverjs?
<p>I'm an experience professional that uses selenium-webdriver. I'm exploring more options on how to test javascript applications and I found webdriverJs. Unfortunately, I dont understand what's the difference between these two (2). </p> <p>Can someone please explain when to use selenium-webdriver over webdriverJs and the benefits?</p> <p>Thanks!</p>
21,609,103
3
1
null
2014-02-06 16:51:36.46 UTC
11
2019-09-16 17:23:32.15 UTC
null
null
null
null
1,270,463
null
1
10
javascript|selenium|selenium-webdriver
12,882
<p>WebDriverJS and selenium-webdriver are both JavaScript bindings for the Webdriver API. </p> <p>The only difference is that selenium-webdriver is the official implementation maintained by the selenium team, whereas WebDriverJS is not. WebDriverJS is maintained by a third-party. </p>
42,568,638
Python multiprocessing installation: Command "python setup.py egg_info" failed with error code 1
<p>Trying to install:</p> <pre><code> pip install multiprocessing </code></pre> <p>Getting an error:</p> <pre><code>Collecting multiprocessing Using cached multiprocessing-2.6.2.1.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/private/var/folders/7s/sswmssj51p73hky4mkqs4_zc0000gn/T/pip-build-8c0dk6ai/multiprocessing/setup.py", line 94 print 'Macros:' ^ SyntaxError: Missing parentheses in call to 'print' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/7s/sswmssj51p73hky4mkqs4_zc0000gn/T/pip-build-8c0dk6ai/multiprocessing/ </code></pre> <p>Anyone knows the way to fix this?</p>
42,653,828
6
1
null
2017-03-03 00:44:33.137 UTC
2
2021-06-13 07:31:28.58 UTC
null
null
null
null
4,588,128
null
1
37
python|pip|multiprocessing
27,647
<p><strong>In short: Multiprocessing is already pre-installed in python 3, no need to install it.</strong></p> <p>I found an answer to my question and it's a silly one - multiprocessing is already pre-installed in my version of Python (3.5.2) by default.</p> <p>It won't show up in the list of packages in Anaconda >> Environments >> root, as it's not a third party package but an internal one.</p> <p>If anyone is not sure whether this applies to you, just check <code>from multiprocessing import Pool</code> in your Python console.</p> <p>This is true of all currently supported versions of Python (2.7 and 3.x) and according to a Python maintainer/contributor <code>multiprocessing</code> has been part of the standard library (batteries included) since Python 2.6. <a href="https://bugs.python.org/msg326646" rel="noreferrer">https://bugs.python.org/msg326646</a></p> <p>You won't need to do a <code>pip install multiprocessing</code> anymore and do NOT include it in your <code>requirements.txt</code> unless you are maintaining a Python 2.4/2.5 application (please migrate!). On most versions you can just <code>import multiprocessing</code> and you should be fine. </p>
32,954,486
zip iterators asserting for equal length in python
<p>I am looking for a nice way to <code>zip</code> several iterables raising an exception if the lengths of the iterables are not equal.</p> <p>In the case where the iterables are lists or have a <code>len</code> method this solution is clean and easy:</p> <pre><code>def zip_equal(it1, it2): if len(it1) != len(it2): raise ValueError(&quot;Lengths of iterables are different&quot;) return zip(it1, it2) </code></pre> <p>However, if <code>it1</code> and <code>it2</code> are generators, the previous function fails because the length is not defined <code>TypeError: object of type 'generator' has no len()</code>.</p> <p>I imagine the <a href="https://docs.python.org/3/library/itertools.html" rel="noreferrer"><code>itertools</code></a> module offers a simple way to implement that, but so far I have not been able to find it. I have come up with this home-made solution:</p> <pre><code>def zip_equal(it1, it2): exhausted = False while True: try: el1 = next(it1) if exhausted: # in a previous iteration it2 was exhausted but it1 still has elements raise ValueError(&quot;it1 and it2 have different lengths&quot;) except StopIteration: exhausted = True # it2 must be exhausted too. try: el2 = next(it2) # here it2 is not exhausted. if exhausted: # it1 was exhausted =&gt; raise raise ValueError(&quot;it1 and it2 have different lengths&quot;) except StopIteration: # here it2 is exhausted if not exhausted: # but it1 was not exhausted =&gt; raise raise ValueError(&quot;it1 and it2 have different lengths&quot;) exhausted = True if not exhausted: yield (el1, el2) else: return </code></pre> <p>The solution can be tested with the following code:</p> <pre><code>it1 = (x for x in ['a', 'b', 'c']) # it1 has length 3 it2 = (x for x in [0, 1, 2, 3]) # it2 has length 4 list(zip_equal(it1, it2)) # len(it1) &lt; len(it2) =&gt; raise it1 = (x for x in ['a', 'b', 'c']) # it1 has length 3 it2 = (x for x in [0, 1, 2, 3]) # it2 has length 4 list(zip_equal(it2, it1)) # len(it2) &gt; len(it1) =&gt; raise it1 = (x for x in ['a', 'b', 'c', 'd']) # it1 has length 4 it2 = (x for x in [0, 1, 2, 3]) # it2 has length 4 list(zip_equal(it1, it2)) # like zip (or izip in python2) </code></pre> <p>Am I overlooking any alternative solution? Is there a simpler implementation of my <code>zip_equal</code> function?</p> <p><strong>Update:</strong></p> <ul> <li>Requiring python 3.10 or newer, see Asocia's <a href="https://stackoverflow.com/a/62773251/446149">answer</a></li> <li>Thorough performance benchmarking and best performing solution on python&lt;3.10: Stefan's <a href="https://stackoverflow.com/a/69485272/446149">answer</a></li> <li>Simple answer without external dependencies: Martijn Pieters' <a href="https://stackoverflow.com/a/32954700/446149">answer</a> (please check the comments for a bugfix in some corner cases)</li> <li>More complex than Martijn's, but with better performance: cjerdonek's <a href="https://stackoverflow.com/a/40596355/446149">answer</a></li> <li>If you don't mind a package dependency, see pylang's <a href="https://stackoverflow.com/a/61832383/446149">answer</a></li> </ul>
69,485,272
6
1
null
2015-10-05 17:32:57.31 UTC
6
2022-01-18 10:46:50.313 UTC
2021-10-18 15:06:33.607 UTC
null
446,149
null
446,149
null
1
39
python|itertools
10,381
<p>A new solution even much faster than cjerdonek's on which it's based, and a benchmark. Benchmark first, my solution is green. Note that the &quot;total size&quot; is the same in all cases, two million values. The x-axis is the number of <em>iterables</em>. From 1 iterable with two million values, then 2 iterables with a million values each, all the way up to 100,000 iterables with 20 values each.</p> <p><a href="https://i.stack.imgur.com/tO7En.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tO7En.png" alt="benchmark plot" /></a></p> <p>The black one is Python's <code>zip</code>, I used Python 3.8 here so it doesn't do this question's task of checking for equal lengths, but I include it as reference/limit of the maximum speed one can hope for. You can see my solution is pretty close.</p> <p>For the perhaps most common case of zipping <em>two</em> iterables, mine's almost three times as fast as the previousy fastest solution by cjerdonek, and not much slower than <code>zip</code>. Times as text:</p> <pre><code> number of iterables 1 2 3 4 5 10 100 1000 10000 50000 100000 ----------------------------------------------------------------------------------------------- more_itertools__pylang 209.3 132.1 105.8 93.7 87.4 74.4 54.3 51.9 53.9 66.9 84.5 fillvalue__Martijn_Pieters 159.1 101.5 85.6 74.0 68.8 59.0 44.1 43.0 44.9 56.9 72.0 chain_raising__cjerdonek 58.5 35.1 26.3 21.9 19.7 16.6 10.4 12.7 34.4 115.2 223.2 ziptail__Stefan_Pochmann 10.3 12.4 10.4 9.2 8.7 7.8 6.7 6.8 9.4 22.6 37.8 zip 10.3 8.5 7.8 7.4 7.4 7.1 6.4 6.8 9.0 19.4 32.3 </code></pre> <p><strong>My code</strong> (<a href="https://tio.run/##pVNNb9swDL3nVxDYIXYhFFjaDYOxHttzD0UvRRFoDt0IUCSNottmw357RsmJv5qd5kNi6ZF85Ht02PPWu6tvgQ6HhvwODCOx9zaC2QVPDPVWG7dYbLCBXyas8WerbXGRwvQPi7GsFguQ5xPceQIm82q0hVpHjAraiBBawpR5mcNMAxZdMaTDd1hVGUoPIbfkUviY4sTwoI2FJtFsERpDkeEUlCPy1TqyDwE3cAN32sYOSd13KEuNohwYnXfW19LyNLnH5zUfqMVZu/1xb9BuzjYrA/V9JBXnXYgszvOUbEAzlTYi5qO2Ld4SeSqaZW9HNRMDTATr3QvSshwGkVbWYFxn6GUye31KKAgjl/9HGLeyLRPGD5Lct5zVCAZrjMD@BeVI3WKc3BaN0/toRQZvBcvdFw7feRShJuZ2CWkkibcmcrHTIUergaaPygvXVU1rlwspuMiKqJFZZfcNsNxP1z@VCWQci0K/x2P8OWrRgUup2FqO1fGWaV9NzCH/luz5x0c2FvVYUN6WKqUNkg8IoNvIwgbUNTattfsjLb7XGHjkK@gIWJ2tkOBKKHA8h@iQNXj6rGD1rODpSsF1@v@i4OtzOQfTz/VwnY4rBWev@2Ll4fAX" rel="nofollow noreferrer" title="Python 3.8 (pre-release) – Try It Online">Try it online!</a>):</p> <pre><code>def zip_equal(*iterables): # For trivial cases, use pure zip. if len(iterables) &lt; 2: return zip(*iterables) # Tail for the first iterable first_stopped = False def first_tail(): nonlocal first_stopped first_stopped = True return yield # Tail for the zip def zip_tail(): if not first_stopped: raise ValueError('zip_equal: first iterable is longer') for _ in chain.from_iterable(rest): raise ValueError('zip_equal: first iterable is shorter') yield # Put the pieces together iterables = iter(iterables) first = chain(next(iterables), first_tail()) rest = list(map(iter, iterables)) return chain(zip(first, *rest), zip_tail()) </code></pre> <p>The basic idea is to let <code>zip(*iterables)</code> do all the work, and then after it stopped because some iterable was exhausted, check whether all iterables were equally long. They were if and only if:</p> <ol> <li><code>zip</code> stopped because the <em>first</em> iterable didn't have another elements (i.e., no other iterable is <em>shorter</em>).</li> <li>None of the other iterables have any further elements (i.e., no other iterable is <em>longer</em>).</li> </ol> <p>How I check these criteria:</p> <ul> <li>Since I need to check these criteria after <code>zip</code> ended, I can't return the <code>zip</code> object purely. Instead, I chain an empty <code>zip_tail</code> iterator behind it that does the checking.</li> <li>To support checking the first criterion, I chain an empty <code>first_tail</code> iterator behind it whose sole job is to log that the first iterable's iteration stopped (i.e., it was asked for another element and it didn't have one, so the <code>first_tail</code> iterator was asked for one instead).</li> <li>To support checking the second criterion, I fetch iterators for all the other iterables and keep them in a list before I give them to <code>zip</code>.</li> </ul> <p>Side note: more-itertools pretty much uses the same method as Martijn's, but does proper <code>is</code> checks instead of Martijn's <a href="https://stackoverflow.com/questions/32954486/zip-iterators-asserting-for-equal-length-in-python#comment67540762_32954700">not quite correct</a> <code>sentinel in combo</code>. That's probably the main reason it's slower.</p> <p>Benchmark code (<a href="https://tio.run/##tVhtb@M2Ev6uXzG3QWEppzhOclscjHNwizY9BOhtg9307oDAUGiJjrWRKJWkE7uL/Pa9GVKi3pxuuogNxJH5MjOceeaZocqtXhXi7O@l/PIlzctCatBpzlPtVb9SzaUuikx5S1nkzU@o5iUvOdMhxCuWihB@T8soK8QdV9puiIss47FOC@G2JPy3NbezautGV3zzwKXChSHkbKPS37nnHRy95sc7gI9FtiZjYLGFfzOp008CrlKOp1KvrcxL@NL4A4/Lsihapln2wLI1j6JKc1Rp9g/JrWyRcRVMPcCP4kKngmcwg2LxCf3nB2Z8WUj0aL4oIBVtX7ckhOAUzWoxlVT6pMtGOMowwppZ@kiWKg7/IQEXUhbSH13WsmHFHjgk6XLJJQqBjIs7vVKjwAnYpjxLrNQ9R6/cZkzc7TtoeSF55EAfRVbrMGCS67UU0F/uJLV3eF6UM3nPZTu6RnGzPrrjAtdrdH9f1Z/EQKWrBQESgHPPhB8BYiYVVDu70w1CfhXGUgcOC5ZnoECne5FzrLY3b97c3uL87S3oFUdLy7WGZtUh6OKO44wMYYEzxiCz8fZ2p1koB8@FG7bAELkjDSzLjGjFcl7heOw528/Pz5HqohOMkMR4c/8s6M@d4hwZ5I/YIh51p7MUw9EcjySFZk/QrLvxJyGM2CgIwcfZ0cI8neITSpt/uynJy22BA0iKWCN2pvDXy3@9/@XDRXTxvx8urq4vf3kf/Xhx/e7yZyfrWrKYL1h8D35eKCL@mCggJkdmTOkWwMbjsXvuBn1MP8c7QzSF52jGyaroxqsh4lV4bUoHnM9gsjmbvJtM3n3fGPTIpEjFnRrTg9/Bsz9A98g5Cx4xi2DB8ax58cATyhgGyzWmOodaY7GE0VAGnfOoOTb8iglDcFus00zbvEVBwhRGVKNXu4QoLdNYz67lmlJAac6ScXdZEHZ@/shLDAsjof@1R27mLSoO4IcVxxg@rkz62Oxyfsfc6CYGVWEbSy23LQZJpdIRTSLyMCoNR91M5kGHaFICGzmOi3VOjMZbi0@m8xBOgi7DdMQGfW4ys3@ZtUwY8tNCcnbvRnmmemsO4HIJj4SwhKjALIdijV0MDsZMwLodrSMbrnG3SFq@x/Eus@9Q0ZZPPucIR3Q15KnKmY5XjeA/4tWEa5ZmauY3Bw/JufQQ1LFFnUxsoRCcYNmNbXVYk1qsSiXcrplp4liCYKmk4L4c1tgjZEaSXGPrhtZbO/km5qWG621pu4PGs5VLvlLD9twVxJ@4TNDq@1dvDGIkOQUXmxVbYyYmNioXxhuou8KwKeJRKpBfI1/xbIkxEgnftCCOvHVtShoOU5WlKE2OFkwZfqHBKnS8VuWCOK45z7aI2XJsN8zsRltlCUQYS8O5ftrU0w82PIhuIw6jglpYVTsVjXfP5pRZVPYOnlrImRpv9aLQPBWY35Xm0Jn97TYAzhlXiKQxx8pouNXcPBzCwr4DgkFPZzZE9bLIQWbYhtRWKnTxTe@Ah0zeqcBwHD09Q3FYyQfsaRsjc/9p@IO0BO0M63tC0USrj68ij4MWBe0O306ew2RXZ/@BUjuve/vaUvj81EKcIZnRGA@HFOVbCAfW5PfoqhbN2XJiokiVozBVpfGbrSiqaGSPh@WhgsLQgyTCFgnDU7N@qei4tf4IvtFue7d@7HTtUEKJmd7dNyghL3EnJrdpzWXjyJ1OpM9@WfGj5ktMrqsiXuVMiH1fmvCRilUUWb1RrbebYFW1@YlIQKYPKfZbMbIgXl6o/JbUY7myi5jutBkB/ANOB6VnZzU@gGu0xYCNqMQg21GT1@pmdFGWCP0Z/ISA5Y7O7Sydx2@hTxQiK7D37W3ud0hOJvVwPXO7fLDTWDyQs4P827cC3SIK3VX2lcv8smlvpz1ntADb7eEic1Uk1hwTeqN6gy95p@//FoVqVUjd0ThwydXaVoEyxSuHcle/hqFNf1NdgVrhd3HAOVskGmowK8JOcIOqvJj15taUs9KsbkqZcqsM4KxUgp0RFMKh8UjYCtY@Gp6f0TjqElSV4uQTuqaokvOErnM8efUUb3RhKTQ@@OpbkrC/7Pk3YIOlz9XowcLnuMYtDL25JSiBFxq/Pkb3tU09Oo4iWhVFNydYdQChT@Ad7SGE1AK6cEFcJHwvpEzS/TwE0fRgH51WqtdNWM0lNG8lFAIMC3LGc7yCY/PB8KZCPZiRg1sjqnqEhs@1jCnczA1f1ANEG07Bk2MyTPlH3K2RQFrkUcpUaGSLz/lTq38oltVVBT6Lafg0rXiCXlJxuSiwLHfE9XWghb75DqEX@UbloT/67iyBXMEIvgNtyZdMNxt7N2zowaihLa/DlvWrmu5bt52O6bU0lVcV0WLi25fxY/uW3c9YvkjY1L5Bd0bgCar5lCJt@6rGiDwIkJEm@IfN1YLL2UlYvbWfvQ2Cm@nZfKcBN7JYCzQADuGEn4VwFvQ8093mEHFTmzUfM6xHwp5BDS7y/fjtCpW3a72NWs/xrQW98I4WhHVsgrB5n7bKzAA2fyJILZNRqr/j7CHc8@0MJ4Ndx@lbxja1ZQOrXmDRi61hm4E1tTOtcs20qqOGtDHoeAFuvnreHZueP8R8L/URW3L7CstRnTGAI0KwY7NZYKjFkd3rl0tyJWXR3Ktw6RpLXWgsXI5YZ3BKKTY5PPzeIzNzchCm6CmmXAh/C@FtiLP0Z7@qb/z3dtL8qm56Nd/3dBwfQ74PR18Renquxg5onaFOOgs18qmNRZkVWmMtBxVLLNmv7vAqpRKmmVHt9GF@rbQu1fT4GFkvQzKNi/z4n2XVJxxjgTetxBHtwCwkfjeR6xL9H2DYc6Wr3vuEctxgDQUc/PLl/w" rel="nofollow noreferrer" title="Python 3.8 (pre-release) – Try It Online">Try it online!</a>):</p> <pre><code>import timeit import itertools from itertools import repeat, chain, zip_longest from collections import deque from sys import hexversion, maxsize #----------------------------------------------------------------------------- # Solution by Martijn Pieters #----------------------------------------------------------------------------- def zip_equal__fillvalue__Martijn_Pieters(*iterables): sentinel = object() for combo in zip_longest(*iterables, fillvalue=sentinel): if sentinel in combo: raise ValueError('Iterables have different lengths') yield combo #----------------------------------------------------------------------------- # Solution by pylang #----------------------------------------------------------------------------- def zip_equal__more_itertools__pylang(*iterables): return more_itertools__zip_equal(*iterables) _marker = object() def _zip_equal_generator(iterables): for combo in zip_longest(*iterables, fillvalue=_marker): for val in combo: if val is _marker: raise UnequalIterablesError() yield combo def more_itertools__zip_equal(*iterables): &quot;&quot;&quot;``zip`` the input *iterables* together, but raise ``UnequalIterablesError`` if they aren't all the same length. &gt;&gt;&gt; it_1 = range(3) &gt;&gt;&gt; it_2 = iter('abc') &gt;&gt;&gt; list(zip_equal(it_1, it_2)) [(0, 'a'), (1, 'b'), (2, 'c')] &gt;&gt;&gt; it_1 = range(3) &gt;&gt;&gt; it_2 = iter('abcd') &gt;&gt;&gt; list(zip_equal(it_1, it_2)) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... more_itertools.more.UnequalIterablesError: Iterables have different lengths &quot;&quot;&quot; if hexversion &gt;= 0x30A00A6: warnings.warn( ( 'zip_equal will be removed in a future version of ' 'more-itertools. Use the builtin zip function with ' 'strict=True instead.' ), DeprecationWarning, ) # Check whether the iterables are all the same size. try: first_size = len(iterables[0]) for i, it in enumerate(iterables[1:], 1): size = len(it) if size != first_size: break else: # If we didn't break out, we can use the built-in zip. return zip(*iterables) # If we did break out, there was a mismatch. raise UnequalIterablesError(details=(first_size, i, size)) # If any one of the iterables didn't have a length, start reading # them until one runs out. except TypeError: return _zip_equal_generator(iterables) #----------------------------------------------------------------------------- # Solution by cjerdonek #----------------------------------------------------------------------------- class ExhaustedError(Exception): def __init__(self, index): &quot;&quot;&quot;The index is the 0-based index of the exhausted iterable.&quot;&quot;&quot; self.index = index def raising_iter(i): &quot;&quot;&quot;Return an iterator that raises an ExhaustedError.&quot;&quot;&quot; raise ExhaustedError(i) yield def terminate_iter(i, iterable): &quot;&quot;&quot;Return an iterator that raises an ExhaustedError at the end.&quot;&quot;&quot; return itertools.chain(iterable, raising_iter(i)) def zip_equal__chain_raising__cjerdonek(*iterables): iterators = [terminate_iter(*args) for args in enumerate(iterables)] try: yield from zip(*iterators) except ExhaustedError as exc: index = exc.index if index &gt; 0: raise RuntimeError('iterable {} exhausted first'.format(index)) from None # Check that all other iterators are also exhausted. for i, iterator in enumerate(iterators[1:], start=1): try: next(iterator) except ExhaustedError: pass else: raise RuntimeError('iterable {} is longer'.format(i)) from None #----------------------------------------------------------------------------- # Solution by Stefan Pochmann #----------------------------------------------------------------------------- def zip_equal__ziptail__Stefan_Pochmann(*iterables): # For trivial cases, use pure zip. if len(iterables) &lt; 2: return zip(*iterables) # Tail for the first iterable first_stopped = False def first_tail(): nonlocal first_stopped first_stopped = True return yield # Tail for the zip def zip_tail(): if not first_stopped: raise ValueError(f'zip_equal: first iterable is longer') for _ in chain.from_iterable(rest): raise ValueError(f'zip_equal: first iterable is shorter') yield # Put the pieces together iterables = iter(iterables) first = chain(next(iterables), first_tail()) rest = list(map(iter, iterables)) return chain(zip(first, *rest), zip_tail()) #----------------------------------------------------------------------------- # List of solutions to be speedtested #----------------------------------------------------------------------------- solutions = [ zip_equal__more_itertools__pylang, zip_equal__fillvalue__Martijn_Pieters, zip_equal__chain_raising__cjerdonek, zip_equal__ziptail__Stefan_Pochmann, zip, ] def name(solution): return solution.__name__[11:] or 'zip' #----------------------------------------------------------------------------- # The speedtest code #----------------------------------------------------------------------------- def test(m, n): &quot;&quot;&quot;Speedtest all solutions with m iterables of n elements each.&quot;&quot;&quot; all_times = {solution: [] for solution in solutions} def show_title(): print(f'{m} iterators of length {n:,}:') if verbose: show_title() def show_times(times, solution): print(*('%3d ms ' % t for t in times), name(solution)) for _ in range(3): for solution in solutions: times = sorted(timeit.repeat(lambda: deque(solution(*(repeat(i, n) for i in range(m))), 0), number=1, repeat=5))[:3] times = [round(t * 1e3, 3) for t in times] all_times[solution].append(times) if verbose: show_times(times, solution) if verbose: print() if verbose: print('best by min:') show_title() for solution in solutions: show_times(min(all_times[solution], key=min), solution) print('best by max:') show_title() for solution in solutions: show_times(min(all_times[solution], key=max), solution) print() stats.append((m, [min(all_times[solution], key=min) for solution in solutions])) #----------------------------------------------------------------------------- # Run the speedtest for several numbers of iterables #----------------------------------------------------------------------------- stats = [] verbose = False total_elements = 2 * 10**6 for m in 1, 2, 3, 4, 5, 10, 100, 1000, 10000, 50000, 100000: test(m, total_elements // m) #----------------------------------------------------------------------------- # Print the speedtest results for use in the plotting script #----------------------------------------------------------------------------- print('data for plotting by https://replit.com/@pochmann/zipequal-plot') names = [name(solution) for solution in solutions] print(f'{names = }') print(f'{stats = }') </code></pre> <p>Code for plotting/table (also <a href="https://replit.com/@pochmann/zipequal-plot" rel="nofollow noreferrer">at Replit</a>):</p> <pre><code>import matplotlib.pyplot as plt names = ['more_itertools__pylang', 'fillvalue__Martijn_Pieters', 'chain_raising__cjerdonek', 'ziptail__Stefan_Pochmann', 'zip'] stats = [(1, [[208.762, 211.211, 214.189], [159.568, 162.233, 162.24], [57.668, 58.94, 59.23], [10.418, 10.583, 10.723], [10.057, 10.443, 10.456]]), (2, [[130.065, 130.26, 130.52], [100.314, 101.206, 101.276], [34.405, 34.998, 35.188], [12.152, 12.473, 12.773], [8.671, 8.857, 9.395]]), (3, [[106.417, 107.452, 107.668], [90.693, 91.154, 91.386], [26.908, 27.863, 28.145], [10.457, 10.461, 10.789], [8.071, 8.157, 8.228]]), (4, [[97.547, 98.686, 98.726], [77.076, 78.31, 79.381], [23.134, 23.176, 23.181], [9.321, 9.4, 9.581], [7.541, 7.554, 7.635]]), (5, [[86.393, 88.046, 88.222], [68.633, 69.649, 69.742], [19.845, 20.006, 20.135], [8.726, 8.935, 9.016], [7.201, 7.26, 7.304]]), (10, [[70.384, 71.762, 72.473], [57.87, 58.149, 58.411], [15.808, 16.252, 16.262], [7.568, 7.57, 7.864], [6.732, 6.888, 6.911]]), (100, [[53.108, 54.245, 54.465], [44.436, 44.601, 45.226], [10.502, 11.073, 11.109], [6.721, 6.733, 6.847], [6.753, 6.774, 6.815]]), (1000, [[52.119, 52.476, 53.341], [42.775, 42.808, 43.649], [12.538, 12.853, 12.862], [6.802, 6.971, 7.002], [6.679, 6.724, 6.838]]), (10000, [[54.802, 55.006, 55.187], [45.981, 46.066, 46.735], [34.416, 34.672, 35.009], [9.485, 9.509, 9.626], [9.036, 9.042, 9.112]]), (50000, [[66.681, 66.98, 67.441], [56.593, 57.341, 57.631], [113.988, 114.022, 114.106], [22.088, 22.412, 22.595], [19.412, 19.431, 19.934]]), (100000, [[86.846, 88.111, 88.258], [74.796, 75.431, 75.927], [218.977, 220.182, 223.343], [38.89, 39.385, 39.88], [32.332, 33.117, 33.594]])] colors = { 'more_itertools__pylang': 'm', 'fillvalue__Martijn_Pieters': 'red', 'chain_raising__cjerdonek': 'gold', 'ziptail__Stefan_Pochmann': 'lime', 'zip': 'black', } ns = [n for n, _ in stats] print('%28s' % 'number of iterables', *('%5d' % n for n in ns)) print('-' * 95) x = range(len(ns)) for i, name in enumerate(names): ts = [min(tss[i]) for _, tss in stats] color = colors[name] if color: plt.plot(x, ts, '.-', color=color, label=name) print('%29s' % name, *('%5.1f' % t for t in ts)) plt.xticks(x, ns, size=9) plt.ylim(0, 133) plt.title('zip_equal(m iterables with 2,000,000/m values each)', weight='bold') plt.xlabel('Number of zipped *iterables* (not their lengths)', weight='bold') plt.ylabel('Time (for complete iteration) in milliseconds', weight='bold') plt.legend(loc='upper center') #plt.show() plt.savefig('zip_equal_plot.png', dpi=200) </code></pre>
32,814,161
How to make "spoiler" text in github wiki pages?
<p>I'm trying to make text which is either <em>invisible until moused over</em>, or, <em>has a "show" / "hide" button</em>, or some other thing, so that it is not visible until the user interacts with it in some way.</p> <p>I'm trying to do this on a github wiki page. (Specifically it's for a short self-quiz.)</p> <p>Basically I want to get a similar effect to what SO achieves with the <code>&gt;!</code> markup:</p> <blockquote class="spoiler"> <p> Hoho! Spoiler text!</p> </blockquote> <p>as described in <a href="https://meta.stackexchange.com/questions/1191/add-markdown-support-for-hidden-until-you-click-text-aka-spoilers">these</a> <a href="https://meta.stackexchange.com/questions/72877/whats-the-exact-syntax-for-spoiler-markup">meta</a> posts.</p> <p>The same markup doesn't work in github, I guess that it's an SO extension?</p> <p>I saw <a href="https://github.com/github/markup/issues/411" rel="noreferrer">this issue</a> about using spoiler text in <em>comments</em> on github, which was closed, but I thought there might be a different answer for the wiki pages, or a different solution based on HTML or something?</p> <p>Does anyone know if there's a way to do this, or if it is definitely unfortunately impossible?</p>
32,814,513
6
1
null
2015-09-28 00:13:03.353 UTC
27
2020-06-12 19:12:37.647 UTC
2017-03-20 10:29:34.447 UTC
null
-1
null
3,598,119
null
1
107
html|github|github-flavored-markdown
51,149
<p>The <a href="https://help.github.com/articles/github-flavored-markdown/">documentation for GitHub Flavored Markdown</a> makes no mention of spoilers, so I suspect it's not supported. It's definitely not part of <a href="https://daringfireball.net/projects/markdown/syntax">the original Markdown spec</a>.</p>
9,135,109
Add content to the bottom of the last page
<p>I am using wkhtmltopdf to create PDF reports from HTML, I need to create a custom report that follows this pattern:</p> <ol> <li>Some information at the top of the first page.</li> <li>A table that can have 1 to n rows (it should use any amount of pages it needs) </li> <li>Some information at the end of the last page.</li> </ol> <p>Putting all this together does the trick; however because step 3 info appears immediately after the table, is there a way to put the content at the end of the page?</p> <p>I am not even sure if this solution is CSS based or wkhtmltopdf based.</p>
9,204,788
3
0
null
2012-02-03 20:31:20.42 UTC
9
2017-12-20 01:49:30.693 UTC
2017-12-20 01:47:41.943 UTC
null
1,264,804
null
124,503
null
1
21
css|wkhtmltopdf
21,942
<p><a href="http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html" rel="noreferrer">http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html</a></p> <p>Take a look at "Footers And Headers" section.</p> <p>You can use <code>--footer-html</code> combined with some JavaScript to do this.</p> <pre><code>wkhtmltopdf --footer-html footer.html http://www.stackoverflow.com/ so.pdf </code></pre> <p>I based the contents of my <code>footer.html</code> on the example provided in the link above:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;script&gt; window.onload = function() { var vars = {}; var x = document.location.search.substring(1).split('&amp;'); for (var i in x) { var z = x[i].split('=', 2); vars[z[0]] = unescape(z[1]); } //if current page number == last page number if (vars['page'] == vars['topage']) { document.querySelectorAll('.extra')[0].textContent = 'extra text here'; } }; &lt;/script&gt; &lt;style&gt; .extra { color: red; } &lt;/style&gt; &lt;div class="extra"&gt;&lt;/div&gt; </code></pre>
9,065,941
How can I change vim status line color?
<p>I'm tring to change vim's status line color by editing my <code>.vimrc</code> .</p> <p>By using the command <code>au</code>, I tried to change the color of the status line when entering or leaving insert mode; by using this command nothing happens:</p> <p><code>hi StatusLine guibg=whatevercolourIwant</code></p> <p>By changing the status line color directly, without any <code>au</code> command, the background remains the same.</p> <p>Is there reason why by executing</p> <p><code>:hi StatusLine guibg=red</code>,</p> <p>for instance, the background of the status bar still remains greenish?</p>
9,066,085
3
0
null
2012-01-30 15:04:31.683 UTC
12
2018-02-22 17:22:01.497 UTC
2018-01-29 19:40:25.437 UTC
null
1,178,243
null
1,178,243
null
1
46
vim|background-color|statusbar
49,424
<p>if you are running vim in terminal, try:</p> <pre><code>hi StatusLine ctermbg=whatever ctermfg=whatever </code></pre> <p>guibg guifg are for GUI.</p> <p>hope it helps.</p>
10,772,799
How to install golang 3rd-party projects from download sources?
<p>I'm trying to install <a href="http://labix.org/mgo">mgo</a> which is a mongo-driver written in golang. </p> <p>The standard command: </p> <pre><code>go get launchpad.net/mgo </code></pre> <p>But it failed because of some cert issues.</p> <p>So I manually download the sources of mgo to local <code>E:\mgo</code>, but I don't know to how install it.</p> <p>The file tree:</p> <pre><code>├─.bzr │ ├─branch │ │ └─lock │ ├─branch-lock │ ├─checkout │ │ └─lock │ └─repository │ ├─indices │ ├─lock │ ├─obsolete_packs │ ├─packs │ └─upload ├─bson └─testdb </code></pre> <p>I tried:</p> <pre><code>cd mgo go install </code></pre> <p>It reports:</p> <pre><code>auth.go:34:2: import "launchpad.net/mgo/bson": cannot find package </code></pre> <p>But if I try to install bson first:</p> <pre><code>cd bson go install </code></pre> <p>It reports another error:</p> <pre><code>go install: no install location for _/E_/mgo/bson </code></pre> <p>So, what's the correct command to install it?</p>
10,773,041
4
1
null
2012-05-27 09:02:16.41 UTC
18
2017-09-21 01:07:01.493 UTC
2012-05-27 09:13:21.073 UTC
null
342,235
null
342,235
null
1
46
installation|go|mgo
65,676
<p>Finally I successfully install the mgo project. I think it will be helpful for beginners, so I answer it here.</p> <p><strong>First, we need GOPATH</strong></p> <p>Define a env variable <code>GOPATH</code>, which is your project root directory, and it should have a sub dir <code>src</code>.</p> <p>For me, I define it to <code>E:\WORKSPACE_GO\mgo</code>, then create a sub dir <code>src</code></p> <p><strong>Copy the project to the src</strong></p> <p>Then copy the <code>mgo</code> project to <code>%GOPATH%/mgo</code>, but we must be careful about the directory structure. It should be exactly the same as the package defined in sources.</p> <p>For <code>mgo</code>, it's package is <code>launchpad.net/mgo</code>, so the structure should be:</p> <pre><code>E:\WORKSPACE_GO\mgo\src\launchpad.net\mgo </code></pre> <p><strong>go install</strong></p> <p>At last, <code>go install</code> them:</p> <pre><code>cd E:\WORKSPACE_GO\mgo\src\launchpad.net\mgo\bson go install cd .. go install </code></pre> <p>If there is no error input, it should be successfully installed.</p>
7,542,480
What are the common use cases for __IPHONE_OS_VERSION_MAX_ALLOWED?
<p>What are the situations in which you would use the __IPHONE_OS_VERSION_MAX_ALLOWED check? What about __IPHONE_OS_VERSION_MIN_REQUIRED?</p>
8,050,536
2
3
null
2011-09-24 22:59:28.507 UTC
12
2012-10-15 08:31:22.06 UTC
2011-09-25 01:38:19.437 UTC
null
66,814
null
66,814
null
1
21
ios|cocoa-touch
16,614
<p>It's important to understand that these are <em>compile-time</em> constants, they are therefore not useful for detecting at runtime what platform or OS version you are running on (e.g. detecting if you are running on iPad vs iPhone).</p> <p>What these constants do is allow you to detect at <em>compile time</em> whether the code is being built for a given SDK or deployment target. For example, if you wrote an open source library that contains code that only works when compiled against the iOS 5 SDK, you might include this check to detect which SDK the code is being compiled for:</p> <pre><code>#if __IPHONE_OS_VERSION_MAX_ALLOWED &gt;= 50000 //you can use iOS 5 APIs here because the SDK supports them //but the code may still crash if run on an iOS 4 device #else //this code can't use iOS 5 APIs as the SDK version doesn't support them #endif </code></pre> <p>Or alternatively, if you want to see what the minimum OS version being targeted is...</p> <pre><code>#if __IPHONE_OS_VERSION_MIN_REQUIRED &gt;= 50000 //minimum deployment target is 5.0, so it's safe to use iOS 5-only code #else //you can use iOS5 APIs, but the code will need to be backwards //compatible or it will crash when run on an iOS 4 device #endif </code></pre> <p>This is different from detecting at runtime what OS you are running on. If you compile the code in the first example above using the iOS 4 SDK it will use your iOS 4-safe code, but won't take advantage of any iOS 5 features when run on an iOS 5 device. If you build it using the iOS 5 SDK then set the deployment target to iOS 4 and try to run it on an iOS 4 device, it will compile and install fine but may still crash at runtime because the iOS 5 APIs aren't there.</p> <p>In the second example above, if you set your deployment target to iOS 4 or below then it will use the iOS 4-safe code path, but if you set the deployment target to iOS 5, it won't run at all on an iOS 4 device (it will refuse to install).</p> <p>To build an app that runs on iOS 4 and 5 and is still able to take advantage of iOS 5 features if they are available, you need to do <em>run-time</em> detection. To detect the iOS version at runtime you can do this:</p> <pre><code>if ([[[UIDevice currentDevice] systemVersion] compare:@"5.0.1" options:NSNumericSearch] != NSOrderedAscending) { //running on iOS 5.0.1 or higher } </code></pre> <p>But that means keeping track of exactly which API features were added in which OS version, which is clunky and should only be done as a last resort. Usually, a better approach is to use feature detection, like this:</p> <pre><code>if ([SomeClass class]) { //this class exists } if ([SomeClass instancesRespondToSelector:@selector(someMethod:)]) { //this method exists } </code></pre> <p>Also, to detect at runtime if you are on an iPad or iPhone, you can do this:</p> <pre><code>if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) { //on an ipad } </code></pre> <p>Performing these checks at runtime allows you to create a single app that runs on multiple devices and iOS versions and is able to take advantage of the features of each platform.</p>
7,510,760
How do Formtastic and simple_form compare?
<p>How do <a href="https://github.com/formtastic/formtastic" rel="nofollow noreferrer">Formtastic</a> and <a href="https://github.com/heartcombo/simple_form" rel="nofollow noreferrer">simple_form</a> compare? What are the pros and cons of each?</p>
7,512,930
2
1
null
2011-09-22 06:56:45.617 UTC
10
2021-06-05 13:53:32.943 UTC
2021-06-05 13:46:14.353 UTC
null
74,089
null
72,442
null
1
63
ruby-on-rails|rubygems
12,893
<p><a href="https://github.com/justinfrench/formtastic" rel="nofollow noreferrer">Formtastic</a> and <a href="https://github.com/plataformatec/simple_form" rel="nofollow noreferrer">simple_form</a> are very similar, the usage is also very similar.</p> <p>The main difference is that the markup of <code>formtastic</code> is fixed. Mind you: if you don't mind, it is fantastic. It is really awesome to get started with. Also it comes with a default css, so your forms will look good straight out of the box.</p> <p>The advantage of <code>simple_form</code> over <code>formtastic</code> is that you can modify the markup to your needs. This can be handy if your designer likes your fields to be grouped inside div instead of li. The downside of <code>simple_form</code> is that it doesn't come with any standard layout (css). That makes formtastic much easier to start off with. Because the API is nearly identical, if needed, you can very easily switch to <code>simple_form</code> if needed.</p> <p>[UPDATE 22-6-2015] Actually, currently simple-form supports bootstrap out of the box, so for me personally I always prefer simple-form now.</p> <p>[UPDATE 29-07-2014] simple_form added an option of being compatible with ZURB Foundation forms.</p>
18,937,792
Github readme image embeds in private repo?
<p>I'm trying to embed an image in my <code>readme.md</code> for display on GitHub. I've had no trouble doing this before with public repositories, in this format:</p> <pre><code>![header image](https://raw.github.com/account/reponame/master/myimage.png) </code></pre> <p>I'm now doing the same for a private repo that lives under an organization account and getting a 404. If I navigate to the image in the repo and get the raw URL, I get something like:</p> <pre><code>https://raw.github.com/account/reponame/master/myimage.png?login=jackaperkins&amp;token=b295d913f6bf6e5cf1115755fb05e770 </code></pre> <p>Is there a way to tell GitHub to embed the real authenticated URL? I figured the access to the resource would be controlled with sessions outside of the URL but apparently not.</p>
18,938,186
3
0
null
2013-09-21 21:23:42.237 UTC
2
2020-06-10 10:48:36.657 UTC
2018-07-03 15:34:07.387 UTC
null
4,100,225
null
1,082,662
null
1
29
github|github-flavored-markdown
15,593
<p>You need a token if you use the raw paths. Assuming that the image file is in the same repository, you can do it like this:</p> <pre><code>![Image](../blob/master/myimage.png?raw=true) </code></pre> <p>More on <a href="https://github.com/blog/1395-relative-links-in-markup-files" rel="noreferrer">github blog</a></p>
19,109,754
Difference between mousedown and click in jquery
<p>I am learning events in jquery. While implementing them i came across a doubt. What is the difference between mousedown() and click() event. And which event should i use at what condition.?</p> <p>For example: Both the events perform the same task in the below code:</p> <pre><code>$("#p1").mousedown(function(){ alert("Mouse down over p1!"); }); $("#p1").click(function(){ alert("Mouse down over p1!"); }); </code></pre> <p>Both perform the same.Can someone clarify the difference. If same, which should i prefer?.</p>
19,109,828
7
1
null
2013-10-01 06:51:59.573 UTC
12
2018-11-16 05:34:19.443 UTC
null
null
null
null
1,703,886
null
1
46
jquery
55,919
<p><code>onMouseDown</code> will trigger when either the left or right (or middle) is pressed. Similarly, <code>onMouseUp</code> will trigger when any button is released. <code>onMouseDown</code> will trigger even when the mouse is clicked on the object then moved off of it, while <code>onMouseUp</code> will trigger if you click and hold the button elsewhere, then release it above the object.</p> <p><code>onClick</code> will only trigger when the left mouse button is pressed and released on the same object. In case you care about order, if the same object has all 3 events set, it's <code>onMouseDown</code>, <code>onMouseUp</code>, then <code>onClick</code>. Each even should only trigger once though.</p> <p>Details:</p> <p><a href="http://api.jquery.com/click/" rel="noreferrer">http://api.jquery.com/click/</a><br> <a href="http://api.jquery.com/mouseup/" rel="noreferrer">http://api.jquery.com/mouseup/</a><br> <a href="http://api.jquery.com/mousedown/" rel="noreferrer">http://api.jquery.com/mousedown/</a> </p> <p><a href="https://stackoverflow.com/a/12572682/2623074">Source</a> written by <a href="https://stackoverflow.com/users/1688274/anton-baksheiev">Anton Baksheiev</a></p>
19,175,084
ActiveRecord query through multiple joins
<p>I have a schema like this.</p> <p><img src="https://i.stack.imgur.com/70Yq9.png" alt="database schema"></p> <pre><code>managers has_many :emails has_many :stores emails belongs_to :manager stores belongs_to :manager belongs_to :region regions has_many :stores has_many :readings readings belongs_to :regions </code></pre> <p>I want to get readings for a manager. In SQL I would do something like this.</p> <pre><code>SELECT * FROM managers JOIN stores ON stores.manager_id = managers.id JOIN regions ON stores.region_id = regions.id JOIN readings ON readings.region_number = regions.number WHERE manager.name = 'John Smith' AND regions.number = '1234567' LIMIT 100 </code></pre> <p>I can't figure out how to do this in activerecord. I have been trying to make sense of <a href="http://guides.rubyonrails.org/active_record_querying.html" rel="noreferrer">http://guides.rubyonrails.org/active_record_querying.html</a> and <a href="http://guides.rubyonrails.org/association_basics.html" rel="noreferrer">http://guides.rubyonrails.org/association_basics.html</a> but it's not sinking in. I think I just need to see it from a different view point.</p> <p>I was thinking I would be accessing the data like this but I think I just don't understand how it works.</p> <pre><code>managers.name managers.stores.name managers.stores.regions.readings.limit(10) </code></pre> <p>I have been having to so something like this which is a whole lot uglier.</p> <pre><code>managers.first.stores.first.regions.first.readings.limit(10) </code></pre>
19,186,799
4
1
null
2013-10-04 06:53:17.023 UTC
13
2016-04-17 00:37:59.203 UTC
null
null
null
null
1,757,006
null
1
25
ruby-on-rails-4|rails-activerecord|active-record-query
43,420
<p>Consider the following models (and use of has_many through) :</p> <pre><code>class Reading &lt; ActiveRecord::Base belongs_to :region, inverse_of: :readings end class Region &lt; ActiveRecord::Base has_many :readings, inverse_of: :region has_many :stores, inverse_of: :region end class Store &lt; ActiveRecord::Base belongs_to :region, inverse_of: :stores belongs_to :manager, inverse_of: :stores end class Manager &lt; ActiveRecord::Base has_many :stores, inverse_of: :region has_many :emails, inverse_of: :manager has_many :regions, through: :stores has_many :readings, through: :regions end class Email &lt; ActiveRecord::Base belongs_to :manager, inverse_of: :emails end </code></pre> <p>Now your question is a little ambiguous because you say you want to obtain readings for a manager but your SQL doesn't select readings at all and also prescribes a region.</p> <p>Assuming you want all Reading's matching a given Manager and Region:</p> <pre><code>@readings = Reading.joins(region: { stores: :manager }).where( manager: { name: 'John Smith' }, region: { id: 1234567 }) </code></pre> <p>Assuming you also want to eager load regions, stores and managers to avoid 1+N queries:</p> <pre><code>@readings = Reading.includes(region: { stores: :manager }).where( manager: { name: 'John Smith' }, region: { id: 1234567 }) </code></pre> <p>Assuming you have a managers name and want both their details and readings:</p> <pre><code>@manager = Manager.where(name: 'John Smith').first! @readings = manager.readings </code></pre> <p>All of the above query examples return <code>ActiveRecord::Relation</code>'s which can be further chained with <code>where</code> conditions, or <code>joins</code>, <code>limit</code>, <code>group</code>, <code>having</code> and <code>order</code> etc</p> <p>You should also consider the differences of <code>joins</code>, <code>includes</code>, <code>preload</code>, <code>eager_load</code> and <code>references</code> methods. There is a brief on them <a href="http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html">here</a> I would alos encourage you to read docs, guides and blogs about Arel as it supports joins and aliasing too.</p> <p>After using ActiveRecord in anger for a while now I have come to the conclusion that Sequel/SequelModel is a much better DB/ORM than ActiveRecord. No disrespect to the developers but I've found Sequel is a better tool. Arel has thin documentation for years now and ActiveRecord/Arel have failings in a number of areas such as join conditions, control of join types and eager loading, unions, intersections, recursive queries, trees/adjacency lists, and many other SQL features that Sequel covers.</p> <p>Since you appear to be just starting out with AR you may wish to instead start out with Sequel than struggle with weaknesses and the frustrations of ActiveRecord querying including the disjointed use of AR and Arel, Relations vs Associations and query composition oddities, it goes on and on. There is nothing more frustrating than knowing the SQL you want but ActiveRecord/Arel conspire to stop you so you're forced to use the touted escape route and 'just use SQL string fragment' and you get back a result that can't be chained, but the rest of your code expects a Relation! (eg paged results)</p>
19,231,742
Bootstrap 3.0 - Fluid Grid that includes Fixed Column Sizes
<p>I am learning how to use Bootstrap. Currently, I'm wading my way through layouts. While Bootstrap is pretty cool, everything I see seems dated. For the life of me, I have what I think is a basic layout that I can't figure out. My layout looks like the following:</p> <pre><code>--------------------------------------------------------------------------- | | | | | | | | | 240px | 160px | All Remaining Width of the Window | | | | | | | | | --------------------------------------------------------------------------| </code></pre> <p>This grid needs to take up the full height of the window. From my understanding, I need to mix fixed and fluid widths. However, Bootstrap 3.0 doesn't seem to have the fluid class anymore. Even if it did, I can't seem to figure out how to mix fluid and fixed column sizes. Does anyone know how to do this in Bootstrap 3.0?</p>
19,234,005
8
2
null
2013-10-07 18:13:58.683 UTC
39
2018-03-14 15:39:03.26 UTC
2018-01-05 19:27:25.67 UTC
null
184,201
null
2,638,067
null
1
127
twitter-bootstrap|twitter-bootstrap-3
143,384
<p>There's really no easy way to mix fluid and fixed widths with Bootstrap 3. It's meant to be like this, as the grid system is designed to be a fluid, responsive thing. You could try hacking something up, but it would go against what the Responsive Grid system is trying to do, the intent of which is to make that layout flow across different device types.</p> <p>If you need to stick with this layout, I'd consider laying out your page with custom CSS and not using the grid.</p>
37,078,494
Dynamic routerLink value from ngFor item giving error "Got interpolation ({{}}) where expression was expected"
<p>I'm trying to set the <code>routerLink</code> value in a directive based on a dynamic set of items from the component. But an error is being thrown from Angular2:</p> <pre><code>EXCEPTION: Template parse errors: Parser Error: Got interpolation ({{}}) where expression was expected at column 1 in [ {{item.routerLink}} ] in AppHeader@5:40 (" &lt;a *ngFor="let item of headerItems" [ERROR -&gt;][routerLink]=" {{item.routerLink}} "&gt; {{item.text}} &lt;/a&gt; "): Header@5:40 </code></pre> <p><strong>header.component.ts</strong></p> <pre><code>import {Component} from '@angular/core'; import {ROUTER_DIRECTIVES} from '@angular/router-deprecated'; @Component({ selector: 'app-header', templateUrl: './app/components/header/header.component.html', directives: [ROUTER_DIRECTIVES] }) export class AppHeader { headerItems: Object[] = []; constructor() { this.headerItems.push( { classes: 'navLink', routerLink: ['/Home'], text: 'Home' } ); } } </code></pre> <p><strong>header.component.html</strong></p> <pre><code>&lt;div id="HeaderRegion"&gt; &lt;nav class="nav"&gt; &lt;a *ngFor="let item of headerItems" [routerLink]=" {{item.routerLink}} "&gt; {{item.text}} &lt;/a&gt; &lt;/nav&gt; &lt;/div&gt; </code></pre>
37,078,532
6
1
null
2016-05-06 17:45:21.337 UTC
7
2020-07-28 06:45:19.677 UTC
null
null
null
null
1,446,415
null
1
50
angular|angular2-directives
62,326
<p>You can't use <code>[]</code> combined with <code>{{}}</code> either the former or the later</p> <pre><code>[routerLink]="item.routerLink" </code></pre> <p>Should do what you want.</p> <pre><code>routerLink="{{item.routerLink}}" </code></pre> <p>would bind <code>item.routerLink.toString()</code> to the <code>routerLink</code> property.</p>
36,887,946
How to set secret files to kubernetes secrets by yaml?
<p>I want to store files in Kubernetes Secrets but I haven't found how to do it using a <code>yaml</code> file.</p> <p>I've been able to make it using the cli with <code>kubectl</code>:</p> <pre><code>kubectl create secret generic some-secret --from-file=secret1.txt=secrets/secret1.txt </code></pre> <p>But when I try something similar in a <code>yaml</code>:</p> <pre><code>apiVersion: v1 kind: Secret metadata: name: some-secret type: Opaque data: secret1.txt: secrets/secret1.txt </code></pre> <p>I´ve got this error:</p> <pre><code>[pos 73]: json: error decoding base64 binary 'assets/elasticsearch.yml': illegal base64 data at input byte 20 </code></pre> <p>I'm following this guide <a href="http://kubernetes.io/docs/user-guide/secrets/" rel="noreferrer">http://kubernetes.io/docs/user-guide/secrets/</a>. It explains how to create a secret using a <code>yaml</code> but not how to create a secret from a <strong>file</strong> using <code>yaml</code>.</p> <p>Is it possible? If so, how can I do it?</p>
36,888,629
6
2
null
2016-04-27 11:04:27.027 UTC
10
2020-07-26 06:50:22.957 UTC
2018-05-09 12:41:36.11 UTC
null
4,511,560
null
1,776,889
null
1
49
kubernetes|yaml|kubernetes-secrets
68,498
<p>When using the <code>CLI</code> format basically you're using a generator of the yaml before posting it to the server-side.</p> <p>Since Kubernetes is client-server app with REST API in between, and the actions need to be atomic, the posted YAML needs to contain the content of the file, and best way to do that is by embedding it as a base64 format in-line. It would be nice if the file could be otherwise embedded (indentation maybe could be used to create the boundaries of the file), but I haven't seen any example of such until now.</p> <p>That being said, putting a file reference on the yaml is not possible, there is no pre-flight rendering of the yaml to include the content.</p>
18,000,093
How to marshall and unmarshall a Parcelable to a byte array with help of Parcel?
<p>I want to marshall and unmarshall a Class that implements <code>Parcelable</code> to/from a byte array. <strong>I am well aware of the fact that the Parcelable representation is not stable and therefore not meant for long term storage of instances.</strong> But I have a use case where I need to serialize a object and it's not a showstopper if the unmarshalling fails because of an internal Android change. Also the class is already implementing the <code>Parcelable</code> interface.</p> <p>Given an class <code>MyClass implements Parcelable</code>, how can I (ab)use the <code>Parcelable</code> interface for marshalling/unmarshalling?</p>
18,000,094
2
0
null
2013-08-01 16:54:37.85 UTC
35
2016-08-11 09:07:52.67 UTC
2015-06-22 12:17:46.53 UTC
null
194,894
null
194,894
null
1
47
android|marshalling|unmarshalling|parcelable|parcel
22,079
<p>First create a helper class <strong>ParcelableUtil.java</strong>:</p> <pre><code>public class ParcelableUtil { public static byte[] marshall(Parcelable parceable) { Parcel parcel = Parcel.obtain(); parceable.writeToParcel(parcel, 0); byte[] bytes = parcel.marshall(); parcel.recycle(); return bytes; } public static Parcel unmarshall(byte[] bytes) { Parcel parcel = Parcel.obtain(); parcel.unmarshall(bytes, 0, bytes.length); parcel.setDataPosition(0); // This is extremely important! return parcel; } public static &lt;T&gt; T unmarshall(byte[] bytes, Parcelable.Creator&lt;T&gt; creator) { Parcel parcel = unmarshall(bytes); T result = creator.createFromParcel(parcel); parcel.recycle(); return result; } } </code></pre> <p>With the help of the util class above, you can marshall/unmarshall instances of your class <code>MyClass implements Parcelable</code> like so:</p> <p><strong>Unmarshalling (with <code>CREATOR</code>)</strong></p> <pre><code>byte[] bytes = … MyClass myclass = ParcelableUtil.unmarshall(bytes, MyClass.CREATOR); </code></pre> <p><strong>Unmarshalling (without <code>CREATOR</code>)</strong></p> <pre><code>byte[] bytes = … Parcel parcel = ParcelableUtil.unmarshall(bytes); MyClass myclass = new MyClass(parcel); // Or MyClass.CREATOR.createFromParcel(parcel). </code></pre> <p><strong>Marshalling</strong></p> <pre><code>MyClass myclass = … byte[] bytes = ParcelableUtil.marshall(myclass); </code></pre>
18,339,500
How to use WordPress Contact Form 7 in my own HTML?
<p>I want to use WordPress Contact Form 7 on my website, but I already have an HTML/CSS layout for it. So, I want to modify the plugin to use it with that custom HTML code.</p> <pre><code>&lt;form id=&quot;contact_form&quot; action=&quot;&quot; method=&quot;post&quot;&gt; &lt;div&gt; &lt;label for=&quot;contact_name&quot;&gt;Nombre&lt;/label&gt; &lt;input id=&quot;contact_name&quot; type=&quot;text&quot; required aria-required=&quot;true&quot; placeholder=&quot;Nombre&quot;&gt; &lt;/div&gt; &lt;div&gt; &lt;label for=&quot;contact_email&quot;&gt;Email&lt;/label&gt; &lt;input id=&quot;contact_email&quot; type=&quot;mail&quot; name=&quot;email&quot; required aria-required=&quot;true&quot; placeholder=&quot;[email protected]&quot;&gt; &lt;/div&gt; &lt;div id=&quot;area_message&quot;&gt; &lt;label for=&quot;contact_message&quot;&gt;Mensaje&lt;/label&gt; &lt;textarea id=&quot;contact_message&quot; type=&quot;mail&quot; required aria-required=&quot;true&quot; placeholder=&quot;Mensaje&quot;&gt;&lt;/textarea&gt; &lt;input id=&quot;contact_btn&quot; type=&quot;submit&quot; value=&quot;enviar&quot;&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>My question is: do I have to modify this code with some Contact Form 7 code or should I include this into the plugin administration?</p>
18,348,181
2
0
null
2013-08-20 15:48:03.94 UTC
1
2022-07-05 08:54:08.053 UTC
2022-07-05 08:53:51.553 UTC
null
1,145,388
null
2,402,579
null
1
12
html|css|wordpress|contact-form-7
56,077
<p>No need to modify anything. Contact Form 7 supports this out of the box. Have you tried using it or looked at the documentation yet? If so, what is or isn't working for you?</p> <p><strong>Update based on comments below</strong></p> <p>Contact Form 7 gives you a shortcode for each field you generated. You can wrap the shortcode in HTML in the &quot;Form&quot; section. Using the example you provided in your question, that would look like this:</p> <pre><code>&lt;div&gt; &lt;label for=&quot;contact_name&quot;&gt;Nombre&lt;/label&gt; [text* your-name 20/40 class:required &quot;John Smith&quot;] &lt;/div&gt; </code></pre> <p>You don't need to wrap this in a <code>&lt;form&gt;</code> tags - Contact Form 7 does that already (and assigns an ID).</p> <p>In your WordPress text editor, use the form shortcode provided at the top of the Contact Form 7 interface to display your final output. If you'd prefer to put this in a PHP template, use this:</p> <pre><code>&lt;?php echo do_shortcode(&quot;SHORTCODE GOES HERE&quot;); ?&gt; </code></pre> <p>Contact Form 7 also has a section for mail, where you would identify who the mail should go to and come from. Some hosting providers (DreamHost, for example), require the FROM email to be the same domain as the site itself (a form on <code>http://example.com</code> would need to send emails from <code>[email protected]</code>, or a similar address). To make sure you can still reply to the right address, you would add a replyto header like this:</p> <pre><code>Reply-To: [email] </code></pre> <p>Only change <code>[email]</code> to match whatever the outputted shortcode for your email field was.</p> <p>But seriously, this stuff is ALL in the documentation for Contact Form 7: <a href="http://contactform7.com/docs/" rel="nofollow noreferrer">http://contactform7.com/docs/</a></p>
1,960,957
Twitter API - Logout
<p>I'm using OAuth in my web app, and users can login with twitter.</p> <p>I want to add "switch twitter account" button, which actually clears the session and then opens the authorize_url.</p> <p>As clearing the session in my web app doesn't log out of twitter, the authorize_url will automatically authenticate the current twitter.com user. That means I can't do logout, unless I send the user to twitter.com.</p> <p>Is it possible with the API? What is the best way to implement this?</p>
1,961,377
3
0
null
2009-12-25 10:46:15.923 UTC
12
2017-07-29 05:31:31.387 UTC
2012-02-21 21:12:50.047 UTC
null
26,406
null
116,925
null
1
29
oauth|twitter|logout
27,247
<p>The session with Twitter is defined by a cookie owned by Twitter -- something you do not have control over. You cannot log them out of Twitter on their behalf. </p> <p>If you want someone to be able to use your "switch twitter account" functionality, you'll need to pass them off to the OAuth handshake again, but use the <code>/oauth/authorize</code> path instead of the <code>/oauth/authenticate</code> path. This will allow the user to switch their user credentials at Twitter during the handshake instead of just re-authenticating using their existing Twitter session.</p> <p>Alternatively, you could have a separate notion of users in your own app whereby you have your own user model that has many twitter accounts associated with it. That way, you could allow your users to switch accounts more seemlessly. They would have to authorize your app up front for each of their twitter accounts, but you would have all their oauth keys for each of their twitter accounts after that.</p>
27,387,912
Keyword not supported: 'provider'. Opening SqlConnection
<p>I don't know why this error, I tried everything. I want to connect my webForm to the Database .accdb and when I use using(){} I got this error "Keyword not supported: 'provider" Here is the code:</p> <p><strong>web.config</strong></p> <pre><code>&lt;connectionStrings&gt; &lt;add name="ConnectionString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Manuel_2\Documents\Login.accdb" providerName="System.Data.OleDb" /&gt; &lt;/connectionStrings&gt; </code></pre> <p><strong>WebForm1</strong></p> <pre><code>private static string conDB = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; protected void Page_Load(object sender, EventArgs e) { using (SqlConnection con = new SqlConnection(connDB)) //here is the error { // ..... } } </code></pre>
27,388,264
5
4
null
2014-12-09 20:10:48.123 UTC
1
2022-01-24 14:16:16.207 UTC
2019-06-16 16:44:59.31 UTC
null
159,270
null
1,507,317
null
1
17
c#|asp.net
63,253
<p>Aleksey Mynkov has it right. But here is more detail since you are needing more clarification.</p> <p>Your web.config is fine. The auto-generated Visual Studios connection string is using the right setup. Instead, on your webform1 file you need to do 2 things.</p> <ol> <li><p>Add <code>using System.Data.OleDb.OleDbConnection;</code> to the top of your file, and remove the <code>using System.Data.SqlConnection;</code></p> </li> <li><p>Change your webform1 code to be:</p> <pre><code> private static string conDB = ConfigurationManager.ConnectionStrings[&quot;ConnectionString&quot;].ConnectionString; protected void Page_Load(object sender, EventArgs e) { using (OleDbConnection con = new OleDbConnection(conDB)) //here is the error { } } </code></pre> </li> </ol>
19,808,710
HTML table width not working
<pre><code>&lt;!DOCTYPE html&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table border="1" width="100%"&gt; &lt;tr&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I am trying to set the table width to 100% for above table but it has no effect it goes beyond window width. how do i change the width of table so it is same size as window.</p>
19,809,081
8
1
null
2013-11-06 09:48:44.983 UTC
7
2021-01-12 10:19:58.247 UTC
2015-11-19 11:44:00.163 UTC
null
4,040,817
null
2,959,594
null
1
28
html|css|width|html-table
82,524
<p>The problem is, the content inside your table requires more space than 100% of your window-size offers. </p> <p>What you could do, is to use the overflow-property of CSS. Try the following example and chose, wether this is an option for you:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;style&gt; .table { color: green; display: block; max-width: 100%; overflow: scroll; &lt;!-- Available options: visible, hidden, scroll, auto --&gt; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;table border="1" class="table"&gt; &lt;tr&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;td&gt;aaaaaaaaaaaaaaaaaaaaaaaaaaaaa&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>There are 4 options available for the overflow-property: visible, hidden, scroll and auto. The above example illustrates the scroll-option, which adds a scroll-bar to the table itself.</p>
58,631,724
Paths.get vs Path.of
<p>As far as I can tell, <code>Paths.get</code> and <code>Path.of</code> seem to do exactly the same thing, turning one or more strings into a <code>Path</code> object; the documentations for <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/file/Paths.html#get-java.lang.String-java.lang.String" rel="noreferrer"><code>Paths.get</code></a> and <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/file/Path.html#of(java.lang.String,java.lang.String)" rel="noreferrer"><code>Path.of</code></a> use the same wording. Are they in fact identical?</p> <p><code>Path.of</code> was introduced later.</p> <p><em>Conjecture:</em> it was introduced for the sake of a consistent <code>Foo.of</code> style. In that case, it would be considered preferable on consistency/aesthetic grounds?</p>
58,631,951
1
2
null
2019-10-30 18:32:08.5 UTC
3
2022-04-15 08:05:33.473 UTC
2022-04-15 08:05:33.473 UTC
null
15,773,392
null
45,843
null
1
53
java|java-11
32,732
<p>Indeed, <code>Path.of</code> was later introduced. </p> <blockquote> <p>Conjecture: it was introduced for the sake of a consistent <code>Foo.of</code> style.</p> </blockquote> <p>From the mailing list archive, this <a href="http://mail.openjdk.java.net/pipermail/nio-dev/2018-March/004810.html" rel="noreferrer">method was once called <code>Path.get</code></a>:</p> <blockquote> <p>The main changes in are in Path and Paths in java.nio.file.</p> <p>This patch copies the Paths.get() methods to static methods in Path.get() and modifies the former to call the latter respective methods. The Path specification is slightly cleaned up not to refer to Paths nor itself, e.g., “(see Path).” @implSpec annotations are added to Paths to indicate that the methods simply call their counterparts in Path.<br> ...</p> </blockquote> <p>This was later changed when <a href="http://mail.openjdk.java.net/pipermail/nio-dev/2018-March/004828.html" rel="noreferrer">Brian Goetz suggested it to be consistent with <code>Foo.of</code></a>:</p> <blockquote> <p>Separately, Brian Goetz suggested off-list that it would be more consistent if these factory methods were named "of" so I assume the webrev will be updated to see how that looks.</p> </blockquote> <p>Now to your last question: "In that case, it would be considered preferable on consistency/aesthetic grounds?"<br> In the <a href="http://mail.openjdk.java.net/pipermail/nio-dev/2018-March/004810.html" rel="noreferrer">initial mail</a> Brian Burkhalter said that he updated all references to the new method in <code>Path</code>:</p> <blockquote> <p>All source files in java.base are modified to change Paths.get() to Path.get() and to remove the import for Paths. ...</p> </blockquote> <p>So I would therefore conclude that <code>Path.of</code> is indeed preferable to <code>Paths.get</code>.<br> Indeed, if you look at the <a href="https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/nio/file/Paths.html" rel="noreferrer">Javadoc for <code>Paths</code> for Java 13</a> you will find this note:</p> <blockquote> <p><strong>API Note</strong>:<br> It is recommended to obtain a <code>Path</code> via the <code>Path.of</code> methods instead of via the <code>get</code> methods defined in this class as this class may be deprecated in a future release.</p> </blockquote>
765,408
Free easy way to draw graphs and charts in C++?
<p>I am doing a little exploring simulation and I want to show the graphs to compare the performance among the algorithms during run-time.</p> <p>What library comes to your mind? I highly prefer those that come small as I'd love if it's easy for my instructor to compile my code. I've checked <a href="http://www.fred.net/brv/chart/" rel="noreferrer">gdchart</a> but it seems to be too heavy. I just want a simple x-y sort of timeline graph.</p> <p>Google chart is of course out of the question, in case you've read <a href="https://stackoverflow.com/questions/82294/is-there-any-open-source-library-in-c-for-3d-chart">this</a> similar question.</p> <hr> <p>Related post <a href="https://stackoverflow.com/questions/215110/scatter-plots-in-c/">Scatter Plots in C++</a>.</p>
765,474
4
4
null
2009-04-19 13:25:47.557 UTC
20
2017-10-28 14:21:18.217 UTC
2017-10-28 14:21:18.217 UTC
null
3,924,118
null
15,345
null
1
32
c++|charts
138,163
<p>My favourite has always been <a href="http://www.gnuplot.info/" rel="noreferrer">gnuplot</a>. It's very extensive, so it might be a bit too complex for your needs though. It is cross-platform and there is <a href="http://www.stahlke.org/dan/gnuplot-iostream/" rel="noreferrer">a C++ API</a>.</p>
726,837
User Group and Role Management in .NET with Active Directory
<p>I'm currently researching methods for storing user roles and permissions for .NET based projects. Some of these projects are web based, some are not. I'm currently struggling to find the best method to achieve what I'm looking for in a consistent, portable way across project types.</p> <p>Where I'm at, we're looking to leverage Active Directory as our single point of contact for basic user information. Because of this, we're looking to not have to maintain a custom database for each application's users since they are already stored in Active Directory and actively maintained there. Additionally, we don't want to write our own security model/code if possible and would like to use something pre-existing, like the security application blocks provided by Microsoft.</p> <p>Some projects require only basic privileges, such as read, write, or no access. Other projects require more complex permissions. Users of those applications might be granted access to some areas, but not others, and their permissions can change across each area. An administration section of the app would control and define this access, <strong>not</strong> the AD tools. </p> <p>Currently, we're using integrated Windows Authentication to perform authentication on our intranet. This works well for finding out basic user information, and I've seen that ASP.NET can be extended to provide an Active Directory roles provider, so I can find out any security groups a user belongs to. But, what seems like the downfall of this method to me is that everything is stored in Active Directory, which could lead to a mess to maintain if things grow too big. </p> <p>Along this same line, I've also heard of Active Directory Lightweight Directory Services, which seems like it could extend our schema and add only application specific attributes and groups. Problem is, I can't find anything on how this would be done or how this works. There are MSDN articles that describe how to talk to this instance and how to create a new instance, but nothing ever seems to answer my question.</p> <p><strong>My question is:</strong> Based on your experience, am I going down the right track? Is what I'm looking to do possible using just Active Directory, or do other tools have to be used?</p> <hr> <p><strong>Other methods I've looked into:</strong></p> <ul> <li>Using multiple web.config files [<a href="https://stackoverflow.com/questions/176338/customer-configurable-asp-net-web-site-security-for-fine-grained-control-of-page">stackoverflow</a>]</li> <li>Creating a custom security model and database to manage users across applications</li> </ul>
728,808
1
1
null
2009-04-07 17:40:35.173 UTC
58
2013-07-30 23:44:17.047 UTC
2017-05-23 11:54:43.513 UTC
null
-1
null
48,421
null
1
62
.net|asp.net|security|active-directory
52,506
<p>Using AD for your authentication is a great idea, since you need to add everyone there anyway, and for intranet users there's no need for an extra login.</p> <p>You're correct that ASP.NET allows you to use a Provider which will allow you to authenticate against AD, although there's nothing included to give you group membership support (although it's quite trivial to implement if you want to, I can provide a sample).</p> <p>The real issue here is if you want to use AD groups to define permissions within each app, yes?</p> <p>If so then you do have the option of creating your own RoleProvider for ASP.NET that can also be used by WinForms and WPF apps via ApplicationServices. This RoleProvider could link the ID of the user in AD to groups/roles per app which you can store in your own custom database, which also allows each app to allow administration of these roles without requiring these admins to have extra privileges in AD. </p> <p>If you want you can also have an override and combine app roles with AD groups, so if they're in some global "Admin" group in AD they get full permission in the App regardless of App role membership. Conversely if they have either a group or property in AD to say they've been fired you could ignore all App role membership and restrict all access (since HR probably wouldn't remove them from each and every app, assuming they even know about them all!).</p> <p>Sample code added as requested:</p> <p><strong>NOTE: based on this original work <a href="http://www.codeproject.com/Articles/28546/Active-Directory-Roles-Provider" rel="noreferrer">http://www.codeproject.com/Articles/28546/Active-Directory-Roles-Provider</a></strong></p> <p>For your ActiveDirectoryMembershipProvider you only need to implement the ValidateUser method, although you could implement more if you desired, the new AccountManagement namespace makes this trivial:</p> <pre><code>// assumes: using System.DirectoryServices.AccountManagement; public override bool ValidateUser( string username, string password ) { bool result = false; try { using( var context = new PrincipalContext( ContextType.Domain, "yourDomainName" ) ) { result = context.ValidateCredentials( username, password ); } } catch( Exception ex ) { // TODO: log exception } return result; } </code></pre> <p>For your role provider it's a little bit more work, there's some key issues we discovered while searching google such as groups you want to exclude, users you want to exclude etc.</p> <p>It's probably worth a full blog post, but this should help you get started, it's caching lookups in Session variables, just as a sample of how you could improve performance (since a full Cache sample would be too long).</p> <pre><code>using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration.Provider; using System.Diagnostics; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; using System.Linq; using System.Web; using System.Web.Hosting; using System.Web.Security; namespace MyApp.Security { public sealed class ActiveDirectoryRoleProvider : RoleProvider { private const string AD_FILTER = "(&amp;(objectCategory=group)(|(groupType=-2147483646)(groupType=-2147483644)(groupType=-2147483640)))"; private const string AD_FIELD = "samAccountName"; private string _activeDirectoryConnectionString; private string _domain; // Retrieve Group Mode // "Additive" indicates that only the groups specified in groupsToUse will be used // "Subtractive" indicates that all Active Directory groups will be used except those specified in groupsToIgnore // "Additive" is somewhat more secure, but requires more maintenance when groups change private bool _isAdditiveGroupMode; private List&lt;string&gt; _groupsToUse; private List&lt;string&gt; _groupsToIgnore; private List&lt;string&gt; _usersToIgnore; #region Ignore Lists // IMPORTANT - DEFAULT LIST OF ACTIVE DIRECTORY USERS TO "IGNORE" // DO NOT REMOVE ANY OF THESE UNLESS YOU FULLY UNDERSTAND THE SECURITY IMPLICATIONS // VERYIFY THAT ALL CRITICAL USERS ARE IGNORED DURING TESTING private String[] _DefaultUsersToIgnore = new String[] { "Administrator", "TsInternetUser", "Guest", "krbtgt", "Replicate", "SERVICE", "SMSService" }; // IMPORTANT - DEFAULT LIST OF ACTIVE DIRECTORY DOMAIN GROUPS TO "IGNORE" // PREVENTS ENUMERATION OF CRITICAL DOMAIN GROUP MEMBERSHIP // DO NOT REMOVE ANY OF THESE UNLESS YOU FULLY UNDERSTAND THE SECURITY IMPLICATIONS // VERIFY THAT ALL CRITICAL GROUPS ARE IGNORED DURING TESTING BY CALLING GetAllRoles MANUALLY private String[] _defaultGroupsToIgnore = new String[] { "Domain Guests", "Domain Computers", "Group Policy Creator Owners", "Guests", "Users", "Domain Users", "Pre-Windows 2000 Compatible Access", "Exchange Domain Servers", "Schema Admins", "Enterprise Admins", "Domain Admins", "Cert Publishers", "Backup Operators", "Account Operators", "Server Operators", "Print Operators", "Replicator", "Domain Controllers", "WINS Users", "DnsAdmins", "DnsUpdateProxy", "DHCP Users", "DHCP Administrators", "Exchange Services", "Exchange Enterprise Servers", "Remote Desktop Users", "Network Configuration Operators", "Incoming Forest Trust Builders", "Performance Monitor Users", "Performance Log Users", "Windows Authorization Access Group", "Terminal Server License Servers", "Distributed COM Users", "Administrators", "Everybody", "RAS and IAS Servers", "MTS Trusted Impersonators", "MTS Impersonators", "Everyone", "LOCAL", "Authenticated Users" }; #endregion /// &lt;summary&gt; /// Initializes a new instance of the ADRoleProvider class. /// &lt;/summary&gt; public ActiveDirectoryRoleProvider() { _groupsToUse = new List&lt;string&gt;(); _groupsToIgnore = new List&lt;string&gt;(); _usersToIgnore = new List&lt;string&gt;(); } public override String ApplicationName { get; set; } /// &lt;summary&gt; /// Initialize ADRoleProvider with config values /// &lt;/summary&gt; /// &lt;param name="name"&gt;&lt;/param&gt; /// &lt;param name="config"&gt;&lt;/param&gt; public override void Initialize( String name, NameValueCollection config ) { if ( config == null ) throw new ArgumentNullException( "config" ); if ( String.IsNullOrEmpty( name ) ) name = "ADRoleProvider"; if ( String.IsNullOrEmpty( config[ "description" ] ) ) { config.Remove( "description" ); config.Add( "description", "Active Directory Role Provider" ); } // Initialize the abstract base class. base.Initialize( name, config ); _domain = ReadConfig( config, "domain" ); _isAdditiveGroupMode = ( ReadConfig( config, "groupMode" ) == "Additive" ); _activeDirectoryConnectionString = ReadConfig( config, "connectionString" ); DetermineApplicationName( config ); PopulateLists( config ); } private string ReadConfig( NameValueCollection config, string key ) { if ( config.AllKeys.Any( k =&gt; k == key ) ) return config[ key ]; throw new ProviderException( "Configuration value required for key: " + key ); } private void DetermineApplicationName( NameValueCollection config ) { // Retrieve Application Name ApplicationName = config[ "applicationName" ]; if ( String.IsNullOrEmpty( ApplicationName ) ) { try { string app = HostingEnvironment.ApplicationVirtualPath ?? Process.GetCurrentProcess().MainModule.ModuleName.Split( '.' ).FirstOrDefault(); ApplicationName = app != "" ? app : "/"; } catch { ApplicationName = "/"; } } if ( ApplicationName.Length &gt; 256 ) throw new ProviderException( "The application name is too long." ); } private void PopulateLists( NameValueCollection config ) { // If Additive group mode, populate GroupsToUse with specified AD groups if ( _isAdditiveGroupMode &amp;&amp; !String.IsNullOrEmpty( config[ "groupsToUse" ] ) ) _groupsToUse.AddRange( config[ "groupsToUse" ].Split( ',' ).Select( group =&gt; group.Trim() ) ); // Populate GroupsToIgnore List&lt;string&gt; with AD groups that should be ignored for roles purposes _groupsToIgnore.AddRange( _defaultGroupsToIgnore.Select( group =&gt; group.Trim() ) ); _groupsToIgnore.AddRange( ( config[ "groupsToIgnore" ] ?? "" ).Split( ',' ).Select( group =&gt; group.Trim() ) ); // Populate UsersToIgnore ArrayList with AD users that should be ignored for roles purposes string usersToIgnore = config[ "usersToIgnore" ] ?? ""; _usersToIgnore.AddRange( _DefaultUsersToIgnore .Select( value =&gt; value.Trim() ) .Union( usersToIgnore .Split( new[] { "," }, StringSplitOptions.RemoveEmptyEntries ) .Select( value =&gt; value.Trim() ) ) ); } private void RecurseGroup( PrincipalContext context, string group, List&lt;string&gt; groups ) { var principal = GroupPrincipal.FindByIdentity( context, IdentityType.SamAccountName, group ); if ( principal == null ) return; List&lt;string&gt; res = principal .GetGroups() .ToList() .Select( grp =&gt; grp.Name ) .ToList(); groups.AddRange( res.Except( groups ) ); foreach ( var item in res ) RecurseGroup( context, item, groups ); } /// &lt;summary&gt; /// Retrieve listing of all roles to which a specified user belongs. /// &lt;/summary&gt; /// &lt;param name="username"&gt;&lt;/param&gt; /// &lt;returns&gt;String array of roles&lt;/returns&gt; public override string[] GetRolesForUser( string username ) { string sessionKey = "groupsForUser:" + username; if ( HttpContext.Current != null &amp;&amp; HttpContext.Current.Session != null &amp;&amp; HttpContext.Current.Session[ sessionKey ] != null ) return ( (List&lt;string&gt;) ( HttpContext.Current.Session[ sessionKey ] ) ).ToArray(); using ( PrincipalContext context = new PrincipalContext( ContextType.Domain, _domain ) ) { try { // add the users groups to the result var groupList = UserPrincipal .FindByIdentity( context, IdentityType.SamAccountName, username ) .GetGroups() .Select( group =&gt; group.Name ) .ToList(); // add each groups sub groups into the groupList foreach ( var group in new List&lt;string&gt;( groupList ) ) RecurseGroup( context, group, groupList ); groupList = groupList.Except( _groupsToIgnore ).ToList(); if ( _isAdditiveGroupMode ) groupList = groupList.Join( _groupsToUse, r =&gt; r, g =&gt; g, ( r, g ) =&gt; r ).ToList(); if ( HttpContext.Current != null ) HttpContext.Current.Session[ sessionKey ] = groupList; return groupList.ToArray(); } catch ( Exception ex ) { // TODO: LogError( "Unable to query Active Directory.", ex ); return new[] { "" }; } } } /// &lt;summary&gt; /// Retrieve listing of all users in a specified role. /// &lt;/summary&gt; /// &lt;param name="rolename"&gt;String array of users&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public override string[] GetUsersInRole( String rolename ) { if ( !RoleExists( rolename ) ) throw new ProviderException( String.Format( "The role '{0}' was not found.", rolename ) ); using ( PrincipalContext context = new PrincipalContext( ContextType.Domain, _domain ) ) { try { GroupPrincipal p = GroupPrincipal.FindByIdentity( context, IdentityType.SamAccountName, rolename ); return ( from user in p.GetMembers( true ) where !_usersToIgnore.Contains( user.SamAccountName ) select user.SamAccountName ).ToArray(); } catch ( Exception ex ) { // TODO: LogError( "Unable to query Active Directory.", ex ); return new[] { "" }; } } } /// &lt;summary&gt; /// Determine if a specified user is in a specified role. /// &lt;/summary&gt; /// &lt;param name="username"&gt;&lt;/param&gt; /// &lt;param name="rolename"&gt;&lt;/param&gt; /// &lt;returns&gt;Boolean indicating membership&lt;/returns&gt; public override bool IsUserInRole( string username, string rolename ) { return GetUsersInRole( rolename ).Any( user =&gt; user == username ); } /// &lt;summary&gt; /// Retrieve listing of all roles. /// &lt;/summary&gt; /// &lt;returns&gt;String array of roles&lt;/returns&gt; public override string[] GetAllRoles() { string[] roles = ADSearch( _activeDirectoryConnectionString, AD_FILTER, AD_FIELD ); return ( from role in roles.Except( _groupsToIgnore ) where !_isAdditiveGroupMode || _groupsToUse.Contains( role ) select role ).ToArray(); } /// &lt;summary&gt; /// Determine if given role exists /// &lt;/summary&gt; /// &lt;param name="rolename"&gt;Role to check&lt;/param&gt; /// &lt;returns&gt;Boolean indicating existence of role&lt;/returns&gt; public override bool RoleExists( string rolename ) { return GetAllRoles().Any( role =&gt; role == rolename ); } /// &lt;summary&gt; /// Return sorted list of usernames like usernameToMatch in rolename /// &lt;/summary&gt; /// &lt;param name="rolename"&gt;Role to check&lt;/param&gt; /// &lt;param name="usernameToMatch"&gt;Partial username to check&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public override string[] FindUsersInRole( string rolename, string usernameToMatch ) { if ( !RoleExists( rolename ) ) throw new ProviderException( String.Format( "The role '{0}' was not found.", rolename ) ); return ( from user in GetUsersInRole( rolename ) where user.ToLower().Contains( usernameToMatch.ToLower() ) select user ).ToArray(); } #region Non Supported Base Class Functions /// &lt;summary&gt; /// AddUsersToRoles not supported. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory. /// &lt;/summary&gt; public override void AddUsersToRoles( string[] usernames, string[] rolenames ) { throw new NotSupportedException( "Unable to add users to roles. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory." ); } /// &lt;summary&gt; /// CreateRole not supported. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory. /// &lt;/summary&gt; public override void CreateRole( string rolename ) { throw new NotSupportedException( "Unable to create new role. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory." ); } /// &lt;summary&gt; /// DeleteRole not supported. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory. /// &lt;/summary&gt; public override bool DeleteRole( string rolename, bool throwOnPopulatedRole ) { throw new NotSupportedException( "Unable to delete role. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory." ); } /// &lt;summary&gt; /// RemoveUsersFromRoles not supported. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory. /// &lt;/summary&gt; public override void RemoveUsersFromRoles( string[] usernames, string[] rolenames ) { throw new NotSupportedException( "Unable to remove users from roles. For security and management purposes, ADRoleProvider only supports read operations against Active Direcory." ); } #endregion /// &lt;summary&gt; /// Performs an extremely constrained query against Active Directory. Requests only a single value from /// AD based upon the filtering parameter to minimize performance hit from large queries. /// &lt;/summary&gt; /// &lt;param name="ConnectionString"&gt;Active Directory Connection String&lt;/param&gt; /// &lt;param name="filter"&gt;LDAP format search filter&lt;/param&gt; /// &lt;param name="field"&gt;AD field to return&lt;/param&gt; /// &lt;returns&gt;String array containing values specified by 'field' parameter&lt;/returns&gt; private String[] ADSearch( String ConnectionString, String filter, String field ) { DirectorySearcher searcher = new DirectorySearcher { SearchRoot = new DirectoryEntry( ConnectionString ), Filter = filter, PageSize = 500 }; searcher.PropertiesToLoad.Clear(); searcher.PropertiesToLoad.Add( field ); try { using ( SearchResultCollection results = searcher.FindAll() ) { List&lt;string&gt; r = new List&lt;string&gt;(); foreach ( SearchResult searchResult in results ) { var prop = searchResult.Properties[ field ]; for ( int index = 0; index &lt; prop.Count; index++ ) r.Add( prop[ index ].ToString() ); } return r.Count &gt; 0 ? r.ToArray() : new string[ 0 ]; } } catch ( Exception ex ) { throw new ProviderException( "Unable to query Active Directory.", ex ); } } } } </code></pre> <p>A sample config sub-section entry for this would be as follows:</p> <pre><code>&lt;roleManager enabled="true" defaultProvider="ActiveDirectory"&gt; &lt;providers&gt; &lt;clear/&gt; &lt;add applicationName="MyApp" name="ActiveDirectory" type="MyApp.Security.ActiveDirectoryRoleProvider" domain="mydomain" groupMode="" connectionString="LDAP://myDirectoryServer.local/dc=mydomain,dc=local" /&gt; &lt;/providers&gt; &lt;/roleManager&gt; </code></pre> <p>Whew, that's a lot of code!</p> <p>PS: Core parts of the Role Provider above are based on another person's work, I don't have the link handy but we found it via Google, so partial credit to that person for the original. We modified it heavily to use LINQ and to get rid of the need for a database for caching.</p>
40,920,441
How to specify a property can be null or a reference with swagger
<p><a href="https://stackoverflow.com/questions/23729973/how-to-specify-a-property-as-null-or-a-reference">How to specify a property as null or a reference?</a> discusses how to specify a property as null or a reference using jsonschema.</p> <p>I'm looking to do the same thing with swagger.</p> <p>To recap the answer to the above, with jsonschema, one could do this:</p> <pre class="lang-json prettyprint-override"><code>{ &quot;definitions&quot;: { &quot;Foo&quot;: { # some complex object } }, &quot;type&quot;: &quot;object&quot;, &quot;properties&quot;: { &quot;foo&quot;: { &quot;oneOf&quot;: [ {&quot;$ref&quot;: &quot;#/definitions/Foo&quot;}, {&quot;type&quot;: &quot;null&quot;} ] } } } </code></pre> <p>The key point to the answer was the use of <code>oneOf</code>.</p> <p>The key points to my question:</p> <ol> <li><p>I have a complex object which I want to keep DRY so I put it in a definitions section for reuse throughout my swagger spec: values of other properties; response objects, etc.</p> </li> <li><p>In various places in my spec a property may be a reference to such an object OR be null.</p> </li> </ol> <p>How do I specify this with Swagger which doesn't support <code>oneOf</code> or <code>anyOf</code>?</p> <p>Note: some swagger implementations use <code>x-nullable</code> (or some-such) to specify a property value can be null, however, <code>$ref</code> <em>replaces</em> the object with what it references, so it would appear any use of <code>x-nullable</code> is ignored.</p>
41,012,155
3
0
null
2016-12-01 21:10:56.67 UTC
5
2022-01-26 10:46:55.733 UTC
2022-01-26 10:46:55.733 UTC
null
4,323,935
null
1,827,414
null
1
30
swagger|openapi|swagger-2.0
33,614
<p>Not easy to do that. Even almost impossible. Your options :</p> <h3>Wait</h3> <p>There is a very long discussion about this <a href="https://github.com/OAI/OpenAPI-Specification/issues/333" rel="noreferrer">point</a>, maybe one day it will be done...</p> <h3>Use vendors extensions</h3> <p>You can use <a href="https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#patterned-objects-9" rel="noreferrer">vendors extensions</a> like <em>x-oneOf</em> and <em>x-anyOf</em>. I have already taken this hard way: You must to upgrade all <strong>used</strong> 'swagger tools' to take into account these vendors extensions.</p> <p>In my case, we needed 'only' to :</p> <ul> <li>Develops our own Jax-RS parser with customized annotations in order to extract swagger API file from sources</li> <li>Extends swagger-codegen to take into account these extensions to generate java code for our clients</li> <li>Develops our own swagger-ui: to facilitate this work, we added a preprocessing step to convert our swagger schema with our extensions to a valid json schema. It's easier to find a module to represent json schemas than swagger schemas in javascript. By cons we gave up the idea to test the API with the 'try it' button.</li> </ul> <p>It was a year ago, maybe now ...</p> <h3>Refactor your APIs</h3> <p>Many projects don't need anyOf and oneOf, why not us ?</p>
32,864,243
EC2 instances cannot ping each other
<p>I have 2 EC2 Ubuntu instances. They are sharing same VPC, subnet and Security Group. Instances' firewall was turnoff. But I still can't ping each other by private IP. How to allow those instances ping each other?</p>
32,865,736
2
0
null
2015-09-30 10:51:57.453 UTC
6
2022-03-31 15:11:02.593 UTC
null
null
null
null
4,344,980
null
1
30
amazon-ec2
36,160
<p>In the security group, add "Custom ICMP" rule for "Echo Request" -- or -- "All ICMP Traffic" -- and as the source IP, instead of an address or block, add the security group's identifier, sg-xxxxxxxx.</p> <p>Simply being in the same security group doesn't mean the instances can communicate among themselves. It only means they follow the same set of rules... but security group membership is a source attribute as well, on traffic originating from instances that are members of the group.</p> <p>Hence, the above.</p>
23,176,800
What's so hard about p2p Hole Punching?
<p>I am trying to experiment with some p2p networking. Upon doing some research, one of the biggest obstacle I learnt is <strong>"What if a client is behind a NAT/Firewall"</strong>, later on I discovered about Hole Punching but that it is not always guaranteed to work. <br/> <br/> As far a I understand, I don't understand why it might fail, This is what I know so far: <hr/> <img src="https://i.stack.imgur.com/MlnEe.jpg" alt="enter image description here"><br/> Based on the diagram above, this is how I understand how a successful connection can be established. </p> <ol> <li><strong>Alice</strong> joins the network <strong>(1)</strong> by creating connection to a directory-server. When this happens, <strong>Alice's</strong> NAT creates a mapping from her public ip to her local ip. </li> <li>The directory server receives the connection and store <strong>Alice's</strong> public <code>ip:port</code> in the directory</li> <li><strong>Bob</strong> does the same <strong>(2)</strong>, Joins the network and publishes his <code>ip:port</code> in the directory</li> <li><strong>Alice</strong> wants to communicate with <strong>bob</strong>. So she looks up <strong>Bob's</strong> <code>ip:port</code> from the directory. <strong>(3)</strong></li> <li><strong>Alice</strong> sends data on <strong>Bob's</strong> <code>ip:port</code> which she got from the server. <strong>(5)</strong></li> <li>Since <strong>Bob</strong> also has a mapping from is <code>ip:port</code> to his local <code>ip:port</code>, the NAT simply forwards any data received on <strong>Bob's</strong> public <code>ip:port</code> to his computer.</li> <li>Same works for <strong>Alice</strong> <hr/> I hope I was clear in my explanation of what I understand. My question is, what is so hard or unreliable about this? i must be clearly missing something. Can you explain me what it is?</li> </ol>
23,177,006
4
0
null
2014-04-19 23:36:16.017 UTC
13
2022-01-30 05:43:55.36 UTC
null
null
null
null
1,463,622
null
1
25
networking|p2p|hole-punching
10,570
<p>One problem is that the NAT mappings in Alice's NAT server <em>may</em> time out, either after a fixed time, or after a period of inactivity.</p> <p>A second potential problem is that the NAT server <em>could</em> make the restriction that Alice's NAT mapping is only &quot;good&quot; for TCP connections established by Alice, or connections between Alice and the initial IP &quot;she&quot; connected to. (In other words, direct communication between Alice &amp; Bob <em>may</em> be blocked.)</p> <p>And so on.</p> <p>The problem is that the <em>behaviour</em> of a NAT server is highly dependent on how the managing organization's configuration / policy decisions. Many of these decisions could mean that your particular P2P usage pattern won't work reliably ... or at all.</p> <hr /> <blockquote> <p>So then is my whole idea about hole punching wrong?</p> </blockquote> <p>No. It just means that it won't always work.</p>
35,282,928
How do i set a timeout for utils::download.file() in R
<p>I'm trying to download a file that requires more than 60 seconds using download.file() function. The documentation mentions the timeout option e.g.</p> <blockquote> <p>The timeout for many parts of the transfer can be set by the option timeout which defaults to 60 seconds.</p> </blockquote> <p>When i try to set it i get an error message</p> <pre><code>download.file("https://server/FileURL", destfile = "file.xml", timeout = 444) </code></pre> <p>Example Message</p> <pre><code>unused argument (timeout = 444) </code></pre>
35,283,374
1
0
null
2016-02-09 02:30:12.04 UTC
4
2016-02-09 03:25:19.2 UTC
null
null
null
null
1,605,665
null
1
34
r
12,190
<p>To retrieve an option </p> <pre><code>getOption('timeout') # [1] 60 </code></pre> <p>To set an option</p> <pre><code>options(timeout=100) </code></pre>
42,864,913
How do I initialize a final class property in a constructor?
<p>In Java you are allowed to do this:</p> <pre><code>class A { private final int x; public A() { x = 5; } } </code></pre> <p>In Dart, I tried:</p> <pre><code>class A { final int x; A() { this.x = 5; } } </code></pre> <p>I get two compilation errors:</p> <blockquote> <p>The final variable 'x' must be initialized.</p> </blockquote> <p>and</p> <blockquote> <p>'x' can't be used as a setter because its final.</p> </blockquote> <p>Is there a way to set final properties in the constructor in Dart?</p>
42,864,979
6
0
null
2017-03-17 18:38:05.63 UTC
12
2021-05-05 13:37:32.907 UTC
2018-09-12 17:36:47.187 UTC
null
3,924,118
null
576,746
null
1
133
constructor|dart|final
72,338
<p>You <em>cannot</em> instantiate final fields in the constructor body. There is a special syntax for that:</p> <pre><code>class Point { final num x; final num y; final num distanceFromOrigin; // Old syntax // Point(x, y) : // x = x, // y = y, // distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2)); // New syntax Point(this.x, this.y) : distanceFromOrigin = sqrt(pow(x, 2) + pow(y, 2)); } </code></pre>
44,978,216
flutter remove back button on appbar
<p>I am wondering, if anyone knows of a way to remove the back button that shows up on the <code>appBar</code> in a flutter app when you use <code>Navigator.pushNamed</code> to go to another page. The reason I do not want it on this resulting page is that it is coming from the navigation and I want users to use the <code>logout</code> button instead, so that the session starts over.</p>
44,978,595
13
0
null
2017-07-07 19:18:03.273 UTC
51
2022-09-01 20:55:30.503 UTC
2021-12-25 03:32:03.063 UTC
user10563627
null
null
4,949,415
null
1
245
flutter|navigation|back-button|appbar
193,462
<p>You can remove the back button by passing an empty <code>new Container()</code> as the <a href="https://docs.flutter.io/flutter/material/AppBar/leading.html" rel="noreferrer"><code>leading</code></a> argument to your <a href="https://docs.flutter.io/flutter/material/AppBar-class.html" rel="noreferrer"><code>AppBar</code></a>.</p> <p>If you find yourself doing this, you probably don't want the user to be able to press the device's back button to get back to the earlier route. Instead of calling <code>pushNamed</code>, try calling <a href="https://docs.flutter.io/flutter/widgets/Navigator/pushReplacementNamed.html" rel="noreferrer"><code>Navigator.pushReplacementNamed</code></a> to cause the earlier route to disappear.</p> <p>The function <code>pushReplacementNamed</code> will remove the previous route in the backstack and replace it with the new route.</p> <p>Full code sample for the latter is below.</p> <pre><code>import 'package:flutter/material.dart'; class LogoutPage extends StatelessWidget { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(&quot;Logout Page&quot;), ), body: new Center( child: new Text('You have been logged out'), ), ); } } class MyHomePage extends StatelessWidget { @override Widget build(BuildContext context) { return new Scaffold( appBar: new AppBar( title: new Text(&quot;Remove Back Button&quot;), ), floatingActionButton: new FloatingActionButton( child: new Icon(Icons.fullscreen_exit), onPressed: () { Navigator.pushReplacementNamed(context, &quot;/logout&quot;); }, ), ); } } void main() { runApp(new MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', home: new MyHomePage(), routes: { &quot;/logout&quot;: (_) =&gt; new LogoutPage(), }, ); } } </code></pre>
50,278,842
Why does $emit not work in my vue component
<p>I've been banging my head against this problem for hours. I can't see a problem and from what I can tell I am following the documentation here: <a href="https://v2.vuejs.org/v2/guide/components-custom-events.html" rel="nofollow noreferrer">https://v2.vuejs.org/v2/guide/components-custom-events.html</a></p> <p>code below</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-html lang-html prettyprint-override"><code>&lt;script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"&gt;&lt;/script&gt; &lt;div id="wrap"&gt; &lt;test-listen&gt; &lt;test-emit&gt;&lt;/test-emit&gt; &lt;/test-listen&gt; &lt;/div&gt; &lt;script&gt; Vue.component('test-listen', { data: function(){ return {}; }, methods: { customHandler : function(e){ console.log(e); console.log("works"); } }, template: ` &lt;div class='test_listen' v-on:custom="customHandler"&gt; &lt;slot&gt;&lt;/slot&gt; &lt;/div&gt; ` }); Vue.component('test-emit',{ data: function(){ return {}; }, methods: { clickHandler : function(){ this.$emit('custom'); } }, template : ` &lt;div class='test_emit' v-on:click="clickHandler"&gt; test &lt;/div&gt; ` }); new Vue({ el:"#wrap" }); &lt;/script&gt; &lt;style&gt; .test_listen{ display:block; padding:20px; border:1px solid #000; } .test_emit{ display:block; width:100px; height:100px; background-color:#f0f; color:#fff; font-weight:700; font-size:20px; } &lt;/style&gt;</code></pre> </div> </div> </p> <p>But the listeners are definitely bound to the element, because if I dispatch a vanillaJS CustomEvent it triggers the console log just fine. What am I missing?</p>
50,280,149
3
0
null
2018-05-10 17:58:12.923 UTC
2
2022-07-14 04:44:41.93 UTC
2022-07-14 04:44:41.93 UTC
null
6,277,151
null
1,146,883
null
1
9
vuejs2
44,177
<p>There are 2 things wrong here.</p> <ol> <li>Vue events can be bound to components only I guess (talking vue events here)</li> <li>Slots are not good with events. (<a href="https://github.com/vuejs/vue/issues/4332#issuecomment-263444492" rel="nofollow noreferrer">Source</a> - Evan You, Vue author)</li> </ol> <p><strong>If you really want to pass data here and there without restriction better to use <code>Global Event Bus Approach</code></strong></p> <blockquote> <p><strong>Working example of your code with some minor correction.</strong></p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"&gt;&lt;/script&gt; &lt;div id="wrap"&gt; &lt;test-listen&gt; &lt;/test-listen&gt; &lt;/div&gt; &lt;script&gt; Vue.component('test-listen', { data: function(){ return {}; }, methods: { customHandler : function(e){ console.log(e); console.log("works"); } }, template: ` &lt;div class='test_listen' &gt; &lt;test-emit v-on:custom="customHandler"&gt;&lt;/test-emit&gt; &lt;/div&gt; ` }); Vue.component('test-emit',{ data: function(){ return {}; }, methods: { clickHandler : function(e){ // e =&gt; event : didnt pass here as console will stuck so this.$emit('custom', 'somedata'); } }, template : ` &lt;div class='test_emit' v-on:click="clickHandler"&gt; test &lt;/div&gt; ` }); new Vue({ el:"#wrap" }); &lt;/script&gt; &lt;style&gt; .test_listen{ display:block; padding:20px; border:1px solid #000; } .test_emit{ display:block; width:100px; height:100px; background-color:#f0f; color:#fff; font-weight:700; font-size:20px; } &lt;/style&gt;</code></pre> </div> </div> </p>
57,459,727
Why is an ObservedObject array not updated in my SwiftUI application?
<p>I'm playing with SwiftUI, trying to understand how <code>ObservableObject</code> works. I have an array of <code>Person</code> objects. When I add a new <code>Person</code> into the array, it is reloaded in my View, however if I change the value of an existing <code>Person</code>, it is not reloaded in the View.</p> <pre><code>// NamesClass.swift import Foundation import SwiftUI import Combine class Person: ObservableObject,Identifiable{ var id: Int @Published var name: String init(id: Int, name: String){ self.id = id self.name = name } } class People: ObservableObject{ @Published var people: [Person] init(){ self.people = [ Person(id: 1, name:&quot;Javier&quot;), Person(id: 2, name:&quot;Juan&quot;), Person(id: 3, name:&quot;Pedro&quot;), Person(id: 4, name:&quot;Luis&quot;)] } } </code></pre> <pre><code>struct ContentView: View { @ObservedObject var mypeople: People var body: some View { VStack{ ForEach(mypeople.people){ person in Text(&quot;\(person.name)&quot;) } Button(action: { self.mypeople.people[0].name=&quot;Jaime&quot; //self.mypeople.people.append(Person(id: 5, name: &quot;John&quot;)) }) { Text(&quot;Add/Change name&quot;) } } } } </code></pre> <p>If I uncomment the line to add a new <code>Person</code> (John), the name of Jaime is shown properly, however if I just change the name this is not shown in the View.</p> <p>I'm afraid I'm doing something wrong or maybe I don't get how the <code>ObservedObjects</code> work with arrays.</p>
57,459,844
5
0
null
2019-08-12 10:43:10.773 UTC
23
2022-03-23 00:16:50.133 UTC
2021-10-21 06:25:20.607 UTC
null
1,940,850
null
11,917,179
null
1
90
swiftui
49,017
<p>You can use a struct instead of a class. Because of a struct's value semantics, a change to a person's name is seen as a change to Person struct itself, and this change is also a change to the people array so @Published will send the notification and the View body will be recomputed.</p> <pre class="lang-swift prettyprint-override"><code>import Foundation import SwiftUI import Combine struct Person: Identifiable{ var id: Int var name: String init(id: Int, name: String){ self.id = id self.name = name } } class Model: ObservableObject{ @Published var people: [Person] init(){ self.people = [ Person(id: 1, name:&quot;Javier&quot;), Person(id: 2, name:&quot;Juan&quot;), Person(id: 3, name:&quot;Pedro&quot;), Person(id: 4, name:&quot;Luis&quot;)] } } struct ContentView: View { @StateObject var model = Model() var body: some View { VStack{ ForEach(model.people){ person in Text(&quot;\(person.name)&quot;) } Button(action: { self.mypeople.people[0].name=&quot;Jaime&quot; }) { Text(&quot;Add/Change name&quot;) } } } } </code></pre> <p>Alternatively (and not recommended), <code>Person</code> is a class, so it is a reference type. When it changes, the <code>People</code> array remains unchanged and so nothing is emitted by the subject. However, you can manually call it, to let it know:</p> <pre class="lang-swift prettyprint-override"><code>Button(action: { self.mypeople.objectWillChange.send() self.mypeople.people[0].name=&quot;Jaime&quot; }) { Text(&quot;Add/Change name&quot;) } </code></pre>
21,965,484
Timeout for python requests.get entire response
<p>I'm gathering statistics on a list of websites and I'm using requests for it for simplicity. Here is my code:</p> <pre><code>data=[] websites=['http://google.com', 'http://bbc.co.uk'] for w in websites: r= requests.get(w, verify=False) data.append( (r.url, len(r.content), r.elapsed.total_seconds(), str([(l.status_code, l.url) for l in r.history]), str(r.headers.items()), str(r.cookies.items())) ) </code></pre> <p>Now, I want <code>requests.get</code> to timeout after 10 seconds so the loop doesn't get stuck. </p> <p>This question has been of interest <a href="https://stackoverflow.com/questions/13573146/how-to-perform-time-limited-response-download-with-python-requests">before</a> too but none of the answers are clean. I will be putting some bounty on this to get a nice answer.</p> <p>I hear that maybe not using requests is a good idea but then how should I get the nice things requests offer. (the ones in the tuple)</p>
22,096,841
22
2
null
2014-02-23 07:36:20.53 UTC
66
2022-07-13 18:23:15.113 UTC
2017-05-23 12:10:44.23 UTC
null
-1
null
814,359
null
1
291
python|timeout|python-requests
481,547
<p>What about using eventlet? If you want to timeout the request after 10 seconds, even if data is being received, this snippet will work for you:</p> <pre><code>import requests import eventlet eventlet.monkey_patch() with eventlet.Timeout(10): requests.get("http://ipv4.download.thinkbroadband.com/1GB.zip", verify=False) </code></pre>
23,518,817
send byte array by HTTP POST in store app
<p>I'm trying to send some images + some meta data to a server by HTTP post from a windows store app but get stuck when trying to actually include the data in the post. It cannot be done the way you would accomplish this in a windows forms app or similar due to the changes to the store app API.</p> <p>I get the error. </p> <pre><code>cannot convert source type byte[] to target type System.Net.Http.httpContent </code></pre> <p>now this is obviously because it's 2 different types that can't be implicitly casted, but it's basically what I'm looking to be able to do. How do I make get my byte array data into the httpContent type so I can include it in the following call</p> <pre><code>httpClient.PostAsync(Uri uri,HttpContent content); </code></pre> <p>here's my full upload method:</p> <pre><code>async private Task UploadPhotos(List&lt;Photo&gt; photoCollection, string recipient, string format) { PhotoDataGroupDTO photoGroupDTO = PhotoSessionMapper.Map(photoCollection); try { var client = new HttpClient(); client.MaxResponseContentBufferSize = 256000; client.DefaultRequestHeaders.Add("Upload", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); // POST action_begin const string actionBeginUri = "http://localhost:51139/PhotoService.axd?action=Begin"; HttpResponseMessage response = await client.GetAsync(actionBeginUri); response.EnsureSuccessStatusCode(); string responseBodyAsText = await response.Content.ReadAsStringAsync(); string id = responseBodyAsText; //// // POST action_upload Uri actionUploadUri = new Uri("http://localhost:51139/PhotoService.axd?action=Upload&amp;brand={0}&amp;id={1}&amp;name={2}.jpg"); var metaData = new Dictionary&lt;string, string&gt;() { {"Id", id}, {"Brand", "M3rror"}, //TODO: Denne tekst skal komme fra en konfigurationsfil. {"Format", format}, {"Recipient", recipient} }; string stringData = ""; foreach (string key in metaData.Keys) { string value; metaData.TryGetValue(key, out value); stringData += key + "=" + value + ","; } UTF8Encoding encoding = new UTF8Encoding(); byte[] byteData = encoding.GetBytes(stringData); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, actionUploadUri); // send meta data // TODO get byte data in as content HttpContent metaDataContent = byteData; HttpResponseMessage actionUploadResponse = await client.PostAsync(actionUploadUri, metaDataContent); actionUploadResponse.EnsureSuccessStatusCode(); responseBodyAsText = await actionUploadResponse.Content.ReadAsStringAsync(); // send photos // TODO get byte data in as content foreach (byte[] imageData in photoGroupDTO.PhotosData) { HttpContent imageContent = imageData; actionUploadResponse = await client.PostAsync(actionUploadUri, imageContent); actionUploadResponse.EnsureSuccessStatusCode(); responseBodyAsText = await actionUploadResponse.Content.ReadAsStringAsync(); } //// // POST action_complete const string actionCompleteUri = "http://localhost:51139/PhotoService.axd?action=Complete"; HttpResponseMessage actionCompleteResponse = await client.GetAsync(actionCompleteUri); actionCompleteResponse.EnsureSuccessStatusCode(); responseBodyAsText = await actionCompleteResponse.Content.ReadAsStringAsync(); //// } catch (HttpRequestException e) { } catch (Exception e) { Debug.WriteLine(e.ToString()); } } </code></pre>
23,547,930
3
1
null
2014-05-07 13:11:37.53 UTC
8
2017-10-03 15:37:00.167 UTC
null
null
null
null
2,996,758
null
1
24
c#|http|windows-store-apps|bytearray
68,298
<p>It will be more straightforward to use <code>System.Net.Http.ByteArrayContent</code>. E.g:</p> <pre><code>// Converting byte[] into System.Net.Http.HttpContent. byte[] data = new byte[] { 1, 2, 3, 4, 5}; ByteArrayContent byteContent = new ByteArrayContent(data); HttpResponseMessage reponse = await client.PostAsync(uri, byteContent); </code></pre> <p>For text only with an specific text encoding use:</p> <pre><code>// Convert string into System.Net.Http.HttpContent using UTF-8 encoding. StringContent stringContent = new StringContent( "blah blah", System.Text.Encoding.UTF8); HttpResponseMessage reponse = await client.PostAsync(uri, stringContent); </code></pre> <p>Or as you mentioned above, for text and images using multipart/form-data: </p> <pre><code>// Send binary data and string data in a single request. MultipartFormDataContent multipartContent = new MultipartFormDataContent(); multipartContent.Add(byteContent); multipartContent.Add(stringContent); HttpResponseMessage reponse = await client.PostAsync(uri, multipartContent); </code></pre>
25,863,144
Calculate the time difference between two timestamps in mysql
<p>I work on a MySQL database table that has a column containing timestamps (Ex. 2014-09-16 09:08:05) of the time I ping different hosts. My question is how could I calculate in minutes the difference between the first ping and the last one for specific hosts? Also how could I specify different timestamps for the start and the end of the difference mentioned above (instead of the first and last ping). Here is an example of the table:</p> <pre><code>|--|---------|-------------------|----| |id|http_code|pingtime |host| |--|---------|-------------------|----| |10|200 |2014-09-16 09:08:05|2 | |--|---------|-------------------|----| |11|200 |2014-09-16 10:07:05|1 | |--|---------|-------------------|----| |12|200 |2014-09-16 10:14:10|2 | |--|---------|-------------------|----| </code></pre> <p>I hope that I've explain myself clear enough.</p>
25,863,597
6
1
null
2014-09-16 07:38:50.853 UTC
null
2021-12-13 14:30:42.493 UTC
2014-09-16 07:52:56.27 UTC
null
2,964,697
null
2,899,983
null
1
5
mysql|sql|database|time
46,079
<p>You could use the native <a href="http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timestampdiff" rel="noreferrer">TIMESTAMPDIFF</a> function :</p> <pre><code>SELECT TIMESTAMPDIFF(&lt;INTERVAL&gt;,&lt;timestampFrom&gt;,&lt;timestampTo&gt;); </code></pre> <p>If you want to find the difference between the first and the last timestamp of a given host ID, here you are:</p> <pre><code>SELECT TIMESTAMPDIFF(MINUTE,MIN(pingtime),MAX(pingtime)) FROM yourTable WHERE host = 2; </code></pre>
20,407,026
What is an <init> method in Java? Can it be overridden?
<p><code>&lt;init&gt;</code> method can be found in stacktrace, for example. As I understood it represents initialization done in constructor.</p> <p>If you try to execute</p> <pre><code>Object.class.getDeclaredMethod("&lt;init&gt;"); </code></pre> <p>You'll get <code>java.lang.NoSuchMethodException</code>.</p> <p>What is this method? When was it added to class? (in compilation - execution terms) Is it virtual, can one <em>anyhow</em> override it?</p>
20,407,196
2
1
null
2013-12-05 17:45:43.007 UTC
5
2017-01-22 14:07:15.553 UTC
2017-01-22 14:07:15.553 UTC
null
1,033,581
null
2,933,541
null
1
15
java|initialization
56,487
<p>Have a look at the <a href="http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.9" rel="noreferrer">Java Virtual Machine Specification</a>, chapter 2.9. It say on the <code>&lt;init&gt;</code> name:</p> <blockquote> <p>At the level of the Java Virtual Machine, every constructor written in the Java programming language (JLS §8.8) appears as an instance initialization method that has the special name <code>&lt;init&gt;</code>. This name is supplied by a compiler. Because the name is not a valid identifier, it cannot be used directly in a program written in the Java programming language.</p> </blockquote> <p>That's why <code>&lt;init&gt;</code> can be found on the stack trace, but is not accessible with code.</p>
32,505,389
How can I add padding-right to an input type="number" when aligning right?
<p>I can't believe I haven't been able to find anything about this problem.</p> <p>In my new project the future user will have a column with some <code>input type="number"</code>, and as numeric fields (there is not a single <code>text</code>one) I want the numbers aligned to the right.</p> <p>I found the numbers too close to the arrows so, logically, I added to them a <code>padding-right</code>.</p> <p>To my surprise, It seems I can't separate a little the numbers from the arrows. <code>padding-right</code> moves the arrows along the numbers.</p> <p>Basically only <code>Opera</code> do the <code>padding</code> the right way. but not the other main 3 browsers I have tested so far as you can see in the image below.</p> <p><a href="https://i.stack.imgur.com/8E7tR.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/8E7tR.jpg" alt="enter image description here"></a></p> <p>So. Is there any way to separate numbers from arrows so it works at least in <code>Firefox</code> and <code>Chrome</code> (as we recomend for our web app's these 2 browsers?) </p> <p>a <a href="http://jsfiddle.net/alvaromenendez/vaLa8yst/" rel="noreferrer">JSFIDDLE</a> with a simple example</p>
32,505,857
6
3
null
2015-09-10 15:01:03.347 UTC
3
2022-05-16 20:53:43.4 UTC
2017-11-09 15:19:21.127 UTC
null
162,698
null
2,550,987
null
1
37
html|css|google-chrome|firefox
14,093
<p>Rather than using <code>padding-right</code> use the following CSS </p> <pre><code>input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { margin-left: 20px; } </code></pre> <p>and for Firefox above solution won't work, so the best solution is just to hide it :</p> <pre><code>input[type=number] { -moz-appearance:textfield; } </code></pre> <p>or you can try to "play" with some jquery plugin.</p>
34,728,883
Fixed height scrollable div inside of a bootstrap 3 column
<p>I have seen similar questions, but nothing exactly like I'm trying. Most of the examples make the entire col-md-2 scroll, I need content within that to scroll.</p> <p>Inside a fluid container, I have a left navigation type column, and a right content column.</p> <p>Inside the left column I want a div at the top class="top", and a div at the bottom class="bottom". And in the middle I have a list. Say bottom and top are 100px. I want the list to take up all of the space between the two, and if the list content is larger than this area, I want it to scroll. If the list content is smaller than the space between the two, I want it to take up all of that space (not collapse).</p> <p>Here is a psuedo example:</p> <pre><code>&lt;div class="container-fluid"&gt; &lt;div class="row"&gt; &lt;div class="col-md-2"&gt; &lt;div class="top"&gt; . . . &lt;/div&gt; &lt;div class="scroll-area"&gt; &lt;ul&gt; &lt;li&gt;one&lt;/li&gt; . . . &lt;li&gt;one-thousand&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="bottom"&gt; . . . &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-10 content"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;style&gt; .top, .bottom { height: 100px; } &lt;/style&gt; </code></pre> <p>I was able to do this before without bootstrap by giving "scroll-area" absolute positioning. I can make the scroll-area work with fixed positioning, but the containing "col-md-2 is collapsed, so "bottom" sits up top.</p> <p><a href="https://i.stack.imgur.com/DvdUZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DvdUZ.png" alt="enter image description here"></a></p> <p>How can I make this work?</p>
34,729,795
2
4
null
2016-01-11 18:51:27.22 UTC
3
2016-09-09 00:30:41.743 UTC
2016-01-11 23:35:07.813 UTC
null
210,757
null
210,757
null
1
10
html|css|twitter-bootstrap-3
45,112
<p>This answer is for when you dont know the window height.</p> <p>You can still achieve this using position:absolute; you just tell the blue and red parts to take top and bottom, the green part should have top 100px, and then you just use css 'calc' to get its height.</p> <p><strong>Styles</strong></p> <pre><code>.side{ position:fixed; top:0; left:0; height:100%; padding:0; } .scroll-area{ width:100%; height:calc(100% - 200px); margin-top:100px; background-color:green; float:left; overflow-y:scroll; } </code></pre> <p><strong>html</strong></p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-md-2 col-xs-2 side"&gt; &lt;div style="position:relative;width:100%;height:100%;"&gt; &lt;div class="top" style="background-color:red;top:0;width:100%;height: 100px; position:absolute;"&gt; top &lt;/div&gt; &lt;div class="scroll-area"&gt; &lt;ul&gt; &lt;li&gt;one&lt;/li&gt; &lt;/ul&gt; &lt;div style="width:100%;height:10000px;"&gt; &lt;/div&gt; &lt;ul&gt; &lt;li&gt;one-thousand&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="bottom" style="background-color:blue;bottom:0;width:100%;height: 100px; position:absolute;"&gt; bottom &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-10 col-xs-offset-2 content col-md-offset-2"&gt; &lt;div style="height:1000px;width:100%;"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>take a look at this filddle - </p> <p><a href="https://jsfiddle.net/jxo6pmju/12/" rel="noreferrer">https://jsfiddle.net/jxo6pmju/12/</a></p>
34,522,988
Attaching a click event to multiple elements at once?
<p>Here is my code in jQuery:</p> <pre><code>$('.paragraph, .section, .heading').on('input', function (e) { localStorage.setItem($(this).attr('id'), $(this).text()); }); </code></pre> <p>Is there any JavaScript equivalent where I could attach all events at once?</p>
34,523,052
4
4
null
2015-12-30 04:40:39.24 UTC
6
2015-12-30 05:01:11.87 UTC
2015-12-30 04:53:52.24 UTC
null
1,677,912
null
5,383,066
null
1
17
javascript|jquery
44,961
<p>You could use <strong><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll" rel="noreferrer"><code>querySelectorAll</code></a></strong> with your multiple element selectors, then add the event listeners to each one</p> <pre><code>var elements = document.querySelectorAll(".a, .b"); for (var i = 0; i &lt; elements.length; i++) { elements[i].addEventListener("click", function() { console.log("clicked"); }); } </code></pre>
25,044,085
When drawing outside the view clip bounds with Android: how do I prevent underling views from drawing on top of my custom view?
<p>I'm wrote a custom Android View that need to draw outside its clipping Bounds.</p> <p>This is what I have:</p> <p><img src="https://i.stack.imgur.com/UGBIZ.png" alt="enter image description here"></p> <p>This is what happens when I click a button, say the right button:</p> <p><img src="https://i.stack.imgur.com/xTOhU.png" alt="enter image description here"></p> <p>How do I prevent the View below to draw on top of my "handle"?</p> <p>Some related pseudo-code from my project follow.</p> <p>My custom view <em>MyHandleView</em> draw like this:</p> <pre><code>@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Path p = mPath; int handleWidth = mHandleWidth; int handleHeight = mHandleHeight; int left = (getWidth() &gt;&gt; 1) - handleWidth; canvas.save(); // allow drawing out of bounds vertically Rect clipBounds = canvas.getClipBounds(); clipBounds.inset(0, -handleHeight); canvas.clipRect(clipBounds, Region.Op.REPLACE); // translate up to draw the handle canvas.translate(left, -handleHeight); // draw my background shape canvas.drawPath(p, mPaint); canvas.restore(); } </code></pre> <p>The layout is something like this (I simplified a little):</p> <pre><code>&lt;RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;!-- Main content of the SlidingUpPanel --&gt; &lt;fragment android:above=@+id/panel" class="com.neosperience.projects.percassi.android.home.HomeFragment" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginTop="?android:attr/actionBarSize" tools:layout="@layout/fragment_home" /&gt; &lt;!-- The Sliding Panel --&gt; &lt;LinearLayout android:id="@id/panel" android:layout_width="match_parent" android:layout_height="@dimen/myFixedSize" android:alignParentBottom="true" android:orientation="vertical" android:clipChildren="false"&gt; &lt;MyHandleView xmlns:custom="http://schemas.android.com/apk/res-auto.com/apk/res/android" android:layout_width="match_parent" android:layout_height="0dp" custom:handleHeight="@dimen/card_panel_handle_height" custom:handleWidthRatio="@dimen/card_panel_handle_width_ratio" custom:handleBackgroundColor="#000"/&gt; &lt;TextView android:id="@+id/loyaltyCardPanelTitle" android:layout_width="match_parent" android:layout_height="@dimen/card_panel_height" android:background="#000" android:gravity="center" android:textStyle="bold" android:textSize="24sp" android:textColor="#fff" android:text="My TEXT"/&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p>You can think of the fragment as a view containing two button at the bottom, in a LinearLayout.</p> <p>In place of the external RelativeLayout I'm really using a view from a library: SlidingUpPanelLayout (<a href="https://github.com/umano/AndroidSlidingUpPanel" rel="noreferrer">https://github.com/umano/AndroidSlidingUpPanel</a>). But I tested the behavior with this RelativeLayout: same thing, meaning the library is not related.</p> <p>I say this just to let you know that <strong>I can't just place there a FrameLayout and avoid drawing outside the clipping bounds</strong>.</p> <p>I suspect this has something to do with the fact that when I touch the button it redraw itself but my other view (which is somewhere else in the hierarchy) doesn't get re-drawed (this is an optimization and I doubt it can be disabled).</p> <p>I'd like to be able to invalidate my custom view whenever any other "near" (or any) view get's invalidated, thus I need some kind of listener on view invalidation but I'm not aware of any.</p> <p>Can someone help?</p>
25,055,747
1
2
null
2014-07-30 18:17:43.267 UTC
15
2015-02-27 14:07:28.58 UTC
2014-07-30 19:38:47.193 UTC
null
902,276
null
902,276
null
1
47
android|android-layout|android-custom-view
63,353
<p>I found the solution myself, even if this is not optimal for performances.</p> <p>Just add:</p> <pre><code>android:clipChildren="false" </code></pre> <p>to the RelativeLayout (or whatever layout you have).</p> <p>This has 2 effects (may be more, this are the two that interested me): - the ViewGroup doesn't clip the drawing of his children (obvious) - the ViewGroup doesn't check for intersection with dirty regions (invalidated) when considering which children to redraw</p> <p>I digged the View code about invalidating.</p> <p>The process goes, more or like, like this:</p> <ol> <li>a View invalidate itself, the region it usually draw (a rectangular) become a "dirty region" to be redrawed</li> <li>the View tell its parent (a ViewGroup of some kind) it need to redraw itself</li> <li>the parents do the same with it's parent to the root</li> <li>each parent in the hierarchy loop for every children and check if the dirty region intersect some of them</li> <li>if it does it also redraw them</li> </ol> <p>In step 4 clipping is involved: the ViewGroup check view bounds of his child only if clipChildren is true: meaning that if you place it to false it <strong>always redraw all its children when any of them is invalidated</strong>.</p> <p>So, my View hierarchy was like this:</p> <pre><code>ViewGroup A | |----- fragment subtree (containing buttons, map, | whatever element that I don't want to draw | on top of my handle) | |----- ViewGroup B | |---- my handle (which draw outside its clip bounds) </code></pre> <p>In my case the "handle" draw ouf of it's bound, on top of something that is usually drawed by some element of the fragment subtree.</p> <p>When any view inside the fragment is invalidated it pass its "dirty region" up in the view tree and each view group check if there are some other children to be redraw in that region.</p> <p>ViewGroup B would clip what I draw outside the clip bounds if I do not set <em>clipBounds="false"</em> on it.</p> <p>If anything get's invalidated in the fragment subtree the ViewGroup A will see that ViewGroup B dirty region is not intersecting the fragment subtree region and will skip redrawing of ViewGroup B.</p> <p>But if I also tell ViewGroup A to not clip children it will still give ViewGroup B an invalidate command which will then cause a redraw of my handle.</p> <p>So the solution is to make sure to set</p> <pre><code>android:clipChildren="false" </code></pre> <p>on any ViewGroup in the hierarchy above the View that draw out of it's bounds on which the content may fall "under" the out-of-bound region you are drawing.</p> <p>The obvious side effect of this is that whenever I invalidate any of the view inside ViewGroup A an invalidate call will be forwarded, with the invalid region, to all the view in it.</p> <p>However any view that doesn't intersect the dirty region which is inside a ViewGroup with clipChildren="true" (default) will be skipped.</p> <p>So to avoid performance issues when doing this make sure your view groups with clipChildren="true" have not many "standard" direct children. And with "standard" I mean that they do not draw outside their view bounds.</p> <p>So for example if in my example ViewGroup B contains many view consider wrapping all those in a ViewGroup with clipChildren="true" and only leave this view group and the one view that draw outside its region as direct children of ViewGroup B. The same goes for ViewGroup A.</p> <p>This simple fact will make sure no other View will get a redraw if they aren't in the invalidated dirty region minimizing the redraws needed.</p> <p>I'm still open to hear any more consideration if someone has one ;)</p> <p>So I'll wait a little bit before marking this as accepted answer.</p> <blockquote> <p>EDIT: Many devices do something different in handling clipChildren="false". I discovered that I had to set clipChildren="false" on all the parent views of my custom widget that may contains elements in their hierarchy which should draw over of the "out of bound region" of the widget or you may see your custom drawing showing ON TOP of another view that was supposed to cover it. For example in my layout I had a Navigation Drawer that was supposed to cover my "handle". If I didn't set clipChildren="false" on the NavigationDrawer layout I may sometimes see my handle pop up in front of the opened drawer.</p> <p>EDIT2: My custom widget had 0 height and drawed "on top" of itself. Worked fine on Nexus devices but many of the others had some "optimization" in place that completely skip drawing of views that have 0 height or 0 width. So be aware of this if you want to write a component that draw out of it's bound: you have to assign it at least 1 pixel height / width.</p> </blockquote>
39,477,684
Should I avoid unwrap in production application?
<p>It's easy to crash at runtime with <code>unwrap</code>:</p> <pre><code>fn main() { c().unwrap(); } fn c() -&gt; Option&lt;i64&gt; { None } </code></pre> <p>Result:</p> <pre class="lang-none prettyprint-override"><code> Compiling playground v0.0.1 (file:///playground) Running `target/debug/playground` thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', ../src/libcore/option.rs:325 note: Run with `RUST_BACKTRACE=1` for a backtrace. error: Process didn't exit successfully: `target/debug/playground` (exit code: 101) </code></pre> <p>Is <code>unwrap</code> only designed for quick tests and proofs-of-concept?</p> <p>I can not affirm "My program will not crash here, so I can use <code>unwrap</code>" if I really want to avoid <code>panic!</code> at runtime, and I think avoiding <code>panic!</code> is what we want in a production application.</p> <p>In other words, can I say my program is reliable if I use <code>unwrap</code>? Or must I avoid <code>unwrap</code> even if the case seems simple? </p> <p>I read <a href="https://stackoverflow.com/a/36362163/978690">this</a> answer: </p> <blockquote> <p>It is best used when you are positively sure that you don't have an error.</p> </blockquote> <p>But I don't think I can be "positively sure".</p> <p>I don't think this is an opinion question, but a question about Rust core and programming.</p>
39,478,185
5
2
null
2016-09-13 19:33:01.977 UTC
5
2019-03-19 22:28:40.233 UTC
2017-05-23 12:16:25.973 UTC
null
-1
null
978,690
null
1
29
error-handling|rust
6,290
<p>While the whole “error handling”-topic is very complicated and often opinion based, this question can actually be answered here, because Rust has rather narrow philosophy. That is:</p> <ul> <li><code>panic!</code> for <strong>programming errors</strong> (“bugs”)</li> <li>proper error propagation and handling with <code>Result&lt;T, E&gt;</code> and <code>Option&lt;T&gt;</code> for <strong>expected and <em>recoverable</em> errors</strong></li> </ul> <p>One can think of <code>unwrap()</code> as <em>converting</em> between those two kinds of errors (it is converting a recoverable error into a <code>panic!()</code>). When you write <code>unwrap()</code> in your program, you are saying: </p> <blockquote> <p>At this point, a <code>None</code>/<code>Err(_)</code> value is a <em>programming error</em> and the program is unable to recover from it.</p> </blockquote> <hr> <p>For example, say you are working with a <code>HashMap</code> and want to insert a value which you may want to mutate later:</p> <pre><code>age_map.insert("peter", 21); // ... if /* some condition */ { *age_map.get_mut("peter").unwrap() += 1; } </code></pre> <p>Here we use the <code>unwrap()</code>, because we can be sure that the key holds a value. It would be a programming error if it didn't and even more important: it's not really recoverable. What would you do when at that point there is no value with the key <code>"peter"</code>? Try inserting it again ... ?</p> <p>But as you may know, there is a beautiful <a href="https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.entry"><code>entry</code> API</a> for the maps in Rust's standard library. With that API you can avoid all those <code>unwrap()</code>s. And this applies to pretty much all situations: <strong>you can very often restructure your code to avoid the <code>unwrap()</code></strong>! Only in a very few situation there is no way around it. But then it's OK to use it, if you want to signal: at this point, it would be a programming bug.</p> <hr> <p>There has been a recent, fairly popular blog post on the topic of “error handling” whose conclusion is similar to Rust's philosophy. It's rather long but worth reading: <a href="http://joeduffyblog.com/2016/02/07/the-error-model/">“The Error Model”</a>. Here is my try on summarizing the article in relation to this question:</p> <ul> <li>deliberately distinguish between <em>programming bugs</em> and <em>recoverable errors</em></li> <li>use a “fail fast” approach for programming bugs</li> </ul> <p><strong>In summary</strong>: use <code>unwrap()</code> when you are sure that the <em>recoverable</em> error that you get is in fact <em>unrecoverable</em> at that point. Bonus points for explaining <em>“why?”</em> in a comment above the affected line ;-) </p>
31,464,345
Fitting a closed curve to a set of points
<p>I have a set of points <code>pts</code> which form a loop and it looks like this:</p> <p><img src="https://i.stack.imgur.com/31KOr.png" alt="enter image description here"></p> <p>This is somewhat similar to <a href="https://stackoverflow.com/questions/31243002/higher-order-local-interpolation-of-implicit-curves-in-python">31243002</a>, but instead of putting points in between pairs of points, I would like to fit a smooth curve through the points (coordinates are given at the end of the question), so I tried something similar to <code>scipy</code> documentation on <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/interpolate.html" rel="noreferrer">Interpolation</a>:</p> <pre><code>values = pts tck = interpolate.splrep(values[:,0], values[:,1], s=1) xnew = np.arange(2,7,0.01) ynew = interpolate.splev(xnew, tck, der=0) </code></pre> <p>but I get this error:</p> <blockquote> <p>ValueError: Error on input data</p> </blockquote> <p>Is there any way to find such a fit?</p> <p>Coordinates of the points:</p> <pre><code>pts = array([[ 6.55525 , 3.05472 ], [ 6.17284 , 2.802609], [ 5.53946 , 2.649209], [ 4.93053 , 2.444444], [ 4.32544 , 2.318749], [ 3.90982 , 2.2875 ], [ 3.51294 , 2.221875], [ 3.09107 , 2.29375 ], [ 2.64013 , 2.4375 ], [ 2.275444, 2.653124], [ 2.137945, 3.26562 ], [ 2.15982 , 3.84375 ], [ 2.20982 , 4.31562 ], [ 2.334704, 4.87873 ], [ 2.314264, 5.5047 ], [ 2.311709, 5.9135 ], [ 2.29638 , 6.42961 ], [ 2.619374, 6.75021 ], [ 3.32448 , 6.66353 ], [ 3.31582 , 5.68866 ], [ 3.35159 , 5.17255 ], [ 3.48482 , 4.73125 ], [ 3.70669 , 4.51875 ], [ 4.23639 , 4.58968 ], [ 4.39592 , 4.94615 ], [ 4.33527 , 5.33862 ], [ 3.95968 , 5.61967 ], [ 3.56366 , 5.73976 ], [ 3.78818 , 6.55292 ], [ 4.27712 , 6.8283 ], [ 4.89532 , 6.78615 ], [ 5.35334 , 6.72433 ], [ 5.71583 , 6.54449 ], [ 6.13452 , 6.46019 ], [ 6.54478 , 6.26068 ], [ 6.7873 , 5.74615 ], [ 6.64086 , 5.25269 ], [ 6.45649 , 4.86206 ], [ 6.41586 , 4.46519 ], [ 5.44711 , 4.26519 ], [ 5.04087 , 4.10581 ], [ 4.70013 , 3.67405 ], [ 4.83482 , 3.4375 ], [ 5.34086 , 3.43394 ], [ 5.76392 , 3.55156 ], [ 6.37056 , 3.8778 ], [ 6.53116 , 3.47228 ]]) </code></pre>
31,466,013
4
6
null
2015-07-16 20:54:42.623 UTC
20
2019-11-26 08:56:12.867 UTC
2017-05-23 12:18:09.657 UTC
null
-1
null
3,349,443
null
1
38
python|numpy|scipy|curve-fitting|data-fitting
20,747
<p>Actually, you were not far from the solution in your question. </p> <p>Using <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.splprep.html" rel="noreferrer"><code>scipy.interpolate.splprep</code></a> for parametric B-spline interpolation would be the simplest approach. It also natively supports closed curves, if you provide the <code>per=1</code> parameter,</p> <pre><code>import numpy as np from scipy.interpolate import splprep, splev import matplotlib.pyplot as plt # define pts from the question tck, u = splprep(pts.T, u=None, s=0.0, per=1) u_new = np.linspace(u.min(), u.max(), 1000) x_new, y_new = splev(u_new, tck, der=0) plt.plot(pts[:,0], pts[:,1], 'ro') plt.plot(x_new, y_new, 'b--') plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/EfS5o.png" alt="enter image description here"></p> <p>Fundamentally, this approach not very different from the one in @Joe Kington's answer. Although, it will probably be a bit more robust, because the equivalent of the <code>i</code> vector is chosen, by default, based on the distances between points and not simply their index (see <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.interpolate.splprep.html" rel="noreferrer"><code>splprep</code> documentation</a> for the <code>u</code> parameter). </p>
48,592,656
firebase.auth is not a function
<p>I am using Webpack with firebase and firebase-admin.</p> <p>To install firebase I ran:</p> <pre><code>npm install --save firebase </code></pre> <p>I am importing firebase using:</p> <pre><code>import * as firebase from 'firebase/app' import 'firebase/auth' </code></pre> <p>I also tried:</p> <pre><code>import * as firebase from 'firebase' </code></pre> <p>And I tried:</p> <pre><code>const firebase = require('firebase') </code></pre> <p>As suggested in <a href="https://firebase.google.com/docs/web/setup" rel="noreferrer">web get started guide</a>.</p> <p>However, when I try to use <code>firebase.auth()</code> I get an error:</p> <blockquote> <p>console.js:32 TypeError: firebase.auth is not a function</p> </blockquote> <p>When I use the debugger to inspect <code>firebase</code> I see that it in fact does not have an <code>auth</code> function:</p> <pre><code>&gt; firebase {__esModule: true, initializeApp: ƒ, app: ƒ, Promise: ƒ, …} </code></pre> <p>How can I get <code>auth()</code> included as a function using webpack?</p>
48,592,798
26
5
null
2018-02-03 00:16:45.833 UTC
13
2022-07-21 19:47:30.873 UTC
2022-01-09 08:32:57.4 UTC
null
6,045,800
null
84,128
null
1
90
javascript|reactjs|firebase|webpack
147,198
<p>I fixed this by deleting my <code>node_modules</code> directory and reinstalling everything.</p> <p>Also I'm importing firebase like so:</p> <pre><code>import firebase from 'firebase' require('firebase/auth') </code></pre>
39,004,750
How to solve SSL certificate: self signed certificate when cloning repo from github?
<p>I just installed git for windows and tried to clone glew's repo like this</p> <pre><code>$ git clone https://github.com/nigels-com/glew.git </code></pre> <p>But I got the following error</p> <pre><code>Cloning into 'glew'... fatal: unable to access 'https://github.com/nigels-com/glew.git/': SSL certificate problem: self signed certificate </code></pre> <p>I've seen people running into this problem and some possible workarounds.</p> <p>First try </p> <pre><code>$ git -c http.sslVerify=false clone https://github.com/nigels-com/glew.git Cloning into 'glew'... fatal: unable to access 'https://github.com/nigels-com/glew.git/': Empty reply from server </code></pre> <p>Second try</p> <pre><code>$ git config --global http.sslVerify false $ git clone https://github.com/nigels-com/glew.git Cloning into 'glew'... fatal: unable to access 'https://github.com/nigels-com/glew.git/': Empty reply from server </code></pre> <p>Then I checked for <code>http.sslcainfo</code> entry in the config files</p> <pre><code>$ git config --system --list credential.helper=manager $ git config --global --list https.proxy=&lt;proxy-address&gt; http.sslverify=false </code></pre> <p>System and global config files does not have that entry. So I tried the following which I don't know what file is reading and try to unset it.</p> <pre><code>$ git config --list core.symlinks=false core.autocrlf=true core.fscache=true color.diff=auto color.status=auto color.branch=auto color.interactive=true help.format=html http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt diff.astextplain.textconv=astextplain rebase.autosquash=true credential.helper=manager http.sslverify=false $ git config --unset http.sslcainfo fatal: not in a git directory </code></pre> <p>Tried with global and system</p> <pre><code>$ git config --global --unset http.sslcainfo $ git clone https://github.com/nigels-com/glew.git Cloning into 'glew'... fatal: unable to access 'https://github.com/nigels-com/glew.git/': SSL certificate problem: self signed certificate $ git config --system --unset http.sslcainfo error: could not lock config file C:\Program Files\Git\mingw64/etc/gitconfig: Permission denied error: could not lock config file C:\Program Files\Git\mingw64/etc/gitconfig: Invalid argument </code></pre> <p>I still cannot clone that github repo. Any other idea I can try to fix this problem? What am I missing?</p>
39,005,967
2
5
null
2016-08-17 19:26:18.553 UTC
3
2021-08-02 08:12:01.847 UTC
null
null
null
null
1,016,721
null
1
17
git|ssl|github
64,842
<p>You're overthinking this. Git requires the SSH key to do the transfer. In order for this to work, you need an account on GitHub. If you have already generated an SSH key pair for other sites, you can reuse that one. All you need to do is log into GitHub.com and copy it there in your settings panel.</p> <p>If you don't have an account, make one. If you haven't generated a key pair, that's simple:</p> <pre><code>ssh-keygen -t rsa -C "[email protected]" </code></pre> <p>Then copy the key to your settings in GitHub.com</p> <p>There are instructions all over the place on how to do this in various ways. I have a self-signed cert and I was able to clone the repo you listed.</p>
20,266,422
Simplest way to print an `IntStream` as a `String`
<p>With Java-8 I can easily treat a <code>String</code> (or any <code>CharSequence</code>) as an <code>IntStream</code> using either the <code>chars</code> or the <code>codePoints</code> method.</p> <pre><code>IntStream chars = "Hello world.".codePoints(); </code></pre> <p>I can then manipulate the contents of the stream</p> <pre><code>IntStream stars = chars.map(c -&gt; c == ' ' ? ' ': '*'); </code></pre> <p>I have been hunting for a tidy way to print the results and I cant even find a simple way. How do I put this stream of <code>int</code>s back into a form that can be printed like I can a <code>String</code>.</p> <p>From the above <code>stars</code> I hope to print</p> <pre><code>***** ****** </code></pre>
20,268,845
10
1
null
2013-11-28 12:36:40.73 UTC
14
2021-04-18 09:38:08.143 UTC
2015-02-17 16:43:43.363 UTC
null
1,441,122
null
823,393
null
1
57
java|java-8|java-stream
18,929
<pre><code>String result = "Hello world." .codePoints() //.parallel() // uncomment this line for large strings .map(c -&gt; c == ' ' ? ' ': '*') .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); </code></pre> <p>But still, <code>"Hello world.".replaceAll("[^ ]", "*")</code> is simpler. Not everything benefits from lambdas.</p>
6,902,135
side effect for increasing maxpermsize and max heap size
<p>Can anybody explain the side effects for increasing the maxpermsize and max heap size? </p> <p>I know that sometimes, we increase -Xmx when we run into the outofmemory issue. But I am just wondering if there is any side effect that I need to keep in mind when we increase the -Xmx. And how does increasing maxpermsize affect the runtime?</p> <p>Thanks.</p>
6,916,718
2
0
null
2011-08-01 17:32:25.207 UTC
33
2016-12-12 05:29:40.84 UTC
2011-08-02 18:15:00.223 UTC
null
826,323
null
826,323
null
1
35
java|jvm
93,305
<p><strong>Short answer</strong> </p> <p>Doubling java heap size, doubles the waiting time for Garbage Collection pauses, that with current JVM technologies become of multiple seconds when the heap is in the Gb order. It seems that the newly released <a href="https://stackoverflow.com/questions/2254041/java-g1-garbage-collection-in-production">Java 7 is going to change that</a>.</p> <p><strong>Long answer</strong></p> <p>The <strong>MaxPermSize</strong> is the maximum size for the permanent generation heap, a heap that holds the byte code of classes and is kept separated from the object heap containing the actual instances. One thing to keep in mind in case of web applications, is that in each hot re-deployment this memory usage is going to increase with multiple copies of the same classes. Unless -XX:+CMSClassUnloadingEnabled is specified.</p> <p><strong>Max Heap Size</strong> (-Xmx) and MaxPermSize have to be set taking into consideration how much memory is needed by the application classes and instances, the total memory of the server and the memory needed by other applications.</p> <p>Another important point is that expanding the memory from the <strong>Min Heap Size</strong> (-Xms) is a costly operation. Especially in case of financial applications this could mean delays. With similar real-time requirements, it could be a good idea to set -Xms and -Xmx to the same value.</p> <p>The following talk may be of interest <a href="http://www.infoq.com/presentations/Java-without-the-GC-Pauses" rel="noreferrer">http://www.infoq.com/presentations/Java-without-the-GC-Pauses</a></p> <p>From the talk you can evince that the side effect of increasing the heap more than a certain limit 2Gb, 10Gb, 100Gb, means longer pause time for Garbage Collection that could stop everything for seconds or a minute in case of very large heaps.</p> <p>For that reason with current JVM technology, you want to set the heap large enough to run your application, but not too large. A way to find the right size, could be set it to the largest possible value, then cut in half and keeping on cutting in half until you find problems, when you do, double the last found value and keep it as the chosen heap size for production. </p> <p>This advice of course applies for large heaps, in the Gb order, if your application runs fine with 256Mb of memory, I would just keep that value without further investigation.</p> <p>And finally for reference here are some example settings:</p> <pre><code>-Xms512m -Xmx512m -XX:MaxPermSize=256m -XX:+CMSClassUnloadingEnabled </code></pre>
6,517,822
Do I need to add armv6 support when limiting apps to iOS 4.0+?
<p>At the moment I'm compiling for both armv6 and armv7. I've also set the target iOS version as 4.0.</p> <p>Am I right in saying that all devices capable of running iOS 4.0+ are armv7, and thus I can stop compiling for armv6?</p> <p>Not a big deal, but it means that my app's binary will be quite a bit smaller if I can.</p>
6,517,863
2
1
null
2011-06-29 08:37:53.233 UTC
25
2014-12-08 14:14:28.97 UTC
null
null
null
null
555,619
null
1
66
iphone|ios|armv7|armv6
25,113
<p>Sorry, but you aren't right. The iPhone 3G and iPod Touch 2G are able to run iOS 4 (barely) and they include a armv6 processor.</p> <pre> ARMv8 / ARM64 = iPhone 5s, iPad Air, Retina iPad Mini ARMv7s = iPhone 5, iPhone 5c, iPad 4 ARMv7 = iPhone 3GS, iPhone 4, iPhone 4S, iPod 3G/4G/5G, iPad, iPad 2, iPad 3, iPad Mini ARMv6 = iPhone, iPhone 3G, iPod 1G/2G </pre> <p>iOS 4.3+ requires ARMv7. If your Deployment Target is 4.3, you can exclude armv6 support.</p> <p>As of XCode 4.5 you cannot build for armv6 @Paul de Lange</p>
7,337,709
Why do I need to apply a window function to samples when building a power spectrum of an audio signal?
<p>I have found for several times the <a href="https://stackoverflow.com/questions/2881583/how-to-extract-semi-precise-frequencies-from-a-wav-file-using-fourier-transforms/2885833#2885833">following guidelines</a> for getting the power spectrum of an audio signal:</p> <ul> <li>collect N samples, where N is a power of 2</li> <li>apply a suitable window function to the samples, e.g. Hanning</li> <li>pass the windowed samples to an FFT routine - ideally you want a real-to-complex FFT but if all you have a is complex-to-complex FFT then pass 0 for all the imaginary input parts</li> <li>calculate the squared magnitude of your FFT output bins (re * re + im * im)</li> <li>(optional) calculate 10 * log10 of each magnitude squared output bin to get a magnitude value in dB</li> <li>Now that you have your power spectrum you just need to identify the peak(s), which should be pretty straightforward if you have a reasonable S/N ratio. Note that frequency resolution improves with larger N. For the above example of 44.1 kHz sample rate and N = 32768 the frequency resolution of each bin is 44100 / 32768 = 1.35 Hz.</li> </ul> <p>But... why do I need to apply a window function to the samples? What does that really means? </p> <p>What about the power spectrum, is it the power of each frequency in the range of sample rate? (example: windows media player visualizer of sound?)</p>
7,339,777
4
0
null
2011-09-07 17:01:03.107 UTC
14
2017-12-04 16:10:20.197 UTC
2017-05-23 11:47:14.977 UTC
null
-1
null
933,104
null
1
22
audio|signal-processing|fft|spectrum|window-functions
17,569
<p>As @cyco130 says, your samples are already windowed by a rectangular function. Since a Fourier Transform assumes periodicity, any discontinuity between the last sample and the repeated first sample will cause artefacts in the spectrum (e.g. "smearing" of the peaks). This is known as <a href="http://en.wikipedia.org/wiki/Spectral_leakage">spectral leakage</a>. To reduce the effect of this we apply a tapered window function such as a <a href="http://en.wikipedia.org/wiki/Hann_window">Hann window</a> which smooths out any such discontinuity and thereby reduces artefacts in the spectrum.</p>
7,666,408
How to request administrator permissions when the program starts?
<p>I need my software to be able to run as administrator on Windows Vista (if someone runs it without administrative permissions, it will crash). </p> <p>When launching other software, I've seen a prompt by the system like "this software will run as administrator. do you want to continue?" when the app was trying to acquire administrative privileges.</p> <p>How do I request administrative privileges when running an c# app on Windows Vista?</p>
7,666,459
4
1
null
2011-10-05 19:13:03.243 UTC
23
2022-06-22 16:03:55.997 UTC
null
null
null
null
847,200
null
1
85
c#|windows|windows-7|windows-vista
94,176
<p>Add the following to your manifest file:</p> <pre><code>&lt;requestedExecutionLevel level="requireAdministrator" uiAccess="false" /&gt; </code></pre> <p>You can also use <code>highestAvailable</code> for the level.</p> <p>Look here about embedding manifest files:</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb756929.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb756929.aspx</a></p> <p>PS: If you don't have a manifest file, you can easily add a new one:</p> <blockquote> <p>In Visual Studio, right click project -> Add Item -> Choose Application Manifest File ( under General for Visual C# items)</p> </blockquote> <p>The added file will already have the above part, just change the level to <code>requireAdministrator</code> from <code>asInvoker</code></p>
7,526,625
Matplotlib - global legend and title aside subplots
<p>I've started with matplot and managed some basic plots, but now I find it hard to discover how to do some stuff I need now :(</p> <p>My actual question is how to place a global title and global legend on a figure with subplots.</p> <p>I'm doing 2x3 subplots where I have a lot of different graphs in various colors (about 200). To distinguish (most) of them I wrote something like</p> <pre><code>def style(i, total): return dict(color=jet(i/total), linestyle=["-", "--", "-.", ":"][i%4], marker=["+", "*", "1", "2", "3", "4", "s"][i%7]) fig=plt.figure() p0=fig.add_subplot(321) for i, y in enumerate(data): p0.plot(x, trans0(y), "-", label=i, **style(i, total)) # and more subplots with other transN functions </code></pre> <p>(any thoughts on this? :)) Each subplot has the same style function.</p> <p>Now I'm trying to get a global title for all subplots and also a global legend which explains all styles. Also I need to make the font tiny to fit all 200 styles on there (I don't need completely unique styles, but at least some attempt)</p> <p>Can someone help me solve this task?</p>
9,221,226
4
1
null
2011-09-23 09:05:13.493 UTC
27
2020-03-13 17:30:14.903 UTC
null
null
null
null
815,443
null
1
156
matplotlib|title|legend|subplot
155,415
<p><strong>Global title</strong>: In newer releases of matplotlib one can use <a href="https://matplotlib.org/3.2.0/api/_as_gen/matplotlib.figure.Figure.html" rel="noreferrer">Figure.suptitle()</a> method of <code>Figure</code>:</p> <pre><code>import matplotlib.pyplot as plt fig = plt.gcf() fig.suptitle("Title centered above all subplots", fontsize=14) </code></pre> <p>Alternatively (based on <a href="https://stackoverflow.com/users/3585557/steven-c-howell">@Steven C. Howell</a>'s comment below (thank you!)), use the <a href="https://matplotlib.org/3.2.0/api/_as_gen/matplotlib.pyplot.suptitle.html" rel="noreferrer">matplotlib.pyplot.suptitle()</a> function:</p> <pre><code> import matplotlib.pyplot as plt # plot stuff # ... plt.suptitle("Title centered above all subplots", fontsize=14) </code></pre>
23,963,580
Get current year in TSQL
<p>I have data I am trying to pull for a report and I am working on a Year to Date report. My columns in the table are formatted as datetime. I am trying to run a select statement to get all the results where date = this year.</p> <p>For example:</p> <pre><code>SELECT A.[id], A.[classXML] FROM tuitionSubmissions as A WHERE A.[status] = 'Approved' AND A.[reimbursementDate] = THISYEAR FOR XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root'); </code></pre> <p>Is there an eay way to acomplish this?</p>
23,963,601
2
1
null
2014-05-30 21:20:23.36 UTC
3
2014-05-30 22:18:59.53 UTC
2014-05-30 21:25:54.793 UTC
null
41,956
null
2,628,921
null
1
36
sql|tsql|datetime
69,138
<p>Yes, it's remarkably easy in fact:</p> <pre><code>WHERE YEAR(A.[reimbursementDate]) = YEAR(GETDATE()) </code></pre>
24,034,483
What is an "unwrapped value" in Swift?
<p>I'm learning Swift for iOS 8 / OSX 10.10 by following <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/GuidedTour.html#//apple_ref/doc/uid/TP40014097-CH2" rel="noreferrer">this tutorial</a>, and the term &quot;<strong>unwrapped value</strong>&quot; is used several times, as in this paragraph (under <em>Objects and Class</em>):</p> <blockquote> <p>When working with optional values, you can write ? before operations like methods, properties, and subscripting. If the value before the ? is nil, everything after the ? is ignored and the value of the whole expression is nil. Otherwise, <strong>the optional value is unwrapped</strong>, and everything after the ? acts on the <strong>unwrapped value</strong>. In both cases, the value of the whole expression is an optional value.</p> </blockquote> <pre><code>let optionalSquare: Square? = Square(sideLength: 2.5, name: &quot;optional square&quot;) let sideLength = optionalSquare?.sideLength </code></pre> <p>I don't get it, and searched on the web without luck.</p> <p>What does this means?</p> <hr /> <h2>Edit</h2> <p>From Cezary's answer, there's a slight difference between the output of the original code and the final solution (tested on playground) :</p> <h3>Original code</h3> <p><img src="https://i.stack.imgur.com/Ns3my.png" alt="Original code" /></p> <h3>Cezary's solution</h3> <p><img src="https://i.stack.imgur.com/RsvFp.png" alt="Cezary's solution" /></p> <p>The superclass' properties are shown in the output in the second case, while there's an empty object in the first case.</p> <p>Isn't the result supposed to be identical in both case?</p> <p><strong>Related Q&amp;A : <a href="https://stackoverflow.com/a/24026093/1437016">What is an optional value in Swift?</a></strong></p>
24,034,551
5
2
null
2014-06-04 10:02:40.767 UTC
63
2021-04-17 17:06:56.61 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,437,016
null
1
160
ios|swift|ios8
85,300
<p>First, you have to understand what an Optional type is. An optional type basically means that the variable <em>can be</em> <code>nil</code>.</p> <p>Example:</p> <pre><code>var canBeNil : Int? = 4 canBeNil = nil </code></pre> <p>The question mark indicates the fact that <code>canBeNil</code> can be <code>nil</code>.</p> <p>This would not work:</p> <pre><code>var cantBeNil : Int = 4 cantBeNil = nil // can't do this </code></pre> <p>To get the value from your variable if it is optional, you have to <strong><em>unwrap it</em></strong>. This just means putting an exclamation point at the end.</p> <pre><code>var canBeNil : Int? = 4 println(canBeNil!) </code></pre> <p>Your code should look like this:</p> <pre><code>let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare!.sideLength </code></pre> <p>A sidenote:</p> <p>You can also declare optionals to automatically unwrap by using an exclamation mark instead of a question mark. </p> <p>Example:</p> <pre><code>var canBeNil : Int! = 4 print(canBeNil) // no unwrapping needed </code></pre> <p>So an alternative way to fix your code is:</p> <pre><code>let optionalSquare: Square! = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare.sideLength </code></pre> <h2>EDIT:</h2> <p>The difference that you're seeing is exactly the symptom of the fact that the optional value is <strong>wrapped</strong>. There is another layer on top of it. The <strong>unwrapped</strong> version just shows the straight object because it is, well, unwrapped.</p> <p>A quick playground comparison:</p> <p><img src="https://i.stack.imgur.com/ClB78.png" alt="playground"></p> <p>In the first and second cases, the object is not being automatically unwrapped, so you see two "layers" (<code>{{...}}</code>), whereas in the third case, you see only one layer (<code>{...}</code>) because the object is being automatically unwrapped.</p> <p>The difference between the first case and the second two cases is that the second two cases will give you a runtime error if <code>optionalSquare</code> is set to <code>nil</code>. Using the syntax in the first case, you can do something like this:</p> <pre><code>if let sideLength = optionalSquare?.sideLength { println("sideLength is not nil") } else { println("sidelength is nil") } </code></pre>
8,175,481
How to use SignalR to notify web clients from ASP.NET MVC 3 that MSMQ tasks were completed
<p>How would one use SignalR to implement notifications in an .NET 4.0 system that consists of an ASP.NET MVC 3 application (which uses forms authentication), SQL Server 2008 database and an MSMQ WCF service (hosted in WAS) to process data? The runtime environment consists of IIS 7.5 running on Windows Server 2008 R2 Standard Edition. </p> <p>I have only played with the samples and do not have extensive knowledge of SignalR.</p> <p><strong>Here is some background</strong></p> <p>The web application accepts data from the user and adds it to a table. It then calls an one way operation (with the database key) of the WCF service to process the data (a task). The web application returns to a page telling the user the data was submitted and they will be notified when processing is done. The user can look at an "index" page an see which tasks are completed, failed or are in progress. They can continue to submit more tasks (which is independent of previous data). They can close their browser and come back later.</p> <p>The MSMQ based WCF service reads the record from the database and processes the data. This may take anything from milliseconds to several minutes. When its done processing the data, the record is updated with the corresponding status (error or fail) and results.</p> <p>Most of the time, the WCF service is not performing any processing, however when it does, users generally want to know when its done as soon as possible. The user will still use other parts of the web application even if they don't have data to be processed by the WCF Service.</p> <p><strong>This is what I have done</strong></p> <p>In the primary navigation bar, I have an indicator (similar to Facebook or Google+) for the user to notify them when the status of tasks has changed. When they click on it, they get a summary of what was done and can then view the results if they wish to.</p> <p>Using jQuery, I poll the server for changes. The controller action checks to see if there is any processes that were modified (completed or failed) and return them otherwise waits a couple of seconds and check again without returning to the client. In order to avoid a time out on the client, it will return after 30 seconds if there was no changes. The jQuery script waits a while and tries again. </p> <p><strong>The problems</strong></p> <p>Performance degrades with every user that views a page. There is no need for them to do anything in particular. We've noticed that memory usage of Firefox 7+ and Safari increases over time.</p> <p><strong>Using SignalR</strong></p> <p>I'm hoping that switching to SignalR can reduce polling and thus reduce resource requirements especially if nothing has changed task wise in the database. I have trouble getting the WCF service to notify clients that its done with processing a task given the fact that it uses forms based authentication. </p> <p>By asking this question, I hope someone will give me better insight how they will redesign my notification scheme using SignalR, if at all.</p>
8,214,570
1
1
null
2011-11-17 22:48:00.327 UTC
10
2013-07-05 16:24:50.727 UTC
null
null
null
null
715,978
null
1
17
c#|wcf|asp.net-mvc-3|msmq|signalr
11,630
<p>If I understand correctly, you need a way of associating a task to a given user/client so that you can tell the client when their task has completed.</p> <p>SignalR API documentation tells me you can call JS methods for specific clients based on the client id (<a href="https://github.com/SignalR/SignalR/wiki/SignalR-Client" rel="noreferrer">https://github.com/SignalR/SignalR/wiki/SignalR-Client</a>). In theory you could do something like:</p> <ol> <li>Store the client id used by SignalR as part of the task metadata:</li> <li>Queue the task as normal.</li> <li>When the task is processed and de-queued: <ul> <li>Update your database with the status.</li> <li>Using the client id stored as part of that task, use SignalR to send that client a notification:</li> </ul></li> </ol> <p>You should be able to retrieve the connection that your client is using and send them a message:</p> <pre><code>string clientId = processedMessage.ClientId //Stored when you originally queued it. IConnection connection = Connection.GetConnection&lt;ProcessNotificationsConnection&gt;(); connection.Send(clientId, "Your data was processed"); </code></pre> <p>This assumes you mapped this connection and the client used that connection to start the data processing request in the first place. Your "primary navigation bar" has the JS that started the connection to the <code>ProcessNotificationsConnection</code> endpoint you mapped earlier.</p> <p><strong>EDIT: From <a href="https://github.com/SignalR/SignalR/wiki/Hubs" rel="noreferrer">https://github.com/SignalR/SignalR/wiki/Hubs</a></strong></p> <pre><code>public class MyHub : Hub { public void Send(string data) { // Invoke a method on the calling client Caller.addMessage(data); // Similar to above, the more verbose way Clients[Context.ClientId].addMessage(data); // Invoke addMessage on all clients in group foo Clients["foo"].addMessage(data); } } </code></pre>
1,447,094
Where does Visual Studio search for txt files when conducting file management operations?
<p>I know this is a noob question, but I've worked with Python before and when you wanted to simply access a .txt file for example, all you had to do was make sure the txt file was in the same directory. I have the following C++ code below but it's not finding the Numbers.txt file that I have saved on my desktop. All I have in the file is one line of numbers of type double. All I want to do is to find the average of all of the numbers in the file. The program runs fine, but it doesn't print the output correctly. After checking to see what is printing into output by just printing output[0], I've discovered that the file is not copying it's contents into the array. Could someone clear this little problem up for me or at least point me in the right direction to a good tutorial?</p> <pre><code>int main() { cout &lt;&lt; "Getting File Information..." &lt;&lt; endl; ifstream file; char output[100]; //int x; file.open("Numbers.txt", ios::in); // open file cout &lt;&lt; "Opened File Successfully ****************" &lt;&lt; endl; file &gt;&gt; output; // empty file contents into output cout &lt;&lt; output; // print out contents of file cout &lt;&lt; "Should have printed out results by now" &lt;&lt; endl; //file &gt;&gt; x; file.close(); return 0; } </code></pre>
1,447,110
4
0
null
2009-09-18 22:30:01.06 UTC
0
2013-03-20 10:35:20.937 UTC
2009-09-18 22:37:09.91 UTC
null
50,109
null
128,422
null
1
13
c++|visual-studio|fstream|ifstream|file-management
68,650
<p>Visual Studio sets the working directory to YourProjectDirectory\Debug\Bin when running in debug mode. If your text file is in YourProjectDirectory, you need to account for that difference.</p> <p>The easiest way to do that is to include your text files in the project and set their build action (in the Properties window) to Content.</p>
1,503,900
Best practices for developing scalable video transcoding server on Amazon Web Services?
<p>What do people think are the most important issues when developing an application that is going to allow users to upload video and images to a server and have them transcoded by FFMPEG and stored in amazon S3? I have a couple of options;</p> <p>1) install FFMPEG on the same server that handles file uploads, when a video is uploaded and stored on EC2 instance, call FFMPEG to convert it then when done, write the file to S3 bucket and dispose of the original. </p> <p>How scalable is this? What happens when many users upload at the same time? How do I manage multiple processes at once? How do I know when to start another instance and load balance this configuration?</p> <p>2) Have one server for processing uploads (updating database, renaming files etc) and one server for doing transcoding. Again what is the best way to manage multiple processes? should I be looking at Amazon SQS for this? Can I tell the transcoding server to get the file from the upload server or should I copy the file to the transcoding server? Should I just store all files on S3 and SQS can read from there. I am trying to have as little traffic as possible.</p> <p>I am running a linux box as the upload server and have FFMPEG running on this. </p> <p>Any advice on best practices for setting up such a configuration would be appreciated. Many thanks</p>
1,509,619
4
1
null
2009-10-01 13:18:18.337 UTC
10
2017-07-06 17:14:33.933 UTC
null
null
null
null
77,174
null
1
16
amazon-ec2|ffmpeg|amazon-web-services|amazon-sqs
8,255
<p>I don't think you'll want to start a new FFMPEG instance every time someone uploads a file for transcoding. Instead, you'll probably want to start the same number of FFMPEG processes as the number of CPUs you have, then queue up the input files you want to transcode and do them in the order they were received. You could do this all on one computer, I don't think the server that accepts the uploads and puts them in the queue will need take much CPU and can probably coexist just fine with the FFMPEG processes. </p> <p>Depending on how big you want to scale to (if you want to do more than just a few FFMPEG processes on a single machine) you could easily make this distributed, and this is where SQS would come in handy. You could run 1 FFMPEG process per core, and instead of looking in a local queue for the data, it could look to the SQS. Then you could instantiate as many transcoding processes as you need, on different machines. </p> <p>The downside to this, is that you will need to transfer the raw videos from the server that accepts them to the server that needs to transcode them. You could put them in S3 then grab them out of S3, but I don't remember off the top of my head if you have to pay for that. Alternatively, you could just keep them on the hard disk of the machine that received them, and have the transcoding process go there to get the raw files. </p>
10,333,098
UTF-8 safe equivalent of ord or charCodeAt() in PHP
<p>I need to be able to use ord() to get the same value as javascript's charCodeAt() function. The problem is that ord() doesn't support UTF8.</p> <p>How can I get Ą to translate to 260 in PHP? I've tried some uniord functions out there, but they all report 256 instead of 260.</p> <p>Thanks a lot for any help!</p> <p>Regards</p>
10,333,307
5
2
null
2012-04-26 12:09:29.413 UTC
9
2020-11-16 16:03:10.793 UTC
2018-06-27 10:05:25.35 UTC
null
1,956,010
null
1,098,946
null
1
17
php|javascript|utf-8|character-encoding
23,351
<p><code>ord()</code> works byte per byte (as most of PHPs standard string functions - if not all). You would need to convert it your own, for example with the help of the multibyte string extension:</p> <pre><code>$utf8Character = 'Ą'; list(, $ord) = unpack('N', mb_convert_encoding($utf8Character, 'UCS-4BE', 'UTF-8')); echo $ord; # 260 </code></pre>
10,600,795
WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."
<p>Hi Friends previously I am using XAMP Server but when I install joomla Templates it creates alots of error. Now I installed the WAMP, but the issues are: 1. I can access with 127.0.0.1, but I cant access with "localhost". 2 When i access phpmyadmin i get this error. </p> <p>Forbidden You don't have permission to access /phpmyadmin/ on this server.</p> <pre><code> Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.4.5/" # to give access to phpmyadmin from outside # replace the lines # # Order Deny,Allow # Deny from all # Allow from 127.0.0.1 # # by # # Order Allow,Deny # Allow from all # </code></pre> <blockquote> <p>After changing, it will look like this</p> </blockquote> <pre><code>&lt;Directory "c:/wamp/apps/phpmyadmin3.4.5/"&gt; Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all &lt;/Directory&gt; </code></pre> <blockquote> <p>After this just restart Wamp</p> </blockquote>
14,077,982
15
2
null
2012-05-15 12:36:34.343 UTC
16
2017-01-27 18:41:00.753 UTC
2016-05-08 21:47:13.347 UTC
null
6,115,214
null
687,146
null
1
30
php|wamp
246,104
<p>Go to <code>C:\wamp\alias</code>. Open the file <code>phpmyadmin.conf</code> and change </p> <pre><code>&lt;Directory "c:/wamp/apps/phpmyadmin3.5.1/"&gt; Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Deny from all Allow from 127.0.0.1 &lt;/Directory&gt; </code></pre> <p>to</p> <pre><code>&lt;Directory "c:/wamp/apps/phpmyadmin3.5.1/"&gt; Options Indexes FollowSymLinks MultiViews AllowOverride all Order Allow,Deny Allow from all &lt;/Directory&gt; </code></pre> <p>problem solved</p>
55,030,498
why don't const and let statements get defined on the window object
<p>Let's take the following code for example:</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>const constVar = 'some string'; let letVar = 'some string'; var varVar = 'some string'; (function() { console.log(window.constVar); // prints undefined console.log(window.letVar); // prints undefined console.log(window.varVar); // prints 'some string' })();</code></pre> </div> </div> </p> <p>According to the description of the <code>const</code> statement by mdn: </p> <blockquote> <p>This declaration creates a constant whose scope can be either global or local to the block in which it is declared.</p> </blockquote> <p>And I assume <code>let</code> works in the same way. </p> <p>In this case, the "block" is contained within the global scope. I guess the important distinction here is that while <code>const constVar</code> is "globally" accessible it still doesn't define it on the <code>window</code> object.</p> <p>Which leads me to think that global scope and the <code>window</code> object are disparate. Which ultimately leads to 2 questions. </p> <ol> <li><p>Why do variables declared using the <code>var</code> keyword get defined on <code>window</code> and variables declared with <code>const</code> and <code>let</code> not defined on <code>window</code>? </p></li> <li><p>What is the difference between "global scope" and the <code>window</code> object provided to us by browsers.</p></li> </ol>
55,031,001
2
7
null
2019-03-06 19:08:36.71 UTC
3
2019-03-06 19:41:00.79 UTC
2019-03-06 19:12:12.887 UTC
user47589
null
null
4,008,366
null
1
35
javascript
8,959
<blockquote> <p>1. Why do variables declared using the <code>var</code> keyword get defined on window and variables declared with <code>const</code> and <code>let</code> not defined on window? </p> </blockquote> <p>Because the specification says so. If you are asking for the reason behind that decision, then you should reach out to the specification maintainers.</p> <p>Classes do not become properties of the global object either btw.</p> <blockquote> <p>2. What is the difference between "global scope" and the <code>window</code> object provided to us by browsers.</p> </blockquote> <p>There are two types of base <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-environment-records" rel="noreferrer">environment records</a> according to the spec:</p> <ul> <li>Declarative Environment Record</li> <li>Object Environment Record</li> </ul> <p>A <em>Declarative Environment Record</em> is basically your standard environment that you get when calling a function. All bindings (variables, constants, etc) are defined in some internal data structure that cannot be accessed from normal code.</p> <p>An <em>Object Environment Record</em> on the other hand uses an actual JavaScript object to store bindings. This is used for example by the now deprecated <code>with</code> statement:</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>with({foo: 42}) { console.log(foo); }</code></pre> </div> </div> </p> <p>Now, a <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-global-environment-records" rel="noreferrer"><strong>Global Environment Record</strong></a> actually consists of two environment records: A declarative environment record and an object environment record. The object environment is backed by the global object, i.e. <code>window</code> and contains <code>var</code> declarations and other globals that the browser provides. The declarative environment contains the <code>let</code>, <code>const</code>, <code>class</code>, etc declarations.</p>
7,249,378
Disabling C++ exceptions, how can I make any std:: throw() immediately terminate?
<p>This C++ program is a CGI script, I have no desire to deal with exceptions. I'd rather get a marginal performance boost and let the OS (Linux) handle cleanup after the process dies.</p> <p>I am using the Standard C++ Library, and want any function to <code>die</code> like in Perl: <strong>Whenever it throws an exception.</strong> Without unwinding, <em>or running any further code</em> in my process.</p> <p>How does -fno-exceptions work? If I have no catch at all in my code, and basically pretend like exceptions do no exist. but I <strong>do</strong> use std:: c++ library which <strong>can</strong> throw()?</p>
7,249,442
5
19
null
2011-08-30 20:27:27.333 UTC
22
2016-10-18 19:21:54.043 UTC
2012-10-02 21:09:33.653 UTC
null
387,076
null
504,239
null
1
55
c++|exception-handling|g++|exit
43,909
<p>Option #1: Simply never catch exceptions.</p> <p>Exceptions don't have much overhead when they're not thrown or caught; if you're throwing and not prepared to catch, well, you're doing to die anyway, so the performance impact at that point is trivial. Note also that stack unwinding will not be performed if an exception is not handled; the program will simply terminate without performing stack unwinding.</p> <p>It's important to note that, in G++, exceptions have almost no overhead when not actually thrown. G++ generates extra information sufficient to trace back the execution of the program through the stack, and some extra code to invoke destructors, etc - however none of this extra code or data is ever used until an exception is actually thrown. So you should not see a performance difference between code with exceptions enabled but not used and code with exceptions disabled (through whatever mechanism).</p> <p>Option #2: Pass <code>-fno-exceptions</code>.</p> <p>This flag instructs G++ to <a href="http://gcc.gnu.org/onlinedocs/libstdc++/manual/using_exceptions.html">do two things</a>:</p> <ol> <li>All exception handling in STL libraries are removed; throws are replaced with <code>abort()</code> calls</li> <li>Stack unwind data and code is removed. This saves some code space, and may make register allocation marginally easier for the compiler (but I doubt it'll have much performance impact). Notably, however, if an exception is thrown, and the library tries to unwind through <code>-fno-exceptions</code> code, it will abort at that point, as there is no unwind data.</li> </ol> <p>This will, effectively, turn all exceptions into <code>abort()</code>s, as you would like. Note, however, that you will not be allowed to <code>throw</code> - any actual <code>throw</code>s or <code>catch</code>s in your code will result in a compile-time error.</p> <p>Option #3: (Nonportable and not recommended!) Hook __cxa_allocate_exception.</p> <p>C++ exceptions are implemented using (among others) the __cxa_allocate_exception and __cxa_throw internal library functions. You can implement a LD_PRELOAD library that hooks these functions to abort():</p> <pre><code>void __cxa_allocate_exception() { abort(); } void __cxa_throw() { abort(); } </code></pre> <p>WARNING: This is a horrible hack. It should work on x86 and x86-64, but I strongly recommend against this. Notably, it won't actually improve performance or save code space, as <code>-fno-exceptions</code> might. However, it will allow the <code>throw</code> <em>syntax</em>, while turning <code>throw</code>s into <code>abort()</code>s.</p>
7,291,731
how to play audio file in android
<p>I have a mp3 file in my android mobile, lets it's a xyz.mp3 somewhere in my sdcard. How to play it through my application?</p>
7,291,756
5
1
null
2011-09-03 07:18:48.753 UTC
14
2021-11-13 11:36:40.863 UTC
2019-02-22 22:01:04.727 UTC
null
4,505,446
null
891,725
null
1
64
android|audio|android-widget|media-player
112,519
<p>Simply you can use <code>MediaPlayer</code> and play the audio file. Check out <a href="http://www.helloandroid.com/tutorials/how-play-video-and-audio-android" rel="noreferrer">this nice example</a> for playing Audio:</p> <pre><code> public void audioPlayer(String path, String fileName){ //set up MediaPlayer MediaPlayer mp = new MediaPlayer(); try { mp.setDataSource(path + File.separator + fileName); mp.prepare(); mp.start(); } catch (Exception e) { e.printStackTrace(); } } </code></pre>
7,605,942
BGI error, How to Resolve it?
<p>I want to run a C program that draws a circle. The program is compiling with no error and it is running. After getting the values like radius from the user, I get the error like this : </p> <p><code>BGI error: Graphics not initialized ( use "initgraph")</code></p> <p>Even though in my source code I have added this line : </p> <pre><code>int gmode,gdrive=DETECT; initgraph(&amp;gdrive,&amp;gmode,"c\\tc\\bgi"); </code></pre> <p>Still I'm getting error.</p> <p>I'm using Windows and I couldn't figure out where I went wrong. Can anyone help me in this regard?</p> <p>Thanks in advance.</p>
7,605,982
6
7
null
2011-09-30 04:27:46.223 UTC
1
2019-10-10 22:44:32.247 UTC
2014-06-29 09:12:04.39 UTC
null
2,521,214
null
678,672
null
1
7
c|turbo-c|bgi
56,587
<p>Your path in <code>initgraph</code> is wrong. Use <code>"c:\\tc\bgi"</code> instead.</p>
7,089,627
How can I retrieve the logical file name of the database from backup file
<p>I was looking into the steps of how to <a href="http://blog.sqlauthority.com/2007/02/25/sql-server-restore-database-backup-using-sql-script-t-sql/">Restore Database Backup using SQL Script (T-SQL)</a>. Here are the steps:</p> <blockquote> <p>Database <code>YourDB</code> has full backup <code>YourBackUpFile.bak</code>. It can be restored using following two steps:</p> <p><strong>Step 1:</strong> Retrieve the logical file name of the database from the backup.</p> <pre><code>RESTORE FILELISTONLY FROM DISK = 'D:BackUpYourBackUpFile.bak' GO </code></pre> <p><strong>Step 2:</strong> Use the values in the <code>LogicalName</code> column in the following step.</p> <pre><code>----Make Database to single user Mode ALTER DATABASE YourDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE ----Restore Database RESTORE DATABASE YourDB FROM DISK = 'D:BackUpYourBackUpFile.bak' WITH MOVE 'YourMDFLogicalName' TO 'D:DataYourMDFFile.mdf', MOVE 'YourLDFLogicalName' TO 'D:DataYourLDFFile.ldf' </code></pre> </blockquote> <p>I am just having problem on how to get the <code>YourMDFLogicalName</code> and <code>YourLDFLogicalName</code>. Can any one help me with that?</p>
7,090,175
7
0
null
2011-08-17 08:09:40.527 UTC
7
2022-01-18 06:50:48.657 UTC
2014-05-22 15:24:16.363 UTC
null
241,211
null
275,092
null
1
37
sql|sql-server|backup|restore
65,014
<pre><code>DECLARE @Table TABLE (LogicalName varchar(128),[PhysicalName] varchar(128), [Type] varchar, [FileGroupName] varchar(128), [Size] varchar(128), [MaxSize] varchar(128), [FileId]varchar(128), [CreateLSN]varchar(128), [DropLSN]varchar(128), [UniqueId]varchar(128), [ReadOnlyLSN]varchar(128), [ReadWriteLSN]varchar(128), [BackupSizeInBytes]varchar(128), [SourceBlockSize]varchar(128), [FileGroupId]varchar(128), [LogGroupGUID]varchar(128), [DifferentialBaseLSN]varchar(128), [DifferentialBaseGUID]varchar(128), [IsReadOnly]varchar(128), [IsPresent]varchar(128), [TDEThumbprint]varchar(128) ) DECLARE @Path varchar(1000)='C:\SomePath\Base.bak' DECLARE @LogicalNameData varchar(128),@LogicalNameLog varchar(128) INSERT INTO @table EXEC(' RESTORE FILELISTONLY FROM DISK=''' +@Path+ ''' ') SET @LogicalNameData=(SELECT LogicalName FROM @Table WHERE Type='D') SET @LogicalNameLog=(SELECT LogicalName FROM @Table WHERE Type='L') SELECT @LogicalNameData,@LogicalNameLog </code></pre> <p><strong>UPDATE</strong></p> <p>According to <a href="http://msdn.microsoft.com/en-us/library/ms179316.aspx">Microsoft site</a>:</p> <blockquote> <p>SQL Server files have two names:</p> <p>logical_file_name</p> <p>The logical_file_name is the name used to refer to the physical file in all Transact-SQL statements. The logical file name must comply with the rules for SQL Server identifiers and must be unique among logical file names in the database.</p> <p>os_file_name</p> <p>The os_file_name is the name of the physical file including the directory path. It must follow the rules for the operating system file names.</p> </blockquote>
7,106,410
looping through arrays of arrays
<p>I have an arrays of arrays (some thing like graph), How to iterate all arrays?</p> <pre><code>var parentArray = [ [[1,2,3],[4,5,6],[7,8,9]], [[10,11,12],[13,14,15],[16,17,18]], [[19,20,21],[22,23,24],[26,27,28]] ]; </code></pre> <p>Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM</p>
7,106,472
10
1
null
2011-08-18 11:07:16.583 UTC
13
2020-10-30 12:24:59.43 UTC
2011-08-18 11:09:34.243 UTC
null
74,314
null
277,696
null
1
19
javascript|arrays|loops
78,118
<p>This recursive function should do the trick with any number of dimensions:</p> <pre><code>var printArray = function(arr) { if ( typeof(arr) == "object") { for (var i = 0; i &lt; arr.length; i++) { printArray(arr[i]); } } else document.write(arr); } printArray(parentArray); </code></pre>
14,083,847
Accented characters in mySQL table
<p>I have some texts in French (containing accented characters such as "é"), stored in a MySQL table whose collation is utf8_unicode_ci (both the table and the columns), that I want to output on an HTML5 page.</p> <p>The HTML page charset is UTF-8 (&lt; meta charset="utf-8" />) and the PHP files themselves are encoded as "UTF-8 without BOM" (I use Notepad++ on Windows). I use PHP5 to request the database and generate the HTML.</p> <p>However, on the output page, the special characters (such as "é") appear garbled and are replaced by "�".</p> <p>When I browse the database (via phpMyAdmin) those same accented characters display just fine.</p> <p>What am I missing here?</p> <p>(Note: changing the page encoding (through Firefox's "web developer" menu) to ISO-8859-1 solves the problem... except for the special characters that appears directly in the PHP files, which become now corrupted. But anyway, I'd rather understand why it doesn't work as UTF-8 than changing the encoding without understanding why it works. ^^;)</p>
14,083,928
6
1
null
2012-12-29 16:52:22.817 UTC
11
2016-07-25 04:49:55.06 UTC
2015-07-30 14:41:49.527 UTC
null
877,819
null
357,546
null
1
14
php|mysql|unicode|utf-8|non-ascii-characters
56,092
<p>I experienced that same problem before, and what I did are the following</p> <p>1) Use notepad++(can almost adapt on any encoding) or eclipse and be sure in to <strong>save or open it in UTF-8 without BOM</strong>.</p> <p>2) set the encoding in PHP header, using <code>header('Content-type: text/html; charset=UTF-8');</code></p> <p>3) remove any extra spaces on the start and end of my PHP files.</p> <p>4) set all my table and columns encoding to <code>utf8mb4_general_ci</code> or <code>utf8mb4_unicode_ci</code> via PhpMyAdmin or any mySQL client you have. A comparison of the two encodings are available <a href="https://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci">here</a></p> <p>5) set mysql connection charset to UTF-8 (I use PDO for my database connection )</p> <pre><code> PDO::MYSQL_ATTR_INIT_COMMAND =&gt; "SET NAMES utf8" PDO::MYSQL_ATTR_INIT_COMMAND =&gt; "SET CHARACTER SET utf8" </code></pre> <p>or just execute the SQL queries before fetching any data</p> <p>6) use a meta tag <code>&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt;</code></p> <p>7) use a certain language code for French <code>&lt;meta http-equiv="Content-language" content="fr" /&gt;</code></p> <p>8) change the html element lang attribute to the desired language </p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr"&gt; </code></pre> <p>and will be updating this more because I really had a hard time solving this problem before because I was dealing with Japanese characters in my past projects</p> <p>9) Some fonts are not available in the client PC, you need to use <a href="https://www.google.com/fonts" rel="noreferrer">Google fonts</a> to include it on your CSS</p> <p>10) Don't end your PHP source file with <code>?&gt;</code></p> <p><strong>NOTE:</strong></p> <p>but if everything I said above doesn't work, try to adjust your encoding depending on the character-set you really want to display, for me I set everything to <code>SHIFT-JIS</code> to display all my japanese characters and it really works fine. But using <code>UFT-8</code> must be your priority</p>
14,278,587
Insert a new contact intent
<p>For one of my apps, I need the user to select one of his existing contacts or to create a new one. Picking one is clearly easy to do with the following code:</p> <pre><code>i = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI); startActivityForResult(i, PICK_CONTACT_REQUEST ); </code></pre> <p>Now I want to create a new contact. I tried to use that code but it doesn't trigger the activity result:</p> <pre><code>i = new Intent(Intent.ACTION_INSERT); i.setType(Contacts.CONTENT_TYPE); startActivityForResult(i, PICK_CONTACT_REQUEST); </code></pre> <p>The above code will start the contact adding form. Then when I validate it, it just asks me to open the contact list and the onActivityResult method is never triggered.</p> <p>Could you help me to make it working ?</p> <p>I read on some boards that this wasn't possible, and I had to create my own contact adding form. Could you confirm that ?</p> <p><strong>EDIT: Problem solved. Check my answer.</strong></p>
14,279,091
9
1
null
2013-01-11 12:52:01.117 UTC
20
2019-08-22 14:01:52.583 UTC
2013-01-11 13:29:44.953 UTC
null
1,295,422
null
1,295,422
null
1
25
android|contacts|android-contacts
27,687
<p>Finally found a solution, I'm sharing it with you. That's only a fix for Android version above 4.0.3 and sup. It doesn't work on 4.0 to 4.0.2.</p> <pre><code>i = new Intent(Intent.ACTION_INSERT); i.setType(Contacts.CONTENT_TYPE); if (Integer.valueOf(Build.VERSION.SDK) &gt; 14) i.putExtra("finishActivityOnSaveCompleted", true); // Fix for 4.0.3 + startActivityForResult(i, PICK_CONTACT_REQUEST); </code></pre>
14,081,410
Extended UIButton border is not initially drawn
<p>I am trying to create a custom UIButton which extends from <code>UIButtonType.RoundedRect</code>.</p> <p>My added functionality is working, but there is an issue with the initial rounded border state of my button. The border of my extended button is not drawn until after it has been tapped.</p> <p><img src="https://i.stack.imgur.com/s20n3.png" alt="Before-After Screenshot"></p> <p>Update (January 24th 2013): Added the result of red background test, as requested by Richard Marskell, which concludes only the label of the button is drawn. <code>BackgroundColor = UIColor.Red;</code></p> <p><img src="https://i.stack.imgur.com/7uEvp.png" alt="Red Background Test, Before-After Screenshot"></p> <p>Below is my source code for creating my custom button.</p> <pre class="lang-cs prettyprint-override"><code>public class TestView : UIView { public TestView(IntPtr p) : base(p) { } public TestView(RectangleF bounds) { Frame = bounds; BackgroundColor = UIColor.White; UIButton button1 = new UIButton(UIButtonType.RoundedRect); button1.Frame = new RectangleF(20,20,100,50); button1.SetTitle("Button 1", UIControlState.Normal); AddSubview(button1); // Drawn Correctly MyButton button2 = new MyButton(); button2.Frame = new RectangleF(20,90,100,50); button2.SetTitle("Button 2", UIControlState.Normal); AddSubview(button2); // Only drawn correctly after Tap // EDIT: Added to test Miguel's theory UIButton button3 = UIButton.FromType(UIButtonType.RoundedRect); button3.Frame = new RectangleF(20,160,100,50); button3.SetTitle("Button 3", UIControlState.Normal); AddSubview(button3); // Drawn Correctly } } public class MyButton : UIButton { public MyButton() : base(UIButtonType.RoundedRect) { } } </code></pre> <ul> <li>I'm just not sure how to force the border to be drawn correctly on loading of the view.</li> <li>I don't need a button of type <code>UIButtonType.Custom</code>, as I don't want to style the button myself.</li> <li>When I debug I the type of MyButton is correctly set to <code>UIButtonType.RoundedRect</code>.</li> <li>The UIButton base properties of MyButton (button2) match the properties of the UIButton instance (button1). </li> </ul> <p><img src="https://i.stack.imgur.com/cKVJ1.png" alt="Debug"></p> <p>How can I resolve this issue?</p> <hr> <p>Update (January 31st 2013): Herman Schoenfeld provided a suitable solution for this bug.</p>
14,619,344
1
11
null
2012-12-29 11:56:47.94 UTC
2
2013-02-01 01:47:14.483 UTC
2013-01-31 09:20:10.2 UTC
null
1,295,344
null
1,295,344
null
1
31
c#|mono|xamarin.ios|uibutton|uikit
1,371
<p>This works</p> <pre><code>public class MyButton : UIButton { public MyButton() : base(UIButtonType.RoundedRect) { } public override RectangleF Frame { get { return base.Frame; } set { var temp = TranslatesAutoresizingMaskIntoConstraints; TranslatesAutoresizingMaskIntoConstraints = false; var constraints = new [] { NSLayoutConstraint.Create(this, NSLayoutAttribute.Width, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1.0f, value.Width), NSLayoutConstraint.Create(this, NSLayoutAttribute.Height, NSLayoutRelation.Equal, null, NSLayoutAttribute.NoAttribute, 1.0f, value.Height) }; AddConstraints(constraints); SizeToFit(); RemoveConstraints(constraints); base.Frame = value; TranslatesAutoresizingMaskIntoConstraints = temp; } } } </code></pre> <p>This is only a workaround, it appears to be a bug. The SizeToFit() fixes the issue, the other code maintains the frame.</p>
13,942,443
Error installing Rmagick on Mountain Lion
<p>I have seen other people with the same issue of <a href="https://stackoverflow.com/questions/11676844/issue-with-installing-imagemagick-and-rmagick-on-mountain-lion">installing RMagick on Mountain Lion</a> However none of the suggested solutions have allowed me to successfully install rmagick. </p> <p>Here is the error message I am getting:</p> <pre><code>Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension. checking for Ruby version &gt;= 1.8.5... yes checking for /usr/local/bin/gcc-4.2... yes checking for Magick-config... yes checking for ImageMagick version &gt;= 6.4.9... yes checking for HDRI disabled version of ImageMagick... yes checking for stdint.h... yes checking for sys/types.h... yes checking for wand/MagickWand.h... yes checking for InitializeMagick() in -lMagickCore... no checking for InitializeMagick() in -lMagick... no checking for InitializeMagick() in -lMagick++... no Can't install RMagick 2.13.1. Can't find the ImageMagick library or one of the dependent libraries. Check the mkmf.log file for more detailed information. *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. </code></pre> <p>Things I have done:</p> <pre><code>Installed XCode Installed the command line tools Installed XQuartz Installed homebrew with imagemagick library Installed most recent version of RVM Symlinked GCC Uninstalled and reinstalled both RVM and imagemagick </code></pre> <p>Any ideas why I still can't download rmagick?</p>
13,960,185
8
0
null
2012-12-18 22:19:22.47 UTC
31
2018-02-07 14:28:54.98 UTC
2017-05-23 12:13:44.563 UTC
null
-1
null
560,831
null
1
66
imagemagick|rvm|bundler|osx-mountain-lion|rmagick
22,226
<p>It appears it's a problem reported on the Homebrew github repo (<a href="https://github.com/mxcl/homebrew/issues/16625">https://github.com/mxcl/homebrew/issues/16625</a>) blaming rmagick itself not supporting newer versions of imagemagick. On that same issue (<a href="https://github.com/mxcl/homebrew/issues/16625#issuecomment-11519383">https://github.com/mxcl/homebrew/issues/16625#issuecomment-11519383</a>), you can find this link: <a href="https://coderwall.com/p/wnomjg">https://coderwall.com/p/wnomjg</a> which actually worked for me. This is what he does:</p> <pre><code>cd /usr/local/Cellar/imagemagick/6.8.0-10/lib ln -s libMagick++-Q16.7.dylib libMagick++.dylib ln -s libMagickCore-Q16.7.dylib libMagickCore.dylib ln -s libMagickWand-Q16.7.dylib libMagickWand.dylib </code></pre> <p>Hope this helps.</p>
13,846,300
How to make Git pull use rebase by default for all my repositories?
<p>Is there a way to setup the host Git repository such that any <code>git pull</code> done from its (local) clones uses <code>--rebase</code> by default? By searching on Stack&nbsp;Overflow, I learned about <code>branch.autosetuprebase</code>, but it needs to be configured per clone individually. </p> <p>My project flow is set up such that we <code>pull</code> the <code>develop</code> branch before <code>merge</code>ing a feature branch to it. This <code>pull</code> nearly always uses <code>--rebase</code>, so I am trying to figure out if this can be the default. </p>
13,974,638
6
7
null
2012-12-12 18:33:20.233 UTC
76
2022-06-09 11:53:51.58 UTC
2018-08-03 14:14:05.86 UTC
null
63,550
null
252,576
null
1
324
git
156,256
<p>There are now 3 different levels of configuration for default pull behaviour. From most general to most fine grained they are:</p> <h3>1. <code>pull.rebase</code></h3> <p>Setting this to <code>true</code> means that <code>git pull</code> is always equivalent to <code>git pull --rebase</code> (unless <code>branch.&lt;branchname&gt;.rebase</code> is explicitly set to <code>false</code>). This can also be set per repository or globally.</p> <h3>2. <code>branch.autosetuprebase</code></h3> <p>Setting this to <code>always</code> means that whenever a tracking branch is created, a configuration entry like the one below will be created for it. For finer grained control, this can also be set to <code>never</code>, <code>local</code> or <code>remote</code> and can be set per repository or globally. See <code>git config --help</code> for further details.</p> <h3>3. <code>branch.&lt;branchname&gt;.rebase</code></h3> <p>Setting this to <code>true</code> means that that particular branch will always pull from its upstream via rebasing, unless <code>git pull --no-rebase</code> is used explicitly.</p> <h1>Conclusion</h1> <p>So while you can't change the default behaviour for all future clones of a repository, you can change the default for all of the current user's (existing and future) repositories via <code>git config --global pull.rebase true</code>. </p>
14,046,838
MySQL - Operand should contain 1 column(s)
<p>While working on a system I'm creating, I attempted to use the following query in my project:</p> <pre class="lang-sql prettyprint-override"><code>SELECT topics.id, topics.name, topics.post_count, topics.view_count, COUNT( posts.solved_post ) AS solved_post, (SELECT users.username AS posted_by, users.id AS posted_by_id FROM users WHERE users.id = posts.posted_by) FROM topics LEFT OUTER JOIN posts ON posts.topic_id = topics.id WHERE topics.cat_id = :cat GROUP BY topics.id </code></pre> <p>":cat" is bound by my PHP code as I'm using PDO. 2 is a valid value for ":cat".</p> <p>That query though gives me an error: "#1241 - Operand should contain 1 column(s)"</p> <p>What stumps me is that I would think that this query would work no problem. Selecting columns, then selecting two more from another table, and continuing on from there. I just can't figure out what the problem is.</p> <p>Is there a simple fix to this, or another way to write my query?</p>
14,046,855
9
0
null
2012-12-26 22:08:15.057 UTC
18
2021-09-24 12:51:03.15 UTC
2014-10-11 17:04:56.22 UTC
null
20,860
user1543386
null
null
1
116
mysql|sql|mysql-error-1241
402,705
<p>Your subquery is selecting two columns, while you are using it to project one column (as part of the outer <code>SELECT</code> clause). You can only select one column from such a query in this context.</p> <p>Consider joining to the <code>users</code> table instead; this will give you more flexibility when selecting what columns you want from <code>users</code>.</p> <pre><code>SELECT topics.id, topics.name, topics.post_count, topics.view_count, COUNT( posts.solved_post ) AS solved_post, users.username AS posted_by, users.id AS posted_by_id FROM topics LEFT OUTER JOIN posts ON posts.topic_id = topics.id LEFT OUTER JOIN users ON users.id = posts.posted_by WHERE topics.cat_id = :cat GROUP BY topics.id </code></pre>
29,200,503
Significant differences between Cookies and JWT for native mobile apps
<p>I have been using Cookies for authentication and session control in my web apps, and am content with its functionalities.</p> <p>I was introduced by an iOS app developer that the new hot thing is JWT (JSON Web Token). He told me that JWT is <em>the way</em> of doing authentication and sessions for native mobile apps, and without giving specific examples, he suggested that both iOS and Android apps have various problems with Cookies.</p> <p>So I looked up JWT, e.g. <a href="http://angular-tips.com/blog/2014/05/json-web-tokens-introduction/" rel="noreferrer">http://angular-tips.com/blog/2014/05/json-web-tokens-introduction/</a> and <a href="https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/" rel="noreferrer">https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/</a>, and I failed to see why it is significant better (or even that different) than Cookies, and more specifically, why it does better in native mobile apps. It seems that, at least iOS, handles Cookies just fine (<a href="https://stackoverflow.com/questions/4597763/persisting-cookies-in-an-ios-application">Persisting Cookies In An iOS Application?</a>).</p> <p>So my question is, for a native mobile app that interacts with a server-side API, what are the specific advantages and associated use cases for using JWT over Cookies for authentication and sessions? Please highlight the ones that Cookies simply cannot do or does it much worse. </p>
40,020,509
2
3
null
2015-03-22 22:16:14.563 UTC
12
2019-05-01 16:50:01.277 UTC
2017-05-23 11:54:17.563 UTC
null
-1
null
548,240
null
1
34
ios|session|authentication|cookies|jwt
13,163
<p><sub>We software developers (sometimes) have the tendency to apply the new hot thing everywhere we look; it's possibly a variation of the saying <em>if all we have is an hammer, everything looks like a nail</em> where in this case we just feel a desperate urge to use this new thing we learned about.</sub></p> <p>One interesting point about this comparison is that neither <a href="https://auth0.com/learn/json-web-tokens/" rel="noreferrer">JWT</a> or Cookies are in fact authentication mechanisms on their own; the first just defines a <a href="https://www.rfc-editor.org/rfc/rfc7519" rel="noreferrer">token format</a> and the second is an <a href="https://www.rfc-editor.org/rfc/rfc6265" rel="noreferrer">HTTP state management mechanism</a>. Only this is sufficient to give us an indication that advocating that one is better than the other is wrong.</p> <p>It's true however that both are vastly used in authentication systems.</p> <p>Traditional server-side web application have used cookies to keep track of an authenticated user so that they were not forced to provide their credentials at every request. Normally, the content of the cookie would be an (hopefully) random generated unique identifier that the server would use to find session data stored on the server.</p> <p>However, for a new type of web application - the API - it's more much more common to accept a token (in JWT format most of the times) as a way for the server to decide if it should grant access to who's making the request. The reason for this is possibly because while a traditional web application had one major type of client, the web browser, which has full support for cookies, the API's are generally used by much simpler HTTP clients that don't natively support cookies.</p> <p>I think this is also why we could possibly argue that token based authentication makes more sense for native mobile applications. These applications generally depend on a server-side Web API and we've seen that if the API supports tokens it will increase the range of clients that can use it, so it's just the most practical thing to do.</p> <p>In conclusion and to try to answer your concrete question, I would say JWT's do have an advantage over cookies on native mobile applications just because of the fact they are currently in very common use, this means more learning resources, SDK's, known pitfalls (mostly because someone else already did it and failed), etc.</p> <p>Nonetheless, only use them if they give you the security assurances you need and end up simplifying your scenario. If you haven't gone through it already, I think you'll also appreciate <a href="https://auth0.com/blog/cookies-vs-tokens-definitive-guide/" rel="noreferrer">Cookies vs Tokens: The Definitive Guide</a>.</p>
43,811,182
parallelStream vs stream.parallel
<p>I have been curious about the difference between <code>Collections.parallelStream()</code> and <code>Collections.stream().parallel()</code>. According to the Javadocs, <code>parallelStream()</code> tries to return a parallel stream, whereas <code>stream().parallel()</code> returns a parallel stream. Through some testing of my own, I have found no differences. Where does the difference in these two methods lie? Is one implementation more time efficient than another? Thanks.</p>
43,818,012
3
2
null
2017-05-05 17:59:21.43 UTC
17
2020-11-25 11:13:07.063 UTC
2020-02-26 03:18:41.353 UTC
null
1,746,118
null
3,854,096
null
1
52
java|java-8|java-stream
25,056
<p>Even if they act the same <em>at the moment</em>, there is a difference - at least in their documentation, as you correctly pointed out; that might be exploited in the future as far as I can tell.</p> <p>At the moment the <code>parallelStream</code> method is defined in the <code>Collection</code> interface as:</p> <pre><code>default Stream&lt;E&gt; parallelStream() { return StreamSupport.stream(spliterator(), true); } </code></pre> <p>Being a default method it could be overridden in implementations (and that's what <code>Collections</code> inner classes actually do).</p> <p>That hints that even if the default method returns a parallel Stream, there could be Collections that override this method to return a <code>non-parallel Stream</code>. That is the reason the documentation is probably the way it is.</p> <p>At the same time <em>even</em> if <code>parallelStream</code> returns a sequential stream - it is still a <code>Stream</code>, and then you could easily call <code>parallel</code> on it:</p> <pre><code> Collections.some() .parallelStream() // actually sequential .parallel() // force it to be parallel </code></pre> <p>At least for me, this looks weird. </p> <p>It seems that the documentation should somehow state that after calling <code>parallelStream</code> there should be no reason to call <code>parallel</code> again to force that - since it might be useless or even bad for the processing. </p> <p><strong>EDIT</strong></p> <p>For anyone reading this - please read the comments by Holger also; it covers cases beyond what I said in this answer. </p>
32,882,742
Android: How to change size of app:fabSize="normal" for Floating Action Button
<p>When using the new <code>FloatingActionButton</code>, the size is determined by <code>app:fabSize="normal"</code>. How can I set what in <code>dp</code> is the size referenced by <code>"normal"</code>?</p> <p>I tried to create <code>values/attrs.xml</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;declare-styleable name="app"&gt; &lt;attr name="fabSize"&gt; &lt;enum name="mini" value="50dp" /&gt; &lt;enum name="normal" value="100dp" /&gt; &lt;/attr&gt; &lt;/declare-styleable&gt; &lt;/resources&gt; </code></pre> <p>But I get the error</p> <pre><code>"normal" in attribute "fabSize" is not a valid integer </code></pre>
32,883,081
9
3
null
2015-10-01 08:21:37.077 UTC
6
2020-08-04 07:39:58.643 UTC
2017-02-01 09:06:57.787 UTC
null
1,072,229
null
3,832,013
null
1
32
android|android-layout|floating-action-button
48,567
<p>There are two different sizes of <code>FAB</code> available: <code>normal</code> or <code>mini</code></p> <ol> <li><p><code>Normal (56dp)</code> — This size should be used in most situations.</p></li> <li><p><code>Mini (40dp)</code> — Should only be used when there is a need for visual continuity with other components displayed on the screen.</p></li> </ol>
52,056,387
How to install Go in alpine linux
<p>I am trying to install Go inside an Alpine Docker image. For that I downloaded tar file from <a href="https://golang.org/doc/install?download=go1.10.3.linux-amd64.tar.gz" rel="noreferrer">here</a> inside my alpine docker image, untar it using following command:</p> <blockquote> <p>tar -C /usr/local -xzf go1.10.3.linux-amd64.tar.gz</p> </blockquote> <p>exported PATH to have go binary as:</p> <blockquote> <p>export PATH=$PATH:/usr/local/go/bin </p> </blockquote> <p>However, when I say <code>go version</code> then it says that <code>sh: go: not found</code>. I am quite new to alpine. Does anyone know, what I am missing here?</p> <p>Steps to reproduce-</p> <pre><code>$ docker run -it alpine sh $ wget https://dl.google.com/go/go1.10.3.linux-amd64.tar.gz $ tar -C /usr/local -xzf go1.10.3.linux-amd64.tar.gz $ export PATH=$PATH:/usr/local/go/bin $ go version </code></pre>
52,474,413
8
7
null
2018-08-28 11:06:47.057 UTC
13
2022-02-09 09:46:01.09 UTC
2018-08-28 11:16:55.22 UTC
null
4,886,861
null
4,886,861
null
1
46
docker|go|dockerfile|tar|alpine-linux
76,576
<p>Thanks BMitch.</p> <p>I compiled the go source code and performed the below steps inside alpine image container. </p> <pre><code>echo "installing go version 1.10.3..." apk add --no-cache --virtual .build-deps bash gcc musl-dev openssl go wget -O go.tgz https://dl.google.com/go/go1.10.3.src.tar.gz tar -C /usr/local -xzf go.tgz cd /usr/local/go/src/ ./make.bash export PATH="/usr/local/go/bin:$PATH" export GOPATH=/opt/go/ export PATH=$PATH:$GOPATH/bin apk del .build-deps go version </code></pre>
45,147,664
How to expose multiple port using a load balancer services in Kubernetes
<p>I have created a cluster using the google cloud platform (container engine) and deployed a pod using the following YAML file:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: extensions/v1beta1 kind: Deployment metadata: name: deployment-name spec: replicas: 1 template: metadata: name: pod-name labels: app: app-label spec: containers: - name: container-name image: gcr.io/project-id/image-name resources: requests: cpu: 1 ports: - name: port80 containerPort: 80 - name: port443 containerPort: 443 - name: port6001 containerPort: 6001 </code></pre> <p>Then I want to create a service that enables the pod to listen on all these ports. I know that the following YAML file works to create a service that listens on one port:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: Service metadata: name: service-name spec: ports: - port: 80 targetPort: 80 selector: app: app-label type: LoadBalancer </code></pre> <p>However when I want the pod to listen on multiple ports like this, it doesn't work:</p> <pre class="lang-yaml prettyprint-override"><code>apiVersion: v1 kind: Service metadata: name: service-name spec: ports: - port: 80 targetPort: 80 - port: 443 targetPort: 443 - port: 6001 targetPort: 6001 selector: app: app-label type: LoadBalancer </code></pre> <p>How can I make my pod listen to multiple ports?</p>
45,162,288
1
2
null
2017-07-17 15:07:00.03 UTC
5
2020-07-22 00:57:07.15 UTC
2020-07-22 00:57:07.15 UTC
null
2,989,261
null
8,289,824
null
1
36
kubernetes|google-cloud-platform|port|load-balancing
49,727
<p>You have two options:</p> <ol> <li>You could have multiple services, one for each port. As you pointed out, each service will end up with a different IP address</li> <li>You could have a single service with multiple ports. In this particular case, you must give all ports a name.</li> </ol> <p>In your case, the service becomes:</p> <pre><code>apiVersion: v1 kind: Service metadata: name: service-name spec: ports: - name: http port: 80 targetPort: 80 - name: https port: 443 targetPort: 443 - name: something port: 6001 targetPort: 6001 selector: app: app-label type: LoadBalancer </code></pre> <p>This is necessary so that endpoints can be disambiguated.</p>
896,274
Select multiple ids from a PostgreSQL sequence
<p>Is there a concise way to select the nextval for a PostgreSQL sequence multiple times in 1 query? This would be the only value being returned.</p> <p>For example, I would like to do something really short and sweet like:</p> <pre><code>SELECT NEXTVAL('mytable_seq', 3) AS id; </code></pre> <p>And get:</p> <pre><code> id ----- 118 119 120 (3 rows) </code></pre>
896,443
5
0
null
2009-05-22 03:47:32.683 UTC
3
2014-05-13 20:17:16.377 UTC
null
null
null
null
122
null
1
28
postgresql|select|nextval
14,943
<pre><code>select nextval('mytable_seq') from generate_series(1,3); </code></pre> <p>generate_series is a function which returns many rows with sequential numbers, configured by it's arguments. </p> <p>In above example, we don't care about the value in each row, we just use generate_series as row generator. And for each row we can call nextval. In this case it returns 3 numbers (nextvals).</p> <p>You can wrap this into function, but I'm not sure if it's really sensible given how short the query is.</p>
406,385
Handling unhandled exceptions problem
<p>I wanted to set some handler for all the unexpected exceptions that I might not have caught inside my code. In <code>Program.Main()</code> I used the following code:</p> <pre><code>AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ErrorHandler.HandleException); </code></pre> <p>But it didn't work as I expected. When I started the application in debugging mode and threw an exception it did call the handler, but afterwards the exception helper in Visual Studio popped up as if the exception occurred without any handling. I tried Application.Exit() inside the handler but it didn't work as well.</p> <p>What I would like to achieve is that the exception is handled with my handler and then the application closes nicely. Is there any other way to do it or am I using the code above in the wrong way?</p>
406,389
5
0
null
2009-01-02 09:42:49.153 UTC
21
2016-06-07 08:33:41.197 UTC
2009-01-02 09:56:51.123 UTC
David Schmitt
4,918
agnieszka
40,872
null
1
39
c#|exception
57,174
<p>It's because you're running it through Visual Studio in Debug mode. If you release and install your app somewhere else, nothing but your global exception handler will be processed.</p>
400,739
What does asterisk * mean in Python?
<p>Does * have a special meaning in Python as it does in C? I saw a function like this in the Python Cookbook:</p> <pre><code>def get(self, *a, **kw) </code></pre> <p>Would you please explain it to me or point out where I can find an answer (Google interprets the * as wild card character and thus I cannot find a satisfactory answer).</p>
400,753
5
2
null
2008-12-30 16:28:53.423 UTC
103
2019-12-07 14:57:43.997 UTC
2019-12-07 14:57:43.997 UTC
Jonathan Leffler
5,446,749
Martin
8,203
null
1
365
python
239,147
<p>See <a href="https://docs.python.org/2.7/reference/compound_stmts.html#function-definitions" rel="noreferrer">Function Definitions</a> in the Language Reference.</p> <blockquote> <p>If the form <code>*identifier</code> is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form <code>**identifier</code> is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.</p> </blockquote> <p>Also, see <a href="https://docs.python.org/2.7/reference/expressions.html#calls" rel="noreferrer">Function Calls</a>.</p> <p>Assuming that one knows what positional and keyword arguments are, here are some examples:</p> <p>Example 1:</p> <pre><code># Excess keyword argument (python 2) example: def foo(a, b, c, **args): print "a = %s" % (a,) print "b = %s" % (b,) print "c = %s" % (c,) print args foo(a="testa", d="excess", c="testc", b="testb", k="another_excess") </code></pre> <p>As you can see in the above example, we only have parameters <code>a, b, c</code> in the signature of the <code>foo</code> function. Since <code>d</code> and <code>k</code> are not present, they are put into the args dictionary. The output of the program is:</p> <pre><code>a = testa b = testb c = testc {'k': 'another_excess', 'd': 'excess'} </code></pre> <p>Example 2:</p> <pre><code># Excess positional argument (python 2) example: def foo(a, b, c, *args): print "a = %s" % (a,) print "b = %s" % (b,) print "c = %s" % (c,) print args foo("testa", "testb", "testc", "excess", "another_excess") </code></pre> <p>Here, since we're testing positional arguments, the excess ones have to be on the end, and <code>*args</code> packs them into a tuple, so the output of this program is:</p> <pre><code>a = testa b = testb c = testc ('excess', 'another_excess') </code></pre> <p>You can also unpack a dictionary or a tuple into arguments of a function:</p> <pre><code>def foo(a,b,c,**args): print "a=%s" % (a,) print "b=%s" % (b,) print "c=%s" % (c,) print "args=%s" % (args,) argdict = dict(a="testa", b="testb", c="testc", excessarg="string") foo(**argdict) </code></pre> <p>Prints:</p> <pre><code>a=testa b=testb c=testc args={'excessarg': 'string'} </code></pre> <p>And</p> <pre><code>def foo(a,b,c,*args): print "a=%s" % (a,) print "b=%s" % (b,) print "c=%s" % (c,) print "args=%s" % (args,) argtuple = ("testa","testb","testc","excess") foo(*argtuple) </code></pre> <p>Prints:</p> <pre><code>a=testa b=testb c=testc args=('excess',) </code></pre>
144,339
What would the best tool to create a natural DSL in Java?
<p>A couple of days ago, I read a blog entry (<a href="http://ayende.com/Blog/archive/2008/09/08/Implementing-generic-natural-language-DSL.aspx" rel="noreferrer">http://ayende.com/Blog/archive/2008/09/08/Implementing-generic-natural-language-DSL.aspx</a>) where the author discuss the idea of a generic natural language DSL parser using .NET.</p> <p>The brilliant part of his idea, in my opinion, is that the text is parsed and matched against classes using the same name as the sentences. </p> <p>Taking as an example, the following lines:</p> <pre> Create user user1 with email [email protected] and password test Log user1 in Take user1 to category t-shirts Make user1 add item Flower T-Shirt to cart Take user1 to checkout </pre> <p>Would get converted using a collection of "known" objects, that takes the result of parsing. Some example objects would be (using Java for my example):</p> <pre><code>public class CreateUser { private final String user; private String email; private String password; public CreateUser(String user) { this.user = user; } public void withEmail(String email) { this.email = email; } public String andPassword(String password) { this.password = password; } } </code></pre> <p>So, when processing the first sentence, CreateUser class would be a match (obviously because it's a concatenation of "create user") and, since it takes a parameter on the constructor, the parser would take "user1" as being the user parameter. </p> <p>After that, the parser would identify that the next part, "with email" also matches a method name, and since that method takes a parameter, it would parse "[email protected]" as being the email parameter. </p> <p>I think you get the idea by now, right? One quite clear application of that, at least for me, would be to allow application testers create "testing scripts" in natural language and then parse the sentences into classes that uses JUnit to check for app behaviors.</p> <p>I'd like to hear ideas, tips and opinions on tools or resource that could code such parser using Java. Better yet if we could avoid using complex lexers, or frameworks like ANTLR, which I think maybe would be using a hammer to kill a fly.</p> <p>More than that, if anyone is up to start an open source project for that, I would definitely be interested.</p>
144,374
6
2
null
2008-09-27 19:56:12.7 UTC
10
2020-01-31 14:40:44.337 UTC
2009-01-28 00:05:28.173 UTC
Fabian Steeg
18,154
null
14,540
null
1
17
java|dsl|nlp|parsing
12,811
<p>Considering the complexity of lexing and parsing, I don't know if I'd want to code all that by hand. <strong><a href="http://www.antlr.org/" rel="noreferrer">ANTLR</a> isn't that hard to pickup and I think it is worthing looking into based on your problem.</strong> If you use a parse grammar to build and abstract syntax tree from the input, its pretty easy to then process that AST with a tree grammar. The tree grammar could easily handle executing the process you described.</p> <p>You'll find ANTLR in many places including Eclipse, Groovy, and Grails for a start. <a href="https://rads.stackoverflow.com/amzn/click/com/0978739256" rel="noreferrer" rel="nofollow noreferrer">The Definitive ANTLR Reference</a> even makes it fairly straightforward to get up to speed on the basic fairly quickly.</p> <p>I had a project that had to handle some user generated query text earlier this year. I started down a path to manually process it, but it quickly became overwhelming. I took a couple days to get up the speed on ANTLR and had an initial version of my grammar and processor running in a few days. Subsequent changes and adjustments to the requirements would have killed any custom version, but required relatively little effort to adjust once I had the ANTLR grammars up and running.</p> <p>Good luck!</p>
32,266,864
Make C floating point literals float (rather than double)
<p>It is well known that in C, floating point literals (e.g. <code>1.23</code>) have type <code>double</code>. As a consequence, any calculation that involves them is promoted to double.</p> <p>I'm working on an embedded real-time system that has a floating point unit that supports only single precision (<code>float</code>) numbers. All my variables are <code>float</code>, and this precision is sufficient. I don't need (nor can afford) <code>double</code> at all. But every time something like</p> <pre><code>if (x &lt; 2.5) ... </code></pre> <p>is written, disaster happens: the slowdown can be up to two orders of magnitude. Of course, the direct answer is to write</p> <pre><code>if (x &lt; 2.5f) ... </code></pre> <p>but this is so easy to miss (and difficult to detect until too late), especially when a 'configuration' value is <code>#define</code>'d in a separate file by a less disciplined (or just new) developer.</p> <p>So, is there a way to force the compiler to treat all (floating point) literals as float, as if with suffix <code>f</code>? Even if it's against the specs, I don't care. Or any other solutions? The compiler is gcc, by the way.</p>
32,266,995
4
12
null
2015-08-28 08:42:37.623 UTC
15
2019-01-17 00:25:42.597 UTC
2015-08-28 09:28:13.033 UTC
null
1,983,495
null
3,513,925
null
1
81
c|gcc|floating-point|literals
14,992
<p><a href="http://gcc.gnu.org/wiki/FloatingPointMath"><code>-fsingle-precision-constant</code></a> flag can be used. It causes floating-point constants to be loaded in single precision even when this is not exact. </p> <p>Note- This will also use single precision constants in operations on double precision variables.</p>
16,773,583
Python: Extracting specific data with html parser
<p>I started using the HTMLParser in Python to extract data from a website. I get everything I wanted, except the text within two tags of HTML. Here is an example of the HTML tag:</p> <pre><code>&lt;a href="http://wold.livingsources.org/vocabulary/1" title="Swahili" class="Vocabulary"&gt;Swahili&lt;/a&gt; </code></pre> <p>There are also other tags starting with . They have other attributes and values and therefore I do not want to have their data:</p> <pre><code>&lt;a href="http://wold.livingsources.org/contributor#schadebergthilo" title="Thilo Schadeberg" class="Contributor"&gt;Thilo Schadeberg&lt;/a&gt; </code></pre> <p>The tag is an embedded tag within a table. I don't know if this makes any difference between other tags. I only want the information in some of the tags called 'a' with the attribute class="Vocabulary" and I want the data within the tag, in the example it would be "Swahili". So what I did is:</p> <pre><code>class AllLanguages(HTMLParser): ''' classdocs ''' #counter for the languages #countLanguages = 0 def __init__(self): HTMLParser.__init__(self) self.inLink = False self.dataArray = [] self.countLanguages = 0 self.lasttag = None self.lastname = None self.lastvalue = None #self.text = "" def handle_starttag(self, tag, attr): #print "Encountered a start tag:", tag if tag == 'a': for name, value in attr: if name == 'class' and value == 'Vocabulary': self.countLanguages += 1 self.inLink = True self.lasttag = tag #self.lastname = name #self.lastvalue = value print self.lasttag #print self.lastname #print self.lastvalue #return tag print self.countLanguages def handle_endtag(self, tag): if tag == "a": self.inlink = False #print "".join(self.data) def handle_data(self, data): if self.lasttag == 'a' and self.inLink and data.strip(): #self.dataArray.append(data) # print data </code></pre> <p>The programm prints every data which is included in an tag, but I only want the one included in the tag with the right attributes. How do I get this specific data?</p>
16,773,765
2
0
null
2013-05-27 12:49:04.577 UTC
2
2015-09-09 20:40:11.457 UTC
2014-04-28 09:30:31.197 UTC
null
755,319
null
2,424,963
null
1
3
python|html|python-2.7|html-parsing|html-parser
38,193
<p>Looks like you forgot to set <code>self.inLink = False</code> in <code>handle_starttag</code> by default:</p> <pre><code>from HTMLParser import HTMLParser class AllLanguages(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.inLink = False self.dataArray = [] self.countLanguages = 0 self.lasttag = None self.lastname = None self.lastvalue = None def handle_starttag(self, tag, attrs): self.inLink = False if tag == 'a': for name, value in attrs: if name == 'class' and value == 'Vocabulary': self.countLanguages += 1 self.inLink = True self.lasttag = tag def handle_endtag(self, tag): if tag == "a": self.inlink = False def handle_data(self, data): if self.lasttag == 'a' and self.inLink and data.strip(): print data parser = AllLanguages() parser.feed(""" &lt;html&gt; &lt;head&gt;&lt;title&gt;Test&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;a href="http://wold.livingsources.org/vocabulary/1" title="Swahili" class="Vocabulary"&gt;Swahili&lt;/a&gt; &lt;a href="http://wold.livingsources.org/contributor#schadebergthilo" title="Thilo Schadeberg" class="Contributor"&gt;Thilo Schadeberg&lt;/a&gt; &lt;a href="http://wold.livingsources.org/vocabulary/2" title="English" class="Vocabulary"&gt;English&lt;/a&gt; &lt;a href="http://wold.livingsources.org/vocabulary/2" title="Russian" class="Vocabulary"&gt;Russian&lt;/a&gt; &lt;/body&gt; &lt;/html&gt;""") </code></pre> <p>prints:</p> <pre><code>Swahili English Russian </code></pre> <p>Also, take a look at:</p> <ul> <li><a href="https://scrapy.readthedocs.org/en/latest/" rel="noreferrer">scrapy</a></li> <li><a href="http://lxml.de/" rel="noreferrer">lxml</a></li> <li><a href="https://pypi.python.org/pypi/BeautifulSoup/" rel="noreferrer">beautifulsoup</a></li> </ul> <p>Hope that helps.</p>
2,180,842
Unable to create index because of duplicate that doesn't exist?
<p>I'm getting an error running the following Transact-SQL command:</p> <pre><code>CREATE UNIQUE NONCLUSTERED INDEX IX_TopicShortName ON DimMeasureTopic(TopicShortName) </code></pre> <p>The error is:</p> <blockquote> <p>Msg 1505, Level 16, State 1, Line 1 The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.DimMeasureTopic' and the index name 'IX_TopicShortName'. The duplicate key value is ().</p> </blockquote> <p>When I run <code>SELECT * FROM sys.indexes WHERE name = 'IX_TopicShortName'</code> or <code>SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[DimMeasureTopic]')</code> the IX_TopicShortName index does not display. So there doesn't appear to be a duplicate.</p> <p>I have the same schema in another database and can create the index without issues there. Any ideas why it won't create here?</p>
2,180,857
5
1
null
2010-02-01 23:28:33.343 UTC
6
2019-06-19 17:30:35.64 UTC
2010-05-02 15:42:50.42 UTC
null
164,901
null
6,651
null
1
57
sql-server-2005|tsql|indexing|unique-index
70,692
<p>It's not that the index already exists, but that there are duplicate values of the <code>TopicShortName</code> field in the table itself. According to the error message the duplicate value is an empty string (it might just be a facet of posting I guess). Such duplicates prevent the creation of a <code>UNIQUE</code> index.</p> <p>You could run a query to confirm that you have a duplicate:</p> <pre><code>SELECT TopicShortName, COUNT(*) FROM DimMeasureTopic GROUP BY TopicShortName HAVING COUNT(*) &gt; 1 </code></pre> <p>Presumably in the other database the data are different, and the duplicates are not present.</p>
1,371,608
C++ pointer to class
<p>Can anyone tell me what the difference is between:</p> <pre><code>Display *disp = new Display(); </code></pre> <p>and</p> <pre><code>Display *disp; disp = new Display(); </code></pre> <p>and</p> <pre><code>Display* disp = new Display(); </code></pre> <p>and</p> <pre><code>Display* disp(new Display()); </code></pre>
1,371,629
6
3
null
2009-09-03 05:51:18.26 UTC
16
2015-07-02 16:19:54.927 UTC
2015-04-16 00:45:41.327 UTC
null
845,704
null
122,238
null
1
26
c++|initialization
61,788
<p>The first case:</p> <pre><code>Display *disp = new Display(); </code></pre> <p>Does three things:</p> <ol> <li>It creates a new variable <code>disp</code>, with the type <code>Display*</code>, that is, a pointer to an object of type <code>Display</code>, and then</li> <li>It allocates a new <code>Display</code> object on the heap, and</li> <li>It sets the <code>disp</code> variable to point to the new <code>Display</code> object.</li> </ol> <p>In the second case:</p> <pre><code>Display *disp; disp = new GzDisplay(); </code></pre> <p>You create a variable <code>disp</code> with type <code>Display*</code>, and then create an object of <em>a different type</em>, <code>GzDisplay</code>, on the heap, and assign its pointer to the <code>disp</code> variable.</p> <p>This will only work if GzDisplay is a subclass of Display. In this case, it looks like an example of <a href="http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming#C.2B.2B" rel="noreferrer">polymorphism</a>.</p> <p>Also, to address your comment, there is no difference between the declarations:</p> <pre><code>Display* disp; </code></pre> <p>and</p> <pre><code>Display *disp; </code></pre> <p>However, because of the way C type rules work, there is a difference between:</p> <pre><code>Display *disp1; Display* disp2; </code></pre> <p>and</p> <pre><code>Display *disp1, disp2; </code></pre> <p>Because in that last case <code>disp1</code> is a <em>pointer</em> to a <code>Display</code> object, probably allocated on the heap, while <code>disp2</code> is an actual object, probably allocated on the stack. That is, while the pointer is arguably part of the type, the parser will associate it with the variable instead.</p>
1,882,334
In Functional Programming, is it considered a bad practice to have incomplete pattern matchings
<p>Is it generally considered a bad practice to use non-exhaustive pattern machings in functional languages like Haskell or F#, which means that the cases specified don't cover all possible input cases?</p> <p>In particular, should I allow code to fail with a <code>MatchFailureException</code> etc. or should I always cover all cases and explicitly throw an error if necessary?</p> <p>Example:</p> <pre><code>let head (x::xs) = x </code></pre> <p>Or</p> <pre><code>let head list = match list with | x::xs -&gt; x | _ -&gt; failwith "Applying head to an empty list" </code></pre> <p>F# (unlike Haskell) gives a warning for the first code, since the <code>[]</code>-case is not covered, but can I ignore it without breaking functional style conventions for the sake of succinctness? A MatchFailure does state the problem quite well after all ...</p>
1,882,367
6
4
null
2009-12-10 16:49:18.133 UTC
6
2012-03-15 15:13:37.813 UTC
null
null
null
null
105,459
null
1
32
haskell|f#|functional-programming
2,606
<p>If you complete your pattern-matchings with a constructor <code>[]</code> and not the catch-all <code>_</code>, the compiler will have a chance to tell you to look again at the function with a warning the day someone adds a third constructor to lists.</p> <p>My colleagues and I, working on a large OCaml project (200,000+ lines), force ourselves to avoid partial pattern-matching warnings (even if that means writing <code>| ... -&gt; assert false</code> from time to time) and to avoid so-called "<a href="http://caml.inria.fr/mantis/view.php?id=4073" rel="noreferrer">fragile pattern-matchings</a>" (pattern matchings written in such a way that the addition of a constructor may not be detected) too. We consider that the maintainability benefits.</p>
1,733,281
Where is the implementation of strlen() in GCC?
<p>Can anyone point me to the definition of <code>strlen()</code> in GCC? I've been grepping release 4.4.2 for about a half hour now (while Googling like crazy) and I can't seem to find where <code>strlen()</code> is actually implemented.</p>
1,733,289
10
0
null
2009-11-14 04:33:15.067 UTC
6
2018-05-06 12:06:06.447 UTC
2018-05-06 11:37:26.04 UTC
null
895,245
null
77,047
null
1
27
c|glibc|strlen
63,214
<p>You should be looking in glibc, not GCC -- it seems to be defined in <code>strlen.c</code> -- here's a link to <a href="http://www.stdlib.net/~colmmacc/strlen.c.html" rel="noreferrer">strlen.c for glibc version 2.7</a>... And here is a link to the <a href="http://cvs.savannah.gnu.org/viewvc/libc/string/strlen.c?root=libc&amp;view=log" rel="noreferrer">glibc SVN repository online for strlen.c</a>.</p> <p>The reason you should be looking at <a href="http://www.gnu.org/software/libc/" rel="noreferrer">glibc</a> and not gcc is:</p> <blockquote> <p>The GNU C library is used as <em>the</em> C library in the GNU system and most systems with the Linux kernel.</p> </blockquote>
2,138,972
iPhone In App Purchase - response.products are still empty?
<p>Basically, I've tried to set up in app purchases on a test app before I implement them into a proper app that my company is working on. I've read the Store kit pdf and other snippets about a 1000 times, but the products are still being returned as empty. Here's exactly what I've done so far:</p> <p><strong>Setup test app and In App Purchase test items</strong><br> I created a new app id for 'Test App One' on my company's developer portal in the iPhone Dev Centre. I made sure that the prefix was <code>com.mycompany.testappone</code> to ensure that in app purchases could be configured. Staying in the App IDs section, I configured in app purchases by ticking the 'Enable In App Purchase' option.</p> <p>I created 'Test App One' in iTunes Connect and completed the usual procedure but selected 'upload binary later' and didn't submit for review as the app does nothing. Surely we don't have to submit the app to review for this to work?! I then clicked on manage in app purchases and created a new one with product id 'test1' and approved it so that it is cleared for sale.</p> <p><strong>Code</strong><br> I set up a new project in XCode called <code>TestAppOne</code> and here are the only 2 classes I am using for now:</p> <p>TestAppOneAppDelegate.h: </p> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import &lt;StoreKit/StoreKit.h&gt; @interface TestAppOneAppDelegate : NSObject &lt;UIApplicationDelegate, SKRequestDelegate, SKProductsRequestDelegate&gt; { UIWindow *window; } </code></pre> <p>TestAppOneDelegate.m:</p> <pre><code>#import "TestAppOneAppDelegate.h" static NSString *kMyFeatureIdentifier1 = @"com.mycompany.testappone.test1"; @implementation TestAppOneAppDelegate @synthesize window; - (void)applicationDidFinishLaunching:(UIApplication *)application { if([SKPaymentQueue canMakePayments]) { NSLog(@"IN-APP:can make payments"); } else { NSLog(@"IN-APP:can't make payments"); } [self requestProductData]; [window makeKeyAndVisible]; } - (void)requestProductData { NSLog(@"IN-APP:requestProductData"); SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers: [NSSet setWithObject:kMyFeatureIdentifier1]]; request.delegate = self; [request start]; NSLog(@"IN-APP:requestProductData END"); } - (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response { NSLog(@"IN-APP:productsRequest"); NSArray *myProduct = response.products; NSLog(@"IN-APP:array count: %i", [myProduct count]); [request autorelease]; NSLog(@"IN-APP:productsRequest END"); } - (void)dealloc { [window release]; [super dealloc]; } @end </code></pre> <p><strong>Testing on the device</strong><br> I created a sandbox test account and logged out of my iTunes account on the iPhone, but didn't log in with the test account as the documentation tells us to not do this until we are prompted at the purchasing stage. I then build the app and here is the log I'm getting:</p> <pre><code>IN-APP:can make payments IN-APP:requestProductData IN-APP:requestProductData END IN-APP:productsRequest IN-APP:array count: 0 IN-APP:productsRequest END </code></pre> <p>Can anyone please tell me if I have left any stages out or if there is anything that I'm doing wrong. Unfortunately there doesn't seem to be any example apps made by Apple.</p>
2,138,987
10
0
null
2010-01-26 11:15:34.913 UTC
15
2020-11-13 14:27:18.64 UTC
2015-12-14 07:29:30.12 UTC
null
331,508
null
218,485
null
1
46
iphone|iphone-sdk-3.0|in-app-purchase|storekit
25,476
<p>Actually I do think you have to submit the binary for this to work.</p> <p>You can set the release date to the distant future.</p>
1,635,136
how to set default main class in java?
<p>I have 2 classes within same package. Both classes have main method in them. Now I want to build a jar file. I want to build 2 jar files which use different main functions as default main.</p> <p>eg </p> <pre><code>class A { public static void main(String args[]) { //do something } } class B { public static void main(String args[]) { //do something } } </code></pre> <p>How do I do it in NetBeans IDE?</p> <p>I found the answer. U can do it easily in netbeans: 1)right click on project >properties > run > select the class frm and drop down list. So simple in netbeans. Netbeans rocks!</p>
1,635,168
11
3
null
2009-10-28 04:05:14.84 UTC
5
2022-01-25 19:55:28.72 UTC
2018-01-16 14:48:45.807 UTC
null
436,560
null
189,352
null
1
27
java|netbeans
203,142
<p>In the jar file you could just add this to your manifest.mft</p> <pre><code>Main-Class : A </code></pre> <p>The jar file would then be executable and would call the correct main.</p> <p>On how to do this in Netbeans you can look at this: <a href="https://stackoverflow.com/questions/602537/producing-executable-jar-in-netbeans">Producing executable jar in NetBeans</a></p>
1,700,870
How do I do OuterHTML in firefox?
<p>Part of my code I get the OuterHTML propery</p> <pre><code>"&lt;LI onclick="TabClicked(this, 'SearchName', 'TabGroup1');"&gt;Name " </code></pre> <p>so I can do stuff involing parsing it.</p> <p>There is no OuterHTML property in javascript on firefox though and I can't find an alternative way to get this string. Ideas?</p>
1,701,158
11
6
null
2009-11-09 13:04:36.61 UTC
16
2013-04-28 14:06:43.77 UTC
2010-08-26 22:15:59.16 UTC
null
65,977
null
174,375
null
1
37
javascript|dom|cross-browser
33,658
<p>Figured it out!</p> <pre><code>child.getAttributeNode("OnClick").nodeValue; </code></pre> <p>getAttribute didn't work, but getAttributeNode worked great ;D</p>
1,995,615
How can I format a decimal to always show 2 decimal places?
<p>I want to display:</p> <p><code>49</code> as <code>49.00</code></p> <p>and:</p> <p><code>54.9</code> as <code>54.90</code></p> <p>Regardless of the length of the decimal or whether there are are any decimal places, I would like to display a <code>Decimal</code> with 2 decimal places, and I'd like to do it in an efficient way. The purpose is to display money values.</p> <p>eg, <code>4898489.00</code></p> <hr /> <p><sub>For the analogous issue with the built-in <code>float</code> type, see <a href="https://stackoverflow.com/questions/455612">Limiting floats to two decimal points</a>.</sub></p>
1,995,846
13
2
null
2010-01-03 17:30:44.403 UTC
66
2022-09-23 14:00:32.94 UTC
2022-09-23 14:00:32.94 UTC
null
523,612
null
128,463
null
1
326
python|string-formatting
636,253
<p>I suppose you're probably using the <a href="https://docs.python.org/2/library/decimal.html#decimal-objects" rel="noreferrer" title="Decimal objects"><code>Decimal()</code></a> objects from the <a href="https://docs.python.org/2/library/decimal.html" rel="noreferrer" title="decimal — Decimal fixed point and floating point arithmetic"><code>decimal</code></a> module? (If you need exactly two digits of precision beyond the decimal point with arbitrarily large numbers, you definitely should be, and that's what your question's title suggests...)</p> <p>If so, the <a href="https://docs.python.org/2/library/decimal.html#decimal-faq" rel="noreferrer" title="Decimal FAQ"><em>Decimal FAQ</em></a> section of the docs has a question/answer pair which may be useful for you:</p> <blockquote> <p>Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?</p> <p>A. The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:</p> </blockquote> <pre><code>&gt;&gt;&gt; TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01') &gt;&gt;&gt; # Round to two places &gt;&gt;&gt; Decimal('3.214').quantize(TWOPLACES) Decimal('3.21') &gt;&gt;&gt; # Validate that a number does not exceed two places &gt;&gt;&gt; Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact])) Decimal('3.21') &gt;&gt;&gt; Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact])) Traceback (most recent call last): ... Inexact: None </code></pre> <p>The next question reads</p> <blockquote> <p>Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application?</p> </blockquote> <p>If you need the answer to that (along with lots of other useful information), see <a href="https://docs.python.org/2/library/decimal.html#decimal-objects" rel="noreferrer" title="Decimal objects"><em>the aforementioned section of the docs</em></a>. Also, if you keep your <code>Decimal</code>s with two digits of precision beyond the decimal point (meaning as much precision as is necessary to keep all digits to the left of the decimal point and two to the right of it and no more...), then converting them to strings with <code>str</code> will work fine:</p> <pre><code>str(Decimal('10')) # -&gt; '10' str(Decimal('10.00')) # -&gt; '10.00' str(Decimal('10.000')) # -&gt; '10.000' </code></pre>
1,524,244
Tool for drawing timing diagrams
<p>Recently I am working with a hardware design group developing an <a href="https://en.wikipedia.org/wiki/Application-specific_integrated_circuit" rel="noreferrer">ASIC</a>. And I am drawing a lot of timing diagrams for which I am using Microsoft Excel, as it is easy to import into Word document. But, things are getting more and more difficult with Excel.</p> <p>What can be used to draw timing diagrams? Is there any easy tool out there?</p>
1,525,498
14
0
null
2009-10-06 08:14:36.117 UTC
19
2022-03-16 22:29:18.44 UTC
2013-07-22 21:23:28.447 UTC
null
63,550
null
70,702
null
1
33
hardware|verilog|asic|timing-diagram
46,223
<p>I have the same problem and tried the following tools:</p> <ul> <li>drawtiming</li> <li>timing (<a href="http://en.wikipedia.org/wiki/LaTeX" rel="noreferrer">LaTeX</a>)</li> <li>tikz-timing (LaTeX)</li> <li><a href="http://en.wikipedia.org/wiki/Microsoft_Visio" rel="noreferrer">Microsoft Visio</a></li> </ul> <p>After trying all these I now ended up using Visio and pen&amp;pencil. All other programs lacked support for adding arrows/relationships between signals easily. In Visio, such things are absolutely easy. And you can export the diagrams directly to <a href="http://en.wikipedia.org/wiki/Microsoft_PowerPoint" rel="noreferrer">PowerPoint</a> or even as <a href="http://en.wikipedia.org/wiki/Portable_Document_Format" rel="noreferrer">PDF</a> for using them in LaTeX.</p>
1,595,848
Configuring Git over SSH to login once
<p>I have cloned my git repository over ssh. So, each time I communicate with the origin master by pushing or pulling, I have to reenter my password. How can I configure git so that I do not need to enter my password multiple times?</p>
1,595,863
14
2
null
2009-10-20 16:27:27.25 UTC
116
2021-06-30 08:53:59.01 UTC
2015-01-29 15:36:07.54 UTC
null
3,481,266
null
130,224
null
1
216
git|ssh|ssh-keys
347,596
<h3>Try <code>ssh-add</code>, you need <code>ssh-agent</code> to be running and holding your private key</h3> <p>(Ok, responding to the updated question, you first run <code>ssh-keygen</code> to generate a public and private key as <a href="https://stackoverflow.com/users/119963/jefromi">Jefromi</a> <a href="https://stackoverflow.com/a/1595858/450913">explained</a>. You put the public key on the server. You should use a passphrase, if you don't you have the equivalent of a plain-text password in your private key. But when you do, then you need as a practical matter <code>ssh-agent</code> as explained below.)</p> <p>You want to be running <code>ssh-agent</code> in the background as you log in. Once you log in, the idea is to run <code>ssh-add</code> once and only once, in order to give the agent your passphrase, to decode your key. The agent then just sits in memory with your key unlocked and loaded, ready to use every time you ssh somewhere. </p> <p>All ssh-family commands<sup>1</sup> will then consult the agent and automatically be able to use your private key.</p> <p>On OSX (err, <em>macOS</em>), GNOME and KDE systems, <code>ssh-agent</code> is usually launched automatically for you. I will go through the details in case, like me, you also have a Cygwin or other windows environment where this most certainly is not done for you.</p> <p>Start here: <code>man ssh-agent</code>.</p> <p>There are various ways to automatically run the agent. As the man page explains, you can run it so that it is a parent of all your login session's other processes. That way, the environment variables it provides will automatically be in all your shells. When you (later) invoke <code>ssh-add</code> or <code>ssh</code> both will have access to the agent because they all have the environment variables with magic socket pathnames or whatever.</p> <p>Alternatively, you can run the agent as an ordinary child, save the environment settings in a file, and source that file in every shell when it starts.</p> <p>My OSX and Ubuntu systems automatically do the agent launch setup, so all I have to do is run <code>ssh-add</code> once. Try running <code>ssh-add</code> and see if it works, if so, then you just need to do that once per reboot. </p> <p>My Cygwin system needed it done manually, so I did this in my <code>.profile</code> and I have <code>.bashrc</code> source <code>.profile</code>:</p> <pre><code>. .agent &gt; /dev/null ps -p $SSH_AGENT_PID | grep ssh-agent &gt; /dev/null || { ssh-agent &gt; .agent . .agent &gt; /dev/null } </code></pre> <p>The <code>.agent</code> file is created automatically by the script; it contains the environment variables definitions and exports. The above tries to source the .agent file, and then tries to <code>ps(1)</code> the agent. If it doesn't work it starts an agent and creates a new agent file. You can also just run <code>ssh-add</code> and if it fails start an agent. <hr> <sup>1. And even local and remote <code>sudo</code> with the right pam extension.</sup></p>
1,453,952
Most useful Python modules from the standard library?
<p>I am teaching a graduate level Python class at the University of Paris, and the students need to be introduced to the standard library. I want to discuss with them about some of the most important standard modules.</p> <p>What modules do you think are absolute musts? Even though responses probably vary depending on your field (web programming, science, etc.), I feel that some modules are commonly needed: <code>math</code>, <code>sys</code>, <code>re</code>, <code>os</code>, <code>os.path</code>, <code>logging</code>,… and maybe: <code>collections</code>, <code>struct</code>,…</p> <p>What modules would you suggest I present, in a 1 or 2 hour slot?</p>
1,454,779
16
9
null
2009-09-21 10:52:52.367 UTC
57
2011-12-09 18:26:42.663 UTC
2011-12-09 18:26:42.663 UTC
null
3,043
null
42,973
null
1
55
python|module|standard-library
24,180
<p>Modules to cover in a 1-2 hour slot entirely depend on your audience's interest or focus. What other classes are they taking? What are they prepared to make use of immediately?</p> <p>Be sure to mention <code>math</code>, <code>decimal</code> and <code>datetime</code> and <code>time</code> and <code>re</code>.</p> <p>For IT-types who will be doing file-oriented work: <code>glob</code>, <code>fnmatch</code>, <code>os</code>, <code>os.path</code>, <code>tempfile</code>, and <code>shutil</code>.</p> <p>Database folks must hear about <code>sqlite</code> and <code>json</code>.</p> <p>Simulation audience may want to hear about <code>random</code>.</p> <p>Web developers must hear about <code>urllib2</code> from a client point of view. Also Beautiful Soup and an XML parser of your choice.</p> <p>Web developers must hear about <code>logging</code> and <code>wsgiref</code> from a server point of view.</p>
33,943,477
import Swift vs import Foundation
<p><strong>Question</strong></p> <p>What is the difference between <code>import Swift</code> and <code>import Foundation</code>?</p> <p>Until I read <a href="https://stackoverflow.com/questions/33942483/swift-extension-example/33942484?noredirect=1#comment55644674_33942484">this comment</a> by <a href="https://stackoverflow.com/users/1187415/martin-r">Martin R</a>, I didn't even know that there was an <code>import Swift</code>.</p> <p><strong>Reading</strong></p> <p>I couldn't find the documentation and doing a Google search didn't turn up much. </p> <p><strong>What I tried</strong></p> <p>Testing it out shows that <code>import Swift</code> does not give any compile errors, but that doesn't really answer my question.</p> <p>If I were to guess, I would say that you import Swift for Swift projects and that you import Foundation for Objective-C projects or maybe for Swift projects that use Objective-C classes (like <code>NSString</code>).</p> <p>Testing this in the Playground:</p> <pre><code>import Foundation import Swift var str = "Hello, playground" let str2: NSString = "hello" let str3: String = "hello" </code></pre> <p>Commenting out <code>import Swift</code> gives no errors and <code>str</code> is of <code>String</code> type. However, commenting out <code>import Foundation</code> gives an "undeclared type" error for <code>NSString</code>. </p> <p><strong>My question revisited</strong></p> <p>I would be happy enough to abandon Foundation and just use Swift. So am I right to just import Swift all the time unless I specifically need to use one of the old Objective-C classes?</p>
33,949,267
3
3
null
2015-11-26 16:39:42.893 UTC
5
2019-06-17 11:08:41.783 UTC
2017-05-23 12:17:26.197 UTC
null
-1
null
3,681,880
null
1
45
ios|objective-c|swift|import|foundation
33,246
<p>Yes, you will only need <code>import Foundation</code> if you want to access NSObject or one of its subclasses. Foundation is the framework that brings in that class hierarchy. However, it's highly likely that in a project you'll need more than just <code>import Swift</code>. Like Rob commented, <code>import UIKit</code> is also a nice option.</p> <p>In case you haven't read it already, Apple explains the Foundation framework <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/ObjC_classic/index.html#//apple_ref/doc/uid/20001091" rel="noreferrer">here</a>.</p>
17,879,533
How to center a UICollectionView when it is tapped?
<p>I have a <code>UICollectionView</code> and it has quite a lot of <code>UICollectionViewCells</code> on it. I want to scroll the cell to the centre of the <code>UICollectionView</code> when it is tapped. My concern is that even if I tap the last or the top cell it should move to the centre of the collection view.</p> <p>I have tried setting the <code>contentInsets</code> and offsets but they don't seem to work. I think I will have to change the content size on selection and change it back to original when the scrolling begins.</p>
17,880,074
5
1
null
2013-07-26 10:54:40.697 UTC
9
2022-03-07 14:00:55.513 UTC
2015-05-03 15:20:42.907 UTC
null
1,135,714
null
919,545
null
1
14
ios|objective-c|uiscrollview|uicollectionview
21,704
<p>Setting contentInsets should give some extra space around first and last cells:</p> <pre><code>CGFloat collectionViewHeight = CGRectGetHeight(collectionView.bounds); [collectionView setContentInset: UIEdgeInsetsMake(collectionViewHeight/2, 0, collectionViewHeight/2, 0) ]; // nb, those are top-left-bottom-right </code></pre> <p>After you should call:</p> <pre><code>[collectionView scrollToItemAtIndexPath:selectedItemPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:YES]; </code></pre> <p>It's important to pass correct scroll position: UICollectionViewScrollPositionCenteredVertically</p> <p>This should center tapped item properly.</p> <p><strong>EDIT</strong></p> <p>It's really strange, but after setting UIEdgeInsets to collection view method scrollToItemAtIndexPath does not works properly, so i make some modification:</p> <pre><code>- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath { CGFloat collectionViewHeight = CGRectGetHeight(self.collectionView.frame); [collectionView setContentInset:UIEdgeInsetsMake(collectionViewHeight / 2, 0, collectionViewHeight / 2, 0)]; UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath]; CGPoint offset = CGPointMake(0, cell.center.y - collectionViewHeight / 2); [collectionView setContentOffset:offset animated:YES]; } </code></pre> <p>it works fine for me.</p>
44,785,540
EF Core add-migration Build Failed
<p>I have a developer that is getting "Build failed." when running add-migration in a .NET Core EF project, with no explanation of why the build failed. How do you troubleshoot this error?</p> <p>This is what he gets in the Package Manager Console:<a href="https://i.stack.imgur.com/xbKFA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xbKFA.png" alt="enter image description here"></a></p> <p><strong>Additional information</strong>:</p> <p>We have a few other developers using the same solution code (myself included) that have not issues with add-migration.</p> <p>This is what I see in Package Manager Console:<a href="https://i.stack.imgur.com/xZiQ8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xZiQ8.png" alt="enter image description here"></a></p> <p>We've verified that the project builds, and the entire solution builds. We've done "dotnet restore" and rebuild all multiple times, in addition to restarting VS2015. We've verified that the correct default solution is selected both in Solution Explorer, and in the Package Manager Console drop-down. We've verified that he has the correct SDK installed on his machine. I'm at a loss as to what to check next...any time I've had a failure during add-migration I've gotten enough information to point me in the direction of what to check, but just "Build failed." is a fairly useless error output.</p>
44,790,365
37
8
null
2017-06-27 16:33:52.843 UTC
16
2022-09-13 08:00:49.887 UTC
2020-04-09 00:47:53.153 UTC
null
114,029
null
1,585,652
null
1
96
.net|entity-framework|asp.net-core|.net-core|entity-framework-migrations
180,368
<p>The developer ended up un-mapping the project from TFS, deleting it, and re-mapping it. It's now working for him.</p>
6,390,695
javascript check if regex apply
<p>First of all, here is my code snippet:</p> <pre><code>var str = '&lt;!--:de--&gt;some german text&lt;!--:--&gt;&lt;!--:en--&gt;some english text&lt;!--:--&gt;'; var match = str.match(/de--&gt;([^&lt;]+).+?en[^&gt;]+&gt;([^&lt;]+)/i); var textInDe = match[1]; var textInEn = match[2]; </code></pre> <p>I've got this regex validation (thanks to The Mask) which works great.</p> <p>Now, I want to check with an if-statement if this regex applies to some string or not. I'm using Javascript jquery.</p> <p>Thanks in advance :)</p>
6,390,718
3
0
null
2011-06-17 19:16:13.7 UTC
4
2012-11-12 14:05:20.28 UTC
2011-06-17 19:46:15.47 UTC
null
767,442
null
787,999
null
1
20
javascript|jquery|regex
61,344
<p>You can use <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp/test" rel="noreferrer">RegExp.test</a></p> <pre><code>if(/de--&gt;([^&lt;]+).+?en[^&gt;]+&gt;([^&lt;]+)/i.test(str)) { // something } </code></pre>
6,819,173
Strip all but first 5 characters - Python
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/663171/is-there-a-way-to-substring-a-string-in-python">Is there a way to substring a string in Python?</a> </p> </blockquote> <p>I have a string in the form 'AAAH8192375948'. How do I keep the first 5 characters of this string, and strip all the rest? Is it in the form l.strip with a negative integer? Thanks. </p>
6,819,197
3
1
null
2011-07-25 16:15:49.213 UTC
2
2012-05-10 01:47:45.183 UTC
2017-05-23 10:30:08.663 UTC
null
-1
null
851,620
null
1
26
python
79,035
<p>A string in Python is a <a href="http://docs.python.org/library/stdtypes.html#mutable-sequence-types" rel="noreferrer">sequence type</a>, like a list or a tuple. Simply grab the first 5 characters:</p> <pre><code> some_var = 'AAAH8192375948'[:5] print some_var # AAAH8 </code></pre> <p>The slice notation is <code>[start:end:increment]</code> -- numbers are optional if you want to use the defaults (start defaults to 0, end to len(my_sequence) and increment to 1). So:</p> <pre><code> sequence = [1,2,3,4,5,6,7,8,9,10] # range(1,11) sequence[0:5:1] == sequence[0:5] == sequence[:5] # [1, 2, 3, 4, 5] sequence[1:len(sequence):1] == sequence[1:len(sequence)] == sequence[1:] # [2, 3, 4, 5, 6, 7, 8, 9, 10] sequence[0:len(sequence):2] == sequence[:len(sequence):2] == sequence[::2] # [1, 3, 5, 7, 9] </code></pre> <p><a href="http://docs.python.org/library/stdtypes.html#str.strip" rel="noreferrer"><code>strip</code></a> removes a character or set of characters from the beginning and end of the string - entering a negative number simply means that you are attempting to remove the string representation of that negative number from the string.</p>
40,018,398
list() uses slightly more memory than list comprehension
<p>So i was playing with <code>list</code> objects and found little strange thing that if <code>list</code> is created with <code>list()</code> it uses more memory, than list comprehension? I'm using Python 3.5.2</p> <pre><code>In [1]: import sys In [2]: a = list(range(100)) In [3]: sys.getsizeof(a) Out[3]: 1008 In [4]: b = [i for i in range(100)] In [5]: sys.getsizeof(b) Out[5]: 912 In [6]: type(a) == type(b) Out[6]: True In [7]: a == b Out[7]: True In [8]: sys.getsizeof(list(b)) Out[8]: 1008 </code></pre> <p>From the <a href="https://docs.python.org/3.5/library/stdtypes.html#list">docs</a>:</p> <blockquote> <p>Lists may be constructed in several ways:</p> <ul> <li>Using a pair of square brackets to denote the empty list: <code>[]</code></li> <li>Using square brackets, separating items with commas: <code>[a]</code>, <code>[a, b, c]</code></li> <li>Using a list comprehension: <code>[x for x in iterable]</code></li> <li>Using the type constructor: <code>list()</code> or <code>list(iterable)</code></li> </ul> </blockquote> <p>But it seems that using <code>list()</code> it uses more memory.</p> <p>And as much <code>list</code> is bigger, the gap increases.</p> <p><a href="https://i.stack.imgur.com/VVHJL.png"><img src="https://i.stack.imgur.com/VVHJL.png" alt="Difference in memory"></a></p> <p>Why this happens?</p> <p><strong>UPDATE #1</strong></p> <p>Test with Python 3.6.0b2:</p> <pre><code>Python 3.6.0b2 (default, Oct 11 2016, 11:52:53) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getsizeof(list(range(100))) 1008 &gt;&gt;&gt; sys.getsizeof([i for i in range(100)]) 912 </code></pre> <p><strong>UPDATE #2</strong></p> <p>Test with Python 2.7.12:</p> <pre><code>Python 2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.getsizeof(list(xrange(100))) 1016 &gt;&gt;&gt; sys.getsizeof([i for i in xrange(100)]) 920 </code></pre>
40,018,719
2
5
null
2016-10-13 10:25:25.57 UTC
19
2019-09-28 05:32:50.03 UTC
2019-09-28 05:32:50.03 UTC
null
202,229
null
3,124,746
null
1
81
python|list|list-comprehension|cpython|python-internals
4,724
<p>I think you're seeing over-allocation patterns this is a <a href="https://github.com/python/cpython/blob/3.5/Objects/listobject.c#L42" rel="noreferrer">sample from the source</a>:</p> <pre class="lang-c prettyprint-override"><code>/* This over-allocates proportional to the list size, making room * for additional growth. The over-allocation is mild, but is * enough to give linear-time amortized behavior over a long * sequence of appends() in the presence of a poorly-performing * system realloc(). * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ... */ new_allocated = (newsize &gt;&gt; 3) + (newsize &lt; 9 ? 3 : 6); </code></pre> <hr> <p>Printing the sizes of list comprehensions of lengths 0-88 you can see the pattern matches:</p> <pre class="lang-py prettyprint-override"><code># create comprehensions for sizes 0-88 comprehensions = [sys.getsizeof([1 for _ in range(l)]) for l in range(90)] # only take those that resulted in growth compared to previous length steps = zip(comprehensions, comprehensions[1:]) growths = [x for x in list(enumerate(steps)) if x[1][0] != x[1][1]] # print the results: for growth in growths: print(growth) </code></pre> <p>Results (format is <code>(list length, (old total size, new total size))</code>):</p> <pre><code>(0, (64, 96)) (4, (96, 128)) (8, (128, 192)) (16, (192, 264)) (25, (264, 344)) (35, (344, 432)) (46, (432, 528)) (58, (528, 640)) (72, (640, 768)) (88, (768, 912)) </code></pre> <hr> <p>The over-allocation is done for performance reasons allowing lists to grow without allocating more memory with every growth (better <a href="https://en.wikipedia.org/wiki/Amortized_analysis" rel="noreferrer">amortized</a> performance).</p> <p>A probable reason for the difference with using list comprehension, is that list comprehension can not deterministically calculate the size of the generated list, but <code>list()</code> can. This means comprehensions will continuously grow the list as it fills it using over-allocation until finally filling it.</p> <p>It is possible that is will not grow the over-allocation buffer with unused allocated nodes once its done (in fact, in most cases it wont, that would defeat the over-allocation purpose).</p> <p><code>list()</code>, however, can add some buffer no matter the list size since it knows the final list size in advance.</p> <hr> <p>Another backing evidence, also from the source, is that we see <a href="https://github.com/python/cpython/blob/3.5/Python/compile.c#L3374" rel="noreferrer">list comprehensions invoking <code>LIST_APPEND</code></a>, which indicates usage of <code>list.resize</code>, which in turn indicates consuming the pre-allocation buffer without knowing how much of it will be filled. This is consistent with the behavior you're seeing.</p> <hr> <p>To conclude, <code>list()</code> will pre-allocate more nodes as a function of the list size</p> <pre><code>&gt;&gt;&gt; sys.getsizeof(list([1,2,3])) 60 &gt;&gt;&gt; sys.getsizeof(list([1,2,3,4])) 64 </code></pre> <p>List comprehension does not know the list size so it uses append operations as it grows, depleting the pre-allocation buffer:</p> <pre><code># one item before filling pre-allocation buffer completely &gt;&gt;&gt; sys.getsizeof([i for i in [1,2,3]]) 52 # fills pre-allocation buffer completely # note that size did not change, we still have buffered unused nodes &gt;&gt;&gt; sys.getsizeof([i for i in [1,2,3,4]]) 52 # grows pre-allocation buffer &gt;&gt;&gt; sys.getsizeof([i for i in [1,2,3,4,5]]) 68 </code></pre>
5,113,318
In a Chrome Extension content script, must I wait for document.ready before processing the document?
<p>Specifically, I'm evaluating all of the images on a page to see if they have a certain attribute, and then adding some new &lt;divs&gt; to the DOM based on those attributes. Must I wait for document.ready to fire before performing these modifications in order to be guaranteed that Chrome has loaded all of the necessary pieces of the DOM?</p> <p>The problem I'm running into is that sometimes document.ready takes a short while to fire and the user is already browsing around the page, wondering why my extension hasn't yet had any effect. The problem usually only lasts a moment, but it's enough to be annoying.</p> <p>If I don't bother waiting for document.ready, and instead immediately process the document, everything <em>seems</em> to work; but I wonder if I'm just getting lucky.</p>
5,114,084
2
0
null
2011-02-25 03:34:57.527 UTC
10
2017-11-07 14:56:50.05 UTC
null
null
null
null
29,696
null
1
36
javascript|jquery|google-chrome|google-chrome-extension
23,578
<p>Actually, you don't have to wait. You can process right away in <a href="http://developer.chrome.com/extensions/content_scripts.html" rel="noreferrer">Content Scripts</a>. Just make sure you don't use <code>document_start</code> in the <code>run_at</code> attribute.</p> <p>In <code>document_end</code>, the files are injected immediately after the DOM is complete, but before subresources like images and frames have loaded. <code>document_idle</code> (the default value) happens even later.</p> <pre><code>{ "name": "My extension", ... "content_scripts": [ { "matches": ["http://www.google.com/*"], "css": ["mystyles.css"], "js": ["jquery.js", "myscript.js"], "run_at": "document_end" } ], ... } </code></pre>
16,103,074
how to set ListView item height
<p>I have a ListActivity which i want to change Item height refer to device height </p> <pre><code>public class MainActivity extends ListActivity { . . . setListAdapter(new ArrayAdapter&lt;String&gt;(MainActivity.this, android.R.layout.simple_list_item_1,mainMenuItems)); } </code></pre> <p>its my ListActivity on galaxy nexus S :</p> <p><img src="https://i.stack.imgur.com/92mXE.png" alt="enter image description here"></p> <p>and on galaxy nexus 7 : <img src="https://i.stack.imgur.com/6BHC8.png" alt="enter image description here"></p> <p>how should I define listview items height ???</p>
16,103,153
4
0
null
2013-04-19 10:59:58.36 UTC
4
2018-06-24 19:30:46.88 UTC
2013-04-19 14:02:57.32 UTC
null
1,731,082
null
1,731,082
null
1
11
android|android-listview|android-activity
39,825
<p>The <code>ListView</code> items height are the height of item layout contents, eg <code>android.R.layout.simple_list_item_1</code> height. If you want different height, create an xml file and put a <code>android:layout_height</code> or <code>android:minHeight</code> attribute.</p> <p>This is a modified <code>simple_list_item_1</code> which refers to your value</p> <pre><code>&lt;TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceListItemSmall" android:gravity="center_vertical" android:paddingStart="?android:attr/listPreferredItemPaddingStart" android:paddingEnd="?android:attr/listPreferredItemPaddingEnd" android:paddingLeft="?android:attr/listPreferredItemPaddingLeft" android:paddingRight="?android:attr/listPreferredItemPaddingRight" android:minHeight="@dimen/your_defined_minumum_height"/&gt; </code></pre> <p>and in your dimen.xml</p> <pre><code>&lt;dimen name="your_defined_minumum_height"&gt;48dp&lt;/dimen&gt; </code></pre>