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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
20,018,507 | Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope? | <p>I need to perform some operations on scope and the template. It seems that I can do that in either the <code>link</code> function or the <code>controller</code> function (since both have access to the scope).</p>
<p>When is it the case when I have to use <code>link</code> function and not the controller?</p>
<pre><code>angular.module('myApp').directive('abc', function($timeout) {
return {
restrict: 'EA',
replace: true,
transclude: true,
scope: true,
link: function(scope, elem, attr) { /* link function */ },
controller: function($scope, $element) { /* controller function */ }
};
}
</code></pre>
<p>Also, I understand that <code>link</code> is the non-angular world. So, I can use <code>$watch</code>, <code>$digest</code> and <code>$apply</code>.</p>
<p>What is the significance of the <code>link</code> function, when we already had controller?</p> | 23,722,351 | 3 | 2 | null | 2013-11-16 12:34:11.733 UTC | 157 | 2020-01-30 07:26:46.343 UTC | 2017-09-17 05:24:53.783 UTC | null | 731,963 | null | 731,963 | null | 1 | 211 | javascript|angularjs|angularjs-directive | 168,605 | <p>After my <strong>initial</strong> struggle with the <code>link</code> and <code>controller</code> functions and reading quite a lot about them, I think now I have the answer.</p>
<p>First lets <strong>understand</strong>,</p>
<p><strong>How do angular directives work in a nutshell:</strong></p>
<ul>
<li><p>We begin with a template (as a string or loaded to a string)</p>
<p><code>var templateString = '<div my-directive>{{5 + 10}}</div>';</code></p></li>
<li><p>Now, this <code>templateString</code> is wrapped as an <strong>angular element</strong></p>
<p><code>var el = angular.element(templateString);</code></p></li>
<li><p>With <code>el</code>, now we compile it with <code>$compile</code> to get back the <strong>link</strong> function.</p>
<p><code>var l = $compile(el)</code></p>
<p>Here is what happens,</p>
<ul>
<li><code>$compile</code> walks through the whole template and collects all the directives that it recognizes.</li>
<li>All the directives that are discovered are <strong>compiled recursively</strong> and their <code>link</code> functions are collected.</li>
<li>Then, all the <code>link</code> functions are wrapped in a new <code>link</code> function and returned as <code>l</code>.</li>
</ul></li>
<li><p>Finally, we provide <code>scope</code> function to this <code>l</code> (link) function which further executes the wrapped link functions with this <code>scope</code> and their corresponding elements.</p>
<p><code>l(scope)</code></p></li>
<li><p>This adds the <code>template</code> as a new node to the <code>DOM</code> and invokes <code>controller</code> which adds its watches to the <strong>scope</strong> which is shared with the template in DOM.</p></li>
</ul>
<p><img src="https://i.stack.imgur.com/0PwGA.png" alt="enter image description here"></p>
<p>Comparing <strong>compile</strong> vs <strong>link</strong> vs <strong>controller</strong> :</p>
<ul>
<li><p>Every directive is <strong>compiled</strong> only once and <strong>link</strong> function is retained for re-use. Therefore, if there's something applicable to all instances of a directive should be performed inside directive's <code>compile</code> function.</p></li>
<li><p>Now, after compilation we have <code>link</code> function which is executed while attaching the <strong>template</strong> to the <strong>DOM</strong>. So, therefore we perform everything that is specific to every instance of the directive. For eg: <strong>attaching events</strong>, <strong>mutating the template based on scope</strong>, etc.</p></li>
<li><p>Finally, the <strong>controller</strong> is meant to be available to be live and reactive while the directive works on the <code>DOM</code> (after getting attached). Therefore:</p>
<p>(1) After setting up the view[<strong>V</strong>] (i.e. template) with link. <code>$scope</code> is our [<strong>M</strong>] and <code>$controller</code> is our [<strong>C</strong>] in <strong>M V C</strong></p>
<p>(2) Take advantage the <strong>2-way</strong> binding with <strong>$scope</strong> by setting up watches.</p>
<p>(3) <code>$scope</code> watches are expected to be added in the controller since this is what is watching the template during run-time.</p>
<p>(4) Finally, <code>controller</code> is also used to be able to communicate among related directives. (Like <code>myTabs</code> example in <a href="https://docs.angularjs.org/guide/directive" rel="noreferrer">https://docs.angularjs.org/guide/directive</a>)</p>
<p>(5) It's true that we could've done all this in the <code>link</code> function as well but its about <strong>separation of concerns</strong>.</p></li>
</ul>
<p>Therefore, finally we have the following which fits all the pieces perfectly :</p>
<p><img src="https://i.stack.imgur.com/SAFpN.png" alt="enter image description here"></p> |
20,159,457 | Bluetooth audio streaming between android devices | <p>I made a research on the same topic and found that android devices are a2dp sources and the audio can be streamed only from an a2dp source to an a2dp sink. A2dp sink can be a bluetooth headset or a bluetooth speaker.</p>
<p>But my question is then <em>how the android app named</em> "<a href="https://play.google.com/store/apps/details?id=com.ilumnis.btplayerfree&hl=en">Bluetooth Music Player</a>" <strong><em>works</em></strong>?</p>
<p>It allows streaming from one mobile to another. So in this case the listening mobile device must act as a sink. How this is possible?
Are they using some other profile instead of a2dp?</p>
<p>Ok, that may be a different profile what they are using. Because the application needs to be installed in the client side also.
But how it becomes possible to stream voice from a <strong><em>bluetooth microphone to an android device</em></strong>?</p>
<p>Please help.</p> | 20,222,491 | 1 | 3 | null | 2013-11-23 06:40:55.883 UTC | 14 | 2015-10-31 12:39:48.937 UTC | 2013-11-26 15:37:46.913 UTC | null | 2,441,654 | null | 2,441,654 | null | 1 | 18 | android|bluetooth|streaming|audio-streaming|a2dp | 40,531 | <p>Without knowing details about the mentioned Bluetooth Music Player, it seems to use simple Bluetooth data connection, otherwise you would not need to install a client on playing/sending device.<br>
<br>
To stream audio from microphone to another device, you can record it on your sending device and send it to the receiving device. You will need to implement a protocol for that purpose.
<br>
<strong>OR</strong>
<br>
You can implement an alternative A2DP sink service. This is, what the sink is: a device with a Bluetooth Protocol Stack with an implementation of A2DP Sink.<br>
<br>
<strong>Edit:</strong><br>
For the case you detailed by your comments, the sending device should be left as-is, without installing any app. That implicitly means that your solution must make use of out-of-the-box Bluetooth functionality of that Android device.<br>
What you can use here is therefor limited to those profiles that Android typically support, which is HSP, HFP and A2DP. Since you obviously want to stream music, A2DP would be your choice.<br>
On the device supposed to receive the audio stream and do the playback, you have to implement a service providing the A2DP sink as an self implemented BluetoothService opening a BluetoothServerSocket on RFCOMM as described in <a href="http://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.html" rel="noreferrer">Android documentation</a>.<br><br>
You will have to spend much effort implementing this, and I am not sure if you will need a license for this.</p> |
27,633,584 | php - Fatal error: Call to undefined function mcrypt_get_iv_size() in AppServ | <p>I found a problem when I use mcrypt_get_iv_size function via <a href="https://www.appserv.org/" rel="noreferrer">AppServ</a>.</p>
<p>I try to find a topic that related to solved a problem.</p>
<p>However, I try yo download libmcrypt.dll into symtem32 and edit php.ini by removing a comment from <code>;extension=php_mcrypt.dll</code> to <code>extension=php_mcrypt.dll</code>. Then restart apache.</p>
<p>Unfortunately, after reload a page to see a result after modify.</p>
<p>It still error as</p>
<blockquote>
<p><strong>Fatal error</strong>: Call to undefined function mcrypt_get_iv_size() in C:\AppServ\www\folder\index.php on line 36</p>
</blockquote>
<p>A function contains following:</p>
<pre><code>class Encryption {
var $skey = "SuPerEncKey2010"; // you can change it
public function safe_b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+','/','='),array('-','_',''),$data);
return $data;
}
public function safe_b64decode($string) {
$data = str_replace(array('-','_'),array('+','/'),$string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}
public function encode($value){
if(!$value){return false;}
$text = $value;
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
return trim($this->safe_b64encode($crypttext));
}
public function decode($value){
if(!$value){return false;}
$crypttext = $this->safe_b64decode($value);
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
return strtolower(trim($decrypttext));
}
}
</code></pre> | 48,150,309 | 4 | 5 | null | 2014-12-24 08:02:21.367 UTC | null | 2019-04-28 21:09:58.89 UTC | 2017-06-14 08:31:55.677 UTC | null | 540,812 | null | 2,971,638 | null | 1 | 27 | php|appserver | 51,282 | <p>in case of php-7:</p>
<blockquote>
<p>sudo apt-get install mcrypt php7.1-mcrypt</p>
</blockquote> |
59,697,071 | What is the (...) called in C and C++? | <p>One of the uses of <code>...</code> is to denote <strong>variadic</strong> entities in C and C++.</p>
<p>What is its name?</p>
<p>Is it classified as an operator or something else when used in that way?</p>
<p>Any other details regarding <code>...</code>?</p>
<p><strong>Edit:</strong>
I know the purpose of <code>...</code>. I am asking about its name and classification, which I hope, is similar in both C and C++.</p> | 59,697,523 | 4 | 3 | null | 2020-01-11 17:49:05.543 UTC | 11 | 2022-08-20 13:45:40.537 UTC | 2020-02-01 17:03:08.99 UTC | null | 12,139,179 | null | 10,251,345 | null | 1 | 31 | c++|c|terminology|ellipsis|variadic | 4,593 | <p>It is one of the <strong>punctuators</strong>.</p>
<blockquote>
<pre class="lang-text prettyprint-override"><code>6.4.6 Punctuators
Syntax punctuator:
one of [ ] ( ) { } . ->
++ -- & * + - ~ !
/ % << >> < > <= >= == != ^ | && ||
? : ; ...
= *= /= %= += -= <<= >>= &= ^= |=
, # ##
<: :> <% %> %: %:%:
</code></pre>
</blockquote>
<p>In the function declaration it is called the <em><strong>ellipsis</strong></em>.</p>
<hr />
<p>Ellipsis is also used by some compiler <code>C</code> language extensions.
Example - gcc switch/case range extension</p>
<pre><code>const char *test(unsigned num)
{
switch(num)
{
case 0 ... 9:
return "the value is in the 0 to 9 range";
case 10 ... 99:
return "the value is in the 10 to 99 range";
default:
return "out of tested range";
}
}
</code></pre>
<p><a href="https://godbolt.org/z/YBLma-" rel="nofollow noreferrer">https://godbolt.org/z/YBLma-</a></p> |
15,254,538 | standard way to handle user session in tornado | <p>So, in order to avoid the "no one best answer" problem, I'm going to ask, not for the best way, but the standard or most common way to handle sessions when using the Tornado framework. That is, if we're not using 3rd party authentication (OAuth, etc.), but rather we have want to have our own Users table with secure cookies in the browser but most of the session info stored on the server, what is the most common way of doing this? I have seen some people using Redis, some people using their normal database (MySQL or Postgres or whatever), some people using memcached.</p>
<p>The application I'm working on won't have millions of users at a time, or probably even thousands. It will need to eventually get some moderately complex authorization scheme, though. What I'm looking for is to make sure we don't do something "weird" that goes down a different path than the general Tornado community, since authentication and authorization, while it is something we need, isn't something that is at the core of our product and so isn't where we should be differentiating ourselves. So, we're looking for what most people (who use Tornado) are doing in this respect, hence I think it's a question with (in theory) an objectively true answer.</p>
<p>The ideal answer would point to example code, of course.</p> | 15,265,556 | 4 | 0 | null | 2013-03-06 17:55:38.937 UTC | 8 | 2016-03-10 14:04:26.587 UTC | 2013-03-07 07:38:55.747 UTC | null | 656,804 | null | 155,946 | null | 1 | 14 | python|tornado | 14,885 | <p>Tornado designed to be stateless and don't have session support out of the box. </p>
<p>Use secure cookies to store sensitive information like user_id.
Use standard cookies to store not critical information. </p>
<p>For storing large objects - use standard scheme - MySQL + memcache.</p> |
38,354,595 | java code execution yields to different results in debug without breakpoints and normal run. Is ExecutorService broken? | <p>TL:DR <code>ExecutorService executorService = Executors.newFixedThreadPool(8);</code>
in debug runs concurrent, but in normal runtime it starts concurrent, but later runs in single thread.</p>
<p>I have some code where I start 4 different tasks in <code>ExecutorService</code>. Two of those tasks should finish almost instantly, the other two should run for a while. </p>
<p>Those tasks return execution time in seconds in <code>Future<Double></code>.</p>
<p>This code is responsible for task execution and measurement:</p>
<pre><code>public Future<Double> measure(int[] arr, ProcessIntArray processIntArray, ExecutorService es) {
Callable<Double> task = () -> {
long start = System.nanoTime();
processIntArray.process(arr);
long end = System.nanoTime();
return (end - start) / 1000000000.0;
};
return es.submit(task);
}
</code></pre>
<p>Later on, after starting those tasks, I print them in the order of execution time from previous runs for the same input size.</p>
<pre><code> Future<Double> bubbleSortTime = measure(bubbleSortArray, Solution::bubbleSort, executorService);
Future<Double> insertionSortTime = measure(insertionSortArray, Solution::insertionSort, executorService);
Future<Double> quickSortTime = measure(quickSortArray, Solution::quickSort, executorService);
Future<Double> mergeSortTime = measure(mergeSortArray, Solution::mergeSort, executorService);
System.out.println();
System.out.println("array size: " + size);
System.out.println("quick sort: " + quickSortTime.get() + "s");
System.out.println("merge sort: " + mergeSortTime.get() + "s");
System.out.println("insertion sort: " + insertionSortTime.get() + "s");
System.out.println("bubble sort: " + bubbleSortTime.get() + "s");
</code></pre>
<p>When I run code in debug mode, 2 results are printed immidiately, and I have to wait a while for 3rd result (I do not bother waiting for the 4th one).</p>
<p>After starting in debug (correct and expected):</p>
<p><code>array size: 1000000
quick sort: 0.186892839s
merge sort: 0.291950604s
insertion sort: 344.534256723s</code></p>
<p>Normal execution differs, It looks like in method measure <code>long start = System.nanoTime();</code> is executed, then thread falls asleep, and after insertionSort is done, quickSort is back in execution, which yields to output:</p>
<p><code>array size: 1000000
quick sort: 345.893922141s
merge sort: 345.944023095s
insertion sort: 345.871908569s</code></p>
<p>Which is wrong. All of those threads should be running at the same time, as from newFixedThreadPool javadoc. </p>
<pre><code>/**
* Creates a thread pool that reuses a fixed number of threads
* operating off a shared unbounded queue. At any point, at most
* {@code nThreads} threads will be active processing tasks.
* If additional tasks are submitted when all threads are active,
* they will wait in the queue until a thread is available.
* If any thread terminates due to a failure during execution
* prior to shutdown, a new one will take its place if needed to
* execute subsequent tasks. The threads in the pool will exist
* until it is explicitly {@link ExecutorService#shutdown shutdown}.
*
* @param nThreads the number of threads in the pool
* @return the newly created thread pool
* @throws IllegalArgumentException if {@code nThreads <= 0}
*/
public static ExecutorService newFixedThreadPool(int nThreads)
</code></pre>
<p>I attach source code:</p>
<pre><code>import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.*;
class ThreadedSortingComparsion {
Random random = new Random(System.currentTimeMillis());
void popul(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt();
}
}
interface ArraySorter {
void sort(int[] array);
}
public Future<Double> measureTime(int[] array, ArraySorter arraySorter, ExecutorService executorService) {
Callable<Double> task = () -> {
long start = System.nanoTime();
arraySorter.sort(array);
long end = System.nanoTime();
return (end - start) / 1000000000.0;
};
return executorService.submit(task);
}
public void start() throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(8);
int size = 1000 * 1000;
int[] quickSortArray = new int[size];
popul(quickSortArray);
int[] bubbleSortArray = Arrays.copyOf(quickSortArray, quickSortArray.length);
int[] mergeSortArray = Arrays.copyOf(quickSortArray, quickSortArray.length);
int[] originalArray = Arrays.copyOf(quickSortArray, quickSortArray.length);
int[] insertionSortArray = Arrays.copyOf(quickSortArray, quickSortArray.length);
Future<Double> bubbleSortTime = measureTime(bubbleSortArray, ThreadedSortingComparsion::bubbleSort, executorService);
Future<Double> insertionSortTime = measureTime(insertionSortArray, ThreadedSortingComparsion::insertionSort, executorService);
Future<Double> quickSortTime = measureTime(quickSortArray, ThreadedSortingComparsion::quickSort, executorService);
Future<Double> mergeSortTime = measureTime(mergeSortArray, ThreadedSortingComparsion::mergeSort, executorService);
System.out.println();
System.out.println("array size: " + size);
System.out.println("quick sort: " + quickSortTime.get() + "s");
System.out.println("merge sort: " + mergeSortTime.get() + "s");
System.out.println("insertion sort: " + insertionSortTime.get() + "s");
System.out.println("bubble sort: " + bubbleSortTime.get() + "s");
executorService.shutdown();
for (int i = 0; i < quickSortArray.length; i++) {
if (quickSortArray[i] != bubbleSortArray[i] || quickSortArray[i] != mergeSortArray[i] || quickSortArray[i] != insertionSortArray[i]) {
throw new RuntimeException(Arrays.toString(originalArray));
}
}
}
public static void mergeSort(int[] ar) {
if (ar.length < 5) {
bubbleSort(ar);
return;
}
int middle = ar.length / 2;
int[] arrayLeft = new int[middle];
int[] arrayRight = new int[ar.length - middle];
for (int i = 0; i < ar.length; i++) {
if (i < middle) {
arrayLeft[i] = ar[i];
} else {
arrayRight[i - middle] = ar[i];
}
}
mergeSort(arrayLeft);
mergeSort(arrayRight);
int indexLeft = 0;
int indexRight = 0;
int inputArrayIndex = 0;
while (true) {
int whatToPutInAR = 0;
if (indexLeft != arrayLeft.length && indexRight != arrayRight.length) {
if (arrayLeft[indexLeft] < arrayRight[indexRight]) {
whatToPutInAR = arrayLeft[indexLeft];
indexLeft++;
} else {
whatToPutInAR = arrayRight[indexRight];
indexRight++;
}
} else if (indexLeft != arrayLeft.length) {
whatToPutInAR = arrayLeft[indexLeft];
indexLeft++;
} else if (indexRight != arrayRight.length) {
whatToPutInAR = arrayRight[indexRight];
indexRight++;
}
if (inputArrayIndex == ar.length) return;
ar[inputArrayIndex++] = whatToPutInAR;
}
}
private static void quickSort(int[] ar) {
quickSort(ar, 0, ar.length);
}
static public void quickSort(int[] array, int start, int end) {
boolean changed = false;
if (end == 0) return;
int pivot = array[end - 1];
int partitionCandidate = start;
for (int i = start; i < end; i++) {
if (array[i] < pivot) {
swap(array, partitionCandidate++, i);
changed = true;
} else if (pivot < array[i]) {
swap(array, end - 1, i);
changed = true;
}
}
if (start < partitionCandidate) {
quickSort(array, start, partitionCandidate);
}
if (partitionCandidate < end) {
if (partitionCandidate != start || changed) quickSort(array, partitionCandidate, end);
}
}
public static void swap(int[] ar, int from, int to) {
int old = ar[from];
ar[from] = ar[to];
ar[to] = old;
}
public static void bubbleSort(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
swap(array, j + 1, j);
}
}
}
}
private static void insertionSort(int[] ar) {
for (int i = 0; i < ar.length; i++) {
for (int j = i; j >= 1; j--) {
boolean breaker = true;
if (ar[j] < ar[j - 1]) {
breaker = false;
swap(ar, j - 1, j);
}
if (breaker) break;
}
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadedSortingComparsion s = new ThreadedSortingComparsion();
s.start();
}
}
</code></pre>
<p>Edit:
when I run it in Ideone, the code works fine.
<a href="http://ideone.com/1E8C51" rel="noreferrer">http://ideone.com/1E8C51</a>
Ideone has java version <code>1.8.0_51</code>
I tested in on <code>1.8.0_91</code>, <code>1.8.0_92</code>. And <code>1.8.0_45</code>.
Why does it work on ideone, but not on 2 other PC's I tested?</p>
<p>When I do thread dump, while executing not in the debug, then I wait a while, and after thread dump is printed, also results are printed. So the thread dump is done after finishing insertion sort.</p>
<pre><code>"C:\Program Files\Java\jdk1.8.0_45\bin\java" -Xmx8G -Xss1G -Didea.launcher.port=7533 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_45\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\deploy.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\access-bridge-64.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\cldrdata.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\dnsns.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\jaccess.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\jfxrt.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\localedata.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\nashorn.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunec.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunjce_provider.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunmscapi.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunpkcs11.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\zipfs.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\javaws.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\jfxswt.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\management-agent.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\plugin.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_45\jre\lib\rt.jar;C:\Users\Tomasz_Mielczarski\IdeaProjects\untitled\out\production\untitled;C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 2016.1.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain ThreadedSortingComparsion
array size: 1000000
2016-07-15 13:45:22
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.45-b02 mixed mode):
"pool-1-thread-4" #15 prio=5 os_prio=0 tid=0x00000000696bd000 nid=0x560 runnable [0x00000002fffee000]
java.lang.Thread.State: RUNNABLE
at ThreadedSortingComparsion.mergeSort(ThreadedSortingComparsion.java:77)
at ThreadedSortingComparsion.mergeSort(ThreadedSortingComparsion.java:78)
at ThreadedSortingComparsion.mergeSort(ThreadedSortingComparsion.java:78)
at ThreadedSortingComparsion.mergeSort(ThreadedSortingComparsion.java:78)
at ThreadedSortingComparsion.mergeSort(ThreadedSortingComparsion.java:77)
at ThreadedSortingComparsion$$Lambda$5/81628611.sort(Unknown Source)
at ThreadedSortingComparsion.lambda$measureTime$0(ThreadedSortingComparsion.java:21)
at ThreadedSortingComparsion$$Lambda$2/1023892928.call(Unknown Source)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
"pool-1-thread-3" #14 prio=5 os_prio=0 tid=0x00000000696bb800 nid=0x2634 runnable [0x00000002bffee000]
java.lang.Thread.State: RUNNABLE
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:123)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:126)
at ThreadedSortingComparsion.quickSort(ThreadedSortingComparsion.java:105)
at ThreadedSortingComparsion$$Lambda$4/1989780873.sort(Unknown Source)
at ThreadedSortingComparsion.lambda$measureTime$0(ThreadedSortingComparsion.java:21)
at ThreadedSortingComparsion$$Lambda$2/1023892928.call(Unknown Source)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
"pool-1-thread-2" #13 prio=5 os_prio=0 tid=0x00000000696b7800 nid=0x1c70 waiting on condition [0x000000027ffef000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x0000000719d72480> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2039)
at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:442)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
"pool-1-thread-1" #12 prio=5 os_prio=0 tid=0x00000000696b6800 nid=0x478 runnable [0x000000023ffee000]
java.lang.Thread.State: RUNNABLE
at ThreadedSortingComparsion.bubbleSort(ThreadedSortingComparsion.java:139)
at ThreadedSortingComparsion$$Lambda$1/990368553.sort(Unknown Source)
at ThreadedSortingComparsion.lambda$measureTime$0(ThreadedSortingComparsion.java:21)
at ThreadedSortingComparsion$$Lambda$2/1023892928.call(Unknown Source)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
"Monitor Ctrl-Break" #11 daemon prio=5 os_prio=0 tid=0x0000000068d3d000 nid=0x2f3c runnable [0x00000001fffee000]
java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:170)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
- locked <0x00000007156892b8> (a java.io.InputStreamReader)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
- locked <0x00000007156892b8> (a java.io.InputStreamReader)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at com.intellij.rt.execution.application.AppMain$1.run(AppMain.java:93)
at java.lang.Thread.run(Thread.java:745)
"Service Thread" #10 daemon prio=9 os_prio=0 tid=0x0000000068c81000 nid=0x2d6c runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C1 CompilerThread3" #9 daemon prio=9 os_prio=2 tid=0x0000000068bea800 nid=0x1ad0 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread2" #8 daemon prio=9 os_prio=2 tid=0x0000000068be4000 nid=0x17d0 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread1" #7 daemon prio=9 os_prio=2 tid=0x0000000068bdd800 nid=0x3238 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"C2 CompilerThread0" #6 daemon prio=9 os_prio=2 tid=0x0000000068bda000 nid=0x1824 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Attach Listener" #5 daemon prio=5 os_prio=2 tid=0x0000000068bd8800 nid=0x910 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Signal Dispatcher" #4 daemon prio=9 os_prio=2 tid=0x0000000068bd7800 nid=0x31f8 waiting on condition [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
"Finalizer" #3 daemon prio=8 os_prio=1 tid=0x0000000043229800 nid=0x2810 in Object.wait() [0x00000000fffee000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x0000000719d707e0> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
- locked <0x0000000719d707e0> (a java.lang.ref.ReferenceQueue$Lock)
at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)
"Reference Handler" #2 daemon prio=10 os_prio=2 tid=0x0000000043223000 nid=0xd48 in Object.wait() [0x00000000bffef000]
java.lang.Thread.State: WAITING (on object monitor)
at java.lang.Object.wait(Native Method)
- waiting on <0x0000000719d78370> (a java.lang.ref.Reference$Lock)
at java.lang.Object.wait(Object.java:502)
at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:157)
- locked <0x0000000719d78370> (a java.lang.ref.Reference$Lock)
"main" #1 prio=5 os_prio=0 tid=0x000000000311d800 nid=0x2ed0 waiting on condition [0x000000004311e000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x0000000719d58fe0> (a java.util.concurrent.FutureTask)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
at java.util.concurrent.FutureTask.awaitDone(FutureTask.java:429)
at java.util.concurrent.FutureTask.get(FutureTask.java:191)
at ThreadedSortingComparsion.start(ThreadedSortingComparsion.java:48)
at ThreadedSortingComparsion.main(ThreadedSortingComparsion.java:162)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
"VM Thread" os_prio=2 tid=0x0000000056348800 nid=0x2984 runnable
"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x0000000043147000 nid=0x27e0 runnable
"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x0000000043148800 nid=0x20b4 runnable
"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x000000004314a000 nid=0x1da4 runnable
"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x000000004314c000 nid=0x29e0 runnable
"GC task thread#4 (ParallelGC)" os_prio=0 tid=0x000000004314e000 nid=0xa04 runnable
"GC task thread#5 (ParallelGC)" os_prio=0 tid=0x0000000043150000 nid=0x14b8 runnable
"GC task thread#6 (ParallelGC)" os_prio=0 tid=0x0000000043153800 nid=0xf00 runnable
"GC task thread#7 (ParallelGC)" os_prio=0 tid=0x0000000043154800 nid=0x243c runnable
"VM Periodic Task Thread" os_prio=2 tid=0x0000000068c82000 nid=0x22d8 waiting on condition
JNI global references: 224
Heap
PSYoungGen total 76288K, used 13755K [0x0000000715580000, 0x000000071aa80000, 0x00000007c0000000)
eden space 65536K, 4% used [0x0000000715580000,0x0000000715874910,0x0000000719580000)
from space 10752K, 99% used [0x0000000719580000,0x0000000719ffa348,0x000000071a000000)
to space 10752K, 0% used [0x000000071a000000,0x000000071a000000,0x000000071aa80000)
ParOldGen total 175104K, used 33211K [0x00000005c0000000, 0x00000005cab00000, 0x0000000715580000)
object space 175104K, 18% used [0x00000005c0000000,0x00000005c206ed30,0x00000005cab00000)
Metaspace used 4277K, capacity 4790K, committed 4992K, reserved 1056768K
class space used 484K, capacity 535K, committed 640K, reserved 1048576K
quick sort: 355.579434803s
merge sort: 355.629940032s
insertion sort: 355.532578023s
</code></pre> | 38,427,546 | 1 | 6 | null | 2016-07-13 14:31:47.833 UTC | 17 | 2016-09-06 16:22:29.11 UTC | 2016-09-06 16:22:29.11 UTC | null | 1,283,519 | null | 3,319,557 | null | 1 | 25 | java|multithreading|jvm|executorservice|java-threads | 3,864 | <blockquote>
<p><strong>TL;DR</strong> HotSpot JIT optimization to eliminate safepoint checks in counted loops played a sick joke.</p>
</blockquote>
<p>This is a very interesting question: a simple Java test reveals a non-trivial problem deep inside JVM.</p>
<p>The fact that a thread dump hasn't appeared immediately indicates that the problem is not in Java code, but is somehow related to JVM. Thread dumps are printed at safepoints. The delay means that VM wasn't able to reach a safepoint in short time.</p>
<h2>Background</h2>
<p>Certain VM operations (GC, Deoptimization, Thread dump and <a href="https://stackoverflow.com/questions/29666057/analysis-on-gc-logs/29673564#29673564">some other</a>) are executed at stop-the-world pauses when no Java threads are running. But Java threads could not be stopped at any arbitrary point, they can pause only at certain places called <em>safepoints</em>. In JIT-compiled code the safepoints are usually placed at method exits and at backward branches, i.e. inside loops.</p>
<p>The safepoint checks are relatively cheap in terms of perfomance, but not free. That's why JIT compiler tries to reduce number of safepoints where possible. One such optimization is to eliminate safepoint checks in counted loops, i.e. loops with an integer counter that are known to have finite number of iterations.</p>
<h2>Verify the theory</h2>
<p>Let's get back to our test and check if safepoints are reached in time.</p>
<p>Add <code>-XX:+SafepointTimeout -XX:SafepointTimeoutDelay=1000</code> JVM options. This should print a debug message whenever VM fails to reach a safepoint in 1000 ms.</p>
<pre><code># SafepointSynchronize::begin: Timeout detected:
# SafepointSynchronize::begin: Timed out while spinning to reach a safepoint.
# SafepointSynchronize::begin: Threads which did not reach the safepoint:
# "pool-1-thread-2" #12 prio=5 os_prio=0 tid=0x0000000019004800 nid=0x1480 runnable [0x0000000000000000]
java.lang.Thread.State: RUNNABLE
# SafepointSynchronize::begin: (End of list)
</code></pre>
<p>Yes, it printed that the thread <code>pool-1-thread-2</code> could not stop in 1000 ms. This is the second thread of the Executor's pool, which should run <code>insertionSort</code> algorithm.</p>
<p><code>insertionSort</code> has two very long nested counted loops, and it looks like JVM has eliminated safepoint checks inside them. So, if this method runs in compiled mode, JVM cannot stop it until the method completes. If a stop-the-world pause is requested while the method is running, all other threads will also wait.</p>
<h2>What to do?</h2>
<p>This issue has been known for a long time. Here is the related JVM bug: <a href="https://bugs.openjdk.java.net/browse/JDK-5014723" rel="noreferrer">JDK-5014723</a>. It's not a high-priority one, since the problem rarely appears in real-life applications.</p>
<p>A new JVM flag appeared in JDK 8u92 to work around the issue.<br>
<code>-XX:+UseCountedLoopSafepoints</code> will always put safepoint checks inside loops.</p>
<p>Another solution would be to transform a long counted loop into generic one by modifying a counter variable inside the loop.</p>
<p>E.g. if you replace <code>if (breaker) break;</code> with <code>if (breaker) j = 0;</code> the problem will also disappear.</p>
<h2>Why does it work in debug mode then?</h2>
<p>When JVM is started with the debugger on, some JIT optimizations are disabled to make the debug info available. In this case the compiled code has all the safepoint checks.</p> |
7,806,921 | Log user in with remember-me functionality in Spring 3.1 | <p>I currently log users in programmatically (like when they login through Facebook or other means than using my login form) with:</p>
<pre><code>SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(user, "", authorities)
);
</code></pre>
<p>What I want to do instead is log the user in as if they set the remember-me option on in the login form. So I'm guessing I need to use the <code>RememberMeAuthenticationToken</code> instead of the <code>UsernamePasswordAuthenticationToken</code>? But what do I put for the <code>key</code> argument of the constructor?</p>
<pre><code>RememberMeAuthenticationToken(String key, Object principal, Collection<? extends GrantedAuthority> authorities)
</code></pre>
<p><strong><em>UPDATE</em></strong>: I'm using the <a href="http://static.springsource.org/spring-security/site/docs/3.1.x/reference/remember-me.html" rel="noreferrer">Persistent Token Approach described here</a>. So there is no key like in the Simple Hash-Based Token Approach.</p> | 7,811,334 | 2 | 2 | null | 2011-10-18 12:05:08.153 UTC | 11 | 2017-03-28 04:54:49.18 UTC | 2011-10-18 22:46:45.597 UTC | null | 326,389 | null | 326,389 | null | 1 | 17 | spring|spring-mvc|spring-security|security|remember-me | 9,908 | <p>I assume you already have <code><remember-me></code> set in your configuration.</p>
<p>The way remember-me works is it sets a cookie that is recognized when the user comes back to the site after their session has expired.</p>
<p>You'll have to subclass the <code>RememberMeServices</code> (<code>TokenBased</code> or <code>PersistentTokenBased</code>) you are using and make the onLoginSuccess() public. For example:</p>
<pre><code>public class MyTokenBasedRememberMeServices extends PersistentTokenBasedRememberMeServices {
@Override
public void onLoginSuccess(HttpServletRequest request, HttpServletResponse response, Authentication successfulAuthentication) {
super.onLoginSuccess(request, response, successfulAuthentication);
}
}
<remember-me services-ref="rememberMeServices"/>
<bean id="rememberMeServices" class="foo.MyTokenBasedRememberMeServices">
<property name="userDetailsService" ref="myUserDetailsService"/>
<!-- etc -->
</bean>
</code></pre>
<p>Inject your RememberMeServices into the bean where you are doing the programmatic login. Then call <code>onLoginSuccess()</code> on it, using the UsernamePasswordAuthenticationToken that you created. That will set the cookie.</p>
<pre><code>UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(user, "", authorities);
SecurityContextHolder.getContext().setAuthentication(auth);
getRememberMeServices().onLoginSuccess(request, response, auth);
</code></pre>
<p><strong>UPDATE</strong></p>
<p>@at improved upon this, with no subclassing of <code>RememberMeServices:</code></p>
<pre><code>UsernamePasswordAuthenticationToken auth =
new UsernamePasswordAuthenticationToken(user, "", authorities);
SecurityContextHolder.getContext().setAuthentication(auth);
// This wrapper is important, it causes the RememberMeService to see
// "true" for the "_spring_security_remember_me" parameter.
HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
@Override public String getParameter(String name) { return "true"; }
};
getRememberMeServices().loginSuccess(wrapper, response, auth);
</code></pre> |
7,880,107 | In proguard, how to preserve a set of classes' method names? | <p>I am using proguard to obfuscate my android application. The android application contains some native code, which makes callbacks to fully qualified java methods. I need to not obfuscate these classes and the names of their methods. The below properly keeps the class names, but not the method names. </p>
<pre><code>-keep public class com.me.dontobf.*
-keepnames public class com.me.dontobf.*
</code></pre> | 7,881,522 | 2 | 0 | null | 2011-10-24 18:30:02.05 UTC | 6 | 2019-05-12 07:39:14.73 UTC | 2011-10-24 18:37:34.163 UTC | null | 426,493 | null | 426,493 | null | 1 | 28 | java|android|proguard | 36,491 | <p>For native methods: <a href="https://www.guardsquare.com/en/products/proguard/manual/examples#native" rel="noreferrer">ProGuard manual > Examples > Processing native methods</a></p>
<pre><code># note that <methods> means any method
-keepclasseswithmembernames,includedescriptorclasses class * {
native <methods>;
}
</code></pre>
<p>In this case, for callback methods: <a href="https://www.guardsquare.com/en/products/proguard/manual/examples#callback" rel="noreferrer">ProGuard manual > Examples > Processing callback methods</a></p>
<pre><code>-keep class mypackage.MyCallbackClass {
void myCallbackMethod(java.lang.String);
}
</code></pre>
<p>Or e.g., if all public methods may be callback methods:</p>
<pre><code>-keep class mypackage.MyCallbackClass {
public <methods>;
}
</code></pre>
<p>You probably also need to keep any program classes that occur in the method descriptors.</p> |
9,067,536 | html5 forms with polyfills - is it worth it? | <p>Despite all of the buzz around html5 forms, it seems to me like you are creating extra work, in most scenarios, by going this route. </p>
<p>Take, for example, a datepicker field. The native html5 implementation of this renders differently in every browser. In addition your polyfilled solution (jquery UI for instance), for a browser not supporting this feature, will also render differently.</p>
<p>Now, we have introduced multiple points of customization and maintenance for the same form, when we had a perfectly working and unified solution with jquery!</p>
<p>I'd love to hear about some real world experiences in this area, because I'm getting annoyed with all of the buzz!</p> | 9,133,465 | 3 | 6 | null | 2012-01-30 16:52:31.38 UTC | 24 | 2015-09-29 10:01:00.807 UTC | 2013-06-06 17:47:40.94 UTC | null | 680,909 | null | 726,523 | null | 1 | 42 | html|forms|polyfills|webshim | 22,029 | <p>First of all I'm the creator of <a href="http://afarkas.github.com/webshim/demos/index.html" rel="noreferrer">webshims lib</a> (one of those polyfills, which isn't maintained anymore). To answer your question:</p>
<h1>Is it worth creating a forms polyfill for a project?</h1>
<p>No, it is really hard to do this just for one project. Well, I have done it, simply because I want to use modern technologies.</p>
<h1>Is it worth using a forms polyfill like webshims lib for a project?</h1>
<p>Yes absolutely! And here is why:</p>
<h2>1. Nice standardized declarative Markup API</h2>
<p>After including webshims and scripting the following:</p>
<pre><code>//polyfill forms (constraint validation) and forms-ext (date, range etc.)
$.webshims.polyfill('forms forms-ext');
</code></pre>
<p>You can simply write your widgets and your constraints into your form:</p>
<pre><code><input type="date" />
<input type="date" min="2012-10-11" max="2111-01-01" />
<input type="range" disabled />
<input type="email" required placeholder="Yo you can use a placeholder" />
</code></pre>
<p>This will create 3 different widgets and each are configured differently. No extra JS needed just standardized, clean and lean code.</p>
<h2>2. Standardized DOM-API</h2>
<p>Same goes to the DOM API. Here are just two examples: <a href="http://jsfiddle.net/trixta/SWQme/" rel="noreferrer">Combining two date fields</a> and <a href="http://jsfiddle.net/trixta/werS3/" rel="noreferrer">combining a range field with a date field</a>.</p>
<h2>3. works without JS in modern browsers</h2>
<p>Degrades gracefully in old browsers and works well in modern ones.</p>
<h2>4. Less file size in modern browsers</h2>
<p>Especially good for mobile (iOS 5, Blackberry have support for date for example)</p>
<h2>5. Better UX [mostly mobile]</h2>
<p>Better mobile UX (better input UI for touch, better performance, fits to the system), if you are using it: <a href="http://www.456bereastreet.com/lab/html5-input-types/email-iphone.png" rel="noreferrer">type="email"</a>, <a href="http://www.456bereastreet.com/lab/html5-input-types/number-iphone.png" rel="noreferrer">type="number"</a> and <a href="http://www.mobilexweb.com/wp-content/uploads/2011/10/input.png" rel="noreferrer">type="date"/type="range"</a></p>
<h1>But still, what about customizability?</h1>
<p>I'm a developer in a bigger agency and you are absolutely right most clients and most designers won't tolerate much differences, but I still want to use modern technologies, which means webshims lib can give you the best of both worlds.</p>
<h2>Customizing the constraint validation</h2>
<p><strong>The polyfilling part</strong></p>
<pre><code>//polyfill constraint validation
$.webshims.polyfill('forms');
</code></pre>
<p><strong>Customizing the UI for the error-bubble:</strong></p>
<pre><code>//on DOM-ready
$(function(){
$('form').bind('firstinvalid', function(e){
//show the invalid alert for first invalid element
$.webshims.validityAlert.showFor( e.target );
//prevent browser from showing native validation message
return false;
});
});
</code></pre>
<p>generates the following markup:</p>
<pre><code><!-- the JS code above will generate the following custom styleable HTML markup for the validation alert -->
<span class="validity-alert-wrapper" role="alert">
<span class="validity-alert">
<span class="va-arrow"><span class="va-arrow-box"></span></span>
<span class="va-box">Error message of the current field</span>
</span>
</span>
</code></pre>
<p><strong>Customizing the style of an invalid/valid form field:</strong></p>
<pre><code>.form-ui-invalid {
border-color: red;
}
.form-ui-valid {
border-color: green;
}
</code></pre>
<p><strong>Customizing the text of the validity alert:</strong></p>
<pre><code><input required data-errormessage="Hey this is required!!!" />
</code></pre>
<p>And now, what's the point:</p>
<ol>
<li>still works without JS</li>
<li>modern browsers load only the customization code (3kb min/gzipped) and old browsers do load the additional API (about 13kb min/gzip) (forms include a lot more than just constraint validation API, for example there is also autofocus, placeholder, output and so on)</li>
</ol>
<h2>And what is with your special example, customizing the datefield?</h2>
<p>No problem:</p>
<pre><code>//configure webshims to use customizable widget UI in all browsers
$.webshims.setOptions('forms-ext', {
replaceUI: true
});
$.webshims.polyfill('forms forms-ext');
</code></pre>
<p>And also here:</p>
<ol>
<li>still works without JS in modern browsers</li>
<li>modern browsers only load the UI and the UI-API glue, but not the DOM-API (valueAsNumber, valueAsDate...)</li>
</ol>
<p>And now, here comes the best:</p>
<pre><code>//configure webshims to use customizable widget UI in all non mobile browsers, but a customizable one in all desktop and all non-capable mobile browsers
$.webshims.setOptions('forms-ext', {
//oh, I know this is bad browser sniffing :-(
replaceUI: !(/mobile|ipad|iphone|fennec|android/i.test(navigator.userAgent))
});
$.webshims.polyfill('forms forms-ext');
</code></pre>
<ol>
<li>less file size and a better UX for mobile browsers (most clients and most designers will love you for having a different UI in mobile!!!)</li>
<li>still works without JS in modern browsers</li>
<li>modern browsers only load the UI and the UI-API glue, but not the DOM-API (valueAsNumber, valueAsDate...)</li>
</ol> |
9,124,995 | Generating Java from WSDL for use on Android with ksoap2-android SOAP client? | <p>I have to access a existing SOAP webservice from an Android application. I have been provided some WSDL files describing the webservice. Reading some <a href="https://stackoverflow.com/questions/297586/how-to-call-soap-web-service-with-android">other answers here on SO</a>, it seems <a href="http://code.google.com/p/ksoap2-android/" rel="noreferrer">ksoap2-android</a> is the way to go, with respect to which SOAP client to use.</p>
<p>The next issue is then how to generate the Java classes needed from the WSDL files, and this is where I am coming up short. As far as I can see there are the following options:</p>
<ol>
<li><a href="http://axis.apache.org/axis2/java/core/tools/eclipse/wsdl2java-plugin.html" rel="noreferrer">AXIS2 code generator</a></li>
<li><a href="http://code.google.com/p/wsdl2ksoap/" rel="noreferrer">WSDL2ksoap</a></li>
<li><a href="http://docs.oracle.com/javase/6/docs/technotes/tools/share/wsimport.html" rel="noreferrer">JAX-WS wsimport tool</a></li>
</ol>
<p>I initially tried #1, with the AXIS2 eclipse plugin for wsdl2code generator. The wizard did successfully generate a lot of Java code, however it also changed my android project to some kind of webservice project, and I was never able to get anything that was generated to compile, let alone work with ksoap2-android. Has anybody has success with this?</p>
<p>I am not able to run wsdl2ksoap successfully, as it seems to require a running webservice, and all I have at the current point in time is WSDL files. Likewise from reading the webpage, it seems to be a project in its initial stages, and not really ready for prime time.</p>
<p>JAX-WS wsimport I have not had a chance to try yet. However I am unsure if what it generates will work with ksoap2-android?</p>
<p><strong>Question: How can I generate Java files from WSDL files, for use on Android with ksoap2-android SOAP client library?</strong></p>
<p>Thanks a lot in advance.</p>
<p>(PS: Yes, the choice is SOAP, it is suboptimal for Android use, but I cannot change that.)</p> | 9,273,472 | 6 | 10 | null | 2012-02-03 07:14:15.717 UTC | 17 | 2019-12-10 11:12:14.02 UTC | 2017-05-23 12:06:45.623 UTC | null | -1 | null | 81,398 | null | 1 | 36 | java|android|soap|wsdl|ksoap2 | 38,909 | <p>My conclusion after quite a bit of researching is that there is no such (mature) tool available, unfortunately. Neither AXIS2 or JAX-WS will work on Android, and WSDL2ksoap is simply too immature for any real use.</p>
<p>However there is a proprietary tool called <a href="http://wsclient.neurospeech.com/" rel="nofollow">wsclient++</a> that will do the job really well. (Read update below, when put to real use, it does not stand the distance at all.) It does not use the ksoap2-android client library, it has it's own.</p>
<p>The client library is a bit crude as it has a hard dependency on the http transport, making (unit) testing a bit complicated. But it can be modified quite easily to allow DI, as the source is available in the distributed jar file.</p>
<p>The wsdl to java generator however works just perfect, and will save us tons of time.</p>
<p><strong>Update</strong>
After working with <code>wsclient++</code> for a while, it is clear that the generated classes are really crude, and does not handle error cases at all. (Every method declares <code>throws Exception</code>).</p>
<p><strong>We are no longer using wsclient++, and I would not recommend anyone to use it!</strong>
We have not really found any working alternative, unfortunately. :/</p>
<p>In the end we converted our WSDL files using AXIS2, and then wrote a bunch of custom script to strip and transform the generated java files to something that will build on android using ksoap2-android library. Very hackish, and needs tons of manual labor to run. Unfortunately. If you find a better way, or one comes up, please provide a new answer.</p> |
23,802,970 | WAMP/MySQL errors not in correct language | <p>I've re-installed WAMP multiple times, searched literally hundreds of pages, and its not fixed this issue:</p>
<p><img src="https://i.stack.imgur.com/slrfD.png" alt="enter image description here"></p>
<p>I've looked inside the phpmyadmin config files, set:</p>
<pre><code>$cfg['Lang'] = 'en-utf-8';
</code></pre>
<p>Uninstalled multiple times (as mentioned) and seemed to have no luck what so ever. Any help would be appreciated. </p> | 23,907,676 | 3 | 6 | null | 2014-05-22 09:34:41.3 UTC | 15 | 2018-08-24 02:26:26.197 UTC | 2014-06-08 14:07:03.543 UTC | null | 3,444,240 | null | 3,664,313 | null | 1 | 76 | php|mysql|phpmyadmin|wampserver | 48,978 | <p>To change the language that MySQL uses when reporting you need to change the <code>my.ini</code> file as follows.</p>
<p>Find this line:</p>
<pre><code># Change your locale here !
lc-messages=fr_FR
</code></pre>
<p>And change it to your prefered language, for example:</p>
<pre><code>lc-messages=en_GB
</code></pre>
<p>To change it to English US, you can do like this:</p>
<pre><code>lc-messages=en_US
</code></pre>
<p>Save the file and then restart MySQL.</p>
<pre><code>left click wampmanager icon -> MySQL -> Service -> Restart Service
</code></pre>
<p>Remember the guys that produce WampServer are French so I guess thats why this has been added to the <code>my.ini</code> file, and they just forgot to remove it on this release.</p>
<h3>How to Find my.ini in WAMPServer</h3>
<p>Use the wampmanager menus like so :-</p>
<pre><code>left click wampmanager icon -> MySQL -> my.ini
</code></pre>
<p>This will load the my.ini file into your editor.</p>
<blockquote>
<p>Here you can find a list of <a href="https://dev.mysql.com/doc/refman/5.7/en/locale-support.html" rel="noreferrer">valid locales</a></p>
</blockquote> |
8,598,021 | iTerm 2 profiles | <p>I have recently switched over to iTerm2 and love it. I am wondering though if there is a way to use profiles to correspond to what environment/specific machine you are on. </p>
<p>Say if I am doing tasks in one window on my mac the profile is displayed as default, but if I ssh into a machine (lets say dev0), the profile on iTerm will update to profile dev0. Once I've finished with dev0 and call exit, the profile will switch to default again. </p>
<p>I realize one work around is to open up a specific profile whenever I want to ssh into another machine and have a way to distinguish, but if the connection is closed it requires you to notice based off text rather than say the background of the window.</p>
<p>Is this possible? If not how can this feature be added, and is there a way I can contribute?</p> | 8,600,248 | 7 | 3 | null | 2011-12-22 00:15:58.903 UTC | 27 | 2019-03-30 02:06:36.013 UTC | null | null | null | null | 1,076,611 | null | 1 | 46 | macos|iterm | 29,048 | <p>iTerm2 supports a custom escape code that changes the profile on the fly. Put it in your .bashrc or .bash_profile.</p>
<pre><code><esc>]50;SetProfile=X^G
</code></pre>
<p>where X is the profile. For instance, to change the profile to one called "Foo", us this shell script:</p>
<pre><code>#!/bin/bash
echo -e "\033]50;SetProfile=Foo\a"
</code></pre>
<p>To change it back when you log out, put code to change the profile back to default in ~/.bash_logout.</p> |
5,058,854 | Using Mathematica to build presentations and documents | <p>I use Mma mainly to solve relatively small problems.</p>
<p>I want to start using it also to prepare my <strong>presentations and documents</strong>, but I am having troubles to learn how to do it from the embedded help, and I guess some good resources may be available elsewhere.</p>
<p>Do you know any useful pointers (books, papers, videos ...)?</p>
<p>Do you have a "bag of tricks" to post here?</p>
<p><strong>Edit</strong></p>
<p>This question received two answers so far (@mzabsky's and Mr.Wizard's) and although both are useful, perhaps my concerns are much more basic. So I am posting an example of the <em>kind</em> of things I am unable to do (or understand how to discern how others did them).</p>
<p>I took the following example from <a href="http://www.mathematica-journal.com/issue/v10i1/contents/graph_draw/graph_draw.nb" rel="noreferrer">The Mathematica Journal</a> (the notebook at the left on the following image - click on the image to see full size):</p>
<p><a href="https://i.stack.imgur.com/iPBRD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iPBRD.png" alt="Enter image description here"></a></p>
<p>So, some issues, just to get the idea of my troubles:</p>
<p>1) I copied the text to my .nb on the right, formatted it with the same style (text), but the appearance is different, so I guess the style definition is different. How can I copy the style definitions from one .nb to the other?</p>
<p>2) The table below the text block doesn't have an attached style. How was it formatted? Where is the background color defined?</p>
<p>I would like pointers to read (or videos to look, or whatever) about these issues. I don't want you to write down here a book on Mathematica formatting!</p>
<h2>Summary of the links posted in answers</h2>
<ul>
<li><a href="http://forums.wolfram.com/mathgroup/archive/2007/Jul/msg00914.html" rel="noreferrer">A Mathgroup thread</a> (John Browne) and <a href="http://forums.wolfram.com/mathgroup/archive/2007/Jul/msg00832.html" rel="noreferrer">here</a> (David Park and
Selwyn Hollis)</li>
<li><a href="http://bobueland.com/2008/06/14/create-a-style-sheet/" rel="noreferrer">Advice from Bob Ueland</a></li>
<li><a href="http://reference.wolfram.com/mathematica/guide/PalettesMenu.html" rel="noreferrer">The Writing Assistant Palette</a></li>
<li><a href="http://home.comcast.net/~djmpark/" rel="noreferrer">David Park's notes</a></li>
<li><a href="ftp://ftp.physics.uwa.edu.au/pub/MATH2200/2010/" rel="noreferrer">Simon's documents</a></li>
<li><a href="http://www.mathematica-users.org/webMathematica/wiki/wiki.jsp?pageName=Notebook:Tips.nb" rel="noreferrer">Tips for Mathematica SlideShow presenters</a></li>
<li><a href="http://library.wolfram.com/tips/notebookformatting.html" rel="noreferrer">Notebook formatting</a></li>
<li><a href="http://library.wolfram.com/infocenter/Conferences/7564/" rel="noreferrer">Presentations with Mathematica</a></li>
<li><a href="http://www.wolfram.com/broadcast/#Tutorials-Notebooks" rel="noreferrer">Videos</a></li>
<li><a href="http://library.wolfram.com/infocenter/TechNotes/5299/" rel="noreferrer">Tips for Mathematica Slide Show Presenters</a></li>
<li><a href="http://library.wolfram.com/infocenter/MathSource/6282/" rel="noreferrer">How to - Automatic Slide Show</a></li>
<li><a href="http://reference.wolfram.com/mathematica/howto/CreateALectureNotebook.html" rel="noreferrer">Create a Lecture Notebook</a></li>
</ul> | 5,061,599 | 4 | 1 | null | 2011-02-20 17:59:44.337 UTC | 42 | 2016-02-13 02:36:56.113 UTC | 2016-02-13 02:36:56.113 UTC | null | 353,410 | null | 353,410 | null | 1 | 40 | wolfram-mathematica | 12,711 | <p>I agree with all that mzabsky said in his answer.
Here's a few of extra things:</p>
<p>I find it useful to make statements using a <code>Text</code> or <code>DisplayFormula</code> cell then manually group a Mathematica check/proof to the statement which is then collapsed and can be displayed when you want.</p>
<p>The <a href="http://reference.wolfram.com/mathematica/guide/PalettesMenu.html" rel="nofollow">Writing Assistant Palette</a> has quite a few useful constructions in it that you can learn from.</p>
<p>Finally, I found it really useful to make my own style sheet for a couple reasons:
1) the built-in ones are a bit ugly; 2) it really helps you to understand how the notebooks work.</p>
<p>To see examples of the stylesheet I made (which I don't claim to be perfect - I didn't bother making it work in all screen environments) look at some of the files in <a href="ftp://ftp.physics.uwa.edu.au/pub/MATH2200/2010/" rel="nofollow">ftp://ftp.physics.uwa.edu.au/pub/MATH2200/2010/</a>. I use a similar stylesheet in all of my notes - I have many research projects primarily contained in Mma notebooks, eg <a href="http://arxiv.org/abs/1102.3043" rel="nofollow">http://arxiv.org/abs/1102.3043</a>.</p>
<p>Like Mr Wizard, I also recommend <a href="http://home.comcast.net/~djmpark/" rel="nofollow">David Park's notes</a> as a starting point. Also, you should study stylesheets that you like by going to the Format menu and clicking "Edit Stylesheet". Don't forget to follow the links through the cascade of stylesheets (version 6 onwards).</p>
<p>To answer the questions in your edit: Once you are viewing a notebook's stylesheet, you can save it, edit it, and use it in your own documents. Stylesheets in
<code>$UserBaseDirectory/SystemFiles/FrontEnd/StyleSheets</code> are automatically available in the menu. You can then use that stylesheet in any notebook by simply selecting it from the menu.</p>
<p>The formating in the screenshot that you posted is all contained in the stylesheet. This includes the grey background in the table.</p>
<h2>Addendum:</h2>
<p>When distributing notebooks to others, if the stylesheet is external from the notebook, then other people will not see it as you do. To include the stylesheet into the current notebook, you need code like</p>
<pre><code>ss = StyleDefinitions /. Options[EvaluationNotebook[]]
fn = ToFileName[{$UserBaseDirectory, "SystemFiles", "FrontEnd", "StyleSheets"}, ss]
If[FileExistsQ[fn],
style=Get[fn];SetOptions[EvaluationNotebook[],StyleDefinitions->style];,
Print["Can not find file"]]
</code></pre>
<p>(Assuming the file is in stored in the conventional place)</p>
<p>Here's an <a href="http://pastebin.com/ENLbMW9L" rel="nofollow">EmbedStylesheet.m</a> that is an improved version of the above.</p> |
5,122,345 | Why use Apache Web Server in front of Glassfish or Tomcat? | <p>Is it good idea to use Apache Webserver in front of GF or Tomcat? Does it improve the performance/security?</p>
<p>Or there is not any reason to use Apache Web Server with GF?</p> | 5,122,553 | 5 | 1 | null | 2011-02-25 20:38:13.31 UTC | 34 | 2020-02-20 23:19:57.2 UTC | 2011-09-13 02:19:01.357 UTC | null | 25,688 | null | 192,315 | null | 1 | 57 | apache|tomcat|glassfish | 39,749 | <p>Taken from <a href="https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q3" rel="nofollow noreferrer">https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q3</a></p>
<ul>
<li>Clustering. By using Apache HTTP as a front end you can let Apache HTTP act as a front door to your content to multiple Apache Tomcat instances. If one of your Apache Tomcats fails, Apache HTTP ignores it and your Sysadmin can sleep through the night. This point could be ignored if you use a hardware loadbalancer and Apache Tomcat's clustering capabilities.</li>
<li>Clustering/Security. You can also use Apache as a front door to different Apache Tomcats for different URL namespaces (/app1/, /app2/, /app3/, or virtual hosts). The Apache Tomcats can then be each in a protected area and from a security point of view, you only need to worry about the Apache HTTP server. Essentially, Apache becomes a smart proxy server.</li>
<li>Security. This topic can sway one either way. Java has the security manager while Apache has a larger mindshare and more tricks with respect to security. I won't go into this in more detail, but let Google be your friend. Depending on your scenario, one might be better than the other. But also keep in mind, if you run Apache with Tomcat - you have two systems to defend, not one.</li>
<li>Add-ons. Adding on CGI, perl, PHP is very natural to Apache. Its slower and more of a kludge for Tomcat. Apache HTTP also has hundreds of modules that can be plugged in at will. Apache Tomcat can have this ability, but the code hasn't been written yet.</li>
<li>Decorators! With Apache HTTP in front of Apache Tomcat, you can perform any number of decorators that Apache Tomcat doesn't support or doesn't have the immediate code support. For example, mod_headers, mod_rewrite, and mod_alias could be written for Apache Tomcat, but why reinvent the wheel when Apache HTTP has done it so well?</li>
<li>Speed. Apache HTTP is faster at serving static content than Apache Tomcat. But unless you have a high traffic site, this point is useless. But in some scenarios, Apache Tomcat can be faster than Apache httpd. So benchmark YOUR site. Apache Tomcat can perform at httpd speeds when using the proper connector (APR with sendFile enabled). Speed should not be considered a factor when choosing between Apache httpd and Tomcat</li>
<li>Socket handling/system stability. Apache HTTP has better socket handling with respect to error conditions than Apache Tomcat. The main reason is Apache Tomcat must perform all its socket handling via the JVM which needs to be cross platform. The problem is socket optimization is a platform specific ordeal. Most of the time the java code is fine, but when you are also bombarded with dropped connections, invalid packets, invalid requests from invalid IP's, Apache HTTP does a better job at dropping these error conditions than JVM based program. (YMMV) </li>
</ul> |
5,224,524 | Lisp and Prolog for Artificial Intelligence? | <p>Now since i've taken a class 3 years ago in A.I. im clearly proficient enough to ask this question......just kidding just kidding ;)</p>
<p>but seriously, what is it about these languages that make them so popular for A.I. research. Even though A.I. research is "old"...it's came probably the longest way in the past 5-10 years it seems like....
Is it because the languages were somewhat "designed" around the concept of A.I. , or just that we have nothing really better to use right now?</p>
<p>I ask this because I've always found it quite interesting, and Im just kinda curious. If im entirely wrong and they use different languages I would love to know what all they use. I mean i can understand prolog, especially with Sentient/Propositional Logic and Fuzzy logic. but I dont understand "Why" we would use Lisp...and even what else A.I. researchers would use to do machine learning etc.</p>
<p>Any articles/books on the subject matter is helpful too :)</p> | 5,224,696 | 6 | 4 | null | 2011-03-07 19:53:14.297 UTC | 20 | 2020-03-05 22:57:46.023 UTC | null | null | null | user475353 | null | null | 1 | 34 | lisp|artificial-intelligence|prolog | 40,835 | <p>Can't really speak to Prolog, but here's why Lisp:</p>
<ul>
<li><p>Lisp is a <a href="http://en.wikipedia.org/wiki/Homoiconicity" rel="noreferrer">homoiconic</a> language, which means that the code is expressed in the same form (<a href="http://en.wikipedia.org/wiki/S-expression" rel="noreferrer">s-expressions</a>) as data structures in the language. i.e. "code is data". This has big advantages if you are writing code that modifies/manipulates other code, e.g. genetic algorithms or symbolic manipulation.</p></li>
<li><p>Lisp's macro system makes it well suited for defining problem-specific DSLs. Most Lisp developers effectively "extend the language" to do what they need. Again the fact that Lisp is homoiconic helps enormously here.</p></li>
<li><p>There is some historical connection, in that Lisp became popular at about the same time as a lot of the early AI research. Some <a href="https://stackoverflow.com/questions/130475/why-is-lisp-used-for-ai">interesting facts in this thread</a>.</p></li>
<li><p>Lisp works pretty well as a functional programming language. This is quite a good domain fit for AI (where you are often just trying to get the machine to learn how to produce the correct output for a given input).</p></li>
<li><p>Subjective view: Lisp seems to appeal to people with a mathematical mindset, which happens to be exactly whet you need for a lot of modern AI..... this is possible due to the fact that Lisp is pretty closely related to the untyped lambda calculus </p></li>
</ul>
<p>I'm doing some AI/machine learning work at the moment, and chose <a href="http://clojure.org/" rel="noreferrer">Clojure</a> (a modern Lisp on the JVM) pretty much for the above reasons.</p> |
5,391,124 | Select rows of a matrix that meet a condition | <p>In R with a matrix:</p>
<pre><code> one two three four
[1,] 1 6 11 16
[2,] 2 7 12 17
[3,] 3 8 11 18
[4,] 4 9 11 19
[5,] 5 10 15 20
</code></pre>
<p>I want to extract the submatrix whose rows have column three = 11. That is:</p>
<pre><code> one two three four
[1,] 1 6 11 16
[3,] 3 8 11 18
[4,] 4 9 11 19
</code></pre>
<p>I want to do this without looping. I am new to R so this is probably very obvious but the
documentation is often somewhat terse.</p> | 5,391,697 | 6 | 1 | null | 2011-03-22 12:21:48.457 UTC | 67 | 2019-06-01 18:35:33.703 UTC | 2018-05-28 10:10:50.423 UTC | null | 2,204,410 | null | 205,063 | null | 1 | 175 | r|select|matrix|submatrix | 513,547 | <p>This is easier to do if you convert your matrix to a data frame using as.data.frame(). In that case the previous answers (using subset or m$three) will work, otherwise they will not.</p>
<p>To perform the operation on a <em>matrix</em>, you can define a column by name:</p>
<pre><code>m[m[, "three"] == 11,]
</code></pre>
<p>Or by number:</p>
<pre><code>m[m[,3] == 11,]
</code></pre>
<p>Note that if only one row matches, the result is an integer vector, not a matrix.</p> |
5,383,401 | Android INJECT_EVENTS permission | <p>I am trying to create an application that will have a service running in the background that will be capable of injecting touch screen events into whatever activity is running. I am able to inject events into an Activity that is part of my application by calling <code>Instrumentation.sendPointerSync(motionEvent);</code> However if I try to do this without an activity from my application running I get a permission error saying that I don't have the INJECT_EVENTS permission. I've added this permission to my manifest like this: <code><uses-permission android:name="android.permission.INJECT_EVENTS"></uses-permission></code> Its still throwing the same permission exception though. After a bit of searching I've gotten the answer that in order to receive the INJECT_EVENTS permission your app must be signed by the same signature that the system is signed with. I am unclear however what exactly this means. I am going to have to find a custom rom build it and sign it with the same signature that the application is signed with. Then install the custom rom on my device, then install my app and I'll be able to inject the touch events correctly? If this is the case am I better off starting with a custom rom that is already put together, like one <a href="http://theunlockr.com/category/roms-2/android-roms-2/htc-g2-desire-z-roms/">from this page</a> Or is it a situation where I am going to need to grab a git copy of the android project and build the whole thing myslef? And either way does anyone know of a place you could point me that would get me working in the right direction to make this happen?</p> | 7,328,055 | 8 | 2 | null | 2011-03-21 20:41:56.967 UTC | 28 | 2021-02-02 11:39:17.573 UTC | null | null | null | null | 507,810 | null | 1 | 47 | android|permissions|rom | 63,331 | <p>Actually, this is pretty simple on a rooted device. I think any app that is running off /system will get access to whatever permissions it requires. So simply manually install your App to /system (as described here <a href="http://androidforums.com/droid-all-things-root/64603-installing-apk-system-app-directory.html" rel="nofollow noreferrer">http://androidforums.com/droid-all-things-root/64603-installing-apk-system-app-directory.html</a> ):</p>
<p>Execute the following commands in the terminal emulator to remount the /system directory as read/write and to install the application into the /system/app directory from the SDCARD:</p>
<pre><code>su
mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system
cp /sdcard/APP.apk /system/app
</code></pre>
<p>If you prefer to use adb from your computer, execute these commands:</p>
<pre><code>adb remount
adb shell cp /sdcard/APP.apk /system/app
</code></pre>
<p>Several users have utilized root explorer from the Google marketplace to simplify this process.</p>
<hr>
<p>Alternatively, check this out: <a href="https://stackoverflow.com/questions/3598662/how-to-compile-android-application-with-system-permissions">How to compile Android Application with system permissions</a></p> |
16,805,288 | JQuery get values from html table | <p>I am attempting to pull data from a dynamic table using JQuery, but every way I've tried turns the values into something else (the below code will return an "l" instead of the N/A I was expecting. I have tried using .each and .map as the function as well as .val .html and as you can see .text to pull the data. I am stuck as to why and what I am doing wrong. Any help would be greatly appreciated.</p>
<p><strong>HTML</strong></p>
<pre><code> <table id="attendees" class="attendees">
<thead>
<tr style="border-bottom: double;border-color: #007fff" ;="">
<th>Full Name</th>
<th>Membership Type</th>
<th>Membership Expiration Date</th>
<th>Free Vouchers</th>
<th>Classes From Pack Remaining</th>
<th>Yelp Check in</th>
<th>Payment Option</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<tr class="data">
<td>Students Name</td>
<td>N/A</td>
<td>N/A</td>
<td>0</td>
<td>0</td>
<td>Yes</td>
<td>
<ul id="list">
<select id="payment" name="payment">
<option>Cash/Credit</option>
<option>Free Voucher</option>
<option>Yelp Check-in</option>
</select>
</ul>
</td>
<td>
<div><a href="#" class="remove"><p>Remove</p></a>
</div>
</td>
</tr>
</tbody>
</table>
</code></pre>
<p><strong>JQuery</strong></p>
<pre><code>$("#submit").live('click', function (e) {
$("#attendees tr.data").map(function (index, elem) {
var x = $(this);
var cells = x.find('td');
var $data = cells.text();
//alert($data[1]);
if ($data[1] == "N/A") {
alert(true);
}
});
e.preventDefault();
});
</code></pre>
<p><strong>Final Solution</strong></p>
<p>Thanks first of all to everyone who chimed in, I honestly learned a little something from each persons answer. In the end this is what I settled on below. In hindsight I probably should of given a more thorough description on what I was attempting to accomplish. Which was to scan multiple rows of data and do something based on the info found in each row. To accomplish this I was forced to separate the <code>tr</code> and <code>td</code> <code>.each</code> functions. This allowed me to scan row by row and still get the individual data.<br>
Thanks again for everyone's help especially @TechHunter</p>
<pre><code>$("#submit").on('click', function (e) {
e.preventDefault();
$("#attendees tbody tr").each(function(i) {
var $data= [];
var x = $(this);
var cells = x.find('td');
$(cells).each(function(i) {
var $d= $("option:selected", this).val()||$(this).text();
$data.push($d);
});
if ($data[1] == "N/A") {
doSomething();
}
});
});
</code></pre> | 16,807,573 | 3 | 0 | null | 2013-05-29 04:02:42.737 UTC | 2 | 2016-10-15 17:28:58.707 UTC | 2016-10-15 17:28:58.707 UTC | null | 4,370,109 | null | 2,333,349 | null | 1 | 3 | jquery|html|arrays|object|html-table | 38,301 | <p>Simplest answer would be to add a class when you need to retrieve a value :</p>
<p><strong>HTML</strong></p>
<pre><code><table id="attendees" class="attendees">
<thead>
<tr style="border-bottom: double;border-color: #007fff" ;="">
<th>Full Name</th>
<th>Membership Type</th>
<th>Membership Expiration Date</th>
<th>Free Vouchers</th>
<th>Classes From Pack Remaining</th>
<th>Yelp Check in</th>
<th>Payment Option</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<tr class="data">
<td class="inputValue">Students Name</td>
<td class="inputValue">N/A</td>
<td class="inputValue">N/A</td>
<td class="inputValue">0</td>
<td class="inputValue">0</td>
<td class="inputValue">Yes</td>
<td>
<ul id="list">
<select id="payment" class="inputValue" name="payment">
<option>Cash/Credit</option>
<option>Free Voucher</option>
<option>Yelp Check-in</option>
</select>
</ul>
</td>
<td>
<div><a href="#" class="remove"><p>Remove</p></a>
</div>
</td>
</tr>
</tbody>
</table>
</code></pre>
<p><strong>Javascript</strong></p>
<pre><code>$("#submit").on('click', function (e) {
e.preventDefault();
var data = $("#attendees tr.data").map(function (index, elem) {
var ret = [];
$('.inputValue', this).each(function () {
var d = $(this).val()||$(this).text();
ret.push(d);
console.log(d);
if (d == "N/A") {
console.log(true);
}
});
return ret;
});
console.log(data);
console.log(data[0]);
});
</code></pre>
<p>It's easier and you only retrieve value you want to retrieve. Fast to implement and to maintain.</p>
<p><a href="http://jsfiddle.net/techunter/Tz4Ux/" rel="nofollow">Fiddle here</a></p> |
12,557,442 | Bug in iPhone Simulator 5.1 with Xcode 4.5 using UIManagedDocument | <p>I have a very weird problem I've spent the last two days trying to solve... I had a piece of code that was working perfectly fine on Xcode 4.4 and iOS 5.1 Simulator, using the 5.1 SDK. After I updated to Xcode 4.5 and the 6.0 SDK, my code stopped working in the iOS 5.1 Simulator... even though it works perfectly fine in the iOS 6.0 Simulator. Was there any change I'm not aware of?</p>
<p>This is the code:</p>
<pre><code>- (void)useDocument
{
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.database.fileURL path]]){
[self.database saveToURL:self.database.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
[self setupFetchedResultsController];
}];
} else if (self.database.documentState == UIDocumentStateClosed){
[self.database openWithCompletionHandler:^(BOOL success){
[self setupFetchedResultsController];
}];
} else if (self.database.documentState == UIDocumentStateNormal) {
[self setupFetchedResultsController];
}
}
</code></pre>
<p>For some reason saveToURL and openWithCompletionHandler never return in the 5.1 Simulator. Any one knows why?</p> | 12,576,978 | 3 | 5 | null | 2012-09-24 00:26:16.057 UTC | 8 | 2012-10-15 08:35:31.813 UTC | 2012-09-25 11:31:09.437 UTC | null | 624,459 | null | 545,207 | null | 1 | 9 | ios|xcode|core-data|xcode4.5|uimanageddocument | 2,457 | <p>I have the same problem under iPhone Simulator 5.1.
The file is created after a long time (30 seconds). But the completion handler is never called. Did you try it on a device?</p>
<p>EDIT: This seems a bug in iOS Simulator 5.1. I compiled the code on my old iPad with iOS 5.1.1 and it worked without an error!</p> |
12,126,731 | How can I make a div with irregular shapes with css3 and html5? | <p>I'm wondering is there any possibility to build div with irregular shapes, something, similar to this (e.g. Greenland, Europe, Africa). I want to create map like here with using CSS3 and HTML5.</p>
<p>Here is link to an example image: </p>
<p><img src="https://i.stack.imgur.com/vMNVT.png" alt=""></p> | 12,332,427 | 3 | 0 | null | 2012-08-26 00:20:27.65 UTC | 9 | 2021-06-25 18:21:12.957 UTC | 2017-01-18 16:53:46.867 UTC | null | 2,756,409 | null | 1,505,516 | null | 1 | 15 | html|css|css-shapes | 51,699 | <p>Elements have always been rectangular. Still, you can simulate other shapes by drawing CSS shapes within the rectangular division and by arranging different divisions (with z-index, etc.). This will help you:</p>
<p><a href="http://css-tricks.com/examples/ShapesOfCSS/" rel="noreferrer">http://css-tricks.com/examples/ShapesOfCSS/</a></p> |
12,479,054 | How to run functions outside websocket loop in python (tornado) | <p>I'm trying to set up a small example of a public Twitter stream over websockets. This is my websocket.py, and it's working.</p>
<p>What I'm wondering is: how can I interact with the websocket from 'outside' the class WSHandler (ie. not only answer when receiving a message from websocket.js)? Say I want to run some other function within this same script that would post "hello!" every five seconds and send that to the websocket (browser) without any interaction from client-side. How could I do that?</p>
<p>So it's kind of a fundamental beginner's question, I suppose, about how to deal with classes as those below. Any pointers in any direction would be greatly appreciated! </p>
<pre><code>import os.path
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
# websocket
class FaviconHandler(tornado.web.RequestHandler):
def get(self):
self.redirect('/static/favicon.ico')
class WebHandler(tornado.web.RequestHandler):
def get(self):
self.render("websockets.html")
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'new connection'
self.write_message("Hi, client: connection is made ...")
def on_message(self, message):
print 'message received: \"%s\"' % message
self.write_message("Echo: \"" + message + "\"")
if (message == "green"):
self.write_message("green!")
def on_close(self):
print 'connection closed'
handlers = [
(r"/favicon.ico", FaviconHandler),
(r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'static'}),
(r'/', WebHandler),
(r'/ws', WSHandler),
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "static"),
)
application = tornado.web.Application(handlers, **settings)
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
</code></pre> | 12,479,455 | 3 | 0 | null | 2012-09-18 14:28:09.753 UTC | 15 | 2016-10-11 08:25:28.643 UTC | 2014-04-03 19:05:31.977 UTC | null | 1,115,197 | null | 1,397,442 | null | 1 | 32 | python|websocket|tornado | 16,079 | <p>You could call a</p>
<pre><code>IOLoop.add_timeout(deadline, callback)
</code></pre>
<p>that calls the callback at specified deadline timeout (one shot, but you can reschedule), or use the</p>
<p><code>tornado.ioloop.PeriodicCallback</code> if you have a more periodic task.</p>
<p>See: <a href="http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.add_timeout" rel="nofollow">http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.add_timeout</a></p>
<p><strong>Update: some example</strong></p>
<pre><code>import datetime
def test():
print "scheduled event fired"
...
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
main_loop = tornado.ioloop.IOLoop.instance()
# Schedule event (5 seconds from now)
main_loop.add_timeout(datetime.timedelta(seconds=5), test)
# Start main loop
main_loop.start()
</code></pre>
<p>it calls <code>test()</code> after 5 seconds.</p>
<p><strong>Update 2:</strong></p>
<pre><code>import os.path
import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
# websocket
class FaviconHandler(tornado.web.RequestHandler):
def get(self):
self.redirect('/static/favicon.ico')
class WebHandler(tornado.web.RequestHandler):
def get(self):
self.render("websockets.html")
class WSHandler(tornado.websocket.WebSocketHandler):
def open(self):
print 'new connection'
self.write_message("Hi, client: connection is made ...")
tornado.ioloop.IOLoop.instance().add_timeout(datetime.timedelta(seconds=5), self.test)
def on_message(self, message):
print 'message received: \"%s\"' % message
self.write_message("Echo: \"" + message + "\"")
if (message == "green"):
self.write_message("green!")
def on_close(self):
print 'connection closed'
def test(self):
self.write_message("scheduled!")
handlers = [
(r"/favicon.ico", FaviconHandler),
(r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'static'}),
(r'/', WebHandler),
(r'/ws', WSHandler),
]
settings = dict(
template_path=os.path.join(os.path.dirname(__file__), "static"),
)
application = tornado.web.Application(handlers, **settings)
import datetime
if __name__ == "__main__":
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
</code></pre> |
12,168,873 | Cross compile Go on OSX? | <p>I am trying to cross-compile a go app on OSX to build binaries for windows and linux. I have read everything what I could find on the net. Closest example that I have found has been published on (apart from many unfinished discussions on go-nuts mailing list):</p>
<p><a href="http://solovyov.net/en/2012/03/09/cross-compiling-go/">http://solovyov.net/en/2012/03/09/cross-compiling-go/</a></p>
<p>yet it does not work on my installation. I have go 1.0.2. As 1.0.2 is quite recent it looks to me that all above examples do not apply to this version.</p>
<p>Tried to do <code>./make.bash --no-clean</code> with ENV vars set to 386/windows, it does build go, however it builds go for my installation which is <code>darwin/amd64</code> and completely ignores what is set in ENV that suppose to build different compiler.</p>
<p>Any advises how it can be done (if it can be done at all)?</p> | 35,878,611 | 8 | 13 | null | 2012-08-28 23:16:30.23 UTC | 99 | 2021-09-28 12:17:30.633 UTC | 2017-02-09 09:03:53.687 UTC | null | 2,932,052 | null | 1,454,391 | null | 1 | 159 | go|compilation|cross-compiling | 151,006 | <p>With Go 1.5 they seem to have improved the cross compilation process, meaning it is built in now. No <code>./make.bash</code>-ing or <code>brew</code>-ing required. The process is described <a href="http://dave.cheney.net/2015/08/22/cross-compilation-with-go-1-5">here</a> but for the TLDR-ers (like me) out there: you just set the <code>GOOS</code> and the <code>GOARCH</code> environment variables and run the go build.</p>
<p>For the even lazier copy-pasters (like me) out there, do something like this if you're on a *nix system:</p>
<pre><code>env GOOS=linux GOARCH=arm go build -v github.com/path/to/your/app
</code></pre>
<p>You even learned the <code>env</code> trick, which let you set environment variables for that command only, completely free of charge.</p> |
18,882,589 | Grails 2.3.0 Auto-reloading not working | <p>I recently upgrade our project to grails 2.3.0. Everything works fine except I've been having problems with auto-reload not working whenever I make changes to our code. This include all projects artefacts - controllers, domain, services, gsps, css and javascript files.</p>
<p>My older versions of grails work correctly and reloads and recompile every time I make a change.</p>
<p>I know this question is popular and I have searched Jira, Nabble and here for days now but none of what I have found have been able to solve my problem (I've even tried to add quotes like Peter suggested in this thread <a href="http://jira.grails.org/browse/GRAILS-7936" rel="nofollow noreferrer">http://jira.grails.org/browse/GRAILS-7936</a> and also this thread <a href="https://stackoverflow.com/questions/12672600/grails-project-not-auto-reloading">Grails Project Not Auto Reloading</a> did not help). </p>
<p>Am currently running grails on a Macbook pro with the following settings:</p>
<ul>
<li>grails version 2.3.0</li>
<li>Java version "1.7.0_17"
Java(TM) SE Runtime Environment (build 1.7.0_17-b02)
Java HotSpot(TM) 64-Bit Server VM (build 23.7-b01, mixed mode)</li>
<li>Running from terminal with Textmate as IDE</li>
</ul>
<p>Any help would be greatly appreciated.</p> | 18,884,692 | 5 | 4 | null | 2013-09-18 21:23:09.09 UTC | 12 | 2016-07-12 17:28:56.31 UTC | 2017-05-23 12:26:13.973 UTC | null | -1 | null | 1,795,776 | null | 1 | 39 | java|grails|grails-2.3 | 16,853 | <p>It seems that in Grails 2.3 the reloading is no longer the default </p>
<blockquote>
<p>In Grails 2.3 the reloading agent is no longer on the build system
path unless you pass the -reloading flag to the grails command:</p>
<p>grails -reloading run-app</p>
</blockquote>
<p>However, you can enable forking in your buildConfig using the following configuration:</p>
<pre><code>forkConfig = [maxMemory: 1024, minMemory: 64, debug: false, maxPerm: 256]
grails.project.fork = [
test: forkConfig, // configure settings for the test-app JVM
run: forkConfig, // configure settings for the run-app JVM
war: forkConfig, // configure settings for the run-war JVM
console: forkConfig // configure settings for the Swing console JVM ]
</code></pre>
<p>More information : <a href="http://grails.org/doc/2.3.x/guide/single.html#upgradingFromPreviousVersionsOfGrails" rel="noreferrer">Forked Execution and the Reloading Agent</a></p> |
3,319,249 | How do I do an LDAP query with JavaScript? | <p>I'm trying to make a sidebar gadget that has an LDAP query function but haven't been able to find very good, or any, useful documentation on the matter. I'm not hugely experienced with Javascript and know little to nothing about how LDAP queries function, so any information at all would be useful.</p>
<p>info:</p>
<ul>
<li>host: a.b.c.d.e</li>
<li>port: 389</li>
<li>ou: people</li>
<li>o: x_y_z</li>
<li>c: us</li>
</ul>
<p>first snippet:</p>
<pre><code>var sSearchURL = "ldap://a.b.c.d.e:389/o=x_y_z,c=us";
var URLsuffix = "dc=" + form.SearchData.value;
document.location = sSearchURL URLsuffix;
</code></pre>
<p>other snippet:</p>
<pre><code>var ldap = GetObject('LDAP:');
var ad = ldap.OpenDSObject(
'LDAP://a.b.c.d.e:389/o=x_y_z',
'cn=Administrator,ou=People,o=rootname',
'password',
0
);
</code></pre> | 3,335,223 | 4 | 2 | null | 2010-07-23 14:45:22.517 UTC | 2 | 2019-08-11 21:19:25.37 UTC | 2019-08-11 21:19:25.37 UTC | null | 5,405,967 | null | 398,259 | null | 1 | 9 | javascript|ldap | 38,226 | <p>As long as you want to run your JavaScript in a web browser, you are limited to the HTTP protocol and to the domain from which your script was loaded in the first place.</p>
<p>So, talking to an LDAP server will not be possible from a web browsers JavaScript engine.</p>
<p>There are JavaScript runtime environments that have less limitations where you can implement socket servers and clients. For LDAP conenctivity you'd have to write your own library or find some existing one.</p> |
11,221,033 | Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed | <p>I have a grid view on my page and I want to export it to the Excel Sheet,
Below is the code I had written to do this task, here I am already passing the dataset to the method to bind the grid and <code>btnExcelExport</code> is the button which will export the Grid Content in to Excel Sheet :-</p>
<pre><code>private void BindGridView(DataSet ds)
{
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
GVUserReport.DataSource = ds;
GVUserReport.DataBind();
btnExcelExport.Visible = true;
}
}
}
protected void btnExcelExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition","attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GVUserReport.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
return;
}
</code></pre>
<p>Now when I am debugging I found that the grid is binded sucessfully but when trying to export it to Excel, I'm getting this error:</p>
<blockquote>
<p>"Microsoft JScript runtime error:
Sys.WebForms.PageRequestManagerParserErrorException: The message
received from the server could not be parsed."</p>
</blockquote> | 11,221,536 | 9 | 0 | null | 2012-06-27 07:06:55.113 UTC | 17 | 2019-04-17 15:00:37.057 UTC | 2016-07-20 14:23:30.447 UTC | null | 6,357,360 | null | 1,423,007 | null | 1 | 60 | c#|asp.net | 133,119 | <p>I fixed this issue. As I'm using <code>UpdatePanel</code>, I added below code in the <code>Page_Load</code> event of the page and it worked for me:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e) {
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
scriptManager.RegisterPostBackControl(this.btnExcelExport);
//Further code goes here....
}
</code></pre> |
10,995,294 | border-radius not working | <p>I'm working on a basic <code>div</code> and for some peculiar reason, <code>border-radius: 7px</code> isn't applying to it.</p>
<pre><code>.panel {
float: right;
width: 120px;
height: auto;
background: #fff;
border-radius: 7px; // not working
}
</code></pre> | 30,584,574 | 12 | 1 | null | 2012-06-12 10:58:15.61 UTC | 16 | 2021-05-13 13:25:20.08 UTC | 2017-02-19 20:48:02.907 UTC | null | 3,885,376 | null | 473,213 | null | 1 | 88 | css|border | 183,758 | <p>To whomever may have this issue. My problem was border-collapse. It was set to:</p>
<pre><code>border-collapse: collapse;
</code></pre>
<p>I set it to:</p>
<pre><code>border-collapse: separate;
</code></pre>
<p>and it fixed the issue. </p> |
11,063,102 | Using Locales with Java's toLowerCase() and toUpperCase() | <p>I wanted code to convert all the characters in strings to uppercase or lowercase in Java.</p>
<p>I found a method that goes something like this:</p>
<pre><code>public static String changelowertoupper()
{
String str = "CyBeRdRaGoN";
str=str.toLowerCase(Locale.ENGLISH);
return str;
}
</code></pre>
<p>Now I've read that using certain <code>Locale</code>s, like Turkish, "returns <strong><em>i (without dot)</em></strong> instead of <strong><em>i (with dot)</em></strong>."</p>
<p>Is it safe to use <code>Locale</code>s like UK, US, ENGLISH, etc.? Are there any big differences between them when applied to strings?</p>
<p>Which is the most preferred <code>Locale</code> for <code>String</code>s?</p> | 11,063,161 | 6 | 4 | null | 2012-06-16 11:40:48.933 UTC | 13 | 2021-07-14 16:11:18.547 UTC | 2014-01-07 13:49:30.353 UTC | null | 1,737,819 | null | 1,456,914 | null | 1 | 93 | java|string|locale | 116,523 | <p>I think you should use locale ,</p>
<blockquote>
<p>For instance, "TITLE".toLowerCase() in a Turkish locale returns
"tıtle", where 'ı' is the LATIN SMALL LETTER DOTLESS I character. To
obtain correct results for locale insensitive strings, use
toLowerCase(Locale.ENGLISH).</p>
</blockquote>
<p>I refer to these links as solution to your problem
and it has point to keep in mind in you situation "Turkish"</p>
<pre><code>**FROM THE LINKS**
</code></pre>
<blockquote>
<p>toLowerCase() respects internationalization (i18n). It performs the
case conversion with respect to your Locale. When you call
toLowerCase(), internally toLowerCase(Locale.getDefault()) is getting
called. It is locale sensitive and you should not write a logic around
it interpreting locale independently.</p>
</blockquote>
<pre><code>import java.util.Locale;
public class ToLocaleTest {
public static void main(String[] args) throws Exception {
Locale.setDefault(new Locale("lt")); //setting Lithuanian as locale
String str = "\u00cc";
System.out.println("Before case conversion is "+str+
" and length is "+str.length());// Ì
String lowerCaseStr = str.toLowerCase();
System.out.println("Lower case is "+lowerCaseStr+
" and length is "+lowerCaseStr.length());// iı`
}
}
</code></pre>
<blockquote>
<p>In the above program, look at the string length before and after
conversion. It will be 1 and 3. Yes the length of the string before
and after case conversion is different. Your logic will go for a toss
when you depend on string length on this scenario. When your program
gets executed in a different environment, it may fail. This will be a
nice catch in code review.</p>
<p>To make it safer, you may use another method
toLowerCase(Locale.English) and override the locale to English always.
But then you are not internationalized.</p>
<p>So the crux is, toLowerCase() is locale specific.</p>
</blockquote>
<p><a href="http://lotusnotus.com/lotusnotus_en.nsf/dx/dotless-i-tolowercase-and-touppercase-functions-use-responsibly.htm" rel="noreferrer">reference 1</a><br>
<a href="https://stackoverflow.com/questions/1190254/tolowercase-with-special-unicode-characters-throws-exception">reference 2</a><br>
<a href="http://javapapers.com/core-java/javas-tolowercase-has-got-a-surprise-for-you/" rel="noreferrer">reference 3</a></p>
<br>
<p>Dotless-i, is a lowercase 'i' without dot. The uppercase of this character is the usual "I". There is another character, "I with dot". The lowercase of this character is the usual lowercase "i".</p>
<p>Have you noticed the problem? This unsymetrical conversion causes a serious problem in programming. We face this problem mostly in Java applications because of (IMHO) poor implementation of toLowerCase and toUpperCase functions.</p>
<p>In Java, String.toLowerCase() method converts characters to lowercase according to the default locale. This causes problems if your application works in Turkish locale and especially if you are using this function for a file name or a url that must obey a certain character set.</p>
<p>I have blogged about two serious examples before: The compile errors with Script libraries with "i" in their names and XSP Manager's fault if an XPage is in a database with "I" in its name.</p>
<p>There is a long history, as I said. For instance in some R7 version, router was unable to send a message to a recipient if his/her name starts with "I". Message reporting agents was not running in Turkish locale until R8. Anyone with Turkish locale could not install Lotus Notes 8.5.1 (it's real!). The list goes on...</p>
<p>There is almost no beta tester from Turkey and customers don't open PMR for these problems. So these problems are not going up to the first priority for development teams.</p>
<p>Even Java team has added a special warning to the latest documentation:</p>
<blockquote>
<p>This method is locale sensitive, and may produce unexpected results if
used for strings that are intended to be interpreted locale
independently. Examples are programming language identifiers, protocol
keys, and HTML tags. For instance, "TITLE".toLowerCase() in a Turkish
locale returns "tıtle", where 'ı' is the LATIN SMALL LETTER DOTLESS I
character. To obtain correct results for locale insensitive strings,
use toLowerCase(Locale.ENGLISH).</p>
</blockquote> |
12,758,425 | how to set the output image use com.android.camera.action.CROP | <p>I have code to crop an image, like this :</p>
<pre><code>public void doCrop(){
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,0);
int size = list.size();
if (size == 0 ){
Toast.makeText(this, "Cant find crop app").show();
return;
} else{
intent.setData(selectImageUri);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
startActivityForResult(i, CROP_RESULT);
}
}
}
public void onActivityResult (int requestCode, int resultCode, Intent dara){
if (resultCode == RESULT_OK){
if (requestCode == CROP_RESULT){
Bundle extras = data.getExtras();
if (extras != null){
bmp = extras.getParcelable("data");
}
File f = new File(selectImageUri.getPath());
if (f.exists()) f.delete();
Intent inten3 = new Intent(this, tabActivity.class);
startActivity(inten3);
}
}
}
</code></pre>
<p>from what i have read, the code <code>intent.putExtra("outputX", 300); intent.putExtra("outputY", 300);</code> is use to set the resolution of crop result, but why i can't get the result image resolution higer than 300x300? when I set the <code>intent.putExtra("outputX", 800); intent.putExtra("outputY", 800);</code> the crop function has no result or crash, any idea for this situation?</p>
<p>the log cat say "! ! ! FAILED BINDER TRANSACTION ! ! !</p> | 12,758,776 | 2 | 2 | null | 2012-10-06 09:19:24.56 UTC | 12 | 2014-12-17 12:02:36.437 UTC | 2014-12-17 12:02:36.437 UTC | null | 3,748,302 | null | 1,247,026 | null | 1 | 9 | android|image|image-processing|crop | 29,843 | <p>That Intent is not part of the public Android API and is not guaranteed to work on all devices. It was used in earlier versions of android 1.x and 2.x but it's not used anymore and is not recommended. That is probably why it's crashing all over the palce or working improperly.</p>
<p>Use methods such as <code>Bitmap.createBitmap(..)</code> or <code>Bitmap.createScaledBitmap(..)</code> to create a resized or cropped version of your original image. These are part of the Android API and are guaranteed to work.</p>
<p>See official docs <a href="http://developer.android.com/reference/android/graphics/Bitmap.html#createBitmap%28int,%20int,%20android.graphics.Bitmap.Config%29" rel="nofollow noreferrer">here</a> and <a href="http://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap%28android.graphics.Bitmap,%20int,%20int,%20boolean%29" rel="nofollow noreferrer">here</a></p>
<p>To crop a bitmap, you can use <code>Bitmap.createBitmap(Bitmap, int x, int y, int width, int height)</code>. For example, if you need to crop 10 pixels from each side of a bitmap then use this:</p>
<pre><code>Bitmap croppedBitmap = Bitmap.createBitmap(originalBitmap, 10, 10, originalBitmap.getWidth() - 20, originalBitmap.getHeight() - 20);
</code></pre>
<p>If you need to show the selector to the user. Then you can do something like this:</p>
<pre><code>private static final String TEMP_PHOTO_FILE = "temporary_holder.jpg";
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra("crop", "true");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, getTempUri());
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
startActivityForResult(photoPickerIntent, REQ_CODE_PICK_IMAGE);
private Uri getTempUri() {
return Uri.fromFile(getTempFile());
}
private File getTempFile() {
if (isSDCARDMounted()) {
File f = new File(Environment.getExternalStorageDirectory(),TEMP_PHOTO_FILE);
try {
f.createNewFile();
} catch (IOException e) {
}
return f;
} else {
return null;
}
}
private boolean isSDCARDMounted(){
String status = Environment.getExternalStorageState();
if (status.equals(Environment.MEDIA_MOUNTED))
return true;
return false;
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case REQ_CODE_PICK_IMAGE:
if (resultCode == RESULT_OK) {
if (imageReturnedIntent!=null){
File tempFile = getTempFile();
String filePath= Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
System.out.println("path "+filePath);
Bitmap selectedImage = BitmapFactory.decodeFile(filePath);
_image = (ImageView) findViewById(R.id.image);
_image.setImageBitmap(selectedImage );
}
}
}
</code></pre>
<p>code from <a href="https://stackoverflow.com/questions/2085003/how-to-select-and-crop-an-image-in-android">here</a></p> |
13,098,960 | Convert ArrayList of Integer Objects to an int array? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/718554/how-to-convert-an-arraylist-containing-integers-to-primitive-int-array">How to convert an ArrayList containing Integers to primitive int array?</a> </p>
</blockquote>
<p>I tried the code below, but it does not work. Do I have to make a loop copy the <code>ArrayList</code> into an array ?</p>
<pre><code>int[]intArray = (int[]) integerArrayList.toArray();
</code></pre> | 13,098,980 | 4 | 1 | null | 2012-10-27 09:42:47.193 UTC | 7 | 2014-04-07 13:23:20.33 UTC | 2017-05-23 11:47:00.513 UTC | null | -1 | null | 1,776,310 | null | 1 | 15 | java|arrays|arraylist | 72,972 | <p>If you want <em>primitive</em> type array, you can use <a href="http://commons.apache.org/lang/"><code>Apache Commons</code></a> <a href="http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/ArrayUtils.html#toPrimitive%28java.lang.Short%5b%5d%29"><code>ArrayUtils#toPrimitive</code></a> method to get primitive array from wrapper array: -</p>
<pre><code>public static int[] toPrimitive(Integer[] array)
</code></pre>
<p>You can use it like this: -</p>
<pre><code>int[] arr = ArrayUtils.toPrimitive((Integer[])integerArrayList.toArray());
</code></pre>
<p>Or, you can use the <em>1-arg</em> version of <em>toArray</em> method, that takes an <em>array</em> and returns the array of that type only. That way, you won't have to the <em>typecasting</em>.</p>
<pre><code>List<Integer> myList = new ArrayList<Integer>();
Integer[] wrapperArr = myList.toArray(new Integer[myList.size()]);
// If you want a `primitive` type array
int[] arr = ArrayUtils.toPrimitive(wrapperArr);
</code></pre>
<hr>
<p>However, if you are Ok with the <code>wrapper type</code> array <em>(Which certainly will not trouble you)</em>, then you <em>don't need</em> to do that last step.</p>
<hr>
<p>Also, you can also create a <em>primitive</em> array, without having to create that intermediate <em>Wrapper type</em> array. For that you would have to write it through <code>loop</code>: -</p>
<pre><code>int[] arr = new int[myList.size()];
for(int i = 0; i < myList.size(); i++) {
if (myList.get(i) != null) {
arr[i] = myList.get(i);
}
}
</code></pre> |
12,856,471 | c# search string in txt file | <p>I want to find a string in a txt file if string compares, it should go on reading lines till another string which I'm using as parameter.</p>
<p>Example:</p>
<pre class="lang-none prettyprint-override"><code>CustomerEN //search for this string
...
some text which has details about the customer
id "123456"
username "rootuser"
...
CustomerCh //get text till this string
</code></pre>
<p>I need the details to work with them otherwise.</p>
<p>I'm using linq to search for "CustomerEN" like this:</p>
<pre><code>File.ReadLines(pathToTextFile).Any(line => line.Contains("CustomerEN"))
</code></pre>
<p>But now I'm stuck with reading lines (data) till "CustomerCh" to extract details.</p> | 12,856,666 | 5 | 0 | null | 2012-10-12 09:51:58.467 UTC | 7 | 2020-11-11 08:14:32.713 UTC | 2020-11-11 08:14:32.713 UTC | null | 3,082,718 | null | 425,247 | null | 1 | 25 | c#|string|file-io | 152,371 | <p>If your pair of lines will only appear once in your file, you could use</p>
<pre><code>File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.Skip(1) // optional
.TakeWhile(line => !line.Contains("CustomerCh"));
</code></pre>
<p>If you could have multiple occurrences in one file, you're probably better off using a regular <code>foreach</code> loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:</p>
<pre><code>List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
current = new List<string>();
else if (line.Contains("CustomerCh") && current != null)
{
groups.Add(current);
current = null;
}
if (current != null)
current.Add(line);
}
</code></pre> |
13,137,766 | Why isn't std::string::max_size a compile-time constant? | <p><code>std::string</code> provides a <code>max_size()</code> method to determine the maximum number of elements it can contain.</p>
<p>However, to work out the maximum length of a string in general, the programmer has to create a (possibly empty) string object.</p>
<p>If this class doesn't need any information from the programmer, why isn't <code>max_size()</code> available as a compile-time constant ? Is there some kind of runtime information necessary for a string to work out its maximum size ?</p> | 13,139,088 | 4 | 4 | null | 2012-10-30 11:11:59.443 UTC | 2 | 2012-10-31 21:10:59.843 UTC | null | null | null | null | 361,535 | null | 1 | 34 | c++|string|compile-time-constant | 2,851 | <p>One reason is that the <code>max_size</code> function isn't very useful at all, and the committee doesn't think it is worth the trouble to try to fix it. So it is just left the way it is, because it is part of the documented interface.</p>
<p>See library defect report #197:</p>
<p><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3440.html#197" rel="noreferrer">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3440.html#197</a></p>
<blockquote>
<p>max_size() isn't useful for very many things, and the existing wording is sufficiently clear for the few cases that max_size() can be used for. None of the attempts to change the existing wording were an improvement.</p>
</blockquote> |
12,720,450 | Unpacking arguments: only named arguments may follow *expression | <p>The following works beautifully in Python:</p>
<pre><code>def f(x,y,z): return [x,y,z]
a=[1,2]
f(3,*a)
</code></pre>
<p>The elements of <code>a</code> get unpacked as if you had called it like <code>f(3,1,2)</code> and it returns <code>[3,1,2]</code>. Wonderful!</p>
<p>But I can't unpack the elements of <code>a</code> into the <em>first</em> two arguments:</p>
<pre><code>f(*a,3)
</code></pre>
<p>Instead of calling that like <code>f(1,2,3)</code>, I get "SyntaxError: only named arguments may follow *expression".</p>
<p>I'm just wondering why it has to be that way and if there's any clever trick I might not be aware of for unpacking arrays into arbitrary parts of argument lists without resorting to temporary variables.</p> | 12,830,036 | 6 | 1 | null | 2012-10-04 04:52:37.99 UTC | 5 | 2018-02-03 23:58:15.643 UTC | null | null | null | null | 4,234 | null | 1 | 47 | python|arrays|arguments | 27,198 | <p>As Raymond Hettinger's answer points out, this <s>may change</s> has changed in Python 3 and <a href="http://www.python.org/dev/peps/pep-3132/" rel="noreferrer">here is a related proposal</a>, which has been accepted.
Especially related to the current question, here's one of the possible changes to that proposal that was discussed:</p>
<blockquote>
<p>Only allow a starred expression as the last item in the exprlist. This would simplify the
unpacking code a bit and allow for the starred expression to be assigned an iterator. This
behavior was rejected because it would be too surprising.</p>
</blockquote>
<p>So there are implementation reasons for the restriction with unpacking function arguments but it is indeed a little surprising!</p>
<p>In the meantime, here's the workaround I was looking for, kind of obvious in retrospect:</p>
<pre><code>f(*(a+[3]))
</code></pre> |
12,795,935 | Checkstyle Eclipse plugin doesn't work | <p>I'm using eclipse checkstyle plugin with Juno Eclipse distribution. Anytime the code is checked for checkstyle error I get the following error: </p>
<pre><code>cannot initialize module TreeWalker - Unable to instantiate DoubleCheckedLocking
</code></pre>
<p>Does anybody know how to fix this problem? Is it a plugin compatibility issue or something else?</p> | 12,798,807 | 4 | 0 | null | 2012-10-09 08:32:58.027 UTC | 5 | 2016-05-06 08:46:52.097 UTC | 2016-05-06 08:46:52.097 UTC | null | 452,775 | null | 859,314 | null | 1 | 57 | eclipse|eclipse-plugin|checkstyle | 33,608 | <p>The DoubleCheckedLocking check has been removed in Checkstyle 5.6 and must be manually removed from your Checkstyle configuration.</p>
<p>See also: <a href="http://sourceforge.net/tracker/index.php?func=detail&aid=3571442&group_id=29721&atid=397078" rel="noreferrer">http://sourceforge.net/tracker/index.php?func=detail&aid=3571442&group_id=29721&atid=397078</a></p> |
13,032,948 | How to create and handle composite primary key in JPA | <p>I want to have versions from the same data entry. In other words, I want to duplicate the entry with another version number.</p>
<p><code>id - Version</code> will be the primary key. </p>
<p>How should the entity look like? How can I duplicate it with another version?</p>
<pre><code>id Version ColumnA
1 0 Some data
1 1 Some Other data
2 0 Data 2. Entry
2 1 Data
</code></pre> | 13,033,039 | 4 | 1 | null | 2012-10-23 14:37:38.54 UTC | 38 | 2017-12-15 21:09:36.603 UTC | 2017-12-15 21:09:36.603 UTC | null | 1,454,671 | null | 643,271 | null | 1 | 123 | java|jakarta-ee|jpa|composite-primary-key | 201,116 | <p>You can make an <code>Embedded class</code>, which contains your two keys, and then have a reference to that class as <code>EmbeddedId</code> in your <code>Entity</code>.</p>
<p>You would need the <a href="https://docs.oracle.com/javaee/6/api/javax/persistence/EmbeddedId.html"><code>@EmbeddedId</code></a> and <a href="https://docs.oracle.com/javaee/6/api/javax/persistence/Embeddable.html"><code>@Embeddable</code></a> annotations.</p>
<pre><code>@Entity
public class YourEntity {
@EmbeddedId
private MyKey myKey;
@Column(name = "ColumnA")
private String columnA;
/** Your getters and setters **/
}
</code></pre>
<pre><code>@Embeddable
public class MyKey implements Serializable {
@Column(name = "Id", nullable = false)
private int id;
@Column(name = "Version", nullable = false)
private int version;
/** getters and setters **/
}
</code></pre>
<hr>
<p>Another way to achieve this task is to use <code>@IdClass</code> annotation, and place both your <code>id</code> in that <code>IdClass</code>. Now you can use normal <code>@Id</code> annotation on both the attributes</p>
<pre><code>@Entity
@IdClass(MyKey.class)
public class YourEntity {
@Id
private int id;
@Id
private int version;
}
</code></pre>
<p></p>
<pre><code>public class MyKey implements Serializable {
private int id;
private int version;
}
</code></pre> |
13,222,671 | Why are flag enums usually defined with hexadecimal values | <p>A lot of times I see flag enum declarations that use hexadecimal values. For example:</p>
<pre class="lang-cs prettyprint-override"><code>[Flags]
public enum MyEnum
{
None = 0x0,
Flag1 = 0x1,
Flag2 = 0x2,
Flag3 = 0x4,
Flag4 = 0x8,
Flag5 = 0x10
}
</code></pre>
<p>When I declare an enum, I usually declare it like this:</p>
<pre class="lang-cs prettyprint-override"><code>[Flags]
public enum MyEnum
{
None = 0,
Flag1 = 1,
Flag2 = 2,
Flag3 = 4,
Flag4 = 8,
Flag5 = 16
}
</code></pre>
<p>Is there a reason or rationale to why some people choose to write the value in hexadecimal rather than decimal? The way I see it, it's easier to get confused when using hex values and accidentally write <code>Flag5 = 0x16</code> instead of <code>Flag5 = 0x10</code>.</p> | 13,222,740 | 7 | 6 | null | 2012-11-04 20:39:49.863 UTC | 39 | 2022-07-26 08:35:13.023 UTC | null | null | null | null | 389,966 | null | 1 | 134 | c#|.net|enums|enum-flags | 41,581 | <p>Rationales may differ, but an advantage I see is that hexadecimal reminds you: "Okay, we're not dealing with numbers in the arbitrary human-invented world of base ten anymore. We're dealing with bits - the machine's world - and we're gonna play by its rules." Hexadecimal is rarely used unless you're dealing with relatively low-level topics where the memory layout of data matters. Using it hints at the fact that that's the situation we're in now.</p>
<p>Also, i'm not sure about C#, but I know that in C <code>x << y</code> is a valid compile-time constant.
Using bit shifts seems the most clear:</p>
<pre class="lang-cs prettyprint-override"><code>[Flags]
public enum MyEnum
{
None = 0,
Flag1 = 1 << 0, //1
Flag2 = 1 << 1, //2
Flag3 = 1 << 2, //4
Flag4 = 1 << 3, //8
Flag5 = 1 << 4 //16
}
</code></pre> |
11,093,943 | Is it possible to make a div 50px less than 100% in CSS3? | <p>Is it possible to make a <code>div</code> 50px less than 100% in pure CSS? I want the <code><div></code> to be only 50px less than 100%. I don't want any JavaScript.</p> | 11,093,944 | 6 | 4 | null | 2012-06-19 03:18:52.41 UTC | 85 | 2013-04-18 02:58:03.713 UTC | 2012-06-21 15:05:26.023 UTC | null | 50,776 | null | 283,863 | null | 1 | 228 | html|css | 42,186 | <p>Yes you can. Without using the IE's <code>expression()</code>, you can do that in CSS3 by using <a href="http://www.w3.org/TR/css3-values/#calc" rel="noreferrer"><code>calc()</code></a>.</p>
<pre class="lang-css prettyprint-override"><code>div {
width: 100%;
width: -webkit-calc(100% - 50px);
width: -moz-calc(100% - 50px);
width: calc(100% - 50px);
}
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/thirtydot/Nw3yd/66/" rel="noreferrer">http://jsfiddle.net/thirtydot/Nw3yd/66/</a></p>
<p>This will make your life so much easier. It is currently supported in the 3 main browsers: Firefox, Google Chrome (WebKit), and IE9: <a href="http://caniuse.com/calc" rel="noreferrer">http://caniuse.com/calc</a></p>
<p>MDN: <a href="https://developer.mozilla.org/en/CSS/-moz-calc" rel="noreferrer">https://developer.mozilla.org/en/CSS/-moz-calc</a></p> |
16,993,904 | Android - Setting TextView to Bold Not Working | <p>Here is the XML:</p>
<pre><code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/modal_list_row"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="7.5dp"
android:orientation="vertical" >
<TextView
android:id="@+id/title_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="@string/alert_title_small"
android:textColor="@color/alert_dialog_text_color"
android:textSize="@dimen/alert_dialog_title_font_size"
android:textStyle="bold" />
</RelativeLayout>
</code></pre>
<p>Although the Graphical Layout shows bold text, on the device it's not. Is it a device thing or what?</p>
<p><strong>Update:</strong></p>
<p>For people who keeps on asking for the ful XML, here it is updated. A simple relative layout. And here is the Java Code:</p>
<pre><code>this.titleTextView.setText(this.modalListState.title);
</code></pre>
<p>Things to think about: Could it be due to the device typefaces? Does anyone have Galaxy S3 to confirm? Could it be the activity style? Here is the one used for the whole app:</p>
<pre><code><resources xmlns:android="http://schemas.android.com/apk/res/android">
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="android:Theme.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
<style name="TransparentActivity" >
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:colorBackgroundCacheHint">@null</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowAnimationStyle">@android:style/Animation</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowFullscreen">false</item>
</style>
</code></pre>
<p></p>
<p>The TransparentActivity style is used for the concerned activity.</p> | 17,063,538 | 10 | 7 | null | 2013-06-07 22:32:45.38 UTC | 3 | 2018-04-13 07:46:57.92 UTC | 2013-06-12 10:22:23.983 UTC | null | 1,149,647 | null | 1,149,647 | null | 1 | 32 | android|textview | 28,609 | <p>Well, I found a silly answer to this problem. I was using a custom font on the device, not the default one. Once I switched to the default one, every things worked as expected!</p> |
16,786,555 | Eclipse compiles successfully but still gives semantic errors | <p><em>NOTE: it apparently is a recurrent question on StackOverflow, but - for what I have seen - either people never find a way or their solution does not work for me</em></p>
<h1>The problem:</h1>
<p>I am using Eclipse Juno ADT. Everything was working fine until I tried to update the NDK. I replaced my <code>ndk</code> folder (that was the <code>ndk-r8d</code>) by the new version (i.e. <code>ndk-r8e</code>) and, in my <code>Paths and Symbols</code> configuration, I changed the includes to go from g++ 4.6 to 4.7.</p>
<p>It seemed to break my index: <strong>I could compile my code, but Eclipse was giving semantic errors, exactly like in [<a href="https://stackoverflow.com/questions/15612673/eclipse-cdt-displays-semantic-error-but-builds-successfully">1</a>] and [<a href="https://stackoverflow.com/questions/10103465/eclipse-cdt-complains-about-unresolved-functions-but-still-builds-successfully">2</a>].</strong> The errors <em>mainly</em> come from symbol used by OpenCV4Android, such as <code>distance</code>, <code>pt</code>, <code>queryIdx</code> and <code>trainIdx</code>.</p>
<p>When I tried to backup to my old configuration, the index was still broken! I cannot find a way to change this.</p>
<hr>
<h1>What I have tried</h1>
<ul>
<li>Clean up the project</li>
<li>Rebuild, refresh, and all the other options in the "Index" submenu (when "right-clicking" on the project)</li>
<li>Disable / enable the indexer in the preferences</li>
<li>Verify that symbols such as <code>trainIdx</code> only appear in my OpenCV4Android include in the <code>Paths and Symbols</code> section.</li>
<li>Change the order of my includes in the <code>Paths and Symbols</code> section. I basically tried to put the OpenCV include in the beginning and in the end.</li>
</ul>
<hr>
<h1>Some observations</h1>
<h2>What is not working</h2>
<p>I assume that it is the <strong>CDT index</strong> because of the following:</p>
<ul>
<li>In command line, I can build my project using <code>ndk-build clean</code> and <code>ndk-build</code>.</li>
<li>When I start Eclipse, I have no error until I open a C++ file (from the <code>jni</code> folder).</li>
<li>I can always build the project, but as long as I have opened a C++ file, I can't run the application anymore because of a lot of <code>Field '<name>' could not be resolved.</code></li>
<li>If I don't open the C++ files, Eclipse doesn't report any error and can build and deploy the Android application successfully.</li>
</ul>
<h2>Interesting fact</h2>
<p>The following code reports errors on <code>line</code>, <code>queryIdx</code>, <code>pt</code>:</p>
<pre><code>cv::line(mRgb, keypointsA[matches[i].queryIdx].pt, keypointsB[matches[i].trainIdx].pt, cv::Scalar(255, 0, 0, 255), 1, 8, 0);
</code></pre>
<p>If I write it as follows, it works:</p>
<pre><code>cv::DMatch tmpMatch = matches[i];
cv::KeyPoint queryKp = keypointsA[tmpMatch.queryIdx];
cv::KeyPoint trainKp = keypointsB[tmpMatch.trainIdx];
cv::line(mRgb, queryKp.pt, trainKp.pt, cv::Scalar(255, 0, 0, 255), 1, 8, 0);
</code></pre>
<p>It is not that all of the OpenCV functions are unresolved: only <code>pt</code>, <code>queryIdx</code> and <code>trainIdx</code> are.</p>
<p>Any comment will be really appreciated.</p> | 16,891,713 | 8 | 3 | null | 2013-05-28 07:46:16.813 UTC | 15 | 2016-07-19 10:42:25.893 UTC | 2017-05-23 10:31:16.803 UTC | null | -1 | null | 1,368,342 | null | 1 | 38 | android|c++|eclipse|opencv|android-ndk | 21,881 | <p>In your selected project preferences within the Eclipse environment, go to C/C++ General -> Code Analysis -> Launching. Make sure that both check boxes are unchecked. Close and reopen the project or restart eclipse and rebuild the project.</p> |
16,855,680 | Are there any drawbacks to using localStorage instead of Cookies? | <p>On my previous websites, I used to use a cookie to display a pre-home page only on the first visit. That worked great (<a href="http://newyork.arte.tv/" rel="noreferrer">see for example here</a>), but using cookies is not so trendy today, so I want to avoid it as much as possible.</p>
<p>Now, my new website projects almost always have pre-home launched via javascript (showing a modalbox), so I don't need to do any action on the server side. I'm considering to use HTML5 localStorage instead of cookies, with a fallback on cookies if the browser does not have localStorage. Is this a good idea? What is the impact in terms of usability, privacy protection and website performance?</p>
<p>Using localStorage will improve usability for users that have disabled cookies. But I know that some HTML5 features are only opt-in (like geolocalisation) in some browser. Is there any restriction like that for localStorage on any browser ? Is there any case where I will get a JS error if localStorage is available but deactivated for my site ?</p> | 16,855,902 | 5 | 0 | null | 2013-05-31 10:57:31.893 UTC | 14 | 2022-08-30 00:04:31.677 UTC | 2013-05-31 14:19:40.827 UTC | null | 1,472,001 | null | 1,472,001 | null | 1 | 59 | javascript|html|cookies|local-storage | 36,684 | <h2>Usability</h2>
<p>The user will not know if you are using localStorage or a cookie. If a user disable cookies, localStorage will not work either.</p>
<h2>Performance</h2>
<p>There is no noticeable speed difference between the two methods.</p>
<h2>sessionStorage</h2>
<p>sessionStorage is only for that browser tab's session. If you close the tab, the session will be lost and the data will be lost too, it's similar to a session variable on any backend language.</p>
<h2>localStorage</h2>
<p>localStorage will be available for any tab or window in the browser, and will exist until it is deleted by the user or the program. Unlike a cookie, you cannot setup expiration. localStorage has a much larger storage limit as well.</p>
<h2>Your Questions</h2>
<ol>
<li>You are not using this data server side, so you don't need a cookie. localStorage is never sent to the server unlike a cookie.</li>
<li>If the user disables the cookies, localStorage will not work either.</li>
</ol>
<h2>Fallback Example</h2>
<p>You can use a Modernizr to verify if localStorage is available and if not, use store a cookie instead.</p>
<pre><code>if (Modernizr.localstorage) {
// supports HTML5 Storage :D
} else {
// does not support HTML5 Storage :(
}
</code></pre>
<p>You can also forego Modernizr and use the check <code>typeof Storage !== 'undefined'</code>.</p> |
16,789,776 | iterating over two values of a list at a time in python | <p>I have a set like (669256.02, 6117662.09, 669258.61, 6117664.39, 669258.05, 6117665.08) which I need to iterate over, like</p>
<pre><code> for x,y in (669256.02, 6117662.09, 669258.61, 6117664.39, 669258.05, 6117665.08)
print (x,y)
</code></pre>
<p>which would print</p>
<pre><code> 669256.02 6117662.09
669258.61 6117664.39
669258.05 6117665.08
</code></pre>
<p>im on Python 3.3 btw</p> | 16,789,817 | 3 | 3 | null | 2013-05-28 10:30:17.837 UTC | 14 | 2019-10-30 00:17:20.73 UTC | 2016-02-16 23:26:10.78 UTC | null | 1,454,176 | null | 2,237,804 | null | 1 | 68 | python|list | 59,170 | <p>You can use an iterator:</p>
<pre><code>>>> lis = (669256.02, 6117662.09, 669258.61, 6117664.39, 669258.05, 6117665.08)
>>> it = iter(lis)
>>> for x in it:
... print (x, next(it))
...
669256.02 6117662.09
669258.61 6117664.39
669258.05 6117665.08
</code></pre> |
17,106,288 | matplotlib.pyplot will not forget previous plots - how can I flush/refresh? | <p>How do you get <code>matplotlib.pyplot</code> to "forget" previous plots</p>
<p>I am trying to plot multiple time using <code>matplotlib.pyplot</code></p>
<p>The code looks like this:</p>
<pre><code>def plottest():
import numpy as np
import matplotlib.pyplot as plt
a=np.random.rand(10,)
b=np.random.rand(10,)
c=np.random.rand(10,)
plt.plot(a,label='a')
plt.plot(b,label='b')
plt.plot(c,label='c')
plt.legend(loc='upper left')
plt.ylabel('mag')
plt.xlabel('element)')
plt.show()
e=np.random.rand(10,)
f=np.random.rand(10,)
g=np.random.rand(10,)
plt.plot(e,label='e')
plt.plot(f,label='f')
plt.plot(g,label='g')
plt.legend(loc='upper left')
plt.ylabel('mag')
plt.xlabel('element)')
plt.show()
</code></pre>
<p>Unfortunately I keep getting the same plot (actually from some other code which I ran and completed a while ago) no matter what I do.</p>
<p>Similar code has worked previously for me.</p>
<p>I have looked at these questions:</p>
<p><a href="https://stackoverflow.com/questions/10819363/how-to-clean-the-slate">How to "clean the slate"?</a></p>
<p><a href="https://stackoverflow.com/questions/5158447/matplotlib-pyplot-show-doesnt-work-once-closed?rq=1">Matplotlib pyplot show() doesn't work once closed</a></p>
<p><a href="https://stackoverflow.com/questions/6187603/python-matplotlib-pyplot-show-blocking-or-not">(python) matplotlib pyplot show() .. blocking or not?</a></p>
<p>and tried using <code>plt.show()</code>, <code>plt.clf()</code> and <code>plt.close</code> to no avail.</p>
<p>Any ideas?</p> | 17,107,568 | 2 | 0 | null | 2013-06-14 10:21:25.563 UTC | 25 | 2019-02-07 14:52:01.597 UTC | 2017-05-23 11:54:39.773 UTC | null | -1 | null | 1,461,850 | null | 1 | 103 | python|matplotlib | 134,772 | <p>I would rather use <code>plt.clf()</code> after every <code>plt.show()</code> to <strong>just clear the current figure</strong> instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.</p>
<p>Similarly, you could do <code>plt.cla()</code> <strong>to just clear the current <a href="https://matplotlib.org/api/axes_api.html" rel="noreferrer">axes</a></strong>.</p>
<p>To clear a specific <a href="https://matplotlib.org/api/axes_api.html" rel="noreferrer">axes</a>, useful when you have multiple axes within one figure, you could do for example:</p>
<pre><code>fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0, 1].clear()
</code></pre> |
20,870,895 | How to diagnose and fix git fatal: unable to read tree | <p>I'm using <code>git</code> to manage files on a project, and keep running into this problem.</p>
<p>When I run <code>git status</code> I get the message</p>
<pre><code>fatal: unable to read tree e2d920161d41631066945a3cbcd1b043de919570
</code></pre>
<p>As I understand it, I should check the output of <code>git fsck</code>, and I receive</p>
<pre><code>broken link from tree e09a42f248afff64336fbbec2523df97c26451ac
to tree e2d920161d41631066945a3cbcd1b043de919570
broken link from tree e09a42f248afff64336fbbec2523df97c26451ac
to tree 9b0dd389bd7f9e8d257395d57e0881b7957f9698
broken link from tree e09a42f248afff64336fbbec2523df97c26451ac
to tree 9e288a4ad60d63f342dfd18237980674426aa725
broken link from tree e09a42f248afff64336fbbec2523df97c26451ac
to tree 2a04647337089f554fab8c49cfd37149e5f4fc9f
broken link from tree e09a42f248afff64336fbbec2523df97c26451ac
to tree ea16658b45ce961adc3c3f519b0e8d9672918ca8
</code></pre>
<p>together with a lot of <code>missing blob</code> messages.</p>
<p>Following various resources (e.g <a href="https://stackoverflow.com/questions/16955523/git-broken-links-missing-dangling-trees">Git - Broken Links, Missing & Dangling Trees</a>) I have simply re-cloned the project from <code>github</code> and started again. </p>
<p>Once I have re-cloned the project, all is good for a few <code>commit</code>s, and then the problem arises again. Re-cloning every time doesn't seem to be optimal, and seems to go against the idea of using <code>git</code>, and I'd like to try and understand what is going on. How can I diagnose and fix this problem?</p> | 20,918,469 | 6 | 9 | null | 2014-01-01 16:54:48.52 UTC | 14 | 2022-02-24 08:55:42.35 UTC | 2017-05-23 12:10:35.467 UTC | null | -1 | null | 1,091,649 | null | 1 | 70 | git | 109,816 | <p>Following my <a href="https://stackoverflow.com/a/1507935/6309">older recommendation</a>, it boils down to being able to find a repo which actually contains the missing elements (here full trees).<br>
This is what is shown in "<a href="https://stackoverflow.com/a/18687206/6309">How to fix corrupted git repository?</a>".</p>
<p>But if a full clone doesn't solve the problem, then it may be:</p>
<ul>
<li>a corruption of the repo on the GitHub side (contact GitHub support to check).</li>
<li>some kind of corruption on the client side (your Ubuntu). Make sure to check if the issue persists with the <a href="https://launchpad.net/~git-core/+archive/ppa" rel="noreferrer">latest Git release</a> (1.8.5.2-1) from a <a href="https://launchpad.net/+help-soyuz/ppa-sources-list.html" rel="noreferrer">custom PPA (Personal Package Archive)</a>.</li>
</ul>
<hr>
<p>Update July 2016, with Git 2.10 soon to be release, you now have:</p>
<pre><code>git fsck --name-objects
</code></pre>
<p>See "<a href="https://stackoverflow.com/a/38598015/6309">How to fix git error broken link from tree to tree?</a>" for more.</p> |
4,380,159 | Writing a Windows NT subsystem | <p>I'd like to try writing my own minimal NT subsystem on Windows 7 for purely educational purposes -- something like a bare-bones equivalent of the posix.exe in Microsoft's Subsystem for Unix-based Applications.</p>
<p>But I can't seem to find any public documentation on this topic. What API does a subsystem need to implement? How does it get registered with Windows? How does the subsystem image need to be built (what flags need to be set in the PE header, etc.)?</p>
<p>I'd most like to find a book or web site with an overview of the entire subject, or even the source code for a "hello world" NT subsystem that someone else has written. But anything at all would be appreciated if you can point me in the right direction here...</p> | 4,653,425 | 2 | 22 | null | 2010-12-07 18:23:22.767 UTC | 18 | 2012-05-18 21:59:13.783 UTC | 2012-05-18 21:59:13.783 UTC | null | 21,234 | null | 40,511 | null | 1 | 51 | windows|subsystem|windows-nt | 4,306 | <p>Here are the major components of a subsystem:</p>
<ul>
<li>User-mode server. The server creates a (A)LPC port and listens for and handles client requests.</li>
<li>User-mode client DLL. In the DLL_INIT_ROUTINE, you can connect to the port set up by the server. This DLL will expose your subsystem's API, and some functions will require communication with the server.</li>
<li>Kernel-mode support driver (you might not need this).</li>
</ul>
<p>You will want to store process or thread state in either your server or driver. If you're storing it in the server, you might need something like <code>NtRegisterThreadTerminatePort</code> to ensure you get to clean up when a process or thread exits. If you're using a driver, you need <a href="http://msdn.microsoft.com/en-us/library/ff559951.aspx" rel="noreferrer">PsSetCreateProcessNotifyRoutine</a>.</p>
<p>And lastly, if you're on XP and below, you can add new system calls. You can do this by calling <code>KeAddSystemServiceTable</code>. To invoke the system calls from user-mode, you need to create stubs like this (for x86):</p>
<pre><code>; XyzCreateFooBar(__out PHANDLE FooBarHandle, __in ACCESS_MASK DesiredAccess, ...)
mov eax, SYSTEM_CALL_NUMBER
mov edx, 0x7ffe0300
call [edx]
retn 4
</code></pre>
<p>On Vista and above you can no longer add new system service tables because there is only room for two: the kernel's system calls and win32k's system calls.</p>
<p>After a bit of Googling I found this: <a href="http://winntposix.sourceforge.net/" rel="noreferrer">http://winntposix.sourceforge.net/</a>. I think it's very similar to what you're looking for, and uses a lot of the things I have mentioned.</p> |
4,316,710 | String.replaceAll without RegEx | <p>I'd like to replace all instances of a substring in a string but <code>String.replaceAll()</code> only accepts a pattern. The string that I have came from a previous match. Is it possible to add escapes to the pattern that I have or is there a version of <code>replaceAll()</code> in another class which accepts a literal string instead of a pattern?</p> | 4,316,725 | 2 | 1 | null | 2010-11-30 17:42:49.377 UTC | 14 | 2021-04-22 17:01:02.49 UTC | 2012-11-26 14:46:13.373 UTC | null | 1,419,007 | null | 271,599 | null | 1 | 132 | java | 73,703 | <p>Just use <a href="http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29" rel="noreferrer"><code>String.replace(CharSequence,CharSequence)</code></a> rather than <code>replaceAll</code>.</p>
<p>NB: <code>replace</code> doesn't just replace the first occurrence, it replaces <strong>all</strong> occurrences, like <code>replaceAll</code>.</p> |
9,986,795 | CSS Selector for a TD in a Table with an ID | <p>I have an html table with an ID of <code>thetable</code>. It has (according to FireBug), an unnamed TBODY tag, and an unnamed TR tag. The three TD tags inside that I want to access are unnamed. Is there any CSS selector that I can use to reference these unnamed tr tags?</p>
<p>I've tried: </p>
<p><code>table#thetable:nth-child(1)</code></p>
<p>But this does not select for those tags.</p>
<p>I'm using <a href="http://www.jsoup.org" rel="noreferrer">jsoup.org</a> to pull this data into strings. I'd like to take the text of each TD in the table (of which I know the name) and put all that into an array. </p>
<p>Something like this:</p>
<pre><code>// Pseudocode for all the TDs into an array
Elements strings = doc.select("table#thetable: children");
</code></pre> | 9,986,975 | 3 | 1 | null | 2012-04-03 03:42:33.917 UTC | null | 2015-07-13 22:45:52.533 UTC | 2015-07-13 22:45:52.533 UTC | null | 445,131 | null | 1,103,669 | null | 1 | 9 | java|html|css|css-selectors|jsoup | 40,453 | <p>If you're simply looking to get all your <code>td</code> elements, this should be enough:</p>
<pre><code>Elements elems = doc.select("table#thetable td");
</code></pre>
<p>Then iterate <code>elems</code>, retrieve the text from your <code>td</code>s and put them in your array.</p>
<p>Also, you should probably use an array list instead of an array if you don't know or can't control how many cells your table will have:</p>
<pre><code>Elements elems = doc.select("table#thetable td");
List<String> strings = new ArrayList<String>();
for (Element e : elems) {
strings.add(e.text());
}
</code></pre> |
10,135,074 | Download file from HTTPS server using Java | <p>I want to download a file from the server which is using the secured connection protocol HTTPS. I could do it in the normal server, But, how I can do it using the HTTPS. If anyone have used the sample API, please help me to find the useful resources.</p> | 10,135,259 | 4 | 1 | null | 2012-04-13 04:03:40.477 UTC | 8 | 2017-12-11 20:34:08.33 UTC | null | null | null | null | 421,753 | null | 1 | 13 | java|network-programming | 64,298 | <p>Access an HTTPS url with Java is the same then access an HTTP url. You can always use the</p>
<pre><code>URL url = new URL("https://hostname:port/file.txt");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
// .. then download the file
</code></pre>
<p>But, you can have some problem when the server's certificate chain cannot be validated.
So you may need to disable the validation of certificates for testing purposes and trust all certificates.</p>
<p>To do that write:</p>
<pre><code>// Create a new trust manager that trust all certificates
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Activate the new trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
// And as before now you can use URL and URLConnection
URL url = new URL("https://hostname:port/file.txt");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
// .. then download the file
</code></pre> |
9,892,356 | create interactive elevated process from windows service and show to logged-on user | <p>I have a service that spawns a WPF application process when a user logs on. </p>
<p><em>But for some reason the WPF application gets killed about 10 minutes after it has been created? The termination is immediate with no traces found in the Event Log nor are any normal close/exit events called in the WPF application.</em></p>
<p>In fact, when the termination occurs, Windows 7 seems to hang for a second, the mouse becoming unresponsive and then acting out the mouse gestures after a short delay (when it normalizes, but now lacking the created process).</p>
<h3>The When</h3>
<pre><code>public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
CanHandleSessionChangeEvent = true;
}
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
if (changeDescription.Reason == SessionChangeReason.SessionLogon
&& changeDescription.SessionId > 0)
{
ApplicationLoader.PROCESS_INFORMATION procInfo;
ApplicationLoader.StartProcessAndBypassUAC(@"myapp.exe", out procInfo);
}
base.OnSessionChange(changeDescription);
}
}
</code></pre>
<h3>Process Creation <a href="http://www.codeproject.com/Articles/35773/Subverting-Vista-UAC-in-Both-32-and-64-bit-Archite" rel="noreferrer">As Per Pero Matic Code</a></h3>
<pre><code>// ...
bool result = CreateProcessAsUser(hUserTokenDup, // client's access token
null, // file to execute
applicationName, // command line
ref sa, // pointer to process SECURITY_ATTRIBUTES
ref sa, // pointer to thread SECURITY_ATTRIBUTES
false, // handles are not inheritable
dwCreationFlags, // creation flags
IntPtr.Zero, // pointer to new environment block
null, // name of current directory
ref si, // pointer to STARTUPINFO structure
out procInfo // receives information about new process
);
</code></pre>
<ul>
<li>the termination does not seem to happen if i target notepad.exe, however?</li>
<li>tested it with a vanilla\empty WPF application (.NET 4), and that crashed as well</li>
</ul>
<h3>Process Creation with Administrative Privileges and No Prompt</h3>
<ul>
<li>It seems that the issue is trying to duplicate the administrative <code>SYSTEM</code> token from <code>winlogon.exe</code> (but which is running in session 1+), because if you duplicate <em>the specific user</em> token instead (e.g. from <code>explorer.exe</code>) then the crashes are no more! </li>
<li>this is confirmed with the same vanilla/empty WPF application, and with running <a href="http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/990e7c4a-afa7-47aa-b9a6-d5b6beb19f41/" rel="noreferrer">Marcel Roma code here</a> - note that he uses <code>explorer.exe</code> instead of <code>winlogon.exe</code></li>
<li><p>although using <code>explorer.exe</code> gets rid of the termination I lose the administrative privileges with that, which does not work for me</p></li>
<li><p>any ideas how to get it to work with the <code>winlogon</code> process token?</p></li>
<li>or is it possible to adjust the <code>exlorer.exe</code> token to make the duplicate elevated? im guessing somehow using <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa379626%28v=vs.85%29.aspx" rel="noreferrer">TokenElevation</a> and <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa379591%28v=vs.85%29.aspx" rel="noreferrer">SetTokenInformation</a> or <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa375202%28v=vs.85%29.aspx" rel="noreferrer">AdjustTokenPrivileges</a></li>
<li>or could it be that <code>Windows 7</code> has been patched to disallow such process impersonation?</li>
<li>alternatively, is there any way to get <em>the specific user</em> token with administrative privileges (rather than the owner being <code>SYSTEM</code>), but again, without password knowledge/prompts (excluding <code>CreateProcessWithLogonW</code>)</li>
<li>is this maybe to do with garbage collection somehow?</li>
</ul> | 10,045,943 | 2 | 6 | null | 2012-03-27 15:12:20.003 UTC | 8 | 2012-04-06 15:57:36.79 UTC | 2012-03-27 20:45:43.013 UTC | null | 742,084 | null | 742,084 | null | 1 | 13 | c#|.net|process|windows-services|impersonation | 6,752 | <p>Well I'm just suggesting you a work around:
Why you don't put your core functionalities in a windows service, and then use the wpf app as a frontend ? So that if the user kill it, it doesn't stop the service. Then the service can regularly check that the wpf front end is started, and if needed restart it.</p>
<p>I think it'll be a more "trusted" design that the one you're trying to do, which could let the antivirus think you're a bad software and block you.</p>
<p>And to protect the windows service there is another question here: <a href="https://stackoverflow.com/questions/4266776/protecting-a-windows-service-from-untrusted-users">Protecting a Windows Service from untrusted users</a></p> |
9,803,947 | Create object from string | <p>Is it possible to create a new object using a string?
For example, how can I convert the string "product" to <code>var p = new Product</code>?</p>
<p>Thanks in advance.</p>
<p><strong>EDIT</strong></p>
<p>What I want to do is to have a menu with <code><a href="#home"></a><a href="#products">products</a></code> and create the corresponding object from the href each time. </p> | 9,804,142 | 3 | 4 | null | 2012-03-21 11:42:27.97 UTC | 8 | 2015-09-25 03:02:26.157 UTC | 2015-09-25 03:02:26.157 UTC | null | 2,227,834 | null | 69,654 | null | 1 | 24 | javascript | 66,102 | <p>If you know the context, yes. Let's say you're in a browser environment and <code>Person</code> is a global constructor. Because any global variable is a property of the global object, it means you can access to <code>Person</code> through the global object <code>window</code>:</p>
<pre><code>var p = new Person()
</code></pre>
<p>Is equivalent to:</p>
<pre><code>var p = new window.Person()
</code></pre>
<p>So you can use the square bracket notation:</p>
<pre><code>var p = new window["Person"]();
</code></pre>
<p>Of course this is valid for every kind of object. If you don't want pollute the global scope, you can have:</p>
<pre><code>var mynamespace = {};
mynamespace.Person = function Person() {..}
var p = new mynamespace["Person"]();
</code></pre> |
9,703,810 | How to disable migration in Entity Framework 4.3.1? | <p>Is there any way to disable migration in Entity Framework 4.3.1? I removed the migrations folder from the project and the generated tables in my database, but it doesn't work! How can you remove the migration?</p> | 9,709,407 | 3 | 5 | null | 2012-03-14 14:23:24.393 UTC | 7 | 2018-04-16 11:31:41.49 UTC | 2013-01-07 02:05:03.113 UTC | null | 90,674 | null | 645,167 | null | 1 | 39 | code-first|entity-framework-migrations|entity-framework-4.3 | 59,425 | <p>If you don't want to use migrations but in the same time you want EF to create database for you, you just need to set correct database initializer:</p>
<pre><code>Database.SetInitializer<YourContextType>(new CreateDatabaseIfNotExists<YourContentType>());
</code></pre> |
9,945,620 | Making a table row into a link in Rails | <p>I am trying to make a row in a table link to the edit page. I know the links are being created, because I can print them out. I am close, but am missing something important. What do I change to make the link work properly?</p>
<pre><code><h1>Scouts</h1>
<p><%= button_to "Add a new Scout", new_scout_path, :method => :get %></p>
<div class="message-board">
<table>
<tr>
<th>Name</th>
<th>Rank</th>
<th>Advancement Date</th>
<th>Age</th>
</tr>
<% @scouts.each do |scout| %>
<tr <% link_to edit_scout_path(scout) %> >
<td><%= scout.name %></td>
<td><%= scout.rank %></td>
<td><%= scout.advancement %></td>
<td><%= scout.age %></td>
</tr>
<% end %>
</table>
</div>
</code></pre> | 9,945,761 | 4 | 1 | null | 2012-03-30 15:07:14.993 UTC | 13 | 2020-11-02 05:40:15.763 UTC | null | null | null | null | 968,801 | null | 1 | 40 | ruby-on-rails | 24,997 | <p>As Robin said, that's invalid HTML. You probably shouldn't do that.</p>
<p>I personally would put an <code>onclick</code> event on the <code>tr</code> using jQuery. The <code>tr</code> element would look like this:</p>
<pre><code><tr data-link="<%= edit_scout_path(scout) %>">
...
</tr>
</code></pre>
<p>And then the associated JavaScript (placed in a file such as <code>app/assets/javascripts/scouts.js</code>) would be something like this:</p>
<pre><code>$("tr[data-link]").click(function() {
window.location = $(this).data("link")
})
</code></pre>
<p>This would make all <code>tr</code> elements that have a <code>data-link</code> attribute act as if they were URLs in the most unobtrusive way I can think possible.</p> |
10,002,439 | Make index.html default, but allow index.php to be visited if typed in | <p>I have the following line in my .htaccess file:</p>
<pre><code>DirectoryIndex index.html index.php
</code></pre>
<p>Everytime I go to index.php it takes me to index.html. Is it possible to allow for both, but leave index.html the default for users visiting www.domain.com?</p> | 10,082,736 | 6 | 6 | null | 2012-04-03 22:35:13.61 UTC | 15 | 2019-03-13 23:17:13.677 UTC | null | null | null | null | 718,341 | null | 1 | 60 | html|.htaccess | 172,243 | <p>By default, the DirectoryIndex is set to:</p>
<pre><code>DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml
</code></pre>
<p>Apache will look for each of the above files, in order, and serve the first one it finds when a visitor requests just a directory. If the webserver finds no files in the current directory that match names in the DirectoryIndex directive, then a directory listing will be displayed to the browser, showing all files in the current directory.</p>
<p>The order should be <code>DirectoryIndex index.html index.php</code> // default is index.html</p>
<p><strong>Reference:</strong> <a href="http://support.modwest.com/content/1/147/en/how-can-i-show-a-default-page-other-than-indexhtml.html" rel="noreferrer">Here</a>.</p> |
9,711,529 | Save Subset of MongoDB Collection to Another Collection | <p>I have a set like so</p>
<pre><code>{date: 20120101}
{date: 20120103}
{date: 20120104}
{date: 20120005}
{date: 20120105}
</code></pre>
<p>How do I save a subset of those documents with the date '20120105' to another collection?</p>
<p><strong>i.e</strong> <code>db.subset.save(db.full_set.find({date: "20120105"}));</code></p> | 9,712,776 | 7 | 0 | null | 2012-03-14 22:52:40.58 UTC | 22 | 2022-06-14 12:25:36.867 UTC | null | null | null | null | 719,919 | null | 1 | 68 | mongodb | 68,699 | <p>Here's the shell version:</p>
<pre><code>db.full_set.find({date:"20120105"}).forEach(function(doc){
db.subset.insert(doc);
});
</code></pre>
<p>Note: As of MongoDB 2.6, the aggregation framework makes it possible to do this faster; see <a href="https://stackoverflow.com/a/25247084/1448678">melan's answer</a> for details.</p> |
7,997,440 | How to create a sidebar similar to the facebook app for iOS? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/7989020/whats-the-best-way-to-develop-a-sideswipe-menu-like-the-one-in-facebooks-new-i">What's the best way to develop a sideswipe menu like the one in Facebook's new iOS app?</a> </p>
</blockquote>
<p>How can i create a sidebar similar to the facebook app for iOS (iPhone/iPad)? That sidebar that appears when you slide your finger horizontally. There is a component for this or is it just a UIView?</p> | 7,997,964 | 3 | 0 | null | 2011-11-03 15:24:06.23 UTC | 16 | 2012-11-27 01:59:44.757 UTC | 2017-05-23 12:14:06.96 UTC | null | -1 | null | 1,028,009 | null | 1 | 10 | iphone|objective-c|ios|ipad | 28,004 | <p>You're in luck! Somebody just created a complete sample app showing how to create that, and includes a video of the effect. Here it is: </p>
<p><a href="https://github.com/BenHall/ios_facebook_style_navigation">https://github.com/BenHall/ios_facebook_style_navigation</a></p> |
11,788,242 | What is the default color of a ListView divider line? | <p>Currently I am using this code to see the divider lines:</p>
<pre><code>medalsList.setDivider(new ColorDrawable(0x99F10529));
medalsList.setDividerHeight(1);
</code></pre>
<p>What is the default RGB color (as shown in the code above) used on a ListView that hasn't had its divider lines changed?</p> | 11,788,321 | 2 | 0 | null | 2012-08-03 01:58:05.067 UTC | 10 | 2015-11-08 18:02:24.853 UTC | 2015-04-18 01:51:27.073 UTC | null | 1,427,098 | null | 546,509 | null | 1 | 31 | android|android-listview | 19,746 | <p>The default divider is determined by the <code>listDivider</code> item in the current theme. For the stock themes, the default divider is one of:</p>
<ul>
<li>android:drawable/divider_horizontal_dark (Theme)</li>
<li>android:drawable/divider_horizontal_bright (Theme.Light)</li>
<li>android:drawable/divider_horizontal_holo_dark (Theme.Holo)</li>
<li>android:drawable/divider_horizontal_holo_light (Theme.Holo.Light)</li>
</ul>
<p>Those drawables can be found in the platforms data folder of your sdk installation.</p> |
11,519,777 | How do I secure Socket.IO? | <p>I've been working with Socket.IO for a few days and it's been both extremely exciting and even more frustrating. The lack of current documentation/tutorials has made learning it very difficult. I finally managed to create a basic chat system, but there is one glaring question. How do I secure it?</p>
<p>What's stopping a malicious user from copying (or editing) my code and connecting to my server? I can grab the username from my PHP script and submit it to Socket.IO so I can recognize them as that user (and the PHP has security of course), but what's stopping someone from just submitting an unregistered username?</p>
<p>How can I make sure that the events submitted are authentic and haven't been tampered with?</p>
<p>My basic socket.io chat for references.</p>
<p>Server:</p>
<pre><code>var io = require('socket.io').listen(8080);
var connectCounter = 0;
io.sockets.on('connection', function (socket) {
connectCounter++;
console.log('People online: ', connectCounter);
socket.on('set username', function(username) {
socket.set('username', username, function() {
console.log('Connect', username);
});
});
socket.on('emit_msg', function (msg) {
// Get the variable 'username'
socket.get('username', function (err, username) {
console.log('Chat message by', username);
io.sockets.volatile.emit( 'broadcast_msg' , username + ': ' + msg );
});
});
socket.on('disconnect', function() { connectCounter--; });
});
</code></pre>
<p>Client:</p>
<pre><code> <?php session_start() ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>untitled</title>
</head>
<body>
<input id='message' type='text'>
<div id="content"></div>
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
$.ajax({
type: 'GET',
url: 'https://mysite.com/execs/login.php?login_check=true',
dataType: 'json',
success: function(data) {
var username = data.username;
socket.emit('set username', username, function (data){
});
}
});
socket.on('broadcast_msg', function (data) {
console.log('Get broadcasted msg:', data);
var msg = '<li>' + data + '</li>';
$('#content').append(msg);
});
$('#message').keydown(function(e) {
if(e.keyCode == 13) {
e.stopPropagation();
var txt = $(this).val();
$(this).val('');
socket.emit('emit_msg', txt, function (data){
console.log('Emit Broadcast msg', data);
});
}
});
</script>
</body>
</html>
</code></pre>
<p>It all works dandy, except for having absolutely no security.</p> | 11,600,116 | 2 | 3 | null | 2012-07-17 09:35:43.583 UTC | 2 | 2014-02-05 22:37:21.303 UTC | 2014-02-05 22:37:21.303 UTC | null | 278,976 | null | 938,745 | null | 1 | 32 | javascript|security|node.js|socket.io | 41,797 | <p>If you can install a key-value store like <a href="http://redis.io/" rel="nofollow noreferrer">Redis</a> on your node server, you can access it remotely from your php server using a Redis client like <a href="https://github.com/nrk/predis/" rel="nofollow noreferrer">Predis</a>. All you have to do is updating the remote session store on node server when a new login/logout happens in your php server.</p>
<p>Check this post for details: <a href="https://stackoverflow.com/questions/6502031/authenticate-user-for-socket-io-nodejs">Authenticate user for socket.io/nodejs</a></p> |
11,873,741 | sampling random floats on a range in numpy | <p>How can I sample random floats on an interval [a, b] in numpy? Not just integers, but any real numbers. For example,</p>
<p><code>random_float(5, 10)</code> </p>
<p>would return random numbers between <code>[5, 10]</code>. thanks.</p> | 11,873,796 | 3 | 0 | null | 2012-08-08 21:52:06.5 UTC | 6 | 2022-03-16 17:55:35.6 UTC | null | null | null | user248237 | null | null | 1 | 48 | python|numpy|scipy | 69,742 | <p>The <a href="https://numpy.org/doc/stable/reference/random/generated/numpy.random.uniform.html" rel="noreferrer">uniform distribution</a> would probably do what you are asking.</p>
<pre><code>np.random.uniform(5,10) # A single value
np.random.uniform(5,10,[2,3]) # A 2x3 array
</code></pre> |
20,251,762 | Sorting an int array from highest to lowest | <p>So I just learned about the <code>Arrays.sort(arrayName);</code> and applied it in a project of mine but I found it sorts from lowest to highest. Is there anyway to have it do the opposite? (I don't think I need to post the code in question but if it is needed I'll post it).</p> | 20,251,835 | 4 | 5 | null | 2013-11-27 19:49:42.353 UTC | 2 | 2016-08-02 16:32:46.227 UTC | 2013-11-27 19:57:26.393 UTC | null | 1,065,197 | null | 2,926,017 | null | 1 | 4 | java|arrays|sorting | 48,990 | <p>If you use an <code>Integer[]</code> instead of <code>int[]</code>, then you can pass a <code>Comparator</code> as 2nd argument to the sort method. To impose reverse ordering, you can make use of <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#reverseOrder%28%29"><code>Collections.reverseOrder()</code></a> method:</p>
<pre><code>Arrays.sort(arr, Collections.reverseOrder());
</code></pre> |
3,292,643 | Python - convert list of tuples to string | <p>Which is the most pythonic way to convert a list of tuples to string?</p>
<p>I have:</p>
<pre><code>[(1,2), (3,4)]
</code></pre>
<p>and I want:</p>
<pre><code>"(1,2), (3,4)"
</code></pre>
<p>My solution to this has been:</p>
<pre><code>l=[(1,2),(3,4)]
s=""
for t in l:
s += "(%s,%s)," % t
s = s[:-1]
</code></pre>
<p>Is there a more pythonic way to do this?</p> | 3,292,703 | 7 | 8 | null | 2010-07-20 17:28:05.88 UTC | 7 | 2018-06-06 18:29:08.157 UTC | 2010-07-20 17:31:48.85 UTC | null | 12,855 | null | 170,912 | null | 1 | 27 | python|list|string-formatting|tuples | 61,949 | <p>you might want to use something such simple as:</p>
<pre><code>>>> l = [(1,2), (3,4)]
>>> str(l).strip('[]')
'(1, 2), (3, 4)'
</code></pre>
<p>.. which is handy, but not guaranteed to work correctly</p> |
3,590,677 | How to do union, intersect, difference and reverse data in java | <p>I want to implement the union, intersect, difference and reverse operations in Java.</p>
<p>First I have 2 instances of <code>ArrayList<Integer></code></p>
<pre><code>a = [0,2,4,5,6,8,10]
b = [5,6,7,8,9,10]
</code></pre>
<p>a union b should return <code>c = [0,2,4,5,6,7,8,9,10]</code></p>
<p>a intersect b should return <code>c = [5,8,10]</code></p>
<p>a difference b should return <code>c = [0,2,4]</code></p>
<p>reverse <code>a = [10,8,6,5,4,2,0]</code></p>
<p>Something like this.</p>
<p>How to implement that method in Java?</p>
<hr>
<p><strong>Update</strong>: I have to start with this template:</p>
<pre><code>package IntSet;
import java.util.ArrayList;
import java.util.Collection;
public class IntSet {
private ArrayList<Integer> intset;
public IntSet(){
intset = new ArrayList<Integer>();
}
public void insert(int x){
intset.add(x);
}
public void remove(int x){
//implement here
intset.indexOf(x);
}
public boolean member(int x){
//implement here
return true;
}
public IntSet intersect(IntSet a){
//implement here
return a;
}
public IntSet union(IntSet a){
//implement here
return a;
}
public IntSet difference(IntSet a){
//implement here
IntSet b = new IntSet();
return b;
}
</code></pre> | 3,590,725 | 7 | 2 | null | 2010-08-28 12:05:21.723 UTC | 25 | 2020-11-27 23:24:05.067 UTC | 2020-04-03 07:19:51.53 UTC | null | 4,742,570 | null | 286,090 | null | 1 | 54 | java | 98,279 | <pre><code>//Union
List<Integer> c = new ArrayList<Integer>(a.size() + b.size());
addNoDups(c,a);
addNoDups(c,b);
private void addNoDups(List<Integer> toAddTo,List<Integer> iterateOver) {
for(Integer num:iterateOver){
if(toAddTo.indexOf(num) == -1) {
toAddTo.add(num);
}
}
}
//intersection
List<Integer> c = new ArrayList<Integer> (a.size() > b.size() ?a.size():b.size());
c.addAll(a);
c.retainAll(b);
//difference a-b
List<Integer> c = new ArrayList<Integer> (a.size());
c.addAll(a);
c.removeAll(b);
</code></pre> |
3,814,234 | How can I subscribe multiple buttons to the same event handler and act according to what button was clicked? | <p>I have 6 buttons that I want to be attached to the same handler. How can I do this?</p> | 3,814,254 | 9 | 3 | null | 2010-09-28 15:13:54.483 UTC | 7 | 2021-02-07 03:51:40.457 UTC | null | null | null | delete | null | null | 1 | 29 | c#|event-handling | 65,406 | <p>When you subscribe to the event on a button, it's just a standard event handler:</p>
<pre><code>button1.Click += myEventHandler;
</code></pre>
<p>You can use the same code to add handlers for every button:</p>
<pre><code>button1.Click += myEventHandler;
button2.Click += myEventHandler;
button3.Click += myEventHandler;
button4.Click += myEventHandler;
button5.Click += myEventHandler;
button6.Click += myEventHandler;
</code></pre>
<p>This will cause your handler in <code>myEventHandler</code> to be run when any of the buttons are clicked.</p> |
3,668,953 | Raise event thread safely - best practice | <p>In order to raise an event we use a method OnEventName like this:</p>
<pre><code>protected virtual void OnSomethingHappened(EventArgs e)
{
EventHandler handler = SomethingHappened;
if (handler != null)
{
handler(this, e);
}
}
</code></pre>
<p>But what is the difference with this one ?</p>
<pre><code>protected virtual void OnSomethingHappened(EventArgs e)
{
if (SomethingHappened!= null)
{
SomethingHappened(this, e);
}
}
</code></pre>
<p>Apparently the first is thread-safe, but why and how ?</p>
<p>It's not necessary to start a new thread ?</p> | 3,669,020 | 10 | 0 | null | 2010-09-08 14:48:53.847 UTC | 18 | 2021-09-01 07:08:17.34 UTC | 2010-09-09 08:23:16.557 UTC | null | 424,072 | null | 424,072 | null | 1 | 48 | c#|event-handling | 38,783 | <p>There is a tiny chance that <code>SomethingHappened</code> becomes <code>null</code> after the null check but before the invocation. However, <code>MulticastDelagate</code>s are immutable, so if you first assign a variable, null check against the variable and invoke through it, you are safe from that scenario (self plug: I wrote a <a href="http://fmork.net/software/writing/2010/Extension-method-for-safe-event-invocations.htm" rel="noreferrer">blog post about this</a> a while ago).</p>
<p>There is a back side of the coin though; if you use the temp variable approach, your code is protected against <code>NullReferenceException</code>s, but it could be that the event will invoke event listeners <em>after they have been detached from the event</em>. That is just something to deal with in the most graceful way possible.</p>
<p>In order to get around this I have an extension method that I sometimes use:</p>
<pre><code>public static class EventHandlerExtensions
{
public static void SafeInvoke<T>(this EventHandler<T> evt, object sender, T e) where T : EventArgs
{
if (evt != null)
{
evt(sender, e);
}
}
}
</code></pre>
<p>Using that method, you can invoke the events like this:</p>
<pre><code>protected void OnSomeEvent(EventArgs e)
{
SomeEvent.SafeInvoke(this, e);
}
</code></pre> |
4,408,858 | Quartz retry when failure | <p>Let's say I have a trigger configured this way:</p>
<pre><code><bean id="updateInsBBTrigger"
class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="updateInsBBJobDetail"/>
<!-- run every morning at 5 AM -->
<property name="cronExpression" value="0 0 5 * * ?"/>
</bean>
</code></pre>
<p>The trigger have to connect with another application and if there is any problem (like a connection failure) it should to retry the task up to five times every 10 minutes or until success. There is any way to configure the trigger to work like this?</p> | 4,409,263 | 3 | 0 | null | 2010-12-10 12:35:02.843 UTC | 18 | 2020-04-02 07:34:36.163 UTC | 2013-09-17 13:31:29.79 UTC | null | 1,250,033 | null | 79,230 | null | 1 | 27 | java|quartz-scheduler | 43,498 | <p><strong>Source</strong>: <a href="http://fahdshariff.blogspot.com/2010/12/automatically-retry-failed-jobs-in.html" rel="noreferrer">Automatically Retry Failed Jobs in Quartz</a></p>
<p>If you want to have a job which keeps trying over and over again until it succeeds, all you have to do is throw a JobExecutionException with a flag to tell the scheduler to fire it again when it fails. The following code shows how:</p>
<pre><code>class MyJob implements Job {
public MyJob() {
}
public void execute(JobExecutionContext context) throws JobExecutionException {
try{
//connect to other application etc
}
catch(Exception e){
Thread.sleep(600000); //sleep for 10 mins
JobExecutionException e2 = new JobExecutionException(e);
//fire it again
e2.setRefireImmediately(true);
throw e2;
}
}
}
</code></pre>
<p>It gets a bit more complicated if you want to retry a certain number of times. You have to use a StatefulJob and hold a retryCounter in its JobDataMap, which you increment if the job fails. If the counter exceeds the maximum number of retries, then you can disable the job if you wish.</p>
<pre><code>class MyJob implements StatefulJob {
public MyJob() {
}
public void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
int count = dataMap.getIntValue("count");
// allow 5 retries
if(count >= 5){
JobExecutionException e = new JobExecutionException("Retries exceeded");
//make sure it doesn't run again
e.setUnscheduleAllTriggers(true);
throw e;
}
try{
//connect to other application etc
//reset counter back to 0
dataMap.putAsString("count", 0);
}
catch(Exception e){
count++;
dataMap.putAsString("count", count);
JobExecutionException e2 = new JobExecutionException(e);
Thread.sleep(600000); //sleep for 10 mins
//fire it again
e2.setRefireImmediately(true);
throw e2;
}
}
}
</code></pre> |
4,269,896 | Creating an instance of a nested class in XAML | <p>in a <strong>XAML</strong> file (a WPF UserControl), is there a way to reference an <strong>inner class</strong> "B" defined in another class "A" ?</p>
<pre><code>public class A
{
public class B
{
}
}
</code></pre>
<p>Something like :</p>
<pre><code><local:A.B ... />
</code></pre>
<p>This syntax does not work because "B" is interpreted as a property named "B" in class "A".</p>
<p>I've tried more exotic syntaxes like "::" or "+" but none seems to work.</p>
<p>I'm currently using <strong>Silverlight 4</strong> with <strong>VS2010</strong>.</p>
<p>Thanks in advance for your help.</p> | 4,270,348 | 3 | 6 | null | 2010-11-24 17:49:09.327 UTC | 10 | 2022-04-02 22:27:10.5 UTC | 2010-11-25 21:23:04.857 UTC | null | 145,757 | null | 145,757 | null | 1 | 39 | wpf|xaml|inner-classes|nested-class | 13,889 | <p>I was searching and searching, because if this is possible, I would like to know. Unfortunately, I found this on <a href="https://msdn.microsoft.com/en-us/library/ms753379(v=vs.100).aspx" rel="noreferrer">msdn</a>: </p>
<blockquote>
<p>Your custom class must not be a nested
class. Nested classes and the "dot"
in their general CLR usage syntax interfere with other WPF and/or XAML
features such as attached properties.</p>
</blockquote>
<p>So, it appears you can't reference a nested class with the dot operator. As for alternative ways of getting to that inner class through XAML, I haven't had any luck in my searches yet. :o( But this is a rather interesting issue, so I will continue searching. Maybe I'll find some luck! :o)</p> |
4,086,800 | Move constructor on derived object | <p>When you have a derived object with a move constructor, and the base object also has move semantics, what is the proper way to call the base object move constructor from the derived object move constructor?</p>
<p>I tried the most obvious thing first:</p>
<pre><code> Derived(Derived&& rval) : Base(rval)
{ }
</code></pre>
<p>However, this seems to end up calling the Base object's <em>copy constructor</em>. Then I tried explicitly using <code>std::move</code> here, like this:</p>
<pre><code> Derived(Derived&& rval) : Base(std::move(rval))
{ }
</code></pre>
<p>This worked, but I'm confused why it's necessary. I thought <code>std::move</code> merely returns an rvalue reference. But since in this example <code>rval</code> is already an rvalue reference, the call to <code>std::move</code> should be superfluous. But if I don't use <code>std::move</code> here, it just calls the copy constructor. So why is the call to <code>std::move</code> necessary?</p> | 4,086,826 | 3 | 0 | null | 2010-11-03 11:59:00.397 UTC | 8 | 2020-05-14 10:37:04.513 UTC | 2013-03-15 13:22:06.963 UTC | null | 313,113 | null | 469,408 | null | 1 | 59 | c++|c++11|move-semantics | 22,031 | <p><code>rval</code> is not a Rvalue. It is an Lvalue inside the body of the move constructor. That's why we have to explicitly invoke <code>std::move</code>.</p>
<p>Refer <a href="http://www.artima.com/cppsource/rvalue.html" rel="noreferrer">this</a>. The important note is</p>
<blockquote>
<p>Note above that the argument x is
treated as an lvalue internal to the
move functions, even though it is
declared as an rvalue reference
parameter. That's why it is necessary
to say move(x) instead of just x when
passing down to the base class. This
is a key safety feature of move
semantics designed to prevent
accidently moving twice from some
named variable. All moves occur only
from rvalues, or with an explicit cast
to rvalue such as using std::move. If
you have a name for the variable, it
is an lvalue.</p>
</blockquote> |
14,450,123 | C - Pointer to a matrix | <p>I am trying to pass a matrix to a function by reference. The function will replace every element <code>A[i][j]</code> of the matrix by <code>-A[i][j]</code>. I first create the matrix:</p>
<pre><code>float a[3][4] =
{
{1.0f, 0.0f, 0.0f, 0.0f},
{0.0f, 1.0f, 0.0f, 0.0f},
{1.0f, 1.0f, 0.0f, 0.0f},
};
</code></pre>
<p>Then, I obtain the pointer to this matrix:</p>
<pre><code>float*** pa = &a;
</code></pre>
<p>Then, I introduce the following function:</p>
<pre><code>void process(float ***matrix, int nRows, int nCols){
short i;
short j;
for (i=0 ; i<nRows; i++){
for (j=0 ; j<nCols ; j++){
(*matrix)[i][j] *= -1;
}
}
}
</code></pre>
<p>which I call as follows:</p>
<pre><code>process(pa,3,4);
</code></pre>
<p>My program fails to execute and returns:</p>
<pre><code>Segmentation fault: 11
</code></pre>
<p>Any ideas?</p>
<p><strong>Summary of the answers:</strong> Some notes based on the questions this question received:</p>
<p>I. The aforementioned function can be used, provided that <code>a</code> is initialized a bit differently so as to be a <code>float**</code>. In particular:</p>
<pre><code>int numberOfRows = 3;
int numberOfColumns = 4;
float **a = (float **) malloc(sizeof (float *) * numberOfRows);
for (i = 0; i < numberOfRows; ++i) {
a[i] = (float *) malloc(sizeof (float) * numberOfColumns);
}
</code></pre>
<p>and then, it is passed to the function <code>process</code> as <code>process(&a, 3,4);</code>.</p>
<p>II. Alternatively, one may use the function:</p>
<pre><code>void multi_by_minus(float *matrix, int nRows, int nCols) {
short i,j;
for (i = 0; i < nRows; i++) {
for (j = 0; j < nCols; j++) {
matrix[i * nCols + j] *= -1;
}
}
}
</code></pre>
<p>which treats the matrix as an one-dimensional array. In that case we simply invoke it as <code>multi_by_minus(&a, 3, 4);</code></p>
<p>III. Finally, we may use the method:</p>
<pre><code>void process2(int nRows, int nCols, float (*matrix)[nCols]) {
short i, j;
for (i = 0; i < nRows; i++) {
for (j = 0; j < nCols; j++) {
matrix[i][j] *= -1;
}
}
}
</code></pre>
<p>to which we provide a pointer to <code>a</code>, i.e., we invoke it like <code>process2(3,4,&a);</code>. In this way, we acquire access to the elements of the matrix in 2D.</p> | 14,450,180 | 4 | 2 | null | 2013-01-22 01:25:31.92 UTC | null | 2017-01-18 03:59:38.09 UTC | 2013-01-22 20:06:28.18 UTC | null | 613,016 | null | 613,016 | null | 1 | 3 | c|pointers|matrix | 44,297 | <p>There is no need for the triple pointer since you are already supplying the memory. You would use that if you were to allocate the memory inside de function.</p>
<p>You can't index a 2 dimension matrix without supplying at least the size of 1 dimension. The reason is that the compiler needs to generate code to access the correct offset taking into account both dimensions. In this particular case, I suggest passing a simple pointer and indexing as a 1D array, like this:</p>
<pre><code>void process(float *matrix, int nRows, int nCols){
short i;
short j;
for (i=0 ; i<nRows; i++){
for (j=0 ; j<nCols ; j++){
matrix[i * nCols + j] *= -1;
}
}
}
</code></pre>
<p>You can then call it like this:</p>
<pre><code>process((float*)a,3,4);
</code></pre>
<p>This way you manually index your buffer.</p> |
14,705,899 | android.permission.INTERNET? | <p>I'm using three buttons in my app
1) Feedback button: It allows the user to send feedback via any mail application
2) A share button which uses a share intent
3) A "rate app" button which opens my app's page on the play store</p>
<p>All the 3 buttons uses other applications to access the internet.</p>
<p>Do I need to add the android.permission.INTERNET permission in my manifest file?</p> | 14,706,014 | 2 | 2 | null | 2013-02-05 10:59:12.09 UTC | 2 | 2015-11-17 05:35:16.223 UTC | null | null | null | null | 1,951,690 | null | 1 | 7 | android | 39,725 | <p>The answer in this case is that no, the permissions are not required in this instance, as Dipendra has pointed out in his answer, as the application is sending it's requests as Intents via external applications and aren't direct requests to the network from within his application.</p>
<p><strong>A little background:</strong></p>
<p>The easiest way you can know whether you need the permission is to use your application on a test device. Does it work as you intended it? Do you get any errors without the <code>INTERNET</code> permission?</p>
<p>If you do, then its clear that you need it! If not (and in the case of this question's scenario), you do not need the <code>INTERNET</code> permission.</p>
<p>The permissions are there as a security feature.</p>
<p>The permission in question is:</p>
<blockquote>
<p>public static final String INTERNET</p>
<p>Allows applications to open network sockets.</p>
<p>Constant Value: "android.permission.INTERNET"</p>
</blockquote>
<p>If your application needs network sockets, then your application needs permission to use them. Simple as that.</p>
<p>Add the below line to your manifest if you require the permission:</p>
<pre><code><uses-permission android:name="android.permission.INTERNET"></uses-permission>
</code></pre>
<p>The permissions are there to protect the user, so it is about being upfront and clear of what your applications intentions are.</p> |
4,434,797 | Read a config file in BASH without using "source" | <p>I'm attempting to read a config file that is formatted as follows:</p>
<pre><code>USER = username
TARGET = arrows
</code></pre>
<p>I realize that if I got rid of the spaces, I could simply source the config file, but for security reasons I'm trying to avoid that. I know there is a way to read the config file line by line. I think the process is something like:</p>
<ol>
<li>Read lines into an array</li>
<li>Filter out all of the lines that start with #</li>
<li>search for the variable names in the array</li>
</ol>
<p>After that I'm lost. Any and all help would be greatly appreciated. I've tried something like this with no success:</p>
<pre><code>backup2.config>cat ~/1
grep '^[^#].*' | while read one two;do
echo $two
done
</code></pre>
<p>I pulled that from a forum post I found, just not sure how to modify it to fit my needs since I'm so new to shell scripting.</p>
<p><a href="http://www.linuxquestions.org/questions/programming-9/bash-shell-program-read-a-configuration-file-276852/" rel="noreferrer">http://www.linuxquestions.org/questions/programming-9/bash-shell-program-read-a-configuration-file-276852/</a></p>
<hr>
<p>Would it be possible to automatically assign a variable by looping through both arrays?</p>
<pre><code>for (( i = 0 ; i < ${#VALUE[@]} ; i++ ))
do
"${NAME[i]}"=VALUE[i]
done
echo $USER
</code></pre>
<p>Such that calling $USER would output "username"? The above code isn't working but I know the solution is something similar to that.</p> | 4,434,843 | 4 | 0 | null | 2010-12-14 00:24:14.87 UTC | 9 | 2019-02-28 20:53:55.143 UTC | 2010-12-14 01:56:02.377 UTC | null | 541,289 | null | 541,289 | null | 1 | 15 | bash|grep|eval|config | 18,688 | <p>The following script iterates over each line in your input file (<em>vars</em> in my case) and does a pattern match against <code>=</code>. If the equal sign is found it will use <a href="http://www.network-theory.co.uk/docs/bashref/ShellParameterExpansion.html">Parameter Expansion</a> to parse out the variable <em>name</em> from the <em>value</em>. It then stores each part in it's own array, <em>name</em> and <em>value</em> respectively. </p>
<pre><code>#!/bin/bash
i=0
while read line; do
if [[ "$line" =~ ^[^#]*= ]]; then
name[i]=${line%% =*}
value[i]=${line#*= }
((i++))
fi
done < vars
echo "total array elements: ${#name[@]}"
echo "name[0]: ${name[0]}"
echo "value[0]: ${value[0]}"
echo "name[1]: ${name[1]}"
echo "value[1]: ${value[1]}"
echo "name array: ${name[@]}"
echo "value array: ${value[@]}"
</code></pre>
<h3>Input</h3>
<pre><code>$ cat vars
sdf
USER = username
TARGET = arrows
asdf
as23
</code></pre>
<h3>Output</h3>
<pre><code>$ ./varscript
total array elements: 2
name[0]: USER
value[0]: username
name[1]: TARGET
value[1]: arrows
name array: USER TARGET
value array: username arrows
</code></pre> |
4,230,746 | Does being a competent scala programmer require you to be a competent java programmer? | <p>I am a big fan of Scala aesthetically, and of a lot of the conceptual work put into things like its typing system and libraries.</p>
<p>However, as I have begun tinkering with Scala (and seen some of my coworkers tinker with it) i find myself having to dig for more and more Java knowledge (especially in the way of libraries).</p>
<p>This presents me with a few problems:</p>
<ul>
<li>Having never been a Java programmer, i'm not familiar or comfortable with the Java standard library, or additional popular libraries (like Apache Commons).</li>
<li>My google-fu in the Java-sphere is weak. It's hard to know what to search for – a problem exacerbated by the ponderously large number of irrelevant or rudimentary java tutorials for programming newbies.</li>
</ul>
<p>At this point though, i'm not sure whether i should bite the bullet and try and find the quickest and most comprehensive tour through Java to catch myself up on 20 years of Java developments, or whether its reasonable to continue trying to incrementally patch my knowledge as i wander around scala.</p>
<p>Any wisdom that scala heads amongst us could offer would be greatly appreciated.</p>
<p>P.S.
I have no doubt in my ability to familiarize myself with Scala syntax, and i'm perfectly comfortable and happy with functional programming and the paradigms in the scala community. But a programmer's competence is not just based on one's ability to teach oneself, but also one's ability to learn from, and adopt tools and skills from other people.</p> | 4,230,824 | 4 | 4 | null | 2010-11-20 01:26:55.643 UTC | 8 | 2015-05-06 22:05:35.517 UTC | 2010-11-20 01:34:30.757 UTC | null | 333,795 | null | 333,795 | null | 1 | 40 | java|scala|libraries | 2,466 | <p>You should take a <code>lazy</code> approach to learning Java. Learn it when you need it.</p>
<p>In my opinion, much of the old Java knowledge is out of date, much of the new tutorials are redundant. You certainly don't want to bother yourself with Java's antiquated <code>Collections</code>, for example. Many Java-based frameworks can be safely ignored. And the heavyweight JavaEE stack can be safely bypassed until you were forced to use a part of it.</p>
<p>Many common patterns in Java are much simpler in Scala, with the former being burdened with much boilerplate code. Core logic should always be implemented in Scala. I believe you can do most of your work directly in Scala and only need to dip down into Java when building things like Swing or integrating with Spring, etc.</p>
<p>In regard to choosing and using Java libraries, my personal guidelines are:</p>
<ol>
<li>If Spring can do it, use Spring</li>
<li>If Spring is too heavyweight, use what Spring uses.</li>
<li>If Spring can't do it, check github projects</li>
<li>If there's nothing on github, check Apache projects</li>
<li>If there's nothing from Apache, check sourceforge(t).</li>
<li>Finally, Google randomly or just build it yourself.</li>
</ol>
<p>That's a bit tounge-in-cheek, but is the impression I get about the maturity and stability of third party libraries after having done Java for the last 12 years.</p> |
4,381,102 | Differences between ARM architectures from a C programmer's perspective? | <p>I'm fairly new to programming for ARM. I've noticed there are several architectures like ARMv4, ARMv5, ARMv6, etc. What is the difference between these? Do they have different instruction sets or behaviors? </p>
<p>Most importantly, if I compile some C code for ARMv6, will it run on ARMv5? What about ARMv5 code running on ARMv6? Or would I only have to worry about the difference if I were writing kernel assembly code?</p> | 4,391,042 | 5 | 0 | null | 2010-12-07 20:11:32.177 UTC | 21 | 2014-03-16 07:12:02.957 UTC | null | null | null | null | 1,891 | null | 1 | 34 | c|architecture|arm|instruction-set | 13,753 | <p>The ARM world is a bit messy.</p>
<p>For the C programmers, things are simple: all ARM architectures offer a regular, 32-bit with flat addressing programming model. As long as you stay with C source code, the only difference you may see is about endianness and performance. Most ARM processors (even old models) can be both big-endian and little-endian; the choice is then made by the logic board and the operating system. Good C code is <em>endian neutral</em>: it compiles and works correctly, regardless of the platform endianness (endian neutrality is good for reliability and maintainability, but also for performance: non-neutral code is code which accesses the same data through pointers of distinct sizes, and this wreaks havoc with the strict aliasing rules that the compiler uses to optimize code).</p>
<p>The situation is quite different if you consider <strong>binary</strong> compatibility (i.e. reusing code which has been compiled once):</p>
<hr>
<ul>
<li>There are several instruction sets:
<ol>
<li>the original ARM instruction set with a 26-bit program counter (very old, very unlikely to be encountered nowadays)</li>
<li>the ARM instruction set with a 32-bit program counter (often called "ARM code")</li>
<li>the Thumb instruction set (16-bit simplified opcodes)</li>
<li>the Thumb-2 instruction set (Thumb with extensions)</li>
</ol></li>
</ul>
<p>A given processor may implement several instruction sets. The newest processor which knows only ARM code is the StrongARM, an ARMv4 representative which is already quite old (15 years). The ARM7TDMI (ARMv4T architecture) knows both ARM and Thumb, as do almost all subsequent ARM systems except the Cortex-M. ARM and Thumb code can be mixed together within the same application, as long as the proper glue is inserted where conventions change; this is called <em>thumb interworking</em> and can be handled automatically by the C compiler.</p>
<p>The Cortex-M0 knows only Thumb instructions. It knows a few extensions, because in "normal" ARM processors, the operating system must use ARM code (for handling interrupts); thus, the Cortex-M0 knows a few Thumb-for-OS things. This does not matter for application code.</p>
<p>The other Cortex-M know only Thumb-2. Thumb-2 is <em>mostly</em> backward compatible with Thumb, at least at assembly level.</p>
<hr>
<ul>
<li>Some architectures add extra instructions.</li>
</ul>
<p>Thus, if some code is compiled with a compiler switch telling that this is for an ARMv6, then the compiler may use one of the few instructions with the ARMv6 has but not the ARMv5. This is a common situation, encountered on almost all platforms: e.g., if you compile C code on a PC, with GCC, using the <code>-march=core2</code> flag, then the resulting binary may fail to run on an older Pentium processor.</p>
<hr>
<ul>
<li>There are several call conventions.</li>
</ul>
<p>The call convention is the set of rules which specify how functions exchange parameters and return values. The processor knows only of its registers, and has no notion of a stack. The call convention tells in which registers parameters go, and how they are encoded (e.g. if there is a <code>char</code> parameter, it goes in the low 8 bits of a register, but is the caller supposed to clear/sign-extend the upper 24 bits, or not ?). It describes the stack structure and alignment. It normalizes alignment conditions and padding for structure fields.</p>
<p>There are two main conventions for ARM, called ATPCS (old) and AAPCS (new). They are quite different on the subject of floating point values. For integer parameters, they are mostly identical (but AAPCS requires a stricter stack alignment). Of course, conventions vary depending on the instruction set, and the presence of Thumb interworking.</p>
<p>In some cases, it is possible to have some binary code which conforms to both ATPCS and AAPCS, but that is not reliable and there is no warning on mismatch. So the bottom-line is: you cannot have true binary compatibility between systems which use distinct call conventions.</p>
<hr>
<ul>
<li>There are optional coprocessors.</li>
</ul>
<p>The ARM architecture can be extended with optional elements, which add their own instructions to the core instruction set. The FPU is such an optional coprocessor (and it is very rarely encountered in practice). Another coprocessor is NEON, a SIMD instruction set found on some of the newer ARM processors.</p>
<p>Code which uses a coprocessor will not run on a processor which does not feature that coprocessor, unless the operating system traps the corresponding opcodes and emulates the coprocessor in software (this is more or less what happens with floating-point arguments when using the ATPCS call convention, and it is <em>slow</em>).</p>
<hr>
<p>To sum up, if you have C code, then recompile it. Do not try to reuse code compiled for another architecture or system.</p> |
4,715,415 | Base64: What is the worst possible increase in space usage? | <p>If a server received a base64 string and wanted to check it's length before converting,, say it wanted to always permit the final byte array to be 16KB. How big could a 16KB byte array possibly become when converted to a Base64 string (assuming one byte per character)?</p> | 4,715,480 | 5 | 0 | null | 2011-01-17 16:27:46.493 UTC | 31 | 2019-09-02 11:28:08.207 UTC | null | null | null | null | 463,304 | null | 1 | 198 | base64|expansion | 106,845 | <p>Base64 encodes each set of three bytes into four bytes. In addition the output is padded to always be a multiple of four.</p>
<p>This means that the size of the base-64 representation of a string of size n is:</p>
<pre><code>ceil(n / 3) * 4
</code></pre>
<p>So, for a 16kB array, the base-64 representation will be ceil(16*1024/3)*4 = 21848 bytes long ~= 21.8kB.</p>
<p>A <strong>rough</strong> approximation would be that the size of the data is increased to 4/3 of the original.</p> |
4,150,435 | php strtotime "last monday" if today is monday? | <p>I want to use <code>strtotime("last Monday")</code>.</p>
<p>The thing is, if today IS MONDAY, what does it return?
It seems to be returning the date for the monday of last week. How can I make it return today's date in that case?</p> | 4,150,501 | 8 | 0 | null | 2010-11-11 00:31:31.307 UTC | 10 | 2017-02-20 11:25:46.443 UTC | 2010-11-11 00:43:37.437 UTC | null | 31,671 | null | 25,645 | null | 1 | 43 | php|datetime|strtotime | 67,244 | <blockquote>
<p>How can I make it return today's date in that case?</p>
</blockquote>
<p>pseudocode:</p>
<pre><code>if (today == monday)
return today;
else
return strtotime(...);
</code></pre>
<p>Btw, this trick also could work:</p>
<pre><code>strtotime('last monday', strtotime('tomorrow'));
</code></pre> |
4,171,140 | How to iterate over values of an Enum having flags? | <p>If I have a variable holding a flags enum, can I somehow iterate over the single-bit values in that specific variable? Or do I have to use Enum.GetValues to iterate over the entire enum and check which ones are set?</p> | 22,222,260 | 18 | 0 | null | 2010-11-13 05:34:54.03 UTC | 27 | 2022-01-30 10:39:41.157 UTC | 2020-09-06 09:29:47.24 UTC | null | 578,411 | user502255 | null | null | 1 | 154 | c#|enums|enum-flags | 81,997 | <p>Coming back at this a few years later, with a bit more experience, my ultimate answer for single-bit values only, moving from lowest bit to highest bit, is a slight variant of Jeff Mercado's inner routine:</p>
<pre><code>public static IEnumerable<Enum> GetUniqueFlags(this Enum flags)
{
ulong flag = 1;
foreach (var value in Enum.GetValues(flags.GetType()).Cast<Enum>())
{
ulong bits = Convert.ToUInt64(value);
while (flag < bits)
{
flag <<= 1;
}
if (flag == bits && flags.HasFlag(value))
{
yield return value;
}
}
}
</code></pre>
<p>It seems to work, and despite my objections of some years ago, I use HasFlag here, since it's far more legible than using bitwise comparisons and the speed difference is insignificant for anything I'll be doing. (It's entirely possible they've improved the speed of HasFlags since then anyway, for all I know...I haven't tested.)</p> |
14,405,693 | Using cluster in an Expressjs app | <p>I'm doing a little OJT on my first node project and, while I can stand up a simple server, the app is going to get hammered so using cluster seems like a good idea. I've cobbled together some code snippets that I've found in various searches (including SO), but the server won't start. I'm sure my inexperience with node has me doing something stupid, but I don't see it.</p>
<pre><code>var express = require( 'express' );
var cluster = require( 'cluster' );
var path = require( 'path' );
var cCPUs = require( 'os' ).cpus().length;
var port = 3000;
var root = path.dirname( __dirname );
if( cluster.isMaster ) {
for( var i = 0; i < cCPUs; i++ ) {
cluster.fork();
}
cluster.on( 'death', function( worker ) {
console.log( 'Worker ' + worker.pid + ' died.' );
});
}
else {
// eyes.inspect( process.env );
console.log( 'Worker: %s', process.env.NODE_WORKER_ID );
var app = express();
var routes = require( './routes' )( app );
app
.use( cluster.repl( root + 'cluster.repl' ) )
.use( cluster.stats({ connections: true, requests: true }) )
.use( cluster.reload( root ) )
.listen( port );
}
</code></pre>
<p>RESULT:</p>
<pre><code>TypeError: Object #<Cluster> has no method 'repl'
</code></pre>
<p>If I remove the <code>use</code> calls, the workers start up correctly, but <code>process.env.NODE_WORKER_ID</code> is <code>undefined</code>. Inspecting <code>process.env</code> shows me that it's definitely not defined. Maybe the snippet I used was from an old version, but I'm not sure how to identify the worker thread in any other way.</p>
<p>If anyone can unscrambled whatever I've scrambled, I'd really appreciate it.</p> | 14,439,764 | 3 | 4 | null | 2013-01-18 18:56:05.58 UTC | 11 | 2021-09-23 07:44:03.34 UTC | null | null | null | null | 1,665 | null | 1 | 17 | node.js|express | 19,800 | <p>For anyone searching later, here's what I ended up with:</p>
<pre class="lang-js prettyprint-override"><code>const cluster = require('cluster');
const express = require('express');
const path = require('path');
const port = 3000;
const root = path.dirname(__dirname);
const cCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Create a worker for each CPU
for (let i = 0; i < cCPUs; i++) {
cluster.fork();
}
cluster.on('online', function (worker) {
console.log('Worker ' + worker.process.pid + ' is online.');
});
cluster.on('exit', function (worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died.');
});
} else {
const app = express();
const routes = require('./routes')(app);
app.use(express.bodyParser()).listen(port);
}
</code></pre>
<p>I'm still very early in the node learning curve, but the server starts and appears to have a working running on each core. Thanks to JohnnyH for getting me on the right track.</p> |
14,741,688 | How to display messages from jQuery Validate plugin inside of Tooltipster tooltips? | <p>I'd like to use the <a href="http://calebjacob.com/tooltipster/">Tooltipster plugin</a> to display form errors generated by the <a href="http://docs.jquery.com/Plugins/Validation">jQuery Validate plugin</a>. </p>
<p><strong>jQuery for Validate plugin</strong>:</p>
<pre><code>$(document).ready(function () {
$('#myform').validate({ // initialize jQuery Validate
// other options,
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
});
</code></pre>
<p><strong>jQuery for Tooltipster plugin</strong>:</p>
<pre><code>$(document).ready(function () {
$('.tooltip').tooltipster({ /* options */ }); // initialize tooltipster
});
</code></pre>
<p><strong>HTML</strong>:</p>
<pre><code><form id="myform">
<input type="text" name="field1" />
<input type="text" name="field2" />
<br/>
<input type="submit" />
</form>
</code></pre>
<p>How would I integrate the usage of these two jQuery plugins so that validation errors appear inside the tooltips?</p> | 14,741,689 | 2 | 0 | null | 2013-02-07 00:46:22.213 UTC | 17 | 2020-06-12 11:46:34.023 UTC | 2016-09-29 17:18:38.413 UTC | null | 594,235 | null | 594,235 | null | 1 | 20 | jquery|jquery-validate|tooltip|tooltipster | 58,332 | <p><strong>Solutions for Tooltipster versions 2.1, 3.0, & 4.0 are included in this answer.</strong></p>
<p><strong>NOTE</strong> that <code>.tooltipster()</code> is only attached to a <code>type="text"</code> <code>input</code> element in my examples below. If your <code>form</code> contains other kinds of data input elements such as <code>type="radio"</code>, <code>type="date"</code>, <code>textarea</code>, <code>select</code>, etc., then you <strong>must</strong> adjust your selector accordingly or create additional instances of <code>.tooltipster()</code> for these other elements. Otherwise, everything will fail with errors.</p>
<hr>
<p><strong>Tooltipster v2.1</strong></p>
<p>First, initialize the Tooltipster plugin (<a href="http://calebjacob.com/tooltipster/#options" rel="nofollow noreferrer">with any options</a>) on <strong>all</strong> specific <code>form</code> elements that will display errors:</p>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
// initialize tooltipster on form input elements
$('#myform input[type="text"]').tooltipster({
trigger: 'custom', // default is 'hover' which is no good here
onlyOne: false, // allow multiple tips to be open at a time
position: 'right' // display the tips to the right of the element
});
});
</code></pre>
<p>Second, use <a href="http://calebjacob.com/tooltipster/#advanced" rel="nofollow noreferrer">Tooltipster's advanced options</a> along with the <a href="http://docs.jquery.com/Plugins/Validation/validate#toptions" rel="nofollow noreferrer"><code>success:</code> and <code>errorPlacement:</code> callback functions built into the Validate plugin</a> to automatically show and hide the tooltips as follows:</p>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
// initialize validate plugin on the form
$('#myform').validate({
// any other options & rules,
errorPlacement: function (error, element) {
$(element).tooltipster('update', $(error).text());
$(element).tooltipster('show');
},
success: function (label, element) {
$(element).tooltipster('hide');
}
});
});
</code></pre>
<p><strong>Working Demo: <a href="http://jsfiddle.net/2DUX2/" rel="nofollow noreferrer">http://jsfiddle.net/2DUX2</a></strong></p>
<p><strong>EDIT</strong>: Updated code to take advantage of the new Tooltipster API features released in version 2.1 on 2/12/13</p>
<hr>
<hr>
<p><strong>UPDATE for Tooltipster v3.0</strong></p>
<p>Tooltipster 3.0 is out and as such doesn't work the same as illustrated above. The following code provides an updated example. This version has the added benefit of not calling Tooltipster on every keystroke when the message has not yet changed.</p>
<p>(<em>Don't forget that you still need to attach <code>.tooltipster()</code> to your relevant <code>input</code> elements as illustrated above.</em>)</p>
<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
// initialize validate plugin on the form
$('#myform').validate({
// any other options & rules,
errorPlacement: function (error, element) {
var lastError = $(element).data('lastError'),
newError = $(error).text();
$(element).data('lastError', newError);
if(newError !== '' && newError !== lastError){
$(element).tooltipster('content', newError);
$(element).tooltipster('show');
}
},
success: function (label, element) {
$(element).tooltipster('hide');
}
});
});
</code></pre>
<p><strong>DEMO using Tooltipster v3.0: <a href="http://jsfiddle.net/2DUX2/3/" rel="nofollow noreferrer">jsfiddle.net/2DUX2/3/</a></strong></p>
<hr>
<hr>
<p><strong>UPDATE for Tooltipster v4.0</strong></p>
<p>Note that the <code>onlyOne</code> option has been removed from the 4.0 version of the Tooltipster plugin.</p>
<p>I also replaced the <code>success</code> callback with <code>unhighlight</code>. On "optional" fields, the error message was never removed when the field was subsequently blanked out... this is because the <code>success</code> function does not fire under these circumstances. This issue is not isolated to Tooltipster version 4, however the following code solves it moving forward.</p>
<pre><code>// initialize Tooltipster on text input elements
$('input[type="text"]').tooltipster({ //find more options on the tooltipster page
trigger: 'custom', // default is 'hover' which is no good here
position: 'top',
animation: 'grow'
});
// initialize jQuery Validate
$("#myform").validate({
errorPlacement: function (error, element) {
var ele = $(element),
err = $(error),
msg = err.text();
if (msg != null && msg !== '') {
ele.tooltipster('content', msg);
ele.tooltipster('open');
}
},
unhighlight: function(element, errorClass, validClass) {
$(element).removeClass(errorClass).addClass(validClass).tooltipster('close');
},
rules: {
....
</code></pre>
<p><strong>DEMO using Tooltipster v4.0: <a href="https://jsfiddle.net/h5grrrr9/" rel="nofollow noreferrer">https://jsfiddle.net/h5grrrr9/</a></strong></p> |
14,448,056 | The app references non-public selector in id (Facebook SDK iOS) | <p>I was having this warning when submitting my app with Application Loader.</p>
<pre><code>The app references non-public selector in MyApp : id
</code></pre>
<p>This warning can potentially reject my app from Apple AppStore's validation.</p>
<p>My app is using Facebook SDK iOS 3.1.1 (also tried with 3.1)</p> | 14,448,057 | 8 | 1 | null | 2013-01-21 22:02:33.543 UTC | 9 | 2014-05-26 21:47:24.01 UTC | null | null | null | null | 836,501 | null | 1 | 43 | ios|facebook|facebook-ios-sdk|application-loader | 18,382 | <p>This problem happens because of the Facebook SDK for iOS.</p>
<p>Application Loader forbids the use of the variable "id" from any FBGraphUser related class (maybe others variables too, didn't test) - e.g. : </p>
<pre><code>id<FBGraphUser> friend
id<FBGraphUserExtraFields>user
</code></pre>
<p>Facebook is informed about this problem as of january 2013 : <a href="https://developers.facebook.com/bugs/143882255765923/" rel="noreferrer">Bug Report</a></p>
<p>The workaround for the moment is to use these:</p>
<pre><code>[user objectForKey:@"id"]
[friend objectForKey:@"id"]
</code></pre>
<p>instead of <code>user.id</code> and <code>friend.id</code> as shown in the different Facebook samples.</p> |
1,832,962 | Can you execute another EXE file from within a C# console application? | <p>Can you execute another EXE file from within a C# console application?</p>
<ul>
<li>Can you pass arguments?</li>
<li>Can you get the exit code back?</li>
</ul> | 1,833,006 | 1 | 0 | null | 2009-12-02 13:37:37.723 UTC | 9 | 2013-08-26 19:51:56.003 UTC | 2013-08-26 19:49:53.183 UTC | null | 63,550 | null | 26,521 | null | 1 | 27 | c#|console-application | 34,063 | <p>Like this:</p>
<pre><code> var proc = new Process();
proc.StartInfo.FileName = "something.exe";
proc.StartInfo.Arguments = "-v -s -a";
proc.Start();
proc.WaitForExit();
var exitCode = proc.ExitCode;
proc.Close();
</code></pre> |
31,259,891 | Put customized functions in Sklearn pipeline | <p>In my classification scheme, there are several steps including:</p>
<ol>
<li>SMOTE (Synthetic Minority Over-sampling Technique)</li>
<li>Fisher criteria for feature selection</li>
<li>Standardization (Z-score normalisation)</li>
<li>SVC (Support Vector Classifier)</li>
</ol>
<p>The main parameters to be tuned in the scheme above are percentile (2.) and hyperparameters for SVC (4.) and I want to go through grid search for tuning.</p>
<p>The current solution builds a "partial" pipeline including step 3 and 4 in the scheme <code>clf = Pipeline([('normal',preprocessing.StandardScaler()),('svc',svm.SVC(class_weight='auto'))])</code>
and breaks the scheme into two parts:</p>
<ol>
<li><p>Tune the percentile of features to keep through the first grid search</p>
<pre class="lang-py prettyprint-override"><code>skf = StratifiedKFold(y)
for train_ind, test_ind in skf:
X_train, X_test, y_train, y_test = X[train_ind], X[test_ind], y[train_ind], y[test_ind]
# SMOTE synthesizes the training data (we want to keep test data intact)
X_train, y_train = SMOTE(X_train, y_train)
for percentile in percentiles:
# Fisher returns the indices of the selected features specified by the parameter 'percentile'
selected_ind = Fisher(X_train, y_train, percentile)
X_train_selected, X_test_selected = X_train[selected_ind,:], X_test[selected_ind, :]
model = clf.fit(X_train_selected, y_train)
y_predict = model.predict(X_test_selected)
f1 = f1_score(y_predict, y_test)
</code></pre>
<p>The f1 scores will be stored and then be averaged through all fold partitions for all percentiles, and the percentile with the best CV score is returned. The purpose of putting 'percentile for loop' as the inner loop is to allow fair competition as we have the same training data (including synthesized data) across all fold partitions for all percentiles.</p>
</li>
<li><p>After determining the percentile, tune the hyperparameters by second grid search</p>
<pre class="lang-py prettyprint-override"><code>skf = StratifiedKFold(y)
for train_ind, test_ind in skf:
X_train, X_test, y_train, y_test = X[train_ind], X[test_ind], y[train_ind], y[test_ind]
# SMOTE synthesizes the training data (we want to keep test data intact)
X_train, y_train = SMOTE(X_train, y_train)
for parameters in parameter_comb:
# Select the features based on the tuned percentile
selected_ind = Fisher(X_train, y_train, best_percentile)
X_train_selected, X_test_selected = X_train[selected_ind,:], X_test[selected_ind, :]
clf.set_params(svc__C=parameters['C'], svc__gamma=parameters['gamma'])
model = clf.fit(X_train_selected, y_train)
y_predict = model.predict(X_test_selected)
f1 = f1_score(y_predict, y_test)
</code></pre>
</li>
</ol>
<p>It is done in the very similar way, except we tune the hyperparamter for SVC rather than percentile of features to select.</p>
<p>My questions are:</p>
<ol>
<li><p>In the current solution, I only involve 3. and 4. in the <code>clf</code> and do 1. and 2. kinda "manually" in two nested loop as described above. Is there any way to include all four steps in a pipeline and do the whole process at once?</p>
</li>
<li><p>If it is okay to keep the first nested loop, then is it possible (and how) to simplify the next nested loop using a single pipeline</p>
<pre class="lang-py prettyprint-override"><code>clf_all = Pipeline([('smote', SMOTE()),
('fisher', Fisher(percentile=best_percentile))
('normal',preprocessing.StandardScaler()),
('svc',svm.SVC(class_weight='auto'))])
</code></pre>
<p>and simply use <code>GridSearchCV(clf_all, parameter_comb)</code> for tuning?</p>
<p>Please note that both <code>SMOTE</code> and <code>Fisher</code> (ranking criteria) have to be done only for the training data in each fold partition.</p>
</li>
</ol>
<p>It would be so much appreciated for any comment.</p>
<p><code>SMOTE</code> and <code>Fisher</code> are shown below:</p>
<pre class="lang-py prettyprint-override"><code>def Fscore(X, y, percentile=None):
X_pos, X_neg = X[y==1], X[y==0]
X_mean = X.mean(axis=0)
X_pos_mean, X_neg_mean = X_pos.mean(axis=0), X_neg.mean(axis=0)
deno = (1.0/(shape(X_pos)[0]-1))*X_pos.var(axis=0) +(1.0/(shape(X_neg[0]-1))*X_neg.var(axis=0)
num = (X_pos_mean - X_mean)**2 + (X_neg_mean - X_mean)**2
F = num/deno
sort_F = argsort(F)[::-1]
n_feature = (float(percentile)/100)*shape(X)[1]
ind_feature = sort_F[:ceil(n_feature)]
return(ind_feature)
</code></pre>
<p><code>SMOTE</code> is from <a href="https://github.com/blacklab/nyan/blob/master/shared_modules/smote.py" rel="noreferrer">https://github.com/blacklab/nyan/blob/master/shared_modules/smote.py</a>, it returns the synthesized data. I modified it to return the original input data stacked with the synthesized data along with its labels and synthesized ones.</p>
<pre class="lang-py prettyprint-override"><code>def smote(X, y):
n_pos = sum(y==1), sum(y==0)
n_syn = (n_neg-n_pos)/float(n_pos)
X_pos = X[y==1]
X_syn = SMOTE(X_pos, int(round(n_syn))*100, 5)
y_syn = np.ones(shape(X_syn)[0])
X, y = np.vstack([X, X_syn]), np.concatenate([y, y_syn])
return(X, y)
</code></pre> | 31,299,784 | 3 | 0 | null | 2015-07-07 04:44:07.187 UTC | 8 | 2021-12-15 02:11:04.7 UTC | 2021-06-18 09:19:11.447 UTC | null | 1,364,007 | null | 3,882,995 | null | 1 | 18 | machine-learning|scikit-learn|pipeline|cross-validation|feature-selection | 26,711 | <p>I don't know where your <code>SMOTE()</code> and <code>Fisher()</code> functions are coming from, but the answer is yes you can definitely do this. In order to do so you will need to write a wrapper class around those functions though. The easiest way to this is inherit sklearn's <code>BaseEstimator</code> and <code>TransformerMixin</code> classes, see this for an example: <a href="http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html" rel="noreferrer">http://scikit-learn.org/stable/auto_examples/hetero_feature_union.html</a></p>
<p>If this isn't making sense to you, post the details of at least one of your functions (the library it comes from or your code if you wrote it yourself) and we can go from there.</p>
<p>EDIT:</p>
<p>I apologize, I didn't look at your functions closely enough to realize that they transform your target in addition to your training data (i.e. both X and y). Pipeline does not support transformations to your target so you will have do them prior as you originally were. For your reference, here is what it would look like to write your custom class for your Fisher process which would work if the function itself did not need to affect your target variable.</p>
<pre><code>>>> from sklearn.base import BaseEstimator, TransformerMixin
>>> from sklearn.preprocessing import StandardScaler
>>> from sklearn.svm import SVC
>>> from sklearn.pipeline import Pipeline
>>> from sklearn.grid_search import GridSearchCV
>>> from sklearn.datasets import load_iris
>>>
>>> class Fisher(BaseEstimator, TransformerMixin):
... def __init__(self,percentile=0.95):
... self.percentile = percentile
... def fit(self, X, y):
... from numpy import shape, argsort, ceil
... X_pos, X_neg = X[y==1], X[y==0]
... X_mean = X.mean(axis=0)
... X_pos_mean, X_neg_mean = X_pos.mean(axis=0), X_neg.mean(axis=0)
... deno = (1.0/(shape(X_pos)[0]-1))*X_pos.var(axis=0) + (1.0/(shape(X_neg)[0]-1))*X_neg.var(axis=0)
... num = (X_pos_mean - X_mean)**2 + (X_neg_mean - X_mean)**2
... F = num/deno
... sort_F = argsort(F)[::-1]
... n_feature = (float(self.percentile)/100)*shape(X)[1]
... self.ind_feature = sort_F[:ceil(n_feature)]
... return self
... def transform(self, x):
... return x[self.ind_feature,:]
...
>>>
>>> data = load_iris()
>>>
>>> pipeline = Pipeline([
... ('fisher', Fisher()),
... ('normal',StandardScaler()),
... ('svm',SVC(class_weight='auto'))
... ])
>>>
>>> grid = {
... 'fisher__percentile':[0.75,0.50],
... 'svm__C':[1,2]
... }
>>>
>>> model = GridSearchCV(estimator = pipeline, param_grid=grid, cv=2)
>>> model.fit(data.data,data.target)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/dmcgarry/anaconda/lib/python2.7/site-packages/sklearn/grid_search.py", line 596, in fit
return self._fit(X, y, ParameterGrid(self.param_grid))
File "/Users/dmcgarry/anaconda/lib/python2.7/site-packages/sklearn/grid_search.py", line 378, in _fit
for parameters in parameter_iterable
File "/Users/dmcgarry/anaconda/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 653, in __call__
self.dispatch(function, args, kwargs)
File "/Users/dmcgarry/anaconda/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 400, in dispatch
job = ImmediateApply(func, args, kwargs)
File "/Users/dmcgarry/anaconda/lib/python2.7/site-packages/sklearn/externals/joblib/parallel.py", line 138, in __init__
self.results = func(*args, **kwargs)
File "/Users/dmcgarry/anaconda/lib/python2.7/site-packages/sklearn/cross_validation.py", line 1239, in _fit_and_score
estimator.fit(X_train, y_train, **fit_params)
File "/Users/dmcgarry/anaconda/lib/python2.7/site-packages/sklearn/pipeline.py", line 130, in fit
self.steps[-1][-1].fit(Xt, y, **fit_params)
File "/Users/dmcgarry/anaconda/lib/python2.7/site-packages/sklearn/svm/base.py", line 149, in fit
(X.shape[0], y.shape[0]))
ValueError: X and y have incompatible shapes.
X has 1 samples, but y has 75.
</code></pre> |
38,792,122 | How to group and count rows by month and year using Pandas? | <p>I have a dataset with personal data such as name, height, weight and date of birth. I would build a graph with the number of people born in a particular month and year. I'm using python pandas to accomplish this and my strategy was to try to group by year and month and add using count. But the closest I got is to get the count of people by year or by month but not by both.</p>
<pre><code>df['birthdate'].groupby(df.birthdate.dt.year).agg('count')
</code></pre>
<p>Other questions in stackoverflow point to a Grouper called TimeGrouper but searching in pandas documentation found nothing. Any idea?</p> | 38,792,175 | 5 | 0 | null | 2016-08-05 14:49:47.5 UTC | 15 | 2020-05-13 02:47:34.033 UTC | 2020-05-13 02:47:34.033 UTC | null | 7,758,804 | null | 831,790 | null | 1 | 37 | python|pandas | 87,788 | <p>To group on multiple criteria, pass a list of the columns or criteria:</p>
<pre><code>df['birthdate'].groupby([df.birthdate.dt.year, df.birthdate.dt.month]).agg('count')
</code></pre>
<p>Example:</p>
<pre><code>In [165]:
df = pd.DataFrame({'birthdate':pd.date_range(start=dt.datetime(2015,12,20),end=dt.datetime(2016,3,1))})
df.groupby([df['birthdate'].dt.year, df['birthdate'].dt.month]).agg({'count'})
Out[165]:
birthdate
count
birthdate birthdate
2015 12 12
2016 1 31
2 29
3 1
</code></pre>
<p><strong>UPDATE</strong></p>
<p>As of version <a href="https://github.com/pandas-dev/pandas/issues/21075" rel="noreferrer"><code>0.23.0</code></a> the above code no longer works due to the restriction that multi-index level names must be unique, you now need to <code>rename</code> the levels in order for this to work:</p>
<pre><code>In[107]:
df.groupby([df['birthdate'].dt.year.rename('year'), df['birthdate'].dt.month.rename('month')]).agg({'count'})
Out[107]:
birthdate
count
year month
2015 12 12
2016 1 31
2 29
3 1
</code></pre> |
38,910,198 | What is a local variable in tensorflow? | <p>Tensorflow has this API defined:</p>
<blockquote>
<p><code>tf.local_variables()</code></p>
<p>Returns all variables created with <code>collection=[LOCAL_VARIABLES]</code>.</p>
<p>Returns:</p>
<p>A list of local Variable objects.</p>
</blockquote>
<p>What exactly is a local variable in TensorFlow? Can someone give me an example?</p> | 38,956,426 | 3 | 1 | null | 2016-08-12 04:54:06.107 UTC | 16 | 2018-09-01 05:30:26.2 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 4,451,484 | null | 1 | 19 | tensorflow | 12,316 | <p>It's the same as regular variable, but it's in a different collection than default (<code>GraphKeys.VARIABLES</code>). That collection is used by saver to initialize the default list of variables to save, so having a <code>local</code> designation has an effect of not saving that variable by default. </p>
<p>I'm seeing only one place that uses it in the codebase, which is the <code>limit_epochs</code> </p>
<pre><code> with ops.name_scope(name, "limit_epochs", [tensor]) as name:
zero64 = constant_op.constant(0, dtype=dtypes.int64)
epochs = variables.Variable(
zero64, name="epochs", trainable=False,
collections=[ops.GraphKeys.LOCAL_VARIABLES])
</code></pre> |
49,633,157 | How do I set headers to all responses in Koa.js? | <p>In Express.js I used to have this kind of code:</p>
<pre><code>app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
next();
});
</code></pre>
<p>How do I do the same thing with Koa.js? I need to preset these several http headers for each server response.</p> | 49,633,526 | 1 | 0 | null | 2018-04-03 14:56:06.927 UTC | 4 | 2018-04-03 15:13:03.167 UTC | null | null | null | null | 2,992,008 | null | 1 | 28 | javascript|node.js|koa | 25,164 | <p>Finaly I found how to do it.</p>
<pre><code>app.use(async (ctx, next) => {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
ctx.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
await next();
});
</code></pre> |
29,735,527 | Why the App is installed twice? | <p>When I run the Android App Studio, the cell is the App is "installed" twice: There are two apps one called "SplashScreenActivity" and other "Doctor Quiz" (my app), <b>the two are equal. If I uninstall one, the other also uninstalls</b>.<br> Why does this happen? How do I "install" just my app? (DoctorQuiz)</p>
<p>AndroidManifest.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.morais.daniela.doctorquiz" >
<uses-permission android:name="android.permission.INTERNET"/>
<provider android:authorities="com.facebook.app.FacebookContentProviderXXXX"
android:name="com.facebook.FacebookContentProvider"
android:exported="true" />
<application
android:allowBackup="true"
android:icon="@drawable/medicine_box_icon2"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<activity
android:name=".Activity.SplashScreenActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="@string/title_activity_splash_screen"
android:theme="@style/FullscreenTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activity.QuestionsActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activity.ResultActivity"
android:label="@string/title_activity_result" >
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:theme="@android:style/Theme.Translucent.NoTitleBar"
android:label="@string/app_name" />
</activity>
</application>
</manifest>
</code></pre>
<p>Screenshot<br>
<img src="https://i.stack.imgur.com/uX20p.png" alt="enter image description here"></p> | 29,735,556 | 2 | 0 | null | 2015-04-19 20:35:24.29 UTC | 8 | 2021-10-05 20:03:28.98 UTC | null | null | null | null | 4,587,985 | null | 1 | 24 | android|android-studio | 12,899 | <p>The app is not installed twice. You are not looking at apps. You are looking at launchable activities, ones with this <code><intent-filter></code>:</p>
<pre><code> <intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</code></pre>
<p>You have two activities with that <code><intent-filter></code>, and so you will have two activities in the home screen launcher. If you do not want both of those activities in the home screen launcher, remove that <code><intent-filter></code> from one of them.</p> |
49,897,639 | How to allow any other key in Joi | <p>I have a simple requirement. I tried to search on the internet as well as documentation but failed. <br>
So here is what I want to achieve:</p>
<p>I have a schema:</p>
<pre><code>const schema = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
});
</code></pre>
<p>Now, How do I configure it such that any other key in the object would be allowed? <br><br>
With this schema, it only allows two keys <code>a</code> and <code>b</code>. If I pass any other key, say, <code>c</code>, it throws an error saying that <code>c</code> is not allowed.</p> | 49,898,360 | 2 | 1 | null | 2018-04-18 10:40:10.633 UTC | 2 | 2020-05-21 22:06:52.987 UTC | null | null | null | null | 5,403,618 | null | 1 | 48 | javascript|hapi.js|joi | 33,990 | <p>You can add unknown keys using <a href="https://github.com/hapijs/joi/blob/v13.2.0/API.md#objectpatternregex-schema" rel="noreferrer">object.pattern(regex, schema)</a> this way IF you want to make sure these unknown keys are strings:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const schema = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
}).pattern(/./, Joi.string());</code></pre>
</div>
</div>
</p>
<p>For a general pass of all key types use <a href="https://github.com/hapijs/joi/blob/master/API.md#objectunknownallow" rel="noreferrer">object.unknown(true)</a>:</p>
<pre><code>const schema = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
}).unknown(true);
</code></pre> |
36,275,459 | Find the closest elements above and below a given number | <pre><code>myArr = array([4,1,88,44,3])
myNumber = 25
FindClosest(myArr, myNumber)
...
4, 44
</code></pre>
<p>Is there any way to find the closest 2 numbers in a list to a given number such that one of them is higher and the other lower?</p>
<p>I can find the closest number by:</p>
<pre><code>min(myArr.tolist(), key=lambda x:abs(x-myNumber))
</code></pre> | 36,275,584 | 4 | 0 | null | 2016-03-29 04:29:49.733 UTC | 9 | 2022-06-17 17:57:31.93 UTC | 2017-03-08 15:42:26.517 UTC | null | 674,039 | null | 308,827 | null | 1 | 15 | python|numpy | 20,813 | <p>Sorting is not necessary, and makes this time complexity O(n logn) when it should be just O(n).</p>
<p>I believe this is what you're looking for, taking advantage of numpy array indexing:</p>
<pre><code>>>> # the smallest element of myArr greater than myNumber
>>> myArr[myArr > myNumber].min()
44
>>> # the largest element of myArr less than myNumber
>>> myArr[myArr < myNumber].max()
4
</code></pre> |
28,207,571 | Camera access with Xamarin.Forms | <p>Is anyone able to give a short, self-contained example on how to access the camera with Xamarin.Forms 1.3.x? Simply calling the native camera application and retrieving the resulting picture would be great. Displaying a live view on the Xamarin.Forms page would be awesome!</p>
<p>I already tried to use Xamarin.Mobile and Xamarin.Forms.Labs, but I couldn't get any solution to work on both platforms (focussing on Android and iOS for now). Most code snippets found on the web (including stackoverflow) are incomplete, e.g. not showing the implementation of an IMediaPicker object or where to anchor the method for taking pictures.</p> | 28,299,259 | 4 | 0 | null | 2015-01-29 05:27:18.587 UTC | 22 | 2017-07-06 07:10:27.363 UTC | null | null | null | null | 3,419,103 | null | 1 | 35 | c#|camera|xamarin.forms|xamarin.mobile|xamarin.forms.labs | 60,279 | <p>I finally created a minimum solution for iOS and Android.</p>
<h2>The shared project</h2>
<p>First, let's look into the shared code. For an easy interaction between the shared <code>App</code> class and the platform-specific code we store a static <code>Instance</code> within the <code>public static App</code>:</p>
<pre class="lang-cs prettyprint-override"><code>public static App Instance;
</code></pre>
<p>Furthermore, we will display an <code>Image</code>, which will be filled with content later. So we create a member:</p>
<pre><code>readonly Image image = new Image();
</code></pre>
<p>Within the <code>App</code> constructor we store the <code>Instance</code> and create the page content, which is a simple <code>button</code> and the aforementioned <code>image</code>:</p>
<pre><code>public App()
{
Instance = this;
var button = new Button {
Text = "Snap!",
Command = new Command(o => ShouldTakePicture()),
};
MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
button,
image,
},
},
};
}
</code></pre>
<p>The button's click handler calls the event <code>ShouldTakePicture</code>.
It is a public member and the platform-specific code parts will assign to it later on.</p>
<pre><code>public event Action ShouldTakePicture = () => {};
</code></pre>
<p>Finally, we offer a public method for displaying the captured image:</p>
<pre><code>public void ShowImage(string filepath)
{
image.Source = ImageSource.FromFile(filepath);
}
</code></pre>
<h2>The Android project</h2>
<p>On Android we modify the <code>MainActivity</code>.
First, we define a path for the captured image file:</p>
<pre><code>static readonly File file = new File(Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures), "tmp.jpg");
</code></pre>
<p>At the end of <code>OnCreate</code> we can use the static <code>Instance</code> of the created <code>App</code> and assign an anonymous event handler, which will start a new <code>Intent</code> for capturing an image:</p>
<pre><code>App.Instance.ShouldTakePicture += () => {
var intent = new Intent(MediaStore.ActionImageCapture);
intent.PutExtra(MediaStore.ExtraOutput, Uri.FromFile(file));
StartActivityForResult(intent, 0);
};
</code></pre>
<p>Last but not least, our activity has to react on the resulting image. It will simply push its file path to the shared <code>ShowImage</code> method.</p>
<pre><code>protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
App.Instance.ShowImage(file.Path);
}
</code></pre>
<p>That's about it!
Just don't forget to set the "Camera" and the "WriteExternalStorage" permission within "AndroidManifest.xml"!</p>
<h2>The iOS project</h2>
<p>For the iOS implementation we create a custom renderer.
Therefore, we add a new file "CustomContentPageRenderer" and add the corresponding assembly attribute right after the using statements:</p>
<pre><code>[assembly:ExportRenderer(typeof(ContentPage), typeof(CustomContentPageRenderer))]
</code></pre>
<p>The <code>CustomContentPageRenderer</code> inherits from <code>PageRenderer</code>:</p>
<pre><code>public class CustomContentPageRenderer: PageRenderer
{
...
}
</code></pre>
<p>We override the <code>ViewDidAppear</code> method and add the following parts.</p>
<p>Create a new image picker controller referring to the camera:</p>
<pre><code>var imagePicker = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.Camera };
</code></pre>
<p>Present the image picker controller, as soon as the <code>ShouldTakePicture</code> event is raised:</p>
<pre><code>App.Instance.ShouldTakePicture += () => PresentViewController(imagePicker, true, null);
</code></pre>
<p>After taking the picture, save it to the <code>MyDocuments</code> folder and call the shared <code>ShowImage</code> method:</p>
<pre><code>imagePicker.FinishedPickingMedia += (sender, e) => {
var filepath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "tmp.png");
var image = (UIImage)e.Info.ObjectForKey(new NSString("UIImagePickerControllerOriginalImage"));
InvokeOnMainThread(() => {
image.AsPNG().Save(filepath, false);
App.Instance.ShowImage(filepath);
});
DismissViewController(true, null);
};
</code></pre>
<p>And finally, we need to handle a cancellation of the image taking process:</p>
<pre><code>imagePicker.Canceled += (sender, e) => DismissViewController(true, null);
</code></pre> |
40,650,338 | Valgrind on macOS Sierra | <p>I following this guide:</p>
<p><a href="http://valgrind.org/downloads/repository.html">valgrind installation guide</a></p>
<p>After I have downloading the package, and I have run the sh script, but when I launch the <code>make install</code> command, it couldn't create the folder because it don't have the permission (even though I have used the <code>sudo</code> command).</p>
<p>Furthermore I tried with brew but I have this error: </p>
<blockquote>
<p>valgrind: This formula either does not compile or function as expected on macOS
versions newer than El Capitan due to an upstream incompatibility.</p>
<p>Error: An unsatisfied requirement failed this build.</p>
</blockquote> | 40,713,782 | 5 | 2 | null | 2016-11-17 08:52:02.61 UTC | 8 | 2022-04-04 17:03:55.577 UTC | null | null | null | null | 6,608,222 | null | 1 | 46 | valgrind|macos-sierra | 69,610 | <p>You can download Valgrind's latest version from their <a href="http://www.valgrind.org/downloads/current.html#current">website</a>. Then, you can just <code>./autogen.sh</code> to install Valgrind. I personally did not encounter anything needed to <code>make</code>. </p>
<p>However, the sad news is, even the most recent version of Valgrind is not very usable on Mac OS Sierra. The reason is that Apple has not released the part of the source code that makes Valgrind crash, without which, the Valgrind maintainers can hardly do anything. You can read more about the discussion around the issue <a href="https://bugs.kde.org/show_bug.cgi?id=365327">here</a> .</p>
<p>Because Mac OS kernel is under <a href="https://en.wikipedia.org/wiki/Apple_Public_Source_License">Apple Public Source License</a>, it has to be open-sourced someday. Thus, a Sierra-complitable version of Valgrind is only a matter of time.</p>
<p>Currently, I use Valgrind under Linux. This is all I can suggest now.</p> |
20,970,672 | How to specify character literal in groovy? | <p>How do I specify a character literal in groovy since both 'a' and "a" result in string?</p>
<p>I do not want to declare a character variable just for this purpose.</p> | 20,970,848 | 4 | 0 | null | 2014-01-07 11:38:54.337 UTC | 1 | 2018-01-18 13:00:54.44 UTC | null | null | null | null | 1,345,655 | null | 1 | 48 | groovy | 23,838 | <p>If this is for a variable, you can also define the type, so:</p>
<pre><code>import java.awt.image.*
new BufferedImage( 1, 1, BufferedImage.TYPE_INT_RGB ).with {
createGraphics().with {
// Declare the type
char aChar = 'a'
// Both ways are equivalent and work
assert fontMetrics.charWidth( aChar ) == fontMetrics.charWidth( 'a' as char )
dispose()
}
}
</code></pre>
<p>(apologies for the long example, but I had brain freeze, and couldn't think of a different standard java function that takes a <code>char</code>) ;-)</p>
<p>This also goes against the second line of the question, but I thought I'd add it for completeness</p> |
21,170,395 | How to include a library module dependency in an Android Studio project? | <p>I am migrating a project from Eclipse to AndroidStudio. I have a project used as a lib in this project. This lib is called PullToRefresh.</p>
<p>I've tried many ways to import this project to AS, but anyting I try works.</p>
<p>In my project I have this folder structure:</p>
<pre><code>Project Root
+-- app
| +-- builds
| +-- libs
| | +-- PullToRefresh (my lib project)
| +-- src
| | +-- main (java code and resources)
</code></pre>
<p>In the build.gradle, I've tried to do this:</p>
<pre><code>dependencies {
compile project(":libs:PullToRefresh")
}
</code></pre>
<p>But I'm getting this error message:</p>
<pre><code>Gradle 'my_project' project refresh failed: Project with path ':libs:PullToRefresh'
could not be found in project ':app'
</code></pre> | 21,170,626 | 2 | 0 | null | 2014-01-16 18:53:51.017 UTC | 10 | 2019-05-30 13:28:06.867 UTC | 2015-10-10 02:03:28.137 UTC | null | 1,771,682 | null | 1,771,682 | null | 1 | 18 | android|android-studio|gradle|android-gradle-plugin|build.gradle | 63,850 | <p>Android Studio works on <strong>project-modules</strong> concept,All your modules should be inside a root directory(Your Project Directory). One module can be depended on other module/modules. Your libraries are considered as different modules under same project and your main module(app in your case) depends on them.</p>
<p>Change your project structure a little bit :</p>
<pre><code>Project Root
+-- libs
+-- PullToRefresh (my lib project)
+-- app
| +-- builds
| +-- src
| | +-- main (java code and resources)
+-- .....
+--settings.gradle
</code></pre>
<p>Include this line in your <code>settings.gradle</code></p>
<pre><code>include ':libs:PullToRefresh'
</code></pre>
<p>Your build.gradle looks fine. I suggest you to change your directory name from libs to library because use libs for your jar dependency not for module dependencies.</p>
<p>and keep this in your main module's build.gradle file :</p>
<pre><code>dependencies {
compile project(":libs:PullToRefresh")
}
</code></pre> |
47,795,937 | How docker handles multiple mount types? | <p>This post is somewhat lenglthy but bear with me for a while...</p>
<p>Suppose you have an app that sits in <code>/app</code> in your local (host) filesystem with the following structure</p>
<pre><code>app
|-- index.php
|-- foo
| `-- file-h1
`-- bar
`-- file-h2
</code></pre>
<p>Now suppose we have an image (tagged <code>myrepo/app</code>) that exploits the following data structure</p>
<pre><code>opt
|-- app
| `-- foo
| `-- file-c1
</code></pre>
<p>If we run a container from that image by mounting host's <code>/app</code> to container's <code>/opt/app</code> as follows</p>
<pre><code>docker container run \
-v /app:/opt/app \
myrepo/app
</code></pre>
<p>The resulting data structure of the container will be the following</p>
<pre><code>opt
|-- app
| |-- index.php
| |-- foo
| | `-- file-h1
| `-- bar
| `-- file-h2
</code></pre>
<p>So far, so good...</p>
<h3>Running container with multiple mounts (both bind-mounts and volumes)</h3>
<p>Now, lets say that we want to use <strong>both</strong> a <strong>named volume</strong> called <code>data</code> to be mounted on <code>/opt/app/foo</code> and a <strong>bind-mount</strong> for mounting <code>/app</code> to <code>/opt/app</code></p>
<pre><code>docker container run \
-v /app:/opt/app \
-v data:/opt/app/foo
myrepo/app
</code></pre>
<p>The resulting data structure inside the container will be:</p>
<pre><code>opt
|-- app
| |-- index.php
| |-- foo
| | `-- file-c1
| `-- bar
| `-- file-h2
</code></pre>
<p>As it is stated in various posts (like <a href="https://github.com/moby/moby/issues/26051#issuecomment-242847347" rel="nofollow noreferrer">this</a> and <a href="https://github.com/moby/moby/issues/19120#issuecomment-169330570" rel="nofollow noreferrer">this</a>) the docker mounts are performed in lexicographic order (i.e shortest path first). According to this, I would expect docker first to execute the bind-mount (<code> -v /app:/opt/app</code>) and then the volume (<code>-v data:/opt/app/foo</code>).</p>
<p>Hence, I would <em>expect</em> that the contents of host's <code>/app</code> would replace/obscure the contents of container's <code>/opt/app</code> and thus <code>file-h1</code> to be inside <code>/opt/app/foo</code>. Finally, <code>file-h1</code> would be <a href="https://docs.docker.com/engine/admin/volumes/#tips-for-using-bind-mounts-or-volumes" rel="nofollow noreferrer">copied</a> in the newly created <code>data</code> volume and the volume would be mounted on <code>/opt/app/foo</code> (so <code>file-h1</code> should be shown instead of <code>file-c1</code> )</p>
<p>My questions raised when I tried to understand <a href="https://stackoverflow.com/a/38601156/2235814">this</a> answer on SO</p> | 47,873,699 | 1 | 0 | null | 2017-12-13 14:51:49.24 UTC | 11 | 2021-11-23 07:34:58.123 UTC | 2021-11-23 07:34:58.123 UTC | null | 2,235,814 | null | 2,235,814 | null | 1 | 17 | docker|docker-compose | 3,612 | <p>Finally, and with a lot of help by github user <a href="https://github.com/moby/moby/issues/19120#issuecomment-352450375" rel="noreferrer">cpuguy83</a>, I figured out <em>what actually docker engine does when we try to run a container that uses multiple mounts of different type (e.g both a <strong>bind-mount</strong> and a <strong>volume</strong>)</em> as, for instance:</p>
<pre><code>docker container run \
-v /app:/opt/app \
-v data:/opt/app/foo
myrepo/app
</code></pre>
<p>The key point to understand here is that docker executes the process in <strong>two steps</strong> that are done in the following order:</p>
<ol>
<li><p>First, it creates a new storage-space (i.e. volume) in the host filesystem (<code>... data/</code>) for the container to persist files and then (since that newly created volume is empty) it <a href="https://docs.docker.com/engine/admin/volumes/#good-use-cases-for-tmpfs-mounts" rel="noreferrer">copies</a> the container's files (i.e whatever is inside <code>/opt/app/foo/*</code>) to the volume's storage location (<code>... data/</code>)</p></li>
<li><p>Then after that, it performs all mounts (binds, volumes, tmpfs mounts, etc... are all lumped together) in lexicographic order (first mounts <code>/app</code> to <code>/opt/app</code> then <code>... data/</code> to <code>/opt/app/foo</code>)</p></li>
</ol>
<p>So, because of that, when we run the container with the mounts in our example, the docker <strong>first</strong> will copy the <code>file-c1</code> to the <code>... data/</code> location in the host filesystem and <strong>second</strong> it will mount first the contents of host's <code>/app</code> to the container's <code>/opt/app</code> and then the host's <code>... data/</code> (which contains <code>file-c1</code>) to container's <code>/opt/app/foo</code> overwriting/obscuring its contents (i.e overwriting <code>file-h1</code> with <code>file-c1</code>). Therefore, if we take a look inside the running container after the mounts are done, the result will be the following:</p>
<pre><code>opt
|-- app
| |-- index.php
| |-- foo
| | `-- file-c1
| `-- bar
| `-- file-h2
</code></pre> |
46,837,936 | ORA-00909: invalid number of arguments | <p>Maybe I am putting the parenthesis wrong or a wrong comma? I know this is a fairly novice question so I apologize in advance. I originally had this code:</p>
<pre><code>es3.last_name || ', ' ||SUBSTR(es3.first_name,1,1)
</code></pre>
<p>But es3 was a Left Outer Join so all the blanks were showing the ', ' so I tried this below and am getting the ERROR</p>
<blockquote>
<p>ORA-00909: invalid number of arguments </p>
</blockquote>
<pre><code>NVL(es3.last_name, ' ' , es3.last_name || ', ' ||SUBSTR(es3.first_name,1,1))
</code></pre>
<p>Thanks!</p> | 46,838,032 | 3 | 0 | null | 2017-10-19 19:55:21.66 UTC | null | 2017-10-19 20:34:51.593 UTC | 2017-10-19 20:34:51.593 UTC | null | 330,315 | null | 7,512,210 | null | 1 | 4 | sql|oracle | 46,714 | <p>From the documentation:</p>
<blockquote>
<p>The syntax for the NVL function in Oracle/PLSQL is:</p>
<p><code>NVL( string1, replace_with )</code></p>
</blockquote>
<p>You are feeding it 3 arguments, hence the error message. I believe you want this instead:</p>
<pre><code>CASE WHEN es3.last_name IS NULL
THEN ''
ELSE es3.last_name || ', ' ||SUBSTR(es3.first_name,1,1)
END
</code></pre> |
5,936,181 | gcc -g vs not -g and strip vs not strip, performance and memory usage? | <p>If binary file size is not an issue, are there any drawbacks using -g and not strip binaries that are to be run in a performance critical environment? I have a lot of disk space but the binary is cpu intensive and uses a lot of memory. The binary is loaded once and is alive for several hours.</p>
<p>EDIT:</p>
<p>The reason why I want to use binaries with debugging information is to generate useful core dumps in case of segmentation faults.</p> | 5,936,606 | 1 | 2 | null | 2011-05-09 11:22:58.797 UTC | 15 | 2011-05-09 12:04:04.02 UTC | 2011-05-09 11:33:45.23 UTC | null | 300,963 | null | 300,963 | null | 1 | 40 | c|optimization|gcc|strip | 6,373 | <p>The ELF loader loads <em>segments</em>, not <em>sections</em>; the mapping from sections to segments is determined by the linker script used for building the executable.</p>
<p>The default linker script does not map debug sections to any segment, so this is omitted.</p>
<p>Symbol information comes in two flavours: static symbols are processed out-of-band and never stored as section data; dynamic symbol tables are generated by the linker and added to a special segment that is loaded along with the executable, as it needs to be accessible to the dynamic linker. The <code>strip</code> command only removes the static symbols, which are never referenced in a segment anyway.</p>
<p>So, you can use full debug information through the entire process, and this will not affect the size of the executable image in RAM, as it is not loaded. This also means that the information is not included in core dumps, so this does not give you any benefit here either.</p>
<p>The <code>objcopy</code> utility has a special option to copy only the debug information, so you can generate a second ELF file containing this information and use stripped binaries; when analyzing the core dump, you can then load both files into the debugger:</p>
<pre><code>objcopy --only-keep-debug myprogram myprogram.debug
strip myprogram
</code></pre> |
25,291,607 | Symfony2 - How to stop Form->handleRequest from nulling fields that don't exist in post data | <p>I've got a form built in Symfony and when rendered in the view, the html form may or may not contain all of the fields in the form object (the entity sort of has a couple of different states and not all fields are rendedered in the view).</p>
<p>The problem is that when the form is processed in the submit handler, via handleRequest() method of the form object, it resets any properties in the entity that are not present in the post data to null, blowing away any existing value.</p>
<p>Is there any way to tell Symfony not to be so stupid and only process the fields present in the POST data?</p>
<p>Or do I have to clone the entity before the handleRequest call and then loop over the POST values and copy the related values from the post-handleRequest entity over to the pre-handleRequest clone of the entity, so I preserve the fields that are not in the POST data.</p>
<p>phew! as you can see, its a bit of a daft solution, to a bit of a daft problem, tbh. </p>
<p>I could understand symfony doing this if the entity was in effect a newly created object, but its been loaded from the DB and then handleRequest called - it should be sensible enough to know the object has already been initialised and only set the fields passed in the POST data.</p>
<p>Thanks for any help.</p>
<p>Regards</p>
<p>Steve.</p> | 25,295,370 | 2 | 0 | null | 2014-08-13 16:37:31.1 UTC | 7 | 2014-08-13 21:12:03.18 UTC | null | null | null | null | 1,484,864 | null | 1 | 30 | php|forms|symfony | 12,819 | <p>In short, don't use <code>handleRequest</code>.</p>
<p>You should use <code>submit</code> directly instead along with the <code>clearMissing</code> parameter set to false.</p>
<p><kbd>Symfony/Component/Form/FormInterface</kbd></p>
<pre><code>/**
* Submits data to the form, transforms and validates it.
*
* @param null|string|array $submittedData The submitted data.
* @param bool $clearMissing Whether to set fields to NULL
* when they are missing in the
* submitted data.
*
* @return FormInterface The form instance
*
* @throws Exception\AlreadySubmittedException If the form has already been submitted.
*/
public function submit($submittedData, $clearMissing = true);
</code></pre>
<p>When you use <code>handleRequest</code> it works out what data you are wanting the submit and then submits it using <code>$form->submit($data, 'PATCH' !== $method);</code>, meaning that unless you have submitted the form using the <code>PATCH</code> method then it will clear the fields.</p>
<p>To submit the form yourself without clearing your can use...</p>
<pre><code>$form->submit($request->get($form->getName()), false);
</code></pre>
<p>.. which get the form data array from the request and submit it directly, but with the clear missing fields parameter set to false.</p> |
25,163,593 | Matplotlib chart does not display in PyCharm | <p>I run the following code in PyCharm 3.4.1, and it highlighted <code>%matplotlib inline</code> showing syntax error, and I delete the first line, and run, I expect it will prompt me some charts, but it runs normally with <code>Process finished with exit code 0</code>, and no charts is showing.</p>
<p>My question is:
1. What is <code>%matplotlib inline</code> use for;
2. How to let pycharm shows matplotlib chart?</p>
<pre><code>%matplotlib inline
from IPython.core.pylabtools import figsize
import numpy as np
from matplotlib import pyplot as plt
figsize(11, 9)
import scipy.stats as stats
dist = stats.beta
n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]
data = stats.bernoulli.rvs(0.5, size=n_trials[-1])
x = np.linspace(0, 1, 100)
# For the already prepared, I'm using Binomial's conj. prior.
for k, N in enumerate(n_trials):
sx = plt.subplot(len(n_trials) / 2, 2, k + 1)
plt.xlabel("$p$, probability of heads") \
if k in [0, len(n_trials) - 1] else None
plt.setp(sx.get_yticklabels(), visible=False)
heads = data[:N].sum()
y = dist.pdf(x, 1 + heads, 1 + N - heads)
plt.plot(x, y, label="observe %d tosses,\n %d heads" % (N, heads))
plt.fill_between(x, 0, y, color="#348ABD", alpha=0.4)
plt.vlines(0.5, 0, 4, color="k", linestyles="--", lw=1)
leg = plt.legend()
leg.get_frame().set_alpha(0.4)
plt.autoscale(tight=True)
plt.suptitle("Bayesian updating of posterior probabilities",
y=1.02,
fontsize=14)
plt.tight_layout()
</code></pre> | 25,163,682 | 6 | 0 | null | 2014-08-06 14:53:00.017 UTC | 13 | 2022-04-25 19:48:31.467 UTC | null | null | null | null | 1,497,720 | null | 1 | 35 | python|matplotlib|pycharm | 65,093 | <p>The <code>%</code> notation is for <a href="http://ipython.org/ipython-doc/dev/interactive/tutorial.html#magic-functions">magic functions</a>. The particular magic function and argument you reference, <code>%matplotlib inline</code>, is meant for an <a href="http://nbviewer.ipython.org/github/ipython/ipython/blob/1.x/examples/notebooks/Part%203%20-%20Plotting%20with%20Matplotlib.ipynb">IPython notebook</a> session. You will get a syntax error using magic functions in a normal python session. </p>
<p>The <code>%matplotlib</code> magic function is meant to specify a backend for matplotlib and the argument <code>inline</code> will produce an error if you are not in an IPython notebook session. </p>
<p>To show your plot you should use <code>plt.show</code> for an interactive window or <code>plt.savefig</code> to save it to file. For example, </p>
<pre><code>plt.show()
</code></pre>
<p>or</p>
<pre><code>plt.savefig( 'myfig.png' )
</code></pre> |
26,262,029 | Objective C to Swift header file with multiple targets | <p>I'm successfully calling my Swift classes from Objective C (for target 'MyApp') via the import statement:</p>
<pre><code>#import "MyApp-Swift.h"
</code></pre>
<p>I've now created a new target called "MyAppLite"</p>
<p>When I compile the new target, I get errors because "MyApp-Swift.h" is required by the code, but the compiler is creating "MyAppLite-Swift.h"</p>
<p>So, I need to create a conditional Swift/ObjC header <code>#import</code> for the target I'm compiling against. </p>
<p>How can this be done, or is there a better way?</p> | 27,411,394 | 7 | 0 | null | 2014-10-08 16:39:54.757 UTC | 16 | 2021-03-10 08:35:31.467 UTC | 2014-10-10 01:24:50.853 UTC | null | 1,402,846 | null | 876,057 | null | 1 | 76 | objective-c|swift|header-files|target | 20,440 | <p>It is also possible to set the <code>Product Module Name</code> setting in <code>Build Settings</code> to be the same across your modules (I set it to <code>$(PROJECT_NAME)</code>), so that the <code><project>-Swift.h</code> file that is generated has the same name across all modules. This eliminates the need for adding/checking preprocessor macros. </p> |
24,856,811 | Why iterator.remove does not throw ConcurrentModificationException | <p>What does <code>iterator.remove()</code> do differently from <code>list.remove()</code>, so that iterator does not throw an exception and <code>list.remove()</code> does throw one? In the end, both are modifying the collection size.</p>
<p>Please ignore multi-threading here. I am just talking about a for-each loop and an iterator loop. As far as I know, a for-each loop creates an iterator only internally.</p>
<p>I am confused.</p> | 25,131,943 | 6 | 0 | null | 2014-07-21 02:10:50.793 UTC | 12 | 2021-12-29 10:18:25.94 UTC | 2019-10-06 12:22:51.98 UTC | null | 8,075,923 | null | 2,419,434 | null | 1 | 23 | java|collections|foreach|iterator | 20,696 | <p><code>ConcurrentModificationException</code> is not thrown by <code>Iterator.remove()</code> because that is the <em>permitted</em> way to modify an collection while iterating. This is what the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#remove--" rel="nofollow noreferrer">javadoc</a> for <code>Iterator</code> says:</p>
<blockquote>
<p>Removes from the underlying collection the last element returned by this iterator (optional operation). This method can be called only once per call to next(). <strong>The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.</strong></p>
</blockquote>
<p>If you change the collection being iterated any other way, then you are liable to get an exception, depending on the implementation of iterator, and the collection (or whatever) that you are iterating. (Some collection classes won't give you a <code>ConcurrentModificationException</code>: check the respective javadocs to see how they specify the behavior of <em>their</em> iterators) </p>
<p>You are also liable to get an exception if you have two iterators on the same collection, and you remove via one of them.</p>
<hr>
<blockquote>
<p>What iterator.remove does different from list.remove that iterator does not throw exception while list.remove does throw?</p>
</blockquote>
<p>Reason #1. If you had a non-concurrent collection being updated simultaneously from two places on the same call stack, the behavior would break the design invariant for the iteration<sup>1</sup>. An iteration of a non-concurrent collection is guaranteed to see all of the elements in the collection exactly once. (By contrast, with concurrent collections these guarantees are relaxed.)</p>
<p>Reason #2. Non-concurrent collection types are not implemented to be thread-safe. Therefore, you could have race conditions and memory anomalies if the collection and iterator are used to update the collection by different threads. This is not <em>strong</em> reason because you will have these problems anyway. However, having the updates happening in two different ways makes the problem worse.</p>
<hr>
<blockquote>
<p>I am just talking about for-each loop and iterator loop. As far as I know for-each loop internally create iterator only.</p>
</blockquote>
<p>That is correct. A for-each loop is really just syntactic sugar for a <code>while</code> loop using an iterator.</p>
<p>On the other hand, if you use a loop like this:</p>
<pre><code> for (int i = 0; i < list.size(); i++) {
if (...) {
list.remove(i);
}
}
</code></pre>
<p>you won't get <code>ConcurrentModificationException</code>, but you will need to adjust the index variable for the elements that you delete, and updates by another thread are liable to cause you to skip elements or visit them more than once<sup>2</sup>.</p>
<hr>
<p><sup>1 - To achieve "exactly once" iteration behavior, when you remove an element via the collection object, the iterator data structure would need to be updated to keep it in step with what has happened to the collection. This is not possible in the current implementations because they don't keep links to the outstanding iterators. And if they did, they would need to use <code>Reference</code> objects or risk memory leaks.</sup></p>
<p><sup>2 - Or even get an <code>IndexOutOfBoundsException</code>. And if the collection is not concurrent / properly synchronized, you can get worse problems.</sup></p> |
22,429,744 | How to setup route for websocket server in express? | <p>I have a setup similar to this one:</p>
<pre><code>var WebSocketServer = require("ws").Server,
express = require("express"),
http = require("http"),
app = express(),
server = http.createServer(app);
app.post("/login", login);
app.get("/...", callSomething);
// ...
server.listen(8000);
var wss = new WebSocketServer({server: server});
wss.on("connection", function(ws){
// ...
});
</code></pre>
<p>I would like to put the WebSocketServer under a specific path which may for instance be <code>"...com/whatever"</code>. The question is how can I set the path? Is it possible?</p> | 22,429,868 | 6 | 0 | null | 2014-03-15 21:08:26.937 UTC | 26 | 2022-09-08 05:03:42.117 UTC | 2017-03-10 01:48:21.773 UTC | null | 3,000,068 | null | 1,244,005 | null | 1 | 66 | javascript|node.js|express|websocket | 104,270 | <p>You'll want to use the <code>path</code> option:</p>
<pre><code>var wss = new WebSocketServer({server: server, path: "/hereIsWS"});
</code></pre>
<p>See full documentation <a href="https://github.com/einaros/ws/blob/master/doc/ws.md" rel="noreferrer">here</a></p> |
2,690,865 | Visibility attribute question | <p>What is the difference between </p>
<p><code>$("#myid").attr("style", "visibility: hidden")</code> </p>
<p>and </p>
<p><code>$("#myid").css("visibility", "hidden")</code> </p>
<p>? </p> | 2,690,892 | 3 | 0 | null | 2010-04-22 12:52:23.22 UTC | 6 | 2010-04-22 14:38:11 UTC | 2010-04-22 14:38:11 UTC | null | 45,433 | null | 247,243 | null | 1 | 26 | jquery|html|css | 87,754 | <p>Doing this:</p>
<pre><code>$("#myid").attr("style", "visibility: hidden")
</code></pre>
<p>Will leave <strong>only</strong> this style attribute, while doing this:</p>
<pre><code>$("#myid").css("visibility", "hidden")
</code></pre>
<p>Will <strong>add</strong> (or set) this style attribute.</p>
<p>Here's an example, the first will <strong>always</strong> result in this:</p>
<pre><code>style="visibility: hidden;"
</code></pre>
<p>The second just adds <code>visibility</code> so your style may now be: </p>
<pre><code>style="width: 50px; color: red; visibility: hidden;"
</code></pre> |
3,118,829 | Why request.getRemoteAddr() returns ipv4 or ipv6 depending on context (post query or ajax query) | <p>I've donne a web app with Spring/GWT that uses Flash to upload files.</p>
<p>When I send an ajax request with GWT and try to get the user ip address, I get an ipv4 address like: 127.0.0.1 </p>
<p>but when I upload my files with flash (and so a post request on the same webapp) I get an ipv6 address 0:0:0:0:0:0:0:1</p>
<p>I use the same code to get the user ip which is: </p>
<pre><code>ServletRequestAttributes att = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
att.getRequest().getRemoteAddr();
</code></pre>
<p>The problem is that I use a signature which uses the ip address to be sure that user can upload files (due to bug with session lost when uploading with flash) and the ip address changes when I use ajax or Post via flash.</p>
<p>What's the problem and how can I get the same ip format ?</p>
<p>thanks</p> | 21,922,867 | 3 | 1 | null | 2010-06-25 14:31:52.46 UTC | 13 | 2014-12-01 05:06:37.54 UTC | null | null | null | null | 231,456 | null | 1 | 28 | java|spring|jakarta-ee|ipv6|ipv4 | 37,515 | <p>You can fix it by starting your server with this flag</p>
<pre><code>-Djava.net.preferIPv4Stack=true
</code></pre> |
2,699,239 | Dynamic attributes with Rails and Mongoid | <p>I'm learning MongoDB through the Mongoid Ruby gem with Rails (Rails 3 beta 3), and I'm trying to come up with a way to create dynamic attributes on a model based on fields from another model, which I thought a schema-less database would be a good choice for.</p>
<p>So for example, I'd have the models:</p>
<pre><code>class Account
include Mongoid::Document
field :name, :type => String
field :token, :type => String
field :info_needed, :type => Array
embeds_many :members
end
class Member
include Mongoid::Document
embedded_in :account, :inverse_of => :members
end
</code></pre>
<p>I'm looking to take the "info_needed" attribute of the Account model and created dynamic attributes on the Member model based on what's inside. If club.info_needed was ["first_name", "last_name"], I'm trying to create a form that would save first_name and last_name attributes to the Member model.</p>
<p>However, upon practice, I just keep getting "undefined method first_name=" errors on the Member model when trying to do this. I know MongoDB can handle dynamic attributes per record, but how can I get Mongoid to do this without an undefined method error?</p> | 2,897,708 | 4 | 1 | null | 2010-04-23 14:16:26.77 UTC | 12 | 2012-07-23 00:16:59.673 UTC | null | null | null | null | 227,528 | null | 1 | 15 | ruby-on-rails|mongodb|mongoid|dynamic-attributes | 19,451 | <p>Mongoid doesn't really support it. </p>
<p>I happen to have <a href="http://groups.google.com/group/mongoid/browse_thread/thread/bbab975df6a40c7/632792f360f68d3d?lnk=gst&q=dynamic#632792f360f68d3d" rel="nofollow noreferrer">asked</a> this at Mongoid group myself.</p>
<p>It is possible when you create new document, like this:</p>
<p><code>account = Account.new(:some_dynamic_field => "...")</code></p> |
2,363,458 | StructureMap singleton usage (A class implementing two interface) | <pre><code>public interface IInterface1
{
}
public interface IInterface2
{
}
public class MyClass : IInterface1, IInterface2
{
}
...
ObjectFactory.Initialize(x =>
{
x.For<IInterface1>().Singleton().Use<MyClass>();
x.For<IInterface2>().Singleton().Use<MyClass>();
});
var x = ObjectFactory.GetInstance<IInterface1>();
var y = ObjectFactory.GetInstance<IInterface2>();
</code></pre>
<p>I get two different MyClass instances with the above code. How can I get one?</p> | 2,366,838 | 4 | 0 | null | 2010-03-02 13:43:23.863 UTC | 12 | 2012-04-04 11:49:05.493 UTC | 2010-03-02 13:44:21.617 UTC | null | 20,402 | James | null | null | 1 | 37 | c#|singleton|structuremap | 15,831 | <p>You can use the Forward<,>() registration to tell StructureMap to resolve a type using the resolution of a different type. This should do what you expect:</p>
<pre><code>ObjectFactory.Initialize(x =>
{
x.For<IInterface1>().Singleton().Use<MyClass>();
x.Forward<IInterface1, IInterface2>();
});
</code></pre> |
31,727,049 | Let user delete a selected fabric js object | <p>I have a simple fabric js based application where I will let users add shapes connect them and animate them.</p>
<p>Following is my JS </p>
<pre><code>var canvas;
window.newAnimation = function(){
canvas = new fabric.Canvas('canvas');
}
window.addRect = function(){
var rect = new fabric.Rect({
left: 100,
top: 100,
fill: 'red',
width: 20,
height: 20,
});
canvas.add(rect);
}
window.addCircle = function(){
var circle = new fabric.Circle({
radius: 20, fill: 'green', left: 100, top: 100
});
canvas.add(circle);
}
</code></pre>
<p>This is my <a href="http://jsfiddle.net/wwerpuj9/" rel="noreferrer">Fiddle</a>. You can click on new animation and then add objects as of now.</p>
<p>I want the user to select some object and then also be able to delete it I am not sure how. I found this <a href="https://stackoverflow.com/questions/11829786/delete-multiple-objects-at-once-on-a-fabric-js-canvas-in-html5">Delete multiple Objects at once on a fabric.js canvas in html5</a> But i was not able to implement it successfully. I basically want users to be able to select an object and delete it.</p> | 31,728,950 | 8 | 0 | null | 2015-07-30 14:49:41.987 UTC | 7 | 2022-04-24 04:21:52.913 UTC | 2017-05-23 11:54:43.123 UTC | user5049061 | -1 | user5049061 | null | null | 1 | 37 | javascript|html|canvas|fabricjs | 47,837 | <p>Edit: This is for older versions now.</p>
<p>You can use the remove() method, eg.</p>
<pre><code>window.deleteObject = function() {
canvas.getActiveObject().remove();
}
</code></pre>
<p><a href="http://jsfiddle.net/wwerpuj9/2/" rel="noreferrer">jsfiddle</a> </p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.