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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6,151,036 | Console app arguments, how arguments are passed to Main method | <p>This would be question from c# beginner.
When I create console application I get Main method with parameter <strong>args</strong> as array string.
I do not understand how this method is called by system and how args are passed to the Main method. Maybe someone could explain? Is Main method are overridden of some kind of console class?</p>
<pre><code>namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
}
}
}
</code></pre> | 6,151,148 | 10 | 1 | null | 2011-05-27 10:35:58.583 UTC | 15 | 2019-08-29 19:45:57.727 UTC | 2012-01-26 10:35:59.82 UTC | null | 41,956 | null | 281,014 | null | 1 | 59 | c#|.net|command-line-arguments | 162,332 | <p>The Main method is the Entry point of your application. If you checkout via <code>ildasm</code> then </p>
<pre><code>.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
</code></pre>
<p>This is what helps in calling the method</p>
<p>The arguments are passed as say <code>C:\AppName arg1 arg2 arg3</code></p> |
6,210,757 | java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener | <p>I included these in the <em>Build Path</em>:</p>
<ul>
<li>all Spring libs</li>
<li>Apache Tomcat 7.0 library</li>
</ul>
<p>The project still fails during startup:</p>
<pre><code>SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4660)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Jun 2, 2011 11:07:38 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.request.RequestContextListener
java.lang.ClassNotFoundException: org.springframework.web.context.request.RequestContextListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4660)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Jun 2, 2011 11:07:38 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class com.sun.faces.config.ConfigureListener
java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:415)
at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:397)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:118)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4660)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
</code></pre>
<p>In <code>org.sprintframework.web-3.1.0.M1.jar</code>, I can see the <code>org.springframework.web.context.ContextLoaderListener</code>.</p>
<p>Someone on Google says that <code>spring.jar</code> should be included but I don't see any <code>spring.jar</code> in 3.x distribution.</p>
<p>Eclipse 3.6.2<br>
Tomcat 7</p>
<p>Edit: Someone on the Spring Forum (offline) said "Automatically update dependencies" should be checked in Project Properties but I don't see anything like that in project properties.</p> | 8,128,255 | 34 | 3 | null | 2011-06-02 05:23:33.94 UTC | 137 | 2022-08-02 16:37:12.17 UTC | 2020-04-27 08:59:39.64 UTC | null | 344,480 | null | 238,190 | null | 1 | 308 | spring|tomcat7|classnotfoundexception | 654,822 | <p>I had a similar problem when running a spring web application in an Eclipse managed tomcat. I solved this problem by adding maven dependencies in the project's web deployment assembly. </p>
<ol>
<li>Open the project's properties (e.g., right-click on the project's name in the project explorer and select "Properties").</li>
<li>Select "Deployment Assembly".</li>
<li>Click the "Add..." button on the right margin.</li>
<li>Select "Java Build Path Entries" from the menu of Directive Type and click "Next".</li>
<li>Select "Maven Dependencies" from the Java Build Path Entries menu and click "Finish".</li>
</ol>
<p>You should see "Maven Dependencies" added to the Web Deployment Assembly definition.</p> |
39,176,248 | React.js - Can't read property of undefined | <p>I'm making very simple react app. Yet as I try to invoke method of parent (actually grandparent) component via onChange event, I keep getting <code>Uncaught TypeError: Cannot read property 'props' of undefined</code>.</p>
<p>Here is the component/form that is triggering the event (thus invoking method on binded parent component... Yes I used .bound(this) on the method as I passed it down from parent component via props.).</p>
<pre><code>class MonthsTable extends Component {
handleChangeOnMonth(e){
this.props.setMonth(e.target.id, e.target.value); // here the method is not found, causing error.
}
render(){
console.log(this.props.setMonth) // here the method is present alright
return (<form>
{this.props.months.map((e, i) =>
<input
type='number'
id={i}
key={i} // yes I know, bad habit, but in this case it doesn't matter
value={this.props.months[i]}
onChange={this.handleChangeOnMonth} />)}
</form>)
}
}
</code></pre>
<p>Here is how I pass the method as props from most parent (grandparent) component.</p>
<pre><code><Months setMonth={this.setMonth.bind(this)} />
</code></pre>
<p>Here is how I pass the method as props in the parent (the component that is between method owner and method invoker)</p>
<pre><code><MonthsTable setMonth={this.props.setMonth} />
</code></pre>
<p>And finally passed to component (MonthsTable) that you saw first. Wheter it is relevant or not, final (most child) components is displayed depending of if statement which works just fine (Might somehow be relevant, I don't know).</p>
<p>Question is... Why is the (setMonth) method 'invisible' inside of (handleChangeOnMonth) method.</p> | 39,176,279 | 3 | 1 | null | 2016-08-27 00:14:01.533 UTC | 4 | 2022-07-14 14:34:11.37 UTC | 2022-07-14 14:34:11.37 UTC | null | 8,565,438 | null | 6,416,743 | null | 1 | 46 | javascript|reactjs | 108,914 | <p>The actual problem here is that the <code>this</code> context is not defined in your <code>handleChangeOnMonth</code> function. This is caused because of the way that javascript handles the contexts of functions, basically when calling functions if you are not calling them directly from the object, and they are not bound they will not have a defined context, and since you are passing the function as a parameter to the input component, it loses the context.</p>
<p>The simplest way to fix this is to bind the function, I suggest that you bind the function in the constructor, like so:</p>
<pre><code>class MonthsTable extends Component {
constructor(props, context){
super(props, context);
this.handleChangeOnMonth = this.handleChangeOnMonth.bind(this);
}
handleChangeOnMonth(e){
this.props.setMonth(e.target.id, e.target.value);
}
render(){
return (<form>
{this.props.months.map((e, i) =>
<input
type='number'
id={i}
key={i}
value={this.props.months[i]}
onChange={this.handleChangeOnMonth} />)}
</form>)
}
}
</code></pre>
<p>alternatively if you are using decorators you could use the <code>core-decorators</code> package to do this in a more elegant way:</p>
<pre><code>import {autobind} from "core-decorators"
@autobind
class MonthsTable extends Component {
handleChangeOnMonth(e){
this.props.setMonth(e.target.id, e.target.value);
}
render(){
return (<form>
{this.props.months.map((e, i) =>
<input
type='number'
id={i}
key={i}
value={this.props.months[i]}
onChange={this.handleChangeOnMonth} />)}
</form>)
}
}
</code></pre> |
24,525,595 | This Android SDK requires Android Developer Toolkit version 23.0.0 or above | <p>I get the following error when I start my Eclipse.</p>
<p><img src="https://i.stack.imgur.com/atObk.png" alt="enter image description here"></p>
<p>And when I try to update from Help > Install New Software...
using the eclipse update link <a href="https://dl-ssl.google.com/eclipse/plugin/4.2" rel="noreferrer">https://dl-ssl.google.com/eclipse/plugin/4.2</a></p>
<p>It gives me following error:</p>
<pre><code>Cannot complete the install because of a conflicting dependency.
Software being installed: Android Development Tools 23.0.1.1256982 (com.android.ide.eclipse.adt.feature.feature.group 23.0.1.1256982)
Software currently installed: Android Development Tools 22.6.3.v201404151837-1123206 (com.android.ide.eclipse.adt.feature.group 22.6.3.v201404151837-1123206)
Only one of the following can be installed at once:
ADT XML Overlay 23.0.1.1256982 (overlay.com.android.ide.eclipse.adt.overlay 23.0.1.1256982)
ADT XML Overlay 22.6.3.v201404151837-1123206 (overlay.com.android.ide.eclipse.adt.overlay 22.6.3.v201404151837-1123206)
Cannot satisfy dependency:
From: Android Development Tools 23.0.1.1256982 (com.android.ide.eclipse.adt.feature.feature.group 23.0.1.1256982)
To: overlay.com.android.ide.eclipse.adt.overlay [23.0.1.1256982]
Cannot satisfy dependency:
From: Android Development Tools 22.6.3.v201404151837-1123206 (com.android.ide.eclipse.adt.feature.group 22.6.3.v201404151837-1123206)
To: overlay.com.android.ide.eclipse.adt.overlay [22.6.3.v201404151837-1123206]
</code></pre>
<p>What should I do now?</p> | 24,630,421 | 10 | 2 | null | 2014-07-02 07:44:44.763 UTC | 9 | 2016-03-01 09:30:45.357 UTC | 2014-07-02 07:50:59.677 UTC | null | 3,683,245 | null | 3,683,245 | null | 1 | 59 | android|eclipse|adt | 50,254 | <p>The best solution to this is to download a new ADT from <a href="http://developer.android.com/sdk/index.html">http://developer.android.com/sdk/index.html</a></p> |
21,909,706 | Laravel previous and next records | <p>I am trying to create a page where I can see all the people in my database and create edits on them. I made a form where I fill in the data from the database of certain fields. </p>
<p>I would like to navigate trough them by a Next and Previous button. </p>
<p>For generating the next step I have to take the ID larger than the current one to load the next profile. </p>
<p>For generating the previous step I have to take the ID smaller than the current one to load the previous profile.</p>
<p>My route:</p>
<pre><code>Route::get('users/{id}','UserController@show');
</code></pre>
<p><strong>Controller:</strong></p>
<pre><code>public function show($id)
{
$input = User::find($id);
// If a user clicks next this one should be executed.
$input = User::where('id', '>', $id)->firstOrFail();
echo '<pre>';
dd($input);
echo '</pre>';
return View::make('hello')->with('input', $input);
}
</code></pre>
<p><strong>View:</strong>
The buttons: </p>
<pre><code><a href="{{ URL::to( 'users/' . $input->id ) }}">Next</a>
</code></pre>
<p>What is the best approach to get the current ID and increment it? </p> | 21,911,647 | 12 | 1 | null | 2014-02-20 13:46:23.767 UTC | 19 | 2021-09-10 07:50:15.103 UTC | null | null | null | null | 1,063,823 | null | 1 | 46 | php|laravel|routing|laravel-4 | 66,757 | <p>Below are your updated controller and view files derived from @ridecar2 link, </p>
<p><strong>Controller:</strong></p>
<pre><code>public function show($id)
{
// get the current user
$user = User::find($id);
// get previous user id
$previous = User::where('id', '<', $user->id)->max('id');
// get next user id
$next = User::where('id', '>', $user->id)->min('id');
return View::make('users.show')->with('previous', $previous)->with('next', $next);
}
</code></pre>
<p><strong>View:</strong></p>
<pre><code><a href="{{ URL::to( 'users/' . $previous ) }}">Previous</a>
<a href="{{ URL::to( 'users/' . $next ) }}">Next</a>
</code></pre> |
21,873,829 | How to fix ambiguous type on method reference (toString of an Integer)? | <p>When doing this</p>
<pre><code>Stream.of(1, 32, 12, 15, 23).map(Integer::toString);
</code></pre>
<p>I get an ambiguous type error. Understandably, the compiler can't tell if I mean <code>toString(int)</code> or <code>toString()</code> from <code>Integer</code>.</p>
<p>When not using a method reference, I might have gotten out of this with an explicit cast or write out the generics long hand, <strong>but how can I let the compiler know what I mean here</strong>? What syntax (if any) can I use to make in unambiguous? </p> | 21,876,077 | 3 | 2 | null | 2014-02-19 07:28:57.257 UTC | 2 | 2017-04-11 13:46:01.437 UTC | 2017-04-11 13:46:01.437 UTC | null | 452,775 | null | 233,266 | null | 1 | 42 | java|java-8 | 11,031 | <p>There is no way to make method references unambiguous; simply said, method references are a feature that is just supported for unambiguous method references only. So you have two solutions:</p>
<ol>
<li><p>use a lambda expression:</p>
<pre><code>Stream.of(1, 32, 12, 15, 23).map(i->Integer.toString(i));
</code></pre></li>
<li><p>(preferred, at least by me) Use a stream of primitive <code>int</code> values when the source consists of primitive <code>int</code> values only:</p>
<pre><code>IntStream.of(1, 32, 12, 15, 23).mapToObj(Integer::toString);
</code></pre>
<p>This will use the static <code>Integer.toString(int)</code> method for consuming the <code>int</code> values.</p></li>
</ol> |
42,294,304 | Minikube install in Ubuntu vm_VT-X/AMD-v enabling to VM inside another VM | <p>I'm tring to install minikube in Ubuntu vm (in virtual box). I have enabled VT-X/AMD-v for the vm. But i'm getting following error.</p>
<pre><code># minikube start
Starting local Kubernetes cluster...
E0217 15:00:35.395801 3869 start.go:107] Error starting host: Error creating host: Error with pre-create check: "This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory".
Retrying.
E0217 15:00:35.396019 3869 start.go:113] Error starting host: Error creating host: Error with pre-create check: "This computer doesn't have VT-X/AMD-v enabled. Enabling it in the BIOS is mandatory"
================================================================================
An error has occurred. Would you like to opt in to sending anonymized crash
information to minikube to help prevent future errors?
To opt out of these messages, run the command:
minikube config set WantReportErrorPrompt false
================================================================================
Please enter your response [Y/n]:
</code></pre>
<p>I found a <a href="https://github.com/docker/machine/issues/2256" rel="noreferrer">reference</a>, according to that, we can not have virtualization inside virtualization. Is it true? How can i fix this?</p> | 43,285,922 | 7 | 2 | null | 2017-02-17 09:35:34.247 UTC | 5 | 2020-08-05 08:10:35.54 UTC | null | null | null | null | 3,001,352 | null | 1 | 28 | ubuntu|kubernetes|minikube | 28,538 | <p><strong>Virtual Box does not support VT-X/AMD-v in nested virtualisation</strong>. See this open <a href="https://www.virtualbox.org/ticket/4032" rel="noreferrer">ticket/feature request</a> on virtualbox.org. </p>
<p>There are also some more questions and answers here on SO discussing <a href="https://stackoverflow.com/questions/21861794/enable-kvm-on-ubuntu-running-on-virtualbox-on-windows/21897478#21897478">this</a> <a href="https://stackoverflow.com/questions/24620599/error-vt-x-not-available-for-vagrant-machine-inside-virtualbox/26475597#26475597">topic</a>. </p>
<p>Possible solutions:</p>
<ol>
<li>As already mentioned: <strong>Use a different hypervisor</strong> that does support VT-X/AMD-v in nested virtualisation (like Xen, KVM or VMware). </li>
<li><strong>Install Minikube on the host OS</strong> and not in a VM.</li>
<li><strong>Run Minikube directly using Docker and the "none" driver option</strong> as described in <a href="https://stackoverflow.com/a/52635546/5730444">Tad Guskis answer</a>. </li>
</ol> |
9,094,276 | Catchable fatal error: Object of class stdClass could not be converted to string in..when tried to insert into database | <p>I have found similar queries like mine in stackoverflow,but found no solutions . So I am asking it again. I have the following <code>insert</code> query :</p>
<pre><code>$purchase_date = date("Y-m-d");
$init = substr($info[fname], 0, 2);
$odr = rand(0,255);
$invoice_number = $this->get_invoice_number();
//$invoice_number = $invoice_number+1;
//$invoice_number = 400 + rand(0,100);
$order_number = $init.'-'.$odr;
$session_id = session_id();
$sql = "
INSERT INTO
tbl_checkout
SET
fname = '$info[fname]',
lname = '$info[lname]',
email = '$info[email]',
phone = '$info[phone]',
address = '$info[address]',
pin = '$info[pin]',
session_id = '$session_id',
purchase_date = '$purchase_date',
invoice_number = '$invoice_number',
order_number = '$order_number' <----This is line no 1038
";
$this->db->insertQuery($sql);
</code></pre>
<p>But when I tried to execute it, it shows error like <code>Catchable fatal error: Object of class stdClass could not be converted to string in c:\.....on line 1038</code></p>
<p>I am lost because I can't even understand what the error means ! Please help.</p> | 9,094,319 | 2 | 0 | null | 2012-02-01 10:29:03.853 UTC | null | 2019-09-06 06:01:24.257 UTC | null | null | null | null | 878,357 | null | 1 | 5 | php|mysql|fatal-error | 40,564 | <p><code>$this->get_invoice_number()</code> is probably returning an object.</p>
<p>you can cast it to a string:</p>
<pre><code>$invoice_number = (string) $this->get_invoice_number();
</code></pre> |
9,046,028 | Paypal - Return url page and variables | <p>Is it possible for me to get paypal post variables in return url. I want to show a response message in return url page depending on whether the user's transaction was completed/pending/failed one. I am testing with paypal sandbox account.</p>
<p>Here is my code,</p>
<pre><code><input type="hidden" name="item_name" value="Credit Purchase">
<input type="hidden" name="business" value="<?php echo paypal_business_id;?>">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="currency_code" id="currency_code" value="GBP">
<input type="hidden" name="custom" id="custom" value="<?php echo $user."@@@".$num_purchase;?>">
<input type="hidden" name="return" value="<?php echo base_url(); ?>buy/success">
<input type="hidden" name="cancel_return" value="<?php echo base_url(); ?>">
<input type="hidden" name="notify_url" value="<?php echo base_url(); ?>buy/notify
</code></pre> | 9,047,619 | 3 | 0 | null | 2012-01-28 14:36:16.773 UTC | null | 2015-03-31 18:55:56.683 UTC | null | null | null | user867241 | null | null | 1 | 12 | paypal|return|sandbox | 48,008 | <p>Its possible to add on <code>return</code> variable, the order id, then you get your order id when the user return and from the order id you show him the informations.</p>
<p>Eg </p>
<pre><code><input type="hidden" name="return" value="myReturnUrl.php?OrderID=88273882717A72734">
</code></pre> |
9,292,940 | how to remove comma if string having comma at end | <p>I want to remove comma at end if string ends with comma</p>
<p>For example </p>
<blockquote>
<p>String names = "A,B,C,"</p>
</blockquote>
<p>i need to remove last comma if string ends with ","</p> | 9,293,022 | 6 | 0 | null | 2012-02-15 11:58:33.68 UTC | 4 | 2019-04-30 09:50:05.013 UTC | 2012-02-15 12:04:02.753 UTC | null | 987,244 | null | 1,071,753 | null | 1 | 28 | java|string | 93,976 | <p>You could try a regular expression:</p>
<pre><code>names = names.replaceAll(",$", "");
</code></pre>
<p>Or a simple substring:</p>
<pre><code>if (names.endsWith(",")) {
names = names.substring(0, names.length() - 1);
}
</code></pre> |
29,973,357 | How do you format code in Visual Studio Code (VSCode)? | <p>What is the equivalent of <kbd>Ctrl</kbd> + <kbd>K</kbd> + <kbd>F</kbd> and <kbd>Ctrl</kbd> + <kbd>K</kbd> + <kbd>D</kbd> on Windows in Visual Studio for formatting, or "beautifying" code in the Visual Studio Code editor?</p> | 29,973,358 | 29 | 3 | null | 2015-04-30 16:43:35.85 UTC | 699 | 2022-05-04 12:55:33.727 UTC | 2021-05-01 20:19:45.303 UTC | null | 3,002,139 | null | 1,730,061 | null | 1 | 988 | code-formatting|visual-studio-code | 3,495,930 | <p>The code formatting is available in Visual Studio Code through the following shortcuts:</p>
<ul>
<li>On Windows <kbd>Shift</kbd> + <kbd>Alt</kbd> + <kbd>F</kbd></li>
<li>On Mac <kbd>Shift</kbd> + <kbd>Option</kbd> + <kbd>F</kbd></li>
<li>On Linux <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>I</kbd></li>
</ul>
<p>Alternatively, you can find the shortcut, as well as other shortcuts, through the 'Command Palette' provided in the editor with <kbd>Ctrl</kbd> +<kbd>Shift</kbd>+ <kbd>P</kbd> (or <kbd>Command</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> on Mac), and then searching for <em><strong>format document</strong>.</em></p>
<h1>For unsaved snippets</h1>
<ol>
<li><p>Open command palette (Win: <kbd>F1</kbd> or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>P</kbd>)</p>
</li>
<li><p>Find "Change Language Mode"</p>
</li>
<li><p>Select language e.g. <code>json</code>. By now syntax should be highlighted.</p>
</li>
<li><p>Format document (e.g. Open Command Palette -> "<em>Format Document</em>")</p>
</li>
</ol>
<h1>Unformat</h1>
<ol>
<li>Select text</li>
<li>Command Palette -> Join Lines</li>
</ol>
<h1>'<em>Show the pics</em>'</h1>
<p><a href="https://i.stack.imgur.com/wPRmb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wPRmb.png" alt="enter image description here" /></a>
<a href="https://i.stack.imgur.com/uirnx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uirnx.png" alt="enter image description here" /></a></p> |
34,376,441 | "If not" condition statement in python | <pre><code>if not start:
new.next = None
return new
</code></pre>
<p>what does "if not" mean?
when will this code execute?</p>
<p>is it the same thing as saying
if start == None: then do something?</p> | 34,376,465 | 2 | 2 | null | 2015-12-19 23:22:25.17 UTC | 5 | 2015-12-19 23:31:24.593 UTC | 2015-12-19 23:24:37.483 UTC | null | 837,534 | null | 5,634,777 | null | 1 | 11 | python|if-statement|conditional | 92,281 | <p><code>if</code> is the statement. <code>not start</code> is the expression, with <code>not</code> being a <a href="https://docs.python.org/2/reference/expressions.html#boolean-operations" rel="noreferrer"><em>boolean operator</em></a>.</p>
<p><code>not</code> returns <code>True</code> if the operand (<code>start</code> here) is considered <em>false</em>. Python considers all objects to be true, unless they are numeric zero, or an empty container, or the <code>None</code> object or the boolean <code>False</code> value. <code>not</code> returns <code>False</code> if <code>start</code> is a true value. See the <a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="noreferrer"><em>Truth Value Testing</em> section</a> in the documentation.</p>
<p>So if <code>start</code> is <code>None</code>, then indeed <code>not start</code> will be true. <code>start</code> can also be <code>0</code>, or an empty list, string, tuple dictionary, or set. Many custom types can also specify they are equal to numeric 0 or should be considered empty:</p>
<pre><code>>>> not None
True
>>> not ''
True
>>> not {}
True
>>> not []
True
>>> not 0
True
</code></pre>
<p>Note: because <code>None</code> is a singleton (there is only ever one copy of that object in a Python process), you should always test for it using <code>is</code> or <code>is not</code>. If you <em>strictly</em> want to test tat <code>start</code> is <code>None</code>, then use:</p>
<pre><code>if start is None:
</code></pre> |
10,664,244 | Django: How to manage development and production settings? | <p>I have been developing a basic app. Now at the deployment stage it has become clear I have need for both a local settings and production settings.</p>
<p>It would be great to know the following:</p>
<ul>
<li>How best to deal with development and production settings. </li>
<li>How to keep apps such as django-debug-toolbar only in a development environment.</li>
<li>Any other tips and best practices for development and deployment settings.</li>
</ul> | 10,664,412 | 19 | 1 | null | 2012-05-19 10:12:34.153 UTC | 88 | 2022-09-23 16:29:01.02 UTC | 2015-04-21 07:35:03.937 UTC | null | 1,394,760 | null | 1,394,760 | null | 1 | 195 | python|django | 113,302 | <p>The <a href="https://docs.djangoproject.com/en/2.1/topics/settings/#envvar-DJANGO_SETTINGS_MODULE" rel="noreferrer"><code>DJANGO_SETTINGS_MODULE</code> environment variable</a> controls which settings file Django will load. </p>
<p>You therefore create separate configuration files for your respective environments (note that they can of course both <code>import *</code> from a separate, "shared settings" file), and use <code>DJANGO_SETTINGS_MODULE</code> to control which one to use.</p>
<p>Here's how:</p>
<p>As noted in the Django documentation:</p>
<blockquote>
<p>The value of DJANGO_SETTINGS_MODULE should be in Python path syntax, e.g. mysite.settings. Note that the settings module should be on the Python import search path.</p>
</blockquote>
<p>So, let's assume you created <code>myapp/production_settings.py</code> and <code>myapp/test_settings.py</code> in your source repository.</p>
<p>In that case, you'd respectively set <code>DJANGO_SETTINGS_MODULE=myapp.production_settings</code> to use the former and <code>DJANGO_SETTINGS_MODULE=myapp.test_settings</code> to use the latter.</p>
<hr>
<p>From here on out, the problem boils down to setting the <code>DJANGO_SETTINGS_MODULE</code> environment variable. </p>
<h2>Setting <code>DJANGO_SETTINGS_MODULE</code> using a script or a shell</h2>
<p>You can then use a bootstrap script or a process manager to load the correct settings (by setting the environment), or just run it from your shell before starting Django: <code>export DJANGO_SETTINGS_MODULE=myapp.production_settings</code>.</p>
<p>Note that you can run this export at any time from a shell — it does not need to live in your <code>.bashrc</code> or anything.</p>
<h2>Setting <code>DJANGO_SETTINGS_MODULE</code> using a Process Manager</h2>
<p>If you're not fond of writing a bootstrap script that sets the environment (and there are very good reasons to feel that way!), I would recommend using a process manager:</p>
<ul>
<li><a href="http://supervisord.org/" rel="noreferrer">Supervisor</a> lets you pass environment variables to managed processes using a <a href="http://supervisord.org/configuration.html#program-x-section-settings" rel="noreferrer">program's <code>environment</code> configuration key</a>.</li>
<li><a href="https://honcho.readthedocs.org/en/latest/" rel="noreferrer">Honcho</a> (a pure-Python equivalent of Ruby's Foreman) lets you define environment variables in <a href="https://honcho.readthedocs.org/en/latest/using_procfiles.html#environment-files" rel="noreferrer">an "environment" (<code>.env</code>) file</a>.</li>
</ul>
<hr>
<p>Finally, note that you <em>can</em> take advantage of the <code>PYTHONPATH</code> variable to store the settings in a completely different location (e.g. on a production server, storing them in <code>/etc/</code>). This allows for separating configuration from application files. You may or may not want that, it depends on how your app is structured. </p> |
22,715,053 | postgresql - view schema privileges | <p>Is there a query I can run to show currently assigned privileges on a particular schema?</p>
<p>i.e. privileges that were assigned like so:</p>
<pre><code>GRANT USAGE ON SCHEMA dbo TO MyUser
</code></pre>
<p>I have tried</p>
<pre><code>SELECT *
FROM information_schema.usage_privileges;
</code></pre>
<p>but this only returns grants to the built-in PUBLIC role. Instead, I want to see which users have been granted privileges on the various schema.</p>
<p>Note: I'm actually using Amazon Redshift rather than pure PostgreSQL, although I will accept a pure PostgreSQL answer if this is not possible in Amazon Redshift. (Though I suspect it is)</p> | 32,451,565 | 10 | 1 | null | 2014-03-28 14:04:31.067 UTC | 10 | 2021-05-18 07:56:23.383 UTC | null | null | null | null | 2,335,502 | null | 1 | 65 | sql|postgresql|amazon-redshift | 98,104 | <p>in console util psql:</p>
<pre><code>\dn+
</code></pre>
<p>will show you</p>
<pre><code> Name | Owner | Access privileges | Description
</code></pre> |
37,798,967 | Tooltip on click of a button | <p>I'm using <a href="https://clipboardjs.com/" rel="noreferrer">clipboard.js</a> to copy some text from a <code>textarea</code>, and that's working fine, but I want to show a tooltip saying "Copied!" if it was successfully copied like they do in the example given on their website. </p>
<p>Here's an example of it working without showing a tooltip: <a href="https://jsfiddle.net/5j50jnhj/" rel="noreferrer">https://jsfiddle.net/5j50jnhj/</a></p> | 37,799,208 | 7 | 1 | null | 2016-06-13 20:56:33.663 UTC | 4 | 2020-11-14 15:02:30.59 UTC | null | null | null | null | 5,368,737 | null | 1 | 24 | javascript|clipboard.js | 65,504 | <p>Clipboard.js creator here. So Clipboard.js is not opinionated about user feedback which means it doesn't come with a tooltip solution. </p>
<p>But here's an example of how you can integrate it with Bootstrap's Tooltip.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Tooltip
$('button').tooltip({
trigger: 'click',
placement: 'bottom'
});
function setTooltip(message) {
$('button').tooltip('hide')
.attr('data-original-title', message)
.tooltip('show');
}
function hideTooltip() {
setTimeout(function() {
$('button').tooltip('hide');
}, 1000);
}
// Clipboard
var clipboard = new Clipboard('button');
clipboard.on('success', function(e) {
setTooltip('Copied!');
hideTooltip();
});
clipboard.on('error', function(e) {
setTooltip('Failed!');
hideTooltip();
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.10/clipboard.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<button class="btn btn-primary" data-clipboard-text="1">Click me</button></code></pre>
</div>
</div>
</p> |
37,747,467 | SimpleDateFormat with TimeZone | <p>I'm trying to format date from java.util.Date. I need this format: </p>
<p><code>2016-06-10T13:38:13.687+02:00</code>. </p>
<p>How correctly convert this from standard Date format </p>
<p><code>May 04 09:51:52 CDT 2009</code> ? </p>
<pre><code>SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss z", Locale.getDefault());
sdf.format(new Date());
</code></pre>
<p>This code unfortunately return value without <code>+02:00</code>.</p> | 37,747,640 | 6 | 2 | null | 2016-06-10 11:45:38.613 UTC | 5 | 2018-11-30 12:52:49.75 UTC | 2018-11-30 12:52:49.75 UTC | null | 6,378,311 | null | 2,730,507 | null | 1 | 22 | java|android | 86,621 | <p>Just turn your z to upperCase</p>
<pre><code> SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z", Locale.getDefault());
sdf.format(new Date());
</code></pre>
<p>Result: 2016-06-10T13:53:22 +0200</p> |
3,408,076 | Difference in Clojure between use and require | <p>I recently started learning Clojure and I'm having a bit of difficulty wrapping my head around namespaces. As the creator of Clojure said, newcomers often struggle to get the concept right. I don't clearly understand the difference between <code>(use ...)</code> and <code>(require ...)</code>. For example playing around in the REPL if I say <code>(use 'clojure.contrib.str-utils2)</code> I get warnings about functions in clojure.core namespace being replaced by the ones in clojure.contrib.str-utils2, but that doesn't happen when I use <code>(require 'clojure.contrib.str-utils2)</code>. I'm not sure that I will always want to replace what's in clojure.core, so can someone point some best practices for importing external stuff and managing namespaces in Clojure?</p>
<p>Oh and also, when should I use <code>:use</code> and <code>:require</code>? Only inside <code>(ns ....)</code>?</p>
<p>Thanks in advance.</p> | 3,408,182 | 1 | 1 | null | 2010-08-04 17:25:55.847 UTC | 4 | 2010-08-05 17:25:15.817 UTC | null | null | null | null | 190,197 | null | 1 | 29 | clojure|namespaces | 7,233 | <p>The answer lies in the docstrings:</p>
<pre><code>user> (doc use)
-------------------------
clojure.core/use
([& args])
Like 'require, but also refers to each lib's namespace using
clojure.core/refer. Use :use in the ns macro in preference to calling
this directly.
'use accepts additional options in libspecs: :exclude, :only, :rename.
The arguments and semantics for :exclude, :only, and :rename are the same
as those documented for clojure.core/refer.
nil
</code></pre>
<p>And the long one for require:</p>
<pre><code>user> (doc require)
-------------------------
clojure.core/require
([& args])
Loads libs, skipping any that are already loaded. Each argument is
either a libspec that identifies a lib, a prefix list that identifies
multiple libs whose names share a common prefix, or a flag that modifies
how all the identified libs are loaded. Use :require in the ns macro
in preference to calling this directly.
Libs
A 'lib' is a named set of resources in classpath whose contents define a
library of Clojure code. Lib names are symbols and each lib is associated
with a Clojure namespace and a Java package that share its name. A lib's
name also locates its root directory within classpath using Java's
package name to classpath-relative path mapping. All resources in a lib
should be contained in the directory structure under its root directory.
All definitions a lib makes should be in its associated namespace.
'require loads a lib by loading its root resource. The root resource path
is derived from the lib name in the following manner:
Consider a lib named by the symbol 'x.y.z; it has the root directory
<classpath>/x/y/, and its root resource is <classpath>/x/y/z.clj. The root
resource should contain code to create the lib's namespace (usually by using
the ns macro) and load any additional lib resources.
Libspecs
A libspec is a lib name or a vector containing a lib name followed by
options expressed as sequential keywords and arguments.
Recognized options: :as
:as takes a symbol as its argument and makes that symbol an alias to the
lib's namespace in the current namespace.
Prefix Lists
It's common for Clojure code to depend on several libs whose names have
the same prefix. When specifying libs, prefix lists can be used to reduce
repetition. A prefix list contains the shared prefix followed by libspecs
with the shared prefix removed from the lib names. After removing the
prefix, the names that remain must not contain any periods.
Flags
A flag is a keyword.
Recognized flags: :reload, :reload-all, :verbose
:reload forces loading of all the identified libs even if they are
already loaded
:reload-all implies :reload and also forces loading of all libs that the
identified libs directly or indirectly load via require or use
:verbose triggers printing information about each load, alias, and refer
Example:
The following would load the libraries clojure.zip and clojure.set
abbreviated as 's'.
(require '(clojure zip [set :as s]))
nil
</code></pre>
<p>They both do the same thing, but <code>use</code> goes the extra step and creates mappings for the stuff in the require'd namespace in the current namespace. That way, rather than doing <code>some.namespace/name</code> you're just referring to it as <code>name</code>. While this is convenient sometimes, it's better to use require or select the individual vars that you want rather than pull in the entire namespace. Otherwise, you could have issues with shadowing (where one var is preferred over another of the same name).</p>
<p>If you don't want to use require, but you know what vars you want out of the namespace, you can do this:</p>
<pre><code>(ns whatever
(:use [some.namespace :only [vars you want]]))
</code></pre>
<p>If you don't know which vars you're going to need, or if you need a lot, it's better to use require. Even when you require, you don't always have to type the totally qualified name. You can do this:</p>
<pre><code>(ns whatever
(:require [some.namespace :as sn]))
</code></pre>
<p>and then you can use vars from some.namespace like this: <code>(sn/somefunction arg1 arg2)</code></p>
<p>And to answer your last question: try to only use :require and :use inside of (ns ...). It's much cleaner this way. Don't <code>use</code> and <code>require</code> outside of (ns ..) unless you have a pretty good reason for it.</p> |
27,916,055 | What's the meaning of /gi in a regex? | <p>I see an line in my JavaScript code like this:</p>
<pre><code>var regex = /[^\w\s]/gi;
</code></pre>
<p>What's the meaning of this <code>/gi</code> in the regex?</p>
<p>Other part I can understand as it accepts a group of word and spaces, but not <code>/gi</code>.</p> | 27,916,097 | 2 | 1 | null | 2015-01-13 06:23:00.81 UTC | 20 | 2018-05-01 21:05:35.22 UTC | 2017-03-11 02:48:36.183 UTC | null | 63,550 | null | 4,136,389 | null | 1 | 102 | javascript|regex | 139,243 | <pre><code>g modifier: global. All matches (don't return on first match)
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])
</code></pre>
<p>In your case though <code>i</code> is immaterial as you dont capture <code>[a-zA-Z]</code>.</p>
<p>For input like <code>!@#$</code> if <code>g</code> modifier is not there regex will return first match <code>!</code><a href="https://regex101.com/r/sH8aR8/55"><strong>See here</strong></a>.</p>
<p>If <code>g</code> is there it will return the whole or whatever it can match.<a href="https://regex101.com/r/sH8aR8/56"><strong>See here</strong></a></p> |
8,570,705 | Managing mongoid migrations | <p>Can someone give me a short introduction to doing DB migrations in Rails using Mongoid? I'm particularly interested in lazy per document migrations. By this, I mean that whenever you read a document from the database, you migrate it to its latest version and save it again. </p>
<p>Has anyone done this sort of thing before? I've come across <a href="https://github.com/adacosta/mongoid_rails_migrations">mongoid_rails_migrations</a>, but it doesn't provide any sort of documentation, and although it looks like it does this, I'm not really sure how to use it.</p>
<p>I should point out I'm only conceptually familiar with ActiveRecord migrations.</p> | 8,632,666 | 3 | 1 | null | 2011-12-20 04:10:31.27 UTC | 13 | 2015-06-25 18:31:05.033 UTC | null | null | null | null | 104,021 | null | 1 | 25 | ruby-on-rails|mongoid|database-migration|rails-migrations | 9,334 | <p>If you want to do the entire migration at once, then mongoid_rails_migrations will do what you need. There isn't really much to document, it duplicates the functionality of the standard ActiveRecord migration. You write your migrations, and then you use <code>rake db:migrate</code> to apply them and it handles figuring out which ones have and haven't been ran. I can answer further questions if there is something specific you want to know about it.</p>
<p>For lazy migrations, the easiest solution is to use the <a href="http://mongoid.org/docs/callbacks.html" rel="noreferrer" title="after_initialize">after_initialize</a> callback. Check if a field matches the old data scheme, and if it does you modify it the object and update it, so for example:</p>
<pre><code>class Person
include Mongoid::Document
after_initialize :migrate_data
field :name, :type => String
def migrate_data
if !self[:first_name].blank? or !self[:last_name].blank?
self.set(:name, "#{self[:first_name]} #{self[:last_name]}".strip)
self.remove_attribute(:first_name)
self.remove_attribute(:last_name)
end
end
end
</code></pre>
<p>The tradeoffs to keep in mind with the specific approach I gave above:</p>
<p>If you run a request that returns a lot of records, such as <code>Person.all.each {|p| puts p.name}</code> and 100 people have the old format, it will immediately run 100 set queries. You could also call <code>self.name = "#{self.first_name} #{self.last_name}".strip</code> instead, but that means your data will only be migrated if the record is saved.</p>
<p>General issues you might have is that any mass queries such as <code>Person.where(:name => /Foo/).count</code> will fail until all of the data is migrated. Also if you do <code>Person.only(:name).first</code> the migration would fail because you forgot to include the <code>first_name</code> and <code>last_name</code> fields.</p> |
605,644 | Is it possible to work in Eclipse with keyboard only? | <p>as most of us surely do every now and then, I try to improve my workflow. As Eclipse is my main IDE, I wondered if it may be possible to use it without mouse. I browsed the available shortcuts and tried to use them instead of my mouse. I found interesting features like Ctrl+3 which opens something like the Apple spotlight.</p>
<p>I know there are a lot of questions concerning favorite shortcuts etc. but I'd like to know if it works because at the moment it feels a bit squishy 100% without mouse.</p>
<p>So is anyone out there using Eclipse like that? And are there some hints to ease the change?</p> | 605,758 | 4 | 0 | null | 2009-03-03 09:08:53.017 UTC | 9 | 2009-05-05 16:25:02.723 UTC | 2009-03-03 09:12:45.783 UTC | starblue | 49,246 | Dazmogan | 72,448 | null | 1 | 19 | eclipse|workflow|keyboard|accessibility | 3,665 | <p>Yes, it is possible. For a start, check out <a href="http://rayfd.wordpress.com/2007/05/20/10-eclipse-navigation-shortcuts-every-java-programmer-should-know/" rel="noreferrer">10 Eclipse navigation shortcuts every java programmer should know</a>. When you use these 10 shortcuts and some of the shortcuts of the comments, you will already see a big performance boost.</p>
<p>The "open type" and "open resource" dialogs are CamelCase-sensitive, so when typing "NPE" in the open type dialog, I get two matching items NoPermissionException and NullPointerException. So using good names with consistent spelling is a must.</p>
<p>Ctrl+F11 starts a program, F11 debugs it. Note howewer to check if in Window-Preferences-Run/Debug-Launching the value of "Launch Operation" is set to your needs.</p>
<p>You may want to customize the search dialog (Ctrl+h) to only show the file search (default is to context sensitively present you with different search tabs).</p>
<p>Ctrl+n allows you to create something new (opens a wizard with an initial filter text to filter the possible next pages).</p> |
17,553,181 | Laravel 4: how to "order by" using Eloquent ORM | <p>Simple question - how do I order by 'id' descending in Laravel 4.</p>
<p>The relevant part of my controller looks like this:</p>
<pre><code>$posts = $this->post->all()
</code></pre>
<p>As I understand you use this line:</p>
<pre><code>->orderBy('id', 'DESC');
</code></pre>
<p>But how does that fit in with my above code?</p> | 18,289,241 | 3 | 4 | null | 2013-07-09 16:13:47.04 UTC | 35 | 2015-04-22 07:23:36.613 UTC | null | null | null | null | 2,332,251 | null | 1 | 256 | php|laravel|laravel-4|eloquent | 655,980 | <p>If you are using post as a model (without dependency injection), you can also do:</p>
<pre><code>$posts = Post::orderBy('id', 'DESC')->get();
</code></pre> |
22,274,823 | Running django in virtualenv - ImportError: No module named django.core.management? | <p>I have installed Django after activating my virtualenv but still I am getting following error</p>
<pre><code>from django.core.management import execute_from_command_line
ImportError: No module named django.core.management
</code></pre> | 22,276,067 | 8 | 1 | null | 2014-03-08 20:43:01.417 UTC | 6 | 2020-10-19 01:25:41.667 UTC | 2014-03-08 22:59:23.053 UTC | null | 1,288,306 | null | 2,612,542 | null | 1 | 11 | django|virtualenv | 52,277 | <p>If you already activated your virtualenv (<code>source /path/bin/activate</code>) then check if you have installed Django.</p>
<pre><code>pip install django
</code></pre>
<p>With next command you can see if Django was installed.</p>
<pre><code>pip freeze | grep django
</code></pre>
<p>Another thing that you can try is to remove first line (<code>#!/usr/bin/env python</code>) in the <code>manage.py</code> file.</p> |
57,441,654 | SwiftUI Repaint View Components on Device Rotation | <p>How to detect device rotation in SwiftUI and re-draw view components?</p>
<p>I have a @State variable initialized to the value of UIScreen.main.bounds.width when the first appears. But this value doesn't change when the device orientation changes. I need to redraw all components when the user changes the device orientation.</p> | 57,442,517 | 18 | 0 | null | 2019-08-10 11:17:45.497 UTC | 26 | 2022-07-08 11:15:05.29 UTC | null | null | null | null | 11,899,171 | null | 1 | 29 | swiftui | 24,126 | <p>@dfd provided two good options, I am adding a third one, which is the one I use.</p>
<p>In my case I subclass UIHostingController, and in function viewWillTransition, I post a custom notification.</p>
<p>Then, in my environment model I listen for such notification which can be then used in any view.</p>
<pre><code>struct ContentView: View {
@EnvironmentObject var model: Model
var body: some View {
Group {
if model.landscape {
Text("LANDSCAPE")
} else {
Text("PORTRAIT")
}
}
}
}
</code></pre>
<p>In SceneDelegate.swift:</p>
<pre class="lang-swift prettyprint-override"><code>window.rootViewController = MyUIHostingController(rootView: ContentView().environmentObject(Model(isLandscape: windowScene.interfaceOrientation.isLandscape)))
</code></pre>
<p>My UIHostingController subclass:</p>
<pre class="lang-swift prettyprint-override"><code>extension Notification.Name {
static let my_onViewWillTransition = Notification.Name("MainUIHostingController_viewWillTransition")
}
class MyUIHostingController<Content> : UIHostingController<Content> where Content : View {
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
NotificationCenter.default.post(name: .my_onViewWillTransition, object: nil, userInfo: ["size": size])
super.viewWillTransition(to: size, with: coordinator)
}
}
</code></pre>
<p>And my model:</p>
<pre class="lang-swift prettyprint-override"><code>class Model: ObservableObject {
@Published var landscape: Bool = false
init(isLandscape: Bool) {
self.landscape = isLandscape // Initial value
NotificationCenter.default.addObserver(self, selector: #selector(onViewWillTransition(notification:)), name: .my_onViewWillTransition, object: nil)
}
@objc func onViewWillTransition(notification: Notification) {
guard let size = notification.userInfo?["size"] as? CGSize else { return }
landscape = size.width > size.height
}
}
</code></pre> |
49,208,528 | How to run build version using create-react-app? | <p>So, I developed a small React application using create-react-app. (I have always made applications from scratch.)</p>
<p>Then, after I was kind of happy with it, I decided to run <code>npm run build</code> to make an optimized production build. </p>
<p>Can someone please tell me how I can run the production build instead of the Dev build?</p> | 49,209,041 | 6 | 0 | null | 2018-03-10 11:28:07.087 UTC | 11 | 2021-11-18 07:17:24.703 UTC | null | null | null | null | 8,588,359 | null | 1 | 89 | reactjs|build|production|create-react-app | 117,839 | <p>When you run <code>npm run build</code> your console should actually say something like the following</p>
<pre><code>The build folder is ready to be deployed.
You may serve it with a static server:
npm install -g serve
serve -s build
</code></pre>
<p>The build script is building your entire app into the build folder, ready to be statically served. However actually serving it require some kind of static file server, like the the one they propose.</p>
<p>After running the command <code>serve -s build</code> you can access your production build at localhost (on the specified port).</p>
<p>You can of course run whatever static file server you like, I usually use express for this, however <code>serve</code> seems like the easiest option to just serve your statics files with a single command.</p> |
41,117,740 | Tensorflow crashes with CUBLAS_STATUS_ALLOC_FAILED | <p>I'm running tensorflow-gpu on Windows 10 using a simple MINST neural network program. When it tries to run, it encounters a <code>CUBLAS_STATUS_ALLOC_FAILED</code> error. A google search doesn't turn up anything.</p>
<pre><code>I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:885] Found device 0 with properties:
name: GeForce GTX 970
major: 5 minor: 2 memoryClockRate (GHz) 1.253
pciBusID 0000:0f:00.0
Total memory: 4.00GiB
Free memory: 3.31GiB
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:906] DMA: 0
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:916] 0: Y
I c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\core\common_runtime\gpu\gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 970, pci bus id: 0000:0f:00.0)
E c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\cuda\cuda_blas.cc:372] failed to create cublas handle: CUBLAS_STATUS_ALLOC_FAILED
W c:\tf_jenkins\home\workspace\release-win\device\gpu\os\windows\tensorflow\stream_executor\stream.cc:1390] attempting to perform BLAS operation using StreamExecutor without BLAS support
Traceback (most recent call last):
File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1021, in _do_call
return fn(*args)
File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1003, in _run_fn
status, run_metadata)
File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\contextlib.py", line 66, in __exit__
next(self.gen)
File "C:\Users\Anonymous\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\errors_impl.py", line 469, in raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InternalError: Blas SGEMM launch failed : a.shape=(100, 784), b.shape=(784, 256), m=100, n=256, k=784
[[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholder_0/_7, Variable/read)]]
[[Node: Mean/_15 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_35_Mean", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code></pre> | 42,894,528 | 10 | 0 | null | 2016-12-13 09:38:13.74 UTC | 12 | 2022-02-26 04:06:13.62 UTC | 2020-01-02 08:59:22.767 UTC | null | 10,685,378 | null | 211,159 | null | 1 | 51 | tensorflow|windows-10|mnist|cublas | 45,613 | <p>The location of the "allow_growth" property of the session config seems to be different now. It's explained here: <a href="https://www.tensorflow.org/tutorials/using_gpu" rel="noreferrer">https://www.tensorflow.org/tutorials/using_gpu</a></p>
<p>So currently you'd have to set it like this:</p>
<pre><code>import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config, ...)
</code></pre> |
40,809,504 | Idiomatic goroutine termination and error handling | <p>I have a simple concurrency use case in go, and I cannot figure out an elegant solution to my problem.</p>
<p>I want to write a method <code>fetchAll</code> that queries an unspecified number of resources from remote servers in parallel. If any of the fetches fails, I want to return that first error immediately.</p>
<p>My initial implementation leaks goroutines:</p>
<pre class="lang-golang prettyprint-override"><code> package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func fetchAll() error {
wg := sync.WaitGroup{}
errs := make(chan error)
leaks := make(map[int]struct{})
defer fmt.Println("these goroutines leaked:", leaks)
// run all the http requests in parallel
for i := 0; i < 4; i++ {
leaks[i] = struct{}{}
wg.Add(1)
go func(i int) {
defer wg.Done()
defer delete(leaks, i)
// pretend this does an http request and returns an error
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
errs <- fmt.Errorf("goroutine %d's error returned", i)
}(i)
}
// wait until all the fetches are done and close the error
// channel so the loop below terminates
go func() {
wg.Wait()
close(errs)
}()
// return the first error
for err := range errs {
if err != nil {
return err
}
}
return nil
}
func main() {
fmt.Println(fetchAll())
}
</code></pre>
<p>Playground: <a href="https://play.golang.org/p/Be93J514R5" rel="noreferrer">https://play.golang.org/p/Be93J514R5</a></p>
<p>I know from reading <a href="https://blog.golang.org/pipelines" rel="noreferrer">https://blog.golang.org/pipelines</a> that I can create a signal channel to cleanup the other threads. Alternatively, I could probably use <code>context</code> to accomplish it. But it seems like such a simple use case should have a simpler solution that I'm missing.</p> | 55,122,595 | 5 | 0 | null | 2016-11-25 16:51:04.37 UTC | 21 | 2021-06-16 01:57:53.773 UTC | 2021-06-16 01:57:53.773 UTC | null | 5,305,519 | null | 1,839,929 | null | 1 | 43 | go|channel|goroutine | 53,807 | <p>Using <a href="http://golang.org/x/sync/errgroup" rel="noreferrer">Error Group</a> makes this even simpler. This automatically waits for all the supplied Go Routines to complete successfully, or cancels all those remaining in the case of any one routine returning an error (in which case that error is the one bubble back up to the caller).</p>
<pre><code>package main
import (
"context"
"fmt"
"math/rand"
"time"
"golang.org/x/sync/errgroup"
)
func fetchAll(ctx context.Context) error {
errs, ctx := errgroup.WithContext(ctx)
// run all the http requests in parallel
for i := 0; i < 4; i++ {
errs.Go(func() error {
// pretend this does an http request and returns an error
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
return fmt.Errorf("error in go routine, bailing")
})
}
// Wait for completion and return the first error (if any)
return errs.Wait()
}
func main() {
fmt.Println(fetchAll(context.Background()))
}
</code></pre> |
38,206,196 | merge one local branch into another local branch | <p>I have multiple branches which are branched off the master (each in a separate subdirectory).</p>
<ul>
<li>Branch1: new development, not yet completely finished</li>
<li>Branch2: hotfix for a problem, but still under test</li>
<li>Branch3: mess around branch, which I will not restore</li>
</ul>
<p>Before testing of the hotfix is finished I would like to have the code already available in Branch1, so I can continue developing with the fix in place.<br />
(But since my experience with git is not that much I first started to play around with merge in a 3rd branch, especially created to mess around in, before I mess up either Branch1 or Branch2)</p>
<p>In my 3rd branch I first tried the following:</p>
<pre><code>git merge feature/Branch1
</code></pre>
<p>but this gave the following error:</p>
<pre><code>fatal: 'feature/Branch1' does not point to a commit
</code></pre>
<p>I next did a commit -a in my Branch1 and tried again, but it keeps giving the same error.</p>
<p>What am I doing wrong? What should I do to merge the code from - in this case - Branch1 with Branch3?</p> | 38,206,292 | 6 | 0 | null | 2016-07-05 14:35:43.657 UTC | 72 | 2022-08-19 12:53:38.983 UTC | 2018-06-19 22:35:02.27 UTC | null | 6,163,621 | null | 1,750,498 | null | 1 | 337 | git|merge | 608,772 | <p>First, checkout to your Branch3:</p>
<pre><code>git checkout Branch3
</code></pre>
<p>Then merge the Branch1:</p>
<pre><code>git merge Branch1
</code></pre>
<p>And if you want the updated commits of Branch1 on Branch2, you are probaly looking for <a href="https://git-scm.com/book/en/v2/Git-Branching-Rebasing" rel="noreferrer"><code>git rebase</code></a></p>
<pre><code>git checkout Branch2
git rebase Branch1
</code></pre>
<p>This will update your Branch2 with the latest updates of Branch1.</p> |
38,457,669 | docker build with Dockerfile, but the image has no name or tag | <p>I installed <strong>Docker desktop for mac</strong>. The version is <code>1.12.0-rc4-beta19</code></p>
<p>when I use <code>docker build -t self/centos:java8 .</code></p>
<p>the image has no name or tag</p>
<pre><code>REPOSITORY TAG IMAGE ID CREATED SIZE
<none> <none> 1581ffcbfd7f 5 minutes ago 196.8 MB
</code></pre>
<p>What is wrong with the build command?</p> | 38,459,403 | 4 | 0 | null | 2016-07-19 11:47:42.42 UTC | 8 | 2021-10-30 11:46:35.483 UTC | 2019-02-11 07:45:53.97 UTC | null | 8,718,377 | null | 3,368,472 | null | 1 | 58 | docker|docker-build|docker-for-mac|docker-desktop | 52,768 | <p>is your image building correctly? the name does not get set when there is an error in the build. This because every step in the build is a new image created and with an error you won't get to the last step with the correctly named image</p>
<p>btw you can set it manually with the tag command <a href="https://docs.docker.com/engine/reference/commandline/tag/" rel="noreferrer">https://docs.docker.com/engine/reference/commandline/tag/</a></p> |
41,674,712 | Angular 2 iframe to parent communication | <p>in my current project I have multiple Angular 2 applications which should be served by a portal application (also Angular 2). So the portal app has a header area with links to all underlying apps. When the user clicks on one app link, the corresponding angular 2 app gets loaded in an iframe of the portal body. </p>
<p><a href="https://i.stack.imgur.com/MsOdd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MsOdd.png" alt="enter image description here"></a></p>
<p>Now I develop a central authorization service. In the portal I have a service which holds the permissions of the current logged-in user. My question is: Is it possible to access angular 2 services / components of the parent (portal) within the individual apps (iframe)? It seemed to be possbile in angular 1 <a href="http://charemza.name/blog/posts/angularjs/iframe/same-domain-iframe-communication/" rel="noreferrer" title="via scope">via scope</a></p> | 45,617,285 | 2 | 0 | null | 2017-01-16 10:53:54.367 UTC | 11 | 2019-07-22 00:07:27.963 UTC | 2017-01-16 10:56:03.36 UTC | null | 4,927,984 | null | 3,120,361 | null | 1 | 23 | javascript|angular|iframe | 24,871 | <p>I am looking at doing something similar at the moment (a portal application with sub apps in an iFrame)
You can communicate between your server and client (in either direction) by using <strong>window.postMessage</strong> to send data.</p>
<p>So for example on the server app:</p>
<pre><code>var iframe = document.getElementById('useriframe');
if (iframe == null) return;
var iWindow = (<HTMLIFrameElement>iframe).contentWindow;
iWindow.postMessage({"for":"user","data":"anything"}, 'http://localhost:4001');
</code></pre>
<p>and on the client app (hosted within the iFrame)</p>
<pre><code>export class AppComponent {
@HostListener('window:message',['$event'])
onMessage(e)
{
if (e.origin!="http://localhost:4200")
{
return false;
}
if (e.data.for=="user")
{
alert('here i am');
}
}
</code></pre>
<p><strong>Showing child frame routes in the parent</strong>
So, in my implementation we pass tokens and user information from the shell application to the child iFrame, and we pass routing information from the child applications back to the shell so that the url reflects the route selected in the child application.
In a child application you may have a route such as:</p>
<blockquote>
<p>[userapp]/edituser/username</p>
</blockquote>
<p>, and we wish to post it to the parent application and display the route like: </p>
<blockquote>
<p><a href="http://mywebsite/main/application/user#edituser/bob" rel="noreferrer">http://mywebsite/main/application/user#edituser/bob</a></p>
</blockquote>
<p>Note that we use hashtag to mark a child route, and in your child applications you intercept every navigation event and post the new route via</p>
<pre><code>export class MyRoutingComponent implements OnInit {
constructor(private router: Router) {
router.events.subscribe((event: Event)=>{
if (event instanceof NavigationEnd){
let url=(<NavigationEnd>event).url;
if (url.length>1)//don't post message about base route '/'
window.parent.postMessage({"for":"dashboard", "operation":"changeroute","route":url},'*')
}
})
}
</code></pre>
<p>and then in the parent application parse the message and use it to update the location path displayed.</p>
<pre><code> url = url +'#' + route;
this.location.go(url);
</code></pre> |
20,794,398 | How can I have ActiveRecord's pluck also return the column name for rendering in json? | <pre><code>def jsontest
@users = User.all.limit(10)
render json: @users
end
</code></pre>
<p>yields</p>
<pre><code>{
...
"id": 7,
"name": "Sage Smith",
"email": "[email protected]",
"created_at": "2013-10-17T02:29:15.638Z",
"updated_at": "2013-10-17T02:29:15.638Z",
"password_digest": "$2a$10$taHk3udtWN61Il5I18akj.E90AB1TmdL1BkQBKPk/4eZ7YyizGOli",
"remember_token": "118f807d0773873fb5e4cd3b5d98048aef4f6f59",
"admin": false
...
}
</code></pre>
<p>But I would like to omit certain certain fields from this API, so I use <code>pluck</code></p>
<pre><code>def jsontest
@users = User.all.limit(10).pluck(:id, :name, :email, :created_at) ###
render json: @users
end
</code></pre>
<p>but pluck returns an array of only values, when I would like to have each object's attributes accessible by hash key. </p>
<pre><code>[
...
7,
"Sage Smith",
"[email protected]",
"2013-10-17T02:29:15.638Z"
...
]
</code></pre>
<p>So how can I effectively pluck the values and their keys?</p>
<p>I realize I could sweep through @users and grab the keys before plucking and recreate the hash, but I'm expecting there to be some convenience method that does exactly what I want. </p> | 20,794,443 | 7 | 0 | null | 2013-12-27 03:42:24.147 UTC | 6 | 2022-01-29 17:34:40.947 UTC | null | null | null | null | 1,922,780 | null | 1 | 33 | ruby-on-rails|activerecord | 21,076 | <p>Use <code>select</code> instead of <code>pluck</code>:</p>
<pre><code>def jsontest
@users = User.select('id, name, email, created_at').limit(10)
render json: @users
end
</code></pre> |
53,768,260 | CSS pseudo selectors with MUI | <p>I have seen in a lot of the MUI code that they use pseudo selectors in their react styled components. I thought I would try to do it myself and I cannot get it to work. I'm not sure what I am doing wrong or if this is even possible.</p>
<p>I am trying to make some CSS that will offset this element against the fixed header.</p>
<pre><code>import React from 'react';
import { createStyles, WithStyles, withStyles, Typography } from '@material-ui/core';
import { TypographyProps } from '@material-ui/core/Typography';
import GithubSlugger from 'github-slugger';
import Link from './link';
const styles = () =>
createStyles({
h: {
'&::before': {
content: 'some content',
display: 'block',
height: 60,
marginTop: -60
}
}
});
interface Props extends WithStyles<typeof styles>, TypographyProps {
children: string;
}
const AutolinkHeader = ({ classes, children, variant }: Props) => {
// I have to call new slugger here otherwise on a re-render it will append a 1
const slug = new GithubSlugger().slug(children);
return (
<Link to={`#${slug}`}>
<Typography classes={{ root: classes.h }} id={slug} variant={variant} children={children} />
</Link>
);
};
export default withStyles(styles)(AutolinkHeader);
</code></pre> | 53,772,369 | 2 | 0 | null | 2018-12-13 18:44:01.413 UTC | 18 | 2021-11-09 15:04:30.08 UTC | 2021-11-09 15:04:30.08 UTC | null | 9,449,426 | null | 4,400,804 | null | 1 | 86 | reactjs|material-ui|jss | 70,115 | <p>I found out that the content attribute needed to be double quoted like this</p>
<pre><code>const styles = () =>
createStyles({
h: {
'&::before': {
content: '"some content"',
display: 'block',
height: 60,
marginTop: -60
}
}
});
</code></pre>
<p>and then everything worked like expected</p> |
18,866,881 | How to get the list of all database users | <p>I am going to get the list of all users, including Windows users and 'sa', who have access to a particular database in MS SQL Server.
Basically, I would like the list to look like as what is shown in <code>SQL Server Management Studio</code> (i.e. the list that is shown when you expand <code>[databse] -> Security -> Users</code>) with one important exception: I do not want to see the <code>'dbo'</code> in the list. Rather, I would like to see the actual user who owns the database. So, for example, if 'sa' is the <code>'dbo'</code>, <code>'sa'</code> must be included in the list instead of <code>'dbo'</code>. Another note not to be missed is, the list in the <code>SQL Server Management Studio</code> normally shows Windows users in addition to SQL users, And I would like those users to be included as well.</p>
<p>So far, I have been able to come up with the following query:</p>
<pre><code>SELECT * FROM sys.database_principals where (type='S' or type = 'U')
</code></pre>
<p>This query is almost right but the problem is it doesn't satisfy the <code>'dbo'</code> condition. </p>
<p>How can I change this query or should I use another one?</p> | 52,371,316 | 7 | 0 | null | 2013-09-18 08:04:59.66 UTC | 20 | 2022-02-10 10:16:33.18 UTC | 2018-05-02 10:02:38.243 UTC | null | 769,137 | null | 1,646,390 | null | 1 | 87 | sql-server | 555,580 | <p>Whenever you 'see' something in the GUI (SSMS) and you're like "that's what I need", you can always run Sql Profiler to fish for the query that was used.</p>
<p>Run Sql Profiler. Attach it to your database of course.</p>
<p>Then right click in the GUI (in SSMS) and click "Refresh".<br>
And then go see what Profiler "catches".</p>
<p>I got the below when I was in MyDatabase / Security / Users and clicked "refresh" on the "Users".</p>
<p>Again, I didn't come up with the WHERE clause and the LEFT OUTER JOIN, it was a part of the SSMS query. And this query is something that somebody at Microsoft has written (you know, the peeps who know the product inside and out, aka, the experts), so they are familiar with all the weird "flags" in the database.</p>
<p>But the SSMS/GUI -> Sql Profiler tricks works in many scenarios.</p>
<pre><code>SELECT
u.name AS [Name],
'Server[@Name=' + quotename(CAST(
serverproperty(N'Servername')
AS sysname),'''') + ']' + '/Database[@Name=' + quotename(db_name(),'''') + ']' + '/User[@Name=' + quotename(u.name,'''') + ']' AS [Urn],
u.create_date AS [CreateDate],
u.principal_id AS [ID],
CAST(CASE dp.state WHEN N'G' THEN 1 WHEN 'W' THEN 1 ELSE 0 END AS bit) AS [HasDBAccess]
FROM
sys.database_principals AS u
LEFT OUTER JOIN sys.database_permissions AS dp ON dp.grantee_principal_id = u.principal_id and dp.type = 'CO'
WHERE
(u.type in ('U', 'S', 'G', 'C', 'K' ,'E', 'X'))
ORDER BY
[Name] ASC
</code></pre> |
19,156,510 | Responsive website zoomed out to full width on mobile | <p>I am testing out Bootstrap responsiveness navbar and I have a <a href="http://myanmarlanguage.training/" rel="noreferrer">demo</a> website. When I resize the browser on a desktop, it all works fine including the nav bar which become collapsible menu with a small icon on the top which I can click to see more menu buttons. </p>
<p>But when I tried it from a mobile browser (I tried it on chrome and internet browser on an Android), I didn't see the responsive design. I could only see very small version of desktop like website. </p>
<p>Could anyone point out what I am doing wrong? </p> | 19,158,781 | 4 | 0 | null | 2013-10-03 10:12:58.41 UTC | 52 | 2020-02-28 17:26:01.68 UTC | 2018-10-23 14:59:03.893 UTC | null | 171,456 | null | 1,029,608 | null | 1 | 144 | twitter-bootstrap|user-interface|twitter-bootstrap-3|responsive-design|bootstrap-4 | 74,087 | <p>Add this to your HTML head..</p>
<pre><code><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</code></pre>
<p>This tells smaller device browsers how to scale the page. You can read more about this here: <a href="https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html" rel="noreferrer">https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html</a></p> |
21,032,759 | Bootstrap 3 2-column form layout | <p>I am still learning the proper use of Bootstrap 3 and was wondering if you all could help me out. I would like a layout something like this:</p>
<pre><code>Label Label
Textbox Textbox
Label Label
Textbox Textbox
Label Label
Textbox Textbox Textarea
</code></pre>
<p>I know that if I use the .form-group it will allow me to accomplish the Label over the top of the textbox. How can I assure that this happens in a column yet allows for some inline things like the example with the two textboxes alongside each other?</p> | 27,159,199 | 3 | 0 | null | 2014-01-09 22:43:27.917 UTC | 13 | 2018-05-25 12:24:18.907 UTC | 2014-01-09 23:15:53.623 UTC | null | 2,002,728 | null | 2,002,728 | null | 1 | 44 | html|css|twitter-bootstrap | 143,523 | <p>As mentioned earlier, you can use the grid system to layout your inputs and labels anyway that you want. The trick is to remember that you can use rows within your columns to break them into twelfths as well.</p>
<p>The example below is one possible way to accomplish your goal and will put the two text boxes near Label3 on the same line when the screen is small or larger.</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="row">
<div class="col-xs-6 form-group">
<label>Label1</label>
<input class="form-control" type="text"/>
</div>
<div class="col-xs-6 form-group">
<label>Label2</label>
<input class="form-control" type="text"/>
</div>
<div class="col-xs-6">
<div class="row">
<label class="col-xs-12">Label3</label>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6">
<input class="form-control" type="text"/>
</div>
<div class="col-xs-12 col-sm-6">
<input class="form-control" type="text"/>
</div>
</div>
</div>
<div class="col-xs-6 form-group">
<label>Label4</label>
<input class="form-control" type="text"/>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/m3u8bjv0/2/">http://jsfiddle.net/m3u8bjv0/2/</a></p> |
43,881,131 | Add badge counter to hamburger navigation menu icon in Android | <p>My question is the same as <a href="https://stackoverflow.com/questions/34633363/how-to-implement-a-badge-counter-on-android-hamburger-menu-icon">this question</a> (which is <strong>not</strong> a duplicate of <a href="https://stackoverflow.com/questions/6011786/add-new-item-count-to-icon-on-button-android">this question</a>).</p>
<p>The <a href="https://stackoverflow.com/a/34633902/1617737">only answer</a> to that question does not work for me as, rather than changing the default hamburger icon to the <strong><em>left</em></strong> of the activity's title, it just adds an additional hamburger icon to the <strong><em>right</em></strong> of my activity's title.</p>
<p>So how do I actually get this:</p>
<p><a href="https://i.stack.imgur.com/wZzdC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wZzdC.png" alt="Android hamburger icon with badge counter"></a></p>
<p>I've been poking around at it all day, but have got nowhere.</p>
<p>I see that <code>Toolbar</code> has a <code>setNavigationIcon(Drawable drawable)</code> method. Ideally, I would like to use a <code>layout</code> (that contains the hamburger icon and the badge view) instead of a <code>Drawable</code>, but I'm not sure if/how this is achievable - or if there is a better way?</p>
<p><em>NB - This isn't a question about how to <strong>create</strong> the badge view. I have already created that and have implemented it on the nav menu items themselves. So I am now just needing to add a similar badge view to the default hamburger icon.</em></p> | 43,886,113 | 1 | 0 | null | 2017-05-09 23:01:41.053 UTC | 23 | 2019-07-10 02:49:42.423 UTC | 2018-10-08 03:18:26.907 UTC | null | 2,821,954 | null | 1,617,737 | null | 1 | 24 | android|android-toolbar|badge|navigation-drawer|android-navigationview | 9,588 | <p>Since version 24.2.0 of the support library, the v7 version of <code>ActionBarDrawerToggle</code> has offered the <code>setDrawerArrowDrawable()</code> method as a means to customize the toggle icon. <code>DrawerArrowDrawable</code> is the class that provides that default icon, and it can be subclassed to alter it as needed.</p>
<p>As an example, the <code>BadgeDrawerArrowDrawable</code> class overrides the <code>draw()</code> method to add a basic red and white badge after the superclass draws itself. This allows the hamburger-arrow animation to be preserved underneath.</p>
<pre><code>import android.content.Context;
import android.graphics.Color;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.support.v7.graphics.drawable.DrawerArrowDrawable;
import java.util.Objects;
public class BadgeDrawerArrowDrawable extends DrawerArrowDrawable {
// Fraction of the drawable's intrinsic size we want the badge to be.
private static final float SIZE_FACTOR = .3f;
private static final float HALF_SIZE_FACTOR = SIZE_FACTOR / 2;
private Paint backgroundPaint;
private Paint textPaint;
private String text;
private boolean enabled = true;
public BadgeDrawerArrowDrawable(Context context) {
super(context);
backgroundPaint = new Paint();
backgroundPaint.setColor(Color.RED);
backgroundPaint.setAntiAlias(true);
textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setAntiAlias(true);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(SIZE_FACTOR * getIntrinsicHeight());
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (!enabled) {
return;
}
final Rect bounds = getBounds();
final float x = (1 - HALF_SIZE_FACTOR) * bounds.width();
final float y = HALF_SIZE_FACTOR * bounds.height();
canvas.drawCircle(x, y, SIZE_FACTOR * bounds.width(), backgroundPaint);
if (text == null || text.length() == 0) {
return;
}
final Rect textBounds = new Rect();
textPaint.getTextBounds(text, 0, text.length(), textBounds);
canvas.drawText(text, x, y + textBounds.height() / 2, textPaint);
}
public void setEnabled(boolean enabled) {
if (this.enabled != enabled) {
this.enabled = enabled;
invalidateSelf();
}
}
public boolean isEnabled() {
return enabled;
}
public void setText(String text) {
if (!Objects.equals(this.text, text)) {
this.text = text;
invalidateSelf();
}
}
public String getText() {
return text;
}
public void setBackgroundColor(int color) {
if (backgroundPaint.getColor() != color) {
backgroundPaint.setColor(color);
invalidateSelf();
}
}
public int getBackgroundColor() {
return backgroundPaint.getColor();
}
public void setTextColor(int color) {
if (textPaint.getColor() != color) {
textPaint.setColor(color);
invalidateSelf();
}
}
public int getTextColor() {
return textPaint.getColor();
}
}
</code></pre>
<p>An instance of this can be set on the toggle any time after it's instantiated, and the badge's properties set directly on the drawable as needed.</p>
<p>As the OP noted below, the <code>Context</code> used for the custom <code>DrawerArrowDrawable</code> should be obtained with <code>ActionBar#getThemedContext()</code> or <code>Toolbar#getContext()</code> to ensure the correct style values are used. For example:</p>
<pre><code>private ActionBarDrawerToggle toggle;
private BadgeDrawerArrowDrawable badgeDrawable;
...
toggle = new ActionBarDrawerToggle(this, ...);
badgeDrawable = new BadgeDrawerArrowDrawable(getSupportActionBar().getThemedContext());
toggle.setDrawerArrowDrawable(badgeDrawable);
badgeDrawable.setText("1");
...
</code></pre>
<hr>
<p><a href="https://i.stack.imgur.com/v65uC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/v65uC.png" alt="screenshots"></a></p>
<hr>
<p>To simplify things a bit, it might be preferable to subclass <code>ActionBarDrawerToggle</code> as well, and handle everything through the toggle instance.</p>
<pre><code>import android.app.Activity;
import android.content.Context;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class BadgeDrawerToggle extends ActionBarDrawerToggle {
private BadgeDrawerArrowDrawable badgeDrawable;
public BadgeDrawerToggle(Activity activity, DrawerLayout drawerLayout,
int openDrawerContentDescRes,
int closeDrawerContentDescRes) {
super(activity, drawerLayout, openDrawerContentDescRes,
closeDrawerContentDescRes);
init(activity);
}
public BadgeDrawerToggle(Activity activity, DrawerLayout drawerLayout,
Toolbar toolbar, int openDrawerContentDescRes,
int closeDrawerContentDescRes) {
super(activity, drawerLayout, toolbar, openDrawerContentDescRes,
closeDrawerContentDescRes);
init(activity);
}
private void init(Activity activity) {
Context c = getThemedContext();
if (c == null) {
c = activity;
}
badgeDrawable = new BadgeDrawerArrowDrawable(c);
setDrawerArrowDrawable(badgeDrawable);
}
public void setBadgeEnabled(boolean enabled) {
badgeDrawable.setEnabled(enabled);
}
public boolean isBadgeEnabled() {
return badgeDrawable.isEnabled();
}
public void setBadgeText(String text) {
badgeDrawable.setText(text);
}
public String getBadgeText() {
return badgeDrawable.getText();
}
public void setBadgeColor(int color) {
badgeDrawable.setBackgroundColor(color);
}
public int getBadgeColor() {
return badgeDrawable.getBackgroundColor();
}
public void setBadgeTextColor(int color) {
badgeDrawable.setTextColor(color);
}
public int getBadgeTextColor() {
return badgeDrawable.getTextColor();
}
private Context getThemedContext() {
// Don't freak about the reflection. ActionBarDrawerToggle
// itself is already using reflection internally.
try {
Field mActivityImplField = ActionBarDrawerToggle.class
.getDeclaredField("mActivityImpl");
mActivityImplField.setAccessible(true);
Object mActivityImpl = mActivityImplField.get(this);
Method getActionBarThemedContextMethod = mActivityImpl.getClass()
.getDeclaredMethod("getActionBarThemedContext");
return (Context) getActionBarThemedContextMethod.invoke(mActivityImpl);
}
catch (Exception e) {
return null;
}
}
}
</code></pre>
<p>With this, the custom badge drawable will be set automatically, and everything toggle-related can be managed through a single object.</p>
<p><code>BadgeDrawerToggle</code> is a drop-in replacement for <code>ActionBarDrawerToggle</code>, and its constructors are exactly the same.</p>
<pre><code>private BadgeDrawerToggle badgeToggle;
...
badgeToggle = new BadgeDrawerToggle(this, ...);
badgeToggle.setBadgeText("1");
...
</code></pre> |
30,541,244 | What does an ampersand (&) mean in the Swift language? | <p>I know about the ampersand as a bit operation but sometimes I see it in front of variable names. What does putting an <code>&</code> in front of variables do?</p> | 30,541,277 | 5 | 1 | null | 2015-05-30 01:22:38.333 UTC | 18 | 2021-07-05 10:28:02.187 UTC | 2017-03-11 11:45:53.98 UTC | null | 3,425,536 | null | 4,171,159 | null | 1 | 70 | swift|ampersand|inout | 21,904 | <p>It works as an <code>inout</code> to make the variable an in-out parameter. In-out means in fact passing value by reference, not by value. And it requires not only to accept value by reference, by also to pass it by reference, so pass it with & - <code>foo(&myVar)</code> instead of just <code>foo(myVar)</code></p>
<p>As you see you can use that in error handing in Swift where you have to create an error reference and pass it to the function using <code>&</code> the function will populate the error value if an error occur or pass the variable back as it was before</p>
<p>Why do we use it? Sometimes a function already returns other values and just returning another one (like an error) would be confusing, so we pass it as an inout. Other times we want the values to be populated by the function so we don't have to iterate over lots of return values, since the function already did it for us - among other possible uses.</p>
<p>I hope that helps you!</p> |
4,581,776 | How do I uninstall Ruby on Rails and do a clean install? | <p>I'm following a Rails tutorial. I'm having version problems with RVM and am getting lots of errors. I would like to start over with a clean version of Ruby, Rails, Gemfiles, etc. </p>
<p>Can anyone give me some brief instructions on how to uninstall my Ruby-on-Rails environment? </p> | 4,581,804 | 1 | 1 | null | 2011-01-03 02:51:18.49 UTC | 9 | 2011-01-03 03:11:51.777 UTC | 2011-01-03 03:11:51.777 UTC | null | 405,017 | null | 537,259 | null | 1 | 15 | ruby-on-rails|ruby|installation|rvm | 26,193 | <p>Try this:</p>
<pre><code>rvm get head
rvm reset
rvm remove ... # take the output of rvm list and do rvm remove for each item in the list
rvm cleanup
rvm repair
rvm notes # make sure that you've got all the dependencies mentioned in the output from this command
rvm install ... # reinstall your rubies
</code></pre>
<p>This is likely overkill, but it should get you close to a known-good configuration. If it doesn't, try:</p>
<pre><code>rvm implode
</code></pre>
<p>That will completely remove RVM and you can start over from scratch.</p>
<p>If none of this works or you are still confused, paste some of the error messages here and tell more about your operating system and configuration details.</p>
<p>Good luck!</p> |
4,814,992 | Honeycomb Android emulator is dog slow - will it get manageable before the official release? | <p>I thought the <a href="https://stackoverflow.com/questions/4432531/gingerbread-emulator-instance-is-much-more-sluggish-than-froyo-and-below-why">Gingerbread emulator was slow</a>, but man - the Honeycomb emulator is so slow on a modern PC, it's practically unusable. Since Reto Meier asked to throw up our Honeycomb questions onto StackOverflow, here is mine - will it get faster any time soon? How are we expected to develop apps for tablets when I want to pull my hair out instead?</p>
<p>The SDK tools site now <a href="http://developer.android.com/sdk/tools-notes.html" rel="nofollow noreferrer">mentions</a> "Known issues with emulator performance: Because the Android emulator must simulate the ARM instruction set architecture on your computer, emulator performance is slow. We're working hard to resolve the performance issues and it will improve in future releases" but I'm wondering just how soon these future releases with the fixes will be coming out.</p> | 4,815,053 | 1 | 4 | null | 2011-01-27 10:07:53.16 UTC | 6 | 2012-04-09 19:51:48.64 UTC | 2017-05-23 11:53:24.813 UTC | null | -1 | null | 47,680 | null | 1 | 40 | android|performance|sdk|android-3.0-honeycomb | 10,393 | <p>The short answer is "yes". The Honeycomb emulator performance will be improved in future release of the development tools.</p>
<p>For right now, you should start by increasing the amount of device RAM used by the emulator. The default is 256Mb but 1Gb is probably more reasonable.</p>
<blockquote>
<p>[Update (April 9 2012) -- The latest developer tools release (r18),
combined with a new system image (4.0.3 r2) dramatically improves
performance of the emulator by supporting GPU and CPU acceleration.
<a href="http://android-developers.blogspot.com/2012/04/faster-emulator-with-better-hardware.html" rel="nofollow">More details here</a>.]</p>
</blockquote> |
31,264,826 | Start a flask application in separate thread | <p>I'm currently developing a Python application on which I want to see real-time statistics. I wanted to use <code>Flask</code> in order to make it easy to use and to understand.</p>
<p>The issue is that my Flask server should start at the very beginning of my Python application and stop at the very end. It should look like this:</p>
<pre><code>def main():
""" My main application """
from watcher.flask import app
# watcher.flask define an app as in the Quickstart flask documentation.
# See: http://flask.pocoo.org/docs/0.10/quickstart/#quickstart
app.run() # Starting the flask application
do_my_stuff()
app.stop() # Undefined, for the idea
</code></pre>
<p>Because I need my application context (for the statistics), I can't use a <code>multiprocessing.Process</code>. Then I was trying to use a <code>threading.Thread</code>, but it looks like Werkzeug doesn't like it: </p>
<pre><code> * Running on http://0.0.0.0:10079/
Exception in thread Flask Server:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File ".../develop-eggs/watcher.flask/src/watcher/flask/__init__.py", line 14, in _run
app.run(host=HOSTNAME, port=PORT, debug=DEBUG)
File ".../eggs/Flask-0.10.1-py2.7.egg/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File ".../eggs/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 609, in run_simple
run_with_reloader(inner, extra_files, reloader_interval)
File ".../eggs/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 524, in run_with_reloader
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
ValueError: signal only works in main thread
</code></pre>
<p>How can I do that without running Flask in the main thread?</p> | 31,265,602 | 5 | 6 | null | 2015-07-07 09:30:33.797 UTC | 15 | 2022-07-13 21:00:23.693 UTC | 2018-01-10 16:31:32.473 UTC | null | 4,907,496 | null | 2,964,982 | null | 1 | 74 | python|multithreading|flask | 69,586 | <p>You're running <code>Flask</code> in debug mode, which enables <strong>the reloader</strong> (reloads the Flask server when your code changes). </p>
<p>Flask can run just fine in a separate thread, but the reloader expects to run in the main thread.</p>
<hr>
<p>To solve your issue, you should either disable debug (<code>app.debug = False</code>), or disable the reloader (<code>app.use_reloader=False</code>). </p>
<p>Those can also be passed as arguments to <code>app.run</code>: <code>app.run(debug=True, use_reloader=False)</code>.</p> |
26,764,978 | Using win32com with multithreading | <p>I am working on a web app with CherryPy that needs to access a few applications via COM. </p>
<p>Right now I create a new instance of the application with each request, which means each request waits 3 seconds for the application to start and 0.01 for the actual job.</p>
<p>I would like to start each COM application once and keep it alive and reuse it for a few seconds on the following requests because most of the time it is used by a burst of 5-10 ajax requests, then nothing for hours.</p>
<p>Is it possible to share a COM abject across all the threads of a CherryPy application?</p>
<p>Here is the summary of a few experiments that show how it is working now on each request and how it does not work across threads.</p>
<p>The following code successfully starts and stops Excel:</p>
<pre><code>>>> import pythoncom, win32com.client
>>> def start():
global xl
xl = win32com.client.Dispatch('Excel.Application')
>>> def stop():
global xl
xl.quit()
xl = None
>>> start()
>>> stop()
</code></pre>
<p>But the following code starts Excel and closes it after 3 seconds.</p>
<pre><code>>>> import pythoncom, win32com.client, threading, time
>>> def start():
global xl
pythoncom.CoInitialize()
xl = win32com.client.Dispatch('Excel.Application')
time.sleep(3)
>>> threading.Thread(target=start).start()
</code></pre>
<p>I added the call to <code>CoInitialize()</code> otherwise the <code>xl</code> object would not work (see <a href="https://stackoverflow.com/questions/26745617/win32com-client-dispatch-cherrypy-coinitialize-has-not-been-called/26753031#26753031">this post</a>).</p>
<p>And I added the 3 second pause, so I could see on the task manager that the EXCEL.EXE process starts and is alive for 3 seconds.</p>
<p>Why does it die after the thread that started it ends?</p>
<p>I checked the documentation of <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms678543(v=vs.85).aspx" rel="noreferrer"><code>CoInitialize()</code></a>, but I couldn't understand if it is possible to get it to work in multithreaded environment.</p> | 27,966,218 | 3 | 1 | null | 2014-11-05 19:00:33.713 UTC | 17 | 2022-09-09 06:25:55.44 UTC | 2017-05-23 12:25:17.26 UTC | null | -1 | null | 1,899,628 | null | 1 | 18 | python|multithreading|python-3.x|win32com | 24,956 | <p>If you want to use win32com in multiple threads you need to do a little bit of work more as <code>COMObject</code> cannot be passed to a thread directly. You need to use <code>CoMarshalInterThreadInterfaceInStream()</code> and <code>CoGetInterfaceAndReleaseStream()</code> to pass instance between threads:</p>
<pre><code>import pythoncom, win32com.client, threading, time
def start():
# Initialize
pythoncom.CoInitialize()
# Get instance
xl = win32com.client.Dispatch('Excel.Application')
# Create id
xl_id = pythoncom.CoMarshalInterThreadInterfaceInStream(pythoncom.IID_IDispatch, xl)
# Pass the id to the new thread
thread = threading.Thread(target=run_in_thread, kwargs={'xl_id': xl_id})
thread.start()
# Wait for child to finish
thread.join()
def run_in_thread(xl_id):
# Initialize
pythoncom.CoInitialize()
# Get instance from the id
xl = win32com.client.Dispatch(
pythoncom.CoGetInterfaceAndReleaseStream(xl_id, pythoncom.IID_IDispatch)
)
time.sleep(5)
if __name__ == '__main__':
start()
</code></pre>
<p>For more info see: <a href="https://mail.python.org/pipermail/python-win32/2008-June/007788.html" rel="nofollow noreferrer">https://mail.python.org/pipermail/python-win32/2008-June/007788.html</a></p> |
7,537,450 | What does "wrong number of arguments (1 for 0)" mean in Ruby? | <p>What does "Argument Error: wrong number of arguments (1 for 0)" mean?</p> | 7,540,802 | 4 | 0 | null | 2011-09-24 06:34:52.37 UTC | 9 | 2020-09-16 14:31:30.05 UTC | 2014-03-28 16:01:00.867 UTC | null | 168,143 | null | 950,465 | null | 1 | 61 | ruby | 105,429 | <p>When you define a function, you also define what info (arguments) that function needs to work. If it is designed to work without any additional info, and you pass it some, you are going to get that error.</p>
<p>Example:
Takes no arguments:</p>
<pre><code>def dog
end
</code></pre>
<p>Takes arguments:</p>
<pre><code>def cat(name)
end
</code></pre>
<p>When you call these, you need to call them with the arguments you defined.</p>
<pre><code>dog #works fine
cat("Fluffy") #works fine
dog("Fido") #Returns ArgumentError (1 for 0)
cat #Returns ArgumentError (0 for 1)
</code></pre>
<p>Check out the <a href="http://rubykoans.com/" rel="noreferrer">Ruby Koans</a> to learn all this.</p> |
59,376,777 | Finding longest overlapping ranges | <p>I have ranges in a list like:</p>
<pre><code>ranges = [(1, 50), (49, 70), (75, 85), (84, 88), (87, 92)]
</code></pre>
<p>I would like to find the longest ranges that can be constructed from these <em>(when they overlap with each other)</em>. </p>
<p>Expected output: </p>
<pre><code>[(1, 70), (75, 92)]
</code></pre>
<p>I have a solution, however it is way too complicated, and I am sure there must be an easier solution to this problem</p>
<p>My solution:</p>
<pre><code>def overlap(x, y):
return range(max(x[0], y[0]), min(x[-1], y[-1]) + 1)
ranges = [(1, 50), (49, 70), (75, 85), (84, 88), (87, 92)]
beg, end = min([x[0] for x in ranges]), 0
for i in ranges:
if i[0] == beg:
end = i[1]
while beg:
for _ in ranges:
for i in ranges:
if i[1] > end and overlap(i, [beg, end]):
end = i[1]
print(beg, end)
try:
beg = min([x[0] for x in ranges if x[0] > end])
for i in ranges:
if i[0] == beg:
end = i[1]
except ValueError:
beg = None
</code></pre>
<p>Output:</p>
<pre><code>1 70
75 92
</code></pre> | 59,378,344 | 9 | 5 | null | 2019-12-17 14:52:58.657 UTC | null | 2019-12-20 07:52:58.987 UTC | 2019-12-17 15:07:22.88 UTC | null | 8,306,666 | null | 4,555,249 | null | 1 | 34 | python|python-3.x|range | 1,685 | <p>I think you can sort your input by the start of the ranges, then iterate through them. At each item, it is either added to the current range (if the start is less than the end of the current range) or we yield out current range and begin accumulating a new range:</p>
<pre><code>def overlaps(ranges):
ranges = sorted(ranges) # If our inputs are garunteed sorted, we can skip this
it = iter(ranges)
try:
curr_start, curr_stop = next(it)
# overlaps = False # If we want to exclude output ranges not produced by overlapping input ranges
except StopIteration:
return
for start, stop in it:
if curr_start <= start <= curr_stop: # Assumes intervals are closed
curr_stop = max(curr_stop, stop)
# overlaps = True
else:
# if overlaps:
yield curr_start, curr_stop
curr_start, curr_stop = start, stop
# overlaps = False
# if overlaps:
yield curr_start, curr_stop
print(list(overlaps([(1, 50), (49, 70), (75, 85), (84, 88), (87, 92)])))
# [(1, 70), (75, 92)]
print(list(overlaps([(20, 30), (5, 10), (1, 7), (12, 21)])))
# [(1, 10), (12, 30)]
</code></pre> |
2,133,651 | Spectrogram C++ library | <p>For my current project in C++ / Qt I need a library (LGPL is preferred) which can calculate a spectrogram from a signal ( basically an array of doubles ). I already use Qwt for the GUI part.</p>
<p>Any suggestions?
Thanks. </p> | 2,133,952 | 4 | 4 | null | 2010-01-25 16:15:23.777 UTC | 14 | 2021-08-25 14:11:51.773 UTC | 2010-01-27 23:30:27.577 UTC | null | 149,237 | null | 149,237 | null | 1 | 24 | c++|fft|scientific-computing|spectrum|spectrogram | 17,887 | <p>It would be fairly easy to put together your own spectrogram. The steps are:</p>
<ol>
<li>window function (fairly trivial,
e.g. Hanning)</li>
<li>FFT (FFTW would be
a good choice but if licensing is an
issue then go for Kiss FFT or
similar)</li>
<li>calculate log magnitude
of frequency domain components
(trivial: log(sqrt(re * re + im *
im))</li>
</ol> |
2,215,462 | HTML form - when I hit enter it refreshes page! | <p>Is there a way to make a form NOT refresh or call anything when you hit "Enter" key on your keyboard?</p>
<p>Thank you so much!!!</p>
<p>I found this code for preventing Enter from working, but it DOESN'T work in IE :(</p>
<pre><code> $(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
}
</code></pre> | 2,215,467 | 4 | 0 | null | 2010-02-07 01:06:05.413 UTC | 6 | 2014-03-01 15:01:20.627 UTC | null | null | null | null | 220,305 | null | 1 | 28 | javascript|jquery|html | 42,273 | <p>Try this:</p>
<pre><code>$(function() {
$("form").submit(function() { return false; });
});
</code></pre> |
1,596,318 | Find working directory from Ant | <p>Is it possible to tell which directory the user ran Ant from?</p>
<p>For example, I might want to run only the unit tests in the current working directory, rather than all tests for the entire project.</p>
<p>I tried this:</p>
<pre><code><property environment="env" />
<echo>${env.CWD}</echo>
</code></pre>
<p>but that doesn't work.</p> | 1,596,354 | 4 | 1 | null | 2009-10-20 18:01:54.173 UTC | 9 | 2018-12-05 08:49:16 UTC | 2011-01-07 04:15:37.253 UTC | null | 166,339 | null | 4,321 | null | 1 | 41 | java|ant | 45,403 | <p>The whole Properties object returned by <code>System.getProperties()</code> is exposed by Ant. Try this:</p>
<pre><code><echo>${user.dir}</echo>
</code></pre> |
2,232,934 | How can I match a whole word in JavaScript? | <p>I am trying to search a single whole word through a textbox. Say I search "me", I should find all occurrences of the word "me" in the text, but not "memmm" per say.</p>
<p>I am using JavaScript's <code>search('my regex expression')</code> to perform the current search (with no success).</p>
<p>After several proposals to use the <code>\b</code> switches (which don't seem to work) I am posting a revised explanation of my problem:</p>
<p>For some reason this doesn't seem to do the trick. Assume the following JavaScript search text:</p>
<pre><code>var lookup = '\n\n\n\n\n\n2 PC Games \n\n\n\n';
lookup = lookup.trim() ;
alert(lookup );
var tttt = 'tttt';
alert((/\b(lookup)\b/g).test(2));
</code></pre>
<p>Moving lines is essential</p> | 2,232,947 | 4 | 1 | null | 2010-02-09 22:17:02.547 UTC | 12 | 2020-11-06 10:06:53.803 UTC | 2020-11-06 10:06:53.803 UTC | null | 479,156 | null | 126,015 | null | 1 | 45 | javascript|regex | 71,228 | <p>To use a dynamic regular expression see my updated code:</p>
<pre><code>new RegExp("\\b" + lookup + "\\b").test(textbox.value)
</code></pre>
<p>Your specific example is backwards:</p>
<pre><code>alert((/\b(2)\b/g).test(lookup));
</code></pre>
<p><a href="http://regexpal.com/" rel="noreferrer">Regexpal</a></p>
<p><a href="http://www.w3schools.com/jsref/jsref_obj_regexp.asp" rel="noreferrer">Regex Object</a></p> |
2,326,499 | Apply CSS styles to an element depending on its child elements | <p>Is it possible to define a CSS style for an element, that is only applied if the matching element contains a specific element (as the direct child item)?</p>
<p>I think this is best explained using an example.</p>
<p><strong>Note</strong>: I'm trying to <strong>style the parent element</strong>, depending on what child elements it contains.</p>
<pre><code><style>
/* note this is invalid syntax. I'm using the non-existing
":containing" pseudo-class to show what I want to achieve. */
div:containing div.a { border: solid 3px red; }
div:containing div.b { border: solid 3px blue; }
</style>
<!-- the following div should have a red border because
if contains a div with class="a" -->
<div>
<div class="a"></div>
</div>
<!-- the following div should have a blue border -->
<div>
<div class="b"></div>
</div>
</code></pre>
<p><strong>Note 2</strong>: I know I can achieve this using javascript, but I just wondered whether this is possible using some unknown (to me) CSS features.</p> | 2,326,571 | 4 | 4 | null | 2010-02-24 14:03:30.003 UTC | 22 | 2019-12-21 00:24:35.693 UTC | 2012-12-18 07:19:43.193 UTC | null | 106,224 | null | 19,635 | null | 1 | 232 | html|css | 236,157 | <p>As far as I'm aware, styling a parent element based on the child element is not an available feature of CSS. You'll likely need scripting for this.</p>
<p>It'd be wonderful if you could do something like <code>div[div.a]</code> or <code>div:containing[div.a]</code> as you said, but this isn't possible. </p>
<p>You may want to consider looking at <a href="http://jquery.com" rel="noreferrer">jQuery</a>. Its selectors work very well with 'containing' types. You can select the div, based on its child contents and then apply a CSS class to the parent all in one line.</p>
<p>If you use jQuery, something along the lines of this would may work (untested but the theory is there):</p>
<pre><code>$('div:has(div.a)').css('border', '1px solid red');
</code></pre>
<p>or</p>
<pre><code>$('div:has(div.a)').addClass('redBorder');
</code></pre>
<p>combined with a CSS class:</p>
<pre><code>.redBorder
{
border: 1px solid red;
}
</code></pre>
<p>Here's the documentation for the <a href="http://api.jquery.com/has-selector/" rel="noreferrer">jQuery "has" selector</a>.</p> |
10,610,963 | How to Position a table HTML? | <p>I am trying to have the table lower and more to the right to were it originally is. How can i do this? What are the attributes? Thanks!</p> | 10,611,021 | 2 | 2 | null | 2012-05-16 01:44:06.153 UTC | null | 2015-10-07 04:17:25.63 UTC | null | null | null | null | 1,394,876 | null | 1 | 12 | html | 154,827 | <p>You would want to use CSS to achieve that.</p>
<p>say you have a table with the attribute id="my_table"</p>
<p>You would want to write the following in your css file</p>
<pre><code>#my_table{
margin-top:10px //moves your table 10pixels down
margin-left:10px //moves your table 10pixels right
}
</code></pre>
<p>if you do not have a CSS file then you may just add <code>margin-top:10px, margin-left:10px</code> to the style attribute in your table element like so</p>
<pre><code><table style="margin-top:10px; margin-left:10px;">
....
</table>
</code></pre>
<p>There are a lot of resources on the net describing CSS and HTML in detail</p> |
7,071,301 | Enum default value for Java enum annotation value | <p>Java allows <code>enum</code> as values for annotation values. How can I define a kind of generic default <code>enum</code> value for an <code>enum</code> annotation value?</p>
<p>I have considered the following, but it won't compile:</p>
<pre><code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public <T extends Enum<T>> @interface MyAnnotation<T> {
T defaultValue();
}
</code></pre>
<p>Is there a solution to this issue or not?</p>
<p><strong>BOUNTY</strong></p>
<p>Is does not seem like there is a direct solution to this Java corner case. So, I am starting a bounty to find the most elegant solution to this issue.</p>
<p>The <em>ideal</em> solution should <em>ideally</em> meet the following criteria:</p>
<ol>
<li>One annotation reusable on all enums</li>
<li>Minimum effort/complexity to retrieve the default enum value as an enum from annotation instances</li>
</ol>
<p><strong>BEST SOLUTION SO FAR</strong></p>
<p>By Dunes:</p>
<pre><code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
// By not specifying default,
// we force the user to specify values
Class<? extends Enum<?>> enumClazz();
String defaultValue();
}
...
public enum MyEnumType {
A, B, D, Q;
}
...
// Usage
@MyAnnotation(enumClazz=MyEnumType.class, defaultValue="A");
private MyEnumType myEnumField;
</code></pre>
<p>Of course, we can't force the user to specify a valid default value at compile time. However, any annotation pre-processing can verify this with <code>valueOf()</code>.</p>
<p><strong>IMPROVEMENT</strong></p>
<p>Arian provides an elegant solution to get rid of <code>clazz</code> in annotated fields:</p>
<pre><code>@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
}
...
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@MyAnnotation()
public @interface MyEnumAnnotation {
MyEnumType value(); // no default has user define default value
}
...
@MyEnumAnnotation(MyEnum.FOO)
private MyEnumType myValue;
</code></pre>
<p>The annotation processor should search for both <code>MyEnumAnnotation</code> on fields for the provided default value.</p>
<p>This requires the creation of one annotation type per enum type, but guarantees compile time checked type safety.</p> | 7,160,646 | 7 | 10 | null | 2011-08-15 21:58:32.99 UTC | 10 | 2017-03-27 18:20:24.933 UTC | 2011-08-23 21:37:52.523 UTC | null | 520,957 | null | 520,957 | null | 1 | 20 | java|enums|annotations|default-value | 15,153 | <p>I'm not sure what your use case is, so I have two answers:</p>
<p><strong>Answer 1:</strong></p>
<p>If you just want to write as little code as possible, here is my suggestion extending <strong>Dunes'</strong> answer:</p>
<pre><code>public enum ImplicitType {
DO_NOT_USE;
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {
Class<? extends Enum<?>> clazz() default ImplicitType.class;
String value();
}
@MyAnnotation("A");
private MyEnumType myEnumField;
</code></pre>
<p>When <code>clazz</code> is <code>ImplicitType.class</code>, use the fields type as enum class.</p>
<p><strong>Answer 2:</strong></p>
<p>If you want to do some framework magic and want to maintain compiler checked type safety, you can do something like this:</p>
<pre><code>/** Marks annotation types that provide MyRelevantData */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface MyAnnotation {
}
</code></pre>
<p>And in the client code, you would have</p>
<pre><code>/** Provides MyRelevantData for TheFramework */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@MyAnnotation
public @interface MyEnumAnnotation {
MyEnumType value(); // default MyEnumType.FOO;
}
@MyEnumAnnotation(MyEnum.FOO)
private MyEnumType myValue;
</code></pre>
<p>In this case you would scan the field for annotations which again are annotated with <code>MyAnnotation</code>. You will have to access the value via reflection on the annotation object, though. Seems like this approach is more complex on the framework side.</p> |
13,978,689 | Balancing contrast and brightness between stitched images | <p>I'm working on an image stitching project, and I understand there's different approaches on dealing with contrast and brightness of an image. I could of course deal with this issue before I even stitched the image, but yet the result is not as consistent as I would hope. So my question is if it's possible by any chance to "balance" or rather "equalize" the contrast and brightness in color pictures after the stitching has taken place?</p> | 13,991,332 | 2 | 0 | null | 2012-12-20 18:57:47.4 UTC | 10 | 2015-12-01 20:02:22.653 UTC | 2015-12-01 20:02:22.653 UTC | null | 4,904,417 | null | 531,203 | null | 1 | 7 | opencv|computer-vision|brightness|contrast | 8,005 | <p>You want to determine the histogram equalization function not from the entire images, but on the zone where they will touch or overlap. You obviously want to have identical histograms in the overlap area, so this is where you calculate the functions. You then apply the equalization functions that accomplish this on the entire images. If you have more than two stitches, you still want to have global equalization beforehand, and then use a weighted application of the overlap-equalizing functions that decreases the impact as you move away from the stitched edge.</p>
<p>Apologies if this is all obvious to you already, but your general question leads me to a general answer.</p> |
14,257,709 | Push is not a function JavaScript error | <p>In the below code, I am getting "push is not a function" error. Can anyone please let me know what I am doing wrong here? I am trying to create 2D array in Javascript.</p>
<pre><code>var myArray = new Array(4);
myArray = ["0","0","0","0"];
for (var i=0; i<myArray.length; i++) {
myArray[i].push("ID");
myArray[i] = new Array(1);
for (var j=0; j<myArray[i].length; i++) {
myArray[i][j].push("Array[j]");
}
}
</code></pre>
<p>Firebug is pointing me to:</p>
<pre><code>myArray[i].push("ID");
</code></pre>
<p>For this line I am getting "TypeError: myArray[i].push is not a function"</p>
<p>Final array it should look like is:</p>
<pre><code>[ID,"SomeValue1"],
[ID,"SomeValue2"],
[ID,"SomeValue3"]
</code></pre>
<p>And I cannot hard code, I need to create this dynamically based on data from DB</p> | 14,258,008 | 3 | 2 | null | 2013-01-10 12:14:23.637 UTC | null | 2016-05-19 07:51:38.773 UTC | 2016-05-19 07:51:38.773 UTC | user1702383 | 305,189 | user1702383 | null | null | 1 | 7 | javascript | 49,570 | <p>This will create your example.</p>
<pre><code>var myArray = new Array(4);
for (var i = 0; i < myArray.length; i++) {
myArray[i] = ["ID", "SomeValue" + (i+1)];
}
</code></pre>
<p>But if you need to set data from a database, how is that being set in the Javascript? if it's in a different array you could do the following:</p>
<pre><code>var dbArray = ["SomeValue1", "SomeValue2", "SomeValue3"];
var myArray = new Array(dbArray.length);
for (var i = 0; i < myArray.length; i++) {
myArray[i] = ["ID", dbArray[i]];
}
</code></pre> |
13,831,251 | flask-login: Chrome ignoring cookie expiration? | <p>I've got the authentication working with flask-login, but it seems like no matter what I use for the cookie duration in flask, the session is still authenticated. Am I setting the config variables properly for flask-login? I've tried</p>
<pre><code>app.REMEMBER_COOKIE_DURATION = datetime.timedelta(seconds=30)
app.config["REMEMBER_COOKIE_DURATION"] = datetime.timedelta(seconds=30)
</code></pre>
<p>Even if I close the browser, wait a while, and hit a url that should be protected, I can still access it. Is this related to <a href="https://stackoverflow.com/questions/10617954/chrome-doesnt-delete-session-cookies">this issue with chrome?</a>. If I clear my cookies, I get the expected login page. All this makes me think that the cookie timeout is not being respected.</p>
<p>Also, what does <code>PERMANENT_SESSION_LIFETIME</code> do in flask? </p> | 13,839,643 | 1 | 0 | null | 2012-12-12 01:16:45.037 UTC | 12 | 2012-12-12 12:19:18.997 UTC | 2017-05-23 12:01:37.133 UTC | null | -1 | null | 1,443,118 | null | 1 | 10 | python|web-applications|python-2.7|flask|flask-login | 6,385 | <p><code>REMEMBER_COOKIE_DURATION</code> is used for "Remember me" functionality, that is, how long to remember logged in user even if he closed the browser. The separate cookie is used for that, the name of which can be set by <code>REMEMBER_COOKIE_NAME</code> (<code>remember_token</code> by default). To force login session to expire after some time (even if the browser is still kept running), set <code>PERMANENT_SESSION_LIFETIME</code> somewhere where you keep your app settings:</p>
<pre><code>PERMANENT_SESSION_LIFETIME = datetime.timedelta(minutes=30)
</code></pre>
<p>And in your login view set <code>session.permanent = True</code>:</p>
<pre><code>from flask import session
@app.route('/login')
def login():
# ...
if login_user(user):
session.permanent = True
return redirect(request.args.get('next') or url_for('index'))
# ...
</code></pre> |
14,043,986 | debugging with visual studio using redirected standard input | <p>I am debugging c++ console application with Visual studio. I exhausted of inserting the same input every time I debug this program. I would like to use the same input more times.</p>
<p>I do this without debugging in command line with command: Program.exe < 1.in</p>
<p>Is it possible to use debugging with standard input redirected from file???</p>
<p>I already tried looking in to procejt properties. I tried setting Command to $(TargetPath) < 1.in instead of $(TargetPath).
I also tried setting Command Arguments to < 1.in. Niether of these method worked.</p>
<p>I am using Visual Studio 2012. But this is probably same in all versions of studio.</p> | 14,044,383 | 3 | 1 | null | 2012-12-26 17:31:32.837 UTC | 9 | 2017-04-27 18:42:59.383 UTC | 2017-04-27 18:42:59.383 UTC | null | 1,033,581 | null | 1,930,362 | null | 1 | 23 | visual-studio|debugging|visual-c++|visual-studio-2012|visual-studio-debugging | 24,604 | <p>This is a supported debugging scenario. You do have to make sure that the debugger can find the file. Leave the Command setting at <code>$(TargetPath)</code>. A possible value for the Command Arguments setting is:</p>
<pre><code> < "$(ProjectDir)test.txt"
</code></pre>
<p>if the input file "test.txt" is located in the project directory. Or type the full path of the file to be sure. The MSDN article that describes this feature is <a href="http://msdn.microsoft.com/en-us/library/kcw4dzyf%28v=VS.110%29.aspx">available here</a>.</p> |
14,002,849 | Copy data between two server instances | <p>I want something like : </p>
<p><code>insert into server2.database1.table1 select * from server1.database1.table1</code> </p>
<p>both tables are exactly the same.</p>
<p>how can I <strong>Copy data between two server instances?</strong> </p> | 14,003,061 | 7 | 0 | null | 2012-12-22 12:31:27.113 UTC | 9 | 2018-01-30 20:57:55.693 UTC | 2012-12-22 15:04:07.687 UTC | null | 1,471,381 | null | 1,471,381 | null | 1 | 23 | sql|sql-server|tsql | 102,264 | <p><strong>SQL - Linked Server</strong></p>
<p>If both servers are SQL Server, you can set up <a href="http://msdn.microsoft.com/en-us/library/ff772782.aspx" rel="noreferrer">Linked servers</a> - I would suggest using an SQL account for security there.</p>
<p>Then you can simply perform</p>
<pre><code>insert into server2.database1.dbo.table1
select * from server1.database1.dbo.table1 where col1 = 'X'
</code></pre>
<p>If you run the query in SQL Management studio connected to server1, and current database set to database1, you won't need the prefix</p>
<pre><code>server1.database1.dbo.
</code></pre>
<p>Also, the linked server would be configured on server1, to connect to server2 (rather than the other way around).</p>
<p>If you have the correct OLE DB drivers, this method can also work between different types of RDBMS (ie. non-SQL Server ones).</p>
<p><em>Open Query</em></p>
<p>Note: Beware not to rely on linked servers too much especially for filtering, and for joins across servers, as they require data to be read in full to the originating RDBMS before any conditions can be applied. Many complications can arise from Linked Servers, so read up before you embark, as even version differences might cause headaches.</p>
<p>I recommend you use the OPENQUERY command for SQL Servers to get around such limitations. Here's an example, but you should find help specific to your needs through further research:</p>
<pre><code>insert into server2.database1.dbo.table1
select * from OPENQUERY(server1, 'select * from database1.dbo.table1 where col1 = ''X''');
</code></pre>
<p>The above code is more efficient, filtering the data on the source server (and using available indexes), before pumping the data through, saving bandwidth/time/resources of both the source and destination servers.</p>
<p>(Also note the double quote '', is an escape sequence to produce a single quote.)</p>
<p><strong>SQL - Temporarily on the same server</strong></p>
<p>Would enable (note the underscore):</p>
<pre><code>insert into server2_database1.dbo.table1
select * from database1.dbo.table1
</code></pre>
<p>Still within the SQL query domain. If you can temporarily move the database on server2 to server1, then you won't need the linked server. A rename of the database would appear to be required while co-locating on server1. Achieving such co-location could use various methods, I suggest shrinking database files before proceeding with either:</p>
<ol>
<li><strong>Backup/Restore</strong> - Backup on server2, Restore on server1 (with different name) - perform insert as described above, but without the server1 or server2 prefixes. Then reverse - backup on server1, restore on server2/</li>
<li><strong>Detach/Attach</strong> - Rename database, Detach on server2, (compress), copy files to server 1, (decompress), attach on server1, perform insert. Then reverse...</li>
</ol>
<p>In either case, SQL Server version could be a barrier. If server1 is of a lower SQL version, then both backup and detach/attach methods will likely fail. This can be worked around by moving the server1 database to server2, which may or may not be more suitible.</p>
<p><strong>Other Methods</strong></p>
<p>May be suitable, non-SQL/TSQL method failing favorable environmental factors for previously mentioned methods. And if you have the correct access (OLE DB Drivers, etc..), this method can also work between different types of RDBMS (ie. non-SQL Server ones), and data-sources (such as XML, flatfiles, Excel Spreadsheets...)</p>
<ul>
<li><strong>SSIS</strong> Explicitly with <strong>Business Development Management Studio</strong> - direct datapump or using delimited file intermeditary. </li>
<li><strong>SSIS</strong> Implicitly through <strong>SQL Management Studio</strong>, by right clicking the database1 on server1 > Tasks > Export, then completing the wizard. May work direct to server2, or using a flat-file intermeditary.</li>
<li><strong>.Net Programming</strong> with <strong>SqlBulkInsert</strong> (I believe the SSIS datapump uses such an object), I can go into more detail about this, if it interests you.</li>
</ul>
<p>Eg. of SQLBulkInsert (psedo-C# code)</p>
<pre><code>SqlConnection c = new SqlConnection("connectionStringForServer1Database1Here");
SqlConnection c2 = new SqlConnection("connectionStringForServer2Database1Here");
c.Open();
SqlCommand cm = new SqlCommand(c);
cm.CommandText = "select * from table1;";
using (SqlDataReader reader = cm.ExecuteReader())
{
using (SqlBulkInsert bc = new SqlBulkInsert(c))
{
c2.Open();
bc.DestinationTable = "table1";
bc.WriteToServer(reader);
}
}
</code></pre>
<p>Pretty cool huh? If speed/efficiency is a concern - SqlBulkInsert based approaches (Such as SSIS) are the best.</p>
<p><strong>Update - Modifying the destination table</strong></p>
<p>If you need to update the destination table, I recommend that you:</p>
<ol>
<li>Write to a staging table on the destination database (a temporary table, or proper table which you truncate before and after process), the latter is preferable. The former may be your only choice if you don't have CREATE TABLE rights. You can perform the transfer using any one of the above options.</li>
<li>Run a MERGE INTO command as per your requirements from the staging table to the destination table. This can Insert, Update and Delete as required very efficiently.</li>
</ol>
<p>Such a whole process could be enhanced with a sliding window (changes since last checked), only taking recently changed rows in the source an applying to the destination, this complicates the process, so you should at least accomplish the simpler one first. After completing a sliding window version, you could run the full-update one periodically to ensure there are no errors in the sliding window.</p> |
13,812,717 | Shoulda/RSpec matchers - conditional validation | <p>In my code I had the following validation with Shoulda matchers, which works fine:</p>
<pre><code>it { should validate_presence_of(:name) }
</code></pre>
<p>In my model, I've added the condition to my validation:</p>
<pre><code>validates_presence_of :name, :if => eligible?
</code></pre>
<p>Is it possible to reflect it in the validations?</p>
<p>I've tried looking at <a href="https://github.com/thoughtbot/shoulda-matchers" rel="noreferrer">documentation</a> for shoulda matchers, but haven't been able to locate the solution.</p>
<p>Many thanks!</p> | 13,812,867 | 1 | 0 | null | 2012-12-11 02:31:31.437 UTC | 17 | 2015-12-04 10:04:57.52 UTC | null | null | null | null | 872,514 | null | 1 | 71 | ruby-on-rails|ruby|rspec|shoulda | 18,422 | <p>It doesn't appear that shoulda_matchers does this, but it's easy enough to write it yourself::</p>
<pre><code> context "if eligible" do
before { allow(subject).to receive(:eligible?).and_return(true) }
it { should validate_presence_of(:name) }
end
context "if ineligible" do
before { allow(subject).to receive(:eligible?).and_return(false) }
it { should_not validate_presence_of(:name) }
end
</code></pre> |
9,338,400 | Incorrect syntax near '1'. Expecting ID, QUOTED_ID, or '.' Error with SQL Pivot | <p>I have a table with stats for universities that looks like this:</p>
<pre><code>StatID | UniversityID | StatValue
1 | 1 | 100
2 | 1 | 90
3 | 1 | 80
1 | 2 | 50
2 | 2 | 55
</code></pre>
<p>I'd like a query to return something like this:</p>
<pre><code>(Rows are StatIDs, Columns are UniversityIDs)
StatID | 1 | 2 | 3
1 | 100 | 50 | NULL
2 | 90 | 55 | NULL
3 | 80 | NULL | NULL
</code></pre>
<p>Here's my query:</p>
<pre><code>SELECT StatID, 1, 2, 3
FROM
(SELECT StatID, UniversityID, StatValue FROM @table) up
PIVOT
(MAX(StatValue) FOR UniversityID IN (1, 2, 3)) AS pvt
ORDER BY StatisticID;
</code></pre>
<p>I get an error on <code>FOR UniversityID IN (1,</code> saying:</p>
<pre><code>Incorrect syntax near '1'. Expecting ID, QUOTED_ID, or '.'.
</code></pre>
<p>What am I doing wrong? Does it have something to do with an <code>int</code> as a column header?</p>
<p>I will be using this with ~260,000 rows (~300 columns and ~3,000 rows)</p> | 9,338,913 | 2 | 1 | null | 2012-02-18 03:59:27.513 UTC | 2 | 2012-02-18 05:44:22.757 UTC | 2012-02-18 05:30:36.157 UTC | null | 585,552 | null | 585,552 | null | 1 | 5 | sql|sql-server|sql-server-2008|pivot|pivot-table | 73,078 | <p>You have the synatx for the IN wrong:</p>
<pre><code>SELECT StatisticID, 1, 2, 3
FROM
(SELECT StatisticID, UniversityID, Value
FROM @table) up
PIVOT
(MAX(Value) FOR UniversityID IN ([1], [2], [3])) AS pvt
ORDER BY StatisticID;
</code></pre> |
9,203,858 | How do I use nested iterators with Mustache.js or Handlebars.js? | <p>I would like to use handlebars.js or mustache.js to iterate over a list of families, and then iterate over that family's members. Inside of both loops, I want to display properties of both. However, once I get into the second iteration, none of the family variables are visible. </p>
<pre><code>{{#each families}}
{{#each members}}
<p>{{ ( here I want a family name property ) }}</p>
<p>{{ ( here I want a member name property ) }}</p>
{{/each}}
{{/each}}
</code></pre>
<p>Is this possible? I'd greatly appreciate any help!</p> | 9,219,644 | 6 | 1 | null | 2012-02-09 00:38:46.517 UTC | 11 | 2019-11-21 10:23:31.123 UTC | 2012-02-09 08:44:06.493 UTC | null | 266,919 | null | 86,537 | null | 1 | 39 | javascript|handlebars.js|mustache | 38,159 | <p>You can nest sections easily with lists of objects. Use a data structure where <code>families</code> is a list that has an object <code>members</code> that has a list of any objects (or even more lists)like:</p>
<pre><code>{
"families" : [
{
"surname": "Jones",
"members": [
{"given": "Jim"},
{"given": "John"},
{"given": "Jill"}
]
},
{
"surname": "Smith",
"members": [
{"given": "Steve"},
{"given": "Sally"}
]
}
]
}
</code></pre>
<p>You would be able to populate a template like:</p>
<pre><code><ul>
{{#families}}
<li>{{surname}}
<ul>
{{#members}}
<li>{{given}}</li>
{{/members}}
</ul>
</li>
{{/families}}
</ul>
</code></pre>
<p>jsFiddle is currently down so here's the full working HTML with JS:</p>
<pre><code><!DOCTYPE html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.3.0/mustache.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function() {
var tpl = $('#fam').html(),
data = {
"families" : [
{
"surname": "Jones",
"members": [
{"given": "Jim"},
{"given": "John"},
{"given": "Jill"}
]
},
{
"surname": "Smith",
"members": [
{"given": "Steve"},
{"given": "Sally"}
]
}
]
},
html = Mustache.to_html(tpl, data);
$("#main").append(html);
});
</script>
</head>
<div id="main"></div>
<script type="template/text" id="fam">
<ul>
{{#families}}
<li>{{surname}}
<ul>
{{#members}}
<li>{{given}}</li>
{{/members}}
</ul>
</li>
{{/families}}
</ul>
</script>
</code></pre> |
45,995,784 | How to set compiler options with CMake in Visual Studio 2017 | <p>Visual Studio 2017 comes with full CMake integration. To learn about this combination, I was starting with this basic sample:</p>
<pre><code># CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project(foo)
add_executable(foo foo.cpp)
</code></pre>
<p>and</p>
<pre><code>// foo.cpp
int main() {}
</code></pre>
<p>This properly generates build scripts, and compiles and links with no issues. That was easy.</p>
<p>Trying to set compiler options, on the other hand, turned out to be anything but trivial. In my case I was attempting to set the warning level to 4.</p>
<p>The obvious solution</p>
<pre><code>add_compile_options("/W4")
</code></pre>
<p>didn't pan out as expected. The command line passed to the compiler now contains both <code>/W4</code> (as intended) as well as <code>/W3</code> (picked up from somewhere else), producing the following warning:</p>
<blockquote>
<pre><code>cl : Command line warning D9025: overriding '/W3' with '/W4'
</code></pre>
</blockquote>
<p>To work around this, I would need to <em>replace</em> any incompatible compiler option(s) instead of just adding one. CMake does not provide any immediate support for this, and the standard solution (as <a href="https://stackoverflow.com/q/2368811/1889329">this Q&A suggests</a>) seems to be:</p>
<pre><code>if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]")
string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4")
endif()
</code></pre>
<p>This, however, has two issues:</p>
<ul>
<li>It sets the global <code>CMAKE_CXX_FLAGS</code>, applying to all C++ targets. This may not be intended (not an issue for me right now).</li>
<li>It doesn't scale. For every compiler option to add, you would have to read up on incompatible options, and manually strip those first. This will inevitably fail<sup>1</sup>.</li>
</ul>
<p>My question is two-fold:</p>
<ol>
<li>Where does the CMake integration pick up default settings from, and can this be controlled?</li>
<li>How do you set compiler options in general? (If this is too broad a topic, I'd be happy for help on setting the warning level only.)</li>
</ol>
<p><hr/>
<sup>1</sup> <em>Incidentally, the solution I replicated fails to account for the <code>/Wall</code> option, that is incompatible with <code>/W4</code> as well.</em></p> | 46,000,520 | 3 | 4 | null | 2017-09-01 08:07:45.217 UTC | 11 | 2021-04-02 11:51:05.537 UTC | null | null | null | null | 1,889,329 | null | 1 | 26 | visual-c++|cmake|visual-studio-2017 | 38,559 | <p>The default settings for the compiler are picked up from standard module files located in the <code>Modules</code> directory of the CMake installation. The actual module file used depends on both the platform and the compiler. E.g., for Visual Studio 2017, CMake will load the default settings from the file <code>Windows-MSVC.cmake</code> and language specific settings from <code>Windows-MSVC-C.cmake</code> or <code>Windows-MSVC-CXX.cmake</code>.</p>
<p>To inspect the default settings, create a file <code>CompilerOptions.cmake</code> in the project directory with the following contents:</p>
<pre><code># log all *_INIT variables
get_cmake_property(_varNames VARIABLES)
list (REMOVE_DUPLICATES _varNames)
list (SORT _varNames)
foreach (_varName ${_varNames})
if (_varName MATCHES "_INIT$")
message(STATUS "${_varName}=${${_varName}}")
endif()
endforeach()
</code></pre>
<p>Then initialize the <a href="https://cmake.org/cmake/help/latest/variable/CMAKE_USER_MAKE_RULES_OVERRIDE.html" rel="noreferrer"><code>CMAKE_USER_MAKE_RULES_OVERRIDE</code></a> variable in your <code>CMakeLists.txt</code>:</p>
<pre><code># CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
set (CMAKE_USER_MAKE_RULES_OVERRIDE "${CMAKE_CURRENT_LIST_DIR}/CompilerOptions.cmake")
project(foo)
add_executable(foo foo.cpp)
</code></pre>
<p>When the project is configured upon opening the directory using <code>Open Folder</code> in Visual Studio 2017, the following information will be shown in the IDE's output window:</p>
<pre><code> ...
-- CMAKE_CXX_FLAGS_DEBUG_INIT= /MDd /Zi /Ob0 /Od /RTC1
-- CMAKE_CXX_FLAGS_INIT= /DWIN32 /D_WINDOWS /W3 /GR /EHsc
-- CMAKE_CXX_FLAGS_MINSIZEREL_INIT= /MD /O1 /Ob1 /DNDEBUG
-- CMAKE_CXX_FLAGS_RELEASE_INIT= /MD /O2 /Ob2 /DNDEBUG
-- CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT= /MD /Zi /O2 /Ob1 /DNDEBUG
...
</code></pre>
<p>So the warning setting <code>/W3</code> is picked up from the CMake variable <code>CMAKE_CXX_FLAGS_INIT</code> which then applies to all CMake targets generated in the project.</p>
<p>To control the warning level on the CMake project or target level, one can alter the <code>CMAKE_CXX_FLAGS_INIT</code> variable in the <code>CompilerOptions.cmake</code> by adding the following lines to the file:</p>
<pre><code>if (MSVC)
# remove default warning level from CMAKE_CXX_FLAGS_INIT
string (REGEX REPLACE "/W[0-4]" "" CMAKE_CXX_FLAGS_INIT "${CMAKE_CXX_FLAGS_INIT}")
endif()
</code></pre>
<p>The warning flags can then be controlled by setting the target compile options in <code>CMakeLists.txt</code>:</p>
<pre><code>...
add_executable(foo foo.cpp)
target_compile_options(foo PRIVATE "/W4")
</code></pre>
<p>For most CMake projects it makes sense to control the default compiler options in a rules override file instead of manually tweaking variables like <code>CMAKE_CXX_FLAGS</code>.</p>
<p>When making changes to the <code>CompilerOptions.cmake</code> file, it is necessary to recreate the build folder. When using Visual Studio 2017 in <code>Open Folder</code> mode, choose the command <code>Cache ... -> Delete Cache Folders</code> from the <code>CMake</code> menu and then <code>Cache ... -> Generate</code> from the <code>CMake</code> menu to recreate the build folder.</p> |
68,802,802 | Repository 'http://security.debian.org/debian-security buster/updates InRelease' changed its 'Suite' value from 'stable' to 'oldstable' | <p>Some of my GitHub Actions workflows started recently to return this error when installing Chromedriver:</p>
<pre class="lang-none prettyprint-override"><code>Get:1 http://security.debian.org/debian-security buster/updates InRelease [65.4 kB]
Get:2 http://deb.debian.org/debian buster InRelease [122 kB]
Get:3 http://deb.debian.org/debian buster-updates InRelease [51.9 kB]
Reading package lists...
E: Repository 'http://security.debian.org/debian-security buster/updates InRelease' changed its 'Suite' value from 'stable' to 'oldstable'
E: Repository 'http://deb.debian.org/debian buster InRelease' changed its 'Suite' value from 'stable' to 'oldstable'
E: Repository 'http://deb.debian.org/debian buster-updates InRelease' changed its 'Suite' value from 'stable-updates' to 'oldstable-updates'
Error: Process completed with exit code 100.
</code></pre>
<p>Here is my step implementation:</p>
<pre class="lang-yaml prettyprint-override"><code>jobs:
build:
runs-on: ubuntu-latest
container:
image: docker://guillaumefalourd/ritchiecli:py-3.8
steps:
- name: Install Chrome Driver
run: |
sudo apt-get update
sudo apt-get install -y unzip xvfb libxi6 libgconf-2-4 gnupg2
sudo curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add
sudo echo "deb https://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list
sudo apt-get -y update
sudo apt-get -y install google-chrome-stable
wget -N https://chromedriver.storage.googleapis.com/89.0.4389.23/chromedriver_linux64.zip -P ~/
unzip ~/chromedriver_linux64.zip -d ~/
rm ~/chromedriver_linux64.zip
sudo mv -f ~/chromedriver /usr/local/bin/chromedriver
sudo chown root:root /usr/local/bin/chromedriver
sudo chmod 0755 /usr/local/bin/chromedriver
</code></pre>
<p>Docker Image Implementation: <a href="https://github.com/GuillaumeFalourd/ritchie-docker-images/blob/master/py-3.8/Dockerfile" rel="noreferrer">docker://guillaumefalourd/ritchiecli:py-3.8</a></p>
<h2>What I tried</h2>
<ol>
<li><p>I read from <a href="https://www.reddit.com/r/debian/comments/ca3se6/for_people_who_gets_this_error_inrelease_changed/" rel="noreferrer">here</a> and <a href="https://superuser.com/questions/1456989/how-to-configure-apt-in-debian-buster-after-release">here</a> that adding <code>sudo apt-get --allow-releaseinfo-change update</code> or <code>sudo apt-get dist-upgrade</code> could resolve the problem, but even adding those to my workflow didn't resolve it.</p>
</li>
<li><p>I tried using this action <a href="https://github.com/marketplace/actions/setup-chromedriver" rel="noreferrer">setup-chromedriver</a> but it returned the same error when following the documentation:</p>
<pre class="lang-yaml prettyprint-override"><code>steps:
- uses: actions/checkout@v2
- uses: nanasess/setup-chromedriver@master
with:
# Optional: do not specify to match Chrome's version
chromedriver-version: '88.0.4324.96'
- run: |
export DISPLAY=:99
chromedriver --url-base=/wd/hub &
sudo Xvfb -ac :99 -screen 0 1280x1024x24 > /dev/null 2>&1 & # optional
</code></pre>
</li>
<li><p>As it seems to be related to <em><a href="https://en.wikipedia.org/wiki/Debian_version_history#Debian_10_(Buster)" rel="noreferrer">Debian 10</a> (Buster)</em> (?) I also tried to use another Ubuntu runner version as a runner (<code>ubuntu-18.04</code> instead of <code>ubuntu-latest</code>), but nothing changed, same error.</p>
</li>
</ol>
<h3>How can I resolve this issue?</h3>
<hr />
<hr/>
<h3>Answer</h3>
<p><em>I observed afterwards that the problem was happening at the first command : <code>sudo apt-get update</code> (and I was adding the other command after...).</em></p>
<p><em>Substituting it for <code>sudo apt-get --allow-releaseinfo-change update</code> resolved my problem.</em></p>
<p><em>Therefore the answer was not to add the <code>sudo apt-get --allow-releaseinfo-change update</code> to the step executed commands, but <strong>substituting</strong> the <code>sudo apt-get update</code> command for it.</em></p>
<pre class="lang-yaml prettyprint-override"><code>jobs:
build:
runs-on: ubuntu-latest
container:
image: docker://guillaumefalourd/ritchiecli:py-3.8
steps:
- name: Install Chrome Driver
run: |
sudo apt-get --allow-releaseinfo-change update
sudo apt-get install -y unzip xvfb libxi6 libgconf-2-4 gnupg2
sudo curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add
sudo echo "deb https://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list
sudo apt-get -y update
sudo apt-get -y install google-chrome-stable
wget -N https://chromedriver.storage.googleapis.com/89.0.4389.23/chromedriver_linux64.zip -P ~/
unzip ~/chromedriver_linux64.zip -d ~/
rm ~/chromedriver_linux64.zip
sudo mv -f ~/chromedriver /usr/local/bin/chromedriver
sudo chown root:root /usr/local/bin/chromedriver
sudo chmod 0755 /usr/local/bin/chromedriver
</code></pre> | 68,804,294 | 2 | 3 | null | 2021-08-16 12:25:54.043 UTC | 9 | 2022-08-02 03:54:26.783 UTC | 2021-09-11 19:23:55.33 UTC | null | 63,550 | null | 8,496,462 | null | 1 | 119 | shell|selenium-chromedriver|debian|github-actions|debian-buster | 64,633 | <p>I know you tried it with</p>
<pre class="lang-sh prettyprint-override"><code>apt-get --allow-releaseinfo-change update
</code></pre>
<p>but it worked for me.</p>
<p>This is my command in the dockerfile:</p>
<pre class="lang-sh prettyprint-override"><code>wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt-get --allow-releaseinfo-change update \
&& apt-get install -y google-chrome-unstable \
--no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
</code></pre>
<p>not required: <code>rm -rf /var/lib/apt/lists/*</code></p> |
34,201,527 | Disable *all* exception handling in ASP.NET Web API 2 (to make room for my own)? | <p>I want to wire up exception handling in a middleware component, something like this:</p>
<pre><code>public override async Task Invoke(IOwinContext context)
{
try
{
await Next.Invoke(context);
}
catch (Exception ex)
{
// Log error and return 500 response
}
}
</code></pre>
<p>However, some of the exceptions I would like to catch are being caught and converted to <code>HttpErrorResponse</code>s by the Web API pipeline before I can get to them. In the process, I lose a lot of details about the errors, so I can't get useful stack traces when debugging etc (the debugger doesn't even stop when the exception is thrown - I have to manually step through the code and see where it fails...).</p>
<p>I tried adding a custom exception handler with the following implementation:</p>
<pre><code>public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
var owinContext = context.Request.GetOwinContext();
owinContext.Set(Constants.ContextKeys.Exception, context.Exception);
return Task.FromResult(0);
}
</code></pre>
<p>registered through <code>config.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler());</code> in my startup configuration, but looking at it after executing <code>Next.Invoke(context)</code> through</p>
<pre><code>context.Get<Exception>(Constants.ContextKeys.Exception);
</code></pre>
<p><em>still</em> doesn't give me all the detail I want, as well as failing to stop at the fault point with the debugger.</p>
<p>Is there a way I can <em>completely</em> turn off <em>all</em> built-in error handling, so that my own middleware can take care of it?</p>
<p><strong>Clarification</strong>, since a lot of people seem to misunderstand what I'm after:</p>
<ul>
<li>The built-in error handling in Web API catches <em>some</em> (but not all) exceptions and rewrites them into 500 responses.</li>
<li>I want to catch <em>all</em> exceptions, do some logging, and <em>then</em> emit 500 responses <em>with the information I choose</em> (for most of them, see next bullet).</li>
<li>There are also some exceptions that signal business logic faults, for which I want to return 40x errors instead.</li>
<li>I want this to be at the top of the (app) pipeline, i.e. wrapping <em>everything</em> else in the request lifecycle</li>
<li>I want to handle this using OWIN, to make it portable to a possible future self-hosted scenario (i.e. it's not written in stone that this app will always be hosted on IIS - HTTP modules, Global.asax.cs et al are not relevant here).</li>
</ul> | 34,312,016 | 5 | 4 | null | 2015-12-10 12:08:25.533 UTC | 17 | 2017-02-13 23:21:59.467 UTC | 2017-02-13 23:21:59.467 UTC | null | 209,259 | null | 38,055 | null | 1 | 46 | c#|asp.net|asp.net-web-api|owin | 8,597 | <p><strong>Update</strong>: <a href="http://www.jayway.com/2016/01/08/improving-error-handling-asp-net-web-api-2-1-owin/" rel="nofollow noreferrer">I blogged about this</a>. When researching the blog post, I found some potential for improvement; I've updated the relevant parts of this answer. For more detail on why I think this is better than all other suggestions here, or the default behavior, read the entire post :)</p>
<hr>
<p>I have now gone with the following approach, which seems to work OK, even if not 100 % compliant with what I was looking for:</p>
<ul>
<li><p>Create a class <code>PassthroughExceptionHandler</code>:</p>
<pre><code>public class PassthroughExceptionHandler : IExceptionHandler
{
public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
{
// don't just throw the exception; that will ruin the stack trace
var info = ExceptionDispatchInfo.Capture(context.Exception);
info.Throw();
return Task.CompletedTask;
}
}
</code></pre></li>
<li><p>Let that class <em>replace</em> the <code>IExceptionHandler</code> service of Web API:</p>
<pre><code>config.Services.Replace(typeof(IExceptionHandler), new PassthroughExceptionHandler());
</code></pre></li>
<li><p>Create a middleware class which does what I want:</p>
<pre><code>public class ExceptionHandlerMiddleware
{
public override async Task Invoke(IOwinContext context)
{
try
{
await Next?.Invoke(context);
}
catch (Exception ex)
{
// handle and/or log
}
}
}
</code></pre></li>
<li><p>Register that middleware first in the stack:</p>
<pre><code>app.Use<ExceptionHandlerMiddleware>()
.UseStageMarker(PipelineStage.Authenticate)
// other middlewares omitted for brevity
.UseStageMarker(PipelineStage.PreHandlerExecute)
.UseWebApi(config);
</code></pre></li>
</ul>
<p><strike>I will still award the bounty to anyone who comes up with</strike> (bounty expired...) I'm still looking for a better solution, which, for example, breaks when an <em>unhandled</em> exception is thrown. (This approach makes VS break when I rethrow the exception in the handler, but the original call stack is lost; I have to set a breakpoint at the faulting line and debug again to be able to intercept the state when an exception is thrown.)</p> |
56,125,874 | how sort array with object by property use ngFor | <p>I neet to display in table sort data</p>
<pre><code>js
let array = [
{idx: number, name: string, btn: number, index: number},
{idx: number, name: string, btn: number, index: number},
{idx: number, name: string, btn: number, index: number}
]
html
<tr *ngFor="let ticket of array">
<td>{{ticket.name}}</td>
<td>{{ticket.btn}}</td>
<td>{{ticket.index}}</td>
<tr>
</code></pre>
<p>I need sort display by index value</p> | 56,125,972 | 5 | 4 | null | 2019-05-14 08:16:23.333 UTC | 1 | 2022-06-08 19:52:56.373 UTC | null | null | null | null | 10,639,866 | null | 1 | 14 | javascript|angular|sorting|ngfor | 45,013 | <pre><code>let array = [
{ idx: 1, name: 'a', btn: 1, index: 2 },
{ idx: 2, name: 'b', btn: 2, index: 3 },
{ idx: 3, name: 'c', btn: 3, index: 1 }
];
// descending
let newarr = array.sort((a, b) => b.index - a.index);
//ascending
let newarr = array.sort((a, b) => a.index - b.index);
console.log(newarr);
</code></pre> |
24,519,980 | Add data to ggvis tooltip that's contained in the input dataset but not directly in the vis | <p>This is my input dataset:</p>
<pre><code>> names(breakingbad.episodes)
[1] "season" "episode" "epnum" "epid" "title"
[6] "url.trakt" "firstaired.utc" "id.tvdb" "rating" "votes"
[11] "loved" "hated" "overview" "firstaired.posix" "year"
[16] "zrating.season" "src"
</code></pre>
<p>For my <code>ggvis</code>, I'm using the following variables <code>firstaired.posix</code> and <code>rating</code>: </p>
<pre><code>> str(breakingbad.episodes[c("firstaired.posix", "rating")])
'data.frame': 62 obs. of 2 variables:
$ firstaired.posix: POSIXct, format: "2008-01-21 02:00:00" "2008-01-28 02:00:00" "2008-02- 11 02:00:00" ...
$ rating : num 87 85 84 84 83 90 87 85 88 83 ...
</code></pre>
<p>I successfully created my <code>ggvis</code> with a tooltip containing the <code>rating</code> information like this:</p>
<pre><code>> breakingbad.episodes %>%
ggvis(x = ~firstaired.posix,
y = ~rating,
fill = ~season) %>%
layer_points() %>%
add_axis("x", title = "Airdate") %>%
add_axis("y", title = "Rating") %>%
add_legend("fill", title = "Season") %>%
add_tooltip(function(data){paste0("Rating: ", data$rating)}, "hover")
</code></pre>
<p>But I actually want the tooltip to contain more data, like the <code>epid</code> variable, so I tried:</p>
<pre><code>…
add_tooltip(function(data){paste0("Rating: ", data$rating, "\n", "Epid: ", as.character(data$epid))}, "hover")
</code></pre>
<p>…Using <code>as.character()</code> because <code>epid</code> is an ordered factor – But the part of the tooltip is empty. (I also noticed the linebreak I intended <code>\n</code> to insert is missing, but that's a different problem).</p>
<p>It looks like the cause of this problem is that the <code>vis</code> object created by piping my dataset into <code>ggvis</code> doesn't contain the information I want to display, at least that's why I gathered by looking through the output of <code>str()</code> on the first example. </p>
<p>EDIT: I solved that linebreak issue, so there's no need to point me to <code>?add_tooltip</code> – totally forgot about that.</p>
<p>EDIT: The accepted answer is working fine, even though it doesn't let me put arbitrary variables in the tooltip, it's pretty much what I need for my usecase, thanks!
Here's what I did in the end:</p>
<pre><code>breakingbad.episodes <- transform(breakingbad.episodes, id = paste0(epid, " - ", title))
breakingbad.episodes %>%
ggvis(x = ~firstaired.posix,
y = ~rating,
fill = ~season,
key := ~id) %>%
layer_points() %>%
add_axis("x", title = "Airdate") %>%
add_axis("y", title = "Rating") %>%
add_legend("fill", title = "Season") %>%
add_tooltip(all_values, "click")
</code></pre> | 24,528,087 | 2 | 3 | null | 2014-07-01 22:06:52.6 UTC | 8 | 2014-07-02 10:20:38.48 UTC | 2014-07-02 10:20:38.48 UTC | null | 409,362 | null | 409,362 | null | 1 | 11 | r|shiny|ggvis | 6,068 | <p>Yes, it's possible. Normally the client only sends back the columns of data that are actually in the plot. To get other columns, you should use a key to index into the original data: This is simple reproducible example</p>
<pre><code>library(ggvis)
mtc <- mtcars
mtc$id <- 1:nrow(mtc)
all_values <- function(x) {
if(is.null(x)) return(NULL)
row <- mtc[mtc$id == x$id, ]
paste0(names(row), ": ", format(row), collapse = "<br />")
}
mtc %>% ggvis(x = ~wt, y = ~mpg, key := ~id) %>%
layer_points() %>%
add_tooltip(all_values, "hover")
</code></pre> |
1,251,151 | How can make Django permission_required decorator not to redirect already logged-in users to login page, but display some message | <p>How can make Django permission_required decorator not to redirect already logged-in users to login page, but display some message like Insufficient permissions?</p>
<p>Thank you.</p> | 1,252,205 | 5 | 0 | null | 2009-08-09 10:59:29.23 UTC | 9 | 2020-09-30 16:22:27.633 UTC | null | null | null | null | 141,969 | null | 1 | 15 | django|decorator|django-authentication | 10,781 | <p>A quick and dirty solution would be to write your own decorator to do this. Something like this:</p>
<pre><code>decorator_with_arguments = lambda decorator: lambda *args, **kwargs: lambda func: decorator(func, *args, **kwargs)
@decorator_with_arguments
def custom_permission_required(function, perm):
def _function(request, *args, **kwargs):
if request.user.has_perm(perm):
return function(request, *args, **kwargs)
else:
request.user.message_set.create(message = "What are you doing here?!")
# Return a response or redirect to referrer or some page of your choice
return _function
</code></pre>
<p>You can then decorate your view thus:</p>
<pre><code>@custom_permission_required('my_perm')
def my_view(request, *args, **kwargs):
#Do stuff
</code></pre> |
836,511 | What are some techniques for migrating a large MFC application to WPF/.NET? | <p>I am currently working on a very large legacy MFC MDI application. It has a large number of UI elements - dockable toolbars, custom tree controls, context menus, etc. It is an image processing application so the main views render themselves using DirectX and OpenGL. The product is about 10 years old and one of the priorities here is to update the look and feel of it.</p>
<p>Knowing that Microsoft has done a good job of providing interoperability between C++/MFC and .NET I thought it would make sense to migrate the code base incrementally. What I'm struggling with now is where to start. </p>
<p>One approach is to rip out the MFC framework with WPF and reuse as much of the C++ code as we can. This will let us maximize the benefits of the WPF architecture but will mean a long development period until we're fully functional again.</p>
<p>Another approach is to replace MFC controls one at a time with their WPF counterparts. This will allow us to work incrementally. My concern with this approach is that it means there will be an awful lot of connection points between managed and unmanaged code and I'm not sure where to start with replacing things like the main menu and toolbars.</p>
<p>Or is there another option here I'm not seeing?</p>
<p>Any suggestions or links to information on this topic would be appreciated. </p>
<p><strong>Update:</strong> DavidK raised some excellent questions so I'm adding the motivations behind this.</p>
<p><em>1) Future development of the product</em> </p>
<p>This product is still being actively developed with new features getting added on a regular basis. I thought that it would make a lot of sense to try and slowly migrate towards C#/WPF. In my limited experience with C#/WPF I found the productivity gains to be amazing over working in C++/MFC.</p>
<p>The other big thing we're getting with WPF is the ability to take advantage of multi-head systems. MFC applications are limited to a single top level frame, making it very difficult to leverage multiple monitors.</p>
<p><em>2) Employee retention and recruitment</em></p>
<p>It's getting harder and harder to find developers who are willing to work on MFC. It's also important for the career development of the current developers to get exposure to newer technologies.</p> | 6,153,500 | 5 | 3 | null | 2009-05-07 19:20:02.737 UTC | 11 | 2011-09-04 11:47:19.493 UTC | 2011-05-27 14:19:14.88 UTC | null | 2,284 | null | 2,284 | null | 1 | 30 | c#|.net|c++|wpf|mfc | 8,991 | <p>Revisiting this because I have successfully replaced our top level MFC UI (the main frame, windows, and toolbars) with WPF.</p>
<p>As it turns out, our core drawing code merely needs to be handed an HWND to render into. This made it really easy to reuse the bulk of our existing C++ codebase.</p>
<p>Here's a quick rundown on the key pieces of the approach I took:</p>
<ul>
<li>Used the .NET <a href="http://msdn.microsoft.com/en-us/library/system.windows.interop.hwndhost.aspx" rel="noreferrer">HwndHost</a> class to host an HWND for the C++ drawing code to render into</li>
<li>Created C++/CLI wrappers for any native C++ code that needed to be exposed to the WPF/C# UI code</li>
<li>Left most of the MFC dialogs as-is in the native C++ code. This minimizes the amount of work needed to finish the UI. The MFC dialogs can be migrated to WPF over time.</li>
</ul>
<p>As a side note, we're using SandDock and SandRibbon from <a href="http://www.divelements.com/net/" rel="noreferrer">Divelements</a> and have been very happy with them so far.</p> |
681,133 | Why does heap space run out only when running JUnit tests? | <p>When running JUnit tests, I always seem to run into this error:</p>
<blockquote>
<p>eclipse outOfMemoryError: heap space</p>
</blockquote>
<p>I have monitored Eclipse with JConsole and heap memory peaks at about 150MB. I have set heap memory to 1GB.</p>
<p>I am using the following arguments when starting Eclipse:</p>
<pre>
-vm "C:\Program Files\Java\jre1.5.0_08\bin\javaw.exe" -vmargs -Xmx1024M
-XX:MaxPermSize=128M -Dcom.sun.management.jmxremote.port=8999
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false
</pre>
<p>Does anyone know what may be causing this issue? It happens only when running JUnit tests.</p> | 681,168 | 5 | 1 | null | 2009-03-25 11:15:33.883 UTC | 3 | 2015-04-16 07:44:59.687 UTC | 2011-02-23 21:14:02.66 UTC | null | 122,607 | null | 68,880 | null | 1 | 32 | java|eclipse|junit|out-of-memory | 48,719 | <p>Junit tests are run in a different vm as the Eclipse IDE. So it is that vm that is out of memory and not the Eclipse one.<br>
You can change the settings of the test vm in the run configurations of the test.<br>
You go to the run configurations and then under arguments, you can set the vm arguments.</p> |
723,199 | Why does my Eclipse project have phantom debugger breakpoints? | <p>I've got a small project which, when run in the Eclipse debugger, always seems to stop in FileInputStream.class line 106, where files are opened. There are no breakpoints set, but Eclipse behaves exactly as if I have a breakpoint here. If I clear all breakpoints, it still happens.</p>
<p>I have a second much-larger project in the same Eclipse workspace which does not suffer from this problem.</p>
<p>I just moved the smaller project off of my old Linux machine, where I developed it in Europa Eclipse and had this problem, onto my new Windows machine, where I continue to see the problem in Ganymede Eclipse. The problem persists across operating systems and across Eclipse versions, yet apparently not across projects. I don't get it! I grepped through every file in this project's directory and couldn't find anything that might be a file somehow directing Eclipse to stop in FileInputStream.</p>
<p><strong>Further info</strong>: the apparent breakpoint is actually not for line 106 of FileInputStream; it appears to be an Exception breakpoint for FileNotFoundException, being thrown from native code called from that line in FileInputStream. But again, I don't appear to have any breakpoints set at all. Are Exception breakpoints defined somewhere else?</p> | 723,313 | 5 | 2 | null | 2009-04-06 20:57:50.167 UTC | 22 | 2017-12-06 23:39:10.443 UTC | 2009-04-06 21:19:49.523 UTC | null | 18,103 | null | 18,103 | null | 1 | 79 | eclipse|debugging|breakpoints | 33,703 | <p>Did you try to un-select </p>
<pre><code>Window > Preferences > Java > Debug : Suspend execution on uncaught exceptions
</code></pre>
<p>? (as <a href="http://web.archive.org/web/20080913140934/http://dev.eclipse.org/newslists/news.eclipse.tools.jdt/msg20144.html" rel="noreferrer">mentioned in this thread</a>, for instance)</p>
<p><img src="https://i.stack.imgur.com/Dd5kp.jpg" alt="alt text"></p>
<p><strong>Why does Eclipse work that way?</strong></p>
<p>It <a href="http://dev.eclipse.org/mhonarc/lists/jdt-debug-dev/msg00077.html" rel="noreferrer">goes back to 2002</a>, when the breakpoint object hierarchy has been stripped down. </p>
<blockquote>
<p>In order to set a breakpoint, with the old API, a client required Java Model Objects - such as <code>IType</code>, <code>IField</code>, etc.<br>
With the new API, all that is required by the debug model is type names, field names, etc. </p>
<p>This allows clients to set breakpoints when Java Model Objects are not available.<br>
Clients now specify the resource to associate a breakpoint with (before we constrained it to the associated Java Model resources).</p>
<p><strong>Breakpoints can now also be "hidden"</strong>. That is, they need not be registered with the breakpoint manager.<br>
Breakpoints can also be selectively persisted (markers only allowed all/none of a marker type to be persisted).<br>
This makes the debug model more flexible, and gives clients more building blocks. </p>
<p>This has also simplified some part of our Java debug implementation - for example, <strong>the feature "<code>suspend on any uncaught exception</code>", simply sets a breakpoint for the type named "<code>java.lang.Throwable</code>", rather than a specific <code>IType</code> in a specific project</strong>.<br>
<strong>The breakpoint is not registered with the breakpoint manager (i.e. <em>hidden</em>) - it is only known and used by one client</strong>.<br>
Another example is the "<code>run to line breakpoint</code>". The <code>IJavaRunToLineBreakpoint</code> has been removed, as its special functionality is no longer required. Now, the Java debug ui simply creates a "line breakpoint" that is hidden, non persisted, and has a hit count of 1. This is an example of providing building blocks to clients.</p>
</blockquote> |
983,202 | Oracle 11g SQL to get unique values in one column of a multi-column query | <p>Given a table <strong>A</strong> of people, their native language, and other columns C3 .. C10 represented by <strong>...</strong></p>
<h3>Table A</h3>
<pre>
PERSON LANGUAGE ...
bob english
john english
vlad russian
olga russian
jose spanish
</pre>
<p>How do I construct a query which selects all columns of one row for each distinct language?</p>
<h3>Desired Result</h3>
<pre>
PERSON LANGUAGE ...
bob english
vlad russian
jose spanish
</pre>
<p>It doesn't matter to me which row of each distinct language makes the result. In the result above, I chose the lowest row number of each language.</p> | 983,513 | 6 | 0 | null | 2009-06-11 19:42:31.943 UTC | 9 | 2012-02-24 20:54:49.253 UTC | null | null | null | null | 115,596 | null | 1 | 27 | sql|oracle|distinct | 124,395 | <p>Eric Petroelje almost has it right:</p>
<pre><code>SELECT * FROM TableA
WHERE ROWID IN ( SELECT MAX(ROWID) FROM TableA GROUP BY Language )
</code></pre>
<p>Note: using ROWID (row unique id), not ROWNUM (which gives the row number within the result set)</p> |
1,241,819 | What does "=>" mean in PHP? | <p>What does the <code>=></code> operator mean in the following code?</p>
<pre><code>foreach ($user_list as $user => $pass)
</code></pre>
<p>The code is a comment at PHP.net.
The user does not specify the value of <code>$user_list</code>, <code>$user</code> or <code>$pass</code>.
I normally see that <code>=></code> means equal or greater than.</p>
<p>However, I am not sure about its purpose here because it is not assigned.
I read the code as </p>
<ol>
<li>process a list of users in integers</li>
<li>such that the value of each user is equal or greater than password </li>
</ol>
<p>The above does not make sense to me.</p> | 1,241,831 | 6 | 4 | null | 2009-08-06 22:12:33.53 UTC | 41 | 2020-05-21 22:00:55.84 UTC | 2020-05-21 22:00:55.84 UTC | null | 506,230 | null | 54,964 | null | 1 | 108 | php | 125,714 | <p><code>=></code> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to <code>$user</code> and the value to <code>$pass</code>.</p>
<p>Example:</p>
<pre><code>$user_list = array(
'dave' => 'apassword',
'steve' => 'secr3t'
);
foreach ($user_list as $user => $pass) {
echo "{$user}'s pass is: {$pass}\n";
}
// Prints:
// "dave's pass is: apassword"
// "steve's pass is: secr3t"
</code></pre>
<p>Note that this can be used for numerically indexed arrays too.</p>
<p>Example:</p>
<pre><code>$foo = array('car', 'truck', 'van', 'bike', 'rickshaw');
foreach ($foo as $i => $type) {
echo "{$i}: {$type}\n";
}
// prints:
// 0: car
// 1: truck
// 2: van
// 3: bike
// 4: rickshaw
</code></pre> |
68,900,763 | How to update pandas DataFrame.drop() for Future Warning - all arguments of DataFrame.drop except for the argument 'labels' will be keyword-only | <p>The following code:</p>
<pre><code>df = df.drop('market', 1)
</code></pre>
<p>generates the warning:</p>
<blockquote>
<p>FutureWarning: In a future version of pandas all arguments of DataFrame.drop except for the argument 'labels' will be keyword-only</p>
</blockquote>
<p><code>market</code> is the column we want to drop, and we pass the <code>1</code> as a second parameter for axis (0 for index, 1 for columns, so we pass 1).</p>
<p>How can we change this line of code now so that it is not a problem in the future version of pandas / to resolve the warning message now?</p> | 68,900,782 | 2 | 9 | null | 2021-08-24 01:31:40.733 UTC | 5 | 2022-05-26 17:03:44.17 UTC | 2022-02-13 19:55:38.743 UTC | null | 15,497,888 | null | 5,573,294 | null | 1 | 30 | python|pandas|dataframe | 21,525 | <p>From the documentation, <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html" rel="noreferrer"><code>pandas.DataFrame.drop</code></a> has the following parameters:</p>
<p>Parameters</p>
<blockquote>
<ul>
<li><p><strong>labels</strong>: single label or list-like Index or column labels to drop.</p>
</li>
<li><p><strong>axis</strong>: {0 or ‘index’, 1 or ‘columns’}, default 0 Whether to drop labels from the index (0 or ‘index’) or columns (1 or ‘columns’).</p>
</li>
<li><p><strong>index</strong>: single label or list-like Alternative to specifying axis (labels, axis=0 is equivalent to index=labels).</p>
</li>
<li><p><strong>columns</strong>: single label or list-like Alternative to specifying axis (labels, axis=1 is equivalent to columns=labels).</p>
</li>
<li><p><strong>level</strong>: int or level name, optional For MultiIndex, level from which the labels will be removed.</p>
</li>
<li><p><strong>inplace</strong>: bool, default False If False, return a copy. Otherwise, do operation inplace and return None.</p>
</li>
<li><p><strong>errors</strong>: {‘ignore’, ‘raise’}, default ‘raise’ If ‘ignore’, suppress error and only existing labels are dropped.</p>
</li>
</ul>
</blockquote>
<p>Moving forward, only <code>labels</code> (the first parameter) can be positional.</p>
<hr />
<p>So, for this example, the <code>drop</code> code should be as follows:</p>
<pre><code>df = df.drop('market', axis=1)
</code></pre>
<p>or (more legibly) with <code>columns</code>:</p>
<pre><code>df = df.drop(columns='market')
</code></pre> |
42,203,673 | In Python, why is a tuple hashable but not a list? | <p>Here below when I try to hash a list, it gives me an error but works with a tuple. Guess it has something to do with immutability. Can someone explain this in detail ?</p>
<p>List</p>
<pre><code> x = [1,2,3]
y = {x: 9}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
</code></pre>
<p>Tuple</p>
<pre><code>z = (5,6)
y = {z: 89}
print(y)
{(5, 6): 89}
</code></pre> | 42,203,721 | 6 | 4 | null | 2017-02-13 12:08:28.117 UTC | 13 | 2021-03-03 04:12:24.547 UTC | 2017-02-13 12:11:35.897 UTC | null | 67,579 | null | 4,735,926 | null | 1 | 40 | python | 18,907 | <p>Dicts and other objects use <a href="https://stackoverflow.com/questions/14535730/what-do-you-mean-by-hashable-in-python">hashes</a> to store and retrieve items really quickly. The mechanics of this all happens "under the covers" - you as the programmer don't need to do anything and Python handles it all internally. The basic idea is that when you create a dictionary with <code>{key: value}</code>, Python needs to be able to hash whatever you used for <code>key</code> so it can store and look up the value quickly.</p>
<p>Immutable objects, or objects that can't be altered, are hashable. They have a single unique value that never changes, so python can "hash" that value and use it to look up dictionary values efficiently. Objects that fall into this category include strings, tuples, integers and so on. You may think, "But I can change a string! I just go <code>mystr = mystr + 'foo'</code>," but in fact what this does is create a <em>new</em> string instance and assigns it to <code>mystr</code>. It doesn't modify the <em>existing</em> instance. Immutable objects never change, so you can always be sure that when you generate a hash for an immutable object, looking up the object by its hash will always return the same object you started with, and not a modified version.</p>
<p>You can try this for yourself: <code>hash("mystring")</code>, <code>hash(('foo', 'bar'))</code>, <code>hash(1)</code></p>
<p>Mutable objects, or objects that <em>can</em> be modified, <em>aren't</em> hashable. A list can be modified in-place: <code>mylist.append('bar')</code> or <code>mylist.pop(0)</code>. You can't safely hash a mutable object because you can't guarantee that the object hasn't changed since you last saw it. You'll find that <code>list</code>, <code>set</code>, and other mutable types don't have a <code>__hash__()</code> method. Because of this, you can't use mutable objects as dictionary keys:</p>
<pre><code>>>> hash([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
</code></pre>
<p><a href="https://stackoverflow.com/users/6419007/eric-duminil">Eric Duminil</a>'s answer provides a great example of the unexpected behaviour that arises from using mutable objects as dictionary keys</p> |
30,795,682 | Error using databinding in android | <p>I am trying to test data binding as given in the guide <a href="https://developer.android.com/tools/data-binding/guide.html" rel="noreferrer">here</a>.
I have included this in my build.gradle file (of module app) :</p>
<pre><code>compileSdkVersion 'android-MNC'
buildToolsVersion '23.0.0 rc2'
</code></pre>
<p>In the project build.gradle file, I have included this in my dependencies :</p>
<pre><code>classpath "com.android.tools.build:gradle:1.3.0-beta2"
classpath "com.android.databinding:dataBinder:1.0-rc0"
</code></pre>
<p>The layout file is exactly the same as the one given in the guide.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="com.example.User"/>
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.firstName}"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.lastName}"/>
</LinearLayout>
</layout>
</code></pre>
<p>Initially it gave an error <code>Element layout does not have the required attribute layout_width and layout_height</code>. </p>
<p>I tried to fix it by assigning match_parent to both. Then I got the error
<code>Error parsing XML: duplicate attribute</code> on the lines where i assigned <code>layout_height</code> and <code>layout_width</code> to the linear layout.</p>
<p>Again I tried to fix this by removing these attributes. Now every time I try to compile, I see this- <code>error: package my.package.name.databinding</code> does not exist.</p>
<p>The code completion is working perfectly in my Fragment where I am trying to use this layout.</p>
<p>So what did I miss ?</p> | 32,691,502 | 12 | 4 | null | 2015-06-12 05:11:17.51 UTC | 3 | 2018-10-01 08:13:43.057 UTC | null | null | null | null | 2,729,235 | null | 1 | 33 | android|android-fragments|data-binding | 30,418 | <p>removing <code>apply plugin: 'com.neenbedankt.android-apt'</code> from my build.gradle solved my problem. </p> |
20,908,620 | How to obtain connection ID of signalR client on the server side? | <p>I need to get the connection ID of a client. I know you can get it from the client side using <code>$.connection.hub.id</code>. What I need is to get in while in a web service I have which updates records in a database, in turn displaying the update on a web page. I am new to signalR and stackoverflow, so any advice would be appreciated. On my client web page I have this:</p>
<pre><code><script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var notify = $.connection.notificationHub;
// Create a function that the hub can call to broadcast messages.
notify.client.broadcastMessage = function (message) {
var encodedMsg = $('<div />').text(message).html();// Html encode display message.
$('#notificationMessageDisplay').append(encodedMsg);// Add the message to the page.
};//end broadcastMessage
// Start the connection.
$.connection.hub.start().done(function () {
$('#btnUpdate').click(function () {
//call showNotification method on hub
notify.server.showNotification($.connection.hub.id, "TEST status");
});
});
});//End Main function
</script>
</code></pre>
<p>everything works up until I want to update the page using signalR. The show notification function in my hub is this:</p>
<pre><code>//hub function
public void showNotification(string connectionId, string newStatus){
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<notificationHub>();
string connection = "Your connection ID is : " + connectionId;//display for testing
string statusUpdate = "The current status of your request is: " + newStatus;//to be displayed
//for testing, you can display the connectionId in the broadcast message
context.Clients.Client(connectionId).broadcastMessage(connection + " " + statusUpdate);
}//end show notification
</code></pre>
<p>how can I send the connectionid to my web service?</p>
<p>Hopefully I'm not trying to do something impossible. Thanks in advance.</p> | 57,409,253 | 4 | 6 | null | 2014-01-03 16:47:21.033 UTC | 23 | 2022-09-21 10:15:38.82 UTC | 2014-01-03 20:26:45.153 UTC | null | 727,208 | null | 3,157,948 | null | 1 | 52 | c#|asp.net-mvc|signalr | 96,455 | <p>Taylor's answer works, however, it doesn't take into consideration a situation where a user has multiple web browser tabs opened and therefore has multiple different connection IDs.</p>
<p>To fix that, I created a Concurrent Dictionary where the dictionary key is a user name and the value for each key is a List of current connections for that given user.</p>
<pre><code>public static ConcurrentDictionary<string, List<string>> ConnectedUsers = new ConcurrentDictionary<string, List<string>>();
</code></pre>
<p>On Connected - Adding a connection to the global cache dictionary:</p>
<pre><code>public override Task OnConnected()
{
Trace.TraceInformation("MapHub started. ID: {0}", Context.ConnectionId);
var userName = "testUserName1"; // or get it from Context.User.Identity.Name;
// Try to get a List of existing user connections from the cache
List<string> existingUserConnectionIds;
ConnectedUsers.TryGetValue(userName, out existingUserConnectionIds);
// happens on the very first connection from the user
if(existingUserConnectionIds == null)
{
existingUserConnectionIds = new List<string>();
}
// First add to a List of existing user connections (i.e. multiple web browser tabs)
existingUserConnectionIds.Add(Context.ConnectionId);
// Add to the global dictionary of connected users
ConnectedUsers.TryAdd(userName, existingUserConnectionIds);
return base.OnConnected();
}
</code></pre>
<p>On disconnecting (closing the tab) - Removing a connection from the global cache dictionary:</p>
<pre><code>public override Task OnDisconnected(bool stopCalled)
{
var userName = Context.User.Identity.Name;
List<string> existingUserConnectionIds;
ConnectedUsers.TryGetValue(userName, out existingUserConnectionIds);
// remove the connection id from the List
existingUserConnectionIds.Remove(Context.ConnectionId);
// If there are no connection ids in the List, delete the user from the global cache (ConnectedUsers).
if(existingUserConnectionIds.Count == 0)
{
// if there are no connections for the user,
// just delete the userName key from the ConnectedUsers concurent dictionary
List<string> garbage; // to be collected by the Garbage Collector
ConnectedUsers.TryRemove(userName, out garbage);
}
return base.OnDisconnected(stopCalled);
}
</code></pre> |
21,159,301 | QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota | <p>Using LocalStorage on iPhone with iOS 7 throws this error. I've been looking around for a resolvant, but considering I'm not even browsing in private, nothing is relevant.</p>
<p>I don't understand why localStorage would be disabled by default in iOS 7, but it seems it is? I've tested on other websites as well, but with no luck. I even tried testing it using this website: <a href="http://arty.name/localstorage.html">http://arty.name/localstorage.html</a>, but it doesn't seem like it's saving anything at all for some weird reason.</p>
<p>Has anyone had the same problem, only they've had luck fixing it? Should I switch my storage method?</p>
<p>I tried hard-debugging it by only storing a few lines of information, but to no avail. I used the standard <code>localStorage.setItem()</code> function to save.</p> | 23,453,866 | 9 | 6 | null | 2014-01-16 10:35:52.613 UTC | 45 | 2018-06-05 08:51:10.27 UTC | null | null | null | null | 1,478,808 | null | 1 | 226 | javascript|iphone|html|local-storage | 143,585 | <p>This can occur when Safari is in private mode browsing. While in private browsing, local storage is not available at all.</p>
<p>One solution is to warn the user that the app needs non-private mode to work.</p>
<p>UPDATE: This has been fixed in <a href="https://bugs.webkit.org/show_bug.cgi?id=157010" rel="noreferrer">Safari 11</a>, so the behaviour is now aligned with other browsers.</p> |
18,177,351 | How to display image inside web form from Byte Array with C# | <p>This is my code, all it does is clear the web page and draw the image, so the rest of the form disappears! I need to show the image inside the form.</p>
<p>This is my User Control to display the images:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (Session["ObjHoteles"] == null)
{
Label1.Text = "Por favor, primero seleccione un hotel para desplegar las fotos.";
}
else
{
if (!IsPostBack)
{
List<Byte[]> ArrayFotos = new List<Byte[]>();
string NombreDelHotel = "";
Hoteles Hotel1 = (Hoteles)Session["ObjHoteles"];
NombreDelHotel = Hotel1.NombreHotel;
ArrayFotos = Persistencia.PersistenciaFotos.FotosDeHotel(NombreDelHotel);
Session["CantFotos"] = ArrayFotos.Count();
Byte[] Foto = ArrayFotos[0];
Response.Buffer = true;
Response.Clear();
Response.ContentType = "image/jpeg";
Response.Expires = 0;
Response.BinaryWrite(Foto);
Session["NumFoto"] = 0;
}
else
{
List<Byte[]> ArrayFotos = new List<Byte[]>();
string NombreDelHotel = "";
Hoteles Hotel1 = (Hoteles)Session["ObjHoteles"];
NombreDelHotel = Hotel1.NombreHotel;
ArrayFotos = Persistencia.PersistenciaFotos.FotosDeHotel(NombreDelHotel);
Session["CantFotos"] = ArrayFotos.Count();
Byte[] Foto = ArrayFotos[(int)Session["NumFoto"]];
Response.Buffer = true;
Response.Clear();
Response.ContentType = "image/jpeg";
Response.Expires = 0;
Response.BinaryWrite(Foto);
}
}
</code></pre>
<p>I need to find a way that doesnt clear all the page, just draw the image inside the user control.</p> | 18,177,430 | 3 | 1 | null | 2013-08-11 22:29:25.61 UTC | 3 | 2014-10-29 08:52:07.67 UTC | 2014-10-29 08:52:07.67 UTC | null | 2,284,676 | null | 2,284,676 | null | 1 | 9 | c#|asp.net|webforms | 46,272 | <p>You could write a page .aspx or a handler maybe .ashx that send the content of the picture back to the browser. You could pass information in the url.
Then use the url to this page with an html tag or html control to display it.</p>
<p>EDIT:
You need to use a Control. You could convert the binary data to base64 and output the content to the html page.</p>
<p>I give you an example with an img html tag:</p>
<pre><code><img alt="" src="data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAsMAAAGhCAIAAAALOi7ZAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QgLEhM6PUSGrwAAIABJREFUeNq8vcuSLEmWHKZ6jnlEZt5761Z3T/eAHAICAYRcEALsuOCWPzbzDfwP/gKXWJACoRDCBSkEBgPhADKY7qnu+4wIdztHuThmHh55q2t6ho+SlpaqyMwID3ez89CjqsY//dM//bM/+zMc/pGE3//PT/z09/1I0t/1Rz/x+o9+0I++vv/n8fU/8MW/9U9+9JVvL/v/u1cy86cv5ttfePXKq//8fTfhp+/qT3/oq8v+6V/+Ay/v25/+4X/46nqO"/>
</code></pre>
<p>You can also use base64 encoding for image with CSS:</p>
<pre><code>background-image: url(data:image/jpeg;base64,IVB)
</code></pre>
<p>To convert into base64 from C# you can use:</p>
<pre><code>using System;
</code></pre>
<p>and:</p>
<pre><code>Convert.ToBase64String(Foto);
</code></pre> |
1,567,935 | How to do Inheritance Modeling in Relational Databases? | <p>My question is regarding Inheritance modeling in Relational Database Systems. I have canonical data model and in that I have some fields related to pricing of product inheriting certain attributes from product table and I want to model this inheritance in MySQL relational database and so, </p>
<p>"How can we do Inheritance Modeling in Relational Databases ?"</p>
<p>Thanks. </p> | 1,568,007 | 5 | 0 | null | 2009-10-14 17:52:52.023 UTC | 27 | 2020-10-20 03:47:46.63 UTC | 2014-06-18 14:46:41.497 UTC | null | 1,478,085 | null | 164,299 | null | 1 | 41 | mysql|database|inheritance|data-modeling|class-table-inheritance | 46,023 | <p>Martin Fowler discusses this extensively in his book Patterns of Enterprise Application Architecture book. Get this book and look into:</p>
<ol>
<li><a href="http://martinfowler.com/eaaCatalog/singleTableInheritance.html" rel="noreferrer">Single Table Inheritance</a></li>
</ol>
<blockquote>
<p><a href="https://i.stack.imgur.com/SlpPi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SlpPi.png" alt="Blockquote" /></a></p>
</blockquote>
<ol start="2">
<li><a href="http://martinfowler.com/eaaCatalog/classTableInheritance.html" rel="noreferrer">Class Table Inheritance</a></li>
</ol>
<blockquote>
<p><a href="https://i.stack.imgur.com/8EsSu.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/8EsSu.gif" alt="enter image description here" /></a></p>
</blockquote>
<ol start="3">
<li><a href="http://martinfowler.com/eaaCatalog/concreteTableInheritance.html" rel="noreferrer">Concrete Table Inheritance</a></li>
</ol>
<blockquote>
<p><a href="https://i.stack.imgur.com/1WGHO.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/1WGHO.gif" alt="Blockquote" /></a></p>
</blockquote>
<p>The Website should give you some idea. You might also want to read the section on <a href="http://martinfowler.com/eaaCatalog/inheritanceMappers.html" rel="noreferrer">inheritance mappers</a>. Each of the different approaches have their pros and cons so choose wisely.</p> |
2,023,032 | catch exception by pointer in C++ | <p>I found that there are three ways to catch an exception, what are the differences?</p>
<p>1) catch by value;</p>
<p>2) catch by reference;</p>
<p>3) catch by pointer;</p>
<p>I only know that catch by value will invoke two copies of the object, catch by reference will invoke one. So how about catch by pointer? When to use catch by pointer? In addition to throw an object, can I throw a pointer to an object like this?</p>
<pre><code>class A {}
void f() {
A *p = new A();
throw p;
}
</code></pre> | 2,023,045 | 5 | 2 | null | 2010-01-07 19:27:51.187 UTC | 23 | 2010-01-08 00:06:24.177 UTC | 2010-01-08 00:06:24.177 UTC | null | 216,063 | null | 233,254 | null | 1 | 53 | c++|exception-handling|throw|try-catch | 23,116 | <p><strong>The recommended way is to throw by value and catch by reference</strong>.</p>
<p>Your example code throws a pointer, which is a bad idea since you would have to manage memory at the catch site.</p>
<p>If you really feel you should throw a pointer, use a smart pointer such as <code>shared_ptr</code>.</p>
<p><strong>Anyway, Herb Sutter and Alexei Alexandrescu explain that really well in their C++ Coding Standards book which I paraphrased.</strong></p>
<p>See <a href="http://www.informit.com/articles/article.aspx?p=373339" rel="noreferrer">C++ Coding Standards: Throw by Value, Catch by Reference</a>.</p> |
2,138,574 | java - path to trustStore - set property doesn't work? | <p>I've setup a self-signed certificate to test an ssl java connection - however, it is refusing to locate the java trustStore. I've saved copies of it in /Java/jre6/lib/security in addition to the folder where the classes are compiled to (im using netbeans) and also to /java/jre6/bin
none of the above appears to work, because when i run the following - trustStore = null.</p>
<pre><code>public class ShowTrustStore {
public static void main(String[] args) {
System.setProperty("javax.net.ssl.keyStore", "keystore.jks");
System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");
System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
String trustStore = System.getProperty("javax.net.ssl.trustStore");
if (trustStore == null) {
System.out.println("javax.net.ssl.trustStore is not defined");
} else {
System.out.println("javax.net.ssl.trustStore = " + trustStore);
}
}
}
</code></pre>
<p>how to set the path correctly?</p>
<p>**********UPDATE************
Using the getFile() method and some more debug data:</p>
<pre><code>package ssltest;
public class Main {
public static void main(String[] args) {
// System.setProperty("javax.net.ssl.keyStore", "/keystore.jks");
// System.setProperty("javax.net.ssl.trustStrore", "/java.home/cacerts.jks");
// System.setProperty("javax.net.ssl.keyStorePassword", "changeit");
// System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
try {
Main.class.getResource("trustStore.jks").getFile();
} catch (Exception e) {
e.printStackTrace();
}
String trustStore = System.getProperty("javax.net.ssl.trustStore");
if (trustStore == null) {
String storeLoc;
storeLoc = System.getProperty("java.class.path");
System.out.println("classpath: " + storeLoc);
}
trustStore = System.getProperty("javax.net.ssl.trustStore");
if (trustStore == null) {
System.out.println("javax.net.ssl.trustStore is not defined");
} else {
System.out.println("javax.net.ssl.trustStore = " + trustStore);
}
}
}
</code></pre>
<p>run:
java.lang.NullPointerException
classpath: C:\Users\Main\Documents\NetBeansProjects\sslTest\build\classes;C:\Users\Main\Documents\NetBeansProjects\sslTest\src
at ssltest.Main.main(Main.java:15)
javax.net.ssl.trustStore is not defined
BUILD SUCCESSFUL (total time: 0 seconds)</p> | 2,138,670 | 5 | 1 | null | 2010-01-26 09:48:14.98 UTC | 24 | 2021-04-17 13:34:37.513 UTC | 2018-04-10 04:36:48.653 UTC | null | 3,042,952 | null | 207,201 | null | 1 | 53 | java|ssl|keystore|jsse|truststore | 300,415 | <p>You have a typo - it is <code>trustStore</code>.</p>
<p>Apart from setting the variables with <code>System.setProperty(..)</code>, you can also use</p>
<pre><code>-Djavax.net.ssl.keyStore=path/to/keystore.jks
</code></pre> |
1,428,911 | Detecting EOF in C | <p>I am using the following C code to take input from user until EOF occurs, but problem is this code is not working, it terminates after taking first input. Can anyone tell me whats wrong with this code. Thanks in advance.</p>
<pre><code>float input;
printf("Input No: ");
scanf("%f", &input);
while(!EOF)
{
printf("Output: %f", input);
printf("Input No: ");
scanf("%f", &input);
}
</code></pre> | 1,428,924 | 6 | 1 | null | 2009-09-15 18:31:08 UTC | 4 | 2015-08-01 13:04:02.253 UTC | 2013-06-12 15:24:02.72 UTC | null | 648,658 | null | 146,603 | null | 1 | 30 | c|stdio | 141,533 | <p><code>EOF</code> is just a macro with a value (usually -1). You have to test something against <code>EOF</code>, such as the result of a <code>getchar()</code> call.</p>
<p>One way to test for the end of a stream is with the <code>feof</code> function.</p>
<pre><code>if (feof(stdin))
</code></pre>
<p>Note, that the 'end of stream' state will only be set <strong>after</strong> a failed read.</p>
<p>In your example you should probably check the return value of scanf and if this indicates that no fields were read, then check for end-of-file.</p> |
2,098,318 | Error referencing an inner class View in layout/main.xml | <p>Grrr...</p>
<p>I create a subclass of view as an inner class in my Activity. Before I simply linked to this view from my activity with:</p>
<pre><code>setContentView(new CustomView(this));
</code></pre>
<p>without problems.</p>
<p>Now, however, my view is getting more complex so I am making it part of a FrameLayout so that I can make this the base view and add a Spinner widget on top of it. The problem is, when I do this I get an error:</p>
<pre><code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.grafightscratch.ochemmer/com.grafightscratch.ochemmer.MoleculeTablet}: android.view.InflateException: Binary XML file line #4: Error inflating class com.grafightscratch.ochemmer.MoleculeTablet.MoleculeTabletView
...
Caused by: android.view.InflateException: Binary XML file line #4: Error inflating class com.grafightscratch.ochemmer.MoleculeTablet.MoleculeTabletView
...
Caused by: java.lang.ClassNotFoundException: com.grafightscratch.ochemmer.MoleculeTablet.MoleculeTabletView in loader dalvik.system.PathClassLoader@43b74a28
</code></pre>
<p>So- this view worked before when I linked to it directly, but when I tried to add it in the main.xml file as part of a framelayout I got the above error. I also tried putting into a layout with only it being displayed via:</p>
<pre><code><com.grafightscratch.ochemmer.MoleculeTablet.MoleculeTabletView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/molecule_tablet_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</code></pre>
<p>Nothing works. I keep getting the InflateException/ClassNotFoundException errors. It complains about "line #3" in the binary XML file, and if it is talking about main.xml that is the package declaration which I have triple checked.</p>
<p><strong>EDIT</strong>
I tried making this view a separate class (ie- not an inner class) and it works. After some searching around I found some posts saying that the xml tag should look like this:</p>
<pre><code><com.grafightscratch.ochemmer.MoleculeTablet$MoleculeTabletView ...>
</code></pre>
<p>Ie, a dollar sign should be used to separate the innerclass from the main class. However, Eclipse barfs on this, calls it an error, and refuses to let me build or deploy with that character there. So now the question becomes: how does one reference a View that is an inner class?</p> | 2,100,111 | 6 | 0 | null | 2010-01-20 00:44:47.36 UTC | 14 | 2017-09-27 07:04:11.703 UTC | 2010-01-20 08:07:31.677 UTC | null | 253,575 | null | 253,575 | null | 1 | 61 | android|layout|view | 30,223 | <p>For inner classes the syntax becomes:</p>
<pre><code><view class="com.grafightscratch.ochemmer.MoleculeTablet$MoleculeTabletView" />
</code></pre>
<p>The reason is that $ is an illegal character in XML tags. </p> |
1,863,537 | What is a Domain Model | <p>I have read the wikipedia definition of a domain model. I still don't get it. I have been reading alot of posts for NHibernate and almost in every post I read I see the term Domain Model. What exactly is it and does any one have an example of a domain model.</p> | 53,559,615 | 7 | 0 | null | 2009-12-07 23:03:44.537 UTC | 12 | 2022-03-26 13:49:17.49 UTC | null | null | null | null | 184,773 | null | 1 | 33 | design-patterns|dns | 29,111 | <p>A domain model is a visual representation of real situation objects in a domain.
A domain is an area of concern. Its used to refer to the area you are dealing with.
The model is a diagram, for domain models the class diagram UML is mostly used. The class diagram is only used for the notation.
<strong>The term domain model does not mean a set of diagrams describing software classes.</strong></p>
<p>So for example imagine a store. For that store you want to build a brand new Point Of Sale system (lets call it POS system). A POS system is a computerized application used to record sale and handle payments. So you focus on the domain of the POS system.
Now you will conceptualize the objects that will be used for this system.
So you will get objects like: Sale, Payment, Register, Item etc.
In a domain model you model these objects and draw associations between them so that you have an high level idea how this system will work.
An example of the POS domain model will be like this:</p>
<p><a href="https://i.stack.imgur.com/WkUGA.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/WkUGA.jpg" alt="enter image description here"></a></p> |
1,693,088 | What is the use of Python's basic optimizations mode? (python -O) | <p>Python has a flag <code>-O</code> that you can execute the interpreter with. The option will generate "optimized" bytecode (written to .pyo files), and given twice, it will discard docstrings. From Python's man page:</p>
<blockquote>
<p>-O Turn on basic optimizations. This changes the filename extension
for compiled (bytecode) files from .pyc to .pyo. Given twice,
causes docstrings to be discarded.</p>
</blockquote>
<p>This option's two major features as I see it are:</p>
<ul>
<li><p>Strip all assert statements. This trades defense against corrupt program state for speed. But don't you need a ton of assert statements for this to make a difference? Do you have any code where this is worthwhile (and sane?)</p></li>
<li><p>Strip all docstrings. In what application is the memory usage so critical, that this is a win? Why not push everything into modules written in C?</p></li>
</ul>
<p>What is the use of this option?
Does it have a real-world value?</p> | 1,693,127 | 7 | 1 | null | 2009-11-07 13:51:35.423 UTC | 9 | 2017-05-19 03:43:21.863 UTC | 2015-10-03 21:12:28.833 UTC | null | 3,318,517 | null | 137,317 | null | 1 | 52 | python|optimization|assert|bytecode | 12,797 | <p>On stripping assert statements: this is a standard option in the C world, where many people believe part of the definition of ASSERT is that it doesn't run in production code. Whether stripping them out or not makes a difference depends less on how many asserts there are than on how much work those asserts do:</p>
<pre><code>def foo(x):
assert x in huge_global_computation_to_check_all_possible_x_values()
# ok, go ahead and use x...
</code></pre>
<p>Most asserts are not like that, of course, but it's important to remember that you can do stuff like that.</p>
<p>As for stripping docstrings, it does seem like a quaint holdover from a simpler time, though I guess there are memory-constrained environments where it could make a difference.</p> |
1,410,511 | Eclipse JVM configuration | <p>Background: I've got a new eclipse installation and have installed the m2eclipse plugin. After startup m2eclipse generates the message:</p>
<blockquote>
<p>Eclipse is running in a JRE, but a JDK
is required</p>
</blockquote>
<p>Following the instructions from <a href="http://blog.dawouds.com/2008/11/eclipse-is-running-in-jre-but-jdk-is.html" rel="noreferrer">here</a> I've changed the eclipse.ini file to use the JDK JVM:</p>
<pre><code>-startup
plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
-vm
"C:\Program Files\Java\jdk1.6.0_16\bin\javaw.exe"
</code></pre>
<p>After restarting eclipse however, I still get the message saying its running under the JRE and not the JDK. </p>
<p>Looking at the eclipse configuration via <em>Help -> About Eclipse -> Installation Details -> Configuration</em> it seems like eclipse is picking up the JVM configuration details from somewhere else:</p>
<pre><code>...
-vm
C:\Program Files (x86)\Java\jre6\bin\client\jvm.dll
eclipse.home.location=file:/C:/Program Files (x86)/eclipse/
eclipse.launcher=C:\Program Files (x86)\eclipse\eclipse.exe
[email protected]/../p2/
eclipse.p2.profile=epp.package.jee
eclipse.product=org.eclipse.epp.package.jee.product
eclipse.startTime=1252669330296
eclipse.vm=C:\Program Files (x86)\Java\jre6\bin\client\jvm.dll
eclipse.vmargs=-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
-vm
"C:\Program Files\Java\jdk1.6.0_16\bin\javaw.exe"
-XX:MaxPermSize=256m
...
</code></pre>
<p>My question is where is the first <em>-vm</em> argument coming from and how can I remove or change it?</p>
<p>Thanks</p>
<p><strong>Update</strong>: I have updated the eclipse.ini file as per VonC's answer. I'm now getting an error when launching eclipse saying:</p>
<blockquote>
<p>A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run Eclipse. No Java virtual machine was found after searching the following locations: "C:\Program Files\Java\jdk1.6.0_16\bin\javaw.exe"</p>
</blockquote>
<p>I've confirmed that the path is correct and can be executed via the command line.</p>
<p>Complete eclipse.ini below:</p>
<pre><code>-startup
plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vm
"C:\Program Files\Java\jdk1.6.0_16\bin\javaw.exe"
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m
</code></pre>
<p><strong>Solution:</strong> it seems like there was still something wrong with the eclipse.ini file. I replaced it completely with the settings given by VonC in the post he linked and eclipse is now starting properly and using the correct JVM. Full eclipse.ini below for anyone else with the same problem:</p>
<pre><code>-showlocation
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
384m
-startup
plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-vm
C:\Program Files (x86)\Java\jdk1.6.0_16\jre\bin\client\jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms128m
-Xmx384m
-Xss4m
-XX:PermSize=128m
-XX:MaxPermSize=128m
-XX:CompileThreshold=5
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-Dcom.sun.management.jmxremote
-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/jv/eclipse/mydropins
</code></pre> | 1,410,524 | 8 | 8 | null | 2009-09-11 12:12:18.303 UTC | 6 | 2018-04-24 18:59:57.077 UTC | 2009-09-11 13:25:17.973 UTC | null | 111,313 | null | 111,313 | null | 1 | 17 | eclipse|configuration|jvm|m2eclipse | 72,055 | <p>See:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/144349#144349">eclipse.ini for 3.4</a> or</li>
<li><a href="https://stackoverflow.com/questions/142357/what-are-the-best-jvm-settings-for-eclipse/1409590#1409590">eclipse.ini for 3.5</a></li>
</ul>
<p>for an example of parameters order.</p>
<p><code>-vm</code> should be before <code>-vmargs</code></p>
<hr>
<p>Update 6 years laters (2015)</p>
<p><a href="https://stackoverflow.com/users/639520/e-riz">E Riz</a> mentions <a href="https://stackoverflow.com/questions/1410511/eclipse-jvm-configuration/1410524#comment51846178_1410524">in the comments</a> that the <strong><a href="https://www.eclipse.org/downloads/installer-instructions.php" rel="nofollow noreferrer">new Eclipse Installer</a></strong> will detect the JVM for you, or propose ones to download.</p>
<p><a href="https://i.stack.imgur.com/u9llp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u9llp.png" alt="https://www.eclipse.org/downloads/assets/public/images/installer-instructions-04.png"></a></p> |
1,971,662 | How to improve my Algorithm to find the Hot-Topics like twitter does | <p>I have created a cron job for my website which runs every 2hours and it counts the words in the feeds and then displays the 10 highest count words as the hot topics.</p>
<p>Something that Twitter does on their homepage, is to show the most popular topics that are being discussed.</p>
<p>What my cron job does right now is it counts the words except for the words that i have mentioned, words like:</p>
<pre><code>array('of', 'a', 'an', 'also', 'besides', 'equally', 'further', 'furthermore', 'in', 'addition', 'moreover', 'too',
'after', 'before', 'when', 'while', 'as', 'by', 'the', 'that', 'since', 'until', 'soon', 'once', 'so', 'whenever', 'every', 'first', 'last',
'because', 'even', 'though', 'although', 'whereas', 'while', 'if', 'unless', 'only', 'whether', 'or', 'not', 'even',
'also', 'besides', 'equally', 'further', 'furthermore', 'addition', 'moreover', 'next', 'too',
'likewise', 'moreover', 'however', 'contrary', 'other', 'hand', 'contrast', 'nevertheless', 'brief', 'summary', 'short',
'for', 'example', 'for instance', 'fact', 'finally', 'in brief', 'in conclusion', 'in other words', 'in short', 'in summary', 'therefore',
'accordingly', 'as a result', 'consequently', 'for this reason', 'afterward', 'in the meantime', 'later', 'meanwhile', 'second', 'earlier', 'finally', 'soon', 'still', 'then', 'third'); //words that are negligible
</code></pre>
<p>But this does not completely solve the issue of eliminating all the non-required words. And give only the words that are useful.</p>
<p>Can someone please guide me on this, and tell me how can I improve my algorithm.</p> | 2,000,909 | 10 | 3 | null | 2009-12-28 21:32:09.89 UTC | 15 | 2022-04-11 00:19:05.41 UTC | 2022-04-11 00:19:05.41 UTC | null | 15,993,687 | null | 122,238 | null | 1 | 12 | php|cron | 3,089 | <p>Here's how we implemented this for the DjangoDose live feed during DjangoCon (note: this is a hackjob, we wrote it in 1 afternoon with no testing, and be yelling Bifurcation occsaionally, as best I can tell bifurcation has nothing to do with anything). All that being said, it more or less worked for us (meaning in the evenings beer was tracked appropriately).</p>
<pre><code>IGNORED_WORDS = set(open(os.path.join(settings.ROOT_PATH, 'djangocon', 'ignores.txt')).read().split())
def trending_topics(request):
logs = sorted(os.listdir(LOG_DIRECTORY), reverse=True)[:4]
tweets = []
for log in logs:
f = open(os.path.join(LOG_DIRECTORY, log), 'r')
for line in f:
tweets.append(simplejson.loads(line)['text'])
words = defaultdict(int)
for text in tweets:
prev = None
for word in text.split():
word = word.strip(string.punctuation).lower()
if word.lower() not in IGNORED_WORDS and word:
words[word] += 1
if prev is not None:
words['%s %s' % (prev, word)] += 1
words[prev] -= 1
words[word] -= 1
prev = word
else:
prev = None
trending = sorted(words.items(), key=lambda o: o[1], reverse=True)[:15]
if request.user.is_staff:
trending = ['%s - %s' % (word, count) for word, count in trending]
else:
trending = [word for word, count in trending]
return HttpResponse(simplejson.dumps(trending))
</code></pre> |
1,646,807 | Quick and Simple Hash Code Combinations | <p>Can people recommend quick and simple ways to combine the hash codes of two objects. I am not too worried about collisions since I have a Hash Table which will handle that efficiently I just want something that generates a code quickly as possible.</p>
<p>Reading around SO and the web there seem to be a few main candidates:</p>
<ol>
<li>XORing</li>
<li>XORing with Prime Multiplication</li>
<li>Simple numeric operations like multiplication/division (with overflow checking or wrapping around)</li>
<li>Building a String and then using the String classes Hash Code method</li>
</ol>
<p>What would people recommend and why?</p> | 1,646,913 | 10 | 0 | null | 2009-10-29 21:53:21.353 UTC | 34 | 2020-08-01 00:07:08.867 UTC | 2009-10-29 22:54:43.14 UTC | null | 60,761 | null | 107,591 | null | 1 | 99 | c#|algorithm|hash|hashcode | 53,453 | <p>I would personally avoid XOR - it means that any two equal values will result in 0 - so hash(1, 1) == hash(2, 2) == hash(3, 3) etc. Also hash(5, 0) == hash(0, 5) etc which may come up occasionally. I <em>have</em> deliberately used it for set hashing - if you want to hash a sequence of items and you <em>don't</em> care about the ordering, it's nice.</p>
<p>I usually use:</p>
<pre><code>unchecked
{
int hash = 17;
hash = hash * 31 + firstField.GetHashCode();
hash = hash * 31 + secondField.GetHashCode();
return hash;
}
</code></pre>
<p>That's the form that Josh Bloch suggests in Effective Java. Last time I answered a similar question I managed to find an article where this was discussed in detail - IIRC, no-one really knows why it works well, but it does. It's also easy to remember, easy to implement, and easy to extend to any number of fields.</p> |
33,647,496 | Custom UI on exoplayer sample | <p>** I really need help if you don't know anything don't give me a negative point :| if something bother you comment**</p>
<p>I want to write custom UI for my player in Exoplayer(change button of pause play or add new buttons like player speed next and etc) .</p>
<p>I use Exoplayer sample from github and before add code to my original project, I want to test the custom UI on official sample.</p>
<p>I read pages in Stackoverflow and tuts+ about custom UI but I really confused!</p>
<p>why change some buttons image or change their place must be so difficult :) how i can handle this?</p>
<p><strong>EDIT</strong></p>
<p>this is the sample
<a href="https://github.com/google/ExoPlayer/tree/master/demo" rel="noreferrer">https://github.com/google/ExoPlayer/tree/master/demo</a></p>
<p>I read these two article:</p>
<p><a href="http://www.brightec.co.uk/ideas/custom-android-media-controller" rel="noreferrer">http://www.brightec.co.uk/ideas/custom-android-media-controller</a></p>
<p><a href="http://code.tutsplus.com/tutorials/create-a-music-player-on-android-user-controls--mobile-22787" rel="noreferrer">http://code.tutsplus.com/tutorials/create-a-music-player-on-android-user-controls--mobile-22787</a></p>
<p>according to this <a href="http://brightec.co.uk/ideas/custom-android-media-controller" rel="noreferrer">link</a> "Instead of writing your own media controller from scratch, you could start with the MediaController class that is included in Android" and I ask this question because i can't do this steps on exoplayer library and tutorial is written for default media player</p> | 33,830,453 | 3 | 5 | null | 2015-11-11 09:22:16.91 UTC | 8 | 2020-03-03 08:09:33.117 UTC | 2017-03-31 13:18:58.703 UTC | null | 5,475,524 | null | 1,950,850 | null | 1 | 21 | android|mediacontroller|exoplayer | 46,631 | <p>Actually the code of involking play & pause methods are in class <a href="https://github.com/google/ExoPlayer/blob/0c060f429f459f1bac2ffa0963cadc45ce35b73a/library/src/main/java/com/google/android/exoplayer/util/PlayerControl.java#L90" rel="noreferrer">PlayerControl</a>. </p>
<p>If you don't want to use default Android media controller UI, just don't use the <code>MediaController</code> class, create your own UI in your layout file with custom play & pause button and bind the actions with the button's onClickListener.</p>
<p>To play the video, call <code>exoPlayer.setPlayWhenReady(true);</code> </p>
<p>And to pause: call <code>exoPlayer.setPlayWhenReady(false);</code></p>
<p>It's similar problem with <a href="https://stackoverflow.com/questions/12482203/how-to-create-custom-ui-for-android-mediacontroller">how to create custom UI for android MediaController</a></p> |
8,605,447 | How to rebase all the commits from the beginning | <p>So I'm migrating from svn (code.google.com) to git(github).</p>
<p>I've imported my project from the svn repo, and it imported all the commit history along way.
I'm not really proud of those comments as it was one of my first project, not really serious.</p>
<p>I'd like to rebase everything into a single 'initial import' commit.</p>
<p>I've pulled everything on my computer and I'm trying to do that. But all I found was:
<code>git rebase -i master</code> but it only rebases new modifications and commits.</p>
<p>How can I clean my github repository from all history with a rebase?</p> | 41,769,800 | 5 | 2 | null | 2011-12-22 14:42:17.737 UTC | 16 | 2018-02-28 14:09:14.413 UTC | null | null | null | null | 709,635 | null | 1 | 84 | git|github | 37,772 | <p><code>git rebase -i --root</code> will start an interactive rebase of all commits from the beginning.</p>
<p>From there, you can squash all commits into one and/or perform other edits.</p> |
46,195,479 | jQuery - set array values to the input with the same name | <p>I was trying to set the array values to the input field named <code>attachments[]</code></p>
<p>I have array stored in js variable <code>attachArray</code></p>
<p>What I have tried is,</p>
<pre><code>$('[name="attachments"]').attr('value', attachArray);
</code></pre>
<p>or</p>
<pre><code>$('[name="attachments"]').val(attachArray);
</code></pre>
<p>But getting empty <code>attachments</code> in the controller like this,</p>
<pre><code>array(1) { ["attachments"]=> array(1) { [0]=> string(0) "" } }
</code></pre>
<p>What I'm doing wrong?</p>
<p><strong>EDIT</strong></p>
<pre><code><div class="col-md-4">
<div class="form-group ticket-align">
<label>Attachment</label>
<label class="btn btn-primary" data-toggle="modal" data-target="#t-attachment-modal">
Browse&hellip;
<input type="hidden" name="attachments[]">
</label>
<span id="fileList"></span>
<span class="error" id="error-atachments" style='display: none;'></span>
</div>
</div>
</code></pre> | 46,195,691 | 4 | 4 | null | 2017-09-13 10:46:18.403 UTC | 2 | 2020-09-23 11:04:35.977 UTC | 2017-09-13 10:52:39.337 UTC | null | 2,210,140 | null | 2,210,140 | null | 1 | 7 | javascript|php|jquery|arrays | 43,107 | <p>Since it's a hidden input, so</p>
<p>Either:-</p>
<pre><code>$('[name=attachments]').val(attachArray);
</code></pre>
<p>OR </p>
<pre><code>$('input:hidden[name=attachments]').val(attachArray);
</code></pre>
<p>Will work.</p>
<p>Note:- Use the backslashes(<strong><em>Escape internal brackets with <code>\\</code>(no space)</em></strong>).</p> |
17,869,144 | jQuery - Set the selected option of a select box using value or text with options nested in optgroups | <p>So I am writing an app that requires an address input and I have a <code>select</code> element for the user to select the state/province. It needs to support the <code>US</code> and <code>Canada</code> so it has nested <code>optgroups</code> to separate those out and a single, first level option as it's default value. Here is a basic example:</p>
<pre><code><select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
</optgroup>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>
</optgroup>
</code></pre>
<p></p>
<p>Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using</p>
<pre><code>$("#state").val(myValue)
</code></pre>
<p>and I know you can set an option based on text in this way</p>
<pre><code>var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);
</code></pre>
<p>Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?</p>
<p>One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable</p>
<pre><code>$element
</code></pre>
<p>so I need a way to do it kind of like this if possible:</p>
<pre><code>$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);
</code></pre> | 17,870,304 | 6 | 3 | null | 2013-07-25 21:34:29.89 UTC | 7 | 2016-11-16 01:41:31.983 UTC | 2016-11-16 01:41:31.983 UTC | null | 7,055,233 | null | 1,489,957 | null | 1 | 4 | javascript|jquery|html|html-select | 96,017 | <p>Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:</p>
<pre><code>$("#state option").filter(
// filter function
).prop('selected', true);
</code></pre>
<p>After a lot of trying, I got this and it works:</p>
<pre><code>function functionIHadToChange($element, value) {
// other code
$element.find("option").filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}
</code></pre> |
17,695,594 | notifyDataSetChanged() makes the list refresh and scroll jumps back to the top | <p>I am trying to implement an endless scroll listview but when I call <code>notifyDataSetChanged()</code> the whole list refreshes then the scroll position goes back to the top.</p>
<p>Is this the normal behavior? how can I make it simply add the items added without refreshing and keep the scroll position?</p> | 17,696,214 | 6 | 1 | null | 2013-07-17 09:06:04.48 UTC | 11 | 2021-06-12 08:40:43.96 UTC | null | null | null | null | 521,180 | null | 1 | 42 | java|android|android-listview | 64,289 | <p>Such behaviour is not normal. Without seeing your code I can suggest following:</p>
<p>1) You are not calling <code>notifyDataSetChanged()</code> from the UI thread. The correct way:</p>
<pre><code>runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
</code></pre>
<p>2) You accidentally or not are making a call to <code>adapter.notifyDataSetInvalidated();</code></p>
<p>3) In your adapter you override the <code>adapter.notifyDataSetChanged();</code> method and added instruction to go to top </p>
<p>4) If you're using a list to populate adapter - you supply new list every time, so adapter settings are refreshed. You should always supply the same list. However you can change it as much as you want. If you're resetting the list use <code>list.clear</code> instead of <code>list = new ArrayList();</code></p>
<p>Here is an example of my adapter:</p>
<pre><code>public class Adapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public MediaItemAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data = d;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.item_composer, null);
}
TextView title = (TextView) vi.findViewById(R.id.item_title); // title
TextView price = (TextView) vi.findViewById(R.id.price);
return vi;
}
}
</code></pre>
<p>Call for adapter:</p>
<pre><code>List myList = new ArrayList<HashMap<String, String>>();
Adapter ma = new Adapter(this, myList);
</code></pre>
<p>myList can be empty before adapter initialization.</p>
<p>Then do some operation with my list:</p>
<pre><code>myList.add(someElement);
ma.notifyDataSetChanged();
</code></pre>
<p>if you need delete all items:</p>
<pre><code>myList.clear();
ma.notifyDataSetChanged();
</code></pre>
<p>Such implementation is pretty endless, I saw more then 15 thousand elements without any problems.</p> |
18,054,798 | Entity Framework not saving modified children | <p>Frustrating, this. Here's a pair of related objects, as generated by database-first Entity Framework:</p>
<pre><code>public partial class DevelopmentType
{
public DevelopmentType()
{
this.DefaultCharges = new HashSet<DefaultCharge>();
}
public System.Guid RowId { get; set; }
public string Type { get; set; }
public virtual ICollection<DefaultCharge> DefaultCharges { get; set; }
}
public partial class DefaultCharge
{
public System.Guid RowId { get; set; }
public decimal ChargeableRate { get; set; }
public Nullable<System.Guid> DevelopmentType_RowId { get; set; }
public virtual DevelopmentType DevelopmentType { get; set; }
}
</code></pre>
<p>Here's the code that I'm calling to save a DevelopmentType - it involves automapper since we differentiate entity objects from DTOs:</p>
<pre><code> public void SaveDevelopmentType(DevelopmentType_dto dt)
{
Entities.DevelopmentType mappedDevType = Mapper.Map<DevelopmentType_dto, Entities.DevelopmentType>(dt);
_Context.Entry(mappedDevType).State = System.Data.EntityState.Modified;
_Context.DevelopmentTypes.Attach(mappedDevType);
_Context.SaveChanges();
}
</code></pre>
<p>In my user interface, the most common operation will be for a user to look at a list of DevelopmentTypes and update their DefaultCharge. So when I test this using the above code, it runs without error, but nothing actually changes.</p>
<p>If I pause in the debugger it's clear that the changed DefaultCharge is being passed into the function, and that it's attached to the DevelopmentType to be saved. </p>
<p>Stepping through it, if I change the value manually inside visual studio, it <em>does</em> save the updated value. Which is just even more confusing.</p>
<p>Monitoring the database with SQL Server Profiler reveals that update commands are issued <em>only</em> for the parent object and <em>not</em> for any attached objects.</p>
<p>I have other similar code elsewhere that functions as expected. What am I doing wrong here?</p>
<p>EDIT:</p>
<p>I have discovered that if you do this prior to the call to SaveDevelopmentType:</p>
<pre><code> using (TransactionScope scope = new TransactionScope())
{
dt.Type = "Test1";
dt.DefaultCharges.First().ChargeableRate = 99;
_CILRepository.SaveDevelopmentType(dt);
scope.Complete();
}
</code></pre>
<p>The change to Type saves, but the change to ChargeableRate does not. I don't think it helps, massively, but thought I'd add it.</p> | 18,058,973 | 7 | 0 | null | 2013-08-05 09:31:12.393 UTC | 10 | 2017-09-22 17:31:40.74 UTC | 2013-08-05 11:13:45.577 UTC | null | 271,907 | null | 271,907 | null | 1 | 27 | c#|entity-framework | 45,348 | <p>The problem is, that EF is not aware of the changed DefaultCharges. </p>
<p>By setting the State of the <code>DevelopmentType</code> to <code>EntityState.Modified</code>, EF only knows that the object <code>DevelopmentType</code> has been changed. However, this means that EF will only update <code>DevelopmentType</code> but not it's navigation properties. </p>
<p>A workaround - which isn't best practice - would be to iterate over all <code>DefaultCharge</code> of the current <code>DevelopmentType</code> and set the entity state to <code>EntityState.Modified</code>.</p>
<p>Additionally I would recommend to attach the entity to the context first, and change the state afterwards.</p>
<p><strong>EDIT after comment</strong></p>
<p>As you are using DTOs I suppose you are transfering these objects either through different layers or different machines. </p>
<p>In this case I would recommend to use self tracking entities, because it is not possible to share one context. These entities additionally holds their current state (ie. new, updated, deleted etc). There are many tutorials on the net about self tracking entities.</p>
<p>e.g. <a href="http://msdn.microsoft.com/en-us/library/vstudio/ff407090%28v=vs.100%29.aspx">MSDN - Working with Self-Tracking Entities</a></p> |
18,095,727 | Limit the length of a string with AngularJS | <p>I have the following:</p>
<pre><code><div>{{modal.title}}</div>
</code></pre>
<p>Is there a way that I could limit the length of the string to say 20 characters?</p>
<p>And an even better question would be is there a way that I could change the string to be truncated and show <code>...</code> at the end if it's more than 20 characters?</p> | 18,096,071 | 27 | 1 | null | 2013-08-07 06:00:45.053 UTC | 79 | 2022-06-01 05:55:47.67 UTC | 2014-08-15 20:23:46.057 UTC | null | 1,590,931 | null | 1,422,604 | null | 1 | 233 | angularjs|filter|angularjs-filter | 310,430 | <p><strong>Edit</strong>
The latest version of <code>AngularJS</code>offers <a href="https://docs.angularjs.org/api/ng/filter/limitTo" rel="noreferrer"><code>limitTo</code> filter</a>.</p>
<p>You need a <em>custom filter</em> like this:</p>
<pre><code>angular.module('ng').filter('cut', function () {
return function (value, wordwise, max, tail) {
if (!value) return '';
max = parseInt(max, 10);
if (!max) return value;
if (value.length <= max) return value;
value = value.substr(0, max);
if (wordwise) {
var lastspace = value.lastIndexOf(' ');
if (lastspace !== -1) {
//Also remove . and , so its gives a cleaner result.
if (value.charAt(lastspace-1) === '.' || value.charAt(lastspace-1) === ',') {
lastspace = lastspace - 1;
}
value = value.substr(0, lastspace);
}
}
return value + (tail || ' …');
};
});
</code></pre>
<h3>Usage:</h3>
<pre><code>{{some_text | cut:true:100:' ...'}}
</code></pre>
<h3>Options:</h3>
<ul>
<li>wordwise (boolean) - if true, cut only by words bounds,</li>
<li>max (integer) - max length of the text, cut to this number of chars,</li>
<li>tail (string, default: ' …') - add this string to the input
string if the string was cut.</li>
</ul>
<p><strong>Another solution</strong>: <a href="http://ngmodules.org/modules/angularjs-truncate" rel="noreferrer">http://ngmodules.org/modules/angularjs-truncate</a> (by @Ehvince)</p> |
42,119,036 | SSIS package shows blank screen in design mode | <p>I created a SSIS package using <code>SQL Server data tools 2015</code> a week back.
And today i opened the package and it just shows the blank screen.</p>
<p>I read about this issue <a href="https://social.msdn.microsoft.com/Forums/sqlserver/en-US/5b4faddc-5723-44fb-926d-e5a92dc8fc0f/ssis-designer-is-solid-white?forum=sqlintegrationservices" rel="noreferrer">here</a> and it seems that was the defect in earlier versions and it is fixed.</p>
<p>Did anyone face this issue in data tools 2015? How can i fix it and save my package?</p> | 45,200,942 | 7 | 4 | null | 2017-02-08 16:50:27.267 UTC | 7 | 2020-11-27 17:05:21.23 UTC | 2017-02-08 17:05:12.55 UTC | null | 979,189 | null | 979,189 | null | 1 | 39 | sql-server|visual-studio|ssis | 24,465 | <p>1) While the package is opened with the white page, rename it in the solution. </p>
<p>2) Save the package and close.</p>
<p>3) Rename the package back original name (while package is closed). This rename will open the package and hopefully set it back so that you can edit it.</p>
<p>This has worked for me, hopefully it will work for others.</p> |
6,679,010 | Converting a unix time stamp to twitter/facebook style | <p>I'm trying to convert a unix time stamp to display like facebook and twitter. For example, when you see tweets or comments placed on twitter/facebook you see the date/time displayed like so:</p>
<p>'2 mins ago' or '2 days ago' or '2 weeks ago' </p>
<p>Does anyone one know of any function to get it working like this. I'm guessing it will be a custom one. </p>
<p>Any help is much appreciated</p> | 6,679,081 | 3 | 1 | null | 2011-07-13 12:38:36.863 UTC | 9 | 2018-01-18 20:35:00.5 UTC | 2011-07-13 13:52:09.353 UTC | null | 181,707 | null | 823,903 | null | 1 | 10 | php|datetime|timestamp|unix-timestamp|string-to-datetime | 7,577 | <p>If you are using php you might want to try the following function which was posted by Matt Jones</p>
<p><a href="http://www.mdj.us/web-development/php-programming/another-variation-on-the-time-ago-php-function-use-mysqls-datetime-field-type/" rel="noreferrer">http://www.mdj.us/web-development/php-programming/another-variation-on-the-time-ago-php-function-use-mysqls-datetime-field-type/</a></p>
<pre><code>// DISPLAYS COMMENT POST TIME AS "1 year, 1 week ago" or "5 minutes, 7 seconds ago", etc...
function time_ago($date,$granularity=2) {
$date = strtotime($date);
$difference = time() - $date;
$periods = array('decade' => 315360000,
'year' => 31536000,
'month' => 2628000,
'week' => 604800,
'day' => 86400,
'hour' => 3600,
'minute' => 60,
'second' => 1);
foreach ($periods as $key => $value) {
if ($difference >= $value) {
$time = floor($difference/$value);
$difference %= $value;
$retval .= ($retval ? ' ' : '').$time.' ';
$retval .= (($time > 1) ? $key.'s' : $key);
$granularity--;
}
if ($granularity == '0') { break; }
}
return ' posted '.$retval.' ago';
}
</code></pre> |
6,405,347 | apache compression Deflate .js and .css files not compressed? | <p>In Apache Im enabling output compression by adding the following to my .htaccess file:</p>
<pre><code># compress text, html, javascript, css, xml:
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
# Or, compress certain file types by extension:
<Files *.html>
SetOutputFilter DEFLATE
</Files>
</code></pre>
<p>So I'm serving all content with Content-Encoding: gzip but when I test my webpage with Yslow I receive:</p>
<pre><code>Grade D on Compress components with gzip
There are 3 plain text components that should be sent compressed
* http://mysite.com/javascript/youTubeEmbed/youTubeEmbed-jquery-1.0.css
* http://mysite.com/javascript/jquery.swfobject.1-1-1.min.js
* http://mysite.com/javascript/youTubeEmbed/youTubeEmbed-jquery-1.0.js
</code></pre>
<p>Where's the problem?Shouldn't they get compressed automatically??</p>
<p>thanks</p>
<p>Luca</p> | 6,511,578 | 3 | 0 | null | 2011-06-19 21:58:15.477 UTC | 10 | 2015-08-04 10:03:40.727 UTC | 2011-06-20 06:47:18.09 UTC | null | 505,762 | null | 505,762 | null | 1 | 23 | apache|gzip|yslow|deflate | 43,340 | <p>Did you remember to clear your cache before reloading the page and running Yslow?</p>
<p>I had the exact same problem and fixed it like that. This is my code:</p>
<pre><code>AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
</code></pre> |
6,526,865 | How can you use PowerShell's . (dot) notation to walk through elements with periods in the element name? | <p>PowerShell makes working with XML fairly easy in most cases. However, I'm having trouble using the "dot" notation to walk through a web.config file. Everything works</p>
<pre><code>Import-Module WebAdministration
$site = get-website | ? { $_.name -eq "My Website - 80" }
$WebConfigFile = $site.physicalPath + "\web.config"
[xml]$WebAppXml = Get-Content $WebConfigFile
$webAppXml.configuration.system.web
</code></pre>
<p>On the last line, PowerShell uses intellisense to fill in system.web, but if you try to run it, the output is null. I know I can use Xpath or the .NET Xml objects, but I'd rather not if I don't have to.</p> | 6,526,971 | 3 | 0 | null | 2011-06-29 20:30:26.52 UTC | 1 | 2019-03-12 18:23:55.193 UTC | null | null | null | null | 681 | null | 1 | 32 | xml|powershell | 6,833 | <pre><code>$webAppXml.configuration.'system.web'
</code></pre> |
6,589,101 | How to get screen size of device? | <p>I would like to get the height of a android screen and if the screen inst a certain height, how would i go about doing this?</p> | 6,589,124 | 3 | 0 | null | 2011-07-05 21:29:00.21 UTC | 8 | 2011-07-05 22:26:54.69 UTC | null | null | null | null | 828,330 | null | 1 | 42 | android | 63,797 | <p>If you want the display dimensions in pixels you can use this code:</p>
<pre><code>Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
</code></pre>
<p>Then you can add condition that compares the height to satisfy your needs.</p>
<p>In inches:</p>
<pre><code>DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
double x = Math.pow(dm.widthPixels/dm.xdpi,2);
double y = Math.pow(dm.heightPixels/dm.ydpi,2);
double screenInches = Math.sqrt(x+y);
Log.d("debug","Screen inches : " + screenInches);
</code></pre> |
6,517,423 | How to do an specific action when a certain breakpoint is hit in GDB? | <p>I am looking for a way to do some action when a particular break point hits in gdb. </p>
<p>Basically I have some memleak in my program. When malloc and free function hits, I need to enter into the function (step) and collect some basic information like the addr and size (basically print there values). Once done resume my program.</p>
<p>Do we have any good way to do this?</p> | 6,517,457 | 3 | 0 | null | 2011-06-29 07:56:33.247 UTC | 17 | 2022-02-14 22:05:21.43 UTC | 2018-07-25 17:13:22.223 UTC | null | 895,245 | null | 406,001 | null | 1 | 70 | c|gdb | 35,544 | <p>For example, here is how you could use breakpoint commands to print the value of x at entry to foo whenever x is positive.</p>
<pre><code>break foo if x>0
commands
silent
printf "x is %d\n",x
cont
end
</code></pre>
<p>If the first command you specify in a command list is <code>silent</code>, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the remaining commands print anything, you see no sign that the breakpoint was reached. silent is meaningful only at the beginning of a breakpoint command list.</p>
<p>One application for breakpoint commands is to compensate for one bug so you can test for another. Put a breakpoint just after the erroneous line of code, give it a condition to detect the case in which something erroneous has been done, and give it commands to assign correct values to any variables that need them. End with the continue command so that your program does not stop, and start with the silent command so that no output is produced. Here is an example:</p>
<pre><code>break 403
commands
silent
set x = y + 4
cont
end
</code></pre> |
6,430,437 | Autorun the Faye server when I start the Rails server | <p>I currently have Faye working with my Rails 3.0.9 application. However I have two separate tabs open in my terminal. One for the Faye server, and one for the Rails server. How can I integrate them and automatically run the Faye server when Rails starts up?</p>
<p>To start the Faye Server, I am running:</p>
<pre><code>rackup faye.ru -s thin -E production
</code></pre>
<p>faye.ru</p>
<pre><code>require 'faye'
faye_server = Faye::RackAdapter.new(:mount => '/faye')
run faye_server
</code></pre>
<p>Please let me know if you need any more information.</p> | 6,431,006 | 4 | 5 | null | 2011-06-21 18:49:20.583 UTC | 11 | 2017-08-23 12:18:36.457 UTC | 2017-08-23 12:18:36.457 UTC | null | 214,812 | null | 214,812 | null | 1 | 17 | ruby-on-rails|ruby-on-rails-3|faye | 8,686 | <p>Simply create an initializer containing:</p>
<pre><code>Thread.new do
system("rackup faye.ru -s thin -E production")
end
</code></pre>
<hr>
<p>Better option:</p>
<p>Use <a href="https://github.com/FooBarWidget/daemon_controller">https://github.com/FooBarWidget/daemon_controller</a></p> |
52,122,011 | Failed to execute 'postMessage' on 'Window' GoogleTagManager | <p>Recently, I get this <strong>postMessage couldn't be cloned</strong> error. It is happening on most of the latest browsers like Chrome 68, Firefox 61.0, IE11, Edge.</p>
<blockquote>
<p>Failed to execute 'postMessage' on 'Window': <code>function (a){if(qe.$a.hasOwnProperty(a))return qe.$a[a]}</code> could not be cloned.</p>
</blockquote>
<p>The stack trace is:</p>
<blockquote>
<p>Error: Failed to execute 'postMessage' on 'Window': <code>function (a){if(qe.$a.hasOwnProperty(a))return qe.$a[a]}</code> could not be cloned.<br>
at _reportEvent (eval at (:1:35637), :94:35)<br>
at eval (eval at (:1:35637), :55:5)<br>
at eval (eval at (:1:35637), :433:11)</p>
</blockquote>
<p>Searching through the source of my page in DevTools shows <code>gtm.js</code> as the source of the code fragment:</p>
<p><a href="https://i.stack.imgur.com/HU78B.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HU78B.png" alt="gtm.js shown as source of the function"></a></p>
<p>I have a Google Tag Manager tracking code on my page. Why is this happening?</p> | 52,223,341 | 3 | 13 | null | 2018-08-31 20:05:19.763 UTC | 12 | 2020-11-27 13:11:39.707 UTC | 2018-09-07 13:47:54.053 UTC | null | 9,801,830 | null | 3,724,845 | null | 1 | 30 | javascript|error-handling|google-tag-manager | 18,674 | <p>This happens all the time, if something can not be duplicated by the <strong><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm" rel="noreferrer">structured clone algorithm</a></strong>. This algorithm is used by <strong><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage" rel="noreferrer"><code>window.postMessage</code></a></strong>. If we read the documentation from <strong><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage" rel="noreferrer"><code>window.postMessage</code></a></strong> for the first parameter:</p>
<blockquote>
<p><strong>message</strong><br>
<em>Data to be sent to the other window. The data is serialized using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm" rel="noreferrer">structured clone algorithm</a>.</em></p>
</blockquote>
<p>and then open the description from <em>structured clone algorithm</em> (see last link above) then we can read:</p>
<blockquote>
<p><em>The structured clone algorithm</em> is an algorithm defined by the HTML5 specification for copying complex JavaScript objects. It is used internally when transferring data to and from Workers via <code>postMessage()</code> or when storing objects with <code>IndexedDB</code>. It builds up a clone by recursing through the input object while maintaining a map of previously visited references in order to avoid infinitely traversing cycles.</p>
<p><strong>Things that don't work with structured clone</strong></p>
<ul>
<li><p><code>Error</code> and <code>Function</code> objects cannot be duplicated by the structured clone algorithm; attempting to do so will throw a
<code>DATA_CLONE_ERR</code> exception.</p>
</li>
<li><p>Attempting to clone <code>DOM</code> nodes will likewise throw a <code>DATA_CLONE_ERR</code> exception.</p>
</li>
<li><p>Certain parameters of objects are not preserved:</p>
<ul>
<li>The <code>lastIndex</code> field of <code>RegExp</code> objects is not preserved.</li>
<li>Property descriptors, setters, and getters (as well as similar metadata-like features) are not duplicated. For example, if an object
is marked read-only using a property descriptor, it will be read-write
in the duplicate, since that's the default condition.</li>
<li>The prototype chain does not get walked and duplicated.</li>
</ul>
</li>
</ul>
<p><strong>Supported types</strong></p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Primitive_values" rel="noreferrer">All primitive types</a> <em>(Note: However not symbols)</em></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean" rel="noreferrer"><code>Boolean</code></a> object</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String" rel="noreferrer"><code>String</code></a> object</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" rel="noreferrer"><code>Date</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp" rel="noreferrer"><code>RegExp</code></a> <em>(Note: The lastIndex field is not preserved.)</em></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob" rel="noreferrer"><code>Blob</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/File" rel="noreferrer"><code>File</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/FileList" rel="noreferrer"><code>FileList</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBuffer" rel="noreferrer"><code>ArrayBuffer</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView" rel="noreferrer"><code>ArrayBufferView</code></a> <em>(Note: This basically means all typed arrays like Int32Array etc.)</em></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/API/ImageData" rel="noreferrer"><code>ImageData</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" rel="noreferrer"><code>Array</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" rel="noreferrer"><code>Object</code></a> <em>(Note: This just includes plain objects (e.g. from object literals))</em></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map" rel="noreferrer"><code>Map</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set" rel="noreferrer"><code>Set</code></a></li>
</ul>
</blockquote>
<p>I tested it with some objects and I can show you following examples when this is happening...</p>
<p><strong>Error-Example with custom function</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = {something: function(){}};
window.postMessage(obj, '*'); // DataCloneError</code></pre>
</div>
</div>
</p>
<p><strong>Error-Example with native function</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = {something: window.alert};
window.postMessage(obj, '*'); // DataCloneError</code></pre>
</div>
</div>
</p>
<p>The same we will see with native functions like <code>Boolean</code>, <code>Date</code>, <code>String</code>, <code>RegExp</code>, <code>Number</code>, <code>Array</code>.</p>
<p><strong>Error-Example with native object</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = {something: document};
window.postMessage(obj, '*'); // DataCloneError</code></pre>
</div>
</div>
</p>
<p><strong>Error-Example with HTML element object</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = {something: document.createElement('b')};
window.postMessage(obj, '*'); // DataCloneError</code></pre>
</div>
</div>
</p>
<p>We could write more examples if we read the description from <em>The structured clone algorithm</em> above, but I think here it is enough.</p>
<h2>What we could do to avoid this error</h2>
<p>In our code we could use only supported types (see the list above) in our objects. But in not our code we have to contact the developers from this code and write them how they have to correct their code. In the case from the Google Tag Manager you could write it to <a href="https://productforums.google.com/forum/#!forum/tag-manager" rel="noreferrer">the Official Google Tag Manager Forum</a> with description how they have to correct their code.</p>
<p><strong>Workaround for some browsers</strong></p>
<p>In some browsers you can not override native methods for security reasons. For example <strong>IE does not allow to override <code>window.postMessage</code></strong>. But other browsers like Chrome allow to override this method like follows:</p>
<pre><code>var postMessageTemp = window.postMessage;
window.postMessage = function(message, targetOrigin, transfer)
{
postMessageTemp(JSON.parse(JSON.stringify(message)), targetOrigin, transfer)
};
</code></pre>
<p>But note that <code>window</code> is a global object of JavaScript context and it is not created from the <code>prototype</code>. In other words: you can not override it with <code>window.prototype.postMessage = ...</code>.</p>
<p><strong>Example with workaround</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var obj = {something: window};
var postMessageTemp = window.postMessage;
window.postMessage = function(message, targetOrigin, transfer)
{
function cloneObject(obj)
{
var clone = {};
for(var i in obj)
{
if(typeof(obj[i]) == 'object' && obj[i] != null)
{
if((''+obj[i]) == '[object Window]')
{
delete obj[i];
continue;
}
clone[i] = cloneObject(obj[i]);
}
else
clone[i] = obj[i];
}
return clone;
}
// to avoid weird error causing by window object by JSON.stringify() execution.
var clone = cloneObject(message);
postMessageTemp(JSON.parse(JSON.stringify(clone)), targetOrigin, transfer)
};
window.postMessage(obj, '*');
console.log('We do not have any errors.');</code></pre>
</div>
</div>
</p>
<p><strong>How to implement this workaround</strong></p>
<p>Please put this overriden <code>window.postMessage</code> function in script part in your HTML page before Google Tag Manager script. But in better way you could help the developers from Google Tag Manager to understand and to correct this error and you can wait for corrected Google Tag Manager script.</p> |
23,538,335 | jQuery data attr not setting | <p>This appears very simple but I cannot see why it's not working. The selector is correct however the div <code>.faqContent</code> is simply not being updated with the <code>data-height</code> attribute.</p>
<pre><code>$('.faqItem .faqContent').each(function(){
var h = $(this).height();
$(this).data('height',h);
});
</code></pre>
<p>I have checked that <code>var h</code> is correct, it is in colsole.log as correctly holding the height. </p>
<p><strong>EDIT</strong>
It's absolutely not conflict, and console shows no errors.</p> | 23,538,368 | 4 | 3 | null | 2014-05-08 09:51:42.333 UTC | 3 | 2022-06-22 06:09:04.663 UTC | null | null | null | null | 1,805,822 | null | 1 | 31 | javascript|jquery | 22,798 | <p>You will not be able to see it in the element inspector but <em>it is there</em> as jquery set the data attribute internally.</p>
<p>try <code>console.log($(this).data('height'));</code></p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.