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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
32,629,379 | How to build react native android app for production? | <p>I've seen new release of react native for android and tried some examples. It works only with USB debug mode and "adb reverse tcp:8081 tcp:8081". How can I build android app for "production" including all dependencies and without react web-server connections.
Thank you.</p> | 32,631,830 | 5 | 1 | null | 2015-09-17 11:36:07.143 UTC | 19 | 2022-03-05 01:40:06.077 UTC | null | null | null | null | 5,173,866 | null | 1 | 57 | react-native | 50,424 | <p>To build a release version of your Android app:</p>
<pre><code>$ cd your-app-folder
$ cd android && ./gradlew assembleRelease
</code></pre>
<p>You'll need to set up signing keys for the Play Store, full documentation here: <a href="https://reactnative.dev/docs/signed-apk-android" rel="nofollow noreferrer">https://reactnative.dev/docs/signed-apk-android</a></p> |
32,687,538 | How to execute 1 command x times in java | <p>I'd like to ask how to execute 1 command multiple times</p>
<p>for example this code</p>
<pre><code>System.out.println("Hello World!");
</code></pre>
<p>I want to run it 500 times
how do i do it ?</p>
<p>Thank You</p>
<p>Regards
Wilhelmus</p> | 32,687,562 | 8 | 2 | null | 2015-09-21 04:46:41.257 UTC | 2 | 2022-01-22 15:11:59.057 UTC | 2015-09-21 05:18:13.52 UTC | null | 3,898,076 | null | 5,357,698 | null | 1 | 2 | java|loops | 43,582 | <p>Use a loop, </p>
<pre><code>for(int i = 0; i < 500; ++i)
System.out.println("Hello World!");
</code></pre>
<hr>
<p>Please go through a basic Java tutorial.
One can be found <a href="http://www.tutorialspoint.com/java/" rel="noreferrer">here</a></p> |
9,321,334 | GRANT EXECUTE to all stored procedures | <p>Does the following command effectively give the user, "MyUser," permission to execute ALL stored procedures in the database?</p>
<pre><code>GRANT EXECUTE TO [MyDomain\MyUser]
</code></pre> | 9,321,592 | 3 | 0 | null | 2012-02-17 00:38:26.147 UTC | 42 | 2019-11-08 17:44:13.707 UTC | 2018-10-18 09:47:24.16 UTC | null | 1,016,343 | null | 109,676 | null | 1 | 174 | sql|sql-server|tsql|sql-server-2008|permissions | 327,192 | <p>SQL Server 2008 and Above:</p>
<pre><code>/* CREATE A NEW ROLE */
CREATE ROLE db_executor
/* GRANT EXECUTE TO THE ROLE */
GRANT EXECUTE TO db_executor
</code></pre>
<p>For just a user (not a role):</p>
<pre><code>USE [DBName]
GO
GRANT EXECUTE TO [user]
</code></pre> |
30,192,263 | Bootstrap JavaScript not working | <p>My toggle javascript buttons worked initially - however I have now found that my toggle button including navbar collapsing toggle and accordion panels.
I have included my header and footer. From what I have researched I cant see why it has stopped working.
Any help would be appreciated.</p>
<p>Header:
WEBSITE TITLE</p>
<pre><code> <!-- Bootstrap -->
<link href="style/css/bootstrap.min.css" rel="stylesheet">
<!--load font awesome-->
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.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>
</code></pre>
<p>Footer:</p>
<pre><code> <footer>
<div class="container">
<p>&copy; Company 2015</p>
</footer>
</div> <!-- /container -->
</div>
</body>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="../../dist/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="../../assets/js/ie10-viewport-bug-workaround.js"></script>
</body>
</html>
</code></pre> | 30,193,899 | 5 | 3 | null | 2015-05-12 13:25:25.75 UTC | 2 | 2022-09-18 13:16:12.503 UTC | 2015-05-12 13:32:29.097 UTC | null | 4,202,664 | null | 4,202,664 | null | 1 | 6 | javascript|twitter-bootstrap | 38,540 | <p>I guess you just copied what was said on the bootstrap side for example: </p>
<pre><code><script src="../../dist/js/bootstrap.min.js"></script>
</code></pre>
<p>If you have the js bootstrap file in one of your folders in the root, you might want to make sure it is the path is right. For example if your html file is in the same directory as your bootstrap.min.js it should be
<code><script src="bootstrap.min.js"></script></code>.</p>
<p>The quick fix you just did which is simply changing it to<br>
<code><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script></code></p>
<p>Might solve the problem now but it will render your local bootstrap file useless which you can make useful by using a <code>bootstrap cdn fallback</code>.
Which is basically loading your local bootstap files if you fail to load remote bootstrap files. <a href="https://stackoverflow.com/questions/25748112/load-local-bootstrap-css-and-js-if-load-fail-from-remote">This is how to make a bootstrap cdn callback</a></p> |
30,992,338 | How to debug memory leaks when Leaks instrument does not show them? | <p>I have an iOS app written in Swift that is leaking memory - in certain situation some objects should be released but they are not. I have learnt about the issue by simply adding <code>deinit</code> debug messages like this:</p>
<pre><code>deinit {
println("DEINIT: KeysProvider released")
}
</code></pre>
<p>So, the deinit message should be present in console after such events that should cause the object to release. However, for some of the objects that should be released, the message is missing. Still, Leaks Developer Tool does not show any leaks. How do I solve such situation?</p> | 30,993,476 | 2 | 1 | null | 2015-06-23 01:15:51.027 UTC | 49 | 2022-05-12 17:33:39.653 UTC | null | null | null | null | 311,865 | null | 1 | 71 | ios|swift|memory-management|memory-leaks|automatic-ref-counting | 25,277 | <p>In Xcode 8, you can click on the "Debug Memory Graph" button, <a href="https://i.stack.imgur.com/JFx6Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JFx6Z.png" alt="debugmemorygraphbutton" /></a> in the debug toolbar (shown at the bottom of the screen):</p>
<p><a href="https://i.stack.imgur.com/tzOFk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tzOFk.png" alt="debug memory graph" /></a></p>
<p>See Apple’s <a href="https://developer.apple.com/documentation/xcode/diagnosing-and-resolving-bugs-in-your-running-app#Visualize-and-Diagnose-Increasing-Memory-Usage" rel="nofollow noreferrer">Diagnosing and Resolving Bugs in Your Running App: Visualize and Diagnose Increasing Memory Usage</a>.</p>
<p>Just identify the object in the left panel that you think should have been deallocated, and it will show you the object graph (shown in the main canvas, above). This is very useful in quickly identifying where the strong references were established on the object in question. From here, you can start your research, diagnosing why those strong references were not resolved (e.g. if the object in question has a strong reference from something else that should have been deallocated, look at that object's graph, too, and you may find the issue (e.g. strong reference cycles, repeating timers, etc.).</p>
<p>Notice, that in the right panel, I'm seeing the call tree. I got that by turning on the "malloc stack" logging option in the scheme settings:</p>
<p><a href="https://i.stack.imgur.com/Wxkmx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wxkmx.png" alt="malloc stack" /></a></p>
<p>Anyway, having done that, one can then click on the arrow next to the relevant method call shown in the stack trace in the right panel of the first screen snapshot above, and you can see where that strong reference was originally established:</p>
<p><a href="https://i.stack.imgur.com/pZBhO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pZBhO.png" alt="code" /></a></p>
<hr />
<p>The traditional Instruments technique (especially useful if using older versions of Xcode) is described below, in my original answer.</p>
<hr />
<p>I would suggest using Instruments' "Allocations" tool with the "Record Reference Counts" feature:</p>
<p><img src="https://i.stack.imgur.com/A9mgM.png" alt="record reference counts" /></p>
<p>You can then run the app in Instruments and then search for your class that you know is leaking and drill in by clicking on the arrow:</p>
<p><img src="https://i.stack.imgur.com/qQFKm.png" alt="enter image description here" /></p>
<p>You can then drill into the details and look at the stack trace using the "Extended Details" panel on the right:</p>
<p><img src="https://i.stack.imgur.com/SY6pu.png" alt="extended details" /></p>
<p>In that "Extended Details" panel, focus on your code in black rather than the system calls in gray. Anyway, from the "Extended Details" panel, you can then drill into your source code, right in Instruments::</p>
<p><img src="https://i.stack.imgur.com/MlwDn.png" alt="your code" /></p>
<p>For more information and demonstrations in using Instruments to track down memory problems, please refer to:</p>
<ul>
<li>WWDC 2021 video <a href="https://developer.apple.com/videos/play/wwdc2021/10180/" rel="nofollow noreferrer">Detect and diagnose memory issues</a></li>
<li>WWDC 2019 video <a href="https://developer.apple.com/videos/play/wwdc2019/411" rel="nofollow noreferrer">Getting Started with Instruments</a></li>
<li>WWDC 2018 video <a href="https://developer.apple.com/videos/play/wwdc2018/416" rel="nofollow noreferrer">iOS Memory Deep Dive</a></li>
<li>WWDC 2013 video <a href="https://developer.apple.com/videos/wwdc/2013/?id=410" rel="nofollow noreferrer">Fixing Memory Issues</a></li>
<li>WWDC 2012 video <a href="https://developer.apple.com/videos/wwdc/2012/?id=242" rel="nofollow noreferrer">iOS App Performance: Memory</a></li>
</ul> |
47,243,139 | How to convert Set to string with space? | <p>I want to convert JavaScript <code>Set</code> to <code>string</code> with space.</p>
<p>For example, if I have a set like:</p>
<pre><code>var foo = new Set();
foo.add('hello');
foo.add('world');
foo.add('JavaScript');
</code></pre>
<p>And I'd like to print the string from the set: <code>hello world JavaScript</code> (space between each element).</p>
<p>I tried below codes but they are not working:</p>
<pre><code>foo.toString(); // Not working
String(foo); // Not working
</code></pre>
<p>Is there <strong>simplest and easiest way</strong> to convert from <strong>Set</strong> to <strong>string</strong>?</p> | 47,243,199 | 2 | 1 | null | 2017-11-11 21:49:59.777 UTC | 7 | 2021-07-08 13:48:46.447 UTC | 2020-01-24 15:24:01.587 UTC | null | 6,583,140 | null | 2,551,287 | null | 1 | 83 | javascript|string|ecmascript-6|set | 52,380 | <p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from" rel="noreferrer"><code>Array.from</code></a>:</p>
<pre><code>Array.from(foo).join(' ')
</code></pre>
<p>or the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax" rel="noreferrer">spread syntax</a>:</p>
<pre><code>[...foo].join(' ')
</code></pre> |
7,141,820 | use of python super function in django model | <p>Here's some code in a django tutorial that I'm going through. I've never come across the super function in python before and the way it's used here is different from the examples I've seen online. I.e., usually when you use super, don't you have multiple classes? It's in the last line: <code>super(Snippet, self).save(force_insert, force_update)</code>
Could you explain exactly what's going on there and what would be an alternative way to write that. It just seems like the save method is calling itself here?</p>
<pre><code>class Snippet(models.Model):
title = models.CharField(max_length=255)
language = models.ForeignKey(Language)
author = models.ForeignKey(User)
description = models.TextField()
description_html = models.TextField(editable=False)
code = models.TextField()
highlighted_code = models.TextField(editable=False)
tags = TagField()
pub_date = models.DateTimeField(editable=False)
updated_date = models.DateTimeField(editable=False)
class Meta:
ordering = ['-pub_date']
def __unicode__(self):
return self.title
def save(self, force_insert=False, force_update=False):
if not self.id:
self.pub_date = datetime.datetime.now()
self.updated_date = datetime.datetime.now()
self.description_html = markdown(self.description)
self.highlighted_code = self.highlight()
super(Snippet, self).save(force_insert, force_update)
</code></pre> | 7,141,837 | 2 | 0 | null | 2011-08-21 23:21:38.61 UTC | 9 | 2018-09-30 19:09:02.787 UTC | null | null | null | user637965 | null | null | 1 | 18 | python|django|super | 35,415 | <p><code>super(Snippet, self)</code> causes Python to look in the <a href="http://www.python.org/download/releases/2.3/mro/" rel="noreferrer">MRO</a> of the class of self (i.e. <code>self.__class__.mro()</code> for the <em>next</em> class listed after <code>Snippet</code>. It returns a <code>super</code> object which acts as a proxy for that class. That is, calling a method on the <code>super</code> object acts like calling that method on the class.</p>
<p><code>super(Snippet, self).save(...)</code> calls that class's <code>save</code> method, with <code>self</code> bound to the first argument.</p>
<p>So <code>super(Snippet, self).save(...)</code> will not call <code>Snippet</code>'s <code>save</code> method; it will call some other class's <code>save</code> method. It is tempting to think this "other class" is the "parent class" or "superclass" of <code>Snippet</code>, that is,
<code>models.Model</code>, but that may not be true and it is absolutely wrong to apprehend <code>super</code> this way. Which class <code>super(Snippet, self)</code> ultimately represents depends on <code>self</code> and in particular its class's MRO. </p>
<p>A very good description of the <code>MRO</code> and <code>super</code> (complete with pictures!) can be found <a href="https://web.archive.org/web/20170820065901/http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#method-resolution-order" rel="noreferrer">here</a>.</p> |
7,060,272 | Split up a dataframe by number of rows | <p>I have a dataframe made up of 400'000 rows and about 50 columns. As this dataframe is so large, it is too computationally taxing to work with.
I would like to split this dataframe up into smaller ones, after which I will run the functions I would like to run, and then reassemble the dataframe at the end. </p>
<p>There is no grouping variable that I would like to use to split up this dataframe. I would just like to split it up by number of rows. For example, I would like to split this 400'000-row table into 400 1'000-row dataframes.
How might I do this?</p> | 7,060,331 | 2 | 0 | null | 2011-08-14 22:50:30.313 UTC | 11 | 2021-07-26 21:51:37.007 UTC | 2016-03-01 14:02:32.983 UTC | null | 190,277 | null | 894,302 | null | 1 | 37 | r|split|dataframe | 41,321 | <p>Make your own grouping variable.</p>
<pre><code>d <- split(my_data_frame,rep(1:400,each=1000))
</code></pre>
<p>You should also consider the <code>ddply</code> function from the <code>plyr</code> package, or the <code>group_by()</code> function from <code>dplyr</code>.</p>
<p><strong>edited</strong> for brevity, after Hadley's comments.</p>
<p>If you don't know how many rows are in the data frame, or if the data frame might be an unequal length of your desired chunk size, you can do</p>
<pre><code>chunk <- 1000
n <- nrow(my_data_frame)
r <- rep(1:ceiling(n/chunk),each=chunk)[1:n]
d <- split(my_data_frame,r)
</code></pre>
<p>You could also use</p>
<pre><code>r <- ggplot2::cut_width(1:n,chunk,boundary=0)
</code></pre>
<p>For future readers, methods based on the <code>dplyr</code> and <code>data.table</code> packages will probably be (much) faster for doing group-wise operations on data frames, e.g. something like</p>
<pre><code>(my_data_frame
%>% mutate(index=rep(1:ngrps,each=full_number)[seq(.data)])
%>% group_by(index)
%>% [mutate, summarise, do()] ...
)
</code></pre>
<p>There are also <strong>many</strong> answers <a href="https://stackoverflow.com/questions/3318333/split-a-vector-into-chunks-in-r">here</a></p> |
18,893,198 | How to disable and enable the scrolling on android ScrollView? | <p>I am a android developer.I also want to use a ScrollView.This ScrollView need to some time disable scrolling and Some time enable scrolling .But i can no able to disable the scrolling .How to i implement it .Please help to me.I also try to use the some code such a s</p>
<pre><code>fullparentscrolling.setHorizontalFadingEdgeEnabled(false);
fullparentscrolling.setVerticalFadingEdgeEnabled(false);
</code></pre>
<p>or</p>
<pre><code> fullparentscrolling.setEnabled(false);
</code></pre>
<p>But it does not work.</p> | 18,893,487 | 4 | 1 | null | 2013-09-19 11:19:20.8 UTC | 6 | 2015-07-04 09:31:35.84 UTC | 2014-07-03 07:56:03.103 UTC | null | 1,367,622 | null | 2,014,570 | null | 1 | 29 | java|android|scrollview | 83,582 | <p>Try this way</p>
<p>Create Your CustomScrollview like this</p>
<pre><code>import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ScrollView;
public class CustomScrollView extends ScrollView {
private boolean enableScrolling = true;
public boolean isEnableScrolling() {
return enableScrolling;
}
public void setEnableScrolling(boolean enableScrolling) {
this.enableScrolling = enableScrolling;
}
public CustomScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomScrollView(Context context) {
super(context);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (isEnableScrolling()) {
return super.onInterceptTouchEvent(ev);
} else {
return false;
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (isEnableScrolling()) {
return super.onTouchEvent(ev);
} else {
return false;
}
}
}
</code></pre>
<p>In your xml</p>
<p>// "com.example.demo" replace with your packagename</p>
<pre><code><com.example.demo.CustomScrollView
android:id="@+id/myScroll"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</com.example.demo.CustomScrollView>
</code></pre>
<p>In your Activity</p>
<pre><code>CustomScrollView myScrollView = (CustomScrollView) findViewById(R.id.myScroll);
myScrollView.setEnableScrolling(false); // disable scrolling
myScrollView.setEnableScrolling(true); // enable scrolling
</code></pre> |
18,911,458 | AngularJs: Select Value From DropDown | <p>I am using AngularJS with JQM I create a drop-down for selecting value and data comies in it using AngularJS Controller. It works fine
But when I add <code>data-native-menu="false</code> in <code><select></code> then strange executions
I select first value it selected second.</p>
<p><strong>My HTML Part</strong></p>
<pre><code><div ng-controller="MyCtrl">
<select data-native-menu="false" data-role="listview" ng-options="size as size.name for size in sizes " ng-model="item" ng-change="update()"></select>
{{item.code}} {{item.name}}
</div>
</code></pre>
<p><strong>JS Part</strong></p>
<pre><code>myApp.controller('MyCtrl',function($scope){
$scope.sizes = [ {code: 1, name: 'n1'}, {code: 2, name: 'n2'}];
$scope.update = function() {
console.log($scope.item.code, $scope.item.name)
}});
</code></pre>
<p>If I remove <code>data-native-menu="false" data-role="listview"</code> then code works fine</p>
<p>Please Help Me</p>
<p>Demo Page of My Example is <a href="http://engineers-web.com/F09/NewDesign/#addexercise" rel="nofollow">Here</a></p> | 18,912,511 | 3 | 1 | null | 2013-09-20 07:45:10.08 UTC | 2 | 2016-06-21 16:11:49.27 UTC | 2013-09-20 08:42:50.15 UTC | null | 1,631,379 | null | 2,385,565 | null | 1 | 4 | javascript|jquery|jquery-mobile|angularjs | 42,698 | <p>You can find working code in <kbd><a href="http://jsfiddle.net/9Ymvt/507/" rel="noreferrer">Fiddle</a></kbd></p>
<p><strong>html</strong></p>
<pre><code><div ng-controller = "fessCntrl" >
<div query-mobile-tpl>
<select data-role="listview" data-inset="true" ng-options="size as size.name for size in sizes " ng-model="item" x-ng-change="update(item)"></select>
<pre> {{item.code | json}} {{item.name | json}}</pre>
</div>
</div>
</code></pre>
<p><strong>controller</strong></p>
<pre><code> var fessmodule = angular.module('myModule', []);
fessmodule.controller('fessCntrl', function ($scope) {
$scope.sizes = [ {code: 1, name: 'n1'}, {code: 2, name: 'n2'}];
$scope.update = function() {
console.log($scope.item.code, $scope.item.name)
};
});
fessmodule.directive('jqueryMobileTpl', function() {
return {
link: function(scope, elm, attr) {
elm.trigger('create');
}
};
});
fessmodule.directive('repeatDone', function () {
return function (scope, element, attrs) {
// When the last element is rendered
if (scope.$last) {
element.parent().parent().trigger('create');
}
}
});
fessmodule.$inject = ['$scope'];
</code></pre>
<p>Sounds like you use old angular sources or get collisions with other sources.</p>
<p>Hope it will help you</p> |
37,655,814 | Gradle sync failed: Unable to find method | <p>I try to import a project in Android studio. When importing it, i've got an Error with Gradle :</p>
<pre><code>Gradle sync failed: Unable to find method
'org.gradle.api.artifacts.Configuration.setExtendsFrom(Ljava/lang/Iterable;)Lorg/gradle/api/artifacts/Configuration;'.
</code></pre>
<p>I have tried :</p>
<ul>
<li><p>Re-download dependencies and sync project: Fail (same error).</p></li>
<li><p>Stop Gradle build processes: Fail (same error).</p></li>
<li><p>Delete the .graddle in the home directory: Fail (same error).</p></li>
<li><p>Invalidate cache and restart Fail (same error).</p></li>
<li><p>Uninstall and reinstall Android studio and SDK: Fail (same error).</p></li>
</ul>
<p><strong>/build.gradle :</strong></p>
<pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
</code></pre>
<p><strong>/app/build.gradle</strong></p>
<pre><code>apply plugin: 'com.android.application'
//apply plugin: 'android'
android {
compileSdkVersion 17
buildToolsVersion '20.0.0'
defaultConfig {
applicationId 'xxx.xxx.xxx'
minSdkVersion 17
targetSdkVersion 17
versionCode 1
versionName '1.0'
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
buildPB {
debuggable false
jniDebuggable false
renderscriptDebuggable false
zipAlignEnabled true
}
}
productFlavors {
}
// lintOptions {
// abortOnError false
// }
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// You must install or update the Support Repository through the SDK manager to use this dependency.
compile ('org.simpleframework:simple-xml:2.7.1') {
exclude module: 'stax'
exclude module: 'stax-api'
exclude module: 'xpp3'
}
compile 'net.sf.opencsv:opencsv:2.3'
compile 'de.greenrobot:greendao:1.3.7'
// You must install or update the Support Repository through the SDK manager to use this dependency.
// compile 'com.android.support:support-v4:19.+'
}
</code></pre> | 38,254,348 | 11 | 2 | null | 2016-06-06 11:05:34.697 UTC | 7 | 2019-10-28 08:10:47.72 UTC | 2019-09-13 12:01:46.29 UTC | null | 5,167,682 | null | 2,206,843 | null | 1 | 47 | java|android|android-studio|gradle | 73,591 | <p>I fixed the error by changing the following things.</p>
<ol>
<li>Open the file under your-app-project\your-app-name\gradle\wrapper\gradle-wrapper.properties</li>
<li><p>replace the old URL path by this one:
distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip</p></li>
<li><p>Rename the folder name from "...\1.12" to your-app-project\your-app-name.gradle\2.10</p></li>
<li><p>Change the classpath of your-app-project\your-app-name\build.gradle to
classpath 'com.android.tools.build:gradle:2.1.2'</p></li>
<li><p>Replace runProguard of your-app-project\your-app-name\app\build.gradle by minifyEnabled</p></li>
<li><p>Click Retry on the error reminder or Reopen your Android Studio and project.</p></li>
</ol>
<p>I am using the latest versions of Android Studio and Gradle.</p> |
36,793,381 | Python get first and last day of current calendar quarter | <p>I've built a function to get the first and last day of the current quarter but it's a bit long winded. I was wondering, is there a more succinct way of accomplishing this?</p>
<p>I understand that <code>pandas</code> has a <code>QuarterBegin()</code> function, but I couldn't implement it in a more concise way.</p>
<pre><code>import datetime as dt
from dateutil.relativedelta import relativedelta
def get_q(first=None,last=None):
today = dt.date.today()
qmonth = [1, 4, 7, 10]
if first:
for i,v in enumerate(qmonth):
if (today.month-1)//3 == i:
return dt.date(today.year,qmonth[i],1).strftime("%Y-%m-%d")
if last:
firstday = dt.datetime.strptime(get_q(first=True),"%Y-%m-%d")
lastday = firstday + relativedelta(months=3, days=-1)
return lastday.strftime("%Y-%m-%d")
</code></pre>
<hr>
<p>EDIT: Please let me know if this would be better suited to <a href="https://codereview.stackexchange.com/">Code Review</a></p> | 36,794,439 | 5 | 2 | null | 2016-04-22 12:04:09.04 UTC | 10 | 2017-07-25 16:59:22.753 UTC | 2017-04-13 12:40:36.833 UTC | null | -1 | null | 3,062,625 | null | 1 | 17 | python|python-2.7|datetime | 22,879 | <p>You can do it this way:</p>
<pre><code>import bisect
import datetime as dt
def get_quarter_begin():
today = dt.date.today()
qbegins = [dt.date(today.year, month, 1) for month in (1,4,7,10)]
idx = bisect.bisect(qbegins, today)
return str(qbegins[idx-1])
</code></pre>
<p>This solves the "first" case; I'm leaving the "last" case as an exercise but I suggest keeping it as an independent function for clarity (with your original version it's pretty strange what happens if no arguments are passed!).</p> |
18,003,021 | How to add border around TableLayout? | <p>Below is my table code. My screen looks like this <a href="http://imgur.com/dFP298o" rel="noreferrer">http://imgur.com/dFP298o</a> but I wanna make it looks like this <a href="http://imgur.com/YuYJiJx" rel="noreferrer">http://imgur.com/YuYJiJx</a>. How can I add borders around each row and around table layout?</p>
<pre><code><TableLayout
android:id="@+id/table2"
android:layout_width="fill_parent"
android:layout_below="@+id/test_button_text23"
android:layout_marginLeft="45dp"
android:layout_marginBottom="25dp"
android:layout_marginRight="45dp"
android:layout_height="fill_parent"
android:stretchColumns="*" >
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:gravity="left"
android:text="Quantity"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:textStyle="bold"
android:text="Item" />
</TableRow>
</TableLayout>
</code></pre>
<p> </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/localTime"
android:textColor="#000000"
android:gravity="left" />
<TextView
android:id="@+id/apprentTemp"
android:textColor="#000000"
android:gravity="center" />
</TableRow>
</code></pre>
<p> </p>
<pre><code>View row = getLayoutInflater().inflate(R.layout.rows, null);
((TextView) row.findViewById(R.id.localTime)).setText(item.getString("Item"));
((TextView) row.findViewById(R.id.apprentTemp)).setText(item.getString("Quantity"));
</code></pre> | 18,003,338 | 2 | 2 | null | 2013-08-01 19:37:26.15 UTC | 4 | 2020-05-04 06:56:54.917 UTC | 2017-02-06 23:34:03.32 UTC | null | 596,013 | null | 2,589,245 | null | 1 | 29 | android|android-tablelayout | 69,213 | <p>In order to create a border around your table rows and around the table layout, you need to create a drawable to serve as a border and then set it as a background to your rows.</p>
<p>For example:</p>
<p><strong>res/drawable/border.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape= "rectangle">
<solid android:color="#ffffff"/>
<stroke android:width="1dp" android:color="#000000"/>
</shape>
</code></pre>
<p><strong>res/layout/your_layout.xml</strong></p>
<pre><code><TableLayout
android:id="@+id/table2"
android:layout_width="fill_parent"
android:layout_below="@+id/test_button_text23"
android:layout_marginLeft="45dp"
android:layout_marginBottom="25dp"
android:layout_marginRight="45dp"
android:layout_height="fill_parent"
android:stretchColumns="*">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/border">
<TextView
android:gravity="left"
android:text="Quantity"
android:background="@drawable/border"
android:textStyle="bold"/>
<TextView
android:gravity="center"
android:textStyle="bold"
android:background="@drawable/border"
android:text="Item" />
</TableRow>
</TableLayout>
</code></pre>
<p>This won't look exactly like the picture you posted, but play with it to get what you want.</p> |
3,936,211 | jQuery "Cannot read property 'defaultView' of undefined" error | <p>I am using jQuery to post a form field to a PHP file that simply returns 1/0 depending on whether it worked or not...</p>
<p>Extract of the code:</p>
<pre><code>$.ajax({
url: "ajax/save_text.php", //Relative?!?
//PHP Script
type: "POST",
//Use post
data: 'test=' + $(this).val(),
datatype: 'text',
//Pass value
cache: false,
//Do not cache the page
success: function(html) {
if (html == 1) {
$(this).hide().siblings('span').html($(this).value).show();
alert("awesome!");
} else alert('It didn\'t work!');
},
//Error
error: function() {
alert("Another type of error");
}
});
</code></pre>
<p>However everytime it is successful (html == 1) the console throws up the error</p>
<blockquote>
<p>Uncaught TypeError: Cannot read property 'defaultView' of undefined"</p>
</blockquote>
<p>and the alert never happens...?</p>
<p>Google doesn't seem to have much info on this error and jQuery, who knows the cause?</p> | 3,936,230 | 1 | 0 | null | 2010-10-14 18:14:37.16 UTC | 2 | 2021-02-13 22:09:00.533 UTC | 2021-02-13 22:09:00.533 UTC | null | 863,110 | null | 193,376 | null | 1 | 25 | jquery|ajax | 73,250 | <p>It's because <code>this</code> isn't what you were dealing with before, it's now tha <code>ajax</code> jQuery object, add the <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer"><code>context</code> option of <code>$.ajax()</code></a> like this:</p>
<pre><code>$.ajax({
context: this,
url: "ajax/save_text.php",
...
</code></pre>
<p>This way <code>this</code> inside your callbacks refers to the same <code>this</code> as when you're calling <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer"><code>$.ajax()</code></a>. Alternatively, just hold onto a reference to <code>this</code> in a separate variable.</p>
<p>Also, you'll need to adjust <code>$(this).value</code>, you probably meant <code>this.value</code> or <code>$(this).val()</code>.</p> |
3,892,271 | How do I change the startup page on a WP7 Silverlight app? | <p>I have added a new XAML page to my WP7 app and I need the application to startup on this new page. How do I do that ? </p>
<p>I cannot find MainPage (which is the current / default start page) referenced anywhere in App.xaml or App.xaml.cs.</p> | 3,892,414 | 1 | 0 | null | 2010-10-08 15:59:17.437 UTC | 12 | 2013-12-13 11:34:40.013 UTC | null | null | null | null | 13,627 | null | 1 | 36 | silverlight|windows-phone-7 | 12,400 | <p>In WMAppManifest.xml you'll find the following.</p>
<pre><code><Tasks>
<DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
</Tasks>
</code></pre>
<p>Change as appropriate.</p> |
20,963,961 | SQL Server stored procedure to insert in multiple tables | <p>I have 2 tables, <code>custlogin</code> and <code>custinfo</code>:</p>
<p><code>custlogin</code>:</p>
<pre><code>custid int primary key auto notnull
custusename varchar(25)
custpassword varchar(50)
</code></pre>
<p><code>custinfo</code>:</p>
<pre><code>custid foriegnkey custlogin.custid ondelete set NULL
custfirstname varchar(25)
custlastname varchar(25)
custaddress varchar(100)
</code></pre>
<p>I want to write a stored procedure which will insert into both tables</p>
<p>More precisely, insert into <code>custlogin</code> with <code>custusername custpassword</code>, which would return <code>custid</code> for use as foreign key for <code>custinfo</code>.</p>
<p>I have searched much but I didn't find any solution.</p> | 20,964,015 | 1 | 2 | null | 2014-01-07 04:32:47.537 UTC | 2 | 2020-01-08 13:57:56.71 UTC | 2014-01-07 05:55:37.857 UTC | null | 13,302 | null | 3,167,711 | null | 1 | 6 | sql|sql-server|stored-procedures|insert | 47,952 | <p>It will be something like below. You can use <code>SCOPE_IDENTITY()</code> to get the last autogenerated ID withing the scope which is this stored proc in this case:</p>
<pre><code>create procedure NameOfYourProcedureHere
as
begin
SET NOCOUNT ON;
SET XACT_ABORT ON;
insert into custlogin(custusename, custpassword)
values ('','') -- put values here (from parameters?)
insert into custinfo(custid, custfirstname, custlastname, custaddress)
values (SCOPE_IDENTITY(), '', '', '') -- put other values here (from parameters?)
SET NOCOUNT OFF;
SET XACT_ABORT OFF;
end
</code></pre> |
41,001,192 | Setting a checkbox as checked with Vue.js | <p>I have been googling and playing with every combination I know but I cannot get my checkboxes to be initialised as checked.</p>
<p>Example:</p>
<pre><code><ul class="object administrator-checkbox-list">
<li v-for="module in modules">
<label v-bind:for="module.id">
<input type="checkbox" v-model="form.modules" v-bind:value="module.id" v-bind:id="module.id">
<span>@{{ module.name }}</span>
</label>
</li>
</ul>
</code></pre>
<p>An example of the modules data:</p>
<pre><code>[
{
"id": 1,
"name": "Business",
"checked": true
},
{
"id": 2,
"name": "Business 2",
"checked": false
},
]
</code></pre>
<p>What can I do to initially set the checked status of the checkboxes?</p> | 41,001,483 | 9 | 1 | null | 2016-12-06 17:18:26.96 UTC | 16 | 2022-09-01 23:38:27.84 UTC | null | null | null | null | 2,921,557 | null | 1 | 64 | javascript|vue.js | 224,751 | <p>To set the state of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over <code>modules</code> and each <code>module</code> has a <code>checked</code> property.</p>
<p>The following code will bind the checkbox to that property:</p>
<pre><code><input type="checkbox" v-model="module.checked" v-bind:id="module.id">
</code></pre>
<hr />
<p>If you'd like to know more about how v-model works in this situation, here's a link to <a href="https://vuejs.org/guide/essentials/forms.html" rel="nofollow noreferrer">the documentation about Form Input Binding</a>.</p> |
28,331,032 | Sails.js with React.js, how to do it correctly? | <p>I want to integrate React.js + browserify in my Sails.js-application.</p>
<p>For this I use a grunt-plugin <a href="https://www.npmjs.com/package/grunt-react" rel="nofollow noreferrer">grunt-react</a>.</p>
<p>I created a file <code>/tasks/config/browserify.js</code></p>
<pre><code>module.exports = function(grunt) {
grunt.config.set('browserify', {
//dev: {
options: {
transform: [ require('grunt-react').browserify ],
extension: 'jsx'
},
app: {
src: 'assets/jsx/app.jsx',
dest: '.tmp/public/js/app.js'
}
//}
});
grunt.loadNpmTasks('grunt-browserify');
};
</code></pre>
<p>Then I added a line in <code>compileAssets.js</code> and <code>syncAssets.js</code>:</p>
<pre><code>// compileAssets.js
module.exports = function (grunt) {
grunt.registerTask('compileAssets', [
'clean:dev',
'stylus:dev',
'browserify', // <<< this added
'copy:dev'
]);
};
</code></pre>
<p>and </p>
<pre><code>// syncAssets.js
module.exports = function (grunt) {
grunt.registerTask('syncAssets', [
'stylus:dev',
'browserify', // <<< this added
'sync:dev'
]);
};
</code></pre>
<p>Then i modified a line in <code>copy.js</code>.</p>
<pre><code>// copy.js
module.exports = function(grunt) {
grunt.config.set('copy', {
dev: {
files: [{
expand: true,
cwd: './assets',
src: ['**/*.!(styl|jsx)'], /// <<< this modified
dest: '.tmp/public'
}]
},
build: {
files: [{
expand: true,
cwd: '.tmp/public',
src: ['**/*'],
dest: 'www'
}]
}
});
grunt.loadNpmTasks('grunt-contrib-copy');
};
</code></pre>
<p><strong>And it worked!</strong></p>
<p>But I think I did not do it quite right.</p>
<p>If i uncommented line <code>dev: {</code> and <code>}</code> in <code>/tasks/config/browserify.js</code> like this:</p>
<pre><code>module.exports = function(grunt) {
grunt.config.set('browserify', {
dev: { /// <<< this uncommented
options: {
transform: [ require('grunt-react').browserify ],
extension: 'jsx'
},
app: {
src: 'assets/jsx/app.jsx',
dest: '.tmp/public/js/app.js'
}
} /// <<< this uncommented
});
grunt.loadNpmTasks('grunt-browserify');
};
</code></pre>
<p>And if I make changes in <code>compileAssets.js</code> and <code>syncAssets.js</code>:</p>
<pre><code>// compileAssets.js
module.exports = function (grunt) {
grunt.registerTask('compileAssets', [
'clean:dev',
'stylus:dev',
'browserify:dev', // <<< this added :dev
'copy:dev'
]);
};
</code></pre>
<p>and </p>
<pre><code>// syncAssets.js
module.exports = function (grunt) {
grunt.registerTask('syncAssets', [
'stylus:dev',
'browserify:dev', // <<< this added :dev
'sync:dev'
]);
};
</code></pre>
<p><strong>it does not work!</strong></p>
<p>Is it worth worrying about it?</p>
<p>And why is it not working when I add <code>browserify: dev</code> in <code>compileAssets.js</code> and <code>syncAssets.js</code> files?</p> | 28,332,622 | 2 | 1 | null | 2015-02-04 20:41:40.38 UTC | 10 | 2020-03-24 01:42:19.72 UTC | 2020-03-24 01:42:19.72 UTC | null | 1,193,786 | null | 1,018,328 | null | 1 | 15 | javascript|node.js|reactjs|gruntjs|sails.js | 14,501 | <p>I found the right solution.</p>
<p><strong>UPD: Now, we can use <a href="https://github.com/erikschlegel/sails-generate-reactjs" rel="noreferrer">https://github.com/erikschlegel/sails-generate-reactjs</a></strong></p> |
1,398,943 | Context Menu for XAML Treeviewitem (Distinguished by different attributes) | <p>In XAML, how do you define a context menu for treeviewitems that are distinguished by different attributes? </p> | 1,426,293 | 3 | 0 | null | 2009-09-09 10:52:59.99 UTC | 6 | 2016-10-19 11:49:05.023 UTC | 2016-02-18 11:32:57.103 UTC | null | 57,159 | null | 124,280 | null | 1 | 24 | wpf|xaml|contextmenu|treeviewitem | 43,501 | <h2>XAML</h2>
<pre><code><TreeView Name="SolutionTree" BorderThickness="0" SelectedItemChanged="SolutionTree_SelectedItemChanged" >
<TreeView.Resources>
<ContextMenu x:Key ="SolutionContext" StaysOpen="true">
<MenuItem Header="Add..." Click="AddFilesToFolder_Click"/>
<MenuItem Header="Rename"/>
</ContextMenu>
<ContextMenu x:Key="FolderContext" StaysOpen="true">
<MenuItem Header="Add..." Click="AddFilesToFolder_Click"/>
<MenuItem Header="Rename"/>
<MenuItem Header="Remove"/>
<Separator/>
<MenuItem Header="Copy"/>
<MenuItem Header="Cut"/>
<MenuItem Header="Paste"/>
<MenuItem Header="Move"/>
</ContextMenu>
</TreeView.Resources>
</TreeView>
</code></pre>
<h2>C-sharp</h2>
<pre><code>private void SolutionTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeViewItem SelectedItem = SolutionTree.SelectedItem as TreeViewItem;
switch (SelectedItem.Tag.ToString())
{
case "Solution":
SolutionTree.ContextMenu = SolutionTree.Resources["SolutionContext"] as System.Windows.Controls.ContextMenu;
break;
case "Folder":
SolutionTree.ContextMenu = SolutionTree.Resources["FolderContext"] as System.Windows.Controls.ContextMenu;
break;
}
}
</code></pre> |
2,214,066 | Get list of all input objects using JavaScript, without accessing a form object | <p>I need to get all the <code>input</code> objects and manipulate the <code>onclick</code> param.</p>
<p>The following does the job for <code><a></code> links. Looking for something like this for <code>input</code> tags.</p>
<pre class="lang-js prettyprint-override"><code>for (var ls = document.links, numLinks = ls.length, i=0; i<numLinks; i++){
var link = unescape(ls[i].href);
link = link.replace(/\\'/ig,"#");
if(ls[i].href.indexOf("javascript:") == -1)
{
ls[i].href = "javascript:LoadExtern(\\""+link+"\\",\\"ControlPanelContent\\",true,true);";
}
}
</code></pre> | 2,214,077 | 3 | 1 | null | 2010-02-06 18:02:07.333 UTC | 14 | 2019-08-28 06:46:06.137 UTC | 2017-10-05 14:20:06.757 UTC | null | 5,463,636 | null | 1,567,109 | null | 1 | 49 | javascript|html|input|field | 166,493 | <p><em>(See update at end of answer.)</em></p>
<p>You can get a <a href="https://developer.mozilla.org/En/DOM/NodeList" rel="noreferrer"><code>NodeList</code></a> of all of the <code>input</code> elements via <code>getElementsByTagName</code> (<a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-A6C9094" rel="noreferrer">DOM specification</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName" rel="noreferrer">MDC</a>, <a href="http://msdn.microsoft.com/en-us/library/ms536439(VS.85).aspx" rel="noreferrer">MSDN</a>), then simply loop through it:</p>
<pre><code>var inputs, index;
inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
</code></pre>
<p>There I've used it on the <code>document</code>, which will search the entire document. It also exists on individual elements (<a href="http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1938918D" rel="noreferrer">DOM specification</a>), allowing you to search only their descendants rather than the whole document, e.g.:</p>
<pre><code>var container, inputs, index;
// Get the container element
container = document.getElementById('container');
// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
}
</code></pre>
<p>...but you've said you don't want to use the parent <code>form</code>, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).</p>
<hr>
<p><strong>Update</strong>: <code>getElementsByTagName</code> is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the <code>input</code> elements?</p>
<p>That's where the useful <code>querySelectorAll</code> comes in: It lets us get a list of elements that match <strong>any CSS selector we want</strong>. So for our checkboxes example:</p>
<pre><code>var checkboxes = document.querySelectorAll("input[type=checkbox]");
</code></pre>
<p>You can also use it at the element level. For instance, if we have a <code>div</code> element in our <code>element</code> variable, we can find all of the <code>span</code>s with the class <code>foo</code> that are inside that <code>div</code> like this:</p>
<pre><code>var fooSpans = element.querySelectorAll("span.foo");
</code></pre>
<p><code>querySelectorAll</code> and its cousin <code>querySelector</code> (which just finds the <em>first</em> matching element instead of giving you a list) are supported by all modern browsers, and also IE8.</p> |
8,482,327 | Learning OpenGLES 2.0 on iOS | <p>I'm a beginner with OpenGL ES 2.0 and I'm looking for a good book/resource that will help me with my learning. I've found several books:</p>
<ul>
<li>OpenGL® ES 2.0 Programming Guide</li>
<li>iPhone 3D Programming: Developing Graphical Applications with OpenGL ES</li>
</ul>
<p>but reading the Amazon reviews I saw that they either assume previous knowledge with OpenGL or are not written specifically for iOS. (I know OpenGL should be easy to port, but I'm looking for a book/resource with examples in C, not C++, that talks about OpenGL in the iOS context)</p>
<p>I also found <a href="http://iphonedevelopment.blogspot.com/2009/05/opengl-es-from-ground-up-table-of.html">this</a> and it really helped me getting a grasp on the basic concepts, but unfortunately, they cover OpenGL ES 1.1 and are only describing the basics.</p>
<p>Any help would be appreciated!</p> | 8,495,261 | 4 | 1 | null | 2011-12-12 23:16:28.893 UTC | 41 | 2017-05-09 00:20:59.13 UTC | 2013-05-03 17:50:49.727 UTC | user1228 | null | null | 399,707 | null | 1 | 28 | iphone|ios|opengl-es|opengl-es-2.0 | 18,469 | <p>It's a lot easier to find OpenGL ES 2.0 material for iOS (or any OS, really) than it used to be a year or so ago.</p>
<p>For something written from a pure iOS perspective, it's hard to beat Jeff LaMarche's chapters from his unpublished book, which start <a href="https://web.archive.org/web/20160714041352/http://iphonedevelopment.blogspot.com/2010/10/opengl-es-20-for-ios-chapter-1.html" rel="nofollow noreferrer">here</a>. You linked to his OpenGL ES 1.1 tutorials, which are also great, but he didn't place his newer 2.0 material on that list.</p>
<p><a href="http://oreilly.com/catalog/9780596804831" rel="nofollow noreferrer">iPhone 3D Programming</a> by Philip Rideout is a great book that covers both OpenGL ES 1.1 and 2.0. It does not assume that you know OpenGL ES, and he does explain a good bit of the math and other fundamentals required to understand what he's talking about. He gets into some pretty advanced techniques towards the end. However, all of his code is in C++, rather than Objective-C, so that may be a little disconcerting for someone used to Cocoa development. Still, the core C API for OpenGL ES is the same, so it's easy to see what's going on.</p>
<p>If you're looking for particular effects, the <a href="https://rads.stackoverflow.com/amzn/click/com/0321637631" rel="nofollow noreferrer" rel="nofollow noreferrer">OpenGL Shading Language</a> book is still one of the primary resources you can refer to. While written for desktop OpenGL, most of the shading language and shaders presented there translate directly across to OpenGL ES 2.0, with only a little modification required.</p>
<p>The books <a href="https://rads.stackoverflow.com/amzn/click/com/1584505443" rel="nofollow noreferrer" rel="nofollow noreferrer">ShaderX6</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/1584505982" rel="nofollow noreferrer" rel="nofollow noreferrer">ShaderX7</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/1568814720" rel="nofollow noreferrer" rel="nofollow noreferrer">GPU Pro</a>, and <a href="https://rads.stackoverflow.com/amzn/click/com/1568817185" rel="nofollow noreferrer" rel="nofollow noreferrer">GPU Pro 2</a> also have sections devoted to OpenGL ES 2.0, which provide some rendering and tuning hints that you won't find elsewhere. Those are more advanced (and expensive) books, though.</p>
<p>If you're just getting started with OpenGL ES 2.0, it might not be a bad idea to start using GLKit (available only on iOS 5.0), which simplifies some of the normal setup chores around your render buffers and simple shader-based effects. Apple's <a href="https://developer.apple.com/videos/wwdc/2011/" rel="nofollow noreferrer">WWDC 2011 videos</a> have some good material on this, but their 2009 and 2010 videos (if you can find them, some are available at <a href="https://developer.apple.com/videos/archive/" rel="nofollow noreferrer">apple archive</a>) provide a lot more introductory material around OpenGL ES 2.0.</p>
<p>Finally, as Andy mentions, I taught a class on the subject as part of my course on iTunes U, which you can download for free <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=407243028" rel="nofollow noreferrer">here</a>. The course notes for that class can be found <a href="http://www.sunsetlakesoftware.com/sites/default/files/Fall2010CourseNotes/index.html" rel="nofollow noreferrer">here</a> or downloaded as a VoodooPad file <a href="http://www.sunsetlakesoftware.com/sites/default/files/AdvancediOSDevelopmentFall2010.zip" rel="nofollow noreferrer">here</a>. I warn you that I go a little technical quite fast in the OpenGL ES 2.0 session, so you may want to watch the 1.1 session from the previous semester <a href="http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewPodcast?id=407243032" rel="nofollow noreferrer">here</a>. I also talk a little bit about what I've done with OpenGL ES 2.0 in <a href="http://www.sunsetlakesoftware.com/2011/05/08/enhancing-molecules-using-opengl-es-20" rel="nofollow noreferrer">this article</a> about my open source application (whose source code can be grabbed from <a href="http://www.sunsetlakesoftware.com/molecules" rel="nofollow noreferrer">here</a>, if you'd like to play with a functional OpenGL ES 2.0 iOS application).</p> |
8,937,817 | DownloadManager.ACTION_DOWNLOAD_COMPLETE broadcast receiver receiving same download id more than once with different download statuses in Android | <p>I am using Android DownloadManger System Service for downloading some files in following way </p>
<pre><code>dwnId = mgr.enqueue(new DownloadManager.Request(serveruri)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI |
DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(getAlbumName())
.setDescription(getTrackName())
.setDestinationUri(deviceUri)
.setShowRunningNotification(true));
</code></pre>
<p>where <code>mgr</code> is Download Manager instance, <code>dwnId</code> is unique ID returned. I am also registering for <code>ACTION_DOWNLOAD_COMPLETE</code></p>
<pre><code>registerReceiver(onDownloadComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
</code></pre>
<p>and in the onDownloadComplete BroadcastReceiver's onReceive() method I am getting download Id like</p>
<pre><code>Long dwnId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
</code></pre>
<p>After that I am querying Download Manager for Download status</p>
<pre><code>Cursor c = downloadManager.query(new DownloadManager.Query().setFilterById(dwnId)); c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
</code></pre>
<p>for DownloadManager.STATUS_* constants. </p>
<p>The problem is I am receiving the same downId twice (means onReceive method is called twice), once with DownloadManager.STATUS_SUCCESSFUL status and once with DownloadManager.STATUS_FAILED status for same dwnId. I am issuing request to download some 10 files at a time and but on device download manager it is showing the download count as some 12 or 13 in the notification bar top left means. I think that Download manager has some problem in downloading files and resumed or automatically restarted to download the same file again. Thats why there is a difference between the files count I requested to download and actual number in download queue. Because of this only I am getting same DownloadId complete action twice. If this is true, how to restrict it. Am I wrong what might be the reason for count difference between what I requested to actual download? Why is the broadcast receiver receiving the same download Id twice. Can anybody please let me know?</p>
<p>Thanks In Advance... </p> | 10,165,819 | 3 | 1 | null | 2012-01-20 06:57:51.943 UTC | 18 | 2021-10-25 14:01:36.327 UTC | 2012-01-21 03:45:13.04 UTC | null | 676,625 | null | 676,625 | null | 1 | 32 | android|download|broadcastreceiver|broadcast|download-manager | 31,678 | <p>This is a reported bug see: <a href="http://code.google.com/p/android/issues/detail?id=18462" rel="noreferrer">http://code.google.com/p/android/issues/detail?id=18462</a></p>
<p>The way around I found is to verify if the download was a success, if not ditch the intent or re-queue the file if it was never downloaded...</p>
<p>Lost a couple of hours figuring that one :(</p>
<p>** Edit: adding code example **</p>
<pre><code>/**
* Check if download was valid, see issue
* http://code.google.com/p/android/issues/detail?id=18462
* @param long1
* @return
*/
private boolean validDownload(long downloadId) {
Log.d(TAG,"Checking download status for id: " + downloadId);
//Verify if download is a success
Cursor c= dMgr.query(new DownloadManager.Query().setFilterById(downloadId));
if(c.moveToFirst()){
int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if(status == DownloadManager.STATUS_SUCCESSFUL){
return true; //Download is valid, celebrate
}else{
int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
Log.d(TAG, "Download not correct, status [" + status + "] reason [" + reason + "]");
return false;
}
}
return false;
}
</code></pre>
<p>For complete code see : <a href="https://github.com/flegare/JAV387_LaboWidget/blob/master/src/com/mobidroid/widgetfact/service/FactService.java" rel="noreferrer">https://github.com/flegare/JAV387_LaboWidget/blob/master/src/com/mobidroid/widgetfact/service/FactService.java</a> </p> |
8,933,307 | Clone a collection in MongoDB | <p>I want to clone a MongoDB collection and save it on the same server with a different name. So for example right now I have the following collections: demo1.categories, demo1.users and demo2.users.</p>
<p>I want to have a "demo2.categories" which is identical to "demo1.categories". (It just has a different name.)</p> | 8,933,781 | 8 | 1 | null | 2012-01-19 21:08:20.023 UTC | 19 | 2021-01-22 13:02:33.61 UTC | 2021-01-22 13:02:33.61 UTC | null | 1,746,118 | null | 260,031 | null | 1 | 59 | mongodb|mongo-collection | 55,272 | <p>Yet again the <a href="http://www.mongodb.org/display/DOCS/Developer+FAQ#DeveloperFAQ-HowdoIcopyallobjectsfromonedatabasecollectiontoanother?">MongoDB documentation comes to the rescue</a></p>
<p>assuming that the collection actually is named "demo1.categories":</p>
<pre><code>db.demo1.categories.find().forEach( function(x){db.demo2.categories.insert(x)} );
</code></pre> |
8,937,384 | What is the difference between HTML tags and elements? | <p>I notice that most people use the words <em>HTML tags</em> and <em>HTML elements</em> interchangeably. </p>
<p>But what is the difference between them? </p>
<p>The way I see it is that tags are in the source code and elements are processed tags (by the browser) in the DOM. Am I wrong?</p> | 8,937,454 | 9 | 1 | null | 2012-01-20 06:04:38.693 UTC | 31 | 2022-08-14 14:52:15.573 UTC | 2016-05-31 21:41:32.563 UTC | null | 1,591,669 | null | 744,184 | null | 1 | 92 | html|terminology | 147,220 | <p>HTML tag is just opening or closing entity. For example:</p>
<p><code><p></code> and <code></p></code> are called HTML tags</p>
<p>HTML element encompasses opening tag, closing tag, content (optional for content-less tags)
Eg:</p>
<p><code><p>This is the content</p></code> : This complete thing is called a HTML element</p> |
27,014,207 | Failure to use adaptiveThreshold: CV_8UC1 in function adaptiveThreshold | <p>I have used openCV python and encountered an error.</p>
<pre><code>img_blur = cv2.medianBlur(self.cropped_img,5)
img_thresh_Gaussian = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
plt.subplot(1,1,1),plt.imshow(img_thresh_Gaussian, cmap = 'gray')
plt.title("Image"), plt.xticks([]), plt.yticks([])
plt.show()
</code></pre>
<p>but I received:</p>
<pre><code>cv2.error: /home/phuong/opencv_src/opencv/modules/imgproc/src/thresh.cpp:1280: error: (-215) src.type() == CV_8UC1 in function adaptiveThreshold
</code></pre>
<p>Do I have to install something else?</p> | 28,145,603 | 7 | 2 | null | 2014-11-19 10:14:59.073 UTC | 5 | 2021-01-03 18:29:15.877 UTC | 2015-12-27 08:49:33.757 UTC | null | 1,090,562 | null | 4,086,376 | null | 1 | 46 | python|opencv | 89,784 | <p>you should load your file like this </p>
<pre><code>src.create(rows, cols, CV_8UC1);
src = imread(your-file, CV_8UC1);
</code></pre>
<p>and after that </p>
<pre><code>adaptiveThreshold(src, dst, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 75, 10);
</code></pre> |
109,855 | Where can I find a complete reference of the ncurses C API? | <p>Where can I find a complete reference of the ncurses C API?</p> | 13,573,388 | 4 | 1 | null | 2008-09-21 00:14:36.47 UTC | 5 | 2016-07-02 11:28:59.973 UTC | 2016-07-02 11:28:59.973 UTC | null | 895,245 | computergeek6 | 19,470 | null | 1 | 41 | c|api|reference|ncurses | 29,075 | <p>I found this question a while back, but none of the answers so far answer the original question. The complete freely available API reference is available through the . . . </p>
<p><a href="http://invisible-island.net/ncurses/man/ncurses.3x.html">NCURSES MAN PAGES</a></p> |
37,564 | What exactly is Appdomain recycling | <p>I am trying to figure out what exactly is Appdomain recycling?
When a aspx page is requested for the first time from a DotNet application, i understand that an appdomain for that app is created, and required assemblies are loaded into that appdomain, and the request will be served.
Now, if the web.config file or the contents of the bin folder, etc are modified, the appdomain will be "recycled".
My question is, at the end of the recycling process, will the appdomain be loaded with assemblies and ready to serve the next request? or a page has to be requested to trigger the assemblies to load?.</p> | 5,651,141 | 4 | 0 | null | 2008-09-01 07:24:22.857 UTC | 18 | 2014-12-01 19:43:09.86 UTC | null | null | null | kudlur | 1,647 | null | 1 | 46 | asp.net | 32,341 | <p>Well, I think the thread was getting smoothly to a final conclusion, but in the end, it was otherwise.</p>
<p>I'll try to answer the question based on my understanding and leveraging what i've just read about in other web sites.</p>
<p>First of all, I myself try to avoid the term recycle other than for Application Pools since this may render someone confused. Now, getting to process, pools and AppDomain, I see the picture as follows:</p>
<p>An Application Pool is, in short, a region of memory that is maintained up and running by a process called W3WP.exe, aka Worker Process. Recycling an Application Pool means bringing that process down, eliminating it from memory and then originating a brand new Worker Process, with a newly assigned process ID.</p>
<p>Regarding Application Domains, I see it as subsets of memory regions, within the aforementioned region that plays the role of a container. In other words, the process in memory, W3WP.exe in this case, is a macro memory region for applications that stores subset regions, called Application Domains. Having said that, one process in memory may store different Application Domains, one for each application that is assigned to run within a given Application Pool.</p>
<p>When it comes to recycling, as I initially told, it's something that I myself reserve only for Application Pools. For AppDomains, I prefer using the term 'restart', in order to avoid misconception. Based on this, restarting a AppDomain means starting over a given application with the newly added settings, such as refreshing the existing configuration. That happens within the boundaries of that sub-region of memory, called AppDomain, that ultimately lies within the process associated with a respective Application Pool. Those new settings may come from files such as </p>
<p>web.config,
machine.config,
global.asax,
Bin directory,
App_Code,</p>
<p>and there may be others.</p>
<p>AppDomain are isolated from each other, that makes total sense. If not so, if changes to a web.config, let's say, of application 1, requited recycle of the pool, all other applications assigned to that pool would get restarted, what was definitely not desired by Microsoft and by anyone else.</p>
<p>Summarizing my point, </p>
<ul>
<li>Process (W3WP.exe)
<ul>
<li>AppDomain 1</li>
<li>AppDomain 2</li>
<li>AppDomain 3</li>
<li>AppDomain n</li>
</ul></li>
</ul>
<p>n = the number of assigned applications to the Application Pool managed by the given W3WP.exe</p>
<ul>
<li>Processes are memory regions isolated from one another</li>
<li>AppDomains are sub-memory regions isolated from one another, within the same process</li>
<li>Global IIS settings changes may require Application Pool recycle (killing and starting a new Worker Process, W3WP.exe)</li>
<li>Application-wide settings changes AppDomains concerns, and they may get restarted after changes in some specific files such as the ones outline above</li>
</ul>
<p>For further information, I recommend:</p>
<p><a href="http://blogs.msdn.com/b/david.wang/archive/2006/03/12/thoughts-on-iis-configuration-changes-and-when-it-takes-effect.aspx" rel="noreferrer">http://blogs.msdn.com/b/david.wang/archive/2006/03/12/thoughts-on-iis-configuration-changes-and-when-it-takes-effect.aspx</a></p>
<p><a href="https://stackoverflow.com/questions/302110/what-causes-an-application-pool-in-iis-to-recycle">What causes an application pool in IIS to recycle?</a></p>
<p><a href="http://blogs.msdn.com/b/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx" rel="noreferrer">http://blogs.msdn.com/b/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx</a></p>
<p>Regards from Brazil!</p> |
2,512,852 | How do I setup ASP.NET MVC 2 with MySQL? | <p>Is it possible to setup ASP.NET MVC 2 to work with a MySQL database?</p> | 2,518,321 | 2 | 6 | null | 2010-03-25 03:14:03.147 UTC | 29 | 2011-11-02 21:04:28.733 UTC | 2010-03-25 14:23:59.957 UTC | null | 172,196 | null | 158,970 | null | 1 | 27 | mysql|asp.net-mvc|asp.net-membership|mysql-connector | 15,027 | <p>I'm assuming that you have Visual Studio Professional 2008, have access to an instance of MySQL server, and have moderate to advanced development experience. This MAY work with VS2008 Web edition, but not at all sure.</p>
<ol>
<li>If you haven't, install <a href="http://dev.mysql.com/downloads/connector/net/" rel="noreferrer">MySQL Connector for .NET</a> (6.2.2.0 at the time of this write-up)</li>
<li>Optional: install <a href="http://dev.mysql.com/downloads/gui-tools/5.0.html" rel="noreferrer">MySQL GUI Tools</a></li>
<li>If you haven't, install <a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=c9ba1fe1-3ba8-439a-9e21-def90a8615a9" rel="noreferrer">MVC 2 RTM</a>, or better yet, use Microsoft's <a href="http://www.microsoft.com/web/downloads/platform.aspx" rel="noreferrer">Web Platform Installer</a>. (<strong>UPDATE:</strong> MVC 2 has now been released for quite some time)</li>
<li>Create an empty MySQL database. If you don't want to access your application with the MySQL root user account (insecure), create a user account and assign the appropriate privileges (outside the scope of this write-up).</li>
<li>Create a new MVC 2 application in Visual Studio</li>
<li>In the MVC 2 app, reference MySql.Web.dll. It will either be in your GAC, or in the folder that the MySQL Connector installer put it.</li>
<li><p>Modify the connection strings portion of your web.config:</p>
<pre><code> <connectionStrings>
<remove name="LocalMySqlServer"/>
<add name="MySqlMembershipConnection"
connectionString="Data Source=[MySql server host name];
userid=[user];
password=[password];
database=[database name];"
providerName="MySql.Data.MySqlClient"/>
</connectionStrings>
</code></pre>
<p>8.</p>
<p>Modify the membership portion of your web.config:</p>
<pre><code> <membership defaultProvider="MySqlMembershipProvider">
<providers>
<clear/>
<add name="MySqlMembershipProvider"
type="MySql.Web.Security.MySQLMembershipProvider, MySql.Web,
Version=6.2.2.0, Culture=neutral,
PublicKeyToken=c5687fc88969c44d"
connectionStringName="MySqlMembershipConnection"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
requiresUniqueEmail="true"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/"
autogenerateschema="true"/>
</providers>
</membership>
</code></pre>
<p>9.</p>
<p>Modify the role manager portion of your web.config:</p>
<pre><code> <roleManager enabled="true" defaultProvider="MySqlRoleProvider">
<providers>
<clear />
<add connectionStringName="MySqlMembershipConnection"
applicationName="/"
name="MySqlRoleProvider"
type="MySql.Web.Security.MySQLRoleProvider, MySql.Web,
Version=6.2.2.0, Culture=neutral,
PublicKeyToken=c5687fc88969c44d"
autogenerateschema="true"/>
</providers>
</roleManager>
</code></pre>
<p>10.</p>
<p>Modify the profile portion of your web.config:</p>
<pre><code> <profile>
<providers>
<clear/>
<add type="MySql.Web.Security.MySQLProfileProvider, MySql.Web,
Version=6.2.2.0, Culture=neutral,
PublicKeyToken=c5687fc88969c44d"
name="MySqlProfileProvider"
applicationName="/"
connectionStringName="MySqlMembershipConnection"
autogenerateschema="true"/>
</providers>
</profile>
</code></pre></li>
</ol>
<p>At this point, you ought to be able to run the app and have the default ASP.NET MVC 2 home page come up in your browser. However, it may be a better idea to first run the ASP.NET Web configuration Tool (in Visual Studio top menus: Project -> ASP.NET Configuration). Once the tool launches, check out each of the tabs; no errors = all good.</p>
<p>The configuration tool at <a href="http://www.integratedwebsystems.com/2010/02/how-to-setup-and-configure-mysql-membership-provider-6-2-2-porting-to-mono-part-2-of-3/" rel="noreferrer">Nathan Bridgewater's blog</a> was essential to getting this working. Kudos, Nathan. Look for the "Configuration Tool" heading half way down the page.</p>
<p>The public key token on the MySql.web.dll that I've posted here ought not change any time soon. But in case you suspect a bad token string from copying and pasting or whatever, just use the Visual Studio command line to run: "sn -T [Path\to\your.dll]" in order to get the correct public key token.</p>
<p>There you have it, ASP.NET MVC 2 running over MySQL. Cheers!</p> |
48,570,827 | From string to enum using mapstruct | <p>I want to convert String to enum using mapstruct</p>
<pre><code>enum TestEnum {
NO("no");
String code;
TestEnum(String code) {
this.code = code
}
public String getCode() {
return code;
}
}
</code></pre>
<p>I have a code that I've got from service and I want to convert this code to Enum how to do it with easier way by mapstruct</p> | 48,622,270 | 3 | 1 | null | 2018-02-01 20:03:00.787 UTC | 1 | 2018-12-29 12:14:10.427 UTC | 2018-02-01 21:14:27.153 UTC | null | 1,045,902 | null | 2,022,081 | null | 1 | 10 | java|enums|mapstruct | 41,516 | <p>Here is a solution with an abstract mapper, but if you want you can convert it with a default methode or a class </p>
<pre><code>@Mapper
public abstract class TestMapper {
abstract Source toSource(Target target);
abstract Target totarget(Source source);
String toString(TestEnum test){
return test.getCode();
}
TestEnum toEnum(String code){
for (TestEnum testEnum : TestEnum.values()) {
if(testEnum.equals(code)){
return testEnum;
}
}
return null;
}
}
public class Source {
String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public class Target {
TestEnum value;
public TestEnum getValue() {
return value;
}
public void setValue(TestEnum value) {
this.value = value;
}
}
</code></pre> |
20,705,643 | Method Overloading with different return type | <p>I am want to dig in that whether it is an ambiguity or an extra feature that is provided:</p>
<pre><code> public class Foo
{
public int Bar(){
//code
}
public string Bar(int a){
//code
}
}
</code></pre>
<p>Any one having any experience with this, overloading on return type with different parameters should be a bad practice, is it?</p>
<p>But if the overloading was done on the basis of return type then why this is not working for. </p>
<pre><code> public class Foo
{
public int Bar(int a){
//code
}
public string Bar(int a){
//code
}
}
</code></pre>
<p>As it will be unable to decide which function to call 1st or second, if we call obj.Bar(); , it should end in error do any one have any idea about it why it allows first code snippet to run.</p> | 20,705,709 | 9 | 0 | null | 2013-12-20 14:20:38.49 UTC | 3 | 2022-07-25 13:59:00.72 UTC | 2017-03-16 19:04:23.94 UTC | null | 480,982 | null | 2,285,848 | null | 1 | 20 | c#|.net|oop|coding-style | 65,588 | <p>The C# specification (section 10.6) states that overloaded members may not differ by only return type and as per <a href="http://msdn.microsoft.com/en-us/library/ms229029.aspx">http://msdn.microsoft.com/en-us/library/ms229029.aspx</a></p>
<p>As per your question regarding creating parameters simply to support differing return types? I personally believe that is a terrible solution to the problem. Code maintenance will become difficult and unused parameters are a definite code smell. Does the method really need to be overloaded in that case? Or does it belong in that class? Should something else be created to convert from one return type to another? All things you should ask to derive a more idiomatic solution.</p> |
18,900,236 | Run command on the Ansible host | <p>Is it possible to run commands on the Ansible host?</p>
<p>My scenario is that I want to take a checkout from a git server that is hosted internally (and isn't accessible outside the company firewall). Then I want to upload the checkout (tarballed) to the production server (hosted externally).</p>
<p>At the moment, I'm looking at running a script that does the checkout, tarballs it, and then runs the deployment script - but if I could integrate this into Ansible that would be preferable.</p> | 18,907,395 | 8 | 0 | null | 2013-09-19 16:29:18.233 UTC | 68 | 2022-07-18 14:40:12.103 UTC | 2022-07-15 15:16:04.997 UTC | null | 967,621 | null | 2,025 | null | 1 | 287 | deployment|ansible|localhost|host | 249,166 | <p>Yes, you can run commands on the Ansible host. You can specify that all tasks in a play run on the Ansible host, or you can mark individual tasks to run on the Ansible host.</p>
<p>If you want to run an entire play on the Ansible host, then specify <code>hosts: 127.0.0.1</code> and <code>connection:local</code> in the play, for example:</p>
<pre class="lang-yaml prettyprint-override"><code> - name: a play that runs entirely on the ansible host
hosts: 127.0.0.1
connection: local
tasks:
- name: check out a git repository
git: repo=git://foosball.example.org/path/to/repo.git dest=/local/path
</code></pre>
<p>See <a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_delegation.html#local-playbooks" rel="nofollow noreferrer">Local Playbooks</a> in the Ansible documentation for more details.</p>
<p>If you just want to run a single task on your Ansible host, you can use <code>local_action</code> to specify that a task should be run locally. For example:</p>
<pre class="lang-yaml prettyprint-override"><code> - name: an example playbook
hosts: webservers
tasks:
- ...
- name: check out a git repository
local_action: git repo=git://foosball.example.org/path/to/repo.git dest=/local/path
</code></pre>
<p>See "<a href="https://docs.ansible.com/ansible/latest/user_guide/playbooks_delegation.html#" rel="nofollow noreferrer">Controlling where tasks run: delegation and local actions</a>" in the Ansible documentation for more details.</p>
<hr />
<p>You can avoid having to type <code>connection: local</code> in your play by adding this to your inventory:</p>
<pre><code>localhost ansible_connection=local
</code></pre>
<p>(Here you'd use "<code>localhost</code>" instead of "<code>127.0.0.1</code>" to refer to the play).</p>
<hr />
<p>In newer versions of Ansible, you no longer need to add the above line to your inventory, Ansible assumes it's already there.</p> |
19,044,660 | socket.io get rooms which socket is currently in | <p>Is it possible to get rooms which socket is currently in, without calling</p>
<pre><code>io.sockets.clients(roomName)
</code></pre>
<p>for every room name and looking for this socket in results</p> | 19,049,708 | 12 | 0 | null | 2013-09-27 07:04:10.94 UTC | 8 | 2022-03-29 09:36:01.153 UTC | null | null | null | null | 1,366,643 | null | 1 | 26 | node.js|websocket|socket.io | 52,594 | <p>From the <a href="https://github.com/LearnBoost/socket.io/wiki/Rooms#rooms-a-client-has-joined" rel="noreferrer">Socket.IO Room doc</a>:</p>
<p><code>io.sockets.manager.roomClients[socket.id]</code></p> |
23,963,979 | How would I detect all European countries with CloudFlare geolocation | <p>I'm trying to detect whether a user is visiting my website from a European country or not. I'm using the Cloudflare proxy & CDN so have to make use of the headers that they pass on (like so):</p>
<pre><code>$country_code = $_SERVER["HTTP_CF_IPCOUNTRY"];
</code></pre>
<p>I'm not sure what return values I should be listening out for from Cloudflare that would allow me to do something like this:</p>
<pre><code>if($location == '1' || $location == '2' || $location == '3'){
// Europe
}else{
// Not Europe
}
</code></pre>
<p>so can anyone help me work out the values I should process?</p>
<p>Thanks for any help!</p> | 23,964,105 | 2 | 0 | null | 2014-05-30 22:00:22.5 UTC | 9 | 2021-03-25 02:32:46.47 UTC | 2020-01-10 22:52:17.543 UTC | null | 3,183,587 | null | 3,183,587 | null | 1 | 13 | php|geolocation|cloudflare|ip-geolocation | 12,291 | <p>The value of <code>$_SERVER["HTTP_CF_IPCOUNTRY"]</code> is a country code. So first you will need a <a href="http://www.geohive.com/earth/gen_codes.aspx" rel="noreferrer">list</a> of all the European country codes.</p>
<pre><code>$europe = array('AD', 'AL', 'AT', 'AX', 'BA', 'BE', 'BG', 'BY', 'CH', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FO', 'FR', 'GB', 'GG', 'GI', 'GR', 'HR', 'HU', 'IE', 'IM', 'IS', 'IT', 'JE', 'LI', 'LT', 'LU', 'LV', 'MC', 'MD', 'ME', 'MK', 'MT', 'NL', 'NO', 'PL', 'PT', 'RO', 'RS', 'RU', 'SE', 'SI', 'SJ', 'SK', 'SM', 'UA', 'VA');
</code></pre>
<p>You can then use this list to validate the request:</p>
<pre><code>if(in_array($country_code, $europe)) {
// Europe
} else {
// Not Europe
}
</code></pre>
<p>If you want to target specific regions, you can use these lists:</p>
<pre><code>$eastern = array('BG', 'BY', 'CZ', 'HU', 'MD', 'PL', 'RO', 'RU', 'SK', 'UA');
$northern = array('AX', 'DK', 'EE', 'FI', 'FO', 'GB', 'GG', 'IE', 'IM', 'IS', 'JE', 'LT', 'LV', 'NO', 'SE', 'SJ');
$southern = array('AD', 'AL', 'BA', 'ES', 'GI', 'GR', 'HR', 'IT', 'ME', 'MK', 'MT', 'PT', 'RS', 'SI', 'SM', 'VA');
$western = array('AT', 'BE', 'CH', 'DE', 'FR', 'LI', 'LU', 'MC', 'NL');
</code></pre>
<p>For example:</p>
<pre><code>if(in_array($country_code, $eastern)) {
// Eastern Europe
} else {
// Not Eastern Europe
}
</code></pre>
<p>I contacted CloudFlare to make sure the list of country codes are valid. They sent me a list of possible values for <code>$_SERVER["HTTP_CF_IPCOUNTRY"]</code>. I validated the above arrays, all country codes in those arrays are in the list of possible values.</p>
<p>For reference, here is the list of possible values:</p>
<pre class="lang-none prettyprint-override"><code>A1 Anonymous Proxy
A2 Satellite Provider
O1 Other Country
AD Andorra
AE United Arab Emirates
AF Afghanistan
AG Antigua and Barbuda
AI Anguilla
AL Albania
AM Armenia
AO Angola
AP Asia/Pacific Region
AQ Antarctica
AR Argentina
AS American Samoa
AT Austria
AU Australia
AW Aruba
AX Aland Islands
AZ Azerbaijan
BA Bosnia and Herzegovina
BB Barbados
BD Bangladesh
BE Belgium
BF Burkina Faso
BG Bulgaria
BH Bahrain
BI Burundi
BJ Benin
BL Saint Bartelemey
BM Bermuda
BN Brunei Darussalam
BO Bolivia
BQ Bonaire, Saint Eustatius and Saba
BR Brazil
BS Bahamas
BT Bhutan
BV Bouvet Island
BW Botswana
BY Belarus
BZ Belize
CA Canada
CC Cocos (Keeling) Islands
CD Congo, The Democratic Republic of the
CF Central African Republic
CG Congo
CH Switzerland
CI Cote d'Ivoire
CK Cook Islands
CL Chile
CM Cameroon
CN China
CO Colombia
CR Costa Rica
CU Cuba
CV Cape Verde
CW Curacao
CX Christmas Island
CY Cyprus
CZ Czech Republic
DE Germany
DJ Djibouti
DK Denmark
DM Dominica
DO Dominican Republic
DZ Algeria
EC Ecuador
EE Estonia
EG Egypt
EH Western Sahara
ER Eritrea
ES Spain
ET Ethiopia
EU Europe
FI Finland
FJ Fiji
FK Falkland Islands (Malvinas)
FM Micronesia, Federated States of
FO Faroe Islands
FR France
GA Gabon
GB United Kingdom
GD Grenada
GE Georgia
GF French Guiana
GG Guernsey
GH Ghana
GI Gibraltar
GL Greenland
GM Gambia
GN Guinea
GP Guadeloupe
GQ Equatorial Guinea
GR Greece
GS South Georgia and the South Sandwich Islands
GT Guatemala
GU Guam
GW Guinea-Bissau
GY Guyana
HK Hong Kong
HM Heard Island and McDonald Islands
HN Honduras
HR Croatia
HT Haiti
HU Hungary
ID Indonesia
IE Ireland
IL Israel
IM Isle of Man
IN India
IO British Indian Ocean Territory
IQ Iraq
IR Iran, Islamic Republic of
IS Iceland
IT Italy
JE Jersey
JM Jamaica
JO Jordan
JP Japan
KE Kenya
KG Kyrgyzstan
KH Cambodia
KI Kiribati
KM Comoros
KN Saint Kitts and Nevis
KP Korea, Democratic People's Republic of
KR Korea, Republic of
KW Kuwait
KY Cayman Islands
KZ Kazakhstan
LA Lao People's Democratic Republic
LB Lebanon
LC Saint Lucia
LI Liechtenstein
LK Sri Lanka
LR Liberia
LS Lesotho
LT Lithuania
LU Luxembourg
LV Latvia
LY Libyan Arab Jamahiriya
MA Morocco
MC Monaco
MD Moldova, Republic of
ME Montenegro
MF Saint Martin
MG Madagascar
MH Marshall Islands
MK Macedonia
ML Mali
MM Myanmar
MN Mongolia
MO Macao
MP Northern Mariana Islands
MQ Martinique
MR Mauritania
MS Montserrat
MT Malta
MU Mauritius
MV Maldives
MW Malawi
MX Mexico
MY Malaysia
MZ Mozambique
NA Namibia
NC New Caledonia
NE Niger
NF Norfolk Island
NG Nigeria
NI Nicaragua
NL Netherlands
NO Norway
NP Nepal
NR Nauru
NU Niue
NZ New Zealand
OM Oman
PA Panama
PE Peru
PF French Polynesia
PG Papua New Guinea
PH Philippines
PK Pakistan
PL Poland
PM Saint Pierre and Miquelon
PN Pitcairn
PR Puerto Rico
PS Palestinian Territory
PT Portugal
PW Palau
PY Paraguay
QA Qatar
RE Reunion
RO Romania
RS Serbia
RU Russian Federation
RW Rwanda
SA Saudi Arabia
SB Solomon Islands
SC Seychelles
SD Sudan
SE Sweden
SG Singapore
SH Saint Helena
SI Slovenia
SJ Svalbard and Jan Mayen
SK Slovakia
SL Sierra Leone
SM San Marino
SN Senegal
SO Somalia
SR Suriname
SS South Sudan
ST Sao Tome and Principe
SV El Salvador
SX Sint Maarten
SY Syrian Arab Republic
SZ Swaziland
TC Turks and Caicos Islands
TD Chad
TF French Southern Territories
TG Togo
TH Thailand
TJ Tajikistan
TK Tokelau
TL Timor-Leste
TM Turkmenistan
TN Tunisia
TO Tonga
TR Turkey
TT Trinidad and Tobago
TV Tuvalu
TW Taiwan
TZ Tanzania, United Republic of
UA Ukraine
UG Uganda
UM United States Minor Outlying Islands
US United States
UY Uruguay
UZ Uzbekistan
VA Holy See (Vatican City State)
VC Saint Vincent and the Grenadines
VE Venezuela
VG Virgin Islands, British
VI Virgin Islands, U.S.
VN Vietnam
VU Vanuatu
WF Wallis and Futuna
WS Samoa
YE Yemen
YT Mayotte
ZA South Africa
ZM Zambia
ZW Zimbabwe
</code></pre> |
30,526,613 | Android Studio - Gradle sync error on gradle-diagnostics-X.X.X.jar | <p>I've just updated Android Studio and I can't sync my project anymore.</p>
<p>The event log reports:</p>
<pre><code>Gradle sync failed: /Applications/Android Studio.app/Contents/gradle/gradle-X.X.X/lib/plugins/gradle-diagnostics-X.X.X.jar (No such file or directory)
</code></pre> | 30,526,660 | 8 | 0 | null | 2015-05-29 09:57:43.667 UTC | 10 | 2019-07-31 07:55:25.88 UTC | 2016-02-28 09:59:02.81 UTC | null | 2,893,843 | null | 2,893,843 | null | 1 | 72 | android-studio|android-gradle-plugin | 68,374 | <p>To solve the Gradle sync error, open <strong><code>gradle-wrapper.properties</code></strong> file and update the Gradle wrapper distribution version from:</p>
<pre><code>distributionUrl=https\://services.gradle.org/distributions/gradle-X.X.X-all.zip
</code></pre>
<p>To:</p>
<ul>
<li>Android Studio 3.4
<code>distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip</code></li>
<li>Android Studio 2.3 <code>distributionUrl=https\://services.gradle.org/distributions/gradle-2.3-all.zip</code></li>
<li>Android Studio 2.2 <code>distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip</code></li>
<li>Android Studio 2.1 <code>distributionUrl=https\://services.gradle.org/distributions/gradle-2.12-all.zip</code></li>
<li>Android Studio 2.0 <code>distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip</code></li>
<li>Android Studio 1.5 <code>distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip</code></li>
<li>Android Studio 1.3 <code>distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip</code></li>
</ul>
<p><br>
You can find the latest Gradle wrapper version visiting:
<a href="https://services.gradle.org/distributions/" rel="noreferrer">https://services.gradle.org/distributions/</a></p>
<h2><br></h2>
<p><strong>EDIT</strong>:<br>
As a side note, as @SeBsZ suggests,
the official repository of the Android Gradle plugin switched from MavenCentral to jCenter (<a href="http://blog.bintray.com/2015/02/09/android-studio-migration-from-maven-central-to-jcenter/" rel="noreferrer">see Bintray blog post</a>).</p>
<p>Make sure your project <strong><code>build.gradle</code></strong> file contains the new repository and the new classpath:</p>
<pre><code>buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
}
}
allprojects {
repositories {
jcenter()
}
}
</code></pre>
<p>This is not strictly related to the question problem, but since we are already migrating to the new IDE preview it's better to make sure everything is in place.</p> |
21,237,976 | How to get the parent of an element | <p>For example, I am randomly picking a <code>button</code> element from within the rows of a <code>table</code>.<br>
After the <code>button</code> is found, I want to retrieve the <code>table</code>'s row which contains a selected button.</p>
<p>Heres is my code snippet:</p>
<pre><code>browser.findElements(by.css('[ng-click*=submit]')).then(function (results) {
var randomNum = Math.floor(Math.random() * results.length);
var row = results[randomNum];
// ^ Here I want to get the parent of my random button
});
</code></pre> | 21,238,692 | 4 | 0 | null | 2014-01-20 15:35:37.013 UTC | 5 | 2018-03-21 20:50:42.69 UTC | 2015-12-18 14:01:08.02 UTC | null | 132,735 | null | 909,796 | null | 1 | 44 | dom|protractor|end-to-end | 29,046 | <p>Decided to use xpath. </p>
<pre><code>var row = results[randomNum].findElement(by.xpath('ancestor::tr'));
</code></pre> |
49,608,656 | saving a dataframe to csv file (python) | <p>I am trying to restructure the way my precipitations' data is being organized in an excel file. To do this, I've written the following code:</p>
<pre><code>import pandas as pd
df = pd.read_excel('El Jem_Souassi.xlsx', sheetname=None, header=None)
data=df["El Jem"]
T=[]
for column in range(1,56):
liste=data[column].tolist()
for row in range(1,len(liste)):
liste[row]=str(liste[row])
if liste[row]!='nan':
T.append(liste[row])
result=pd.DataFrame(T)
result
</code></pre>
<p>This code works fine and through Jupyter I can see that the result is good
<a href="https://i.stack.imgur.com/gttE6.jpg" rel="noreferrer">screenshot</a></p>
<p>However, I am facing a problem when attempting to save this dataframe to a csv file.</p>
<pre><code> result.to_csv("output.csv")
</code></pre>
<p>The resulting file contains the vertical index column and it seems I am unable to call for a specific cell.</p>
<p>(Hopefully, someone can help me with this problem)
Many thanks !!</p> | 49,608,737 | 1 | 0 | null | 2018-04-02 09:26:26.21 UTC | 3 | 2018-04-18 06:59:56.44 UTC | null | null | null | null | 6,140,399 | null | 1 | 8 | python|pandas|csv|dataframe | 60,660 | <p>It's all in <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="noreferrer">the docs</a>.</p>
<p>You are interested in skipping the index column, so do:</p>
<p><code>result.to_csv("output.csv", index=False)</code></p>
<p>If you also want to skip the header add:</p>
<p><code>result.to_csv("output.csv", index=False, header=False)</code></p>
<hr>
<p>I don't know how your input data looks like (it is a good idea to make it available in your question). But note that currently you can obtain the same results just by doing:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([0]*16)
df.to_csv('results.csv', index=False, header=False)
</code></pre> |
45,203,543 | VS Code extension Api to get the Range of the whole text of a document? | <p>I haven't found a good way to do it. My current approach is to select all first:</p>
<pre><code>vscode.commands.executeCommand("editor.action.selectAll").then(() =>{
textEditor.edit(editBuilder => editBuilder.replace(textEditor.selection, code));
vscode.commands.executeCommand("cursorMove", {"to": "viewPortTop"});
});
</code></pre>
<p>which is not ideal because it flashes when doing selection then replacement.</p> | 46,427,868 | 4 | 0 | null | 2017-07-20 01:14:02.513 UTC | 8 | 2020-09-17 23:07:15.977 UTC | 2018-12-27 13:00:41.283 UTC | null | 2,631,715 | null | 2,170,938 | null | 1 | 22 | typescript|visual-studio-code|vscode-extensions | 14,486 | <p>This may not be robust, but I've been using this:</p>
<pre><code>var firstLine = textEditor.document.lineAt(0);
var lastLine = textEditor.document.lineAt(textEditor.document.lineCount - 1);
var textRange = new vscode.Range(firstLine.range.start, lastLine.range.end);
</code></pre> |
22,007,143 | What's the access modifier of the default constructor in java? | <p>We all know that if we don't specifically define a constructor, the compiler inserts an invisible zero-parameter constructor. I thought its access modifier was public, but in dealing with an inner class issue, I found maybe I was wrong. Here is my code:</p>
<pre><code>public class Outer {
protected class ProtectedInner {
// adding a public constructor will solve the error in SubOuterInAnotherPackage class
//public ProtectedInner() {}
}
}
</code></pre>
<p>And there is a subclass of <code>Outer</code> in another package:</p>
<pre><code>public class SubOuterInAnotherPackage extends Outer {
public static void main(String[] args) {
SubOuterInAnotherPackage.ProtectedInner protectedInner
= new SubOuterInAnotherPackage().new ProtectedInner(); // Error!! Can't access the default constructor
}
}
</code></pre>
<p>You will get an error in the <code>main()</code> method, but if you add a public constructor to the <code>ProtectedInner</code> class, that error is solved. That's why I'm thinking that the modifier of the default constructor is not public! So could anyone tell me what the access modifier of the default constructor is?</p> | 22,007,183 | 3 | 0 | null | 2014-02-25 07:14:14.073 UTC | 15 | 2021-01-09 15:49:30.63 UTC | 2015-10-21 12:37:01.063 UTC | null | 964,243 | null | 3,226,107 | null | 1 | 31 | java|access-specifier | 15,124 | <blockquote>
<p>I thought its access modifier is public, but when I deal with a inner class issue, I found maybe I was wrong.</p>
</blockquote>
<p>Yup. Indeed, I found myself in the same situation a couple of years ago. I was surprised by an error (through Guice injection, which made it slightly harder to find).</p>
<p>The key is to check the spec, in this case <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9">section 8.8.9</a>:</p>
<blockquote>
<p>In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.</p>
</blockquote>
<p>So in this case, your constructor is implicitly <code>protected</code>.</p> |
36,289,495 | How to make a simple JSONP asynchronous request in Angular 2? | <p>I'm trying to convert the following Angular 1 code to Angular 2:</p>
<pre><code>$http.jsonp('https://accounts.google.com/logout');
</code></pre>
<p>It needs to be a JSONP request to skip the CORS policy issue.</p> | 40,027,481 | 3 | 0 | null | 2016-03-29 16:06:20.97 UTC | 13 | 2021-02-27 09:25:11.69 UTC | null | null | null | null | 2,892,404 | null | 1 | 37 | asynchronous|typescript|xmlhttprequest|angular|jsonp | 52,377 | <p><strong>In the latest version of Angular</strong></p>
<ol>
<li><p>Import <strong>HttpClientModule</strong> and <strong>HttpClientJsonpModule</strong> modules in your app module's definition file</p>
<pre><code> import {
HttpClientModule,
HttpClientJsonpModule
} from '@angular/common/http';
@NgModule({
declarations: [
//... List of components that you need.
],
imports: [
HttpClientModule,
HttpClientJsonpModule,
//...
],
providers: [
//...
],
bootstrap: [AppComponent]
})
</code></pre>
</li>
<li><p>Inject <em>http</em> and <em>map</em> rxjs operator into your service:</p>
<pre><code> import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MegaSuperService {
constructor(private _http: HttpClient) {}
}
</code></pre>
</li>
<li><p>Make JSONP requests in the following way:</p>
<pre><code> // inside your service
this._http.jsonp('/api/get', 'callback').map(data => {
// Do stuff.
});
</code></pre>
</li>
</ol>
<p><strong>In Angular version 2 - version 4.3</strong></p>
<ol>
<li><p>Import JSONP module in your app module's definition file:</p>
<pre><code> import {JsonpModule} from '@angular/http';
@NgModule({
declarations: [
//... List of components that you need.
],
imports: [
JsonpModule,
//...
],
providers: [
//...
],
bootstrap: [AppComponent]
})
</code></pre>
</li>
<li><p>Inject <em>jsonp</em> service and <em>map</em> rxjs operator into your service:</p>
<pre><code> import {Injectable} from '@angular/core';
import {Jsonp} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class MegaSuperService {
constructor(private _jsonp: Jsonp) {}
}
</code></pre>
</li>
<li><p>Make requests using "JSONP_CALLBACK" as a callback property:</p>
<pre><code> // inside your service
this._jsonp.get('/api/get?callback=JSONP_CALLBACK').map(data => {
// Do stuff.
});
</code></pre>
</li>
</ol> |
37,599,128 | docker - how do you disable auto-restart on a container? | <p>I can enable auto-restart with <code>--restart=always</code>, but after I stop the container, how do I turn off that attribute?</p>
<p>I normally run a webserver and typically map port 80:</p>
<pre><code>docker run -d --restart=always -p 80:80 -i -t myuser/myproj /bin/bash
</code></pre>
<p>But there are times when I want to run a newer version of my image, but I want to keep the old container around. The problem is that if there are multiple containers with <code>--restart=always</code>, only one of them (random?) starts because they're all contending for port 80 on the host.</p> | 37,600,885 | 8 | 0 | null | 2016-06-02 18:03:51.01 UTC | 69 | 2022-04-21 14:15:58.997 UTC | null | null | null | null | 1,760,405 | null | 1 | 238 | docker | 116,386 | <p>You can use the <code>--restart=unless-stopped</code> option, as @Shibashis mentioned, or update the restart policy (this requires docker 1.11 or newer);</p>
<p>See the <a href="https://github.com/docker/docker/blob/v1.11.2/docs/reference/commandline/update.md#update-a-containers-restart-policy" rel="noreferrer">documentation for <code>docker update</code></a> and <a href="https://docs.docker.com/engine/reference/run/#restart-policies---restart" rel="noreferrer">Docker restart policies</a>.</p>
<pre><code>docker update --restart=no my-container
</code></pre>
<p>that updates the restart-policy for an existing container (<code>my-container</code>)</p> |
31,581,854 | Enabling intel virtualization (VT-X) without option in BIOS | <p>Sorry if the question is already answered, but I haven't found answer for my particular situation, that is a little different.</p>
<p>I'm installing all the tools necessary for android programming. I have created an android virtual device, but the problem come installing intel hardware acceleration (HAXM), the installer say to me I need activate VT-x and it seems that this tool only can be activated in BIOS, but my BIOS is InsydeH20 rev 3.5 and the option doesn't appear anywhere.</p>
<p>What can I do? How can I activate VT-x without BIOS?</p>
<p>My processor is intel i7 2630qm, I have check in the intel page if my processor is compatible with VT-x and yes it is.</p>
<p>Thank you very much!!</p> | 31,591,380 | 2 | 1 | null | 2015-07-23 08:21:03.427 UTC | 8 | 2018-09-08 03:22:52.763 UTC | 2018-01-18 11:42:08.323 UTC | null | 5,147,016 | null | 5,147,016 | null | 1 | 17 | android|intel|virtualization|bios|haxm | 98,720 | <p>You can run some bcedit commands from the command line to set ND Bit and VT<br>
bcdedit /set hypervisorlaunchtype off <br>
bcdedit /set nx AlwaysOn <br>
Also do the install from <a href="https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager">https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager</a> <br>
If you're using Avast, disable "Enable hardware-assisted virtualization" under: Settings > Troubleshooting. Restart the PC and try to run the HAXM installation again</p>
<p>(instead of using the one downloaded through </p> |
54,279,223 | Flutter: Default assignment of List parameter in a constructor | <p>Is it possible to assign a constant value to an optional parameter of datatype List while defining a constructor.
for example,</p>
<pre><code>`class sample{
final int x;
final List<String> y;
sample({this.x = 0; this.y = ["y","y","y","y"]});
}`
</code></pre>
<p>the above code throws an error focused at y assignment saying <code>Default values of an optional parameter must be constant</code></p>
<p>what is the reason for this error?
how else can I assign a default value to the List?</p> | 54,279,284 | 2 | 1 | null | 2019-01-20 17:49:37.837 UTC | 4 | 2022-07-20 00:39:16.96 UTC | null | null | null | null | 9,536,168 | null | 1 | 35 | dart|flutter | 35,514 | <p>Default values currently need to be const. This might change in the future.</p>
<p>If your default value can be const, adding <code>const</code> would be enough</p>
<pre><code>class sample{
final int x;
final List<String> y;
sample({this.x = 0, this.y = const ["y","y","y","y"]});
}
</code></pre>
<p>Dart usually just assumes <code>const</code> when <code>const</code> is required, but for default values this was omitted to not break existing code in case the constraint is actually removed.</p>
<p>If you want a default value that can't be const because it's calculated at runtime you can set it in the initializer list</p>
<pre><code>class sample{
final int x;
final List<String> y;
sample({this.x = 0; List<String> y}) : y = y ?? ["y","y","y","y"];
}
</code></pre> |
56,862,089 | Cannot find command 'dotnet ef' | <p>I am using .NET Core 2.0 on <a href="https://en.wikipedia.org/wiki/Arch_Linux" rel="noreferrer">Arch Linux</a> / Visual Studio Code and am trying to get <a href="https://en.wikipedia.org/wiki/Entity_Framework" rel="noreferrer">EF</a> tools to work, but I keep getting the error:</p>
<blockquote>
<p>cannot find command dotnet ef</p>
</blockquote>
<p>I've just about looked everywhere and none of the suggestions worked.</p>
<p>The result of running 'dotnet ef':</p>
<pre class="lang-none prettyprint-override"><code>[wasiim@wasiim-PC WebApiServerApp]$ dotnet ef --help
Cannot find command 'dotnet ef', please run the following command to install
dotnet tool install --global dotnet-ef
[wasiim@wasiim-PC WebApiServerApp]$ dotnet tool list -g
Package Id Version Commands
---------------------------------------------------
dotnet-dev-certs 2.2.0 dotnet-dev-certs
dotnet-ef 2.2.3 dotnet-ef
[wasiim@wasiim-PC WebApiServerApp]$
</code></pre>
<p>This is the 'dotnet --info' result, if it's of help:</p>
<pre class="lang-none prettyprint-override"><code>[wasiim@wasiim-PC WebApiServerApp]$ dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 2.2.105
Commit: 7cecb35b92
Runtime Environment:
OS Name: arch
OS Version:
OS Platform: Linux
RID: arch-x64
Base Path: /opt/dotnet/sdk/2.2.105/
Host (useful for support):
Version: 2.2.3
Commit: 6b8ad509b6
.NET Core SDKs installed:
2.2.105 [/opt/dotnet/sdk]
.NET Core runtimes installed:
Microsoft.NETCore.App 2.2.3 [/opt/dotnet/shared/Microsoft.NETCore.App]
To install additional .NET Core runtimes or SDKs:
https://aka.ms/dotnet-download
</code></pre>
<p>This is my .csproj file:</p>
<pre class="lang-xml prettyprint-override"><code><Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Lucene.Net.Analysis.Common" Version="4.8.0-beta00005" />
<PackageReference Include="Lucene.Net.QueryParser" Version="4.8.0-beta00005" />
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.2.5" />
<PackageReference Include="Lucene.Net" Version="4.8.0-beta00005" />
<PackageGroup Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.4" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.3" />
</ItemGroup>
</Project>
</code></pre> | 56,876,020 | 13 | 2 | null | 2019-07-03 02:22:54.657 UTC | 27 | 2021-11-29 20:46:04.303 UTC | 2021-06-10 15:06:23.343 UTC | null | 63,550 | null | 4,630,201 | null | 1 | 104 | c#|entity-framework|asp.net-core|.net-core|csproj | 86,242 | <p>Note to readers: If you haven't installed <code>dotnet ef</code>, you need to install it first: <code>dotnet tool install --global dotnet-ef</code>. The question-asker already did that. You need to do that first before the rest of this answer can help.</p>
<h1>How to fix this</h1>
<p>For <strong>Linux</strong> and <strong>macOS</strong>, add a line to your shell's configuration:</p>
<ul>
<li><p><code>bash</code>/<code>zsh</code>:</p>
<pre><code>export PATH="$PATH:$HOME/.dotnet/tools/"
</code></pre>
</li>
<li><p><code>csh</code>/<code>tcsh</code>:</p>
<pre><code>set path = ($path $HOME/.dotnet/tools/)
</code></pre>
</li>
</ul>
<p>When you start a new shell/terminal (or the next time you log in) <code>dotnet ef</code> should work.</p>
<p>For <strong>Windows</strong>:</p>
<p>See <a href="https://stackoverflow.com/questions/9546324/adding-directory-to-path-environment-variable-in-windows">this question</a> on how to add to the <code>PATH</code> environment variable.</p>
<p>You need to add <code>%USERPROFILE%\.dotnet\tools</code> to the <code>PATH</code>.</p>
<h1>What's going on?</h1>
<p>The .NET Core 3.0 (preview) version of this failure is much more illuminating:</p>
<pre><code>$ dotnet ef
Could not execute because the specified command or file was not found.
Possible reasons for this include:
* You misspelled a built-in dotnet command.
* You intended to execute a .NET Core program, but dotnet-ef does not exist.
* You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.
</code></pre>
<p>The second and the third one both refer to <code>dotnet</code> trying to find a <code>dotnet-ef</code> command but can't find it. As the third point says, <code>dotnet-ef</code> is not in your path.</p>
<p>Here's <a href="https://docs.microsoft.com/en-us/dotnet/core/tools/global-tools" rel="noreferrer">what the docs say</a>:</p>
<blockquote>
<p>Global Tools can be installed in the default directory or in a specific location. The default directories are:</p>
<p><code>OS Path</code></p>
<p><code>Linux/macOS $HOME/.dotnet/tools</code></p>
<p><code>Windows %USERPROFILE%\.dotnet\tools</code></p>
</blockquote>
<p>So, you should add <code>$HOME/.dotnet/tools/</code> to your <code>$PATH</code>.</p>
<p>But also note this part from docs:</p>
<blockquote>
<p>These locations are added to the user's path when the SDK is first run, so Global Tools installed there can be called directly.</p>
</blockquote>
<p>So, it sounds like something went wrong. If you installed using a manual tarball, the SDK screwed up and you should report this bug to Microsoft. If you use a distribution package, they screwed up and you should report this as a bug to them.</p> |
40,131,672 | Storing production secrets in ASP.NET Core | <p>I try to figure out where to best store application production secrets for an ASP.NET Core app. There are two similar questions
<a href="https://stackoverflow.com/questions/31426358/where-should-i-store-the-connection-string-for-the-production-environment-of-my">Where should I store the connection string for the production environment of my ASP.NET Core app?</a>
and
<a href="https://stackoverflow.com/questions/39668456/how-to-deploy-asp-net-core-usersecrets-to-production">How to deploy ASP.NET Core UserSecrets to production</a>
which both recommend using environment variables. </p>
<p>My problem is that I want to run several instances of my web app with different databases and different database credentials. So there should be some per-instance configuration including secrets.</p>
<p>How could this be achieved in a safe way?</p>
<p>Note that the application should be able to self-host and be hostable under IIS! (Later we also plan to run it on Linux if that is of any importance for the question)</p>
<p><strong>Update</strong></p>
<p>This question is not about trying to use ASP.NET user secrets in production! UserSecrets are ruled out for production.</p> | 40,132,369 | 3 | 2 | null | 2016-10-19 12:40:39.357 UTC | 13 | 2021-12-30 22:40:01.88 UTC | 2020-02-21 10:17:52.823 UTC | null | 133 | null | 1,626,597 | null | 1 | 56 | asp.net-core | 40,807 | <p>As they state, user secrets is <strong>only</strong> for development (to avoid commiting credentials accidentally into the SCM) and not intended for production. You should use one connection string per database, i.e. <code>ConnectionStrings:CmsDatabaseProduction</code>,<code>ConnectionStrings:CmsDatabaseDevelopment</code>, etc. </p>
<p>Or use docker containers (when you're not using Azure App Service), then you can set it on per container basis.</p>
<p>Alternatively you can also use environment based appsetting files. <code>appsettings.production.json</code>, but they must not be included in the source control management (Git, CSV, TFS)! </p>
<p>In the startup just do:</p>
<pre><code> public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
</code></pre>
<p>This way, you can load specific stuff from the <code>appsettings.production.json</code> and can still override it via environment variable. </p> |
22,118,004 | Why am I getting the error "connection refused" with JMX | <p>I am unable to connect to JMX object. Here is how I create a JMX object:</p>
<pre><code>public static void main(String... args) {
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
try {
ObjectName name = new ObjectName("org.javasimon.jmx.example:type=Simon");
if (mbs.isRegistered(name)) {
mbs.unregisterMBean(name);
}
SimonManagerMXBean simonManagerMXBean = new SimonManagerMXBeanImpl(SimonManager.manager());
mbs.registerMBean(simonManagerMXBean, name);
System.out.println("SimonManagerMXBean registerd under name: "+name);
} catch (JMException e) {
System.out.println("SimonManagerMXBean registration failed!\n"+e);
}
while (true) {
// waiting for connections
}
}
</code></pre>
<p>This is a code for connecting to the remote JMX object:</p>
<pre><code>JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://127.0.0.1:9999/jndi/rmi://127.0.0.1:1099/jmxrmi");
JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
SimonManagerMXBean simonManagerMXBean = JMX.newMXBeanProxy(mbsc, new ObjectName("org.javasimon.jmx.example:type=Simon"), SimonManagerMXBean.class);
return simonManagerMXBean;
</code></pre>
<p>Unfortunatelly I receive the following error:</p>
<pre><code>java.io.IOException: Failed to retrieve RMIServer stub: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused: connect]
at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:338)
at javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:248)
at my.code.RemoteSimonManagerFactoryImpl.createSimonManager(RemoteSimonManagerFactoryImpl.java:24)
at my.code.Demo.main(DemoAggregation.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: javax.naming.ServiceUnavailableException [Root exception is java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused: connect]
at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:101)
at com.sun.jndi.toolkit.url.GenericURLContext.lookup(GenericURLContext.java:185)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at javax.management.remote.rmi.RMIConnector.findRMIServerJNDI(RMIConnector.java:1886)
at javax.management.remote.rmi.RMIConnector.findRMIServer(RMIConnector.java:1856)
at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:255)
... 9 more
Caused by: java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is:
java.net.ConnectException: Connection refused: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:601)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:198)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:184)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:322)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:97)
... 14 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at java.net.Socket.<init>(Socket.java:375)
at java.net.Socket.<init>(Socket.java:189)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:22)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:128)
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:595)
... 19 more
</code></pre>
<p>If I try to connect to my JMX server (as to local process) using "jconsole" utility, I first get "ConnectionFailedSSL1" error, but when I click "Insecure" button in the error form, I connect successfully. </p>
<p>Both server and client are on the same computer.</p>
<p>I am using Windows 7 x64. Windows firewall is disabled.</p> | 22,118,090 | 4 | 0 | null | 2014-03-01 17:50:36.827 UTC | 1 | 2020-08-10 10:51:23.997 UTC | 2016-12-07 03:50:04.76 UTC | null | 179,850 | null | 1,112,503 | null | 1 | 10 | java|networking|jmx | 88,819 | <blockquote>
<p>Caused by: java.rmi.ConnectException: Connection refused to host: 127.0.0.1; nested exception is: </p>
</blockquote>
<p>Most likely you are not running your server with the right JVM parameters. Jconsole uses a different mechanism to find and to connect to local processes. Your client code is trying to use TCP/IP to connect to your server. To turn this on you'll need to add something like the following to your Java command line on your server:</p>
<pre><code>-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=1099
</code></pre>
<p>See: <a href="https://stackoverflow.com/questions/856881/how-to-activate-jmx-on-my-jvm-for-access-with-jconsole/856882#856882">How to activate JMX on my JVM for access with jconsole?</a></p>
<p>As an aside, you might want to consider using my <a href="http://256stuff.com/sources/simplejmx/" rel="nofollow noreferrer"><code>SimpleJMX</code> library</a> which does all this code for you. It includes a JMX client code as well.</p> |
23,569,229 | What exactly flex-basis property sets? | <p>Is there a difference between setting <code>max-width</code> or <code>width</code> to a flex item instead of the <code>flex-basis</code>?</p>
<p>Is it the "breaking point" for the <code>flex-grow/shrink</code> properties?</p>
<p>And when I set <code>flex-wrap: wrap</code> how does the browser decides at which point to move down item to new line? Is it according to their width or 'flex-basis'?</p>
<p>Example: <a href="http://jsfiddle.net/wP5UP/">http://jsfiddle.net/wP5UP/</a>
The last two boxes have the same <code>flex-basis: 200px</code>, yet <strong>only</strong> one of them moves down when the window is between 300px and 400px. Why?</p> | 23,569,407 | 2 | 1 | null | 2014-05-09 16:06:36.73 UTC | 11 | 2019-02-13 09:27:26.747 UTC | 2014-05-09 16:21:24.67 UTC | null | 747,024 | null | 747,024 | null | 1 | 45 | css|flexbox | 25,457 | <p><code>flex-basis</code> allows you to specify the initial/starting size of the element, before anything else is computed. It can either be a percentage or an absolute value.</p>
<p>It is, however, <strong>not</strong> the breaking point for flex-grow/shrink properties. The browser determines when to wrap the element on the basis of if the initial sizes of elements exceed the width of the cross-axis (in conventional sense, that is the width).</p>
<p>Based on your fiddle, the reason why the last one moves down the window is because the width of the parent has been fully occupied by the previous siblings — and when you allow content to wrap, the elements that fail to fit in the first row gets pushed to the subsequent row. Since <code>flex-grow</code> is a non-zero value, it will simply stretch to fill all spaces left in the second row.</p>
<p><a href="http://jsfiddle.net/teddyrised/wP5UP/2/" rel="noreferrer">See demo fiddle (modified from yours)</a>.</p>
<p>If you look at the fiddle, I have modified for the last item to have a new size declaration:</p>
<pre><code>.size3 {
flex: 0 1 300px;
}
</code></pre>
<p>You will realize that the element measures 300px across as intended. However, when you tweak the flex-grow property such that its value exceeds 0 (<a href="http://jsfiddle.net/teddyrised/wP5UP/1/" rel="noreferrer">see example</a>), it will stretch to fill the row, which is the expected behavior. Since in its <em>new row context</em> it has no siblings to compare to, an integer between 1 to infinity will not influence it's size.</p>
<p>Therefore, <code>flex-grow</code> can be seen as this:</p>
<ul>
<li><code>0</code>: (Default value) <em>Do not stretch</em>. Either size to element's content width, or obey <code>flex-basis</code>.</li>
<li><code>1</code>: <em>Stretch</em>.</li>
<li><code>≥2</code> (integer <em>n</em>): <em>Stretch</em>. Will be <em>n</em> times the size of other elements with <code>flex-grow: 1</code> on the same row, for example. </li>
</ul> |
48,255,871 | Failed to start the virtual machine 'MobyLinuxVM' because one of the Hyper-V components is not running | <p>I have got some problem when I installed Docker with Window Server.<br>
The environment list: </p>
<blockquote>
<p>1 Windows 10 (Physical Machine)<br>
2.VMware® Workstation Player (12~ above) <a href="https://my.vmware.com/en/web/vmware/free#desktop_end_user_computing/vmware_workstation_player/14_0" rel="noreferrer">URL</a><br>
3.Windows Server 2016 at the VM<br>
4.Docker CE for Windows(stable) <a href="https://store.docker.com/editions/community/docker-ce-desktop-windows" rel="noreferrer">URL</a> </p>
</blockquote>
<p>the problem picture and content<br>
<a href="https://i.stack.imgur.com/wJZ5H.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wJZ5H.png" alt="enter image description here"></a></p>
<pre><code>Unable to start: The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: 'MobyLinuxVM' failed to start.
Failed to start the virtual machine 'MobyLinuxVM' because one of the Hyper-V components is not running.
'MobyLinuxVM' failed to start. (Virtual machine ID BBD755F7-05B6-4933-B1E0-F8ACA3D2467B)
The Virtual Machine Management Service failed to start the virtual machine 'MobyLinuxVM' because one of the Hyper-V components is not running (Virtual machine ID BBD755F7-05B6-4933-B1E0-F8ACA3D2467B).
at Start-MobyLinuxVM, <No file>: line 315
at <ScriptBlock>, <No file>: line 410
at Docker.Backend.ContainerEngine.Linux.DoStart(Settings settings, String daemonOptions) in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Backend\ContainerEngine\Linux.cs:line 256
at Docker.Backend.ContainerEngine.Linux.Start(Settings settings, String daemonOptions) in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Backend\ContainerEngine\Linux.cs:line 130
at Docker.Core.Pipe.NamedPipeServer.<>c__DisplayClass9_0.<Register>b__0(Object[] parameters) in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Core\pipe\NamedPipeServer.cs:line 47
at Docker.Core.Pipe.NamedPipeServer.RunAction(String action, Object[] parameters) in C:\gopath\src\github.com\docker\pinata\win\src\Docker.Core\pipe\NamedPipeServer.cs:line 145
</code></pre>
<p>How can I fix this problem issue,Thanks.</p> | 48,260,575 | 9 | 2 | null | 2018-01-15 01:24:21.167 UTC | 21 | 2022-03-31 07:33:54.7 UTC | 2018-01-16 10:45:06.357 UTC | null | 4,887,423 | null | 4,887,423 | null | 1 | 58 | docker|windows-server-2016|vmware-workstation | 72,123 | <p>Hi all I have found the answer to deal with this problem hopefully this content can help someone who has the same issue.<br>
1. to setup VM at Virtual Machine Settings (like as following picture)
<a href="https://i.stack.imgur.com/Qbj3A.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Qbj3A.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/GlxvX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GlxvX.png" alt="enter image description here"></a></p>
<ol start="2">
<li>to setup the Hyper-V in the Windows Server 2016 (like as following picture)
<a href="https://i.stack.imgur.com/O6LNM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/O6LNM.png" alt="enter image description here"></a> </li>
</ol>
<p>Mandarin reference <a href="https://skychang.github.io/2017/01/06/Docker-Docker_for_Windows_10_First/" rel="noreferrer">URL</a></p> |
20,740,632 | Mapping between Android permissions (that we define in the manisfest file ) to corresponding API calls /methods | <p>Where can I find the mapping between Android permissions (that we define in the manisfest file ) to corresponding API calls /methods?</p>
<p>For example</p>
<pre><code>GET-ACCOUNTS” is a permission type which maps to
getAccountsByType(), getDeviceId(), and getLine1Number().
</code></pre>
<p>Similarly I want to know, If I use permission <code>Internet,ACCESS_COARSE_LOCATION,ACCESS_WIFI_STATE etc..</code> Then which all methods/API calls
map to it?</p>
<p>Please let me know where can I find this information. Below link lists the permission
<a href="http://developer.android.com/reference/android/Manifest.permission.html" rel="noreferrer">http://developer.android.com/reference/android/Manifest.permission.html</a></p>
<p>But could not find the mapping.</p>
<p>If this is not the right forum to post this , Then please let me know where should I post this?</p> | 24,019,120 | 3 | 1 | null | 2013-12-23 09:33:25.06 UTC | 12 | 2019-12-18 10:28:38.497 UTC | 2019-12-18 10:28:38.497 UTC | null | 6,275,653 | null | 1,737,225 | null | 1 | 14 | android|methods|permissions|android-security | 3,846 | <p>The mapping is not provided by Google, but <strike>two</strike> three major research studies have been attempted to recover this information. </p>
<p>The first study was done by Berkeley using a dynamic analysis technique to mine the mapping from Android 2.2. They created an online tool where you can submit your app for some analysis (now offline).</p>
<p>The second study was done by the University of Toronto. They used a static analysis approach to mine the mappings from a few representative versions of Android (2.2.3, 2.3.6, 3.2.2, 4.0.1, and 4.1.1). <strike>Note that it appears that PScout is now being actively maintained again by the authors and there are current mappings available.</strike></p>
<p>Both of these tools have some caveats as discussed by the papers and as a result the mappings produced are not perfect, but it is better than nothing.</p>
<hr>
<p>Update: PScout is no longer being actively maintained. A group in Germany at Saarland University was able make some improvements on PScout and produce published mapping results for Android APIs 16, 17, 18, 19, 21, 22, and 23. The tool source does not appear to be available.</p>
<hr>
<p>Link: <a href="https://www.cs.berkeley.edu/~dawnsong/papers/2011%20Android%20permissions%20demystified.pdf" rel="nofollow noreferrer">Berkeley Paper (Android Permissions Demystified)</a></p>
<p>Link: <a href="http://www.android-permissions.org/" rel="nofollow noreferrer">Berkeley Stowaway Tool</a> (tool appears to be permanently offline now, and the authors now recommend using PScout results for analysis)</p>
<p>Link: <a href="http://www.eecg.toronto.edu/~lie/papers/PScout-CCS2012-web.pdf" rel="nofollow noreferrer">Toronto Paper (PScout: Analyzing the Android Permission Specification)</a></p>
<p>Link: <a href="http://pscout.csl.toronto.edu/" rel="nofollow noreferrer">Toronto PScout Tool</a></p>
<p>Link: <a href="https://github.com/zd2100/PScout" rel="nofollow noreferrer">PScout II on Github</a></p>
<p>Link: <a href="http://axplorer.org/files/sec16_paper_backes-android.pdf" rel="nofollow noreferrer">Saarland University Paper (axplorer: On Demystifying the Android Application Framework: Re-Visiting Android Permission Specification Analysis)</a></p>
<p>Link: <a href="http://axplorer.org/" rel="nofollow noreferrer">axplorer Permission Mapping Results</a></p>
<hr>
<p>Update: Shameless self-promotion of my <a href="https://ensoftcorp.github.io/android-essentials-toolbox/" rel="nofollow noreferrer">Android Essentials Toolbox</a> open source Eclipse plugin that can be used to apply the permission mappings in the <a href="http://www.ensoftcorp.com/atlas/" rel="nofollow noreferrer">Atlas</a> visual program analysis framework. Permission mappings are based on PScout and axplorer results and can be applied to Android source or binary projects. A UI is included for browsing the permission mappings (used permissions are highlighted red).</p>
<p><a href="https://i.stack.imgur.com/o8fnw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/o8fnw.png" alt="enter image description here"></a></p> |
20,595,716 | Control mouse by writing to /dev/input/mice | <p>I am using Ubuntu 12.04. For one of my applications I require to control the mouse in software using a script.</p>
<p>I understand that the mouse device is <code>/dev/input/mice</code>. If I do a <code>cat /dev/input/mice</code> and then move my mouse, I see a lot of output being dumped to the screen.</p>
<p>Now I wish to remove the mouse, and have a script which writes to <code>/dev/input/mice</code> in order to control the mouse pointer</p>
<p>Please help me with commands for the following:<br>
(1) Perform a left click<br>
(2) Perform a right click<br>
(3) Move the mouse from one location to another. </p>
<p>Kindly note that I am looking for a shell script solution, rather than a C/C++ solution.</p> | 20,665,793 | 7 | 1 | null | 2013-12-15 14:42:03.897 UTC | 24 | 2016-08-25 16:26:56.213 UTC | 2013-12-18 10:33:15.123 UTC | null | 2,091,948 | null | 2,091,948 | null | 1 | 41 | linux|shell|ubuntu|mouse | 49,171 | <p>this is not trough the file you mentioned, but its way quicker to use this tool instead of decypering the dump of that file. And it does everything you want in bash.</p>
<p>xdotool does the trick in my terminal.<br>
<a href="https://launchpad.net/ubuntu/+source/xdotool" rel="noreferrer">this</a> is the package site for ubuntu.
you probably can install it trough</p>
<pre><code># apt-get install xdotool
</code></pre>
<p>I could just emerge it on gentoo without adding any repositories.<br>
<a href="http://manpages.ubuntu.com/manpages/lucid/man1/xdotool.1.html" rel="noreferrer">the tool works fairly simple</a>:</p>
<pre><code>#! /bin/bash
# move the mouse x y
xdotool mousemove 1800 500
# left click
xdotool click 1
# right click
xdotool click 3
</code></pre>
<p><a href="http://www.linuxquestions.org/questions/linux-desktop-74/control-mouse-from-shell-479800/" rel="noreferrer">found it here</a></p> |
29,467,510 | How does multi-level page table save memory space? | <p>I am trying to understand how multi-level page table saves memory. As per my understanding, Multi-level page table in total consumes more memory than single-level page table. </p>
<p>Example : Consider a memory system with page size 64KB and 32-bit processor. Each entry in the page table is 4 Bytes. </p>
<p><strong>Single-level Page Table</strong> : 16 (2^16 = 64KB) bits are required to represent page offset. So rest 16-bits are used to index into page table. So </p>
<p><strong>*Size of page table = 2^16(# of pages) * 4 Bytes(Size of each page table entry) = 2^18 Bytes*</strong></p>
<p><strong>Multi-level Page Table</strong> : In case of two-level page table, lets use first 10-most significant bits to index into first level page table. Next 10-bits to index into second level page table, which has the page number to frame number mappings. Rest 12-bits represents the page offset. </p>
<p>Size of a second-level page table = 2^10 (# of entries) * 4 bytes(size of each entry) = 4 KB</p>
<p>Total size of all the second-level page tables = 2^10 (# of second-level page tables) * 4KB (Size of each second-level page table) = 4 MB</p>
<p>Size of first-level page table = 2^10(# of entries) * (10/8) Bytes (Size of each entry) = 1.25 KB</p>
<p><strong><em>Total memory required to store first and second level page tables = 4 MB + 1.25 KB</em></strong> </p>
<p><strong><em>So we need more memory to store multi-level page tables.</em></strong> </p>
<p>If this is the case, How does multi-level page tables save memory space ?</p> | 30,471,717 | 4 | 2 | null | 2015-04-06 07:58:27.237 UTC | 28 | 2020-11-16 10:49:08.053 UTC | null | null | null | null | 888,415 | null | 1 | 50 | memory|operating-system|paging|virtual-memory|page-tables | 57,499 | <ol>
<li>In singlelevel pagetable you need the whole table to access even a small amount of data(less memory references). i.e 2^20 pages each PTE occupying 4bytes as you assumed.</li>
</ol>
<p>Space required to access any data is 2^20 * 4bytes = 4MB</p>
<ol start="2">
<li>Paging pages is multi-level paging.In multilevel paging it is more specific, you can with the help of multi-level organization decide which specific page among the 2^20 pages your data exists, and select it . So here you need only that specific page to be in the memory while you run the process.</li>
</ol>
<p>In the 2 level case that you discussed you need 1st level pagetable and then 1 of the 2^10 pagetables in second level.
So,
1st level size = 2^10 * 4bytes = 4KB
2nd level we need only 1 among the 2^10 pagetables = so size is 2^10 * 4bytes = 4KB</p>
<p>Total size required is now : 4KB + 4KB = 8KB.</p>
<p>Final comparision is 4MB vs 8KB .</p> |
36,254,452 | Counting Cars OpenCV + Python Issue | <p>I have been <em>trying</em> to count cars when crossing the line and it works, but the problem is it counts one car many times which is ridiculous because it should only be counted once.</p>
<p>Here is the code I am using:</p>
<pre><code>import cv2
import numpy as np
bgsMOG = cv2.BackgroundSubtractorMOG()
cap = cv2.VideoCapture("traffic.avi")
counter = 0
if cap:
while True:
ret, frame = cap.read()
if ret:
fgmask = bgsMOG.apply(frame, None, 0.01)
cv2.line(frame, (0,60), (160,60), (255,255,0), 1)
# To find the countours of the Cars
contours, hierarchy = cv2.findContours(fgmask,
cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
try:
hierarchy = hierarchy[0]
except:
hierarchy = []
for contour, hier in zip(contours, hierarchy):
(x, y, w, h) = cv2.boundingRect(contour)
if w > 20 and h > 20:
cv2.rectangle(frame, (x,y), (x+w,y+h), (255, 0, 0), 1)
# To find the centroid of the car
x1 = w/2
y1 = h/2
cx = x+x1
cy = y+y1
## print "cy=", cy
## print "cx=", cx
centroid = (cx,cy)
## print "centoid=", centroid
# Draw the circle of Centroid
cv2.circle(frame,(int(cx),int(cy)),2,(0,0,255),-1)
# To make sure the Car crosses the line
## dy = cy-108
## print "dy", dy
if centroid > (27, 38) and centroid < (134, 108):
## if (cx <= 132)and(cx >= 20):
counter +=1
## print "counter=", counter
## if cy > 10 and cy < 160:
cv2.putText(frame, str(counter), (x,y-5),
cv2.FONT_HERSHEY_SIMPLEX,
0.5, (255, 0, 255), 2)
## cv2.namedWindow('Output',cv2.cv.CV_WINDOW_NORMAL)
cv2.imshow('Output', frame)
## cv2.imshow('FGMASK', fgmask)
key = cv2.waitKey(60)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
</code></pre>
<p>And the video is on my GitHub page @ <a href="https://github.com/Tes3awy/MATLAB-Tutorials/blob/f24b680f2215c1b1bb96c76f5ba81df533552983/traffic.avi" rel="nofollow noreferrer">https://github.com/Tes3awy/MATLAB-Tutorials/blob/f24b680f2215c1b1bb96c76f5ba81df533552983/traffic.avi</a> (and it's also a built-in video in Matlab library)</p>
<p>How can make it so that each car is only counted once?</p>
<hr />
<p>The individual frames of the video look as follows:</p>
<p><a href="https://i.imgur.com/R5O1yYD.png" rel="nofollow noreferrer"><img src="https://i.imgur.com/R5O1yYD.png" width="640"></a></p> | 36,274,515 | 1 | 3 | null | 2016-03-28 00:57:19.933 UTC | 62 | 2021-10-11 19:04:38.387 UTC | 2021-10-11 19:04:38.387 UTC | null | 63,550 | null | 5,865,393 | null | 1 | 46 | python|numpy|opencv|image-processing | 36,524 | <h1>Preparation</h1>
<p>In order to understand what is happening, and eventually solve our problem, we first need to improve the script a little.</p>
<p>I've added logging of the important steps of your algorithm, refactored the code a little, and added saving of the mask and processed images, added ability to run the script using the individual frame images, along with some other modifications.</p>
<p>This is what the script looks like at this point:</p>
<pre><code>import logging
import logging.handlers
import os
import time
import sys
import cv2
import numpy as np
from vehicle_counter import VehicleCounter
# ============================================================================
IMAGE_DIR = "images"
IMAGE_FILENAME_FORMAT = IMAGE_DIR + "/frame_%04d.png"
# Support either video file or individual frames
CAPTURE_FROM_VIDEO = False
if CAPTURE_FROM_VIDEO:
IMAGE_SOURCE = "traffic.avi" # Video file
else:
IMAGE_SOURCE = IMAGE_FILENAME_FORMAT # Image sequence
# Time to wait between frames, 0=forever
WAIT_TIME = 1 # 250 # ms
LOG_TO_FILE = True
# Colours for drawing on processed frames
DIVIDER_COLOUR = (255, 255, 0)
BOUNDING_BOX_COLOUR = (255, 0, 0)
CENTROID_COLOUR = (0, 0, 255)
# ============================================================================
def init_logging():
main_logger = logging.getLogger()
formatter = logging.Formatter(
fmt='%(asctime)s.%(msecs)03d %(levelname)-8s [%(name)s] %(message)s'
, datefmt='%Y-%m-%d %H:%M:%S')
handler_stream = logging.StreamHandler(sys.stdout)
handler_stream.setFormatter(formatter)
main_logger.addHandler(handler_stream)
if LOG_TO_FILE:
handler_file = logging.handlers.RotatingFileHandler("debug.log"
, maxBytes = 2**24
, backupCount = 10)
handler_file.setFormatter(formatter)
main_logger.addHandler(handler_file)
main_logger.setLevel(logging.DEBUG)
return main_logger
# ============================================================================
def save_frame(file_name_format, frame_number, frame, label_format):
file_name = file_name_format % frame_number
label = label_format % frame_number
log.debug("Saving %s as '%s'", label, file_name)
cv2.imwrite(file_name, frame)
# ============================================================================
def get_centroid(x, y, w, h):
x1 = int(w / 2)
y1 = int(h / 2)
cx = x + x1
cy = y + y1
return (cx, cy)
# ============================================================================
def detect_vehicles(fg_mask):
log = logging.getLogger("detect_vehicles")
MIN_CONTOUR_WIDTH = 21
MIN_CONTOUR_HEIGHT = 21
# Find the contours of any vehicles in the image
contours, hierarchy = cv2.findContours(fg_mask
, cv2.RETR_EXTERNAL
, cv2.CHAIN_APPROX_SIMPLE)
log.debug("Found %d vehicle contours.", len(contours))
matches = []
for (i, contour) in enumerate(contours):
(x, y, w, h) = cv2.boundingRect(contour)
contour_valid = (w >= MIN_CONTOUR_WIDTH) and (h >= MIN_CONTOUR_HEIGHT)
log.debug("Contour #%d: pos=(x=%d, y=%d) size=(w=%d, h=%d) valid=%s"
, i, x, y, w, h, contour_valid)
if not contour_valid:
continue
centroid = get_centroid(x, y, w, h)
matches.append(((x, y, w, h), centroid))
return matches
# ============================================================================
def filter_mask(fg_mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
# Fill any small holes
closing = cv2.morphologyEx(fg_mask, cv2.MORPH_CLOSE, kernel)
# Remove noise
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)
# Dilate to merge adjacent blobs
dilation = cv2.dilate(opening, kernel, iterations = 2)
return dilation
# ============================================================================
def process_frame(frame_number, frame, bg_subtractor, car_counter):
log = logging.getLogger("process_frame")
# Create a copy of source frame to draw into
processed = frame.copy()
# Draw dividing line -- we count cars as they cross this line.
cv2.line(processed, (0, car_counter.divider), (frame.shape[1], car_counter.divider), DIVIDER_COLOUR, 1)
# Remove the background
fg_mask = bg_subtractor.apply(frame, None, 0.01)
fg_mask = filter_mask(fg_mask)
save_frame(IMAGE_DIR + "/mask_%04d.png"
, frame_number, fg_mask, "foreground mask for frame #%d")
matches = detect_vehicles(fg_mask)
log.debug("Found %d valid vehicle contours.", len(matches))
for (i, match) in enumerate(matches):
contour, centroid = match
log.debug("Valid vehicle contour #%d: centroid=%s, bounding_box=%s", i, centroid, contour)
x, y, w, h = contour
# Mark the bounding box and the centroid on the processed frame
# NB: Fixed the off-by one in the bottom right corner
cv2.rectangle(processed, (x, y), (x + w - 1, y + h - 1), BOUNDING_BOX_COLOUR, 1)
cv2.circle(processed, centroid, 2, CENTROID_COLOUR, -1)
log.debug("Updating vehicle count...")
car_counter.update_count(matches, processed)
return processed
# ============================================================================
def main():
log = logging.getLogger("main")
log.debug("Creating background subtractor...")
bg_subtractor = cv2.BackgroundSubtractorMOG()
log.debug("Pre-training the background subtractor...")
default_bg = cv2.imread(IMAGE_FILENAME_FORMAT % 119)
bg_subtractor.apply(default_bg, None, 1.0)
car_counter = None # Will be created after first frame is captured
# Set up image source
log.debug("Initializing video capture device #%s...", IMAGE_SOURCE)
cap = cv2.VideoCapture(IMAGE_SOURCE)
frame_width = cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)
frame_height = cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)
log.debug("Video capture frame size=(w=%d, h=%d)", frame_width, frame_height)
log.debug("Starting capture loop...")
frame_number = -1
while True:
frame_number += 1
log.debug("Capturing frame #%d...", frame_number)
ret, frame = cap.read()
if not ret:
log.error("Frame capture failed, stopping...")
break
log.debug("Got frame #%d: shape=%s", frame_number, frame.shape)
if car_counter is None:
# We do this here, so that we can initialize with actual frame size
log.debug("Creating vehicle counter...")
car_counter = VehicleCounter(frame.shape[:2], frame.shape[0] / 2)
# Archive raw frames from video to disk for later inspection/testing
if CAPTURE_FROM_VIDEO:
save_frame(IMAGE_FILENAME_FORMAT
, frame_number, frame, "source frame #%d")
log.debug("Processing frame #%d...", frame_number)
processed = process_frame(frame_number, frame, bg_subtractor, car_counter)
save_frame(IMAGE_DIR + "/processed_%04d.png"
, frame_number, processed, "processed frame #%d")
cv2.imshow('Source Image', frame)
cv2.imshow('Processed Image', processed)
log.debug("Frame #%d processed.", frame_number)
c = cv2.waitKey(WAIT_TIME)
if c == 27:
log.debug("ESC detected, stopping...")
break
log.debug("Closing video capture device...")
cap.release()
cv2.destroyAllWindows()
log.debug("Done.")
# ============================================================================
if __name__ == "__main__":
log = init_logging()
if not os.path.exists(IMAGE_DIR):
log.debug("Creating image directory `%s`...", IMAGE_DIR)
os.makedirs(IMAGE_DIR)
main()
</code></pre>
<p>This script is responsible for processing of the stream of images, and identifying all the vehicles in each frame -- I refer to them as <code>matches</code> in the code.</p>
<hr>
<p>The task of counting the detected vehicles is delegated to class <code>VehicleCounter</code>. The reason why I chose to make this a class will become evident as we progress. I did not implement your vehicle counting algorithm, because it will not work for reasons that will again become evident as we dig into this deeper.</p>
<p>File <code>vehicle_counter.py</code> contains the following code:</p>
<pre><code>import logging
# ============================================================================
class VehicleCounter(object):
def __init__(self, shape, divider):
self.log = logging.getLogger("vehicle_counter")
self.height, self.width = shape
self.divider = divider
self.vehicle_count = 0
def update_count(self, matches, output_image = None):
self.log.debug("Updating count using %d matches...", len(matches))
# ============================================================================
</code></pre>
<hr>
<p>Finally, I wrote a script that will stitch all the generated images together, so it's easier to inspect them:</p>
<pre><code>import cv2
import numpy as np
# ============================================================================
INPUT_WIDTH = 160
INPUT_HEIGHT = 120
OUTPUT_TILE_WIDTH = 10
OUTPUT_TILE_HEIGHT = 12
TILE_COUNT = OUTPUT_TILE_WIDTH * OUTPUT_TILE_HEIGHT
# ============================================================================
def stitch_images(input_format, output_filename):
output_shape = (INPUT_HEIGHT * OUTPUT_TILE_HEIGHT
, INPUT_WIDTH * OUTPUT_TILE_WIDTH
, 3)
output = np.zeros(output_shape, np.uint8)
for i in range(TILE_COUNT):
img = cv2.imread(input_format % i)
cv2.rectangle(img, (0, 0), (INPUT_WIDTH - 1, INPUT_HEIGHT - 1), (0, 0, 255), 1)
# Draw the frame number
cv2.putText(img, str(i), (2, 10)
, cv2.FONT_HERSHEY_PLAIN, 0.7, (255, 255, 255), 1)
x = i % OUTPUT_TILE_WIDTH * INPUT_WIDTH
y = i / OUTPUT_TILE_WIDTH * INPUT_HEIGHT
output[y:y+INPUT_HEIGHT, x:x+INPUT_WIDTH,:] = img
cv2.imwrite(output_filename, output)
# ============================================================================
stitch_images("images/frame_%04d.png", "stitched_frames.png")
stitch_images("images/mask_%04d.png", "stitched_masks.png")
stitch_images("images/processed_%04d.png", "stitched_processed.png")
</code></pre>
<hr>
<h1>Analysis</h1>
<p>In order to solve this problem, we should have some idea about what results we expect to get. We should also label all the distinct cars in the video, so it's easier to talk about them.</p>
<p><img src="https://i.imgur.com/RKZ8inQ.png" alt="All 10 vehicles from the video"></p>
<p>If we run our script, and stitch the images together, we get the a number of useful files to help us analyze the problem:</p>
<ul>
<li>Image containing a <a href="https://i.imgur.com/R5O1yYD.png" rel="noreferrer">mosaic of input frames</a></li>
<li>Image containing a <a href="https://i.imgur.com/zXKlmBN.png" rel="noreferrer">mosaic of foreground masks</a>:</li>
</ul>
<p><a href="https://i.imgur.com/zXKlmBN.png" rel="noreferrer"><img src="https://i.imgur.com/zXKlmBN.png"></a></p>
<ul>
<li>Image containing a <a href="https://i.imgur.com/4ceMiT2.png" rel="noreferrer">mosaic of processed frames</a></li>
</ul>
<p><a href="https://i.imgur.com/4ceMiT2.png" rel="noreferrer"><img src="https://i.imgur.com/4ceMiT2.png"></a></p>
<ul>
<li>The <a href="http://pastebin.com/7yAMxLkz" rel="noreferrer">debug log</a> for the run.</li>
</ul>
<p>Upon inspecting those, a number of issues become evident:</p>
<ul>
<li>The foreground masks tend to be noisy. We should do some filtering (erode/dilate?) to get rid of the noise and narrow gaps.</li>
<li>Sometimes we miss vehicles (grey ones).</li>
<li>Some vehicles get detected twice in the single frame.</li>
<li>Vehicles are rarely detected in the upper regions of the frame.</li>
<li>The same vehicle is often detected in consecutive frames. We need to figure out a way of tracking the same vehicle in consecutive frames, and counting it only once.</li>
</ul>
<hr>
<h1>Solution</h1>
<h2>1. Pre-Seeding the Background Subtractor</h2>
<p>Our video is quite short, only 120 frames. With learning rate of <code>0.01</code>, it will take a substantial part of the video for the background detector to stabilize.</p>
<p>Fortunately, the last frame of the video (frame number 119) is completely devoid of vehicles, and therefore we can use it as our initial background image. (Other options of obtaining suitable image are mentioned in notes and comments.)</p>
<p><img src="https://i.imgur.com/0r2qEjw.png" alt="Background Image"></p>
<p>To use this initial background image, we simply load it, and <code>apply</code> it on the background subtractor with learning factor <code>1.0</code>:</p>
<pre><code>bg_subtractor = cv2.BackgroundSubtractorMOG()
default_bg = cv2.imread(IMAGE_FILENAME_FORMAT % 119)
bg_subtractor.apply(default_bg, None, 1.0)
</code></pre>
<p>When we look at the new <a href="https://i.imgur.com/vcQ66Zb.png" rel="noreferrer">mosaic of masks</a> we can see that we get less noise and the vehicle detection works better in the early frames.</p>
<p><a href="https://i.imgur.com/vcQ66Zb.png" rel="noreferrer"><img src="https://i.imgur.com/vcQ66Zb.png"></a></p>
<h2>2. Cleaning Up the Foreground Mask</h2>
<p>A simple approach to improve our foreground mask is to apply a few <a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_morphological_ops/py_morphological_ops.html" rel="noreferrer">morphological transformations</a>.</p>
<pre><code>def filter_mask(fg_mask):
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
# Fill any small holes
closing = cv2.morphologyEx(fg_mask, cv2.MORPH_CLOSE, kernel)
# Remove noise
opening = cv2.morphologyEx(closing, cv2.MORPH_OPEN, kernel)
# Dilate to merge adjacent blobs
dilation = cv2.dilate(opening, kernel, iterations = 2)
return dilation
</code></pre>
<p>Inspecting the <a href="https://i.imgur.com/iavT8I1.png" rel="noreferrer">masks</a>, <a href="https://i.imgur.com/ZKqDpfU.png" rel="noreferrer">processed frames</a> and the <a href="http://pastebin.com/XvijCjYR" rel="noreferrer">log file</a> generated with filtering, we can see that we now detect vehicles more reliably, and have mitigated the issue of different parts of one vehicle being detected as separate objects.</p>
<p><a href="https://i.imgur.com/iavT8I1.png" rel="noreferrer"><img src="https://i.imgur.com/iavT8I1.png"></a></p>
<p><a href="https://i.imgur.com/ZKqDpfU.png" rel="noreferrer"><img src="https://i.imgur.com/ZKqDpfU.png"></a></p>
<h2>3. Tracking Vehicles Between Frames</h2>
<p>At this point, we need to go through our log file, and collect all the centroid coordinates for each vehicle. This will allow us to plot and inspect the path each vehicle traces across the image, and develop an algorithm to do this automatically. To make this process easier, we can create a <a href="http://pastebin.com/vsQ4wYSJ" rel="noreferrer">reduced log</a> by grepping out the relevant entries.</p>
<p>The lists of centroid coordinates:</p>
<pre><code>traces = {
'A': [(112, 36), (112, 45), (112, 52), (112, 54), (112, 63), (111, 73), (111, 86), (111, 91), (111, 97), (110, 105)]
, 'B': [(119, 37), (120, 42), (121, 54), (121, 55), (123, 64), (124, 74), (125, 87), (127, 94), (125, 100), (126, 108)]
, 'C': [(93, 23), (91, 27), (89, 31), (87, 36), (85, 42), (82, 49), (79, 59), (74, 71), (70, 82), (62, 86), (61, 92), (55, 101)]
, 'D': [(118, 30), (124, 83), (125, 90), (116, 101), (122, 100)]
, 'E': [(77, 27), (75, 30), (73, 33), (70, 37), (67, 42), (63, 47), (59, 53), (55, 59), (49, 67), (43, 75), (36, 85), (27, 92), (24, 97), (20, 102)]
, 'F': [(119, 30), (120, 34), (120, 39), (122, 59), (123, 60), (124, 70), (125, 82), (127, 91), (126, 97), (128, 104)]
, 'G': [(88, 37), (87, 41), (85, 48), (82, 55), (79, 63), (76, 74), (72, 87), (67, 92), (65, 98), (60, 106)]
, 'H': [(124, 35), (123, 40), (125, 45), (127, 59), (126, 59), (128, 67), (130, 78), (132, 88), (134, 93), (135, 99), (135, 107)]
, 'I': [(98, 26), (97, 30), (96, 34), (94, 40), (92, 47), (90, 55), (87, 64), (84, 77), (79, 87), (74, 93), (73, 102)]
, 'J': [(123, 60), (125, 63), (125, 81), (127, 93), (126, 98), (125, 100)]
}
</code></pre>
<p>Individual vehicle traces plotted on the background:</p>
<p><img src="https://i.imgur.com/wOegu9l.png" alt="Traces of the detected vehicles"></p>
<p>Combined enlarged image of all the vehicle traces:</p>
<p><img src="https://i.imgur.com/Y4dhUPp.png" alt="All traces together on a scaled up background"></p>
<h3>Vectors</h3>
<p>In order to analyze the movement, we need to work with vectors (i.e. the distance and direction moved). The following diagram shows how the angles correspond to movement of vehicles in the image.</p>
<p><img src="https://i.imgur.com/2PGIa8D.png" alt=""></p>
<p>We can use the following function to calculate the vector between two points:</p>
<pre><code>def get_vector(a, b):
"""Calculate vector (distance, angle in degrees) from point a to point b.
Angle ranges from -180 to 180 degrees.
Vector with angle 0 points straight down on the image.
Values increase in clockwise direction.
"""
dx = float(b[0] - a[0])
dy = float(b[1] - a[1])
distance = math.sqrt(dx**2 + dy**2)
if dy > 0:
angle = math.degrees(math.atan(-dx/dy))
elif dy == 0:
if dx < 0:
angle = 90.0
elif dx > 0:
angle = -90.0
else:
angle = 0.0
else:
if dx < 0:
angle = 180 - math.degrees(math.atan(dx/dy))
elif dx > 0:
angle = -180 - math.degrees(math.atan(dx/dy))
else:
angle = 180.0
return distance, angle
</code></pre>
<h3>Categorization</h3>
<p>One way we can look for patterns that could be used to categorize the movements as valid/invalid is to make a scatter plot (angle vs. distance):</p>
<p><img src="https://i.imgur.com/cm7DyUX.png" alt="Plot of angle vs distance"></p>
<ul>
<li>Green points represent valid movement, that we determined using the lists of points for each vehicle.</li>
<li>Red points represent invalid movement - vectors between points in adjacent traffic lanes.</li>
<li>I plotted two blue curves, which we can use to separate the two types of movements. Any point that lies below either curve can be considered as valid. The curves are:
<ul>
<li><code>distance = -0.008 * angle**2 + 0.4 * angle + 25.0</code></li>
<li><code>distance = 10.0</code></li>
</ul></li>
</ul>
<p>We can use the following function to categorize the movement vectors:</p>
<pre><code>def is_valid_vector(a):
distance, angle = a
threshold_distance = max(10.0, -0.008 * angle**2 + 0.4 * angle + 25.0)
return (distance <= threshold_distance)
</code></pre>
<p>NB: There is one outlier, which is occurs due to our loosing track of vehicle <strong>D</strong> in frames 43..48.</p>
<h3>Algorithm</h3>
<p>We will use class <code>Vehicle</code> to store information about each tracked vehicle:</p>
<ul>
<li>Some kind of identifier</li>
<li>List of positions, most recent at front</li>
<li>Last-seen counter -- number of frames since we've last seen this vehicle</li>
<li>Flag to mark whether the vehicle was counted or not</li>
</ul>
<p>Class <code>VehicleCounter</code> will store a list of currently tracked vehicles and keep track of the total count. On each frame, we will use the list of bounding boxes and positions of identified vehicles (candidate list) to update the state of <code>VehicleCounter</code>:</p>
<ol>
<li>Update currently tracked <code>Vehicle</code>s:
<ul>
<li>For each vehicle
<ul>
<li>If there is any valid match for given vehicle, update vehicle position and reset its last-seen counter. Remove the match from the candidate list.</li>
<li>Otherwise, increase the last-seen counter for that vehicle.</li>
</ul></li>
</ul></li>
<li>Create new <code>Vehicle</code>s for any remaining matches</li>
<li>Update vehicle count
<ul>
<li>For each vehicle
<ul>
<li>If the vehicle is past divider and has not been counted yet, update the total count and mark the vehicle as counted</li>
</ul></li>
</ul></li>
<li>Remove vehicles that are no longer visible
<ul>
<li>For each vehicle
<ul>
<li>If the last-seen counter exceeds threshold, remove the vehicle</li>
</ul></li>
</ul></li>
</ol>
<h2>4. Solution</h2>
<p>We can reuse the main script with the final version of <code>vehicle_counter.py</code>, containing the implementation of our counting algorithm:</p>
<pre><code>import logging
import math
import cv2
import numpy as np
# ============================================================================
CAR_COLOURS = [ (0,0,255), (0,106,255), (0,216,255), (0,255,182), (0,255,76)
, (144,255,0), (255,255,0), (255,148,0), (255,0,178), (220,0,255) ]
# ============================================================================
class Vehicle(object):
def __init__(self, id, position):
self.id = id
self.positions = [position]
self.frames_since_seen = 0
self.counted = False
@property
def last_position(self):
return self.positions[-1]
def add_position(self, new_position):
self.positions.append(new_position)
self.frames_since_seen = 0
def draw(self, output_image):
car_colour = CAR_COLOURS[self.id % len(CAR_COLOURS)]
for point in self.positions:
cv2.circle(output_image, point, 2, car_colour, -1)
cv2.polylines(output_image, [np.int32(self.positions)]
, False, car_colour, 1)
# ============================================================================
class VehicleCounter(object):
def __init__(self, shape, divider):
self.log = logging.getLogger("vehicle_counter")
self.height, self.width = shape
self.divider = divider
self.vehicles = []
self.next_vehicle_id = 0
self.vehicle_count = 0
self.max_unseen_frames = 7
@staticmethod
def get_vector(a, b):
"""Calculate vector (distance, angle in degrees) from point a to point b.
Angle ranges from -180 to 180 degrees.
Vector with angle 0 points straight down on the image.
Values increase in clockwise direction.
"""
dx = float(b[0] - a[0])
dy = float(b[1] - a[1])
distance = math.sqrt(dx**2 + dy**2)
if dy > 0:
angle = math.degrees(math.atan(-dx/dy))
elif dy == 0:
if dx < 0:
angle = 90.0
elif dx > 0:
angle = -90.0
else:
angle = 0.0
else:
if dx < 0:
angle = 180 - math.degrees(math.atan(dx/dy))
elif dx > 0:
angle = -180 - math.degrees(math.atan(dx/dy))
else:
angle = 180.0
return distance, angle
@staticmethod
def is_valid_vector(a):
distance, angle = a
threshold_distance = max(10.0, -0.008 * angle**2 + 0.4 * angle + 25.0)
return (distance <= threshold_distance)
def update_vehicle(self, vehicle, matches):
# Find if any of the matches fits this vehicle
for i, match in enumerate(matches):
contour, centroid = match
vector = self.get_vector(vehicle.last_position, centroid)
if self.is_valid_vector(vector):
vehicle.add_position(centroid)
self.log.debug("Added match (%d, %d) to vehicle #%d. vector=(%0.2f,%0.2f)"
, centroid[0], centroid[1], vehicle.id, vector[0], vector[1])
return i
# No matches fit...
vehicle.frames_since_seen += 1
self.log.debug("No match for vehicle #%d. frames_since_seen=%d"
, vehicle.id, vehicle.frames_since_seen)
return None
def update_count(self, matches, output_image = None):
self.log.debug("Updating count using %d matches...", len(matches))
# First update all the existing vehicles
for vehicle in self.vehicles:
i = self.update_vehicle(vehicle, matches)
if i is not None:
del matches[i]
# Add new vehicles based on the remaining matches
for match in matches:
contour, centroid = match
new_vehicle = Vehicle(self.next_vehicle_id, centroid)
self.next_vehicle_id += 1
self.vehicles.append(new_vehicle)
self.log.debug("Created new vehicle #%d from match (%d, %d)."
, new_vehicle.id, centroid[0], centroid[1])
# Count any uncounted vehicles that are past the divider
for vehicle in self.vehicles:
if not vehicle.counted and (vehicle.last_position[1] > self.divider):
self.vehicle_count += 1
vehicle.counted = True
self.log.debug("Counted vehicle #%d (total count=%d)."
, vehicle.id, self.vehicle_count)
# Optionally draw the vehicles on an image
if output_image is not None:
for vehicle in self.vehicles:
vehicle.draw(output_image)
cv2.putText(output_image, ("%02d" % self.vehicle_count), (142, 10)
, cv2.FONT_HERSHEY_PLAIN, 0.7, (127, 255, 255), 1)
# Remove vehicles that have not been seen long enough
removed = [ v.id for v in self.vehicles
if v.frames_since_seen >= self.max_unseen_frames ]
self.vehicles[:] = [ v for v in self.vehicles
if not v.frames_since_seen >= self.max_unseen_frames ]
for id in removed:
self.log.debug("Removed vehicle #%d.", id)
self.log.debug("Count updated, tracking %d vehicles.", len(self.vehicles))
# ============================================================================
</code></pre>
<p>The program now draws the historical paths of all currently tracked vehicles into the output image, along with the vehicle count. Each vehicle is assigned 1 of 10 colours.</p>
<p>Notice that vehicle D ends up being tracked twice, however it is counted only once, since we lose track of it before crossing the divider. Ideas on how to resolve this are mentioned in the appendix.</p>
<p>Based on the last processed frame generated by the script</p>
<p><img src="https://i.imgur.com/zWVm5tu.png" alt="Last processed frame"></p>
<p>the total vehicle count is <strong>10</strong>. This is a correct result.</p>
<p>More details can be found in the output the script generated:</p>
<ul>
<li>Full <a href="http://pastebin.com/M1rtdqk9" rel="noreferrer">debug log</a></li>
<li>Filtered out <a href="http://pastebin.com/kaZLzBTz" rel="noreferrer">vehicle counter log</a></li>
<li>A mosaic of the processed frames:</li>
</ul>
<p><a href="https://i.imgur.com/Ipi0vkB.png" rel="noreferrer"><img src="https://i.imgur.com/Ipi0vkB.png"></a></p>
<hr>
<h2>A. Potential Improvements</h2>
<ul>
<li>Refactor, add unit tests.</li>
<li>Improve filtering/preprocessing of the foreground mask
<ul>
<li>Multiple iterations of filtering, fill holes using <code>cv2.drawContours</code> with <code>CV_FILLED</code>?</li>
<li>Watershed Algorithm?</li>
</ul></li>
<li>Improve categorization of movement vectors
<ul>
<li>Create a predictor to estimate initial movement angle when vehicles are created (and only one position is known)... in order to be able to</li>
<li>Use <em>change in direction</em> rather than <em>direction</em> alone (I think this would cluster the angles of valid motion vectors close to zero).</li>
</ul></li>
<li>Improve vehicle tracking
<ul>
<li>Predict position for frames where vehicle is not seen.</li>
</ul></li>
</ul>
<h2>B. Notes</h2>
<ul>
<li>It seems it's not possible to directly extract the current background image from <code>BackgroundSubtractorMOG</code> in Python (at least in OpenCV 2.4.x), but <a href="https://stackoverflow.com/questions/19031836/get-background-model-from-backgroundsubtractormog2-in-python">there is a way to do it</a> with a little work.</li>
<li>As suggested by <a href="https://stackoverflow.com/users/1331076/henrik">Henrik</a>, we can obtain a good estimate of the background using <a href="http://petapixel.com/2013/05/29/a-look-at-reducing-noise-in-photographs-using-median-blending/" rel="noreferrer">median blending</a>.</li>
</ul> |
36,371,190 | Mongoose Query to filter an array and Populate related content | <p>I'm trying to query the property that is an array of both reference to another schema and some additional data. For better clarification, here's the schema:</p>
<pre><code> var orderSchema = new Schema({
orderDate: Date,
articles: [{
article: {
type: Schema.Types.ObjectId,
ref: 'Article'
},
quantity: 'Number'
}]
}),
Order = mongoose.model('Order', orderSchema);
</code></pre>
<p>While I managed to successfully query the reference, i.e.:</p>
<pre><code>Order.find({}).populate('articles.article', null, {
price: {
$lte: 500
}
}).exec(function(err, data) {
for (var order of data) {
for (var article of order.articles) {
console.log(article);
}
}
});
</code></pre>
<p>I have some issues querying the <code>quantity</code> attribute, i.e. this doesn't work:</p>
<pre><code>Order.find({}).where({
'articles.quantity': {
$gte: 5
}
}).populate('articles.article', null, {
/*price: {
$lte: 500
}*/
}).exec(function(err, data) {
for (var order of data) {
for (var article of order.articles) {
console.log(article);
}
}
});
</code></pre>
<p>Is it even possible to base the query on <code>quantity</code>? And if so, what would be the best approach? </p>
<p>Thank you!</p>
<p><strong>UPDATE:</strong></p>
<p>The problem is, the result is either a complete array, or nothing (see updated question). I want to get only those records that have quantity more or the same as 5. With your (and mine) approach I get either no records at all (if I set $gte: 5001) or both records (if I set $gte:5000)</p>
<pre><code>{
"_id": ObjectId('56fe76c12f7174ac5018054f'),
"orderDate": ISODate('2016-04-01T13:25:21.055Z'),
"articles": [
{
"article": ObjectId('56fe76c12f7174ac5018054b'),
"quantity": 5000,
"_id": ObjectId('56fe76c12f7174ac50180551')
},
{
"article": ObjectId('56fe76c12f7174ac5018054c'),
"quantity": 1,
"_id": ObjectId('56fe76c12f7174ac50180552')
}
],
"__v": 1
}
</code></pre> | 36,371,665 | 2 | 4 | null | 2016-04-02 08:50:55.47 UTC | 3 | 2020-05-20 00:08:06.177 UTC | 2016-04-02 09:45:12.773 UTC | null | 5,031,275 | null | 4,180,290 | null | 1 | 12 | node.js|mongodb|mongoose|mongodb-query|aggregation-framework | 68,033 | <p>You need to "project" the match here since all the MongoDB query does is look for a "document" that has <em>"at least one element"</em> that is <em>"greater than"</em> the condition you asked for.</p>
<p>So filtering an "array" is not the same as the "query" condition you have.</p>
<p>A simple "projection" will just return the "first" matched item to that condtion. So it's probably not what you want, but as an example:</p>
<pre><code>Order.find({ "articles.quantity": { "$gte": 5 } })
.select({ "articles.$": 1 })
.populate({
"path": "articles.article",
"match": { "price": { "$lte": 500 } }
}).exec(function(err,orders) {
// populated and filtered twice
}
)
</code></pre>
<p>That "sort of" does what you want, but the problem is really going to be that will only ever return at most <strong>one</strong> element within the <code>"articles"</code> array.</p>
<p>To do this properly you need <code>.aggregate()</code> to filter the array content. Ideally this is done with MongoDB 3.2 and <a href="https://docs.mongodb.org/manual/reference/operator/aggregation/filter/" rel="noreferrer"><code>$filter</code></a>. But there is also a special way to <code>.populate()</code> here:</p>
<pre><code>Order.aggregate(
[
{ "$match": { "artciles.quantity": { "$gte": 5 } } },
{ "$project": {
"orderdate": 1,
"articles": {
"$filter": {
"input": "$articles",
"as": "article",
"cond": {
"$gte": [ "$$article.quantity", 5 ]
}
}
},
"__v": 1
}}
],
function(err,orders) {
Order.populate(
orders.map(function(order) { return new Order(order) }),
{
"path": "articles.article",
"match": { "price": { "$lte": 500 } }
},
function(err,orders) {
// now it's all populated and mongoose documents
}
)
}
)
</code></pre>
<p>So what happens here is the actual "filtering" of the array happens within the <code>.aggregate()</code> statement, but of course the result from this is no longer a "mongoose document" because one aspect of <code>.aggregate()</code> is that it can "alter" the document structure, and for this reason mongoose "presumes" that is the case and just returns a "plain object".</p>
<p>That's not really a problem, since when you see the <code>$project</code> stage, we are actually asking for all of the same fields present in the document according to the defined schema. So even though it's just a "plain object" there is no problem "casting" it back into an mongoose document.</p>
<p>This is where the <code>.map()</code> comes in, as it returns an array of converted "documents", which is then important for the next stage.</p>
<p>Now you call <a href="http://mongoosejs.com/docs/api.html#model_Model.populate" rel="noreferrer"><code>Model.populate()</code></a> which can then run the further "population" on the "array of mongoose documents".</p>
<p>The result then is finally what you want.</p>
<hr>
<h2>MongoDB older versions than 3.2.x</h2>
<p>The only things that really change here are the aggregation pipeline, So that is all that needs to be included for brevity.</p>
<p><strong>MongoDB 2.6</strong> - Can filter arrays with a combination of <a href="https://docs.mongodb.org/manual/reference/operator/aggregation/map/" rel="noreferrer"><code>$map</code></a> and <a href="https://docs.mongodb.org/manual/reference/operator/aggregation/setDifference/" rel="noreferrer"><code>$setDifference</code></a>. The result is a "set" but that is not a problem when mongoose creates an <code>_id</code> field on all sub-document arrays by default:</p>
<pre><code> [
{ "$match": { "artciles.quantity": { "$gte": 5 } } },
{ "$project": {
"orderdate": 1,
"articles": {
"$setDiffernce": [
{ "$map": {
"input": "$articles",
"as": "article",
"in": {
"$cond": [
{ "$gte": [ "$$article.price", 5 ] },
"$$article",
false
]
}
}},
[false]
]
},
"__v": 1
}}
],
</code></pre>
<p>Older revisions of than that must use <a href="https://docs.mongodb.org/manual/reference/operator/aggregation/unwind/" rel="noreferrer"><code>$unwind</code></a>:</p>
<pre><code> [
{ "$match": { "artciles.quantity": { "$gte": 5 } }},
{ "$unwind": "$articles" },
{ "$match": { "artciles.quantity": { "$gte": 5 } }},
{ "$group": {
"_id": "$_id",
"orderdate": { "$first": "$orderdate" },
"articles": { "$push": "$articles" },
"__v": { "$first": "$__v" }
}}
],
</code></pre>
<h2>The $lookup Alternative</h2>
<p>Another alternate is to just do everything on the "server" instead. This is an option with <a href="https://docs.mongodb.org/manual/reference/operator/aggregation/lookup/" rel="noreferrer"><code>$lookup</code></a> of MongoDB 3.2 and greater:</p>
<pre><code>Order.aggregate(
[
{ "$match": { "artciles.quantity": { "$gte": 5 } }},
{ "$project": {
"orderdate": 1,
"articles": {
"$filter": {
"input": "$articles",
"as": "article",
"cond": {
"$gte": [ "$$article.quantity", 5 ]
}
}
},
"__v": 1
}},
{ "$unwind": "$articles" },
{ "$lookup": {
"from": "articles",
"localField": "articles.article",
"foreignField": "_id",
"as": "articles.article"
}},
{ "$unwind": "$articles.article" },
{ "$group": {
"_id": "$_id",
"orderdate": { "$first": "$orderdate" },
"articles": { "$push": "$articles" },
"__v": { "$first": "$__v" }
}},
{ "$project": {
"orderdate": 1,
"articles": {
"$filter": {
"input": "$articles",
"as": "article",
"cond": {
"$lte": [ "$$article.article.price", 500 ]
}
}
},
"__v": 1
}}
],
function(err,orders) {
}
)
</code></pre>
<p>And though those are just plain documents, it's just the same results as what you would have got from the <code>.populate()</code> approach. And of course you can always go and "cast" to mongoose documents in all cases again if you really must.</p>
<h2>The "shortest" Path</h2>
<p>This really goes back to the orginal statement where you basically just "accept" that the "query" is not meant to "filter" the array content. The <code>.populate()</code> can happilly do so becuse it's just another "query" and is stuffing in "documents" by convenience.</p>
<p>So if you really are not saving "bucketloads" of bandwith by the removal of additional array members in the orginal document array, then just <code>.filter()</code> them out in post processing code:</p>
<pre><code>Order.find({ "articles.quantity": { "$gte": 5 } })
.populate({
"path": "articles.article",
"match": { "price": { "$lte": 500 } }
}).exec(function(err,orders) {
orders = orders.filter(function(order) {
order.articles = order.articles.filter(function(article) {
return (
( article.quantity >= 5 ) &&
( article.article != null )
)
});
return order.aricles.length > 0;
})
// orders has non matching entries removed
}
)
</code></pre> |
39,496,598 | Laravel 5.3 storage:link -> symlink(): Protocol error | <p>I'm trying to run the following artisan command: </p>
<p><code>php artisan storage:link</code></p>
<p>I get this error:</p>
<p><code>[ErrorException]
symlink(): Protocol error</code></p>
<p>Can you help me to solve this.<br></p>
<p>This is my setup:</p>
<ul>
<li>Windows 10 using vagrant with Homestead (v0.5.0) box</li>
<li>Ubuntu 16.04 LTS (GNU/Linux 4.4.0-22-generic x86_64)<br></li>
<li>Laravel Framework version 5.3.6<br></li>
<li>PHP 7.0</li>
</ul> | 39,572,148 | 9 | 2 | null | 2016-09-14 17:41:44.813 UTC | 6 | 2021-11-05 19:48:45.003 UTC | 2017-08-18 11:04:29.447 UTC | null | 1,810,087 | null | 5,543,999 | null | 1 | 29 | homestead|laravel-artisan|laravel-5.3 | 31,833 | <p>Your problem probably is that you have to start your vagrant box as a system administrator.</p>
<p>So hit start type "cmd", right click it choose "Run as administrator". Navigate to your project, type "vagrant up". Retry the command.</p>
<p><a href="https://laracasts.com/discuss/channels/servers/creating-symbolic-link-on-homestead" rel="noreferrer">Creating symbolic link on Homestead?</a></p> |
31,412,537 | numpy-like package for node | <p>During my years on Python development, I've always been amazed at how much much much faster things become if you manage to rewrite that code that loops though your ndarray and does something, with numpy functions that work on the whole array at once. More recently I'm switching more and more to node, and I'm looking for something similar. So far I have turned up some things, none of which look promising:</p>
<ul>
<li><a href="https://www.npmjs.com/package/scikit-node" rel="noreferrer">scikit-node</a>, runs scikit-learn in python, and interfaces with node. I haven't tried it, but I don't expect it gives me the cutting edge speed that I would like.</li>
<li>There are some rather old, and newer, javascript matrix libraries (<a href="https://www.npmjs.com/package/scikit-node" rel="noreferrer">sylvester</a>, <a href="https://github.com/toji/gl-matrix" rel="noreferrer">gl-matrix</a>, ...). In addition to not being sure they work well with matrices larger than 4x4 (which is most useful in 3D rendering), they seem to be native javascript (and some, not sure these, use webGL acceleration). Great on the browser, not so on node.</li>
</ul>
<p>As far as I know, npms can be written in C++, so I'm wondering why there are no numpy-like libraries for node. Is there just not enough interest in node yet from the community that needs that kind of power? Is there a hope that ES6 features (list comprehensions) will allow javascript compilers to automatically vectorise native JS code to C++ speeds? Am I possibly missing something else?</p>
<p><strong>Edit</strong>, in response to close-votes: Note, I'm not asking for "what is the best package to do xyz". I'm just wondering if there is a technical reason there is no package to do this on node, a social reason, or no reason at all and there is just a package I missed. Maybe to avoid too many opinionated criticism, I want to know: I have about 10000 matrices that are 100 x 100 each. What's the best (* correction, a reasonable fast) way to add them together?</p>
<p><strong>Edit2</strong>
After some more digging, it turned out I was googling for the wrong thing. Google for "node.js scientific computing" and there are links to some very interesting notes:</p>
<ul>
<li><a href="https://cs.stackexchange.com/questions/1693/a-faster-leaner-javascript-for-scientific-computing-what-features-should-i-kee">https://cs.stackexchange.com/questions/1693/a-faster-leaner-javascript-for-scientific-computing-what-features-should-i-kee</a></li>
<li><a href="http://www.quora.com/Can-Node-js-handle-numerical-computation-the-same-way-that-languages-like-R-or-Julia-can" rel="noreferrer">http://www.quora.com/Can-Node-js-handle-numerical-computation-the-same-way-that-languages-like-R-or-Julia-can</a></li>
<li><a href="https://stackoverflow.com/questions/11651081/javascript-and-scientific-processing">Javascript and Scientific Processing?</a></li>
</ul>
<p>Basically as far as I understand now, no-one has bothered so far. Also, since there are some major omissions in the js TypedArrays (such as 64bit ints), it might be hard to add good support by just using NPMs, and not hacking the engine itself --- something that would defeat the purpose. Then again, I didn't further research this last statement.</p> | 49,213,594 | 8 | 9 | null | 2015-07-14 16:40:06.117 UTC | 18 | 2021-03-03 10:15:23.907 UTC | 2018-01-05 12:11:18.883 UTC | null | 527,702 | null | 1,207,489 | null | 1 | 79 | javascript|c++|node.js|numpy|multidimensional-array | 48,002 | <p>Here is Google's <a href="https://js.tensorflow.org/" rel="noreferrer">TensorFlow.js</a> (previously <a href="https://deeplearnjs.org" rel="noreferrer">https://deeplearnjs.org</a>), which does exactly that, and has built in capacities to train deep neural networks on GPUs using WebGL. You can also <a href="https://js.tensorflow.org/tutorials/import-saved-model.html" rel="noreferrer">port TensorFlow models to it</a>.</p>
<p>Don't be fooled into thinking this is only for deep learning. It is a fully fledged numerical computing platform with built-in GPU acceleration. It follows the eager "execute as you go" model, like NumPy (and Tensorflow Eager, and PyTorch, and others), not the "define then run" model like Tensorflow. As such, it will feel natural to use to anyone who has used NumPy before.</p>
<p>Here is the very informative Github repo:</p>
<p><a href="https://github.com/tensorflow/tfjs-core" rel="noreferrer">https://github.com/tensorflow/tfjs-core</a> (the old link <a href="https://github.com/PAIR-code/deeplearnjs" rel="noreferrer">https://github.com/PAIR-code/deeplearnjs</a> now redirects there)</p> |
48,596,157 | Fragments giving Unexpected token error in React 16.2 | <p>I have the following component that renders a series of components. However, I downloaded React 16.2 and tried to use fragments instead of divs, but I get the following error:</p>
<pre><code>Error in ./src/containers/answers.js
Syntax error: Unexpected token (24:5)
22 |
23 | return (
> 24 | <>
| ^
25 | {AnswersCard}
26 | </>
27 | )
</code></pre>
<p>Why am I getting this error when fragments are supposed to be able to replace divs in React 16.2?</p>
<pre><code> question ?
AnswersCard = ( question.answers.sort(function(a,b) { return (a.count < b.count) ? 1 : ((b.count > a.count) ? -1 : 0)}
).map(answer =>
<Answer key={answer.id} answer={answer} questionId={question.id} />
)) : AnswersCard = ( <p>Loading...</p> )
return (
<>
{AnswersCard}
</>
)
}
}
</code></pre> | 48,596,334 | 1 | 5 | null | 2018-02-03 10:08:16.22 UTC | 4 | 2020-03-22 10:28:45.5 UTC | null | null | null | null | 5,676,949 | null | 1 | 39 | reactjs|react-16 | 16,630 | <p>As per the <a href="https://reactjs.org/docs/fragments.html#short-syntax" rel="noreferrer">documentation</a>, the syntax <code><></></code> is not supported by all tools and they encourage you to use <code><React.Fragment></code> instead</p>
<p>Check <strong><a href="https://reactjs.org/blog/2017/11/28/react-v16.2.0-fragment-support.html#support-for-fragment-syntax" rel="noreferrer">this</a></strong> documentation on Support for Fragment syntax</p> |
20,261,574 | Set default value of HTML5 date input field with angularJS | <p>I am hoping to bind the default value I generated in moment to the date and time input field. I tried ng-model and directly binding it to the value attributes. But none of it seems to work. Is there a way to make it work?</p>
<p><strong>Edit:</strong> Also, how to bind the time input field as well?</p>
<pre><code><body ng-app="myApp">
<div ng-controller="MyCtrl">
<input type="date" ng-model="date" value="{{date}}">
<p>{{date}}</p>
<input type="time" ng-model="time" value="{{time}}">
</div>
</code></pre>
<p></p>
<p>Here is a fiddle for it: <a href="http://jsfiddle.net/chrisyeung/bF9Pq/">http://jsfiddle.net/chrisyeung/bF9Pq/</a></p> | 20,262,097 | 4 | 1 | null | 2013-11-28 08:57:45.767 UTC | 6 | 2020-01-08 19:04:26.31 UTC | 2013-11-28 09:26:12.05 UTC | null | 1,156,761 | null | 1,156,761 | null | 1 | 17 | javascript|angularjs|momentjs | 61,024 | <p>If you're using chrome you have to specify the Date format as 'yyyy-MM-dd'. </p>
<pre><code>$scope.date = $filter("date")(Date.now(), 'yyyy-MM-dd');
</code></pre>
<p>It simply won't work otherwise. Here's a working version <a href="http://jsfiddle.net/bF9Pq/4/">http://jsfiddle.net/bF9Pq/4/</a></p> |
6,606,891 | Opencv virtually camera rotating/translating for bird's eye view | <p>I've a calibrated camera where I exactly know the intrinsic and extrinsic data. Also the height of the camera is known. Now I want to virtually rotate the camera for getting a Bird's eye view, such that I can build the Homography matrix with the three rotation angles and the translation. </p>
<p>I know that 2 points can be transformed from one image to another via Homography as </p>
<p>x=K*(R-t*n/d)K^-1 * x' </p>
<p>there are a few things I'd like to know now:
if I want to bring back the image coordinate in ccs, I have to multiply it with K^-1, right? As Image coordinate I use (x',y',1) ? </p>
<p>Then I need to built a rotation matrix for rotating the ccs...but which convention should I use? And how do I know how to set up my WCS? </p>
<p>The next thing is the normal and the distance. Is it right just to take three points lying on the ground and compute the normal out of them? and is the distance then the camera height? </p>
<p>Also I'd like to know how I can change the height of the virtually looking bird view camera, such that I can say I want to see the ground plane from 3 meters height. How can I use the unit "meter" in the translation and homography Matrix? </p>
<p>So far for now, it would be great if someone could enlighten and help me. And please don't suggest generating the bird view with "getperspective", I ve already tried that but this way is not suitable for me. </p>
<p>Senna </p> | 6,667,784 | 2 | 1 | null | 2011-07-07 06:49:19.023 UTC | 9 | 2014-05-22 09:31:50.707 UTC | 2011-07-07 06:50:59.883 UTC | null | 21,234 | null | 832,997 | null | 1 | 7 | opencv|rotation|translation|homography | 16,362 | <p>That is the code i would advise (it's one of mine), to my mind it answers a lot of your questions,
If you want the distance, i would precise that it is in the Z matrix, the (4,3) coefficient.</p>
<p>Hope it will help you...</p>
<pre><code>Mat source=imread("Whatyouwant.jpg");
int alpha_=90., beta_=90., gamma_=90.;
int f_ = 500, dist_ = 500;
Mat destination;
string wndname1 = getFormatWindowName("Source: ");
string wndname2 = getFormatWindowName("WarpPerspective: ");
string tbarname1 = "Alpha";
string tbarname2 = "Beta";
string tbarname3 = "Gamma";
string tbarname4 = "f";
string tbarname5 = "Distance";
namedWindow(wndname1, 1);
namedWindow(wndname2, 1);
createTrackbar(tbarname1, wndname2, &alpha_, 180);
createTrackbar(tbarname2, wndname2, &beta_, 180);
createTrackbar(tbarname3, wndname2, &gamma_, 180);
createTrackbar(tbarname4, wndname2, &f_, 2000);
createTrackbar(tbarname5, wndname2, &dist_, 2000);
imshow(wndname1, source);
while(true) {
double f, dist;
double alpha, beta, gamma;
alpha = ((double)alpha_ - 90.)*PI/180;
beta = ((double)beta_ - 90.)*PI/180;
gamma = ((double)gamma_ - 90.)*PI/180;
f = (double) f_;
dist = (double) dist_;
Size taille = source.size();
double w = (double)taille.width, h = (double)taille.height;
// Projection 2D -> 3D matrix
Mat A1 = (Mat_<double>(4,3) <<
1, 0, -w/2,
0, 1, -h/2,
0, 0, 0,
0, 0, 1);
// Rotation matrices around the X,Y,Z axis
Mat RX = (Mat_<double>(4, 4) <<
1, 0, 0, 0,
0, cos(alpha), -sin(alpha), 0,
0, sin(alpha), cos(alpha), 0,
0, 0, 0, 1);
Mat RY = (Mat_<double>(4, 4) <<
cos(beta), 0, -sin(beta), 0,
0, 1, 0, 0,
sin(beta), 0, cos(beta), 0,
0, 0, 0, 1);
Mat RZ = (Mat_<double>(4, 4) <<
cos(gamma), -sin(gamma), 0, 0,
sin(gamma), cos(gamma), 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
// Composed rotation matrix with (RX,RY,RZ)
Mat R = RX * RY * RZ;
// Translation matrix on the Z axis change dist will change the height
Mat T = (Mat_<double>(4, 4) <<
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, dist,
0, 0, 0, 1);
// Camera Intrisecs matrix 3D -> 2D
Mat A2 = (Mat_<double>(3,4) <<
f, 0, w/2, 0,
0, f, h/2, 0,
0, 0, 1, 0);
// Final and overall transformation matrix
Mat transfo = A2 * (T * (R * A1));
// Apply matrix transformation
warpPerspective(source, destination, transfo, taille, INTER_CUBIC | WARP_INVERSE_MAP);
imshow(wndname2, destination);
waitKey(30);
}
</code></pre> |
7,208,645 | What does <| in this code mean? | <pre><code>function foo() {}
var bar = foo <| function() {};
</code></pre>
<p>This is the first time I've seen something like this. What does <code><|</code> mean?</p>
<p>Source: <a href="https://github.com/allenwb/ESnext-experiments/blob/master/ST80collections-exp1.js" rel="noreferrer">https://github.com/allenwb/ESnext-experiments/blob/master/ST80collections-exp1.js</a></p> | 7,208,789 | 3 | 12 | null | 2011-08-26 17:49:22.957 UTC | 3 | 2012-09-05 14:42:10.19 UTC | 2012-09-05 14:42:10.19 UTC | null | 912,144 | null | 701,092 | null | 1 | 28 | javascript|syntax|operators | 1,518 | <p>Now that you have posted the link to the source, you can see in the comments at the top of the file exactly what it does (<a href="https://github.com/allenwb/ESnext-experiments/blob/master/ST80collections-exp1.js#L36">line 36</a>):</p>
<blockquote>
<p>the <| operator -- defines the [[Prototype]] of a literal...</p>
<p>For these examples <| used with a function expression sets the
[[Prototype]] of the object created as the value of the function's
"prototype" property to the value of the "prototype" property of the
the LHS object. This is in addition to setting the [[Prototype]] of
the function object itself. In other words, it builds sets the
[[Prototype]] of both the function and of function.prototype to
potentially different values.</p>
</blockquote>
<p><strong>Update:</strong> I've just remembered this question as I came across the <a href="http://wiki.ecmascript.org/doku.php?id=harmony%3aproto_operator">full ECMAScript Harmony proposal for this "literal [[Prototype]] operator"</a>. There is a lot more information in there than in the quote above, so it's worth a read.</p> |
7,290,857 | Using jQuery UI icons | <p>jQuery UI comes with handy icons in a sprite image; see the <a href="http://jqueryui.com/themeroller/">themeroller</a>.</p>
<p>I have an <code>input</code> element for which I want the clock icon (with class <code>.ui-icon-clock</code>) as background image. How do I have a background icon to an <code>input</code>?</p> | 7,290,894 | 3 | 0 | null | 2011-09-03 02:54:56.467 UTC | 5 | 2013-04-10 23:07:43.873 UTC | 2013-04-10 23:07:43.873 UTC | null | 707,381 | null | 707,381 | null | 1 | 39 | jquery|jquery-ui | 55,432 | <p>just use an empty span and add the jQuery UI classes. </p>
<pre><code><span class="ui-icon ui-icon-clock" style="display:inline-block"></span><input type="text" />
</code></pre>
<p>You have to override the display style to make it inline-block rather than block otherwise the input will be pushed to the next line. </p>
<p>Other than that, I'm not sure exactly what you're after when you say make the clock the background image. </p> |
7,062,383 | Putting a image inside a input box | <p>Similar to <a href="https://stackoverflow.com/questions/917610/put-icon-inside-input-element-in-a-form">Put icon inside input element in a form</a></p>
<p>But how to I get the icon inside and on the <em>right side</em> of the box?</p> | 7,062,417 | 4 | 1 | null | 2011-08-15 06:57:26.033 UTC | 6 | 2017-03-27 16:11:56.167 UTC | 2017-05-23 11:54:26.267 UTC | null | -1 | null | 286,289 | null | 1 | 15 | css | 43,783 | <p>Try this:</p>
<pre><code>background: url(images/icon.png) no-repeat right center;
</code></pre>
<p>The explanation for this CSS is as follows:</p>
<p>background: [url to image] [don't repeat] [horizontal position] [vertical position]</p> |
7,064,269 | The method getJspApplicationContext(ServletContext) is undefined for the type JspFactory | <p>I am working on a JSP project that uses Apache Tomcat 7.</p>
<p>When running the project on its loading <em>index.html</em> it's OK, but when trying to navigate to another page it's showing the error:</p>
<blockquote>
<p>The method getJspApplicationContext(ServletContext) is undefined for the type JspFactory</p>
</blockquote>
<p>Please provide me a solution to get rid of this.</p> | 7,064,839 | 4 | 0 | null | 2011-08-15 11:12:04.68 UTC | 11 | 2021-01-31 17:12:29.543 UTC | 2012-12-20 10:02:59.003 UTC | null | 447,356 | null | 605,343 | null | 1 | 32 | jsp|tomcat | 57,919 | <p>Get rid of any servletcontainer-specific libraries such as <code>jsp-api.jar</code> in your <code>/WEB-INF/lib</code> folder. This exception indicates that you've put servletcontainer-specific libraries of a container which supports only Servlet 2.4 / JSP 2.0 or older in there (the <code>getJspApplicationContext()</code> method was introduced in Servlet 2.5 / JSP 2.1). This is a major mistake. Those libraries don't belong in the webapp's classpath.</p>
<p>Perhaps you did this to overcome project compilation errors, which is indeed a pretty common beginner's mistake. This should have been solved differently, you should refer the target runtime in your project, not copy some libraries of an arbitrary servletcontainer make/version into your project. It would make your project incompatible with servletcontainers of a different make and/or version.</p>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/4076601/how-do-i-import-the-javax-servlet-api-in-my-eclipse-project">How do I import the javax.servlet API in my Eclipse project?</a></li>
</ul> |
7,556,045 | How to map function address to function in *.so files | <p>backtrace function give set of backtrace how to map it with function name/file name/line number?</p>
<pre><code>for ex:-
backtrace() returned 8 addresses
./libtst.so(myfunc5+0x2b) [0xb7767767]
./libtst.so(fun4+0x4a) [0xb7767831]
./libtst.so(fun3+0x48) [0xb776787f]
./libtst.so(fun2+0x35) [0xb77678ba]
./libtst.so(fun1+0x35) [0xb77678f5]
./a.out() [0x80485b9]
/lib/libc.so.6(__libc_start_main+0xe5) [0xb75e9be5]
./a.out() [0x80484f1]
</code></pre>
<p>From the above stack how can I get the file name and line number?
I did following things, but no luck. Correct me if I am wrong :)</p>
<pre><code>for ex:-
./libtst.so(fun2+0x35) [0xb77dc887]
0xb77dc887(fun2 addr+offset)-0xb77b6000 (lib starting addr) = 0x26887 (result)
result is no way related to function in nm output.
I used addr2line command:-
addr2line -f -e libtst.so 0xb77dc887
??
??:0
</code></pre>
<p>So, how can I resolve either at runtime or post runtime?
Thanks in advance...</p>
<pre><code>nm:-
00000574 T _init
00000680 t __do_global_dtors_aux
00000700 t frame_dummy
00000737 t __i686.get_pc_thunk.bx
0000073c T myfunc5
000007e7 T fun4
00000837 T fun3
00000885 T fun2
000008c0 T fun1
00000900 t __do_global_ctors_aux
00000938 T _fini
000009b4 r __FRAME_END__
00001efc d __CTOR_LIST__
00001f00 d __CTOR_END__
00001f04 d __DTOR_LIST__
00001f08 d __DTOR_END__
00001f0c d __JCR_END__
00001f0c d __JCR_LIST__
00001f10 a _DYNAMIC
00001ff4 a _GLOBAL_OFFSET_TABLE_
00002030 d __dso_handle
00002034 A __bss_start
00002034 A _edata
00002034 b completed.5773
00002038 b dtor_idx.5775
0000203c B funptr
00002040 A _end
U backtrace@@GLIBC_2.1
U backtrace_symbols@@GLIBC_2.1
U free@@GLIBC_2.0
U __isoc99_scanf@@GLIBC_2.7
U perror@@GLIBC_2.0
U printf@@GLIBC_2.0
U puts@@GLIBC_2.0
w __cxa_finalize@@GLIBC_2.1.3
w __gmon_start__
w _Jv_RegisterClasses
pmap:-
START SIZE RSS PSS DIRTY SWAP PERM MAPPING
08048000 4K 4K 4K 0K 0K r-xp /home/test/libtofun/a.out
08049000 4K 4K 4K 4K 0K r--p /home/test/libtofun/a.out
0804a000 4K 4K 4K 4K 0K rw-p /home/test/libtofun/a.out
...
b7767000 4K 4K 4K 0K 0K r-xp /home/test/libtofun/libtst.so
b7768000 4K 4K 4K 4K 0K r--p /home/test/libtofun/libtst.so
b7769000 4K 4K 4K 4K 0K rw-p /home/test/libtofun/libtst.so
....
Total: 1688K 376K 82K 72K 0K
</code></pre>
<p>128K writable-private, 1560K readonly-private, 0K shared, and 376K referenced</p>
<pre><code>libtst.c:-
void myfunc5(void){
int j, nptrs;
#define SIZE 100
void *buffer[100];
char **strings;
nptrs = backtrace(buffer, SIZE);
printf("backtrace() returned %d addresses\n", nptrs);
strings = backtrace_symbols(buffer, nptrs);
if (strings == NULL) {
perror("backtrace_symbols");
}
for (j = 0; j < nptrs; j++)
printf("%s\n", strings[j]);
free(strings);
}
void fun4(){
char ip;
char *fun = "fun4\0";
printf("Fun name %s\n",fun);
scanf("%c",&ip);
myfunc5();
}
void fun3(){
char *fun = "fun3\0";
printf("Fun name %s\n",fun);
funptr = fun4;
funptr();
}
void fun2(){
char *fun = "fun2\0";
printf("Fun name %s\n",fun);
fun3();
}
void fun1(){
char *fun = "fun1\0";
printf("Fun name %s\n",fun);
fun2();
}
main.c:-
int main(){
char ip;
funptr = &fun1;
scanf("%c",&ip);
funptr();
return 0;
}
</code></pre>
<p>Let me know if need more information...</p> | 7,557,756 | 4 | 3 | null | 2011-09-26 13:45:30.177 UTC | 20 | 2021-05-10 10:13:50.06 UTC | 2018-02-01 13:53:17.76 UTC | null | 72,178 | null | 406,001 | null | 1 | 44 | c|debugging|shared-libraries|stack-trace | 43,795 | <p>Try giving the offset to addr2line, along with the section name. Like this:</p>
<p><code>addr2line -j .text -e libtst.so 0x26887</code></p>
<p>Edit: By the way, if it wasn't clear, the <code>0x26887</code> comes from what you provided:</p>
<blockquote>
<p><code>0xb77dc887(fun2 addr+offset)-0xb77b6000 (lib starting addr) = 0x26887 (result)</code></p>
</blockquote> |
21,674,222 | Extract characters after certain other characters Excel | <p>I have a list of cells that looks more or less like this:</p>
<ul>
<li>ARB:d.p.1-4-12</li>
<li>ANT:d.p.1-12-1</li>
<li>D:d.p.1-1-1</li>
<li>ONN:d.p.4-2-12</li>
</ul>
<p>I'm trying to figure out how I can extract certain key elements from these strings.
If we take the first entry as example, this is what I want to extract and display in another cell:</p>
<pre><code>ARB d 1
</code></pre>
<p>I want all characters before ":", then the first character after ":" and the first number (or ONE character before the first "-").</p>
<p>I've played around with TRIM, LEFT/RIGHT and FIND - but can't figure out how to get only ONE character after/before a certain character. This is what I've tried, but dont know how to limit the output to only ONE character:</p>
<pre><code>TRIM(LEFT(E5;FIND(":";E5)-1))
</code></pre>
<p>Thanks in advance for any pointers or tips :-)</p>
<p><strong>Update, got it working:</strong></p>
<p>I ended up using this code, which was tweaked after jiggle's suggestion.</p>
<pre><code>=TRIM(LEFT(E2;FIND(":";E2)-1)) & RIGHT(MID(E2;FIND(":";E2);2);1) & RIGHT(MID(E2;FIND("p.";E2);3);1)
</code></pre>
<p>This gave me the following output:
ARBd1</p>
<p>Now I just need to add some separators and im all good to go. Thanks for all the help.</p> | 21,674,435 | 1 | 2 | null | 2014-02-10 10:10:12.047 UTC | 1 | 2017-08-21 08:49:10.387 UTC | 2014-02-10 12:28:21.02 UTC | null | 2,692,167 | null | 2,692,167 | null | 1 | 2 | excel | 65,174 | <p>Find the first part : <code>=LEFT(E5,FIND(":",E5)-1)</code></p>
<p>Find the second part: <code>=MID(E5,FIND(":",E5)+1,1)</code></p>
<p>= MID ( Text , Start_num , Num_chars )</p>
<p>so here we're starting at the character after the ":", by adding 1 to the FIND</p>
<p>and taking 1 character, at the end</p>
<p>Find the last part: <code>=MID(E5,FIND("-",E5)-1,1)</code></p>
<p>doing a similar thing to the second part, but now starting at the character before the "-" by subtracting 1 from where we found it, and again taking just 1 character</p>
<p>To combine them all together, just use the concatenation character "&" and space:</p>
<p><code>=LEFT(E5,FIND(":",E5)-1)&" "&MID(E5,FIND(":",E5)+1,1) & " " & MID(E5,FIND("-",E5)-1,1)</code></p>
<p>EDITED to replace commas with semi colons (for different cultures):</p>
<pre><code>=LEFT(E5;FIND(":";E5)-1)&" "&MID(E5;FIND(":";E5)+1;1) & " " & MID(E5;FIND("-";E5)-1;1)
</code></pre> |
2,114,186 | Core Data NSFetchedResultsController - Total number of records returned | <p>I'm using an NSFetchedResultsController in an iPhone app, and am wondering if there is some easy way of getting the total number of rows returned in all sections.</p>
<p>Instead of getting the [[fetchedResultsController sections] count] and then looping through each section to get its count, can it be done in one line?</p>
<p>Thanks!</p> | 2,114,200 | 4 | 0 | null | 2010-01-22 00:51:15.907 UTC | 3 | 2018-08-15 16:38:36.88 UTC | null | null | null | null | 256,324 | null | 1 | 41 | iphone|core-data|nsfetchedresultscontroller | 19,167 | <p>This line returns the total number of fetched objects:</p>
<pre><code>[fetchedResultsController.fetchedObjects count]
</code></pre> |
1,439,364 | What are the WCF Service Reference .datasource files? | <p>What are the .datasource files that are automatically generated by "Create Service Reference" in Visual Studio? The comment in the file is this:</p>
<blockquote>
<p>This file is automatically generated
by Visual Studio .Net. It is
used to store generic object data source configuration information.<br>
Renaming the file extension or editing the content of this file may<br>
cause the file to be unrecognizable by the program.</p>
</blockquote>
<p>However, it sounds like these files are optional, so I'm wondering what they are used for. I'm also wondering if it is truly safe to delete them, since they often cause path length problems on XP.</p>
<p><a href="http://www.eggheadcafe.com/conversation.aspx?messageid=34104031&threadid=34104026" rel="noreferrer">http://www.eggheadcafe.com/conversation.aspx?messageid=34104031&threadid=34104026</a></p>
<p>Can anyone point me to some official MS documentation on these files?</p> | 1,439,916 | 4 | 0 | null | 2009-09-17 14:50:41.74 UTC | 9 | 2017-06-02 07:16:13.273 UTC | 2012-04-13 06:59:36.313 UTC | null | 40,961 | null | 60,096 | null | 1 | 93 | wcf|file|datasource|service-reference | 33,899 | <p>As far as I remember, they are just generated so that you can use the data contracts used in the service as object data sources for data binding against UI controls.</p> |
52,523,816 | Confusing templates in C++17 example of std::visit | <p>When looking at <code>std::visit()</code> page in cppreference,
<a href="https://en.cppreference.com/w/cpp/utility/variant/visit" rel="noreferrer">https://en.cppreference.com/w/cpp/utility/variant/visit</a>, I encountered the code I can't make sense of... </p>
<p>Here's the abbreviated version:</p>
<pre><code>#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...)->overloaded<Ts...>;
int main() {
std::vector<std::variant<int,long,double,std::string>> vec = { 10, 15l, 1.5, "hello" };
for (auto& v : vec) {
std::visit(overloaded{
[](auto arg) { std::cout << arg << ' '; },
[](double arg) { std::cout << std::fixed << arg << ' '; },
[](const std::string& arg) { std::cout << std::quoted(arg) << ' '; },
}, v);
}
}
</code></pre>
<p>What do the two lines declaring <code>overloaded</code>, just above <code>int main()</code>, mean? </p>
<p>Thank you for explaining!</p>
<p><strong>2019 Addition</strong><br>
After the two gentlemen below provided detailed explanations (thank you so much!), I've stumbled upon the same code in the very fine book <em>C++17 in Detail -
Learn the Exciting Features of The New C++ Standard!</em> by Bartłomiej Filipek. Such a well written book!</p> | 52,523,917 | 2 | 5 | null | 2018-09-26 18:10:51.383 UTC | 12 | 2019-08-13 19:49:12.66 UTC | 2019-08-13 19:49:12.66 UTC | null | 6,199,585 | null | 6,199,585 | null | 1 | 38 | c++|lambda|c++17|variadic-templates|generic-lambda | 3,112 | <blockquote>
<p>What are the two lines declaring overloaded, just above int main(), mean? </p>
</blockquote>
<p>The first one</p>
<pre><code>template<class... Ts>
struct overloaded : Ts...
{ using Ts::operator()...; };
</code></pre>
<p>is a classic class/struct declaration/definition/implementation. Valid from C++11 (because use variadic templates).</p>
<p>In this case, <code>overloaded</code> inherits from all template parameters and enables (<code>using</code> row) all inherited <code>operator()</code>. This is an example of <a href="https://isocpp.org/blog/tag/crtp/P100" rel="noreferrer">Variadic CRTP</a>.</p>
<p>Unfortunately the variadic <code>using</code> is available only starting from C++17. </p>
<p>The second one</p>
<pre><code>template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
</code></pre>
<p>is a "deduction guide" (see <a href="https://en.cppreference.com/w/cpp/language/class_template_argument_deduction" rel="noreferrer">this page</a> for more details) and it's a new C++17 feature.</p>
<p>In your case, the deduction guide says that when you write something as</p>
<pre><code>auto ov = overloaded{ arg1, arg2, arg3, arg4 };
</code></pre>
<p>or also</p>
<pre><code>overloaded ov{ arg1, args, arg3, arg4 };
</code></pre>
<p><code>ov</code> becomes an <code>overloaded<decltype(arg1), decltype(arg2), decltype(arg3), decltype(arg4)></code></p>
<p>This permits you to write something as</p>
<pre><code>overloaded
{
[](auto arg) { std::cout << arg << ' '; },
[](double arg) { std::cout << std::fixed << arg << ' '; },
[](const std::string& arg) { std::cout << std::quoted(arg) << ' '; },
}
</code></pre>
<p>that in C++14 was </p>
<pre><code>auto l1 = [](auto arg) { std::cout << arg << ' '; };
auto l2 = [](double arg) { std::cout << std::fixed << arg << ' '; };
auto l3 = [](const std::string& arg) { std::cout << std::quoted(arg) << ' '; }
overloaded<decltype(l1), decltype(l2), decltype(l3)> ov{l1, l2, l3};
</code></pre>
<p><strong>-- EDIT --</strong></p>
<p>As pointed by Nemo (thanks!) in the example code in your question there is another interesting new C++17 feature: the aggregate initialization of base classes.</p>
<p>I mean... when you write</p>
<pre><code>overloaded
{
[](auto arg) { std::cout << arg << ' '; },
[](double arg) { std::cout << std::fixed << arg << ' '; },
[](const std::string& arg) { std::cout << std::quoted(arg) << ' '; }
}
</code></pre>
<p>you're passing three lambda functions to initialize three base classes of <code>overloaded</code>.</p>
<p>Before C++17, you could do this only if you wrote an explicit constructor to do it. Starting from C++17, it works automatically.</p>
<p>At this point, it seems to me that it can be useful to show a simplified full example of your <code>overloaded</code> in C++17 and a corresponding C++14 example.</p>
<p>I propose the following C++17 program</p>
<pre><code>#include <iostream>
template <typename ... Ts>
struct overloaded : public Ts ...
{ using Ts::operator()...; };
template <typename ... Ts> overloaded(Ts...) -> overloaded<Ts...>;
int main ()
{
overloaded ov
{
[](auto arg) { std::cout << "generic: " << arg << std::endl; },
[](double arg) { std::cout << "double: " << arg << std::endl; },
[](long arg) { std::cout << "long: " << arg << std::endl; }
};
ov(2.1);
ov(3l);
ov("foo");
}
</code></pre>
<p>and the best C++14 alternative (following also the bolov's suggestion of a "make" function and his recursive <code>overloaded</code> example) that I can imagine.</p>
<pre><code>#include <iostream>
template <typename ...>
struct overloaded;
template <typename T0>
struct overloaded<T0> : public T0
{
template <typename U0>
overloaded (U0 && u0) : T0 { std::forward<U0>(u0) }
{ }
};
template <typename T0, typename ... Ts>
struct overloaded<T0, Ts...> : public T0, public overloaded<Ts ...>
{
using T0::operator();
using overloaded<Ts...>::operator();
template <typename U0, typename ... Us>
overloaded (U0 && u0, Us && ... us)
: T0{std::forward<U0>(u0)}, overloaded<Ts...> { std::forward<Us>(us)... }
{ }
};
template <typename ... Ts>
auto makeOverloaded (Ts && ... ts)
{
return overloaded<Ts...>{std::forward<Ts>(ts)...};
}
int main ()
{
auto ov
{
makeOverloaded
(
[](auto arg) { std::cout << "generic: " << arg << std::endl; },
[](double arg) { std::cout << "double: " << arg << std::endl; },
[](long arg) { std::cout << "long: " << arg << std::endl; }
)
};
ov(2.1);
ov(3l);
ov("foo");
}
</code></pre>
<p>I suppose that it's matter of opinion, but it seems to me that the C++17 version is a lot simpler and more elegant.</p> |
10,661,482 | Remove a specific word from a string | <p>I'm trying to remove a specific word from a certain string using the function <code>replace()</code> or <code>replaceAll()</code> but these remove all the occurrences of this word even if it's part of another word!</p>
<p><em>Example:</em></p>
<pre><code>String content = "is not like is, but mistakes are common";
content = content.replace("is", "");
</code></pre>
<p><strong>output:</strong> <code>"not like , but mtakes are common"</code></p>
<p><strong>desired output:</strong> <code>"not like , but mistakes are common"</code></p>
<p>How can I substitute only whole words from a string?</p> | 10,661,497 | 4 | 2 | null | 2012-05-19 01:01:25.91 UTC | 5 | 2020-06-04 20:58:31.303 UTC | 2012-05-20 02:59:44.847 UTC | null | 815,632 | null | 1,404,514 | null | 1 | 25 | java|replace | 93,063 | <p>What the heck,</p>
<pre><code>String regex = "\\s*\\bis\\b\\s*";
content = content.replaceAll(regex, "");
</code></pre>
<p>Remember you need to use <code>replaceAll(...)</code> to use regular expressions, not <code>replace(...)</code></p>
<ul>
<li><code>\\b</code> gives you the word boundaries</li>
<li><code>\\s*</code> sops up any white space on either side of the word being removed (if you want to remove this too).</li>
</ul> |
10,707,626 | Is there a command in Vim/Vi to move the cursor to the end of a search highlight? | <p>Are there any commands in Vim/Vi to move within a selected search segment? </p>
<p>For instance, if I search for a word, are there any commands to motion the cursor to the end of the highlighted segment? Say I have a word, "FishTaco" and I want to search for all instances of "Fish" and insert something after it. I know I could do a global replace, but what if I want to only make the change in a couple non-sequential instances?</p>
<p>I could see where it would be convenient to be able to motion the cursor to the end of the current highlighted segment to perform an action.</p> | 10,707,807 | 6 | 2 | null | 2012-05-22 18:10:31.84 UTC | 25 | 2015-06-27 14:21:56.81 UTC | null | null | null | null | 20,133 | null | 1 | 97 | vim|vi | 13,868 | <p>You can do it with this:</p>
<p><code>/Fish/e</code></p>
<p>The <code>/e</code> at the end lands your cursor at the end of the search region (instead of the first character by default.</p> |
10,487,292 | Position absolute but relative to parent | <p>I have two divs inside another div, and I want to position one child div to the top right of the parent div, and the other child div to the bottom of the parent div using css. Ie, I want to use absolute positioning with the two child divs, but position them relative to the parent div rather than the page. How can I do this? </p>
<p>Sample html:</p>
<pre><code><div id="father">
<div id="son1"></div>
<div id="son2"></div>
</div>
</code></pre> | 10,487,329 | 5 | 2 | null | 2012-05-07 18:41:54.5 UTC | 145 | 2021-06-24 09:02:28.467 UTC | 2013-07-23 22:49:29.347 UTC | null | 881,229 | null | 1,056,852 | null | 1 | 665 | html|css | 523,487 | <pre><code>#father {
position: relative;
}
#son1 {
position: absolute;
top: 0;
}
#son2 {
position: absolute;
bottom: 0;
}
</code></pre>
<p>This works because <code>position: absolute</code> means something like "use <code>top</code>, <code>right</code>, <code>bottom</code>, <code>left</code> to position yourself in relation to the nearest ancestor who has <code>position: absolute</code> or <code>position: relative</code>."</p>
<p>So we make <code>#father</code> have <code>position: relative</code>, and the children have <code>position: absolute</code>, then use <code>top</code> and <code>bottom</code> to position the children.</p> |
28,422,551 | Adding a background image to a single table cell | <p>Hello I was wondering if it's possible to add a background image to a single table cell? If you look at the image I have below I would like the green background image I have to be in those cells.</p>
<p><img src="https://i.stack.imgur.com/k9CNE.jpg" alt="example image"></p>
<p>My code for the table is,</p>
<pre><code><table class="TFtable" style="height: 448px;" width="1007">
<tbody>
<tr>
<td style="background-color: #000000;">
<p><span style="font-size: 200%; color: #749d36;"> Pricing</span></p>
<p><span style="font-size: 200%;"> Structure</span></p>
</td>
<td style="text-align: center;">
<p><span style="font-size: medium;">Professional</span></p>
<p><span style="font-size: medium;">Resume</span></p>
<br /><br />
<p><span style="font-size: xx-large; color: #749d36;">$199</span></p>
</td>
<td style="text-align: center;">
<p>Managerial</p>
<p>Resume</p>
<p>$299</p>
</td>
<td style="text-align: center;">
<p><span style="font-size: medium;">Executive</span></p>
<p><span style="font-size: medium;">Resume</span></p>
<br /><br />
<p><span style="font-size: xx-large; color: #749d36;">$399</span></p>
</td>
<td style="text-align: center;">
<p>C-Suite</p>
<p>Resume</p>
<p>$499</p>
</td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: medium;">Resume Specs</span></td>
<td style="text-align: center;"><span style="font-size: small;">2-3 pg resume</span></td>
<td style="text-align: center;">4-5 pg resume</td>
<td style="text-align: center;">
<p>+ cover sheet and</p>
<p>graphics</p>
</td>
<td style="text-align: center;">+ standalone bio pg</td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: medium;">Phone Interview</span></td>
<td style="text-align: center;"><img src="images/greentick.png" alt="" width="24" height="24" /></td>
<td style="text-align: center;"><img src="images/greentick.png" alt="" width="24" height="24" /></td>
<td style="text-align: center;"><img src="images/greentick.png" alt="" width="24" height="24" /></td>
<td style="text-align: center;">
<p><img src="images/greentick.png" alt="" width="24" height="24" /></p>
</td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: medium;">Draft To Approve</span></td>
<td style="text-align: center;"><img src="images/greentick.png" alt="" width="24" height="24" /></td>
<td style="text-align: center;"><img src="images/greentick.png" alt="" width="24" height="24" /></td>
<td style="text-align: center;"><img src="images/greentick.png" alt="" width="24" height="24" /></td>
<td style="text-align: center;">
<p><img src="images/greentick.png" alt="" width="24" height="24" /></p>
</td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: medium;">Template Options</span></td>
<td style="text-align: center;"> </td>
<td style="text-align: center;"> </td>
<td style="text-align: center; vertical-align: middle;"><br /><img src="images/greentick.png" alt="" width="24" height="24" /></td>
<td style="text-align: center;"><img src="images/greentick.png" alt="" width="24" height="24" /></td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: medium;">Extras</span></td>
<td style="text-align: center;"> </td>
<td style="text-align: center;"> </td>
<td style="text-align: center;">
<p>+ free LinkedIn</p>
<p>profile</p>
</td>
<td style="text-align: center;">
<p>+ free LinkedIn</p>
<p>profile</p>
</td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: medium;">Delivery</span></td>
<td style="text-align: center;">
<p>.docx &amp; .pdf</p>
<p>versions</p>
</td>
<td style="text-align: center;">
<p>.docx &amp; .pdf</p>
<p>versions</p>
</td>
<td style="text-align: center;">
<p>.docx &amp; .pdf</p>
<p>versions</p>
</td>
<td style="text-align: center;">
<p>.docx &amp; .pdf</p>
<p>versions</p>
</td>
</tr>
<tr>
<td style="text-align: center;"><span style="font-size: medium;">Cover Letter</span></td>
<td style="text-align: center;"><br />+ $50<br /><br /></td>
<td style="text-align: center;"><br />+ $50<br /><br /></td>
<td style="text-align: center;"><br />+ $50<br /><br /></td>
<td style="text-align: center;"><br />+ $50<br /><br /></td>
</tr>
<tr>
<td style="background-color: #000000; text-align: center;">
<p>If you're not sure where</p>
<p>your job would fit, please</p>
<p>get in touch to discuss </p>
<p>your requirements.</p>
</td>
<td style="text-align: center;">
<p>Vocations (such as</p>
<p>Teaching &amp; Nursing)</p>
<p>Early Career Professionals</p>
</td>
<td style="text-align: center;">
<p>Managers and Senior</p>
<p>Professionals (Lawyers,</p>
<p>Medical Doctors), BDMs,</p>
<p>Consultants...</p>
</td>
<td style="text-align: center;">
<p>Senior Managers and Exec</p>
<p>Directors (Operations</p>
<p>Managers, GMs, Heads of</p>
<p>Department</p>
</td>
<td style="text-align: center;">
<p>CEOs, CFOs, COOs, CIOs,</p>
<p>Managing Directors, Board</p>
<p>Members &amp; Non-Execs,</p>
<p>Practice Directors &amp; Principals</p>
</td>
</tr>
</tbody>
</table>
<p> </p>
</code></pre> | 28,422,610 | 3 | 2 | null | 2015-02-10 01:24:35.58 UTC | 1 | 2019-05-22 08:12:37.35 UTC | 2015-02-10 01:25:01.67 UTC | null | 3,285,730 | null | 4,336,095 | null | 1 | 5 | html|css|joomla | 38,298 | <p>This can be achieved using CSS:</p>
<p>First you will need to create an ID for the table cell that you wish to have an image as the background.</p>
<p>After this, you will need to do this in CSS:</p>
<pre><code>#tableCellWithBackground {
background-image: url("<The location of your image in your webspace, or the url of the image.");
}
</code></pre>
<p>This should work, tell me if there is a bug or something wrong.</p> |
55,020,041 | react hooks useEffect() cleanup for only componentWillUnmount? | <p>Let me explain the result of this code for asking my issue easily.</p>
<pre><code>const ForExample = () => {
const [name, setName] = useState('');
const [username, setUsername] = useState('');
useEffect(() => {
console.log('effect');
console.log({
name,
username
});
return () => {
console.log('cleaned up');
console.log({
name,
username
});
};
}, [username]);
const handleName = e => {
const { value } = e.target;
setName(value);
};
const handleUsername = e => {
const { value } = e.target;
setUsername(value);
};
return (
<div>
<div>
<input value={name} onChange={handleName} />
<input value={username} onChange={handleUsername} />
</div>
<div>
<div>
<span>{name}</span>
</div>
<div>
<span>{username}</span>
</div>
</div>
</div>
);
};
</code></pre>
<p>When the <code>ForExample component</code> mounts, 'effect' will be logged. This is related to the <code>componentDidMount()</code>.</p>
<p>And whenever I change name input, both 'effect' and 'cleaned up' will be logged. Vice versa, no message will be logged whenever I change username input since I added <code>[username]</code> to the second parameter of <code>useEffect()</code>. This is related to the <code>componentDidUpdate()</code></p>
<p>Lastly, when the <code>ForExample component</code> unmounts, 'cleaned up' will be logged. This is related to the <code>componentWillUnmount()</code>.</p>
<p>We all know that.</p>
<p>To sum, 'cleaned up' is invoked whenever the component is being re-rendered(includes unmount)</p>
<p>If I want to make this component to log 'cleaned up' for only the moment when it is unmount, I just have to change the second parameter of <code>useEffect()</code> to <code>[]</code>.</p>
<p>But If I change <code>[username]</code> to <code>[]</code>, <code>ForExample component</code> no longer implements the <code>componentDidUpdate()</code> for name input.</p>
<p>What I want to do is that, to make the component supports both <code>componentDidUpdate()</code> only for name input and <code>componentWillUnmount()</code>. (logging 'cleaned up' for only the moment when the component is being unmounted)</p> | 55,020,668 | 10 | 9 | null | 2019-03-06 09:49:28.26 UTC | 58 | 2022-09-03 17:28:09.247 UTC | 2019-03-06 10:20:47.43 UTC | null | 10,851,011 | null | 10,851,011 | null | 1 | 168 | reactjs|react-hooks | 251,270 | <p>Since the cleanup is not dependent on the <code>username</code>, you could put the cleanup in a separate <code>useEffect</code> that is given an empty array as second argument.</p>
<p><strong>Example</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { useState, useEffect } = React;
const ForExample = () => {
const [name, setName] = useState("");
const [username, setUsername] = useState("");
useEffect(
() => {
console.log("effect");
},
[username]
);
useEffect(() => {
return () => {
console.log("cleaned up");
};
}, []);
const handleName = e => {
const { value } = e.target;
setName(value);
};
const handleUsername = e => {
const { value } = e.target;
setUsername(value);
};
return (
<div>
<div>
<input value={name} onChange={handleName} />
<input value={username} onChange={handleUsername} />
</div>
<div>
<div>
<span>{name}</span>
</div>
<div>
<span>{username}</span>
</div>
</div>
</div>
);
};
function App() {
const [shouldRender, setShouldRender] = useState(true);
useEffect(() => {
setTimeout(() => {
setShouldRender(false);
}, 5000);
}, []);
return shouldRender ? <ForExample /> : null;
}
ReactDOM.render(<App />, document.getElementById("root"));</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div></code></pre>
</div>
</div>
</p> |
26,368,883 | How to stop VBA macro automatically? | <p>I know you can manually stop a running VBA macro with <kbd>Ctrl</kbd>+<kbd>Break</kbd>, but is there any way to have the code stop automatically if a certain condition is met? <code>exit function</code> / <code>exit sub</code> are not working, because they are only terminating the method they are called within.</p>
<p>For example,</p>
<pre><code>sub a
call b
msgbox "a complete"
end sub
sub b
call c
msgbox "b complete" 'this msgbox will still show after the `exit sub` in 'c'
end sub
sub c
msgbox "entering c"
exit sub 'this will only `exit sub` 'c', but not 'a' or 'b'
msgbox "exiting c"
end sub
'OUTPUT:
'entering c
'b complete
'a complete
</code></pre>
<p>I suppose I could turn these <code>sub</code>'s into <code>function</code>'s and utilize return codes to know if the method executed successfully, but is there a simpler way to do this?</p> | 26,369,009 | 3 | 2 | null | 2014-10-14 19:33:39.047 UTC | 2 | 2019-03-14 04:53:37.187 UTC | 2016-12-05 01:48:44.43 UTC | null | 3,739,391 | null | 3,739,391 | null | 1 | 6 | vba|excel|error-handling | 61,984 | <p>You can raise your own user-defined error with <code>err.raise</code>. This is similar to your example, but a little more powerful in that it is an actual error that will halt code execution, even if it's applied to a nested call.</p>
<p>For example,</p>
<pre><code>sub a
on error goto exitCode
call b
msgbox "a complete"
exit sub 'you need this to prevent the error handling code from always running
exitCode:
msgbox "code is exiting..."
'clean up code here
end sub
sub b
call c
msgbox "b complete"
end sub
sub c
msgbox "entering c"
err.raise 555, "foo", "an error occurred"
msgbox "exiting c"
end sub
'OUTPUT:
'entering c
'code is exiting...
</code></pre>
<p>The <code>err.raise</code> line will send the control to the <code>exitCode:</code> label even though it was called outside of <code>a</code>. You could use any conditions to test if this custom error should be thrown.</p>
<p>More on the <code>err</code> object and VBA error handling- </p>
<p><a href="https://msdn.microsoft.com/en-us/library/ka13cy19(v=vs.90).aspx" rel="nofollow noreferrer">https://msdn.microsoft.com/en-us/library/ka13cy19(v=vs.90).aspx</a></p>
<p><a href="http://www.cpearson.com/excel/errorhandling.htm" rel="nofollow noreferrer">http://www.cpearson.com/excel/errorhandling.htm</a></p> |
7,121,053 | How to enable zoom controls and pinch zoom in a WebView? | <p>The default Browser app for Android shows zoom controls when you're scrolling and also allows for pinch zooming. How can I enable this feature for my own Webview?</p>
<p>I've tried: </p>
<pre><code>webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);
</code></pre>
<p>but neither of the features get enabled as a result. Btw I've set a <code>WebChromeClient</code> and a <code>WebViewClient</code> for the Webview if that makes a difference. </p>
<p>Thanks!</p> | 7,172,165 | 6 | 0 | null | 2011-08-19 11:44:59.13 UTC | 19 | 2019-06-14 07:16:56.937 UTC | 2011-12-13 13:08:08.687 UTC | null | 840,532 | null | 666,014 | null | 1 | 148 | android|webview | 120,101 | <p>Strange. Inside OnCreate method, I'm using</p>
<pre><code>webView.getSettings().setBuiltInZoomControls(true);
</code></pre>
<p>And it's working fine here.
Anything particular in your webview ?</p> |
7,578,055 | How can I create custom SEO-friendly URLs in OpenCart? | <p>How can you customize system URLs in OpenCart? For example, I would like <a href="http://example.com/index.php?route=checkout/cart">http://example.com/index.php?route=checkout/cart</a> to be displayed as <a href="http://example.com/cart">http://example.com/cart</a></p>
<p>I know OpenCart provides SEO URLs for products, categories, manufacturers and information pages, but it doesn't look like there is anything built-in (at least prior to version 1.5.0) for anything else.</p> | 7,578,088 | 8 | 1 | null | 2011-09-28 03:44:36.777 UTC | 21 | 2019-03-08 05:30:36.97 UTC | 2011-10-05 21:45:38.95 UTC | null | 961,455 | null | 961,455 | null | 1 | 26 | php|.htaccess|seo|opencart | 57,917 | <p>It turns out this can be done with a relatively simple change to a single file. No .htaccess rewrite rules, simply patch the catalog/controller/common/seo_url.php file and add your pretty URLs to an existing database table.</p>
<hr>
<p><strong>The patch to seo_url.php:</strong></p>
<pre><code>Index: catalog/controller/common/seo_url.php
===================================================================
--- catalog/controller/common/seo_url.php (old)
+++ catalog/controller/common/seo_url.php (new)
@@ -48,7 +42,12 @@
$this->request->get['route'] = 'product/manufacturer/product';
} elseif (isset($this->request->get['information_id'])) {
$this->request->get['route'] = 'information/information';
- }
+ } else {
+ $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($this->request->get['_route_']) . "'");
+ if ($query->num_rows) {
+ $this->request->get['route'] = $query->row['query'];
+ }
+ }
if (isset($this->request->get['route'])) {
return $this->forward($this->request->get['route']);
@@ -88,7 +87,15 @@
}
unset($data[$key]);
- }
+ } else {
+ $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($data['route']) . "'");
+
+ if ($query->num_rows) {
+ $url .= '/' . $query->row['keyword'];
+
+ unset($data[$key]);
+ }
+ }
}
}
</code></pre>
<p>There are two edits required. The first extends the <code>index()</code> function to look in the <code>url_alias</code> table for <em>any</em> keyword matching <code>$this->request->get['_route_']</code>.</p>
<p>The second extends the <code>rewrite()</code> function to look in the <code>url_alias</code> table for <em>all</em> routes, not just those for products, manufacturers, and information pages.</p>
<hr>
<p><strong>Adding entries to the database:</strong></p>
<pre><code>INSERT INTO `url_alias` (`url_alias_id`, `query`, `keyword`) VALUES
(NULL, 'checkout/cart', 'cart');
</code></pre>
<hr>
<p>That's it. <a href="http://example.com/cart">http://example.com/cart</a> should return the same thing that <a href="http://example.com/index.php?route=checkout/cart">http://example.com/index.php?route=checkout/cart</a> does, and OpenCart should recognize <code>$this->url->link('checkout/cart');</code> and return a link to the pretty URL <a href="http://example.com/cart">http://example.com/cart</a></p> |
7,352,099 | std::string to char* | <p>I want to convert a <strong>std::string</strong> into a <strong>char*</strong> or <strong>char[]</strong> data type.</p>
<pre><code>std::string str = "string";
char* chr = str;
</code></pre>
<p>Results in: <strong>“error: cannot convert ‘std::string’ to ‘char’ ...”</strong>.</p>
<p>What methods are there available to do this?</p> | 7,352,131 | 18 | 1 | null | 2011-09-08 17:25:22.883 UTC | 128 | 2021-09-08 21:12:09.08 UTC | null | user1598585 | null | user1598585 | null | null | 1 | 446 | c++|string|char | 1,107,065 | <p>It won't automatically convert (thank god). You'll have to use the method <code>c_str()</code> to get the C string version.</p>
<pre><code>std::string str = "string";
const char *cstr = str.c_str();
</code></pre>
<p>Note that it returns a <code>const char *</code>; you aren't allowed to change the C-style string returned by <code>c_str()</code>. If you want to process it you'll have to copy it first:</p>
<pre><code>std::string str = "string";
char *cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());
// do stuff
delete [] cstr;
</code></pre>
<p>Or in modern C++:</p>
<pre><code>std::vector<char> cstr(str.c_str(), str.c_str() + str.size() + 1);
</code></pre> |
47,406,344 | How to open a page in new tab on click of a button in react? I want to send some data to that page also | <p>I'm working on a raise invoice page, in which user can raise a invoice on clicking of a button, I would call a api call and after getting the response I want to send some data to a <strong>page</strong>(RaisedInvoice.jsx) which should open in a <strong>new tab</strong>, how can i do it. The thing which I am not getting is how to open a page in new tab on click of a button in <strong>ReactJs</strong>.</p>
<p>RaiseInvoice.jsx:</p>
<pre><code>import React from 'react';
import Links from './Links.jsx';
import history from './history.jsx';
import axios from 'axios';
class RaiseInvoice extends React.Component {
constructor(props) {
super(props);
// This binding is necessary to make `this` work in the callback
this.state = {projects: [], searchParam : ''};
this.raiseInvoiceClicked = this.raiseInvoiceClicked.bind(this);
}
raiseInvoiceClicked(){
// here i wish to write the code for opening the page in new tab.
}
render() {
return (
<div>
<Links activeTabName="tab2"></Links>
<div className="container">
<div className = "row col-md-4">
<h1>Raise Invoice...</h1>
</div>
<div className = "row col-md-4"></div>
<div className = "row col-md-4" style ={{"marginTop":"24px"}}>
<button type="button" className="btn btn-default pull-right" onClick={this.raiseInvoiceClicked}>Raise Invoice</button>
</div>
</div>
</div>
)
}
}
export default RaiseInvoice;
</code></pre> | 47,406,575 | 6 | 4 | null | 2017-11-21 06:12:49.823 UTC | 3 | 2022-08-17 07:32:12.183 UTC | 2020-12-22 16:24:47.607 UTC | null | 1,783,163 | null | 8,578,554 | null | 1 | 43 | reactjs|react-router | 147,685 | <p>Since you were going to send big data, appending them to your target URL looks shabby. I would suggest you use 'LocalStorage' for this purpose. So your code looks like this,</p>
<pre><code>raiseInvoiceClicked(){
// your axios call here
localStorage.setItem("pageData", "Data Retrieved from axios request")
// route to new page by changing window.location
window.open(newPageUrl, "_blank") //to open new page
}
</code></pre>
<p>In your RaisedInvoice.jsx, retrieve the data from Local Storage like this,</p>
<pre><code>componentWillMount() {
localStorage.pagedata= "your Data";
// set the data in state and use it through the component
localStorage.removeItem("pagedata");
// removing the data from localStorage. Since if user clicks for another invoice it overrides this data
}
</code></pre> |
43,806,188 | How can I access an activated child route's data from the parent route's component? | <pre><code>const appRoutes: Routes = [
{ path: 'parent', component: parentComp, data: { foo: 'parent data' }, children: [
{ path: 'child1', component: childComp1, data: { bar: 'child data 1' },
{ path: 'child2', component: childComp2, data: { bar: 'child data 2' }
]}
];
</code></pre>
<p>If I navigate to <code>/parent/child2</code> and then look at the <code>ActivatedRoute</code> from <code>parentComp</code>, <code>data.foo</code> is defined, but <code>data.bar</code> is not. I have access to an array of all the children, but I don't know which one is activated.</p>
<p>How can I access the activated child route's data from a parent route's component? </p> | 43,806,807 | 5 | 1 | null | 2017-05-05 13:25:59.23 UTC | 9 | 2020-09-15 11:04:07.133 UTC | null | null | null | null | 1,221,537 | null | 1 | 48 | angular|angular2-routing | 54,436 | <p>First child will give you access to data</p>
<pre><code>constructor(route: ActivatedRoute) {
route.url.subscribe(() => {
console.log(route.snapshot.firstChild.data);
});
}
</code></pre> |
30,047,122 | Java ForkJoinPool with non-recursive tasks, does work-stealing work? | <p>I want to submit <code>Runnable</code> tasks into ForkJoinPool via a method:</p>
<pre><code>forkJoinPool.submit(Runnable task)
</code></pre>
<p>Note, I use JDK 7.</p>
<p>Under the hood, they are transformed into ForkJoinTask objects.
I know that ForkJoinPool is efficient when a task is split into smaller ones recursively.</p>
<p><strong>Question:</strong></p>
<p>Does work-stealing still work in the ForkJoinPool if there is no recursion?</p>
<p>Is it worth it in this case?</p>
<p><strong>Update 1:</strong>
Tasks are small and can be unbalanced. Even for strictly equal tasks, such things like context switching, thread scheduling, parking, pages misses etc. get in the way leading to the <strong>imbalance</strong>.</p>
<p><strong>Update 2:</strong>
Doug Lea wrote in the <a href="http://cs.oswego.edu/pipermail/concurrency-interest/2012-January/008987.html" rel="noreferrer">Concurrency JSR-166 Interest</a> group, by giving a hint on this:</p>
<blockquote>
<p>This also greatly improves throughput when all tasks are async and
submitted to the pool rather than forked, which becomes a reasonable
way to structure actor frameworks, as well as many plain services that
you might otherwise use ThreadPoolExecutor for.</p>
</blockquote>
<p>I presume, when it comes to reasonably small CPU-bound tasks, ForkJoinPool is the way to go, thanks to this optimization. The main point is that these tasks are already small and needn't a recursive decomposition. <strong>Work-stealing</strong> works, regardless whether it is a big or small task - tasks can be grabbed by another free worker from the Deque's tail of a busy worker.</p>
<p><strong>Update 3:</strong>
<a href="http://letitcrash.com/post/17607272336/scalability-of-fork-join-pool" rel="noreferrer">Scalability of ForkJoinPool</a> - benchmarking by Akka team of ping-pong shows great results.</p>
<p>Despite this, to apply ForkJoinPool more efficiently requires performance tuning.</p> | 30,085,265 | 1 | 5 | null | 2015-05-05 07:52:26.747 UTC | 6 | 2015-05-06 19:06:36.9 UTC | 2015-05-06 11:11:45.897 UTC | null | 1,863,694 | null | 1,863,694 | null | 1 | 28 | java|multithreading|fork-join|forkjoinpool|work-stealing | 3,450 | <p><code>ForkJoinPool</code> source code has a nice section called "Implementation Overview", read up for an ultimate truth. The explanation below is my understanding for JDK 8u40.</p>
<p>Since day one, <code>ForkJoinPool</code> had a work queue per worker thread (let's call them "worker queues"). The forked tasks are pushed into the local worker queue, ready to be popped by the worker again and be executed -- in other words, it looks like a stack from worker thread perspective. When a worker depletes its worker queue, it goes around and tries to steal the tasks from other worker queues. That is <em>"work stealing"</em>. </p>
<p>Now, before (IIRC) JDK 7u12, <code>ForkJoinPool</code> had a single global <em>submission queue</em>. When worker threads ran out of local tasks, as well the tasks to steal, they got there and tried to see if external work is available. In this design, there is no advantage against a regular, say, <code>ThreadPoolExecutor</code> backed by <code>ArrayBlockingQueue</code>. </p>
<p>It changed significantly after then. After this submission queue was identified as the serious performance bottleneck, Doug Lea et al. striped the submission queues as well. In hindsight, that is an obvious idea: you can reuse most of the mechanics available for worker queues. You can even loosely distribute these submission queues per worker threads. Now, the external submission goes into one of the submission queues. Then, workers that have no work to munch on, can first look into the submission queue associated with a particular worker, and then wander around looking into the submission queues of others. One can call <em>that</em> "work stealing" too.</p>
<p>I have seen many workloads benefiting from this. This particular design advantage of <code>ForkJoinPool</code> even for plain non-recursive tasks was recognized a long ago. Many users at concurrency-interest@ asked for a simple work-stealing executor without all the <code>ForkJoinPool</code> arcanery. This is one of the reasons, why we have <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newWorkStealingPool--" rel="noreferrer"><code>Executors.newWorkStealingPool()</code></a> in JDK 8 onward -- currently delegating to <code>ForkJoinPool</code>, but open for providing a simpler implementation.</p> |
9,207,267 | How to update excel embedded charts in powerpoint? | <p>I have 30 charts that were created from excel and were pasted onto powerpoint slides. Every month, I have to update these 30 embedded charts by manually clicking on the charts and edit. </p>
<p>I am aware there is an option to use paste special, so that the data in the charts can be updated automatically by clicking the update links. However, my charts needs to be edited by some users. Paste special option does not allow users to edit the charts. Hence, I am unable to use this paste special option.</p>
<p>I think the solution lies in writing a vba in powerpoint. Can any expert here offer to write this vba code to allow all the charts to be updated in powerpoint? I am currently using powerpoint 2007. Your assistance is greatly appreciated.</p> | 9,209,837 | 2 | 1 | null | 2012-02-09 08:03:39.17 UTC | 4 | 2020-07-03 08:44:51.487 UTC | 2020-07-03 08:44:51.487 UTC | null | 100,297 | null | 1,199,080 | null | 1 | 8 | vba|powerpoint | 91,294 | <p>If you need to edit the charts then clearly you will either need to edit the underlying Excel files, or be able to edit in PowerPoint</p>
<p>As you are using PowerPoint2007 which provides full Excel support (unlike PowerPoint 2003 which has a datasheet) I would</p>
<p><strong>Part 1</strong></p>
<ol>
<li>Link your Excel file data to the Excel data underneath each chart</li>
<li>Provide the ability to either use that data directly, or over-ride it with user data</li>
</ol>
<p><img src="https://i.stack.imgur.com/nCYo2.png" alt="Sample"></p>
<p>This gives you a flexible solution, except that Excel underlying each chart cannot be updated automatically via a PowerPoint menu Update Links command.</p>
<p><strong>Part 2</strong> </p>
<p>You can use the code below to test each whether each shape on each slide has a chart. If so this code will update the first Excel link in the Excel file underneath the chart (this part can be tweaked to handle multiple links)</p>
<pre><code> Sub ChangeChartData()
Dim pptChart As Chart
Dim pptChartData As ChartData
Dim pptWorkbook As Object
Dim sld As Slide
Dim shp As Shape
For Each sld In ActivePresentation.Slides
For Each shp In sld.Shapes
If shp.HasChart Then
Set pptChart = shp.Chart
Set pptChartData = pptChart.ChartData
pptChartData.Activate
Set pptWorkbook = pptChartData.Workbook
On Error Resume Next
'update first link
pptWorkbook.UpdateLink pptWorkbook.LinkSources(1)
On Error GoTo 0
pptWorkbook.Close True
End If
Next
Next
Set pptWorkbook = Nothing
Set pptChartData = Nothing
Set pptChart = Nothing
End Sub
</code></pre> |
34,926,253 | Rebase only part of a branch | <p>I've got two branches (and master). Branch 2 is based on Branch 1 is based on master. I've submitted Branch 1 for review, it had some changes, I rebased some of those changes into history and merged the result into master. </p>
<p>Now I need to rebase Branch 2 on top of master to prepare it for review/merge.</p>
<p>The problem is that Branch 2 still contains the original commits of Branch 1, which don't exist anymore, so git gets confused. I tried rebase -i to drop the original commits of Branch 1, but the commits of Branch 2 don't base on top of master-before-branch-1.</p>
<p>What I need to do is take branch 2, drop some commits, and rebase just the remaining commits on top of master in a single operation. But I only know how to do these two operations in two distinct steps.</p>
<p>How can I rebase part of my branch onto another branch, dropping all commits that are not in common ancestry, except the ones I specify (e.g. from HEAD~2 up)?</p>
<p>Here's the current state:</p>
<pre><code>master new branch 1
- - - - - - - - - - - | - - - - - - - - -
\
\ branch 1
\ _ _ _ _ _ _ _
\
\ branch 2
\ _ _ _ _ _ _ _
</code></pre>
<p>What I want to end up with:</p>
<pre><code>master new branch 1
- - - - - - - | - - - - - - - - - -
\
\
\
\ branch 2
- - - - - - - - -
</code></pre> | 34,926,593 | 5 | 3 | null | 2016-01-21 14:20:40.583 UTC | 31 | 2021-06-18 13:17:11.353 UTC | 2016-01-21 14:28:32.357 UTC | null | 298,661 | null | 298,661 | null | 1 | 79 | git | 19,698 | <p>The solution is considerably simpler than I expected. It turns out that you can supply <code>-i</code> to a much larger variety of rebase commands (I thought it was only for rebasing a branch to itself for changing history). So I simply ran <code>git rebase -i master</code> and dropped those extra commits.</p> |
807,415 | CSS selector for an element having class .a and class .b | <p>I need to style an element that has both class <code>.a</code> and class <code>.b</code>. How do I do it?</p>
<p>The order the classes appear in the HTML might vary.</p>
<pre><code><style>
div.a ? div.b {
color:#f00;
}
</style>
<div class="a">text not red</div>
<div class="b">text not red</div>
<div class="a b">red text</div>
<div class="b a">red text</div>
</code></pre> | 807,450 | 5 | 0 | null | 2009-04-30 15:11:01.773 UTC | 7 | 2020-08-04 21:17:53.917 UTC | 2018-09-27 14:49:29.53 UTC | null | 3,345,644 | null | 17,781 | null | 1 | 34 | css|css-selectors | 63,665 | <p>That's entirely possible. If you specify two classes on an element (without any spaces), that means that it must have both for the rule to apply.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div.a {
color: blue;
}
div.b {
color: green;
}
div.a.b {
color: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
A
</div>
<div class="b">
B
</div>
<div class="a b">
AB
</div></code></pre>
</div>
</div>
</p> |
501,069 | Functions with generic parameter types | <p>I am trying to figure out how to define a function that works on multiple types of parameters (e.g. int and int64). As I understand it, function overloading is not possible in F# (certainly the compiler complains). Take for example the following function.</p>
<pre><code>let sqrt_int = function
| n:int -> int (sqrt (float n))
| n:int64 -> int64 (sqrt (float n))
</code></pre>
<p>The compiler of course complains that the syntax is invalid (type constraints in pattern matching are not supported it seems), though I think this illustrates what I would like to achieve: a function that operates on several parameter types and returns a value of the according type. I have a feeling that this is possible in F# using some combination of generic types/type inference/pattern matching, but the syntax has eluded me. I've also tried using the :? operator (dynamic type tests) and <em>when</em> clauses in the pattern matching block, but this still produces all sorts errors.</p>
<p>As I am rather new to the language, I may very well be trying to do something impossible here, so please let me know if there is alternative solution.</p> | 501,356 | 5 | 0 | null | 2009-02-01 16:09:47.503 UTC | 19 | 2015-05-06 21:59:44.143 UTC | 2014-03-19 04:15:11.523 UTC | Brian | 41,956 | Noldorin | 44,389 | null | 1 | 48 | generics|f#|overloading|type-inference|typeclass | 19,451 | <p>Overloading is typically the bugaboo of type-inferenced languages (at least when, like F#, the type system isn't powerful enough to contain type-classes). There are a number of choices you have in F#:</p>
<ul>
<li>Use overloading on methods (members of a type), in which case overloading works much like as in other .Net languages (you can ad-hoc overload members, provided calls can be distinguished by the number/type of parameters)</li>
<li>Use "inline", "^", and static member constraints for ad-hoc overloading on functions (this is what most of the various math operators that need to work on int/float/etc.; the syntax here is weird, this is little-used apart from the F# library)</li>
<li>Simulate type classes by passing an extra dictionary-of-operations parameter (this is what INumeric does in one of the F# PowerPack libraries to generalize various Math algorithms for arbitrary user-defined types)</li>
<li>Fall back to dynamic typing (pass in an 'obj' parameter, do a dynamic type test, throw a runtime exception for bad type)</li>
</ul>
<p>For your particular example, I would probably just use method overloading:</p>
<pre><code>type MathOps =
static member sqrt_int(x:int) = x |> float |> sqrt |> int
static member sqrt_int(x:int64) = x |> float |> sqrt |> int64
let x = MathOps.sqrt_int 9
let y = MathOps.sqrt_int 100L
</code></pre> |
1,330,692 | Distinct pair of values SQL | <p>Consider</p>
<pre><code> create table pairs ( number a, number b )
</code></pre>
<p>Where the data is </p>
<pre><code>1,1
1,1
1,1
2,4
2,4
3,2
3,2
5,1
</code></pre>
<p>Etc. </p>
<p>What query gives me the distinct values the number column b has So I can see</p>
<pre><code>1,1
5,1
2,4
3,2
</code></pre>
<p>only </p>
<p>I've tried</p>
<pre><code>select distinct ( a ) , b from pairs group by b
</code></pre>
<p>but gives me "not a group by expression" </p> | 1,330,704 | 5 | 0 | null | 2009-08-25 20:14:11.617 UTC | 12 | 2014-02-14 16:42:41.417 UTC | 2009-08-25 21:34:03.923 UTC | null | 20,654 | null | 20,654 | null | 1 | 77 | sql|group-by|distinct | 132,756 | <p>What you mean is either</p>
<pre><code>SELECT DISTINCT a, b FROM pairs;
</code></pre>
<p>or</p>
<pre><code>SELECT a, b FROM pairs GROUP BY a, b;
</code></pre> |
750,565 | Writing data back to SQL from Excel sheet | <p>I know it is possible to get data from a SQL database into an excel sheet, but i'm looking for a way to make it possible to edit the data in excel, and after editing, writing it back to the SQL database.</p>
<p>It appears this is not a function in excel, and google didn't come up with much usefull.</p> | 757,892 | 6 | 0 | null | 2009-04-15 06:51:25.967 UTC | 7 | 2018-03-15 01:08:16.72 UTC | null | null | null | null | 71,897 | null | 1 | 16 | sql|excel | 56,651 | <p>If you want to have the Excel file do all of the work (retrieve from DB; manipulate; update DB) then you could look at ActiveX Data Objects (ADO). You can get an overview at:</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms680928(VS.85).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms680928(VS.85).aspx</a></p> |
122,483 | Specifying "all odd values" in crontab? | <p>In crontab, I can use an asterisk to mean every value, or "*/2" to mean every even value.</p>
<p>Is there a way to specify every <strong>odd</strong> value? (Would something like "1+*/2" work?)</p> | 122,499 | 6 | 0 | null | 2008-09-23 17:32:25.057 UTC | 9 | 2019-07-01 16:41:34.153 UTC | null | null | null | levik | 4,465 | null | 1 | 80 | cron|crontab | 39,141 | <p>Depending on your version of cron, you should be able to do (for hours, say):</p>
<pre><code> 1-23/2
</code></pre>
<p>Going by the EXTENSIONS section in the crontab(5) manpage:</p>
<pre><code> Ranges can include "steps", so "1-9/2" is the same as "1,3,5,7,9".
</code></pre>
<p>For a more portable solution, I suspect you just have to use the simple list:</p>
<pre><code> 1,3,5,7,9,11,13,15,17,19,21,23
</code></pre>
<p>But it might be easier to wrap your command in a shell script that will immediately exit if it's not called in an odd minute.</p> |
588,892 | Can you 'exit' a loop in PHP? | <p>I have a loop that is doing some error checking in my PHP code. Originally it looked something like this...</p>
<pre><code>foreach($results as $result) {
if (!$condition) {
$halt = true;
ErrorHandler::addErrorToStack('Unexpected result.');
}
doSomething();
}
if (!$halt) {
// do what I want cos I know there was no error
}
</code></pre>
<p>This works all well and good, but it is still looping through despite after one error it needn't. Is there a way to escape the loop?</p> | 588,900 | 6 | 0 | null | 2009-02-26 02:44:51.22 UTC | 18 | 2019-10-06 21:09:49.05 UTC | 2013-03-08 01:06:59.437 UTC | alex | 31,671 | alex | 31,671 | null | 1 | 131 | php|loops | 291,709 | <p>You are looking for the <a href="http://www.php.net/break" rel="noreferrer">break</a> statement.</p>
<pre><code>$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
while (list(, $val) = each($arr)) {
if ($val == 'stop') {
break; /* You could also write 'break 1;' here. */
}
echo "$val<br />\n";
}
</code></pre> |
1,036,351 | Is it possible to use jQuery to read meta tags | <p>Is it possible to use jQuery to read meta tags. If so do you know what the basic structure of the code will be, or have links to any tutorials.</p> | 1,036,362 | 6 | 0 | null | 2009-06-24 04:09:11.73 UTC | 31 | 2021-04-17 22:37:00.35 UTC | null | null | null | null | 69,803 | null | 1 | 168 | jquery|dom|meta-tags | 133,954 | <p>Just use something like:</p>
<pre><code>var author = $('meta[name=author]').attr('content');
</code></pre>
<p>or this as well</p>
<pre><code>var author = $('meta[name=author]').prop('content');
</code></pre> |
37,833,307 | Django Rest Framework POST Update if existing or create | <p>I am new to DRF.
I read the API docs, maybe it is obvious but I couldn't find a handy way to do it.</p>
<p>I have an <code>Answer</code> object which has one-to-one relationship with a <code>Question</code>.</p>
<p>On the frontend I used to use POST method to create an answer sent to <code>api/answers</code>, and PUT method to update sent to e.g. <code>api/answers/24</code></p>
<p>But I want to handle it on the server side. I will only send a POST method to <code>api/answers</code> and DRF will check based on <code>answer_id</code> or <code>question_id</code> (since it is one to one) if the object exists.
If it does, it will update the existing one, and if it doesn't, it will create a new answer.</p>
<p>I couldn't figure out where I should implement it. Should I override <code>create()</code> in serializer or in ViewSet or something else?</p>
<p>Here are my model, serializer, and view:</p>
<pre><code>class Answer(models.Model):
question = models.OneToOneField(
Question, on_delete=models.CASCADE, related_name="answer"
)
answer = models.CharField(
max_length=1, choices=ANSWER_CHOICES, null=True, blank=True
)
class AnswerSerializer(serializers.ModelSerializer):
question = serializers.PrimaryKeyRelatedField(
many=False, queryset=Question.objects.all()
)
class Meta:
model = Answer
fields = ("id", "answer", "question")
class AnswerViewSet(ModelViewSet):
queryset = Answer.objects.all()
serializer_class = AnswerSerializer
filter_fields = ("question", "answer")
</code></pre> | 43,393,253 | 8 | 4 | null | 2016-06-15 10:48:20.103 UTC | 20 | 2021-07-06 18:49:45.593 UTC | 2021-07-05 19:04:51.21 UTC | null | 7,487,335 | null | 6,469,020 | null | 1 | 50 | python|django|django-rest-framework | 65,906 | <p>Unfortunately your provided and accepted answer does not answer your original question, since it does not update the model. This however is easily achieved by another convenience method: <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#update-or-create" rel="noreferrer">update-or-create</a></p>
<pre><code>def create(self, validated_data):
answer, created = Answer.objects.update_or_create(
question=validated_data.get('question', None),
defaults={'answer': validated_data.get('answer', None)})
return answer
</code></pre>
<p>This should create an <code>Answer</code> object in the database if one with <code>question=validated_data['question']</code> does not exist with the answer taken from <code>validated_data['answer']</code>. If it already exists, django will set its answer attribute to <code>validated_data['answer']</code>.</p>
<p>As noted by the answer of Nirri, this function should reside inside the serializer. If you use the generic <a href="http://www.django-rest-framework.org/api-guide/generic-views/#listcreateapiview" rel="noreferrer">ListCreateView</a> it will call the create function once a post request is sent and generate the corresponding response.</p> |
21,268,558 | Application failed to start because it could not find or load the QT platform plugin "windows" | <p>I have looked through all of the questions that appear to be related on stack overflow, and none of the solutions seem to help me.</p>
<p>I am building a Qt application with this setup:</p>
<ul>
<li>Windows 7 Professional x64</li>
<li>Visual Studio 2012</li>
<li>Qt 5.2.0 built with <code>configure -developer-build -debug-and-release -opensource -nomake examples -nomake tests -platform win32-msvc2012 -no-opengl</code></li>
<li>Project uses QtSingleApplication (qt-solutions)</li>
<li>Application is a 32 bit application</li>
<li>qmake run with the following: -makefile -spec win32-msvc2012</li>
<li>.pri uses <code>QMAKE_CXX += /D_USING_V110_SDK71_</code></li>
</ul>
<p>I can build and run my program fine on my development machine (noted above); I can also install and run the package from Program Files directory on dev machine.</p>
<p>When I install and run on a Windows Vista machine (multiple machines)</p>
<ul>
<li>VC++ redist 2012 11.0.61030.0 installed</li>
<li>VC++ redist 2010 10.0.40219 installed</li>
<li>plus 2005, 2008 versions of redist</li>
</ul>
<p>(also fails on a clean install of Windows 7)</p>
<p>I get: </p>
<p><code>Application failed to start because it could not find or load the QT platform plugin "windows"</code></p>
<p>So I followed the instructions and added a .platforms/ directory, and added qwindows.dll (also added qminimal.dll and qoffscreen.dll); I also added libEGL.dll, libGLESv2.dll (even though I shouldn't need them I don't think)</p>
<p>Once I added qoffscreen.dll I now get the additional message: <code>Available platform plugins are: offscreen</code></p>
<p>If I run through Dependency Walker I get this error listed:</p>
<pre><code>GetProcAddress(0x76CA0000 [KERNEL32.DLL], "GetCurrentPackageId") called from "MSVCR110.DLL" at address 0x6AC6FDFA and returned NULL. Error: The specified procedure could not be found (127).
</code></pre>
<p>and then further down get the:</p>
<pre><code>GetProcAddress(0x745A0000 [UXTHEME.DLL], "BufferedPaintUnInit") called from "COMCTL32.DLL" at address 0x745FFBF8 and returned 0x745AE18C.
This application failed to start because it could not find or load the Qt platform plugin "windows".
Available platform plugins are: offscreen.
Reinstalling the application may fix this problem.
</code></pre>
<p>Any ideas how to fix this dll issue?</p> | 21,291,286 | 13 | 4 | null | 2014-01-21 20:35:19.333 UTC | 6 | 2019-06-20 17:40:27.84 UTC | 2014-01-22 17:50:36.143 UTC | null | 229,204 | null | 229,204 | null | 1 | 34 | c++|qt|dll|platform | 81,222 | <p>Well I solved my issue, although I'm not sure what the difference is:</p>
<p>I copied every dll from my qt directory into both ./ and ./platforms of my application directory.</p>
<p>The application got past the error, but then crashed.</p>
<p>VERSION.dll was causing the crash (noted in dependency walker), so I removed it from both places.</p>
<p>The Application started up, so I systematically removed all unneeded dll's.</p>
<p>This got me back to the same state I had originally.</p>
<p>I then uninstalled my application and re-installed (with only the ./platforms/qwindows.dll file remaining), application works correctly.</p>
<p>So all I can assume is that I had an incorrect version of qwindows.dll in the platforms directory.</p> |
17,682,267 | Bootstrap Popover, .click not catching button inside popover | <p>First off, a fiddle of the problem: <a href="http://jsfiddle.net/timotheus/jjYQp/4/" rel="noreferrer">jsfiddle.net</a></p>
<p>I am using a popover, and it's content is html, a button with class "click_me". I have jquery to listen for a click on "click_me" and it should throw an alert. However, it doesn't. Am I missing something?</p>
<p>JS:</p>
<pre><code>jQuery(document).ready(function($) {
$('.demo_button').click(function () {
$(this).popover({
html: true,
trigger: 'manual',
placement: 'right',
content: function () {
var $buttons = $('#popover_template').html();
return $buttons;
}
}).popover('toggle');
});
$('.click_me').click(function() {
alert('it works!');
});
});
</code></pre>
<p>HTML:</p>
<pre><code><button class="btn btn-primary demo_button">Click here</button>
<div id="popover_template">
<button class="btn click_me">Make Alert</button>
</div>
</code></pre> | 17,682,320 | 4 | 0 | null | 2013-07-16 16:39:48.807 UTC | 3 | 2017-02-06 17:41:47.863 UTC | 2013-07-16 17:33:48.16 UTC | null | 171,456 | null | 1,013,661 | null | 1 | 30 | jquery|html|twitter-bootstrap|popover | 30,986 | <p>.click() will only work for elements that are present on load you need to use on()</p>
<pre><code>$(document).on("click", ".click_me", function() {
alert('it works!');
});
</code></pre> |
65,316,558 | Azure Application not registered with AAD | <p>Getting below error while logging to container registry</p>
<p>Command:</p>
<pre><code>docker login <MY_REGISTRY_NAME>.azurecr.io
</code></pre>
<p>Error Message:</p>
<pre><code>Error response from daemon: Get https://<MY_REGISTRY_NAME>.azurecr.io/v2/: unauthorized: Application not registered with AAD
</code></pre> | 65,316,883 | 8 | 1 | null | 2020-12-16 02:41:17.047 UTC | 3 | 2022-08-05 13:32:15.463 UTC | 2020-12-16 08:52:51.397 UTC | null | 11,942,268 | null | 7,683,673 | null | 1 | 29 | azure|azure-active-directory|azure-container-registry | 14,589 | <p>Go to Access Keys in Container Registry and enable the admin user, then use the autogenerated credentials to login via Docker</p> |
1,992,532 | Monad trait in Scala | <p>(How) is it possible to represent monads in Scala in a generic way (like the <code>Monad</code> typeclass in Haskell)? Is it somehow possible to define a <code>trait Monad</code> for this purpose?</p> | 1,993,982 | 5 | 0 | null | 2010-01-02 19:19:45.623 UTC | 19 | 2015-11-27 20:34:09.667 UTC | null | null | null | null | 105,459 | null | 1 | 25 | generics|scala|functional-programming | 9,802 | <p>You could try something like this:</p>
<pre><code>trait Monad[+M[_]] {
def unit[A](a: A): M[A]
def bind[A, B](m: M[A])(f: A => M[B]): M[B]
}
// probably only works in Scala 2.8
implicit def monadicSyntax[M[_], A](m: M[A])(implicit tc: Monad[M]) = new {
private val bind = tc.bind(m) _
def map[B](f: A => B) = bind(f compose tc.unit)
def flatMap[B](f: A => M[B]) = bind(f)
}
implicit object MonadicOption extends Monad[Option] {
def unit[A](a: A) = Some(a)
def bind[A, B](opt: Option[A])(f: A => Option[B]) = opt flatMap f
}
</code></pre>
<p>You would of course define similar implicit objects for any other monad your heart desires. In Haskell terms, you can think of <code>Monad</code> like the typeclass and <code>MonadicOption</code> as a particular instance of that type class. The <code>monadicSyntax</code> implicit conversion simply demonstrates how this typeclass could be used to allow the use of Scala's <code>for</code>-comprehensions with anything which satisfies the <code>Monad</code> typeclass.</p>
<p>Generally speaking, most things in the Scala standard library which implement <code>flatMap</code> are monads. Scala doesn't define a generic <code>Monad</code> typeclass (though that would be very useful). Instead, it relies on a syntactic trick of the parser to allow the use of <code>for</code>-comprehensions with <em>anything</em> which implements the appropriate methods. Specifically, those methods are <code>map</code>, <code>flatMap</code> and <code>filter</code> (or <code>foreach</code> and <code>filter</code> for the imperative form).</p> |
1,634,739 | iPhone Pull Down Refresh like Tweetie | <p>I am trying to find an example of placing an element above the Table View outside the normal scrollable region. How would I do this? An example would be what the Tweetie 2 app for the iPhone does to refresh tweets.</p>
<p>Sample code would be extremely helpful.</p> | 1,634,981 | 5 | 5 | null | 2009-10-28 01:46:05.417 UTC | 26 | 2015-05-22 10:20:06.763 UTC | 2013-04-11 14:24:52.413 UTC | null | 1,401,895 | null | 115,986 | null | 1 | 44 | iphone|uitableview|pull-to-refresh | 37,450 | <p>I did find the answer to my own question, for anyone who is interested.</p>
<p><a href="http://github.com/enormego/EGOTableViewPullRefresh" rel="noreferrer">EGOTableViewPullRefresh</a></p>
<p>I tried this solution and it works great! It is almost identical to the Tweetie Pull Down refresh.</p> |
1,847,310 | Count number of points inside a circle fast | <p>Given a set of n points on plane, I want to preprocess these points somehow faster than O(n^2) (O(nlog(n)) preferably), and then be able to answer on queries of the following kind "How many of n points lie inside a circle with given center and radius?" faster than O(n) (O(log(n) preferably). </p>
<p>Can you suggest some data structure or algorithm I can use for this problem?</p>
<p>I know that such types of problems are often solved using Voronoi diagrams, but I don't know how to apply it here.</p> | 1,847,921 | 6 | 6 | null | 2009-12-04 14:32:50.303 UTC | 12 | 2017-04-03 23:35:12.84 UTC | 2017-04-03 23:35:12.84 UTC | null | -1 | null | 224,813 | null | 1 | 13 | algorithm|math|search|geometry|range | 8,538 | <p>Build a spatial subdivision structure such as a <a href="http://en.wikipedia.org/wiki/Quadtree" rel="noreferrer">quadtree</a> or <a href="http://en.wikipedia.org/wiki/Kd_tree" rel="noreferrer">KD-tree</a> of the points. At each node store the amount of points covered by that node. Then when you need to count the points covered by the lookup circle, traverse the tree and for each subdivision in a node check if it is fully outside the circle, then ignore it, if it is fully inside the circle then add its count to the total if it intersects with the circle, recurse, when you get to the leaf, check the point(s) inside the leaf for containment.</p>
<p>This is still O(n) worst case (for instance if all the points lie on the circle perimeter) but average case is O(log(n)).</p> |
1,419,194 | Algorithm for nice graph labels for time/date axis? | <p>I'm looking for a "nice numbers" algorithm for determining the labels on a date/time value axis. I'm familiar with <a href="http://books.google.com/books?id=fvA7zLEFWZgC&pg=PA61&lpg=PA61#v=onepage&q&f=false" rel="nofollow noreferrer">Paul Heckbert's Nice Numbers algorithm</a>.</p>
<p>I have a plot that displays time/date on the X axis and the user can zoom in and look at a smaller time frame. I'm looking for an algorithm that picks nice dates to display on the ticks. </p>
<p>For example:</p>
<ul>
<li>Looking at a day or so: 1/1 12:00, 1/1 4:00, 1/1 8:00...</li>
<li>Looking at a week: 1/1, 1/2, 1/3...</li>
<li>Looking at a month: 1/09, 2/09, 3/09...</li>
</ul>
<p>The nice label ticks don't need to correspond to the first visible point, but close to it.</p>
<p>Is anybody familiar with such an algorithm?</p> | 2,144,398 | 6 | 0 | null | 2009-09-14 00:16:21.433 UTC | 11 | 2018-02-13 11:31:02.703 UTC | 2015-07-03 11:33:32.347 UTC | null | 2,630,337 | null | 172,871 | null | 1 | 21 | algorithm|graph|label | 5,354 | <p>The 'nice numbers' article you linked to mentioned that</p>
<blockquote>
<p>the nicest numbers in decimal are 1, 2, 5 and all power-of-10 multiples of these numbers</p>
</blockquote>
<p>So I think for doing something similar with date/time you need to start by similarly breaking down the component pieces. So take the nice factors of each type of interval:</p>
<ul>
<li>If you're showing seconds or minutes use 1, 2, 3, 5, 10, 15, 30
(I skipped 6, 12, 15, 20 because they don't "feel" right).</li>
<li>If you're showing hours use 1, 2, 3, 4, 6, 8, 12</li>
<li>for days use 1, 2, 7</li>
<li>for weeks use 1, 2, 4 (13 and 26 fit the model but seem too odd to me)</li>
<li>for months use 1, 2, 3, 4, 6</li>
<li>for years use 1, 2, 5 and power-of-10 multiples</li>
</ul>
<p>Now obviously this starts to break down as you get into larger amounts. Certainly you don't want to do show 5 weeks worth of minutes, even in "pretty" intervals of 30 minutes or something. On the other hand, when you only have 48 hours worth, you don't want to show 1 day intervals. The trick as you have already pointed out is finding decent transition points.</p>
<p>Just on a hunch, I would say a reasonable crossover point would be about twice as much as the next interval. That would give you the following (min and max number of intervals shown afterwards)</p>
<ul>
<li>use seconds if you have less than 2 minutes worth (1-120)</li>
<li>use minutes if you have less than 2 hours worth (2-120)</li>
<li>use hours if you have less than 2 days worth (2-48)</li>
<li>use days if you have less than 2 weeks worth (2-14)</li>
<li>use weeks if you have less than 2 months worth (2-8/9)</li>
<li>use months if you have less than 2 years worth (2-24)</li>
<li>otherwise use years (although you could continue with decades, centuries, etc if your ranges can be that long)</li>
</ul>
<p>Unfortunately, our inconsistent time intervals mean that you end up with some cases that can have over 1 hundred intervals while others have at most 8 or 9. So you'll want to pick the size of your intervals such than you don't have more than 10-15 intervals at most (or less than 5 for that matter). Also, you could break from a strict definition of 2 times the next biggest interval if you think its easy to keep track of. For instance, you could use hours up to 3 days (72 hours) and weeks up to 4 months. A little trial and error might be necessary.</p>
<p>So to go back over, choose the interval type based on the size of your range, then choose the interval size by picking one of the "nice" numbers that will leave you with between 5 and about 15 tick marks. Or if you know and/or can control the actual number of pixels between tick marks you could put upper and lower bounds on how many pixels are acceptable between ticks (if they are spaced too far apart the graph may be hard to read, but if there are too many ticks the graph will be cluttered and your labels may overlap).</p> |
2,150,767 | How to start Solr automatically? | <p>At the moment I have to go to <code>/usr/java/apache-solr-1.4.0/example</code> and then do:</p>
<pre><code>java -jar start.jar
</code></pre>
<p>How do I get this to start automatically on boot? </p>
<p>I'm on a shared Linux server.</p> | 2,219,064 | 8 | 0 | null | 2010-01-27 22:25:02.547 UTC | 43 | 2016-01-14 13:58:40.917 UTC | 2012-12-29 08:07:11.423 UTC | null | 63,550 | null | 131,912 | null | 1 | 51 | linux|solr|shared|boot | 83,944 | <p>If you have root access to your machine, there are a number of ways to do this based on your system's initialization flow (init scripts, systemd, etc.)</p>
<p>But if you don't have root, <code>cron</code> has a clean and consistent way to execute programs upon reboot.</p>
<p>First, find out where java is located on your machine. The command below will tell you where it is:</p>
<pre><code>$ which java
</code></pre>
<p>Then, stick the following code into a shell script, replacing the java path below (/usr/bin) with the path you got from the above command.</p>
<pre><code>#!/bin/bash
cd /usr/java/apache-solr-1.4.0/example
/usr/bin/java -jar start.jar
</code></pre>
<p>You can save this script in some location (e.g., $HOME) as start.sh. Give it world execute permission (to simplify) by running the following command:</p>
<pre><code>$ chmod og+x start.sh
</code></pre>
<p>Now, test the script and ensure that it works correctly from the command line.</p>
<pre><code>$ ./start.sh
</code></pre>
<p>If all works well, you need to add it to one of your machine's startup scripts. The simplest way to do this is to add the following line to the end of <em>/etc/rc.local</em>. </p>
<pre><code># ... snip contents of rc.local ...
# Start Solr upon boot.
/home/somedir/start.sh
</code></pre>
<p>Alternatively, if you don't have permission to edit rc.local, then you can add it to your user crontab as so. First type the following on the commandline:</p>
<pre><code>$ crontab -e
</code></pre>
<p>This will bring up an editor. Add the following line to it:</p>
<pre><code>@reboot /home/somedir/start.sh
</code></pre>
<p>If your Linux system supports it (which it usually does), this will ensure that your script is run upon startup.</p>
<p>If I don't have any typos above, it should work out well for you. Let me know how it goes.</p> |
1,662,309 | Good examples of MVVM Template | <p>I am currently working with the Microsoft MVVM template and find the lack of detailed examples frustrating. The included ContactBook example shows very little Command handling and the only other example I've found is from an MSDN Magazine article where the concepts are similar but uses a slightly different approach and still lack in any complexity. Are there any decent MVVM examples that at least show basic CRUD operations and dialog/content switching?</p>
<hr>
<p>Everyone's suggestions were really useful and I will start compiling a list of good resources</p>
<p><strong>Frameworks/Templates</strong></p>
<ul>
<li><a href="http://wpf.codeplex.com/wikipage?title=WPF%20Model-View-ViewModel%20Toolkit&referringTitle=Home" rel="noreferrer">WPF Model-View-ViewModel Toolkit</a></li>
<li><a href="http://mvvmlight.codeplex.com/" rel="noreferrer">MVVM Light Toolkit</a></li>
<li><a href="http://www.codeplex.com/CompositeWPF" rel="noreferrer">Prism</a></li>
<li><a href="http://www.codeplex.com/caliburn" rel="noreferrer">Caliburn</a></li>
<li><a href="http://cinch.codeplex.com/" rel="noreferrer">Cinch</a></li>
</ul>
<p><strong>Useful Articles</strong></p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx" rel="noreferrer">WPF Apps With The Model-View-ViewModel Design Pattern</a></li>
<li><a href="http://blogs.msdn.com/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx" rel="noreferrer">Data Validation in .NET 3.5</a></li>
<li><a href="http://joshsmithonwpf.wordpress.com/2008/11/14/using-a-viewmodel-to-provide-meaningful-validation-error-messages/" rel="noreferrer">Using a ViewModel to Provide Meaningful Validation Error Messages</a></li>
<li><a href="http://peteohanlon.wordpress.com/2009/01/22/action-based-viewmodel-and-model-validation/" rel="noreferrer">Action based ViewModel and Model validation</a></li>
<li><a href="https://stackoverflow.com/questions/1667888/wpf-mvvm-dialog-example">Dialogs</a></li>
<li><a href="http://codingcontext.wordpress.com/2008/12/10/commandbindings-in-mvvm/" rel="noreferrer">Command Bindings in MVVM</a></li>
<li><a href="http://marlongrech.wordpress.com/2008/03/20/more-than-just-mvc-for-wpf/" rel="noreferrer">More than just MVC for WPF</a></li>
<li><a href="http://marlongrech.wordpress.com/2009/04/02/mvvm-mediator-acb-cool-wpf-app-intro/" rel="noreferrer">MVVM + Mediator Example
Application</a></li>
</ul>
<p><strong>Screencasts</strong></p>
<ul>
<li><a href="http://blog.lab49.com/archives/2650" rel="noreferrer">Jason Dolinger on Model-View-ViewModel</a></li>
</ul>
<p><strong>Additional Libraries</strong></p>
<ul>
<li><a href="http://marlongrech.wordpress.com/2009/04/16/mediator-v2-for-mvvm-wpf-and-silverlight-applications/" rel="noreferrer">WPF Disciples' improved Mediator Pattern implementation</a>(I highly recommend this for applications that have more complex navigation)</li>
<li><a href="http://blog.galasoft.ch/archive/2009/09/27/mvvm-light-toolkit-messenger-v2-beta.aspx" rel="noreferrer">MVVM Light Toolkit Messenger</a></li>
</ul> | 1,711,730 | 9 | 0 | null | 2009-11-02 16:32:58.43 UTC | 139 | 2019-02-15 08:26:43.607 UTC | 2017-05-23 10:31:20.83 UTC | null | -1 | null | 3,111 | null | 1 | 151 | wpf|mvvm | 70,205 | <p>Unfortunately there is no one great MVVM example app that does everything, and there are a lot of different approaches to doing things. First, you might want to get familiar with one of the app frameworks out there (Prism is a decent choice), because they provide you with convenient tools like dependency injection, commanding, event aggregation, etc to easily try out different patterns that suit you. </p>
<p>The prism release:
<br><a href="http://www.codeplex.com/CompositeWPF" rel="nofollow noreferrer">http://www.codeplex.com/CompositeWPF</a></p>
<p>It includes a pretty decent example app (the stock trader) along with a lot of smaller examples and how to's. At the very least it's a good demonstration of several common sub-patterns people use to make MVVM actually work. They have examples for both CRUD and dialogs, I believe. </p>
<p>Prism isn't necessarily for every project, but it's a good thing to get familiar with. </p>
<p><b>CRUD:</b>
This part is pretty easy, WPF two way bindings make it really easy to edit most data. The real trick is to provide a model that makes it easy to set up the UI. At the very least you want to make sure that your ViewModel (or business object) implements <code>INotifyPropertyChanged</code> to support binding and you can bind properties straight to UI controls, but you may also want to implement <code>IDataErrorInfo</code> for validation. Typically, if you use some sort of an ORM solution setting up CRUD is a snap.</p>
<p>This article demonstrates simple crud operations:
<a href="http://dotnetslackers.com/articles/wpf/WPFDataBindingWithLINQ.aspx" rel="nofollow noreferrer">http://dotnetslackers.com/articles/wpf/WPFDataBindingWithLINQ.aspx</a></p>
<p>It is built on LinqToSql, but that is irrelevant to the example - all that is important is that your business objects implement <code>INotifyPropertyChanged</code> (which classes generated by LinqToSql do). MVVM is not the point of that example, but I don't think it matters in this case.</p>
<p>This article demonstrates data validation
<br><a href="http://blogs.msdn.com/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx</a></p>
<p>Again, most ORM solutions generate classes that already implement <code>IDataErrorInfo</code> and typically provide a mechanism to make it easy to add custom validation rules.</p>
<p>Most of the time you can take an object(model) created by some ORM and wrap it in a ViewModel that holds it and commands for save/delete - and you're ready to bind UI straight to the model's properties. </p>
<p>The view would look like something like this (ViewModel has a property <code>Item</code> that holds the model, like a class created in the ORM):</p>
<pre><code><StackPanel>
<StackPanel DataContext=Item>
<TextBox Text="{Binding FirstName, Mode=TwoWay, ValidatesOnDataErrors=True}" />
<TextBox Text="{Binding LastName, Mode=TwoWay, ValidatesOnDataErrors=True}" />
</StackPanel>
<Button Command="{Binding SaveCommand}" />
<Button Command="{Binding CancelCommand}" />
</StackPanel>
</code></pre>
<p><b>Dialogs:</b>
Dialogs and MVVM are a bit tricky. I prefer to use a flavor of the Mediator approach with dialogs, you can read a little more about it in this StackOverflow question:
<br><a href="https://stackoverflow.com/questions/1667888/wpf-mvvm-dialog-example">WPF MVVM dialog example</a></p>
<p>My usual approach, which is not quite classic MVVM, can be summarized as follows:</p>
<p>A base class for a dialog ViewModel that exposes commands for commit and cancel actions, an event to lets the view know that a dialog is ready to be closed, and whatever else you will need in all of your dialogs. </p>
<p>A generic view for your dialog - this can be a window, or a custom "modal" overlay type control. At its heart it is a content presenter that we dump the viewmodel into, and it handles the wiring for closing the window - for example on data context change you can check if the new ViewModel is inherited from your base class, and if it is, subscribe to the relevant close event (the handler will assign the dialog result). If you provide alternative universal close functionality (the X button, for instance), you should make sure to run the relevant close command on the ViewModel as well. </p>
<p>Somewhere you need to provide data templates for your ViewModels, they can be very simple especially since you probably have a view for each dialog encapsulated in a separate control. The default data template for a ViewModel would then look something like this:</p>
<pre><code><DataTemplate DataType="{x:Type vmodels:AddressEditViewModel}">
<views:AddressEditView DataContext="{Binding}" />
</DataTemplate>
</code></pre>
<p>The dialog view needs to have access to these, because otherwise it won't know how to show the ViewModel, aside from the shared dialog UI its contents are basically this:</p>
<pre><code><ContentControl Content="{Binding}" />
</code></pre>
<p>The implicit data template will map the view to the model, but who launches it?</p>
<p>This is the not-so-mvvm part. One way to do it is to use a global event. What I think is a better thing to do is to use an event aggregator type setup, provided through dependency injection - this way the event is global to a container, not the whole app. Prism uses the unity framework for container semantics and dependency injection, and overall I like Unity quite a bit.</p>
<p>Usually, it makes sense for the root window to subscribe to this event - it can open the dialog and set its data context to the ViewModel that gets passed in with a raised event.</p>
<p>Setting this up in this way lets ViewModels ask the application to open a dialog and respond to user actions there without knowing anything about the UI so for the most part the MVVM-ness remains complete.</p>
<p>There are times, however, where the UI has to raise the dialogs, which can make things a bit trickier. Consider for example, if the dialog position depends on the location of the button that opens it. In this case you need to have some UI specific info when you request a dialog open. I generally create a separate class that holds a ViewModel and some relevant UI info. Unfortunately some coupling seems unavoidable there. </p>
<p>Pseudo code of a button handler that raises a dialog which needs element position data:</p>
<pre><code>ButtonClickHandler(sender, args){
var vm = DataContext as ISomeDialogProvider; // check for null
var ui_vm = new ViewModelContainer();
// assign margin, width, or anything else that your custom dialog might require
...
ui_vm.ViewModel = vm.SomeDialogViewModel; // or .GetSomeDialogViewModel()
// raise the dialog show event
}
</code></pre>
<p>The dialog view will bind to position data, and pass the contained ViewModel to the inner <code>ContentControl</code>. The ViewModel itself still doesn't know anything about the UI. </p>
<p>In general I don't make use of the <code>DialogResult</code> return property of the <code>ShowDialog()</code> method or expect the thread to block until the dialog is closed. A non-standard modal dialog doesn't always work like that, and in a composite environment you often don't really want an event handler to block like that anyhow. I prefer to let the ViewModels deal with this - the creator of a ViewModel can subscribe to its relevant events, set commit/cancel methods, etc, so there is no need to rely on this UI mechanism. </p>
<p>So instead of this flow:</p>
<pre><code>// in code behind
var result = somedialog.ShowDialog();
if (result == ...
</code></pre>
<p>I use:</p>
<pre><code>// in view model
var vm = new SomeDialogViewModel(); // child view model
vm.CommitAction = delegate { this.DoSomething(vm); } // what happens on commit
vm.CancelAction = delegate { this.DoNothing(vm); } // what happens on cancel/close (optional)
// raise dialog request event on the container
</code></pre>
<p>I prefer it this way because most of my dialogs are non-blocking pseudo-modal controls and doing it this way seems more straightforward than working around it. Easy to unit test as well.</p> |
1,935,139 | Using std::map<K,V> where V has no usable default constructor | <p>I have a symbol table implemented as a <code>std::map</code>. For the value, there is no way to legitimately construct an instance of the value type via a default constructor. However if I don't provide a default constructor, I get a compiler error and if I make the constructor assert, my program compile just fine but crashes inside of <code>map<K,V>::operator []</code> if I try to use it to add a new member.</p>
<p><em>Is there a way I can get C++ to disallow <code>map[k]</code> as an l-value at compile time (while allowing it as an r-value)?</em></p>
<hr>
<p>BTW: I know I can insert into the map using <code>Map.insert(map<K,V>::value_type(k,v))</code>.</p>
<hr>
<p><strong>Edit:</strong> several people have proposed solution that amount to altering the type of the value so that the map can construct one without calling the default constructor. <strong>This has exactly the opposite result of what I want</strong> because it hides the error until later. If I were willing to have that, I could simply remove the assert from the constructor. What I <em>Want</em> is to make the error happen even sooner; at compile time. However, it seems that there is no way to distinguish between r-value and l-value uses of <code>operator[]</code> so it seems what I want can't be done so I'll just have to dispense with using it all together.</p> | 1,935,670 | 10 | 0 | null | 2009-12-20 07:35:38.103 UTC | 6 | 2021-04-15 14:25:56.903 UTC | 2009-12-21 20:51:49.797 UTC | null | 1,343 | null | 1,343 | null | 1 | 57 | c++|stl|map|compile-time | 14,613 | <p>You can't make the compiler differentiate between the two uses of operator[], because they are the same thing. Operator[] returns a reference, so the assignment version is just assigning to that reference.</p>
<p>Personally, I never use operator[] for maps for anything but quick and dirty demo code. Use insert() and find() instead. Note that the make_pair() function makes insert easier to use:</p>
<pre><code>m.insert( make_pair( k, v ) );
</code></pre>
<hr>
<p>In C++11, you can also do</p>
<pre><code>m.emplace( k, v );
m.emplace( piecewise_construct, make_tuple(k), make_tuple(the_constructor_arg_of_v) );
</code></pre>
<p>even if the copy/move constructor is not supplied.</p> |
1,554,689 | Evaluate Expressions in Switch Statements in C# | <p>I have to implement the following in a <code>switch</code> statement:</p>
<pre><code>switch(num)
{
case 4:
// some code ;
break;
case 3:
// some code ;
break;
case 0:
// some code ;
break;
case < 0:
// some code ;
break;
}
</code></pre>
<p>Is it possible to have the switch statement evaluate <code>case < 0</code>? If not, how could I do that?</p> | 1,554,693 | 13 | 1 | null | 2009-10-12 13:48:15.017 UTC | 16 | 2021-06-23 12:00:57.847 UTC | 2009-10-12 13:57:00.523 UTC | null | 16,587 | null | 111,663 | null | 1 | 70 | c#|switch-statement | 111,588 | <p>Note: the answer below was written in 2009. Switch patterns were introduced in C# 7.</p>
<hr />
<p>You can't - switch/case is only for individual values. If you want to specify conditions, you need an "if":</p>
<pre><code>if (num < 0)
{
...
}
else
{
switch(num)
{
case 0: // Code
case 1: // Code
case 2: // Code
...
}
}
</code></pre> |
2,279,647 | How to emulate GPS location in the Android Emulator? | <p>I want to get longitude and latitude in Android emulator for testing.</p>
<p>Can any one guide me how to achieve this?</p>
<p>How do I set the location of the emulator to a test position?</p> | 2,279,827 | 35 | 2 | null | 2010-02-17 09:55:51.79 UTC | 179 | 2021-12-25 03:33:35.38 UTC | 2021-12-25 03:33:35.38 UTC | user10563627 | null | null | 249,991 | null | 1 | 497 | android|testing|geolocation|android-emulator|gps | 489,662 | <p>You can connect to the Emulator via Telnet. You then have a Emulator console that lets you enter certain data like geo fixes, network etc. </p>
<p>How to use the console is extensively explained <a href="https://developer.android.com/studio/run/emulator-console.html" rel="noreferrer">here</a>.
To connect to the console open a command line and type</p>
<pre><code>telnet localhost 5554
</code></pre>
<p>You then can use the geo command to set a latitude, longitude and if needed altitude on the device that is passed to all programs using the gps location provider. See the link above for further instructions. </p>
<p>The specific command to run in the console is</p>
<pre><code>geo fix <longitude value> <latitude value>
</code></pre>
<p>I found this site useful for finding a realistic lat/lng: <a href="http://itouchmap.com/latlong.html" rel="noreferrer">http://itouchmap.com/latlong.html</a></p>
<p>If you need more then one coordinate you can use a kml file with a route as well it is a little bit described in this <a href="http://developer.android.com/tools/debugging/ddms.html#ops-location" rel="noreferrer">article</a>. I can't find a better source at the moment.</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.