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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
936,684 | Getting the class name from a static method in Java | <p>How can one get the name of the class from a static method in that class. For example</p>
<pre><code>public class MyClass {
public static String getClassName() {
String name = ????; // what goes here so the string "MyClass" is returned
return name;
}
}
</code></pre>
<p>To put it in context, I actually want to return the class name as part of a message in an exception.</p> | 936,696 | 15 | 1 | null | 2009-06-01 20:42:16.66 UTC | 62 | 2022-08-19 13:54:27.897 UTC | null | null | null | null | 3,898 | null | 1 | 282 | java|static | 208,918 | <p>In order to support refactoring correctly (rename class), then you should use either:</p>
<pre><code> MyClass.class.getName(); // full name with package
</code></pre>
<p>or (thanks to <a href="https://stackoverflow.com/questions/936684/getting-the-class-name-from-a-static-method-in-java/936715#936715">@James Van Huis</a>):</p>
<pre><code> MyClass.class.getSimpleName(); // class name and no more
</code></pre> |
215,026 | The located assembly's manifest definition does not match the assembly reference | <p>I am trying to run some unit tests in a C# Windows Forms application (Visual Studio 2005), and I get the following error:</p>
<blockquote>
<p>System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)**</p>
<p>at x.Foo.FooGO()</p>
<p>at x.Foo.Foo2(String groupName_) in Foo.cs:line 123</p>
<p>at x.Foo.UnitTests.FooTests.TestFoo() in FooTests.cs:line 98**</p>
<p>System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.203, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)</p>
</blockquote>
<p>I look in my references, and I only have a reference to <code>Utility version 1.2.0.203</code> (the other one is old).</p>
<p>Any suggestions on how I figure out what is trying to reference this old version of this DLL file?</p>
<p>Besides, I don't think I even have this old assembly on my hard drive.
Is there any tool to search for this old versioned assembly?</p> | 215,054 | 60 | 1 | null | 2008-10-18 13:16:26.373 UTC | 97 | 2022-09-07 11:00:17.5 UTC | 2020-06-20 09:12:55.06 UTC | Adam Bellaire | -1 | akantro | 4,653 | null | 1 | 863 | c#|reference|compiler-errors|dependencies|version | 1,213,297 | <p>The .NET Assembly loader:</p>
<ul>
<li>is unable to find 1.2.0.203</li>
<li>but did find a 1.2.0.200</li>
</ul>
<p>This assembly does not match what was requested and therefore you get this error.</p>
<p>In simple words, it can't find the assembly that was referenced. Make sure it can find the right assembly by putting it in the GAC or in the application path.</p>
<p>run below command to add the assembly dll file to GAC:</p>
<pre class="lang-bash prettyprint-override"><code>gacutil /i "path/to/my.dll"
</code></pre>
<p>Also see <a href="https://docs.microsoft.com/archive/blogs/junfeng/the-located-assemblys-manifest-definition-with-name-xxx-dll-does-not-match-the-assembly-reference" rel="nofollow noreferrer">https://docs.microsoft.com/archive/blogs/junfeng/the-located-assemblys-manifest-definition-with-name-xxx-dll-does-not-match-the-assembly-reference</a>.</p> |
6,416,418 | include php script inside HTML | <p>I am a newbie and have never used PHP before. I want to execute PHP script from an HTML file on Linux. What do I need to do?</p>
<p>This is the content of my HTML file:</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>Testing Weather Data</TITLE>
</HEAD>
<BODY>
<div id="weather">
<p>Weather Information
<?php include "/home/tahoang/Desktop/weatherData.php"; ?>
</div>
</BODY>
</HTML>
</code></pre> | 6,416,457 | 5 | 1 | null | 2011-06-20 19:32:58.757 UTC | 5 | 2018-07-04 06:12:05.987 UTC | null | null | null | null | 801,807 | null | 1 | 3 | php|html|linux | 52,665 | <p>What output do you receive? Does it just show the PHP code?</p>
<p>I assume that's the case.</p>
<p>For a test, change the extension on the file to <code>.php</code> and run it again. Does it work now?</p>
<p>If so, you will need to associate PHP with <code>.html</code> and <code>.htm</code> files on your server.</p>
<p><strong>EDIT</strong></p>
<p>This is the line you want to add to your Apache config:</p>
<pre><code>AddType application/x-httpd-php .html
</code></pre> |
6,599,436 | As of 2011: Netbeans 7 or Eclipse Indigo for C++? | <p>This is basically a duplicate of:
<a href="https://stackoverflow.com/questions/308450/netbeans-or-eclipse-for-c">Netbeans or Eclipse for C++?</a></p>
<p>But, that question as 3+ years old, and a lot has changed since then.</p>
<p>I have a large code base with a custom (but Makefile based) build system. The areas I am specifically wondering about include:</p>
<ol>
<li>Syntax highlighting</li>
<li>Code navigation.</li>
<li>Code hints.</li>
<li>"ReSharper style" code helpers.</li>
<li>Documentation integration.</li>
<li>Debugger UI and features.</li>
</ol>
<p>Has anyone had the chance to evaluate both Netbeans and Eclipse?</p>
<p>EDIT: As a followup question, are any of the Netbeans users here concerned with its future given Oracle's recent bad history with "open" efforts? (Open Solaris, MySQL, Open Office)</p>
<p>Thank you</p> | 6,612,097 | 5 | 7 | null | 2011-07-06 15:58:06.863 UTC | 10 | 2011-12-25 22:46:10.68 UTC | 2017-05-23 10:33:19.14 UTC | null | -1 | null | 489,549 | null | 1 | 20 | c++|eclipse|netbeans|ide|eclipse-cdt | 7,236 | <p>I cannot comment on Netbeans, but I can offer you information on Eclipse. I work with C++ on UNIX systems, and I have started to use Eclipse when exploring large code bases that I know little about. I don't use it to build, but it would be easy to integrate our build system with it as one only needs commands.</p>
<p>Eclipse has most of what you are looking for: (I'm speaking of Eclipse/CDT)</p>
<ol>
<li><p>Not only can you completely customize your syntax highlighting, you can also have it format the code with templates. My company has a code standard for spacing, tabs and formatting of functions and conditional code, and with little effort I was able to modify an existing template to meet our code standards.</p></li>
<li><p>The navigation is not bad, if you highlight and hover over a variable, it shows you the definition in a small pop-up bubble. If you do the same for a type, it will you show you where the type is defined. For functions, it will show the first few lines of the implementation of the function, with an option to expand it and see the whole function. I find all of these nice for code discovery and navigation. You can also highlight a variable, and use a right-click menu option to jump to its declaration.</p></li>
<li><p>I suppose by code hints you are referring to something like intellisense? This is the main reason why I use Eclipse when looking over a large code base. Just hit the '.' or '->' and a second later you get your options. </p></li>
<li><p>The debugger UI is quite capable. You can launch gdb within the tool and it allows you to graphically move through your code just as you would in a tool like ddd or Visual C++. It offers standard features like viewing registers, memory, watching variables, etc.</p></li>
</ol>
<p>That being said, I have found some weaknesses. The first is that it doesn't really strongly support revision control systems outside of CVS and SVN very easily (integrated into the GUI). I found a plug-in for the system we use at my company, but it spews XML and Unicode garbage. It was easier to just use the revision control on the command line. I suspect this is the plug-in's issue and not Eclipse. I wish there were better tool integration though.</p>
<p>The second complaint is that for each project I have to manually setup the include directories and library paths. Perhaps with an environment variable this could be circumvented? Or I may just do not know how to set things up correctly. Then again if it is not obvious to a developer how to do this, I consider that a weakness of the tool.</p>
<p>All in all I like working with Eclipse. It is not my main editing environment, but I appreciate it for working on large code bases.</p> |
6,752,714 | If input value is blank, assign a value of "empty" with Javascript | <p>So I have an input field, if it's blank, I want its value to be the words "empty", but if there is any value inputted, I want the value to be the inputted value. I want to use javascript for this, any idea how this can be done?</p>
<p><strong>UPDATE:</strong> Sorry, I don't think I explained it too well. I don't mean placeholder text. I mean the captured value of it. So if it's blank, the captured val() for it should be "empty", if it's filled, the captured val() for it should be that val()</p> | 6,752,767 | 6 | 1 | null | 2011-07-19 19:09:02.03 UTC | 8 | 2021-02-23 22:07:30.53 UTC | 2013-09-08 08:59:25.447 UTC | null | 2,256,325 | null | 841,414 | null | 1 | 16 | javascript|forms|input | 148,967 | <p>If you're using pure JS you can simply do it like:</p>
<pre><code>var input = document.getElementById('myInput');
if(input.value.length == 0)
input.value = "Empty";
</code></pre>
<p>Here's a demo: <a href="http://jsfiddle.net/nYtm8/">http://jsfiddle.net/nYtm8/</a></p> |
6,433,492 | preg_match() vs strpos() for match finding? | <p>For <strong>single value check</strong>, which of both is preferred and why?</p>
<pre><code>$string == 'The quick brown fox jumps over the lazy dog';
if(strpos($string, 'fox') !== false){
// do the routine
}
# versus
if(preg_match('/fox/i', $string)){
// do the routine
}
</code></pre> | 6,433,513 | 6 | 2 | null | 2011-06-22 00:17:42.943 UTC | 6 | 2021-11-16 16:03:37.757 UTC | 2011-06-24 08:50:31.64 UTC | user456814 | null | null | 393,406 | null | 1 | 35 | php | 43,541 | <p>I would prefer the <code>strpos</code> over <code>preg_match</code>, because regexes are generally more expensive to execute.</p>
<p>According to the official php docs for <a href="http://php.net/manual/function.preg-match.php"><code>preg_match</code></a>:</p>
<blockquote>
<p>Do not use <code>preg_match()</code> if you only
want to check if one string is
contained in another string. Use
<code>strpos()</code> or <code>strstr()</code> instead as they
will be faster.</p>
</blockquote> |
6,682,451 | Animate scroll to ID on page load | <p>Im tring to animate the scroll to a particular ID on page load. I have done lots of research and came across this:</p>
<pre><code>$("html, body").animate({ scrollTop: $('#title1').height() }, 1000);
</code></pre>
<p>but this seems to start from the ID and animate to the top of the page?</p>
<p>The HTML (which is half way down the page) is simply:</p>
<pre><code><h2 id="title1">Title here</h2>
</code></pre> | 6,682,515 | 6 | 1 | null | 2011-07-13 16:42:18.647 UTC | 50 | 2021-03-04 16:09:55.593 UTC | 2016-11-02 17:35:10.66 UTC | null | 322,020 | null | 275,119 | null | 1 | 131 | jquery|scroll|jquery-animate | 331,787 | <p>You are only scrolling the height of your element. <a href="http://api.jquery.com/offset/">offset()</a> returns the coordinates of an element relative to the document, and <code>top</code> param will give you the element's distance in pixels along the y-axis:</p>
<pre><code>$("html, body").animate({ scrollTop: $('#title1').offset().top }, 1000);
</code></pre>
<p>And you can also add a delay to it:</p>
<pre><code>$("html, body").delay(2000).animate({scrollTop: $('#title1').offset().top }, 2000);
</code></pre> |
6,871,201 | Plot two histograms on single chart with matplotlib | <p>I created a histogram plot using data from a file and no problem. Now I wanted to superpose data from another file in the same histogram, so I do something like this</p>
<pre><code>n,bins,patchs = ax.hist(mydata1,100)
n,bins,patchs = ax.hist(mydata2,100)
</code></pre>
<p>but the problem is that for each interval, only the bar with the highest value appears, and the other is hidden. I wonder how could I plot both histograms at the same time with different colors.</p> | 6,873,956 | 13 | 0 | null | 2011-07-29 09:37:08.633 UTC | 94 | 2021-08-24 03:14:29.527 UTC | 2020-02-22 03:25:53.337 UTC | null | 12,526,884 | null | 171,546 | null | 1 | 328 | python|matplotlib|plot|histogram | 556,125 | <p>Here you have a working example:</p>
<pre><code>import random
import numpy
from matplotlib import pyplot
x = [random.gauss(3,1) for _ in range(400)]
y = [random.gauss(4,2) for _ in range(400)]
bins = numpy.linspace(-10, 10, 100)
pyplot.hist(x, bins, alpha=0.5, label='x')
pyplot.hist(y, bins, alpha=0.5, label='y')
pyplot.legend(loc='upper right')
pyplot.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/acUlv.png" alt="enter image description here"></p> |
41,668,813 | How to add and remove new layers in keras after loading weights? | <p>I am trying to do a transfer learning; for that purpose I want to remove the last two layers of the neural network and add another two layers. This is an example code which also output the same error.</p>
<pre><code>from keras.models import Sequential
from keras.layers import Input,Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers.core import Dropout, Activation
from keras.layers.pooling import GlobalAveragePooling2D
from keras.models import Model
in_img = Input(shape=(3, 32, 32))
x = Convolution2D(12, 3, 3, subsample=(2, 2), border_mode='valid', name='conv1')(in_img)
x = Activation('relu', name='relu_conv1')(x)
x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool1')(x)
x = Convolution2D(3, 1, 1, border_mode='valid', name='conv2')(x)
x = Activation('relu', name='relu_conv2')(x)
x = GlobalAveragePooling2D()(x)
o = Activation('softmax', name='loss')(x)
model = Model(input=in_img, output=[o])
model.compile(loss="categorical_crossentropy", optimizer="adam")
#model.load_weights('model_weights.h5', by_name=True)
model.summary()
model.layers.pop()
model.layers.pop()
model.summary()
model.add(MaxPooling2D())
model.add(Activation('sigmoid', name='loss'))
</code></pre>
<p>I removed the layer using <code>pop()</code> but when I tried to add its outputting this error </p>
<blockquote>
<p>AttributeError: 'Model' object has no attribute 'add'</p>
</blockquote>
<p>I know the most probable reason for the error is improper use of <code>model.add()</code>. what other syntax should I use?</p>
<p><strong>EDIT:</strong></p>
<p>I tried to remove/add layers in keras but its not allowing it to be added after loading external weights.</p>
<pre><code>from keras.models import Sequential
from keras.layers import Input,Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.layers.core import Dropout, Activation
from keras.layers.pooling import GlobalAveragePooling2D
from keras.models import Model
in_img = Input(shape=(3, 32, 32))
def gen_model():
in_img = Input(shape=(3, 32, 32))
x = Convolution2D(12, 3, 3, subsample=(2, 2), border_mode='valid', name='conv1')(in_img)
x = Activation('relu', name='relu_conv1')(x)
x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), name='pool1')(x)
x = Convolution2D(3, 1, 1, border_mode='valid', name='conv2')(x)
x = Activation('relu', name='relu_conv2')(x)
x = GlobalAveragePooling2D()(x)
o = Activation('softmax', name='loss')(x)
model = Model(input=in_img, output=[o])
return model
#parent model
model=gen_model()
model.compile(loss="categorical_crossentropy", optimizer="adam")
model.summary()
#saving model weights
model.save('model_weights.h5')
#loading weights to second model
model2=gen_model()
model2.compile(loss="categorical_crossentropy", optimizer="adam")
model2.load_weights('model_weights.h5', by_name=True)
model2.layers.pop()
model2.layers.pop()
model2.summary()
#editing layers in the second model and saving as third model
x = MaxPooling2D()(model2.layers[-1].output)
o = Activation('sigmoid', name='loss')(x)
model3 = Model(input=in_img, output=[o])
</code></pre>
<p>its showing this error</p>
<pre><code>RuntimeError: Graph disconnected: cannot obtain value for tensor input_4 at layer "input_4". The following previous layers were accessed without issue: []
</code></pre> | 41,670,915 | 4 | 1 | null | 2017-01-16 02:56:46.877 UTC | 31 | 2021-12-06 19:49:54.383 UTC | 2017-01-20 06:38:52.913 UTC | null | 996,366 | null | 996,366 | null | 1 | 75 | python|theano|keras|keras-layer | 96,689 | <p>You can take the <code>output</code> of the last model and create a new model. The lower layers remains the same.</p>
<pre><code>model.summary()
model.layers.pop()
model.layers.pop()
model.summary()
x = MaxPooling2D()(model.layers[-1].output)
o = Activation('sigmoid', name='loss')(x)
model2 = Model(input=in_img, output=[o])
model2.summary()
</code></pre>
<p>Check <a href="https://stackoverflow.com/questions/41378461/how-to-use-models-from-keras-applications-for-transfer-learnig/41386444#41386444">How to use models from keras.applications for transfer learnig?</a> </p>
<p><strong>Update on Edit:</strong></p>
<p>The new error is because you are trying to create the new model on global <code>in_img</code> which is actually not used in the previous model creation.. there you are actually defining a local <code>in_img</code>. So the global <code>in_img</code> is obviously not connected to the upper layers in the symbolic graph. And it has nothing to do with loading weights.</p>
<p>To better resolve this problem you should instead use <code>model.input</code> to reference to the input.</p>
<p><code>model3 = Model(input=model2.input, output=[o])</code></p> |
15,783,694 | How to remove Subscription from product list in developer console and what will be its effect on the old subscribed users? | <p>I want to remove the existing subscription product from product list. </p>
<p>How would I be able to perform so as I didn't found any option on my developer console to delete the subscriptions ?</p>
<p>Also if in any way possible it is allowed, then will it have any effect on the existing users who have purchased that subscription when they call for RESTORE_TRANSACTION from their app while communicating with Google Play ?</p> | 19,169,695 | 2 | 0 | null | 2013-04-03 09:32:36.9 UTC | 9 | 2022-06-27 17:29:10.537 UTC | null | null | null | null | 1,518,273 | null | 1 | 34 | android|in-app-billing|subscription|android-billing | 23,202 | <p>Unfortunately, It's not possible to remove a subscription product from the product list of the developer console. You can just remove the subscription product from the product list offered in your app to prevent users from seeing or purchasing it.</p> |
15,611,374 | Customize UITableView header section | <p>I want to customize <code>UITableView</code> header for each section. So far, I've implemented</p>
<pre><code>-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
</code></pre>
<p>this <code>UITabelViewDelegate</code> method. What I want to do is to get current header for each section and just add <code>UILabel</code> as a subview.</p>
<p>So far, I'm not able to accomplish that. Because, I couldn't find anything to get default section header. First question,<strong>is there any way to get default section header</strong>?</p>
<p>If it's not possible, I need to create a container view which is a <code>UIView</code> but,this time I need to set default background color,shadow color etc. Because, if you look carefully into section's header, it's already customized.</p>
<p>How can I get these default values for each section header?</p> | 15,611,529 | 24 | 4 | null | 2013-03-25 09:23:16.833 UTC | 50 | 2021-06-02 15:54:46.36 UTC | 2020-12-14 16:36:25.26 UTC | null | 1,265,393 | null | 1,248,444 | null | 1 | 147 | ios|objective-c|swift|uitableview | 270,105 | <p>You can try this:</p>
<pre><code> -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 18)];
/* Create custom view to display section header... */
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, tableView.frame.size.width, 18)];
[label setFont:[UIFont boldSystemFontOfSize:12]];
NSString *string =[list objectAtIndex:section];
/* Section header is in 0th index... */
[label setText:string];
[view addSubview:label];
[view setBackgroundColor:[UIColor colorWithRed:166/255.0 green:177/255.0 blue:186/255.0 alpha:1.0]]; //your background color...
return view;
}
</code></pre> |
50,237,516 | Proper fix for Java 10 complaining about illegal reflection access by jaxb-impl 2.3.0? | <p>We are looking at upgrading some legacy code to Java 10. As JAXB is not visible by default (EDIT: and the proper long term solution is <em>not</em> to circumvent the symptom using various JVM flags, but fix it properly) I have added this snippet to my pom.xml:</p>
<pre><code> <!-- https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
</code></pre>
<p>Unfortunately there is still a warning printed at startup to stderr. Apparently this is not the correct fix. </p>
<pre><code>WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.sun.xml.bind.v2.runtime.reflect.opt.Injector (file:/home/tra/.m2/repository/com/sun/xml/bind/jaxb-impl/2.3.0/jaxb-impl-2.3.0.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int)
WARNING: Please consider reporting this to the maintainers of com.sun.xml.bind.v2.runtime.reflect.opt.Injector
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
</code></pre>
<p>The full output from <code>--illegal-access=debug</code> is:</p>
<pre><code>WARNING: Illegal reflective access by com.sun.xml.bind.v2.runtime.reflect.opt.Injector (file:/home/tra/.m2/repository/com/sun/xml/bind/jaxb-impl/2.3.0/jaxb-impl-2.3.0.jar) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.getMethod(Injector.java:222)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.access$000(Injector.java:74)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector$1.run(Injector.java:175)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector$1.run(Injector.java:172)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.<clinit>(Injector.java:171)
at com.sun.xml.bind.v2.runtime.reflect.opt.AccessorInjector.prepare(AccessorInjector.java:81)
at com.sun.xml.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory.get(OptimizedAccessorFactory.java:179)
at com.sun.xml.bind.v2.runtime.reflect.Accessor$FieldReflection.optimize(Accessor.java:285)
at com.sun.xml.bind.v2.runtime.property.ArrayProperty.<init>(ArrayProperty.java:68)
at com.sun.xml.bind.v2.runtime.property.ArrayERProperty.<init>(ArrayERProperty.java:88)
at com.sun.xml.bind.v2.runtime.property.ArrayElementProperty.<init>(ArrayElementProperty.java:100)
at com.sun.xml.bind.v2.runtime.property.ArrayElementNodeProperty.<init>(ArrayElementNodeProperty.java:62)
at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:128)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:181)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:514)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:331)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:139)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1156)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:165)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:297)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:286)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:409)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
at dk.statsbiblioteket.medieplatform.autonomous.PremisManipulatorFactory.<init>(PremisManipulatorFactory.java:28)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule.providePremisManipulatorFactory(DomsModule.java:182)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvidePremisManipulatorFactoryFactory.get(DomsModule_ProvidePremisManipulatorFactoryFactory.java:32)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvidePremisManipulatorFactoryFactory.get(DomsModule_ProvidePremisManipulatorFactoryFactory.java:11)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvideSBOIEventIndexFactory.get(DomsModule_ProvideSBOIEventIndexFactory.java:56)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvideSBOIEventIndexFactory.get(DomsModule_ProvideSBOIEventIndexFactory.java:12)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.doms.DomsRepository_Factory.get(DomsRepository_Factory.java:53)
WARNING: Illegal reflective access by com.sun.xml.bind.v2.runtime.reflect.opt.Injector (file:/home/tra/.m2/repository/com/sun/xml/bind/jaxb-impl/2.3.0/jaxb-impl-2.3.0.jar) to method java.lang.ClassLoader.resolveClass(java.lang.Class)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.getMethod(Injector.java:222)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.access$000(Injector.java:74)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector$1.run(Injector.java:175)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector$1.run(Injector.java:172)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.<clinit>(Injector.java:171)
at com.sun.xml.bind.v2.runtime.reflect.opt.AccessorInjector.prepare(AccessorInjector.java:81)
at com.sun.xml.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory.get(OptimizedAccessorFactory.java:179)
at com.sun.xml.bind.v2.runtime.reflect.Accessor$FieldReflection.optimize(Accessor.java:285)
at com.sun.xml.bind.v2.runtime.property.ArrayProperty.<init>(ArrayProperty.java:68)
at com.sun.xml.bind.v2.runtime.property.ArrayERProperty.<init>(ArrayERProperty.java:88)
at com.sun.xml.bind.v2.runtime.property.ArrayElementProperty.<init>(ArrayElementProperty.java:100)
at com.sun.xml.bind.v2.runtime.property.ArrayElementNodeProperty.<init>(ArrayElementNodeProperty.java:62)
at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:128)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:181)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:514)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:331)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:139)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1156)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:165)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:297)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:286)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:409)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
at dk.statsbiblioteket.medieplatform.autonomous.PremisManipulatorFactory.<init>(PremisManipulatorFactory.java:28)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule.providePremisManipulatorFactory(DomsModule.java:182)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvidePremisManipulatorFactoryFactory.get(DomsModule_ProvidePremisManipulatorFactoryFactory.java:32)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvidePremisManipulatorFactoryFactory.get(DomsModule_ProvidePremisManipulatorFactoryFactory.java:11)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvideSBOIEventIndexFactory.get(DomsModule_ProvideSBOIEventIndexFactory.java:56)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvideSBOIEventIndexFactory.get(DomsModule_ProvideSBOIEventIndexFactory.java:12)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.doms.DomsRepository_Factory.get(DomsRepository_Factory.java:53)
WARNING: Illegal reflective access by com.sun.xml.bind.v2.runtime.reflect.opt.Injector (file:/home/tra/.m2/repository/com/sun/xml/bind/jaxb-impl/2.3.0/jaxb-impl-2.3.0.jar) to method java.lang.ClassLoader.findLoadedClass(java.lang.String)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.getMethod(Injector.java:222)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.access$000(Injector.java:74)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector$1.run(Injector.java:175)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector$1.run(Injector.java:172)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at com.sun.xml.bind.v2.runtime.reflect.opt.Injector.<clinit>(Injector.java:171)
at com.sun.xml.bind.v2.runtime.reflect.opt.AccessorInjector.prepare(AccessorInjector.java:81)
at com.sun.xml.bind.v2.runtime.reflect.opt.OptimizedAccessorFactory.get(OptimizedAccessorFactory.java:179)
at com.sun.xml.bind.v2.runtime.reflect.Accessor$FieldReflection.optimize(Accessor.java:285)
at com.sun.xml.bind.v2.runtime.property.ArrayProperty.<init>(ArrayProperty.java:68)
at com.sun.xml.bind.v2.runtime.property.ArrayERProperty.<init>(ArrayERProperty.java:88)
at com.sun.xml.bind.v2.runtime.property.ArrayElementProperty.<init>(ArrayElementProperty.java:100)
at com.sun.xml.bind.v2.runtime.property.ArrayElementNodeProperty.<init>(ArrayElementNodeProperty.java:62)
at com.sun.xml.bind.v2.runtime.property.PropertyFactory.create(PropertyFactory.java:128)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.<init>(ClassBeanInfoImpl.java:181)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getOrCreate(JAXBContextImpl.java:514)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:331)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:139)
at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1156)
at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:165)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:297)
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:286)
at javax.xml.bind.ContextFinder.find(ContextFinder.java:409)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721)
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662)
at dk.statsbiblioteket.medieplatform.autonomous.PremisManipulatorFactory.<init>(PremisManipulatorFactory.java:28)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule.providePremisManipulatorFactory(DomsModule.java:182)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvidePremisManipulatorFactoryFactory.get(DomsModule_ProvidePremisManipulatorFactoryFactory.java:32)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvidePremisManipulatorFactoryFactory.get(DomsModule_ProvidePremisManipulatorFactoryFactory.java:11)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvideSBOIEventIndexFactory.get(DomsModule_ProvideSBOIEventIndexFactory.java:56)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.tools.modules.DomsModule_ProvideSBOIEventIndexFactory.get(DomsModule_ProvideSBOIEventIndexFactory.java:12)
at dk.statsbiblioteket.digital_pligtaflevering_aviser.doms.DomsRepository_Factory.get(DomsRepository_Factory.java:53)
</code></pre>
<p>What are the proper dependencies to use here to resolve this problem?</p> | 50,251,510 | 4 | 5 | null | 2018-05-08 15:42:24.163 UTC | 17 | 2022-07-17 03:32:08.83 UTC | 2018-05-09 09:29:30.417 UTC | null | 53,897 | null | 53,897 | null | 1 | 49 | java|maven|jaxb|java-10 | 36,986 | <p>jaxb-ri runtime uses <code>ClassLoader#defineClass / Unsafe#defineClass</code> to do some bytecode modification in runtime to optimize performance. <code>ClassLoader#defineClass</code> is tried first which causes the warning.</p>
<p>This legacy optimization is removed completely in jaxb-ri master (after 2.3.0, not released yet).</p>
<p>To disable this optimization for 2.3.0, set system property
<code>com.sun.xml.bind.v2.bytecode.ClassTailor.noOptimize</code>.</p>
<p>After next jaxb-ri release updating to newest version will remove the warning.
jaxb-core artifact will be discontinued in favor for JPMS support. Correct pom will look like:</p>
<pre><code><dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.4.0</version>
</dependency>
</code></pre>
<p>If you wish to try early, you can pick latest promoted build from:
<a href="https://maven.java.net/content/groups/promoted/org/glassfish/jaxb/jaxb-runtime/" rel="noreferrer">https://maven.java.net/content/groups/promoted/org/glassfish/jaxb/jaxb-runtime/</a></p> |
10,668,948 | System.ComponentModel.DataAnnotations.compare vs System.Web.Mvc.Compare | <p>MVC 4 Beta project fails to compile after upgrading to .Net 4.5.</p>
<p>This happens due to conflict between
<code>System.ComponentModel.DataAnnotations.CompareAttribute</code> and <code>System.Web.Mvc.CompareAttribute</code></p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.compareattribute%28v=vs.110%29.aspx" rel="nofollow"><code>System.ComponentModel.DataAnnotations.CompareAttribute</code> MSDN documentation</a> says: </p>
<blockquote>
<p>Provides an attribute that compares two properties.</p>
</blockquote>
<p>While <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.compareattribute%28v=vs.108%29" rel="nofollow"><code>System.Web.Mvc.CompareAttribute</code> MSDN documentation</a> says: </p>
<blockquote>
<p>Provides an attribute that compares two properties of a model.</p>
</blockquote>
<p>What is the difference between the two and when it would be "smarter" to use each of them?</p>
<p>10x.</p> | 11,961,402 | 6 | 3 | null | 2012-05-19 21:21:37.457 UTC | 10 | 2015-11-02 16:30:00.91 UTC | 2015-11-02 16:12:21.773 UTC | null | 4,390,133 | null | 739,558 | null | 1 | 52 | asp.net-mvc-4 | 21,495 | <p>So, looking at the MSDN documentation and doing a literal comparison of the two classes, I noticed both classes are derived from System.ComponentModel.DataAnnotations.ValidationAttribute. In fact, the classes are almost exactly the same. The only notable difference is that the MVC version also implements IClientValidatable which adds the following properties:</p>
<ul>
<li>FormatPropertyForClientValidation - (static member) Formats the property for client validation by prepending an asterisk and a dot. </li>
<li>GetClientValidationRules - Gets a list of compare-value client validation rules for the property using the specified model metadata and controller context.</li>
</ul>
<p>As for which class you should use, if the model will be directly bound to a view, use the MVC version so that you can take advantage of the client-side validation. However, if you're using ViewModels, you can stick with the ComponentModel class and avoid the unnecessary overhead of the additional properties. Your call!</p>
<ul>
<li><p><a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.compareattribute%28v=vs.108%29" rel="nofollow noreferrer">System.Web.Mvc.CompareAttribute</a></p></li>
<li><p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.compareattribute.aspx" rel="nofollow noreferrer">System.ComponentModel.DataAnnotations.CompareAttribute</a></p></li>
</ul> |
10,659,875 | In PHP, is there a function that returns an array made up of the value of a key from an array of associative arrays? | <p>I'm sure this question has been asked before, my apologies for not finding it first.</p>
<p>The original array:</p>
<pre><code>[0] => Array
(
[categoryId] => 1
[eventId] => 2
[eventName] => 3
[vendorName] => 4
)
[1] => Array
(
[categoryId] => 5
[eventId] => 6
[eventName] => 7
[vendorName] => 8
)
[2] => Array
(
[categoryId] => 9
[eventId] => 10
[eventName] => 11
[vendorName] => 12
)
</code></pre>
<p>My hoped for result out of: print_r(get_values_from_a_key_in_arrays('categoryId', $array));</p>
<pre><code>[0] => 1
[1] => 5
[2] => 9
</code></pre>
<p>I'm just looking for something cleaner than writing my own foreach based function. If foreach is the answer, I already have that in place.</p>
<p><strong>Edit:</strong> I don't want to use a hard-coded key, I was just showing an example call to the solution. Thanks! ^_^</p>
<p><strong>Quick Grab Solution for PHP 5.3:</strong></p>
<pre><code>private function pluck($key, $data) {
return array_reduce($data, function($result, $array) use($key) {
isset($array[$key]) && $result[] = $array[$key];
return $result;
}, array());
}
</code></pre> | 10,660,002 | 8 | 5 | null | 2012-05-18 21:17:16.087 UTC | 9 | 2016-10-26 15:05:25.467 UTC | 2014-01-24 03:31:05.473 UTC | null | 128,346 | null | 975,132 | null | 1 | 27 | php|arrays|associative-array|array-reduce|pluck | 16,956 | <p>So, the cool thing about <a href="http://c2.com/cgi/wiki?HigherOrderFunction" rel="nofollow noreferrer">higher-order</a> <a href="http://docs.python.org/library/itertools.html" rel="nofollow noreferrer">collection/iterator functions</a> such as <a href="http://api.prototypejs.org/language/Enumerable/prototype/pluck/" rel="nofollow noreferrer">pluck</a>, <a href="http://yuilibrary.com/yui/docs/api/classes/Array.html#method_filter" rel="nofollow noreferrer">filter</a>, <a href="http://underscorejs.org/#each" rel="nofollow noreferrer">each</a>, <a href="http://apidock.com/ruby/Enumerable/map" rel="nofollow noreferrer">map</a>, and friends is that they can be mixed and matched to compose a more complex set of operations.</p>
<p>Most languages provide these types of functions (look for packages like collection, iterator, or enumeration/enumerable)...some provide more functions than others and you will commonly see that the functions are named differently across languages (i.e. collect == map, reduce == fold). If a function <a href="http://kourge.net/node/100" rel="nofollow noreferrer">doesn't exist in your language, you can create it</a> from the ones that do exist. </p>
<p>As for your test case...we can use <a href="http://php.net/array_reduce" rel="nofollow noreferrer">array_reduce</a> to implement <strong>pluck</strong>. The first version I posted relied on <code>array_map</code>; however, I agree with <a href="https://stackoverflow.com/users/113938/salathe">@salathe</a> that <a href="http://php.net/array_reduce" rel="nofollow noreferrer">array_reduce</a> is more succinct for this task; <a href="http://php.net/array_map" rel="nofollow noreferrer">array_map</a> is an OK option, but you end up having to do more work in the end. <code>array_reduce</code> can look a bit odd at first, but if the callback is neatly organized, all is well.</p>
<p>A less naive <code>pluck</code> would also check to see if it can "call" (a function/method) on the iterated value. In the naive implementation below, we assume the structure to be a hash (associative array).</p>
<p><strong>This will setup the test-case data (Fixtures):</strong></p>
<pre><code><?php
$data[] = array('categoryId' => 1, 'eventId' => 2, 'eventName' => 3, 'vendorName' => 4);
$data[] = array('categoryId' => 5, 'eventId' => 6, 'eventName' => 7, 'vendorName' => 8);
$data[] = array('categoryId' => 9, 'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
$data[] = array(/* no categoryId */ 'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
$data[] = array('categoryId' => false,'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
$data[] = array('categoryId' => 0.0, 'eventId' => 10, 'eventName' => 11, 'vendorName' => 12);
</code></pre>
<p><strong>Choose the version of pluck you'd prefer</strong></p>
<pre><code>$preferredPluck = 'pluck_array_reduce'; // or pluck_array_map
</code></pre>
<p><strong>"pluck" for PHP 5.3+: array_reduce provides a terse implementation though not as easy to reason about as the array_map version:</strong></p>
<pre><code>function pluck_array_reduce($key, $data) {
return array_reduce($data, function($result, $array) use($key){
isset($array[$key]) &&
$result[] = $array[$key];
return $result;
}, array());
}
</code></pre>
<p><strong>"pluck" for PHP 5.3+: array_map isn't perfect for this so we have to do more checking (and it still doesn't account for many potential cases):</strong></p>
<pre><code>function pluck_array_map($key, $data) {
$map = array_map(function($array) use($key){
return isset($array[$key]) ? $array[$key] : null;
}, $data);
// is_scalar isn't perfect; to make this right for you, you may have to adjust
return array_filter($map, 'is_scalar');
}
</code></pre>
<p><strong>"pluck" for legacy PHP <5.3</strong></p>
<p>We could have used the legacy <a href="http://php.net/create_function" rel="nofollow noreferrer">create_function</a>; however, it is bad form, not recommended, and also not at all elegant, thus, I've decided not to show it.</p>
<pre><code>function pluck_compat($key, $data) {
$map = array();
foreach ($data as $array) {
if (array_key_exists($key, $array)) {
$map[] = $array[$key];
}
}
unset($array);
return $map;
}
</code></pre>
<p><strong>Here we choose a version of "pluck" to call based on the version of PHP we are running. If you run the entire script, you should get the correct answer no matter what version you are on.</strong></p>
<pre><code>$actual = version_compare(PHP_VERSION, '5.3.0', '>=')
? $preferredPluck('categoryId', $data)
: pluck_compat('categoryId', $data);
$expected = array(1, 5, 9, false, 0.0);
$variance = count(array_diff($expected, $actual));
var_dump($expected, $actual);
echo PHP_EOL;
echo 'variance: ', $variance, PHP_EOL;
print @assert($variance)
? 'Assertion Failed'
: 'Assertion Passed';
</code></pre>
<p>Notice there is no ending '?>'. That is because it isn't needed. More good can come of leaving it off than from keeping it around.</p>
<p>FWIW, it looks like this is being added to PHP 5.5 as <a href="http://benramsey.com/blog/2013/03/introducing-array-column-in-php-5-dot-5/" rel="nofollow noreferrer">array_column</a>.</p> |
25,031,557 | Rotate mp4 videos without re-encoding | <p>I'm looking for a way to rotate videos shot with my Nexus 4 on my Debian Wheezy sytem. The videos are shot in portrait mode and I would like to rotate them to landscape mode. Preferably the rotation is command-line driven.</p>
<p>I have found several previous questions which are hinting at a good solution but I can't seem to manage to get it working.</p>
<p>To begin with there was this question:
<a href="https://stackoverflow.com/questions/3937387/rotating-videos-with-ffmpeg">Rotating videos with FFmpeg</a></p>
<p>But it indicates that ffmpeg is outdated and that I should use avconv. I found this question detailing the way to go forward.
<a href="https://askubuntu.com/questions/269429/how-can-i-rotate-video-by-180-degrees-with-avconv">https://askubuntu.com/questions/269429/how-can-i-rotate-video-by-180-degrees-with-avconv</a></p>
<p>This made me using following command:</p>
<pre><code>avconv -i original.mp4 -vf "transpose=1" -codec:v libx264 -preset slow -crf 25 -codec:a copy flipped.mp4
</code></pre>
<p>However, this is painstakingly slow (last test took me more than 6 hours for less than 3 minutes of footage) and does not result in a playable movie. I also get an error in logging output which states Mb Rate > level limit.</p>
<p>Is there an issue here with the re-encoding? Should I first re-encode the videos from my phone to another, more "workable" encoding before applying the rotations? Or am I missing another important point?</p> | 27,768,317 | 5 | 4 | null | 2014-07-30 07:56:36.767 UTC | 52 | 2021-11-12 10:53:29.353 UTC | 2018-12-28 05:51:52.837 UTC | null | 9,170,457 | null | 1,982,870 | null | 1 | 99 | ffmpeg|rotation|debian|video-encoding|avconv | 90,714 | <p>If you just want to change the metadata such that mediaplayers that consider the flag play the file rotated, try something like:</p>
<pre><code>ffmpeg -i input.mp4 -c copy -metadata:s:v:0 rotate=90 output.mp4
</code></pre>
<p>as found <a href="https://stackoverflow.com/a/15336581">elsewhere on stackoverflow</a>.</p> |
25,003,961 | Find array index if given value | <p>I want to retrieve the index in the array where the value is stored. I know the value of the item at that point in the array. I'm thinking it's similar to the findIndex function in c#.
For example, array[2] = {4, 7, 8}. I know the value is 7, how do I get the value of the index, 1, if I know it is at array[1]?</p> | 25,004,042 | 3 | 5 | null | 2014-07-28 20:41:06.867 UTC | 4 | 2020-09-26 11:06:39.227 UTC | 2020-09-26 11:06:39.227 UTC | null | 2,877,241 | null | 1,798,299 | null | 1 | 9 | arrays|c|algorithm|search|indexing | 69,493 | <p>For example you can define the corresponding function the following way</p>
<pre><code>size_t FindIndex( const int a[], size_t size, int value )
{
size_t index = 0;
while ( index < size && a[index] != value ) ++index;
return ( index == size ? -1 : index );
}
</code></pre>
<p>Also instead of type size_t you can use type int.</p>
<p>But the better way is to use standard algorithm <code>std::find</code> or <code>std::find_if</code> declared in header <code><algorithm></code> provided that you use <code>C++</code></p>
<p>For example</p>
<pre><code>#include <algorithm>
#include <iterator>
int main()
{
int a[] = { 4, 7, 8 };
auto it = std::find( std::begin( a ), std::end( a ), 7 );
if ( it != std::end( a ) )
{
std::cout << "The index of the element with value 7 is "
<< std::distance( std::begin( a ), it )
<< std::endl;
}
}
</code></pre>
<p>The output is</p>
<pre><code>The index of the element with value 7 is 1
</code></pre>
<p>Otherwise you have to write the function yourself as I showed abve.:)</p>
<p>If the array is sorted you can use standard C function <code>bsearch</code> declared in header <code><stdlib.h></code></p>
<p>For example</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int cmp( const void *lhs, const void *rhs )
{
if ( *( const int * )lhs < *( const int * )rhs ) return -1;
else if ( *( const int * )rhs < *( const int * )lhs ) return 1;
else return 0;
}
int main()
{
int a[] = { 4, 7, 8 };
int x = 7;
int *p = ( int * )bsearch( &x, a, 3, sizeof( int ), cmp );
if ( p != NULL ) printf( "%d\n", p - a );
return 0;
}
</code></pre> |
35,437,313 | Read a .csv file in c# efficiently? | <p>I'm reading huge csv files (about 350K lines by file) using this way:</p>
<pre><code>StreamReader readFile = new StreamReader(fi);
string line;
string[] row;
readFile.ReadLine();
while ((line = readFile.ReadLine()) != null)
{
row = line.Split(';');
x=row[1];
y=row[2];
//More code and assignations here...
}
readFile.Close();
}
</code></pre>
<p>The point here is that reading line by line a huge file for every day of the month may be slow and I think that it must be another method to do it faster.</p> | 35,437,460 | 2 | 7 | null | 2016-02-16 16:03:36.163 UTC | null | 2016-02-16 17:25:26.4 UTC | 2016-02-16 17:25:26.4 UTC | null | 4,987,132 | null | 4,987,132 | null | 1 | 3 | c#|csv|streamreader | 65,541 | <p><strong>Method 1</strong></p>
<p>By using LINQ: </p>
<pre><code>var Lines = File.ReadLines("FilePath").Select(a => a.Split(';'));
var CSV = from line in Lines
select (line.Split(',')).ToArray();
</code></pre>
<p><strong>Method 2</strong></p>
<p>As <a href="https://stackoverflow.com/a/1050149/2118383">Jay Riggs</a> stated here</p>
<p>Here's an excellent class that will copy CSV data into a datatable using the structure of the data to create the DataTable:</p>
<p><a href="http://www.codeproject.com/KB/database/GenericParser.aspx" rel="noreferrer">A portable and efficient generic parser for flat files</a></p>
<p>It's easy to configure and easy to use. I urge you to take a look.</p>
<p><strong>Method 3</strong></p>
<p>Rolling your own CSV reader is a waste of time unless the files that you're reading are <em>guaranteed</em> to be <em>very</em> simple. Use a <a href="http://www.codeproject.com/KB/database/CsvReader.aspx" rel="noreferrer">pre-existing, tried-and-tested implementation</a> instead.</p> |
13,748,970 | Server is unwilling to process the request - Active Directory - Add User via C# | <p>I used the example in <a href="http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C#36" rel="noreferrer">this page</a> to add a user to an Active Directory group, but I get an exception with the message "Server is unwilling to process the request" when executing</p>
<p><code>dirEntry.Properties["member"].Add(userDn);</code></p> | 31,832,601 | 6 | 2 | null | 2012-12-06 17:17:22.47 UTC | 1 | 2020-02-18 12:30:10.123 UTC | 2015-08-05 12:30:15.257 UTC | null | 1,448,536 | null | 1,448,536 | null | 1 | 13 | active-directory|active-directory-group | 51,309 | <p>This question took me a lot of time to solve. First of all, the error message looks like a joke. Second, there is nothing more, just that message.</p>
<p>Anyway, I managed to fix it by:</p>
<ol>
<li><p>Making sure that <code>userDn</code> contains the whole path (e.g., <code>"LDAP://server-address/CN=" + userDn + ",OU=optional,DC=your-domain,DC=com"</code>. This is actually <strong>very important</strong>, if you don't supply the full path it will throw an <strong>Exception from HRESULT: 0x80005000</strong>.</p></li>
<li><p>Replacing <code>dirEntry.Properties["member"].Add(userDn);</code> by <code>entry.Invoke("Add", new object[] { userDn });</code></p></li>
</ol>
<p>Then I wanted to remove a user and I expected <code>entry.Invoke("Remove", new object[] { userDn });</code> to work. However, this devilish AD will only work if you use <strong>lower case "remove"</strong>, so <code>entry.Invoke("remove", new object[] { userDn });</code> worked for me.</p> |
13,561,238 | App Rejected on 17.2 clause. Asking for email ID | <p>My app is a sync solution (imagine dropbox).
The user needs to sign in to access the app's features, and if he does not have any account already created, he can sign up.</p>
<p>The sign up asks for email id verification, and this email id is also used if the user has forgotten his password to send him one.</p>
<p>but Apple has rejected this app saying:</p>
<blockquote>
<p>17.2: Apps that require users to share personal information, such as email address and date of birth, in order to function will be rejected</p>
<p>We found that your app requires customers to register with personal information to access non-account-based features, which is not in compliance with the App Store Review Guidelines.</p>
<p>Apps cannot require user registration prior to allowing access to app features and content that are not associated specifically to the user. User registration that requires the sharing of personal information must be optional or tied to account-specific functionality. Additionally, the requested information must be relevant to the features.</p>
<p>Although guideline 11.6 of the App Store Review Guidelines requires an application to make subscription content available to all the iOS devices owned by a single user, it is not appropriate to force user registration to meet this requirement; such user registration must be made optional.</p>
<p>It would be appropriate to make it clear to the user that registering will enable them to access the content from any of their iOS devices, and to provide them a way to register at any time, if they wish to later extend access to additional iOS devices</p>
</blockquote>
<p>Please help me solve this. Many apps like dropbox/facebook require login.
I don't get the exact reason why they rejected my app.</p>
<p>Also, please guide about the in app purchase, why registering cannot be mandatory</p> | 13,599,173 | 8 | 0 | null | 2012-11-26 08:39:09.013 UTC | 9 | 2016-01-20 02:35:44.353 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 1,554,632 | null | 1 | 24 | iphone|ios|in-app-purchase|privacy | 26,857 | <p>Asked App Store Review people for clarification on their rejection.
They accepted it. and the app got approved :D
Its on Appstore now :)</p> |
13,478,372 | jQuery: append() vs appendTo() | <p>I am testing jQuery's <code>.append()</code> vs <code>.appendTo()</code> methods using following code:</p>
<pre><code>$('div/>', {
id : id,
text : $(this).text()
}).appendTo('div[type|="item"]#'+id);
$('div[type|="item"]#'+id).append($(this).text());
</code></pre>
<p>Note that the selectors are identical in <code>.appendTo()</code> and <code>.append()</code>, yet the latter works (within the same page), while the former does not. Why?</p>
<p>How do I get <code>.appendTo()</code> to work with this type of (complex) <em>selector</em>? Do the two methods interpolate differently? Is there some syntax I'm missing?</p>
<p>I don't want to clutter the post with impertinent code: suffice it to say that elements referenced by selectors exist, as is evidenced by the <code>.append()</code> method producing desired result. Let me know if more info is needed.</p>
<p>Thanks!</p> | 13,478,425 | 10 | 3 | null | 2012-11-20 17:08:45.197 UTC | 3 | 2020-08-18 01:15:12.923 UTC | 2018-09-21 17:27:49.267 UTC | null | 814,702 | null | 1,189,757 | null | 1 | 32 | jquery|jquery-selectors|jquery-append | 61,684 | <p>To answer the question, you don't have an element to <code>appendTo</code> anything, as you're missing characters (in your case it's an <strong><em>opening angle bracket</em></strong> <code><</code>).</p>
<p>This</p>
<pre><code>$('div/>',{});
</code></pre>
<p>needs to be</p>
<pre><code>$('<div/>',{});
</code></pre>
<p>to create an element, otherwise it does exactly what you say it does - nothing!</p>
<hr>
<p>Otherwise you seem to have the order of things right, it's like this:</p>
<ul>
<li><p><a href="http://api.jquery.com/append/" rel="noreferrer"><code>.append()</code></a> inserts the content specified by the parameter, to
the end of each element in the set of matched elements, as in</p>
<pre><code>$(Append_To_This).append(The_Content_Given_Here);
</code></pre></li>
<li><p>while <a href="http://api.jquery.com/appendto/" rel="noreferrer"><code>.appendTo()</code></a> works the <em>other way around</em>: it insert every
element in the set of matched elements to the end of the target given
in the parameter, as in</p>
<pre><code>$(The_Content_Given_Here).appendTo(Append_To_This);
</code></pre></li>
</ul>
<p><br>
There's also <a href="http://api.jquery.com/prepend/" rel="noreferrer"><code>.prepend()</code></a> and <a href="http://api.jquery.com/prependto/" rel="noreferrer"><code>prependTo()</code></a> which works exactly the same, with the only difference being that the prepended elements are added at the beginning of the target elements content instead of the end.</p> |
13,510,849 | Linq where clause compare only date value without time value | <pre><code>var _My_ResetSet_Array = _DB
.tbl_MyTable
.Where(x => x.Active == true
&& x.DateTimeValueColumn <= DateTime.Now)
.Select(x => x);
</code></pre>
<p>Upper query is working correct.<br>
But I want to check only date value only.<br>
But upper query check date + time value.</p>
<p>In traditional mssql, I could write query like below.</p>
<pre><code>SELECT * FROM dbo.tbl_MyTable
WHERE
CAST(CONVERT(CHAR(10), DateTimeValueColumn, 102) AS DATE) <=
CAST(CONVERT(CHAR(10),GETDATE(),102) AS DATE)
AND
Active = 1
</code></pre>
<p>So could anyone give me suggestion how could I check only date value in Linq.</p> | 19,935,487 | 10 | 0 | null | 2012-11-22 10:38:25.883 UTC | 11 | 2020-02-06 15:43:21.49 UTC | 2012-11-23 17:41:07.517 UTC | null | 314,488 | null | 900,284 | null | 1 | 63 | c#|entity-framework|datetime|linq-to-entities|compare | 140,621 | <p>There is also <code>EntityFunctions.TruncateTime</code> or <strong><code>DbFunctions.TruncateTime</code></strong> in EF 6.0</p> |
20,683,732 | MySQL column count doesn't match value count at row 1 | <p>I'm trying to insert data into a MySQL table using PHP, but getting the error </p>
<blockquote>
<p>Column count doesn't match value count at row 1</p>
</blockquote>
<pre><code>mysql_query("INSERT INTO file (id, filename, extention, filelink, filesize, filepass) VALUES('{$random}', '{$filename}', '{$extension}', '{$filelink}', '{$filesize}' '{$filepass}') ") or die(mysql_error());
</code></pre> | 20,683,763 | 2 | 3 | null | 2013-12-19 14:03:21.373 UTC | 2 | 2015-08-03 06:47:21.213 UTC | 2013-12-26 16:22:43.937 UTC | null | 693,207 | null | 2,251,733 | null | 1 | 8 | php|mysql | 50,974 | <pre><code>mysql_query("INSERT INTO file (id, filename, extention, filelink, filesize, filepass) VALUES('{$random}', '{$filename}', '{$extension}', '{$filelink}', '{$filesize}' '{$filepass}') ") or die(mysql_error());
</code></pre>
<p>You should add the missing comma after {$filesize}:</p>
<pre><code>mysql_query("INSERT INTO file (id, filename, extention, filelink, filesize, filepass) VALUES('{$random}', '{$filename}', '{$extension}', '{$filelink}', '{$filesize}', '{$filepass}') ") or die(mysql_error());
</code></pre> |
3,912,303 | Boolean.hashCode() | <p>The <code>hashCode()</code> method of class Boolean is implemented like this:</p>
<pre><code>public int hashCode() {
return value ? 1231 : 1237;
}
</code></pre>
<p>Why does it use 1231 and 1237? Why not something else?</p> | 3,912,325 | 2 | 1 | null | 2010-10-12 07:02:29.88 UTC | 27 | 2019-09-09 12:24:52.107 UTC | 2019-09-09 12:24:52.107 UTC | null | 5,091,346 | null | 471,011 | null | 1 | 130 | java|boolean|hashcode | 17,261 | <p>1231 and 1237 are just two (sufficiently large) <strong>arbitrary prime numbers</strong>. Any other two large prime numbers would do fine.</p>
<p><strong>Why primes?</strong><br/>
Suppose for a second that we picked composite numbers (non-primes), say 1000 and 2000. When inserting booleans into a hash table, <em>true</em> and <em>false</em> would go into bucket <code>1000 % N</code> resp <code>2000 % N</code> (where <code>N</code> is the number of buckets).</p>
<p>Now notice that</p>
<ul>
<li><code>1000 % 8</code> same bucket as <code>2000 % 8</code></li>
<li><code>1000 % 10</code> same bucket as <code>2000 % 10</code></li>
<li><code>1000 % 20</code> same bucket as <code>2000 % 20</code></li>
<li>....</li>
</ul>
<p>in other words, it would lead to <em>many collisions</em>.</p>
<p>This is because the factorization of 1000 (2<sup>3</sup>, 5<sup>3</sup>) and the factorization of 2000 (2<sup>4</sup>, 5<sup>3</sup>) have so many common factors. Thus prime numbers are chosen, since they are unlikely to have any common factors with the bucket size.</p>
<p><strong>Why <em>large</em> primes. Wouldn't 2 and 3 do?</strong><br/>
When computing hash codes for composite objects it's common to add the hash codes for the components. If too small values are used in a hash set with a large number of buckets there's a risk of ending up with an uneven distribution of objects.</p>
<p><strong>Do collisions matter? Booleans just have two different values anyway?</strong><br/>
Maps can contain booleans together with other objects. Also, as pointed out by Drunix, a common way to create hash functions of composite objects is to reuse the subcomponents hash code implementations in which case it's good to return large primes.</p>
<p><strong>Related questions:</strong></p>
<ul>
<li><a href="https://stackoverflow.com/questions/3613102/why-use-a-prime-number-in-hashcode">Why use a prime number in hashCode?</a></li>
<li><a href="https://stackoverflow.com/questions/1835976/what-is-a-sensible-prime-for-hashcode-calculation">What is a sensible prime for hashcode calculation?</a></li>
<li><a href="https://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier/299748">Why does Java's hashCode() in String use 31 as a multiplier?</a></li>
</ul> |
3,505,662 | Change attributes of a group of files in MS-DOS | <p>The MS-DOS command <code>attrib</code> changes the attributes of a single file. How can I use it to change the attributes of a group of files?</p> | 3,505,710 | 3 | 2 | null | 2010-08-17 18:25:08.987 UTC | null | 2014-02-02 08:26:43.587 UTC | 2010-11-05 17:09:09.797 UTC | null | 393,280 | null | 327,104 | null | 1 | 2 | command-line|batch-file|dos | 42,435 | <p>This is the info you need</p>
<pre>
Displays or changes file attributes.
ATTRIB [+R | -R] [+A | -A ] [+S | -S] [+H | -H] [drive:][path][filename]
[/S [/D]]
+ Sets an attribute.
- Clears an attribute.
R Read-only file attribute.
A Archive file attribute.
S System file attribute.
H Hidden file attribute.
[drive:][path][filename]
Specifies a file or files for attrib to process.
/S Processes matching files in the current folder
and all subfolders.
/D Processes folders as well.
</pre>
<p>By using the '/s' parameter will do it for matching files for example</p>
<pre>
attrib -rhsa *.txt /s
</pre>
<p>That will remove the read, hidden, system and archive attributes from <strong>ALL</strong> files ending with '.txt'.</p> |
9,138,959 | parsing json dictionary in javascript to iterate through keys | <p>I have the below json data coming from web service which is nothing but a dictionary serialized into json, now on client side i need to parse this back to iterate through the keys of this json dictionary using javascript or jquery</p>
<pre><code>{
"AboutToExpire": {
"Display": true,
"Message": "Several of your subscriptions are about to expire. <a id=\"lnkShowExpiringSubs\" href=\"#\">View subscriptions<\/a>"
},
"Expired": {
"Display": true,
"Message": "Your McAfee WaveSecure - Tablet Edition subscription has expired and you’ve been without protection for 384 days. <a id=\"lnkNotificationRenewNow\" href=\"http://home.mcafee.com/root/campaign.aspx?cid=96035&pk=FAB37CF4-3680-4A87-A253-77E7D48BF6D7&affid=0\">Renew now<\/a>"
}
}
</code></pre> | 9,139,126 | 4 | 2 | null | 2012-02-04 06:40:46.41 UTC | 1 | 2020-12-21 17:03:46.907 UTC | 2014-12-15 19:00:07.487 UTC | null | 1,474,939 | null | 1,188,985 | null | 1 | 11 | jquery|json | 55,168 | <pre><code>var s = '{"AboutToExpire":{"Display":true,"Message":"Several of your subscriptions are about to expire. \u003ca id=\"lnkShowExpiringSubs\" href=\"#\"\u003eView subscriptions\u003c/a\u003e"},"Expired":{"Display":true,"Message":"Your McAfee WaveSecure - Tablet Edition subscription has expired and you’ve been without protection for 384 days. \u003ca id=\"lnkNotificationRenewNow\" href=\"http://home.mcafee.com/root/campaign.aspx?cid=96035&pk=FAB37CF4-3680-4A87-A253-77E7D48BF6D7&affid=0\"\u003eRenew now\u003c/a\u003e"}}';
var data = eval(s); // this will convert your json string to a javascript object
for (var key in data) {
if (data.hasOwnProperty(key)) { // this will check if key is owned by data object and not by any of it's ancestors
alert(key+': '+data[key]); // this will show each key with it's value
}
}
</code></pre> |
9,348,264 | Does tkinter have a table widget? | <p>I'm learning Python, and I would like to use it to create a simple GUI application, and since <code>Tkinter</code> is already built-in (and very simple to use) I would like to use it to build my application.</p>
<p>I would like to make an app that will display a table that contains some data that I've loaded from my database.</p>
<p>I've searched for <code>table</code> but have not been able to find any examples and / or documentation regarding a <code>Tkinter table</code> component.</p>
<p>Does <code>Tkinter</code> have a built in <code>table</code> component? If not, what could I / should I use instead?</p> | 9,348,306 | 10 | 2 | null | 2012-02-19 09:59:15.003 UTC | 19 | 2021-12-06 03:40:41.417 UTC | 2017-08-21 10:40:12.57 UTC | null | 4,528,269 | null | 342,235 | null | 1 | 60 | python|tkinter | 191,988 | <p>Tkinter doesn't have a built-in table widget. The closest you can use is a <code>Listbox</code> or a <code>Treeview</code> of the tkinter's sub package <a href="https://docs.python.org/3/library/tkinter.ttk.html" rel="noreferrer"><code>ttk</code></a>.</p>
<p>However, you can use <a href="https://github.com/dossan/tktable" rel="noreferrer">tktable</a>, which is a wrapper around the <code>Tcl/Tk</code> <a href="http://wiki.tcl.tk/1877" rel="noreferrer"><code>TkTable</code></a> widget, written by <a href="https://github.com/gpolo" rel="noreferrer">Guilherme Polo</a>. <strong>Note</strong>: to use this wrapper library you need first to have installed the original Tk's <code>TkTable</code> library, otherwise you will get an "import error".</p> |
29,763,620 | How to select all columns except one in pandas? | <p>I have a dataframe that look like this:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df
a b c d
0 0.418762 0.042369 0.869203 0.972314
1 0.991058 0.510228 0.594784 0.534366
2 0.407472 0.259811 0.396664 0.894202
3 0.726168 0.139531 0.324932 0.906575
</code></pre>
<p>How I can get all columns except <code>b</code>?</p> | 29,763,653 | 11 | 3 | null | 2015-04-21 05:24:59.34 UTC | 109 | 2022-06-04 15:13:14.35 UTC | 2022-06-04 15:13:14.35 UTC | null | 4,518,341 | null | 4,744,765 | null | 1 | 504 | python|pandas | 655,446 | <p>When the columns are not a MultiIndex, <code>df.columns</code> is just an array of column names so you can do:</p>
<pre><code>df.loc[:, df.columns != 'b']
a c d
0 0.561196 0.013768 0.772827
1 0.882641 0.615396 0.075381
2 0.368824 0.651378 0.397203
3 0.788730 0.568099 0.869127
</code></pre> |
28,918,519 | Does securing a REST application with a JWT and Basic authentication make sense? | <p>I have a Spring REST application which at first was secured with Basic authentication.</p>
<p>Then I added a login controller that creates a JWT JSON Web Token which is used in subsequent requests.</p>
<p>Could I move the following code out of the login controller and into the security filter? Then I would not need the login controller any longer. </p>
<pre><code>tokenAuthenticationService.addTokenToResponseHeader(responseHeaders, credentialsResource.getEmail());
</code></pre>
<p>Or could I remove the Basic authentication?</p>
<p>Is it a good design to mix Basic authentication with a JWT?</p>
<p>Although it all works fine, I'm a bit in the dark here as to best design this security.</p> | 28,953,341 | 2 | 9 | null | 2015-03-07 18:35:12.257 UTC | 42 | 2021-07-28 17:57:14.993 UTC | 2015-10-22 12:46:09.05 UTC | null | 413,180 | null | 958,373 | null | 1 | 48 | spring-security|basic-authentication|jwt | 29,816 | <p>Assuming 100% TLS for all communication - both during and at all times after login - authenticating with username/password via basic authentication and receiving a JWT in exchange is a valid use case. This is <em>almost</em> exactly how one of OAuth 2's flows ('password grant') works.</p>
<p>The idea is that the end user is authenticated via one endpoint, e.g. <code>/login/token</code> using whatever mechanism you want, and the response should contain the JWT that is to be sent back on all subsequent requests. The JWT should be a JWS (i.e. a cryptographically signed JWT) with a proper JWT expiration (<code>exp</code>) field: this ensures that the client cannot manipulate the JWT or make it live longer than it should.</p>
<p>You don't need an <code>X-Auth-Token</code> header either: the HTTP Authentication <code>Bearer</code> scheme was created for this exact use case: basically any bit of information that trails the <code>Bearer</code> scheme name is 'bearer' information that should be validated. You just set the <code>Authorization</code> header:</p>
<pre><code>Authorization: Bearer <JWT value here>
</code></pre>
<p>But, that being said, if your REST client is 'untrusted' (e.g. JavaScript-enabled browser), I wouldn't even do that: any value in the HTTP response that is accessible via JavaScript - basically any header value or response body value - could be sniffed and intercepted via MITM XSS attacks.</p>
<p>It's better to store the JWT value in a secure-only, http-only cookie (cookie config: setSecure(true), setHttpOnly(true)). This guarantees that the browser will:</p>
<ol>
<li>only ever transmit the cookie over a TLS connection and,</li>
<li>never make the cookie value available to JavaScript code.</li>
</ol>
<p>This approach is <em>almost</em> everything you need to do for best-practices security. The last thing is to ensure that you have CSRF protection on every HTTP request to ensure that external domains initiating requests to your site cannot function.</p>
<p>The easiest way to do this is to set a secure only (but NOT http only) cookie with a random value, e.g. a UUID.</p>
<p>Then, on every request into your server, ensure that your own JavaScript code reads the cookie value and sets this in a custom header, e.g. X-CSRF-Token and verify that value on every request in the server. External domain clients cannot set custom headers for requests to your domain unless the external client gets authorization via an HTTP Options request, so any attempt at a CSRF attack (e.g. in an IFrame, whatever) will fail for them.</p>
<p>This is the best of breed security available for untrusted JavaScript clients on the web today that we know of. Stormpath wrote an article on <a href="https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/" rel="noreferrer">these techniques</a> as well if you're curious. HTH!</p> |
15,431,801 | How to delete multiple rows without a loop in Excel VBA | <p>Frequently we are asked how to delete rows based on criteria in one or more columns, and can we use a SpecialCells trick for this?</p> | 15,431,802 | 3 | 0 | null | 2013-03-15 11:55:06.49 UTC | 3 | 2019-03-19 15:43:40.553 UTC | 2018-07-09 18:41:45.953 UTC | null | -1 | null | 2,107,722 | null | 1 | 3 | excel|vba | 40,631 | <p>First, let me say categorically that <strong>there is nothing wrong with loops</strong> - they certainly have their place!</p>
<p>Recently we were presented with the below situation:</p>
<pre><code>400000 | Smith, John| 2.4 | 5.66| =C1+D1
400001 | Q, Suzy | 4.6 | 5.47| =C2+D2
400002 | Schmoe, Joe| 3.8 | 0.14| =C3+D3
Blank | | | | #VALUE
Blank | | | | #VALUE
</code></pre>
<p>The OP wanted to delete rows where Column A is blank, but there is a value in Column E.</p>
<p>I suggest that this is an example where we could make use of SpecialCells and a temporary <em>Error Column</em> to identify the rows to be deleted.</p>
<p>Consider that you might add a column H to try and identify those rows; in that row you could use a formula like below:</p>
<pre><code>=IF(AND(A:A="",E:E<>""),"DELETE THIS ROW","LEAVE THIS ROW")
</code></pre>
<p>now, it is possible get that formula to put an error in the rows where I test returns True. The reason we would do this is a feature of Excel called SpecialCells.</p>
<p>In Excel select any empty cell, and in the formula bar type</p>
<pre><code>=NA()
</code></pre>
<p>Next, hit F5 or CTRL+G (<em>Go to...</em> on the <strong>Edit</strong> menu) then click the <em>Special</em> button to show the SpecialCells dialog.</p>
<p>In that dialog, click the radio next to 'Formulas' and underneath, clear the checkboxes so that only <strong>Errors</strong> is selected. Now click OK</p>
<p>Excel should have selected all the cells in the worksheet with an Error (<strong>#N/A</strong>) in them.</p>
<p>The code below takes advantage of this trick by creating a formula in column H that will put an <strong>#N/A</strong> in all the rows you want to delete, then calling SpecialCells to find the rows, and clear (delete) them...</p>
<pre><code> Sub clearCells()
'
Dim sFormula As String
'
' this formula put's an error if the test returns true,
' so we can use SpecialCells function to highlight the
' rows to be deleted!
</code></pre>
<p>Create a formula that will return <strong>#NA</strong> when the formula returns TRUE</p>
<pre><code>sFormula = "=IF(AND(A:A="""",E:E<>""""),NA(),"""")"
</code></pre>
<p>Put that formula in Column H, to find the rows that are to be deleted...</p>
<pre><code>Range("H5:H" & Range("E65536").End(xlUp).Row).Formula = sFormula
</code></pre>
<p>Now use SpecialCells to highlight the rows to be deleted:</p>
<pre><code>Range("H5:H" & Range("E65536").End(xlUp).Row).SpecialCells(xlCellTypeFormulas, xlErrors).entirerow.select
</code></pre>
<p>This line of code would highlight just Column A by using <strong>OFFSET</strong> in case instead of deleting the entire row, you wanted to put some text in, or clear it</p>
<pre><code>Range("H5:H" & Range("E65536").End(xlUp).Row).SpecialCells(xlCellTypeFormulas, xlErrors).Offset(0, -7).select
</code></pre>
<p>and the below line of code will delete thhe entire row <strong>because we can :)</strong></p>
<pre><code>Range("H5:H" & Range("E65536").End(xlUp).Row).SpecialCells(xlCellTypeFormulas, xlErrors).EntireRow.Delete shift:=xlup
' clean up the formula
Range("H5:H" & Range("E65536").End(xlUp).Row).Clear
'
End Sub
</code></pre>
<p>BTW, it's also possible <strong>WITH A LOOP</strong> if you really want one :)</p>
<p><strong>One more thing, before Excel 2010 there was a limit of 8192 rows</strong> (I think because this feature <em>went all the way back to 8-bit versions of Excel maybe</em>)</p>
<p>The VBA legend Ron de Bruin (on whose website I first picked up this technique, among others) <a href="http://www.rondebruin.nl/specialcells.htm" rel="nofollow">has something to say about this</a></p>
<p>Philip</p> |
17,297,764 | JQuery event handler when select element is loaded | <p>Is there an event handler to use in JQuery when a DOM <strong>select</strong> element has finished loading?
This is what I want to achieve. It is working with other events except 'load'. </p>
<p>This piece of code is loaded in the head.</p>
<pre><code>$(document).on('load', 'select', function(){
var currentSelectVal = $(this).val();
alert(currentSelectVal);
} );
</code></pre>
<p>The question was badly formed earlier. I need to attach the event handler to all <strong>select</strong> elements, both present when the document is loaded and dynamically created later. </p>
<p>They are loaded from a JQuery Post to a php-page. Similar to this: </p>
<pre><code>$.post("./user_functions.php",
{reason: "get_users", userID: uID})
.done(function(data) { $("#userSelector").html(data);
});
</code></pre> | 17,298,020 | 7 | 6 | null | 2013-06-25 12:47:10.873 UTC | 3 | 2022-07-17 07:45:51.597 UTC | 2022-07-17 07:45:51.597 UTC | null | 4,370,109 | null | 1,743,457 | null | 1 | 5 | javascript|jquery|dom|jquery-events | 43,994 | <p>I think we're all confused. But a quick break down of your options.<br /><sub>
After an update made to the Question, it looks like the answer you might seek is my last example. Please consider all other information as well though, as it might help you determine a better process for your "End Goal".</sub></p>
<p>First, You have the DOM Load event as pointed out in another answer. This will trigger when the page is finished loading and should always be your first call in HEAD JavaScript. to learn more, please see <a href="http://api.jquery.com/ready/" rel="noreferrer">this API Documentation</a>.</p>
<h2>Example</h2>
<pre><code>$(document).ready(function () {
alert($('select').val());
})
/* |OR| */
$(function() {
alert($('select').val());
})
</code></pre>
<p>Then you have Events you can attach to the Select Element, such as "change", "keyup", "keydown", etc... The usual event bindings are on "change" and "keyup" as these 2 are the most common end events taking action in which the user expects "change". To learn more please read about jQuery's <a href="http://api.jquery.com/delegate/" rel="noreferrer">.delegate()</a> (out-dated ver 1.6 and below only), <a href="http://api.jquery.com/on/" rel="noreferrer">.on()</a>, <a href="http://api.jquery.com/change/" rel="noreferrer">.change()</a>, and <a href="http://api.jquery.com/keyup/" rel="noreferrer">.keyup()</a>.</p>
<h2>Example</h2>
<pre><code>$(document).on('change keyup', 'select', function(e) {
var currentSelectVal = $(this).val();
alert(currentSelectVal);
})
</code></pre>
<p>Now <code>delegating</code> the change event to the document is not <em>"necessary</em>", however, it can really save headache down the road. Delegating allow future Elements (stuff not loaded on DOM Load event), that meet the Selector qualifications (exp. 'select', '#elementID', or '.element-class') to automatically have these event methods assigned to them.</p>
<p>However, if you know this is not going to be an issue, then you can use event names as jQuery Element Object Methods with a little shorter code.</p>
<h2>Example</h2>
<pre><code>$('select').change(function(e) {
var currentSelectVal = $(this).val();
alert(currentSelectVal);
})
</code></pre>
<p>On a final note, there is also the "success" and "complete" events that take place during some Ajax call. All jQuery Ajax methods have these 2 events in one way or another. These events allow you to perform action after the Ajax call is complete. </p>
<p>For example, if you wanted to get the value of a select box AFTER and Ajax call was made.</p>
<h2>Example</h2>
<pre><code>$.ajax({
url: 'http://www.mysite.com/ajax.php',
succuess: function(data) {
alert($("select#MyID").val());
}
})
/* |OR| */
$.post("example.php", function() { alert("success"); })
.done(function() { alert($("select#MyID").val()); })
/* |OR| */
$("#element").load("example.php", function(response, status, xhr) {
alert($("select#MyID").val());
});
</code></pre>
<p>More reading:</p>
<ul>
<li><a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">.ajax()</a></li>
<li><a href="http://api.jquery.com/jQuery.get/" rel="noreferrer">.get()</a></li>
<li><a href="http://api.jquery.com/jQuery.load/" rel="noreferrer">.load()</a></li>
<li><a href="http://api.jquery.com/jQuery.post/" rel="noreferrer">.post()</a></li>
</ul>
<p>Something else to keep in mind, all jQuery Ajax methods (like .get, .post) are just shorthand versions of <code>$.ajax({ /* options|callbacks */ })</code>!</p> |
58,215,104 | What's the net::ERR_HTTP2_PROTOCOL_ERROR about? | <p>I'm currently working on a website, which triggers a <code>net::ERR_HTTP2_PROTOCOL_ERROR 200</code> error on Google Chrome. I'm not sure exactly what can provoke this error, I just noticed it pops out only when accessing the website in HTTPS. I can't be 100% sure it is related, but it looks like it prevents JavaScript to be executed properly.</p>
<p>For instance, the following scenario happens :</p>
<ol>
<li><p>I'm accessing the website in HTTPS</p>
</li>
<li><p>My Twitter feed integrated via <a href="https://publish.twitter.com" rel="noreferrer">https://publish.twitter.com</a> isn't loaded at all</p>
</li>
<li><p>I can notice in the console the ERR_HTTP2_PROTOCOL_ERROR</p>
</li>
<li><p>If I remove the code to load the Twitter feed, the error remains</p>
</li>
<li><p>If I access the website in HTTP, the Twitter feed appears and the error disappears</p>
</li>
</ol>
<p>Google Chrome is the only web browser triggering the error: it works well on both Edge and Firefox.
(NB: I tried with Safari, and I have a similar <code>kcferrordomaincfnetwork 303</code> error)</p>
<p>I was wondering if it could be related to the header returned by the server since there is this '200' mention in the error, and a 404 / 500 page isn't triggering anything.</p>
<p>Thing is the error isn't documented at all. Google search gives me very few results. Moreover, I noticed it appears on very recent Google Chrome releases; the error doesn't pop on v.64.X, but it does on v.75+ (regardless of the OS; I'm working on Mac tho).</p>
<hr />
<p>Might be related to <a href="https://stackoverflow.com/questions/49927327/website-ok-on-firefox-but-not-on-safari-kcferrordomaincfnetwork-error-303-neit">Website OK on Firefox but not on Safari (kCFErrorDomainCFNetwork error 303) neither Chrome (net::ERR_SPDY_PROTOCOL_ERROR)</a></p>
<hr />
<p>Findings from further investigations are the following:</p>
<ul>
<li><strong>error doesn't pop on the exact same page if server returns 404 instead of 2XX</strong></li>
<li>error doesn't pop on local with a HTTPS certificate</li>
<li>error pops on a different server (both are OVH's), which uses a different certificate</li>
<li>error pops no matter what PHP version is used, from 5.6 to 7.3 (framework used : Cakephp 2.10)</li>
</ul>
<p>As requested, below is the returned header for the failing ressource, which is the whole web page. Even if the error is triggering on each page having a HTTP header 200, those pages are always loading on client's browser, but sometimes an element is missing (in my exemple, the external Twitter feed). Every other asset on the Network tab has a success return, except the whole document itself.
<a href="https://i.stack.imgur.com/ZkdHo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZkdHo.png" alt="line that failed in console" /></a></p>
<p>Google Chrome header (with error):</p>
<p><a href="https://i.stack.imgur.com/0wCrD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0wCrD.png" alt="Chrome header" /></a></p>
<p>Firefox header (without error):</p>
<p><a href="https://i.stack.imgur.com/AAtn8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AAtn8.png" alt="Firefox header" /></a></p>
<p>A <code>curl --head --http2</code> request in console returns the following success:</p>
<pre><code>HTTP/2 200
date: Fri, 04 Oct 2019 08:04:51 GMT
content-type: text/html; charset=UTF-8
content-length: 127089
set-cookie: SERVERID31396=2341116; path=/; max-age=900
server: Apache
x-powered-by: PHP/7.2
set-cookie: xxxxx=0919c5563fc87d601ab99e2f85d4217d; expires=Fri, 04-Oct-2019 12:04:51 GMT; Max-Age=14400; path=/; secure; HttpOnly
vary: Accept-Encoding
</code></pre>
<hr />
<p>Trying to go deeper with the chrome://net-export/ and <a href="https://netlog-viewer.appspot.com" rel="noreferrer">https://netlog-viewer.appspot.com</a> tools is telling me the request ends with a RST_STREAM :</p>
<pre><code>t=123354 [st=5170] HTTP2_SESSION_RECV_RST_STREAM
--> error_code = "2 (INTERNAL_ERROR)"
--> stream_id = 1
</code></pre>
<p>For what I read in <a href="https://stackoverflow.com/questions/28736463/rst-stream-frame-in-http2">this other post</a>, "<em>In HTTP/2, if the client wants to abort the request, it sends a RST_STREAM. When the server receives a RST_STREAM, it will stop sending DATA frames to the client, thereby stopping the response (or the download). The connection is still usable for other requests, and requests/responses that were concurrent with the one that has been aborted may continue to progress.
[...]
It is possible that by the time the RST_STREAM travels from the client to the server, the whole content of the request is in transit and will arrive to the client, which will discard it. However, for large response contents, sending a RST_STREAM may have a good chance to arrive to the server before the whole response content is sent, and therefore will save bandwidth.</em>"</p>
<p>The described behavior is the same as the one I can observe. But that would mean the browser is the culprit, and then I wouldn't understand why it happens on two identical pages with one having a 200 header and the other a 404 (same goes if I disable JS).</p> | 58,238,847 | 33 | 11 | null | 2019-10-03 08:23:48.727 UTC | 32 | 2022-08-27 17:04:41.01 UTC | 2021-04-22 06:11:29.473 UTC | null | 9,431,571 | null | 12,158,041 | null | 1 | 167 | php|wordpress|google-chrome|curl|http2 | 450,827 | <p>I didn't figure out what exactly was happening, but I found a solution.</p>
<p>The <strong>CDN feature of OVH</strong> was the culprit. I had it installed on my host service but disabled for my domain because I didn't need it.</p>
<p>Somehow, when I enable it, everything works.</p>
<p>I think it forces Apache to use the HTTP2 protocol, but what I don't understand is that there indeed was an HTTP2 mention in each of my headers, which I presume means the server was answering using the right protocol.</p>
<p>So the solution for my very particular case was to enable the CDN option on all concerned domains.</p>
<p>If anyone understands better what could have happened here, feel free to share explanations.</p> |
26,752,481 | remove git submodule but keep files | <p>I have a git submodule that I would like to become part of my main project (since I have a lot of project specific code that will go into the submodule). </p>
<p>So I'd like to remove the git references to the submodule and add the files to my main git repository.</p>
<p>But how ?</p> | 26,752,628 | 3 | 2 | null | 2014-11-05 08:20:00.887 UTC | 22 | 2021-09-18 16:33:32.187 UTC | 2015-06-07 20:20:01.787 UTC | null | 6,309 | null | 2,663,538 | null | 1 | 62 | git | 24,543 | <p>You must remove the <a href="https://stackoverflow.com/a/16581096/6309">gitlink entry</a> in your index:</p>
<pre><code>mv subfolder subfolder_tmp
git submodule deinit subfolder
git rm --cached subfolder
mv subfolder_tmp subfolder
git add subfolder
</code></pre>
<p>Replace <code>subfolder</code> with the name of the folder for your submodule, and make sure to not add any trailing slash.</p>
<p>This is what I detail in "<a href="https://stackoverflow.com/a/16162000/6309">Remove a Git submodule?</a>" and "<a href="https://stackoverflow.com/a/16162228/6309">un-submodule a git submodule</a>".</p>
<p>The <code>--cached</code> option allows you to keep the subfolder content in your disk... except <code>git submodule deinit</code> would already have removed that content anyway. Hence the <code>mv</code> part.</p>
<p>You then can add and commit that subfolder.</p> |
17,287,542 | How to set JAVA_HOME path on Ubuntu? | <p>How can I setup <code>JAVA_HOME</code> path without having to set it each time I restart my machine?</p>
<p>I've used the following ways when trying to set JAVA_HOME on my Ubuntu machine:</p>
<p>1) From terminal I've executed the following command:</p>
<pre><code>export JAVA_HOME=/usr/lib/jvm/jdk1.7.0
</code></pre>
<p>2) I've edited the <code>/etc/enviroment</code> file directly to add <code>JAVA_HOME</code> path in it</p>
<p>What's really strange is that if I test <code>JAVA_HOME</code> using the <code>echo</code> command after an of the above two ways, I can see it is set correctly, but if I restart, logout/ login again or even after working on the machine for a while the <code>JAVA_HOME</code> is no more set and I have to set it again using any of the above two ways.</p>
<p>So can someone please tell me what I am doing wrong here?</p> | 17,287,562 | 2 | 3 | null | 2013-06-25 01:01:21.24 UTC | 12 | 2019-07-02 17:41:59.247 UTC | 2019-07-02 17:41:59.247 UTC | null | 608,639 | null | 1,574,486 | null | 1 | 57 | java|linux|ubuntu|java-home | 216,150 | <p>I normally set paths in </p>
<pre><code>~/.bashrc
</code></pre>
<p>However for Java, I followed instructions at
<a href="https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7">https://askubuntu.com/questions/55848/how-do-i-install-oracle-java-jdk-7</a></p>
<p>and it was sufficient for me.</p>
<p>you can also define multiple java_home's and have only one of them active (rest commented).</p>
<p>suppose in your bashrc file, you have</p>
<p><code>export JAVA_HOME=......jdk1.7</code></p>
<p><code>#export JAVA_HOME=......jdk1.8</code></p>
<p>notice 1.8 is commented. Once you do </p>
<p><code>source ~/.bashrc</code></p>
<p>jdk1.7 will be in path.</p>
<p>you can switch them fairly easily this way. There are other more permanent solutions too. The link I posted has that info.</p> |
30,649,994 | Can I catch an error from async without using await? | <p>Can errors from a non-awaited async call be caught, sent to an original encapsulating try/catch, or raise an uncaught exception?</p>
<p>Here's an example of what I mean:</p>
<pre><code>async function fn1() {
console.log('executing fn1');
}
async function fn2() {
console.log('executing fn2');
throw new Error('from fn2');
}
async function test() {
try {
await fn1();
fn2();
}
catch(e) {
console.log('caught error inside test:', e);
}
}
test();
</code></pre>
<p>In this scenario, the error thrown from <code>fn2</code> will be swallowed silently, and definitely not caught by the original <code>try/catch</code>. I believe this is expected behavior, since <code>fn2</code> is most likely being shoved off to the event loop to finish at some point in the future, and <code>test</code> doesn't care when it finishes (which is intentional).</p>
<p>Is there any way to ensure that errors are not accidentally swallowed by a structure like this, short of putting a <code>try/catch</code> internal to <code>fn2</code> and doing something like emitting an error? I would even settle for an uncaught error without knowing how to catch it, I think -- I don't expect thrown errors to be typical program flow with what I am writing, but swallowing errors makes it relatively annoying to debug.</p>
<p>Side note, I'm using Babel to transpile the code using the babel-runtime transform, and executing it with node.</p> | 30,650,609 | 2 | 4 | null | 2015-06-04 17:05:39.703 UTC | 4 | 2019-09-28 11:04:37.237 UTC | 2015-07-10 15:47:55.423 UTC | null | 100,297 | null | 2,012,235 | null | 1 | 34 | javascript|async-await|promise|ecmascript-2016 | 16,210 | <p>Dealing with unhandled rejected native promises (and async/await uses native promises) is a feature supported now in V8. It's used in the latest Chrome to output debugging information when a rejected promise is unhandled; try the following at <a href="https://babeljs.io/repl/" rel="nofollow noreferrer">the Babel REPL</a>:</p>
<pre><code>async function executor() {
console.log("execute");
}
async function doStuff() {
console.log("do stuff");
throw new Error("omg");
}
function handleException() {
console.error("Exception handled");
}
(async function() {
try {
await executor();
doStuff();
} catch(e) {
handleException();
}
})()
</code></pre>
<p>You see that, even though the exception from <code>doStuff()</code> is lost (because we're not using <code>await</code> when we call it), Chrome logs that a rejected promise was unhandled to the console:</p>
<p><a href="https://i.stack.imgur.com/LLi8E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LLi8E.png" alt="Screenshot"></a>
</p>
<p>This is also available in Node.js 4.0+, though it requires listening to <a href="https://nodejs.org/docs/latest/api/process.html#process_event_unhandledrejection" rel="nofollow noreferrer">a special <code>unhandledRejection</code> event</a>:</p>
<pre><code>process.on('unhandledRejection', function(reason, p) {
console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason);
// application specific logging, throwing an error, or other logic here
});
</code></pre> |
18,396,501 | How to get/set current page URL (which works across space-time-browsers-versions) | <p>I want to get/set URL of the current page upon certain event.</p>
<p>It seems there are more than one approach for doing it as mentioned in questions/answers below.</p>
<p>Using Jquery</p>
<pre><code>Get URL - $(location).attr('href');
Set URL - $(location).attr('href',url);
</code></pre>
<p>Using JavaScript</p>
<pre><code>Get URL - myVar = window.location.href;
Set URL - window.location.href = "http://stackoverflow.com";
</code></pre>
<p>Which approach works across space-time-browsers-versions?</p>
<p><a href="https://stackoverflow.com/questions/406192/how-to-get-the-current-url-in-jquery?rq=1">Get current URL in JavaScript?</a></p>
<p><a href="https://stackoverflow.com/questions/503093/how-can-i-make-a-redirect-page-in-jquery-javascript?rq=1">How to redirect to another webpage in JavaScript/jQuery?</a></p> | 18,396,584 | 2 | 1 | null | 2013-08-23 06:43:43.797 UTC | 1 | 2014-09-26 12:53:06.84 UTC | 2017-05-23 12:25:19.71 UTC | null | -1 | null | 2,201,455 | null | 1 | 33 | javascript|jquery|dom | 97,274 | <p>I don't see any need to use jQuery for this. The following will work perfectly fine in all browsers:</p>
<pre><code>window.location.href = "http://stackoverflow.com";
</code></pre>
<p>Or even more simply:</p>
<pre><code>location.href = "http://stackoverflow.com";
</code></pre> |
18,393,448 | how to create and call a custom function in jQuery | <p>I need to create a simple function in jQuery which will call within other few functions</p>
<pre><code>$(document).ready(function() {
function reload_cart() {
alert('reload cart called');
}
});
$(document).ready(function() {
reload_cart(); //i need to call from here.
});
$(document).ready(function() {
$('a.add_to_cart').live('click', function (e) {
reload_cart(); //i need to call from here.
});
});
</code></pre>
<p>The error I get in firebug: <code>reload_cart() is not defined</code>.</p> | 18,393,488 | 3 | 0 | null | 2013-08-23 01:54:17.767 UTC | 3 | 2019-03-18 09:52:15.39 UTC | 2013-08-23 02:00:13.66 UTC | null | 1,380,918 | null | 1,911,703 | null | 1 | 19 | jquery|function | 104,290 | <p><code>reload_cart</code> is local to your first <code>$(document).ready()</code> callback. You can't call it from an outside scope.</p>
<p>You should merge your functions together:</p>
<pre><code>$(document).ready(function() {
function reload_cart() {
alert('reload cart called');
}
reload_cart();
$('a.add_to_cart').live('click', function(e) {
reload_cart();
});
});
</code></pre>
<p>An even better solution would be to create a <code>cart</code> object, add <code>reload</code> to its prototype, and initialize it outside of all of the callbacks.</p> |
23,093,327 | Is it possible to declare default argument in Java in String? | <p>Is it possible to use default argument in the method with String. The code is shown below:</p>
<pre><code>public void test(String name="exampleText") {
}
</code></pre>
<p>The code above generate error. Is it possible to correct it?</p> | 23,093,356 | 2 | 4 | null | 2014-04-15 20:00:54.32 UTC | 4 | 2017-11-23 17:48:49.01 UTC | 2014-04-15 20:03:51.78 UTC | null | 2,864,740 | null | 3,455,638 | null | 1 | 32 | java|methods|default-value | 84,004 | <p>No, the way you would normally do this is overload the method like so:</p>
<pre><code>public void test()
{
test("exampleText");
}
public void test(String name)
{
}
</code></pre> |
5,085,533 | Is a C++ preprocessor identical to a C preprocessor? | <p>I am wondering how different the preprocessors for C++ and <strong>C</strong> are.</p>
<p>The reason for the question is <a href="https://stackoverflow.com/questions/5085392/what-is-the-value-of-an-undefined-constant-used-in-if-c">this question</a> on a preprocessor-specific question where the paragraph of the standard that addresses the question has a different wording (and a different paragraph number) and also are difference concerning the <code>true</code> and <code>false</code> keywords in C++.</p>
<p>So, are there more differences or is this the only difference.</p>
<p>An extension of the question would be when is a source file emitted differently by a C++ preprocessor and a <strong>C</strong> preprocessor.</p> | 5,085,588 | 3 | 4 | null | 2011-02-23 00:00:07.303 UTC | 6 | 2016-03-10 06:22:57.073 UTC | 2017-05-23 11:54:25.38 UTC | null | -1 | null | 180,275 | null | 1 | 28 | c++|c|standards|c-preprocessor | 3,278 | <p>The C++03 preprocessor is (at least intended to be) similar to the C preprocessor before C99. Although the wording and paragraph numbers are slightly different, the only technical differences I'm aware of between the two are that the C++ preprocessor handles digraphs and universal character names, which are not present in C.</p>
<p>As of C99, the C preprocessor added some new capabilities (e.g., variadic macros) that do not exist in the current version of C++. I don't remember for sure, but don't believe that digraphs were added.</p>
<p>I believe C++0x will bring the two in line again (at least that's the intent). Again, the paragraph numbers and wording won't be identical, but I believe the intent is that they should work the same (other than retaining the differences mentioned above).</p> |
5,543,651 | Computing Standard Deviation in a stream | <p>Using Python, assume I'm running through a known quantity of items <code>I</code>, and have the ability to time how long it takes to process each one <code>t</code>, as well as a running total of time spent processing <code>T</code> and the number of items processed so far <code>c</code>. I'm currently calculating the average on the fly <code>A = T / c</code> but this can be skewed by say a single item taking an extraordinarily long time to process (a few seconds compared to a few milliseconds). </p>
<p>I would like to show a running Standard Deviation. How can I do this without keeping a record of each <code>t</code>?</p> | 5,543,818 | 3 | 2 | null | 2011-04-04 20:00:06.453 UTC | 21 | 2017-07-12 11:34:19.42 UTC | null | null | null | null | 185,657 | null | 1 | 40 | python|math | 20,179 | <p>I use <a href="https://stackoverflow.com/questions/895929/how-do-i-determine-the-standard-deviation-stddev-of-a-set-of-values">Welford's Method</a>, which gives more accurate results. This link points to <a href="http://www.johndcook.com/standard_deviation.html" rel="noreferrer">John D. Cook's overview</a>. Here's a paragraph from it that summarizes why it is a preferred approach:</p>
<blockquote>
<p>This better way of computing variance goes back to a 1962 paper by B. P. Welford and is presented in Donald Knuth’s Art of Computer Programming, Vol 2, page 232, 3rd edition. Although this solution has been known for decades, not enough people know about it. Most people are probably unaware that computing sample variance can be difficult until the first time they compute a standard deviation and get an exception for taking the square root of a negative number.</p>
</blockquote> |
25,438,560 | Disable Laravel's built-in error handling methods | <p>Is there anyway to disable the Laravel error handler all together?</p>
<p>I want to simply display <strong>standard PHP errors</strong>, <strong>not</strong> the <code>Whoops, looks like something went wrong</code> errors.</p> | 25,496,104 | 7 | 3 | null | 2014-08-22 02:03:02.03 UTC | 11 | 2021-11-29 16:09:42.587 UTC | 2021-11-29 16:09:42.587 UTC | null | 1,255,289 | null | 268,074 | null | 1 | 30 | php|laravel|error-handling | 28,187 | <p>Not without majorly violating the principles of the framework (which I'll tell you how to do below, if you're still interested). </p>
<p>There's a few things that make this difficult to accomplish. It's easy enough to unset the default error and exception handlers</p>
<pre><code>set_error_handler(null);
set_exception_handler(null);
</code></pre>
<p>but that leaves you with two major hurdles.</p>
<p>The first is Laravel registers a shutdown handler as part of its bootstrapping, and this shutdown function will look for the last error, and if it was a fatal error, manually call the exception handling code. There's <a href="https://stackoverflow.com/questions/2726524/can-you-unregister-a-shutdown-function">no easy way to un-register a shutdown function</a>.</p>
<p>The second is, the main Laravel Application handler looks like this</p>
<pre><code>#File: vendor/laravel/framework/src/Illuminate/Foundation/Application.php
public function handle(SymfonyRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
try
{
$this->refreshRequest($request = Request::createFromBase($request));
$this->boot();
return $this->dispatch($request);
}
catch (\Exception $e)
{
if ($this->runningUnitTests()) throw $e;
return $this['exception']->handleException($e);
}
}
</code></pre>
<p>That is -- if you application code throws an exception, Laravel catches it here and manually calls the exception's <code>handleException</code> method (which triggers the standard Laravel exception handling). There's no way to let PHP handle a fatal exception that happens in your application, Laravel blocks that from ever happening. </p>
<h2>The part where I tell you how to do what you want</h2>
<p>All this means we need to replace the main Laravel application with our own. In <code>bootstrap/start.php</code>, there's the following line</p>
<pre><code>#File: bootstrap/start.php
$app = new Illuminate\Foundation\Application;
</code></pre>
<p>Replace it with the following</p>
<pre><code>ini_set('display_errors','1');
class MyApplication extends Illuminate\Foundation\Application
{
function startExceptionHandling()
{
//do nothing
}
public function handle(Symfony\Component\HttpFoundation\Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
$this->refreshRequest($request = Request::createFromBase($request));
$this->boot();
return $this->dispatch($request);
}
}
$app = new MyApplication;
</code></pre>
<p>The first thing we're doing is setting PHP's display errors ini to <code>1</code>. This makes sure errors are output to the browser.</p>
<p>Next, we're defining a new application class that extends the real application class.</p>
<p>Finally, we replace the real Laravel <code>$app</code> object with an object instantiated by our class.</p>
<p>In our application class itself we blank out <code>startExceptionHandling</code>. This prevents Laravel from setting up custom exception, error, and shutdown callbacks. We also define <code>handle</code> to remove the application boot/dispatch from a try/catch. This is the most fragile part of the process, and may look different depending on your Laravel version. </p>
<h2>Final Warnings</h2>
<p>If the <code>handle</code> method changes in future version of Laravel this will break.</p>
<p>If custom packages rely on adding custom exception handlers, they may break.</p>
<p>I'd recommend staying away from this as anything other than a temporary debugging technique.</p> |
9,072,844 | How can I check if a string contains ANY letters from the alphabet? | <p>What is best pure Python implementation to check if a string contains ANY letters from the alphabet?</p>
<pre><code>string_1 = "(555).555-5555"
string_2 = "(555) 555 - 5555 ext. 5555
</code></pre>
<p>Where <code>string_1</code> would return <code>False</code> for having no letters of the alphabet in it and <code>string_2</code> would return <code>True</code> for having letter.</p> | 9,072,937 | 7 | 4 | null | 2012-01-31 00:29:55.87 UTC | 35 | 2020-03-30 11:06:50.32 UTC | 2017-09-19 15:22:20.313 UTC | null | 754,991 | null | 1,030,126 | null | 1 | 113 | python|string | 269,297 | <p>Regex should be a fast approach:</p>
<pre><code>re.search('[a-zA-Z]', the_string)
</code></pre> |
18,487,406 | How do I tell Gradle to use specific JDK version? | <p>I can't figure out to get this working.</p>
<p>Scenario:</p>
<ul>
<li>I have an application built with gradle</li>
<li>The application uses JavaFX</li>
</ul>
<p>What I want</p>
<ul>
<li>Use a variable (defined per developer machine) which points to an installation of a JDK which will be used for building the whole application / tests / ...</li>
</ul>
<p>I thought about having the <code>gradle.properties</code> file, defining the variable. Something like</p>
<pre><code>JAVA_HOME_FOR_MY_PROJECT=<path to my desired JDK>
</code></pre>
<p>What I don't want</p>
<ul>
<li>point <code>JAVA_HOME</code> to the desired JDK</li>
</ul>
<p>I could live with many suggestions:</p>
<ul>
<li>a solution that defines a system environment variable which I'm able to check in my build.gradle script</li>
<li>a variable defined in gradle.properties</li>
<li>overriding the JAVA_HOME variable only for the build context (something like <code>use JAVA_HOME=<my special JDK path defined somewhere else defined></code>)</li>
<li>something else I didn't think about</li>
</ul>
<p>Question:</p>
<ul>
<li>How to wire a variable (how ever defined, as variable in the <code>gradle.properties</code>, system environment variable, ...) to the build process?</li>
</ul>
<p>I have more than one JDK7 available and need to point to a special version (minimum JDK_u version).</p>
<p>Any answer is appreciated and I'm thankful for every hint to the right direction.</p> | 21,212,790 | 23 | 8 | null | 2013-08-28 12:05:50.31 UTC | 124 | 2022-08-10 07:49:37.997 UTC | 2017-08-23 22:27:31.753 UTC | null | 3,885,376 | null | 367,277 | null | 1 | 468 | java|gradle|build.gradle | 585,021 | <p>Two ways</p>
<ol>
<li>In <code>gradle.properties</code> in the <code>.gradle</code> directory in your <code>HOME_DIRECTORY</code> set <code>org.gradle.java.home=/path_to_jdk_directory</code></li>
</ol>
<p>or:</p>
<ol start="2">
<li><p>In your <code>build.gradle</code></p>
<pre><code> compileJava.options.fork = true
compileJava.options.forkOptions.executable = '/path_to_javac'
</code></pre>
</li>
</ol> |
14,927,980 | How to make a transparent JFrame but keep everything else the same? | <p>I want to make the <code>JFrame</code> transparent, but the image on top of it to be non-transparent. This is what I have now: </p>
<p><img src="https://i.stack.imgur.com/V9In2.jpg" alt="enter image description here"></p>
<p>Does anyone know a way to make only the <code>JFrame</code> transparent?</p>
<p>Here's my code:</p>
<pre><code>import javax.swing.*;
import java.awt.*;
import com.sun.awt.AWTUtilities;
import static java.awt.GraphicsDevice.WindowTranslucency.*;
public class SplashDemo extends JFrame
{
public SplashDemo()
{
setUndecorated(true);
setSize(200, 200);
add(new JLabel(new ImageIcon("puppy2.png")));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
setOpacity(0.85f);
}
public static void main(String[] args)
{
new SplashDemo();
}
}
</code></pre> | 14,928,212 | 1 | 1 | null | 2013-02-18 00:53:12.07 UTC | 10 | 2017-12-04 18:53:49.98 UTC | 2014-07-04 04:34:05.123 UTC | null | 418,556 | null | 1,196,747 | null | 1 | 14 | java|swing|jframe|transparency|translucency | 16,251 | <p>Basically, you need to make a transparent window and a translucent content pane. This will mean anything added to the content pane will continue to be rendered without additional alphering...</p>
<p><img src="https://i.stack.imgur.com/CsG0T.png" alt="enter image description here"></p>
<pre><code>public class TranscluentWindow {
public static void main(String[] args) {
new TranscluentWindow();
}
public TranscluentWindow() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JWindow frame = new JWindow();
frame.setAlwaysOnTop(true);
frame.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
SwingUtilities.getWindowAncestor(e.getComponent()).dispose();
}
}
});
frame.setBackground(new Color(0,0,0,0));
frame.setContentPane(new TranslucentPane());
frame.add(new JLabel(new ImageIcon(ImageIO.read(getClass().getResource("/Puppy.png")))));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class TranslucentPane extends JPanel {
public TranslucentPane() {
setOpaque(false);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setComposite(AlphaComposite.SrcOver.derive(0.85f));
g2d.setColor(getBackground());
g2d.fillRect(0, 0, getWidth(), getHeight());
}
}
}
</code></pre> |
15,082,316 | how to set active class to nav menu from twitter bootstrap | <p>I'm new to the <strong>twitter bootstrap</strong>. Using there <strong>navigation menus</strong> . I'm trying to set active class to selected menu.
my menu is - </p>
<pre><code><div class="nav-collapse">
<ul class="nav">
<li id="home" class="active"><a href="~/Home/Index">Home</a></li>
<li><a href="#">Project</a></li>
<li><a href="#">Customer</a></li>
<li><a href="#">Staff</a></li>
<li id="broker"><a href="~/Home/Broker">Broker</a></li>
<li><a href="#">Sale</a></li>
</ul>
</div>
</code></pre>
<p>I tried following thing after googling on this that i have to set active class on each page from menu like as--</p>
<pre><code><script>
$(document).ready(function () {
$('#home').addClass('active');
});
</script>
</code></pre>
<p>but problem for above is that i set home menu selected by default. Then it always get selected. <strong>Is there any other way to do this ? , or which i can generalize and keep my js in layout file itself?</strong> </p>
<p>After executing application my menu looks -
<img src="https://i.stack.imgur.com/qhndE.png" alt="enter image description here"></p>
<p>after clicking on other menu item i get following result-
<img src="https://i.stack.imgur.com/cbFtT.png" alt="enter image description here"></p>
<p>And i added following scripts on Index view and Broker view ---</p>
<pre><code><script>
$(document).ready(function () {
$('#home').addClass('active');
});
</script>
<script>
$(document).ready(function () {
$('#broker').addClass('active');
});
</script>
</code></pre>
<p>respectively.</p> | 15,082,879 | 13 | 4 | null | 2013-02-26 05:53:44.437 UTC | 13 | 2019-10-22 03:57:29.113 UTC | 2018-01-06 00:24:21.56 UTC | null | 2,666,042 | null | 709,397 | null | 1 | 30 | javascript|jquery|css|twitter-bootstrap|menu | 110,019 | <p>it is a workaround. try </p>
<pre><code><div class="nav-collapse">
<ul class="nav">
<li id="home" class="active"><a href="~/Home/Index">Home</a></li>
<li><a href="#">Project</a></li>
<li><a href="#">Customer</a></li>
<li><a href="#">Staff</a></li>
<li id="demo"><a href="~/Home/demo">Broker</a></li>
<li id='sale'><a href="#">Sale</a></li>
</ul>
</div>
</code></pre>
<p>and on each page js add</p>
<pre><code>$(document).ready(function () {
$(".nav li").removeClass("active");//this will remove the active class from
//previously active menu item
$('#home').addClass('active');
//for demo
//$('#demo').addClass('active');
//for sale
//$('#sale').addClass('active');
});
</code></pre> |
15,287,678 | Warning: attempt to present ViewController whose view is not in the window hierarchy | <p>In one of my apps, I'm calling a viewController from the <code>application didReceiveLocalNotification</code> method. The page loads successfully, but it shows a warning as :</p>
<pre><code> Warning: Attempt to present <blankPageViewController: 0x1fda5190> on
<ViewController: 0x1fd85330> whose view is not in the window hierarchy!
</code></pre>
<p>My code is as follows :</p>
<pre><code> -(void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
blankPageViewController *myView = [[blankPageViewController alloc]
initWithNibName:@"blankPageViewController" bundle: nil];
myView.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self.viewController presentViewController:myView animated:NO completion:nil];
}
</code></pre> | 15,360,428 | 9 | 2 | null | 2013-03-08 05:59:34.44 UTC | 16 | 2016-06-03 07:35:21.95 UTC | 2014-07-25 19:32:13.97 UTC | null | 2,144,085 | null | 1,968,887 | null | 1 | 31 | ios|objective-c|xcode|uiviewcontroller | 50,206 | <p>Finally I solved that issue with the following code.</p>
<pre><code>-(void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.blankviewController = [[blankPageViewController alloc] initWithNibName:@"blankPageViewController" bundle:nil];
self.window.rootViewController = self.blankviewController;
[self.window makeKeyAndVisible];
}
</code></pre> |
43,495,549 | Cannot install Support repository and sync project in Android Studio | <p>I am trying to use the support libraries of version 25.2.0
so I will be able to use the <a href="https://android-arsenal.com/details/1/5383" rel="noreferrer">CameraKit</a> library.</p>
<p>I have got the newest build tools downloaded: </p>
<p><a href="https://i.stack.imgur.com/uNsOl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uNsOl.png" alt="enter image description here"></a></p>
<p>and the support repository:
<a href="https://i.stack.imgur.com/gNhKG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gNhKG.png" alt="enter image description here"></a></p>
<p>my gradle file: </p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
defaultConfig {
applicationId "com.sample.myapp"
minSdkVersion 21
targetSdkVersion 25
versionCode 1
versionName "1.1"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
maven {
url "https://jitpack.io"
}
mavenCentral()
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile 'junit:junit:4.12'
// Google libraries
compile 'com.android.support:appcompat-v7:25.2.0'
compile 'com.android.support:design:25.2.0'
compile 'com.android.support:support-v4:25.2.0'
compile 'com.google.android.gms:play-services-vision:10.0.1'
compile 'com.android.volley:volley:1.0.0'
// Third party libraries
compile 'com.flurgle:camerakit:0.9.17'
compile 'com.android.support:recyclerview-v7:25.2.0'
compile 'com.android.support:cardview-v7:25.2.0'
}
</code></pre>
<p>Problem:
For each support-library I get the issue: </p>
<pre><code>Failed to resolve com.android.support:cardview-v7:25.2.0
</code></pre>
<p>If I try to click on <strong>Install repository and sync project</strong> nothing happens. </p>
<p><a href="https://i.stack.imgur.com/IIMYU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IIMYU.png" alt="enter image description here"></a></p>
<p>I have followed that <a href="https://github.com/gogopop/CameraKit-Android/blob/master/demo/build.gradle" rel="noreferrer">gradle file</a> as an example. Were could be my mistake?</p> | 43,495,905 | 4 | 6 | null | 2017-04-19 12:18:42.95 UTC | 12 | 2020-03-07 21:58:01.577 UTC | 2018-05-28 16:27:19.313 UTC | null | 2,308,683 | null | 4,125,633 | null | 1 | 40 | android|android-studio|gradle|android-support-library|build-tools | 61,260 | <p>Try using the latest support library versions:</p>
<pre><code>compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.google.android.gms:play-services-vision:10.2.1'
compile 'com.android.volley:volley:1.0.0'
// Third party libraries
compile 'com.flurgle:camerakit:0.9.17'
compile 'com.android.support:recyclerview-v7:25.3.1'
compile 'com.android.support:cardview-v7:25.3.1'
</code></pre>
<p>here is the detail <a href="https://developer.android.com/topic/libraries/support-library/packages.html#custom-tabs" rel="noreferrer">Dependencies</a> </p>
<p><strong>EDIT</strong></p>
<p>Use <a href="https://developer.android.com/studio/build/dependencies.html#google-maven" rel="noreferrer">Google Maven Repository</a></p>
<p>To add them to your build, you need to first include Google's Maven repository in your top-level build.gradle file:</p>
<p><strong>Project -- build.gradle</strong> (Not app <code>build.gradle</code>)</p>
<pre><code> allprojects {
repositories {
// If you're using a version of Gradle lower than 4.1, you must instead use:
maven {
url 'https://maven.google.com'
}
// An alternative URL is 'https://dl.google.com/dl/android/maven2/'
jcenter()
}
}
</code></pre> |
28,221,271 | How to write a test for Elasticsearch custom plugin? | <p>I create custom <strong>Elasticsearch</strong> plugin. Now I want to write a test for this plugin.
My expectations were - that I could run embedded <strong>Elasticsearch</strong> instance, set up it properly and then do some testing (index some documents, then query for it)</p>
<p>Problem is that I couldn't set up my plugin properly</p>
<p>Custom plugin code is parsing JSON query and set up some objects for later usage:</p>
<pre><code>public class CustomQueryParserPlugin extends AbstractPlugin {
public static final String PLUGIN_NAME = "custom_query";
private final Settings settings;
@Inject
public CustomQueryParserPlugin (Settings settings) {
this.settings = settings;
}
@Override
public String name() {
return PLUGIN_NAME;
}
@Override
public String description() {
return "custom plugin";
}
public void onModule(IndicesQueriesModule module) {
module.addQuery(new CustomQueryParser(settings));
}
}
</code></pre>
<p>Test code:</p>
<pre><code>public class CustomParserPluginTest extends ElasticsearchSingleNodeTest {
private static Node newNode() {
final Settings settings = ImmutableSettings.builder()
.put(ClusterName.SETTING, nodeName())
.put("node.name", nodeName())
.put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1)
.put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)
.put(EsExecutors.PROCESSORS, 1) // limit the number of threads created
.put("http.enabled", false)
.put("plugin.types", CustomParserPlugin.class.getName())
.put("path.plugins", pathToPlugin)
.put("index.store.type", "ram")
.put("config.ignore_system_properties", true) // make sure we get what we set :)
.put("gateway.type", "none").build();
Node build = NodeBuilder.nodeBuilder().local(true).data(true).settings(
settings).build();
build.start();
assertThat(DiscoveryNode.localNode(build.settings()), is(true));
return build;
}
@Test
public void jsonParsing() throws URISyntaxException {
final Client client = newNode().client();
final SearchResponse test = client.prepareSearch("test-index").setSource(addQuery()).execute().actionGet();
}
private String addQuery() {
return "{"match_all":{"boost":1.2}}"
}
</code></pre>
<p>I've try multiple values for <strong>pathToPlugin</strong> - but nothing seems to works well, because JSON query always give me an exception:</p>
<pre><code>QueryParsingException[[test-index] No query registered for [custom_query]];
</code></pre>
<p>All documentation I could find was about installing plugins and testing them on some local Elasticsearch installation.</p>
<p>What I am doing wrong here? Is there any documentation or examples of tests like that?</p>
<p><strong>UPD</strong>. Here is a repo with extracted code of CustomQueryParserPlugin - <a href="https://github.com/MysterionRise/es-custom-parser">https://github.com/MysterionRise/es-custom-parser</a></p>
<p>May be in initialize section in test I need to create in memory index?</p> | 29,945,160 | 1 | 2 | null | 2015-01-29 17:49:13.54 UTC | 8 | 2015-10-13 03:59:16.613 UTC | 2015-04-29 10:37:24.27 UTC | null | 2,663,985 | null | 2,663,985 | null | 1 | 26 | java|elasticsearch | 3,526 | <p>To write tests for you plugin you can use <a href="https://github.com/codelibs/elasticsearch-cluster-runner">Elasticsearch Cluster Runner</a>.
For reference check how <a href="https://github.com/codelibs/elasticsearch-minhash">MinHash Plugin</a> wrote test. </p>
<p><strong>UPDATE:</strong></p>
<p>I've changed <code>CustomParserPluginTest</code> class to use Elasticsearch Cluster Runner:</p>
<pre><code>import static org.codelibs.elasticsearch.runner.ElasticsearchClusterRunner.newConfigs;
import java.util.Map;
import junit.framework.TestCase;
import org.codelibs.elasticsearch.runner.ElasticsearchClusterRunner;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.ImmutableSettings.Builder;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.get.GetField;
import org.junit.Assert;
import org.elasticsearch.action.search.SearchResponse;
import static org.hamcrest.core.Is.is;
public class CustomParserPluginTest extends TestCase {
private ElasticsearchClusterRunner runner;
@Override
protected void setUp() throws Exception {
// create runner instance
runner = new ElasticsearchClusterRunner();
// create ES nodes
runner.onBuild(new ElasticsearchClusterRunner.Builder() {
@Override
public void build(final int number, final Builder settingsBuilder) {
}
}).build(newConfigs().ramIndexStore().numOfNode(1));
// wait for yellow status
runner.ensureYellow();
}
@Override
protected void tearDown() throws Exception {
// close runner
runner.close();
// delete all files
runner.clean();
}
public void test_jsonParsing() throws Exception {
final String index = "test_index";
runner.createIndex(index, ImmutableSettings.builder().build());
runner.ensureYellow(index);
final SearchResponse test = runner.client().prepareSearch(index).setSource(addQuery()).execute().actionGet();
}
private String addQuery() {
return "{\"match_all\":{\"boost\":1.2}}";
}
}
</code></pre>
<p>I've created <code>es-plugin.properties</code>(pluginrootdirectory\src\main\resources) file with following content which will force elasticsearch instance to load plugin:</p>
<pre><code>plugin=CustomQueryParserPlugin
</code></pre>
<p>When you will run the this test you will see in the output that the newly created insance of elasticsearch loaded the plugin.</p>
<blockquote>
<p>[2015-04-29 19:22:10,783][INFO ][org.elasticsearch.node ] [Node 1]
version[1.5 .0], pid[34360], build[5448160/2015-03-23T14:30:58Z]
[2015-04-29 19:22:10,784][INFO ][org.elasticsearch.node ] [Node 1]
initializin g ... [2015-04-29 19:22:10,795][INFO
][org.elasticsearch.plugins] [Node 1] loaded [<strong>custom_query</strong>], sites []
[2015-04-29 19:22:13,342][INFO ][org.elasticsearch.node ] [Node 1]
initialized</p>
<p>[2015-04-29 19:22:13,342][INFO ][org.elasticsearch.node ] [Node 1]
starting .. .</p>
</blockquote>
<p>Hope this helps.</p> |
8,672,472 | Is there a built-in binary-search In Ruby? | <p>I am looking for a built-in Ruby method that has the same functionality as <code>index</code> but uses a binary search algorithm, and thus requires a pre-sorted array.</p>
<p>I know I could write my own implementation, but according to "<a href="https://stackoverflow.com/questions/7436155/rubyindex-method-vs-binary-search">Ruby#index Method VS Binary Search</a>", the built-in simple iterative search used by index is faster than a pure-Ruby version of binary search, since the built-in method is written in C. </p>
<p>Does Ruby provide any built-in methods that do binary search?</p> | 8,672,512 | 3 | 4 | null | 2011-12-29 19:28:47.087 UTC | 4 | 2018-05-07 13:28:21.64 UTC | 2017-05-23 11:45:52.017 UTC | null | -1 | null | 438,615 | null | 1 | 39 | ruby|binary-search | 24,858 | <p>Ruby 2.0 introduced <a href="http://ruby-doc.org/core/Array.html#method-i-bsearch"><code>Array#bsearch</code></a> and <a href="http://ruby-doc.org/core/Range.html#method-i-bsearch"><code>Range#bsearch</code></a>.</p>
<p>For Ruby 1.9, you should look into the <a href="http://rubygems.org/gems/bsearch"><code>bsearch</code></a> and <a href="https://github.com/tyler/binary_search"><code>binary_search</code></a> gems.
Other possibility is to use a different collection than an array, like <a href="http://rubygems.org/gems/rbtree">using <code>rbtree</code></a></p>
<p><code>bsearch</code> is in my <a href="https://github.com/marcandre/backports"><code>backports</code> gem</a>, but this is a pure Ruby version, so quite a bit slower. Note that a pure Ruby binary search will still be faster than a linear builtin search like <code>index</code> or <code>include?</code> for big enough arrays/ranges (or expensive comparisons), since it's not the same order of complexity <code>O(log n)</code> vs <code>O(n)</code>.</p>
<p>To play with it today, you can <code>require 'backports/2.0.0/array/bsearch'</code> or <code>require 'backports/2.0.0/range/bsearch'</code>.</p>
<p>Good luck!</p> |
8,773,721 | How to send a string over a socket in C# | <p>I am testing this locally, so the IP to connect to can be <code>localhost or 127.0.0.1</code></p>
<p>After sending it, it receives a string back. That would also be handy.</p> | 8,777,012 | 2 | 5 | null | 2012-01-07 22:41:41.32 UTC | 6 | 2021-01-13 13:03:46.073 UTC | 2013-01-22 05:22:27.78 UTC | null | 1,410,342 | null | 1,122,834 | null | 1 | 10 | c#|string|sockets | 54,636 | <pre><code>Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(server);
System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 3456);
soc.Connect(remoteEP);
</code></pre>
<p>For connecting to it.
To send something:</p>
<pre><code>//Start sending stuf..
byte[] byData = System.Text.Encoding.ASCII.GetBytes("un:" + username + ";pw:" + password);
soc.Send(byData);
</code></pre>
<p>And for reading back..</p>
<pre><code>byte[] buffer = new byte[1024];
int iRx = soc.Receive(buffer);
char[] chars = new char[iRx];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
System.String recv = new System.String(chars);
</code></pre> |
5,455,866 | error: invalid type argument of ‘unary *’ (have ‘int’) | <p>I have a C Program:</p>
<pre><code>#include <stdio.h>
int main(){
int b = 10; //assign the integer 10 to variable 'b'
int *a; //declare a pointer to an integer 'a'
a=(int *)&b; //Get the memory location of variable 'b' cast it
//to an int pointer and assign it to pointer 'a'
int *c; //declare a pointer to an integer 'c'
c=(int *)&a; //Get the memory location of variable 'a' which is
//a pointer to 'b'. Cast that to an int pointer
//and assign it to pointer 'c'.
printf("%d",(**c)); //ERROR HAPPENS HERE.
return 0;
}
</code></pre>
<p>Compiler produces an error: </p>
<pre><code>error: invalid type argument of ‘unary *’ (have ‘int’)
</code></pre>
<p>Can someone explain what this error means? </p> | 5,455,962 | 4 | 0 | null | 2011-03-28 07:30:02.08 UTC | 9 | 2019-02-05 16:37:36.007 UTC | 2013-09-30 19:23:02.033 UTC | null | 445,131 | null | 679,815 | null | 1 | 30 | c|pointers | 147,977 | <p>Since <code>c</code> is holding the address of an integer pointer, its type should be <code>int**</code>:</p>
<pre><code>int **c;
c = &a;
</code></pre>
<p>The entire program becomes:</p>
<pre><code>#include <stdio.h>
int main(){
int b=10;
int *a;
a=&b;
int **c;
c=&a;
printf("%d",(**c)); //successfully prints 10
return 0;
}
</code></pre> |
4,902,198 | PIL how to scale text size in relation to the size of the image | <p>I'm trying to dynamically scale text to be placed on images of varying but known dimensions. The text will be applied as a watermark. Is there any way to scale the text in relation to the image dimensions? I don't require that the text take up the whole surface area, just to be visible enough so its easily identifiable and difficult to remove. I'm using Python Imaging Library version 1.1.7. on Linux.</p>
<p>I would like to be able to set the ratio of the text size to the image dimensions, say like 1/10 the size or something.</p>
<p>I have been looking at the font size attribute to change the size but I have had no luck in creating an algorithm to scale it. I'm wondering if there is a better way.</p>
<p>Any ideas on how I could achieve this?</p>
<p>Thanks</p> | 4,902,713 | 4 | 0 | null | 2011-02-04 19:41:36.457 UTC | 14 | 2021-02-07 18:08:45.857 UTC | 2011-02-04 23:49:45.21 UTC | null | 31,676 | null | 506,892 | null | 1 | 58 | python|fonts|image-manipulation|python-imaging-library|scaling | 91,943 | <p>You could just increment the font size until you find a fit. <code>font.getsize()</code> is the function that tells you how large the rendered text is.</p>
<pre><code>from PIL import ImageFont, ImageDraw, Image
image = Image.open('hsvwheel.png')
draw = ImageDraw.Draw(image)
txt = "Hello World"
fontsize = 1 # starting font size
# portion of image width you want text width to be
img_fraction = 0.50
font = ImageFont.truetype("arial.ttf", fontsize)
while font.getsize(txt)[0] < img_fraction*image.size[0]:
# iterate until the text size is just larger than the criteria
fontsize += 1
font = ImageFont.truetype("arial.ttf", fontsize)
# optionally de-increment to be sure it is less than criteria
fontsize -= 1
font = ImageFont.truetype("arial.ttf", fontsize)
print('final font size',fontsize)
draw.text((10, 25), txt, font=font) # put the text on the image
image.save('hsvwheel_txt.png') # save it
</code></pre>
<p>If this is not efficient enough for you, you can implement a root-finding scheme, but I'm guessing that the <code>font.getsize()</code> function is small potatoes compared to the rest of your image editing processes.</p> |
5,472,162 | How to read HTML as XML? | <p>I want to extract a couple of links from an html page downloaded from the internet, I think that using linq to XML would be a good solution for my case.<br>
My problem is that I can't create an XmlDocument from the HTML, using Load(string url) didn't work so I downloaded the html to a string using:</p>
<pre><code>public static string readHTML(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string html = sr.ReadToEnd();
sr.Close();
return html;
}
</code></pre>
<p>When I try to load that string using LoadXml(string xml) I get the exception</p>
<pre><code>'--' is an unexpected token. The expected token is '>'
</code></pre>
<p>What way should I take to read the html file to a parsable XML</p> | 5,472,221 | 5 | 2 | null | 2011-03-29 12:03:00.083 UTC | 1 | 2017-11-23 17:31:27.23 UTC | null | null | null | null | 365,408 | null | 1 | 18 | c#|html|xml|html-parsing | 64,715 | <p>HTML simply isn’t the same as XML (unless the HTML actually happens to be conforming XHTML or HTML5 in XML mode). The best way is to use a <a href="http://html-agility-pack.net/?z=codeplex" rel="nofollow noreferrer">HTML parser</a> to read the HTML. Afterwards you may transform it to Linq to XML – or process it directly.</p> |
5,254,732 | Difference between map and collect in Ruby? | <p>I have Googled this and got patchy / contradictory opinions - is there actually any difference between doing a <code>map</code> and doing a <code>collect</code> on an array in Ruby/Rails? </p>
<p>The <a href="http://www.ruby-doc.org/core/classes/Array.html#M000248" rel="noreferrer">docs</a> don't seem to suggest any, but are there perhaps differences in method or performance?</p> | 5,254,764 | 6 | 3 | null | 2011-03-10 02:19:40.16 UTC | 71 | 2020-10-28 23:11:14.357 UTC | 2013-11-13 18:49:01.373 UTC | null | 1,017,941 | null | 341,583 | null | 1 | 454 | ruby|arrays|map|collect | 128,213 | <p>There's no difference, in fact <code>map</code> is implemented in C as <code>rb_ary_collect</code> and <code>enum_collect</code> (eg. there is a difference between <code>map</code> on an array and on any other enum, but no difference between <code>map</code> and <code>collect</code>).</p>
<hr>
<p><strong>Why do both <code>map</code> and <code>collect</code> exist in Ruby?</strong> The <code>map</code> function has many naming conventions in different languages. <a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)" rel="noreferrer">Wikipedia provides an overview</a>:</p>
<blockquote>
<p>The map function originated in functional programming languages but is today supported (or may be defined) in many procedural, object oriented, and multi-paradigm languages as well: In C++'s Standard Template Library, it is called <code>transform</code>, in C# (3.0)'s LINQ library, it is provided as an extension method called <code>Select</code>. Map is also a frequently used operation in high level languages such as Perl, Python and Ruby; the operation is called <code>map</code> in all three of these languages. <em>A <code>collect</code> alias for map is also provided in Ruby (from Smalltalk)</em> [emphasis mine]. Common Lisp provides a family of map-like functions; the one corresponding to the behavior described here is called <code>mapcar</code> (-car indicating access using the CAR operation). </p>
</blockquote>
<p>Ruby provides an alias for programmers from the Smalltalk world to feel more at home.</p>
<hr>
<p><strong>Why is there a different implementation for arrays and enums?</strong> An enum is a generalized iteration structure, which means that there is no way in which Ruby can predict what the next element can be (you can define infinite enums, see <a href="http://apidock.com/ruby/Prime" rel="noreferrer">Prime</a> for an example). Therefore it must call a function to get each successive element (typically this will be the <code>each</code> method). </p>
<p>Arrays are the most common collection so it is reasonable to optimize their performance. Since Ruby knows a lot about how arrays work it doesn't have to call <code>each</code> but can only use simple <a href="http://www.eskimo.com/~scs/cclass/notes/sx10b.html" rel="noreferrer">pointer manipulation</a> which is significantly faster.</p>
<p>Similar optimizations exist for a number of Array methods like <code>zip</code> or <code>count</code>.</p> |
5,584,586 | Find the division remainder of a number | <p>How could I go about finding the division remainder of a number in Python?</p>
<p>For example:<br>
If the number is 26 and divided number is 7, then the division remainder is 5.<br>
(since 7+7+7=21 and 26-21=5.)</p> | 5,584,604 | 13 | 1 | null | 2011-04-07 16:44:16.82 UTC | 14 | 2022-05-25 14:29:29.703 UTC | 2022-05-25 14:29:29.703 UTC | null | 967,621 | null | 465,137 | null | 1 | 208 | python|modulo|integer-division | 706,027 | <p>you are looking for the modulo operator:</p>
<pre><code>a % b
</code></pre>
<p>for example:</p>
<pre><code>>>> 26 % 7
5
</code></pre>
<p>Of course, maybe they wanted you to implement it yourself, which wouldn't be too difficult either.</p> |
16,786,813 | input onclick new tab | <pre><code><form name="test">
<select name="choose" style="width:300px;">
<option selected="">Select option</option>
<option value="http://url.com">Test</option>
</select>
<input onclick="location=document.test.choose.options[document.test.choose.selectedIndex].value;" value="Take me there!" type="button"></p>
</form>
</code></pre>
<p>Im using the following to make a dropdown list and was just wondering how i would make selected open in a new tab and not in its own window</p>
<p>Works fine as it is just need it to open in a new tab.</p>
<p><strong>* Edit *</strong></p>
<p>This worked as needed thanks</p>
<pre><code><input onClick="window.open(document.test.choose.options[document.test.choose.selectedIndex].value);" value="Take me there!" type="button">
</code></pre> | 16,786,881 | 4 | 3 | null | 2013-05-28 07:59:36.473 UTC | 3 | 2019-01-25 12:08:48.327 UTC | 2013-05-28 12:02:05.087 UTC | null | 2,361,412 | null | 2,361,412 | null | 1 | 7 | html|onclick | 53,813 | <p>try window.open</p>
<pre><code>window.open('http://www.google.com');
</code></pre>
<h2>update</h2>
<p>live demo - <a href="http://jsfiddle.net/im4aLL/tzp4H/">http://jsfiddle.net/im4aLL/tzp4H/</a></p> |
17,071,297 | Background image using HTML5 to fit the page | <p>I want to make one image the full background of a website! I know it sounds pretty simple, but it just got me crazy, it doesn't fit the page, this the last try I reached with!</p>
<p>CSS :</p>
<pre><code>body {
background:url('images/bg_img1.jpg') #A98436 no-repeat left top;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
}
</code></pre>
<p>I'm using Twitter Bootstrap as well, but the thing is even without that I can't get it right!</p>
<p>Any help would be appreciated.</p>
<p>EDIT: and I didn't use exact pixels because I'm trying to make a responsive + mobile design.</p>
<p>I don't know why they downvoted the question! But this is how I solved it!</p>
<pre><code>html, body {
margin: 0;
padding: 0;
height: 100%;
}
#mybody {
background: url('images/bodybg.jpg') no-repeat center left;
background-size: 100% 100%;
width: 100%;
height: 100%;
height: auto !important;
min-height:100%;
}
#myheader {
background: url('images/headerbg.jpg') no-repeat center left;
background-size: 100% 100%;
width: 100%;
height: 100%;
height: auto !important;
min-height:100%;
}
#myfooter {
background: url('images/footerbg.jpg') no-repeat center left;
background-size: 100% 100%;
width: 100%;
height: 100%;
height: auto !important;
min-height:100%;
}
</code></pre> | 17,072,366 | 4 | 13 | null | 2013-06-12 17:07:42.007 UTC | 5 | 2020-01-28 22:49:56.723 UTC | 2013-06-12 20:48:54.7 UTC | null | 539,075 | null | 539,075 | null | 1 | 9 | html|css|twitter-bootstrap|background-image | 95,156 | <p>EDIT: I created a <a href="http://jsfiddle.net/a59Mg/" rel="noreferrer">DEMO</a> with some unnecessary things removed. This has the benefit of not windowing your background picture. The <a href="http://jsfiddle.net/a59Mg/" rel="noreferrer">DEMO</a> works but was not as extensively tested as the quoted code below.</p>
<p>I recently worked on a project where we needed this exact thing. I'm posting from my project files, so some of this may be unnecessary as it was a team member that wrote this.</p>
<p>Start by setting properties of html and body.
Then, I have a root div inside body called background.</p>
<pre><code>html, body {
margin: 0;
padding: 0;
height: 100%;
}
#background {
background: #000000 url(urlHere) no-repeat bottom left;
background-size: 100% 100%;
width: 100%;
height: 100%;
height: auto !important;
min-height:100%;
}
</code></pre>
<p>Again, some of that I'm sure is unnecessary, but I hope it helps.</p> |
29,379,425 | Where to report issues of OpenJDK when you're not a OpenJDK developer? | <p>First I thought it's strange that there's no link to a bug tracker on the <a href="http://openjdk.java.net/" rel="noreferrer">OpenJDK project page</a>, then I found <a href="https://bugs.openjdk.java.net/" rel="noreferrer">bugs.openjdk.java.net</a>, but it's only for accredited project members. How do people outside the ivory tower contribute issues? There's the mailing list and some people call sending issues and patches to a mailing list bug tracking... but the development and usage of bug tracker contradicts.</p> | 38,789,513 | 2 | 6 | null | 2015-03-31 22:06:53.06 UTC | 11 | 2021-09-24 19:14:06.493 UTC | 2017-03-14 20:25:23.31 UTC | null | 1,797,006 | null | 1,797,006 | null | 1 | 56 | openjdk|issue-tracking | 3,356 | <p>Go to <a href="http://bugs.java.com" rel="nofollow noreferrer">http://bugs.java.com</a> or jump straight to the report page: <a href="http://bugreport.java.com/" rel="nofollow noreferrer">http://bugreport.java.com/</a></p>
<p>My interpretation of their <a href="https://bugs.java.com/bugdatabase/faq.do" rel="nofollow noreferrer">FAQ</a> is that this will be triaged by an Oracle engineer, and if accepted it will be assigned a number and (usually) become visible in both Oracles + the OpenJDK bug databases.</p>
<p><em>It would be <strong>really</strong> helpful if this info/link were on the OpenJDK bug page too. The database split is already confusing enough - when your goal is to contribute to <strong>OpenJDK</strong> but you find yourself at an Oracle-branded page, it seems like you've gone to the wrong place.</em></p>
<p>UDPATE (Nov 2019): To add <strong>Additional information</strong> to a bug (<a href="https://bugs.java.com/bugdatabase/faq.do" rel="nofollow noreferrer">FAQ</a> point 6):</p>
<blockquote>
<p>File a new incident with the subject line "Additional information to JDK-XXXXXXX'. Replace XXXXXXX with the reference number received when the report is filed. We are working on a system where you will be able to provide additional information to the existing bug.</p>
</blockquote>
<hr />
<p>Now, if you're curious who can get <em>direct</em> access to the bug database...</p>
<p>From (<a href="https://bugs.openjdk.java.net/" rel="nofollow noreferrer">https://bugs.openjdk.java.net/</a>):</p>
<blockquote>
<p>Everyone with OpenJDK <strong>Author</strong> status or above has a [JDK Bug System] account which may be used to create and edit bugs. Those without accounts can view bugs anonymously.</p>
</blockquote>
<p>To understand that, you need to navigate the various "role" definitions:</p>
<p><a href="http://openjdk.java.net/bylaws#author" rel="nofollow noreferrer">http://openjdk.java.net/bylaws#author</a></p>
<p>From Section 7:</p>
<blockquote>
<p>An <strong>Author</strong> for a Project is a Contributor who has been granted the right to create changesets intended to be pushed into a specific Project’s code repositories, but does not have the right to push such changesets directly.</p>
</blockquote>
<p>From Section 2:</p>
<blockquote>
<p>A <strong>Contributor</strong> is a Participant who has signed the Oracle Contributor Agreement (OCA), or who works for an organization that has signed that agreement or its equivalent and makes contributions within the scope of that work and subject to that agreement. A Contributor may submit changes larger than a simple patch, may propose new Projects, and may take on various roles within Groups and Projects.</p>
</blockquote>
<p>and ...</p>
<blockquote>
<p>A <strong>Participant</strong> is an individual who has subscribed to one or more OpenJDK mailing lists. A Participant may post messages to a list, submit simple patches, and make other kinds of small contributions.</p>
</blockquote>
<p>So the bar is set pretty high. <code>:-/</code></p> |
29,579,811 | Changing number of columns with GridLayoutManager and RecyclerView | <p>Inside my fragment I'm setting my GridLayout in the following way:
<code>mRecycler.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));</code></p>
<p>So, I just want to change that <code>2</code> for a <code>4</code> when the user rotates the phone/tablet. I've read about <code>onConfigurationChanged</code> and I tried to make it work for my case, but it isn't going in the right way. When I rotate my phone, the app crashes...</p>
<p>Could you tell me how to solve this issue?</p>
<p>Here is my approach to find the solution, which is not working correctly:</p>
<pre><code> @Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation = newConfig.orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));
} else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));
}
}
</code></pre>
<p>Thanks in advance!</p> | 29,582,477 | 9 | 10 | null | 2015-04-11 15:49:38.327 UTC | 20 | 2022-02-20 18:17:31.593 UTC | null | null | null | null | 4,201,917 | null | 1 | 67 | android|android-orientation|android-gridlayout|android-recyclerview | 67,194 | <p>Try handling this inside your onCreateView method instead since it will be called each time there's an orientation change:</p>
<pre><code>if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));
}
else{
mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));
}
</code></pre> |
12,383,044 | Complexity for towers of Hanoi? | <p>I was recently solving Towers of Hanoi problem. I used a "Divide and Conquer" Strategy to solve this problem. I divided the main problem into three smaller sub problems and thus following recurrence was generated.</p>
<blockquote>
<p>T(n)=2T(n-1)+1</p>
</blockquote>
<p>Solving this leads to</p>
<blockquote>
<p>O(2^n) [exponential time]</p>
</blockquote>
<p>Then i tried to use memoization technique to solve it, but here too the space complexity was exponential and heap space exhausted very soon and problem was still unsolvable for larger n.</p>
<p>Is there a way to solve the problem in less than exponential time? What is the best time in which the problem can be solved?</p> | 12,383,299 | 5 | 4 | null | 2012-09-12 07:21:03.95 UTC | 4 | 2018-02-21 14:39:04.297 UTC | null | null | null | user1581106 | null | null | 1 | 13 | algorithm|complexity-theory | 78,932 | <p>It depends what you mean by "solved". The Tower of Hanoi problem with 3 pegs and <code>n</code> disks takes <code>2**n - 1</code> moves to solve, so if you want to enumerate the moves, you obviously can't do better than <code>O(2**n)</code> since enumerating <code>k</code> things is <code>O(k)</code>. </p>
<p>On the other hand, if you just want to know the number of moves required (without enumerating them), calculating <code>2**n - 1</code> is a much faster operation.</p>
<p>Also worth noting, the enumeration of the moves can be done iteratively with <code>O(n)</code> space complexity as follows (<code>disk1</code> is the smallest disk):</p>
<pre><code>while true:
if n is even:
move disk1 one peg left (first peg wraps around to last peg)
else:
move disk1 one peg right (last peg wraps around to first peg)
if done:
break
else:
make the only legal move not involving disk1
</code></pre> |
12,305,021 | Efficient way to normalize a Scipy Sparse Matrix | <p>I'd like to write a function that normalizes the rows of a large sparse matrix (such that they sum to one).</p>
<pre><code>from pylab import *
import scipy.sparse as sp
def normalize(W):
z = W.sum(0)
z[z < 1e-6] = 1e-6
return W / z[None,:]
w = (rand(10,10)<0.1)*rand(10,10)
w = sp.csr_matrix(w)
w = normalize(w)
</code></pre>
<p>However this gives the following exception:</p>
<pre><code>File "/usr/lib/python2.6/dist-packages/scipy/sparse/base.py", line 325, in __div__
return self.__truediv__(other)
File "/usr/lib/python2.6/dist-packages/scipy/sparse/compressed.py", line 230, in __truediv__
raise NotImplementedError
</code></pre>
<p>Are there any reasonably simple solutions? I have looked at <a href="https://stackoverflow.com/questions/10475457/iterating-over-scipy-sparse-matrix-by-column">this</a>, but am still unclear on how to actually do the division.</p> | 12,396,922 | 5 | 3 | null | 2012-09-06 17:06:03.517 UTC | 7 | 2019-12-16 23:18:46.53 UTC | 2017-05-23 12:02:29.63 UTC | null | -1 | null | 1,652,672 | null | 1 | 32 | python|numpy|scipy|sparse-matrix | 24,605 | <p>This has been implemented in <a href="http://scikit-learn.org/dev/modules/generated/sklearn.preprocessing.normalize.html#sklearn.preprocessing.normalize">scikit-learn sklearn.preprocessing.normalize</a>.</p>
<pre><code>from sklearn.preprocessing import normalize
w_normalized = normalize(w, norm='l1', axis=1)
</code></pre>
<p><code>axis=1</code> should normalize by rows, <code>axis=0</code> to normalize by column. Use the optional argument <code>copy=False</code> to modify the matrix in place.</p> |
12,112,844 | How to detect support for the HTML5 "download" attribute? | <p>One of the new features implemented in HTML5 is the <code>download</code> attribute for anchor tags. The benefit of this attribute is that it gives users the means to download content created within a client application, such as an image (converted from a canvas, for instance).</p>
<p>Currently, support for this feature is very poor, so I'd like to know how can I detect support for this feature in a browser.</p> | 12,112,905 | 2 | 1 | null | 2012-08-24 16:00:00.997 UTC | 7 | 2017-10-20 10:12:32.777 UTC | 2017-06-07 16:56:11.853 UTC | null | 2,788,872 | null | 918,592 | null | 1 | 45 | javascript|html | 20,423 | <p>Use the <a href="https://github.com/Modernizr/Modernizr/blob/master/feature-detects/a/download.js" rel="noreferrer">Modernizr</a> approach: create the element, and check if the attribute is defined:</p>
<pre><code>var a = document.createElement('a');
if (typeof a.download != "undefined") {
alert('has support');
}
</code></pre> |
12,369,957 | Dealing with an ArrayStoreException | <pre><code>Object[] o = "a;b;c".split(";");
o[0] = 42;
</code></pre>
<p>throws</p>
<pre><code>java.lang.ArrayStoreException: java.lang.Integer
</code></pre>
<p>while</p>
<pre><code>String[] s = "a;b;c".split(";");
Object[] o = new Object[s.length];
for (int i = 0; i < s.length; i++) {
o[i] = s[i];
}
o[0] = 42;
</code></pre>
<p>doesn't.</p>
<p>Is there any other way to deal with that exception without creating a temporary <code>String[]</code> array?</p> | 12,370,259 | 4 | 2 | null | 2012-09-11 12:40:24.787 UTC | 22 | 2022-02-09 14:22:12.04 UTC | null | null | null | null | 1,225,328 | null | 1 | 55 | java|arrays|casting|type-conversion | 76,442 | <p>In Java an array is also an <em>object</em>.</p>
<p>You can put an object of a <em>subtype</em> into a variable of a <em>supertype</em>. For example you can put a <code>String</code> object into an <code>Object</code> variable.</p>
<p>Unfortunately, the array definition in Java is somehow broken. <code>String[]</code> is considered a subtype of <code>Object[]</code>, but that is <em>wrong</em>! For a more detailed explanation read about "covariance and contravariance", but the essence it this: A type should be considered a subtype of another type only if the subtype fulfills <em>all obligations</em> of the supertype. That means, that if you get a subtype object instead of a supertype object, you should not expect behavior contradictory to supertype contract.</p>
<p>Problem is that <code>String[]</code> only supports a <em>part</em> of <code>Object[]</code> contract. For example you can <em>read</em> <code>Object</code> values from <code>Object[]</code>. And you can also <em>read</em> <code>Object</code> values (which happen to be <code>String</code> objects) from <code>String[]</code>. So far so good. Problem is with the other part of contract. You can put <em>any</em> <code>Object</code> into <code>Object[]</code>. But you cannot put <em>any</em> <code>Object</code> into <code>String[]</code>. Therefore, <code>String[]</code> should not be considered a subtype of <code>Object[]</code>, but Java specification says it is. And thus we have consequences like this.</p>
<p>(Note that a similar situation appeared again with the generic classes, but this time it was solved <em>correctly</em>. <code>List<String></code> is <em>not</em> a subtype of <code>List<Object></code>; and if you want to have a common supertype for these, you need <code>List<?></code>, which is read-only. This is how it should be also with arrays; but it's not. And because of the backwards compatibility, it is too late to change it.)</p>
<p>In your first example the <code>String.split</code> function creates a <code>String[]</code> object. You can put it into a <code>Object[]</code> variable, but the object remains <code>String[]</code>. This is why it rejects an <code>Integer</code> value. You have to create a new <code>Objects[]</code> array, and copy the values. You could use the <code>System.arraycopy</code> function to copy the data, but you cannot avoid creating the new array.</p> |
12,145,357 | What is a stream in C++? | <p>I have been hearing about streams, more specifically file streams.</p>
<p>So what are they?</p>
<p>Is it something that has a location in the memory?</p>
<p>Is it something that contains data?</p>
<p>Is it just a connection between a file and an object?</p> | 12,145,419 | 4 | 1 | null | 2012-08-27 15:58:01.013 UTC | 18 | 2021-01-02 04:43:13.873 UTC | 2021-01-02 04:43:13.873 UTC | null | 63,550 | null | 1,356,331 | null | 1 | 59 | c++|stream|filestream|fstream | 37,052 | <p>The term stream is an abstraction of a construct that allows you to send or receive an unknown number of bytes. The metaphor is a stream of water. You take the data as it comes, or send it as needed. Contrast this to an array, for example, which has a fixed, known length.</p>
<p>Examples where streams are used include reading and writing to files, receiving or sending data across an external connection. However the term <em>stream</em> is generic and says nothing about the specific implementation.</p> |
24,263,291 | Define a Makefile variable using a ENV variable or a default value | <p>I am trying to do a simple thing:</p>
<pre><code>TMPDIR ?= /tmp
test:
@echo $(TMPDIR)
</code></pre>
<p>This works if I run:</p>
<pre><code>$ make test
/tmp
</code></pre>
<p>It also works if I run:</p>
<pre><code>$ make test -e TMPDIR=~/tmp
/home/user/tmp
</code></pre>
<p>What can I do to also have it works for:</p>
<pre><code>$ TMPDIR=~/tmp make test
/home/user/tmp
</code></pre> | 24,264,930 | 4 | 6 | null | 2014-06-17 12:02:30.89 UTC | 14 | 2022-01-15 01:29:05.557 UTC | 2014-06-18 07:29:28.433 UTC | null | 186,202 | null | 186,202 | null | 1 | 121 | bash|shell|makefile|environment-variables | 89,893 | <p>To follow up on my comments above, here's an example:</p>
<pre><code>T ?= foo
all:
: '$(T)'
</code></pre>
<p>Now if I run the Makefile in various ways, it behaves as we expect (I get <code>foo</code> only if I don't set <code>T</code> either on the command line or environment):</p>
<pre><code>$ make
: 'foo'
$ make T=bar
: 'bar'
$ T=bar make
: 'bar'
</code></pre> |
3,822,546 | Using Html.RenderPartial() in ascx files | <p>I'm trying to use Html.RenderPartial in acsx file
and I'm getting an error:</p>
<blockquote>
<p>Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper'
has no applicable method named 'RenderPartial' but appears to have an
extension method by that name. Extension methods cannot be dynamically
dispatched. Consider casting the dynamic arguments or calling the
extension method without the extension method syntax</p>
</blockquote>
<pre><code><a href="/projects/<%=project.Id %>">
<% Html.Label("fdf"); %>
<% Html.RenderPartial("ProjectName", Model.Id); %></a></li>
<%} %>
</code></pre>
<p>However I've import neccessary namespaces, so it won't be error at</p>
<pre><code><% Html.Label("fdf"); %>
</code></pre>
<p>Are there any methods to use Html.RenderPartial in ascx file?</p> | 3,822,588 | 3 | 0 | null | 2010-09-29 14:25:48.293 UTC | 3 | 2015-07-02 14:56:25.887 UTC | 2015-07-02 14:56:25.887 UTC | null | 1,664,443 | null | 418,251 | null | 1 | 24 | asp.net-mvc|partial-views|renderpartial | 54,354 | <p>The compiler cannot choose the correct method because your Model is <code>dynamic</code>. Change the call to:</p>
<pre><code><% Html.RenderPartial("ProjectName", (int)(Model.Id)); %>
</code></pre>
<p>Or any other datatype Id is.</p> |
3,405,055 | Java DOM - Inserting an element, after another | <p>Given the following XML file:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<process
name="TestSVG2"
xmlns="http://www.example.org"
targetNamespace="http://www.example.org"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<sequence>
<receive name="Receive1" createInstance="yes"/>
<assign name="Assign1"/>
<invoke name="Invoke1"/>
<assign name="Assign2"/>
<reply name="Reply1"/>
</sequence>
</process>
</code></pre>
<p>I want to add a new element inside the <code><sequence></sequence></code> <strong>after a certain pre-existing element</strong>. For example if I want to add the node after <code>"Assign1"</code>, the new XML should like this:</p>
<pre><code> <sequence>
<receive name="Receive1" createInstance="yes"/>
<assign name="Assign1"/>
<newtype name="NewNode"/>
<invoke name="Invoke1"/>
<assign name="Assign2"/>
<reply name="Reply1"/>
</sequence>
</code></pre>
<p>I have to do this by using Java DOM, in a function. The function signature should like this:</p>
<pre><code> public void addActionDom(String name, String stepType, String stepName)
</code></pre>
<p>Where:</p>
<ul>
<li><code>name</code> is the pre-existing element, after which the insertion will be made;</li>
<li><code>stepType</code> is the inserted element type;</li>
<li><code>stepName</code> is the name attribute of the newly inserted element.</li>
</ul>
<p><strong>Currently I am lacking experience with JDOM, or any other Java XML library. Can you please give a sample code, or point me to a tutorial where an insertion after a certain element is made.</strong> </p>
<p>This is the code I have until now:</p>
<pre><code> public void addActionDom(String name, String stepType, String stepName) {
File xmlFile = new File(path + "/resources/" + BPELFilename);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try {
/* Load XML */
db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlFile);
doc.getDocumentElement().normalize();
/* Iterate throughout the type tags and delete */
for (String cTag : typeTags) {
NodeList cnl = doc.getElementsByTagName(cTag);
for (int i = 0; i < cnl.getLength(); ++i) {
Node cnode = cnl.item(i);
if (cnode.getNodeType() == Node.ELEMENT_NODE) {
Element elem = (Element)cnode; // 'elem' Element after which the insertion should be made
if (elem.getAttribute("name").equals(name)) {
Element newElement = doc.createElement(stepType); // Element to be inserted
newElement.setAttribute("name", stepName);
// CODE HERE
}
}
}
}
/* Save the editing */
Transformer transformer =
TransformerFactory.newInstance().newTransformer();
StreamResult result =
new StreamResult(new FileOutputStream(path + "/resources/" +
BPELFilename));
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
} catch (Exception e) {
/* ParserConfigurationException */
/* SAXException */
/* IOException */
/* TransformerConfigurationException */
/* TransformerException */
/* Exception */
e.printStackTrace();
}
}
}
</code></pre> | 3,405,173 | 4 | 0 | null | 2010-08-04 11:31:49.24 UTC | 4 | 2014-09-01 08:20:54.553 UTC | null | null | null | null | 211,701 | null | 1 | 13 | java|xml|dom | 55,176 | <p>Ok, Aaron Digulla beat me regarding speed. Had to figure it out myself as well.
I didnt use <code>cnl.item(i+1)</code> but <code>nextSibling()</code>:</p>
<pre><code>Element newElement = doc.createElement(stepType); // Element to be inserted
newElement.setAttribute("name", stepName);
elem.getParentNode().insertBefore(newElement, elem.getNextSibling());
</code></pre>
<p>You cannot insert Nodes at a specified index. The only node-inserting methods are </p>
<pre><code>appendChild(Node node) //appends the given child to the end of the list of children
</code></pre>
<p>and</p>
<pre><code>insertBefore(Node new, Node child) //inserts "new" into the list, before the 'child' node.
</code></pre>
<p>If there was a insertAfter(Node new, Node child) method, this would be very easy for you. But there isn't, unfortunately.</p> |
22,603,847 | How to extract Month from date in R | <p>I am using the <code>lubridate</code> package and applying the <code>month</code> function to extract month from date. I ran the str command on date field and I got </p>
<pre><code>Factor w/ 9498 levels "01/01/1979","01/01/1980",..: 5305 1 1 1 1 1 1 1 1 1 ...
> v1$Date<-month(v1$Date)
Error in as.POSIXlt.character(as.character(x), ...) :
character string is not in a standard unambiguous format
</code></pre>
<p>Here is an example of my data frame</p>
<p><a href="https://drive.google.com/file/d/0B6cqWmwsEk20Q2dHblhXZi14Wk0/edit?usp=sharing">https://drive.google.com/file/d/0B6cqWmwsEk20Q2dHblhXZi14Wk0/edit?usp=sharing</a></p>
<p>I don't know what I am doing wrong. </p> | 22,604,060 | 5 | 5 | null | 2014-03-24 07:58:53.013 UTC | 10 | 2021-12-15 05:06:23.57 UTC | 2014-03-24 14:03:39.337 UTC | null | 1,900,149 | null | 3,264,912 | null | 1 | 55 | r|lubridate | 301,540 | <p><code>?month</code> states:</p>
<blockquote>
<p>Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon,
yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts
objects.</p>
</blockquote>
<p>Your object is a factor, not even a character vector (presumably because of <code>stringsAsFactors = TRUE</code>). You have to convert your vector to some datetime class, for instance to <code>POSIXlt</code>:</p>
<pre><code>library(lubridate)
some_date <- c("01/02/1979", "03/04/1980")
month(as.POSIXlt(some_date, format="%d/%m/%Y"))
[1] 2 4
</code></pre>
<p>There's also a convenience function <code>dmy</code>, that can do the same (tip proposed by @Henrik): </p>
<pre><code>month(dmy(some_date))
[1] 2 4
</code></pre>
<p>Going even further, @IShouldBuyABoat gives another hint that dd/mm/yyyy character formats are accepted without any explicit casting:</p>
<pre><code>month(some_date)
[1] 2 4
</code></pre>
<p>For a list of formats, see <code>?strptime</code>. You'll find that "standard unambiguous format" stands for</p>
<blockquote>
<p>The default formats follow the rules of the ISO 8601 international
standard which expresses a day as "2001-02-28" and a time as
"14:01:02" using leading zeroes as here.</p>
</blockquote> |
20,420,890 | Getting errors stray ‘\342’ and ‘\200’ and ‘\214’ | <p>I'm trying to write a program for a simple game, but I am getting errors, stray ‘\342’ and ‘\200’ and ‘\214’, using g++ and gedit in <a href="https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_13.10_.28Saucy_Salamander.29" rel="nofollow noreferrer">Ubuntu 13.10</a> (Saucy Salamander).</p>
<p>The code is:</p>
<pre><code>#include <iostream>
#include <cctype>
using namespace std;
char all_d()
{
return 'D';
}
int main()
{
bool more = true;
while ( more )
{
cout << "enter C to cooperate, D to defect, Q to quit\n";
char player_choice;
cin >> player_choice;
if ( player_choice != 'C' || player_choice != 'D' || player_choice != 'Q' )
{
cout << "Illegal input.\nenter an other\n";
cin >> player_choice;
}
char cpu_choice = all_d();
cout << "player's choice is " << player_choice << endl;
cout << "cpu's choice is " << cpu_choice << endl;
}
if ( player_choice == 'Q' )
{
cout << "Game is Over!\n";
more = false;
}
}
</code></pre>
<p>and terminal output is:</p>
<pre class="lang-none prettyprint-override"><code>IPD.cpp:18:3: error: stray ‘\342’ in program
cin >> player_choice;
^
IPD.cpp:18:3: error: stray ‘\200’ in program
IPD.cpp:18:3: error: stray ‘\214’ in program
IPD.cpp: In function ‘int main()’:
IPD.cpp:29:47: error: ‘end’ was not declared in this scope
cout << "cpu's choice is " << cpu_choice << end;
^
IPD.cpp:32:7: error: ‘player_choice’ was not declared in this scope
if ( player_choice == 'Q' )
^
</code></pre>
<p>I even tried to to compile this:</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
char a;
cin >> a;
}
</code></pre>
<p>and the terminal again says:</p>
<pre class="lang-none prettyprint-override"><code>a.cpp:8:2: error: stray ‘\342’ in program
cin >> a;
^
a.cpp:8:2: error: stray ‘\200’ in program
a.cpp:8:2: error: stray ‘\214’ in program
</code></pre>
<p>How can I fix this?</p>
<p>Note that I installed Ubuntu last night.</p> | 20,421,130 | 4 | 4 | null | 2013-12-06 09:54:23.75 UTC | 3 | 2021-03-06 22:00:21.107 UTC | 2021-03-06 22:00:21.107 UTC | null | 63,550 | null | 3,073,850 | null | 1 | 6 | c++|ubuntu|g++ | 74,040 | <p>You are using a <a href="http://www.fileformat.info/info/unicode/char/200c/index.htm" rel="nofollow noreferrer">Zero Width Non Joiner</a> character after the <code>>></code> in your code. This is a Unicode character that is encoded in UTF-8 as three characters with values <code>0x2e</code>, <code>0x80</code>, <code>0x8c</code> (or in base 8, <code>\342</code>, <code>\200</code>, <code>\214</code>). This probably happened because you copy and pasted some code from a document (HTML web page?) that uses those special characters.</p>
<p>The C++ language requires that the whole program uses mostly the ASCII encoding, except for the content of strings or character literals (that may be in a implementation-dependent encoding). So to fix your problem, make sure that you only use simple ASCII space, quotes, double quotes and not smart characters.</p> |
20,580,968 | Xcode error : Distill failed for unknown reasons | <p>Does anybody know why this error happens on Xcode 5?</p>
<p><img src="https://i.stack.imgur.com/uBCcr.png" alt="error" /></p>
<p><strong>Answer</strong></p>
<p>I had this problem when I accidentally renamed a .psd as a .png. Converting the image to an actual png instead of a Photoshop file fixed it for me.</p> | 20,581,066 | 18 | 6 | null | 2013-12-14 07:51:40.463 UTC | 3 | 2021-09-09 02:53:48.103 UTC | 2021-03-16 14:13:17.827 UTC | null | 865,175 | null | 1,282,896 | null | 1 | 51 | ios|iphone|xcode|ios7|xcode5 | 24,973 | <p>You might have migrated from a normal project to use an image.catalog. So you can definitely try to copy the bundle resource like launch images. It is so because migrating to an asset catalog for icons and launch images apparently doesn't always add itself to the target automatically. </p>
<p>You can find more on this <a href="https://stackoverflow.com/a/19148032/1307844">here</a> & <a href="https://stackoverflow.com/a/20502937/1307844">here</a>.</p>
<p>I hope that helps.</p> |
20,739,941 | Export JSON to CSV or Excel with UTF-8 (e.g. Greek) encoding using JavaScript | <p>I am trying to export and download a <em>JSON</em> object to <em>CSV</em> file and I have problem with Greek characters. My code works; it is not perfect, but it works. </p>
<p>The problem is that Greek characters looks like junk. </p>
<p>Here is my existing code:</p>
<pre><code>function downloadJsonToCsv(jsonObject) {
var array = typeof jsonObject != "object" ? JSON.parse(jsonObject) : jsonObject;
if (array == null) {
return; // No data found on the jsonObject
}
var str = "";
for (var i = 0; i < array.length; i++) {
var line = "";
for (var index in array[i]) {
line += array[i][index] + ";"; // Set delimiter
}
// Here is an example where you would wrap the values in double quotes
// for (var index in array[i]) {
// line += '"' + array[i][index] + '",';
// }
line.slice(0,line.Length-1);
str += line + "\r\n";
}
window.open("data:text/csv;charset=utf-8," + encodeURI(str));
}
</code></pre>
<p>I have two questions.</p>
<ol>
<li>How can export this <em>CSV</em> file with correct Greek chars?</li>
<li>How can I export this data in <em>Excel</em> format and not in <em>CSV</em> format?</li>
</ol> | 20,965,911 | 2 | 7 | null | 2013-12-23 08:48:52.623 UTC | 6 | 2018-01-18 21:20:58.653 UTC | 2014-01-18 21:26:39.807 UTC | null | 503,900 | null | 2,455,661 | null | 1 | 17 | javascript|csv|character-encoding|export-to-excel|export-to-csv | 38,182 | <p><strong>Export to CSV</strong> </p>
<p>Exporting to CSV with non-ASCII characters requires prepending the file with the <a href="https://en.wikipedia.org/wiki/Byte_order_mark" rel="noreferrer">Byte Order Mark</a> aka BOM. In your code change</p>
<p><code>var str = "";</code></p>
<p>to:</p>
<p><code>var str = "\uFEFF";</code></p>
<p>You need a modern version of Excel to recognize the BOM. As mentioned in this helpful <a href="https://stackoverflow.com/questions/155097/">StackOverflow article</a>, Excel 2003 and earlier will not honor the BOM correctly. I only have access to Excel 2003 on Windows, so I cannot test this at the moment, but it's fairly well documented.</p>
<p>Sadly, Excel 2011 for the Macintosh is NOT a "modern Excel" in this sense. Happily, Google Sheets do the right thing.</p>
<p><strong>Export directly to Excel</strong></p>
<p>Here's a <strong><a href="http://jsfiddle.net/kmqz9/265/" rel="noreferrer">jsFiddle</a></strong> implementation of the code below. It generates a <a href="http://msdn.microsoft.com/en-us/library/office/aa140066%28v=office.10%29.aspx" rel="noreferrer">SpreadsheetXml</a> document. The upside to this method is you could get VERY tricky ... adding in formulas and doing a lot more things specific to Excel.</p>
<pre><code>// Test script to generate a file from JavaScript such
// that MS Excel will honor non-ASCII characters.
testJson = [
{
"name": "Tony Peña",
"city": "New York",
"country": "United States",
"birthdate": "1978-03-15",
"amount": 42
},
{
"name": "Ζαλώνης Thessaloniki",
"city": "Athens",
"country": "Greece",
"birthdate": "1987-11-23",
"amount": 42
}
];
// Simple type mapping; dates can be hard
// and I would prefer to simply use `datevalue`
// ... you could even add the formula in here.
testTypes = {
"name": "String",
"city": "String",
"country": "String",
"birthdate": "String",
"amount": "Number"
};
emitXmlHeader = function () {
var headerRow = '<ss:Row>\n';
for (var colName in testTypes) {
headerRow += ' <ss:Cell>\n';
headerRow += ' <ss:Data ss:Type="String">';
headerRow += colName + '</ss:Data>\n';
headerRow += ' </ss:Cell>\n';
}
headerRow += '</ss:Row>\n';
return '<?xml version="1.0"?>\n' +
'<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">\n' +
'<ss:Worksheet ss:Name="Sheet1">\n' +
'<ss:Table>\n\n' + headerRow;
};
emitXmlFooter = function() {
return '\n</ss:Table>\n' +
'</ss:Worksheet>\n' +
'</ss:Workbook>\n';
};
jsonToSsXml = function (jsonObject) {
var row;
var col;
var xml;
var data = typeof jsonObject != "object"
? JSON.parse(jsonObject)
: jsonObject;
xml = emitXmlHeader();
for (row = 0; row < data.length; row++) {
xml += '<ss:Row>\n';
for (col in data[row]) {
xml += ' <ss:Cell>\n';
xml += ' <ss:Data ss:Type="' + testTypes[col] + '">';
xml += data[row][col] + '</ss:Data>\n';
xml += ' </ss:Cell>\n';
}
xml += '</ss:Row>\n';
}
xml += emitXmlFooter();
return xml;
};
console.log(jsonToSsXml(testJson));
</code></pre>
<p>This generates the XML document below. If this XML is saved in a file named test.xls, Excel should recognize this and open it with the proper encoding.</p>
<pre><code><?xml version="1.0"?>
<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet">
<ss:Worksheet ss:Name="Sheet1">
<ss:Table>
<ss:Row>
<ss:Cell>
<ss:Data ss:Type="String">name</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="String">city</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="String">country</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="String">birthdate</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="String">amount</ss:Data>
</ss:Cell>
</ss:Row>
<ss:Row>
<ss:Cell>
<ss:Data ss:Type="String">Tony Peña</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="String">New York</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="String">United States</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="String">1978-03-15</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="Number">42</ss:Data>
</ss:Cell>
</ss:Row>
<ss:Row>
<ss:Cell>
<ss:Data ss:Type="String">Ζαλώνης Thessaloniki</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="String">Athens</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="String">Greece</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="String">1987-11-23</ss:Data>
</ss:Cell>
<ss:Cell>
<ss:Data ss:Type="Number">42</ss:Data>
</ss:Cell>
</ss:Row>
</ss:Table>
</ss:Worksheet>
</ss:Workbook>
</code></pre>
<p>I must admit, however, my strong inclination would be to do this server-side if possible. I've used the Python library <code>openpyxl</code> to do this in the past and it is fairly simple. Most server-side languages have a library that generates Excel files and they should provide much better constructs than string concatenation.</p>
<p>Anyway, see this <a href="http://blogs.msdn.com/b/brian_jones/archive/2005/06/27/433152.aspx" rel="noreferrer">MSDN blog</a> for the basics. And this <a href="https://stackoverflow.com/questions/150339/">StackOverflow article</a> for some pros/cons of various other options.</p> |
26,124,914 | How to test React PropTypes through Jest? | <p>I'm writing Jest tests for my React code and hoping to make use of/test the PropType checks. I am quite new to the Javascript universe. I'm using npm to install <code>react-0.11.2</code> and have a simple:</p>
<pre><code>var React = require('react/addons');
</code></pre>
<p>In my tests. My test looks quite similar to the jest/react tutorial example with code like:</p>
<pre class="lang-js prettyprint-override"><code>var eventCell = TestUtils.renderIntoDocument(
<EventCell
slot={slot}
weekId={weekId}
day={day}
eventTypes={eventTypes}
/>
);
var time = TestUtils.findRenderedDOMComponentWithClass(eventCell, 'time');
expect(time.getDOMNode().textContent).toEqual('19:00 ');
</code></pre>
<p>However it seems that the PropType checks in the <code>EventCell</code> component aren't being triggered. I understand that the checks are only run in Development mode but then I also thought that getting <code>react</code> through npm gave you the development version. The checks trigger in my browser when I build the component with watchify.</p>
<p>What am I missing?</p> | 31,835,256 | 7 | 4 | null | 2014-09-30 15:45:33.06 UTC | 8 | 2022-03-17 09:25:03.62 UTC | 2016-11-14 23:59:58.89 UTC | null | 5,921 | null | 98,555 | null | 1 | 35 | reactjs|jestjs|reactjs-testutils|react-proptypes | 29,321 | <p>The underlying problem is <a href="https://stackoverflow.com/questions/7246884/detecting-console-log-calls">How to test <code>console.log</code>?</a></p>
<p>The short answer is that you should replace the <code>console.{method}</code> for the duration of the test. The common approach is to use <a href="http://sinonjs.org/releases/v4.0.0/spies/" rel="noreferrer">spies</a>. In this particular case, you might want to use <a href="http://sinonjs.org/releases/v4.0.0/stubs/" rel="noreferrer">stubs</a> to prevent the output.</p>
<p>Here is an example implementation using <a href="http://sinonjs.org/" rel="noreferrer">Sinon.js</a> (Sinon.js provides standalone spies, stubs and mocks):</p>
<pre class="lang-js prettyprint-override"><code>import {
expect
} from 'chai';
import DateName from './../../src/app/components/DateName';
import createComponent from './create-component';
import sinon from 'sinon';
describe('DateName', () => {
it('throws an error if date input does not represent 12:00:00 AM UTC', () => {
let stub;
stub = sinon.stub(console, 'error');
createComponent(DateName, {date: 1470009600000});
expect(stub.calledOnce).to.equal(true);
expect(stub.calledWithExactly('Warning: Failed propType: Date unix timestamp must represent 00:00:00 (HH:mm:ss) time.')).to.equal(true);
console.error.restore();
});
});
</code></pre>
<p>In this example <code>DataName</code> component will throw an error when initialised with a timestamp value that does not represent a precise date (12:00:00 AM).</p>
<p>I am stubbing the <code>console.error</code> method (This is what Facebook <code>warning</code> module is using internally to generate the error). I ensure that the stub has been called once and with exactly one parameter representing the error.</p> |
11,317,278 | Python IOError: File not open for writing and global name 'w' is not defined | <p>I'm trying to write a little procedure that write (append would be even better) a line in a file with Python, like this: </p>
<pre><code>def getNewNum(nlist):
newNum = ''
for i in nlist:
newNum += i+' '
return newNum
def writeDoc(st):
openfile = open("numbers.txt", w)
openfile.write(st)
newLine = ["44", "299", "300"]
writeDoc(getNewNum(newLine))
</code></pre>
<p>But when I run this, I get the error: </p>
<pre><code>openfile = open("numbers.txt", w)
NameError: global name 'w' is not defined
</code></pre>
<p>If I drop the "w" paremeter, I get this other error:</p>
<pre><code>line 9, in writeDoc
openfile.write(st)
IOError: File not open for writing
</code></pre>
<p>I'm following exactly (I hope) what is <a href="http://www.sthurlow.com/python/lesson10/" rel="noreferrer">here</a>. </p>
<p>The same occurs when I try to append the new line. How can I fix that?</p> | 11,317,288 | 2 | 1 | null | 2012-07-03 18:50:54.863 UTC | 0 | 2015-04-19 08:18:56.81 UTC | 2015-04-19 08:18:56.81 UTC | null | 319,204 | null | 955,883 | null | 1 | 10 | python|io|syntax-error | 42,993 | <p>The problem is in the <a href="http://docs.python.org/library/functions.html?highlight=open#open">open()</a> call in <code>writeDoc()</code> that file mode specification is not correct. </p>
<pre><code>openfile = open("numbers.txt", w)
^
</code></pre>
<p>The <code>w</code> needs to have (a pair of single or double) quotes around it, i.e.,</p>
<pre><code>openfile = open("numbers.txt", "w")
^
</code></pre>
<p>To quote from the <a href="http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files">docs</a> re file mode:</p>
<blockquote>
<p>The first argument is a string containing the filename.
The second argument is another <strong><em>string</em></strong> containing a few characters
describing the way in which the file will be used.</p>
</blockquote>
<p><strong>Re</strong>: "If I drop the "w" paremeter, I get this other error: ..IOError: File not open for writing"</p>
<p>This is because if <em>no</em> file mode is specified the default value is <code>'r'</code>ead, which explains the message about the file not being open for "writing", it's been opened for "reading".</p>
<p>See this Python doc for more information on <a href="http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files">Reading/Writing files</a> and for the valid mode specifications.</p> |
11,412,467 | dismissModalViewController with transition: left to right | <p>I was using a nice method to dismiss my modal view controller:</p>
<pre><code>[self dismissModalViewControllerWithTransition:2];
</code></pre>
<p>which makes a slide transition from left to right, like a navigation controller does to pop a view.</p>
<p>As this method is a non-public method, apple will not accept it. How can I program this kind of animation in my code (slide from left to right, to dismiss a modal view, and slide from right to left to present a modal view) ?</p>
<p>Thanks in advance</p> | 11,414,021 | 3 | 0 | null | 2012-07-10 11:34:06.603 UTC | 11 | 2017-10-04 07:33:52.443 UTC | null | null | null | null | 363,131 | null | 1 | 17 | iphone|animation|uiviewanimationtransition|catransition | 10,373 | <p>I have accepted the answer from Safecase, but I would like to publish my final solution here:</p>
<p>1) To present a modal view controller with a from right to left transition I have written following method:</p>
<pre><code>-(void) presentModalView:(UIViewController *)controller {
CATransition *transition = [CATransition animation];
transition.duration = 0.35;
transition.timingFunction =
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionMoveIn;
transition.subtype = kCATransitionFromRight;
// NSLog(@"%s: self.view.window=%@", _func_, self.view.window);
UIView *containerView = self.view.window;
[containerView.layer addAnimation:transition forKey:nil];
[self presentModalViewController:controller animated:NO];
}
</code></pre>
<p>2) To dismiss a modal view with an slide transition left to right:</p>
<pre><code>-(void) dismissMe {
CATransition *transition = [CATransition animation];
transition.duration = 0.35;
transition.timingFunction =
[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionMoveIn;
transition.subtype = kCATransitionFromLeft;
// NSLog(@"%s: controller.view.window=%@", _func_, controller.view.window);
UIView *containerView = self.view.window;
[containerView.layer addAnimation:transition forKey:nil];
[self dismissModalViewControllerAnimated:NO];
}
</code></pre>
<p>Thanks guys!</p> |
10,960,998 | How different async programming is from Threads? | <p>I've been reading some <code>async</code> articles here: <a href="http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45" rel="noreferrer">http://www.asp.net/web-forms/tutorials/aspnet-45/using-asynchronous-methods-in-aspnet-45</a> and the author says :</p>
<blockquote>
<p>When you’re doing asynchronous work, you’re not always using a thread.
For example, when you make an asynchronous web service request,
ASP.NET will not be using any threads between the async method call
and the await.</p>
</blockquote>
<p>So what I am trying to understand is, how does it become <code>async</code> if we don't use any Threads for concurrent execution? What does it mean "you're not always using a thread."?</p>
<p>Let me first explain what I know regarding working with threads (A quick example, of course Threads can be used in different situations other than UI and Worker methodology here)</p>
<ol>
<li>You have UI Thread to take input, give output.</li>
<li>You can handle things in UI Thread but it makes the UI unresponsive.</li>
<li>So lets say we have a stream-related operation and we need to download some sort of data.</li>
<li>And we also allow users to do other things while it is being downloaded.</li>
<li>We create a new worker thread which downloads the file and changes the progress bar.</li>
<li>Once it is done, there is nothing to do so thread is killed.</li>
<li>We continue from UI thread.</li>
</ol>
<p>We can either wait for the worker thread in UI thread depending on the situation but before that while the file is being downloaded, we can do other things with UI thread and then wait for the worker thread.</p>
<p>Isn't the same for <code>async</code> programming? If not, what's the difference? I read that <code>async</code> programming uses <code>ThreadPool</code> to pull threads from though.</p> | 10,969,951 | 3 | 0 | null | 2012-06-09 12:27:49.48 UTC | 20 | 2014-11-10 16:16:00.97 UTC | null | null | null | null | 44,852 | null | 1 | 33 | c#|asp.net|.net|asynchronous | 8,273 | <p>Threads are not necessary for asynchronous programming.</p>
<p>"Asynchronous" means that the API doesn't block the <em>calling</em> thread. It does <em>not</em> mean that there is another thread that <em>is</em> blocking.</p>
<p>First, consider your UI example, this time using actual asynchronous APIs:</p>
<ol>
<li>You have UI Thread to take input, give output.</li>
<li>You can handle things in UI Thread but it makes the UI unresponsive.</li>
<li>So lets say we have a stream-related operation and we need to download some sort of data.</li>
<li>And we also allow users to do other things while it is being downloaded.</li>
<li><strong>We use asynchronous APIs to download the file.</strong> No worker thread is necessary.</li>
<li>The asynchronous operation reports its progress back to the UI thread (which updates the progress bar), and it also reports its completion to the UI thread (which can respond to it like any other event).</li>
</ol>
<p>This shows how there can be only one thread involved (the UI thread), yet also have asynchronous operations going on. You can start up multiple asynchronous operations and yet only have one thread involved in those operations - no threads are blocked on them.</p>
<p><code>async</code>/<code>await</code> provides a very nice syntax for starting an asynchronous operation and then returning, and having the rest of the method continue when that operation completes.</p>
<p>ASP.NET is similar, except it doesn't have a main/UI thread. Instead, it has a "request context" for every incomplete request. ASP.NET threads come from a thread pool, and they enter the "request context" when they work on a request; when they're done, they exit their "request context" and return to the thread pool.</p>
<p>ASP.NET keeps track of incomplete asynchronous operations for each request, so when a thread returns to the thread pool, it checks to see if there are any asynchronous operations in progress for that request; if there are none, then the request is complete.</p>
<p>So, when you <code>await</code> an incomplete asynchronous operation in ASP.NET, the thread will increment that counter and return. ASP.NET knows the request isn't complete because the counter is non-zero, so it doesn't finish the response. The thread returns to the thread pool, and at that point: there are <em>no</em> threads working on that request.</p>
<p>When the asynchronous operation completes, it schedules the remainder of the <code>async</code> method to the request context. ASP.NET grabs one of its handler threads (which may or may not be the same thread that executed the earlier part of the <code>async</code> method), the counter is decremented, and the thread executes the <code>async</code> method.</p>
<p>ASP.NET vNext is slightly different; there's more support for asynchronous handlers throughout the framework. But the general concept is the same.</p>
<p>For more information:</p>
<ul>
<li><a href="http://nitoprograms.blogspot.com/2012/02/async-and-await.html" rel="noreferrer">My async/await intro post</a> tries to be both an <em>intro</em> yet also <em>reasonably complete</em> picture of how <code>async</code> and <code>await</code> work.</li>
<li>The <a href="http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/10293335.aspx" rel="noreferrer">official async/await FAQ</a> has lots of great links that go into a lot of detail.</li>
<li>The MSDN magazine article <a href="http://msdn.microsoft.com/en-us/magazine/gg598924.aspx" rel="noreferrer">It's All About the SynchronizationContext</a> exposes some of the plumbing underneath.</li>
</ul> |
11,116,399 | crt1.o: In function `_start': - undefined reference to `main' in Linux | <p>I am porting an application from Solaris to Linux</p>
<p>The object files which are linked do not have a main() defined. But compilation and linking is done properly in Solaris and executable is generated. In Linux I get this error </p>
<pre><code> /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
</code></pre>
<p>My problem is, I cannot include new .c/.o files since its a huge application and has been running for years. How can I get rid of this error?</p>
<p>Code extractes of makefile:</p>
<pre><code>RPCAPPN = api
LINK = cc
$(RPCAPPN)_server: $(RPCAPIOBJ)
$(LINK) -g $(RPCAPIOBJ) -o $(RPCAPPN)_server $(IDALIBS) $(LIBS) $(ORALIBS) $(COMMONLIB) $(LIBAPI) $(CCLIB) $(THREADLIB) $(DBSERVERLIB) $(ENCLIB)
</code></pre> | 11,117,836 | 7 | 3 | null | 2012-06-20 09:19:00.68 UTC | 18 | 2022-07-29 09:34:51.41 UTC | 2012-06-20 09:24:42.02 UTC | null | 1,397,853 | null | 1,397,853 | null | 1 | 51 | linux|program-entry-point|undefined-reference | 121,925 | <p>Try adding <code>-nostartfiles</code> to your linker options, i.e.</p>
<pre><code>$(LINK) -nostartfiles -g ...
</code></pre>
<p>From the <a href="http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html" rel="noreferrer">gcc documentation</a>:</p>
<pre><code>-nostartfiles
Do not use the standard system startup files when linking. The standard system libraries are used normally, unless -nostdlib or -nodefaultlibs is used.
</code></pre>
<p>This causes <code>crt1.o</code> not to be linked (it's normally linked by default) - normally only used when you implement your own <code>_start</code> code.</p> |
10,971,149 | The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts" | <p>I'm new to ASP MVC and utilizing the Intro to ASP MVC 4 Beta tutorial <a href="http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4" rel="noreferrer">http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/intro-to-aspnet-mvc-4</a></p>
<p>I'm encountering an error that I can't seem to find an answer to nor do I have much programming experience so I don't know where to even start to fix this an move on with the tutorial. I appreciate any help you can provide.</p>
<p>I'm in the Accessing Your Model's Data from a Controller section and I am getting this error when I attempt to creat a Movie as a part of the tutorial, I click on the the link "Create New" and I get the following error</p>
<blockquote>
<p>The following sections have been defined but have not been rendered for the layout page >"~/Views/Shared/_Layout.cshtml": "Scripts"</p>
</blockquote>
<p>Rather than use Visual Studio express, I opted to download Visual Studio 2012 RC (not sure if that would be the root cause of my issue. </p>
<p>I realize you may require me to include code to answer this but I'm not sure what code to even include. Please advise what code you need me to include if any and I will be happy to add it to my question.</p>
<p>Thank you,</p> | 10,971,246 | 19 | 4 | null | 2012-06-10 18:17:28.897 UTC | 30 | 2021-11-05 12:53:07.263 UTC | null | null | null | null | 613,888 | null | 1 | 119 | asp.net|asp.net-mvc | 150,200 | <p>It means that you have defined a section in your master Layout.cshtml, but you have not included anything for that section in your View.</p>
<p>If your _Layout.cshtml has something like this:</p>
<pre><code>@RenderSection("scripts")
</code></pre>
<p>Then all Views that use that Layout <strong>must</strong> include a <code>@section</code> with the same name (even if the contents of the section are empty):</p>
<pre><code>@{
ViewBag.Title = "Title";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section scripts{
// Add something here
}
</code></pre>
<p>As an alternative,
you can set required to false, then you won't be required to add the section in every View,</p>
<pre><code>@RenderSection("scripts", required: false)
</code></pre>
<p>or also you can wrap the <code>@RenderSection</code> in an <code>if</code> block,</p>
<pre><code>@if (IsSectionDefined("scripts"))
{
RenderSection("scripts");
}
</code></pre> |
13,028,604 | sending a javascript object through websockets with faye | <p>Hi all I'm trying to send a javascript object through websockets:</p>
<p>the faye-websockets documentation says:</p>
<p><strong>send(message)</strong> <em>accepts either a String or a Buffer and sends a text or binary message over the connection to the other peer.</em></p>
<p>server side I'm using node and faye.</p>
<pre><code>var WebSocket = require('faye-websocket');
var http = require('http');
var server = http.createServer();
server.addListener('upgrade', function(request, socket, head) {
var ws = new WebSocket(request, socket, head);
ws.send({topic:'handshake', data:'sdf487rgiuh7'});
});
server.listen(8000);
</code></pre>
<p>client side:</p>
<pre><code><script>
var ws = new WebSocket('ws://localhost:8000');
ws.onmessage = function(e) {
console.log(e.data); //prints [Object object] string and not the object
};
</script>
</code></pre>
<p>what is my error? Thanks</p> | 13,034,191 | 3 | 2 | null | 2012-10-23 10:39:21.38 UTC | 18 | 2018-01-09 12:29:56.187 UTC | 2015-03-12 16:29:02.133 UTC | null | 149,841 | null | 280,235 | null | 1 | 43 | node.js|serialization|websocket|javascript-objects|faye | 79,181 | <p>WebSockets support sending and receiving: strings, typed arrays (ArrayBuffer) and Blobs. Javascript objects must be serialized to one of the above types before sending.</p>
<p>To send an object as a string you can use the builtin JSON support:</p>
<pre><code>ws.send(JSON.stringify(object));
</code></pre>
<p>To send an object as a typed array you can use a javascript BSON library such as <a href="https://github.com/schteppe/js-bson" rel="noreferrer">this one</a>:</p>
<pre><code>ws.send(BSON.serialize(object));
</code></pre>
<p>When you receive a WebSocket message you will need to deserialize it.</p>
<p>To deserialize a JSON string from a WebSocket message:</p>
<pre><code>ws.onmessage = function (e) {
var object = JSON.parse(e.data);
...
};
</code></pre>
<p>If you are using binary messages over WebSocket, then first you should set the binaryType attribute in order to receive all binary messages as typed arrays:</p>
<pre><code>ws.binaryType = "arraybuffer";
</code></pre>
<p>Then the deserialization will look like this:</p>
<pre><code>ws.onmessage = function (e) {
var object = BSON.deserialize(e.data);
...
};
</code></pre>
<p>Here is a blog post about <a href="http://granular.cs.umu.se/browserphysics/?p=1025" rel="noreferrer">using BSON in Javascript</a>;</p> |
12,669,805 | When to use InvalidOperationException or NotSupportedException? | <p>I am implementing a custom collection implementation that can either be readonly or non-readonly; that is, all the methods that change the collection call a function that is the moral equivalent of:</p>
<pre><code>private void ThrowIfReadOnly() {
if (this.isReadOnly)
throw new SomeException("Cannot modify a readonly collection.");
}
</code></pre>
<p>I am not sure which of <code>NotSupportedException</code> or <code>InvalidOperationException</code> I should use in that case.</p> | 12,669,807 | 1 | 0 | null | 2012-10-01 08:28:48.237 UTC | 7 | 2016-03-09 06:24:16.71 UTC | 2013-05-06 10:45:07.037 UTC | null | 57,428 | null | 113,158 | null | 1 | 52 | c#|.net|exception|invalidoperationexception|notsupportedexception | 20,503 | <p>The MSDN only has one bit of guidance on this precise topic, on <a href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx" rel="noreferrer"><code>NotSupportedException</code></a>:</p>
<blockquote>
<p>For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see <a href="http://msdn.microsoft.com/en-us/library/system.invalidoperationexception.aspx" rel="noreferrer"><code>InvalidOperationException</code></a>.</p>
</blockquote>
<p>What follows is purely my own interpretation of the rule:</p>
<ul>
<li>If the object's state can change so that the operation can become invalid / valid during the object's lifetime, then <code>InvalidOperationException</code> should be used.</li>
<li>If the operation is always invalid / valid during the whole object's lifetime, then <code>NotSupportedException</code> should be used.</li>
<li>In that case, "lifetime" means "the whole time that anyone can get a reference to the object" - that is, even after a <code>Dispose()</code> call that often makes most other instance methods unusable;
<ul>
<li>As pointed out by Martin Liversage, in the case of an object having been disposed, the more specific <code>ObjectDisposedException</code> type should be used. (That is still a subtype of <code>InvalidOperationException</code>).</li>
</ul></li>
</ul>
<p>The practical application of these rules in that case would be as follows:</p>
<ul>
<li>If <code>isReadOnly</code> can only be set at the time when the object is created (e.g. a constructor argument), and never at any other time, then <code>NotSupportedException</code> should be used.</li>
<li>If <code>isReadOnly</code> can change during the lifetime of the object, then <code>InvalidOperationException</code> should be used.
<ul>
<li>However, the point of <code>InvalidOperationException</code> vs <code>NotSupportedException</code> is actually moot in the case of implementing a collection - given the description of <a href="http://msdn.microsoft.com/en-us/library/0cfatk9t.aspx" rel="noreferrer"><code>IsReadOnly</code></a> on MSDN, the only permitted behavior for <code>IsReadOnly</code> is that its value never changes after the collection is initialized. Meaning that a collection instance can either be modifiable or read-only - but it should choose one at initialization and stick with it for the rest of its lifetime.</li>
</ul></li>
</ul> |
13,224,553 | How to convert a huge list-of-vector to a matrix more efficiently? | <p>I have a list of length 130,000 where each element is a character vector of length 110. I would like to convert this list to a matrix with dimension 1,430,000*10. How can I do it more efficiently?\
My code is :</p>
<pre><code>output=NULL
for(i in 1:length(z)) {
output=rbind(output,
matrix(z[[i]],ncol=10,byrow=TRUE))
}
</code></pre> | 13,224,720 | 5 | 5 | null | 2012-11-05 00:40:34.23 UTC | 22 | 2019-02-26 20:41:07.573 UTC | 2019-02-26 20:41:07.573 UTC | null | 190,277 | null | 1,787,675 | null | 1 | 68 | r|list|matrix|performance | 154,103 | <p>This should be equivalent to your current code, only a lot faster:</p>
<pre><code>output <- matrix(unlist(z), ncol = 10, byrow = TRUE)
</code></pre> |
12,960,574 | pandas read_csv index_col=None not working with delimiters at the end of each line | <p>I am going through the 'Python for Data Analysis' book and having trouble in the 'Example: 2012 Federal Election Commision Database' section reading the data to a DataFrame. The trouble is that one of the columns of data is always being set as the index column, even when the index_col argument is set to None. </p>
<p>Here is the link to the data : <a href="http://www.fec.gov/disclosurep/PDownload.do">http://www.fec.gov/disclosurep/PDownload.do</a>.</p>
<p>Here is the loading code (to save time in the checking, I set the nrows=10):</p>
<pre><code>import pandas as pd
fec = pd.read_csv('P00000001-ALL.csv',nrows=10,index_col=None)
</code></pre>
<p>To keep it short I am excluding the data column outputs, but here is my output (please not the Index values):</p>
<pre><code>In [20]: fec
Out[20]:
<class 'pandas.core.frame.DataFrame'>
Index: 10 entries, C00410118 to C00410118
Data columns:
...
dtypes: float64(4), int64(3), object(11)
</code></pre>
<p>And here is the book's output (again with data columns excluded):</p>
<pre><code>In [13]: fec = read_csv('P00000001-ALL.csv')
In [14]: fec
Out[14]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 1001731 entries, 0 to 1001730
...
dtypes: float64(1), int64(1), object(14)
</code></pre>
<p>The Index values in my output are actually the first column of data in the file, which is then moving all the rest of the data to the left by one. Would anyone know how to prevent this column of data to be listed as an index? I would like to have the index just +1 increasing integers.</p>
<p>I am fairly new to python and pandas, so I apologize for any inconvenience. Thanks.</p> | 12,961,158 | 3 | 3 | null | 2012-10-18 17:44:44.1 UTC | 12 | 2021-11-07 11:25:39.153 UTC | 2018-08-14 00:22:36.963 UTC | null | 202,229 | null | 1,757,088 | null | 1 | 72 | python|pandas | 204,998 | <h2>Quick Answer</h2>
<p>Use <code>index_col=False</code> instead of <code>index_col=None</code> when you have delimiters at the end of each line to turn off index column inference and discard the last column.</p>
<h2>More Detail</h2>
<p>After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created):</p>
<blockquote>
<p>index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index.</p>
</blockquote>
<p>from <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#column-and-index-locations-and-names" rel="noreferrer">the documentation</a> shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index.</p>
<hr />
<p>EDIT 10/20/2014 - More information</p>
<p>I found <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#index-columns-and-trailing-delimiters" rel="noreferrer">another valuable entry</a> that is specifically about trailing limiters and how to simply ignore them:</p>
<blockquote>
<p>If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ...</p>
<p>Ordinarily, you can achieve this behavior using the index_col option.</p>
<p>There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...</p>
</blockquote> |
12,937,470 | Twitter Bootstrap: Center Text on Progress Bar | <p>I've been using Twitter's bootstrap and I would like the text on the progress bar to be centered on the on bar regardless of value.</p>
<p>The below link is what I have now. I would like all text to be aligned with the bottom most bar.</p>
<p>Screenshot:</p>
<p><img src="https://i.imgur.com/gaE4U.png" alt="progress bar"></p>
<p>I've tried my best with pure CSS and I'm trying to avoid using JS if possible but I'm willing to accept it if it's the cleanest way to do it.</p>
<pre><code><div class="progress">
<div class="bar" style="width: 86%">517/600</div>
</div>
</code></pre> | 17,326,764 | 2 | 0 | null | 2012-10-17 15:08:51.637 UTC | 18 | 2021-12-14 17:04:32.487 UTC | 2016-10-17 10:40:58.187 UTC | null | 5,676,192 | user830186 | null | null | 1 | 78 | css|twitter-bootstrap|progress-bar|centering | 90,370 | <p><strong>Bootstrap 5:</strong> (Same as v4x)</p>
<pre><code><div class="progress position-relative">
<div class="progress-bar" role="progressbar" style="width: 60%" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>
<small class="justify-content-center d-flex position-absolute w-100">60% complete</small>
</div>
</code></pre>
<hr />
<p><strong>Bootstrap 4 with utility classes:</strong> (Thanks to <em>MaPePeR</em> for the addition)</p>
<pre><code><div class="progress position-relative">
<div class="progress-bar" role="progressbar" style="width: 60%" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100"></div>
<small class="justify-content-center d-flex position-absolute w-100">60% complete</small>
</div>
</code></pre>
<hr />
<p><strong>Bootstrap 3:</strong></p>
<p>Bootstrap now supports text within a span element in the Progress bar. HTML as provided in Bootstrap's example. (Notice the class <code>sr-only</code>is removed)</p>
<p>HTML:</p>
<pre><code><div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%;">
<span>60% Complete</span>
</div>
</div>
</code></pre>
<p>... It does however only center the text according to the bar itself, so we need a little bit of custom CSS.</p>
<p>Paste this in another stylesheet/below where you load bootstrap's css:</p>
<p>CSS:</p>
<pre><code>/**
* Progress bars with centered text
*/
.progress {
position: relative;
}
.progress span {
position: absolute;
display: block;
width: 100%;
color: black;
}
</code></pre>
<p><strong>JsBin file:</strong> <a href="http://jsbin.com/IBOwEPog/1/edit" rel="nofollow noreferrer">http://jsbin.com/IBOwEPog/1/edit</a></p>
<hr />
<p><strong>Bootstrap 2:</strong></p>
<p>Paste this in another stylesheet/below where you load Bootstrap's CSS:</p>
<pre><code>/**
* Progress bars with centered text
*/
.progress {
position: relative;
}
.progress .bar {
z-index: 1;
position: absolute;
}
.progress span {
position: absolute;
top: 0;
z-index: 2;
color: black; /* Change according to needs */
text-align: center;
width: 100%;
}
</code></pre>
<p>Then add text to a progress bar by adding a <code>span</code> element outside <code>.bar</code>:</p>
<pre><code><div class="progress">
<div class="bar" style="width: 50%"></div>
<span>Add your text here</span>
</div>
</code></pre>
<p><strong>JsBin:</strong> <a href="http://jsbin.com/apufux/2/edit" rel="nofollow noreferrer">http://jsbin.com/apufux/2/edit</a></p> |
13,134,983 | List<String> to ArrayList<String> conversion issue | <p>I have a following method...which actually takes the list of sentences and splits each sentence into words. Here is it:</p>
<pre><code>public List<String> getWords(List<String> strSentences){
allWords = new ArrayList<String>();
Iterator<String> itrTemp = strSentences.iterator();
while(itrTemp.hasNext()){
String strTemp = itrTemp.next();
allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));
}
return allWords;
}
</code></pre>
<p>I have to pass this list into a hashmap in the following format</p>
<pre><code>HashMap<String, ArrayList<String>>
</code></pre>
<p>so this method returns List and I need an ArrayList? If I try to cast it doesn't work out... any suggestions?</p>
<p>Also, if I change the ArrayList to List in a HashMap, I get</p>
<pre><code>java.lang.UnsupportedOperationException
</code></pre>
<p>because of this line in my code</p>
<pre><code>sentenceList.add(((Element)sentenceNodeList.item(sentenceIndex)).getTextContent());
</code></pre>
<p>Any better suggestions?</p> | 13,135,054 | 8 | 0 | null | 2012-10-30 08:12:21.243 UTC | 14 | 2022-05-02 06:21:45.97 UTC | 2022-05-02 06:21:45.97 UTC | null | 18,467,494 | null | 1,780,520 | null | 1 | 104 | java|list|arraylist | 253,611 | <p>First of all, why is the map a <code>HashMap<String, ArrayList<String>></code> and not a <code>HashMap<String, List<String>></code>? Is there some reason why the value must be a specific implementation of interface <code>List</code> (<code>ArrayList</code> in this case)?</p>
<p><code>Arrays.asList</code> does not return a <code>java.util.ArrayList</code>, so you can't assign the return value of <code>Arrays.asList</code> to a variable of type <code>ArrayList</code>.</p>
<p>Instead of:</p>
<pre><code>allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));
</code></pre>
<p>Try this:</p>
<pre><code>allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));
</code></pre> |
30,362,546 | How to use 2 or more databases with spring? | <p>I have an application that runs Spring MVC.</p>
<p>I need it to access 2 different databases in my app (one is a PostgreSQL and the other one is a MySQL database).</p>
<p>How do I configure this using just annotations or application.properties file?</p>
<p>Regards.</p> | 30,408,034 | 4 | 5 | null | 2015-05-21 00:24:26.82 UTC | 38 | 2020-04-15 15:10:28.39 UTC | 2015-05-22 22:27:07.31 UTC | null | 88,211 | null | 88,211 | null | 1 | 69 | spring|spring-boot|multiple-databases | 94,188 | <p>Here is the example code for having <code>multiple Database/datasource</code> on <code>Spring-Boot</code> I hope it helps! </p>
<p><strong>application.properties</strong></p>
<pre><code>spring.ds_items.driverClassName=org.postgresql.Driver
spring.ds_items.url=jdbc:postgresql://srv0/test
spring.ds_items.username=test0
spring.ds_items.password=test0
spring.ds_users.driverClassName=org.postgresql.Driver
spring.ds_users.url=jdbc:postgresql://srv1/test
spring.ds_users.username=test1
spring.ds_users.password=test1
</code></pre>
<p><strong>DatabaseItemsConfig.java</strong></p>
<pre><code>package sb;
import org.springframework.boot.autoconfigure.jdbc.TomcatDataSourceConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
@ConfigurationProperties(name = "spring.ds_items")
public class DatabaseItemsConfig extends TomcatDataSourceConfiguration {
@Bean(name = "dsItems")
public DataSource dataSource() {
return super.dataSource();
}
@Bean(name = "jdbcItems")
public JdbcTemplate jdbcTemplate(DataSource dsItems) {
return new JdbcTemplate(dsItems);
}
}
</code></pre>
<p><strong>DatabaseUsersConfig.java</strong></p>
<pre><code>package sb;
import org.springframework.boot.autoconfigure.jdbc.TomcatDataSourceConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
@ConfigurationProperties(name = "spring.ds_users")
public class DatabaseUsersConfig extends TomcatDataSourceConfiguration {
@Bean(name = "dsUsers")
public DataSource dataSource() {
return super.dataSource();
}
@Bean(name = "jdbcUsers")
public JdbcTemplate jdbcTemplate(DataSource dsUsers) {
return new JdbcTemplate(dsUsers);
}
}
</code></pre>
<p><strong>ItemRepository.java</strong></p>
<pre><code>package sb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
@Repository
public class ItemRepository {
protected final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("jdbcItems")
protected JdbcTemplate jdbc;
public Item getItem(long id) {
return jdbc.queryForObject("SELECT * FROM sb_item WHERE id=?", itemMapper, id);
}
private static final RowMapper<Item> itemMapper = new RowMapper<Item>() {
public Item mapRow(ResultSet rs, int rowNum) throws SQLException {
Item item = new Item(rs.getLong("id"), rs.getString("title"));
item.price = rs.getDouble("id");
return item;
}
};
}
</code></pre>
<p><strong>UserRepository.java</strong></p>
<pre><code>package sb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
@Repository
public class UserRepository {
protected final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
@Qualifier("jdbcUsers")
protected JdbcTemplate jdbc;
public User getUser(long id) {
return jdbc.queryForObject("SELECT * FROM sb_user WHERE id=?", userMapper, id);
}
private static final RowMapper<User> userMapper = new RowMapper<User>() {
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User(rs.getLong("id"), rs.getString("name"));
user.alias = rs.getString("alias");
return user;
}
};
}
</code></pre>
<p><strong>Controller.java</strong></p>
<pre><code>package sb;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Controller {
protected final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private UserRepository users;
@Autowired
private ItemRepository items;
@RequestMapping("test")
public String test() {
log.info("Test");
return "OK";
}
@RequestMapping("user")
public User getUser(@RequestParam("id") long id) {
log.info("Get user");
return users.getUser(id);
}
@RequestMapping("item")
public Item getItem(@RequestParam("id") long id) {
log.info("Get item");
return items.getItem(id);
}
}
</code></pre>
<p><strong>Application.java</strong></p>
<pre><code>package sb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@EnableAutoConfiguration(exclude = DataSourceAutoConfiguration.class)
@Configuration
@ComponentScan(basePackages = "sb")
public class Application {
public static void main(String[] args) throws Throwable {
SpringApplication app = new SpringApplication(Application.class);
app.run();
}
}
</code></pre> |
37,445,838 | Returning values in Elixir? | <p>I've recently decided to learn Elixir. Coming from a C++/Java/JavaScript background I've been having a lot of trouble grasping the basics. This might sound stupid but how would return statements work in Elixir? I've looked around and it seems as though it's just the last line of a function i.e.</p>
<pre><code>def Hello do
"Hello World!"
end
</code></pre>
<p>Would this function return "Hello World!", is there another way to do a return? Also, how would you return early? in JavaScript we could write something like this to find if an array has a certain value in it:</p>
<pre><code>function foo(a){
for(var i = 0;i<a.length;i++){
if(a[i] == "22"){
return true;
}
}
return false;
}
</code></pre>
<p>How would that work in Elixir?</p> | 37,446,794 | 2 | 6 | null | 2016-05-25 19:17:29.26 UTC | 2 | 2016-05-25 20:15:03.72 UTC | null | null | null | null | 3,072,896 | null | 1 | 28 | function|elixir | 26,742 | <p>Elixir has no 'break out' keyword that would be equivalent to the 'return' keyword in other languages.</p>
<p>Typically what you would do is re-structure your code so the last statement executed is the return value.</p>
<p>Below is an idiomatic way in elixir to perform the equivalent of your code test, assuming you meant 'a' as something that behaves kind of array like in your initial example:</p>
<pre><code>def is_there_a_22(a) do
Enum.any?(a, fn(item) -> item == "22" end.)
end
</code></pre>
<p>What's actually going on here is we're restructuring our thinking a little bit. Instead of the procedural approach, where we'd search through the array and return early if we find what we were looking for, we're going to ask what you are really after in the code snippet:
"Does this array have a 22 anywhere?"</p>
<p>We are then going to use the elixir Enum library to run through the array for us, and provide the <code>any?</code> function with a test which will tell us if anything matches the criteria we cared about.</p>
<p>While this is a case that is easily solved with enumeration, I think it's possible the heart of your question applies more to things such as the 'bouncer pattern' used in procedural methods. For example, if I meet certain criteria in a method, return right away. A good example of this would be a method that returns false if the thing you're going to do work on is null:</p>
<pre><code>function is_my_property_true(obj) {
if (obj == null) {
return false;
}
// .....lots of code....
return some_result_from_obj;
}
</code></pre>
<p>The only way to really accomplish this in elixir is to put the guard up front and factor out a method:</p>
<pre><code>def test_property_val_from_obj(obj) do
# ...a bunch of code about to get the property
# want and see if it is true
end
def is_my_property_true(obj) do
case obj do
nil -> false
_ -> test_property_value_from_obj(obj)
end
end
</code></pre>
<p>tl;dr - No there isn't an equivalent - you need to structure your code accordingly. On the flip side, this tends to keep your methods small - and your intent clear.</p> |
16,937,207 | Android - How to Set a semi-transparent layout? | <p>I'm new to android application. <img src="https://i.stack.imgur.com/94X8c.png" alt="enter image description here"></p>
<p>In this picture,there is a bottom layout with some options like play,delete etc.., and has its transparency to show its background.</p>
<p>How to I get like that ?</p> | 16,937,268 | 5 | 4 | null | 2013-06-05 10:12:07.123 UTC | 12 | 2019-05-23 01:04:06.237 UTC | null | null | null | null | 2,409,495 | null | 1 | 19 | java|android | 45,756 | <p>use <code>android:background ="#88676767"</code> change the first <em>88</em> to your selection of opacity</p>
<p>In reply to your comment:</p>
<pre><code>ImageView iv = (ImageView) findViewById(your_imageId);
iv.setColorFilter(Color.argb(150, 155, 155, 155), Mode.SRC_ATOP);
</code></pre>
<p><strong>Third option:</strong></p>
<pre><code>LinearLayout layout = (LinearLayout) findViewById(R.id.your_id);
Drawable d = getResources().getDrawable(R.relevant_drawable);
d.setAlpha(50);
layout.setBackgroundDrawable(d);
</code></pre> |
16,891,530 | Publish one web project from solution with msbuild | <p>I'm trying to deploy one of the web projects in my solution to a server. I am using msbuild on TeamCity like so:</p>
<pre><code>msbuild MySolution.sln /t:WebSite:Rebuild /p:DeployOnBuild=True /p:PublishProfile=Prod ...
</code></pre>
<p>However, when I run it, msbuild still tries to build my <code>WebService</code> project, even though my <code>WebSite</code> project does not depend on it (but it does depend on a <code>Services</code> project also in the solution). How do only publish one project, aka just <code>WebSite</code>?</p>
<p>I have also tried building the project file using</p>
<pre><code>msbuild WebSite/WebSite.csproj /p:DeployOnBuild=True ...
</code></pre>
<p>but it then complains that it can't restore packages:</p>
<pre><code>[07:47:17]WebSite\WebSite.csproj.teamcity: Build target: Build
[07:47:17][WebSite\WebSite.csproj.teamcity] RestorePackages
[07:47:17][RestorePackages] Exec
[07:47:17][Exec] C:\TeamCity\buildAgent\work\cab8a3d752df3a51\.nuget\NuGet.targets(90, 15): error MSB4064: The "LogStandardErrorAsError" parameter is not supported by the "Exec" task. Verify the parameter exists on the task, and it is a settable public instance property.
[07:47:17][Exec] C:\TeamCity\buildAgent\work\cab8a3d752df3a51\.nuget\NuGet.targets(89, 9): error MSB4063: The "Exec" task could not be initialized with its input parameters.
[07:47:17][WebSite\WebSite.csproj.teamcity] Project WebSite\WebSite.csproj.teamcity failed.
</code></pre>
<p>When I disable NuGet Package Restore, CoreCompile (Csc) fails with errors I've never heard of and shouldn't be happening:</p>
<pre><code>[07:54:43]WebSite\WebSite.csproj.teamcity: Build target: Build (13s)
[07:54:55][WebSite\WebSite.csproj.teamcity] CoreCompile
[07:54:55][CoreCompile] Csc
[07:54:56][Csc] Areas\Api\Services\TripService.cs(19, 104): error CS0241: Default parameter specifiers are not permitted
[07:54:56][Csc] Helpers\StatisticsUtility.cs(11, 35): error CS1031: Type expected
[07:54:56][Csc] Helpers\StatisticsUtility.cs(11, 53): error CS1002: ; expected
[07:54:56][Csc] Helpers\StatisticsUtility.cs(16, 28): error CS1519: Invalid token '(' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(16, 37): error CS1519: Invalid token ',' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(17, 27): error CS1519: Invalid token '(' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(17, 32): error CS1519: Invalid token ')' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(23, 17): error CS1519: Invalid token 'for' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(23, 26): error CS1519: Invalid token '<=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(23, 45): error CS1519: Invalid token '-' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(23, 51): error CS1519: Invalid token '++' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(24, 34): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
[07:54:56][Csc] Helpers\StatisticsUtility.cs(24, 37): error CS1519: Invalid token '==' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(24, 51): error CS1519: Invalid token ')' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(24, 63): error CS1519: Invalid token '++' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(25, 41): error CS1519: Invalid token '>' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(25, 53): error CS1519: Invalid token ')' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(27, 36): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(27, 48): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(28, 36): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(29, 37): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(29, 48): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
[07:54:56][Csc] Helpers\StatisticsUtility.cs(29, 50): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(30, 33): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(30, 44): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
[07:54:56][Csc] Helpers\StatisticsUtility.cs(30, 50): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(32, 21): error CS0116: A namespace does not directly contain members such as fields or methods
[07:54:56][Csc] Helpers\StatisticsUtility.cs(35, 50): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\StatisticsUtility.cs(38, 21): error CS0116: A namespace does not directly contain members such as fields or methods
[07:54:56][Csc] Helpers\StatisticsUtility.cs(40, 50): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\StatisticsUtility.cs(42, 21): error CS1022: Type or namespace definition, or end-of-file expected
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(8, 59): error CS1031: Type expected
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(8, 80): error CS1002: ; expected
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(10, 55): error CS1519: Invalid token '(' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(10, 60): error CS1520: Class, struct, or interface method must have a return type
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(10, 82): error CS1002: ; expected
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(13, 23): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(15, 60): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(18, 23): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(20, 25): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(23, 28): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(26, 28): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(29, 24): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(29, 84): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(32, 28): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(35, 9): error CS1022: Type or namespace definition, or end-of-file expected
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(23, 26): error CS0101: The namespace '<global namespace>' already contains a definition for '?'
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(26, 26): error CS0101: The namespace '<global namespace>' already contains a definition for '?'
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(29, 22): error CS0101: The namespace '<global namespace>' already contains a definition for '?'
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(29, 83): error CS0101: The namespace '<global namespace>' already contains a definition for '?'
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(32, 26): error CS0101: The namespace '<global namespace>' already contains a definition for '?'
[07:54:56][Csc] Controllers\SessionController.cs(13, 51): error CS0241: Default parameter specifiers are not permitted
[07:54:56][Csc] Helpers\JsonNetResult.cs(13, 44): error CS1031: Type expected
[07:54:56][Csc] Helpers\JsonNetResult.cs(13, 72): error CS1041: Identifier expected, 'object' is a keyword
[07:54:56][Csc] Helpers\JsonNetResult.cs(13, 91): error CS1002: ; expected
[07:54:56][Csc] Helpers\JsonNetResult.cs(16, 38): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(16, 59): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(17, 64): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(17, 90): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(18, 32): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(18, 46): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(19, 33): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(22, 23): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\JsonNetResult.cs(25, 37): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\JsonNetResult.cs(32, 23): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\JsonNetResult.cs(35, 37): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\JsonNetResult.cs(40, 9): error CS1022: Type or namespace definition, or end-of-file expected
[07:54:56][Csc] Mailers\ITripMailer.cs(13, 132): error CS0241: Default parameter specifiers are not permitted
[07:54:56][Csc] Mailers\TripMailer.cs(54, 85): error CS0241: Default parameter specifiers are not permitted
[07:54:56][Csc] Services\Impl\AuthorizationService.cs(12, 70): error CS0241: Default parameter specifiers are not permitted
[07:54:56][Csc] Services\Impl\AuthorizationService.cs(43, 77): error CS0241: Default parameter specifiers are not permitted
[07:54:56][WebSite\WebSite.csproj.teamcity] Project WebSite\WebSite.csproj.teamcity failed.
</code></pre> | 16,903,952 | 3 | 0 | null | 2013-06-03 07:01:02.11 UTC | 17 | 2020-09-08 06:37:33.2 UTC | 2013-06-03 08:13:17.53 UTC | null | 264,675 | null | 264,675 | null | 1 | 46 | c#|msbuild|teamcity|webdeploy | 34,974 | <p>I blogged about this at <a href="http://sedodream.com/2013/03/06/HowToPublishOneWebProjectFromASolution.aspx" rel="noreferrer">http://sedodream.com/2013/03/06/HowToPublishOneWebProjectFromASolution.aspx</a> a few months back. I've copied the details here as well, see below.</p>
<hr>
<p>Today on twitter <a href="https://twitter.com/nunofcosta" rel="noreferrer">@nunofcosta</a> asked me roughly the question “How do I publish one web project from a solution that contains many?”</p>
<p>The issue that he is running into is that he is building from the command line and passing the following properties to msbuild.exe.</p>
<pre><code>/p:DeployOnBuild=true
/p:PublishProfile='siteone - Web Deploy'
/p:Password=%password%
</code></pre>
<p>You can read more about how to automate publishing at <a href="http://sedodream.com/2013/01/06/CommandLineWebProjectPublishing.aspx" rel="noreferrer">http://sedodream.com/2013/01/06/CommandLineWebProjectPublishing.aspx</a>.</p>
<p>When you pass these properties to msbuild.exe they are known as global properties. These properties are difficult to override and are passed to every project that is built. Because of this if you have a solution with multiple web projects, when each web project is built it is passed in the same set of properties. Because of this when each project is built the publish process for that project will start and it will expect to find a file named <strong>siteone – Web Deploy.pubxml</strong> in the folder *Properties\PublishProfiles*. If the file doesn’t exist the operation may fail.</p>
<p><strong>Note: If you are interested in using this technique for an orchestrated publish see my comments at <a href="https://stackoverflow.com/a/14231729/105999">https://stackoverflow.com/a/14231729/105999</a> before doing so.</strong></p>
<p>So how can we resolve this?</p>
<p>Let’s take a look at a sample (see links below). I have a solution, <strong>PublishOnlyOne</strong>, with the following projects.</p>
<ol>
<li>ProjA</li>
<li>ProjB</li>
</ol>
<p>ProjA has a publish profile named ‘<strong>siteone – Web Deploy</strong>’, ProjB does not. When trying to publish this you may try the following command line.</p>
<pre><code>msbuild.exe PublishOnlyOne.sln /p:DeployOnBuild=true /p:PublishProfile=’siteone – Web Deploy’ /p:Password=%password%
</code></pre>
<p><em>See publish-sln.cmd in the samples.</em></p>
<p>If you do this, when its time for ProjB to build it will fail because there’s no <strong>siteone – Web Deploy</strong> profile for that project. Because of this, we cannot pass DeployOnBuild. Instead here is what we need to do.</p>
<ol>
<li>Edit ProjA.csproj to define another property which will conditionally set DeployOnBuild</li>
<li>From the command line pass in that property</li>
</ol>
<p>I edited ProjA and added the following property group before the Import statements in the .csproj file.</p>
<pre><code><PropertyGroup>
<DeployOnBuild Condition=" '$(DeployProjA)'!='' ">$(DeployProjA)</DeployOnBuild>
</PropertyGroup>
</code></pre>
<p>Here you can see that DeployOnBuild is set to whatever value DeployProjA is as long as it’s not empty. Now the revised command is:</p>
<pre><code>msbuild.exe PublishOnlyOne.sln /p:DeployProjA=true /p:PublishProfile=’siteone – Web Deploy’ /p:Password=%password%
</code></pre>
<p>Here instead of passing DeployOnBuild, I pass in DeployProjA which will then set DeployOnBuild. Since DeployOnBuild wasn’t passed to ProjB it will not attempt to publish.</p>
<p>You can find the complete sample at <a href="https://github.com/sayedihashimi/sayed-samples/tree/master/PublishOnlyOne" rel="noreferrer">https://github.com/sayedihashimi/sayed-samples/tree/master/PublishOnlyOne</a>.</p> |
63,110,475 | PhpStorm Debugger extension is not detected while using with PHPUnit | <p>I am using PHPUnit through PhpStorm with a remote interpreter from docker.
The Container is run through <code>docker-compose</code></p>
<p>PHPUnit works. Xdebug works through the browser. In <code>docker-php-ext-xdebug.ini</code>, I have all the mandatory options, and I can see in the <code>CLI Interpreter Config</code> that PhpStorm does load this config.</p>
<p>BUT when I try to run PHPUnit with the debugger I get:</p>
<blockquote>
<p>PhpStorm Debugger extension is not detected</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/A7YuV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/A7YuV.png" alt="PhpStorm Debugger extension is not detected" /></a></p>
<p><strong>CLI Interpreter Config:</strong></p>
<p><a href="https://i.stack.imgur.com/uj2SX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uj2SX.png" alt="CLI Interpreter Config" /></a></p>
<p><strong>DockerFile</strong></p>
<pre><code>FROM php:7.4-fpm-alpine
# OS DEPENDENCIES
RUN apk update
RUN apk add --no-cache bash git curl libmcrypt libmcrypt-dev openssh-client icu-dev
RUN apk add --no-cache libxml2-dev freetype-dev libpng-dev libjpeg-turbo-dev zip libzip-dev g++ make autoconf
RUN apk add --no-cache postgresql-dev
RUN docker-php-source extract
RUN pecl install xdebug redis
RUN docker-php-ext-enable xdebug redis
RUN docker-php-source delete
RUN docker-php-ext-install -j$(nproc) pgsql
RUN docker-php-ext-install -j$(nproc) pdo_pgsql
RUN docker-php-ext-install soap intl zip
RUN docker-php-ext-install opcache
# XDEBUG CONFIGURATION
ARG XDEBUG_REMOTE_HOST
ARG XDEBUG_REMOTE_PORT
ARG XDEBUG_REMOTE_CONNECT_BACK
ARG XDEBUG_INI=/usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini
RUN echo "error_reporting = E_ALL" >> ${XDEBUG_INI}
RUN echo "display_startup_errors=1" >> ${XDEBUG_INI}
RUN echo "display_errors=1" >> ${XDEBUG_INI}
RUN echo "xdebug.profiler_enable=1" >> ${XDEBUG_INI}
RUN echo "xdebug.remote_enable=1" >> ${XDEBUG_INI}
RUN echo "xdebug.remote_connect_back=$XDEBUG_REMOTE_CONNECT_BACK" >> ${XDEBUG_INI}
RUN echo "xdebug.idekey=\"PHPSTORM\"" >> ${XDEBUG_INI}
RUN echo "xdebug.remote_handler=dbgp" >> ${XDEBUG_INI}
RUN echo "xdebug.remote_port=$XDEBUG_REMOTE_PORT" >> ${XDEBUG_INI}
RUN echo "xdebug.remote_host=$XDEBUG_REMOTE_HOST" >> ${XDEBUG_INI}
RUN echo "xdebug.remote_autostart=1" >> ${XDEBUG_INI}
# COMPOSER INSTALLATION
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
# EXORT COMPOSER GLOBAL PATH
ENV PATH="$PATH:$HOME/.composer/vendor/bin" #edited
</code></pre>
<p><strong>docker-compose.yaml</strong></p>
<pre><code> dataapi:
container_name: dataapi
build:
context: ${DOCKER_FILES_PATH}/privateapi/
args:
- XDEBUG_REMOTE_PORT=10000
- XDEBUG_REMOTE_HOST=172.17.0.1 #DOCKER network IP
- XDEBUG_REMOTE_CONNECT_BACK=0 #edited
command: sh -c "composer install && bin/console doctrine:migrations:migrate --allow-no-migration -n && php-fpm"
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>Here is the result of phpinto() in phpunit:</p>
<pre><code>sodium
sodium support => enabled
libsodium headers version => 1.0.18
libsodium library version => 1.0.18
SPL
SPL support => enabled
Interfaces => OuterIterator, RecursiveIterator, SeekableIterator, SplObserver, SplSubject
Classes => AppendIterator, ArrayIterator, ArrayObject, BadFunctionCallException, BadMethodCallException, CachingIterator, CallbackFilterIterator, DirectoryIterator, DomainException, EmptyIterator, FilesystemIterator, FilterIterator, GlobIterator, InfiniteIterator, InvalidArgumentException, IteratorIterator, LengthException, LimitIterator, LogicException, MultipleIterator, NoRewindIterator, OutOfBoundsException, OutOfRangeException, OverflowException, ParentIterator, RangeException, RecursiveArrayIterator, RecursiveCachingIterator, RecursiveCallbackFilterIterator, RecursiveDirectoryIterator, RecursiveFilterIterator, RecursiveIteratorIterator, RecursiveRegexIterator, RecursiveTreeIterator, RegexIterator, RuntimeException, SplDoublyLinkedList, SplFileInfo, SplFileObject, SplFixedArray, SplHeap, SplMinHeap, SplMaxHeap, SplObjectStorage, SplPriorityQueue, SplQueue, SplStack, SplTempFileObject, UnderflowException, UnexpectedValueException
sqlite3
SQLite3 support => enabled
SQLite Library => 3.32.1
Directive => Local Value => Master Value
sqlite3.defensive => 1 => 1
sqlite3.extension_dir => no value => no value
standard
Dynamic Library Support => enabled
Path to sendmail => /usr/sbin/sendmail -t -i
Directive => Local Value => Master Value
assert.active => 1 => 1
assert.bail => 0 => 0
assert.callback => no value => no value
assert.exception => 0 => 0
assert.quiet_eval => 0 => 0
assert.warning => 1 => 1
auto_detect_line_endings => 0 => 0
default_socket_timeout => 60 => 60
from => no value => no value
session.trans_sid_hosts => no value => no value
session.trans_sid_tags => a=href,area=href,frame=src,form= => a=href,area=href,frame=src,form=
unserialize_max_depth => 4096 => 4096
url_rewriter.hosts => no value => no value
url_rewriter.tags => form= => form=
user_agent => no value => no value
tokenizer
Tokenizer Support => enabled
xdebug
xdebug support => enabled
Version => 2.9.6
Support Xdebug on Patreon, GitHub, or as a business: https://xdebug.org/support
Debugger => enabled
IDE Key => PHPSTORM
Directive => Local Value => Master Value
xdebug.auto_trace => Off => Off
xdebug.cli_color => 0 => 0
xdebug.collect_assignments => Off => Off
xdebug.collect_includes => On => On
xdebug.collect_params => 0 => 0
xdebug.collect_return => Off => Off
xdebug.collect_vars => Off => Off
xdebug.coverage_enable => On => On
xdebug.default_enable => On => On
xdebug.dump.COOKIE => no value => no value
xdebug.dump.ENV => no value => no value
xdebug.dump.FILES => no value => no value
xdebug.dump.GET => no value => no value
xdebug.dump.POST => no value => no value
xdebug.dump.REQUEST => no value => no value
xdebug.dump.SERVER => no value => no value
xdebug.dump.SESSION => no value => no value
xdebug.dump_globals => On => On
xdebug.dump_once => On => On
xdebug.dump_undefined => Off => Off
xdebug.file_link_format => no value => no value
xdebug.filename_format => no value => no value
xdebug.force_display_errors => Off => Off
xdebug.force_error_reporting => 0 => 0
xdebug.gc_stats_enable => Off => Off
xdebug.gc_stats_output_dir => /tmp => /tmp
xdebug.gc_stats_output_name => gcstats.%p => gcstats.%p
xdebug.halt_level => 0 => 0
xdebug.idekey => PHPSTORM => PHPSTORM
xdebug.max_nesting_level => 256 => 256
xdebug.max_stack_frames => -1 => -1
xdebug.overload_var_dump => 2 => 2
xdebug.profiler_append => Off => Off
xdebug.profiler_enable => On => On
xdebug.profiler_enable_trigger => Off => Off
xdebug.profiler_enable_trigger_value => no value => no value
xdebug.profiler_output_dir => /tmp => /tmp
xdebug.profiler_output_name => cachegrind.out.%p => cachegrind.out.%p
xdebug.remote_addr_header => no value => no value
xdebug.remote_autostart => On => On
xdebug.remote_connect_back => Off => Off
xdebug.remote_cookie_expire_time => 3600 => 3600
xdebug.remote_enable => On => On
xdebug.remote_host => 172.17.0.1 => 172.17.0.1
xdebug.remote_log => no value => no value
xdebug.remote_log_level => 7 => 7
xdebug.remote_mode => req => req
xdebug.remote_port => 10000 => 10000
xdebug.remote_timeout => 200 => 200
xdebug.scream => Off => Off
xdebug.show_error_trace => Off => Off
xdebug.show_exception_trace => Off => Off
xdebug.show_local_vars => Off => Off
xdebug.show_mem_delta => Off => Off
xdebug.trace_enable_trigger => Off => Off
xdebug.trace_enable_trigger_value => no value => no value
xdebug.trace_format => 0 => 0
xdebug.trace_options => 0 => 0
xdebug.trace_output_dir => /tmp => /tmp
xdebug.trace_output_name => trace.%c => trace.%c
xdebug.var_display_max_children => 128 => 128
xdebug.var_display_max_data => 512 => 512
xdebug.var_display_max_depth => 3 => 3
xml
XML Support => active
XML Namespace Support => active
libxml2 Version => 2.9.10
xmlreader
XMLReader => enabled
xmlwriter
XMLWriter => enabled
Zend OPcache
Opcode Caching => Disabled
Optimization => Disabled
SHM Cache => Enabled
File Cache => Disabled
Startup Failed => Opcode Caching is disabled for CLI
Directive => Local Value => Master Value
opcache.blacklist_filename => no value => no value
opcache.consistency_checks => 0 => 0
opcache.dups_fix => Off => Off
opcache.enable => On => On
opcache.enable_cli => Off => Off
opcache.enable_file_override => Off => Off
opcache.error_log => no value => no value
opcache.file_cache => no value => no value
opcache.file_cache_consistency_checks => On => On
opcache.file_cache_only => Off => Off
opcache.file_update_protection => 2 => 2
opcache.force_restart_timeout => 180 => 180
opcache.huge_code_pages => Off => Off
opcache.interned_strings_buffer => 8 => 8
opcache.lockfile_path => /tmp => /tmp
opcache.log_verbosity_level => 1 => 1
opcache.max_accelerated_files => 10000 => 10000
opcache.max_file_size => 0 => 0
opcache.max_wasted_percentage => 5 => 5
opcache.memory_consumption => 128 => 128
opcache.opt_debug_level => 0 => 0
opcache.optimization_level => 0 => 0x7FFEBFFF
opcache.preferred_memory_model => no value => no value
opcache.preload => no value => no value
opcache.preload_user => no value => no value
opcache.protect_memory => Off => Off
opcache.restrict_api => no value => no value
opcache.revalidate_freq => 2 => 2
opcache.revalidate_path => Off => Off
opcache.save_comments => On => On
opcache.use_cwd => On => On
opcache.validate_permission => Off => Off
opcache.validate_root => Off => Off
opcache.validate_timestamps => On => On
zip
Zip => enabled
Zip version => 1.15.6
Libzip headers version => 1.6.1
Libzip library version => 1.6.1
zlib
ZLib Support => enabled
Stream Wrapper => compress.zlib://
Stream Filter => zlib.inflate, zlib.deflate
Compiled Version => 1.2.11
Linked Version => 1.2.11
Directive => Local Value => Master Value
zlib.output_compression => Off => Off
zlib.output_compression_level => -1 => -1
zlib.output_handler => no value => no value
Additional Modules
Module Name
Environment
Variable => Value
PATH => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/.composer/vendor/bin
HOSTNAME => fb6d372627df
JETBRAINS_REMOTE_RUN => 1
IDE_PHPUNIT_PHPUNIT_PHAR => /var/www/privateapi/vendor/bin/.phpunit/phpunit-7.5-0/phpunit
IDE_PHPUNIT_VERSION => 7.5.20
PHPIZE_DEPS => autoconf dpkg-dev dpkg file g++ gcc libc-dev make pkgconf re2c
PHP_INI_DIR => /usr/local/etc/php
PHP_EXTRA_CONFIGURE_ARGS => --enable-fpm --with-fpm-user=www-data --with-fpm-group=www-data --disable-cgi
PHP_CFLAGS => -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
PHP_CPPFLAGS => -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
PHP_LDFLAGS => -Wl,-O1 -pie
GPG_KEYS => 42670A7FE4D0441C8E4632349E4FDC074A4EF02D 5A52880781F755608BF815FC910DEB46F53EA312
PHP_VERSION => 7.4.7
PHP_URL => https://www.php.net/distributions/php-7.4.7.tar.xz
PHP_ASC_URL => https://www.php.net/distributions/php-7.4.7.tar.xz.asc
PHP_SHA256 => 53558f8f24cd8ab6fa0ea252ca8198e2650160649681ce5230c1df1dc2b52faf
PHP_MD5 =>
HOME => /root
APP_ENV => test
KERNEL_CLASS => App\Kernel
APP_AUTH_API_HOST => http://authapi
DATABASE_URL_TEST => postgresql://postgres:[email protected]:5433/privateapi_test
CORS_ALLOW_ORIGIN => ^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$
PHP Variables
Variable => Value
$_ENV['PATH'] => /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/.composer/vendor/bin
$_ENV['HOSTNAME'] => fb6d372627df
$_ENV['JETBRAINS_REMOTE_RUN'] => 1
$_ENV['IDE_PHPUNIT_PHPUNIT_PHAR'] => /var/www/privateapi/vendor/bin/.phpunit/phpunit-7.5-0/phpunit
$_ENV['IDE_PHPUNIT_VERSION'] => 7.5.20
$_ENV['PHPIZE_DEPS'] => autoconf dpkg-dev dpkg file g++ gcc libc-dev make pkgconf re2c
$_ENV['PHP_INI_DIR'] => /usr/local/etc/php
$_ENV['PHP_EXTRA_CONFIGURE_ARGS'] => --enable-fpm --with-fpm-user=www-data --with-fpm-group=www-data --disable-cgi
$_ENV['PHP_CFLAGS'] => -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
$_ENV['PHP_CPPFLAGS'] => -fstack-protector-strong -fpic -fpie -O2 -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64
$_ENV['PHP_LDFLAGS'] => -Wl,-O1 -pie
$_ENV['GPG_KEYS'] => 42670A7FE4D0441C8E4632349E4FDC074A4EF02D 5A52880781F755608BF815FC910DEB46F53EA312
$_ENV['PHP_VERSION'] => 7.4.7
$_ENV['PHP_URL'] => https://www.php.net/distributions/php-7.4.7.tar.xz
$_ENV['PHP_ASC_URL'] => https://www.php.net/distributions/php-7.4.7.tar.xz.asc
$_ENV['PHP_SHA256'] => 53558f8f24cd8ab6fa0ea252ca8198e2650160649681ce5230c1df1dc2b52faf
$_ENV['PHP_MD5'] =>
$_ENV['HOME'] => /root
$_ENV['APP_ENV'] => test
$_ENV['KERNEL_CLASS'] => App\Kernel
$_ENV['APP_AUTH_API_HOST'] => http://authapi
$_ENV['DATABASE_URL_TEST'] => postgresql://postgres:[email protected]:5433/privateapi_test
$_ENV['CORS_ALLOW_ORIGIN'] => ^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$
$_ENV['APP_SECRET'] => $ecretf0rt3st
$_ENV['DATABASE_URL'] =>
$_ENV['SYMFONY_DOTENV_VARS'] => APP_SECRET,DATABASE_URL,SYMFONY_DEPRECATIONS_HELPER,PANTHER_APP_ENV
$_ENV['SYMFONY_DEPRECATIONS_HELPER'] => 999999
$_ENV['PANTHER_APP_ENV'] => panther
$_ENV['APP_DEBUG'] => 1
</code></pre>
<p>Set Up:</p>
<ul>
<li>Ubuntu 20.04</li>
<li>PhpStorm 2020.1.4</li>
<li>Docker 19.03.12</li>
<li>docker-compose 1.26.0</li>
</ul> | 63,117,292 | 4 | 5 | null | 2020-07-27 07:20:46.623 UTC | 1 | 2022-07-07 20:36:09.057 UTC | 2020-07-27 13:41:17.68 UTC | null | 1,361,124 | null | 1,361,124 | null | 1 | 32 | php|docker|phpunit|phpstorm|xdebug | 18,417 | <p>Your Xdebug settings look fine to me. It shows expected values for PHPUnit and it works for a web page debug.</p>
<p>This has to be the IDE settings / some IDE misconfiguration. In particular, <strong>make sure that you have selected the default PHP Interpreter.</strong> Even though you have specified one in your Run/Debug Configuration, PhpStorm still requires a project-default interpreter to be selected -- it's a know limitation: <a href="https://youtrack.jetbrains.com/issue/WI-51570" rel="noreferrer">WI-51570</a>.</p>
<p><code>Settings/Preferences | Languages & Frameworks | PHP | CLI Interpreter</code></p>
<p><a href="https://i.stack.imgur.com/zY6Wc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zY6Wc.png" alt="enter image description here" /></a></p>
<p><strong>NOTE:</strong> as of <strong>2021.1</strong> version the PHP settings node has been moved to the top level and now it's <code>Settings/Preferences | PHP | CLI Interpreter</code></p>
<p><a href="https://i.stack.imgur.com/ZSwbi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZSwbi.png" alt="enter image description here" /></a></p>
<p><strong>P.S.</strong> You can also set it via <code>File | New Projects Settings | Settings for New Projects...</code>. This way it will be set for all <strong>future new projects</strong> created on that computer (which you can then change as required on per project basis).</p> |
9,683,516 | How do I get swipe-to-delete working when tableView's allowsMultipleSelectionDuringEditing property is YES? | <p>In iOS 5, if I set <code>allowsMultipleSelectionDuringEditing</code> to YES on a UITableView then swipe-to-delete no longer works. The built-in Mail app supports both swipe-to-delete and multiple selections in edit mode, and I'd like to do likewise. How do I achieve this?</p> | 9,683,541 | 1 | 0 | null | 2012-03-13 11:55:20.007 UTC | 9 | 2013-07-08 10:44:19.38 UTC | 2012-10-10 22:38:38.19 UTC | null | 263,871 | null | 263,871 | null | 1 | 27 | ios|uitableview | 3,149 | <p>The trick is to set <code>allowsMultipleSelectionDuringEditing</code> to YES on entering edit mode and set it back to NO on exiting edit mode. This way, both swipe-to-delete and multiple selections in edit mode work.</p>
<p>If you've subclassed <code>UITableViewController</code> (which you probably have), then you can simply do this:</p>
<pre><code>- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
// Set allowsMultipleSelectionDuringEditing to YES only while
// editing. This gives us the golden combination of swipe-to-delete
// while out of edit mode and multiple selections while in it.
self.tableView.allowsMultipleSelectionDuringEditing = editing;
[super setEditing:editing animated:animated];
}
</code></pre> |
9,884,033 | Ruby on Rails: Switch from test_unit to rspec | <p>I'm going through a tutorial that has suggested using <code>rspec</code>, but I have already gone through a lot of default rails installation. I really don't want to have to redo the installation at all. Anyway, when I run</p>
<pre><code>$ rails g integration_test named
</code></pre>
<p>I get</p>
<pre><code> invoke test_unit
create test/integration/named_test.rb
</code></pre>
<p>When I run <code>bundle</code>, various <code>rspec</code> gems are listed, but <code>test_unit</code> is not. The tutorial seems to have rails invoke <code>rspec</code> instead of <code>test_unit</code> without doing anything additional. How do I get rails to use <code>rspec</code> with the integration test generator command?</p> | 9,884,102 | 9 | 0 | null | 2012-03-27 05:53:27.93 UTC | 24 | 2018-11-09 22:26:25.09 UTC | null | null | null | null | 454,533 | null | 1 | 82 | ruby-on-rails|rspec|gem|testunit | 31,056 | <p>In your <code>config/application.rb</code> file :</p>
<pre><code>config.generators do |g|
g.test_framework :rspec
end
</code></pre>
<p>Now when you run your generators (example <code>rails generate scaffold post</code>), you get rspec test files. Remember to restart your server. For more information on generators see:</p>
<p><a href="http://railscasts.com/episodes/216-generators-in-rails-3" rel="noreferrer">RailsCasts #216 Generators in Rails 3</a></p>
<p>If you really want to use the integration_test generator you'll need to specifically modify the command:</p>
<pre><code>rails g integration_test named --integration-tool=rspec
</code></pre> |
10,007,094 | java.lang.IllegalStateException: The specified child already has a parent | <p>I am using fragments, when I instantiate a fragment the first time it it. but the second time I got this exception. I couldn't find the line where I got the error?</p>
<pre><code> 04-04 08:51:54.320: E/AndroidRuntime(29713): FATAL EXCEPTION: main
04-04 08:51:54.320: E/AndroidRuntime(29713): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.view.ViewGroup.addViewInner(ViewGroup.java:3013)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.view.ViewGroup.addView(ViewGroup.java:2902)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.view.ViewGroup.addView(ViewGroup.java:2859)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.view.ViewGroup.addView(ViewGroup.java:2839)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.support.v4.app.NoSaveStateFrameLayout.wrap(Unknown Source)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.support.v4.app.FragmentManagerImpl.moveToState(Unknown Source)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.support.v4.app.FragmentManagerImpl.moveToState(Unknown Source)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.support.v4.app.BackStackRecord.run(Unknown Source)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.support.v4.app.FragmentManagerImpl.execPendingActions(Unknown Source)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.support.v4.app.FragmentManagerImpl$1.run(Unknown Source)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.os.Handler.handleCallback(Handler.java:587)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.os.Handler.dispatchMessage(Handler.java:92)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.os.Looper.loop(Looper.java:132)
04-04 08:51:54.320: E/AndroidRuntime(29713): at android.app.ActivityThread.main(ActivityThread.java:4126)
04-04 08:51:54.320: E/AndroidRuntime(29713): at java.lang.reflect.Method.invokeNative(Native Method)
04-04 08:51:54.320: E/AndroidRuntime(29713): at java.lang.reflect.Method.invoke(Method.java:491)
04-04 08:51:54.320: E/AndroidRuntime(29713): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
04-04 08:51:54.320: E/AndroidRuntime(29713): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
04-04 08:51:54.320: E/AndroidRuntime(29713): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Here are what i do when i click on an element of my list fragment.</p>
<pre><code>// If we are not currently showing a fragment for the new
// position, we need to create and install a new one.
RouteSearchFragment df = RouteSearchFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.details_full, df);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
</code></pre>
<p>The first time it is Ok, I click element2 from list, it's also ok; but when I return to element1 I got this bug.</p>
<p>Thanks every one!</p> | 10,010,792 | 12 | 4 | null | 2012-04-04 08:00:30.143 UTC | 26 | 2022-03-23 13:51:13.483 UTC | 2016-04-26 14:04:01.423 UTC | null | 5,400,454 | null | 833,219 | null | 1 | 99 | android|android-layout|android-fragments | 110,544 | <p>When you override <code>OnCreateView</code> in your <code>RouteSearchFragment</code> class, do you have the </p>
<pre><code>if(view != null) {
return view;
}
</code></pre>
<p>code segment?</p>
<p>If so, removing the return statement should solve your problem.</p>
<p>You can keep the code and return the view if you don't want to regenerate view data, and onDestroyView() method you remove this view from its parent like so:</p>
<pre><code> @Override
public void onDestroyView() {
super.onDestroyView();
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeAllViews();
}
}
}
</code></pre> |
7,956,865 | Python Subprocess Grep | <p>I am trying to use the grep command in a python script using the subprocess module.</p>
<p>Here's what I have:</p>
<pre><code>userid = 'foo12'
p = subprocess.Popen(['grep', "%s *.log"%userid], stdout=subprocess.PIPE)
</code></pre>
<p>And it returns nothing.
I am not entirely sure what I am doing wrong so can someone please explain. The current method that I am using that works is by adding the shell=true which makes it output the correct output but as the help pages have pointed out it is unsafe. I need help trying to make this work so that my script isn't unsafe. </p> | 7,957,083 | 3 | 0 | null | 2011-10-31 16:52:50.613 UTC | 2 | 2019-05-17 16:26:11.33 UTC | 2019-05-17 16:26:11.33 UTC | null | 5,736,236 | null | 1,248,984 | null | 1 | 14 | python|grep|subprocess|popen | 37,997 | <p>I think you're running up against two problems:</p>
<ol>
<li><p>This call:</p>
<pre><code>p = subprocess.Popen(['grep', "%s *.log"%userid]...
</code></pre>
<p>will not work as expected without <code>shell=True</code> because the list of arguments are being passed directly to <code>os.execvp</code>, which requires each item to be a single string representing an argument. You've squished <em>two separate arguments</em> together into a single string (in other words, grep is interpreting "<code>foo12 *.log</code>" as the <em>pattern</em> to search, and not pattern+file list).</p>
<p>You can fix this by saying:</p>
<pre><code>p = subprocess.Popen(['grep', userid, '*.log']...)
</code></pre></li>
<li><p>The second issue is that, again without <code>shell=True</code>, <code>execvp</code> doesn't know what you mean by <code>*.log</code> and passes it directly along to grep, without going through the shell's wildcard expansion mechanism. If you don't want to use <code>shell=True</code>, you can instead do something like:</p>
<pre><code>import glob
args = ['grep', userid]
args.extend(glob.glob('*.log')
p = subprocess.Popen(args, ...)
</code></pre></li>
</ol> |
11,925,228 | How to pass multiple values of a variable through a URL | <p>I've an application that I'm building, and I'm stuck at a certain point.</p>
<p>I'm trying to pass a variable that has multiple values. So my URL will look like:</p>
<pre><code>localhost/report.php?variable=value1, value2, value3
</code></pre>
<p>Problem is I'm not sure how I can do this. The variables are to be used to retrieve data from a database. I'm using PHP and no Javascript.</p>
<p>Any help would be great!</p>
<p><strong>EDIT:</strong><br />
Here is the HTML I have in my page where the variables are selected:</p>
<pre><code><select name="types" size="19" multiple>
<option value="all" selected>All Types</option>
<option value="book" selected>Books</option>
<option value="cd" selected>CD</option>
</select>
</code></pre>
<p>So a user could select Books and CD, and I would need to pass these two values in the "types" variable.</p> | 11,938,999 | 6 | 6 | null | 2012-08-12 19:31:04.65 UTC | 2 | 2012-08-13 17:07:51.183 UTC | 2012-08-12 19:39:29.403 UTC | null | 395,729 | null | 395,729 | null | 1 | 8 | php|url|urlvariables | 86,620 | <p>As noted at <a href="https://stackoverflow.com/a/2407401/1265817">https://stackoverflow.com/a/2407401/1265817</a>, you can use this method.</p>
<p>If you want PHP to treat $_GET['select2'] as an array of options just add square brackets to the name of the select element like this: <code><select name="select2[]" multiple …</code></p>
<p>Then you can acces the array in your PHP script</p>
<pre><code><?php
header("Content-Type: text/plain");
foreach ($_GET['select2'] as $selectedOption)
echo $selectedOption."\n";
</code></pre> |
12,026,555 | How to do a UNION on a single table? | <p>I need to display the name and surname and address and DOB for all customers who reside in 'Peters' or 'Crows' avenue only.</p>
<p>This is fine I did it like so:</p>
<pre><code>SELECT Customers.FirstName, Customers.Surname,
Customers.CustomerAddress, Customers.DOB
FROM Customers
WHERE
( Customers.CustomerAddress LIKE '%'+ 'Peters' + '%'
or Customers.CustomerAddress LIKE '%'+ 'Crows'+ '%')
</code></pre>
<p>but then I read a bit harder and it said: </p>
<blockquote>
<p>Use a UNION query to produce the results.</p>
</blockquote>
<p>So I read up a bit on <code>UNION</code>s, but mostly I see that the returned values from both <em>SELECT</em> queries <strong>must be of the same length</strong>, and normally examples are using 2 different tables?</p>
<p>So I need to perform a <code>UNION</code> on the same table such the all the customers with the words <em>Peters</em> and <em>Crows</em> in their address are shown. I tried:</p>
<pre><code>SELECT Customers.CustomerAddress
FROM Customers
WHERE
( Customers.CustomerAddress LIKE '%'+ 'Peters' + '%'
or Customers.CustomerAddress LIKE '%'+ 'Crows'+ '%')
UNION
SELECT Customers.FirstName, Customers.Surname,
Customers.CustomerAddress, Customers.DOB
FROM Customers
</code></pre>
<p>But I get the Error:</p>
<blockquote>
<p>All queries combined using a UNION, INTERSECT or EXCEPT operator must
have an equal number of expressions in their target lists.</p>
</blockquote>
<p>which is understandable because my first <em>SELECT</em> only returns 3 results (i.e the results I'm looking for) while the other returns all the addressed (including the ones I need).</p>
<p>So my exact problem is, How do I do I perform a <code>UNION</code> on the same table (Customers total of 10 records) so that all the customers with the words <em>Peters</em> and <em>Crows</em> in their address are shown? (3 of the records match the condition the other 7 dont)</p> | 12,026,615 | 3 | 2 | null | 2012-08-19 12:42:01.937 UTC | 1 | 2020-01-22 20:57:19.383 UTC | 2012-09-23 09:44:55.27 UTC | null | 635,608 | null | 1,133,011 | null | 1 | 12 | sql|sql-server-2008|union | 45,189 | <pre><code> SELECT Customers.FirstName, Customers.Surname, Customers.DOB, Customers.CustomerAddress
FROM Customers
WHERE Customers.CustomerAddress LIKE '%'+ 'Main' + '%'
UNION
SELECT Customers.FirstName, Customers.Surname, Customers.DOB, Customers.CustomerAddress
FROM Customers
WHERE Customers.CustomerAddress LIKE '%'+ 'Gladys'+ '%'
</code></pre>
<p>In a union, the two or more queries should always have the same number of fields in the <code>SELECT</code> statement. The <code>WHERE</code> clause seemed to be the problem in your union query.</p> |
11,622,539 | How do I use tabHost for Android | <p>I have looked at posts on Stack Overflow and at tutorials on other websites, and I cannot understand how to use <code>TabHost</code>. Can someone please explain it to me and maybe send me a link to a tutorial?</p> | 11,627,734 | 2 | 2 | null | 2012-07-24 00:35:55.49 UTC | 15 | 2017-05-13 04:21:34.693 UTC | 2016-12-05 01:46:39.33 UTC | null | 3,681,880 | null | 1,527,377 | null | 1 | 18 | java|android|xml|android-tabhost | 49,274 | <p><img src="https://i.stack.imgur.com/Gg96o.png" alt="Concept TabHost"></p>
<p><img src="https://i.stack.imgur.com/s6QYI.png" alt="enter image description here"></p>
<ol>
<li><p>In ManiActivity extends TabActivity</p>
<pre><code>public class MainActivity extends TabActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
TabHost mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("first").setIndicator("First").setContent(new Intent(this ,FirstActivity.class )));
mTabHost.addTab(mTabHost.newTabSpec("second").setIndicator("Second").setContent(new Intent(this , SecondActivity.class )));
mTabHost.setCurrentTab(0);
}
}
</code></pre></li>
</ol>
<blockquote>
<ul>
<li><p>In this activity not use layout "activity_main.xml" .</p></li>
<li><p>Tabhost mTabHost = getTabHost(); is create main tab.</p></li>
<li><p>mTabHost.newTabSpec("first") is create tabspec id "first".</p></li>
<li><p>setIndicator("First") is create text "First" in title tab.</p></li>
<li><p>setContent(new Intent(this ,FirstActivity.class )) is use content from FirstActivity.class ( FirstActivity.java )</p></li>
<li><p>mTabHost.addTab(....) is add spectab to main tab</p></li>
<li><p>mTabHost.setCurrentTab(0) is defult tab when start page.</p></li>
</ul>
</blockquote>
<p>FirstActivity.java</p>
<pre><code>public class FirstActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.first_layout );
}
}
</code></pre>
<p>SecondActivity.java</p>
<pre><code>public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView( R.layout.second_layout );
}
}
</code></pre>
<blockquote>
<ul>
<li><p>"R.layout.first_layout" is content from first_layout.xml</p></li>
<li><p>"R.layout.second_layout" is content from second_layout.xml</p></li>
</ul>
</blockquote>
<p>In AndroidManifest.xml add activity name ".FirstActivity" and ".SecondActivity" in example xml.</p>
<p><img src="https://i.stack.imgur.com/QMceL.png" alt="enter image description here"></p>
<p>Finish!!!!!</p>
<p><img src="https://i.stack.imgur.com/ksFUS.png" alt="enter image description here"></p> |
20,343,014 | adb doesn't show nexus 5 device | <pre><code>Android Studio 0.3.6
Fedora 18 3.11.7-100.fc18.x86_64
Nexus 5 Kitkat
</code></pre>
<p>Hello,</p>
<p>I have been using my <code>Samsung Galaxy Tab 3 7.0</code> running <code>Android 4.1.2</code> everything works fine with <code>adb</code>.</p>
<p>However, I have just bought a new Nexus 5 device, and when I do the following command <code>adb devices</code> it doesn't show my Nexus 5.</p>
<p>Under <code>Android SDK Manager | Extras | Google USB Driver | status "Not compatiable with Linux"</code></p>
<p>Because I am running <code>Fedora 18</code> if I need drivers what drivers for the USB do I need?</p>
<p>Because the Samsung works fine and I can deploy and run my apps, I think my setup is correct. So I am wondering if there is something wrong with my Nexus 5.</p>
<p>I have tried the following:</p>
<pre><code>adb kill-server
adb start-server
</code></pre>
<p>Setting the Nexus 5 <code>Camera PTP</code> and <code>media device MTP</code> didn't work.</p>
<p>Many thanks for any suggestions,</p> | 21,551,646 | 22 | 5 | null | 2013-12-03 04:40:40.783 UTC | 18 | 2021-08-02 21:49:16.733 UTC | 2013-12-03 16:35:53.127 UTC | null | 136,445 | null | 70,942 | null | 1 | 82 | android|linux|adb | 124,092 | <p>I had a similar problem with my Nexus 4(Android version 4.4.2), it wasn't listed in adb devices.</p>
<p>Make sure USB debugging is enabled from device, and do the following on your PC:</p>
<ol>
<li><p>Update Android SDK (<strong>Google USB Driver</strong>)</p></li>
<li><p>From PC Control Panel, System -> Device manager -> Right click Nexus 4 -> Update driver.</p></li>
<li><p>Set <strong>android-sdk-folder\extras\google\usb_driver</strong> as path to search, include subfolders checked.</p></li>
</ol>
<p>If windows tells you that the driver is up to date, just uninstall the driver (right click on nexu4 -> uninstall driver) and start from step 2 again.</p>
<p>After that, open a cmd and type <strong>adb kill-server</strong> and then a <strong>adb devices</strong>, now it will include your device.</p>
<p><a href="https://developer.android.com/studio/run/oem-usb.html">https://developer.android.com/studio/run/oem-usb.html</a></p> |
3,861,493 | How to pass userInfo in NSNotification? | <p>I am trying to send some data using NSNotification but get stuck. Here is my code:</p>
<pre><code>// Posting Notification
NSDictionary *orientationData;
if(iFromInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
orientationData = [NSDictionary dictionaryWithObject:@"Right"
forKey:@"Orientation"];
}
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:@"Abhinav"
object:nil
userInfo:orientationData];
// Adding observer
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(orientationChanged)
name:@"Abhinav"
object:nil];
</code></pre>
<p>Now how to fetch this userInfo dictionary in my selector <em>orientationChanged</em>?</p> | 3,861,543 | 4 | 0 | null | 2010-10-05 07:07:22.103 UTC | 11 | 2016-04-06 10:11:48.413 UTC | 2010-10-05 07:23:02.843 UTC | null | 24,587 | null | 418,029 | null | 1 | 50 | iphone|cocoa|cocoa-touch | 54,085 | <p>You get an NSNotification object passed to your function. This includes the name, object and user info that you provided to the NSNotificationCenter.</p>
<pre><code>- (void)orientationChanged:(NSNotification *)notification
{
NSDictionary *dict = [notification userInfo];
}
</code></pre> |
3,868,140 | Using a DISTINCT clause to filter data but still pull other fields that are not DISTINCT | <p>I am trying to write a query in Postgresql that pulls a set of ordered data and filters it by a distinct field. I also need to pull several other fields from the same table row, but they need to be left out of the distinct evaluation. example: </p>
<pre><code> SELECT DISTINCT(user_id) user_id,
created_at
FROM creations
ORDER BY created_at
LIMIT 20
</code></pre>
<p>I need the <code>user_id</code> to be <code>DISTINCT</code>, but don't care whether the created_at date is unique or not. Because the created_at date is being included in the evaluation, I am getting duplicate <code>user_id</code> in my result set.</p>
<p>Also, the data must be ordered by the date, so using <code>DISTINCT ON</code> is not an option here. It required that the <code>DISTINCT ON</code> field be the first field in the <code>ORDER BY</code> clause and that does not deliver the results that I seek.</p>
<p>How do I properly use the <code>DISTINCT</code> clause but limit its scope to only one field while still selecting other fields?</p> | 3,868,242 | 5 | 4 | null | 2010-10-05 22:07:14.743 UTC | 3 | 2015-09-04 13:48:39.03 UTC | 2015-09-04 12:58:42.537 UTC | null | 5,053,499 | null | 467,359 | null | 1 | 14 | sql|ruby-on-rails|postgresql|distinct | 39,361 | <p>As you've discovered, standard SQL treats <code>DISTINCT</code> as applying to the whole select-list, not just one column or a few columns. The reason for this is that it's ambiguous what value to put in the columns you exclude from the <code>DISTINCT</code>. For the same reason, standard SQL doesn't allow you to have ambiguous columns in a query with <code>GROUP BY</code>.</p>
<p>But PostgreSQL has a nonstandard extension to SQL to allow for what you're asking: <code>DISTINCT ON (expr)</code>.</p>
<pre><code>SELECT DISTINCT ON (user_id) user_id, created_at
FROM creations
ORDER BY user_id, created_at
LIMIT 20
</code></pre>
<p>You have to include the distinct expression(s) as the leftmost part of your ORDER BY clause.</p>
<p>See the manual on <a href="http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-DISTINCT" rel="noreferrer">DISTINCT Clause</a> for more information.</p> |
3,222,856 | DataGridTextColumn.IsReadOnly seems to be faulty | <p>If I create a binding to the <code>IsReadOnly</code> property of the <code>DataGridTextColumn</code>, it does not actualize. If I set it through markup, it works.</p>
<pre class="lang-xml prettyprint-override"><code><DataGridTextColumn IsReadOnly="{Binding IsReferenceInactive}"/> <!-- NOP -->
<DataGridTextColumn IsReadOnly="True"/> <!-- Works as expected, cell is r/o -->
</code></pre>
<p>The <code>IsReferenceInactive</code> property is a DP and works fine (For testing purposes I've bound it to a checkbox, that worked)</p>
<p>Is this a known limitation?</p>
<p><strong>Update</strong></p>
<p>Uups, other than I wrote, there is a message in the output window:</p>
<blockquote>
<p>System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=IsReferenceInactive; DataItem=null; target element is 'DataGridTextColumn' (HashCode=23836176); target property is 'IsReadOnly' (type 'Boolean')</p>
</blockquote> | 18,657,986 | 6 | 1 | null | 2010-07-11 11:22:51.543 UTC | 5 | 2022-06-03 13:41:43.923 UTC | 2022-06-03 13:41:43.923 UTC | null | 340,628 | null | 340,628 | null | 1 | 29 | .net|wpf|datagrid | 13,628 | <p>Same as codekaizen but simpler:</p>
<pre><code><DataGridTextColumn>
<DataGridTextColumn.CellStyle>
<Style>
<Setter Property="UIElement.IsEnabled" Value="{Binding IsEditable}" />
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
</code></pre> |
3,386,889 | Difference between creating new object and dependency injection | <p>What is the difference between creating a new object and dependency injection? Please explain in detail.</p> | 3,386,918 | 6 | 0 | null | 2010-08-02 10:31:40.18 UTC | 15 | 2020-04-12 12:33:13.627 UTC | 2010-08-02 10:33:44.81 UTC | null | 57,095 | null | 381,737 | null | 1 | 29 | java|object|dependency-injection | 35,235 | <p>Well,
creating a new object is as explicit as it can get - you create a new instance of the desired class.</p>
<p>Dependency injections is a mechanism that provides you with references where you need them.
Imagine a class that represents a connection pool to your database - you usually only have one instance of that class. Now you need to distribute that reference to all the classes that use it.
Here is where Dependency Injection comes in handy - by using a DI framework such as Spring you can define that the one instance of your pool will be injected into the classes that need it.</p>
<p>Your question itself is not easy to answer since the creation of an object and dependency injection can't be compared that easily...</p> |
3,763,846 | What is an in-place constructor in C++? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/222557/cs-placement-new">C++'s “placement new”</a> </p>
</blockquote>
<p>What is an in-place constructor in C++?</p>
<p>e.g. <code>Datatype *x = new(y) Datatype();</code></p> | 3,763,887 | 6 | 1 | null | 2010-09-21 19:44:05.933 UTC | 9 | 2020-06-15 22:40:48.503 UTC | 2020-06-15 22:40:48.503 UTC | null | 1,783,163 | null | 249,560 | null | 1 | 30 | c++|constructor|placement-new|in-place | 43,428 | <p>This is called the placement new operator. It allows you to supply the memory the data will be allocated in without having the <code>new</code> operator allocate it. For example:</p>
<pre><code>Foo * f = new Foo();
</code></pre>
<p>The above will allocate memory for you.</p>
<pre><code>void * fm = malloc(sizeof(Foo));
Foo *f = new (fm) Foo();
</code></pre>
<p>The above will use the memory allocated by the call to <code>malloc</code>. <code>new</code> will not allocate any more. You are not, however, limited to classes. You can use a placement new operator for any type you would allocate with a call to <code>new</code>.</p>
<p>A 'gotcha' for placement new is that you <strong>should not</strong> release the memory allocated by a call to the placement new operator using the <code>delete</code> keyword. You will destroy the object by calling the destructor directly.</p>
<pre><code>f->~Foo();
</code></pre>
<p>After the destructor is manually called, the memory can then be freed as expected.</p>
<pre><code>free(fm);
</code></pre> |
Subsets and Splits