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
42,726,029
How to compile Less/Sass files in Visual Studio 2017+
<p>In VS &lt;= 2015 we can use a WebEssentials extension that takes care for compiling the less/sass files for us, but currently it does not support VS 2017. Is there a similar extension that can compile Less/Sass on build?</p>
42,726,151
5
0
null
2017-03-10 19:11:37.71 UTC
13
2022-04-18 01:16:53.23 UTC
2021-09-28 14:42:30.757 UTC
null
2,756,409
null
795,797
null
1
90
css|visual-studio|sass|visual-studio-2017|less
96,896
<p>WebEssentials is being split up into multiple extensions. I believe the functionality you want is now in the <a href="https://marketplace.visualstudio.com/items?itemName=MadsKristensen.WebCompiler" rel="noreferrer">Web Compiler</a> extension.</p> <p>If you want to do it without extensions, you could use a task runner like Gulp. See <a href="https://docs.microsoft.com/en-us/aspnet/core/client-side/using-gulp" rel="noreferrer">here</a> for a walkthrough of how to integrate Gulp tasks into VS.</p>
22,622,034
Frosted Glass Effect in JavaFX?
<p>I'm making an iOS7-themed JavaFX2/FXML project and I was wondering how I could make a Rectangle object have a iOS7-like frosted glass effect.</p> <p>I'd also like it to have a small shadow. This is tricky, since you might be able to see the shadow behind the semi-transparent object. I'd just like it to be present around the edges.</p> <p>Is this possible? Here's a picture showing the desired effect (not including the small drop-shadow):</p> <p><img src="https://i.stack.imgur.com/PfZka.png" alt="I&#39;d like it to look like this"></p> <p>UPDATE: <a href="https://stackoverflow.com/questions/22663681/javafx-effect-on-background">Here's</a> a continuation of the issue. This is going to look amazing :D.</p>
22,630,754
1
0
null
2014-03-24 22:38:14.233 UTC
19
2016-12-06 23:59:10.837 UTC
2017-05-23 11:53:02.63 UTC
null
-1
null
2,965,505
null
1
15
java|user-interface|ios7|javafx-2|blur
13,326
<p><strong>Sample Solution</strong></p> <p><a href="https://i.stack.imgur.com/5BeG3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5BeG3.png" alt="frost"></a></p> <p>Run the program below and scroll or swipe up to show the glass pane.</p> <p>The purpose of the program is just to sample the techniques involved not to act as a general purpose library for the frost effect.</p> <pre><code>import javafx.animation.*; import javafx.application.Application; import javafx.beans.property.*; import javafx.geometry.Rectangle2D; import javafx.scene.*; import javafx.scene.Node; import javafx.scene.control.Label; import javafx.scene.effect.*; import javafx.scene.image.*; import javafx.scene.input.ScrollEvent; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; // slides a frost pane in on scroll or swipe up; slides it out on scroll or swipe down. public class Frosty extends Application { private static final double W = 330; private static final double H = 590; private static final double BLUR_AMOUNT = 60; private static final Duration SLIDE_DURATION = Duration.seconds(0.4); private static final double UPPER_SLIDE_POSITION = 100; private static final Effect frostEffect = new BoxBlur(BLUR_AMOUNT, BLUR_AMOUNT, 3); @Override public void start(Stage stage) { DoubleProperty y = new SimpleDoubleProperty(H); Node background = createBackground(); Node frost = freeze(background, y); Node content = createContent(); content.setVisible(false); Scene scene = new Scene( new StackPane( background, frost, content ) ); stage.setScene(scene); stage.show(); addSlideHandlers(y, content, scene); } // create a background node to be frozen over. private Node createBackground() { Image backgroundImage = new Image( getClass().getResourceAsStream("ios-screenshot.png") ); ImageView background = new ImageView(backgroundImage); Rectangle2D viewport = new Rectangle2D(0, 0, W, H); background.setViewport(viewport); return background; } // create some content to be displayed on top of the frozen glass panel. private Label createContent() { Label label = new Label("The overlaid text is clear and the background below is frosty."); label.setStyle("-fx-font-size: 25px; -fx-text-fill: midnightblue;"); label.setEffect(new Glow()); label.setMaxWidth(W - 20); label.setWrapText(true); return label; } // add handlers to slide the glass panel in and out. private void addSlideHandlers(DoubleProperty y, Node content, Scene scene) { Timeline slideIn = new Timeline( new KeyFrame( SLIDE_DURATION, new KeyValue( y, UPPER_SLIDE_POSITION ) ) ); slideIn.setOnFinished(e -&gt; content.setVisible(true)); Timeline slideOut = new Timeline( new KeyFrame( SLIDE_DURATION, new KeyValue( y, H ) ) ); scene.setOnSwipeUp(e -&gt; { slideOut.stop(); slideIn.play(); }); scene.setOnSwipeDown(e -&gt; { slideIn.stop(); slideOut.play(); content.setVisible(false); }); // scroll handler isn't necessary if you have a touch screen. scene.setOnScroll((ScrollEvent e) -&gt; { if (e.getDeltaY() &lt; 0) { slideOut.stop(); slideIn.play(); } else { slideIn.stop(); slideOut.play(); content.setVisible(false); } }); } // create a frosty pane from a background node. private StackPane freeze(Node background, DoubleProperty y) { Image frostImage = background.snapshot( new SnapshotParameters(), null ); ImageView frost = new ImageView(frostImage); Rectangle filler = new Rectangle(0, 0, W, H); filler.setFill(Color.AZURE); Pane frostPane = new Pane(frost); frostPane.setEffect(frostEffect); StackPane frostView = new StackPane( filler, frostPane ); Rectangle clipShape = new Rectangle(0, y.get(), W, H); frostView.setClip(clipShape); clipShape.yProperty().bind(y); return frostView; } public static void main(String[] args) { launch(args); } } </code></pre> <p><strong>Source image</strong></p> <p>Save this image parallel to the Java source as a file named <code>ios-screenshot.png</code> and have your build system copy it to the target directory for the binary output of the build.</p> <p><a href="https://i.stack.imgur.com/1lDGo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1lDGo.png" alt="ios-screenshot"></a></p> <p><strong>Answers to additional questions</strong></p> <blockquote> <p>"JDK 8," would that happen to be a requirement of this?</p> </blockquote> <p>The sample code above is written against JDK 8. Porting it back to JDK 7 by replacing the lambda calls with anonymous inner classes is pretty trivial.</p> <p>In general, Java 7 is pretty dated for JavaFX work. I advise upgrading at your earliest convenience to work with a Java 8 minimum version.</p> <blockquote> <p>initiating your Panes with arguments</p> </blockquote> <p>More convenient constructors for most parent nodes is a <a href="http://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/StackPane.html#StackPane-javafx.scene.Node...-" rel="noreferrer">Java 8 feature</a>. You can easily convert the Java 8 format:</p> <pre><code> StackPane stack = new StackPane(child1, child2); </code></pre> <p>To Java 7:</p> <pre><code> StackPane stack = new StackPane(); stack.getChildren().setAll(child1, child2); </code></pre> <blockquote> <p>will this working if the desktop is behind a frosty pane? </p> </blockquote> <p>Not directly, you can create a new question for that.</p> <p><strong>Update: Related Questions</strong></p> <p>User created: <a href="https://stackoverflow.com/questions/22663681/javafx-effect-on-background">JavaFX effect on background</a> to allow the frosted effect to apply to a window over a desktop background.</p> <p>Another user created: <a href="https://stackoverflow.com/questions/25534204/how-do-i-create-a-javafx-transparent-stage-with-shadows-on-only-the-border">How do I create a JavaFX transparent stage with shadows on only the border?</a> to apply a halo shadow effect around this window.</p>
22,491,229
Load Testing and Benchmarking With siege vs wrk
<p>I have been looking around for tools that can help me to do load testing and benchmarking. I found a couple like:</p> <ul> <li><a href="https://github.com/wg/wrk" rel="nofollow noreferrer">https://github.com/wg/wrk</a></li> <li><a href="http://www.joedog.org/siege-home/" rel="nofollow noreferrer">http://www.joedog.org/siege-home/</a></li> <li><a href="https://github.com/rakyll/boom" rel="nofollow noreferrer">https://github.com/rakyll/boom</a></li> </ul> <p>I'm wondering if anyone has any experience with these tools and have any feedback pros vs cons of these tools. My load stress will include different test cases using DELETE, PUT, GET, POST, etc. headers.</p>
23,774,073
3
0
null
2014-03-18 21:16:59.83 UTC
39
2020-07-30 10:00:00.34 UTC
2020-07-30 10:00:00.34 UTC
null
366,904
null
1,881,450
null
1
23
benchmarking|performance-testing|stress-testing|siege|wrk
23,114
<p>I've used wrk and siege, siege is a really easy to use tool, but I'm not sure if you can test DELETE or PUT with siege.</p> <p>Wrk can use provided lua script to generate requests, so DELETE and PUT won't be a problem. AND wrk is a tool that can overpower NGINX static file server, so I think it's fast enough for general purpose load testing.</p> <p>I've never used boom or Yandex.tank suggested by @Direvius, basically because wrk is simple enough and fit our needs. But JMeter is too complex for me.</p>
39,074,678
how to end ng serve or firebase serve
<p>I've been doing web development with Angular2 and have been using both Angular2 and Firebase to run local servers. I haven't been able to find a command similar to typing quit when using Ionic to create a server, so I have to close the terminal tab each time. Is there a way to end the server and get my terminal tab back?</p> <p>Thanks.</p>
39,080,622
14
0
null
2016-08-22 08:30:59.117 UTC
30
2021-05-31 18:10:47.38 UTC
2018-11-29 12:12:10.64 UTC
null
4,000,674
null
3,543,254
null
1
151
angular|firebase|angular-cli|firebase-tools
271,661
<p>You can use the following command to end an ongoing process:</p> <p><kbd>ctrl</kbd> + <kbd>c</kbd></p>
39,247,411
How to add dynamically attribute in VueJs
<p>I'm using vuejs and I wanna know how to have control on inputs (add disabled attribute when necessary). Is there any way to add dynamically attribute in vuejs ? Below my <strong>Textfield component</strong> : </p> <pre><code> &lt;template&gt; &lt;input type="text" placeholder="{{ placeholder }}" v-model="value"&gt; &lt;/template&gt; &lt;script&gt; export default { props: { disabled: {type: Boolean, default: false}, placeholder: {type: String, default: ""}, value: {twoWay: true, default: ""} } } &lt;/script&gt; </code></pre> <p><strong>Usage</strong> :</p> <pre><code>&lt;textfield placeholder="Name" value.sync="el.name" :disabled="true"&gt;&lt;/textfield&gt; </code></pre>
39,247,482
7
0
null
2016-08-31 10:41:43.267 UTC
10
2022-07-15 20:07:46.513 UTC
2018-11-05 16:08:24.637 UTC
null
2,825,966
null
1,706,697
null
1
76
javascript|vue.js|dynamic|vue-component
135,249
<p>You can bind it to a variable using <code>v-bind:disabled=&quot;foo&quot;</code> or <code>:disabled=&quot;foo&quot;</code> for short:</p> <pre><code>&lt;textfield label=&quot;Name&quot; value.sync=&quot;el.name&quot; :disabled=&quot;myVar&quot;&gt; </code></pre> <p>Then in Vue you can just set <code>this.myVar = true</code> and it will disable the input.</p> <p>Edit: add this to your template:</p> <pre><code>&lt;template&gt; &lt;input type=&quot;text&quot; :disabled=&quot;disabled&quot; :placeholder=&quot;placeholder&quot; v-model=&quot;value&quot;&gt; &lt;/template&gt; </code></pre>
50,694,913
Angular 6 - httpClient passing basic auth in httpOptions
<p>I have a service in Angular 6 and I'm trying to change a record but it's saying I'm not authorized.</p> <p>Right now I have this:</p> <pre><code>const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; update(id, title, content) { const updateData = { id: id, title: title, content: content }; return this.http.put(`http://myurl/${id}`, updateData, httpOptions); } </code></pre> <p>My question is:</p> <p>How to I add basic authorization to my httpOptions or do I add it direct to the update method?</p>
50,694,988
7
0
null
2018-06-05 07:52:46.873 UTC
12
2021-10-07 12:35:53.03 UTC
null
null
null
user9855223
null
null
1
24
angular|typescript|angular6
65,567
<p>You can add basic authorization by appending it in headers, as below:</p> <pre><code>var headers_object = new HttpHeaders(); headers_object.append('Content-Type', 'application/json'); headers_object.append("Authorization", "Basic " + btoa("username:password")); const httpOptions = { headers: headers_object }; </code></pre>
20,902,583
AngularJs - Best-Practices on adding an active class on click (ng-repeat)
<p>I want to add an active class on click in a list, i tried the following code, but it adds the active class on all my items :/ :</p> <p><strong>HTML :</strong></p> <pre><code>&lt;div class="filters_ct" ng-controller="selectFilter"&gt; &lt;ul&gt; &lt;li ng-repeat="filters in filter" ng-click="select(item)" ng-class="{sel: item == selected}"&gt; &lt;span class="filters_ct_status"&gt;&lt;/span&gt; {{filters.time}} &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p><strong>Js :</strong></p> <pre><code> var filters = [ { 'filterId': 1, 'time': 'last 24 hours', }, { 'filterId': 2, 'time': 'all', }, { 'filterId': 3, 'time': 'last hour', }, { 'filterId': 4, 'time': 'today', }, { 'filterId': 5, 'time': 'yersteday', } ]; function selectFilter($scope) { $scope.items = ['filters']; $scope.selected = $scope.items[0]; $scope.select= function(item) { $scope.selected = item; }; } </code></pre> <p>Please, give me some help.</p> <p>Thanks</p>
20,903,079
4
0
null
2014-01-03 11:27:35.543 UTC
16
2015-03-12 05:38:59.15 UTC
2014-01-03 11:31:17.827 UTC
null
2,967,572
null
3,130,019
null
1
40
javascript|html|angularjs
78,945
<p>The best solution would be to target it via angulars <code>$index</code> which is the objects index/position in the array;</p> <p><strong>HTML</strong></p> <pre><code>&lt;div ng-app='app' class="filters_ct" ng-controller="selectFilter"&gt; &lt;ul&gt; &lt;li ng-repeat="filter in filters" ng-click="select($index)" ng-class="{sel: $index == selected}"&gt; &lt;span class="filters_ct_status"&gt;&lt;/span&gt; {{filter.time}} &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p><strong>JS/Controller</strong></p> <pre><code>var app = angular.module('app', []); app.controller('selectFilter', function($scope) { var filters = [ { 'filterId': 1, 'time': 'last 24 hours', }, { 'filterId': 2, 'time': 'all', }, { 'filterId': 3, 'time': 'last hour', }, { 'filterId': 4, 'time': 'today', }, { 'filterId': 5, 'time': 'yersteday', } ]; $scope.filters = filters; $scope.selected = 0; $scope.select= function(index) { $scope.selected = index; }; }); </code></pre> <p><strong><a href="http://jsfiddle.net/dcodesmith/3G7Kd/">JSFIDDLE</a></strong></p>
37,152,031
Numpy remove a dimension from np array
<p>I have some images I want to work with, the problem is that there are two kinds of images both are 106 x 106 pixels, some are in color and some are black and white. </p> <p>one with only two (2) dimensions:</p> <p>(106,106)</p> <p>and one with three (3)</p> <p>(106,106,3)</p> <p>Is there a way I can strip this last dimension?</p> <p>I tried np.delete, but it did not seem to work.</p> <pre><code>np.shape(np.delete(Xtrain[0], [2] , 2)) Out[67]: (106, 106, 2) </code></pre>
37,152,121
6
0
null
2016-05-11 02:20:55.47 UTC
9
2022-05-26 02:00:01.543 UTC
null
null
null
null
1,726,404
null
1
62
python|arrays|numpy
132,129
<p>You could use numpy's fancy indexing (an extension to Python's built-in slice notation):</p> <pre><code>x = np.zeros( (106, 106, 3) ) result = x[:, :, 0] print(result.shape) </code></pre> <p>prints</p> <pre><code>(106, 106) </code></pre> <p>A shape of <code>(106, 106, 3)</code> means you have 3 sets of things that have shape <code>(106, 106)</code>. So in order to "strip" the last dimension, you just have to pick one of these (that's what the fancy indexing does).</p> <p>You can keep any slice you want. I arbitrarily choose to keep the 0th, since you didn't specify what you wanted. So, <code>result = x[:, :, 1]</code> and <code>result = x[:, :, 2]</code> would give the desired shape as well: it all just depends on which slice you need to keep. </p>
31,254,435
How to select a portion of an image, crop, and save it using Swift?
<p>I am trying to create an iOS app using Swift to capture images and let the user save a selected portion of the image. In many cam based apps, I noticed that a rectangular frame is offered to let the users choose the desired portion. This involves either sliding the edges of the rectangle or moving the corners to fit the required area.</p> <p>Could you please guide me on how to implement that moveable rectangle and how to save only that piece of the image?</p>
31,323,789
5
0
null
2015-07-06 19:50:25.363 UTC
9
2020-06-17 06:45:55.217 UTC
null
null
null
null
3,681,985
null
1
18
ios|image|camera|uiimagepickercontroller|crop
38,095
<p>Found one more solution. This time it is in Swift. The solution looks elegant and the code relative to other such solutions is written in fewer number of lines.</p> <p>Here it is.. <a href="https://github.com/DuncanMC/CropImg" rel="nofollow noreferrer">https://github.com/DuncanMC/CropImg</a> Thanks to Duncan Champney for making his work available on github.</p>
5,762,836
What does "%1$#" mean when used in String.format (Java)?
<p>Language is Java. What does the <code>%1$#</code> mean in...</p> <pre><code>static String padright (String str, int num) { return String.format("%1$#" + num + "str", str); } </code></pre> <p>In the Java API, <code>String.format()</code> is used in this way:</p> <pre><code>public static String format(String format, Object... args) </code></pre> <p>So I think <code>%1$#</code> is a format specifier.</p> <p><code>%[flags][width][.precision][argsize]typechar</code> is the template.</p> <ul> <li>1 is a flag? </li> <li>$ is the width? </li> <li># is the precision? </li> <li>num is the argsize? </li> <li>"str" is the typechar? </li> </ul> <p>Is that right?</p>
5,762,867
1
0
null
2011-04-23 07:11:15.08 UTC
10
2015-06-15 23:05:47.51 UTC
2012-08-22 17:47:00.223 UTC
null
328,725
null
320,844
null
1
23
java|string|format|string-formatting
45,316
<p>Template:</p> <pre><code>%[argument_index$][flags][width][.precision]conversion </code></pre> <blockquote> <p>The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by "1$", the second by "2$", etc. </p> <p>The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion. </p> <p>The optional width is a decimal integer indicating the minimum number of characters to be written to the output. </p> <p>The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion. </p> <p>The required conversion is a character indicating how the argument should be formatted. The set of valid conversions for a given argument depends on the argument's data type.</p> </blockquote> <p><code>%1$</code> refers to the first substitution. In this case the string <code>str</code>. <code>#</code> is flag which says the result should use a conversion-dependent alternate form.</p> <p><a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html">http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html</a></p>
24,657,326
How to use git branch with Android Studio
<p>I am new to git. I have a very simple scenario for using git. I had my first release written with Android Studio. Now I want to work with some new features. What I did so far:</p> <ol> <li>enabled the VCS in my Android Studio </li> <li>created a local repository for my project from Android Studio</li> <li>pushed my local repository to my Bitbucket remote repository (<code>$git push -u origin master</code>)</li> </ol> <p>Now I am confused for the next step: create a feature branch. Should I create a branch in the local repository: </p> <pre><code>$ git branch --track feature1 origin/master </code></pre> <p>or should I create a new branch from the Bitbucket web portal, and clone the new branch?</p> <p>I also want to know how I can switch branches with Android Studio? For example, switch from feature branch to master branch to work on some hotfix. Do I need to use the Bitbucket plugin to checkout the project very time from the remote repository every time I switch branches or I can hot switch it inside Android Studio?</p> <p>Thanks!</p>
24,657,635
3
0
null
2014-07-09 15:08:39.18 UTC
20
2017-01-23 18:54:51.357 UTC
null
null
null
null
3,746,596
null
1
51
android|git|android-studio|git-branch
88,064
<p>You should be able to do this directly from Android studio.</p> <p>The easiest way is going to the <strong>bottom right corner</strong> of the Android Studio window where you should see the text "Git: branch name", in your case it should say "Git: master". Click on it and it will show a small menu consisting of the different branches available both locally and remotely, also there should be an option "+ New Branch" which will create a new branch for you and switch you to it. </p> <p>You should then be able to change some code, commit it and push it to remote. Merging and checking out branches can also be done from that same menu. The same thing can also be done from the menubar option "VCS"</p>
35,476,948
Remove empty or whitespace strings from array - Javascript
<p>I've found <a href="https://stackoverflow.com/a/19888749/4341456">this</a> beautiful method for removing empty strings - <code>arr = arr.filter(Boolean)</code>.</p> <p>But it doesn't seem to work on whitespace strings.</p> <pre><code>var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry']; arr = arr.filter(Boolean); // ["Apple", " ", "Mango", "Banana", " ", "Strawberry"] // should be ["Apple", "Mango", "Banana", "Strawberry"] </code></pre> <p>Is there a nice way to expand this method to removing whitespaces as well or should i trim the whitespaces by iterating the array first?</p>
35,476,997
9
0
null
2016-02-18 09:03:07.493 UTC
6
2020-12-09 03:55:55.48 UTC
2017-05-23 12:17:34.92 UTC
null
-1
null
4,341,456
null
1
22
javascript|arrays|regex|string|filter
50,536
<p><code>filter</code> works, but you need the right predicate function, which <code>Boolean</code> isn't (for this purpose):</p> <pre><code>// Example 1 - Using String#trim (added in ES2015, needs polyfilling in outdated // environments like IE) arr = arr.filter(function(entry) { return entry.trim() != ''; }); </code></pre> <p>or</p> <pre><code>// Example 2 - Using a regular expression instead of String#trim arr = arr.filter(function(entry) { return /\S/.test(entry); }); </code></pre> <p>(<code>\S</code> means &quot;a non-whitespace character,&quot; so <code>/\S/.test(...)</code> checks if a string contains at least one non-whitespace char.)</p> <p>or (perhaps a bit overboard and harder to read)</p> <pre><code>// Example 3 var rex = /\S/; arr = arr.filter(rex.test.bind(rex)); </code></pre> <hr /> <p>With an ES2015 (aka ES6) arrow function, that's even more concise:</p> <pre><code>// Example 4 arr = arr.filter(entry =&gt; entry.trim() != ''); </code></pre> <p>or</p> <pre><code>// Example 5 arr = arr.filter(entry =&gt; /\S/.test(entry)); </code></pre> <hr /> <p><strong>Live Examples</strong> -- The ES5 and earlier ones:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry']; console.log("Example 1: " + JSON.stringify(arr.filter(function(entry) { return entry.trim() != ''; }))); console.log("Example 2: " + JSON.stringify(arr.filter(function(entry) { return /\S/.test(entry); }))); var rex = /\S/; console.log("Example 3: " + JSON.stringify(arr.filter(rex.test.bind(rex))));</code></pre> </div> </div> </p> <p>...and the ES2015 (ES6) ones <em>(won't work if your browser doesn't support arrow functions yet)</em>:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = ['Apple', ' ', 'Mango', '', 'Banana', ' ', 'Strawberry']; console.log("Example 4: " + JSON.stringify(arr.filter(entry =&gt; !entry.trim() == ''))); console.log("Example 5: " + JSON.stringify(arr.filter(entry =&gt; /\S/.test(entry))));</code></pre> </div> </div> </p>
2,674,468
Making Jenkins (Hudson) job depend on another job
<p>I have two jobs:</p> <ol> <li><em>Upload</em> </li> <li><em>Launch-instance</em></li> </ol> <p>I want to make <em>Launch-instance</em> dependent on the other one, so that triggering <em>Launch-instance</em> automatically causes <em>Upload</em> to be run first. </p> <p>Can I achieve this using built-in Jenkins features or with a plugin?</p> <p>Note that I do <strong>not</strong> want <em>Upload</em> to always trigger <em>Launch-instance</em>, which is what the "Build after other projects are built" option on <em>Launch-instance</em> would do. What I want is more <strong>analogous to how <code>depends</code> attribute works in <a href="http://ant.apache.org/manual/targets.html" rel="noreferrer">Ant</a></strong>.</p>
7,496,963
5
2
null
2010-04-20 11:02:03.76 UTC
3
2019-07-23 17:13:59.793 UTC
2011-07-20 15:22:52.093 UTC
null
56,285
null
56,285
null
1
24
hudson|build-automation|jenkins
40,562
<p>Have you tried the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+Trigger+Plugin" rel="noreferrer">Parametrized Trigger Plugin</a>?</p> <p>You can use it as a build step, and mark the checkbox for "Block until the triggered projects finish their builds". That should be exactly what you are looking for.</p>
2,925,153
Can I pass an array as arguments to a method with variable arguments in Java?
<p>I'd like to be able to create a function like:</p> <pre><code>class A { private String extraVar; public String myFormat(String format, Object ... args){ return String.format(format, extraVar, args); } } </code></pre> <p>The problem here is that <code>args</code> is treated as <code>Object[]</code> in the method <code>myFormat</code>, and thus is a single argument to <code>String.format</code>, while I'd like every single <code>Object</code> in <code>args</code> to be passed as a new argument. Since <code>String.format</code> is also a method with variable arguments, this should be possible.</p> <p>If this is not possible, is there a method like <code>String.format(String format, Object[] args)</code>? In that case I could prepend <code>extraVar</code> to <code>args</code> using a new array and pass it to that method.</p>
2,925,300
5
3
null
2010-05-27 21:36:38.8 UTC
53
2021-02-11 04:58:04.027 UTC
2010-05-28 08:53:17.67 UTC
null
179,878
null
352,382
null
1
338
java|arrays|backwards-compatibility|variadic-functions
268,128
<p>The underlying type of a <a href="https://en.wikipedia.org/wiki/Variadic" rel="noreferrer">variadic</a> method <code>function(Object... args)</code> <em>is</em> <code>function(Object[] args)</code>. Sun added varargs in this manner to preserve backwards compatibility.</p> <p>So you should just be able to prepend <code>extraVar</code> to <code>args</code> and call <code>String.format(format, args)</code>.</p>
3,002,168
Should a service layer return view models for an MVC application?
<p>Say you have an ASP.NET MVC project and are using a service layer, such as in this contact manager tutorial on the asp.net site: <a href="http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs" rel="noreferrer">http://www.asp.net/mvc/tutorials/iteration-4-make-the-application-loosely-coupled-cs</a></p> <p>If you have viewmodels for your views, is the service layer the appropriate place to provide each viewmodel? For instance, in the service layer code sample there is a method</p> <pre><code> public IEnumerable&lt;Contact&gt; ListContacts() { return _repository.ListContacts(); } </code></pre> <p>If instead you wanted a IEnumerable, should it go in the service layer, or is there somewhere else that is the "correct" place? </p> <p>Perhaps more appropriately, if you have a separate viewmodel for each view associated with ContactController, should ContactManagerService have a separate method to return each viewmodel? If the service layer is not the proper place, where should viewmodel objects be initialized for use by the controller?</p>
3,002,303
6
3
null
2010-06-08 23:45:03.263 UTC
19
2020-11-10 08:14:49.93 UTC
2014-09-07 21:05:45.133 UTC
null
727,208
null
282,606
null
1
65
asp.net-mvc|service-layer|asp.net-mvc-viewmodel
22,227
<p>Generally, no. </p> <p>View models are intended to provide information to and from views and should be specific to the application, as opposed to the general domain. Controllers should orchestrate interaction with repositories, services (I am making some assumptions of the definition of service here), etc and handle building and validating view models, and also contain the logic of determining views to render.</p> <p>By leaking view models into a "service" layer, you are blurring your layers and now have possible application and presentation specific mixed in with what should focused with domain-level responsibilities.</p>
3,046,449
Calculate the contentsize of scrollview
<p>I'm having a scrollview as the detailedview of tableview cell. There are multiple views on the detailedview like labels, buttons etc. which I'm creating through interface builder. What I'm creating through interface builder is static. I'm putting everything on a view of height 480. </p> <p>A label on my detailedview is having dynamic text which can extend to any length. The problem is that I need to set the scrollview's content size for which I need its height. </p> <p>How shall I set scrollview's height provided the content is dynamic?</p>
3,080,525
7
0
null
2010-06-15 15:08:20.363 UTC
10
2019-04-17 03:32:45.603 UTC
null
null
null
null
227,943
null
1
7
iphone|uiscrollview
23,552
<p>You could try to use the scrollview'ers ContentSize. It worked for me and I had the same problem with the control using dynamic content.</p> <pre><code> // Calculate scroll view size float sizeOfContent = 0; int i; for (i = 0; i &lt; [myScrollView.subviews count]; i++) { UIView *view =[myScrollView.subviews objectAtIndex:i]; sizeOfContent += view.frame.size.height; } // Set content size for scroll view myScrollView.contentSize = CGSizeMake(myScrollView.frame.size.width, sizeOfContent); </code></pre> <p>I do this in the method called viewWillAppear in the controller for the view that holds the scrollview. It is the last thing i do before calling the viewDidLoad on the super.</p> <p>Hope it will solve your problem.</p> <p>//hannes</p>
2,806,693
Why isn't there a regular expression standard?
<p>I know there is the perl regex that is sort of a minor de facto standard, but why hasn't anyone come up with a universal set of standard symbols, syntax and behaviors?</p>
2,806,733
7
1
null
2010-05-10 21:48:54.873 UTC
7
2021-10-04 13:56:12.953 UTC
null
null
null
null
333,861
null
1
43
regex|standards
8,051
<p>There is a standard by <a href="http://en.wikipedia.org/wiki/Regular_expression#POSIX_.28Portable_Operating_System_Interface_.5Bfor_Unix.5D.29" rel="nofollow noreferrer">IEEE associated with the POSIX effort</a>. The real question is <em>&quot;why doesn't everyone follow it&quot;</em>? The answer is probably that it is not quite as complex as PCRE (Perl Compatible Regular Expression) with respect to greedy matching and what not.</p>
2,826,029
Passing additional variables from command line to make
<p>Can I pass variables to a GNU Makefile as command line arguments? In other words, I want to pass some arguments which will eventually become variables in the Makefile.</p>
2,826,178
8
0
null
2010-05-13 10:31:50.807 UTC
200
2022-02-04 07:13:51.273 UTC
2016-11-11 05:59:14.433 UTC
null
5,236,093
null
315,427
null
1
843
makefile|gnu|command-line-arguments
744,582
<p>You have several options to set up variables from outside your makefile:</p> <ul> <li><p><strong>From environment</strong> - each environment variable is transformed into a makefile variable with the same name and value.</p> <p>You may also want to set <code>-e</code> option (aka <code>--environments-override</code>) on, and your environment variables will override assignments made into makefile (unless these assignments themselves use the <a href="http://www.gnu.org/software/make/manual/make.html#Override-Directive" rel="noreferrer"><code>override</code> directive</a> . However, it's not recommended, and it's much better and flexible to use <code>?=</code> assignment (the conditional variable assignment operator, it only has an effect if the variable is not yet defined):</p> <pre><code>FOO?=default_value_if_not_set_in_environment </code></pre> <p>Note that certain variables are not inherited from environment:</p> <ul> <li><code>MAKE</code> is gotten from name of the script</li> <li><code>SHELL</code> is either set within a makefile, or defaults to <code>/bin/sh</code> (rationale: commands are specified within the makefile, and they're shell-specific).</li> </ul></li> <li><p><strong>From command line</strong> - <code>make</code> can take variable assignments as part of his command line, mingled with targets:</p> <pre><code>make target FOO=bar </code></pre> <p>But then <em>all assignments to <code>FOO</code> variable within the makefile will be ignored</em> unless you use the <a href="http://www.gnu.org/software/make/manual/make.html#Override-Directive" rel="noreferrer"><code>override</code> directive</a> in assignment. (The effect is the same as with <code>-e</code> option for environment variables).</p></li> <li><p><strong>Exporting from the parent Make</strong> - if you call Make from a Makefile, you usually shouldn't explicitly write variable assignments like this:</p> <pre><code># Don't do this! target: $(MAKE) -C target CC=$(CC) CFLAGS=$(CFLAGS) </code></pre> <p>Instead, better solution might be to export these variables. Exporting a variable makes it into the environment of every shell invocation, and Make calls from these commands pick these environment variable as specified above.</p> <pre><code># Do like this CFLAGS=-g export CFLAGS target: $(MAKE) -C target </code></pre> <p>You can also export <em>all</em> variables by using <code>export</code> without arguments.</p></li> </ul>
2,762,611
Why would a Delphi programmer use Lazarus as the IDE instead of using Delphi's IDE?
<p>I've been very happy with the Delphi IDE for programming in Delphi. </p> <p>But I've heard about the <a href="http://www.lazarus.freepascal.org/index.php?PHPSESSID=57d8d7652b6acbce0a69f0d93ae87ee9&amp;page=7" rel="noreferrer">Lazarus</a> programming environment, and I've also heard that some Delphi programmers use it instead of the Delphi IDE.</p> <p>What are the advantages that Lazarus has over the Delphi IDE, and why would, or should a Delphi programmer switch to it?</p> <hr> <p>The answers are leaving me with more questions than I had before. There seems to be some disagreement as to whether Lazarus can or cannot be used as an editor in developing Delphi code. I guess I thought you could leave everything in Delphi and just change IDEs. <a href="http://wiki.lazarus.freepascal.org/Lazarus_For_Delphi_Users" rel="noreferrer">The Lazarus for Delphi Users section of the Lazarus Wiki</a> says:</p> <blockquote> <p><strong>The first thing to do when converting a Delphi project</strong><br> Having opened Lazarus, you should go to to Tools and then Convert Delphi Project to Lazarus Project. This won't do everything for you, but nonetheless will take you a good deal of the way. Note that the Lazarus IDE's conversion tools are generally one-way conversions. If you need to retain Delphi compatibility so you can compile your project with both Delphi and Lazarus, consider converting your files with the <a href="http://wiki.lazarus.freepascal.org/XDev_Toolkit" rel="noreferrer">XDev Toolkit</a> instead.</p> </blockquote> <p>Because Lazarus is free is not a reason to switch, but does not penalize you in physical $'s for switching. (You will still have to invest your time to convert and learn. Time = $).</p> <p>My as-much-as-I-understand conclusions from your answers as to why someone might switch from Delphi to Lazarus: obviously it must be providing something that Delphi currently can't. Currently that is multiplatform support and possibly 64-bit support. Delphi did have Kylix at one time, but not Mac support. </p> <p>But with both of those and 64-bit promised soon by Embarcadero, you've answered my question by telling me there's no reason (at least for me) to switch.</p>
2,762,741
12
14
null
2010-05-04 03:21:26.863 UTC
11
2017-05-22 20:06:04.51 UTC
2010-05-05 00:00:32.553 UTC
null
30,176
null
30,176
null
1
47
delphi|ide|lazarus
47,775
<p>Well a Delphi programmer cannot use Lazarus to write Delphi code because Lazarus is not Delphi. Lazarus is actually an IDE and a bunch of Delphi-ish class libraries for Free Pascal. But note, things like Delphi's VCL is not there, and to be perfectly blunt the IDE and debugging experiences in Lazarus are pretty spotty, however it is free, so that counts for a lot.</p> <p>Bottom line, Delphi &lt;> Lazarus. Use Delphi if you want a great IDE and debugger huge 3rd party support and tech suport you are targeting MS Windows, plus you are willing to pay for it. Use Lazarus (free pascal) if you want a Free IDE that supports multiple platforms and has a Delphi-ish syntax.</p>
2,514,445
Turning off auto indent when pasting text into vim
<p>I am making the effort to learn Vim.</p> <p>When I paste code into my document from the clipboard, I get extra spaces at the start of each new line:</p> <pre><code>line line line </code></pre> <p>I know you can turn off auto indent but I can't get it to work because I have some other settings conflicting or something (which look pretty obvious in my .vimrc but don't seem to matter when I take them out). </p> <p>How do I turn off auto indenting when I paste code but still have vim auto indent when I am writing code? Here is my <code>.vimrc</code> file:</p> <pre><code>set expandtab set tabstop=2 set shiftwidth=2 set autoindent set smartindent set bg=dark set nowrap </code></pre>
2,514,520
25
4
null
2010-03-25 09:52:47.883 UTC
519
2022-06-01 08:11:59.553 UTC
2018-05-03 14:57:49.86 UTC
null
42,223
null
63,810
null
1
1,426
vim|configuration|editor|indentation|auto-indent
538,275
<p><strong>Update:</strong> Better answer here: <a href="https://stackoverflow.com/a/38258720/62202">https://stackoverflow.com/a/38258720/62202</a></p> <p>To turn off autoindent when you paste code, there's a special "paste" mode.</p> <p>Type </p> <pre><code>:set paste </code></pre> <p>Then paste your code. Note that the text in the tooltip now says <code>-- INSERT (paste) --</code>.</p> <p>After you pasted your code, turn off the paste-mode, so that auto-indenting when you type works correctly again.</p> <pre><code>:set nopaste </code></pre> <p>However, I always found that cumbersome. That's why I map <code>&lt;F3&gt;</code> such that it can switch between paste and nopaste modes <em>while editing the text!</em> I add this to <code>.vimrc</code></p> <pre><code>set pastetoggle=&lt;F3&gt; </code></pre>
23,853,553
Python Pandas: How to read only first n rows of CSV files in?
<p>I have a very large data set and I can't afford to read the entire data set in. So, I'm thinking of reading only one chunk of it to train but I have no idea how to do it. Any thought will be appreciated.</p>
23,853,569
2
0
null
2014-05-25 08:50:00.203 UTC
31
2022-07-22 05:45:04.277 UTC
2018-04-11 00:03:09.977 UTC
null
202,229
null
1,334,657
null
1
164
python|pandas|csv|file-io
210,619
<p>If you only want to read the first 999,999 (non-header) rows:</p> <pre><code>read_csv(..., nrows=999999) </code></pre> <p>If you only want to read rows 1,000,000 ... 1,999,999</p> <pre><code>read_csv(..., skiprows=1000000, nrows=999999) </code></pre> <p><strong><em>nrows</em></strong> : int, default None Number of rows of file to read. Useful for reading pieces of large files*</p> <p><strong><em>skiprows</em></strong> : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file</p> <p>and for large files, you'll probably also want to use chunksize:</p> <p><strong><em>chunksize</em></strong> : int, default None Return TextFileReader object for iteration</p> <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html" rel="noreferrer">pandas.io.parsers.read_csv documentation</a></p>
42,340,649
What is `cdk` in Angular Material 2 components
<p>In multiple places within angular material source, there are elements/ css classes that have <code>cdk</code> as their prefix.</p> <p>Does anyone know what the abbreviation for <code>cdk</code> in angular material context?</p>
42,370,299
4
0
null
2017-02-20 09:22:21.21 UTC
12
2019-03-12 04:41:39.89 UTC
2018-03-28 21:17:54.877 UTC
null
4,694,994
null
211,794
null
1
114
angular-material2|angular-cdk
36,587
<p>CDK is the short form of <code>component dev kit</code>. This signifies that these are general-purpose tools for building components that are not coupled to Material Design</p> <p>From the <a href="https://github.com/angular/material2/blob/master/CHANGELOG.md" rel="noreferrer">material2 changelog</a></p> <ul> <li>Several components in <code>core/</code>, such as Overlay, have had their prefix changed to <code>cdk-</code> (short for "component dev kit"). This signifies that these are general-purpose tools for building components that are not coupled to Material Design.The old selectors are still available as deprecated but will be removed in the next release. The CSS classes have been changed.</li> </ul> <p>For more info on how to use cdk components such as table, overlay, portal, portal host, e.t.c, you can find examples here:</p> <ol> <li><a href="https://github.com/angular/material2/tree/master/src/demo-app" rel="noreferrer">https://github.com/angular/material2/tree/master/src/demo-app</a></li> <li><a href="https://medium.com/@caroso1222/a-first-look-into-the-angular-cdk-67e68807ed9b" rel="noreferrer">https://medium.com/@caroso1222/a-first-look-into-the-angular-cdk-67e68807ed9b</a></li> </ol>
10,435,697
TestFlight rejecting build "get-task-allow" error
<p>So I'm using testflightapp to distribute an ad-hoc build.</p> <p>But I keep getting this message: 'Invalid Profile: distribution build entitlements must have get-task-allow set to false.'</p> <p>I don't have an entitlements file for my App, so XCode automatically produces one and includes it in the build. I unzip the App.ipa and open up the embedded.mobileprovision file and look at the entitlement dictionary.</p> <p>It looks like this:</p> <pre><code>&lt;key&gt;Entitlements&lt;/key&gt; &lt;dict&gt; &lt;key&gt;application-identifier&lt;/key&gt; &lt;string&gt;E9PBH9V8TB.*&lt;/string&gt; &lt;key&gt;get-task-allow&lt;/key&gt; &lt;false/&gt; &lt;key&gt;keychain-access-groups&lt;/key&gt; &lt;array&gt; &lt;string&gt;E9PBH9V8TB.*&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; </code></pre> <p>Anyone else experienced this before? I don't understand why I'm getting this error.</p>
10,436,081
11
0
null
2012-05-03 16:39:37.983 UTC
5
2016-07-04 18:41:45.94 UTC
2012-05-03 16:41:42.64 UTC
null
141,172
null
545,129
null
1
39
testflight
26,846
<p>Turns out the Code-Signing Identity in my build configuration didn't match the one I selected when I saved the archive for Ad-Hoc distribution.</p>
30,808,430
How to select columns from dataframe by regex
<p>I have a dataframe in python pandas. The structure of the dataframe is as the following: </p> <pre><code> a b c d1 d2 d3 10 14 12 44 45 78 </code></pre> <p>I would like to select the columns which begin with d. Is there a simple way to achieve this in python . </p>
30,808,571
7
0
null
2015-06-12 16:55:19.12 UTC
19
2021-10-25 18:09:45.85 UTC
2015-06-12 19:25:53.117 UTC
null
2,411,802
null
4,867,396
null
1
105
python|python-2.7|pandas
86,678
<p>You can use <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.filter.html" rel="noreferrer"><code>DataFrame.filter</code></a> this way:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame(np.array([[2,4,4],[4,3,3],[5,9,1]]),columns=['d','t','didi']) &gt;&gt; d t didi 0 2 4 4 1 4 3 3 2 5 9 1 df.filter(regex=("d.*")) &gt;&gt; d didi 0 2 4 1 4 3 2 5 1 </code></pre> <p>The idea is to select columns by <code>regex</code></p>
47,210,512
Using PyKalman on Raw Acceleration Data to Calculate Position
<p>This is my first question on Stackoverflow, so I apologize if I word it poorly. I am writing code to take raw acceleration data from an IMU and then integrate it to update the position of an object. Currently this code takes a new accelerometer reading every milisecond, and uses that to update the position. My system has a lot of noise, which results in crazy readings due to compounding error, even with the ZUPT scheme I implemented. I know that a Kalman filter is theoretically ideal for this scenario, and I would like to use the pykalman module instead of building one myself.</p> <p>My first question is, can pykalman be used in real time like this? From the documentation it looks to me like you have to have a record of all measurements and then perform the smooth operation, which would not be practical as I want to filter recursively every milisecond.</p> <p>My second question is, for the transition matrix can I only apply pykalman to the acceleration data by itself, or can I somehow include the double integration to position? What would that matrix look like?</p> <p>If pykalman is not practical for this situation, is there another way I can implement a Kalman Filter? Thank you in advance!</p>
48,069,535
1
0
null
2017-11-09 19:58:37.51 UTC
11
2020-08-19 13:55:35.013 UTC
null
null
null
null
8,915,916
null
1
17
python|noise|kalman-filter|pykalman
13,000
<p>You can use a Kalman Filter in this case, but your position estimation will strongly depend on the precision of your acceleration signal. The Kalman Filter is actually useful for a fusion of several signals. So error of one signal can be compensated by another signal. Ideally you need to use sensors based on different physical effects (for example an IMU for acceleration, GPS for position, odometry for velocity).</p> <p>In this answer I'm going to use readings from two acceleration sensors (both in X direction). One of these sensors is an expansive and precise. The second one is much cheaper. So you will see the sensor precision influence on the position and velocity estimations.</p> <p>You already mentioned the ZUPT scheme. I just want to add some notes: it is very important to have a good estimation of the pitch angle, to get rid of the gravitation component in your X-acceleration. If you use Y- and Z-acceleration you need both pitch and roll angles. </p> <p>Let's start with modelling. Assume you have only acceleration readings in X-direction. So your observation will look like </p> <p><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=z_%7Bk%7D%3D%5Bacc_%7Bk%7D%5E%7Bin%7D%5D" alt="formula"> </p> <p>Now you need to define the smallest data set, which completely describes your system in each point of time. It will be the system state.</p> <p><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=%5Chat%7Bx%7D%3D%5Cbegin%7Bbmatrix%7D%0Apos%5E%7Bst%7D%5C%5C%20%0Avel%5E%7Bst%7D%5C%5C%20%0Aacc%5E%7Bst%7D%0A%5Cend%7Bbmatrix%7D" alt="formula"> </p> <p>The mapping between the measurement and state domains is defined by the observation matrix:</p> <p><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=H%5Ccdot%20x%3Dz" alt="formula"></p> <p><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=H%3D%5Cbegin%7Bbmatrix%7D%0A0%20%26%200%20%26%201%0A%5Cend%7Bbmatrix%7D" alt="formula"></p> <p>Now you need to describe the system dynamics. According to this information the Filter will predict a new state based on the previous one. </p> <p><img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=F%3D%5Cbegin%7Bbmatrix%7D%0A1%20%26%20dt%20%26%200.5%5Ccdot%20dt%5E%7B2%7D%5C%5C%20%0A0%20%26%201%20%26%20dt%5C%5C%20%0A0%20%26%200%20%26%201%0A%5Cend%7Bbmatrix%7D" alt="formula"></p> <p>In my case dt=0.01s. Using this matrix the Filter will integrate the acceleration signal to estimate the velocity and position.</p> <p>The observation covariance R can be described by the variance of your sensor readings. In my case I have only one signal in my observation, so the observation covariance is equal to the variance of the X-acceleration (the value can be calculated based on your sensors datasheet).</p> <p>Through the transition covariance Q you describe the system noise. The smaller the matrix values, the smaller the system noise. The Filter will become stiffer and the estimation will be delayed. The weight of the system's past will be higher compared to new measurement. Otherwise the filter will be more flexible and will react strongly on each new measurement.</p> <p>Now everything is ready to configure the Pykalman. In order to use it in real time, you have to use the <strong>filter_update</strong> function.</p> <pre><code>from pykalman import KalmanFilter import numpy as np import matplotlib.pyplot as plt load_data() # Data description # Time # AccX_HP - high precision acceleration signal # AccX_LP - low precision acceleration signal # RefPosX - real position (ground truth) # RefVelX - real velocity (ground truth) # switch between two acceleration signals use_HP_signal = 1 if use_HP_signal: AccX_Value = AccX_HP AccX_Variance = 0.0007 else: AccX_Value = AccX_LP AccX_Variance = 0.0020 # time step dt = 0.01 # transition_matrix F = [[1, dt, 0.5*dt**2], [0, 1, dt], [0, 0, 1]] # observation_matrix H = [0, 0, 1] # transition_covariance Q = [[0.2, 0, 0], [ 0, 0.1, 0], [ 0, 0, 10e-4]] # observation_covariance R = AccX_Variance # initial_state_mean X0 = [0, 0, AccX_Value[0, 0]] # initial_state_covariance P0 = [[ 0, 0, 0], [ 0, 0, 0], [ 0, 0, AccX_Variance]] n_timesteps = AccX_Value.shape[0] n_dim_state = 3 filtered_state_means = np.zeros((n_timesteps, n_dim_state)) filtered_state_covariances = np.zeros((n_timesteps, n_dim_state, n_dim_state)) kf = KalmanFilter(transition_matrices = F, observation_matrices = H, transition_covariance = Q, observation_covariance = R, initial_state_mean = X0, initial_state_covariance = P0) # iterative estimation for each new measurement for t in range(n_timesteps): if t == 0: filtered_state_means[t] = X0 filtered_state_covariances[t] = P0 else: filtered_state_means[t], filtered_state_covariances[t] = ( kf.filter_update( filtered_state_means[t-1], filtered_state_covariances[t-1], AccX_Value[t, 0] ) ) f, axarr = plt.subplots(3, sharex=True) axarr[0].plot(Time, AccX_Value, label="Input AccX") axarr[0].plot(Time, filtered_state_means[:, 2], "r-", label="Estimated AccX") axarr[0].set_title('Acceleration X') axarr[0].grid() axarr[0].legend() axarr[0].set_ylim([-4, 4]) axarr[1].plot(Time, RefVelX, label="Reference VelX") axarr[1].plot(Time, filtered_state_means[:, 1], "r-", label="Estimated VelX") axarr[1].set_title('Velocity X') axarr[1].grid() axarr[1].legend() axarr[1].set_ylim([-1, 20]) axarr[2].plot(Time, RefPosX, label="Reference PosX") axarr[2].plot(Time, filtered_state_means[:, 0], "r-", label="Estimated PosX") axarr[2].set_title('Position X') axarr[2].grid() axarr[2].legend() axarr[2].set_ylim([-10, 1000]) plt.show() </code></pre> <p>When using the better IMU-sensor, the estimated position is exactly the same as the ground truth:</p> <p><a href="https://i.stack.imgur.com/6qjum.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6qjum.png" alt="position estimation based on a good IMU-sensor"></a></p> <p>The cheaper sensor gives significantly worse results:</p> <p><a href="https://i.stack.imgur.com/sxWhh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sxWhh.png" alt="position estimation based on a cheap IMU-sensor"></a></p> <p>I hope I could help you. If you have some questions, I will try to answer them.</p> <p><strong>UPDATE</strong></p> <p>If you want to experiment with different data you can generate them easily (unfortunately I don't have the original data any more).</p> <p>Here is a simple matlab script to generate reference, good and poor sensor set.</p> <pre><code>clear; dt = 0.01; t=0:dt:70; accX_var_best = 0.0005; % (m/s^2)^2 accX_var_good = 0.0007; % (m/s^2)^2 accX_var_worst = 0.001; % (m/s^2)^2 accX_ref_noise = randn(size(t))*sqrt(accX_var_best); accX_good_noise = randn(size(t))*sqrt(accX_var_good); accX_worst_noise = randn(size(t))*sqrt(accX_var_worst); accX_basesignal = sin(0.3*t) + 0.5*sin(0.04*t); accX_ref = accX_basesignal + accX_ref_noise; velX_ref = cumsum(accX_ref)*dt; distX_ref = cumsum(velX_ref)*dt; accX_good_offset = 0.001 + 0.0004*sin(0.05*t); accX_good = accX_basesignal + accX_good_noise + accX_good_offset; velX_good = cumsum(accX_good)*dt; distX_good = cumsum(velX_good)*dt; accX_worst_offset = -0.08 + 0.004*sin(0.07*t); accX_worst = accX_basesignal + accX_worst_noise + accX_worst_offset; velX_worst = cumsum(accX_worst)*dt; distX_worst = cumsum(velX_worst)*dt; subplot(3,1,1); plot(t, accX_ref); hold on; plot(t, accX_good); plot(t, accX_worst); hold off; grid minor; legend('ref', 'good', 'worst'); title('AccX'); subplot(3,1,2); plot(t, velX_ref); hold on; plot(t, velX_good); plot(t, velX_worst); hold off; grid minor; legend('ref', 'good', 'worst'); title('VelX'); subplot(3,1,3); plot(t, distX_ref); hold on; plot(t, distX_good); plot(t, distX_worst); hold off; grid minor; legend('ref', 'good', 'worst'); title('DistX'); </code></pre> <p>The simulated data looks pretty the same like the data above.</p> <p><a href="https://i.stack.imgur.com/fzv7I.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fzv7I.png" alt="simulated data for different sensor variances"></a></p>
32,900,809
How to suppress "function is never used" warning for a function used by tests?
<p>I'm writing a program in Rust and I have some tests for it. I wrote a helper function for these tests, but whenever I build using <code>cargo build</code> it warns me that the function is never used:</p> <blockquote> <p>warning: function is never used: ... #[warn(dead_code)] on by default</p> </blockquote> <p>How I can mark this function as used so as not to get the warnings?</p>
32,908,553
7
1
null
2015-10-02 05:00:13.56 UTC
8
2021-12-11 21:01:09.5 UTC
2015-10-02 14:58:59.217 UTC
null
155,423
null
1,636,594
null
1
60
rust
25,635
<h3>Specific question</h3> <blockquote> <p>How I can mark this function as used so as not to get the warnings?</p> </blockquote> <p>The Rust compiler runs many <a href="https://en.wikipedia.org/wiki/Lint_(software)" rel="noreferrer">lints</a> to warn you about possible issues in your code and the <code>dead_code</code> lint is one of them. It can be very useful in pointing out mistakes when code is complete, but may also be a nuisance at earlier stages. Often, this can be solved by either deleting unused code, or by marking a public method. However, all lints can be turned off by <code>allow</code>ing them, and your error message (<code>#[warn(dead_code)] on by default</code>) contains the name of the lint you could disable.</p> <pre><code>#[allow(dead_code)] fn my_unused_function() {} </code></pre> <h3>Alternative for testing</h3> <blockquote> <p>I wrote a helper function for these tests, but whenever I build using <code>cargo build</code> it warns me that the function is never used.</p> </blockquote> <p>This happens to be a special case, which is that code that is only used for testing isn't needed in the real executable and should probably not be included.</p> <p>In order to optionally disable compilation of test code, you can mark it accordingly using the <a href="https://doc.rust-lang.org/book/conditional-compilation.html" rel="noreferrer"><code>cfg</code> attribute</a> with the <code>test</code> profile.</p> <pre><code>#[cfg(test)] fn my_test_specific_function() {} </code></pre> <p>When marked in this way, the compiler knows to ignore the method during compilation. This is similar to commonly used <code>ifdef</code> usage in other languages like C or C++, where you are telling a preprocessor to ignore the enclosed code unless <code>TESTING</code> is defined.</p> <pre class="lang-c prettyprint-override"><code>#ifdef TESTING ... #endif </code></pre>
20,984,183
Best way to preload images with Angular.js
<p>Angular's ng-src keeps previous model until it preloads image internally. I am using different image for the banner on each page, when I switch routes, i change main view, leaving header view as it is, just changing bannerUrl model when I have it. </p> <p>This is resulting in seeing previous banner image while new one is loading. </p> <p>I was surprised that there's no directive for it yet, but I wanted to make a discussion before trying to build one.</p> <p>What I want to do I think is have banner model on custom attribute. like:</p> <pre><code>&lt;img preload-src="{{bannerUrl}}" ng-src="{{preloadedUrl}}"&gt; </code></pre> <p>Then $scope.watch for bannerUrl change, and as soon as it changes, replace ng-src with loader spinner first, and then create temproary img dom element, preload image from preload-src and then assing it to preloadUrl.</p> <p>Need to think how to handle multiple images too for galleries for example.</p> <p>Does anyone have any input on it? or maybe someone can point me to existing code?</p> <p>I've seen existing code on github that uses background-image - but that doesn't work for me as I need dynamic height/width as my app is responsive, and I cannot do it with background-image.</p> <p>Thank you</p>
20,990,053
9
2
null
2014-01-07 23:31:35.89 UTC
19
2017-09-15 04:06:04.29 UTC
null
null
null
null
3,001,647
null
1
26
javascript|angularjs|image-preloader
53,026
<p>Having the 2 urls on the directive seems a touch overcomplicated. What I think is better is to write a directive that works like:</p> <pre><code>&lt;img ng-src="{{bannerUrl}}" spinner-on-load /&gt; </code></pre> <p>And the directive can watch <code>ng-src</code> and (for example) set visibility:false with a spinner until the image has loaded. So something like:</p> <pre><code>scope: { ngSrc: '=' }, link: function(scope, element) { element.on('load', function() { // Set visibility: true + remove spinner overlay }); scope.$watch('ngSrc', function() { // Set visibility: false + inject temporary spinner overlay }); } </code></pre> <p>This way the element behaves very much like a standard img with an <code>ng-src</code> attribute, just with a bit of extra behaviour bolted on.</p> <p><a href="http://jsfiddle.net/2CsfZ/47/">http://jsfiddle.net/2CsfZ/47/</a></p>
21,916,870
Apply [Authorize] attribute implicitly to all Web API controllers
<p>My application is setup where all requests except login must be 'authorized' using the authorization attribute in Web API. E.g.</p> <pre><code> [Authorize] [HttpGet, Route("api/account/profile")] public ApplicationUser Profile() { return userModel; } </code></pre> <p>and only the login needs to not authorize since thats where you get the token ;)</p> <pre><code>[AllowAnonymous] [HttpPost, Route("api/account/login")] public async Task&lt;IHttpActionResult&gt; Login(LoginViewModel model) { .... } </code></pre> <p>instead of having to add the <code>[Authorize]</code> attribute to ALL my routes, is there a way to set it globally?</p>
21,917,732
5
0
null
2014-02-20 18:49:11.46 UTC
11
2021-09-03 12:35:23.907 UTC
2018-01-17 12:15:59.897 UTC
null
1,023,618
null
1,288,340
null
1
37
c#|.net|asp.net-web-api|asp.net-web-api2
30,904
<p>You have two options</p> <ol> <li><p>Controller level by decorating your controller with authorize attribute. </p> <pre><code>[Authorize] [RoutePrefix("api/account")] public class AccountController : ApiController { </code></pre></li> <li><p>You can also set it global level to all routes, in <code>Register</code> method of WebApiConfig.cs file</p> <pre><code> config.Filters.Add(new AuthorizeAttribute()); </code></pre></li> </ol>
28,041,953
Create table with date column
<p>I want to create a student table with column 'student_birthday' and its format should be dd-mm-yy.</p> <pre><code>create table `student`.`studentinfo`( `student_id` int(10) not null auto_increment, `student_name` varchar(45) not null, `student_surname` varchar(45) not null, `student_birthday` date(???), (some lines of code) primary key(student_id)); </code></pre> <p>what should be inputted in the (???) to get the right format above?</p>
28,042,040
3
0
null
2015-01-20 09:38:23.297 UTC
1
2019-12-06 10:15:13.92 UTC
2015-01-22 18:27:29.497 UTC
null
114,823
null
2,531,488
null
1
15
mysql
102,355
<p>Just use "DATE" without the brackets. The brackets are only needed for certain column types where you want to specify the maximum number of bytes/characters that can be stored.</p> <p>For MySQL, it's documented at <a href="https://dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html" rel="noreferrer">https://dev.mysql.com/doc/refman/5.7/en/date-and-time-types.html</a></p>
28,281,653
How to listen to global hotkeys with Swift in a macOS app?
<p>I'm trying to have a handler in my Mac OS X app written in Swift for a global (system-wide) hotkey combo but I just cannot find proper documentation for it. I've read that I'd have to mess around in some legacy Carbon API for it, is there no better way? Can you show me some proof of concept Swift code? Thanks in advance!</p>
34,864,422
7
1
null
2015-02-02 15:58:22.893 UTC
27
2022-01-22 19:04:44.5 UTC
2022-01-03 02:11:00.613 UTC
null
64,949
null
740,002
null
1
49
swift|macos|cocoa|keyboard-shortcuts
13,580
<p>Since Swift 2.0, you can now pass a function pointer to C APIs.</p> <pre><code>var gMyHotKeyID = EventHotKeyID() gMyHotKeyID.signature = OSType("swat".fourCharCodeValue) gMyHotKeyID.id = UInt32(keyCode) var eventType = EventTypeSpec() eventType.eventClass = OSType(kEventClassKeyboard) eventType.eventKind = OSType(kEventHotKeyPressed) // Install handler. InstallEventHandler(GetApplicationEventTarget(), {(nextHanlder, theEvent, userData) -&gt; OSStatus in var hkCom = EventHotKeyID() GetEventParameter(theEvent, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID), nil, sizeof(EventHotKeyID), nil, &amp;hkCom) // Check that hkCom in indeed your hotkey ID and handle it. }, 1, &amp;eventType, nil, nil) // Register hotkey. let status = RegisterEventHotKey(UInt32(keyCode), UInt32(modifierKeys), gMyHotKeyID, GetApplicationEventTarget(), 0, &amp;hotKeyRef) </code></pre>
8,461,005
How to force the form focus?
<p>How can I force the focus of an form? <code>.Focus()</code> is not working for me.</p> <pre><code>private void button1_Click(object sender, EventArgs e) { var form = new loginForm(); if (Application.OpenForms[form.Name] == null) { form.Show(); } else { form.Focus(); } } </code></pre> <p>What am I doing wrong?</p>
8,461,035
5
0
null
2011-12-11 00:25:24.45 UTC
2
2020-03-11 13:48:31.893 UTC
2011-12-11 01:30:00.33 UTC
null
825,024
null
800,123
null
1
14
c#|.net|winforms|focus
77,683
<p>it should be </p> <pre><code>private void button1_Click(object sender, EventArgs e) { var form = new loginForm(); if (Application.OpenForms[form.Name] == null) { form.Show(); } else { Application.OpenForms[form.Name].Focus(); } } </code></pre>
8,593,303
Could not connect to SMTP host: email-smtp.us-east-1.amazonaws.com, port: 465, response: -1
<p>I am trying to send email with Amazon's SES/SMTP and I am getting the following error:</p> <p><em><strong>javax.mail.MessagingException: Could not connect to SMTP host: email-smtp.us-east-1.amazonaws.com, port: 465, response: -1</em></strong></p> <p>Here is how I am trying to send the mail:</p> <p>Spring mail sender config:</p> <pre><code>&lt;bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt; &lt;property name="host" value="${mail.server}"/&gt; &lt;property name="port" value="${mail.port}"/&gt; &lt;property name="username" value="${aws.mail.smtp.user}"/&gt; &lt;property name="password" value="${aws.mail.smtp.password}"/&gt; &lt;property name="javaMailProperties"&gt; &lt;props&gt; &lt;!-- Use SMTP-AUTH to authenticate to SMTP server --&gt; &lt;prop key="mail.smtp.auth"&gt;true&lt;/prop&gt; &lt;!-- Use TLS to encrypt communication with SMTP server --&gt; &lt;prop key="mail.smtp.starttls.enable"&gt;true&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>with: </p> <pre><code>mail.server =email-smtp.us-east-1.amazonaws.com mail.port = 465 </code></pre>
8,623,335
7
0
null
2011-12-21 16:46:44.117 UTC
7
2019-09-13 17:37:01.81 UTC
2012-01-25 09:09:29.833 UTC
null
45,773
null
536,299
null
1
14
smtp|amazon-web-services|ssl|amazon-ses
40,255
<p>With amazon SES, configuration needs to be as follows:</p> <pre><code>&lt;prop key="mail.smtp.auth"&gt;true&lt;/prop&gt; &lt;prop key="mail.smtp.ssl.enable"&gt;true&lt;/prop&gt; </code></pre> <p>instead of:</p> <pre><code>&lt;prop key="mail.smtp.auth"&gt;true&lt;/prop&gt; &lt;prop key="mail.smtp.starttls.enable"&gt;true&lt;/prop&gt; </code></pre> <p>as hinted by dave.</p> <p><strong>EDIT</strong>: Please use this solution: <a href="https://stackoverflow.com/a/8928559/536299">https://stackoverflow.com/a/8928559/536299</a></p>
8,707,586
Symfony 2 Forward Request passing along GET/POST params
<p>Is it possible to forward a request, passing along all GET/POST params? </p> <p>I think if I just do </p> <pre><code>$this-&gt;forward('dest') </code></pre> <p>I will go to <code>dest</code> without any GET/POST params?</p> <p><strong>UPDATE</strong></p> <p>My objective is actually to have a controller action like <code>addSomething</code> that takes checks that the user has the sufficient "items" to add something. Then forward the request to the approperiate controller to continue the actual adding of adding{Type}Something</p> <p>Or would getting a "checking" service in all controllers that does the checking be more appropriate? Anyways, I think its informative to know how to forward to a controller action with all params</p>
8,713,594
4
0
null
2012-01-03 03:25:44.56 UTC
2
2017-12-20 20:53:44.413 UTC
2012-01-03 03:38:32.053 UTC
null
292,291
null
292,291
null
1
15
php|symfony|forwarding
39,034
<p>I don't see any reason here to forward the request back through the kernel. You can go the route of encapsulating this logic in a checker service, as you've suggested, or you may be able to create a <code>kernel.request</code> listener that runs after the router listener and applies the <code>_controller</code> attribute only if your conditions are met.</p> <p>For example, this <code>routing.yml</code>:</p> <pre><code>some_route: pattern: /xyz defaults: { _controller_candidate: "FooBundle:Bar:baz" } </code></pre> <p>And this listener:</p> <pre><code>class MyListener { public function onKernelRequest($event) { $request = $event-&gt;getRequest(); if (!$controller = $request-&gt;attributes-&gt;get('_controller_candidiate')) { return; } if (/* your logic... */) { $request-&gt;attributes-&gt;set('_controller', $controller'); } } } </code></pre> <p>Configured to run <em>after</em> the core router listener:</p> <pre><code>services: my_listener: class: MyListener tags: - name: kernel.event_listener event: kernel.request priority: -10 </code></pre> <p>The priority of the core router listener is <code>0</code> in Symfony 2.0 and <code>32</code> in Symfony 2.1. In either case, a priority of <code>-10</code> should work.</p> <p>I'm curious to see if this works :)</p>
8,985,053
NSSet to NSArray casting calling objectAtIndex?
<p>I'm trying to update an MKMapView by removing all annotations outside the visible area, and adding and removing some annotations inside the visible area. This is my code:</p> <pre><code>NSSet *visibleAnnotations = [mapView annotationsInMapRect:[mapView visibleMapRect]]; NSSet *allAnnotations = [NSSet setWithArray:[mapView annotations]]; NSMutableSet *nonVisibleAnnotations = [NSMutableSet setWithSet:allAnnotations]; [nonVisibleAnnotations minusSet:visibleAnnotations]; [mapView removeAnnotations:(NSArray *)nonVisibleAnnotations]; NSMutableSet *newAnnotations = [NSMutableSet setWithArray:[_zoomLevels objectAtIndex:clusterLevel]]; [newAnnotations minusSet:visibleAnnotations]; [mapView addAnnotations:(NSArray *)newAnnotations]; </code></pre> <p>This gives me the error <strong>-[__NSCFSet objectAtIndex:]: unrecognized selector sent to instance 0x13cd40</strong> after the final line in which I cast newAnnotations to an NSArray then add the annotations. Is there something about casting an array to a set that causes this? If so, is there a way round it?</p>
8,985,088
6
0
null
2012-01-24 10:13:27.017 UTC
7
2019-11-27 14:49:33.097 UTC
null
null
null
null
49,128
null
1
50
objective-c|ios|nsarray|mkmapview|nsset
52,726
<p>Despite you're casting <code>NSMutableSet</code> to <code>NSArray</code>, that simple casting won't make <code>NSSet</code> class respond to <code>NSArray</code>'s messages. You have to fill an actual <code>NSArray</code> with the elements of the <code>NSSet</code> like this:</p> <pre><code>NSArray *array = [theNsSet allObjects]; </code></pre>
39,652,122
How to list all category from custom post type?
<p>I have a post type called 'dining' and has a taxonomy called 'dining-category'.</p> <p>What I want to do is, I want to display all the category from post type 'dining' in my footer area.</p>
39,652,814
4
0
null
2016-09-23 03:31:01.407 UTC
4
2021-03-30 05:13:17.6 UTC
2016-09-23 03:38:46.863 UTC
null
616,443
null
3,199,555
null
1
14
wordpress
75,965
<p>In WordPress 4.6 <code>get_terms</code> is deprecated. So there is an alternate of this (<code>get_categories</code>) <a href="https://developer.wordpress.org/reference/functions/get_categories/" rel="noreferrer">Read this</a></p> <p><strong>And here is Example code:</strong></p> <pre><code>&lt;?php $args = array( 'taxonomy' =&gt; 'dining-category', 'orderby' =&gt; 'name', 'order' =&gt; 'ASC' ); $cats = get_categories($args); foreach($cats as $cat) { ?&gt; &lt;a href="&lt;?php echo get_category_link( $cat-&gt;term_id ) ?&gt;"&gt; &lt;?php echo $cat-&gt;name; ?&gt; &lt;/a&gt; &lt;?php } ?&gt; </code></pre> <p>Hope this will help you.</p>
13,159,272
How to export data in CSV format using Java?
<p>The reason may be the the short of knowledge in java :( ,so I'm asking this question,</p> <p>Here in this piece of code I'm getting dynamic value(from a jsp page) :</p> <pre><code>&lt;form action=""&gt; &lt;% Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost/apps","root","root"); Statement stmt = con.createStatement(); String sql = "select * from info;"; ResultSet rs = stmt.executeQuery(sql); System.out.println(sql); System.out.println("hi Tirtha"); %&gt; &lt;center&gt; &lt;h3&gt;Information of User's&lt;/h3&gt; &lt;table cellpadding="4" cellspacing="2" border="1" bgcolor=""&gt; &lt;tr&gt; &lt;th&gt;User Name&lt;/th&gt; &lt;th&gt;Email Id&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;%while(rs.next()){%&gt; &lt;td&gt;&lt;input type="text" name="name" value="&lt;%= rs.getString(1)%&gt;" readonly="readonly"&gt; &lt;td&gt;&lt;input type="text" name="email" value="&lt;%= rs.getString(2)%&gt;" readonly="readonly"&gt; &lt;/tr&gt; &lt;%}%&gt; &lt;/table&gt; &lt;/center&gt; &lt;/form&gt; </code></pre> <p><em>Now I want to save this data in a csv file</em>(having an export option in it).</p> <p>Any inputs will be appreciated.</p>
13,159,689
2
5
null
2012-10-31 13:37:12.813 UTC
3
2012-11-01 14:56:11.38 UTC
2012-10-31 13:59:59.49 UTC
null
3,340
null
1,422,086
null
1
1
java|jsp|servlets
45,321
<p>here is a class you can using to export to CSV:</p> <pre><code>import java.io.FileWriter; import java.io.IOException; import User; public class GenerateCsv { private static void generateCsvFile(ArrayList&lt;User&gt; users) { String output = "Email, Name\n"; for (User user in users) { output += user.getEmail() + ", " + user.getName() + "\n"; } return output; } } </code></pre> <p>Working the MVC way</p> <p>Here is how your code should be written:</p> <p>Let's say you have a class called. <em>User.java</em> inside of which there is a static function called get all users</p> <pre><code>public class User { String name; String email; public static ArrayList&lt;User&gt; getAllUsers() { // returns all users ... } } </code></pre> <p>Then let's say you have a servlet called UsersServlet which get these users:</p> <pre><code>import javax.servlet.*; import javax.servlet.http.*; public class UsersServlet extends HttpServlet { public void doGet (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("application/csv"); PrintWriter w = res.getWriter(); ArrayList&lt;User&gt; users = Users.getAllUsers(); w.prinln(GenerateCsv.generateCsvFile(users)); w.flush(); w.close(); } public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ... } } </code></pre> <p>in your jsp, for example, you will have a simple anchor tag which calls the servlet (the servlets calls User.java, get data, forms them into a CSV and then outputs it to the browser...). Something like this would work:</p> <pre><code>&lt;a href='/getCSV' &gt; Export CSV &lt;/a&gt; </code></pre> <p>but please note that you have to link the servlet to the <em>url</em> using web.xml:</p> <pre><code>&lt;web-app&gt; &lt;servlet&gt; &lt;servlet-name&gt;UsersServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;__package__.UsersServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;UsersServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;getCSV&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>EDIT: Writing to disk instead of sending to browser</p> <pre><code> import java.io.FileWriter; import java.io.IOException; import User; public class GenerateCsv { private static void generateCsvFile(String fileName, ArrayList&lt;User&gt; users) { try { FileWriter writer = new FileWriter(fileName); writer.append("Email"); writer.append(','); writer.append("Name"); writer.append('\n'); for (User user in users) { writer.append(user.getEmail()); writer.append(','); writer.append(user.getName()); writer.append('\n'); } writer.flush(); writer.close(); } catch(IOException e) { e.printStackTrace(); } } } </code></pre>
6,388,793
Using an IHttpAsyncHandler to call a WebService Asynchronously
<p>Here's the basic setup. We have an ASP.Net WebForms application with a page that has a Flash application that needs to access an external Web Service. Due to (security I presume) limitations in Flash (don't ask me, I'm not a Flash expert at all), we can't connect to the Web Service directly from Flash. The work around is to create a proxy in ASP.Net that the Flash application will call, which will in turn call the WebService and forward the results back to the Flash application. </p> <p>The WebSite has very high traffic though, and the issue is, if the Web Service hangs at all, then the ASP.Net request threads will start backing up which could lead to serious thread starvation. In order to get around that, I've decided to use an <a href="http://msdn.microsoft.com/en-us/library/system.web.ihttpasynchandler.aspx" rel="noreferrer">IHttpAsyncHandler</a> which was designed for this exact purpose. In it, I'll use a WebClient to asynchronously call the Web Service and the forward the response back. There are very few samples on the net on how to correctly use the IHttpAsyncHandler, so I just want to make sure I'm not doing it wrong. I'm basing my useage on the example show here: <a href="http://msdn.microsoft.com/en-us/library/ms227433.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms227433.aspx</a></p> <p>Here's my code:</p> <pre><code>internal class AsynchOperation : IAsyncResult { private bool _completed; private Object _state; private AsyncCallback _callback; private readonly HttpContext _context; bool IAsyncResult.IsCompleted { get { return _completed; } } WaitHandle IAsyncResult.AsyncWaitHandle { get { return null; } } Object IAsyncResult.AsyncState { get { return _state; } } bool IAsyncResult.CompletedSynchronously { get { return false; } } public AsynchOperation(AsyncCallback callback, HttpContext context, Object state) { _callback = callback; _context = context; _state = state; _completed = false; } public void StartAsyncWork() { using (var client = new WebClient()) { var url = "url_web_service_url"; client.DownloadDataCompleted += (o, e) =&gt; { if (!e.Cancelled &amp;&amp; e.Error == null) { _context.Response.ContentType = "text/xml"; _context.Response.OutputStream.Write(e.Result, 0, e.Result.Length); } _completed = true; _callback(this); }; client.DownloadDataAsync(new Uri(url)); } } } public class MyAsyncHandler : IHttpAsyncHandler { public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { var asynch = new AsynchOperation(cb, context, extraData); asynch.StartAsyncWork(); return asynch; } public void EndProcessRequest(IAsyncResult result) { } public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { } } </code></pre> <p>Now this all works, and I THINK it should do the trick, but I'm not 100% sure. Also, creating my own IAsyncResult seems a bit overkill, I'm just wondering if there's a way I can leverage the IAsyncResult returned from Delegate.BeginInvoke, or maybe something else. Any feedback welcome. Thanks!!</p>
6,389,323
1
0
null
2011-06-17 16:28:27.547 UTC
10
2011-06-17 17:15:47.73 UTC
2011-06-17 16:40:33.993 UTC
null
15,861
null
15,861
null
1
6
c#|.net|asp.net|asynchronous|ihttpasynchandler
6,505
<p>Wow, yeah you can make this a lot easier/cleaner if you're on .NET 4.0 by leveraging the Task Parallel Library. Check it:</p> <pre><code>public class MyAsyncHandler : IHttpAsyncHandler { public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { // NOTE: the result of this operation is void, but TCS requires some data type so we just use bool TaskCompletionSource&lt;bool&gt; webClientDownloadCompletionSource = new TaskCompletionSource&lt;bool&gt;(); WebClient webClient = new WebClient()) HttpContext currentHttpContext = HttpContext.Current; // Setup the download completed event handler client.DownloadDataCompleted += (o, e) =&gt; { if(e.Cancelled) { // If it was canceled, signal the TCS is cacnceled // NOTE: probably don't need this since you have nothing canceling the operation anyway webClientDownloadCompletionSource.SetCanceled(); } else if(e.Error != null) { // If there was an exception, signal the TCS with the exception webClientDownloadCompletionSource.SetException(e.Error); } else { // Success, write the response currentHttpContext.Response.ContentType = "text/xml"; currentHttpContext.Response.OutputStream.Write(e.Result, 0, e.Result.Length); // Signal the TCS that were done (we don't actually look at the bool result, but it's needed) taskCompletionSource.SetResult(true); } }; string url = "url_web_service_url"; // Kick off the download immediately client.DownloadDataAsync(new Uri(url)); // Get the TCS's task so that we can append some continuations Task webClientDownloadTask = webClientDownloadCompletionSource.Task; // Always dispose of the client once the work is completed webClientDownloadTask.ContinueWith( _ =&gt; { client.Dispose(); }, TaskContinuationOptions.ExecuteSynchronously); // If there was a callback passed in, we need to invoke it after the download work has completed if(cb != null) { webClientDownloadTask.ContinueWith( webClientDownloadAntecedent =&gt; { cb(webClientDownloadAntecedent); }, TaskContinuationOptions.ExecuteSynchronously); } // Return the TCS's Task as the IAsyncResult return webClientDownloadTask; } public void EndProcessRequest(IAsyncResult result) { // Unwrap the task and wait on it which will propagate any exceptions that might have occurred ((Task)result).Wait(); } public bool IsReusable { get { return true; // why not return true here? you have no state, it's easily reusable! } } public void ProcessRequest(HttpContext context) { } } </code></pre>
6,359,673
How do I dynamically create the variable name in a PHP loop?
<p>Ok so i have this php foreach loop</p> <pre><code>&lt;?php foreach ($step_count-&gt;rows as $step) { ?&gt; </code></pre> <p>and $step will be the step numbers 1, 2, 3, 4, 5 up to the total steps </p> <p>within the loop i a need to set the value of the images within the loop to standard_image_1 or whatever step there is...so for example</p> <pre><code>&lt;input value="&lt;?php echo {$standard_image_"$step['number']"}; ?&gt;" /&gt; </code></pre> <p>so basically i need the variable $standard_image_1 and so on depending on the steps but i dont know the correct syntax to do this</p>
6,359,710
1
0
null
2011-06-15 14:50:23.027 UTC
4
2011-06-15 15:03:25.127 UTC
2011-06-15 15:03:25.127 UTC
null
610,573
null
223,367
null
1
12
php|loops|variable-variables
42,719
<p>Look at the docs for "variable variables" - <a href="http://php.net/manual/en/language.variables.variable.php" rel="noreferrer">http://php.net/manual/en/language.variables.variable.php</a></p> <pre><code>&lt;?php echo ${'standard_image_'.$step['number']}; ?&gt; </code></pre> <p>Here's a mock-up, using the details you've given: <a href="http://codepad.org/hQe56tEU" rel="noreferrer">http://codepad.org/hQe56tEU</a></p>
41,916,386
ARG or ENV, which one to use in this case?
<p>This could be maybe a trivial question but reading docs for <a href="https://docs.docker.com/engine/reference/builder/#arg" rel="noreferrer">ARG</a> and <a href="https://docs.docker.com/engine/reference/builder/#env" rel="noreferrer">ENV</a> doesn't put things clear to me.</p> <p>I am building a PHP-FPM container and I want to give the ability for enable/disable some extensions on user needs.</p> <p>Would be great if this could be done in the Dockerfile by adding conditionals and passing flags on the build command perhaps but AFAIK is not supported.</p> <p>In my case and my personal approach is to run a small script when container starts, something like the following:</p> <pre><code>#!/bin/sh set -e RESTART=&quot;false&quot; # This script will be placed in /config/init/ and run when container starts. if [ &quot;$INSTALL_XDEBUG&quot; == &quot;true&quot; ]; then printf &quot;\nInstalling Xdebug ...\n&quot; yum install -y php71-php-pecl-xdebug RESTART=&quot;true&quot; fi ... if [ &quot;$RESTART&quot; == &quot;true&quot; ]; then printf &quot;\nRestarting php-fpm ...\n&quot; supervisorctl restart php-fpm fi exec &quot;$@&quot; </code></pre> <p>This is how my <code>Dockerfile</code> looks like:</p> <pre><code>FROM reynierpm/centos7-supervisor ENV TERM=xterm \ PATH=&quot;/root/.composer/vendor/bin:${PATH}&quot; \ INSTALL_COMPOSER=&quot;false&quot; \ COMPOSER_ALLOW_SUPERUSER=1 \ COMPOSER_ALLOW_XDEBUG=1 \ COMPOSER_DISABLE_XDEBUG_WARN=1 \ COMPOSER_HOME=&quot;/root/.composer&quot; \ COMPOSER_CACHE_DIR=&quot;/root/.composer/cache&quot; \ SYMFONY_INSTALLER=&quot;false&quot; \ SYMFONY_PROJECT=&quot;false&quot; \ INSTALL_XDEBUG=&quot;false&quot; \ INSTALL_MONGO=&quot;false&quot; \ INSTALL_REDIS=&quot;false&quot; \ INSTALL_HTTP_REQUEST=&quot;false&quot; \ INSTALL_UPLOAD_PROGRESS=&quot;false&quot; \ INSTALL_XATTR=&quot;false&quot; RUN yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm \ https://rpms.remirepo.net/enterprise/remi-release-7.rpm RUN yum install -y \ yum-utils \ git \ zip \ unzip \ nano \ wget \ php71-php-fpm \ php71-php-cli \ php71-php-common \ php71-php-gd \ php71-php-intl \ php71-php-json \ php71-php-mbstring \ php71-php-mcrypt \ php71-php-mysqlnd \ php71-php-pdo \ php71-php-pear \ php71-php-xml \ php71-pecl-apcu \ php71-php-pecl-apfd \ php71-php-pecl-memcache \ php71-php-pecl-memcached \ php71-php-pecl-zip &amp;&amp; \ yum clean all &amp;&amp; rm -rf /tmp/yum* RUN ln -sfF /opt/remi/php71/enable /etc/profile.d/php71-paths.sh &amp;&amp; \ ln -sfF /opt/remi/php71/root/usr/bin/{pear,pecl,phar,php,php-cgi,phpize} /usr/local/bin/. &amp;&amp; \ mv -f /etc/opt/remi/php71/php.ini /etc/php.ini &amp;&amp; \ ln -s /etc/php.ini /etc/opt/remi/php71/php.ini &amp;&amp; \ rm -rf /etc/php.d &amp;&amp; \ mv /etc/opt/remi/php71/php.d /etc/. &amp;&amp; \ ln -s /etc/php.d /etc/opt/remi/php71/php.d COPY container-files / RUN chmod +x /config/bootstrap.sh WORKDIR /data/www EXPOSE 9001 </code></pre> <p>Currently this is working but ... If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable then I will end with 20 non necessary <code>ENV</code> (because Dockerfile doesn't support .env files) definition whose only purpose would be set this flag for let the script knows what to do then ...</p> <ul> <li>Is this the right way to do it?</li> <li>Should I use <code>ENV</code> for this purpose?</li> </ul> <p>I am open to ideas if you have a different approach for achieve this please let me know about it</p>
41,919,137
2
2
null
2017-01-29 00:24:58.153 UTC
40
2021-02-15 14:52:09.247 UTC
2021-02-15 14:52:09.247 UTC
null
1,815,058
null
719,427
null
1
174
docker|arguments|environment-variables|dockerfile
142,248
<p>From <a href="https://docs.docker.com/engine/reference/builder/" rel="noreferrer">Dockerfile reference</a>:</p> <blockquote> <ul> <li><p>The <code>ARG</code> instruction defines a variable that users can pass at build-time to the builder with the docker build command using the <code>--build-arg &lt;varname&gt;=&lt;value&gt;</code> flag.</p> </li> <li><p>The <code>ENV</code> instruction sets the environment variable <code>&lt;key&gt;</code> to the value <code>&lt;value&gt;</code>.<br /> The environment variables set using <code>ENV</code> will persist when a container is run from the resulting image.</p> </li> </ul> </blockquote> <p>So if you need <em>build-time</em> customization, <code>ARG</code> is your best choice.<br /> If you need run-time customization (to run the same image with different settings), <code>ENV</code> is well-suited.</p> <blockquote> <p>If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable</p> </blockquote> <p>Given the number of combinations involved, using <code>ENV</code> to set those features at runtime is best here.</p> <p>But you can <a href="https://stackoverflow.com/a/33936014/6309">combine both</a> by:</p> <ul> <li>building an image with a specific <code>ARG</code></li> <li>using that <code>ARG</code> as an <code>ENV</code></li> </ul> <p>That is, with a Dockerfile including:</p> <pre><code>ARG var ENV var=${var} </code></pre> <p>You can then either build an image with a specific <code>var</code> value at build-time (<code>docker build --build-arg var=xxx</code>), or run a container with a specific runtime value (<code>docker run -e var=yyy</code>)</p>
3,002,438
The HTTP request was forbidden with client authentication scheme 'Anonymous'
<p>I am trying to configure a WCF server\client to work with SSL</p> <p>I get the following exception:</p> <blockquote> <p>The HTTP request was forbidden with client authentication scheme 'Anonymous'</p> </blockquote> <p>I have a self hosted WCF server. I have run hhtpcfg both my client and server certificates are stored under Personal and Trusted People on the Local Machine</p> <p>Here is the server code:</p> <pre><code>binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; binding.Security.Mode = WebHttpSecurityMode.Transport; _host.Credentials.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.PeerOrChainTrust; _host.Credentials.ClientCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck; _host.Credentials.ClientCertificate.Authentication.TrustedStoreLocation = StoreLocation.LocalMachine; _host.Credentials.ServiceCertificate.SetCertificate("cn=ServerSide", StoreLocation.LocalMachine, StoreName.My); </code></pre> <p>Client Code:</p> <pre><code>binding.Security.Mode = WebHttpSecurityMode.Transport; binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; WebChannelFactory&lt;ITestClientForServer&gt; cf = new WebChannelFactory&lt;ITestClientForServer&gt;(binding, url2Bind); cf.Credentials.ClientCertificate.SetCertificate("cn=ClientSide", StoreLocation.LocalMachine, StoreName.My); ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate; </code></pre> <p>Looking at web_tracelog.svclog and trace.log reveals that the server cannot autheticate the client certificate My certificate are not signed by an Authorized CA but this is why I added them to the Trusted People....</p> <p>What Am I missing? What am I missing?</p>
3,013,760
2
0
null
2010-06-09 00:57:25.867 UTC
3
2013-03-07 03:54:49.03 UTC
2013-03-07 03:54:49.03 UTC
null
1,210,760
null
106,865
null
1
15
wcf|security|https|certificate
44,577
<p>The trick was to make the Client Certificate valid,</p> <p>To do that you have two option:</p> <p>1) make it self signed and then put it under the "Trusted Root Certification Authority".</p> <p>Obviously in production you would like your client certificate to be signed by a trusted CA and not self signed. see <a href="http://msdn.microsoft.com/en-us/library/ms733813.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms733813.aspx</a></p> <p>2) Sign your client certificate by another certificate you created (let's call it MyCA) and put MyCA in the "Trusted Root Certification Authority" and have the client certificate in the "Trusted People". This way your development environment is even more close to the deployment.</p> <p>How to create and sign the certificates: Look under <a href="http://msdn.microsoft.com/en-us/library/bfsktky3.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bfsktky3.aspx</a></p> <p>Here is the series of commands I used:</p> <p>1)makecert -r -pe -ss My -sr LocalMachine -a sha1 -sky exchange -n cn=MyCA -sv "MyCAPrivate.pvk"</p> <p>2) makecert -pe -ss My -sr LocalMachine -a sha1 -sky exchange -n cn=SignedClientCertificate -iv "MyCAPrivate.pvk" -ic "MyCAPublic.cer"</p>
2,342,974
When does the browser execute Javascript? How does the execution cursor move?
<p>I was wondering if there are any available resources that describe how a browser's cursor executes Javascript.</p> <p>I know it loads and executes tags when a page loads, and that you can attach functions to various window events, but where things get fuzzy is when, for instance, I retrieve a remote page via AJAX and put its contents into a div.</p> <p>If that remote page has got to load script libraries such as <code>&lt;script src="anotherscript.js" /&gt;</code>, when is "anotherscript.js" being loaded and its contents are being executed?</p> <p>What happens if I included "anotherscript.js" on my current page, and then I load some remote content which has a duplicate include of this script? Does it overwrite the original one? What if the original "anotherscript.js" has a var in it whose value I altered, and then I reload that file... do I lose the original value or is the second inclusion of this script ignored?</p> <p>If I load some procedural Javascript via AJAX, when is it executed? Immediately after I do <code>mydiv.innerHTML(remoteContent)</code>? Or is it executed before that?</p>
2,343,051
2
3
null
2010-02-26 16:13:12.7 UTC
33
2012-09-04 12:04:11.367 UTC
2012-09-04 12:04:11.367 UTC
null
-1
null
208,066
null
1
63
javascript|ajax
42,139
<p>The answer varies depending on where the script tag is and how you've added it:</p> <ol> <li><p>Script tags inline with your markup are executed synchronously with the browser's processing of that markup (except, see #2), and so if -- for instance -- those tags reference external files, they tend to slow down the processing of the page. (This is so the browser can handle <code>document.write</code> statements, which change the markup they're processing.)</p></li> <li><p>Script tags with the <code>defer</code> attribute may, on some browsers, not be executed until after the DOM has been fully rendered. Naturally these can't use <code>document.write</code>. (Similarly there's an <code>async</code> attribute that makes the script asynchronous, but I don't know much about it or how well it's supported; <a href="http://dev.w3.org/html5/spec/semantics.html#script" rel="noreferrer">details</a>.)</p></li> <li><p>Script tags in content you assign to elements after DOM load (via <code>innerHTML</code> and similar) are not executed at all, barring your use of a library like jQuery or Prototype to do it for you. <em>(With one exception pointed out by Andy E: On IE, if they have a <code>defer</code> attribute, it will execute them. Doesn't work in other browsers.)</em></p></li> <li><p>If you append an actual <code>script</code> element to the document via <a href="https://developer.mozilla.org/En/DOM/Node.appendChild" rel="noreferrer"><code>Element#appendChild</code></a>, the browser begins downloading that script immediately and will execute it as soon as the download is finished. Scripts added this way are not executed synchronously or necessarily in order. First appending a <code>&lt;script type="text/javascript" src="MyFct.js"&gt;&lt;/script&gt;</code>, and then appending <code>&lt;script type="text/javascript"&gt;myFunction();&lt;/script&gt;</code> may well execute the inline (second) one before the remote (first) one. If that happens and <code>MyFct.js</code> declares <code>myFunction()</code>, it will not be defined when we try to use it with the inline script. If you need things done in order, you can tell when a remote script has been loaded by watching the <code>load</code> and <code>readyStateChange</code> events on the <code>script</code> element you add (<code>load</code> is the event on most browsers, <code>readyStateChange</code> on some versions of IE, and some browsers do both, so you have to handle multiple notifications for the same script).</p></li> <li><p>Script inside event handlers on attributes (<code>&lt;a href='#' onclick='myNiftyJavaScript();'&gt;</code>) rather than in a script tag is executed when the relevant event occurs.</p></li> </ol> <hr> <p>I was working away at my Real Job and suddenly my hindbrain said "You know, you've been <em>told</em> they won't be executed if you assign them to <code>innerHTML</code>, but have you personally checked?" And I hadn't, so I did -- FWIW:</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-type" content="text/html;charset=UTF-8"&gt; &lt;title&gt;Script Test Page&lt;/title&gt; &lt;style type='text/css'&gt; body { font-family: sans-serif; } &lt;/style&gt; &lt;script type='text/javascript'&gt; function addScript() { var str, div; div = document.getElementById('target'); str = "Content added&lt;" + "script type='text/javascript'&gt;alert('hi there')&lt;" + "/" + "script&gt;"; alert("About to add:" + str); div.innerHTML = str; alert("Done adding script"); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt;&lt;div&gt; &lt;input type='button' value='Go' onclick='addScript();'&gt; &lt;div id='target'&gt;&lt;/div&gt; &lt;/div&gt;&lt;/body&gt; &lt;/html&gt; </code></pre> <p>The alert from the script doesn't appear on IE7, FF3.6, or Chrome4 (I haven't bothered to check others, I'm meant to be working :-) ). Whereas if you append elements as shown <a href="http://proto-scripty.wikidot.com/prototype:how-to-load-scripts-dynamically" rel="noreferrer">here</a>, the script gets executed.</p>
33,033,129
Xcode 7.1 Swift 2 Unknown class in Interface Builder file
<p>I've created new Cocoa Touch File. Named it SwipingViewController. <img src="https://i.stack.imgur.com/rSGPF.png" alt="enter image description here"></p> <p>Then try to add Custom Class to ViewController.</p> <p>And when I run the app I receive an error</p> <blockquote> <p><strong>2015-10-09 10:53:25.054 ParseStarterProject[5369:389307] Unknown class SwipingViewController in Interface Builder file.</strong></p> </blockquote> <p><img src="https://i.stack.imgur.com/7zqE8.png" alt="Unknown class SwipingViewController in Interface Builder file"></p> <p>Related: <a href="https://stackoverflow.com/questions/24924966/xcode-6-strange-bug-unknown-class-in-interface-builder-file">Xcode 6 Strange Bug: Unknown class in Interface Builder file</a></p> <p>Here is my <a href="https://www.dropbox.com/s/8d2o2vugrfh5no6/Tinder%202.zip?dl=0" rel="noreferrer">projects files</a></p>
33,034,445
8
0
null
2015-10-09 08:08:54.953 UTC
9
2019-03-23 10:41:22.977 UTC
2018-01-15 05:22:39.163 UTC
null
1,033,581
null
5,343,376
null
1
52
ios|xcode|swift|cocoa
39,718
<p>In storyboard below the Custom Class field the module is set to None. Change that to your app module or just remove and enter class again, it should set to default like this:</p> <p><img src="https://i.stack.imgur.com/iuVFL.png" alt=""></p>
42,148,583
Pyspark filter dataframe by columns of another dataframe
<p>Not sure why I'm having a difficult time with this, it seems so simple considering it's fairly easy to do in R or pandas. I wanted to avoid using pandas though since I'm dealing with a lot of data, and I believe <code>toPandas()</code> loads all the data into the driver’s memory in pyspark.</p> <p>I have 2 dataframes: <code>df1</code> and <code>df2</code>. I want to filter <code>df1</code> (remove all rows) where <code>df1.userid = df2.userid</code> AND <code>df1.group = df2.group</code>. I wasn't sure if I should use <code>filter()</code>, <code>join()</code>, or <code>sql</code> For example:</p> <pre><code>df1: +------+----------+--------------------+ |userid| group | all_picks | +------+----------+--------------------+ | 348| 2|[225, 2235, 2225] | | 567| 1|[1110, 1150] | | 595| 1|[1150, 1150, 1150] | | 580| 2|[2240, 2225] | | 448| 1|[1130] | +------+----------+--------------------+ df2: +------+----------+---------+ |userid| group | pick | +------+----------+---------+ | 348| 2| 2270| | 595| 1| 2125| +------+----------+---------+ Result I want: +------+----------+--------------------+ |userid| group | all_picks | +------+----------+--------------------+ | 567| 1|[1110, 1150] | | 580| 2|[2240, 2225] | | 448| 1|[1130] | +------+----------+--------------------+ </code></pre> <p>EDIT: I've tried many join() and filter() functions, I believe the closest I got was:</p> <pre><code>cond = [df1.userid == df2.userid, df2.group == df2.group] df1.join(df2, cond, 'left_outer').select(df1.userid, df1.group, df1.all_picks) # Result has 7 rows </code></pre> <p>I tried a bunch of different join types, and I also tried different</p> <pre><code>cond values: cond = ((df1.userid == df2.userid) &amp; (df2.group == df2.group)) # result has 7 rows cond = ((df1.userid != df2.userid) &amp; (df2.group != df2.group)) # result has 2 rows </code></pre> <p>However, it seems like the joins are adding additional rows, rather than deleting.</p> <p>I'm using <code>python 2.7</code> and <code>spark 2.1.0</code></p>
42,149,646
1
0
null
2017-02-09 23:04:08.017 UTC
7
2021-12-13 20:33:04.267 UTC
2021-08-20 03:49:55.863 UTC
null
10,954,152
null
2,539,931
null
1
38
python-2.7|apache-spark|dataframe|pyspark|apache-spark-sql
47,118
<p>Left anti join is what you're looking for:</p> <pre><code>df1.join(df2, ["userid", "group"], "leftanti") </code></pre> <p>but the same thing can be done with left outer join:</p> <pre><code>(df1 .join(df2, ["userid", "group"], "leftouter") .where(df2["pick"].isNull()) .drop(df2["pick"])) </code></pre>
41,632,225
Android - Where and how securely is fingerprint information stored in a device
<p>I have been reading quite a bit about fingerprint sensors and their growing presence in smart phones. I understand that at the basic level, there is a digital image that gets registered and it serves as a template for authentication. I understand that fingerprint related processing takes place in a Trusted Execution Environment. However, I would like to know where the "template" gets saved and in what format? </p>
41,632,309
1
0
null
2017-01-13 10:19:12.603 UTC
9
2017-01-16 08:10:29.533 UTC
null
null
null
null
5,962,381
null
1
11
android|fingerprint|android-fingerprint-api
13,880
<blockquote> <p>Trusted Execution Environment (TEE)</p> </blockquote> <p>Google has made a noteworthy step in the right direction by moving all print data manipulation to the Trusted Execution Environment (TEE) and providing strict guidelines for fingerprint data storage that manufacturers must follow. </p> <ul> <li><p>All fingerprint data manipulation is performed within TEE</p></li> <li><p>All fingerprint data must be secured within sensor hardware or trusted memory so that images of your fingerprint are inaccessible</p></li> <li><p>Fingerprint data can be stored on the file system only in encrypted form,<br> regardless of whether the file system itself is encrypted or not</p></li> <li><p>Removal of the user must result in removal of the user's existing fingerprint data</p></li> <li><p>Root access must not compromise fingerprint data</p></li> </ul> <p><a href="https://i.stack.imgur.com/HMbe6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HMbe6.png" alt="enter image description here"></a></p> <p>Data Source <a href="https://infinum.co/the-capsized-eight/android-fingerprint-security" rel="noreferrer">infinum.co</a></p>
64,718,274
how to update python in raspberry pi
<p>I need python newest version in raspberry pi.<br> I tried <code>apt install python3 3.8</code><br> <code>apt install python3</code> but this didnot work.<br> And I also needed to update my raspberry pi python <strong>IDLE</strong></p>
64,737,929
3
2
null
2020-11-06 16:27:05.81 UTC
7
2021-06-01 10:40:39 UTC
null
null
null
null
14,589,833
null
1
13
python|python-3.x|raspberry-pi|raspberry-pi3
42,253
<p>First update the Raspbian.</p> <pre><code>sudo apt-get update </code></pre> <p>Then install the prerequisites that will make any further installation of Python and/or packages much smoother.</p> <pre><code>sudo apt-get install -y build-essential tk-dev libncurses5-dev libncursesw5-dev libreadline6-dev libdb5.3-dev libgdbm-dev libsqlite3-dev libssl-dev libbz2-dev libexpat1-dev liblzma-dev zlib1g-dev libffi-dev </code></pre> <p>And then install Python, maybe by downloading a compressed file?</p> <p>example 1 :</p> <pre><code>wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgz </code></pre> <p>Extract the folder :</p> <pre><code>sudo tar zxf Python-3.8.0.tgz </code></pre> <p>Move into the folder :</p> <pre><code>cd Python-3.8.0 </code></pre> <p>Initial configuration :</p> <pre><code>sudo ./configure --enable-optimizations </code></pre> <p>Run the makefile inside the folder with the mentioned parameters :</p> <pre><code>sudo make -j 4 </code></pre> <p>Run again the makefile this time installing directly the package :</p> <pre><code>sudo make altinstall </code></pre> <p>Maybe You already did it but You don't know how to setup the new version as a default version of the system?</p> <p>Check first that it has been installed :</p> <pre><code>python3.8 -V </code></pre> <p>Send a strong command to .bashrc telling him who (which version) is in charge of Python</p> <pre><code>echo &quot;alias python=/usr/local/bin/python3.8&quot; &gt;&gt; ~/.bashrc </code></pre> <p>Again! Tell him because .bashrc has to understand! I am joking - You have to source the file so the changes can be applied immediately :</p> <pre><code>source ~/.bashrc </code></pre> <p>And then check that Your system changed the default version of Python to Python 3.8</p> <pre><code>python -V </code></pre> <p>The failure depends on many factors : what dependencies are installed, what are the packages added to the source_list.d, some inconvenient coming up during the installation. All may give you more information than you think, just read carefully. Hope it helped.</p>
33,851,379
How to install pyaudio on mac using Python 3?
<p>I first tried:</p> <pre><code>pip install pyaudio </code></pre> <p>but I was told that</p> <pre><code>-bash: pip: command not found </code></pre> <p>Then I tried:</p> <pre><code>pip3 install pyaudio </code></pre> <p>Then I got:</p> <pre><code>src/_portaudiomodule.c:29:10: fatal error: 'portaudio.h' file not found #include &quot;portaudio.h&quot; ^ 1 error generated. error: command '/usr/bin/clang' failed with exit status 1 ---------------------------------------- Command &quot;/Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 -c &quot;import setuptools, tokenize;__file__='/private/var/folders/77/gz1txkwj2z925vk6jrkx3wp80000gn/T/pip-build-43z_qk7o/pyaudio/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))&quot; install --record /var/folders/77/gz1txkwj2z925vk6jrkx3wp80000gn/T/pip-tkf78ih4-record/install-record.txt --single-version-externally-managed --compile&quot; failed with error code 1 in /private/var/folders/77/gz1txkwj2z925vk6jrkx3wp80000gn/T/pip-build-43z_qk7o/pyaudio </code></pre> <p>but I had installed portaudio</p> <pre><code>brew install portaudio </code></pre> <p>Warning: portaudio-19.20140130 already installed</p> <p>So what can I do?</p>
33,851,618
9
0
null
2015-11-22 03:46:24.65 UTC
10
2022-08-12 18:46:38.607 UTC
2021-03-27 03:08:21.2 UTC
null
2,745,495
null
5,590,767
null
1
39
python|python-3.x|macos|pyaudio
67,785
<p>I'm assuming you are on a Mac. This is a simple issue to fix. </p> <p>First install Xcode. Then restart your computer. Afterwards run the commands in sequence,</p> <pre class="lang-bash prettyprint-override"><code>xcode-select --install brew remove portaudio brew install portaudio pip3 install pyaudio </code></pre> <p>So to clarify, Xcode is installed through the App Store. Xcode command line tools are required for some installations, for others they are not. I'm including it here just to be on the safe side. You also probably do not need to uninstall and reinstall the formula via Homebrew, I did that to ensure that there would be absolutely no problems.</p> <p>Edit: I have been told Homebrew requires Xcode. So just run the</p> <pre><code>xcode-select --install </code></pre> <p>command to be able to use Clang. Also what version of Mac are you on?</p>
33,553,828
Page transition animations with Angular 2.0 router and component interface promises
<p>In Angular 1.x we can use ngAnimate to detect when we are leaving or entering a particular route. Furthermore we are able to apply behaviors to them:</p> <pre><code>animateApp.animation('.myElement', function(){ return { enter : function(element, done) { //Do something on enter }, leave : function(element, done) { //Do something on leave } }; )}; </code></pre> <p>Resulting in a product like this: <a href="http://embed.plnkr.co/uW4v9T/preview" rel="noreferrer">http://embed.plnkr.co/uW4v9T/preview</a></p> <p>I would like to do something similar with Angular 2.0 and I feel like I'm pretty close... </p> <p>So here goes, I've created a simple router in the main application component that controls the navigation between the <em>home</em> and <em>about</em> components. </p> <pre><code>import { bootstrap, bind, Component, provide, View } from 'angular2/angular2'; import {RouteConfig, RouteParams, ROUTER_DIRECTIVES, ROUTER_PROVIDERS, APP_BASE_HREF, ROUTER_BINDINGS} from 'angular2/router' ///////////////////////////////////////////////////////////////// // Home Component Start ///////////////////////////////////////////////////////////////// @Component({ selector: 'home-cmp' }) @View({ template: ` &lt;h2 class="title"&gt;Home Page&lt;/h2&gt; ` }) class HomeCmp implements OnActivate, onDeactivate{ onActivate(next: ComponentInstruction, prev: ComponentInstruction) { console.log("Home Page - initialized"); } onDeactivate(next: ComponentInstruction, prev: ComponentInstruction) { console.log("Home Page - destroyed"); } } ///////////////////////////////////////////////////////////////// // Home Component End ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // About Component Start ///////////////////////////////////////////////////////////////// @Component({ selector: 'about-cmp' }) @View({ template: ` &lt;h2 class="title"&gt;About Page&lt;/h2&gt; ` }) class AboutCmp implements OnActivate, onDeactivate { onActivate(next: ComponentInstruction, prev: ComponentInstruction) { console.log("About Page - initialized"); } onDeactivate(next: ComponentInstruction, prev: ComponentInstruction) { console.log("About Page - destroyed"); } } ///////////////////////////////////////////////////////////////// // About Component End ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // Main Application Componenent Start ///////////////////////////////////////////////////////////////// @Component({ selector: 'my-app' }) @View({ template: ` &lt;div&gt; &lt;h1&gt;Hello {{message}}!&lt;/h1&gt; &lt;a [router-link]="['./HomeCmp']"&gt;home&lt;/a&gt; &lt;a [router-link]="['./AboutCmp']"&gt;about&lt;/a&gt; &lt;hr&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;/div&gt; `, directives: [ROUTER_DIRECTIVES] }) @RouteConfig([ {path: '/', component: HomeCmp, as: 'HomeCmp'}, {path: '/about', component: AboutCmp, as: 'AboutCmp'} ]) export class App { } ///////////////////////////////////////////////////////////////// // Main Application Componenent End ///////////////////////////////////////////////////////////////// bootstrap(App, [ ROUTER_BINDINGS, ROUTER_PROVIDERS, ROUTER_DIRECTIVES, provide(APP_BASE_HREF, {useValue: '/'}) ]) </code></pre> <p>At the moment I am able to capture when the router has instantiated or destroyed a particular component when it moves from one to the next. This is great, but when the the <em>previous</em> component is <em>destroyed</em> I am not able to apply an <em>on leave</em> transition animation before the next component is initialized. </p> <pre><code>class HomeCmp implements OnActivate, onDeactivate{ onActivate(next: ComponentInstruction, prev: ComponentInstruction) { //This works TweenMax.fromTo($(".title"), 1, {opacity: 0}, {opacity: 1}); } onDeactivate(next: ComponentInstruction, prev: ComponentInstruction) { //This get ignored TweenMax.fromTo($(".title"), 1, {opacity: 0}, {opacity: 1}); } } </code></pre> <p>It seems like there is a solution to this using promises. Angular.io's API preview they state:</p> <p><strong>If onDeactivate returns a promise, the route change will wait until the promise settles.</strong> </p> <p>and</p> <p><strong>If onActivate returns a promise, the route change will wait until the promise settles to instantiate and activate child components.</strong> </p> <p><a href="https://angular.io/docs/ts/latest/api/" rel="noreferrer">https://angular.io/docs/ts/latest/api/</a></p> <p>I am super brand new to promises so I mashed this together into my code which solved the problem of my current component being destroyed on initialization of the next one, but then it <em>never</em> gets destroyed, it only creates a new instance of it. Every time I navigate back to it, it will create a new instance resulting in multiple copies.</p> <pre><code>onDeactivate(next: ComponentInstruction, prev: ComponentInstruction) { function ani(){ TweenMax.fromTo($(".title"), 1, {opacity: 1}, {opacity: 0}); } var aniPromise = ani(); aniPromise.then(function (ani) { ani(); }); } </code></pre> <p>So to recap, the router should be able to wait for the current component to finish it's <em>business</em> before destroying it and initializing the next component.</p> <p>I hope that all makes sense and I really appreciate the help!</p>
33,554,846
2
0
null
2015-11-05 20:08:08.75 UTC
8
2017-09-19 13:57:28.787 UTC
2017-09-19 13:57:28.787 UTC
null
5,765,795
null
5,468,991
null
1
25
angular|typescript|promise
14,029
<p>As you quoted from the docs, if any of this hooks returns a Promise it will wait until its completed to move to the next one, so you can easily return a Promise that basically does nothing and wait a second (or as many time as you need).</p> <p></p> <pre><code> onActivate(next: ComponentInstruction, prev: ComponentInstruction) { TweenMax.fromTo($(".title"), 1, {opacity: 0}, {opacity: 1}); return new Promise((res, rej) =&gt; setTimeout(() =&gt; res(1), 1000)); } onDeactivate(next: ComponentInstruction, prev: ComponentInstruction) { TweenMax.fromTo($(".title"), 1, {opacity:1}, {opacity: 0}); return new Promise((res, rej) =&gt; setTimeout(() =&gt; res(1), 1000)); } </code></pre> <p>Note that I'm returning a Promise which runs a setTimeout. We wait a second to give the animation time enough to be completed.</p> <p>I don't really like using setTimeouts, so we can use Observables as well, that personally I like the best.</p> <pre class="lang-js prettyprint-override"><code>return Rx.Observable.of(true).delay(1000).toPromise(); </code></pre> <p>Here I'm passing a random value (true in this case) and delay it a second and finally cast it to Promise. Yes, it ends up being a Promise but I don't use it directly.</p> <p>Here's a <a href="http://plnkr.co/edit/pCxVob?p=preview">plnkr</a> with an example working (expecting to be what you are looking for). </p> <p>PS: If sometimes it complains about that it can't find a path to Rx, just keep refreshing until it works (I added Rx.js manually and it's a little heavy for plnkr apprently).</p>
22,985,671
How to Check either Session is Set or Not in Codeigniter?
<p>I know how to create session in core PHP, and I have understand how to do this in codeigniter, but I am unable to understand how to check, if the session is set or not? I have tried to check this through View but it always give me the meesage <code>Please Login</code>. </p> <p>Kindly tell me how can I check whether the session is Set or not Set </p> <p><strong>Controller</strong></p> <pre><code>if ($user_type=='Student') { if ($LoginData= $this-&gt;loginmodel-&gt;studentLogin($username,$password)) { foreach($LoginData as $UserId) { $currentId= $UserId-&gt;StudentId; } //[[session]] $data['students_data']= $this-&gt;loginmodel-&gt;student_profile($currentId); $this-&gt;session-&gt;userdata('$data'); $this-&gt;load-&gt;view('students',$data); } else { //$data['message']= array('Invalid Username or Password'); $this-&gt;load-&gt;view('Login'); echo "Invalid Username or Password"; } } elseif ($user_type=="Faculty") { if($data['faculty_data']=$this-&gt;loginmodel-&gt;faculty_admin($username, $password)) { $this-&gt;session-&gt;userdata('$data'); $this-&gt;load-&gt;view('faculty'); } else { $this-&gt;load-&gt;view('Login'); echo "Invalid Username or Password"; } } </code></pre> <p><strong>VIEW</strong></p> <pre><code>&lt;?php if (!$this-&gt;session-&gt;userdata('$data')) { echo "Please Login"; } else { } ?&gt; &lt;!DOCTYPE </code></pre>
22,986,040
3
0
null
2014-04-10 10:40:24.763 UTC
2
2018-08-18 06:47:44.63 UTC
2014-04-10 12:55:05.913 UTC
null
988,174
null
3,480,644
null
1
6
php|html|mysql|codeigniter|session
69,467
<p>Creating Session:</p> <pre><code>$newdata = array( 'username' =&gt; 'johndoe', 'email' =&gt; '[email protected]', 'logged_in' =&gt; TRUE ); $this-&gt;session-&gt;set_userdata($newdata); </code></pre> <p>or</p> <pre><code> $this-&gt;session-&gt;set_userdata('some_name', 'some_value'); </code></pre> <p>But before that ensure that you have the session library included.</p> <pre><code>$this-&gt;load-&gt;library('session'); </code></pre> <p>Get Session Data:</p> <pre><code>if($this-&gt;session-&gt;userdata('whatever_session_name_is')){ // do something when exist }else{ // do something when doesn't exist } </code></pre>
1,741,415
Linux Kernel Modules: When to use try_module_get / module_put
<p>I was reading the LKMPG ( <a href="http://tldp.org/LDP/lkmpg/2.6/html/x569.html" rel="noreferrer">See Section 4.1.4. Unregistering A Device</a> ) and it wasn't clear to me when to use the <code>try_module_get / module_put</code> functions. Some of the LKMPG examples use them, some don't.</p> <p>To add to the confusion, <code>try_module_get</code> appears 282 times in 193 files in the 2.6.24 source, yet in <a href="http://lwn.net/Kernel/LDD3/" rel="noreferrer">Linux Device Drivers ( LDD3 )</a> and <a href="http://www.elinuxdd.com/" rel="noreferrer">Essential Linux Device Drivers</a>, they appears in not even a single code example.</p> <p>I thought maybe they were tied to the old <code>register_chrdev</code> interface ( superseded in 2.6 by the cdev interface ), but they only appear together in the same files 8 times:</p> <pre><code>find -type f -name *.c | xargs grep -l try_module_get | sort -u | xargs grep -l register_chrdev | sort -u | grep -c . </code></pre> <p>So when is it appropriate to use these functions and are they tied to the use of a particular interface or set of circumstances?</p> <p><strong>Edit</strong></p> <p>I loaded the <a href="http://tldp.org/LDP/lkmpg/2.6/html/x1211.html#AEN1250" rel="noreferrer">sched.c</a> example from the LKMPG and tried the following experiment:</p> <pre><code>anon@anon:~/kernel-source/lkmpg/2.6.24$ tail /proc/sched -f &amp; Timer called 5041 times so far [1] 14594 anon@anon:~$ lsmod | grep sched sched 2868 1 anon@anon:~$ sudo rmmod sched ERROR: Module sched is in use </code></pre> <p>This leads me to believe that the kernel now does it's own accounting and the gets / puts may be obsolete. Can anyone verify this?</p>
6,079,839
1
2
null
2009-11-16 10:50:32.217 UTC
9
2011-05-21 05:32:56.88 UTC
2009-11-17 10:28:28.553 UTC
null
71,074
null
71,074
null
1
23
linux-kernel|linux-device-driver|kernel-module
16,512
<p>You should essentially never have to use try_module_get(THIS_MODULE); pretty much all such uses are unsafe since if you are already in your module, it's too late to bump the reference count -- there will always be a (small) window where you are executing code in your module but haven't incremented the reference count. If someone removes the module exactly in that window, then you're in the bad situation of running code in an unloaded module.</p> <p>The particular example you linked in LKMPG where the code does try_module_get() in the open() method would be handled in the modern kernel by setting the .owner field in struct file_operations:</p> <pre><code>struct file_operations fops = { .owner = THIS_MODULE, .open = device_open, //... }; </code></pre> <p>this will make the VFS code take a reference to the module <em>before</em> calling into it, which eliminates the unsafe window -- either the try_module_get() will succeed before the call to .open(), or the try_module_get() will fail and the VFS will never call into the module. In either case, we never run code from a module that has already been unloaded.</p> <p>The only good time to use try_module_get() is when you want to take a reference on a <em>different</em> module before calling into it or using it in some way (eg as the file open code does in the example I explained above). There are a number of uses of try_module_get(THIS_MODULE) in the kernel source but most if not all of them are latent bugs that should be cleaned up.</p> <p>The reason you were not able to unload the sched example is that your</p> <pre><code>$ tail /proc/sched -f &amp; </code></pre> <p>command keeps /proc/sched open, and because of</p> <pre><code> Our_Proc_File-&gt;owner = THIS_MODULE; </code></pre> <p>in the sched.c code, opening /proc/sched increments the reference count of the sched module, which accounts for the 1 reference that your lsmod shows. From a quick skim of the rest of the code, I think if you release /proc/sched by killing your tail command, you would be able to remove the sched module.</p>
19,866,192
How to get base URL in Web API controller?
<p>I know that I can use <code>Url.Link()</code> to get URL of a specific route, but how can I get Web API base URL in Web API controller?</p>
19,866,294
16
0
null
2013-11-08 18:35:33.897 UTC
8
2020-08-03 17:01:32.193 UTC
2015-11-16 15:46:16.257 UTC
null
3,474,146
null
1,267,021
null
1
84
url|asp.net-web-api|base-url|asp.net-web-api2
185,882
<p>You could use <code>VirtualPathRoot</code> property from <code>HttpRequestContext</code> (<code>request.GetRequestContext().VirtualPathRoot</code>)</p>
40,154,104
Spark 2.0, DataFrame, filter a string column, unequal operator (!==) is deprecated
<p>I am trying to filter a DataFrame by keeping only those rows that have a certain string column non-empty.</p> <p>The operation is the following:</p> <pre><code>df.filter($"stringColumn" !== "") </code></pre> <p>My compiler shows that the !== is deprecated since I moved to Spark 2.0.1</p> <p>How can I check if a string column value is empty in Spark > 2.0?</p>
40,154,140
2
0
null
2016-10-20 12:12:35.06 UTC
2
2022-02-22 16:27:30.37 UTC
2016-10-20 12:15:24.127 UTC
null
1,374,804
null
1,374,804
null
1
26
apache-spark|spark-dataframe
45,070
<p>Use <code>=!=</code> as a replacement:</p> <pre><code>df.filter($"stringColumn" =!= "") </code></pre>
36,857,441
When adding Facebook SDK " appeventslogger.activateapp(this)" is shown deprecated
<p>Using Facebook SDK 4.5. Tried using SDK 4.5 to 4.11. Problem still facing.</p> <p>AS per this changelog : <a href="https://developers.facebook.com/docs/android/change-log-4.x">https://developers.facebook.com/docs/android/change-log-4.x</a></p> <p>Its changed to AppEventsLogger.activateApp(Application)</p> <p>But I am facing trouble while implementing it.</p> <p><a href="https://i.stack.imgur.com/gT0pi.png"><img src="https://i.stack.imgur.com/gT0pi.png" alt="Screenshot"></a>:</p>
36,889,612
1
0
null
2016-04-26 06:57:05.353 UTC
3
2017-02-20 17:14:53.78 UTC
2016-04-28 08:20:51.387 UTC
null
3,618,581
null
4,326,383
null
1
44
android|facebook|android-studio-2.0
12,135
<p>Just replace <code>AppEventsLogger.activateApp(this)</code> to </p> <pre><code>AppEventsLogger.activateApp(getApplication()); </code></pre>
27,389,974
Locally installed versus globally installed NPM modules
<p>In my <code>package.json</code> file, I have bower listed as a dependency. After I run <code>npm install</code>, bower gets installed locally. When I try to run bower after installing it locally I get an error </p> <blockquote> <p>"bower" is not recognized as an internal or external command</p> </blockquote> <p>It seems the only way to resolve this is to install bower globally. Why should I have to do this? If my project contains a local copy of bower, why won't node use it?</p>
27,390,102
4
0
null
2014-12-09 22:21:14.35 UTC
5
2018-08-27 13:28:55.103 UTC
2018-08-27 13:28:55.103 UTC
null
3,924,118
null
668,545
null
1
41
node.js|npm|windows-7|bower
38,776
<p>Installing locally makes bower available to the current project (where it stores all of the node modules in <code>node_modules</code>). This is usually only good for using a module like so <code>var module = require('module');</code> It will not be available as a <strong>command</strong> that the shell can resolve until you install it globally <code>npm install -g module</code> where npm will install it in a place where your path variable will resolve this <strong>command</strong>. </p> <p><strong>Edit:</strong> <a href="https://nodejs.org/en/blog/npm/npm-1-0-global-vs-local-installation/">This documentation</a> explains it pretty thorougly.</p>
21,031,160
When is the connection closed with SignalR from browser
<p>I'm making a little chat application with SignalR 2.0 (just like everyone).</p> <p>I have a win8.1 application and when the application is closed, the hub receives the OnDisconnected event and removes the user from the list on the hub. The hub sends to every client that the user has left the chat, so we can visualize that the user has left.</p> <p>But when I'm using SignalR and Javascript in a webpage and the page gets closed, the hub doesn't get notified that the tab/browser is closed...</p> <p>Anyone any idea how the connection can be closed?</p> <p>What i've coded:</p> <p><strong>Startup Hub</strong></p> <pre><code>[assembly: OwinStartup(typeof(ChatServer.Startup))] namespace ChatServer { public class Startup { public void Configuration(IAppBuilder app) { // Map all hubs to "/signalr" app.MapSignalR(); } } } </code></pre> <p><strong>Hub</strong></p> <pre><code>[HubName("ChatHub")] public class ChatHub : Hub { private static List&lt;User&gt; Users = new List&lt;User&gt;(); public void Send(string name, string message) { // Call the broadcastMessage method to update clients. Clients.All.broadcastMessage(name, message, DateTime.Now); } public void UserConnected(string name) { Clients.Caller.connected(JsonConvert.SerializeObject(Users)); User user = new User() { Name = name, ConnectionID = Context.ConnectionId }; Clients.Others.userConnected(JsonConvert.SerializeObject(user)); Users.Add(user); } public void UserLeft() { if(Users.Any(x=&gt;x.ConnectionID == Context.ConnectionId)) { User user = Users.First(x =&gt; x.ConnectionID == Context.ConnectionId); Users.Remove(user); Clients.Others.userLeft(JsonConvert.SerializeObject(user), Context.ConnectionId); } } public override System.Threading.Tasks.Task OnDisconnected() { // Only called when win8.1 app closes // Not called when browsers closes page UserLeft(); return base.OnDisconnected(); } } </code></pre> <p><strong>HTML - Javascript:</strong></p> <p>Javascript:</p> <pre><code>chat = new function () { var ChatHub; // Connecting to the hub this.attachEvents = function () { if ($.connection != null) { ChatHub = $.connection.ChatHub; $.connection.hub.start({ transport: 'auto' }, function () { // Register client on hub ChatHub.server.userConnected("web name"); }); } this.send = function (name,message) { if ($.connection != null) { //Send chat message ChatHub.server.send(name, message).fail(function (e) { alert(e); }); } } } }; window.onbeforeunload = function (e) { //This is called when we close the page $.connection.hub.stop(); return "You killed me! :'("; }; </code></pre> <p><strong>Win8.1 client</strong></p> <pre><code> internal async void ConnectToHub(string userName) { try { HubConnection hubConnection = new HubConnection(SERVER_PROXY); chat = hubConnection.CreateHubProxy("ChatHub"); Context = SynchronizationContext.Current; MakeHubFunctionsAvailableOnClient(); await hubConnection.Start(); // Register client on hub await chat.Invoke("UserConnected", userName); } catch (Exception) { throw; } } private void MakeHubFunctionsAvailableOnClient() { //Receive chat messages chat.On&lt;string, string, DateTime&gt;("broadcastMessage", (name, message, date) =&gt; Context.Post( delegate { Messages.Add(new UserMessage() { Message = message, User = name, Date = date }); }, null ) ); //Receive all online users chat.On&lt;string&gt;("connected", (users) =&gt; Context.Post( delegate { List&lt;User&gt; userList = JsonConvert.DeserializeObject&lt;List&lt;User&gt;&gt;(users); foreach (User user in userList) { Users.Add(user); } Messages.Add(new UserMessage() { Message = "CONNECTED", User = "System", Date = DateTime.Now }); }, null ) ); //New user connected chat.On&lt;string&gt;("userConnected", (user) =&gt; Context.Post( delegate { User newUser = JsonConvert.DeserializeObject&lt;User&gt;(user); Users.Add(newUser); Messages.Add(new UserMessage() { Message = newUser.Name + " CONNECTED", User = "System", Date = DateTime.Now }); }, null ) ); //User left, remove user from list on client chat.On&lt;string&gt;("userLeft", (user) =&gt; Context.Post( delegate { User newUser = JsonConvert.DeserializeObject&lt;User&gt;(user); User y = Users.First(x=&gt;x.ConnectionID == newUser.ConnectionID); bool ux = Users.Remove(y); Messages.Add(new UserMessage() { Message = newUser.Name + " left the conversation", User = "System", Date = DateTime.Now }); }, null ) ); } </code></pre> <p>My hub doesn't trigger OnDisconnected, when i close tab / browser / navigating to other site The site is a singe page website (for the moment)</p> <p>What browser am i using? <br />Chrome: Version 32.0.1700.68 beta-m <br/>Internet Explorer 11 </p>
21,031,579
2
0
null
2014-01-09 21:08:14.26 UTC
8
2017-09-12 15:52:19.063 UTC
2014-01-10 18:49:12.217 UTC
null
1,080,372
null
1,080,372
null
1
7
javascript|signalr
23,991
<p>I guess your question is how to detect whether a specific user left or closed the browser. When a user comes in or leaves, send a notification to other users.</p> <p>I think the problem is you didn't handle <code>OnConnected</code> and <code>OnDisconnected</code> properly. To make it work, first you need to know each client connecting to a hub passes a unique connection id. You can retrieve this value in the Context.ConnectionId property of the hub context. When each client comes in, they go through <code>OnConnected</code>, when they leave, they go through <code>OnDisconnected</code>. Below is a working example:</p> <p><strong>Hub Class</strong></p> <pre><code>[HubName("ChatHub")] public class ChatHub : Hub { private static List&lt;User&gt; Users = new List&lt;User&gt;(); public void Send(string message) { var name = Context.User.Identity.Name; Clients.All.broadcastMessage(name, message, DateTime.Now.ToShortDateString()); } public override Task OnConnected() { User user = new User() { Name = Context.User.Identity.Name, ConnectionID = Context.ConnectionId }; Users.Add(user); Clients.Others.userConnected(user.Name); return base.OnConnected(); } public override Task OnDisconnected() { if (Users.Any(x =&gt; x.ConnectionID == Context.ConnectionId)) { User user = Users.First(x =&gt; x.ConnectionID == Context.ConnectionId); Clients.Others.userLeft(user.Name); Users.Remove(user); } return base.OnDisconnected(); } } </code></pre> <p><strong>View</strong></p> <pre><code>&lt;input type="text" id="message" /&gt; &lt;button class="btn"&gt;Send&lt;/button&gt; &lt;ul id="contents"&gt;&lt;/ul&gt; @section scripts { &lt;script src="~/Scripts/jquery-1.10.2.js"&gt;&lt;/script&gt; &lt;script src="~/Scripts/jquery.signalR-2.0.1.js"&gt;&lt;/script&gt; &lt;script src="/signalr/hubs"&gt;&lt;/script&gt; &lt;script&gt; var chatHub = $.connection.ChatHub; chatHub.client.broadcastMessage = function (name, message, time) { var encodedName = $('&lt;div /&gt;').text(name).html(); var encodedMsg = $('&lt;div /&gt;').text(message).html(); var encodedTime = $('&lt;div /&gt;').text(time).html(); $('#contents').append('&lt;li&gt;&lt;strong&gt;' + encodedName + '&lt;/strong&gt;:&amp;nbsp;&amp;nbsp;' + encodedMsg + '&lt;/strong&gt;:&amp;nbsp;&amp;nbsp;' + encodedTime + '&lt;/li&gt;'); }; chatHub.client.userConnected = function (data) { $('#contents').append('&lt;li&gt;Wellcome&lt;strong&gt;' + '&lt;/strong&gt;:' + data + '&lt;/li&gt;'); }; chatHub.client.userLeft = function (data) { $('#contents').append('&lt;li&gt;Bye&lt;strong&gt;' + '&lt;/strong&gt;:' + data + '&lt;/li&gt;'); }; $(".btn").on("click", function() { chatHub.server.send($("#message").val()); }); $.connection.hub.start().done(function() { console.log("connected..."); }); &lt;/script&gt; } </code></pre>
38,563,217
Converting getdate() to yyyymmdd & getting the date two years back
<p>I have found a couple of different methods to convert it. However, I still get the <code>yyyy-mm-dd</code> format or <code>yyyy-mm-dd hh:mm:ss</code>. I am currently using SQL Server 2014.</p> <pre><code>SELECT dateadd(day, convert(int, getdate()), 112) SELECT DATEADD(YEAR, -2, convert(DATE, GETDATE(), 112)) </code></pre> <p>I am doing a date range of 2 years. Thus I need the codes to the find the date two years back. </p>
38,563,486
2
5
null
2016-07-25 08:45:26.087 UTC
null
2019-01-22 09:45:19.56 UTC
2016-07-25 09:38:41.39 UTC
null
472,495
null
6,616,946
null
1
5
sql|sql-server|sql-server-2014
66,191
<p>You can also use FORMAT:</p> <pre><code> select FORMAT(getdate(), 'yyyyMMdd') </code></pre>
44,259,851
Set restAssured to log all requests and responses globally
<p>I want to enable logging for all <code>RestAssured</code> responses and requests by default.</p> <p>Here's what I do:</p> <pre><code>RestAssured.requestSpecification = new RequestSpecBuilder(). setBaseUri(&quot;api&quot;). setContentType(ContentType.JSON). build(). log().all(); RestAssured.responseSpecification = new ResponseSpecBuilder(). build(). log().all(); </code></pre> <p><code>requestSpecification</code> works alright, but with <code>responseSpecification</code> I get:</p> <blockquote> <p>Cannot configure logging since request specification is not defined. You may be misusing the API.</p> </blockquote> <p>I really don't want to use <code>log().all()</code> after each then.</p>
44,316,721
4
0
null
2017-05-30 10:34:58.833 UTC
3
2021-04-14 18:41:17.583 UTC
2021-04-14 18:41:17.583 UTC
null
7,451,109
null
4,572,848
null
1
35
java|rest|logging|rest-assured
53,264
<p>Add logging filters to RestAssured defaults, see <a href="https://github.com/rest-assured/rest-assured/wiki/Usage#filters" rel="noreferrer">filters</a> and <a href="https://github.com/rest-assured/rest-assured/wiki/Usage#default-values" rel="noreferrer">defaults</a>.</p> <blockquote> <p>To create a filter you need to implement the io.restassured.filter.Filter interface. To use a filter you can do:<br> given().filter(new MyFilter()). .. </p> <p>There are a couple of filters provided by REST Assured that are ready to use:<br> 1. io.restassured.filter.log.RequestLoggingFilter: A filter that'll print the request specification details.<br> 2. io.restassured.filter.log.ResponseLoggingFilter: A filter that'll print the response details if the response matches a given status code.<br> 3. io.restassured.filter.log.ErrorLoggingFilter: A filter that'll print the response body if an error occurred (status code is between 400 and 500)</p> </blockquote> <p>Any filter could be added to request, spec or global defaults:</p> <blockquote> <p>RestAssured.filters(..); // List of default filters</p> </blockquote>
41,728,043
Detect when input value changed in directive
<p>I'm trying to detect when the <strong>value</strong> of an input changed in a directive. I have the following directive:</p> <pre class="lang-js prettyprint-override"><code> import { ElementRef, Directive, Renderer} from '@angular/core'; @Directive({ selector: '[number]', host: {"(input)": 'onInputChange($event)'} }) export class Number { constructor(private element: ElementRef, private renderer: Renderer){ } onInputChange(event){ console.log('test'); } } </code></pre> <p>The problem in this directive is that it detects only when there is an input and not when the value changes programatically. I use reacive form and sometimes I set the value with the <code>patchValue()</code> function. How can I do so the change function gets triggered?</p>
41,728,823
4
0
null
2017-01-18 19:39:56.15 UTC
8
2022-09-02 08:59:10.967 UTC
2020-03-09 12:13:32.047 UTC
null
7,795,731
null
276,439
null
1
56
angular|angular-directive|angular2-directives
85,905
<p>You need to make an input property of <code>input</code> and then use the <code>ngOnChanges</code> hook to tell when the input property changes.</p> <pre class="lang-js prettyprint-override"><code>@Directive({ selector: '[number]' }) export class NumberDirective implements OnChanges { @Input() public number: any; @Input() public input: any; ngOnChanges(changes: SimpleChanges){ if(changes.input){ console.log('input changed'); } } } </code></pre> <h1><a href="http://plnkr.co/edit/Ygd9CDWg2OxG6n88zRqD" rel="noreferrer">Plunkr</a></h1> <h1><a href="https://stackblitz.com/edit/angular-ufm4wv" rel="noreferrer">Stackblitz</a></h1>
39,255,973
Split 1 column into 3 columns in spark scala
<p>I have a dataframe in Spark using scala that has a column that I need split.</p> <pre><code>scala&gt; test.show +-------------+ |columnToSplit| +-------------+ | a.b.c| | d.e.f| +-------------+ </code></pre> <p>I need this column split out to look like this:</p> <pre><code>+--------------+ |col1|col2|col3| | a| b| c| | d| e| f| +--------------+ </code></pre> <p>I'm using Spark 2.0.0</p> <p>Thanks</p>
39,256,038
7
0
null
2016-08-31 17:47:31.107 UTC
24
2021-05-27 19:38:29.99 UTC
null
null
null
null
695,240
null
1
42
scala|apache-spark
93,624
<p>Try:</p> <pre><code>import sparkObject.spark.implicits._ import org.apache.spark.sql.functions.split df.withColumn("_tmp", split($"columnToSplit", "\\.")).select( $"_tmp".getItem(0).as("col1"), $"_tmp".getItem(1).as("col2"), $"_tmp".getItem(2).as("col3") ) </code></pre> <p>The important point to note here is that the <code>sparkObject</code> is the SparkSession object you might have already initialized. So, the (1) import statement has to be compulsorily put inline within the code, not before the class definition.</p>
31,815,205
Use Personal.xlsb function in new workbook?
<p>I've searched around and I know how to call a function from Personal.xlsb from a VB macro, but how can I call the function to be used in a new workbook?</p> <p>Here's my function, saved in 'Module1' in my <code>Personal.xlsb</code>:</p> <pre><code>Public Function GetColumnLetter(colNum As Integer) As String Dim d As Integer Dim m As Integer Dim name As String d = colNum name = "" Do While (d &gt; 0) m = (d - 1) Mod 26 name = Chr(65 + m) + name d = Int((d - m) / 26) Loop GetColumnLetter= name End Function </code></pre> <p>I have created a new workbook and thought I could call that just by <code>=getcolumnletter(1)</code>, but the function doesn't "populate" when I start typing <code>=...</code> </p> <p>Am I overlooking something?? How do I use this function in other workbooks, without VBA?</p> <p>Thanks for any advice!</p>
31,815,353
4
0
null
2015-08-04 17:03:12.613 UTC
10
2021-09-01 14:51:48.617 UTC
2015-08-04 17:09:24.683 UTC
null
4,650,297
null
4,650,297
null
1
23
vba|excel
21,636
<p>Ah, it was more simple than I thought. Just use the workbook name before the macro - so</p> <pre><code>=Personal.xlsb![macroname] </code></pre> <p>So in my case, I just put this into the cell: <code>=Personal.xlsb!GetColumnLetter(2)</code> to return &quot;B&quot;.</p>
28,484,398
Starting Zookeeper Cluster. Error: Could not find or load main class org.apache.zookeeper.server.quorum.QuorumPeerMain
<p>(I'm running on CentOS 5.8). I've been following the direction for a <a href="http://zookeeper.apache.org/doc/r3.3.3/zookeeperAdmin.html#sc_zkMulitServerSetup" rel="noreferrer">Clustered (Multiserver) Zookeeper Set-up</a>, but getting an error when I try to start up my server. When I run the command as described in the documentation:</p> <pre><code>java -cp zookeeper-3.4.6.jar:lib/log4j-1.2.16.jar:conf \ org.apache.zookeeper.server.quorum.QuorumPeerMain conf/zoo.cfg </code></pre> <p>I get the error: </p> <pre><code>Error: Could not find or load main class org.apache.zookeeper.server.quorum.QuorumPeerMain </code></pre> <p>I have my files location as such and am running from the ~/zookeeper-3.4.6 directory:</p> <pre><code>~/zookeeper-3.4.6/zookeeper-3.4.6.jar ~/zookeeper-3.4.6/conf/zoo.cfg ~/zookeeper-3.4.6/data/myid ~/zookeeper-3.4.6/lib/log4j-1.2.16.jar ~/zookeeper-3.4.6/bin/zkServer.sh </code></pre> <p>Does anyone know why this error is happening? I don't quite understand the arguments that are being passed, so it is hard for me to debug the path issue. As a side note, I've tried running <code>./zookeeper-3.4.6/bin/zkServer.sh start</code>, which did successfully work, but the documentation seems to indicate that command is meant for a single-node instance. </p> <p><strong>Edit</strong>:</p> <p>I was able to make <em>some</em> progress by modifying the command and taking out the <code>:conf \</code> part, so now I'm running:</p> <pre><code>java -cp zookeeper-3.4.6.jar:lib/log4j-1.2.16.jar: org.apache.zookeeper.server.quorum.QuorumPeerMain conf/zoo.cfg </code></pre> <p>I get a new error, but this is progress...</p> <pre class="lang-html prettyprint-override"><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFacto ry at org.apache.zookeeper.server.quorum.QuorumPeerMain.&lt;clinit&gt;(QuorumPeer Main.java:64) Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory at java.net.URLClassLoader$1.run(URLClassLoader.java:366) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) ... 1 more </code></pre> <p>which corresponds to lines 63 and 64 from QuorumPeerMain</p> <pre><code>public class QuorumPeerMain { private static final Logger LOG = LoggerFactory.getLogger(QuorumPeerMain.class); </code></pre>
28,488,883
7
0
null
2015-02-12 17:51:47.74 UTC
6
2022-07-08 12:52:23.427 UTC
2015-02-12 19:05:55.673 UTC
null
923,986
null
923,986
null
1
25
apache|cluster-computing|apache-zookeeper
55,702
<p>You should be able to run zkServer.sh to get a clustered setup. It will use the same conf/zoo.cfg that you are providing manually, which will contain the cluster endpoints.</p> <p>The best way to check what you are missing from your classpath (and see the proper java command) is to run the zkServer.sh you said worked for you. </p> <p>When it starts up, check the actual command used like this:</p> <pre><code>ps -ef | grep zookeeper </code></pre>
5,662,538
Android display another dialog from a dialog
<p>I am trying to display a dialog from the onClick listener of a button of another dialog, but the 2nd dialog won't display. I searched and found a similar problem- <a href="https://stackoverflow.com/questions/3989767/dialogs-order-in-android">Dialogs order in Android</a>, tried the solution provided, but even that does not work.</p> <p>My code is very similar to the one provided in the answer.</p> <blockquote> <p>public void onClick(DialogInterface dialog, int id) { showDialog(SECOND_DIALOG); dialog.dismiss(); }</p> </blockquote> <p>any help will be really appreciated.</p> <p>Thanks,</p> <p>Akshay</p>
5,663,010
3
2
null
2011-04-14 11:29:40.133 UTC
6
2016-09-08 07:29:01.29 UTC
2017-05-23 10:31:06.357 UTC
null
-1
null
705,627
null
1
15
android|dialog
52,379
<p>This is how I'm doing it:</p> <pre><code> if (!appPrefs.getAcceptedUsageAggrement()) { tracker.trackPageView("/UsageAgreementDialog"); acceptedUsage_alertDialog = new AlertDialog.Builder(BroadcastSMSActivity.this) .setTitle(R.string.accept_usage_title) .setMessage(R.string.accept_usage_message) .setNegativeButton(android.R.string.cancel, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }) .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (appPrefs.getAppVer().equals("")) { tracker.trackEvent("Application", "Install", getAppVerName(), 1); } else { tracker.trackEvent("Application", "Upgrade", appPrefs.getAppVer().toString()+"-&gt;"+getAppVerName(), 1); } displayRecentChanges = true; appPrefs.saveAppVer(getAppVerName()); appPrefs.saveAcceptedUsageAggrement(true); // Display Recent Changes on 1st use of new version if (displayRecentChanges) { tracker.trackPageView("/RecentChangesDialog"); recentChanges_alertDialog = new AlertDialog.Builder(BroadcastSMSActivity.this) .setTitle(getString(R.string.changes_title, getAppVerName())) .setMessage(R.string.changes_dialog) .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { recentChanges_alertDialog.cancel(); acceptedUsage_alertDialog.cancel(); } }) .create(); recentChanges_alertDialog.show(); } } }) .create(); acceptedUsage_alertDialog.show(); } </code></pre>
6,154,879
Nginx - wordpress in a subdirectory, what data should be passed?
<p>I've tried so many different things. The point I'm at right now is this:</p> <pre><code>location ^~ /wordpress { alias /var/www/example.com/wordpress; index index.php index.html index.htm; try_files $uri $uri/ /wordpress/index.php; location ~ \.php$ { include fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_split_path_info ^(/wordpress)(/.*)$; fastcgi_param SCRIPT_FILENAME /var/www/example.com/wordpress/index.php; fastcgi_param PATH_INFO $fastcgi_path_info; } } </code></pre> <p>Right now, all resources as far as I can tell (images, etc) are loading correctly. And <code>http://www.example.com/wordpress</code> loads wordpress, but a page that says "page not found". (Wordpress is in use for this though). If I try any post urls I get the same result, "page not found". So I know the problem is that wordpress isn't obtaining the data about the path or something. Another potential problem is that if I run <code>example.com/wp-admin.php</code> then it will still run <code>index.php</code>.</p> <p>What data needs to be passed? What may be going wrong here?</p>
6,155,935
3
0
null
2011-05-27 16:04:24.03 UTC
22
2020-01-07 13:12:06.947 UTC
null
null
null
null
299,216
null
1
36
php|wordpress|path|nginx|webserver
36,345
<p>Since your location alias end match, you should just use root. Also, not <em>everything</em> is routed through index.php on wordpress afaik. Also, unless you know you need path info, you probably dont. I think you want something like:</p> <pre><code>location @wp { rewrite ^/wordpress(.*) /wordpress/index.php?q=$1; } location ^~ /wordpress { root /var/www/example.com; index index.php index.html index.htm; try_files $uri $uri/ @wp; location ~ \.php$ { include fastcgi_params; fastcgi_param SCRIPT_FILENAME $request_filename; fastcgi_pass 127.0.0.1:9000; } } </code></pre> <p>or if you really do need path info (urls look like /wordpress/index.php/foo/bar):</p> <pre><code>location ^~ /wordpress { root /var/www/example.com; index index.php index.html index.htm; try_files $uri $uri/ /wordpress/index.php; location ~ \.php { fastcgi_split_path_info ^(.*\.php)(.*)$; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info; fastcgi_pass 127.0.0.1:9000; } } </code></pre> <p>EDIT: Updated first server{} to strip initial /wordpress from uri and pass remainder as q param</p> <p>EDIT2: Named locations are only valid at server level</p>
6,080,596
How can I load this file into an NUnit Test?
<p>I have the following IntegrationTest project structure ...</p> <p><img src="https://i.stack.imgur.com/HRR0O.png" alt="enter image description here"></p> <p>If i wish to use that test data <code>126.txt</code> in an <code>NUnit Test</code>, how do I load that plain txt file data? </p> <p>NOTE: The file is <code>-linked-</code> and I'm using c# (as noted by the image).</p> <p>cheers :)</p>
6,080,607
4
0
null
2011-05-21 08:35:43.99 UTC
13
2022-02-18 14:32:45.35 UTC
null
null
null
null
30,674
null
1
64
c#|.net|testing|tdd|nunit
40,678
<p>You could specify in the properties of the file to be copied to the output folder and inside the unit test:</p> <pre><code>string text = File.ReadAllText(Path.Combine(TestContext.CurrentContext.TestDirectory, &quot;TestData&quot;, &quot;126.txt&quot;)); </code></pre> <p>As an alternative you could embed this file as a resource into the test assembly and then:</p> <pre><code>var assembly = Assembly.GetExecutingAssembly(); using (var stream = assembly.GetManifestResourceStream(&quot;ProjectName.Tests.IntegrationTests.TestData.126.txt&quot;)) using (var reader = new StreamReader(stream)) { string text = reader.ReadToEnd(); } </code></pre>
34,786,115
Swift doesn't convert Objective-C NSError** to throws
<p>I have some Objective-C legacy code, that declares method like</p> <pre><code>- (void)doSomethingWithArgument:(ArgType)argument error:(NSError **)error </code></pre> <p>As written here <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html" rel="noreferrer">https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html</a> </p> <blockquote> <p>Swift automatically translates Objective-C methods that produce errors into methods that throw an error according to Swift’s native error handling functionality.</p> </blockquote> <p>But in my project described methods are called like this:</p> <pre><code>object.doSomething(argument: ArgType, error: NSErrorPointer) </code></pre> <p>Moreover, it throws runtime exception when I try to use them like:</p> <pre><code>let errorPtr = NSErrorPointer() object.doSomething(argumentValue, error: errorPtr) </code></pre> <p>Do I need something more to convert Objective-C "NSError **" methods to Swift "trows" methods?</p>
34,787,941
2
1
null
2016-01-14 09:40:47.15 UTC
8
2021-08-04 09:45:09.01 UTC
2019-01-03 08:20:25.01 UTC
null
100,297
null
3,989,175
null
1
29
ios|objective-c|swift|nserror
9,143
<p>Only <code>Objective-C</code> methods are translated to throwing <code>Swift</code> methods, which do return a <code>BOOL</code> (not lower-cased <code>bool</code>), or a nullable-object. (Tested with Xcode 11.7, and Swift 5 language.)</p> <p>The reason is that Cocoa methods always use a return value <code>NO</code> or <code>nil</code> to indicate the failure of a method, and <em>not</em> just set an error object. This is documented in <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html" rel="noreferrer">Using and Creating Error Objects</a>:</p> <blockquote> <p><strong>Important:</strong> Success or failure is indicated by the return value of the method. Although Cocoa methods that indirectly return error objects in the Cocoa error domain are guaranteed to return such objects if the method indicates failure by directly returning nil or NO, you should always check that the return value is nil or NO before attempting to do anything with the NSError object.</p> </blockquote> <p>For example, the Objective-C interface</p> <pre><code>@interface OClass : NSObject NS_ASSUME_NONNULL_BEGIN -(void)doSomethingWithArgument1:(int) x error:(NSError **)error; -(BOOL)doSomethingWithArgument2:(int) x error:(NSError **)error; -(NSString *)doSomethingWithArgument3:(int) x error:(NSError **)error; -(NSString * _Nullable)doSomethingWithArgument4:(int) x error:(NSError **)error; -(BOOL)doSomething:(NSError **)error; NS_ASSUME_NONNULL_END @end </code></pre> <p>is mapped to Swift as</p> <pre><code>open class OClass : NSObject { open func doSomethingWithArgument1(x: Int32, error: NSErrorPointer) open func doSomethingWithArgument2(x: Int32) throws open func doSomethingWithArgument3(x: Int32, error: NSErrorPointer) -&gt; String open func doSomethingWithArgument4(x: Int32) throws -&gt; String open func doSomething() throws } </code></pre> <p>If you can change the interface of your method then you should add a boolean return value to indicate success or failure.</p> <p>Otherwise you would call it from Swift as</p> <pre><code>var error : NSError? object.doSomethingWithArgument(argumentValue, error: &amp;error) if let theError = error { print(theError) } </code></pre> <p><em>Remark:</em> At</p> <ul> <li><a href="https://github.com/apple/swift/blob/master/test/Inputs/clang-importer-sdk/usr/include/errors.h" rel="noreferrer">https://github.com/apple/swift/blob/master/test/Inputs/clang-importer-sdk/usr/include/errors.h</a></li> </ul> <p>I found that Clang has an attribute which forces a function to throw an error in Swift:</p> <pre><code>-(void)doSomethingWithArgument5:(int) x error:(NSError **)error __attribute__((swift_error(nonnull_error))); </code></pre> <p>is mapped to Swift as</p> <pre><code>public func doSomethingWithArgument5(x: Int32) throws </code></pre> <p>and seems to work &quot;as expected&quot;. However, I could not find any official documentation about this attribute, so it might not be a good idea to rely on it.</p>
28,973,253
How to search nearby places stored in my database?
<p>I'm developing a web app where the user sets a place in a map (Google Maps API) and I store the coordinates in a database.</p> <p>At another page, I want to do a search which consists in getting my local coordinates and retrieve nearby places previously stored at my database based on a radius.</p> <p>How can I do this?</p>
28,982,339
2
1
null
2015-03-10 20:14:06.82 UTC
9
2020-08-12 04:18:40.02 UTC
2020-08-12 04:18:40.02 UTC
null
214,143
null
1,521,080
null
1
8
google-maps|google-maps-api-3
6,887
<p>You can use what is called the <a href="http://en.wikipedia.org/wiki/Haversine_formula">Haversine formula</a>.</p> <pre><code>$sql = "SELECT *, ( 3959 * acos( cos( radians(" . $lat . ") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(" . $lng . ") ) + sin( radians(" . $lat . ") ) * sin( radians( lat ) ) ) ) AS distance FROM your_table HAVING distance &lt; 5"; </code></pre> <p>Where <code>$lat</code> and <code>$lng</code> are the coordinates of your point, and <code>lat</code> / <code>lng</code> are your table columns. The above will list the locations within a 5 nm range. Replace <code>3959</code> by <code>6371</code> to change to kilometers.</p>
50,482,814
Image preview before upload in angular 5
<p>I have this code to show the image preview before uploading it. However I am working with Angular 5 so I have a <code>.ts</code> file instead of a <code>.js</code> one. How can I do the same in Angular 5? I also want to show the image in all browsers.</p> <p>My HTML:</p> <pre class="lang-html prettyprint-override"><code>&lt;input type='file' onchange=&quot;readURL(this);&quot;/&gt; &lt;img id=&quot;blah&quot; src=&quot;http://placehold.it/180&quot; alt=&quot;your image&quot;/&gt; </code></pre> <p>My CSS:</p> <pre class="lang-css prettyprint-override"><code>img { max-width:180px; } input[type=file] { padding: 10px; background: #2d2d2d; } </code></pre> <p>My JavaScript:</p> <pre class="lang-js prettyprint-override"><code>function readURL(input) { if (input.files &amp;&amp; input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { document.getElementById('blah').src=e.target.result }; reader.readAsDataURL(input.files[0]); } } </code></pre>
50,483,118
9
2
null
2018-05-23 07:53:53.647 UTC
7
2021-12-19 15:51:14.017 UTC
2021-12-19 15:51:14.017 UTC
null
16,543,631
null
9,762,627
null
1
23
javascript|angular|image|file-upload|path
58,730
<p>.html</p> <p>Update event attr and handler param for input. And you should use data binding for src attribute. Following will apply src if it's not null or undefined or hardcoded url ('<a href="http://placehold.it/180" rel="noreferrer">http://placehold.it/180</a>')</p> <pre><code>&lt;input type='file' (change)="readURL($event);" /&gt; &lt;img id="blah" [src]="imageSrc || 'http://placehold.it/180'" alt="your image" /&gt; </code></pre> <p>.ts</p> <p>In component ts file (class) you should have property <code>imageSrc</code> which be used in view (html) and your function should be a method of that class</p> <pre><code>... imageSrc: string; ... constructor(...) {...} ... readURL(event: Event): void { if (event.target.files &amp;&amp; event.target.files[0]) { const file = event.target.files[0]; const reader = new FileReader(); reader.onload = e =&gt; this.imageSrc = reader.result; reader.readAsDataURL(file); } } </code></pre>
32,393,026
Exclude multiple folders using AWS S3 sync
<p>How to exclude multiple folders while using aws s3 syn ?</p> <p>I tried :</p> <pre><code> # aws s3 sync s3://inksedge-app-file-storage-bucket-prod-env \ s3://inksedge-app-file-storage-bucket-test-env \ --exclude 'reportTemplate/* orders/* customers/*' </code></pre> <p>But still it's doing sync for folder &quot;customer&quot;</p> <p>Output :</p> <pre><code> copy: s3://inksedge-app-file-storage-bucket-prod-env/customers/116/miniimages/IMG_4800.jpg to s3://inksedge-app-file-storage-bucket-test-env/customers/116/miniimages/IMG_4800.jpg copy: s3://inksedge-app-file-storage-bucket-prod-env/customers/116/miniimages/DSC_0358.JPG to s3://inksedge-app-file-storage-bucket-test-env/customers/116/miniimages/DSC_0358.JPG </code></pre>
32,394,703
4
1
null
2015-09-04 08:01:54.947 UTC
10
2021-08-27 04:20:58.327 UTC
2021-08-27 04:20:58.327 UTC
null
11,861,319
null
3,425,138
null
1
77
amazon-web-services|amazon-s3|s3cmd
79,010
<p>At last this worked for me:</p> <pre><code>aws s3 sync s3://my-bucket s3://my-other-bucket \ --exclude 'customers/*' \ --exclude 'orders/*' \ --exclude 'reportTemplate/*' </code></pre> <p><strong>Hint</strong>: you have to enclose your wildcards and special characters in single or double quotes to work properly. Below are examples of matching characters. for more information regarding S3 commands, check it in <a href="http://docs.aws.amazon.com/cli/latest/reference/s3/" rel="noreferrer">amazon here</a>.</p> <pre><code>*: Matches everything ?: Matches any single character [sequence]: Matches any character in sequence [!sequence]: Matches any character not in sequence </code></pre>
5,652,957
What event catches a change of value in a combobox in a DataGridViewCell?
<p>I want to handle the event when a value is changed in a <code>ComboBox</code> in a <code>DataGridView</code> cell.</p> <p>There's the <code>CellValueChanged</code> event, but that one doesn't fire until I click somewhere else inside the <code>DataGridView</code>. </p> <p>A simple <code>ComboBox</code> <code>SelectedValueChanged</code> does fire immediately after a new value is selected. </p> <p>How can I add a listener to the combobox that's inside the cell?</p>
21,321,724
5
0
null
2011-04-13 17:09:27.783 UTC
9
2021-04-14 19:55:27.167 UTC
2016-06-15 21:19:40.147 UTC
null
214,296
null
249,878
null
1
35
c#|.net|datagridview|combobox|event-handling
73,140
<p>The above answer led me down the primrose path for awhile. It does not work as it causes multiple events to fire and just keeps adding events. The problem is that the above catches the DataGridViewEditingControlShowingEvent and it does not catch the value changed. So it will fire every time you focus then leave the combobox whether it has changed or not.</p> <p>The last answer about <code>CurrentCellDirtyStateChanged</code> is the right way to go. I hope this helps someone avoid going down a rabbit hole.</p> <p>Here is some code:</p> <pre class="lang-cs prettyprint-override"><code>// Add the events to listen for dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged); dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged); // This event handler manually raises the CellValueChanged event // by calling the CommitEdit method. void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e) { if (dataGridView1.IsCurrentCellDirty) { // This fires the cell value changed handler below dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit); } } private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) { // My combobox column is the second one so I hard coded a 1, flavor to taste DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[1]; if (cb.Value != null) { // do stuff dataGridView1.Invalidate(); } } </code></pre>
5,630,689
Select all empty tables in SQL Server
<p>How to get the list of the tables in my <code>sql-server</code> database that do not have any records in them?</p>
5,630,752
6
1
null
2011-04-12 05:15:13.083 UTC
9
2021-06-18 06:04:56.627 UTC
2018-05-30 11:31:07.237 UTC
null
6,281,993
null
507,669
null
1
30
sql-server|tsql
40,100
<p>On SQL Server 2005 and up, you can use something like this:</p> <pre><code>;WITH TableRows AS ( SELECT SUM(row_count) AS [RowCount], OBJECT_NAME(OBJECT_ID) AS TableName FROM sys.dm_db_partition_stats WHERE index_id = 0 OR index_id = 1 GROUP BY OBJECT_ID ) SELECT * FROM TableRows WHERE [RowCount] = 0 </code></pre> <p>The inner select in the CTE (Common Table Expression) calculates the number of rows for each table and groups them by table (<code>OBJECT_ID</code>), and the outer SELECT from the CTE then grabs only those rows (tables) which have a total number of rows equal to zero.</p> <p><strong>UPDATE:</strong> if you want to check for non-Microsoft / system tables, you need to extend the query like this (joining the <code>sys.tables</code> catalog view):</p> <pre><code>;WITH TableRows AS ( SELECT SUM(ps.row_count) AS [RowCount], t.Name AS TableName FROM sys.dm_db_partition_stats ps INNER JOIN sys.tables t ON t.object_id = ps.object_id WHERE (ps.index_id = 0 OR ps.index_id = 1) AND t.is_ms_shipped = 0 GROUP BY t.Name ) SELECT * FROM TableRows WHERE [RowCount] = 0 </code></pre>
6,225,392
How to get first two characters of a string in oracle query?
<p>Suppose I have a column name <code>OrderNo</code> with value <code>AO025631</code> in a table <code>shipment</code>.</p> <p>I am trying to query the table so that I can get only first two character of column value i.e. <code>AO</code>.</p> <p>Can I do this in the SQL query itself? </p>
6,225,414
6
0
null
2011-06-03 09:40:00.93 UTC
4
2022-08-09 21:57:36.91 UTC
2013-06-19 08:15:14.487 UTC
null
1,065,525
null
517,066
null
1
61
sql|oracle
317,166
<p><strong><em>SUBSTR</em></strong> <a href="http://download.oracle.com/docs/cd/B28359_01/olap.111/b28126/dml_functions_2101.htm" rel="noreferrer">(documentation)</a>:</p> <pre><code>SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName from shipment </code></pre> <p>When selected, it's like any other column. You should give it a name (with <code>As</code> keyword), and you can selected other columns in the same statement:</p> <pre><code>SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName, column2, ... from shipment </code></pre>
5,956,999
What does "return $this" mean?
<p>I'm trying to understand this code, and when I arrived at the final line, I didn't get it. :(</p> <p><strong>Can I have your help in order to find out, what does <code>return $this</code> mean ?</strong></p> <pre><code>public function setOptions(array $options) { $methods = get_class_methods($this); foreach ($options as $key =&gt; $value) { $method = 'set' . ucfirst($key); if (in_array($method, $methods)) { $this-&gt;$method($value); } } //???? - return what ? return $this; } </code></pre> <p><strong>Update:</strong><br> I've removed my comments for better clarification.</p>
5,957,038
7
2
null
2011-05-10 21:59:00.677 UTC
16
2019-02-11 14:11:53.393 UTC
2014-01-30 17:11:52.297 UTC
null
507,738
null
378,170
null
1
33
php|oop|zend-framework|return
28,905
<p>This way of coding is called <a href="https://secure.wikimedia.org/wikipedia/en/wiki/Fluent_interface"><em>fluent interface</em></a>. <code>return $this</code> returns the current object, so you can write code like this:</p> <pre><code>$object -&gt;function1() -&gt;function2() -&gt;function3() ; </code></pre> <p>instead of:</p> <pre><code>$object-&gt;function1(); $object-&gt;function2(); $object-&gt;function3(); </code></pre>
17,708,971
Using custom simpleCursorAdapter
<p>I am trying to access a list-activity using custom adapter.I have tried it directly without using any custom adapter it was working good but because I want to add more functions in list-view I want to implement a custom adapter.Now I have tried it but I am getting an empty list-view with no data visible. List-Activity</p> <pre><code>public class MainActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0"; String[] projection = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DURATION, }; //query musiccursor = this.managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,projection,selection,null,sortOrder); music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA); int a[]= new int[]{R.id.TitleSong,R.id.Artist}; Custom_Adapter adapter = new Custom_Adapter(this,R.layout.music_items, musiccursor, new String[]{MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media.ARTIST} ,a); this.setAdapter(adapter); } } </code></pre> <p>Custom-Adapter</p> <pre><code> public class Custom_Adapter extends SimpleCursorAdapter { private Context mContext; private Context appContext; private int layout; private Cursor cr; private final LayoutInflater inflater; public Custom_Adapter(Context context,int layout, Cursor c,String[] from,int[] to) { super(context,layout,c,from,to); this.layout=layout; this.mContext = context; this.inflater=LayoutInflater.from(context); this.cr=c; } @Override public void bindView(View view, Context context, Cursor cursor) { // TODO Auto-generated method stub super.bindView(view, context, cursor); view=inflater.inflate(layout, null, false); TextView titleS=(TextView)view.findViewById(R.id.TitleSong); TextView artistS=(TextView)view.findViewById(R.id.Artist); int Title_index; int Artist_index; cursor.moveToFirst(); while(cursor.isLast()){ Title_index=cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME); Artist_index=cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST); titleS.setText(cursor.getString(Title_index)); artistS.setText(cursor.getString(Artist_index)); cr.moveToNext(); } } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub return convertView; } } </code></pre>
17,709,253
2
0
null
2013-07-17 19:51:05.527 UTC
11
2021-12-28 17:10:44.503 UTC
2021-12-28 17:10:44.503 UTC
null
4,294,399
null
1,810,612
null
1
5
android|listview|android-listview|simplecursoradapter|android-cursor
12,806
<p>When extending a cursor adapter you should override the methods <a href="http://developer.android.com/reference/android/widget/CursorAdapter.html#bindView%28android.view.View,%20android.content.Context,%20android.database.Cursor%29">bindView</a> and <a href="http://developer.android.com/reference/android/widget/CursorAdapter.html#newView%28android.content.Context,%20android.database.Cursor,%20android.view.ViewGroup%29">newView</a>. The bindView method is used to bind all data to a given view such as setting the text on a TextView. The newView method is used to inflate a new view and return it, you don't bind any data to the view at this point. Most adapters use the getView function but when extending a cursor adapter you should use bindView and newView.</p> <pre><code> public class Custom_Adapter extends SimpleCursorAdapter { private Context mContext; private Context appContext; private int layout; private Cursor cr; private final LayoutInflater inflater; public Custom_Adapter(Context context,int layout, Cursor c,String[] from,int[] to) { super(context,layout,c,from,to); this.layout=layout; this.mContext = context; this.inflater=LayoutInflater.from(context); this.cr=c; } @Override public View newView (Context context, Cursor cursor, ViewGroup parent) { return inflater.inflate(layout, null); } @Override public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); TextView titleS=(TextView)view.findViewById(R.id.TitleSong); TextView artistS=(TextView)view.findViewById(R.id.Artist); int Title_index=cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME); int Artist_index=cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST); titleS.setText(cursor.getString(Title_index)); artistS.setText(cursor.getString(Artist_index)); } } </code></pre>
44,060,253
How to Remove Chrome Logo from PWA App Home Screen Link (Android O Preview)
<p>I just updated to Android O Preview and installed a few PWAs. On the home screen a miniature Chrome logo is placed by the icon. This wasn't there before the OS update. </p> <p>Ideally, I would like the PWA to look like a regular app on the home screen considering it has service workers enabled.</p> <p>Is it possible to remove this with some settings in the app.yaml or manifest.json?</p>
49,761,109
6
0
null
2017-05-19 01:56:29.103 UTC
8
2021-09-18 06:09:25.72 UTC
null
null
null
null
6,606,273
null
1
37
android|google-chrome|homescreen|progressive-web-apps
32,419
<p>Above answer is not accurate except for the part that Chrome had the issue of adding Chrome badge to App icon, which is changed in the following updates. </p> <p><strong>Before getting into whats wrong, here is how web apps are added to home screen.</strong> </p> <p>1) <strong>As a simple shortcut</strong>(like a bookmark), when the users web browser don't have service worker support(<a href="https://developers.google.com/web/fundamentals/primers/service-workers/#browser_support" rel="noreferrer">which all recent versions of major browsers have support now</a>), targeted web URL don't have a valid manifest.json and service worker files configured(this can be validated in Application-> Manifest and Service worker tabs in chrome developer tools). In this case, what is added to home screen is not an APK and the bookmark kind of shortcut was represented by a specific version of Chrome with a badge. </p> <p>2) <strong>As an installed APK</strong>: When the targeted URL have a valid Manifest.json, service workers and one of supported Chrome version is used, Chrome for Android uses WebAPK to build and sign an .APK file with the package name starting "org.chromium.webapk". <a href="https://stackoverflow.com/a/49760845/1057093">Read here</a> for more details on apk generation and PWA distribution here.</p> <p><strong>Whats not accurate in the above answer/linked article,</strong> </p> <p>1) <strong>The chrome badge is not a security measure</strong>. Chrome team added the badge for web apps created as bookmark/URL shortcut as it was not using WebApk in some particular version. Badge is a simple visual representation which was later withdrawn.</p> <p>2) <strong>PWA is not abandoned in favor of WebApk.</strong> WebApk is part of PWA solution, which compliments PWA by building an installable APK file to get the native app like behavior. WebApk is used to build .apk files by Chrome for Android. <a href="https://chromium.googlesource.com/chromium/src/+/master/chrome/android/webapk/README" rel="noreferrer">Here is official read me file.</a> </p> <p>So if you are building a PWA, you can still be assured you are not left behind in outdated/abandoned/being abandoned technology. Its still a constantly progressing positively, which got iOS support for service worker in march-2018(iOS 11.3), making it the last major browser vendor aboard PWA game. </p>
27,829,051
Enable submit button only when all fields are filled
<p>In my form, I want to enable form only when all fields (and radio button list) has been selected. </p> <p>So far, I have successfully made the submit button <code>enable</code> when the <code>title</code> field has content with: </p> <pre><code>onkeyup="if(this.textLength != 0) {subnewtopic.disabled = false} else {subnewtopic.disabled = true}" </code></pre> <p>My aim is to enable submit button only once <strong>everything</strong> has been filled. How do I do this?</p> <p>Here is my full code with working <a href="http://jsfiddle.net/soyn0xag/" rel="noreferrer">jsfiddle</a>:</p> <pre><code> &lt;form action="" method="post" id="subnewtopicform" /&gt; Title: &lt;input type="text" name="title" onkeyup="if(this.textLength != 0) {subnewtopic.disabled = false} else {subnewtopic.disabled = true}"&gt; &lt;br/&gt; Description: &lt;textarea name="description"&gt;&lt;/textarea&gt; &lt;br/&gt; Category: &lt;ul class="list:category categorychecklist form-no-clear" id="categorychecklist"&gt; &lt;li id="category-19"&gt;&lt;label class="selectit"&gt;&lt;input type="radio" id="in-category-19" name="category" value="19"&gt; Animation&lt;/label&gt;&lt;/li&gt; &lt;li id="category-20"&gt;&lt;label class="selectit"&gt;&lt;input type="radio" id="in-category-20" name="category" value="20"&gt; Anime&lt;/label&gt;&lt;/li&gt; &lt;/ul&gt; &lt;input type="submit" value="Submit Topic" class="button-primary" name="subnewtopic" id="subnewtopic" disabled="disabled" /&gt; &lt;/form&gt; </code></pre>
27,829,274
5
1
null
2015-01-07 21:35:22.76 UTC
5
2018-01-31 19:18:24.43 UTC
null
null
null
null
1,185,126
null
1
8
jquery|html|forms
64,637
<p>Here is a fiddle for you. <a href="http://jsfiddle.net/soyn0xag/6/" rel="noreferrer">http://jsfiddle.net/soyn0xag/6/</a></p> <pre><code>$("input[type='text'], textarea").on("keyup", function(){ if($(this).val() != "" &amp;&amp; $("textarea").val() != "" &amp;&amp; $("input[name='category']").is(":checked") == true){ $("input[type='submit']").removeAttr("disabled"); } else { $("input[type='submit']").attr("disabled", "disabled"); } }); $("input[name='category']").on("change", function(){ if($(this).val() != "" &amp;&amp; $("textarea").val() != "" &amp;&amp; $("input[name='category']").is(":checked") == true){ $("input[type='submit']").removeAttr("disabled"); } else { $("input[type='submit']").attr("disabled", "disabled"); } }); </code></pre>
42,402,064
Using a Strategy and Factory Pattern with Dependency Injection
<p>I am working on a side project to better understand Inversion of Control and Dependency Injection and different design patterns.</p> <p>I am wondering if there are <strong>best practices to using DI with the factory and strategy patterns</strong>?</p> <p><strong>My challenge comes about when a strategy (built from a factory) requires different parameters for each possible constructor and implementation</strong>. As a result I find myself declaring all possible interfaces in the service entry point, and passing them down through the application. As a result, the entry point must be changed for new and various strategy class implementations.</p> <p>I have put together a paired down example for illustration purposes below. My stack for this project is .NET 4.5/C# and Unity for IoC/DI.</p> <p>In this example application, I have added a default Program class that is responsible for accepting a fictitious order, and depending on the order properties and the shipping provider selected, calculating the shipping cost. There are different calculations for UPS, DHL, and Fedex, and each implemnentation may or may not rely on additional services (to hit a database, api, etc).</p> <pre><code>public class Order { public string ShippingMethod { get; set; } public int OrderTotal { get; set; } public int OrderWeight { get; set; } public int OrderZipCode { get; set; } } </code></pre> <p><strong>Fictitious program or service to calculate shipping cost</strong></p> <pre><code>public class Program { // register the interfaces with DI container in a separate config class (Unity in this case) private readonly IShippingStrategyFactory _shippingStrategyFactory; public Program(IShippingStrategyFactory shippingStrategyFactory) { _shippingStrategyFactory = shippingStrategyFactory; } public int DoTheWork(Order order) { // assign properties just as an example order.ShippingMethod = "Fedex"; order.OrderTotal = 90; order.OrderWeight = 12; order.OrderZipCode = 98109; IShippingStrategy shippingStrategy = _shippingStrategyFactory.GetShippingStrategy(order); int shippingCost = shippingStrategy.CalculateShippingCost(order); return shippingCost; } } // Unity DI Setup public class UnityConfig { var container = new UnityContainer(); container.RegisterType&lt;IShippingStrategyFactory, ShippingStrategyFactory&gt;(); // also register IWeightMappingService and IZipCodePriceCalculator with implementations } public interface IShippingStrategyFactory { IShippingStrategy GetShippingStrategy(Order order); } public class ShippingStrategyFactory : IShippingStrategyFactory { public IShippingStrategy GetShippingStrategy(Order order) { switch (order.ShippingMethod) { case "UPS": return new UPSShippingStrategy(); // The issue is that some strategies require additional parameters for the constructor // SHould the be resolved at the entry point (the Program class) and passed down? case "DHL": return new DHLShippingStrategy(); case "Fedex": return new FedexShippingStrategy(); default: throw new NotImplementedException(); } } } </code></pre> <p><strong>Now for the Strategy interface and implementations.</strong> UPS is an easy calculation, while DHL and Fedex may require different services (and different constructor parameters).</p> <pre><code>public interface IShippingStrategy { int CalculateShippingCost(Order order); } public class UPSShippingStrategy : IShippingStrategy() { public int CalculateShippingCost(Order order) { if (order.OrderWeight &lt; 5) return 10; // flat rate of $10 for packages under 5 lbs else return 20; // flat rate of $20 } } public class DHLShippingStrategy : IShippingStrategy() { private readonly IWeightMappingService _weightMappingService; public DHLShippingStrategy(IWeightMappingService weightMappingService) { _weightMappingService = weightMappingService; } public int CalculateShippingCost(Order order) { // some sort of database call needed to lookup pricing table and weight mappings return _weightMappingService.DeterminePrice(order); } } public class FedexShippingStrategy : IShippingStrategy() { private readonly IZipCodePriceCalculator _zipCodePriceCalculator; public FedexShippingStrategy(IZipCodePriceCalculator zipCodePriceCalculator) { _zipCodePriceCalculator = zipCodePriceCalculator; } public int CalculateShippingCost(Order order) { // some sort of dynamic pricing based on zipcode // api call to a Fedex service to return dynamic price return _zipCodePriceService.CacluateShippingCost(order.OrderZipCode); } } </code></pre> <p>The issue with the above is that each strategy requires additional and different services to perform the 'CalculateShippingCost' method. Do these interfaces/implementations need to be registered with the entry point (the Program class) and passed down through the constructors?</p> <p>Are there other patterns that would be a better fit to accomplish the above scenario? Maybe something that Unity could handle specifically (<a href="https://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx" rel="noreferrer">https://msdn.microsoft.com/en-us/library/dn178463(v=pandp.30).aspx</a>)?</p> <p>I greatly appreciate any help or a nudge in the right direction.</p> <p>Thanks, Andy</p>
42,402,842
5
1
null
2017-02-22 20:53:14.94 UTC
11
2022-08-23 07:26:23.617 UTC
2017-02-22 21:21:40.273 UTC
null
3,211,509
null
3,211,509
null
1
28
c#|design-patterns|dependency-injection|factory-pattern|strategy-pattern
31,315
<p>There are a few ways of doing this, but the way I prefer is to inject a list of available strategies into your factory, and then filtering them to return the one(s) you're interested in.</p> <p>Working with your example, I'd modify <code>IShippingStrategy</code> to add a new property:</p> <pre><code>public interface IShippingStrategy { int CalculateShippingCost(Order order); string SupportedShippingMethod { get; } } </code></pre> <p>Then I'd implement the factory like so:</p> <pre><code>public class ShippingStrategyFactory : IShippingStrategyFactory { private readonly IEnumerable&lt;IShippingStrategy&gt; availableStrategies; public ShippingStrategyFactory(IEnumerable&lt;IShippingStrategy&gt; availableStrategies) { this.availableStrategies = availableStrategies; } public IShippingStrategy GetShippingStrategy(Order order) { var supportedStrategy = availableStrategies .FirstOrDefault(x =&gt; x.SupportedShippingMethod == order.ShippingMethod); if (supportedStrategy == null) { throw new InvalidOperationException($"No supported strategy found for shipping method '{order.ShippingMethod}'."); } return supportedStrategy; } } </code></pre> <p>The main reason I like using it this way is that I never have to come back and modify the factory. If ever I have to implement a new strategy, the factory doesn't have to be changed. If you're using auto-registration with your container, you don't even have to register the new strategy either, so it's simply a case of allowing you to spend more time writing new code.</p>
51,330,155
Implicit conversion from data type varchar to varbinary is not allowed. (SQL)
<p>Error: </p> <blockquote> <p>Implicit conversion from data type varchar to varbinary is not allowed. Use the CONVERT function to run this query.</p> </blockquote> <p>Any question? I am new to SQL Server</p> <pre><code>USE schemas GO CREATE PROCEDURE Table @LineaNegocioId INT, --null @PaisId INT, -- required @AreaId INT, --required @Nombre VARCHAR(100), --required @Descripcion VARCHAR(100), --required @fechaCreacion DATETIME, --required @fechaUltimaModificacion DATETIME --null AS BEGIN SET NOCOUNT ON INSERT INTO Table (LineaNegocioId, PaisId, AreaId, Nombre, Descripcion, fechaCreacion, fechaUltimaModificacion) VALUES (@LineaNegocioId, @PaisId, @AreaId, @Nombre, @Descripcion, @fechaCreacion, @fechaUltimaModificacion) SET NOCOUNT OFF END </code></pre>
51,330,242
2
2
null
2018-07-13 17:28:50.193 UTC
null
2022-05-22 05:37:14.613 UTC
2018-07-13 19:41:22.59 UTC
null
13,302
null
3,562,098
null
1
5
sql-server|tsql
41,692
<p>Either the field <code>Nombre</code> or <code>Descripcion</code> is a <code>varbinary</code> and you must explicitly <code>convert</code> those inputs for your <code>insert</code> clause. </p> <p>It would look like this. </p> <p><code>VALUES (... ,CONVERT(varbinary, [@Nombre or @Descripcion]) ,...)</code></p>
9,455,838
Create user with admin option oracle 11g command not working
<p>okay , This command is not working </p> <p><code>create user username identified by password with admin option ;</code></p> <p>It throws an error which says <code>missing or invalid option</code> </p> <p>And i am logged in as system . I have tried searching Oracle docs and they have written the same command . what i am doing wrong here ?</p>
9,455,877
3
0
null
2012-02-26 18:28:29.823 UTC
8
2017-08-03 13:03:01.707 UTC
2012-02-26 18:44:20.957 UTC
null
1,096,194
null
1,096,194
null
1
7
sql|oracle|oracle11g
52,960
<p>You need to first create the user;</p> <pre><code>CREATE USER username IDENTIFIED BY password; </code></pre> <p>then separately grant privileges with ADMIN OPTION;</p> <pre><code>GRANT dba TO username WITH ADMIN OPTION; </code></pre>
9,595,925
How to get ipa file from Xcode to run an iPhone app in real device?
<p>My client asked me to get the review of the app on which I am working. So, I want to get the ipa file and mobile provision file from Xcode 4.2 to share my app to run in real device. I have a paid account of apple with me. Please tell me the procedure to get it.</p> <p>Thanks in advance.</p>
9,596,069
5
0
null
2012-03-07 04:39:08.067 UTC
7
2016-02-04 00:32:37.797 UTC
2012-03-07 04:46:40.94 UTC
null
147,019
null
775,761
null
1
13
iphone|ios|xcode|distribution|ipa
50,689
<p><strong>STEP-1:</strong> </p> <p>You need to refer steps for <strong>AdHoc Distribution</strong></p> <p>I think you need to login with your credentials at <a href="https://daw.apple.com/cgi-bin/WebObjects/DSAuthWeb.woa/wa/login?appIdKey=d4f7d769c2abecc664d0dadfed6a67f943442b5e9c87524d4587a95773750cea&amp;path=//devcenter/ios/index.action" rel="nofollow noreferrer">Developer Apple Login</a></p> <p>Once you are logged in go through this link and read through it step by step.</p> <p>I think this is the best solution you can get as this documentation guide is given by Apple</p> <p><a href="https://developer.apple.com/ios/manage/certificates/team/howto.action" rel="nofollow noreferrer">https://developer.apple.com/ios/manage/certificates/team/howto.action</a></p> <p>This has multiple steps like:</p> <pre><code>1. Generating a Certificate Signing Request 2. Submitting a Certificate Signing Request for Approval 3. Approving Certificate Signing Requests 4. Downloading and Installing Development Certificates 5. Saving your Private Key and Transferring to other Systems </code></pre> <p>I think if you read all this steps on the apple documentation at the given link then you don't need to refer to any other guide. </p> <p><strong>STEP-2:</strong> </p> <p>Then just you need to download your certificates and provisioning profile.</p> <p><strong>STEP-3:</strong> </p> <p>Just set the profile into your Project and Target Settings and then put proper Entitlements using "Entitlements.plist".</p> <p><strong>STEP-4:</strong> </p> <p>Once you have done that, just set up your project in AdHoc Scheme.</p> <p><strong>STEP-5:</strong> </p> <p>Clean your Project.</p> <p><strong>STEP-6:</strong> </p> <p>Go to Product -> Click on Build For -> "Build For Archiving"</p> <p><strong>STEP-7:</strong> </p> <p>Product -> Archive</p> <p>Now your Archive can be obtained in your <strong>Organizer</strong> where in you can save it to disk with an IPA extension and send it your client.</p> <p><strong>EDIT:</strong></p> <p>Here are some of the useful links you can refer to for creating provisioning profile and IPA file: </p> <p><a href="https://stackoverflow.com/questions/7817162/create-ipa-file-in-xcode-4-2-ios-5-0-beta">Create IPA file in Xcode 4.2, iOS 5.0 Beta</a></p> <p><a href="http://www.makebetterthings.com/iphone/how-to-create-ipa-file-for-your-iphone-app-xcode-build-and-archive/" rel="nofollow noreferrer">http://www.makebetterthings.com/iphone/how-to-create-ipa-file-for-your-iphone-app-xcode-build-and-archive/</a></p> <p><a href="http://www.wikihow.com/Create-a-Provisioning-Profile-for-iPhone" rel="nofollow noreferrer">http://www.wikihow.com/Create-a-Provisioning-Profile-for-iPhone</a></p> <p><a href="https://stackoverflow.com/questions/368062/create-provisioning-profile-in-iphone-application">Create provisioning profile in iphone application</a></p> <p>Hope this helps you.</p>
9,262,871
Android: two Spinner onItemSelected()
<p>I have two spinners (day_spin and time_spin) in one <code>Activity</code>. I want to save the selected day_spin value into a variable. Is it possible to differenciate between the two spinners in the same <code>Listener</code>? Or do I have to write my own <code>Listener</code> class for each spinner?</p> <p>Also I want to get the number of the selected item. For example I have String Array with 6 elements. I select number 3. How can I get the id?</p> <pre><code> day_spin = (Spinner) findViewById(R.id.spinner); ArrayAdapter&lt;CharSequence&gt; adapter_day = ArrayAdapter .createFromResource(this, R.array.spinner_day_array, android.R.layout.simple_spinner_item); adapter_day .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); day_spin.setAdapter(adapter_day); day_spin.setOnItemSelectedListener(this); time_spin = (Spinner) findViewById(R.id.spinner1); ArrayAdapter&lt;CharSequence&gt; adapter_time = ArrayAdapter .createFromResource(this, R.array.spinner_time_array, android.R.layout.simple_spinner_item); adapter_time .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); time_spin.setAdapter(adapter_time); time_spin.setOnItemSelectedListener(this); </code></pre> <p>This is my <code>Listener</code>:</p> <pre><code>public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int pos, long id) { DAY = parent.getItemAtPosition(pos).toString(); TIME = parent.getItemAtPosition(pos).toString(); } </code></pre> <p>I hope you can help me!</p>
9,263,046
6
0
null
2012-02-13 15:15:00.633 UTC
9
2020-11-21 07:09:53.643 UTC
2013-03-21 22:43:23.337 UTC
null
12,388
null
1,197,351
null
1
44
android|spinner|listener|android-spinner
64,197
<pre><code>public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int pos, long id) { if(parent.getId() == R.id.spinner1) { //do this } else if(parent.getId() == R.id.spinner2) { //do this } } </code></pre>
9,238,953
how to empty recyclebin through command prompt?
<p>Usually we delete the recycle bin contents by right-clicking it with the mouse and selecting "Empty Recycle Bin". But I have a requirement where I need to delete the recycle bin contents using the command prompt. Is this possible? If so, how can I achieve it?</p>
9,239,158
14
0
null
2012-02-11 08:50:22.883 UTC
33
2021-03-19 22:06:27.913 UTC
2016-12-09 15:04:51.983 UTC
null
4,666,542
null
1,016,403
null
1
87
windows|windows-7|command-line|batch-file|recycle-bin
297,138
<p>You can effectively "empty" the Recycle Bin from the command line by permanently deleting the Recycle Bin directory on the drive that contains the system files. (In most cases, this will be the <code>C:</code> drive, but you shouldn't hardcode that value because it won't always be true. Instead, use the <code>%systemdrive%</code> environment variable.)</p> <p>The reason that this tactic works is because each drive has a hidden, protected folder with the name <code>$Recycle.bin</code>, which is where the Recycle Bin actually stores the deleted files and folders. When this directory is deleted, Windows automatically creates a new directory.</p> <p>So, to remove the directory, use the <code>rd</code> command (<em>r</em>​emove <em>d</em>​irectory) with the <code>/s</code> parameter, which indicates that all of the files and directories within the specified directory should be removed as well:</p> <pre><code>rd /s %systemdrive%\$Recycle.bin </code></pre> <p>Do note that this action will <em>permanently</em> delete all files and folders currently in the Recycle Bin <strong>from all user accounts</strong>. Additionally, you will (obviously) have to run the command from an elevated command prompt in order to have sufficient privileges to perform this action. </p>
34,104,270
Filter and sort on multiple values with Firebase
<p>I'm building a social app using Firebase. I store posts in Firebase like this:</p> <pre><code>posts: { "postid": { author: "userid" text: "", date: "timestamp" category: "categoryid" likes: 23 } } </code></pre> <p>Each post belong to a category and it's possible to like posts.</p> <p>Now, I'm trying to show posts that belong to a specific category, sorted by the number of likes. It's possible I also want to limit the filter by date, to show only the most recent, most liked posts in a category. How can I do this?</p> <p>Firebase query functionality doesn't seem to support multiple queries like this, which seems strange...</p>
34,105,063
1
1
null
2015-12-05 11:22:11.583 UTC
15
2015-12-05 12:46:36.223 UTC
null
null
null
null
543,224
null
1
13
firebase
18,047
<p>You can use only one ordering function <a href="https://www.firebase.com/docs/ios/guide/retrieving-data.html#section-queries" rel="noreferrer">with Firebase database queries</a>, <strong>but proper data structure will allow you to query by multiple fields</strong>.</p> <p>In your case you want to order by category. Rather than have category as a property, it can act as an index under <code>posts</code>:</p> <pre><code>posts: { "categoryid": { "postid": { author: "userid" text: "", date: "timestamp", category: "categoryid", likes: 23 } } } </code></pre> <p>Now you can write a query to get all the posts underneath a specific category.</p> <pre><code>let postsRef = Firebase(url: "&lt;my-firebase-app&gt;/posts") let categoryId = "my-category" let categoryRef = postsRef.childByAppendingPath(categoryId) let query = categoryRef.queryOrderedByChild("date") query.observeEventType(.ChildAdded) { (snap: FDataSnapshot!) { print(snap.value) } </code></pre> <p>The code above creates a reference for posts by a specific category, and orders by the date. The multiple querying is possible by the data structure. The callback closure fires off for each individual item underneath the specified category.</p> <p>If you want to query further, you'll have to do a client-side filtering of the data. </p>
47,349,422
How to interpret adfuller test results?
<p>I am struggling to understand the concept of p-value and the various other results of adfuller test.</p> <p>The code I am using:</p> <p>(I found this code in Stack Overflow)</p> <pre class="lang-py prettyprint-override"><code>import numpy as np import os import pandas as pd import statsmodels.api as sm import cython import statsmodels.tsa.stattools as ts loc = r&quot;C:\Stock Study\Stock Research\Hist Data&quot; os.chdir(loc) xl_file1 = pd.ExcelFile(&quot;HDFCBANK.xlsx&quot;) xl_file2 = pd.ExcelFile(&quot;KOTAKBANK.xlsx&quot;) y1 = xl_file1.parse(&quot;Sheet1&quot;) x1 = xl_file2.parse(&quot;Sheet1&quot;) x = x1['Close'] y = y1['Close'] def cointegration_test(y, x): # Step 1: regress on variable on the other ols_result = sm.OLS(y, x).fit() # Step 2: obtain the residual (ols_resuld.resid) # Step 3: apply Augmented Dickey-Fuller test to see whether # the residual is unit root return ts.adfuller(ols_result.resid) </code></pre> <p>The output:</p> <pre><code>(-1.8481210964862593, 0.35684591783869046, 0, 1954, {'10%': -2.5675580437891359, '1%': -3.4337010293693235, '5%': -2.863020285222162}, 21029.870846458849) </code></pre> <p>If I understand the test correctly:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>Value</th> <th></th> </tr> </thead> <tbody> <tr> <td>adf : float</td> <td>Test statistic</td> </tr> <tr> <td>pvalue : float</td> <td>MacKinnon’s approximate p-value based on MacKinnon (1994, 2010)</td> </tr> <tr> <td>usedlag : int</td> <td>Number of lags used</td> </tr> <tr> <td>nobs : int</td> <td>Number of observations used for the ADF regression and calculation of the critical values</td> </tr> <tr> <td>critical values : dict</td> <td>Critical values for the test statistic at the 1 %, 5 %, and 10 % levels. Based on MacKinnon (2010)</td> </tr> <tr> <td>icbest : float</td> <td>The maximized information criterion if autolag is not None.</td> </tr> <tr> <td>resstore : ResultStore, optional</td> <td></td> </tr> </tbody> </table> </div> <p>I am unable to completely understand the results and was hoping someone would be willing to explain them in layman's language. All the explanations I am finding are very technical.</p> <p>My interpretation is: they are cointegrated, i.e. we failed to disprove the null hypothesis(i.e. unit root exists). Confidence levels are the % numbers.</p> <p>Am I completely wrong?</p>
54,953,670
3
1
null
2017-11-17 11:15:59.23 UTC
9
2021-12-26 11:47:57.167 UTC
2021-12-26 11:47:57.167 UTC
null
4,685,471
null
6,387,095
null
1
14
statistics|statsmodels
23,018
<p>what you stated in your question is correct. Once you applied the Adfuller test over your OLS regression residue, you were checking whether your residue had any heterocedasticity, in another words, if your residue was stationary.</p> <p>Since your adfuller p-value is lower than a certain specified alpha (i.e.: 5%), then you may reject the null hypothesis (Ho), because the probability of getting a p-value as low as that by mere luck (random chance) is very unlikely.</p> <p>Once the Ho is rejected, the alternative hypothesis (Ha) can be accepted, which in this case would be: the residue series is stationary.</p> <p>Here is the hypothesis relation for you:</p> <p>Ho: the series is not stationary, it presents heterocedasticity. In another words, your residue depends on itself (i.e.: yt depends on yt-1, yt-1 depends on yt-2 ..., and so on)</p> <p>Ha: the series is stationary (That is normally what we desire in regression analysis). Nothing more is needed to be done.</p>
10,818,319
When do I need to call setNeedsDisplay in iOS?
<p>When creating an iOS app, I'm confused as to when exactly I need to call <code>setNeedsDisplay</code>? I know that it has something to do with updating/redrawing the UI; however, do I need to call this every time I change any of my views?</p> <p>For example, do I need to call it:</p> <ul> <li>After programatically changing the text in a text field</li> <li>When changing the background of a view?</li> <li>When I make changes in viewDidLoad? </li> <li>How about in viewDidAppear?</li> </ul> <p>Could someone give me some general guidelines regarding when to use this method?</p>
10,818,417
5
1
null
2012-05-30 14:28:04.103 UTC
34
2018-04-25 15:27:48.757 UTC
2018-04-25 15:27:48.757 UTC
null
5,175,709
null
1,174,719
null
1
67
ios|objective-c|swift|uiview|setneedsdisplay
48,622
<p>You should only be calling setNeedsDisplay if you override drawRect in a subclass of UIView which is basically a custom view drawing something on the screen, like lines, images, or shapes like a rectangle.</p> <p>So you should call setNeedsDisplay when you make changes to few variables on which this drawing depends and for view to represent that change , you need to call this method which internally will give a call to drawRect and redraw the components.</p> <p>When you add an imageView or a UIButton as a subview or make changes to any subview, you need not call this method.</p> <p><strong>Example:</strong></p> <p>You have a view that shows a moving circle, either you touch and move it, or may be timer based animation. Now for this, you will need a custom view that draws a circle at given center and with given radius. These are kept as instance variables which are modified to move the circle by changing its center or make it bigger by increasing radius of it.</p> <p>Now in this case either you will modify these variables(centre or radius) in a loop and timer Or may be by your fingers in touchesEnded and touchesMoved methods. To reflect the change in this property you need to redraw this view for which you will call setNeedsDisplay.</p>
10,477,607
Avoid printStackTrace(); use a logger call instead
<p>In my application, I am running my code through PMD.It shows me this message:</p> <blockquote> <ul> <li>Avoid printStackTrace(); use a logger call instead. </li> </ul> </blockquote> <p>What does that mean?</p>
10,477,646
7
1
null
2012-05-07 06:23:57.383 UTC
32
2021-12-06 07:27:12.11 UTC
2012-05-07 06:29:02.073 UTC
null
605,744
null
1,305,398
null
1
99
java|logging|pmd|printstacktrace
135,551
<p>It means you should use logging framework like <a href="/questions/tagged/logback" class="post-tag" title="show questions tagged 'logback'" rel="tag">logback</a> or <a href="/questions/tagged/log4j" class="post-tag" title="show questions tagged 'log4j'" rel="tag">log4j</a> and instead of printing exceptions directly:</p> <pre><code>e.printStackTrace(); </code></pre> <p>you should log them using this frameworks' API:</p> <pre><code>log.error("Ops!", e); </code></pre> <p>Logging frameworks give you a lot of flexibility, e.g. you can choose whether you want to log to console or file - or maybe skip some messages if you find them no longer relevant in some environment.</p>
22,968,631
How to filter filter_horizontal in Django admin?
<p>I'm looking for a way to use filter_horizontal on the base of a filtered queryset.</p> <p>I've tried to use it with a custom manager:</p> <p><strong>In models.py:</strong></p> <pre><code>class AvailEquipManager(models.Manager): def get_query_set(self): return super(AvailEquipManager, self).get_query_set().filter(id=3) class Equipment(models.Model): description = models.CharField(max_length=50) manufacturer = models.ForeignKey(Manufacturer) [...] objects = models.Manager() avail = AvailEquipManager() def __unicode__(self): return u"%s" % (self.description) </code></pre> <p><strong>In admin.py:</strong></p> <pre><code>class SystemAdmin(admin.ModelAdmin): filter_horizontal = ('equipment',) # this works but obviously shows all entries #filter_horizontal = ('avail',) # this does not work </code></pre> <p>So the questions is, how can I reduce the left side of the filter_horizontal to show only specific items?</p>
23,140,826
2
1
null
2014-04-09 16:31:08.563 UTC
8
2020-06-13 19:50:56.373 UTC
null
null
null
null
427,942
null
1
17
python|django|django-admin
34,702
<p>I found a solution by adapting the answer to a different question which I found in <a href="https://groups.google.com/forum/#!topic/django-users/-46GAa0FMlc">Google Groups</a></p> <p>It works with a custom ModelForm like so:</p> <p>Create a new forms.py:</p> <pre><code>from django import forms from models import Equipment class EquipmentModelForm(forms.ModelForm): class Meta: model = Equipment def __init__(self, *args, **kwargs): forms.ModelForm.__init__(self, *args, **kwargs) self.fields['equipment'].queryset = Equipment.avail.all() </code></pre> <p>Then in admin.py:</p> <pre><code>class SystemAdmin(admin.ModelAdmin): form = EquipmentModelForm filter_horizontal = ('equipment',) </code></pre> <p>Hope this helps someone else out sometime.</p>
23,066,756
What are tracepoints used for?
<p>They can only be placed on method names. How are they used and what are they for?</p> <p><img src="https://i.stack.imgur.com/UJVwc.png" alt="enter image description here"></p>
23,115,921
3
1
null
2014-04-14 17:48:00.067 UTC
7
2019-03-28 14:10:45.027 UTC
2017-12-06 01:49:33.57 UTC
null
933,198
null
2,037,335
null
1
37
c#|c++|asp.net|visual-studio|debugging
19,946
<p>The Debugger team has a good blog post on this subject with examples as well: <s><a href="http://blogs.msdn.com/b/visualstudioalm/archive/2013/10/10/tracepoints.aspx" rel="noreferrer">http://blogs.msdn.com/b/visualstudioalm/archive/2013/10/10/tracepoints.aspx</a></s></p> <p><a href="https://web.archive.org/web/20190109221722/https://blogs.msdn.microsoft.com/devops/2013/10/10/tracepoints/" rel="noreferrer">https://web.archive.org/web/20190109221722/https://blogs.msdn.microsoft.com/devops/2013/10/10/tracepoints/</a></p> <p>Tracepoints are not a new feature at all (they been in Visual Studio since VS 2005). And they aren't breakpoints per se, as they don't cause the program execution to break. That can be useful when you need to inspect something, but not stop the program as that causes the behavior of a bug not to repro, etc. </p> <p>Tracepoints are an attempt to overcome the case when you can't stop the program to inspect something as that will cause some behavior not to repro, by allowing a breakpoint to log information to the debug output window and continue, without pausing at the UI. You can also do this with macros, but it can be more time consuming. </p> <p>To set a tracepoint, first set a breakpoint in code. Then use the context menu on the breakpoint and select the “When Hit...” menu item. You can now add log statements for the breakpoint and switch off the default Stop action, so that you log and go. There is a host of other info you can add to the log string, including static information about the location of the bp, such as file, line, function and address. You can also add dynamic information such as expressions, the calling function or callstack. Things like adding thread info and process info, can help you track down timing bugs when dealing with multiple threads and/or processes.</p>
18,977,320
Convert from .mov to .mp4 (or h264) using avconv
<p>Looking at the avconv website there seem to be a vast array of options to convert video.</p> <p>However, I'm getting lost in all the technical detail.</p> <p>Is there a simple way to convert a .mov to a .mp4 (or h264)?</p> <p>I'm happy if it's slightly lossy. </p> <p>If it helps I'm on Ubuntu 12.04.2 LTS.</p>
18,979,552
1
1
null
2013-09-24 09:11:24.093 UTC
9
2017-05-11 08:13:20.037 UTC
null
null
null
null
343,204
null
1
17
mp4|mov|avconv
39,455
<p>In a very basic form, it would look a bit like this:</p> <blockquote> <p>avconv -i inputfile.mov -c:v libx264 outputfile.mp4</p> </blockquote> <p>This will only work if you compiled avconv with libx264 support - you can <a href="https://stackoverflow.com/questions/11234662/how-to-compile-avconv-with-libx264-on-ubuntu-12-04">see here</a> on how to do that. <hr> If you're not that concerned about codecs and just need an ".mp4" file, you can also run this:</p> <blockquote> <p>avconv -i inputfile.mov -c copy outputfile.mp4</p> </blockquote> <p>This will copy all codec information from the .mov container and place it into the .mp4 container file.</p> <hr> <p>Just as a note, avconv is a fork of ffmpeg, many of the switches for ffmpeg will work for avconv (if that helps your search for answers)</p>
18,968,963
SELECT COUNT(DISTINCT... ) error on multiple columns?
<p>I have a table, VehicleModelYear, containing columns id, year, make, and model.</p> <p>The following two queries work as expected:</p> <pre><code>SELECT DISTINCT make, model FROM VehicleModelYear SELECT COUNT(DISTINCT make) FROM VehicleModelYear </code></pre> <p>However, this query doesn't work</p> <pre><code>SELECT COUNT(DISTINCT make, model) FROM VehicleModelYear </code></pre> <p>It's clear the answer is the number of results returned by the first query, but just wondering what is wrong with this syntax or why it doesn't work.</p>
18,969,000
3
1
null
2013-09-23 21:11:12.09 UTC
4
2016-07-30 07:04:28.82 UTC
null
null
null
null
2,631,315
null
1
22
sql|sql-server|tsql
62,788
<p><code>COUNT()</code> in <code>SQL Server</code> accepts the following syntax</p> <pre><code>COUNT(*) COUNT(colName) COUNT(DISTINCT colName) </code></pre> <p>You can have a subquery which returns unique set of <code>make</code> and <code>model</code> that you can count with.</p> <pre><code>SELECT COUNT(*) FROM ( SELECT DISTINCT make, model FROM VehicleModelYear ) a </code></pre> <p>The "a" at the end is not a typo. It's an alias without which SQL will give an error <code>ERROR 1248 (42000): Every derived table must have its own alias</code>.</p>
21,090,076
How to get error_message from SQL Server TRY.....CATCH block
<pre><code>BEGIN TRY BEGIN TRANSACTION --Lots of T-SQL Code here COMMIT END TRY BEGIN CATCH ROLLBACK USE [msdb]; EXEC sp_send_dbmail @profile_name='Mail Profile', @recipients='[email protected]', @subject='Data Error', @body = SELECT ERROR_MESSAGE(); END CATCH </code></pre> <p>I am getting the following error at this line</p> <pre><code>@body = SELECT ERROR_MESSAGE(); </code></pre> <blockquote> <p>Incorrect syntax near the keyword 'SELECT'.</p> </blockquote> <p>Any one know why?</p>
21,090,122
3
2
null
2014-01-13 11:24:04.143 UTC
3
2014-01-13 11:48:58.85 UTC
2014-01-13 11:48:43.91 UTC
null
13,302
null
77,121
null
1
21
sql-server|tsql
49,381
<p>You can not issue a SELECT statement directly into the parameter of a stored procedure. Do something like this instead:</p> <pre><code>DECLARE @err_msg AS NVARCHAR(MAX); SET @err_msg = ERROR_MESSAGE(); EXEC sp_send_dbmail @profile_name='your Mail Profile here', @recipients='[email protected]', @subject='Data Error', @body=@err_msg </code></pre>
18,554,889
Difference between XML Over HTTP & SOAP Over HTTP
<p>Is SOAP over HTTP a subset of XML over HTTP since I assume SOAP also an xml that confirms to a schema (SOAP schema)? I assume XML over HTTP service can either be accessed using GET or POST method. Does SOAP over HTTP always use POST method? In case of XML over HTTP I assume the disadvantage is that schema file has to be shared with all the consumers whereas in case of SOAP over HTTP it will be a single WSDL file. Would it be possible to help in letting me know the difference and also advantage of one over the other?</p>
18,555,101
1
0
null
2013-09-01 03:19:31.033 UTC
16
2013-09-01 04:03:08.907 UTC
null
null
null
null
1,042,646
null
1
23
web-services|http|soap|service|xmlhttprequest
57,543
<p>SOAP is a specialization of XML, as it has a schema, such as <a href="http://www.xmlsoap.org/soap/envelope/" rel="noreferrer">http://www.xmlsoap.org/soap/envelope/</a>, whereas XML is more general.</p> <p>For using GET, you can read through this discussion: <a href="http://www.coderanch.com/t/463869/Web-Services/java/SOAP-request-HTTP" rel="noreferrer">http://www.coderanch.com/t/463869/Web-Services/java/SOAP-request-HTTP</a>, but basically SOAP is done via POST, though Axis2 appears to have support for GET, as a way to have SOAP work in a world where REST seems to rule.</p> <p>And, according to this IBM article (<a href="http://www.ibm.com/developerworks/xml/library/x-tipgetr/index.html" rel="noreferrer">http://www.ibm.com/developerworks/xml/library/x-tipgetr/index.html</a>) SOAP 1.2 introduces GET.</p> <p>As you mentioned, SOAP is a standard, so there are tools that can easily work with it, including dynamic client generation, as shown in this question, <a href="https://stackoverflow.com/questions/6447974/dynamic-proxy-soap-web-service-client-in-java">dynamic proxy soap web service client in java?</a>, whansere the client generates the stubs needed upon connection.</p> <p>If you use XML over http, it may be better, depending on the need, as a way to transfer data, but in the use cases I can think of it would seem better to just use JSON and REST, but, if you want to transfer XML, or send XML, then you could look at using REST. </p> <p>POST would be the better option though as GET has size limitations (<a href="https://stackoverflow.com/questions/2659952/maximum-length-of-http-get-request">maximum length of HTTP GET request?</a>), which is probably why SOAP is almost always POST.</p> <p>The WSDL is not necessarily a single file, in WCF, if I remember, there are many xml files that need to be put together for the WSDL to be complete.</p> <p>The advantage depends on what your use case is, but I find that use REST and allowing the user to select the type is useful as it can be trivial to switch between JSON and XML, for example, and is the better choice for XML over HTTP.</p> <p>SOAP is best when integrating with older technologies as that may be all they can easily use. For example, when I have made webservices for SAP integration, it can be more work to have it not use SOAP, depending on the ability of the ABAP programmer.</p> <p>You may find this question of use: </p> <p><a href="https://stackoverflow.com/questions/8599833/how-soap-and-rest-work-with-xml-json-response">How SOAP and REST work with XML/JSON response?</a></p> <p>and for a discussion about JSON and XML in webservices you may find this helpful:</p> <p><a href="http://digitalbazaar.com/2010/11/22/json-vs-xml/" rel="noreferrer">http://digitalbazaar.com/2010/11/22/json-vs-xml/</a></p> <p>I forgot this link, as they do a brief comparison, but in the end you can easily support both. In WCF I had a controller that had the business logic, and had to .aspx files, one for SOAP and one for REST, and some webservices supported both, as it was just a matter of handling the request and response differences. So, if you want to provide support for both, and have a business case showing it makes sense, then pick a framework that will make it easy to do.</p> <p><a href="http://digitalbazaar.com/2010/11/22/json-vs-xml/" rel="noreferrer">http://digitalbazaar.com/2010/11/22/json-vs-xml/</a></p> <p>Basically, the goal is to provide services to clients via the web. What clients are going to connect? How will the clients find it easiest to reach out? How much data is being passed in the request?</p> <p>These types of questions will lead to the best solution for your needs.</p>
8,624,633
org.hibernate.MappingException: Unable to find column with logical name
<p>hi my tables are as follows:</p> <p>1- <strong>medical_company</strong>:</p> <ul> <li>medical_company_id <strong>foreign key</strong> on <strong>account_entity</strong> table <strong>account_entity_id</strong> column (not a pk)</li> <li>column1</li> <li>column2</li> <li>column3</li> </ul> <p>2- <strong>account_entity</strong>:</p> <ul> <li><strong>account_entity_id</strong> (pk)</li> <li>column1</li> <li>column2</li> <li>column3</li> </ul> <p>3- <strong>person:</strong></p> <ul> <li><strong>person_id</strong> (pk)</li> <li>column1</li> <li>column2</li> <li>column3</li> </ul> <p>4- <strong>employee_company:</strong></p> <ul> <li>company_id foreign key on <strong>medical_company</strong> table on <strong>medical_company_id</strong></li> <li>employee_id foreign key on <strong>person</strong> table on <strong>person_id</strong></li> <li>column1</li> <li>column2</li> </ul> <p><strong>ENTITIES:</strong></p> <p>1- <strong>MedicalCompany:</strong></p> <pre><code>@SuppressWarnings("serial") @Entity @Table(name = "medical_company") public class MedicalCompany implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false) @Basic(fetch = FetchType.EAGER) private Long id; @OneToOne @Cascade(value = { CascadeType.ALL }) @JoinColumn(name = "medical_company_id", referencedColumnName = "account_entity_id") private AccountEntity accountEntity; </code></pre> <p>}</p> <p>2- <strong>AccountEntity:</strong></p> <pre><code>@SuppressWarnings("serial") @Entity @Table(name = "account_entity") public class AccountEntity implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "account_entity_id", unique = true, nullable = false) @Basic(fetch = FetchType.EAGER) private Long id; } </code></pre> <p>3- <strong>Person:</strong></p> <pre><code> @SuppressWarnings("serial") @Entity @Table(name = "person") public class Person implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "person_id", unique = true, nullable = false) @Basic(fetch = FetchType.EAGER) private Long id; } </code></pre> <p>4- <strong>EmployeeCompanyId</strong>:</p> <pre><code>@SuppressWarnings("serial") @Embeddable public class EmployeeCompanyId implements Serializable { @ManyToOne private Person person; @ManyToOne private MedicalCompany medicalCompany; @Size(max = 150, message = "{long.value}") @Column(name = "title_text", length = 150, nullable = true) private String titleText; @Column(name = "employee_manager") private long employeeManager; } </code></pre> <p>5- <strong>EmployeeCompany:</strong></p> <pre><code>@SuppressWarnings("serial") @Entity @Table(name = "employee_company") @AssociationOverrides(value = { @AssociationOverride(name = "pk.medicalCompany", joinColumns = @JoinColumn(referencedColumnName = "medical_company_id")), @AssociationOverride(name = "pk.person", joinColumns = @JoinColumn(referencedColumnName = "person_id")), @AssociationOverride(name = "pk.titleText"), @AssociationOverride(name = "pk.employeeManager") }) public class EmployeeCompany implements Serializable { @EmbeddedId private EmployeeCompanyId pk = new EmployeeCompanyId(); @Transient public void setEmployeeManager(long employeeManager) { this.pk.setEmployeeManager(employeeManager); } public long getEmployeeManager() { return pk.getEmployeeManager(); } @Transient public void setTitleText(String titleText) { this.pk.setTitleText(titleText); } public String getTitleText() { return pk.getTitleText(); } public void setPerson(Person person) { this.pk.setPerson(person); } @Transient public Person getPerson() { return this.pk.getPerson(); } public void setMedicalCompany(MedicalCompany medicalCompany) { this.pk.setMedicalCompany(medicalCompany); } @Transient public MedicalCompany getMedicalCompany() { return this.pk.getMedicalCompany(); } public void setPk(EmployeeCompanyId pk) { this.pk = pk; } public EmployeeCompanyId getPk() { return pk; } } </code></pre> <p>when trying to run the application, i am getting the following error:</p> <pre><code>org.hibernate.MappingException: Unable to find column with logical name: medical_company_id in org.hibernate.mapping.Table(medical_company) and its related supertables and secondary tables at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:550) at org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:126) at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:110) at org.hibernate.cfg.AnnotationConfiguration.processFkSecondPassInOrder(AnnotationConfiguration.java:520) at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:380) at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1206) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1477) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1417) </code></pre> <p>please advise why i am getting this error, and how to solve it.</p>
8,625,429
4
1
null
2011-12-24 12:51:05.783 UTC
6
2021-06-03 08:08:28.757 UTC
null
null
null
null
429,377
null
1
29
hibernate|jakarta-ee|jpa|hibernate-mapping|hbm2ddl
83,936
<p>This error is telling you that there is no column on the medical_company table called medical_company_id. The column on medical_company is just called id. </p>
19,797,139
How to make a button scroll down page in HTML?
<p>Couldn't find a tutorial for this anywhere or just didn't use the right keywords. I'm making a one-paged website, and I'd like the navigation bar buttons to scroll the page up/down to the right part. Would this be possible in just HTML and CSS?<br> I'm not so experienced with JavaScript.</p> <p>Similar to ''Scroll to the top'' but that I could decide to where it scrolls the page, like middle, top, bottom etc. .</p>
19,797,171
2
1
null
2013-11-05 19:24:26.007 UTC
3
2017-02-13 09:30:27.857 UTC
null
null
null
null
2,907,241
null
1
15
javascript|html|css|scroll
55,989
<p><strong>Update:</strong> There is now a better way to use this, using the HTML <code>id</code> attribute:</p> <p>Set the destination id: <code>&lt;h1 id="section1"&gt;Section 1&lt;/h1&gt;</code></p> <p>And create a link to that destination using the anchor tag: <code>&lt;a href="#section1"&gt;Go to section 1&lt;/a&gt;</code></p> <p>The benefit of this new method is that the <code>id</code> attribute can be set on any HTML element. You don't have to wrap superfluous anchor tags around destination links anymore!</p> <p><strong>Original answer:</strong></p> <p>You can look at using the HTML anchor tag. </p> <p><code>&lt;a name="section1"&gt;Section 1&lt;/a&gt;</code></p> <p>alongside</p> <p><code>&lt;a href="#section1"&gt;Go to section 1&lt;/a&gt;</code></p> <p>When the user clicks on "Go to section 1", they will be sent to the section of the page where the "Section 1" text is displayed.</p>
19,787,747
Insert a date into a textbox and then that date would be selected in the calendar asp.net c#
<p>I need to know is it possible to insert a date into a textbox and then that date would be selected in the calendar. I am using the calendar in Microsoft visual studio express 2012 for web.</p> <p>Below is the code for inserting a date into a textbox by selecting the date on the calendar. (However I want to do the opposite) </p> <p>Default.aspx </p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head id="Head1" runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:Calendar ID="Calendar1" runat="server" Visible="False" OnSelectionChanged="Calendar1_SelectionChanged"&gt;&lt;/asp:Calendar&gt; &lt;/div&gt; &lt;asp:TextBox ID="TextBox1" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click"&gt;PickDate...&lt;/asp:LinkButton&gt; &lt;/form&gt; </code></pre> <p> </p> <p>Default.aspx.cs </p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void LinkButton1_Click(object sender, EventArgs e) { Calendar1.Visible = true; } protected void Calendar1_SelectionChanged(object sender, EventArgs e) { TextBox1.Text = Calendar1.SelectedDate.ToLongDateString(); Calendar1.Visible = false; } } </code></pre> <p>Thanks </p>
19,787,820
3
1
null
2013-11-05 11:18:01.277 UTC
2
2013-11-06 14:22:10.053 UTC
null
null
null
null
2,855,068
null
1
3
c#|asp.net|calendar
47,321
<p>How about</p> <pre><code>protected void TextBox1_TextChanged(object sender, EventArgs e) { Calendar1.SelectedDate = Convert.ToDateTime(TextBox1.Text); } </code></pre>
962,449
Array of Labels
<p>How to create array of labels with Microsoft Visual C# Express Edition ? Is there way to do it with graphical (drag'n'drop) editor or I have to manually add it to auto generated code ?</p>
962,453
4
1
null
2009-06-07 18:16:00.163 UTC
1
2014-01-07 20:17:14.397 UTC
null
null
null
null
80,204
null
1
5
c#|.net
49,806
<p>You have to manually add it. But don't add it to auto generated code as it can be overwritten by Visual Studio designer.</p> <p>I would add it in Load event handler for the form. The code can look like this: </p> <pre><code>Label[] labels = new Label[10]; labels[0] = new Label(); labels[0].Text = "blablabla"; labels[0].Location = new System.Drawing.Point(100, 100); ... labels[9] = new Label(); ... </code></pre> <p>PS. Your task seems a little unusual to me. What do you want to do? Maybe there are better ways to accomplish your task.</p>
40,071,845
How to import CSS from node_modules in webpack angular2 app
<p>Let's say that we start with the following starter pack: <a href="https://github.com/angularclass/angular2-webpack-starter" rel="noreferrer">https://github.com/angularclass/angular2-webpack-starter</a></p> <p>After <code>npm install</code> and <code>npm run start</code> everything works fine.</p> <p>I want to add an external css module, for example bootstrap 4's css (and only the css). (I know that bootstrap has a bootstrap-loader, but now I'm asking for general solution, so please think about bootstrap 4 here as it could be any other css module that is available via npm).</p> <p>I install bootstrap via npm: <code>npm install [email protected] --save</code></p> <p>First I thought that it is enough to add <code>import 'bootstrap/dist/css/bootstrap.css';</code> to the vendor.browser.ts file.</p> <p>But it isn't.</p> <p>What should I do to have a proper solution?</p> <p>Solutions I'm NOT asking for:</p> <ol> <li>"Copy the external css module to the assets folder, and use it from there" <ul> <li>I'm looking for a solution that works together with npm package.</li> </ul></li> <li>"Use bootstrap-loader for webpack" <ul> <li>As I described above, I'm looking for a general solution, bootstrap is only an example here.</li> </ul></li> <li>"Use another stack" <ul> <li>I'm looking for a solution in the exact starter pack that I've mentioned above.</li> </ul></li> </ol>
40,073,067
3
2
null
2016-10-16 15:12:36.893 UTC
17
2019-02-07 19:08:48.647 UTC
2017-10-06 20:02:11.48 UTC
null
3,885,376
null
1,010,777
null
1
70
css|angular|typescript|npm|webpack
101,621
<p>You won't be able to import any css to your <strong>vendors</strong> file using that stack, without making some changes.</p> <p>Why? Well because this line:</p> <pre><code>import 'bootstrap/dist/css/bootstrap.css'; </code></pre> <p>It's only importing your css as string, when in reality what you want is your vendor css in a style tag. If you check <code>config/webpack.commons.js</code> you will find this rule:</p> <pre><code> { test: /\.css$/, loaders: ['to-string-loader', 'css-loader'] }, </code></pre> <p>This rule allows your components to import the css files, basically this:</p> <pre><code>@Component({ selector: 'app', encapsulation: ViewEncapsulation.None, styleUrls: [ './app.component.css' // this why you import css as string ], </code></pre> <p>In the AppComponent there's no encapsulation, because of this line <code>encapsulation: ViewEncapsulation.None,</code> which means any css rules will be applied globally to your app. So you can import the bootstrap styles in your app component:</p> <pre><code>@Component({ selector: 'app', encapsulation: ViewEncapsulation.None, styleUrls: [ './app.component.css', '../../node_modules/bootstrap/dist/css/bootstrap.css' ], </code></pre> <p>But if you insist in importing to your <code>vendor.ts</code> then you will need to install a new loader, <code>npm i style-loader --save-dev</code> this will allow webpack to inject css to your page. Then you need to create a specific rule, on your webpack.common.js and change the existing one:</p> <pre><code> { //this rule will only be used for any vendors test: /\.css$/, loaders: ['style-loader', 'css-loader'], include: [/node_modules/] }, { test: /\.css$/, loaders: ['to-string-loader', 'css-loader'], exclude: [/node_modules/] //add this line so we ignore css coming from node_modules }, </code></pre> <p>The firs rule will be only applied when you try to import css, from any package inside <code>node_modules</code> the second rule will be applied to any css that you import from outside the <code>node_modules</code></p>
22,107,788
How include an external JS file in a JSP page
<p>I have an spring mvc app where in my main page, I need use an javascript file. I try include the file this way:</p> <pre><code>&lt;script type="text/javascript" src="js/index.js"&gt;&lt;/script&gt; </code></pre> <p>but when I running the application, the system behavior seems like no script is running. T also try this:</p> <pre><code>&lt;script type="text/javascript" src="&lt;c:url value='js/index.js'/&gt;"&gt;&lt;/script&gt; </code></pre> <p>but the result was the same. Someone have any idea why this is happening?</p> <p>ps.: the entire code of my page is:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"&gt; &lt;title&gt;HorarioLivre&lt;/title&gt; &lt;script src="http://code.jquery.com/jquery-2.1.0.min.js"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/index.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="css/style-main.css"&gt; &lt;link rel="stylesheet" href="css/style-popup.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;header&gt; &lt;div class="container"&gt; &lt;h1&gt;&lt;a href="#"&gt;HorarioLivre&lt;/a&gt;&lt;/h1&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="listagem_evento.html" class="icon evento"&gt;Eventos&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="cadastra_horario.html" class="icon horario"&gt;Cadastrar Horarios&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="listagem_horario.html" class="icon horario"&gt;Listar Horarios&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="listagem_usuario.html" class="icon usuario"&gt;Usuarios&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;${usuario.nome}&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="usuario_perfil.html" class="icon perfil"&gt;Perfil&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="usuario_config.html" class="icon settings"&gt;Configura&amp;ccedil;&amp;otilde;es&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="usuario_logoff.html" class="icon logout"&gt;Sair&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/header&gt; &lt;div id="results"&gt; &lt;a href="#" id="close"&gt;Fechar&lt;/a&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The script should open my subpages in a pop-up windows, but they are being opened in the browser window.</p> <p>** UPDATE 1 **</p> <p>My index.js is:</p> <pre><code>$(document).ready(function(){ setupPopup(); }); function setupPopup() { $('a').click(function() { $('#content').load($(this).attr('href')); $('#container').append('&lt;div id="cover"&gt;'); $('#results').fadeIn(500); popupPosition(); }); $('#close').click(function() { $('#results').fadeOut(100); $('#cover').remove(); }); $(window).bind('resize', popupPosition); } function popupPosition() { if(!$("#results").is(':visible')){ return; } $("#results").css({ left: ($(window).width() - $('#results').width()) / 2, top: ($(window).width() - $('#results').width()) / 7, position:'absolute' }); $('#results').draggable(); } </code></pre>
42,076,844
3
1
null
2014-02-28 23:30:41.78 UTC
5
2021-08-17 00:20:45.087 UTC
2014-02-28 23:47:15.89 UTC
null
2,692,962
null
2,692,962
null
1
15
javascript|jsp
93,030
<blockquote> <p>but when I running the application, the system behavior seems like no script is running.</p> </blockquote> <p>This is because the browser is unable to load the javascript 'index.js' from the specified location. If you open the browser console and go to the 'networks' tab, you will see 404 (resource not found) against it. You cannot specify a relative URL to a JavaScript in a JSP file that way.</p> <p>You need to provide your folder structure (where index.js is located in your project) and how you have configured web.xml. But if you try the following, it will surely work:</p> <p><code>&lt;script type="text/javascript" src="${pageContext.request.contextPath}/js/index.js"&gt;&lt;/script&gt;</code></p> <p>And then keep the 'js' folder containing 'index.js' at the same level as 'WEB-INF'.</p>
35,375,757
Test ActiveModel::Serializer classes with Rspec
<p>Given the following <code>ActiveModel::Serializer</code> class:</p> <pre><code>class SampleSerializer &lt; ActiveModel::Serializer attributes :id, :name end </code></pre> <p>How can this be tested with <code>RSpec</code>?</p>
35,375,758
5
0
null
2016-02-13 03:33:16.47 UTC
10
2021-03-03 13:55:31.177 UTC
2019-07-10 16:48:08.387 UTC
null
3,678,689
null
2,259,144
null
1
38
ruby-on-rails|ruby-on-rails-4|rspec|active-model-serializers
18,093
<h3>Assumptions</h3> <p>This answer assumes you have the <code>rspec-rails</code>, <code>active_model_serializers</code> and <code>factory_girl_rails</code> gems installed and configured.</p> <p>This answer also assumes you have defined a factory for the <code>Sample</code> resource.</p> <h3>Serializer spec</h3> <p>For the current version(0.10.0.rc3) of <a href="https://github.com/rails-api/active_model_serializers" rel="noreferrer">active_model_serializers</a> at the time of writing, <code>ActiveModel::Serializer</code> classes do not receive <code>to_json</code> and are , instead, wrapped in an adapter class. To obtain the serialization of a model wrapped in a serializer instance, an instance of an adapter must be created:</p> <pre><code>before(:each) do # Create an instance of the model @sample = FactoryGirl.build(:sample) # Create a serializer instance @serializer = SampleSerializer.new(@sample) # Create a serialization based on the configured adapter @serialization = ActiveModelSerializers::Adapter.create(@serializer) end </code></pre> <p>The adapter instance receives the <code>to_json</code> method and returns the serialization of the model. </p> <pre><code>subject { JSON.parse(@serialization.to_json) } </code></pre> <p>Expectations can then be run on the JSON returned.</p> <pre><code>it 'should have a name that matches' do expect(subject['name']).to eql(@sample.name) end </code></pre> <p>When parsing the JSON response, the adapter configuration must be taken into consideration:</p> <ul> <li><p>The default config, <code>:attributes</code>, generates a JSON response without a root key:</p> <pre><code>subject { JSON.parse(@serialization.to_json) } </code></pre></li> <li><p>The <code>:json</code> config generates a JSON response with a root key based on the model's name:</p> <pre><code>subject { JSON.parse(@serialization.to_json)['sample'] } </code></pre></li> <li><p>The <code>:json_api</code> config generates a JSON that conforms to the <a href="http://jsonapi.org/format/#document-structure" rel="noreferrer">jsonapi</a> standard:</p> <pre><code>subject { JSON.parse(@serialization.to_json)['data']['attributes'] } </code></pre></li> </ul>
25,838,183
What is the OAuth 2.0 Bearer Token exactly?
<p>According to <a href="https://www.rfc-editor.org/rfc/rfc6750" rel="noreferrer">RFC6750</a>-The OAuth 2.0 Authorization Framework: Bearer Token Usage, the bearer token is:</p> <blockquote> <p>A security token with the property that any party in possession of the token (a &quot;bearer&quot;) can use the token in any way that any other party in possession of it can.</p> </blockquote> <p>To me this definition is vague and I can't find any specification.</p> <ul> <li>Suppose I am implementing an authorization provider, can I supply any kind of string for the bearer token?</li> <li>Can it be a random string?</li> <li>Does it have to be a base64 encoding of some attributes?<br /> Should it be hashed?</li> <li>And does the service provider need to query the authorization provider in order to validate this token?</li> </ul> <p>Thank you for any pointer.</p>
25,843,058
6
1
null
2014-09-14 21:27:46.397 UTC
89
2021-08-04 23:23:25.733 UTC
2021-10-07 05:46:31.917 UTC
null
-1
null
933,211
null
1
241
oauth|bearer-token
236,871
<blockquote> <p>Bearer Token<br> A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).</p> </blockquote> <p>The Bearer Token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for you a Token. Bearer Tokens are the predominant type of access token used with OAuth 2.0. A Bearer token basically says "Give the bearer of this token access".</p> <p>The Bearer Token is normally some kind of opaque value created by the authentication server. It isn't random; it is created based upon the user giving you access and the client your application getting access.</p> <p>In order to access an API for example you need to use an Access Token. Access tokens are short lived (around an hour). You use the bearer token to get a new Access token. To get an access token you send the Authentication server this bearer token along with your client id. This way the server knows that the application using the bearer token is the same application that the bearer token was created for. Example: I can't just take a bearer token created for your application and use it with my application it wont work because it wasn't generated for me.</p> <p>Google Refresh token looks something like this: 1/mZ1edKKACtPAb7zGlwSzvs72PvhAbGmB8K1ZrGxpcNM</p> <p>copied from comment: I don't think there are any restrictions on the bearer tokens you supply. Only thing I can think of is that its nice to allow more than one. For example a user can authenticate the application up to 30 times and the old bearer tokens will still work. oh and if one hasn't been used for say 6 months I would remove it from your system. It's your authentication server that will have to generate them and validate them so how it's formatted is up to you.</p> <p><strong>Update:</strong></p> <p>A Bearer Token is set in the Authorization header of every Inline Action HTTP Request. For example:</p> <pre><code>POST /rsvp?eventId=123 HTTP/1.1 Host: events-organizer.com Authorization: Bearer AbCdEf123456 Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/1.0 (KHTML, like Gecko; Gmail Actions) rsvpStatus=YES </code></pre> <p>The string <code>"AbCdEf123456"</code> in the example above is the bearer authorization token. This is a cryptographic token produced by the authentication server. All bearer tokens sent with actions have the issue field, with the audience field specifying the sender domain as a URL of the form https://. For example, if the email is from [email protected], the audience is <a href="https://example.com" rel="noreferrer">https://example.com</a>.</p> <p>If using bearer tokens, verify that the request is coming from the authentication server and is intended for the the sender domain. If the token doesn't verify, the service should respond to the request with an HTTP response code 401 (Unauthorized).</p> <p>Bearer Tokens are part of the OAuth V2 standard and widely adopted by many APIs.</p>
30,678,303
Extremely large numbers in javascript
<p>I'm working on the Project Euler problems (currently <a href="http://projecteuler.net/problem=13" rel="noreferrer">question 13</a>).</p> <p>For this question I have to find the first 10 digits of the sum of 100 numbers all of a size similar to this:</p> <pre><code>91,942,213,363,574,161,572,522,430,563,301,811,072,406,154,908,250 </code></pre> <p>I think I could use something like Java's BigInteger, but I started solving the problems in JavaScript (I'm trying to boost my js abilities for work), and I would like to continue using it, even to solve this problem. </p> <p>I'd like to stick to pure JS if possible.</p>
30,678,327
5
2
null
2015-06-06 02:21:30.73 UTC
8
2020-03-24 10:15:37.253 UTC
2017-07-15 09:19:50.687 UTC
null
46,914
null
2,558,418
null
1
15
javascript|types|numbers|integer|biginteger
46,089
<p>You are going to need a javascript based BigInteger library. There are many to choose from. Here is one <a href="https://github.com/peterolson/BigInteger.js" rel="noreferrer">https://github.com/peterolson/BigInteger.js</a></p> <p>You can use it like this </p> <pre><code>var n = bigInt("91942213363574161572522430563301811072406154908250") .plus("91942213363574161572522430563301811072406154908250"); </code></pre>
20,807,131
Espresso: return boolean if view exists
<p>I am trying to check to see if a view is displayed with Espresso. Here is some pseudo code to show what I am trying:</p> <pre><code>if (!Espresso.onView(withId(R.id.someID)).check(doesNotExist()){ // then do something } else { // do nothing, or what have you } </code></pre> <p>But my problem is <code>.check(doesNotExist())</code> does not return boolean. It is just an assertion. With UiAutomator I was able to just do something like so:</p> <pre><code> if (UiAutomator.getbyId(SomeId).exists()){ ..... } </code></pre>
20,811,193
8
1
null
2013-12-27 20:07:34.94 UTC
6
2020-07-29 18:09:18.587 UTC
2017-10-23 17:03:58.173 UTC
null
1,642,079
null
1,642,079
null
1
47
java|android|android-testing|android-espresso
41,964
<p>Conditional logic in tests is <a href="http://xunitpatterns.com/Conditional%20Test%20Logic.html" rel="noreferrer">undesirable</a>. With that in mind, Espresso's API was designed to guide the test author away from it (by being explicit with test actions and assertions).</p> <p>Having said that, you can still achieve the above by implementing your own ViewAction and capturing the isDisplayed check (inside the perform method) into an AtomicBoolean.</p> <p>Another less elegant option - catch the exception that gets thrown by failed check:</p> <pre><code> try { onView(withText("my button")).check(matches(isDisplayed())); //view is displayed logic } catch (NoMatchingViewException e) { //view not displayed logic } </code></pre> <p><em>Kotlin version with an extension function:</em></p> <pre><code> fun ViewInteraction.isDisplayed(): Boolean { try { check(matches(ViewMatchers.isDisplayed())) return true } catch (e: NoMatchingViewException) { return false } } if(onView(withText("my button")).isDisplayed()) { //view is displayed logic } else { //view not displayed logic } </code></pre>