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
16,945,518
Finding the index of the value which is the min or max in Python
<p>I've got a structure of the form:</p> <pre><code>&gt;&gt;&gt; items [([[0, 1], [2, 20]], 'zz', ''), ([[1, 3], [5, 29], [50, 500]], 'a', 'b')] </code></pre> <p>The first item in each tuple is a list of ranges, and I want to make a generator that provides me the ranges in ascending order based on the starting index. </p> <p>Since the range-lists are already sorted by their starting index this operation is simple: it is just a sorted merge. I'm hoping to do it with good computational efficiency, so I'm thinking that one good way to implicitly track the state of my merge is to simply pop the front off of the list of the tuple which has the smallest starting index in its range list. </p> <p>I can use <code>min()</code> to obtain <code>[0, 1]</code> which is the first one I want, but how do I get the index of it? </p> <p>I have this: </p> <pre><code>[ min (items[i][0]) for i in range(len(items)) ] </code></pre> <p>which gives me the first item in each list, which I can then <code>min()</code> over somehow, but it fails once any of the lists becomes empty, and also it's not clear how to get the index to use <code>pop()</code> with without looking it back up in the list. </p> <p>To summarize: Want to build generator that returns for me: </p> <pre><code>([0,1], 'zz', '') ([1,3], 'a', 'b') ([2,20], 'zz', '') ([5,29], 'a', 'b') ([50,500], 'a', 'b') </code></pre> <p>Or even more efficiently, I only need this data: </p> <pre><code>[0, 1, 0, 1, 1] </code></pre> <p>(the indices of the tuples i want to take the front item of)</p>
16,946,252
9
3
null
2013-06-05 16:46:55.027 UTC
5
2022-01-14 10:11:17.553 UTC
2017-09-17 22:57:04.47 UTC
null
55,075
null
340,947
null
1
40
python
70,233
<p>This works:</p> <pre><code>by_index = ([sub_index, list_index] for list_index, list_item in enumerate(items) for sub_index in list_item[0]) [item[1] for item in sorted(by_index)] </code></pre> <p>Gives:</p> <pre><code>[0, 1, 0, 1, 1] </code></pre> <p>In detail. The generator:</p> <pre><code>by_index = ([sub_index, list_index] for list_index, list_item in enumerate(items) for sub_index in list_item[0]) list(by_index) [[[0, 1], 0], [[2, 20], 0], [[1, 3], 1], [[5, 29], 1], [[50, 500], 1]] </code></pre> <p>So the only thing needed is sorting and getting only the desired index:</p> <pre><code>[item[1] for item in sorted(by_index)] </code></pre>
16,739,322
How to keep the shell window open after running a PowerShell script?
<p>I have a very short PowerShell script that connects to a server and imports the AD module. I'd like to run the script simply by double clicking, but I'm afraid the window immediately closes after the last line.</p> <p>How can I sort this out?</p>
24,620,771
6
1
null
2013-05-24 16:11:50.903 UTC
19
2021-01-29 05:12:11.22 UTC
2016-01-20 13:49:04.433 UTC
null
63,550
null
1,571,299
null
1
83
active-directory|powershell-2.0
136,197
<p>You basically have 3 options to prevent the PowerShell Console window from closing, that I describe <a href="http://blog.danskingdom.com/keep-powershell-console-window-open-after-script-finishes-running/" rel="noreferrer">in more detail on my blog post</a>.</p> <ol> <li><strong>One-time Fix:</strong> Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. <code>PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"</code></li> <li><strong>Per-script Fix:</strong> Add a prompt for input to the end of your script file. e.g. <code>Read-Host -Prompt "Press Enter to exit"</code></li> <li><strong>Global Fix:</strong> Change your registry key by adding the <code>-NoExit</code> switch to always leave the PowerShell Console window open after the script finishes running.</li> </ol> <pre><code>Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command Description: Key used when you right-click a .ps1 file and choose Open With -&gt; Windows PowerShell. Default Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1" Desired Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "&amp; \"%1\"" Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command Description: Key used when you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed). Default Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; &amp; '%1'" Desired Value: "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; &amp; \"%1\"" </code></pre> <p>See my blog for more information and a script to download that will make the registry change for you.</p>
9,647,693
How to calculate average of a column and then include it in a select query in oracle?
<p>My table is--</p> <pre><code>create table mobile ( id integer, m_name varchar(20), cost integer ) </code></pre> <p>and the values are --</p> <pre><code>insert into mobile values(10,'NOkia',100); insert into mobile values(11,'Samsung',150); insert into mobile values(12,'Sony',120); </code></pre> <p>I know how to calculate average on column cost, my code is--</p> <pre><code> select avg(cost) from mobile; </code></pre> <p>and the result is <strong>123</strong></p> <p>But i want to calculate average and then also show the difference.I was able to this but, I am not able to add avg column in the select query--</p> <p>My code is ---</p> <pre><code>SELECT id, m_name as "Mobile Name", cost as Price,avg(cost) as Average, cost-(select avg(cost) from mobile) as Difference FROM mobile group by id,m_name,cost; </code></pre> <p>and the output is --</p> <pre><code>id Mobile Name Price Average Difference 10 Nokia 100 100 -23 11 Samsung 150 150 27 12 Sony 120 120 -3 </code></pre> <p>what I wants is to correct this average column.. I wants this---</p> <pre><code>id Mobile Name Price Average Difference 10 Nokia 100 123 -23 11 Samsung 150 123 27 12 Sony 120 123 -3 </code></pre> <p>please help...</p>
9,647,731
6
3
null
2012-03-10 15:39:43.073 UTC
5
2016-08-08 20:01:55.013 UTC
2013-11-24 01:44:39.37 UTC
null
508,666
null
1,252,001
null
1
6
sql|oracle
96,363
<p>Your group by is what aggregates your average, and it is grouping by the whole table (I am assuming you did this to allow the select for everything) Just move your avg into another subquery, remove the overarching group by and that should solve it. </p> <pre><code>SELECT id, m_name AS "Mobile Name", cost AS Price, (SELECT AVG(cost) FROM mobile) AS Average, cost-(SELECT AVG(cost) FROM mobile) AS Difference FROM mobile; </code></pre> <p>When you run the basic <code>SELECT AVG(cost)</code> statement it is naturally grouping by the column specified (cost in this case) as that is what you are requesting. I would suggest reading up more on <a href="http://www.w3schools.com/sql/sql_groupby.asp" rel="noreferrer">GROUP BY</a> and <a href="http://www.w3schools.com/sql/sql_functions.asp" rel="noreferrer">aggregates</a> to get a better grasp on the concept. That should help you more than just a simple solution.</p> <p><strong>UPDATE:</strong></p> <p>The answer below is actually from David's answer. It makes use the analytical functions. Basically, what is happening is that on each AVG call, you are telling the engine what to use for the function (in this case, nothing). A decent writeup on analytical functions can be found <a href="http://www.orafusion.com/art_anlytc.htm" rel="noreferrer">here</a> and <a href="http://www.orafaq.com/node/55" rel="noreferrer">here</a> and more with a google on the matter.</p> <pre><code>SELECT id, m_name AS "Mobile Name" cost AS Price, AVG(cost) OVER( ) AS Average, cost - AVG(cost) OVER ( ) AS Difference FROM mobile </code></pre> <p>However, if your SQL engine allows for variables, you could just as easily do the below answer. I actually prefer this for future maintainability/readability. The reason is that a variable with a good name can be very descriptive to future readers of the code, versus an analytical function that does require a little bit more work to read (especially if you do not understand the over function). </p> <p>Also, this solution duplicates the same query twice, so it might be worth storing your average in a SQL variable. Then you ca change your statement to simply use that global average</p> <p>This is variables in SQL-Server (you will have to adapt it for your own instance of SQL)</p> <pre><code>DECLARE @my_avg INT; SELECT @my_avg = AVG(cost) FROM Mobile; SELECT id, m_name AS "Mobile Name", cost AS Price, @my_avg AS Average, cost-@my_avg AS Difference FROM mobile; </code></pre> <p>This solution will read a lot cleaner to future readers of your SQL, too</p>
9,922,928
What does pss mean in /proc/pid/smaps
<p>I was confused about the <code>Pss</code> column in <code>/proc/pid/smaps</code>, so I wrote a program to test it:</p> <pre class="lang-c prettyprint-override"><code>void sa(); int main(int argc,char *argv[]) { int fd; sa(); sleep(1000); } void sa() { char *pi=new char[1024*1024*10]; for(int i=0;i&lt;4;++i) { for(int j=0;j&lt;1024*1024;++j){ *pi='o'; pi++; } } int cnt; for(int i=0;i&lt;6;++i) { for(int j=0;j&lt;1024*1024;++j){ cnt+=*pi; pi++; } } printf(&quot;%d&quot;,cnt); } </code></pre> <pre><code>$cat /proc/`pidof testprogram`/smaps 08838000-0885b000 rw-p 00000000 00:00 0 [heap] Size: 140 kB Rss: 12 kB Pss: 12 kB Shared_Clean: 0 kB Shared_Dirty: 0 kB Private_Clean: 0 kB Private_Dirty: 12 kB Referenced: 12 kB Swap: 0 kB KernelPageSize: 4 kB MMUPageSize: 4 kB b6dcd000-b77d0000 rw-p 00000000 00:00 0 Size: 10252 kB Rss: 10252 kB Pss: 4108 kB Shared_Clean: 0 kB Shared_Dirty: 0 kB Private_Clean: 0 kB Private_Dirty: 4108 kB Referenced: 4108 kB Swap: 0 kB KernelPageSize: 4 kB MMUPageSize: 4 kB </code></pre> <p>Here I found <code>Pss</code> equal to <code>Private_Dirty</code>, but I wonder why.</p> <p>BTW: Is there any detailed documentation for <code>smaps</code>?</p>
9,923,021
1
0
null
2012-03-29 09:48:21.563 UTC
13
2022-03-26 18:37:40.813 UTC
2022-03-26 18:37:40.813 UTC
null
3,241,243
null
440,403
null
1
26
linux|memory|memory-management|linux-kernel
52,429
<p>Quoting from <a href="http://lwn.net/Articles/230975/" rel="noreferrer">lwn.net</a></p> <blockquote> <p>The "proportional set size" (PSS) of a process is the count of pages it has in memory, where each page is divided by the number of processes sharing it. So if a process has 1000 pages all to itself, and 1000 shared with one other process, its PSS will be 1500</p> </blockquote> <p>From <a href="http://www.mjmwired.net/kernel/Documentation/filesystems/proc.txt" rel="noreferrer">Linux Kernel Documentation</a>,</p> <p>The <code>/proc/PID/smaps</code> is an extension based on maps, showing the memory consumption for each of the process's mappings. For each of mappings there is a series of lines such as the following:</p> <pre><code>08048000-080bc000 r-xp 00000000 03:02 13130 /bin/bash Size: 1084 kB Rss: 892 kB Pss: 374 kB Shared_Clean: 892 kB Shared_Dirty: 0 kB Private_Clean: 0 kB Private_Dirty: 0 kB Referenced: 892 kB Anonymous: 0 kB Swap: 0 kB KernelPageSize: 4 kB MMUPageSize: 4 kB Locked: 374 kB </code></pre> <blockquote> <p>The first of these lines shows the same information as is displayed for the mapping in <strong>/proc/PID/maps</strong>. The remaining lines show the size of the mapping (<strong>size</strong>), the amount of the mapping that is currently resident in RAM (<strong>RSS</strong>), the process' proportional share of this mapping (<strong>PSS</strong>), the number of clean and dirty private pages in the mapping. Note that even a page which is part of a <strong>MAP_SHARED</strong> mapping, but has only a single pte mapped, i.e. is currently used by only one process, is accounted as private and not as shared. "<strong>Referenced</strong>" indicates the amount of memory currently marked as referenced or accessed. "<strong>Anonymous</strong>" shows the amount of memory that does not belong to any file. Even a mapping associated with a file may contain anonymous pages: when <strong>MAP_PRIVATE</strong> and a page is modified, the file page is replaced by a private anonymous copy. "<strong>Swap</strong>" shows how much would-be-anonymous memory is also used, but out on swap.</p> </blockquote> <p><a href="https://unix.stackexchange.com/questions/33381/getting-information-about-a-process-memory-usage-from-proc-pid-smaps">This Question</a> on <code>Unix and Linux</code> Stackexchange covers almost the topic. See Mat's excellent answer which will surely clear all your doubts.</p>
11,485,486
Regarding thread safety of servlet
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading">How do servlets work? Instantiation, session variables and multithreading</a> </p> </blockquote> <p>Is servlet is thread safe ..? For ex If I open 5 different browsers and sending request to one servlet in the container , is it still thread safe , I means the <code>service()</code> method specially</p>
11,485,565
1
0
null
2012-07-14 16:34:59.843 UTC
12
2019-04-22 18:39:42.857 UTC
2017-05-23 12:25:19.77 UTC
null
-1
null
1,508,454
null
1
12
java|multithreading|servlets|thread-safety
11,520
<p>Your question boils down to: <em>is calling a method from multiple threads on the same object thread safe</em>. And the answer is: <strong>it depends</strong>. If your object (let it be servlet) is stateless or has only <code>final</code> fields, this is completely thread safe. Local variables and parameters are local to the thread (reside on stack, not on heap).</p> <p>Also each <code>service()</code> call receives a distinct instance of <code>ServletRequest</code> and <code>ServletResponse</code>. However, here is an example of an unsafe servlet:</p> <pre><code>public class UnsafeServlet implements Servlet { private int counter; public void init(ServletConfig config) throws ServletException { } public void service(ServletRequest request, ServletResponse response) ++counter; } public void destroy() { } } </code></pre> <p>Since multiple threads can access the <code>counter</code> variable, it has to be secured somehow: either by using <code>synchronized</code> (<code>volatile</code> is not enough):</p> <pre><code>synchronized(this) { ++counter; } </code></pre> <p>or <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicInteger.html" rel="noreferrer"><code>AtomicInteger</code></a>:</p> <pre><code>private AtomicInteger counter = new AtomicInteger(); //... counter.incrementAndGet(); </code></pre> <p>In this particular case <code>AtomicInteger</code> is much better since it is lock-free using CAS CPU operations while <code>synchronized</code> is a mutex.</p>
12,005,526
Erase multiple packages using rpm or yum
<p>I was given access to a server with 50+ php rpms installed. I'm trying to remove them all.</p> <p>Basically, I'm trying to combine these two commands:</p> <pre><code>rpm -qa | grep 'php' </code></pre> <p>and</p> <pre><code>rpm --erase </code></pre> <p>I know a little about pipes and redirection, but I don't see how to use them for this purpose. Please help.</p>
22,312,983
5
0
null
2012-08-17 12:10:10.357 UTC
9
2020-04-05 20:11:43.66 UTC
2016-11-08 18:11:40.51 UTC
null
832,230
null
1,382,299
null
1
18
unix|rpm|yum
43,883
<h2>Using <code>yum</code></h2> <p>List and remove the indicated packages and all their dependencies, but with a <code>y/N</code> confirmation:</p> <pre><code>yum remove 'php*' </code></pre> <p>To bypass the confirmation, replace <code>yum</code> with <code>yum -y</code>.</p> <h2>Using <code>rpm</code></h2> <p>This section builds upon the answers by <a href="https://stackoverflow.com/a/12009218/832230">twalburg</a> and <a href="https://stackoverflow.com/a/16769089/832230">Ricardo</a>.</p> <p>List which RPMs are installed:</p> <pre><code>rpm -qa 'php*' rpm -qa | grep '^php' # Alternative listing. </code></pre> <p>List which RPMs which will be erased, without actually erasing them:</p> <pre><code>rpm -e --test -vv $(rpm -qa 'php*') 2&gt;&amp;1 | grep '^D: erase:' </code></pre> <p>On Amazon Linux, you may need to use <code>grep '^D: ========== ---'</code> instead.</p> <p>If the relevant RPMs are not listed by the command above, investigate errors:</p> <pre><code>rpm -e --test -vv $(rpm -qa 'php*') </code></pre> <p>Erase these RPMs:</p> <pre><code>rpm -e $(rpm -qa 'php*') </code></pre> <p>Confirm the erasure:</p> <pre><code>rpm -qa 'php*' </code></pre>
11,555,418
why is the enhanced for loop more efficient than the normal for loop
<p>I read that the <em>enhanced for loop</em> is more efficient than the normal <em>for loop</em> here:</p> <p><a href="http://developer.android.com/guide/practices/performance.html#foreach" rel="noreferrer">http://developer.android.com/guide/practices/performance.html#foreach</a></p> <p>When I searched for the difference between their efficiency, all I found is: In case of normal for loop we need an extra step to find out the length of the array or size etc.,</p> <pre><code>for(Integer i : list){ .... } int n = list.size(); for(int i=0; i &lt; n; ++i){ .... } </code></pre> <p>But is this the only reason, the enhanced for loop is better than the normal for loop? In that case better use the normal <em>for loop</em> because of the slight complexity in understanding the enhanced <em>for loop</em>.</p> <p>Check this for an interesting issue: <a href="http://www.coderanch.com/t/258147/java-programmer-SCJP/certification/Enhanced-Loop-Vs-Loop" rel="noreferrer">http://www.coderanch.com/t/258147/java-programmer-SCJP/certification/Enhanced-Loop-Vs-Loop</a></p> <p>Can any one please explain the internal implementation of these two types of for loops, or explain other reasons to use the enhanced <em>for loop</em>?</p>
11,555,489
7
6
null
2012-07-19 06:54:51.793 UTC
18
2018-02-11 13:17:29.397 UTC
2018-02-11 13:17:29.397 UTC
null
312,172
null
1,457,863
null
1
32
java|for-loop|foreach
40,391
<p>It's a bit of an oversimplification to say that the enhanced for loop is more efficient. It <em>can</em> be, but in many cases it's almost exactly the same as an old-school loop.</p> <p>The first thing to note is that for collections the enhanced for loop uses an <code>Iterator</code>, so if you manually iterate over a collection using an <code>Iterator</code> then you should have pretty much the same performance than the enhanced for loop.</p> <p>One place where the enhanced for loop is faster than a <em>naively implemented</em> traditional loop is something like this:</p> <pre><code>LinkedList&lt;Object&gt; list = ...; // Loop 1: int size = list.size(); for (int i = 0; i&lt;size; i++) { Object o = list.get(i); /// do stuff } // Loop 2: for (Object o : list) { // do stuff } // Loop 3: Iterator&lt;Object&gt; it = list.iterator(); while (it.hasNext()) { Object o = it.next(); // do stuff } </code></pre> <p>In this case Loop 1 will be slower than both Loop 2 and Loop 3, because it will have to (partially) traverse the list in each iteration to find the element at position <code>i</code>. Loop 2 and 3, however will only ever step one element further in the list, due to the use of an <code>Iterator</code>. Loop 2 and 3 will also have pretty much the same performance since Loop 3 is pretty much exactly what the compiler will produce when you write the code in Loop 2.</p>
19,958,667
Stray start tag script
<p>I'm trying to get a tooltip from <a href="http://www.wowhead.com/hearthstone/tooltips">http://www.wowhead.com/hearthstone/tooltips</a> to work on my site but it doesn't work so I tried the W3C validator for answers and I got the following error:</p> <p>Error Line 88, Column 84: <strong>Stray start tag script</strong>. …//static.wowhead.com/widgets/power.js"<strong>></strong>var wowhead_tooltips =…</p> <p>Heres my code of that section:</p> <pre><code>&lt;script type="text/javascript" src="http://static.wowhead.com/widgets/power.js"&gt; &lt;/script&gt; &lt;script&gt; var wowhead_tooltips = { "colorlinks": true, "iconizelinks": true, "renamelinks": true } &lt;/script&gt; </code></pre> <p>And it's within the <code>&lt;html&gt;</code> and <code>&lt;head&gt;</code> tags.</p>
19,958,777
1
4
null
2013-11-13 16:08:12.193 UTC
5
2021-07-04 08:39:33.123 UTC
2014-08-08 15:23:35.733 UTC
null
50,447
null
2,988,514
null
1
49
javascript|html
47,832
<p>Validator gives that error when you've something outside <code>&lt;/body&gt;</code>.</p> <p>Just move your script tags inside <code>&lt;body&gt;</code>, or keep them in <code>&lt;head&gt;</code>. </p>
20,198,696
CORS request with IE11
<p>I have a CORS (cross origin resource sharing) request coming from my login page to the application site, on a different URL. I have a simple page I ping to determine if a user is already logged in, and if so, redirects them. Otherwise I show a login page. I use jQuery.</p> <p>This works great in safari, chrome, firefox... and not IE (naturally). According to MS, IE 10 and later should support <a href="http://msdn.microsoft.com/en-us/library/ie/hh673569%28v=vs.85%29.aspx">CORS requests with withCredentials</a></p> <p>I'm using jquery-2.0.3.min.js</p> <p>Any ideas why this isn't working in IE11?</p> <p>EDIT: It appears as though it IS partially working, as it is now returning a value of {"id":false}. This happens every time, meaning that the server is never getting the credentials. I am also posting my is_logged_in page, I am using the code igniter framework.</p> <p>EDIT: After enabling "Allow data sources across domains" under IE's security settings, I no longer receive any error messages.</p> <p><del>The exact error I receive is:</del></p> <blockquote> <p><del>SEC7118: XMLHttpRequest for <a href="http://mysite.net/guest/is_logged_in">http://mysite.net/guest/is_logged_in</a> required Cross Origin Resource Sharing (CORS).</del></p> </blockquote> <pre><code>$.ajax({ url: 'http://mysite.net/guest/is_logged_in', type: 'POST', crossDomain: true, xhrFields: { withCredentials: true }, dataType: 'json', success: function(data) { if(data.id) { window.location.replace("http://mysite.net"); } } }); </code></pre> <p>and</p> <pre><code>public function is_logged_in() { $allowed = array( 'http://mysite.net', 'http://www.mysite.net', 'http://www.mysite.com', ); $url = $_SERVER['HTTP_REFERER']; $url = substr($url, 0, strpos($url, '/', 8)); if(isset($_SERVER['HTTP_ORIGIN'])) { if(in_array($_SERVER['HTTP_ORIGIN'], $allowed)) { $this-&gt;output-&gt;set_header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']); } } else { if(in_array($url, $allowed)) { $this-&gt;output-&gt;set_header('Access-Control-Allow-Origin: ' . $url); } } $this-&gt;output-&gt;set_header('Access-Control-Allow-Headers: X-Requested-With'); $this-&gt;output-&gt;set_header('Access-Control-Allow-Credentials: true'); $this-&gt;output-&gt;set_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin"); //TODO: Try to detect if this is an ajax request, and disallow it if not. $data = new stdClass(); $this-&gt;load-&gt;library("ion_auth"); if($this-&gt;ion_auth-&gt;logged_in()) { $data-&gt;name = $this-&gt;ion_auth-&gt;user()-&gt;row()-&gt;first_name; $data-&gt;id = $this-&gt;ion_auth-&gt;get_user_id(); } else { $data-&gt;id = false; } $this-&gt;output-&gt;set_output(json_encode($data)); } </code></pre> <p>Thanks in advance</p>
21,682,899
6
8
null
2013-11-25 16:54:33.43 UTC
11
2018-10-01 07:30:44.28 UTC
2013-11-25 19:32:05.687 UTC
null
980,857
null
980,857
null
1
26
jquery|cors|internet-explorer-11
83,015
<p>Changing the setting for "Access data sources across domains" to Enabled turns off cross-domain checks in IE and is horrifically unsafe. Instead, you need to ensure that the target 3rd-party resource sends a <a href="http://blogs.msdn.com/b/ieinternals/archive/2013/09/17/simple-introduction-to-p3p-cookie-blocking-frame.aspx" rel="noreferrer">valid P3P policy</a> that indicates that it's not doing horrible things to the user's privacy.</p>
3,898,750
installing MySQLdb for Python 2.6 on OSX
<p>I am trying to install MySQLdb for Python 2.6 as per these instructions:</p> <p><a href="http://www.tutorialspoint.com/python/python_database_access.htm" rel="noreferrer">http://www.tutorialspoint.com/python/python_database_access.htm</a></p> <p>When I get to this step: <code>$ python setup.py build</code> I get the error:</p> <pre>users-MacBook-Pro:MySQL-python-1.2.3 user$ sudo python setup.py build sh: mysql_config: command not found Traceback (most recent call last): File "setup.py", line 15, in metadata, options = get_config() File "/my_crawler/MySQL-python-1.2.3/setup_posix.py", line 43, in get_config libs = mysql_config("libs_r") File "/my_crawler/MySQL-python-1.2.3/setup_posix.py", line 24, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found </pre> <p>I have MySQL installed and added to my <code>bash</code></p> <p>What am I doing wrong?</p>
3,898,766
4
0
null
2010-10-10 02:23:43.373 UTC
9
2016-08-22 05:30:07.047 UTC
2012-09-10 15:52:02.153 UTC
null
388,916
null
109,859
null
1
17
python|mysql|macos
20,053
<p>It's not looking for 'mysql', it's looking for 'mysql_config'. Try running 'which mysql_config' from bash. It probably won't be found. That's why the build isn't finding it either. Try running 'locate mysql_config' and see if anything comes back. The path to this binary needs to be either in your shell's $PATH environment variable, or it needs to be explicitly in the setup.py file for the module assuming it's looking in some specific place for that file. </p> <p>If you installed mysql from source in /usr/local, I believe the file will be found at /usr/local/mysql/bin/mysql_config</p>
3,942,880
Hibernate - AnnotationConfiguration deprecated
<p>I am using Hibernate in version 3.6.0 and the AnnotationConfiguration is marked as deprecated.</p> <p>Here is the the line in my HibernateUtil.java class:</p> <pre><code>sessionFactory = new AnnotationConfiguration().configure("/hib.cfg.xml").buildSessionFactory(); </code></pre> <p>What's the replacement for AnnotationConfiguration?</p>
3,942,913
4
0
null
2010-10-15 13:56:17.603 UTC
5
2017-12-01 12:05:08.177 UTC
2017-12-01 12:05:08.177 UTC
null
3,885,376
null
224,030
null
1
37
hibernate|annotations|deprecated
58,376
<p>"All functionality has been moved to Configuration": <a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/cfg/AnnotationConfiguration.html" rel="noreferrer">http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/cfg/AnnotationConfiguration.html</a></p> <p>And here is Configuration:</p> <p><a href="http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/cfg/Configuration.html" rel="noreferrer">http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/cfg/Configuration.html</a></p>
3,998,786
change list display link in django admin
<p>I am trying to change the link for an object in the django admin list display. Here is what I have so far:</p> <pre><code>class FooModelAdmin(admin.ModelAdmin): fields = ('foo','bar') list_display = ('foo_link','bar') def foo_link(self,obj): return u'&lt;a href="/foos/%s/"&gt;%s&lt;/a&gt;' % (obj.foo,obj) domain_link.allow_tags = True domain_link.short_description = "foo" </code></pre> <p>This produces another link within the original list display link e.g.</p> <pre><code>&lt;a href="/admin/app/model/pk/"&gt;&lt;a href="/foos/foo/"&gt;Foo&lt;/a&gt;&lt;/a&gt; </code></pre>
3,999,436
6
0
null
2010-10-22 16:14:26.2 UTC
9
2020-10-26 08:31:45.817 UTC
2010-10-22 17:34:39.71 UTC
null
95,472
null
95,472
null
1
28
django|django-admin|modeladmin
25,713
<p>The solution was to override the init and set the list_display_links to None e.g. </p> <pre><code>class FooModelAdmin(admin.ModelAdmin): fields = ('foo','bar') list_display = ('foo_link','bar') def foo_link(self,obj): return u'&lt;a href="/foos/%s/"&gt;%s&lt;/a&gt;' % (obj.foo,obj) foo_link.allow_tags = True foo_link.short_description = "foo" def __init__(self,*args,**kwargs): super(FooModelAdmin, self).__init__(*args, **kwargs) self.list_display_links = (None, ) </code></pre>
3,458,461
Find file then cd to that directory in Linux
<p>In a shell script how would I find a file by a particular name and then navigate to that directory to do further operations on it?</p> <p>From here I am going to copy the file across to another directory (but I can do that already just adding it in for context.)</p>
3,458,564
11
0
null
2010-08-11 12:57:13.58 UTC
12
2019-12-28 11:04:02.663 UTC
2015-06-08 15:18:01.573 UTC
null
4,342,498
null
400,309
null
1
28
linux|shell|filesystems
34,155
<p>You can use something like:</p> <pre><code>pax[/home/pax]&gt; cd "$(dirname "$(find / -type f -name ls | head -1)")" pax[/usr/bin]&gt; _ </code></pre> <p>This will locate the first <code>ls</code> regular file then change to that directory.</p> <p>In terms of what each bit does:</p> <ul> <li>The find will start at <code>/</code> and search down, listing out all regular files (<code>-type f</code>) called <code>ls</code> (<code>-name ls</code>). There are other things you can add to <code>find</code> to further restrict the files you get.</li> <li>The piping through <code>head -1</code> will filter out all but the first.</li> <li><code>$()</code> is a way to take the output of a command and put it on the command line for <em>another</em> command.</li> <li><code>dirname</code> can take a full file specification and give you the path bit.</li> <li><code>cd</code> just changes to that directory.</li> </ul> <p>If you execute each bit in sequence, you can see what happens:</p> <pre><code>pax[/home/pax]&gt; find / -type f -name ls /usr/bin/ls pax[/home/pax]&gt; find / -type f -name ls | head -1 /usr/bin/ls pax[/home/pax]&gt; dirname "$(find / -type f -name ls | head -1)" /usr/bin pax[/home/pax]&gt; cd "$(dirname "$(find / -type f -name ls | head -1)")" pax[/usr/bin]&gt; _ </code></pre>
3,565,368
Ternary operator ?: vs if...else
<p>In C++, is the ?: operator faster than if()...else statements? Are there any differences between them in compiled code?</p>
3,565,374
14
5
null
2010-08-25 11:34:12.937 UTC
21
2022-07-21 18:03:32.74 UTC
2015-11-03 06:28:11.823 UTC
null
15,727
null
427,135
null
1
89
c++|performance|conditional-operator
120,915
<p>Depends on your compiler, but on any modern compiler there is generally no difference. It's something you shouldn't worry about. Concentrate on the maintainability of your code.</p>
3,730,019
Why not use Double or Float to represent currency?
<p>I've always been told <em>never</em> to represent money with <code>double</code> or <code>float</code> types, and this time I pose the question to you: why? </p> <p>I'm sure there is a very good reason, I simply do not know what it is.</p>
3,730,040
16
5
null
2010-09-16 19:23:57.087 UTC
493
2022-08-09 06:25:04.86 UTC
2019-08-17 01:29:32.43 UTC
null
207,421
null
439,836
null
1
1,157
floating-point|currency
377,782
<p>Because floats and doubles cannot accurately represent the base 10 multiples that we use for money. This issue isn't just for Java, it's for any programming language that uses base 2 floating-point types.</p> <p>In base 10, you can write 10.25 as 1025 * 10<sup>-2</sup> (an integer times a power of 10). <a href="http://en.wikipedia.org/wiki/IEEE_floating_point" rel="noreferrer">IEEE-754 floating-point numbers</a> are different, but a very simple way to think about them is to multiply by a power of two instead. For instance, you could be looking at 164 * 2<sup>-4</sup> (an integer times a power of two), which is also equal to 10.25. That's not how the numbers are represented in memory, but the math implications are the same.</p> <p>Even in base 10, this notation cannot accurately represent most simple fractions. For instance, you can't represent 1/3: the decimal representation is repeating (0.3333...), so there is no finite integer that you can multiply by a power of 10 to get 1/3. You could settle on a long sequence of 3's and a small exponent, like 333333333 * 10<sup>-10</sup>, but it is not accurate: if you multiply that by 3, you won't get 1.</p> <p>However, for the purpose of counting money, at least for countries whose money is valued within an order of magnitude of the US dollar, usually all you need is to be able to store multiples of 10<sup>-2</sup>, so it doesn't really matter that 1/3 can't be represented.</p> <p>The problem with floats and doubles is that the <em>vast majority</em> of money-like numbers don't have an exact representation as an integer times a power of 2. In fact, the only multiples of 0.01 between 0 and 1 (which are significant when dealing with money because they're integer cents) that can be represented exactly as an IEEE-754 binary floating-point number are 0, 0.25, 0.5, 0.75 and 1. All the others are off by a small amount. As an analogy to the 0.333333 example, if you take the floating-point value for 0.01 and you multiply it by 10, you won't get 0.1. Instead you will get something like 0.099999999786...</p> <p>Representing money as a <code>double</code> or <code>float</code> will probably look good at first as the software rounds off the tiny errors, but as you perform more additions, subtractions, multiplications and divisions on inexact numbers, errors will compound and you'll end up with values that are visibly not accurate. This makes floats and doubles inadequate for dealing with money, where perfect accuracy for multiples of base 10 powers is required.</p> <p>A solution that works in just about any language is to use integers instead, and count cents. For instance, 1025 would be $10.25. Several languages also have built-in types to deal with money. Among others, Java has the <a href="http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html" rel="noreferrer"><code>BigDecimal</code></a> class, and Rust has the <a href="https://docs.rs/rust_decimal/latest/rust_decimal/" rel="noreferrer"><code>rust_decimal</code></a> crate, and C# has the <a href="http://msdn.microsoft.com/en-us/library/364x0z75.aspx" rel="noreferrer"><code>decimal</code></a> type.</p>
3,429,959
Why is Eclipse's Android Device Chooser not showing my Android device?
<p>I am using the Android plugin for Eclipse, and when I try to run my program using a real device through the <em>Android Device Chooser</em>, my phone is not listed as a device. I have updated Eclipse, all of the Android packages, and the USB driver, but it still isn't showing up. My phone is running Android 2.1, which is also the target version listed in the Eclipse project.</p> <p>Also it happens that the device shows up as an unknown target and the serial number as question marks as shown in the screenshot.</p> <p><img src="https://i.stack.imgur.com/9Zl6F.jpg" alt="Android Device Chooser"></p>
3,470,439
19
3
null
2010-08-07 09:45:17.107 UTC
42
2015-07-23 12:34:10.577 UTC
2012-12-02 13:22:36.473 UTC
null
356,895
null
412,168
null
1
87
android|eclipse|adb
95,002
<p>I just had the same issue with the Motorola Droid. I had 3 devices and only 1 was detected in the ADB. The one that worked showed up in device manager as "android adb composite interface" and the 2 that did not work showed up as "android adb interface". In Windows 7 I did the following.</p> <ol> <li>Right Click Computer then Manage</li> <li>Expand Android phone at the top of the list</li> <li>Right click Android ADB Interface then Update Driver Software</li> <li>Browse my computer for driver software</li> <li>Let me pick from a list of device drivers on my computer</li> <li>Choose USB Composite Device then next</li> </ol> <p>If USB Composite Device doesn't show up then try browsing to the usb_driver folder in your android sdk directory for step 5 then try step 5 and 6 again.</p> <p>Note : If Android does not appear at the top of this list as described in #2 and/or you find a device ADB with no drivers then you probably need to install the device driver, which in my case (HTC Glacier) was located right on my phone.</p>
7,716,004
Will Dart support the use of existing JavaScript libraries?
<p>I understand Dart compiles to JavaScript, and I read the <a href="http://www.dartlang.org/docs/spec/dartLangSpec.pdf" rel="noreferrer">Dart Language Spec</a> on Libraries, although I didn't see an answer there. Also a search on their <a href="https://groups.google.com/a/dartlang.org/group/misc/search?group=misc%C3%A5&amp;q=existing&amp;qt_g=Search%20this%20group" rel="noreferrer">discussion form</a> for the word 'existing' turns up 3 results that are not related.</p> <p>Does anyone know if Dart will support the use of existing JavaScript libraries such as jQuery or Raphael?</p>
8,753,738
4
1
null
2011-10-10 16:44:52.887 UTC
21
2018-12-12 09:57:25.86 UTC
2011-10-18 22:10:43.32 UTC
null
213,269
null
298,240
null
1
111
javascript|libraries|dart
15,899
<p>The answer is now Yes! Dart now ships a JS-interop library to use existing JavaScript code with your Dart app. Learn more here: <a href="https://www.dartlang.org/articles/js-dart-interop/" rel="noreferrer">https://www.dartlang.org/articles/js-dart-interop/</a></p>
8,149,364
Android: Button click event
<p>I have 2 buttons in my xml file with RelativeLayout. In my class I have extended Dialog &amp; implemetned OnClickListener and also added OnClick(View v) method. But somehow the onClick code is never executed when the button is clicked. Can anyone help me find the problem with my code :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10px"&gt; ...... &lt;Button android:id="@+id/saveBtn_settingDlg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText1" android:layout_marginLeft="10px" android:text="Save" /&gt; &lt;Button android:id="@+id/closeBtn_settingDlg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Close" android:layout_alignBaseline="@+id/saveBtn_setting" android:layout_toRightOf="@+id/saveBtn_setting" android:onClick="CloseDialog" /&gt; </code></pre> <p>Class </p> <pre><code> public class SettingDialog extends Dialog implements OnClickListener { private Button btn_save, btn_close; // In Constructor btn_save = (Button) findViewById(R.id.saveBtn_settingDlg); btn_close = (Button) findViewById(R.id.closeBtn_settingDlg); btn_save.setOnClickListener(this); btn_close.setOnClickListener(this); @Override public void onClick(View v) { if (v == btn_save) SaveSettings(); else if (v == btn_close) CloseDialog(); return; } private void CloseDialog() { disposeAll(); this.dismiss(); } public void CloseBtnClicked(View v) { CloseDialog(); } </code></pre> <p>In xml for close btn I tried CloseBtnClicked also but no difference and I get an UnexpectedError message and application shuts down. Somehow the event is only not activated in any ways. And also on adding onClick to closebtn the button is now shown on the top-left of the screen and lost the actual location of it.</p> <p>Calling SettingDialog from Activity class :</p> <pre><code> private void OpenSettingDialog() { AlertDialog.Builder ad = new AlertDialog.Builder(this); ad.setIcon(R.drawable.ic_dialog_small); View inflatedView = LayoutInflater.from(this).inflate(R.layout.settings_dialog, null); ad.setView(inflatedView); AlertDialog adlg = ad.create(); adlg.show(); } </code></pre> <p>Can anyone help me know the reason for this problem and how do I solve it. I am a newbie to Android.</p> <p>Thanks</p>
8,151,780
8
1
null
2011-11-16 09:28:59.123 UTC
3
2014-11-15 05:56:32.99 UTC
2011-11-16 10:25:01.42 UTC
null
455,979
null
455,979
null
1
13
android|button|click|onclick
100,068
<p>Solution to my Problem :</p> <p>Instead of using AlertBuilder and AlertDialog, I just called the dialog as :</p> <pre><code> SettingDialog sd = new SettingDialog(this, mySettings); sd.show(); </code></pre> <p>And this worked well. All click events were handled within SettingDialog only. No changes were to be made in SettingDialog. Only the way to call SettingDialog is changed in the Activity. That's it.</p> <p>BTW, In onClick() comapring a View with its name :</p> <pre><code> public void onClick(View v) { Log.i("APP: ", "Into OnClick of SettingDialog. View = " + v); if (v == btn_save) SaveSettings(); else if (v == btn_close) CloseDialog(); return; } </code></pre> <p>Also works perfectly. I use this way only and it works well. No need to check with the Id only.</p> <p>Hope my solution will help others who are stuck like me. Thanks to all for your efforts and helping hand.</p>
8,007,108
Java Sorting based on Enum constants
<p>We have an enum </p> <pre><code>enum listE { LE1, LE4, LE2, LE3 } </code></pre> <p>Furthermore, we have a list that contains the strings <code>["LE1","LE2","LE3","LE4"]</code>. Is there a way to sort the list based on the enum defined order (not the natural <code>String</code> order).</p> <p>The sorted list should be <code>["LE1", "LE4", "LE2", "LE3"]</code>.</p>
8,007,155
11
0
null
2011-11-04 09:23:48.707 UTC
11
2020-12-02 20:52:27.603 UTC
2017-07-20 17:39:47.787 UTC
null
3,745,896
null
227,100
null
1
61
java|sorting|enums
103,976
<p><a href="http://download.oracle.com/javase/6/docs/api/java/lang/Enum.html" rel="noreferrer"><code>Enum&lt;E&gt;</code></a> implements <code>Comparable&lt;E&gt;</code> via the natural order of the enum (the order in which the values are declared). If you just create a list of the enum values (instead of strings) via parsing, then sort that list using <code>Collections.sort</code>, it should sort the way you want. If you need a list of strings again, you can just convert back by calling <code>name()</code> on each element.</p>
4,495,796
How much performance do you get out a Heroku dynos/workers?
<p>How much traffic can a site with 1 or 2 Dynos handle on <a href="http://heroku.com" rel="noreferrer">www.Heroku.com</a> and would increasing workers improve this? Any help on dynos/workers would be appreciated. </p>
4,495,871
3
0
null
2010-12-21 02:24:42.053 UTC
16
2013-05-08 15:16:47.43 UTC
null
null
null
null
444,021
null
1
37
ruby-on-rails|ruby|heroku|ruby-on-rails-3
10,257
<p>This <a href="http://benscheirman.com/2010/08/load-testing-our-heroku-app" rel="noreferrer">blog entry</a> may be of use. He does a great breakdown of the kind of bottlenecks heroku can run into, and how increasing dynos can help, and provides links and information to the <a href="https://devcenter.heroku.com/articles/performance-overview" rel="noreferrer">official performance guide on heroku</a> as well as some tools that will help you test your own app.</p> <p>Worker performance really depends on how your site is built and what you are using them for. Background processing (image formatting, account pruning, etc) called <a href="https://devcenter.heroku.com/articles/delayed-job" rel="noreferrer">Delayed Jobs</a> is how you put them to work </p> <p>EDIT // 1 March 2012: <a href="http://blog.evanweaver.com/2012/02/29/hello-heroku-world/" rel="noreferrer">Here is another blog entry</a> that explored heroku latency and throughput performance for a variable number Dynos. </p> <p>EDIT // 28 Feb 2013: There have been some concerns <a href="http://rapgenius.com/James-somers-herokus-ugly-secret-lyrics" rel="noreferrer">raised in this post</a> regarding Heroku's random routing algorithm and how metrics may be misreported when scaling Dynos, specifically those provided by New Relic. This is still an ongoing issue and is something to note in the context of my previous answer. Heroku's responses are linked within the post.</p> <p>EDIT // 8 May 2013: <a href="http://blog.shellycloud.com/2013/05/is-shelly-cloud-faster-than-heroku.html" rel="noreferrer">A recent post on Shelly Cloud blog</a> analyses impact of number of dynos and web server used on application perfomance. <a href="https://github.com/shellycloud/baseline-performance" rel="noreferrer">Baseline performance script</a> used there should be useful in performing further tests.</p>
4,239,941
Difference between URL and URI?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/176264/whats-the-difference-between-a-uri-and-a-url">What&#39;s the difference between a URI and a URL?</a> </p> </blockquote> <p>Just to get it right:</p> <p>URI = Tells you in which hotel you should go to sleep.</p> <p>URL = Tells you in which room in what hotel you should go to sleep.</p> <p>So URL is a lot more specific, it points to a final destination. The thing you want. While URI is something strange.</p> <p>So what exactly is URI when it's not an URL? What's the real difference?</p>
4,239,952
3
2
null
2010-11-21 19:44:11.503 UTC
10
2010-11-21 19:49:27.563 UTC
2017-05-23 12:18:01.347 UTC
null
-1
null
472,300
null
1
42
url|uri
67,785
<p>URI: Uniform Resource Identifier (URI) is a string of characters used to identify a name or a resource on the Internet. Such identification enables interaction with representations of the resource over a network (typically the World Wide Web) using specific protocols</p> <p>URL: In computing, a Uniform Resource Locator (URL) is a subset of the Uniform Resource Identifier (URI) that specifies where an identified resource is available and the mechanism for retrieving it.</p> <p><strong>Example</strong></p> <p>To identify a specific resource and how to access it - in all completeness</p> <pre><code>URI: mysql://localhost@databasename:password </code></pre> <p>The URL shows you where you can find the database on the internet and which protocol you should use.</p> <pre><code>URL: mysql://localhost </code></pre>
4,237,394
ASP.NET MVC 3 using Authentication
<p>How can I save something using FormsAuthentication? I don't want to store UserId through URL's.</p> <p>For example, now I have this code:</p> <pre><code>//UserController class: [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl) { if (ModelState.IsValid) { if (repository.ValidateUser(model.Login, model.Password)) { FormsAuthentication.SetAuthCookie(model.Login, model.RememberMe); if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(&quot;Project&quot;, &quot;Index&quot;); } } else { ModelState.AddModelError(&quot;&quot;, &quot;Incorrect name or password.&quot;); } } return View(model); } </code></pre> <p><code>ProjectController</code> class:</p> <pre><code>public ViewResult Index() { return View(repository.GetUserProjects( this.ControllerContext.HttpContext.User.Identity.Name)); } </code></pre> <p><code>ProjectRepository</code>:</p> <pre><code>ProjectsContext context = new ProjectsContext(); UsersContext uCnt = new UsersContext(); public IEnumerable&lt;Project&gt; GetUserProjects(String username) { if (String.IsNullOrEmpty(username)) throw new ArgumentNullException(&quot;username&quot;, &quot;Login is empty&quot;); return this.uCnt.Users .FirstOrDefault(u =&gt; u.Login == username) .Projects .ToList(); } </code></pre> <p>ProjectController and ProjectRepository don't looks like good code... Maybe someone can give advise, how to store UserID without using URL's? Best way to do this is save IDs on autorisation, I think. I don't found any properties in User.Identity to do this...</p> <h1>UPD</h1> <p>I beg a pardon, but I forgot to say that I'm using MVC-3 with Razor view. And that UserId is not a string (User.Identity.Name is a string) it could be GUID or maybe my own object...</p>
4,692,843
4
0
null
2010-11-21 10:31:43.72 UTC
29
2012-04-23 19:07:56.963 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
513,723
null
1
22
authentication|asp.net-mvc-3
31,750
<p>Save the UserID in the UserData property of the FormsAuthentication ticket in the authorization cookie when the user logs on:</p> <pre><code>string userData = userID.ToString(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.Email, DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes), createPersistentCookie, userData); string hashedTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket); HttpContext.Current.Response.Cookies.Add(cookie); </code></pre> <p>You can read it back in the PostAuthenticateRequest method in Global.asax:</p> <pre><code>HttpCookie formsCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (formsCookie != null) { FormsAuthenticationTicket auth = FormsAuthentication.Decrypt(formsCookie.Value); Guid userID = new Guid(auth.UserData); var principal = new CustomPrincipal(Roles.Provider.Name, new GenericIdentity(auth.Name), userID); Context.User = Thread.CurrentPrincipal = principal; } </code></pre> <p>Note that in this case, CustomPrincipal derives from RolePrincipal (although if you're not using Roles, I think you need to derive from GenericPrincipal), and simply adds the UserID property and overloads the constructor.</p> <p>Now, wherever you need the UserID in your app, you can do this:</p> <pre><code>if(HttpContext.Current.Request.IsAuthenticated) Guid userID = ((CustomPrincipal)HttpContext.Current.User).UserID; </code></pre>
4,597,893
Specifically, how does fork() handle dynamically allocated memory from malloc() in Linux?
<p>I have a program with a parent and a child process. Before the fork(), the parent process called malloc() and filled in an array with some data. After the fork(), the child needs that data. I know that I could use a pipe, but the following code appears to work:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;unistd.h&gt; int main( int argc, char *argv[] ) { char *array; array = malloc( 20 ); strcpy( array, &quot;Hello&quot; ); switch( fork() ) { case 0: printf( &quot;Child array: %s\n&quot;, array ); strcpy( array, &quot;Goodbye&quot; ); printf( &quot;Child array: %s\n&quot;, array ); free( array ); break; case -1: printf( &quot;Error with fork()\n&quot; ); break; default: printf( &quot;Parent array: %s\n&quot;, array ); sleep(1); printf( &quot;Parent array: %s\n&quot;, array ); free( array ); } return 0; } </code></pre> <p>The output is:</p> <pre><code>Parent array: Hello Child array: Hello Child array: Goodbye Parent array: Hello </code></pre> <p>I know that data allocated on the stack is available in the child, but it appears that data allocated on the heap is also available to the child. And similarly, the child cannot modify the parent's data on the stack, the child cannot modify the parent's data on the heap. So I assume the child gets its own copy of both stack and heap data.</p> <p>Is this always the case in Linux? If so, where the is the documentation that supports this? I checked the fork() man page, but it didn't specifically mention dynamically allocated memory on the heap.</p>
4,597,931
4
0
null
2011-01-04 20:06:14.713 UTC
9
2021-08-18 18:21:42.943 UTC
2021-08-18 18:21:42.943 UTC
null
5,459,839
null
394,336
null
1
41
c|linux|malloc|fork|heap-memory
25,157
<p>Each page that is allocated for the process (be it a virtual memory page that has the stack on it or the heap) is copied for the forked process to be able to access it.</p> <p>Actually, it is not copied right at the start, it is set to Copy-on-Write, meaning once one of the processes (parent or child) try to modify a page it is copied so that they will not harm one-another, and still have all the data from the point of fork() accessible to them.</p> <p>For example, the code pages, those the actual executable was mapped to in memory, are usually read-only and thus are reused among all the forked processes - they will not be copied again, since no one writes there, only read, and so copy-on-write will never be needed.</p> <p>More information is available <a href="http://linux.die.net/man/2/fork" rel="noreferrer">here</a> and <a href="http://en.wikipedia.org/wiki/Fork_(operating_system)" rel="noreferrer">here</a>.</p>
4,145,605
std::vector needs to have dll-interface to be used by clients of class 'X<T> warning
<p>I'm trying to make my library exportable as a DLL but I'm getting a lot of these warnings for one specific class that uses std::vector:</p> <pre><code>template &lt;typename T&gt; class AGUI_CORE_DECLSPEC AguiEvent { typedef void (*AguiCallbackFptr)(T arg, AguiWidget* sender); std::vector&lt;AguiCallbackFptr&gt; events; public: void call(AguiWidget* sender, T arg) const; void addHandler(AguiCallbackFptr proc); void removeHandler(AguiCallbackFptr proc); void removeHandler(); AguiEvent(); }; </code></pre> <p>I get warnings like these:</p> <blockquote> <p>Warning 57 warning C4251: 'AguiEvent::events' : class 'std::vector&lt;_Ty>' needs to have dll-interface to be used by clients of class 'AguiEvent'</p> </blockquote> <p>I tried to find how to do this properly but MSDN's documentation is very Windows Only, and I need this to be cross platform so that it only does MS specific stuff when AGUI_CORE_DECLSPEC is in fact defined.</p> <p>What should I do to get rid of these warnings?</p> <p>Thanks</p>
4,145,722
4
1
null
2010-11-10 14:41:52.477 UTC
8
2018-05-01 11:05:46.35 UTC
null
null
null
null
146,780
null
1
62
c++|dll
68,848
<p>Exporting from a DLL is platform-specific. You will have to <a href="https://jeffpar.github.io/kbarchive/kb/168/Q168958/" rel="noreferrer">fix this for Windows</a> (basically use <code>declspec(dllexport/dllimport)</code> on the instantiated class template) and encapsulate the required code in your Windows-specific preprocessor macro.</p> <p>My experience is that exporting STL classes from DLLs on Windows is fraught with pain, generally I try to design the interface such that this is not needed.</p>
4,397,755
MySQL: Curdate() vs Now()
<p>What is difference between MySQL <code>Curdate()</code> and <code>Now()</code>?</p>
4,397,776
4
0
null
2010-12-09 11:36:41.947 UTC
13
2017-10-31 10:50:09.333 UTC
2015-10-03 10:52:35.867 UTC
null
4,519,059
user529649
null
null
1
85
mysql|sql|datetime
119,975
<p>For questions like this, it is always worth taking a look in the manual first. <a href="http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html" rel="noreferrer">Date and time functions in the mySQL manual</a></p> <p><code>CURDATE()</code> returns the DATE part of the current time. <a href="http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_curdate" rel="noreferrer">Manual on CURDATE()</a></p> <p><code>NOW()</code> returns the date and time portions as a timestamp in various formats, depending on how it was requested. <a href="http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_now" rel="noreferrer">Manual on NOW()</a>.</p>
4,490,981
hibernate table does not exist error
<p>In configuration hibernate.cfg.xml, i add <code>&lt;property name="hibernate.hbm2ddl.auto"&gt;create&lt;/property&gt;</code> Hibernate do create table automatically when i run the application. However, i remove the table from database manually by running drop table sql. Then run the hibernate application again. The exception appear</p> <blockquote> <p>Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test.person' doesn't exist</p> </blockquote> <p>only way to fix the problem is restart the Mysql database. Could anyone explain this issue for me? </p> <p>this is my hibernate.cfg.xml</p> <pre><code>&lt;hibernate-configuration&gt; &lt;session-factory&gt; &lt;property name="hibernate.connection.driver_class"&gt; com.mysql.jdbc.Driver &lt;/property&gt; &lt;property name="hibernate.connection.url"&gt; jdbc:mysql://localhost/test &lt;/property&gt; &lt;property name="connection.username"&gt;root&lt;/property&gt; &lt;property name="connection.password"&gt;root&lt;/property&gt; &lt;property name="dialect"&gt; org.hibernate.dialect.MySQLDialect &lt;/property&gt; &lt;!-- Drop and re-create the database schema on startup --&gt; &lt;property name="hibernate.hbm2ddl.auto"&gt;create&lt;/property&gt; &lt;!-- Enable Hibernate's automatic session context management --&gt; &lt;property name="current_session_context_class"&gt;thread&lt;/property&gt; &lt;!-- Disable the second-level cache --&gt; &lt;property name="cache.provider_class"&gt;org.hibernate.cache.NoCacheProvider&lt;/property&gt; &lt;!-- Echo all executed SQL to stdout --&gt; &lt;property name="show_sql"&gt;true&lt;/property&gt; &lt;!-- Mapping files --&gt; &lt;mapping resource="com/mapping/Event.hbm.xml" /&gt; &lt;mapping resource="com/mapping/Person.hbm.xml"/&gt; &lt;/session-factory&gt; </code></pre> <p> </p> <p>Thx </p>
4,491,322
10
2
null
2010-12-20 15:18:39.743 UTC
2
2020-09-23 05:25:46.8 UTC
2010-12-20 15:42:39.89 UTC
null
380,690
null
380,690
null
1
18
hibernate
43,426
<p>I don't believe using <code>create</code> will update an in-place schema to re-add the table that you dropped. Try:</p> <pre><code>&lt;property name="hibernate.hbm2ddl.auto"&gt;update&lt;/property&gt; </code></pre> <p>This is create a schema if one doesn't exist, and attempt to modify an existing one to match the mapping you have defined.</p> <p>Also, read <a href="https://stackoverflow.com/questions/438146/hibernate-question-hbm2ddl-auto-possible-values-and-what-they-do">this question</a> about all the possible values.</p>
14,763,363
How to create equal height columns in pure CSS
<p>How to get your div to reach all the way down? How to fill up the vertical space of parent div? How to get equal length columns without using background images?</p> <p>I spent a couple days googling and dissecting code to understand how to accomplish equal length columns as easy and efficient as possible. This is the answer I came up with and I wanted to share this knowledge with the community copy and paste style in a little tutorial.</p> <p>For those that think this is a duplicate, it is not. I was inspired by several websites, among them <a href="http://matthewjamestaylor.com/blog/equal-height-columns-cross-browser-css-no-hacks">http://matthewjamestaylor.com/blog/equal-height-columns-cross-browser-css-no-hacks</a> but the code below is unique.</p>
14,763,364
2
2
null
2013-02-07 23:51:43.677 UTC
10
2015-05-31 07:51:54.097 UTC
2015-05-31 07:51:54.097 UTC
null
891,052
null
891,052
null
1
13
css|css-float|html|multiple-columns
52,549
<p>One of the tricky things in modern web design is to create a two (or more) column layout where all the columns are of equal height. I set out on a quest to find a way to do this in pure CSS.</p> <p>You can easiest accomplish this by using a background image in a wrap-div that holds both of your columns (or the background of the page).</p> <p>You can also do this by using CSS table cells, but unfortunately the browser support for this is still shady, so it's not a preferred solution. Read on, there is a better way.</p> <p>I found my inspiration from two pages on the web, although I prefer my solution, since it gives me more freedom to use rounded corners and precise widths or percent layouts, and it is easier to edit, your final layout holding div is not forcing you to do negative number crunching.</p> <p><strong>== The trick: ==</strong></p> <p>First you create the background design cols, then you put a full width div that can hold your regular content. The trick is all about floated columns within columns, creating a push effect on all parent columns when the content extends in length, no matter what end column is the longest.</p> <p>In this example I will use a 2 column grid in a centered wrap-div with rounded corners. I have tried to keep the fluff out for easy copy-paste.</p> <p><strong>== Step 1 ==</strong></p> <p>Create your basic web page.</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>== Step 2 ==</strong></p> <p>Create one floated div inside another floated div. Then apply a negative margin on the inside div to pop it out of its frame visually. I added dotted borders for illustrating purposes. Know that if you float the outside div to the left and give the inside div a negative margin to the left, the inside div will go under the page edge without giving you a scroll bar.</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; #rightsideBG{ float:right; background:silver; width:300px; border: 3px dotted silver; /*temporary css*/ } #leftsideBG{ float:left; background:gold; width:100px; margin-left:-100px; border: 3px dotted gold; /*temporary css*/ } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="rightsideBG"&gt; &lt;div id="leftsideBG"&gt; this content obviously only fits the left column for now. &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>== Step 3 ==</strong></p> <p>In the inside div: Create a div without background that has the with of all the columns combined. It will push over the edge of the inside div. I added a dotted border for illustrating purposes.This will be the canvas for your content.</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; #rightsideBG{ float:right; background:silver; width:300px; border: 3px dotted silver; /*temporary css*/ } #leftsideBG{ float:left; background:gold; width:100px; margin-left:-100px; border: 3px dotted gold; /*temporary css*/ } #overbothsides{ float:left; width:400px; border: 3px dotted black; /*temporary css*/ } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="rightsideBG"&gt; &lt;div id="leftsideBG"&gt; &lt;div id="overbothsides"&gt; this content spans over both columns now. &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>== Step 4 ==</strong></p> <p>Add your content. In this example I place two divs that are positioned over the layout. I also took away the dotted borders. Presto, that's it. You can use this code if you like.</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; #rightsideBG{ float:right; background:silver; width:300px; } #leftsideBG{ float:left; background:gold; width:100px; margin-left:-100px; } #overbothsides{ float:left; width:400px; } #leftcol{ float:left; width:80px; padding: 10px; } #rightcol{ float:left; width:280px; padding: 10px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="rightsideBG"&gt; &lt;div id="leftsideBG"&gt; &lt;div id="overbothsides"&gt; &lt;div id="leftcol"&gt;left column content&lt;/div&gt; &lt;div id="rightcol"&gt;right column content&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>== Step 5 ==</strong></p> <p>To make it nicer you can centered the whole design in a wrap div and give it rounded corners. The rounded corners wont show in old IE unless you use a special fix for that.</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; #wrap{ position:relative; width:500px; margin:20px auto; -webkit-border-bottom-right-radius: 20px; -moz-border-radius-bottomright: 20px; border-bottom-right-radius: 20px; } #rightsideBG{ float:right; background:silver; width:300px; } #leftsideBG{ float:left; background:gold; width:100px; margin-left:-100px; } #overbothsides{ float:left; width:400px; } #leftcol{ float:left; width:80px; padding: 10px; } #rightcol{ float:left; width:280px; padding: 10px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrap"&gt; &lt;div id="rightsideBG"&gt; &lt;div id="leftsideBG"&gt; &lt;div id="overbothsides"&gt; &lt;div id="leftcol"&gt;left column content&lt;/div&gt; &lt;div id="rightcol"&gt;right column content&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>== Inspiration sources ==</strong></p> <ul> <li><a href="http://www.pmob.co.uk/pob/equal-columns.htm" rel="noreferrer">http://www.pmob.co.uk/pob/equal-columns.htm</a></li> <li><a href="http://matthewjamestaylor.com/blog/equal-height-columns-2-column.htm" rel="noreferrer">http://matthewjamestaylor.com/blog/equal-height-columns-2-column.htm</a></li> </ul>
14,614,512
Merging two tables with millions of rows in Python
<p>I am using Python for some data analysis. I have two tables, the first (let's call it 'A') has 10 million rows and 10 columns and the second ('B') has 73 million rows and 2 columns. They have 1 column with common ids and I want to intersect the two tables based on that column. In particular I want the inner join of the tables.</p> <p>I could not load the table B on memory as a pandas dataframe to use the normal merge function on pandas. I tried by reading the file of table B on chunks, intersecting each chunk with A and the concatenating these intersections (output from inner joins). This is OK on speed but every now and then this gives me problems and spits out a segmentation fault ... no so great. This error is difficult to reproduce, but it happens on two different machines (Mac&nbsp;OS&nbsp;X&nbsp;v10.6 (Snow&nbsp;Leopard) and UNIX, Red Hat Linux).</p> <p>I finally tried with the combination of Pandas and PyTables by writing table B to disk and then iterating over table A and selecting from table B the matching rows. This last options works but it is slow. Table B on pytables has been indexed already by default.</p> <p>How do I tackle this problem?</p>
14,617,925
1
2
null
2013-01-30 21:51:56.04 UTC
9
2017-07-06 18:22:11.397 UTC
2017-07-06 18:16:47.173 UTC
null
63,550
null
2,027,051
null
1
13
python|join|merge|pandas|pytables
24,448
<p>This is a little pseudo codish, but I think should be quite fast.</p> <p>Straightforward disk based merge, with all tables on disk. The key is that you are not doing selection per se, just indexing into the table via start/stop, which is quite fast.</p> <p>Selecting the rows that meet a criteria in B (using A's ids) won't be very fast, because I think it might be bringing the data into Python space rather than an in-kernel search (I am not sure, but you might want to investigate on pytables.org more in the in-kernel optimization section. There is a way to tell if it's going to be in-kernel or not).</p> <p>Also if you are up to it, this is a very parallel problem (just don't write the results to the same file from multiple processes. pytables is not write-safe for that).</p> <p>See <a href="https://stackoverflow.com/questions/20217417/what-are-some-alternatives-for-overcoming-a-merge-fail-in-pandas-that-is-to-big">this answer</a> for a comment on how doing a join operation will actually be an 'inner' join.</p> <p>For your merge_a_b operation I think you can use a standard pandas join which is quite efficient (when in-memory).</p> <p>One other option (depending on how 'big' A) is, might be to separate A into 2 pieces (that are indexed the same), using a smaller (maybe use single column) in the first table; instead of storing the merge results per se, store the row index; later you can pull out the data you need (kind of like using an indexer and take). See <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#multiple-table-queries" rel="nofollow noreferrer">http://pandas.pydata.org/pandas-docs/stable/io.html#multiple-table-queries</a></p> <pre><code>A = HDFStore('A.h5') B = HDFStore('B.h5') nrows_a = A.get_storer('df').nrows nrows_b = B.get_storer('df').nrows a_chunk_size = 1000000 b_chunk_size = 1000000 def merge_a_b(a,b): # Function that returns an operation on passed # frames, a and b. # It could be a merge, join, concat, or other operation that # results in a single frame. for a in xrange(int(nrows_a / a_chunk_size) + 1): a_start_i = a * a_chunk_size a_stop_i = min((a + 1) * a_chunk_size, nrows_a) a = A.select('df', start = a_start_i, stop = a_stop_i) for b in xrange(int(nrows_b / b_chunk_size) + 1): b_start_i = b * b_chunk_size b_stop_i = min((b + 1) * b_chunk_size, nrows_b) b = B.select('df', start = b_start_i, stop = b_stop_i) # This is your result store m = merge_a_b(a, b) if len(m): store.append('df_result', m) </code></pre>
14,593,291
Xcode 4.6 zXing compile error after Xcode update (4H127)
<p>Different projects using ZXing have error after last Xcode update:</p> <p>Error messages are:</p> <ol> <li>private field 'cached_y_' is not used</li> <li>Private field 'bits_' is not used</li> <li>Private field 'cached_row_num_' is not used</li> <li>Private field 'dataHeight_' is not used</li> </ol> <p>Any compiler flag I have to set up? </p>
14,703,794
4
6
null
2013-01-29 22:33:35.937 UTC
9
2013-02-22 07:31:08.73 UTC
2013-02-22 07:31:08.73 UTC
null
762,913
null
148,988
null
1
16
ios|xcode|ios-simulator|zxing|xcode4.6
7,043
<p>Just add this flag</p> <pre><code>-Wno-unused-private-field </code></pre> <p>under ZXingWidget target -> Build Settings -> Other Warning Flags. Click the + button and paste the flag, clean and build again.</p> <p><img src="https://i.stack.imgur.com/dTvXs.png" alt="How to set compiler flags"></p> <p>(No need to remove any other flag, just ignore unused private field warning)</p>
14,871,272
Plotting using a CSV file
<p>I have a csv file which has 5 entries on every row. Every entry is whether a network packet is triggered or not. The last entry in every row is the size of packet. Every row = time elapsed in ms.</p> <p>e.g. row </p> <pre><code>1 , 0 , 1 , 2 , 117 </code></pre> <p>How do I plot a graph for e.g. where x axis is the row number and y is the value for e.g. 1st entry in every row?</p>
14,871,346
2
0
null
2013-02-14 09:12:50.217 UTC
14
2018-07-26 00:02:55.55 UTC
2015-09-08 11:07:45.99 UTC
null
1,799,272
user494461
null
null
1
65
csv|graph|gnuplot
150,833
<p>This should get you started:</p> <pre><code>set datafile separator "," plot 'infile' using 0:1 </code></pre>
2,688,659
How do I create a UIViewController programmatically?
<p>I am working in a app where i have data in <code>UITableView</code>. It is like a drill down application. User will click on a row and will go to next page showing more records in a <code>UITableView</code>. But problem in my case is that i dont know upto how many level user can drill. The number of levels are not fixed. So now i am thinking to create and add the viewcontrollers programmatically. Is it possible?? if yes how? thanks in advance.</p>
2,688,774
2
0
null
2010-04-22 06:32:22.703 UTC
2
2012-05-31 06:40:51.353 UTC
2010-04-22 07:17:56.447 UTC
null
19,410
null
260,056
null
1
21
iphone|uitableview|uiviewcontroller
50,100
<pre><code>UIViewController *controller = [[UIViewController alloc] init]; controller.view = whateverViewYouHave; </code></pre> <p>Do you have your own view controller that you coded? In that case you probably don't need to set the view property as it has been set in IB if that is what you used. When you have your controller you can push it onto the navigationController or view it modally etc.</p>
2,632,425
How do I start Maven "compile" goal on save in Eclipse?
<p>I have a Maven project with JavaScript code. There is a special javascript compiler plugin connected to the compile goal in the pom.xml. So when I type "mvn compile" then the JavaScript sources in src/main/javascript are compiled (compressed and obfuscated) and saved into the target/classes directory. On the command line this works great.</p> <p>But now I want to make the development easier by using Eclipse with the m2eclipse plugin. I want Eclipse to call the compile goal whenever I change a JavaScript file. How can I do this? When I save a JavaScript file then I just see a "AUTO_BUILD" logging line in the maven console and that's it.</p> <p>In the project preferences it is possible to configure a lifecycle mapping. But for some reason I can only add custom goals to "after clean" and "on resource changed". When I add the "compile" goal to the "resource changed" lifecycle mapping, then the JavaScript files are compiled when I change a resource. So I could put my JavaScript files into the resources folder instead and it would work but this sounds pretty ugly.</p> <p>It is also working when I tell Eclipse to "clean" my project. Then the compile goal target is called. So the functionality is all there I just want to have it executed when I save a JavaScript file. This must be possible somehow, or not?</p> <p>Any hints?</p>
2,633,133
2
0
null
2010-04-13 19:06:08.923 UTC
15
2015-11-04 13:13:58.093 UTC
2012-12-17 17:18:51.22 UTC
null
5,849
null
274,473
null
1
26
eclipse|maven-2|m2eclipse
57,448
<blockquote> <p>In the project preferences it is possible to configure a lifecycle mapping. But for some reason I can only add custom goals to "after clean" and "on resource changed". When I add the "compile" goal to the "resource changed" lifecycle mapping, then the JavaScript files are compiled when I change a resource. So I could put my JavaScript files into the resources folder instead and it would work but this sounds pretty ugly.</p> </blockquote> <p>As you've noticed, the default goals run on incremental builds in Eclipse are <code>process-resources</code> and <code>resources:testResources</code>. Personally, I don't find ugly to put js file under resources and I would just bind the javascript plugin on <code>process-resources</code>.</p> <blockquote> <p>It is also working when I tell Eclipse to "clean" my project. Then the compile goal target is called.</p> </blockquote> <p>On full build (after a clean from Eclipse), goals run are <code>process-test-resources</code> which is actually a build lifecycle phase that includes the <code>compile</code> phase, that's why <code>compile</code> get called when you clean your project from Eclipse. But this doesn't solve your issue (running your plugin on save).</p> <hr> <p>As I said, I would just put the js file under resources. But there is maybe another option: adding another Builder to the project. <strong>Right-click</strong> on your project, then <strong>Properties > Builders > New > Maven Build</strong> and define your plugin goal as goal to run during <strong>Auto Build Goals</strong> (change or remove the other goals to suit your needs):</p> <p><a href="http://img694.imageshack.us/img694/2382/screenshot003wo.png">alt text http://img694.imageshack.us/img694/2382/screenshot003wo.png</a></p> <p>But I prefer the other approach.</p>
2,847,575
How-To Integrate IIS 7 Web Deploy with MSBuild (TeamCity)
<p>How-To Integrate IIS 7 Web Deploy with MSBuild (TeamCity) ?</p>
5,305,223
2
0
null
2010-05-17 08:28:34.69 UTC
32
2019-08-04 16:51:44.363 UTC
null
null
null
null
50,974
null
1
41
.net|msbuild|teamcity
16,930
<p>Troy Hunt has an excellent <a href="http://www.troyhunt.com/2010/11/you-deploying-it-wrong-teamcity.html" rel="noreferrer">5-part blog series</a> that goes over this topic in detail.</p> <p>He has effectively compiled all of the other resources out there and turned them into a tutorial.</p> <p>It's the clearest (and believe it or not, the most concise) way to do what you want.</p>
2,812,622
Get Google Chrome's root bookmarks folder
<p>I'm trying to write a better bookmark manager in Chrome extensions. The problem is that there are no simple examples (that I can find) about how to actually use the <a href="https://developer.chrome.com/extensions/bookmarks" rel="noreferrer"><code>bookmarks</code> API</a>.</p> <p>I've looked at the example source (when I d/led and installed it on my computer it didn't do anything except provide a search box. Typing/typing and pressing return failed to do anything) and can't find anything useful.</p> <p>My ultimate goal is to make an extension that allows me to save pages to come and read later <strong>without</strong> having to go sign up for an account on some service somewhere. So I plan to create either one or two bookmark folders in the root folder/other bookmarks - at minimum an "unread pages" folder. In that folder I'll create the unread bookmarks. When the user marks the item as read, it will be removed from that folder.</p> <p>So that's what I'm trying to do... any help will be greatly appreciated, even if it's just pointing me to some good examples.</p> <p>UPDATE:</p> <pre class="lang-html prettyprint-override"><code>...&lt;script&gt; function display(tree){ document.getElementById("Output").innerHTML = tree; } function start(){ chrome.bookmarks.getTree(display); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h4 id="Output"&gt;&lt;/h4&gt; &lt;script&gt; start(); &lt;/script&gt; ... </code></pre> <p>That displays <code>[object Object]</code>, that suggests (at least to me with a limited JavaScript experience) that an object exists. But how to access the members of that object?</p> <p>Changing <code>tree</code> to <code>tree.id</code> or any other of what look to be parameters displays <code>undefined</code>.</p>
2,815,066
3
0
null
2010-05-11 16:42:51.537 UTC
12
2016-03-19 22:32:43.043 UTC
2016-03-19 22:32:43.043 UTC
null
934,239
null
344,286
null
1
9
javascript|google-chrome|google-chrome-extension|bookmarks
15,687
<p>Currently, there is no good way to find folders such as "Other Bookmarks" or "Bookmarks Bar" in the bookmarks API. You would have to iterate through all the bookmarks and find which node has those root folders and save its bookmark id. The bug is filed <a href="http://code.google.com/p/chromium/issues/detail?id=21330" rel="noreferrer">Issue 21330</a>.</p> <p>The root id is always 0, and when I mean 0, it corresponds to "Bookmarks bar" and "Other bookmarks". As any tree structure, each node has children. If you want to fetch all the bookmarks under one folder, you can use getChildren API and get every node recursively (you can do it iteratively too). For example, the following will get every single bookmark:</p> <pre><code>printBookmarks('0'); function printBookmarks(id) { chrome.bookmarks.getChildren(id, function(children) { children.forEach(function(bookmark) { console.debug(bookmark.title); printBookmarks(bookmark.id); }); }); } </code></pre> <p>Now, why do we have to call the API for every iteration? Their is an API to get the whole Tree. If you tried it out, you will see that every node in the getTree will have a list of children. That is perfect:</p> <pre><code>chrome.bookmarks.getTree(function(bookmarks) { printBookmarks(bookmarks); }); function printBookmarks(bookmarks) { bookmarks.forEach(function(bookmark) { console.debug(bookmark.id + ' - ' + bookmark.title + ' - ' + bookmark.url); if (bookmark.children) printBookmark(bookmark.children); }); } </code></pre> <p>That is all, you can do all this iteratively as well which is better performance, but you can figure that out :) Note that since you want to redo the bookmarks bar, you can override that page in extensions (soon): <a href="http://code.google.com/chrome/extensions/override.html" rel="noreferrer">http://code.google.com/chrome/extensions/override.html</a></p> <p>If you want to show a nice HTML tree of your bookmarks, you can easily do that by extending the getTree functionality I showed above to accept a parent DOM. You can do something <a href="http://src.chromium.org/viewvc/chrome/trunk/src/chrome/test/data/extensions/samples/bookmarks/bookmark_view.html?revision=18056&amp;view=markup&amp;pathrev=18056" rel="noreferrer">like this</a>. Edit the code to make use of the getTree or collapse everything and make use of the getChildren and fetch more bookmarks if they request it.</p>
31,515,776
How can I catch UniqueKey Violation exceptions with EF6 and SQL Server?
<p>One of my tables have a unique key and when I try to insert a duplicate record it throws an exception as expected. But I need to distinguish unique key exceptions from others, so that I can customize the error message for unique key constraint violations.</p> <p>All the solutions I've found online suggests to cast <code>ex.InnerException</code> to <code>System.Data.SqlClient.SqlException</code> and check the if <code>Number</code> property is equal to 2601 or 2627 as follows:</p> <pre><code>try { _context.SaveChanges(); } catch (Exception ex) { var sqlException = ex.InnerException as System.Data.SqlClient.SqlException; if (sqlException.Number == 2601 || sqlException.Number == 2627) { ErrorMessage = "Cannot insert duplicate values."; } else { ErrorMessage = "Error while saving data."; } } </code></pre> <p>But the problem is, casting <code>ex.InnerException</code> to <code>System.Data.SqlClient.SqlException</code> causes invalid cast error since <code>ex.InnerException</code> is actually type of <code>System.Data.Entity.Core.UpdateException</code>, not <code>System.Data.SqlClient.SqlException</code>.</p> <p>What is the problem with the code above? How can I catch Unique Key Constraint violations?</p>
31,516,402
8
0
null
2015-07-20 11:50:30.763 UTC
19
2021-09-11 09:19:44.823 UTC
null
null
null
null
1,412,786
null
1
71
c#|sql-server|exception-handling|entity-framework-6|unique-key
72,813
<p>With EF6 and the <code>DbContext</code> API (for SQL Server), I'm currently using this piece of code:</p> <pre><code>try { // Some DB access } catch (Exception ex) { HandleException(ex); } public virtual void HandleException(Exception exception) { if (exception is DbUpdateConcurrencyException concurrencyEx) { // A custom exception of yours for concurrency issues throw new ConcurrencyException(); } else if (exception is DbUpdateException dbUpdateEx) { if (dbUpdateEx.InnerException != null &amp;&amp; dbUpdateEx.InnerException.InnerException != null) { if (dbUpdateEx.InnerException.InnerException is SqlException sqlException) { switch (sqlException.Number) { case 2627: // Unique constraint error case 547: // Constraint check violation case 2601: // Duplicated key row error // Constraint violation exception // A custom exception of yours for concurrency issues throw new ConcurrencyException(); default: // A custom exception of yours for other DB issues throw new DatabaseAccessException( dbUpdateEx.Message, dbUpdateEx.InnerException); } } throw new DatabaseAccessException(dbUpdateEx.Message, dbUpdateEx.InnerException); } } // If we're here then no exception has been thrown // So add another piece of code below for other exceptions not yet handled... } </code></pre> <p>As you mentioned <code>UpdateException</code>, I'm assuming you're using the <code>ObjectContext</code> API, but it should be similar.</p>
49,900,629
Django serializer inherit and extend fields
<p>I have these 2 serializers:</p> <pre><code>class BasicSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('lengthy', 'touple', 'of', \ 'fields', 'like', '10', 'of', 'them') class AdvandedSerializer(BasicSerializer): additional_field = serializers.SerializerMethodField() def get_additional_field(self, obj): return('not important') class Meta: model = MyModel fields = ('lengthy', 'touple', 'of', \ 'fields', 'like', '10', 'of', 'them', 'additional_field') </code></pre> <p>This is obviously rather ugly code. I would like to get and extend the <code>fields</code> touple from <code>super()</code>, however I have no idea how.</p>
49,901,198
2
0
null
2018-04-18 13:11:37.04 UTC
9
2018-04-18 13:42:06.62 UTC
null
null
null
null
4,507,367
null
1
53
django
18,802
<p>You can do:</p> <pre><code>class BasicSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('lengthy', 'touple', 'of', 'fields', 'like', '10', 'of', 'them') class AdvandedSerializer(BasicSerializer): additional_field = serializers.SerializerMethodField() def get_additional_field(self, obj): return('not important') class Meta(BasicSerializer.Meta): fields = BasicSerializer.Meta.fields + ('additional_field',) </code></pre>
42,821,330
Restore original text from Keras’s imdb dataset
<p>Restore original text from Keras’s imdb dataset</p> <p>I want to restore imdb’s original text from Keras’s imdb dataset.</p> <p>First, when I load Keras’s imdb dataset, it returned sequence of word index.</p> <p> <pre><code>&gt;&gt;&gt; (X_train, y_train), (X_test, y_test) = imdb.load_data() &gt;&gt;&gt; X_train[0] [1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 22665, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 21631, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2025, 19, 14, 22, 4, 1920, 4613, 469, 4, 22, 71, 87, 12, 16, 43, 530, 38, 76, 15, 13, 1247, 4, 22, 17, 515, 17, 12, 16, 626, 18, 19193, 5, 62, 386, 12, 8, 316, 8, 106, 5, 4, 2223, 5244, 16, 480, 66, 3785, 33, 4, 130, 12, 16, 38, 619, 5, 25, 124, 51, 36, 135, 48, 25, 1415, 33, 6, 22, 12, 215, 28, 77, 52, 5, 14, 407, 16, 82, 10311, 8, 4, 107, 117, 5952, 15, 256, 4, 31050, 7, 3766, 5, 723, 36, 71, 43, 530, 476, 26, 400, 317, 46, 7, 4, 12118, 1029, 13, 104, 88, 4, 381, 15, 297, 98, 32, 2071, 56, 26, 141, 6, 194, 7486, 18, 4, 226, 22, 21, 134, 476, 26, 480, 5, 144, 30, 5535, 18, 51, 36, 28, 224, 92, 25, 104, 4, 226, 65, 16, 38, 1334, 88, 12, 16, 283, 5, 16, 4472, 113, 103, 32, 15, 16, 5345, 19, 178, 32] </code></pre> <p>I found imdb.get_word_index method(), it returns word index dictionary like {‘create’: 984, ‘make’: 94,…}. For converting, I create index word dictionary. <pre><code>&gt;&gt;&gt; word_index = imdb.get_word_index() &gt;&gt;&gt; index_word = {v:k for k,v in word_index.items()} </code></pre> <p>Then, I tried to restore original text like following.</p> <p> <pre><code>&gt;&gt;&gt; ' '.join(index_word.get(w) for w in X_train[5]) "the effort still been that usually makes for of finished sucking ended cbc's an because before if just though something know novel female i i slowly lot of above freshened with connect in of script their that out end his deceptively i i" </code></pre> <p>I’m not good at English, but I know this sentence is something strange.</p> <p>Why is this happened? How can I restore original text?</p>
44,891,281
9
0
null
2017-03-15 21:49:19.953 UTC
7
2021-03-13 22:24:13.21 UTC
2017-07-12 08:30:30.7 UTC
null
5,974,433
null
7,233,229
null
1
40
python|machine-learning|neural-network|nlp|keras
15,113
<p>Your example is coming out as gibberish, it's much worse than just some missing stop words.</p> <p>If you re-read the docs for the <code>start_char</code>, <code>oov_char</code>, and <code>index_from</code> parameters of the [<code>keras.datasets.imdb.load_data</code>](<a href="https://keras.io/datasets/#imdb-movie-reviews-sentiment-classification" rel="noreferrer">https://keras.io/datasets/#imdb-movie-reviews-sentiment-classification</a> ) method they explain what is happening:</p> <p><code>start_char</code>: int. The start of a sequence will be marked with this character. Set to 1 because 0 is usually the padding character.</p> <p><code>oov_char</code>: int. words that were cut out because of the num_words or skip_top limit will be replaced with this character.</p> <p><code>index_from</code>: int. Index actual words with this index and higher.</p> <p>That dictionary you inverted assumes the word indices start from <code>1</code>.</p> <p>But the indices returned my keras have <code>&lt;START&gt;</code> and <code>&lt;UNKNOWN&gt;</code> as indexes <code>1</code> and <code>2</code>. (And it assumes you will use <code>0</code> for <code>&lt;PADDING&gt;</code>).</p> <p>This works for me:</p> <pre><code>import keras NUM_WORDS=1000 # only use top 1000 words INDEX_FROM=3 # word index offset train,test = keras.datasets.imdb.load_data(num_words=NUM_WORDS, index_from=INDEX_FROM) train_x,train_y = train test_x,test_y = test word_to_id = keras.datasets.imdb.get_word_index() word_to_id = {k:(v+INDEX_FROM) for k,v in word_to_id.items()} word_to_id["&lt;PAD&gt;"] = 0 word_to_id["&lt;START&gt;"] = 1 word_to_id["&lt;UNK&gt;"] = 2 word_to_id["&lt;UNUSED&gt;"] = 3 id_to_word = {value:key for key,value in word_to_id.items()} print(' '.join(id_to_word[id] for id in train_x[0] )) </code></pre> <p>The punctuation is missing, but that's all:</p> <pre><code>"&lt;START&gt; this film was just brilliant casting &lt;UNK&gt; &lt;UNK&gt; story direction &lt;UNK&gt; really &lt;UNK&gt; the part they played and you could just imagine being there robert &lt;UNK&gt; is an amazing actor ..." </code></pre>
27,389,954
How to re-send external tester invitations on Apple's TestFlight service
<p>Is there a way to re-send an invitation to an external tester on Apple's TestFlight Beta Testing service?</p> <p>(I am referring to facility for external beta testing accessed via iTunes Connect, not to the standalone TestFlight service that has been provided since before Apple acquired it.)</p> <p>Within iTunes Connect, under My Apps / Prerelease / External Testers, the tester's status just shows itself as "Invited". Unfortunately, this tester had a hyperactive spam filter that simply deletes all spam, so he cannot access the original invitation. And I cannot find any control on the TestFlight UI to re-send it. I have tried turning testing off and on, but this doesn't seem to help.</p>
27,390,153
5
0
null
2014-12-09 22:20:13.19 UTC
18
2017-04-29 13:01:30.663 UTC
null
null
null
null
577,888
null
1
101
ios|app-store-connect|testflight
66,928
<p>Try removing the tester and re-adding them:</p> <p>Click the 'edit' button at to top-right of the testers table, and remove the tester:</p> <p><img src="https://i.stack.imgur.com/1Goto.png" alt="enter image description here"></p> <p>Then add them back. This should resend the invite email.</p> <p>// UPDATE: The interface has changed somewhat, though the process remains the same. Now after removing the external user, you must hit "save". Then add them, and hit "save" again.</p>
39,156,293
Jackson deserialize extra fields as Map
<p>I'm looking to deserialize any unknown fields in a JSON object as entries in a <code>Map</code> which is a member of a POJO.</p> <p>For example, here is the JSON:</p> <pre><code>{ &quot;knownField&quot; : 5, &quot;unknownField1&quot; : &quot;926f7c2f-1ae2-426b-9f36-4ba042334b68&quot;, &quot;unknownField2&quot; : &quot;ed51e59d-a551-4cdc-be69-7d337162b691&quot; } </code></pre> <p>Here is the POJO:</p> <pre><code>class MyObject { int knownField; Map&lt;String, UUID&gt; unknownFields; // getters/setters whatever } </code></pre> <p>Is there a way to configure this with Jackson? If not, is there an effective way to write a <code>StdDeserializer</code> to do it (assume the values in <code>unknownFields</code> can be a more complex but well known consistent type)?</p>
40,926,692
1
0
null
2016-08-25 23:35:56.98 UTC
8
2021-01-30 18:52:27.073 UTC
2021-01-30 18:52:27.073 UTC
null
294,317
null
2,133,111
null
1
45
java|json|jackson|deserialization
14,903
<p>There is a feature and an annotation exactly fitting this purpose. </p> <p>I tested and it works with UUIDs like in your example:</p> <pre><code>class MyUUIDClass { public int knownField; Map&lt;String, UUID&gt; unknownFields = new HashMap&lt;&gt;(); // Capture all other fields that Jackson do not match other members @JsonAnyGetter public Map&lt;String, UUID&gt; otherFields() { return unknownFields; } @JsonAnySetter public void setOtherField(String name, UUID value) { unknownFields.put(name, value); } } </code></pre> <p>And it would work like this:</p> <pre><code> MyUUIDClass deserialized = objectMapper.readValue("{" + "\"knownField\": 1," + "\"foo\": \"9cfc64e0-9fed-492e-a7a1-ed2350debd95\"" + "}", MyUUIDClass.class); </code></pre> <p>Also more common types like Strings work:</p> <pre><code>class MyClass { public int knownField; Map&lt;String, String&gt; unknownFields = new HashMap&lt;&gt;(); // Capture all other fields that Jackson do not match other members @JsonAnyGetter public Map&lt;String, String&gt; otherFields() { return unknownFields; } @JsonAnySetter public void setOtherField(String name, String value) { unknownFields.put(name, value); } } </code></pre> <p>(<a href="https://blog.layer4.fr/2013/08/19/how-to-map-unknown-json-properties-with-jackson/" rel="noreferrer">I found this feature in this blog post first</a>).</p>
2,692,048
What are the differences between plug-ins, features, and products in Eclipse RCP?
<p>What are the differences? What gets used for which purpose?</p>
2,692,822
1
0
null
2010-04-22 15:14:11.093 UTC
32
2019-11-01 17:59:04.7 UTC
2013-11-06 15:56:04.56 UTC
null
2,282,562
null
66,686
null
1
79
eclipse|plugins|rcp|product
32,756
<p>As the <strong><a href="http://www.vogella.com/articles/EclipseRCP/article.html" rel="noreferrer">RCP tutorial</a></strong> details</p> <blockquote> <p>Plugins are the smallest deployable and installable software components of Eclipse.</p> <p>Each plugin can define extension-points which define possibilities for functionality contributions (code and non-code) by other plugins. Non-code functionality contributions can, for example, provide help content.</p> <p>The basis for this architecture is the runtime environment Equinox of Eclipse which is the reference implementation of OSGI. See <a href="http://www.vogella.com/articles/OSGi/article.html" rel="noreferrer">OSGi development - Tutorial</a> for details.<br /> The Plugin concept of Eclipse is the same as the bundle concept of OSGI. Generally speaking a OSGI bundle equals a Plugin and vice-versa.</p> </blockquote> <p><img src="https://i.stack.imgur.com/X4img.png" alt="first rcp" /></p> <hr /> <p>The <strong><a href="http://www.vogella.com/articles/EclipseFeatureProject/article.html" rel="noreferrer">Feature Tutorial</a></strong> mentions</p> <blockquote> <p>A feature project is basically a <strong>list of plugins and other features which can be understood as a logical separate unit</strong>.</p> <p>Eclipse uses feature projects for the updates manager and for the build process. You can also supply a software license with a feature</p> </blockquote> <p><img src="https://i.stack.imgur.com/fwmmG.png" alt="new feature" /></p> <hr /> <p>Finally, a <strong><a href="http://help.eclipse.org/galileo/index.jsp?topic=/org.eclipse.pde.doc.user/concepts/product.htm" rel="noreferrer">product</a></strong> is a stand-alone program built with the Eclipse platform. A product may optionally be packaged and delivered as one or more features, which are simply groupings of plug-ins that are managed as a single entity by the Eclipse update mechanisms.</p> <p><img src="https://i.stack.imgur.com/EmfVT.png" alt="Product definition file show the overview tab" /></p> <hr /> <p>So:</p> <p><strong>plugins can be grouped into features which can be packaged as one executable unit called product</strong>.</p>
50,764,572
How can I test a .tflite model to prove that it behaves as the original model using the same Test Data?
<p>I have generated a .tflite model based on a trained model, I would like to test that the tfilte model gives the same results as the original model.</p> <p>Giving both the same test data and obtaining the same result.</p>
51,987,281
3
0
null
2018-06-08 16:08:34.517 UTC
7
2020-06-12 22:22:13.003 UTC
2018-06-08 20:13:44.93 UTC
null
606,314
null
9,899,807
null
1
30
python|tensorflow|tensorflow-lite
28,989
<p>You may use <strong><em>TensorFlow Lite Python interpreter</em></strong> to test your tflite model. </p> <p>It allows you to feed input data in python shell and read the output directly like you are just using a normal tensorflow model. </p> <p>I have answered this question <a href="https://stackoverflow.com/a/51986982/7413964">here</a>.</p> <p>And you can read this <a href="https://www.tensorflow.org/lite/guide/inference#load_and_run_a_model_in_python" rel="noreferrer"><strong>TensorFlow lite official guide</strong></a> for detailed information.</p> <p>You can also use <a href="https://github.com/lutzroeder/Netron" rel="noreferrer">Netron</a> to visualize your model. It allows you to load your .tflite file directly and inspect your model architecture and model weights. </p>
42,029,347
Position a SceneKit object in front of SCNCamera's current orientation
<p>I would like to create a new SceneKit node when the user taps the screen, and have it appear directly in front of the camera at a set distance. For testing, this will be a SCNText reads reads "you tapped here". It should also be at right angles to the line of sight - that is, "face on" to the camera.</p> <p>So, given the <code>self.camera.orientation</code> SCNVector4 (or similar), how can I:</p> <ol> <li>produce the SCNVector3 that puts the node in "front" of the camera at a given distance?</li> <li>produce the SCNVector4 (or SCNQuaternion) that orients the node so it is "facing" the camera?</li> </ol> <p>I suspect that the answer to (2) is that it's the same as the `self.camera.orientation? But (1) has me a little lost.</p> <p>I see a number of similar questions, like <a href="https://stackoverflow.com/questions/39402064/scenekit-use-transform-or-directly-manipulate-rotation-position-properties-if-g">this one</a>, but no answers.</p>
50,657,180
5
0
null
2017-02-03 17:02:17.593 UTC
18
2021-06-16 01:14:18.283 UTC
2017-05-23 12:10:05.507 UTC
null
-1
null
1,469,457
null
1
18
swift3|scenekit
26,176
<p><strong>(Swift 4)</strong></p> <p>Hey, you can use this simpler function if you want to put the object a certain position relative to another node (e.g. the camera node) and also in the same orientation as the reference node:</p> <pre><code>func updatePositionAndOrientationOf(_ node: SCNNode, withPosition position: SCNVector3, relativeTo referenceNode: SCNNode) { let referenceNodeTransform = matrix_float4x4(referenceNode.transform) // Setup a translation matrix with the desired position var translationMatrix = matrix_identity_float4x4 translationMatrix.columns.3.x = position.x translationMatrix.columns.3.y = position.y translationMatrix.columns.3.z = position.z // Combine the configured translation matrix with the referenceNode's transform to get the desired position AND orientation let updatedTransform = matrix_multiply(referenceNodeTransform, translationMatrix) node.transform = SCNMatrix4(updatedTransform) } </code></pre> <p>If you'd like to put 'node' 2m right in front of a certain 'cameraNode', you'd call it like:</p> <pre><code>let position = SCNVector3(x: 0, y: 0, z: -2) updatePositionAndOrientationOf(node, withPosition: position, relativeTo: cameraNode) </code></pre> <p><strong>Edit: Getting the camera node</strong></p> <p>To get the camera node, it depends if you're using SceneKit, ARKit, or other framework. Below are examples for ARKit and SceneKit.</p> <p>With ARKit, you have ARSCNView to render the 3D objects of an SCNScene overlapping the camera content. You can get the camera node from ARSCNView's pointOfView property:</p> <pre><code>let cameraNode = sceneView.pointOfView </code></pre> <p>For SceneKit, you have an SCNView that renders the 3D objects of an SCNScene. You can create camera nodes and position them wherever you want, so you'd do something like:</p> <pre><code>let scnScene = SCNScene() // (Configure scnScene here if necessary) scnView.scene = scnScene let cameraNode = SCNNode() cameraNode.camera = SCNCamera() cameraNode.position = SCNVector3(0, 5, 10) // For example scnScene.rootNode.addChildNode(cameraNode) </code></pre> <p>Once a camera node has been setup, you can access the current camera in the same way as ARKit:</p> <pre><code>let cameraNode = scnView.pointOfView </code></pre>
24,753,893
How to set editor theme in IntelliJ Idea
<p>I'm trying to change the editor color schemes in IntelliJ Idea 13.1.3 community edition to a darker theme. I downloaded a theme from a website [Editor's note: the website has since been replaced with spam, and has been edited out] and imported settings through <code>File-&gt;Import Settings...</code>. The jar imported successfully and I restarted the IDE, but after restart there is no change in appearance. I have checked in appearance settings and everything is the same as before(no new theme). I'm new to IntelliJ Idea, so I may have missed a step or something. Any ideas?</p>
24,765,954
6
0
null
2014-07-15 08:57:04.51 UTC
5
2021-01-30 10:19:20.307 UTC
2021-01-30 10:19:01.053 UTC
null
6,296,561
null
3,836,923
null
1
75
intellij-idea|themes|editor
143,386
<p>OK I found the problem, I was checking in the wrong place which is for the whole IDE's look and feel at <code>File-&gt;Settings-&gt;Appearance</code></p> <p>The correct place to change the editor appearance is through <code>File-&gt;Settings-&gt;Editor-&gt;Colors &amp;Fonts</code> and then choose the scheme there. The imported settings appear there :)</p> <p>Note: The <a href="https://github.com/sdvoynikov/color-themes" rel="nofollow noreferrer">theme site</a> seems to have moved.</p>
24,873,485
Using onBlur with JSX and React
<p>I am trying to create a password confirmation feature that renders an error only after a user leaves the confirmation field. I'm working with Facebook's React JS. This is my input component:</p> <pre><code>&lt;input type="password" placeholder="Password (confirm)" valueLink={this.linkState('password2')} onBlur={this.renderPasswordConfirmError()} /&gt; </code></pre> <p>This is renderPasswordConfirmError :</p> <pre><code>renderPasswordConfirmError: function() { if (this.state.password !== this.state.password2) { return ( &lt;div&gt; &lt;label className="error"&gt;Please enter the same password again.&lt;/label&gt; &lt;/div&gt; ); } return null; }, </code></pre> <p>When I run the page the message is not displayed when conflicting passwords are entered. </p>
24,874,979
1
0
null
2014-07-21 19:50:31.223 UTC
6
2016-02-08 03:19:48.857 UTC
2016-02-08 03:19:48.857 UTC
null
1,434,116
null
3,862,066
null
1
42
html|reactive-programming|reactjs|onblur
153,449
<p>There are a few problems here.</p> <p>1: onBlur expects a callback, and you are calling <code>renderPasswordConfirmError</code> and using the return value, which is null.</p> <p>2: you need a place to render the error.</p> <p>3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.</p> <pre><code>handleBlur: function () { this.setState({validating: true}); }, render: function () { return &lt;div&gt; ... &lt;input type="password" placeholder="Password (confirm)" valueLink={this.linkState('password2')} onBlur={this.handleBlur} /&gt; ... {this.renderPasswordConfirmError()} &lt;/div&gt; }, renderPasswordConfirmError: function() { if (this.state.validating &amp;&amp; this.state.password !== this.state.password2) { return ( &lt;div&gt; &lt;label className="error"&gt;Please enter the same password again.&lt;/label&gt; &lt;/div&gt; ); } return null; }, </code></pre>
23,795,926
Share sessions between php and node
<p>Is there an recent guide (or example code) to using node, express, and redis/predis to share PHPSESSID?</p> <p>I've found several tutorials 1-2 years old and they are all either using old versions express or not using express.</p> <p>Express cookie parser is also deprecated.</p> <p><a href="https://simplapi.wordpress.com/2012/04/13/php-and-node-js-session-share-redi/" rel="nofollow noreferrer">https://simplapi.wordpress.com/2012/04/13/php-and-node-js-session-share-redi/</a></p> <p><a href="https://stackoverflow.com/questions/20752898/nodejs-expressjs-redisstore-session-is-undefined">NodeJS + ExpressJS + RedisStore Session is undefined</a></p> <p>It would be great if someone could post some more recent code...</p> <p>EDIT - extract of node server code so far:</p> <pre><code>var express = require('express'), app = express(), server = require('http').createServer(app), io = require('socket.io').listen(server), redis = require('redis'), client = redis.createClient(); var session = require('express-session'), RedisStore = require('connect-redis')(session); app.get('/', function(req, res) { res.sendfile('/'); }); app.use( session({ name: 'PHPSESSID' store: new RedisStore({ prefix: 'PHPSESSID', port: 6379 }) }) ); io.sockets.on('connection', function (socket) { app.use(function(req, res, next) { console.log(req.session); }); ....... </code></pre> <p>Packages:</p> <pre><code>├─┬ [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ └─┬ [email protected] │ │ └── [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ ├── [email protected] │ │ ├── [email protected] │ │ └── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ ├── [email protected] │ │ └── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ ├── [email protected] │ │ ├── [email protected] │ │ └── [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ └── [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ ├─┬ [email protected] │ │ │ ├── [email protected] │ │ │ ├── [email protected] │ │ │ ├── [email protected] │ │ │ └── [email protected] │ │ └── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ ├── [email protected] │ │ └── [email protected] │ ├─┬ [email protected] │ │ └─┬ [email protected] │ │ ├── [email protected] │ │ ├── [email protected] │ │ ├── [email protected] │ │ └── [email protected] │ ├─┬ [email protected] │ │ └── [email protected] │ └── [email protected] ├─┬ [email protected] │ └── [email protected] ├─┬ [email protected] │ ├─┬ [email protected] │ │ ├── [email protected] │ │ └── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ ├── [email protected] │ │ └── [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ └── [email protected] │ └── [email protected] ├─┬ [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ └── [email protected] ├─┬ [email protected] │ ├── [email protected] │ ├─┬ [email protected] │ │ ├── [email protected] │ │ ├── [email protected] │ │ ├── [email protected] │ │ └── [email protected] │ └── [email protected] ├── [email protected] └─┬ [email protected] ├── [email protected] ├── [email protected] ├── [email protected] └─┬ [email protected] ├─┬ [email protected] │ └── [email protected] ├── [email protected] ├─┬ [email protected] │ ├── [email protected] │ ├── [email protected] │ ├── [email protected] │ └── [email protected] └── [email protected] </code></pre>
23,796,095
2
0
null
2014-05-22 00:22:08.56 UTC
8
2019-08-26 16:46:15.563 UTC
2017-05-23 10:30:49.21 UTC
null
-1
null
1,156,785
null
1
2
node.js|express|redis|session-cookies
10,788
<p><strong>For node (and Express 4.x):</strong></p> <p>Start with the example from <a href="https://github.com/expressjs/session" rel="noreferrer">express-session</a>, but use <a href="https://github.com/visionmedia/connect-redis" rel="noreferrer">connect-redis</a> as your session store instead.</p> <p>Example code:</p> <pre class="lang-js prettyprint-override"><code>var express = require('express'), app = express(), cookieParser = require('cookie-parser'), session = require('express-session'), RedisStore = require('connect-redis')(session); app.use(express.static(__dirname + '/public')); app.use(function(req, res, next) { if (req.url.indexOf('favicon') &gt; -1) return res.send(404); next(); }); app.use(cookieParser()); app.use(session({ store: new RedisStore({ // this is the default prefix used by redis-session-php prefix: 'session:php:' }), // use the default PHP session cookie name name: 'PHPSESSID', secret: 'node.js rules' })); app.use(function(req, res, next) { req.session.nodejs = 'Hello from node.js!'; res.send(JSON.stringify(req.session, null, ' ')); }); app.listen(8080); </code></pre> <p><strong>For PHP:</strong></p> <p>Use a redis session handler like <a href="https://github.com/TheDeveloper/redis-session-php" rel="noreferrer">redis-session-php</a>.</p> <p>Example code:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php // from https://github.com/TheDeveloper/redis-session-php require('redis-session-php/redis-session.php'); RedisSession::start(); $_SESSION["php"] = "Hello from PHP"; // `cookie` is needed by express-session to store information // about the session cookie if (!isset($_SESSION["cookie"])) $_SESSION["cookie"] = array(); var_dump($_SESSION); ?&gt; </code></pre> <p>Note: Make sure you use the same <code>prefix</code>(connect-redis)/<code>REDIS_SESSION_PREFIX</code>(redis-session-php) (connect-redis uses 'sess:' and redis-session-php uses 'session:php:' by default) and <code>ttl</code>(connect-redis)/<code>session.gc_maxlifetime</code>(PHP) (and same database if you are using a redis database other than the default) for both redis-session-php and connect-redis.</p>
56,892,691
How to show HTML or Markdown in a SwiftUI Text?
<p>How can I set a SwiftUI <code>Text</code> to display rendered HTML or Markdown?</p> <p>Something like this: </p> <pre><code>Text(HtmlRenderedString(fromString: "&lt;b&gt;Hi!&lt;/b&gt;")) </code></pre> <p>or for MD: </p> <pre><code>Text(MarkdownRenderedString(fromString: "**Bold**")) </code></pre> <p>Perhaps I need a different View?</p>
56,895,086
9
0
null
2019-07-04 18:09:47.677 UTC
10
2022-09-05 03:42:11.203 UTC
2019-07-05 11:02:47.523 UTC
null
11,636,607
null
11,636,607
null
1
30
html|swift|text|markdown|swiftui
22,204
<p><code>Text</code> can just display <code>String</code>s. You can use a <code>UIViewRepresentable</code> with an <code>UILabel</code> and <code>attributedText</code>.</p> <p>Probably attributedText text support will come later for <code>SwiftUI.Text</code>.</p>
49,652,453
Is it possible to emulate the notch from the Huawei P20 with Android Studio
<p>Huawei's P20 has an iPhone X like notch on the top of the screen. Can this "notch" be emulated in Android Studio so it is possible to test how an app is rendered on it without owning a P20? I looked in the settings and it is possible to select a "skin" in the Hardware profile but Huawei's P20 is not part of it.</p>
52,872,669
4
0
null
2018-04-04 13:35:33.36 UTC
6
2020-10-14 17:08:38.93 UTC
null
null
null
null
2,652,054
null
1
44
android|android-studio
24,572
<p>Follow the screen shots.</p> <p><strong>first make sure 9.0 (api 28) run in your Emulater or testing device.</strong></p> <ol> <li>Open System settings.</li> </ol> <p><a href="https://i.stack.imgur.com/WPVQg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WPVQg.png" alt="enter image description here" /></a></p> <ol start="2"> <li>Open Developer option (*if u not found developer option please tap 7 times on build number. after that you get developer option.)</li> </ol> <p><a href="https://i.stack.imgur.com/q4IDj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/q4IDj.png" alt="enter image description here" /></a></p> <ol start="3"> <li>Scroll Down Until You Found -&gt; Simulate a Display With a Cutout(click on it)</li> </ol> <p><a href="https://i.stack.imgur.com/v2NMI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/v2NMI.png" alt="enter image description here" /></a></p> <ol start="4"> <li>there is a multiple option to select screen Cutout style.</li> </ol> <p><a href="https://i.stack.imgur.com/cOA6O.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cOA6O.png" alt="enter image description here" /></a></p> <ol start="5"> <li>if you select <strong>Tall Display Cutout</strong> , your display is like that.</li> </ol> <p><a href="https://i.stack.imgur.com/iFLFa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iFLFa.png" alt="enter image description here" /></a></p> <p>or if you select <strong>Double Display Cutout</strong> your display like.</p> <p><a href="https://i.stack.imgur.com/KiVtw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KiVtw.png" alt="enter image description here" /></a></p>
38,777,701
"ISO C++ forbids forward references to 'enum' types" when specifying enum underlying type
<p>Given the program:</p> <pre><code>enum E : int { A, B, C }; </code></pre> <p><code>g++ -c test.cpp</code> works just fine. However, <code>clang++ -c test.cpp</code> gives the following errors:</p> <pre><code>test.cpp:1:6: error: ISO C++ forbids forward references to 'enum' types enum E : int ^ test.cpp:1:8: error: expected unqualified-id enum E : int ^ 2 errors generated. </code></pre> <p>These error messages don't make any sense to me. I don't see any forward references here.</p>
38,777,702
1
7
null
2016-08-04 21:29:39.16 UTC
4
2022-08-09 20:20:15.077 UTC
2022-07-23 05:52:56.273 UTC
null
21,501
null
21,501
null
1
38
c++|clang
19,934
<p>Specifying the underlying type for an enum is a C++11 language feature. To get the code to compile, you must add the switch <code>-std=c++11</code>. This works for both GCC and Clang.</p> <p>For enums in C++03, the underlying integral type is implementation-defined, unless the values of the enumerator cannot fit in an int or unsigned int. (However, Microsoft's compiler has allowed specifying the underlying type of an enum as a proprietary extension since VS&nbsp;2005.)</p>
7,177,004
adding two arraylists into one
<p>I want to check branchList whether has same element or not, if same put branchList and tglList element separate arraylist and put that arraylist into another arraylist, </p> <p>The result I want is BranchList1 have 2 arraylist where 1st arraylist contain for element '1' and 2nd arraylist contain element '2' and TglList1 have 2 arraylist as element, but what i get is both 1st and 2nd array get same value.</p> <p>How can this be done?</p> <pre><code>ArrayList branchList = new ArrayList(); branchList.add("1"); branchList.add("1"); branchList.add("1"); branchList.add("2"); branchList.add("2"); branchList.add("2"); ArrayList tglList = new ArrayList(); tglList.add("5"); tglList.add("10"); tglList.add("20"); tglList.add("100"); tglList.add("500"); tglList.add("1000"); ArrayList newBranchList = new ArrayList(); ArrayList newTglList = new ArrayList(); ArrayList BranchList1 = new ArrayList(); ArrayList TglList1 = new ArrayList(); ArrayList abc = new ArrayList(); String checkBranch = new String(); for(int i=0;i&lt;branchList.size();i++){ String branch = branchList.get(i).toString(); if(i==0 || checkBranch.equals(branch)){ newBranchList.add(branch); newTglList.add(tglList.get(i).toString()); }else{ BranchList1.add(newBranchList); TglList1.add(newTglList); newBranchList.clear(); newTglList.clear(); newBranchList.add(branch); newTglList.add(tglList.get(i).toString()); } if(i==(branchList.size()-1)){ BranchList1.add(newBranchList); TglList1.add(newTglList); } checkBranch = branch; } } </code></pre> <p>so expected result is as below:</p> <pre><code>BranchList1 = [ [1,1,1],[2,2,2]] TglList1 = [[5,10,20],[50,100,200]] </code></pre> <p>but what I get is </p> <pre><code>BranchList1 = [ [2,2,2],[2,2,2]] TglList1 = [[50,100,200],[50,100,200]] </code></pre> <p>How can I modify the code</p>
7,177,220
1
5
null
2011-08-24 14:18:59.96 UTC
3
2017-11-13 05:31:23.967 UTC
2017-11-13 05:31:23.967 UTC
null
1,009,479
null
438,159
null
1
12
java|arraylist
60,364
<p>I didn't thoroughly read through your code (and I don't quite get what you're asking for), but if you want to merge (add the elements of) <code>branchList</code> and <code>tglList</code> to <code>TglList1</code>, try this:</p> <pre><code>TglList1.addAll(branchList); TglList1.addAll(tglList); </code></pre> <p>After that, <code>TglList1</code> should contain all elements of both lists. If you need the list to be sorted, you might want to call <code>Collections.sort(TglList1)</code> afterwards (just note that sorting strings might place "100" before "2", due to "1" being lexically smaller than "2").</p>
7,139,466
Get difference of arrays in Ruby
<blockquote> <p><strong>Possible Duplicate:</strong><br /> <a href="https://stackoverflow.com/questions/80091/diff-a-ruby-string-or-array">diff a ruby string or array</a></p> </blockquote> <p>I have an old array: <code>[1, 2, 3, 4, 5]</code>, and new: <code>[1, 2, 4, 6]</code></p> <p>How to get difference with Ruby: that <code>5, 3</code> was removed and <code>6</code> was added?</p>
7,139,479
1
0
null
2011-08-21 16:17:48.377 UTC
5
2020-11-13 16:12:10.083 UTC
2020-11-13 16:12:10.083 UTC
null
967,621
null
531,272
null
1
50
arrays|ruby
38,476
<pre><code>irb(main):001:0&gt; a = [1, 2, 3, 4, 5] =&gt; [1, 2, 3, 4, 5] irb(main):002:0&gt; b = [1, 2, 4, 6] =&gt; [1, 2, 4, 6] irb(main):003:0&gt; a - b =&gt; [3, 5] irb(main):005:0&gt; b - a =&gt; [6] irb(main):006:0&gt; </code></pre>
22,663,484
get "ERROR: Can't get master address from ZooKeeper; znode data == null" when using Hbase shell
<p>I installed Hadoop2.2.0 and Hbase0.98.0 and here is what I do :</p> <pre><code>$ ./bin/start-hbase.sh $ ./bin/hbase shell 2.0.0-p353 :001 &gt; list </code></pre> <p>then I got this:</p> <pre><code>ERROR: Can't get master address from ZooKeeper; znode data == null </code></pre> <p>Why am I getting this error ? Another question: do I need to run <code>./sbin/start-dfs.sh</code> and <code>./sbin/start-yarn.sh</code> before I run base ?</p> <p>Also, what are used <code>./sbin/start-dfs.sh</code> and <code>./sbin/start-yarn.sh</code> for ?</p> <p>Here is some of my conf doc :</p> <h2>hbase-sites.xml</h2> <pre><code>&lt;configuration&gt; &lt;property&gt; &lt;name&gt;hbase.rootdir&lt;/name&gt; &lt;value&gt;hdfs://127.0.0.1:9000/hbase&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;hbase.cluster.distributed&lt;/name&gt; &lt;value&gt;true&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;hbase.tmp.dir&lt;/name&gt; &lt;value&gt;/Users/apple/Documents/tools/hbase-tmpdir/hbase-data&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;hbase.zookeeper.quorum&lt;/name&gt; &lt;value&gt;localhost&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;hbase.zookeeper.property.dataDir&lt;/name&gt; &lt;value&gt;/Users/apple/Documents/tools/hbase-zookeeper/zookeeper&lt;/value&gt; &lt;/property&gt; &lt;/configuration&gt; </code></pre> <h2>core-sites.xml</h2> <pre><code>&lt;configuration&gt; &lt;property&gt; &lt;name&gt;fs.defaultFS&lt;/name&gt; &lt;value&gt;hdfs://localhost:9000&lt;/value&gt; &lt;description&gt;The name of the default file system.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;hadoop.tmp.dir&lt;/name&gt; &lt;value&gt;/Users/micmiu/tmp/hadoop&lt;/value&gt; &lt;description&gt;A base for other temporary directories.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;io.native.lib.available&lt;/name&gt; &lt;value&gt;false&lt;/value&gt; &lt;/property&gt; &lt;/configuration&gt; </code></pre> <h2>yarn-sites.xml</h2> <pre><code>&lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.aux-services&lt;/name&gt; &lt;value&gt;mapreduce_shuffle&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.aux-services.mapreduce.shuffle.class&lt;/name&gt; &lt;value&gt;org.apache.hadoop.mapred.ShuffleHandler&lt;/value&gt; &lt;/property&gt; &lt;/configuration&gt; </code></pre>
22,670,992
8
0
null
2014-03-26 14:06:06.527 UTC
6
2019-04-07 07:29:45.167 UTC
2014-06-30 08:34:28.67 UTC
null
2,376,945
null
3,463,279
null
1
14
shell|hadoop|hbase
61,918
<p>If you just want to run HBase without going into Zookeeper management for standalone HBase, then remove all the <code>property</code> blocks from <code>hbase-site.xml</code> except the property block named <code>hbase.rootdir</code>. </p> <p>Now run <code>/bin/start-hbase.sh</code>. HBase comes with its own Zookeeper, which gets started when you run <code>/bin/start-hbase.sh</code>, which will suffice if you are trying to get around things for the first time. Later you can put distributed mode configurations for Zookeeper.</p> <p>You only need to run <code>/sbin/start-dfs.sh</code> for running HBase since the value of <code>hbase.rootdir</code> is set to <code>hdfs://127.0.0.1:9000/hbase</code> in your <code>hbase-site.xml</code>. If you change it to some location on local the filesystem using <code>file:///some_location_on_local_filesystem</code>, then you don't even need to run <code>/sbin/start-dfs.sh</code>. </p> <p><code>hdfs://127.0.0.1:9000/hbase</code> says it's a place on HDFS and <code>/sbin/start-dfs.sh</code> starts namenode and datanode which provides underlying API to access the HDFS file system. For knowing about Yarn, please look at <a href="http://hadoop.apache.org/docs/r2.3.0/hadoop-yarn/hadoop-yarn-site/YARN.html" rel="noreferrer">http://hadoop.apache.org/docs/r2.3.0/hadoop-yarn/hadoop-yarn-site/YARN.html</a>.</p>
39,168,390
Use ItExpr.IsNull<TValue> rather than a null argument value, as it prevents proper method lookup
<p>I am trying to write a unit test where I need to set up a protected method. I am using Moq for this setup.</p> <pre><code>_innerHandler.Protected() .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;("SendAsync", It.IsAny&lt;HttpRequestMessage&gt;(), It.IsAny&lt;CancellationToken&gt;()) .ReturnsAsync(responseMessage); </code></pre> <p>When this line executes, it throws the following exception:</p> <blockquote> <p>System.ArgumentException : Use <code>ItExpr.IsNull&lt;TValue&gt;</code> rather than a null argument value, as it prevents proper method lookup.</p> </blockquote> <p>When I change it to use <code>ItExpr.IsNull&lt;TValue&gt;</code>, it does allow the test to execute. However, it is of course missing the setup I wanted to configure.</p> <p>What do I need to do in order to set up a protected method using <code>It.IsAny&lt;TValue&gt;</code>?</p>
39,169,044
1
0
null
2016-08-26 14:14:20.313 UTC
null
2016-08-26 14:50:46.033 UTC
2016-08-26 14:50:46.033 UTC
null
5,233,410
null
2,546,997
null
1
38
c#|unit-testing|moq
5,342
<p>When setting up an <code>IProtectedMock</code>, you should use <code>Moq.Protected.ItExpr</code> instead of <code>Moq.It</code>.</p> <p>Here is the corrected implementation of what I was trying to do in my question:</p> <pre><code>_innerHandler.Protected() .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;("SendAsync", ItExpr.IsAny&lt;HttpRequestMessage&gt;(), ItExpr.IsAny&lt;CancellationToken&gt;()) .ReturnsAsync(responseMessage); </code></pre>
49,832,787
LiveData prevent receive the last value when start observing
<p>Is it possible to prevent <code>LiveData</code> receive the last value when start observing? I am considering to use <code>LiveData</code> as events.</p> <p>For example events like show message, a navigation event or a dialog trigger, similar to <code>EventBus</code>.</p> <p>The problem related to communication between <code>ViewModel</code> and fragment, Google gave us <code>LiveData</code> to update the view with data, but this type of communication not suitable when we need update the view only once with single event, also we cannot hold view's reference in <code>ViewModel</code> and call some methods because it will create memory leak.</p> <p>I found something similar <a href="https://github.com/googlesamples/android-architecture/blob/dev-todo-mvvm-live/todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/SingleLiveEvent.java" rel="noreferrer">SingleLiveEvent</a> - but it work only for 1 observer and not for multiple observers.</p> <p><strong>--- Update ----</strong> </p> <p>As @EpicPandaForce said "<em>There is no reason to use LiveData as something that it is not</em>", probably the intent of the question was <a href="https://stackoverflow.com/questions/59057941/communication-between-view-and-viewmodel-in-mvvm-with-livedata">Communication between view and ViewModel in MVVM with LiveData</a></p>
55,212,795
14
7
null
2018-04-14 14:56:33.353 UTC
17
2022-03-23 01:17:21.65 UTC
2021-01-02 18:06:15.203 UTC
null
5,827,565
null
5,827,565
null
1
52
android|android-livedata|android-architecture-components|android-viewmodel|mutablelivedata
61,563
<p>I`m using this EventWraper class from Google Samples inside MutableLiveData</p> <pre><code>/** * Used as a wrapper for data that is exposed via a LiveData that represents an event. */ public class Event&lt;T&gt; { private T mContent; private boolean hasBeenHandled = false; public Event( T content) { if (content == null) { throw new IllegalArgumentException(&quot;null values in Event are not allowed.&quot;); } mContent = content; } @Nullable public T getContentIfNotHandled() { if (hasBeenHandled) { return null; } else { hasBeenHandled = true; return mContent; } } public boolean hasBeenHandled() { return hasBeenHandled; } } </code></pre> <p><strong>In ViewModel :</strong></p> <pre><code> /** expose Save LiveData Event */ public void newSaveEvent() { saveEvent.setValue(new Event&lt;&gt;(true)); } private final MutableLiveData&lt;Event&lt;Boolean&gt;&gt; saveEvent = new MutableLiveData&lt;&gt;(); public LiveData&lt;Event&lt;Boolean&gt;&gt; onSaveEvent() { return saveEvent; } </code></pre> <p><strong>In Activity/Fragment</strong></p> <pre><code>mViewModel .onSaveEvent() .observe( getViewLifecycleOwner(), booleanEvent -&gt; { if (booleanEvent != null) final Boolean shouldSave = booleanEvent.getContentIfNotHandled(); if (shouldSave != null &amp;&amp; shouldSave) saveData(); } }); </code></pre>
3,186,333
What is the benefit of using NginX for Node.js?
<p>From what I understand Node.js doesnt need NginX to work as a http server (or a websockets server or any server for that matter), but I keep reading about how to use NginX instead of Node.js internal server and cant find of a good reason to go that way</p>
3,186,487
3
2
null
2010-07-06 12:57:36.907 UTC
5
2017-05-12 14:33:38.477 UTC
2017-03-06 07:52:00.037 UTC
null
363,217
null
363,217
null
1
29
nginx|node.js
5,534
<p>Here <a href="http://developer.yahoo.com/yui/theater/video.php?v=dahl-node" rel="noreferrer">http://developer.yahoo.com/yui/theater/video.php?v=dahl-node</a> Node.js author says that Node.js is still in development and so there may be security issues that NginX simply hides.<br> On the other hand, in case of a heavy traffic NginX will be able to split the job between many Node.js running servers. </p>
2,501,723
CSS "color" vs. "font-color"
<p>Anyone know why CSS provides <code>color</code> for text, but does not have <code>font-color</code> or <code>text-color</code>?</p> <p>Seems very counter-intuitive, kind of like <code>text-decoration: underline</code> rather than <code>font-style</code> or something related to fonts.</p> <p>Does anyone know why/how the W3C came up with such a wide array of CSS names like this?</p>
2,501,800
3
4
null
2010-03-23 16:28:37.727 UTC
21
2019-04-15 23:01:32.573 UTC
2016-02-07 00:10:04.33 UTC
null
3,853,934
null
89,161
null
1
138
css
361,230
<p>I would think that one reason could be that the color is applied to things other than font. For example:</p> <pre><code>div { border: 1px solid; color: red; } </code></pre> <p>Yields both a red font color and a red border.</p> <p>Alternatively, it could just be that the W3C's CSS standards are completely backwards and nonsensical as evidenced elsewhere.</p>
924,449
How to create a simple c# http monitor/blocker?
<p>I was reading that question (<a href="https://stackoverflow.com/questions/226784/how-to-create-a-simple-proxy-in-c">How to create a simple proxy in C#?</a>) that is near of my wishes.</p> <p>I simply want develop a c# app that, by example, monitors Firefox, IE, etc and logs all navigated pages. Depending of the visited page, I want to block the site (like a parental filter).</p> <p>Code snippets/samples are good, but if you can just tell me some direction of that classes to use I will be grateful. :-)</p>
967,782
2
0
null
2009-05-29 04:58:32.487 UTC
10
2017-09-12 08:13:47.917 UTC
2017-05-23 12:01:25.433 UTC
null
-1
null
48,729
null
1
8
c#|http|monitoring|blocking
29,762
<p>I’ll answer appropriate for a parent: ala "Parental Controls"</p> <p>You can start out with a proxy server when the kids are less than about 10 years old. After that, they will figure out how to get around the proxy (or run their own client applications that bypass the proxy). In the early teen years, you can use raw sockets. Type this program into Visual Studio (C#). </p> <pre><code>class Program { static void Main(string[] args) { try { byte[] input = BitConverter.GetBytes(1); byte[] buffer = new byte[4096]; Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); s.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.91"), 0)); s.IOControl(IOControlCode.ReceiveAll, input, null); int bytes = 0; do { bytes = s.Receive(buffer); if (bytes &gt; 0) { Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytes)); } } while (bytes &gt; 0); } catch (Exception ex) { Console.WriteLine(ex); } } } </code></pre> <p>Note that this is just a “snippet”, lacking appropriate design and error checking. [Please do not use 'as-is' - you did request just a head start] Change the IP address to your machine. Run the program <strong>AS Administrator</strong> (use “runas” on the command line, or right-click “Run as Administrator”). Only administrators can create and use raw sockets on modern versions of windows. Sit back and watch the show. </p> <p>All network traffic is delivered to your code (displayed on the screen, which will not look nice, with this program).</p> <p>Your next step is to create some protocol filters. Learn about the various internet application protocols (assuming you don't already know), modify the program to examine the packets. Look for HTTP protocol, and save the appropriate data (like GET requests). </p> <p>I personally have setup filters for AIM (AOL Instant Messenger), HTTP, MSN messenger (Windows Live Messenger), POP, and SMTP. Today, HTTP gets just about everything since the kids prefer the facebook wall to AIM nowadays.</p> <p>As the kids reach their early-to-mid teenage years, you will want to back-off on the monitoring. Some say this is to enable the kids to “grow up”, but the real reason is that “<strong><em>you don’t wanna know</em></strong>”. I backed off to just collecting URLs of get requests, and username/passwords (for emergency situations) that are in clear text (pop, basic auth, etc.).</p> <p>I don't know what happens in late teen years; I cannot image things getting much worse, but I am told that "I have not seen anything yet".</p> <p>Like someone earlier said, this only works when run on the target machine (I run a copy on all of the machines in the house). Otherwise, for simple monitoring check your router - mine has some nice logging features.</p> <p>My final comment is that this application should be written in C/C++ against the Win32 API directly, and installed as a service running with administrative rights on the machine. I don't think this type of code is appropriate for managed c#. You can attach a UI in C# for monitoring and control. You have to engineer the code so as to have zero noticeable effect on the system.</p>
993,409
Basic HTTP Authentication on iPhone
<p>I'm trying to get a small twitter client running and I ran into a problem when testing API calls that require authentication.</p> <p>My password has special characters in it, so when I try to use the following code it doesn't work.</p> <pre><code>NSString *post = [NSString stringWithFormat:@"status=%@", [status stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]]; NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@@%@/statuses/update.json", username, password, TwitterHostname]]; [request setURL:url]; [request setHTTPMethod:@"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody:postData]; NSURLResponse *response; NSError *error; [NSURLConnection sendSynchronousRequest:request returningResponse:&amp;response error:&amp;error]; </code></pre> <p>I started looking into base64 and putting the authentication into the headers. I found <a href="http://www.dribin.org/dave/blog/archives/2006/03/12/base64_cocoa/" rel="noreferrer">Dave Dribin's</a> post on his base64 implementation, and it seemed to make sense. However when I tried to use it the compiler started complaining about how it couldn't find the openssl libraries. So I read that I needed to link in the libcrypto library, but it doesn't seem to exist for iphone.</p> <p>I've also read people saying that apple won't allow apps that use crypto libraries, which doesn't make sense to me.</p> <p>So now I'm kinda stuck and confused. What's the easiest way to get basic authentication into my app?</p> <p>Cheers</p>
993,421
2
0
null
2009-06-14 18:23:00.923 UTC
23
2014-01-28 05:38:50.05 UTC
2009-06-25 22:54:50.44 UTC
null
52,963
null
59,877
null
1
13
iphone|objective-c|httpwebrequest|http-authentication
19,300
<p>Two things. Firstly you have to use the async methods rather than the synchronous/class method.</p> <pre><code>NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:req] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0]; // create the connection with the request // and start loading the data NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; </code></pre> <p>The authentication is managed by implementing this method in your delegate:</p> <pre><code>- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge; </code></pre> <p>And you'll probably also need to implement these methods too:</p> <pre><code>- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error; - (void)connectionDidFinishLoading:(NSURLConnection *)connection; </code></pre> <p>Using the async method tends to give a better user experience anyway so despite the extra complexity is worth doing even without the ability to do authentication.</p>
1,054,937
Programmatically send to front/back elements created from interface builder
<p>In interface builder, there are layout options to send to back or send to front any elements such as <code>UIButton</code>, <code>UIImage</code>, <code>UILabel</code> etc...</p> <p>Now, I would like to do the same at runtime, programmatically.</p> <p>Is there an easy way to do that?</p> <p>I do not want to create different views, just update the z-axis.</p>
1,054,946
2
0
null
2009-06-28 13:27:08.493 UTC
32
2017-08-21 12:46:59.627 UTC
2017-05-28 02:22:46.987 UTC
null
947,934
null
117,330
null
1
84
cocoa-touch|interface-builder|z-axis
78,577
<p>There are a number of methods of <code>UIView</code> that allow you to modify the view hierarchy.</p> <ul> <li><a href="https://developer.apple.com/documentation/uikit/uiview/1622541-bringsubview" rel="noreferrer"><code>bringSubviewToFront:</code></a></li> <li><a href="https://developer.apple.com/documentation/uikit/uiview/1622618-sendsubview" rel="noreferrer"><code>sendSubviewToBack:</code></a></li> <li><a href="https://developer.apple.com/documentation/uikit/uiview/1622538-insertsubview" rel="noreferrer"><code>insertSubview:atIndex:</code></a></li> <li><a href="https://developer.apple.com/documentation/uikit/uiview/1622570-insertsubview" rel="noreferrer"><code>insertSubview:aboveSubview:</code></a></li> <li><a href="https://developer.apple.com/documentation/uikit/uiview/1622598-insertsubview" rel="noreferrer"><code>insertSubview:belowSubview:</code></a></li> <li><a href="https://developer.apple.com/documentation/uikit/uiview/1622448-exchangesubview" rel="noreferrer"><code>exchangeSubviewAtIndex:withSubviewAtIndex:</code></a></li> </ul> <p>Since your views are already inserted into your superview, you could easily call <code>bringSubviewToFront:</code> once for each view in whatever order you like.</p>
2,498,599
Can some hacker steal a web browser cookie from a user and login with that name on a web site?
<p>Reading this question, <a href="https://stackoverflow.com/questions/2448720/different-users-get-the-same-cookie-value-in-aspxanonymous">Different users get the same cookie - value in .ASPXANONYMOUS</a></p> <p>and search for a solution, I start thinking, <strong>if it is possible for some one to really steal the cookie with some way, and then place it on his browser and login lets say as administrator</strong>.</p> <p>Do you know how form authentication can ensure that even if the cookie is stolen, the hacker does not get to use it in an actual login?</p> <p>Is there any other alternative automatic defense mechanism?</p>
2,505,406
5
1
null
2010-03-23 09:09:54.57 UTC
23
2019-12-07 16:34:16.763 UTC
2019-12-07 16:34:16.763 UTC
null
1,033,581
null
159,270
null
1
31
asp.net|security|cookies|forms-authentication
29,703
<blockquote> <p>Is it possible to steal a cookie and authenticate as an administrator?</p> </blockquote> <p>Yes it is possible, if the Forms Auth cookie is not encrypted, someone could hack their cookie to give them elevated privileges or if SSL is not require, copy someone another person's cookie. However, there are steps you can take to mitigate these risks:</p> <p>On the system.web/authentication/forms element:</p> <ol> <li>requireSSL=true. This requires that the cookie only be transmitted over SSL</li> <li>slidingExpiration=false. When true, an expired ticket can be reactivated.</li> <li>cookieless=false. Do not use cookieless sessions in an environment where are you trying to enforce security.</li> <li>enableCrossAppRedirects=false. When false, processing of cookies across apps is not allowed.</li> <li>protection=all. Encrypts and hashes the Forms Auth cookie using the machine key specified in the machine.config or web.config. This feature would stop someone from hacking their own cookie as this setting tells the system to generate a signature of the cookie and on each authentication request, compare the signature with the passed cookie.</li> </ol> <p>If you so wanted, you could add a small bit of protection by putting some sort of authentication information in Session such as a hash of the user's username (Never the username in plain text nor their password). This would require the attacker to steal both the Session cookie and the Forms Auth cookie. </p>
2,778,247
How do I construct a Django reverse/url using query args?
<p>I have URLs like <a href="http://example.com/depict?smiles=CO&amp;width=200&amp;height=200" rel="noreferrer">http://example.com/depict?smiles=CO&amp;width=200&amp;height=200</a> (and with several other optional arguments)</p> <p>My urls.py contains:</p> <pre><code>urlpatterns = patterns('', (r'^$', 'cansmi.index'), (r'^cansmi$', 'cansmi.cansmi'), url(r'^depict$', cyclops.django.depict, name="cyclops-depict"), </code></pre> <p>I can go to that URL and get the 200x200 PNG that was constructed, so I know that part works.</p> <p>In my template from the "cansmi.cansmi" response I want to construct a URL for the named template "cyclops-depict" given some query parameters. I thought I could do</p> <blockquote> <p>{% url cyclops-depict smiles=input_smiles width=200 height=200 %}</p> </blockquote> <p>where "input_smiles" is an input to the template via a form submission. In this case it's the string "CO" and I thought it would create a URL like the one at top.</p> <p>This template fails with a TemplateSyntaxError:</p> <blockquote> <p>Caught an exception while rendering: Reverse for 'cyclops-depict' with arguments '()' and keyword arguments '{'smiles': u'CO', 'height': 200, 'width': 200}' not found.</p> </blockquote> <p>This is a rather common error message both here on StackOverflow and elsewhere. In every case I found, people were using them with parameters in the URL path regexp, which is not the case I have where the parameters go into the query.</p> <p>That means I'm doing it wrong. How do I do it right? That is, I want to construct the full URL, including path and query parameters, using something in the template.</p> <p>For reference,</p> <pre><code>% python manage.py shell Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) &gt;&gt;&gt; from django.core.urlresolvers import reverse &gt;&gt;&gt; reverse("cyclops-depict", kwargs=dict()) '/depict' &gt;&gt;&gt; reverse("cyclops-depict", kwargs=dict(smiles="CO")) Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "/Library/Python/2.6/site-packages/django/core/urlresolvers.py", line 356, in reverse *args, **kwargs))) File "/Library/Python/2.6/site-packages/django/core/urlresolvers.py", line 302, in reverse "arguments '%s' not found." % (lookup_view_s, args, kwargs)) NoReverseMatch: Reverse for 'cyclops-depict' with arguments '()' and keyword arguments '{'smiles': 'CO'}' not found. </code></pre>
2,778,275
6
1
null
2010-05-06 03:31:05.07 UTC
14
2019-08-29 11:03:12.25 UTC
2014-08-03 00:10:11.963 UTC
null
8,331
null
64,618
null
1
40
django|url|query-string|reverse
44,032
<p>Your regular expresion has no place holders (that's why you are getting NoReverseMatch):</p> <pre><code>url(r'^depict$', cyclops.django.depict, name="cyclops-depict"), </code></pre> <p>You could do it like this:</p> <pre><code>{% url cyclops-depict %}?smiles=CO&amp;width=200&amp;height=200 </code></pre> <p><a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#what-the-urlconf-searches-against" rel="noreferrer">URLconf search does not include GET or POST parameters</a></p> <p>Or if you wish to use {% url %} tag you should restructure your url pattern to something like </p> <pre><code>r'^depict/(?P&lt;width&gt;\d+)/(?P&lt;height&gt;\d+)/(?P&lt;smiles&gt;\w+)$' </code></pre> <p>then you could do something like </p> <pre><code>{% url cyclops-depict 200 200 "CO" %} </code></pre> <hr> <p><strong>Follow-up:</strong></p> <p>Simple example for custom tag:</p> <pre><code>from django.core.urlresolvers import reverse from django import template register = template.Library() @register.tag(name="myurl") def myurl(parser, token): tokens = token.split_contents() return MyUrlNode(tokens[1:]) class MyUrlNode(template.Node): def __init__(self, tokens): self.tokens = tokens def render(self, context): url = reverse('cyclops-depict') qs = '&amp;'.join([t for t in self.tokens]) return '?'.join((url,qs)) </code></pre> <p>You could use this tag in your templates like so:</p> <pre><code>{% myurl width=200 height=200 name=SomeName %} </code></pre> <p>and hopefully it should output something like</p> <pre><code>/depict?width=200&amp;height=200&amp;name=SomeName </code></pre>
2,699,534
How to convert int* to int
<p>Given a pointer to <code>int</code>, how can I obtain the actual <code>int</code>?</p> <p>I don't know if this is possible or not, but can someone please advise me?</p>
2,699,545
7
2
null
2010-04-23 14:54:47.627 UTC
5
2020-04-13 09:21:40.653 UTC
2015-12-04 11:23:59.23 UTC
null
4,850,040
null
268,247
null
1
22
c++|pointers
66,416
<p>Use the * on pointers to get the variable pointed (dereferencing).</p> <pre><code>int val = 42; int* pVal = &amp;val; int k = *pVal; // k == 42 </code></pre> <p>If your pointer points to an array, then dereferencing will give you the first element of the array.</p> <p>If you want the "value" of the pointer, that is the actual memory address the pointer contains, then cast it (but it's generally not a good idea) :</p> <pre><code>int pValValue = reinterpret_cast&lt;int&gt;( pVal ); </code></pre>
2,429,045
iFrame src change event detection?
<p>Assuming I have no control over the content in the iframe, is there any way that I can detect a src change in it via the parent page? Some sort of onload maybe?</p> <p>My last resort is to do a 1 second interval test if the iframe src is the same as it was before, but doing this hacky solution would suck.</p> <p>I'm using the jQuery library if it helps.</p>
2,429,058
7
2
null
2010-03-11 22:07:46.053 UTC
61
2020-03-20 17:30:21.897 UTC
null
null
null
null
174,621
null
1
230
javascript|jquery|iframe|onload
311,311
<p>You may want to use the <code>onLoad</code> event, as in the following example:</p> <pre><code>&lt;iframe src="http://www.google.com/" onLoad="alert('Test');"&gt;&lt;/iframe&gt; </code></pre> <p>The alert will pop-up whenever the location within the iframe changes. It works in all modern browsers, but may not work in some very older browsers like IE5 and early Opera. (<a href="http://www.tipstrs.com/tip/3126/Telling-when-an-iframe-is-done-loading" rel="noreferrer">Source</a>)</p> <p><strong>If the iframe is showing a page within the same domain of the parent</strong>, you would be able to access the location with <code>contentWindow.location</code>, as in the following example:</p> <pre><code>&lt;iframe src="/test.html" onLoad="alert(this.contentWindow.location);"&gt;&lt;/iframe&gt; </code></pre>
2,511,315
Method for finding memory leak in large Java heap dumps
<p>I have to find a memory leak in a Java application. I have some experience with this but would like advice on a methodology/strategy for this. Any reference and advice is welcome. </p> <p>About our situation:</p> <ol> <li>Heap dumps are larger than 1 GB</li> <li>We have heap dumps from 5 occasions.</li> <li>We don't have any test case to provoke this. It only happens in the (massive) system test environment after at least a weeks usage.</li> <li>The system is built on a internally developed legacy framework with so many design flaws that they are impossible to count them all.</li> <li>Nobody understands the framework in depth. It has been transfered to <em>one</em> guy in India who barely keeps up with answering e-mails.</li> <li>We have done snapshot heap dumps over time and concluded that there is not a single component increasing over time. It is everything that grows slowly.</li> <li>The above points us in the direction that it is the frameworks homegrown ORM system that increases its usage without limits. (This system maps objects to files?! So not really a ORM)</li> </ol> <p><strong>Question:</strong> <em>What is the methodology that helped you succeed with hunting down leaks in a enterprise scale application?</em></p>
2,511,709
8
6
null
2010-03-24 20:53:27.69 UTC
31
2021-12-14 20:15:15.223 UTC
null
null
null
null
226,174
null
1
35
java|methodology|enterprise|legacy-code|memory-leaks
38,523
<p>It's almost impossible without some understanding of the underlying code. If you understand the underlying code, then you can better sort the wheat from chaff of the zillion bits of information you are getting in your heap dumps.</p> <p>Also, you can't know if something is a leak or not without know why the class is there in the first place.</p> <p>I just spent the past couple of weeks doing exactly this, and I used an iterative process.</p> <p>First, I found the heap profilers basically useless. They can't analyze the enormous heaps efficiently.</p> <p>Rather, I relied almost solely on <a href="http://java.sun.com/javase/6/docs/technotes/tools/share/jmap.html" rel="nofollow noreferrer">jmap</a> histograms.</p> <p>I imagine you're familiar with these, but for those not:</p> <pre><code>jmap -histo:live &lt;pid&gt; &gt; histogram.out </code></pre> <p>creates a histogram of the live heap. In a nutshell, it tells you the class names, and how many instances of each class are in the heap.</p> <p>I was dumping out heap regularly, every 5 minutes, 24hrs a day. That may well be too granular for you, but the gist is the same.</p> <p>I ran several different analyses on this data.</p> <p>I wrote a script to take two histograms, and dump out the difference between them. So, if java.lang.String was 10 in the first dump, and 15 in the second, my script would spit out &quot;5 java.lang.String&quot;, telling me it went up by 5. If it had gone down, the number would be negative.</p> <p>I would then take several of these differences, strip out all classes that went down from run to run, and take a union of the result. At the end, I'd have a list of classes that continually grew over a specific time span. Obviously, these are prime candidates for leaking classes.</p> <p>However, some classes have some preserved while others are GC'd. These classes could easily go up and down in overall, yet still leak. So, they could fall out of the &quot;always rising&quot; category of classes.</p> <p>To find these, I converted the data in to a time series and loaded it in a database, Postgres specifically. Postgres is handy because it offers <a href="http://www.postgresql.org/docs/8.2/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-STATISTICS-TABLE" rel="nofollow noreferrer">statistical aggregate functions</a>, so you can do simple <a href="http://en.wikipedia.org/wiki/Linear_regression" rel="nofollow noreferrer">linear regression analysis</a> on the data, and find classes that trend up, even if they aren't always on top of the charts. I used the regr_slope function, looking for classes with a positive slope.</p> <p>I found this process very successful, and really efficient. The histograms files aren't insanely large, and it was easy to download them from the hosts. They weren't super expensive to run on the production system (they do force a large GC, and may block the VM for a bit). I was running this on a system with a 2G Java heap.</p> <p>Now, all this can do is identify potentially leaking classes.</p> <p>This is where understanding how the classes are used, and whether they should or should not be their comes in to play.</p> <p>For example, you may find that you have a lot of Map.Entry classes, or some other system class.</p> <p>Unless you're simply caching String, the fact is these system classes, while perhaps the &quot;offenders&quot;, are not the &quot;problem&quot;. If you're caching some application class, THAT class is a better indicator of where your problem lies. If you don't cache com.app.yourbean, then you won't have the associated Map.Entry tied to it.</p> <p>Once you have some classes, you can start crawling the code base looking for instances and references. Since you have your own ORM layer (for good or ill), you can at least readily look at the source code to it. If you ORM is caching stuff, it's likely caching ORM classes wrapping your application classes.</p> <p>Finally, another thing you can do, is once you know the classes, you can start up a local instance of the server, with a much smaller heap and smaller dataset, and using one of the profilers against that.</p> <p>In this case, you can do unit test that affects only 1 (or small number) of the things you think may be leaking. For example, you could start up the server, run a histogram, perform a single action, and run the histogram again. You leaking class should have increased by 1 (or whatever your unit of work is).</p> <p>A profiler may be able to help you track the owners of that &quot;now leaked&quot; class.</p> <p>But, in the end, you're going to have to have some understanding of your code base to better understand what's a leak, and what's not, and why an object exists in the heap at all, much less why it may be being retained as a leak in your heap.</p>
2,645,009
binary protocols v. text protocols
<p>does anyone have a good definition for what a binary protocol is? and what is a text protocol actually? how do these compare to each other in terms of bits sent on the wire? </p> <p>here's what wikipedia says about binary protocols:</p> <p>A binary protocol is a protocol which is intended or expected to be read by a machine rather than a human being (<a href="http://en.wikipedia.org/wiki/Binary_protocol" rel="noreferrer">http://en.wikipedia.org/wiki/Binary_protocol</a>)</p> <p>oh come on! </p> <p>to be more clear, if I have jpg file how would that be sent through a binary protocol and how through a text one? in terms of bits/bytes sent on the wire of course. </p> <p>at the end of the day if you look at a string it is itself an array of bytes so the distinction between the 2 protocols should rest on what actual data is being sent on the wire. in other words, on how the initial data (jpg file) is encoded before being sent.</p>
2,645,168
9
1
null
2010-04-15 12:06:07.777 UTC
59
2021-12-12 14:15:53.313 UTC
2018-12-11 17:03:56.453 UTC
null
165,071
null
317,416
null
1
114
text|binary|protocols
49,770
<p>Binary protocol versus text protocol isn't really about how binary blobs are encoded. The difference is really whether the protocol is oriented around data structures or around text strings. Let me give an example: HTTP. HTTP is a text protocol, even though when it sends a jpeg image, it just sends the raw bytes, not a text encoding of them.</p> <p>But what makes HTTP a text protocol is that the exchange to <em>get</em> the jpg looks like this:</p> <p>Request:</p> <pre class="lang-http prettyprint-override"><code>GET /files/image.jpg HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.01 [en] (Win95; I) Host: hal.etc.com.au Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */* Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 </code></pre> <p>Response:</p> <pre class="lang-http prettyprint-override"><code>HTTP/1.1 200 OK Date: Mon, 19 Jan 1998 03:52:51 GMT Server: Apache/1.2.4 Last-Modified: Wed, 08 Oct 1997 04:15:24 GMT ETag: &quot;61a85-17c3-343b08dc&quot; Content-Length: 60830 Accept-Ranges: bytes Keep-Alive: timeout=15, max=100 Connection: Keep-Alive Content-Type: image/jpeg &lt;binary data goes here&gt; </code></pre> <p>Note that this could very easily have been packed much more tightly into a structure that would look (in C) something like</p> <p>Request:</p> <pre class="lang-c prettyprint-override"><code>struct request { int requestType; int protocolVersion; char path[1024]; char user_agent[1024]; char host[1024]; long int accept_bitmask; long int language_bitmask; long int charset_bitmask; }; </code></pre> <p>Response:</p> <pre class="lang-c prettyprint-override"><code>struct response { int responseType; int protocolVersion; time_t date; char host[1024]; time_t modification_date; char etag[1024]; size_t content_length; int keepalive_timeout; int keepalive_max; int connection_type; char content_type[1024]; char data[]; }; </code></pre> <p>Where the field names would not have to be transmitted at all, and where, for example, the <code>responseType</code> in the response structure is an int with the value 200 instead of three characters '2' '0' '0'. That's what a text based protocol is: one that is designed to be communicated as a flat stream of (usually human-readable) lines of text, rather than as structured data of many different types.</p>
2,677,431
Where to install Android SDK on Mac OS X?
<p>Where should the Android SDK be installed on Mac OS X?</p>
43,797,501
13
3
null
2010-04-20 17:52:28.453 UTC
47
2021-10-08 14:02:08.14 UTC
2015-02-21 14:09:49.3 UTC
null
16,587
null
82,118
null
1
206
android|configuration|macos
212,028
<p>In <a href="https://brew.sh/" rel="nofollow noreferrer">homebrew</a> the <code>android-sdk</code> has migrated from <code>homebrew/core</code> to <code>homebrew/cask</code>.</p> <pre><code>brew tap homebrew/cask </code></pre> <p>and install <code>android-sdk</code> using</p> <pre><code>brew install android-sdk --cask </code></pre> <p>You will have to add the <code>ANDROID_HOME</code> to profile (.zshrc or .bashrc)</p> <pre><code>export ANDROID_HOME=/usr/local/share/android-sdk </code></pre> <p>If you prefer otherwise, copy the package to</p> <pre><code>~/opt/local/android-sdk-mac </code></pre>
25,340,847
Control the height in fluidRow in R shiny
<p>I am trying to build a layout for a <code>shiny</code> app. I have been looking at the application <a href="http://shiny.rstudio.com/articles/layout-guide.html" rel="noreferrer">layout guide</a> and did some google search but it seems the layout system in shiny has its limits.</p> <p>You can create something like this:</p> <pre><code>fluidPage( fluidRow( column(6,"Topleft"), column(6,"Topright")), fluidRow( column(6,"Bottomleft"), column(6,"Bottomright")) ) </code></pre> <p>This gives you 4 same sized objects.</p> <p>Is it possible now to give the 2 <code>Top-Objects</code> a different height as the <code>Bottom-Objects</code>? </p> <p>And is it possible to merge the <code>Topright-Object</code> and the <code>Bottomright-Object</code>?</p>
25,341,329
2
0
null
2014-08-16 13:57:19.83 UTC
11
2018-09-08 22:26:39.587 UTC
2015-07-19 10:00:06.66 UTC
null
2,901,002
null
3,947,186
null
1
36
r|layout|shiny
66,686
<p>The height of the rows is responsive and is determined by the height of the elements of the columns. As an example we use two elements in the first row with heights 200 and 100 pixels respectively. The row takes the maximum height of its elements. The second row has elements with heights 100 and 150 pixels respectively and again takes the height of the largest element.</p> <pre><code>library(shiny) runApp(list( ui = fluidPage( fluidRow( column(6,div(style = "height:200px;background-color: yellow;", "Topleft")), column(6,div(style = "height:100px;background-color: blue;", "Topright"))), fluidRow( column(6,div(style = "height:100px;background-color: green;", "Bottomleft")), column(6,div(style = "height:150px;background-color: red;", "Bottomright"))) ), server = function(input, output) { } )) </code></pre> <p><img src="https://i.stack.imgur.com/wtGzy.png" alt="enter image description here"></p> <p>For greater control the idea with libraries like bootstrap is that you style your elements with CSS so for example we can add a class to each row and set its height and other attributes as we please:</p> <pre><code>library(shiny) runApp(list( ui = fluidPage( fluidRow(class = "myRow1", column(6,div(style = "height:200px;background-color: yellow;", "Topleft")), column(6,div(style = "height:100px;background-color: blue;", "Topright"))), fluidRow(class = "myRow2", column(6,div(style = "height:100px;background-color: green;", "Bottomleft")), column(6,div(style = "height:150px;background-color: red;", "Bottomright"))) , tags$head(tags$style(" .myRow1{height:250px;} .myRow2{height:350px;background-color: pink;}" ) ) ), server = function(input, output) { } )) </code></pre> <p><img src="https://i.stack.imgur.com/pBH2Q.png" alt="enter image description here"></p> <p>We passed a style tag to the head element here to stipulate our styling. There are a number of ways styling can be achieved see <a href="http://shiny.rstudio.com/articles/css.html" rel="noreferrer">http://shiny.rstudio.com/articles/css.html</a></p>
10,844,641
How to change the path to php.ini in PHP CLI version
<p>The php that run on the webserver and the CLI version is not using the same php.ini file. If I do a command <code>php --ini</code>, it show this</p> <pre class="lang-none prettyprint-override"><code>Configuration File (php.ini) Path: C:\Windows Loaded Configuration File: C:\wamp\bin\php\php5.3.8\php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none) </code></pre> <p>while my web version uses the php.ini in <code>C:\wamp\bin\apache\Apache2.2.21\bin\php.ini</code>. This is probably very common for people using wamp.</p> <p>How do I change the Loaded Configuration File to read from <code>C:\wamp\bin\apache\Apache2.2.21\bin\php.ini</code> so I don't have to maintain 2 different php.ini versions?</p>
10,844,817
6
0
null
2012-06-01 04:59:24.21 UTC
9
2022-07-21 09:04:30.387 UTC
2012-06-01 05:18:39.827 UTC
user212218
null
null
654,989
null
1
34
command-line-interface|php
64,476
<p>Per <a href="http://php.net/configuration.file" rel="noreferrer">http://php.net/configuration.file</a>:</p> <blockquote> <p>php.ini is searched for in these locations (in order):</p> <ul> <li>SAPI module specific location (PHPIniDir directive in Apache 2, -c command line option in CGI and CLI, php_ini parameter in NSAPI, PHP_INI_PATH environment variable in THTTPD)</li> <li>The PHPRC environment variable. Before PHP 5.2.0, this was checked after the registry key mentioned below.</li> <li>As of PHP 5.2.0, the location of the php.ini file can be set for different versions of PHP. The following registry keys are examined in order: <ul> <li>[HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z], [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] and [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x], where x, y and z mean the PHP major, minor and release versions. If there is a value for IniFilePath in any of these keys, the first one found will be used as the location of the php.ini (Windows only).</li> <li>[HKEY_LOCAL_MACHINE\SOFTWARE\PHP], value of IniFilePath (Windows only).</li> </ul> </li> <li>Current working directory (except CLI).</li> <li>The web server's directory (for SAPI modules), or directory of PHP (otherwise in Windows).</li> <li>Windows directory (C:\windows or C:\winnt) (for Windows), or --with-config-file-path compile time option.</li> </ul> </blockquote> <p>For CLI, your best bet is probably either to set the <code>$PHPRC</code> environment variable for the account that will be executing scripts, or recompile PHP with a different <code>--with-config-file-path</code> configuration setting.</p> <p>You can also override the php.ini search dir on a per-execution basis by specifying the <code>-c</code> option when invoking PHP:</p> <pre> > php --help Usage: php [options] [-f] [--] [args...] ... -c | Look for php.ini file in this directory </pre>
10,456,044
what is a good invalid IP address to use for unit tests?
<p>I am writing unit tests for a client library. I want to test connecting with an invalid port and an invalid ip. What is a good ip address to use that won't potentially be routed somewhere? I don't want to make any assumptions about the network the machine running the unit tests is on. LOCALHOST seems like a bad choice since that is the valid machine running the server component and I want to test an invalid port separately. Is there an INVALID-IP reserved somewhere in the IPv4 spec?</p>
10,456,065
5
0
null
2012-05-04 20:57:05.533 UTC
15
2020-11-05 21:20:43.88 UTC
null
null
null
null
1,195,522
null
1
64
unit-testing|tcp|ip
38,194
<p>According to <a href="https://www.rfc-editor.org/rfc/rfc5737" rel="noreferrer">RFC 5737</a>:</p> <blockquote> <p>The blocks 192.0.2.0/24 (TEST-NET-1), 198.51.100.0/24 (TEST-NET-2), and 203.0.113.0/24 (TEST-NET-3) are provided for use in documentation.</p> </blockquote> <p>This means you can use pick an IP address from these ranges:</p> <ul> <li>192.0.2.0 - 192.0.2.255</li> <li>198.51.100.0 - 198.51.100.255</li> <li>203.0.113.0 - 203.0.113.255</li> </ul>
5,666,523
iOS: Connect to Facebook without leaving the app for authorization
<p>I know that it was possible before the Graph API.</p> <p>I work on an iPhone app that may not be in the background (one of the requirements).<br> In addition there is a login screen on the app launching.<br> Therefore it is not suitable to go to background in order to authenticate to Facebook and then return to the app and login once again each time the user wants to share something.</p> <p>So, my question is if there is a way to authenticate with Facebook without leaving the app.</p> <p>BTW, I have tried to use the old API.<br> It worked in the beginning but yesterday it stopped working.<br> I just see a blank screen inside the old Facebook login web view.<br> I have also checked one of my old apps that use that old Facebook Connect API and I get the same blank login screen in that app too.</p> <p>Any idea will be appreciated.</p> <p>Thank you in advance.</p> <p>--<br> Michael.</p>
5,666,558
2
0
null
2011-04-14 16:36:03.603 UTC
9
2011-09-02 13:16:12.05 UTC
null
null
null
null
246,119
null
1
7
iphone|ios|facebook|background|facebook-graph-api
6,585
<p>In Facebook.m </p> <pre><code>- (void)authorizeWithFBAppAuth:(BOOL)tryFBAppAuth safariAuth:(BOOL)trySafariAuth { NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys: _appId, @"client_id", @"user_agent", @"type", kRedirectURL, @"redirect_uri", @"touch", @"display", kSDKVersion, @"sdk", nil]; </code></pre> <p>method comment out this</p> <pre><code> UIDevice *device = [UIDevice currentDevice]; if ([device respondsToSelector:@selector(isMultitaskingSupported)] &amp;&amp; [device isMultitaskingSupported]) { if (tryFBAppAuth) { NSString *fbAppUrl = [FBRequest serializeURL:kFBAppAuthURL params:params]; didOpenOtherApp = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:fbAppUrl]]; } if (trySafariAuth &amp;&amp; !didOpenOtherApp) { NSString *nextUrl = [NSString stringWithFormat:@"fb%@://authorize", _appId]; [params setValue:nextUrl forKey:@"redirect_uri"]; NSString *fbAppUrl = [FBRequest serializeURL:loginDialogURL params:params]; didOpenOtherApp = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:fbAppUrl]]; } } </code></pre> <p>This will prevent the app from going to background and show you the standard fb dialog.</p>
5,892,176
Getting cookies in a google chrome extension
<p>I am trying to get a cookie specifically from a domain using this code:</p> <pre><code>&lt;script language="javascript" type="text/javascript"&gt; var ID; function getCookies(domain, name) { chrome.cookies.get({"url": domain, "name": name}, function(cookie) { ID = cookie.value; }); } getCookies("http://www.example.com", "id") alert(ID); &lt;/script&gt; </code></pre> <p>The problem is that the alert always says undefined. However, if I change</p> <pre><code>ID = cookie.value; </code></pre> <p>to</p> <pre><code>alert(cookie.value); </code></pre> <p>it works properly. How do I save the value to use later?</p> <p>Update: It appears that if I call alert(ID) from the chrome console after the script runs, it works. How can I set my code to wait until chrome.cookies.get finishes running?</p>
5,892,242
2
0
null
2011-05-05 03:02:38.567 UTC
10
2020-08-05 20:38:58.747 UTC
2015-11-15 22:16:03.5 UTC
null
516,476
null
516,476
null
1
18
javascript|google-chrome|google-chrome-extension
55,356
<p>Almost all Chrome API calls are asynchronous, so you need to use callbacks to run code in order:</p> <pre><code>function getCookies(domain, name, callback) { chrome.cookies.get({"url": domain, "name": name}, function(cookie) { if(callback) { callback(cookie.value); } }); } //usage: getCookies("http://www.example.com", "id", function(id) { alert(id); }); </code></pre>
60,365,440
How to programmatically use bootstrap icons in an angular project?
<p>Here is the <a href="https://icons.getbootstrap.com/#usage" rel="noreferrer">official bootstrap documentation</a> on the usage of their icons:</p> <p><a href="https://i.stack.imgur.com/N4z2R.png" rel="noreferrer"><img src="https://i.stack.imgur.com/N4z2R.png" alt="enter image description here"></a></p> <p>I'm trying to figure out how to use the package, if I'm supposed to be using it at all. None of their usage options say <strong>anything</strong> about the package I was told to install 6 seconds ago.</p> <p>I just don't understand why the documentation would tell me to install the package if all I was supposed to do was copy the svg's I needed and then uninstall the package.</p> <p>Is there some way for me to import one into an angular component, in the spirit of actual source control?</p> <p>EDIT: in response to why I'm not using the following html as recommended in an answer <code>&lt;svg class="bi bi-chevron-right" width="32" height="32" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg"&gt;&lt;path fill-rule="evenodd" d="M6.646 3.646a.5.5 0 01.708 0l6 6a.5.5 0 010 .708l-6 6a.5.5 0 01-.708-.708L12.293 10 6.646 4.354a.5.5 0 010-.708z" clip-rule="evenodd"/&gt;&lt;/svg&gt;</code></p> <p>is because this doesn't use the bootstrap icon library at all. Pasted into your response for demonstration, and stack overflow doesn't use bootstrap.</p> <p><a href="https://i.stack.imgur.com/5GYkx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5GYkx.png" alt="enter image description here"></a></p>
65,440,311
5
0
null
2020-02-23 18:28:08.387 UTC
5
2021-06-15 12:23:31.997 UTC
2020-02-23 19:18:37.213 UTC
null
8,652,920
null
8,652,920
null
1
31
angular|typescript|bootstrap-4|icons
39,084
<p>Quite old, but since I had the same problem and these answers where not helpful at all, here is the Solution I came up with.</p> <p>First install the bootstrap icons package (--save adds it to your dependencies as well):</p> <pre><code>$ npm i bootstrap-icons --save </code></pre> <p>Then add this line to your styles.css file:</p> <pre><code>@import &quot;~bootstrap-icons/font/bootstrap-icons.css&quot;; </code></pre> <p>From now on you can use it anywhere in your app, just like intended by the bootstrap documentation:</p> <pre><code>&lt;i class=&quot;bi bi-star-fill&quot;&gt;&lt;/i&gt; </code></pre>
23,417,403
TypeError: argument of type 'NoneType' is not iterable
<p>I am making a Hangman game in Python. In the game, one python file has a function that selects a random string from an array and stores it in a variable. That variable is then passed to a function in another file. That function stores a users guess as a string in a variable, then checks to see if that guess is in the word. However, whenever I type a letter and press enter, I get the error in the title of this question. Just so you know, I'm using Python 2.7. Here's the code for the function that takes a word:</p> <pre><code>import random easyWords = ["car", "dog", "apple", "door", "drum"] mediumWords = ["airplane", "monkey", "bananana", "window", "guitar"] hardWords = ["motorcycle", "chuckwalla", "strawberry", "insulation", "didgeridoo"] wordCount = [] #is called if the player chooses an easy game. #The words in the array it chooses are the shortest. #the following three functions are the ones that #choose the word randomly from their respective arrays. def pickEasy(): word = random.choice(easyWords) word = str(word) for i in range(1, len(word) + 1): wordCount.append("_") #is called when the player chooses a medium game. def pickMedium(): word = random.choice(mediumWords) for i in range(1, len(word) + 1): wordCount.append("_") #is called when the player chooses a hard game. def pickHard(): word = random.choice(hardWords) for i in range(1, len(word) + 1): wordCount.append("_") </code></pre> <p>Now here is the code that takes the users guess and determines whether or not it is in the word chosen for the game (Pay no attention to the wordCount variable. Also, "words" is the name of the file with the code above.)):</p> <pre><code>from words import * from art import * def gamePlay(difficulty): if difficulty == 1: word = pickEasy() print start print wordCount getInput(word) elif difficulty == 2: word = pickMedium() print start print wordCount elif difficulty == 3: word = pickHard() print start print wordCount def getInput(wordInput): wrong = 0 guess = raw_input("Type a letter to see if it is in the word: \n").lower() if guess in wordInput: print "letter is in word" else: print "letter is not in word" </code></pre> <p>So far I have tried converting the "guess" variable in the gamePlay function to a string with str(), I've tried making it lowercase with .lower(), and I've done similar things in the words file. Here is the full error I get when I run this:</p> <pre><code>File "main.py", line 42, in &lt;module&gt; main() File "main.py", line 32, in main diff() File "main.py", line 17, in diff gamePlay(difficulty) File "/Users/Nathan/Desktop/Hangman/gameplay.py", line 9, in gamePlay getInput(word) File "/Users/Nathan/Desktop/Hangman/gameplay.py", line 25, in getInput if guess in wordInput: </code></pre> <p>The "main.py" you see is another python file I wrote. If you would like to see the others let me know. However, I feel the ones I've shown are the only important ones. Thank you for your time! Let me know if I left out any important details.</p>
23,417,508
2
0
null
2014-05-01 22:01:52.687 UTC
10
2014-05-01 22:11:15.21 UTC
null
null
null
null
2,446,135
null
1
22
python|python-2.7
173,217
<p>If a function does not return anything, e.g.:</p> <pre><code>def test(): pass </code></pre> <p>it has an implicit return value of <code>None</code>.</p> <p>Thus, as your <code>pick*</code> methods do not return anything, e.g.:</p> <pre><code>def pickEasy(): word = random.choice(easyWords) word = str(word) for i in range(1, len(word) + 1): wordCount.append("_") </code></pre> <p>the lines that call them, e.g.:</p> <pre><code>word = pickEasy() </code></pre> <p>set <code>word</code> to <code>None</code>, so <code>wordInput</code> in <code>getInput</code> is <code>None</code>. This means that:</p> <pre><code>if guess in wordInput: </code></pre> <p>is the equivalent of:</p> <pre><code>if guess in None: </code></pre> <p>and <code>None</code> is an instance of <code>NoneType</code> which does not provide iterator/iteration functionality, so you get that type error.</p> <p>The fix is to add the return type:</p> <pre><code>def pickEasy(): word = random.choice(easyWords) word = str(word) for i in range(1, len(word) + 1): wordCount.append("_") return word </code></pre>
52,431,764
Difference between OpenJDK and Adoptium/AdoptOpenJDK
<p>Due to recent <a href="https://www.oracle.com/technetwork/java/javase/eol-135779.html" rel="noreferrer">Oracle Java SE Support Roadmap</a> policy update (end of $free release updates from Oracle after March 2019 in particular), I've been searching for alternatives to Oracle Java. I've found that OpenJDK is an open-source alternative. And I've found <a href="https://adoptopenjdk.net/" rel="noreferrer">AdoptOpenJDK</a>, <a href="https://blog.adoptopenjdk.net/2020/06/adoptopenjdk-to-join-the-eclipse-foundation/" rel="noreferrer">now known</a> as Adoptium, which is a <em>prebuilt binary</em>. It puzzles.</p> <p>What is the difference between OpenJDK and Adoptium/AdoptOpenJDK?</p>
52,431,765
2
1
null
2018-09-20 19:10:58.573 UTC
167
2022-06-08 17:31:12.877 UTC
2020-12-18 19:28:06.38 UTC
null
418,413
null
3,523,579
null
1
331
java|sdk|adoptopenjdk
197,710
<p>In short:</p> <ul> <li><strong>OpenJDK</strong> has multiple meanings and can refer to:</li> <li>free and open source implementation of the Java Platform, Standard Edition (Java SE)</li> <li><a href="//hg.openjdk.java.net" rel="noreferrer">open source repository</a> — the Java source code aka OpenJDK project</li> <li>prebuilt OpenJDK binaries maintained by Oracle</li> <li>prebuilt OpenJDK binaries maintained by the OpenJDK community</li> <li><strong>AdoptOpenJDK</strong> — prebuilt OpenJDK binaries maintained by community (<a href="//adoptopenjdk.net/about.html" rel="noreferrer">open source licensed</a>)</li> </ul> <hr /> <p>Explanation:</p> <p><strong>Prebuilt OpenJDK</strong> (or distribution) — binaries, built from <a href="https://hg.openjdk.java.net/" rel="noreferrer">https://hg.openjdk.java.net/</a>, provided as an archive or installer, offered for various platforms, with a possible support contract.</p> <p><strong>OpenJDK, the source repository</strong> (also called <strong>OpenJDK project</strong>) - is a <a href="//en.wikipedia.org/wiki/Mercurial" rel="noreferrer">Mercurial</a>-based open source repository, hosted at <a href="https://hg.openjdk.java.net" rel="noreferrer">https://hg.openjdk.java.net</a>. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.</p> <p><strong>OpenJDK, the distribution</strong> (see the list of providers below) - is <a href="//en.wiktionary.org/wiki/free_as_in_beer" rel="noreferrer">free as in beer</a> and kind of <a href="//en.wiktionary.org/wiki/free_as_in_speech" rel="noreferrer">free as in speech</a>, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.</p> <p>Some OpenJDK projects - such as <a href="https://wiki.openjdk.java.net/display/jdk8u" rel="noreferrer">OpenJDK 8</a> and <a href="https://wiki.openjdk.java.net/display/JDKUpdates/JDK11u" rel="noreferrer">OpenJDK 11</a> - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.</p> <p><strong>AdoptOpenJDK, the distribution</strong> is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.</p> <p><strong>OracleJDK</strong> - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.</p> <p><em>Note</em>. It may be best to call the OpenJDK builds by Oracle the &quot;Oracle OpenJDK builds&quot;.</p> <p>Donald Smith, Java product manager at Oracle <a href="//blogs.oracle.com/java-platform-group/oracle-jdk-releases-for-java-11-and-later" rel="noreferrer">writes</a>:</p> <blockquote> <p>Ideally, we would simply refer to all Oracle JDK builds as the &quot;Oracle JDK&quot;, either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.</p> </blockquote> <hr /> <h2>OpenJDK Providers and Comparison</h2> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Provider</th> <th>Free Builds<br>from Source</th> <th>Free Binary<br>Distributions</th> <th>Extended<br>Updates</th> <th>Commercial<br>Support</th> <th>Permissive<br>License</th> <th>Website</th> </tr> </thead> <tbody> <tr> <td>AdoptOpenJDK</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td><a href="https://adoptopenjdk.net" rel="noreferrer">https://adoptopenjdk.net</a></td> </tr> <tr> <td>Amazon – Corretto</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td><a href="https://aws.amazon.com/corretto" rel="noreferrer">https://aws.amazon.com/corretto</a></td> </tr> <tr> <td>Azul Zulu</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td><a href="https://www.azul.com/downloads/zulu/" rel="noreferrer">https://www.azul.com/downloads/zulu/</a></td> </tr> <tr> <td>BellSoft Liberica</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td><a href="https://bell-sw.com/java.html" rel="noreferrer">https://bell-sw.com/java.html</a></td> </tr> <tr> <td>IBM</td> <td>No</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td><a href="https://www.ibm.com/developerworks/java/jdk" rel="noreferrer">https://www.ibm.com/developerworks/java/jdk</a></td> </tr> <tr> <td>jClarity</td> <td>No</td> <td>No</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td><a href="https://www.jclarity.com/adoptopenjdk-support/" rel="noreferrer">https://www.jclarity.com/adoptopenjdk-support/</a></td> </tr> <tr> <td>OpenJDK</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>Yes</td> <td><a href="https://adoptopenjdk.net/upstream.html" rel="noreferrer">https://adoptopenjdk.net/upstream.html</a></td> </tr> <tr> <td>Oracle JDK</td> <td>No</td> <td>Yes</td> <td>No**</td> <td>Yes</td> <td>No</td> <td><a href="https://www.oracle.com/technetwork/java/javase/downloads" rel="noreferrer">https://www.oracle.com/technetwork/java/javase/downloads</a></td> </tr> <tr> <td>Oracle OpenJDK</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>No</td> <td>Yes</td> <td><a href="https://jdk.java.net" rel="noreferrer">https://jdk.java.net</a></td> </tr> <tr> <td>ojdkbuild</td> <td>Yes</td> <td>Yes</td> <td>No</td> <td>No</td> <td>Yes</td> <td><a href="https://github.com/ojdkbuild/ojdkbuild" rel="noreferrer">https://github.com/ojdkbuild/ojdkbuild</a></td> </tr> <tr> <td>RedHat</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td><a href="https://developers.redhat.com/products/openjdk/overview" rel="noreferrer">https://developers.redhat.com/products/openjdk/overview</a></td> </tr> <tr> <td>SapMachine</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td>Yes</td> <td><a href="https://sap.github.io/SapMachine" rel="noreferrer">https://sap.github.io/SapMachine</a></td> </tr> </tbody> </table> </div> <p><sub> <strong>Free Builds from Source</strong> - the distribution source code is publicly available and one can assemble its own build </sub></p> <p><sub> <strong>Free Binary Distributions</strong> - the distribution binaries are publicly available for download and usage </sub></p> <p><sub> <strong>Extended Updates</strong> - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle </sub></p> <p><sub> <strong>Commercial Support</strong> - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (<a href="//www.oracle.com/java/java-se-subscription.html" rel="noreferrer">support details</a>) </sub></p> <p><sub> <strong>Permissive License</strong> - the distribution license is non-protective, e.g. Apache 2.0 </sub></p> <hr /> <h2>Which Java Distribution Should I Use?</h2> <p>In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their <a href="https://jdk.java.net/" rel="noreferrer">https://jdk.java.net/</a> site.</p> <p>What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.</p> <p>Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).</p> <p>If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most <em>standard</em> JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.</p> <hr /> <p><strong>Additional information</strong></p> <p><a href="//blog.joda.org/2018/09/time-to-look-beyond-oracles-jdk.html" rel="noreferrer">Time to look beyond Oracle's JDK</a> by Stephen Colebourne</p> <p><a href="//medium.com/@javachampions/java-is-still-free-c02aef8c9e04" rel="noreferrer">Java Is Still Free</a> by Java Champions community (published on September 17, 2018)</p> <p><a href="//medium.com/@javachampions/java-is-still-free-2-0-0-6b9aa8d6d244" rel="noreferrer">Java is Still Free 2.0.0</a> by Java Champions community (published on March 3, 2019)</p> <p><a href="//www.opsian.com/blog/aleksey-shipilev-on-jdk-updates/" rel="noreferrer">Aleksey Shipilev about JDK updates</a> interview by Opsian (published on June 27, 2019)</p>
53,191,753
Get react-select selected option when using multi dropdown
<p>I have two working <a href="https://github.com/JedWatson/react-select/" rel="noreferrer">react-select</a> drop downs on my page, one that allows the user to select A or B, and one that allows them to choose multiple items from &quot;blue, yellow , red&quot;.</p> <p>When they have chosen these items, I want to use them. For now I just want to check the values that have been selected, so I'm just printing them to screen. For the single selection drop down I have used the example code from the github successfully. This is as follows:</p> <pre><code>import React from 'react'; import Select from 'react-select'; const options = [ { value: 'a', label: 'a' }, { value: 'b', label: 'b' }, ]; class App extends React.Component { state = { selectedOption: null, } handleChange = (selectedOption) =&gt; { this.setState({ selectedOption }); document.write(`Option selected:`, selectedOption.value); //this prints the selected option } render() { const { selectedOption } = this.state; return ( &lt;Select value={selectedOption} onChange={this.handleChange} options={options} //isMulti //added when the user can pick more than one /&gt; ); } } </code></pre> <p>My question is how do I successfully do this for the multi option? The user can select as many as they wish, but an 'undefined' error is thrown when it prints the option that has been selected. I think this is because the option is stored in an array but I'm not sure.</p> <p>Thanks all.</p>
53,192,114
3
0
null
2018-11-07 14:45:07.413 UTC
1
2020-07-06 13:49:34.603 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
10,618,834
null
1
13
javascript|reactjs|react-select
43,412
<p>You need to change the <code>handleChange</code> to deal with the <code>isMulti</code>. Here's an example:</p> <pre><code>import React, { Component } from 'react'; import { render } from 'react-dom'; import Select from 'react-select'; const options = [ { value: 'a', label: 'a' }, { value: 'b', label: 'b' }, ]; class App extends React.Component { state = { selectedOptions: [], } handleChange = (selectedOptions) =&gt; { this.setState({ selectedOptions }); } render() { const { selectedOptions } = this.state; return ( &lt;React.Fragment&gt; &lt;Select isMulti value={selectedOption} onChange={this.handleChange} options={options} /&gt; {selectedOptions.map(o =&gt; &lt;p&gt;{o.value}&lt;/p&gt;)} &lt;/React.Fragment&gt; ); } } render(&lt;App /&gt;, document.getElementById('root')); </code></pre> <p>Here's a working example: <a href="https://stackblitz.com/edit/react-czf4ib" rel="noreferrer">https://stackblitz.com/edit/react-czf4ib</a></p>
46,717,693
Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory
<h2>The problem</h2> <p>Whenever I run my projects JUnit test (using JUnit 5 with Java 9 and Eclipse Oxygen 1.a) I encounter the problem that eclipse can't find any tests.</p> <h2>The description</h2> <p>Under the run configuration, eclipse can't even find the method which is annotated with @Test, but instead only shows me "<em>(all methods)</em>". The following picture hopefully gives a better glimps of my setup:</p> <p><a href="https://i.stack.imgur.com/wVTPt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wVTPt.png" alt="https://imgur.com/a/FTe9c"></a></p> <h2>Console output:</h2> <pre><code>java.lang.NoClassDefFoundError: org/junit/platform/launcher/core/LauncherFactory at org.eclipse.jdt.internal.junit5.runner.JUnit5TestLoader.&lt;init&gt;(JUnit5TestLoader.java:31) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.base/java.lang.reflect.Constructor.newInstance(Unknown Source) at java.base/java.lang.Class.newInstance(Unknown Source) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createRawTestLoader(RemoteTestRunner.java:368) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.createLoader(RemoteTestRunner.java:363) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.defaultInit(RemoteTestRunner.java:307) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.init(RemoteTestRunner.java:222) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206) Caused by: java.lang.ClassNotFoundException: org.junit.platform.launcher.core.LauncherFactory at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(Unknown Source) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(Unknown Source) at java.base/java.lang.ClassLoader.loadClass(Unknown Source) ... 11 more </code></pre> <h2>What I tried so far</h2> <p>I've already tried</p> <ul> <li>to remove the test folder from build path and add it again.</li> <li>to start the test with hovering over the method annotated with @Test and then click "Run as JUnit Test". </li> <li>remove JUnit from Buildpath and add it again</li> <li>restart eclipse</li> <li>I've also moved the project whole project from one machine to another machine and tried it with the provided eclipse installation there</li> <li>to rename the test method.</li> <li>to retype the @Test annotation</li> </ul> <p>Some of these steps <a href="https://stackoverflow.com/questions/20057771/no-junit-tests-found-in-eclipse">can be found here</a>, but in the end the problem remained.</p>
46,723,851
46
1
null
2017-10-12 19:44:33.89 UTC
20
2022-09-15 01:12:55.143 UTC
2021-03-26 13:41:26.623 UTC
null
236,247
null
6,307,084
null
1
126
java|eclipse|junit|junit5
261,664
<p>You ran into <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=525948" rel="noreferrer"><strong>Eclipse bug 525948</strong></a> which has already been fixed and which will be published in the upcoming release Oxygen.3 (4.7.3), March 21, 2018.</p> <p>As workaround, <strong>put your test code in a separate project</strong> and add the project under test to the modulepath, but do not add a <code>module-info.java</code> to your test project. With your project, class and module naming, it should look something like this:</p> <p><a href="https://i.stack.imgur.com/NBXME.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NBXME.png" alt="enter image description here"></a></p> <p>See also <a href="https://www.youtube.com/watch?v=wI3VC1lhbK8" rel="noreferrer">my video that shows Java 9 and JUnit 5 in Eclipse Oxygen.1a in action</a></p>
8,987,926
how to find which packets got dropped
<p>I'm getting thousands of dropped packages from a Broadcom Network Card:</p> <pre><code>eth1 Link encap:Ethernet HWaddr 01:27:B0:14:DA:FE UP BROADCAST RUNNING SLAVE MULTICAST MTU:1500 Metric:1 RX packets:2746252626 errors:0 dropped:1151734 overruns:0 frame:0 TX packets:4109502155 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:427998700000 (408171.3 Mb) TX bytes:3530782240047 (3367216.3 Mb) Interrupt:40 Memory:d8000000-d8012700 </code></pre> <p>Here is the installed version:</p> <pre><code>filename: /lib/modules/2.6.27.54-0.2-default/kernel/drivers/net/bnx2.ko version: 1.8.0 license: GPL description: Broadcom NetXtreme II BCM5706/5708/5709 Driver </code></pre> <p>The packets get dropped in bulks ranging from 500 to 5000 packets several times an hour. The Server (running Postgres) is running fine - just the dropps are annoying.</p> <p>After trying lots of different things, I'm asking: How may I find out where the packets came from and why were they dropped?</p>
22,710,199
3
0
null
2012-01-24 13:50:27.53 UTC
5
2015-06-08 07:48:31.96 UTC
null
null
null
null
1,165,144
null
1
11
linux|networking|broadcom
40,743
<p>(For the benefit of those that come to this via a search) I've seen the same problem (also with a bnx2 module, IIRC).</p> <p>You might try turning off the irqbalance service. In my case, it completely stopped the solution.</p> <p>Please also note that not so long ago, there were plenty of updates (RHEL 6) for irqbalance. Firmware updates should also be checked for both main system and the ethernet board(s).</p> <p>We were seeing this only a very large subnet with a very large amount of broadcast/multicast activity. We weren't seeing this on the same equipment on a less noisy -- but still very active -- part of the network.</p> <p>Potentially, setting the ethernet ring buffer size for the NIC can also be of use. I know there were some alterations for sysctl on that busy network...</p>
8,698,726
Constructor function vs Factory functions
<p>Can someone clarify the difference between a constructor function and a factory function in Javascript.</p> <p>When to use one instead of the other?</p>
8,699,045
9
0
null
2012-01-02 08:19:55.917 UTC
123
2022-02-03 12:29:35.647 UTC
null
null
null
null
256,895
null
1
180
javascript|oop
72,372
<p>The basic difference is that a constructor function is used with the <code>new</code> keyword (which causes JavaScript to automatically create a new object, set <code>this</code> within the function to that object, and return the object):</p> <pre><code>var objFromConstructor = new ConstructorFunction(); </code></pre> <p>A factory function is called like a "regular" function:</p> <pre><code>var objFromFactory = factoryFunction(); </code></pre> <p>But for it to be considered a "factory" it would need to return a new instance of some object: you wouldn't call it a "factory" function if it just returned a boolean or something. This does not happen automatically like with <code>new</code>, but it does allow more flexibility for some cases.</p> <p>In a really simple example the functions referenced above might look something like this:</p> <pre><code>function ConstructorFunction() { this.someProp1 = "1"; this.someProp2 = "2"; } ConstructorFunction.prototype.someMethod = function() { /* whatever */ }; function factoryFunction() { var obj = { someProp1 : "1", someProp2 : "2", someMethod: function() { /* whatever */ } }; // other code to manipulate obj in some way here return obj; } </code></pre> <p>Of course you can make factory functions much more complicated than that simple example.</p> <p>One advantage to factory functions is when the object to be returned could be of several different types depending on some parameter.</p>
48,008,675
Run Docker on Ubuntu on Windows Subsystem for Linux
<p>I've tried to run Docker on WSL unsuccessfully. I've installed Docker on WSL following the steps given to <a href="https://docs.docker.com/engine/installation/linux/docker-ce/ubuntu/" rel="noreferrer">install Docker on Ubuntu</a> but when I execute <code>docker ps</code> I get the following error:</p> <pre><code>docker ps Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? </code></pre> <p>Watching docker logs I found this:</p> <pre><code>level=warning msg="Running modprobe nf_nat failed with message: `modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.4.0-43-Microsoft/modules.dep.bin'\nmodprobe: WARNING: Module nf_nat not found in directory /lib/modules/4.4.0-43-Microsoft`, error: exit status 1" time="2017-12-28T12:07:23.227671600+01:00" level=warning msg="Running modprobe xt_conntrack failed with message: `modprobe: ERROR: ../libkmod/libkmod.c:586 kmod_search_moddep() could not open moddep file '/lib/modules/4.4.0-43-Microsoft/modules.dep.bin'\nmodprobe: WARNING: Module xt_conntrack not found in directory /lib/modules/4.4.0-43-Microsoft`, error: exit status 1" Error starting daemon: Error initializing network controller: error obtaining controller instance: failed to create NAT chain: iptables failed: iptables -t nat -N DOCKER: iptables v1.6.0: can't initialize iptables table `nat': Table does not exist (do you need to insmod?) Perhaps iptables or your kernel needs to be upgraded. (exit status 3) </code></pre> <p>Any idea how can I run Docker on WSL?</p>
48,008,676
11
0
null
2017-12-28 13:48:56.483 UTC
18
2022-01-25 16:06:25.787 UTC
2018-07-07 12:02:27.74 UTC
null
995,714
null
6,135,178
null
1
31
windows|docker|windows-subsystem-for-linux
42,169
<p>Finally, I could run Docker on WSL in an easy way: You need first to install and run Docker Engine on Windows and then just create a symbolic link on Ubuntu bash pointing to the Windows executable:</p> <pre><code>sudo ln -s /mnt/c/Program\ Files/Docker/Docker/resources/bin/docker.exe /usr/bin/docker </code></pre> <p>This link works because from version <strong><em>Windows 10 Creators Update</em></strong> it's possible to run Windows executables from Bash. If your Windows version is previous to Windows 10 Creators Update you can try the <a href="https://blog.jayway.com/2017/04/19/running-docker-on-bash-on-windows/" rel="noreferrer">solution explained in this blog</a></p>
59,958,294
How do I Execute Terraform Actions Without the Interactive Prompt?
<p>How am I able to execute the following command:</p> <pre class="lang-sh prettyprint-override"><code>terraform apply #=&gt; . . . Do you want to perform these actions? Terraform will perform the actions described above. Only 'yes' will be accepted to approve. Enter a value: </code></pre> <p><strong>without</strong> the interactive prompt that follows?</p>
59,958,372
2
0
null
2020-01-28 22:51:57.027 UTC
7
2022-08-21 19:34:59.697 UTC
2022-02-23 22:52:02.38 UTC
null
472,495
null
4,415,079
null
1
41
terraform
17,032
<pre class="lang-sh prettyprint-override"><code>terraform apply -auto-approve </code></pre> <p><a href="https://www.terraform.io/docs/commands/apply.html#auto-approve" rel="noreferrer">https://www.terraform.io/docs/commands/apply.html#auto-approve</a></p>
27,158,106
WebSocket with Sockjs & Spring 4 but without Stomp
<p>Is there a way to use WebSockets with SockJS client and Spring 4 server but not using STOMP?</p> <p>Based on this tutorial from Spring's website, I know how to set up a WebSocket based application using Stomp and Spring 4. On the client side, we have:</p> <pre><code> var socket = new SockJS('/hello'); stompClient = Stomp.over(socket); stompClient.connect({}, function(frame) { setConnected(true); console.log('Connected: ' + frame); stompClient.subscribe('/topic/greetings', function(greeting){ showGreeting(JSON.parse(greeting.body).content); }); }); </code></pre> <p>And on the server side, we have the following in the controller:</p> <pre><code>@MessageMapping("/hello") @SendTo("/topic/greetings") public Greeting greeting(HelloMessage message) throws Exception { Thread.sleep(3000); // simulated delay return new Greeting("Hello, " + message.getName() + "!"); } </code></pre> <p>Now, I understand that <code>@MessageMapping("/hello")</code> ensures that if a message is sent to a destination <code>"/hello"</code>, then the <code>greeting()</code> method will be called. And since the <code>stompClient</code> is subscribed to <code>"/topic/greetings"</code>, the <code>@SendTo("/topic/greetings")</code> will send the message back to the <code>stompClient</code>.</p> <p>But the problem with the above is that stompClient is a Stomp object. And I want to simply use <code>sock.send('test');</code> and have it delivered to my server's destination. And I want to do <code>@SendTo("myownclientdestinationmap")</code>, I can receive it by </p> <pre><code>sock.onmessage = function(e) { console.log('message', e.data); }; </code></pre> <p>So, any way to do this with Spring 4, SockJS and without Stomp? Or does Spring 4 WebSocket only supports Stomp?</p>
27,161,986
1
1
null
2014-11-26 20:15:28.943 UTC
33
2015-03-11 15:24:34.737 UTC
null
null
null
null
1,244,329
null
1
40
java|websocket|sockjs|spring-4
24,499
<p>Spring supports <code>STOMP</code> over <code>WebSocket</code> but the use of a subprotocol is <strong>not mandatory</strong>, you can deal with the raw websocket. When using a raw websocket, the message sent lacks of information to make Spring route it to a specific message handler method (we don't have any messaging protocol), so instead of annotating your controller, you'll have to implement a <code>WebSocketHandler</code>:</p> <pre><code>public class GreetingHandler extends TextWebSocketHandler { @Override public void handleTextMessage(WebSocketSession session, TextMessage message) { Thread.sleep(3000); // simulated delay TextMessage msg = new TextMessage("Hello, " + message.getPayload() + "!"); session.sendMessage(msg); } } </code></pre> <p>And then add your handler to the registry in the configuration (you can add more than one handler and use <code>SockJS</code> for fallback options):</p> <pre><code>@Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(greetingHandler(), "/greeting").withSockJS(); } @Bean public WebSocketHandler greetingHandler() { return new GreetingHandler(); } } </code></pre> <p>The client side will be something like this:</p> <pre><code>var sock = new SockJS('http://localhost:8080/greeting'); sock.onmessage = function(e) { console.log('message', e.data); } </code></pre>
4,922
Is this really widening vs autoboxing?
<p>I saw this in <a href="https://stackoverflow.com/a/4384/697449">an answer to another question</a>, in reference to shortcomings of the Java spec:</p> <blockquote> <p>There are more shortcomings and this is a subtle topic. Check <a href="http://kiranthakkar.blogspot.com/2007/05/method-overloading-with-new-features-of.html" rel="noreferrer">this</a> out:</p> <pre><code>public class methodOverloading{ public static void hello(Integer x){ System.out.println(&quot;Integer&quot;); } public static void hello(long x){ System.out.println(&quot;long&quot;); } public static void main(String[] args){ int i = 5; hello(i); } } </code></pre> <p>Here &quot;long&quot; would be printed (haven't checked it myself), because the compiler chooses widening over auto-boxing. Be careful when using auto-boxing or don't use it at all!</p> </blockquote> <p><em>Are we sure that this is actually an example of widening instead of autoboxing, or is it something else entirely?</em></p> <p>On my initial scanning, I would agree with the statement that the output would be &quot;long&quot; on the basis of <code>i</code> being declared as a primitive and not an object. However, if you changed</p> <pre><code>hello(long x) </code></pre> <p>to</p> <pre><code>hello(Long x) </code></pre> <p>the output would print &quot;Integer&quot;</p> <p>What's really going on here? I know nothing about the compilers/bytecode interpreters for java...</p>
5,091
3
1
null
2008-08-07 16:30:32.18 UTC
null
2018-04-24 20:33:39.063 UTC
2020-06-20 09:12:55.06 UTC
Andy
-1
null
670
null
1
31
java|primitive|autoboxing
4,552
<p>In the first case, you have a widening conversion happening. This can be see when runinng the "javap" utility program (included w/ the JDK), on the compiled class:</p> <pre><code>public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: i2l 4: invokestatic #6; //Method hello:(J)V 7: return } </code></pre> <p>Clearly, you see the I2L, which is the mnemonic for the widening Integer-To-Long bytecode instruction. See reference <a href="http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html" rel="noreferrer">here</a>.</p> <p>And in the other case, replacing the "long x" with the object "Long x" signature, you'll have this code in the main method:</p> <pre><code>public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: invokestatic #6; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 6: invokestatic #7; //Method hello:(Ljava/lang/Integer;)V 9: return } </code></pre> <p>So you see the compiler has created the instruction Integer.valueOf(int), to box the primitive inside the wrapper.</p>
1,254,512
Decrease line spacing in a TextBlock / FlowDocument
<p>Some fonts have a large amount of whitespace above and below the characters. Is there a way to correct for that, and tighten up the space between lines of a word-wrapped paragraph in WPF (in either a TextBlock or a FlowDocument)? Kind of like a negative margin between lines?</p> <p>There's a <code>LineHeight</code> property on <code>Paragraph</code> and <code>TextBlock</code>, but it only seems to let you <em>increase</em> the spacing -- if you set it to a smaller value than the default, it's simply ignored.</p>
1,441,087
3
0
null
2009-08-10 12:08:02.273 UTC
4
2014-08-08 15:09:37.24 UTC
null
null
null
null
87,399
null
1
45
wpf|fonts|word-wrap
20,268
<p>Set the <code>LineHeight</code> like before, but change the <code>LineStackingStrategy</code> to <code>BlockLineHeight</code></p>
252,906
How to get the list of open windows from xserver
<p>Anyone got an idea how to get from an Xserver the list of all open windows?</p>
252,911
3
0
null
2008-10-31 08:53:18.42 UTC
15
2020-05-13 20:40:35.493 UTC
2010-09-08 07:28:12.097 UTC
Paul
300,863
kender
4,172
null
1
52
x11|xserver
39,577
<p>From the CLI you can use</p> <pre><code>xwininfo -tree -root </code></pre> <p>If you need to do this within your own code then you need to use the <code>XQueryTree</code> function from the <code>Xlib</code> library.</p>
39,643,394
Swift-3 error: '-[_SwiftValue unsignedIntegerValue]: unrecognized selector
<p>Following code was perfectly worked with old swift. This is an extension of String</p> <pre><code>func stringByConvertingHTML() -&gt; String { let newString = replacingOccurrences(of: "\n", with: "&lt;br&gt;") if let encodedData = newString.data(using: String.Encoding.utf8) { let attributedOptions : [String: AnyObject] = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject ] do { let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) //Crash here return attributedString.string } catch { return self } } return self } </code></pre> <p>But in swift 3 it crashes saying </p> <blockquote> <p>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue unsignedIntegerValue]: unrecognized selector sent to instance 0x6080002565f0'</p> </blockquote> <p>Anyone please suggest me what need to do?</p>
39,644,620
3
0
null
2016-09-22 15:41:33.28 UTC
8
2018-08-13 23:23:41.413 UTC
2016-09-22 15:51:33.22 UTC
null
1,810,390
null
1,810,390
null
1
56
ios|xcode|exception|swift3
11,675
<p>I ran into the same problem:</p> <pre><code>let attributedOptions : [String: AnyObject] = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject ] </code></pre> <p>Here the <code>String.Encoding.utf8</code> the type check fails. Use <code>NSNumber(value: String.Encoding.utf8.rawValue)</code></p>
41,990,250
What is cross-entropy?
<p>I know that there are a lot of explanations of what cross-entropy is, but I'm still confused.</p> <p>Is it only a method to describe the loss function? Can we use gradient descent algorithm to find the minimum using the loss function?</p>
41,990,932
3
2
null
2017-02-01 21:38:07.823 UTC
78
2021-06-26 02:06:44.6 UTC
2021-06-26 02:06:44.6 UTC
null
4,561,314
null
573,082
null
1
111
machine-learning|cross-entropy
61,494
<p>Cross-entropy is commonly used to quantify the difference between two probability distributions. In the context of machine learning, it is a measure of error for categorical multi-class classification problems. Usually the &quot;true&quot; distribution (the one that your machine learning algorithm is trying to match) is expressed in terms of a one-hot distribution.</p> <p>For example, suppose for a specific training instance, the true label is B (out of the possible labels A, B, and C). The one-hot distribution for this training instance is therefore:</p> <pre><code>Pr(Class A) Pr(Class B) Pr(Class C) 0.0 1.0 0.0 </code></pre> <p>You can interpret the above true distribution to mean that the training instance has 0% probability of being class A, 100% probability of being class B, and 0% probability of being class C.</p> <p>Now, suppose your machine learning algorithm predicts the following probability distribution:</p> <pre><code>Pr(Class A) Pr(Class B) Pr(Class C) 0.228 0.619 0.153 </code></pre> <p>How close is the predicted distribution to the true distribution? That is what the cross-entropy loss determines. Use this formula:</p> <p><a href="https://i.stack.imgur.com/gNip2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gNip2.png" alt="Cross entropy loss formula" /></a></p> <p>Where <code>p(x)</code> is the true probability distribution (one-hot) and <code>q(x)</code> is the predicted probability distribution. The sum is over the three classes A, B, and C. In this case the loss is <strong>0.479</strong> :</p> <pre><code>H = - (0.0*ln(0.228) + 1.0*ln(0.619) + 0.0*ln(0.153)) = 0.479 </code></pre> <h3>Logarithm base</h3> <p>Note that it does not matter what logarithm base you use as long as you consistently use the same one. As it happens, the Python Numpy <code>log()</code> function computes the natural log (log base e).</p> <h3>Python code</h3> <p>Here is the above example expressed in Python using Numpy:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np p = np.array([0, 1, 0]) # True probability (one-hot) q = np.array([0.228, 0.619, 0.153]) # Predicted probability cross_entropy_loss = -np.sum(p * np.log(q)) print(cross_entropy_loss) # 0.47965000629754095 </code></pre> <p>So that is how &quot;wrong&quot; or &quot;far away&quot; your prediction is from the true distribution. A machine learning optimizer will attempt to minimize the loss (i.e. it will try to reduce the loss from 0.479 to 0.0).</p> <h3>Loss units</h3> <p>We see in the above example that the loss is 0.4797. Because we are using the natural log (log base e), the units are in <a href="https://en.wikipedia.org/wiki/Nat_(unit)" rel="noreferrer"><em>nats</em></a>, so we say that the loss is 0.4797 nats. If the log were instead log base 2, then the units are in bits. See <a href="https://machinelearningmastery.com/cross-entropy-for-machine-learning/" rel="noreferrer">this page</a> for further explanation.</p> <h3>More examples</h3> <p>To gain more intuition on what these loss values reflect, let's look at some extreme examples.</p> <p>Again, let's suppose the true (one-hot) distribution is:</p> <pre><code>Pr(Class A) Pr(Class B) Pr(Class C) 0.0 1.0 0.0 </code></pre> <p>Now suppose your machine learning algorithm did a really great job and predicted class B with very high probability:</p> <pre><code>Pr(Class A) Pr(Class B) Pr(Class C) 0.001 0.998 0.001 </code></pre> <p>When we compute the cross entropy loss, we can see that the loss is tiny, only 0.002:</p> <pre class="lang-py prettyprint-override"><code>p = np.array([0, 1, 0]) q = np.array([0.001, 0.998, 0.001]) print(-np.sum(p * np.log(q))) # 0.0020020026706730793 </code></pre> <p>At the other extreme, suppose your ML algorithm did a terrible job and predicted class C with high probability instead. The resulting loss of 6.91 will reflect the larger error.</p> <pre><code>Pr(Class A) Pr(Class B) Pr(Class C) 0.001 0.001 0.998 </code></pre> <pre class="lang-py prettyprint-override"><code>p = np.array([0, 1, 0]) q = np.array([0.001, 0.001, 0.998]) print(-np.sum(p * np.log(q))) # 6.907755278982137 </code></pre> <p>Now, what happens in the middle of these two extremes? Suppose your ML algorithm can't make up its mind and predicts the three classes with nearly equal probability.</p> <pre><code>Pr(Class A) Pr(Class B) Pr(Class C) 0.333 0.333 0.334 </code></pre> <p>The resulting loss is 1.10.</p> <pre class="lang-py prettyprint-override"><code>p = np.array([0, 1, 0]) q = np.array([0.333, 0.333, 0.334]) print(-np.sum(p * np.log(q))) # 1.0996127890016931 </code></pre> <h3>Fitting into gradient descent</h3> <p>Cross entropy is one out of many possible loss functions (another popular one is SVM hinge loss). These loss functions are typically written as J(theta) and can be used within gradient descent, which is an iterative algorithm to move the parameters (or coefficients) towards the optimum values. In the equation below, you would replace <code>J(theta)</code> with <code>H(p, q)</code>. But note that you need to compute the derivative of <code>H(p, q)</code> with respect to the parameters first.</p> <p><a href="https://i.stack.imgur.com/ZSyZE.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/ZSyZE.jpg" alt="gradient descent" /></a></p> <p>So to answer your original questions directly:</p> <blockquote> <p>Is it only a method to describe the loss function?</p> </blockquote> <p>Correct, cross-entropy describes the loss between two probability distributions. It is one of many possible loss functions.</p> <blockquote> <p>Then we can use, for example, gradient descent algorithm to find the minimum.</p> </blockquote> <p>Yes, the cross-entropy loss function can be used as part of gradient descent.</p> <p>Further reading: one of my <a href="https://stackoverflow.com/a/39499486/4561314">other answers</a> related to TensorFlow.</p>
63,169,865
How to do multiprocessing in FastAPI
<p>While serving a FastAPI request, I have a CPU-bound task to do on every element of a list. I'd like to do this processing on multiple CPU cores.</p> <p>What's the proper way to do this within FastAPI? Can I use the standard <code>multiprocessing</code> module? All the tutorials/questions I found so far only cover I/O-bound tasks like web requests.</p>
63,171,013
1
0
null
2020-07-30 09:09:06.547 UTC
31
2021-08-22 04:12:40.927 UTC
2021-01-24 18:53:35.88 UTC
null
13,782,669
null
8,233,844
null
1
36
python|multiprocessing|python-asyncio|fastapi|uvicorn
25,306
<h2><code>async def</code> endpoint</h2> <p>You could use <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor" rel="noreferrer">loop.run_in_executor</a> with <a href="https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor" rel="noreferrer">ProcessPoolExecutor</a> to start function at a separate process.</p> <pre><code>@app.post(&quot;/async-endpoint&quot;) async def test_endpoint(): loop = asyncio.get_event_loop() with concurrent.futures.ProcessPoolExecutor() as pool: result = await loop.run_in_executor(pool, cpu_bound_func) # wait result </code></pre> <h2><code>def</code> endpoint</h2> <p>Since <code>def</code> endpoints are <a href="https://fastapi.tiangolo.com/async/?h=%20threadpool#path-operation-functions" rel="noreferrer">run implicitly</a> in a separate thread, you can use the full power of modules <a href="https://docs.python.org/3/library/multiprocessing.html" rel="noreferrer">multiprocessing</a> and <a href="https://docs.python.org/3/library/concurrent.futures.html" rel="noreferrer">concurrent.futures</a>. Note that inside <code>def</code> function, <code>await</code> may not be used. Samples:</p> <pre><code>@app.post(&quot;/def-endpoint&quot;) def test_endpoint(): ... with multiprocessing.Pool(3) as p: result = p.map(f, [1, 2, 3]) </code></pre> <pre><code>@app.post(&quot;/def-endpoint/&quot;) def test_endpoint(): ... with concurrent.futures.ProcessPoolExecutor(max_workers=3) as executor: results = executor.map(f, [1, 2, 3]) </code></pre> <p><em>Note</em>: <em>It should be remembered that creating a pool of processes in an endpoint, as well as creating a large number of threads, can lead to a slowdown in response as the number of requests increases.</em></p> <hr /> <h2>Executing on the fly</h2> <p>The easiest and most native way to execute a function in a separate process and immediately wait for the results is to use the <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.loop.run_in_executor" rel="noreferrer">loop.run_in_executor</a> with <a href="https://docs.python.org/3/library/concurrent.futures.html#processpoolexecutor" rel="noreferrer">ProcessPoolExecutor</a>.</p> <p>A pool, as in the example below, can be created when the application starts and do not forget to shutdown on application exit. The number of processes used in the pool can be set using the <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor" rel="noreferrer">max_workers</a> <code>ProcessPoolExecutor</code> constructor parameter. If <code>max_workers</code> is <code>None</code> or not given, it will default to the number of processors on the machine.</p> <p>The disadvantage of this approach is that the request handler (path operation) waits for the computation to complete in a separate process, while the client connection remains open. And if for some reason the connection is lost, then the results will have nowhere to return.</p> <pre><code>import asyncio from concurrent.futures.process import ProcessPoolExecutor from fastapi import FastAPI from calc import cpu_bound_func app = FastAPI() async def run_in_process(fn, *args): loop = asyncio.get_event_loop() return await loop.run_in_executor(app.state.executor, fn, *args) # wait and return result @app.get(&quot;/{param}&quot;) async def handler(param: int): res = await run_in_process(cpu_bound_func, param) return {&quot;result&quot;: res} @app.on_event(&quot;startup&quot;) async def on_startup(): app.state.executor = ProcessPoolExecutor() @app.on_event(&quot;shutdown&quot;) async def on_shutdown(): app.state.executor.shutdown() </code></pre> <h2>Move to background</h2> <p>Usually, CPU bound tasks are executed in the background. FastAPI offers the ability to run <a href="https://fastapi.tiangolo.com/tutorial/background-tasks/" rel="noreferrer">background tasks</a> to be run <strong>after</strong> returning a response, inside which you can start and asynchronously wait for the result of your CPU bound task.</p> <p>In this case, for example, you can immediately return a response of <code>&quot;Accepted&quot;</code> (HTTP code 202) and a unique task <code>ID</code>, continue calculations in the background, and the client can later request the status of the task using this <code>ID</code>.</p> <p><code>BackgroundTasks</code> provide some features, in particular, you can run several of them (including in dependencies). And in them you can use the resources obtained in the dependencies, which will be cleaned only when all tasks are completed, while in case of exceptions it will be possible to handle them correctly. This can be seen more clearly in this <a href="https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-with-yield/#dependencies-with-yield-and-httpexception" rel="noreferrer">diagram</a>.</p> <p>Below is an example that performs minimal task tracking. One instance of the application running is assumed.</p> <pre><code>import asyncio from concurrent.futures.process import ProcessPoolExecutor from http import HTTPStatus from fastapi import BackgroundTasks from typing import Dict from uuid import UUID, uuid4 from fastapi import FastAPI from pydantic import BaseModel, Field from calc import cpu_bound_func class Job(BaseModel): uid: UUID = Field(default_factory=uuid4) status: str = &quot;in_progress&quot; result: int = None app = FastAPI() jobs: Dict[UUID, Job] = {} async def run_in_process(fn, *args): loop = asyncio.get_event_loop() return await loop.run_in_executor(app.state.executor, fn, *args) # wait and return result async def start_cpu_bound_task(uid: UUID, param: int) -&gt; None: jobs[uid].result = await run_in_process(cpu_bound_func, param) jobs[uid].status = &quot;complete&quot; @app.post(&quot;/new_cpu_bound_task/{param}&quot;, status_code=HTTPStatus.ACCEPTED) async def task_handler(param: int, background_tasks: BackgroundTasks): new_task = Job() jobs[new_task.uid] = new_task background_tasks.add_task(start_cpu_bound_task, new_task.uid, param) return new_task @app.get(&quot;/status/{uid}&quot;) async def status_handler(uid: UUID): return jobs[uid] @app.on_event(&quot;startup&quot;) async def startup_event(): app.state.executor = ProcessPoolExecutor() @app.on_event(&quot;shutdown&quot;) async def on_shutdown(): app.state.executor.shutdown() </code></pre> <h2>More powerful solutions</h2> <p>All of the above examples were pretty simple, but if you need some more powerful system for heavy distributed computing, then you can look aside message brokers <code>RabbitMQ</code>, <code>Kafka</code>, <code>NATS</code> and etc. And libraries using them like Celery.</p>
41,674,979
flex child is growing out of parent
<p>How to force the green boxes to be contained in the red one without setting a static height value and no absolute position?</p> <p>I want to shrink the content to fit into the parent.</p> <p>The content (video in this case) is allowed to shrink and scrollbars are allowed.</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-css lang-css prettyprint-override"><code>.my-box { height: 300px; width: 600px; background: red; padding: 5px; } .content-box { background: blue; } .col { display: flex; flex-direction: column; justify-content: space-between } .box-shrink { flex: 0 1 auto; background: green; padding: 5px; margin: 5px; } .box-grow { flex: 1 0 auto; background: green; padding: 5px; margin: 5px; } video { max-height: 100%; max-width: 100%; margin: auto; display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="my-box col"&gt; &lt;div class="box-shrink"&gt; small sized static content &lt;/div&gt; &lt;div class="content-box box-grow"&gt; &lt;video controls&gt; &lt;source src="http://techslides.com/demos/sample-videos/small.webm" type="video/webm"&gt; &lt;/video&gt; &lt;/div&gt; &lt;div class="box-shrink"&gt; small sized static content &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
41,675,912
3
0
null
2017-01-16 11:07:13.35 UTC
14
2022-02-24 13:17:52.663 UTC
2017-01-16 12:01:56.713 UTC
null
3,597,276
null
1,055,015
null
1
72
html|css|flexbox
76,775
<h2>Solution #1 - Without Scroll</h2> <p>Instead of <code>flex: 1 0 auto</code> on the video container, just use <code>flex: 1</code>. This sizes the item based on available space, not the intrinsic height of the content.</p> <p>Then, because flex items cannot be smaller than the size of their content &ndash; <code>min-height: auto</code> is the default &ndash; add <code>min-height: 0</code> to allow the item to shrink to fit inside the container.</p> <pre><code>.box-grow { flex: 1; /* formerly flex: 1 0 auto; */ background: green; padding: 5px; margin: 5px; min-height: 0; /* new */ } </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.my-box { height: 300px; width: 600px; background: red; padding: 5px; } .content-box { background: blue; } .col { display: flex; flex-direction: column; justify-content: space-between } .box-shrink { flex: 0 1 auto; background: green; padding: 5px; margin: 5px; } .box-grow { flex: 1; /* formerly flex: 1 0 auto; */ background: green; padding: 5px; margin: 5px; min-height: 0; /* new */ } video { max-height: 100%; max-width: 100%; margin: auto; display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="my-box col"&gt; &lt;div class="box-shrink"&gt; small sized static content &lt;/div&gt; &lt;div class="content-box box-grow"&gt; &lt;video controls&gt; &lt;source src="http://techslides.com/demos/sample-videos/small.webm" type="video/webm"&gt; &lt;/video&gt; &lt;/div&gt; &lt;div class="box-shrink"&gt; small sized static content &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <h2>Solution #2 - With Scroll</h2> <p>Alternatively, give the video container <code>overflow: auto</code>, which does the same as above, except it keeps the video full-width. You need to enable <code>flex-shrink</code> for this to work.</p> <pre><code>.box-grow { flex: 1 1 auto; /* formerly flex: 1 0 auto; */ background: green; padding: 5px; margin: 5px; overflow: auto; /* new */ } </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.my-box { height: 300px; width: 600px; background: red; padding: 5px; } .content-box { background: blue; } .col { display: flex; flex-direction: column; justify-content: space-between } .box-shrink { flex: 0 1 auto; background: green; padding: 5px; margin: 5px; } .box-grow { flex: 1 1 auto; /* formerly flex: 1 0 auto; */ background: green; padding: 5px; margin: 5px; overflow: auto; /* new */ } video { max-height: 100%; max-width: 100%; margin: auto; display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="my-box col"&gt; &lt;div class="box-shrink"&gt; small sized static content &lt;/div&gt; &lt;div class="content-box box-grow"&gt; &lt;video controls&gt; &lt;source src="http://techslides.com/demos/sample-videos/small.webm" type="video/webm"&gt; &lt;/video&gt; &lt;/div&gt; &lt;div class="box-shrink"&gt; small sized static content &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Both solutions are explained in more detail here:</p> <ul> <li><a href="https://stackoverflow.com/q/36247140/3597276">Why doesn&#39;t flex item shrink past content size?</a></li> </ul>
6,244,307
concatenate two strings
<p>Let's say I have a string obtained from a cursor,this way:</p> <pre><code>String name = cursor.getString(numcol); </code></pre> <p>and another String like this one:</p> <pre><code>String dest=cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE)); </code></pre> <p>If finally I wanna obtain a String from the two of them,something like:</p> <pre><code>name - dest </code></pre> <p>Let say if name=Malmo and dest=Copenhagen</p> <p>How could I finally obtain Malmo-Copenhagen???</p> <p>Because android won't let me write :</p> <pre><code>name"-"dest </code></pre>
6,244,371
3
0
null
2011-06-05 16:41:35.003 UTC
2
2017-01-07 13:33:16.167 UTC
2016-07-16 04:32:32.997 UTC
null
3,329,664
null
778,076
null
1
19
android|string
118,466
<p>The best way in my eyes is to use the <code>concat()</code> method provided by the <code>String</code> class itself.</p> <p>The useage would, in your case, look like this:</p> <pre><code>String myConcatedString = cursor.getString(numcol).concat('-'). concat(cursor.getString(cursor.getColumnIndexOrThrow(db.KEY_DESTINATIE))); </code></pre>
5,860,216
No expires header sent, content cached, how long until browser makes conditional GET request?
<p>Assume browser default settings, and content is sent without expires headers. </p> <ol> <li>user visits website, browser caches images etc. </li> <li>user does not close browser, or refresh page. </li> <li>user continues to surf site normally.</li> <li>assume the browse doesn't dump the cache for any reason. </li> </ol> <p>The browser will cache images etc as the user surfs, but it's unclear when it will issue a conditional GET request to ask about content freshness (apart from refreshing the page). If this is a browser specific setting, where can I see it's value (for browsers like: safari, IE, FireFox, Chrome). </p> <p>[edit: yes - I understand that you should always send expires headers. However, this research is aimed at understanding how the browser works with content w/o expires headers.]</p>
5,860,508
3
2
null
2011-05-02 17:21:31.353 UTC
6
2017-01-27 15:17:59.36 UTC
2014-01-23 20:48:42.15 UTC
null
2,642,204
null
332,751
null
1
35
caching|browser|cache-control
19,059
<p>HTTP/1.1 defines a selection of caching mechanisms; the <code>expires</code> header is merely one, there is also the <code>cache-control</code> header.</p> <p>To directly answer your question: for a resource returned with no <code>expires</code> header, you must consider the returned <code>cache-control</code> directives.</p> <p>HTTP/1.1 defines no caching behaviour for a resource served with no cache-related headers. If a resource is sent with no <code>cache-control</code> or <code>expires</code> headers you must assume the client will make a regular (non-conditional) request the next time the same resources is requested.</p> <p>Any deviation from this behaviour qualifies the client as being not a fully conformant HTTP client, in which case the question becomes: what behaviour is to be expected from a non-conformant HTTP client? There is no way to answer that.</p> <p>HTTP caching is complex, to fully understand what a conformant client should do in a given scenario, read and understand the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html" rel="noreferrer">HTTP caching spec</a>.</p>
6,071,607
how can i use a helper in different views
<p>i am using refinery cms at the moment. I created an engine and with it some helpers in <code>app/helpers/admin/</code>. now i would like to use those helpers in my frontend view (ie. <code>app/views/myapp/index</code>) as well. but i can not...undefined methode error. what do i have to do short of copying the whole thing to <code>app/helpers/</code>? the helper looks like this</p> <pre><code>module Admin module myHelper def somefunc end end end </code></pre> <p>so is it possible to use <code>somefunc</code> outside of the Admin module?</p>
6,071,741
3
1
null
2011-05-20 12:02:08.113 UTC
4
2012-12-04 12:17:04.973 UTC
null
null
null
null
762,693
null
1
37
ruby-on-rails|ruby|refinerycms
24,281
<p>In your <code>application_helper.rb</code>:</p> <pre><code>module ApplicationHelper include Admin::MyHelper end </code></pre> <p>This will import those helper methods into the <code>ApplicationHelper</code>, thus making them available in your views. You could do this in any of your helpers really.</p>
5,628,647
Geolocation APIs: SimpleGeo vs CityGrid vs PublicEarth vs Twitter vs Foursquare vs Loopt vs Fwix. How to retrieve venue/location information?
<p>We need to display meta information (e.g, address, name) on our site for various venues like bars, restaurants, and theaters.</p> <p>Ideally, users would type in the name of a venue, along with zip code, and we present the closest matches. </p> <p>Which APIs have people used for similar geolocation purposes? What are the pros and cons of each?</p> <p>Our basic research yielded a few options (listed in title and below). We're curious to hear how others have deployed these APIs and which ones are ultimately in use.</p> <ul> <li>Fwix API: <a href="http://developers.fwix.com/" rel="noreferrer">http://developers.fwix.com/</a></li> <li>Zumigo</li> </ul> <p>Does Facebook plan on offering a Places API eventually that could accomplish this?</p> <p>Thanks!</p>
5,760,083
4
4
null
2011-04-11 23:13:02.297 UTC
15
2012-02-22 22:16:35.037 UTC
2011-04-19 17:29:22.54 UTC
null
144,088
null
144,088
null
1
8
facebook|api|geolocation|twitter
5,070
<p>Facebook Places is based on Factual. You can use Factual's API which is pretty good (and still free, I think?)</p> <p><a href="http://www.factual.com/topic/local" rel="noreferrer">http://www.factual.com/topic/local</a></p> <p>You can also use unauthenticated Foursquare as a straight places database. The data is of uneven quality since it's crowdsourced, but I find it generally good. It's free to a certain API limit, but I think the paid tier is negotiated.</p> <p><a href="https://developer.foursquare.com/" rel="noreferrer">https://developer.foursquare.com/</a></p> <p>I briefly looked at Google Places but didn't like it because of all the restrictions on how you have to display results (Google wants their ad revenue).</p>
5,773,961
All possible permutations of a given String?
<p>How would I do this in Ruby?</p> <pre><code>p "abc".all_possible_permutations </code></pre> <p>Would return:</p> <pre><code>[ "abc", "acb", "bca", "bac", "cba", "cab", ] </code></pre> <h1>Edit</h1> <p>Thanks to Jakub Hampl:</p> <pre><code>class String def all_possible_permutations self.chars.to_a.permutation.map(&amp;:join) end end </code></pre>
5,773,980
4
9
null
2011-04-24 23:34:53.617 UTC
10
2017-06-25 02:52:24.93 UTC
2011-11-09 10:46:19.023 UTC
null
6,444
null
139,089
null
1
27
ruby
15,610
<pre><code>%w[a b c].permutation.map &amp;:join </code></pre>
5,693,997
Android: How to create an "Ongoing" notification?
<p><img src="https://i.stack.imgur.com/QV4Kt.png" alt="enter image description here"></p> <p>Hello, How do i create the permanent notification like the first one for Battery Indicator?</p>
5,694,012
4
0
null
2011-04-17 14:10:13.11 UTC
23
2013-01-06 21:42:21.77 UTC
null
null
null
null
481,239
null
1
53
android|notifications
55,221
<p>Assign <code>Notification.FLAG_ONGOING_EVENT</code> flag to your <code>Notification</code>.</p> <p>Sample code:</p> <pre><code>yourNotification.flags = Notification.FLAG_ONGOING_EVENT; // Notify... </code></pre> <p>If you aren't familiar with the <code>Notification</code> API, read <a href="http://developer.android.com/guide/topics/ui/notifiers/notifications.html" rel="noreferrer">Creating Status Bar Notifications</a> on Android developers website.</p>
6,295,481
Learning Algorithms
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/5282969/learning-efficient-algorithms">Learning efficient algorithms</a> </p> </blockquote> <p>I recently came across an problem that was solved by applying the correct algorithm: <a href="https://stackoverflow.com/questions/6287160/calculating-plugin-dependencies">Calculating plugin dependencies</a></p> <p>While I was eventually able to understand the logic of the prescribed algorithm, it was not an easy task for me. The only reason I was able to come up with code that worked was because of the logic example on the wikipedia page.</p> <p>Being entirely self taught, without any CS or math background, I'd like to at least get some practical foundation to being able to apply algorithms to solve problems.</p> <p>That said, are there any great books / resources (something akin to 'algorithms for dummies') that doesn't expect you have completed college Algebra 9 or Calculus 5 that can teach the basics? I don't expect to ever be a wizard, just expand my problem solving tool-set a little bit. </p> <p>Doing an amazon search turns up a bunch of books, but I'm hoping you guys can point me to the truly useful resources.</p> <p>The only language I have any real experience with is Python (a tiny bit of C) so whatever I find needs to be language agnostic or centred around Python/C. </p>
6,295,520
5
6
null
2011-06-09 15:35:58.807 UTC
10
2011-06-09 16:04:23.26 UTC
2017-05-23 10:28:59.593 UTC
null
-1
null
592,851
null
1
8
python|c|algorithm
3,238
<p>"Art of Computer Programming" by Donald Knuth is a Very Useful Book.</p>
34,428,952
If with multiple &&, || conditions Evaluation in java
<pre><code>if(a &amp;&amp; b || c || d || e) </code></pre> <p>whether it check <code>(a &amp;&amp; b)</code>, if <strong>a</strong> and <strong>b</strong> must be true always, then only allow inside ? or</p> <p><code>((a &amp;&amp; b) || a &amp;&amp; c || a &amp;&amp; d || a &amp;&amp; e))</code>, any of the condition is true will it allow inside ?</p>
34,429,054
6
1
null
2015-12-23 05:02:25.943 UTC
3
2021-07-04 11:29:26.19 UTC
2015-12-23 05:30:50.837 UTC
null
1,997,093
null
4,675,067
null
1
8
java|if-statement
44,508
<p>If I understand you correctly, in the first part of your question, you are asking whether <code>a</code> and <code>b</code> must both be true for the entire expression <code>(a &amp;&amp; b || c || d || e)</code> to evaluate as true.</p> <p>The answer to that question is no. Java operators are such that <code>&amp;&amp;</code> has higher precedence than <code>||</code>. So the equivalent expression is:</p> <pre><code>(a &amp;&amp; b) || c || d || e </code></pre> <p>Therefore the expression as a whole will evaluate to true if any of <code>a &amp;&amp; b</code> or <code>c</code> or <code>d</code> or <code>e</code> is true. For example, if <code>a</code> was false and <code>c</code> was true, the expression as a whole is true.</p> <p>Note that Java conditional operators short-circuit. This means that once the end result of the expression is known, evaluation stops. For example, if <code>a</code> and <code>b</code> were both true, meaning the overall expression must evaluate to true, then <code>c</code>, <code>d</code> and <code>e</code> are not evaluated.</p> <p>For the second part of your question, we can apply the same logic. The equivalent expression is therefore:</p> <pre><code>(a &amp;&amp; b) || (a &amp;&amp; c) || (a &amp;&amp; d) || (a &amp;&amp; e) </code></pre> <p>This will evaluate to true if any of the sub-components, eg. <code>a &amp;&amp; c</code> evaluates to true. As others have noted, <code>a</code> must be true for the expression to be true as it is part of every sub-component. Then if any of the other variables is true, the expression is true.</p> <p>Once you understand that, you can see how the simplification of this expression suggested by @Arc676 is arrived at:</p> <pre><code>a &amp;&amp; (b || c || d || e) </code></pre> <p>I should also add that the two expressions in your question are different logically. They are equivalent to:</p> <pre><code>(a &amp;&amp; b) || c || d || e </code></pre> <p>and </p> <pre><code>a &amp;&amp; (b || c || d || e) </code></pre> <p>The parentheses affect the order of evaluation. In the first, <code>a</code> and <code>b</code> are grouped together by an <code>&amp;&amp;</code>, hence both must be true for that part of the expression (in the parentheses) to be true. In the second, <code>b</code>, <code>c</code>, <code>d</code> and <code>e</code> are grouped together by <code>||</code>. In this case, only one of <code>b</code>, <code>c</code>, <code>d</code> and <code>e</code> needs to be true for that part of the expression (in the parentheses) to be true.</p>
2,269,593
Best way to handle view and helper-only constants in Rails
<p>I have a constant that is only used in views, but it's used in different ways in different places. It's an array of option names, and is used for select boxes, but I also use this in other views to see if strings are found in this array, and respond accordingly.</p> <p>What's the best way to handle this to keep DRY?</p> <p>I initially created a constant in a helper, but that doesn't seem to be accessible in the views.</p> <p>I've since switched to creating a method in a helper, that does nothing except return the constant. However, this really seems to be against the spirit of Rails, since now essentially I'm using a lower-cased constant.</p> <p>I could of course stick it in a model, but it's really got nothing to do with any of the models.</p>
2,269,972
2
0
null
2010-02-15 23:08:57.237 UTC
9
2010-07-28 23:05:44.77 UTC
null
null
null
null
257,611
null
1
28
ruby-on-rails|view|constants|dry|helper
12,108
<p>You can define constants in helpers, but you will need to refer to them by their fully qualified name in your views.</p> <p>application_helper.rb</p> <pre><code>module ApplicationHelper MyConstant = "something" end </code></pre> <p>In any view:</p> <pre><code>&lt;%= ApplicationHelper::MyConstant %&gt; </code></pre>
1,363,527
Cannot convert '0000-00-00 00:00:00' to TIMESTAMP
<p>the field definition</p> <pre><code> /** Date. */ @Column(columnDefinition = "datetime") private Date date; </code></pre> <p>setter</p> <pre><code>public void setDate(final Date date) { DateFormat dfmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { this.date = dfmt.parse(dfmt.format(date)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } </code></pre> <p>Does anyone have idea how to convert "zero date" into proper value ? Because i have error:</p> <pre><code>Cannot convert value '0000-00-00 00:00:00' from column 13 to TIMESTAMP </code></pre> <p>And even if i set "default" field and setter like this:</p> <pre><code>/** Date. */ @Column private Date date; public void setDate(final Date date) { this.date = date; } </code></pre> <p>I'll still have the same problem....</p>
1,363,750
2
3
null
2009-09-01 16:49:23.42 UTC
4
2013-05-07 19:23:55.217 UTC
2012-03-06 08:06:31.333 UTC
null
411,951
null
87,383
null
1
29
java|hibernate|date|hql
32,768
<p>I'm going to take a wild guess here that you're using MySQL :-) It uses "zero dates" as <a href="http://dev.mysql.com/doc/refman/5.4/en/date-and-time-types.html" rel="noreferrer">special placeholder</a> - unfortunatelly, JDBC can not handle them by default.</p> <p>The solution is to specify "zeroDateTimeBehavior=convertToNull" as parameter to your MySQL connection (either in datasource URL or as an additional property), e.g.:</p> <pre><code>jdbc:mysql://localhost/myDatabase?zeroDateTimeBehavior=convertToNull </code></pre> <p>This will cause all such values to be retrieved as NULLs.</p>
29,760,668
Conditionally iterate over one of several possible iterators
<p>I'm trying to switch behavior based on an <code>Option</code> input to a function. The idea is to iterate based on whether or not a given <code>Option</code> is present. Here's a minimal, if silly, example:</p> <pre><code>use std::iter; fn main() { let x: Option&lt;i64&gt; = None; // Repeat x 5 times if present, otherwise count from 1 to 5 for i in match x { None =&gt; 1..5, Some(x) =&gt; iter::repeat(x).take(5), } { println!("{}", i); } } </code></pre> <p>I get an error:</p> <pre class="lang-none prettyprint-override"><code>error[E0308]: match arms have incompatible types --&gt; src/main.rs:7:14 | 7 | for i in match x { | ______________^ 8 | | None =&gt; 1..5, 9 | | Some(x) =&gt; iter::repeat(x).take(5), | | ----------------------- match arm with an incompatible type 10 | | } { | |_____^ expected struct `std::ops::Range`, found struct `std::iter::Take` | = note: expected type `std::ops::Range&lt;{integer}&gt;` found type `std::iter::Take&lt;std::iter::Repeat&lt;i64&gt;&gt;` </code></pre> <p>This makes perfect sense, of course, but I'd really like to choose my iterator based on a condition, since the code in the for-loop is non-trivial and copy-pasting all of that just to change iterator selection would be pretty ugly and unmaintainable.</p> <p>I tried using <code>as Iterator&lt;Item = i64&gt;</code> on both arms, but that gives me an error about unsized types because it's a trait object. Is there an easy way to go about this?</p> <p>I could, of course, use <code>.collect()</code> since they return the same type and iterate over that vector. Which is a good quick fix, but for large lists seems a bit excessive.</p>
29,760,740
4
0
null
2015-04-21 00:14:56.867 UTC
8
2020-02-21 12:03:44.103 UTC
2018-05-06 20:50:14.387 UTC
null
155,423
null
901,827
null
1
29
rust
5,617
<p>The most straightforward solution is to use a <em>trait object</em>:</p> <pre><code>use std::iter; fn main() { let mut a; let mut b; let x: Option&lt;i64&gt; = None; // Repeat x 5 times if present, otherwise count from 1 to 5 let iter: &amp;mut dyn Iterator&lt;Item = i64&gt; = match x { None =&gt; { a = 1..5; &amp;mut a } Some(x) =&gt; { b = iter::repeat(x).take(5); &amp;mut b } }; for i in iter { println!("{}", i); } } </code></pre> <p>The main downside for this solution is that you have to allocate stack space for each concrete type you have. This also means variables for each type. A good thing is that only the used type needs to be initialized.</p> <p>The same idea but requiring heap allocation is to use <em>boxed trait objects</em>:</p> <pre><code>use std::iter; fn main() { let x: Option&lt;i64&gt; = None; // Repeat x 5 times if present, otherwise count from 1 to 5 let iter: Box&lt;dyn Iterator&lt;Item = i64&gt;&gt; = match x { None =&gt; Box::new(1..5), Some(x) =&gt; Box::new(iter::repeat(x).take(5)), }; for i in iter { println!("{}", i); } } </code></pre> <p>This is mostly useful when you want to <a href="https://stackoverflow.com/q/27535289/155423">return the iterator from a function</a>. The stack space taken is a single pointer, and only the needed heap space will be allocated.</p> <p>You can also <a href="https://stackoverflow.com/a/50204370/155423">use an enum for each possible concrete iterator</a>.</p>
5,710,568
markerClusterer on click zoom
<p>I just added a MarkerClusterer to my google map. It works perfectly fine.</p> <p>I am just wondering if there is any way of adjusting the zoom-in behaviour when the cluster is clicked. I would like to change the zoom level if possible.</p> <p>Is there any way of achieving this?</p> <p>Thanks</p>
5,718,739
5
0
null
2011-04-19 01:14:36.24 UTC
6
2019-07-26 17:19:47.163 UTC
2012-07-02 11:37:27.973 UTC
null
97,160
null
269,106
null
1
30
javascript|google-maps|zooming|google-maps-markers|markerclusterer
44,942
<p>I modified the clusterclick event as suggested:</p> <pre><code>/** * Triggers the clusterclick event and zoom's if the option is set. */ ClusterIcon.prototype.triggerClusterClick = function() { var markerClusterer = this.cluster_.getMarkerClusterer(); // Trigger the clusterclick event. google.maps.event.trigger(markerClusterer, 'clusterclick', this.cluster_); if (markerClusterer.isZoomOnClick()) { // Zoom into the cluster. // this.map_.fitBounds(this.cluster_.getBounds()); // modified zoom in function this.map_.setZoom(markerClusterer.getMaxZoom()+1); } }; </code></pre> <p>It works great! Thanks a lot</p>
6,157,485
What are Content-Language and Accept-Language?
<p>I have seen the HTTP headers of <code>Content-Language</code> and <code>Accept-Language</code>, could someone explain what these are for and the difference between them? I have a multilingual site and wondering should I be setting both to the sites current selected language, by the user.</p>
6,157,546
6
2
null
2011-05-27 20:41:34.227 UTC
18
2022-04-26 08:59:28.113 UTC
2017-06-15 15:01:28.44 UTC
null
19,068
null
373,674
null
1
104
http-headers|request|response
119,428
<p><code>Content-Language</code>, an entity header, is used to describe the language(s) intended for the audience, so that it allows a user to differentiate according to the users' own preferred language. Entity headers are used in both, HTTP requests and responses.<sup><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language" rel="noreferrer">1</a></sup></p> <p><code>Accept-Language</code>, a request HTTP header, advertises which languages the client is able to understand, and which locale variant is preferred.<sup><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language" rel="noreferrer">2</a></sup> There can be multiple languages, each with an optional weight or 'quality' value. For example:</p> <pre><code>Accept-Language: da, en-GB;q=0.8, en;q=0.7 </code></pre> <p>(The default weight is 1, so this is equivalent to <code>da;q=1, en-GB;q=0.8, en;q=0.7</code>).</p> <p>You're going to have to parse the values and weights to see if an appropriate translation is available, and provide the user the translation in the highest preferred language weight.</p> <p>It is recommended you give the users an alternative, such as a cookie set value, to force a certain language for your site. This is because some users may want to see your site in a certain language, without changing their language acceptance preferences.</p>