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
5,221,794
Magento: Get store contact telephone
<p>Seems like it should be simple, but cant find a solution anywhere. I need to output the Store Contact Telephone number, which is in Store Informtion in the admin.</p> <p>I need to output it in template files and CMS pages, what would the code be for each?</p> <p>Thanks :)</p>
5,222,003
1
0
null
2011-03-07 15:55:37.05 UTC
8
2016-06-09 04:37:14.327 UTC
2011-03-07 16:51:24.503 UTC
null
226,431
null
564,190
null
1
35
magento
35,740
<p>That's a <strong>Core configuration</strong>, so it's saved in <code>core_config_data</code> table, and the phone information is the field:</p> <pre><code>general/store_information/phone </code></pre> <p>So, all you need is to read the configuration data as</p> <pre><code>$storePhone = Mage::getStoreConfig('general/store_information/phone'); </code></pre> <p>For CMS pages insert the following variable:</p> <pre><code>{{config path="general/store_information/phone"}} </code></pre> <p>You can find more info on this <a href="http://www.khemissi.com/2010/07/09/magento-diagram-website-store-store-view/" rel="noreferrer">here</a>, and you can always <a href="http://inchoo.net/ecommerce/magento/how-to-programmatically-change-magentos-core-config-data/" rel="noreferrer">do the reverse programmatically</a></p>
24,466,302
Basic difference between add() and replace() method of Fragment
<p>How do <code>Fragment</code>'s replace and add methods work differently, and is there any real life scenario where we would need these methods for specific purposes.</p>
24,466,345
2
1
null
2014-06-28 11:24:59.05 UTC
5
2014-06-28 11:51:44.467 UTC
2014-06-28 11:38:09.233 UTC
null
3,558,960
null
3,235,780
null
1
23
android|android-fragments
42,684
<p>The important difference is:</p> <p><code>replace</code> removes the existing fragment and adds a new fragment..</p> <p>but <code>add</code> retains the existing fragments and adds a new fragment that means existing fragment will be active and they wont be in 'paused' state hence when a back button is pressed <code>onCreateView()</code> is not called for the existing fragment(the fragment which was there before new fragment was added). </p> <p>For more information just visit <a href="https://stackoverflow.com/questions/18634207/difference-between-add-replace-and-addtobackstack">this conversation.</a></p>
24,647,078
Android activity/fragment responsibilities for data loading
<p>When starting a new application for a client, I am asking myself again the same question about who should be responsible for loading data: activities or fragments. I have taken both options for various apps and I was wondering which pattern is best according to you in terms of:</p> <ul> <li>limiting the code complexity.</li> <li>handling edge cases (like screen rotation, screen going power save, loss of connectivity, etc.)</li> </ul> <h3>Option 1 - Activity loads data &amp; fragment only displays it</h3> <p>This allows to have fragments that are just fed a bunch of objects to display. They know nothing about loading data and how we load that.</p> <p>On the other side, the activity loads data using whichever method is required (for instance initially the latest 50 entries and on a search, loads the search result). It then passes it to the fragment which displays it. Method to load the data could be anything (from service, from DB, ... fragments only know about POJOs)</p> <p>It's kind of a MVC architecture where the activity is the controller and fragments are the view.</p> <h3>Option 2 - Activity arranges fragments &amp; fragments are responsible to fetch the data</h3> <p>In this pattern, fragments are autonomous pieces of application. They know how to load the data they are displaying and how to show it to the user.</p> <p>Activities are simply a way to arrange fragments on screen and to coordinate transitions between application activities. </p>
24,907,813
4
2
null
2014-07-09 06:51:53.15 UTC
20
2017-08-14 10:50:54.743 UTC
2014-07-09 07:45:12.23 UTC
null
490,961
null
490,961
null
1
38
android
12,354
<p>Ideally neither <code>Activity</code> nor <code>Fragment</code> <strong>with UI</strong> should contain any "model" logic - these classes should be lightweight and responsible only for UI logic. But when you decide to make a separate model object you have a dilemma to choose where to initialise and store this object and how to deal with configuration changes. And here comes some handy trick:</p> <p>You can create a <strong>model</strong> <code>Fragment</code> <strong>without UI</strong>, make it <a href="http://developer.android.com/reference/android/app/Fragment.html#setRetainInstance(boolean)" rel="noreferrer">retain instance</a> to deal with configuration changes (it's AFAIK the simplest way to save data across config. changes without troubles) and retrieve it anywhere you need via <code>findFragmentById()</code>. You make all expensive operations inside it once (using background thread, of course), store your data and you're done. For more info, see <a href="http://developer.android.com/guide/components/fragments.html#Adding" rel="noreferrer">Adding a fragment without a UI</a> section.</p> <p><strong>UPD</strong>: There's now a better way to deal with configuration changes: <a href="https://developer.android.com/topic/libraries/architecture/viewmodel.html" rel="noreferrer">ViewModel</a> from <a href="https://developer.android.com/topic/libraries/architecture/index.html" rel="noreferrer">Google's Architecture Components</a>. Here's <a href="https://blog.stylingandroid.com/architecture-components-viewmodel/" rel="noreferrer">a good example</a>.</p>
44,441,830
VSCode: use WSL Git instead of Git for Windows
<p>I would like to use WSL (Bash on Windows) Git with VSCode instead of Git for Windows to avoid multiple Git installations.</p> <p>I created a simple bat script to emulate <code>git.exe</code> comportment by redirecting git commands in WSL. It works nicely in CMD but not with VSCode. Also, WSL is my default terminal in VSCode.</p> <p>VSCode <strong>settings.json</strong>:</p> <pre class="lang-json prettyprint-override"><code>{ "git.path": "D:\\tools\\git.bat", "terminal.integrated.shell.windows": "C:\\Windows\\Sysnative\\bash.exe" } </code></pre> <p>and <strong>git.bat</strong>:</p> <pre class="lang-bat prettyprint-override"><code>@echo off bash -c 'git %*' </code></pre> <p>Any idea to make VSCode working with WSL Git ?</p>
57,323,373
4
2
null
2017-06-08 17:09:44.397 UTC
6
2019-08-02 09:13:42.583 UTC
2017-06-09 08:53:13.22 UTC
null
7,716,337
null
7,716,337
null
1
32
visual-studio-code|windows-subsystem-for-linux
31,369
<p>Since VS Code 1.34 (April 2019) a remote extension has been introduced to develop into WSL: <a href="https://code.visualstudio.com/docs/remote/wsl" rel="noreferrer">https://code.visualstudio.com/docs/remote/wsl</a>. </p> <p>Basically, a server instance of VS Code is started into WSL, allowing you to use all the WSL tools (e.g. git) from your client instance on Windows.</p> <p><em>Thank you for pointing that out <a href="https://stackoverflow.com/questions/44441830/vscode-use-wsl-git-instead-of-git-for-windows?noredirect=1#comment101130755_44441830">@Noornashriq Masnon</a>!</em></p>
32,650,536
Using thymeleaf variable in onclick attribute
<p>In my current spring-boot project, I have one view with this html code:</p> <pre><code>&lt;button type="button" class="btn btn-primary" onclick="upload()" th:utext="#{modal.save}"&gt;&lt;/button&gt; </code></pre> <p>in the <code>onclick</code> attribute, the call for the function <code>upload()</code> should have one parameter, which value is stored in the thymeleaf variable <code>${gallery}</code>.</p> <p>Anyone can tell mehow to use the expression in the above command?</p> <p>I already try this:</p> <ul> <li><p><code>th:onclick="upload(${gallery)"</code></p></li> <li><p><code>th:attr="onclick=upload(${gallery)"</code></p></li> </ul> <p>None of this worked.</p>
32,760,756
8
1
null
2015-09-18 11:09:44.703 UTC
9
2022-03-09 17:50:47.443 UTC
null
null
null
null
2,692,962
null
1
36
javascript|spring|onclick|spring-boot|thymeleaf
91,086
<p>I solve this issue with this approach:</p> <pre><code>th:onclick="|upload('${command['class'].simpleName}', '${gallery}')|" </code></pre>
9,046,003
Onclick on href in html
<p>I want to make a button that will redirect me to another page. </p> <p>the code: </p> <pre><code> &lt;div align="right" &gt;&lt;input type="submit" id="logout" onclick="location.href=/login?dis=yes" value="Sign Out" &gt;&lt;/div&gt;&lt;BR&gt; </code></pre> <p>but when i press the button, i dont get any redirection to the other page.</p> <p>any idea why?</p>
9,046,100
7
0
null
2012-01-28 14:31:31.663 UTC
1
2012-12-09 11:47:03.273 UTC
null
null
null
null
576,786
null
1
5
javascript|html|onclick
91,196
<p>Your current code, even if the syntax is fixed by adding quotation marks, creates a button that does not work when JavaScript is disabled. The simpler and safer approach is a small HTML form:</p> <pre><code>&lt;form action="/login"&gt; &lt;input type=hidden name=dis value=yes&gt; &lt;input type=submit value="Sign Out"&gt; &lt;/form&gt; </code></pre> <p>To achieve the desired styling, you could add the following stylesheet:</p> <pre><code>form { display: inline; float: right; } </code></pre>
30,120,230
How to suppress variable type within value attribute using ng-options?
<p>Running AngularJS 1.4.0-rc.1 the value within a <code>ng-options</code> loop contains the type of the variable.</p> <p>See the following code:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.1/angular.js"&gt; &lt;/script&gt; &lt;script&gt; angular.module("selectOptionsTest", []). controller("SelectOptionsController", ["$scope", function($scope) { $scope.options = [ {id: 1, label: "Item 1"}, {id: 2, label: "Item 2"}, {id: 3, label: "Item 3"} ]; }]); &lt;/script&gt; &lt;div ng-app="selectOptionsTest" ng-controller="SelectOptionsController"&gt; &lt;select ng-model="opt" ng-options="option.id as option.label for option in options"&gt; &lt;/select&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>This generates HTML code which looks like this:</p> <pre><code>&lt;select ng-options="option.id as option.label for option in options" ng-model="option" class="ng-pristine ng-valid ng-touched"&gt; &lt;option value="?" selected="selected"&gt;&lt;/option&gt; &lt;option value="number:1" label="Item 1"&gt;Item 1&lt;/option&gt; &lt;option value="number:2" label="Item 2"&gt;Item 2&lt;/option&gt; &lt;option value="number:3" label="Item 3"&gt;Item 3&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Why is the value prefixed by the type of the variable, i.e. <code>number:</code>? In previous versions of AngularJS (e.g. the current stable 1.3.15) the <code>value</code> attributes are filled with the expected values of <code>1</code>, <code>2</code> and <code>3</code>.</p> <p>So is this a bug in 1.4.0-rc.1 or do those cases need to be handled differently now?</p>
30,292,209
2
2
null
2015-05-08 09:21:51.04 UTC
8
2017-02-06 23:27:18.653 UTC
null
null
null
null
432,681
null
1
35
javascript|angularjs
21,215
<p>Obviously there was a change in how the <code>ngOptions</code> directive is handled. This change is briefly explained in the <a href="https://docs.angularjs.org/guide/migration#ngoptions">migration notes for AngularJS 1.4</a>. A more detailed description of the changes can be found in the <a href="https://github.com/angular/angular.js/commit/7fda214c4f65a6a06b25cf5d5aff013a364e9cef">commit message</a>:</p> <blockquote> <p>When using <code>ngOptions</code>: the directive applies a surrogate key as the value of the <code>&lt;option&gt;</code> element. This commit changes the actual string used as the surrogate key. We now store a string that is computed by calling <code>hashKey</code> on the item in the options collection; previously it was the index or key of the item in the collection.</p> <p>(This is in keeping with the way that the unknown option value is represented in the select directive.)</p> <p>Before you might have seen:</p> <p><code>&lt;select ng-model="x" ng-option="i in items"&gt; &lt;option value="1"&gt;a&lt;/option&gt; &lt;option value="2"&gt;b&lt;/option&gt; &lt;option value="3"&gt;c&lt;/option&gt; &lt;option value="4"&gt;d&lt;/option&gt; &lt;/select&gt;</code></p> <p>Now it will be something like:</p> <p><code>&lt;select ng-model="x" ng-option="i in items"&gt; &lt;option value="string:a"&gt;a&lt;/option&gt; &lt;option value="string:b"&gt;b&lt;/option&gt; &lt;option value="string:c"&gt;c&lt;/option&gt; &lt;option value="string:d"&gt;d&lt;/option&gt; &lt;/select&gt;</code></p> <p>If your application code relied on this value, which it shouldn't, then you will need to modify your application to accommodate this. You may find that you can use the <code>track by</code> feaure of <code>ngOptions</code> as this provides the ability to specify the key that is stored.</p> </blockquote> <p>This means that you now need to use <code>track by</code> to get the same result as before. To fix the example in the question it needs to look like this then:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.2/angular.js"&gt; &lt;/script&gt; &lt;script&gt; angular.module("selectOptionsTest", []). controller("SelectOptionsController", ["$scope", function($scope) { $scope.options = [ {id: 1, label: "Item 1"}, {id: 2, label: "Item 2"}, {id: 3, label: "Item 3"} ]; }]); &lt;/script&gt; &lt;div ng-app="selectOptionsTest" ng-controller="SelectOptionsController"&gt; &lt;select ng-model="opt" ng-options="option.id as option.label for option in options track by option.id"&gt; &lt;/select&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
34,155,718
VBA Saving single sheet as CSV (not whole workbook)
<p>I appreciate there are lots of entries like <a href="https://stackoverflow.com/questions/7331624/save-individual-excel-sheets-as-csv">save individual excel sheets as csv</a> and <a href="https://stackoverflow.com/questions/8434994/export-each-sheet-to-a-separate-csv-file">Export each sheet to a separate csv file</a> - But I want to save a <strong>single worksheet</strong> in a workbook. </p> <p>My code in my xlsm file has a params and data sheet. I create a worksheet copy of the data with pasted values and then want to save it as csv. Currently my whole workbook changes name and becomes a csv.</p> <p><strong>How do I "save as csv" a single sheet in an Excel workbook?</strong></p> <p>Is there a <code>Worksheet.SaveAs</code> or do I have to move my data sheet to another workbook and save it that way?</p> <p><strong>CODE SAMPLE</strong></p> <pre><code>' [Sample so some DIMs and parameters passed in left out] Dim s1 as Worksheet Dim s2 as Worksheet Set s1 = ThisWorkbook.Sheets(strSourceSheet) ' copy across s1.Range(s1.Cells(1, 1), s1.Cells(lastrow, lastcol)).Copy ' Create new empty worksheet for holding values Set s2 = Worksheets.Add s2.Range("A1").PasteSpecial Paste:=xlPasteValuesAndNumberFormats ' save sheet s2.Activate strFullname = strPath &amp; strFilename ' &gt;&gt;&gt; BIT THAT NEEDS FIXIN' s2.SaveAs Filename:=strFullname, _ FileFormat:=xlCSV, CreateBackup:=True ' Can I do Worksheets.SaveAs? </code></pre> <p>Using Windows 10 and Office 365</p>
34,157,731
4
2
null
2015-12-08 12:19:11.7 UTC
3
2022-08-01 03:02:07.277 UTC
2017-05-23 11:46:42.47 UTC
null
-1
null
4,606,130
null
1
26
vba|excel
87,612
<p>This code works fine for me.</p> <pre><code>Sub test() Application.DisplayAlerts = False ThisWorkbook.Sheets(strSourceSheet).Copy ActiveWorkbook.SaveAs Filename:=strFullname, FileFormat:=xlCSV, CreateBackup:=True ActiveWorkbook.Close Application.DisplayAlerts = True End Sub </code></pre> <p>It's making a copy of the entire strSourceSheet sheet, which opens a new workbook, which we can then save as a .csv file, then it closes the newly saved .csv file, not messing up file name on your original file.</p>
10,399,060
Excel Two Columns With Duplicates
<p>So I have two columns in excel with column A containing nearly the exact same data as column B.</p> <p>I need a way to Match column A with Column B and any values that are the same in Column A and Column B need to be removed from Column B.</p> <p>So Column A has 11,592 product SKU numbers.</p> <p>Column B has 12,555 product SKU numbers.</p> <p>And I need a way to get the SKU product numbers from Column B that are <strong>not</strong> in Column A. Maybe put them into Column C?</p>
10,399,384
2
1
null
2012-05-01 14:22:05.7 UTC
6
2012-05-01 14:48:18.307 UTC
null
null
null
null
993,346
null
1
8
excel
42,886
<p>In cell C1 use this formula:</p> <pre><code>=IF(VLOOKUP(B1,A:A,1)=B1,"",B1) </code></pre> <p>Copy and paste it to all rows that have a value in column B and it will show the unique values.</p> <p>Then copy column C to column D by Paste Values so that you can sort it / filter out blanks.</p>
10,832,640
input checkbox true or checked or yes
<p>I've seen the three implementations of pre-selecting a checkbox. I started off using checked="checked" because I thought it was the "proper" way (never did like the "checked"="yes" however). I am thinking of changing to checked="true" as it seems more readable and is easier to code the JavaScript. Note that this same question applies to other attributes such as "disabled"="disabled" versus "disabled"="true". As long as I am consistent, is using "true" the preferred approach? Thank you</p> <pre><code>&lt;input type="checkbox" checked="checked" value="123" name="howdy" /&gt; &lt;input type="checkbox" checked="true" value="123" name="howdy" /&gt; &lt;input type="checkbox" checked="yes" value="123" name="howdy" /&gt; </code></pre>
10,832,683
2
1
null
2012-05-31 11:24:49.823 UTC
1
2014-10-08 20:52:11.273 UTC
2014-10-08 20:52:11.273 UTC
null
1,002,210
null
1,032,531
null
1
37
javascript|html|checkbox|html-input
156,800
<p>Only <code>checked</code> and <code>checked="checked"</code> are valid. Your other options depend on error recovery in browsers.</p> <p><code>checked="yes"</code> and <code>checked="true"</code> are particularly bad as they imply that <code>checked="no"</code> and <code>checked="false"</code> will set the default state to be <em>unchecked</em> … which they will not.</p>
10,722,773
Import existing Gradle Git project into Eclipse
<p>I've installed eclipse gradle plugin from here </p> <p><a href="http://kaczanowscy.pl/tomek/2010-03/gradle-ide-integration-eclipse-plugin">http://kaczanowscy.pl/tomek/2010-03/gradle-ide-integration-eclipse-plugin</a></p> <p>Is there a simple way to import into eclipse gradle project using gui, not doing stuff</p> <p>described here: <a href="http://gradle.org/docs/current/userguide/eclipse_plugin.html">http://gradle.org/docs/current/userguide/eclipse_plugin.html</a></p> <p>?</p>
10,730,545
11
1
null
2012-05-23 15:08:13.06 UTC
22
2020-10-01 17:10:27.997 UTC
2016-08-22 07:38:06.183 UTC
null
1,400,768
null
1,035,646
null
1
58
eclipse|gradle|import
142,822
<p>Usually it is a simple as adding <code>apply plugin: "eclipse"</code> in your <code>build.gradle</code> and running</p> <pre><code>cd myProject/ gradle eclipse </code></pre> <p>and then refreshing your Eclipse project.</p> <p>Occasionally you'll need to adjust <code>build.gradle</code> to generate Eclipse settings in some very specific way.</p> <p>There is <a href="http://static.springsource.org/sts/docs/2.7.0.M1/reference/html/gradle/gradle-sts-tutorial.html">gradle support for Eclipse</a> if you are using STS, but I'm not sure how good it is.</p> <p>The only IDE I know that has decent native support for gradle is <a href="http://www.jetbrains.com/idea/">IntelliJ IDEA</a>. It can do full import of gradle projects from GUI. There is a free Community Edition that you can try.</p>
22,870,624
Convert JSON String to JSON Object c#
<p>I have this String stored in my database:</p> <pre><code>str = "{ "context_name": { "lower_bound": "value", "upper_bound": "value", "values": [ "value1", "valueN" ] } }" </code></pre> <p>This string is already in the JSON format but I want to convert it into a JObject or JSON Object.</p> <pre><code>JObject json = new JObject(); </code></pre> <p>I tried the <code>json = (JObject)str;</code> cast but it didn't work so how can I do it?</p>
22,870,647
10
1
null
2014-04-04 18:41:18.607 UTC
28
2022-08-09 00:55:22.08 UTC
2015-09-16 03:10:06.16 UTC
null
28,074
null
2,613,886
null
1
222
c#|asp.net|json|string|parsing
741,444
<p><code>JObject</code> defines method <code>Parse</code> for this:</p> <pre><code>JObject json = JObject.Parse(str); </code></pre> <p>You might want to refer to Json.NET <a href="http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_Linq_JObject.htm">documentation</a>.</p>
7,637,752
Using Scala traits with implemented methods in Java
<p>I guess it is not possible to invoke methods implemented in Scala traits from Java, or is there a way? </p> <p>Suppose I have in Scala:</p> <pre><code>trait Trait { def bar = {} } </code></pre> <p>and in Java if I use it as </p> <pre><code>class Foo implements Trait { } </code></pre> <p>Java complains that <code>Trait is not abstract and does not override abstract method bar() in Trait</code></p>
7,637,888
2
1
null
2011-10-03 16:22:37.053 UTC
27
2015-01-07 12:33:25.873 UTC
2012-06-16 17:33:17.727 UTC
null
243,233
null
243,233
null
1
63
java|scala|scala-java-interop
15,627
<h2>Answer</h2> <p>From Java perspective <code>Trait.scala</code> is compiled into <code>Trait</code> <strong>interface</strong>. Hence implementing <code>Trait</code> in Java is interpreted as implementing an interface - which makes your error messages obvious. Short answer: you can't take advantage of trait implementations in Java, because this would enable multiple inheritance in Java (!)</p> <h3>How is it implemented in Scala?</h3> <p>Long answer: so how does it work in Scala? Looking at the generated bytecode/classes one can find the following code:</p> <pre><code>interface Trait { void bar(); } abstract class Trait$class { public static void bar(Trait thiz) {/*trait implementation*/} } class Foo implements Trait { public void bar() { Trait$class.bar(this); //works because `this` implements Trait } } </code></pre> <ul> <li><code>Trait</code> is an interface</li> <li>abstract <code>Trait$class</code> (do not confuse with <code>Trait.class</code>) class is created transparently, which technically does <strong>not</strong> implement <code>Trait</code> interface. However it does have a <code>static bar()</code> method taking <code>Trait</code> instance as argument (sort of <code>this</code>)</li> <li><code>Foo</code> implements <code>Trait</code> interface</li> <li><code>scalac</code> automatically implements <code>Trait</code> methods by delegating to <code>Trait$class</code>. This essentially means calling <code>Trait$class.bar(this)</code>.</li> </ul> <p>Note that <code>Trait$class</code> is neither a member of <code>Foo</code>, nor does <code>Foo</code> extend it. It simply delegates to it by passing <code>this</code>.</p> <h2>Mixing in multiple traits</h2> <p>To continue the digression on how Scala works... That being said it is easy to imagine how mixing in multiple traits works underneath:</p> <pre><code>trait Trait1 {def ping(){}}; trait Trait2 {def pong(){}}; class Foo extends Trait1 with Trait2 </code></pre> <p>translates to:</p> <pre><code>class Foo implements Trait1, Trait2 { public void ping() { Trait1$class.ping(this); //works because `this` implements Trait1 } public void pong() { Trait2$class.pong(this); //works because `this` implements Trait2 } } </code></pre> <h2>Multiple traits overriding same method</h2> <p>Now it's easy to imagine how mixing in multiple traits overriding same method:</p> <pre><code>trait Trait {def bar(){}}; trait Trait1 extends Trait {override def bar(){}}; trait Trait2 extends Trait {override def bar(){}}; </code></pre> <p>Again <code>Trait1</code> and <code>Trait2</code> will become interfaces extending <code>Trait</code>. Now if <code>Trait2</code> comes last when defining <code>Foo</code>:</p> <pre><code>class Foo extends Trait1 with Trait2 </code></pre> <p>you'll get:</p> <pre><code>class Foo implements Trait1, Trait2 { public void bar() { Trait2$class.bar(this); //works because `this` implements Trait2 } } </code></pre> <p>However switching <code>Trait1</code> and <code>Trait2</code> (making <code>Trait1</code> to be last) will result in:</p> <pre><code>class Foo implements Trait2, Trait1 { public void bar() { Trait1$class.bar(this); //works because `this` implements Trait1 } } </code></pre> <h2>Stackable modifications</h2> <p>Now consider how traits as stackable modifications work. Imagine having a really useful class Foo:</p> <pre><code>class Foo { def bar = "Foo" } </code></pre> <p>which you want to enrich with some new functionality using traits:</p> <pre><code>trait Trait1 extends Foo { abstract override def bar = super.bar + ", Trait1" } trait Trait2 extends Foo { abstract override def bar = super.bar + ", Trait2" } </code></pre> <p>Here is the new 'Foo' on steroids:</p> <pre><code>class FooOnSteroids extends Foo with Trait1 with Trait2 </code></pre> <p>It translates to:</p> <h3>Trait1</h3> <pre><code>interface Trait1 { String Trait1$$super$bar(); String bar(); } abstract class Trait1$class { public static String bar(Trait1 thiz) { // interface call Trait1$$super$bar() is possible // since FooOnSteroids implements Trait1 (see below) return thiz.Trait1$$super$bar() + ", Trait1"; } } </code></pre> <h3>Trait2</h3> <pre><code>public interface Trait2 { String Trait2$$super$bar(); String bar(); } public abstract class Trait2$class { public static String bar(Trait2 thiz) { // interface call Trait2$$super$bar() is possible // since FooOnSteroids implements Trait2 (see below) return thiz.Trait2$$super$bar() + ", Trait2"; } } </code></pre> <h3>FooOnSteroids</h3> <pre><code>class FooOnSteroids extends Foo implements Trait1, Trait2 { public final String Trait1$$super$bar() { // call superclass 'bar' method version return Foo.bar(); } public final String Trait2$$super$bar() { return Trait1$class.bar(this); } public String bar() { return Trait2$class.bar(this); } } </code></pre> <p>So the whole stack invocations are as follows:</p> <ul> <li>'bar' method on FooOnSteroids instance (entry point);</li> <li>Trait2$class's 'bar' static method passing this as argument and returning a concatenation of 'Trait2$$super$bar()' method call and string ", Trait2";</li> <li>'Trait2$$super$bar()' on FooOnSteroids instance which calls ...</li> <li>Trait1$class's 'bar' static method passing this as argument and returning a concatenation of 'Trait1$$super$bar()' method call and string ", Trait1";</li> <li>'Trait1$$super$bar' on FooOnSteroids instance which calls ...</li> <li>original Foo's 'bar' method</li> </ul> <p>And the result is "Foo, Trait1, Trait2".</p> <h2>Conclusion</h2> <p>If you've managed to read everything, an answer to the original question is in the first four lines...</p>
37,003,862
How to upload a file to Google Cloud Storage on Python 3?
<p>How can I upload a file to <a href="https://cloud.google.com/storage/" rel="noreferrer">Google Cloud Storage</a> from Python 3? Eventually Python 2, if it's infeasible from Python 3.</p> <p>I've looked and looked, but haven't found a solution that actually works. I tried <a href="https://github.com/boto/boto" rel="noreferrer">boto</a>, but when I try to generate the necessary .boto file through <code>gsutil config -e</code>, it keeps saying that I need to configure authentication through <code>gcloud auth login</code>. However, I have done the latter a number of times, without it helping.</p>
37,102,815
5
2
null
2016-05-03 12:14:39.76 UTC
24
2022-09-21 20:43:47.417 UTC
2020-08-31 23:27:03.913 UTC
null
5,780,109
null
265,261
null
1
71
python|python-3.x|google-cloud-storage|boto|google-cloud-platform
100,458
<p>Use the standard <a href="https://github.com/googleapis/google-cloud-python#google-cloud-python-client" rel="nofollow noreferrer">gcloud</a> library, which supports both Python 2 and Python 3.</p> <h2>Example of Uploading File to Cloud Storage</h2> <pre><code>from gcloud import storage from oauth2client.service_account import ServiceAccountCredentials import os credentials_dict = { 'type': 'service_account', 'client_id': os.environ['BACKUP_CLIENT_ID'], 'client_email': os.environ['BACKUP_CLIENT_EMAIL'], 'private_key_id': os.environ['BACKUP_PRIVATE_KEY_ID'], 'private_key': os.environ['BACKUP_PRIVATE_KEY'], } credentials = ServiceAccountCredentials.from_json_keyfile_dict( credentials_dict ) client = storage.Client(credentials=credentials, project='myproject') bucket = client.get_bucket('mybucket') blob = bucket.blob('myfile') blob.upload_from_filename('myfile') </code></pre>
17,936,515
Best practice for structuring libraries to be required in node.js
<p>I have several utility libraries which contain helper functions and I want to load them in order they can be used from the controllers and I'm wondering what is the best practice for coding utility libraries in node.</p> <p>I'm little bit confused because there are several ways to do it and I'm not sure what is the best/more suitable/more reliable. Here are 2 options but I'm wondering if they are the best (for example I've seen snippets that use <code>module.exports = exports = function(){}</code>, etc)</p> <p>//option1.js</p> <hr> <pre><code>"use strict"; module.exports = function(){ exports.test1 = function(){ console.log('hi I'm test1')}; exports.test2 = function(){ console.log('hi I'm test2')}; return exports; }; </code></pre> <p>//option2.js</p> <pre><code>"use strict"; module.exports = { test1 : function(){ console.log('soy test1')}, test2 : function(){ console.log('soy test2')} }; </code></pre> <p>//test_controller.js</p> <pre><code>/* Requiring helpers in different ways */ var option1 = require('./option1.js')(); var option2 = require('./option2.js'); </code></pre>
17,937,167
2
3
null
2013-07-30 00:36:01.903 UTC
12
2016-06-22 15:56:55.663 UTC
2016-06-22 15:56:55.663 UTC
null
1,235,615
null
1,235,615
null
1
23
node.js|design-patterns|require
10,385
<p>I think of my files in 3 sections:</p> <h1>Section 1: CommonJS Dependencies</h1> <pre><code>var lib1 = require("lib1"); var lib2 = require("lib2"); </code></pre> <p>You don't need any additional wrapper functions. All node modules are <a href="https://github.com/joyent/node/blob/6bd922fce83d505e44ee3706df9a78c0ad449d64/src/node.js#L800">automatically wrapped</a> by node.js in a function and doing so has no benefits and just adds clutter</p> <h1>Section 2: Plain JavaScript Code</h1> <p>This should be almost exclusively functions with a sprinkling of supporting variables or top level module code if needed.</p> <pre><code>var MY_CONST = 42; function helper1() { //excellent code here } function helper2() { //excellent code here } </code></pre> <p>Keep section 2 pure JS. Don't use commonJS idioms in this middle "pure" section. Don't use <code>module</code>, <code>exports</code>, <code>require</code>, etc. This is just my personal guideline as JS itself is stable but packaging in to modules is still under a lot of change and it's better to keep the CommonJS bits that are extraneous and likely to change separate from the interesting bits of code. ECMAScript 6 modules are most likely to replace CommonJS in a few years, so make this easier on yourself by keeping section 2 pure ECMAScript 5 and making an "CommonJS Sandwich™" as I like to call it.</p> <h1>Section 3: CommonJS exports</h1> <pre><code>exports.helper1 = helper1; exports.helper2 = helper2; </code></pre> <ul> <li>Putting all your exports at the end also gives you a quick way to understand what your public API is and prevents accidentally exporting properties due to a careless copy/paste.</li> <li>I prefer the above <code>exports.foo = foo;</code> syntax as opposed to assigning <code>module.exports</code> to a new object literal. I find this avoids the trailing comma issue with the last property of an object literal.</li> <li>Doing anything else with your <code>require</code> or <code>exports</code> statements is almost certainly unnecessary and needlessly slick or magic. Until you get to be advanced, don't do anything fancy here. (even then, if you're not TJ Holowaychuk, you're probably just being silly)</li> </ul> <h1>What should I export</h1> <h2>A single function (@substack style)</h2> <pre><code>function degreesToRadians(degrees) {} module.exports = degreesToRadians; </code></pre> <p>Keep it small and simple.</p> <h2>An object of functions</h2> <p>If your module is a set of helper functions, you should export an object containing those functions as properties</p> <pre><code>var foo = require("foo"); function doubleFoo(value) { return foo(value) * 2; } function tripleFoo(value) { return foo(value) * 3; } exports.doubleFoo = doubleFoo; exports.tripleFoo = tripleFoo; </code></pre> <h2>A Constructor Function</h2> <p>If your module is a class design for object-oriented use, export the constructor function</p> <pre><code>function GoCart() { this.wheels = 4; } GoCart.prototype.drive = function drive() { //vroom vroom } module.exports = GoCart; </code></pre> <h2>A Factory/Config Closure Function</h2> <p>Once you have mastered the above 2 patterns (really!) and feel confident exporting a factory function that takes options and maybe does some other dynamic stuff, go for it, but when in doubt, stick with the first 2, simpler choices.</p> <pre><code>//do-stuff.js function doStuff(howFast, what) { return "I am doing " + what + " at speed " + howFast; } function setup(options) { //The object returned by this will have closure access to options //for its entire lifetime return {doStuff: doStuff.bind(null, options.howFast)}; } module.exports = setup; </code></pre> <p>So you could use that like</p> <pre><code>var doStuff = require("./do-stuff")({howFast: "blazing speed"}); console.log(doStuff.doStuff("jogging")); //"I am doing jogging at speed blazing speed" </code></pre>
35,432,378
Python reshape list to ndim array
<p>Hi I have a list flat which is length 2800, it contains 100 results for each of 28 variables: Below is an example of 4 results for 2 variables</p> <pre><code>[0, 0, 1, 1, 2, 2, 3, 3] </code></pre> <p>I would like to reshape the list to an array (2,4) so that the results for each variable are in a single element. </p> <pre><code>[[0,1,2,3], [0,1,2,3]] </code></pre>
35,432,621
4
1
null
2016-02-16 12:16:03.567 UTC
6
2022-04-28 11:17:26.133 UTC
2019-12-07 15:25:03.147 UTC
null
4,538,066
null
4,538,066
null
1
28
python|numpy|reshape
161,144
<p>You can think of reshaping that the new shape is filled row by row (last dimension varies fastest) from the flattened original list/array.</p> <p>If you want to fill an array by column instead, an easy solution is to shape the list into an array with reversed dimensions and then transpose it:</p> <pre><code>x = np.reshape(list_data, (100, 28)).T </code></pre> <p>Above snippet results in a 28x100 array, filled column-wise.</p> <p>To illustrate, here are the two options of shaping a list into a 2x4 array:</p> <pre><code>np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (4, 2)).T # array([[0, 1, 2, 3], # [0, 1, 2, 3]]) np.reshape([0, 0, 1, 1, 2, 2, 3, 3], (2, 4)) # array([[0, 0, 1, 1], # [2, 2, 3, 3]]) </code></pre>
3,296,050
How does this regex find primes?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2795065/how-to-determine-if-a-number-is-a-prime-with-regex">How to determine if a number is a prime with regex?</a> </p> </blockquote> <p><a href="http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/" rel="noreferrer">This page</a> claims that this regular expression discovers non-prime numbers (and by counter-example: primes):</p> <pre><code>/^1?$|^(11+?)\1+$/ </code></pre> <p>How does this find primes?</p>
3,296,068
1
5
null
2010-07-21 03:18:29.847 UTC
32
2017-10-19 17:21:18.31 UTC
2017-05-23 11:54:22.457 UTC
null
-1
null
356
null
1
70
regex|primes
21,195
<p>I think the article explains it rather well, but I'll try my hand at it as well.</p> <p>Input is in <a href="http://en.wikipedia.org/wiki/Unary_numeral_system" rel="noreferrer">unary</a> form. 1 is <code>1</code>, 2 is <code>11</code>, 3 is <code>111</code>, etc. Zero is an empty string.</p> <p>The first part of the regex matches 0 and 1 as non-prime. The second is where the magic kicks in.</p> <p><code>(11+?)</code> starts by finding divisors. It starts by being defined as <code>11</code>, or 2. <code>\1</code> is a variable referring to that previously captured match, so <code>\1+</code> determines if the number is divisible by that divisor. (<code>111111</code> starts by assigning the variable to <code>11</code>, and then determines that the remaining <code>1111</code> is <code>11</code> repeated, so 6 is divisible by 2.)</p> <p>If the number is not divisible by two, the regex engine increments the divisor. <code>(11+?)</code> becomes <code>111</code>, and we try again. If at any point the regex matches, the number has a divisor that yields no remainder, and so the number cannot be prime.</p>
3,951,840
How to invoke a function on an object dynamically by name?
<p>In Python, say I have a string that contains the name of a class function that I know a particular object will have, how can I invoke it?</p> <p>That is:</p> <pre><code>obj = MyClass() # this class has a method doStuff() func = "doStuff" # how to call obj.doStuff() using the func variable? </code></pre>
3,951,850
1
3
null
2010-10-17 03:01:52.877 UTC
11
2021-11-05 01:57:29.983 UTC
2019-06-08 08:48:34.293 UTC
null
7,851,470
null
18,494
null
1
78
python
54,171
<p>Use the <code>getattr</code> built-in function. See the <a href="http://docs.python.org/library/functions.html?highlight=getattr#getattr" rel="noreferrer">documentation</a></p> <pre class="lang-py prettyprint-override"><code>obj = MyClass() try: func = getattr(obj, &quot;dostuff&quot;) func() except AttributeError: print(&quot;dostuff not found&quot;) </code></pre>
41,067,025
How to retrieve a value from dictionary in Swift 3
<p>I have this function that fetch users from <code>FireBase</code> and convert them in <code>Dictionary</code>:</p> <pre><code> let leaderBoardDB = FIRDatabase.database().reference().child("scores1").queryOrderedByValue().queryLimited(toLast: 5) leaderBoardDB.observe( .value, with: { (snapshot) in print("scores scores", snapshot) if let dictionary = snapshot.value as? [String: Any] { for playa in dictionary { let player = Player() print("plaaaaayyyyyaaaaa", playa) print("plaaaaayyyyyaaaaa key", playa.key) print("plaaaaayyyyyaaaaa.value", playa.value) player.id = playa.key print(playa.key["name"]) } } }, withCancel: nil) } </code></pre> <p>and I get this result: </p> <blockquote> <p>plaaaaayyyyyaaaaa ("inovoID", { name = Tatiana; points = 6; }) plaaaaayyyyyaaaaa key inovoID plaaaaayyyyyaaaaa.value { name = Tatiana; points = 6; } aaaa i id Optional("inovoID")</p> </blockquote> <p>the problem is that i can't obtain the name and the points of the user. when i try it with:</p> <pre><code>print(playa.key["name"]) </code></pre> <p>it gaves me this error:</p> <blockquote> <p>Cannot subscript a value of type 'String' with an index of type 'String'</p> </blockquote> <p>can anyone help me with this, please?</p>
41,067,662
2
2
null
2016-12-09 18:50:15.653 UTC
3
2016-12-09 19:42:17.64 UTC
2016-12-09 19:42:17.64 UTC
null
5,044,042
null
7,227,567
null
1
6
swift|dictionary
44,014
<p>Since your JSON is </p> <pre><code>"inovoID" : { "name" : "Tatiana", "points" : 6 } </code></pre> <ul> <li><code>playa.key</code> is <code>"inovoID"</code></li> <li><code>playa.value</code> is <code>{ "name" : "Tatiana", "points" : 6 }</code></li> </ul> <p>The <strong>key</strong> is <code>String</code> and cannot be subscripted. That's what the error says.</p> <p>You need to subscribe the <strong>value</strong> and safely cast the type to help the compiler.</p> <pre><code>if let person = playa.value as? [String:Any] { print(person["name"] as! String) } </code></pre>
2,032,417
Android - Activity vs. ListActivity - Which one should my activity class extend?
<p>I've been learning to develop in Android and had more of a general question: If I have a layout that uses a list and some other views, should I be using Activity or ListActivity for my activity class?</p> <p>I know that ListActivity will probably make things easier to override list-specific events, but is there any other advantage to using a ListActivity over Activity? What if I wanted to change the layout in the future to a GridView? Would it be any more/less of a pain to change the class' code?</p> <p>I was just curious about "best practices" in this regard and what the benefits entail, so any answer would be helpful :)</p> <p>Bara</p>
2,032,590
3
0
null
2010-01-09 05:08:48.653 UTC
8
2018-01-25 07:05:05.377 UTC
null
null
null
null
164,312
null
1
30
android|android-activity|listactivity
23,006
<p>I'd use a <code>ListActivity</code> since it gives you a lot of shortcut methods to make things easier and keep your code more readable.</p> <p>For example, you get the <a href="http://developer.android.com/reference/android/app/ListActivity.html#onListItemClick(android.widget.ListView,%20android.view.View,%20int,%20long)" rel="noreferrer"><code>onListItemClick() method</code></a> which is called whenever you click a item which saves you from creating a separate listener.</p> <p>If you want to change the layout of a <code>ListActivity</code> you still can with <a href="http://developer.android.com/reference/android/app/Activity.html#setContentView(int)" rel="noreferrer"><code>setContentView()</code> method from <code>Activity</code></a>. As long as there is a <code>ListView</code> called <code>@android:id/list</code> somewhere in your <code>View</code> the <code>ListActivity</code> will still work.</p> <p>If you're still not sure, you could always look at the <a href="http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/app/ListActivity.java;h=19b99c874afbaa1ca9a0bf2a0ae01ee064bb6b43;hb=HEAD" rel="noreferrer">source code for <code>ListActivity</code></a> and see that it doesn't do all that much other than make your life a little easier.</p>
8,409,095
Set markers for individual points on a line in Matplotlib
<p>I have used Matplotlib to plot lines on a figure. Now I would now like to set the style, specifically the marker, for individual points on the line. How do I do this?</p> <p>To clarify my question, I want to be able to set the style for individual markers on a line, not every marker on said line.</p>
8,409,110
5
1
null
2011-12-07 00:56:02.277 UTC
123
2022-09-14 06:51:32.663 UTC
2020-05-23 11:30:58.127 UTC
null
7,851,470
null
179,352
null
1
260
python|matplotlib
483,809
<p>Specify the keyword args <code>linestyle</code> and/or <code>marker</code> in your call to <code>plot</code>.</p> <p>For example, using a dashed line and blue circle markers:</p> <pre><code>plt.plot(range(10), linestyle='--', marker='o', color='b', label='line with marker') plt.legend() </code></pre> <p>A shortcut call for the same thing:</p> <pre><code>plt.plot(range(10), '--bo', label='line with marker') plt.legend() </code></pre> <p><a href="https://i.stack.imgur.com/iRLpX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iRLpX.png" alt="enter image description here" /></a></p> <p>Here is a list of the possible line and marker styles:</p> <pre><code>================ =============================== character description ================ =============================== - solid line style -- dashed line style -. dash-dot line style : dotted line style . point marker , pixel marker o circle marker v triangle_down marker ^ triangle_up marker &lt; triangle_left marker &gt; triangle_right marker 1 tri_down marker 2 tri_up marker 3 tri_left marker 4 tri_right marker s square marker p pentagon marker * star marker h hexagon1 marker H hexagon2 marker + plus marker x x marker D diamond marker d thin_diamond marker | vline marker _ hline marker ================ =============================== </code></pre> <hr /> <p><em>edit:</em> with an example of marking an arbitrary subset of points, as requested in the comments:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt xs = np.linspace(-np.pi, np.pi, 30) ys = np.sin(xs) markers_on = [12, 17, 18, 19] plt.plot(xs, ys, '-gD', markevery=markers_on, label='line with select markers') plt.legend() plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/xG4iV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xG4iV.png" alt="enter image description here" /></a></p> <p>This last example using the <code>markevery</code> kwarg is possible in since 1.4+, due to the merge of <a href="https://github.com/matplotlib/matplotlib/pull/2662" rel="noreferrer">this feature branch</a>. If you are stuck on an older version of matplotlib, you can still achieve the result by overlaying a scatterplot on the line plot. See the <a href="https://stackoverflow.com/posts/8409110/revisions">edit history</a> for more details.</p>
8,761,992
Launch a script as root through ADB
<p>I have created a script to mount partitions and do some stuff in my Android system. I saved the script as install.sh in the /bin folder of Android.</p> <p>I want to call the script from ADB, which is itself called from a batch file on Windows, but it needs to be executed as root.</p> <p>The first solution I tried was to call the script using</p> <pre><code>adb shell "su -c sh /bin/script.sh" </code></pre> <p>but it does not work as it gives me a shell access (with root permissions), but nothing is executed. I also tried to call </p> <pre><code>adb root "sh /bin/script.sh" </code></pre> <p>but I got the following error</p> <pre><code>adbd cannot run as root in production builds </code></pre> <p>I then tried to write</p> <pre><code>su -c "command" </code></pre> <p>for all the commands which need a root access in my script, but I have the same problem. When I run the script I only obtain a root shell and nothing is executed.</p> <p>If I use the first solution by hand (e.g. I call adb shell su, then my script), it works. However the whole point is to automate the process, so that adb shell can be called from another script.</p> <p>Do you have any idea of how I could achieve this ?</p> <p>Thanks !</p>
9,418,553
6
1
null
2012-01-06 17:37:11.4 UTC
12
2018-09-28 04:42:47.553 UTC
null
null
null
null
1,073,197
null
1
27
android|shell|root|adb
89,583
<p>This works for me: </p> <p>Create myscript.bat and put into it (note the single quotes around the commands to be executed in superuser mode):</p> <pre><code>adb shell "su -c 'command1; command2; command3'" </code></pre> <p>then run myscript.bat from a DOS shell.</p> <p>Note: it doesn't appear that the the DOS line continuation character (^) works in this situation. In other words, the following doesn't work for me:</p> <pre><code>adb shell "su -c '^ command1; ^ command2; ^ command3'" </code></pre> <p>This results in "Syntax error: Unterminated quoted string"</p>
19,502,546
Cronjob for 1st of January every year
<p>I am trying to get the correct cronjob time for 1st of January every year.</p> <p>I thougth about this: <code>0 0 1 1 *</code></p> <p>Can anybody tell me, if it is correct?</p>
19,502,604
3
1
null
2013-10-21 19:00:21.807 UTC
9
2020-08-12 02:05:11.503 UTC
null
null
null
null
804,432
null
1
32
cron
35,710
<p>Yes that is correct.</p> <p>Here is a quick chart you can use for future reference</p> <pre><code># * * * * * command to execute # ┬ ┬ ┬ ┬ ┬ # │ │ │ │ │ # │ │ │ │ │ # │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday) # │ │ │ └────────── month (1 - 12) # │ │ └─────────────── day of month (1 - 31) # │ └──────────────────── hour (0 - 23) # └───────────────────────── min (0 - 59) </code></pre>
1,271,143
jquery adding an onclick event to a href link
<p>i am converting over from websforms to asp.net mvc and i have a question.</p> <p>i have a loop that generates links dynamicallly where picNumberLink is a variable in a loop and image is a variable image link.</p> <p></p> <p>i want to avoid putting javascript actions inline so in my webforms project is did the following:</p> <pre><code>hyperLink.Attributes.Add("onclick", "javascript:void(viewer.show(" + picNumberlink + "))"); </code></pre> <p>what is the equivalent using jquery in asp.net mvc?</p> <p>I have seen examples of using the $(document).ready event to attach on clicks but i can't figure out the syntax to pass in the picNumberLink variable into the javascript function.</p> <p>suggestions?</p>
1,271,157
4
0
null
2009-08-13 10:15:44.897 UTC
null
2020-01-30 10:36:24.647 UTC
null
null
null
null
4,653
null
1
5
asp.net|jquery|asp.net-mvc
38,189
<p>EDIT: If you generate your links with the ID of this form:</p> <pre><code>&lt;a id="piclink_1" class="picLinks"&gt;...&lt;/a&gt; &lt;a id="picLink_2" class="picLinks"&gt;...&lt;/a&gt; &lt;script type="text/javascript"&gt; $('a.picLinks').click(function () { //split at the '_' and take the second offset var picNumber = $(this).attr('id').split('_')[1]; viewer.show(picNumber); }); &lt;/script&gt; </code></pre>
1,001,374
Mac driver development
<p>I am thinking about migrating a Windows driver into OS X. Now I am just starting to look around to see what is available and there is a lot about objective C and cocoa. Seems that the language and the cocoa framework are high level APIs, am I right to assume that?</p> <p>I have strong C++ skills and I use them for kernel development, can I use the same skills for Mac driver development (I imagine the answer is yes). Has Macintosh any type of application/dev environment for building drivers?</p>
1,001,388
4
0
null
2009-06-16 13:08:19.863 UTC
13
2020-04-06 21:16:51.36 UTC
2014-07-23 11:29:08.957 UTC
null
321,731
null
87,602
null
1
12
macos|kernel|driver
13,958
<p>The <a href="http://developer.apple.com/samplecode/HardwareDrivers/index.html" rel="noreferrer">Apple Hardware &amp; Drivers page</a> has lots of information about Mac driver development. It should be enough to get you started. Some of the highlights:</p> <ul> <li><p><a href="https://developer.apple.com/library/mac/#referencelibrary/GettingStarted/GS_HardwareDrivers/_index.html" rel="noreferrer"><strong>Getting Started</strong></a> - A guided learning path for hardware and driver developers new to Mac OS X.</p></li> <li><p><a href="http://developer.apple.com/referencelibrary/API_Fundamentals/HardwareDrivers-api-date.html" rel="noreferrer"><strong>Frameworks</strong></a> - API references organized by framework. </p></li> <li><p><a href="http://developer.apple.com/samplecode/HardwareDrivers/idxUSB-date.html" rel="noreferrer"><strong>USB Sample Code</strong></a> - Resources for developing USB devices and software to access them. </p></li> <li><p><a href="http://developer.apple.com/samplecode/HardwareDrivers/idxFireWire-date.html" rel="noreferrer"><strong>FireWire Sample Code</strong></a> - Resources for developing FireWire devices and software to access them. </p></li> </ul>
874,082
Show only the first N lines of output of a SQL query
<p>Is there a way to only show the first N lines of output from an <code>SQL</code> query?<br> Bonus points, if the query stops running once the <code>N</code> lines are outputted.</p> <p>I am most interested in finding something which works in <code>Oracle</code>.</p>
874,092
4
0
null
2009-05-17 07:28:24.243 UTC
6
2016-03-30 19:32:35.323 UTC
2015-05-09 19:31:38.363 UTC
null
27,060
null
95,375
null
1
22
sql
101,363
<p>It would be helpful if you specify what database you are targetting. Different databases have different syntax and techniques to achieve this:</p> <p>For example in Oracle you can ahieve this by putting condition on <code>RowNum</code> (<code>select ... from ... where ... rownum &lt; 11</code> -> would result in outputting first 10 records)</p> <p>In <code>MySQL</code> you can use you can use <code>limit</code> clause.</p> <p><strong>Microsoft SQL Server =></strong> <code>SELECT TOP 10 column FROM table</code></p> <p><strong>PostgreSQL and MySQL =></strong> <code>SELECT column FROM table LIMIT 10</code></p> <p><strong>Oracle =></strong> <code>select * from (SELECT column FROM table ) WHERE ROWNUM &lt;= 10</code> (thanks to stili)</p> <p><strong>Sybase =></strong> <code>SET rowcount 10 SELECT column FROM table</code> </p> <p><strong>Firebird =></strong> <code>SELECT FIRST 10 column FROM table</code></p> <p>NOTE: Modern <code>ORM</code> tools such as Hibernate give high level API (Query, Restriction, Condition interfaces) that abstract the logic of top n rows based on the dialect you choose.</p>
1,188,760
In Jquery how do you find out the 'eq' of an element of what is being clicked?
<p>When one of the divs inside 'uploadChoice' is clicked, how can I ascertain which one is clicked? Can I return an 'eq' value somehow?</p> <pre><code> &lt;div id=uploadChoice&gt; &lt;div&gt;Text&lt;/div&gt; &lt;div&gt;Image&lt;/div&lt; &lt;div&gt;Text &amp; Image&lt;/div&gt; &lt;/div&gt; $("#uploadChoice div").click(function(){ //insert code here! :) }); </code></pre>
1,188,774
4
0
null
2009-07-27 15:14:21.983 UTC
5
2015-04-06 09:13:13.003 UTC
2009-08-19 17:06:22.603 UTC
null
6,440
null
145,672
null
1
34
jquery
24,662
<pre><code>$('#uploadChoice div').click(function(event) { var index = $(this).index(); }); </code></pre>
1,012,408
What's wrong with this HQL? "No data type for node"
<pre><code>session.createQuery("Select attribute from GoodsSection tgs " + "join gs.ascendants ags join ags.attributes attribute " + "where attribute.outerId = :outerId and tgs = :section ") .setString("outerId", pOuterId) .setEntity("section", section) .setMaxResults(1) .uniqueResult(); </code></pre> <p>Looks fine to me, but the result is</p> <pre><code>java.lang.IllegalStateException: No data type for node: org.hibernate.hql.ast.tree.IdentNode \-[IDENT] IdentNode: 'attribute' {originalText=attribute} at org.hibernate.hql.ast.tree.SelectClause.initializeExplicitSelectClause(SelectClause.java:145) at org.hibernate.hql.ast.HqlSqlWalker.useSelectClause(HqlSqlWalker.java:705) at org.hibernate.hql.ast.HqlSqlWalker.processQuery(HqlSqlWalker.java:529) at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:645) at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281) at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229) </code></pre> <p>Why? What's wrong?</p>
1,012,518
1
0
null
2009-06-18 12:36:34.917 UTC
1
2016-04-18 08:19:03.447 UTC
null
null
null
null
36,498
null
1
47
java|hibernate|hql
65,416
<p>You haven't defined the "gs" alias. You only have "ags" and "tgs".</p>
55,801,157
How to fix gradle build error A problem occurred configuring root project?
<p>Every time I try to build a project this happens. Android studio version 3.4 Gradle sync fails at configure build</p> <p>For some reason it can not get resource at the url. But I can download the file from browser.</p> <pre><code>Caused by: org.gradle.api.resources.ResourceException: Could not get resource 'https://maven.google.com/com/android/tools/build/gradle/3.2.1/gradle-3.2.1.jar'. </code></pre> <p>Full Error:</p> <pre><code>org.gradle.api.ProjectConfigurationException: A problem occurred configuring root project 'Web2App'. at org.gradle.configuration.project.LifecycleProjectEvaluator.addConfigurationFailure(LifecycleProjectEvaluator.java:94) at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:66) at org.gradle.configuration.project.LifecycleProjectEvaluator.access$100(LifecycleProjectEvaluator.java:34) at org.gradle.configuration.project.LifecycleProjectEvaluator$ConfigureProject.run(LifecycleProjectEvaluator.java:110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55) at java.lang.Thread.run(Thread.java:745) Caused by: org.gradle.api.internal.artifacts.ivyservice.DefaultLenientConfiguration$ArtifactResolveException: Could not resolve all files for configuration ':classpath'. at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.rethrowFailure(DefaultConfiguration.java:915) at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.access$1600(DefaultConfiguration.java:116) at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration$ConfigurationFileCollection.getFiles(DefaultConfiguration.java:889) at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration.getFiles(DefaultConfiguration.java:401) at org.gradle.api.internal.artifacts.configurations.DefaultConfiguration_Decorated.getFiles(Unknown Source) at org.gradle.api.internal.file.AbstractFileCollection.iterator(AbstractFileCollection.java:68) at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199) at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110) at org.gradle.configuration.BuildOperationScriptPlugin.apply(BuildOperationScriptPlugin.java:58) at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:41) at org.gradle.configuration.project.BuildScriptProcessor.execute(BuildScriptProcessor.java:26) at org.gradle.configuration.project.ConfigureActionsProjectEvaluator.evaluate(ConfigureActionsProjectEvaluator.java:34) at org.gradle.configuration.project.LifecycleProjectEvaluator.doConfigure(LifecycleProjectEvaluator.java:64) ... 84 more Caused by: org.gradle.internal.resolve.ArtifactResolveException: Could not download gradle.jar (com.android.tools.build:gradle:3.2.1) at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver$RemoteRepositoryAccess.resolveArtifact(ExternalResourceResolver.java:439) at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleComponentRepository$ResolveAndCacheRepositoryAccess.resolveArtifact(CachingModuleComponentRepository.java:409) at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.BaseModuleComponentRepositoryAccess.resolveArtifact(BaseModuleComponentRepositoryAccess.java:65) at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.memcache.InMemoryCachedModuleComponentRepository$CachedAccess.resolveArtifact(InMemoryCachedModuleComponentRepository.java:124) at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.resolveArtifact(ErrorHandlingModuleComponentRepository.java:174) at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.RepositoryChainArtifactResolver.resolveArtifact(RepositoryChainArtifactResolver.java:80) at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.DefaultArtifactSet$LazyArtifactSource.create(DefaultArtifactSet.java:170) at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.DefaultArtifactSet$LazyArtifactSource.create(DefaultArtifactSet.java:157) at org.gradle.api.internal.artifacts.DefaultResolvedArtifact.getFile(DefaultResolvedArtifact.java:135) at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ArtifactBackedResolvedVariant$DownloadArtifactFile.run(ArtifactBackedResolvedVariant.java:146) at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336) at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328) at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199) at org.gradle.internal.progress.DefaultBuildOperationExecutor.access$900(DefaultBuildOperationExecutor.java:63) at org.gradle.internal.progress.DefaultBuildOperationExecutor$ParentPreservingQueueWorker.execute(DefaultBuildOperationExecutor.java:378) at org.gradle.internal.operations.DefaultBuildOperationQueue$WorkerRunnable.runOperation(DefaultBuildOperationQueue.java:230) at org.gradle.internal.operations.DefaultBuildOperationQueue$WorkerRunnable.access$600(DefaultBuildOperationQueue.java:172) at org.gradle.internal.operations.DefaultBuildOperationQueue$WorkerRunnable$1.call(DefaultBuildOperationQueue.java:209) at org.gradle.internal.operations.DefaultBuildOperationQueue$WorkerRunnable$1.call(DefaultBuildOperationQueue.java:203) at org.gradle.internal.progress.DefaultBuildOperationExecutor.runAll(DefaultBuildOperationExecutor.java:130) at org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ParallelResolveArtifactSet$VisitingSet.visit(ParallelResolveArtifactSet.java:60) ... 139 more Caused by: org.gradle.internal.resource.transport.http.HttpRequestException: Could not GET 'https://maven.google.com/com/android/tools/build/gradle/3.2.1/gradle-3.2.1.jar'. at org.gradle.internal.resource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:96) at org.gradle.internal.resource.transport.http.HttpClientHelper.performRawGet(HttpClientHelper.java:80) at org.gradle.internal.resource.transport.http.HttpClientHelper.performGet(HttpClientHelper.java:84) at org.gradle.internal.resource.transport.http.HttpResourceAccessor.openResource(HttpResourceAccessor.java:43) at org.gradle.internal.resource.transport.http.HttpResourceAccessor.openResource(HttpResourceAccessor.java:29) at org.gradle.internal.resource.transfer.DefaultExternalResourceConnector.openResource(DefaultExternalResourceConnector.java:56) at org.gradle.internal.resource.transfer.ProgressLoggingExternalResourceAccessor.openResource(ProgressLoggingExternalResourceAccessor.java:36) at org.gradle.internal.resource.transfer.AccessorBackedExternalResource.withContentIfPresent(AccessorBackedExternalResource.java:130) at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator$11.call(BuildOperationFiringExternalResourceDecorator.java:237) at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator$11.call(BuildOperationFiringExternalResourceDecorator.java:229) at org.gradle.internal.progress.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:350) at org.gradle.internal.progress.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:340) at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199) at org.gradle.internal.progress.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:120) at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator.withContentIfPresent(BuildOperationFiringExternalResourceDecorator.java:229) at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.copyToCache(DefaultCacheAwareExternalResourceAccessor.java:199) ... 148 more Caused by: java.net.SocketException: Software caused connection abort: recv failed at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.socketRead(SocketInputStream.java:116) at java.net.SocketInputStream.read(SocketInputStream.java:170) at java.net.SocketInputStream.read(SocketInputStream.java:141) at sun.security.ssl.InputRecord.readFully(InputRecord.java:465) at sun.security.ssl.InputRecord.read(InputRecord.java:503) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973) at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:930) at sun.security.ssl.AppInputStream.read(AppInputStream.java:105) at org.apache.http.impl.io.SessionInputBufferImpl.streamRead(SessionInputBufferImpl.java:139) at org.apache.http.impl.io.SessionInputBufferImpl.fillBuffer(SessionInputBufferImpl.java:155) at org.apache.http.impl.io.SessionInputBufferImpl.readLine(SessionInputBufferImpl.java:284) at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:140) at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:57) at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:261) at org.apache.http.impl.DefaultBHttpClientConnection.receiveResponseHeader(DefaultBHttpClientConnection.java:165) at org.apache.http.impl.conn.CPoolProxy.receiveResponseHeader(CPoolProxy.java:167) at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:272) at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:124) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:271) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.gradle.internal.resource.transport.http.HttpClientHelper.performHttpRequest(HttpClientHelper.java:148) at org.gradle.internal.resource.transport.http.HttpClientHelper.performHttpRequest(HttpClientHelper.java:126) at org.gradle.internal.resource.transport.http.HttpClientHelper.executeGetOrHead(HttpClientHelper.java:103) at org.gradle.internal.resource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:94) ... 163 more </code></pre> <p>Below is the gradle file:</p> <pre><code>// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() maven { url 'https://maven.google.com/' name 'Google' } } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } ext { supportlib_version = '28.0.0' gps_version = '[16.0.0, 17.0.0)' fb_version = '[15.0.0, 17.0.0)' } //Ensure that all dependencies use the same version of the Android Support library subprojects { project.configurations.all { resolutionStrategy.eachDependency { details -&gt; if (details.requested.group == 'com.android.support' &amp;&amp; !details.requested.name.contains('multidex')) { details.useVersion "$supportlib_version" } if (details.requested.group == 'com.google.android.gms' &amp;&amp; !details.requested.name.contains('multidex')) { details.useVersion "$gps_version" } if (details.requested.group == 'com.google.firebase' &amp;&amp; !details.requested.name.contains('multidex')) { details.useVersion "$fb_version" } } } } allprojects { repositories { google() jcenter() } } </code></pre> <p>I have tried following.</p> <ol> <li>Invalided cache restart,</li> <li>Local gradle distribution</li> <li>rebuild project/clean project</li> <li>Reinstall android studio</li> <li>Re download sdk</li> <li>sync project with gradle files</li> <li>Check marked enable embedded maven repository.</li> </ol>
55,801,337
5
1
null
2019-04-22 21:09:03.987 UTC
1
2021-11-25 10:55:46.837 UTC
2019-04-24 02:30:48.433 UTC
null
8,034,839
null
5,394,546
null
1
6
java|android|gradle|build|android-gradle-plugin
60,778
<p>The very first thing I'd guess, there might be a Firewall blocking the connection of Android Studio. </p> <p>If so, try to disable it for a brief moment and test again. If it works, you might want to add Android Studio to your firewall whitelist.</p>
19,648,088
Pass environment variables to vagrant shell provisioner
<p>It looks like passing environment variables when calling <code>vagrant up</code> is simple if you're using a Ruby provisioner:</p> <pre><code>VAR=123 vagrant up </code></pre> <p>In the Vagrantfile:</p> <pre><code>ENV['VAR'] </code></pre> <p>How do I do this with the <code>:shell</code> provisioner? Simply doing this does not seem to work:</p> <pre><code>$VAR </code></pre>
19,648,220
12
0
null
2013-10-29 01:26:34.81 UTC
26
2022-08-07 09:47:30.213 UTC
2015-07-09 16:28:24.53 UTC
null
56,083
null
47,110
null
1
88
vagrant|environment-variables
72,980
<p>It's not ideal, but I got this to work for now:</p> <pre><code>config.vm.provision "shell" do |s| s.inline = "VAR1 is $1 and VAR2 is $2" s.args = "#{ENV['VAR1']} #{ENV['VAR2']}" end </code></pre>
48,565,643
Get the metadata of an order item in woocommerce 3
<p>how to get metadata of a product woocommerce? I have field custom en my products and I need to get this data.</p> <pre><code>{"ID":151, "ORDER_ID":251, "NAME":"car", "PRODUCT_ID":87, "VARIATION_ID":0, "QUANTITY":1, "TAX_CLASS":"", "SUBTOTAL":"3", "SUBTOTAL_TAX":"0", "TOTAL":"3", "TOTAL_TAX":"0", "TAXES":{"TOTAL":[], "SUBTOTAL":[]}, "META_DATA":[{"ID":1433, "KEY":"my_car", "VALUE":"red"}]} </code></pre> <p>But the always result is the same, I can't access to field <code>meta_data</code>. The field <code>ID</code> and <code>name</code> I have access.</p> <p>I used <code>get_data()</code> and <code>get_item()</code>, but when I try access with <code>get_data()</code> to field <code>meta_data</code> it give me this error:</p> <pre><code> UNCAUGHT ERROR: CANNOT USE OBJECT OF TYPE WC_DATETIME AS ARRAY IN </code></pre> <p>And with <code>get_item()</code>, the value <code>meta_data</code> is null because is protected.</p> <p>How can i get these values?</p>
48,567,687
2
1
null
2018-02-01 14:54:54.077 UTC
6
2021-04-14 07:07:09.817 UTC
2018-02-01 16:46:16.507 UTC
null
3,730,754
null
9,240,307
null
1
19
php|wordpress|woocommerce|metadata|orders
41,833
<p>Try the following:</p> <pre><code>// Get the $order object from an ID (if needed only) $order = wc_get_order( $order_id); // Loop through order line items foreach( $order-&gt;get_items() as $item ){ // get order item data (in an unprotected array) $item_data = $item-&gt;get_data(); // get order item meta data (in an unprotected array) $item_meta_data = $item-&gt;get_meta_data(); // get only All item meta data even hidden (in an unprotected array) $formatted_meta_data = $item-&gt;get_formatted_meta_data( '_', true ); // Display the raw outputs (for testing) echo '&lt;pre&gt;' . print_r($item_meta_data, true) . '&lt;/pre&gt;'; echo '&lt;pre&gt;' . print_r($formatted_meta_data, true) . '&lt;/pre&gt;'; } </code></pre> <p>Related:</p> <ul> <li><a href="https://stackoverflow.com/questions/39401393/how-to-get-woocommerce-order-details">How to get WooCommerce order details</a></li> <li><a href="https://stackoverflow.com/questions/45706007/get-order-items-and-wc-order-item-product-in-woocommerce-3/45706318#45706318">Get Order items and WC_Order_Item_Product in WooCommerce 3</a></li> </ul>
41,254,011
SparkSQL - Read parquet file directly
<p>I am migrating from Impala to SparkSQL, using the following code to read a table:</p> <pre><code>my_data = sqlContext.read.parquet('hdfs://my_hdfs_path/my_db.db/my_table') </code></pre> <p>How do I invoke SparkSQL above, so it can return something like:</p> <pre><code>'select col_A, col_B from my_table' </code></pre>
41,254,078
4
0
null
2016-12-21 02:03:19.81 UTC
15
2020-09-08 04:05:08.95 UTC
2018-12-06 01:48:07.483 UTC
null
1,592,191
null
3,993,270
null
1
28
scala|apache-spark|hive|apache-spark-sql|hdfs
106,854
<p>After creating a Dataframe from parquet file, you have to register it as a temp table to run <code>sql queries</code> on it.</p> <pre><code>val sqlContext = new org.apache.spark.sql.SQLContext(sc) val df = sqlContext.read.parquet("src/main/resources/peopleTwo.parquet") df.printSchema // after registering as a table you will be able to run sql queries df.registerTempTable("people") sqlContext.sql("select * from people").collect.foreach(println) </code></pre>
33,695,702
How can I add hostnames to a container on the same docker network?
<p>Suppose I have a docker compose file with two containers. Both reference each other in their /etc/hosts file. Container A has a reference for container B and vice versa. And all of this happens automatically. Now I want to add one or more hostnames to B in A's hosts file. How can I go about doing this? Is there a special way I can achieve this in Docker Compose?</p> <p>Example:</p> <p>172.0.10.166 service-b my-custom-hostname</p>
39,707,966
3
0
null
2015-11-13 15:04:04.147 UTC
8
2020-07-28 07:24:17.773 UTC
null
null
null
null
1,204,900
null
1
18
docker|hostname|docker-compose
32,394
<p>Yes. In your compose file, you can specify <a href="https://docs.docker.com/compose/compose-file/#aliases" rel="noreferrer">network aliases</a>.</p> <pre class="lang-yaml prettyprint-override"><code>services: db: networks: default: aliases: - database - postgres </code></pre> <p>In this example, the <code>db</code> service could be reached by other containers on the default network using <code>db</code>, <code>database</code>, or <code>postgres</code>.</p> <p>You can also <a href="https://docs.docker.com/engine/reference/commandline/network_connect/" rel="noreferrer">add aliases to running containers</a> using the <code>docker network connect</code> command with the <code>--alias=</code> option.</p>
20,098,912
Kerberos authentication in Node.js https.get or https.request
<p>I'm trying to write a simple script that requests some data from a tool on an internal network. Here is the code:</p> <pre><code>#!/usr/bin/node var https = require('https'); var fs = require('fs'); var options = { host: '&lt;link&gt;', port: 443, path: '&lt;path&gt;', auth: 'username:password', ca: [fs.readFileSync('../.cert/newca.crt')] }; https.get(options, function(res) { console.log("Got response: " + res.statusCode); res.on('data', function (d) { console.log('BODY: ' + d); }); }).on('error', function(e) { console.log("Got error: " + e.message); }); </code></pre> <p>Now the question is, how can I use a Kerberos ticket to authenticate rather than supplying my credentials in <code>auth:</code> in plain text?</p>
22,166,697
6
0
null
2013-11-20 14:42:19.503 UTC
6
2021-09-16 11:45:22.177 UTC
null
null
null
null
864,413
null
1
18
javascript|node.js|https|kerberos
38,198
<p>In Paul Scheltema's answer, you need to get ticketdata from depth of operating system. You (or a module on behalf of you) must use GSS-API to have ticketdata generated by Active Directory for you. </p> <p>Such mechanism is present in Chrome, but it seems that it's not included in Node.js (only the javascript engine from Chrome), so you may need to add a module, for example:</p> <ul> <li>Passport-Kerberos: <a href="https://www.npmjs.org/package/passport-kerberos" rel="noreferrer">https://www.npmjs.org/package/passport-kerberos</a> and <a href="http://passportjs.org/guide/" rel="noreferrer">http://passportjs.org/guide/</a></li> <li>Kerberos (npm install kerberos)</li> <li>In source code of Node.js at github there's a trace that someone has been using Bones module for that (<a href="https://github.com/joyent/node/search?q=kerberos&amp;ref=cmdform" rel="noreferrer">https://github.com/joyent/node/search?q=kerberos&amp;ref=cmdform</a>). 3 years ago, with DES (this encoding type is very weak and has been deprecated for years)</li> </ul> <p>To install/compile such module you may need to have Visual Studio.</p> <hr> <p>To set up environment, - On all computers you must have tcp and udp enabled on ports 88 (Kerberos) and 53 (dns). - On Windows Server Active Directory must be running (ldap, dns, kdc) - On the page <a href="https://www.npmjs.org/package/passport-kerberos" rel="noreferrer">https://www.npmjs.org/package/passport-kerberos</a> they use term REALM. It's a name of domain, <strong>written uppercase</strong>.</p>
40,291,084
Use reselect selector with parameters
<p>How do I pass additional parameters to combined selectors? I am trying to</p> <p>• Get data</p> <p>• Filter data</p> <p>• Add custom value to my data set / group data by myValue</p> <pre><code>export const allData = state =&gt; state.dataTable export const filterText = state =&gt; state.filter.get('text') export const selectAllData = createSelector( allData, (data) =&gt; data ) export const selectAllDataFiltered = createSelector( [ selectAllData, filterText ], (data, text) =&gt; { return data.filter(item =&gt; { return item.name === text }) } ) export const selectWithValue = createSelector( [ selectAllDataFiltered ], (data, myValue) =&gt; { console.log(myValue) return data } ) let data = selectWithValue(state, 'myValue') </code></pre> <p><code>console.log(myValue)</code> returns <code>undefined</code></p>
40,294,848
6
0
null
2016-10-27 17:44:35.383 UTC
5
2022-07-06 14:39:41.133 UTC
null
null
null
null
4,766,136
null
1
49
javascript|reactjs|ecmascript-6|redux|reselect
68,682
<p>The answer to your questions is detailed in an FAQ here: <a href="https://github.com/reactjs/reselect#q-how-do-i-create-a-selector-that-takes-an-argument" rel="noreferrer">https://github.com/reactjs/reselect#q-how-do-i-create-a-selector-that-takes-an-argument</a></p> <p>In short, reselect doesn't support arbitrary arguments passed to selectors. The recommended approach is, instead of passing an argument, store that same data in your Redux state. </p>
19,010,870
Fat libraries in XCode 5
<p>I've been trying to build a static library and then create a binding project from it in Xamarin. Everything was working fine until iOS 7 hit. I had to grab the latest version of the native library and try and build it in XCode 5, but it's been giving me all kinds of problems. I <em>think</em> it might be related to the build process or possibly some changed setting in XCode 5 (vs. 4) but I'm not sure.</p> <p>I was using <a href="https://github.com/xamarin/monotouch-samples/blob/master/BindingSample/src/binding/XMBindingLibrarySample/RunScript.sh" rel="nofollow noreferrer">this</a> script to build a universal binary which is based of work in this question:</p> <p><a href="https://stackoverflow.com/questions/3520977/build-fat-static-library-device-simulator-using-xcode-and-sdk-4">Build fat static library (device + simulator) using Xcode and SDK 4+</a></p> <p>One thing I did notice is that previous, in the old iOS 6.1 version of my binary (built in XCode 4), my binary was about 24 Mb, now with XCode 5 it's ballooned to almost 50 Mb! Which is leading me to think that there is something wrong with the compiling and linking step.</p> <p>Any ideas? Has anybody else encountered problems with universal binaries in XCode 5 (vs 4)?</p>
19,030,872
2
0
null
2013-09-25 16:53:33.223 UTC
11
2014-07-19 06:02:38.497 UTC
2017-05-23 12:32:49.777 UTC
null
-1
null
1,250,301
null
1
15
iphone|xcode|xamarin|universal-binary
4,890
<p>I'm using the makefile below for my library and it works flawless even with XCode 5 and the iOS7 SDK.</p> <pre><code>XBUILD=/Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild PROJECT_ROOT=. PROJECT=$(PROJECT_ROOT)/GIFLibFrontEnd.xcodeproj TARGET=GIFLibFrontEnd all: libUniversal.a libi386.a: $(XBUILD) -project $(PROJECT) -target $(TARGET) -sdk iphonesimulator -configuration Release clean build -mv $(PROJECT_ROOT)/build/Release-iphonesimulator/lib$(TARGET).a $@ libArmv7.a: $(XBUILD) -project $(PROJECT) -target $(TARGET) -sdk iphoneos -arch armv7 -configuration Release clean build -mv $(PROJECT_ROOT)/build/Release-iphoneos/lib$(TARGET).a $@ libArmv7s.a: $(XBUILD) -project $(PROJECT) -target $(TARGET) -sdk iphoneos -arch armv7s -configuration Release clean build -mv $(PROJECT_ROOT)/build/Release-iphoneos/lib$(TARGET).a $@ libArm64.a: $(XBUILD) -project $(PROJECT) -target $(TARGET) -sdk iphoneos -arch arm64 -configuration Release clean build -mv $(PROJECT_ROOT)/build/Release-iphoneos/lib$(TARGET).a $@ libUniversal.a: libi386.a libArmv7.a libArmv7s.a libArm64.a lipo -create -output lib$(TARGET)Universal.a $^ clean: -rm -f *.a *.dll -rm -rf build </code></pre>
27,242,603
pluralize without count number in rails 4
<p>I am building a blog app. I'd like to be able to pluralize the word "article" if more than one "post" is "published."</p> <p>Like so: Available Articles or Available Article</p> <p>This is what I have....</p> <pre><code> Available &lt;%= pluralize @posts.published, "Article" %&gt;: </code></pre> <p>I've tried</p> <pre><code> Available &lt;%= pluralize @posts.published.count, "Article" %&gt;: </code></pre> <p>and that works...but I don't want the number. It shouldn't read Available 5 Articles....it should have no number.</p>
28,618,377
5
0
null
2014-12-02 05:38:56.8 UTC
3
2018-09-17 14:48:59.49 UTC
2017-08-18 03:12:33.017 UTC
null
184,184
null
3,689,085
null
1
51
ruby-on-rails|ruby-on-rails-4|activerecord|pluralize
14,477
<p>I have been looking for the answer to this myself and wasn't satisfied with any of the existing ones. Here's the tidiest solution I found:</p> <pre><code> Available &lt;%= "Article".pluralize(@posts.published.count) %&gt;: </code></pre> <p>Documentation is <a href="http://api.rubyonrails.org/classes/String.html#method-i-pluralize">here</a>. Relevant bits:</p> <blockquote> <p>Returns the plural form of the word in the string.</p> <pre><code>If the optional parameter count is specified, the singular form will be returned if count == 1. For any other value of count the plural will be returned. 'post'.pluralize # =&gt; "posts" 'apple'.pluralize(1) # =&gt; "apple" 'apple'.pluralize(2) # =&gt; "apples" </code></pre> </blockquote>
43,575,864
How to add a package to python in Visual Studio 2017
<p>I just installed the new VS2017 Preview and imported a Python project. This project has many import statements but VS2017 does show error in some import packages like cv2, socketio, eventlet, eventlet.wsgi. This Python project runs fine, out of VS2017, in my Anaconda environment. Do I need to install OpenCV 2, socketio, etc in Windows? Or is there a solution like pip, anaconda, apt-get, in the VS2017 environment that can automate the installation of unresolved package? I also noticed that it is possible to add Anaconda to VS project created. Can this Anaconda inside VS help to install the missing packages? Regards.</p>
43,652,779
2
0
null
2017-04-23 20:00:09.37 UTC
3
2017-05-25 20:07:32.173 UTC
null
null
null
null
4,435,220
null
1
20
python|visual-studio|opencv|socket.io|anaconda
47,948
<p>You can, however it is not perfect.</p> <p>Firstly you need to bring up the Python Environments menu which can be accessed by going:</p> <blockquote> <p>Tools -> Python -> Python Environments</p> </blockquote> <p>It should bring up a sidebar (depending on how you have VS setup). There should be a dropdown box about half way down with the text "Overview". Click on that and you can select "Packages". This will bring up a textbox under it that will allow you to use standard pip commands to install packages.</p> <p>If you are on Windows though there is one added step for some packages though. As pip does not work well on Windows, due to the fact that the standard Windows package site (<a href="https://pypi.python.org/pypi" rel="noreferrer">PyPI</a>) does not yet have Windows wheels for a lot of common packages.</p> <p>Therefore, you are best off going to <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="noreferrer">Christoph Gohlke's unofficial package site</a> and then downloading the package you need. Once it's downloaded locally just copy and paste the LOCAL address into the textbox under "Packages". It will then install the package and you'll be good to go.</p>
25,490,641
check how many elements are equal in two numpy arrays python
<p>I have two numpy arrays with number (Same length), and I want to count how many elements are equal between those two array (equal = same value and position in array)</p> <pre><code>A = [1, 2, 3, 4] B = [1, 2, 4, 3] </code></pre> <p>then I want the return value to be 2 (just 1&amp;2 are equal in position and value)</p>
25,490,688
2
0
null
2014-08-25 16:49:32.987 UTC
8
2016-10-30 18:11:20.903 UTC
2014-08-25 16:56:10.353 UTC
null
2,225,682
null
1,851,268
null
1
69
python|arrays|numpy
110,198
<p>Using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html" rel="noreferrer"><code>numpy.sum</code></a>:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([1, 2, 3, 4]) &gt;&gt;&gt; b = np.array([1, 2, 4, 3]) &gt;&gt;&gt; np.sum(a == b) 2 &gt;&gt;&gt; (a == b).sum() 2 </code></pre>
27,913,261
Python Storing Data
<p>I have a list in my program. I have a function to append to the list, unfortunately when you close the program the thing you added goes away and the list goes back to the beginning. Is there any way that I can store the data so the user can re-open the program and the list is at its full.</p>
27,913,281
4
0
null
2015-01-13 00:43:11.863 UTC
6
2021-03-12 12:43:40.663 UTC
2015-01-13 00:51:38.45 UTC
null
4,015,623
null
4,064,791
null
1
17
python|storage
57,510
<p>You can make a database and save them, the only way is this. A database with SQLITE or a .txt file. For example:</p> <pre><code>with open("mylist.txt","w") as f: #in write mode f.write("{}".format(mylist)) </code></pre> <p>Your list goes into the <code>format()</code> function. It'll make a .txt file named <code>mylist</code> and will save your list data into it.</p> <p>After that, when you want to access your data again, you can do:</p> <pre><code>with open("mylist.txt") as f: #in read mode, not in write mode, careful rd=f.readlines() print (rd) </code></pre>
40,151,410
IntelliJ highlights Lombok generated methods as “cannot resolve method”
<p>I am using Lombok’s <code>@Data</code> annotation to create the basic functionality of my POJOs. When I try to use these generated methods, IntelliJ highlights these as errors (<code>Cannot resolve method ‘getFoo()’</code>) and seems to be unable to find them. They do however exist, as I am able to run code using these methods without any trouble.</p> <p>I made sure to enable annotation processing, so that shouldn’t cause any problems.</p> <p>How can I get IntelliJ to find the methods and stop wrongly marking them as errors?</p>
40,151,497
2
2
null
2016-10-20 10:08:18.82 UTC
4
2020-01-29 14:20:08.237 UTC
null
null
null
null
7,047,234
null
1
41
java|intellij-idea|lombok
26,945
<p>You will also need the <a href="https://plugins.jetbrains.com/plugin/6317" rel="noreferrer">lombok</a> plugin.</p>
22,163,583
How to wait for page loading when using casperjs?
<p>I am trying to scrape a webpage which has a form with many dropdowns and values in the form are interdependent. At many point I need the code to wait till the refresh of the page complete. Eg after selecting an option from the list, the code should wait till the next list is populated based on this selection. It would be really helpful if someone could give pointers because strangely my code is working only after I gave so much unnecessary logging statements which in-turn created some delay. Any suggestions to improve the code would be very helpful.</p> <pre><code>var casper = require('casper').create({ verbose: true, logLevel: 'debug', userAgent: 'Mozilla/5.0 poi poi poi (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22', pageSettings: {} }); casper.start('http://www.abc.com', function () { console.log("casper started"); this.fill('form[action="http://www.abc.com/forum/member.php"]', { quick_username: "qwe", quick_password: "qwe" }, true); this.capture('screen.png'); }); casper.thenOpen("http://www.abc.com/search/index.php").then(function () { this.click('input[type="checkbox"][name="firstparam"]'); this.click('a#poi'); casper.evaluate(function () { document.getElementsByName("status")[0].value = 1; document.getElementsByName("state")[0].value = 1078; changeState(); //This function is associated with the dropdown ie state and the page reloads at this point. Only after complete refresh the code shoud execute! How can this be achieved? return true; }); this.echo('Inside the first thenOpen' + this.evaluate(function () { return document.search.action; })); }); casper.then(function () { this.capture("poi.png"); console.log('just before injecting jquery'); casper.page.injectJs('./jquery.js'); this.click('input[type="checkbox"][name="or"]'); this.evaluate(function () { $('.boxline .filelist input:checkbox[value=18127]').attr("checked", true); }); this.echo('Just before pressing the add college button' + this.evaluate(function () { return document.search.action; })); this.capture('collegeticked.png'); if (this.exists('input[type="button"][name="niv"]')) { this.echo('button is there'); } else { this.echo('button is not there'); } this.echo("Going to print return value"); this.click('input[type="button"][name="poi"]'); // This click again causes a page refresh. Code should wait at this point for completion. this.echo('Immediately after pressing the add college btn getPresentState()' + this.evaluate(function () { return getPresentState(); })); this.echo('Immediately after pressing add colleg button' + this.evaluate(function () { return document.search.action; })); this.capture('iu.png'); }); casper.then(function () { console.log('just before form submit'); this.click('form[name="search"] input[type="submit"]'); //Again page refresh. Wait. this.echo('Immediately after search btn getPresentState()' + this.evaluate(function () { return getPresentState(); })); this.echo('Immediately after search button-action' + this.evaluate(function () { return document.search.action; })); this.capture("mnf.png"); }); casper.then(function () { casper.page.injectJs('./jquery.js'); this.capture("resultspage.png"); this.echo('Page title is: ' + this.evaluate(function () { return document.title; }), 'INFO'); var a = casper.evaluate(function () { return $('tbody tr td.tdbottom:contains("tye") ').siblings().filter($('td&gt;a').parent()); }); console.log("ARBABU before" + a.length); }); casper.run(); </code></pre>
25,977,861
7
0
null
2014-03-04 05:22:48.63 UTC
6
2017-07-15 09:42:09.537 UTC
null
null
null
null
910,032
null
1
23
javascript|phantomjs|casperjs
52,477
<p>I've been using the waitForSelector 'workaround' mentioned by Arun here: <a href="https://stackoverflow.com/a/22217657/1842033">https://stackoverflow.com/a/22217657/1842033</a></p> <p>It's the best solution I've found; the 'drawback' as it were is that you need to be aware of what element you're expecting to load. I say drawback, personally I don't think I've encountered a situation where I've not had <em>some</em> kind of feedback saying that whatever I'm waiting for has happened</p> <pre><code>this.waitForSelector("{myElement}", function pass () { test.pass("Found {myElement}"); }, function fail () { test.fail("Did not load element {myElement}"); }, 20000 // timeout limit in milliseconds ); </code></pre> <p>Although I'd guess you could use <a href="http://docs.casperjs.org/en/latest/modules/casper.html#waitforresource" rel="nofollow noreferrer">waitForResource()</a> or something like that if you didn't have visual feedback.</p>
23,640,594
Reading multiple files and calculating mean based on user input
<p>I am trying to write a function in R which takes 3 inputs:</p> <ol> <li>Directory</li> <li>pollutant</li> <li>id</li> </ol> <p>I have a directory on my computer full of CSV's files i.e. over 300. What this function would do is shown in the below prototype:</p> <pre><code>pollutantmean &lt;- function(directory, pollutant, id = 1:332) { ## 'directory' is a character vector of length 1 indicating ## the location of the CSV files ## 'pollutant' is a character vector of length 1 indicating ## the name of the pollutant for which we will calculate the ## mean; either "sulfate" or "nitrate". ## 'id' is an integer vector indicating the monitor ID numbers ## to be used ## Return the mean of the pollutant across all monitors list ## in the 'id' vector (ignoring NA values) } </code></pre> <p>An example output of this function is shown here:</p> <pre><code>source("pollutantmean.R") pollutantmean("specdata", "sulfate", 1:10) ## [1] 4.064 pollutantmean("specdata", "nitrate", 70:72) ## [1] 1.706 pollutantmean("specdata", "nitrate", 23) ## [1] 1.281 </code></pre> <p>I can read the whole thing in one go by:</p> <pre><code>path = "C:/Users/Sean/Documents/R Projects/Data/specdata" fileList = list.files(path=path,pattern="\\.csv$",full.names=T) all.files.data = lapply(fileList,read.csv,header=TRUE) DATA = do.call("rbind",all.files.data) </code></pre> <p>My issue are:</p> <ol> <li>User enters id either atomic or in a range e.g. suppose user enters 1 but the file name is 001.csv or what if user enters a range 1:10 then file names are 001.csv ... 010.csv</li> <li>Column is enetered by user i.e. "sulfate" or "nitrate" which he/she is interested in getting the mean of...There are alot of missing values in these columns (which i need to omit from the column before calculating the mean.</li> </ol> <p>The whole data from all the files look like this :</p> <pre><code>summary(DATA) Date sulfate nitrate ID 2004-01-01: 250 Min. : 0.0 Min. : 0.0 Min. : 1.0 2004-01-02: 250 1st Qu.: 1.3 1st Qu.: 0.4 1st Qu.: 79.0 2004-01-03: 250 Median : 2.4 Median : 0.8 Median :168.0 2004-01-04: 250 Mean : 3.2 Mean : 1.7 Mean :164.5 2004-01-05: 250 3rd Qu.: 4.0 3rd Qu.: 2.0 3rd Qu.:247.0 2004-01-06: 250 Max. :35.9 Max. :53.9 Max. :332.0 (Other) :770587 NA's :653304 NA's :657738 </code></pre> <p>Any idea how to formulate this would be highly appreciated...</p> <p>Cheers</p>
23,653,407
8
1
null
2014-05-13 20:04:45.77 UTC
6
2017-10-12 20:34:13.8 UTC
2015-11-13 16:35:54.913 UTC
null
2,573,061
null
3,107,664
null
1
1
r|function|subset|mean|missing-data
48,719
<p>That's the way I fixed it:</p> <pre><code>pollutantmean &lt;- function(directory, pollutant, id = 1:332) { #set the path path = directory #get the file List in that directory fileList = list.files(path) #extract the file names and store as numeric for comparison file.names = as.numeric(sub("\\.csv$","",fileList)) #select files to be imported based on the user input or default selected.files = fileList[match(id,file.names)] #import data Data = lapply(file.path(path,selected.files),read.csv) #convert into data frame Data = do.call(rbind.data.frame,Data) #calculate mean mean(Data[,pollutant],na.rm=TRUE) } </code></pre> <p>The last question is that my function should call "specdata" (the directory name where all the csv's are located) as the directory, is there a directory type object in r?</p> <p>suppose i call the function as:</p> <pre><code>pollutantmean(specdata, "niterate", 1:10) </code></pre> <p>It should get the path of specdata directory which is on my working directory... how can I do that?</p>
23,631,628
LAST_NUMBER on oracle sequence
<p>I have a sequence SEQ_PAGE_ID </p> <pre><code>SEQUENCE_NAME INCREMENT_BY CACHE_SIZE LAST_NUMBER ------------------------------------------------------- SEQ_PAGE_ID 1 20 2222292456 </code></pre> <p>To change the CACHE_SIZE, I used below script,</p> <p><code>alter sequence SEQ_PAGE_ID CACHE 5000;</code></p> <p>When I checked the query,</p> <pre><code>select ... from user_sequences where sequence_name = 'SEQ_PAGE_ID'; SEQUENCE_NAME INCREMENT_BY CACHE_SIZE LAST_NUMBER ------------------------------------------------------- SEQ_PAGE_ID 1 5000 2222292447 </code></pre> <p>The <code>LAST_NUMBER</code> changed from <code>2222292456</code> to <code>2222292447</code>. Is this happened due to the alter script?</p>
23,632,947
3
1
null
2014-05-13 12:43:16.553 UTC
4
2022-02-08 16:42:12.423 UTC
null
null
null
null
930,544
null
1
12
oracle
83,905
<p>This is normal, yes. From the <a href="http://docs.oracle.com/cd/E18283_01/server.112/e17110/statviews_2062.htm">documentation for the <code>all_sequences</code> data dictionary view</a>, <code>last_number</code> is:</p> <blockquote> <p>Last sequence number written to disk. If a sequence uses caching, the number written to disk is the last number placed in the sequence cache. This number is likely to be greater than the last sequence number that was used.</p> </blockquote> <p>This can be recreated with a fresh sequence:</p> <pre><code>SQL&gt; create sequence SEQ_PAGE_ID start with 2222292436 increment by 1 cache 20; sequence SEQ_PAGE_ID created. SQL&gt; select sequence_name, increment_by, cache_size, last_number 2 from user_sequences where sequence_name = 'SEQ_PAGE_ID'; SEQUENCE_NAME INCREMENT_BY CACHE_SIZE LAST_NUMBER ------------------------------ ------------ ---------- ----------- SEQ_PAGE_ID 1 20 2222292436 SQL&gt; select SEQ_PAGE_ID.nextval from dual; NEXTVAL ---------- 2222292436 SQL&gt; select sequence_name, increment_by, cache_size, last_number 2 from user_sequences where sequence_name = 'SEQ_PAGE_ID'; SEQUENCE_NAME INCREMENT_BY CACHE_SIZE LAST_NUMBER ------------------------------ ------------ ---------- ----------- SEQ_PAGE_ID 1 20 2222292456 </code></pre> <p>The <code>last_number</code> jumped up by the cache size, which is normal.</p> <pre><code>SQL&gt; alter sequence SEQ_PAGE_ID CACHE 5000; sequence SEQ_PAGE_ID altered. SQL&gt; select sequence_name, increment_by, cache_size, last_number 2 from user_sequences where sequence_name = 'SEQ_PAGE_ID'; SEQUENCE_NAME INCREMENT_BY CACHE_SIZE LAST_NUMBER ------------------------------ ------------ ---------- ----------- SEQ_PAGE_ID 1 5000 2222292437 </code></pre> <p>The <code>last_number</code> goes down, but now reflects the actual last sequence number generated. The DDL has (apparently) caused the data written to disk to be updated to reflect what happens to be the current value, rather than the top of the cache - either the old 20-value cache or the new 5000-value cache. In your case you got <code>2222292447</code>, which just means you were ten values further through the cache than I was when I ran the <code>alter</code>.</p> <p>The value saved to disk is largely there so that if the database crashes it knows where to pick up from. On restart the sequence will start generating numbers from the recorded <code>last_number</code>. During normal running it doesn't need to refer back to that, it just updates the value on disk when new values are cached. This prevents sequence numbers being reissued after a crash, without needing to do expensive (slow) locking to maintain the value in real time - which is what the cache is there to avoid, after all.</p> <p>There would only be a problem if the <code>last_value</code> was lower than an actual generated sequence, but that can't happen. (Well, unless the sequence is set to cycle).</p> <pre><code>SQL&gt; select SEQ_PAGE_ID.nextval from dual; NEXTVAL ---------- 2222292437 </code></pre> <p>The next sequence number generated follows on from the last one before the cache size change; it hasn't reused an old value as you might have been worried about from the dictionary value.</p> <pre><code>SQL&gt; select sequence_name, increment_by, cache_size, last_number 2 from user_sequences where sequence_name = 'SEQ_PAGE_ID'; SEQUENCE_NAME INCREMENT_BY CACHE_SIZE LAST_NUMBER ------------------------------ ------------ ---------- ----------- SEQ_PAGE_ID 1 5000 2222297437 </code></pre> <p>The <code>last_number</code> now shows the previous stored value incremented by the cache size of 5000. What is in the data dictionary now won't change again until we've consumed all 5000 values form the cache, or something happens elsewhere that affects it - the database being bounced, the sequence being altered again, etc.</p>
23,689,964
javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]
<p>I'm new to ldap and I was trying what I thought was a trivial example to test the spring ldap module with an ldap instance that someone had already setup for testing.</p> <p>Details about the ldap instance that I am using can be found here: <a href="http://blog.stuartlewis.com/2008/07/07/test-ldap-service/comment-page-3/" rel="noreferrer">http://blog.stuartlewis.com/2008/07/07/test-ldap-service/comment-page-3/</a></p> <p>I've used an ldap browser/admin tool (Softerra LDAP Admin) and I can access the directory without any issues.</p> <p>When I try it using java and spring-ldap (2.0.1) I get the Authentication Exception mentioned above. Before setting up my own ldap instance to try and troubleshoot this further I wanted to check here in case someone with more experience could point out something obvious that I missed. </p> <p>Below is the code I am using:</p> <pre><code>import org.springframework.ldap.core.LdapTemplate; import org.springframework.ldap.core.support.LdapContextSource; import java.util.List; public class LdapTest { public List&lt;String&gt; getListing() { LdapTemplate template = getTemplate(); List&lt;String&gt; children = template.list("dc=testathon,dc=net"); return children; } private LdapTemplate getTemplate(){ LdapContextSource contextSource = new LdapContextSource(); contextSource.setUrl("ldap://ldap.testathon.net:389"); contextSource.setUserDn("cn=john"); contextSource.setPassword("john"); try { contextSource.afterPropertiesSet(); } catch (Exception ex) { ex.printStackTrace(); } LdapTemplate template = new LdapTemplate(); template.setContextSource(contextSource); return template; } public static void main(String[] args){ LdapTest sClient = new LdapTest(); List&lt;String&gt; children = sClient.getListing(); for (String child :children) { System.out.println(child); } } } </code></pre> <p>Stack trace:</p> <pre><code>Exception in thread "main" org.springframework.ldap.AuthenticationException: [LDAP: error code 49 - Invalid Credentials]; nested exception is javax.naming.AuthenticationException: [LDAP: error code 49 - Invalid Credentials] at org.springframework.ldap.support.LdapUtils.convertLdapException(LdapUtils.java:191) at org.springframework.ldap.core.support.AbstractContextSource.createContext(AbstractContextSource.java:356) at org.springframework.ldap.core.support.AbstractContextSource.doGetContext(AbstractContextSource.java:140) </code></pre>
23,701,042
1
1
null
2014-05-15 22:47:47.96 UTC
3
2018-06-11 10:20:52.647 UTC
null
null
null
null
979,467
null
1
12
java|spring-ldap
43,992
<p>It turns out I just needed to include everything in the distinguished name(including the organization unit). Using </p> <pre><code>contextSource.setBase(...); </code></pre> <p>for some reason did not work. After making that correction all was fine.</p> <pre><code>contextSource.setUserDn("cn=john,ou=Users,dc=testathon,dc=net"); </code></pre>
25,880,767
Chart.js number format
<p>I went over the <a href="http://www.chartjs.org/docs/" rel="noreferrer">Chart.js documentation</a> and did not find anything on number formatting ie) 1,000.02 from number format "#,###.00"</p> <p>I also did some basic tests and it seems charts do not accept non-numeric text for its values</p> <p>Has anyone found a way to get values formatted to have thousands separator and a fixed number of decimal places? I would like to have the axis values and values in the chart formatted.</p>
26,567,557
7
2
null
2014-09-17 01:10:54.857 UTC
4
2022-04-08 07:58:21.757 UTC
2014-11-26 12:57:24.317 UTC
null
569,101
null
1,776,090
null
1
39
javascript|charts|formatting|number-formatting|chart.js
75,305
<p>There is no built-in functionality for number formatting in Javascript. I found the easiest solution to be the <a href="http://www.mredkj.com/javascript/numberFormat.html" rel="noreferrer">addCommas function on this page</a>.</p> <p>Then you just have to modify your <code>tooltipTemplate</code> parameter line from your <code>Chart.defaults.global</code> to something like this:</p> <pre><code>tooltipTemplate: "&lt;%= addCommas(value) %&gt;" </code></pre> <p>Charts.js will take care of the rest.</p> <p>Here's the <code>addCommas</code> function:</p> <pre><code>function addCommas(nStr) { nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length &gt; 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } </code></pre>
29,738,787
Filling water animation
<p>I am trying to get a wipe up animation to make a circle look like <strong>it's filling with water</strong>. I've run into two errors, and haven't been able to even tackle the 3rd one:</p> <ol> <li>It fills up the wrong way</li> <li><strike>It resets to empty (black) after it has filled</strike> *</li> <li>For now, I am using the <code>&lt;img&gt;</code> tags, but I would like to move this effect to <code>body { background-image: }</code> and need some direction on how to do this.</li> </ol> <p><a href="http://jsfiddle.net/um0rnL56/1/" rel="noreferrer">What I have tried so far:</a> </p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#banner { width: 300px; height: 300px; position: relative; } #banner div { position: absolute; } #banner div:nth-child(2) { -webkit-animation: wipe 6s; -webkit-animation-delay: 0s; -webkit-animation-direction: up; -webkit-mask-size: 300px 3000px; -webkit-mask-position: 300px 300px; -webkit-mask-image: -webkit-gradient(linear, left bottom, left top, color-stop(0.00, rgba(0, 0, 0, 1)), color-stop(0.25, rgba(0, 0, 0, 1)), color-stop(0.27, rgba(0, 0, 0, 0)), color-stop(0.80, rgba(0, 0, 0, 0)), color-stop(1.00, rgba(0, 0, 0, 0))); } @-webkit-keyframes wipe { 0% { -webkit-mask-position: 0 0; } 100% { -webkit-mask-position: 300px 300px; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="banner"&gt; &lt;div&gt; &lt;img src="http://i.imgur.com/vklf6kK.png" /&gt; &lt;/div&gt; &lt;div&gt; &lt;img src="http://i.imgur.com/uszeRpk.png" /&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p>Giving it a default mask position as <a href="https://stackoverflow.com/users/473016/anpsmn">@anpsmn</a> suggested, doesn't reset it to black anymore.</p>
29,739,227
6
1
null
2015-04-20 03:17:32.59 UTC
28
2020-07-03 09:51:29.747 UTC
2017-05-23 11:33:17.723 UTC
null
-1
null
1,509,580
null
1
69
css|svg|css-animations|css-shapes
31,219
<p>This can be achieved with a single div and a <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/::before" rel="noreferrer"><code>::before</code> pseudo element:</a></p> <ul> <li><p>The <code>#banner</code> is given <code>border-radius: 50%</code> to create a circle and <code>overflow: hidden</code> to clip its children inside it</p> </li> <li><p>The <code>::before</code> pseudo element is animated to 100% height and the animation is paused at 100% using <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode" rel="noreferrer">the <code>forwards</code> value</a>. It begins at the bottom with the use of <code>bottom: 0</code></p> </li> <li><p>The background images would be applied in place of the black and blue backgrounds on <code>#banner</code> and <code>#banner::before</code></p> </li> </ul> <p><strong>Compatibility:</strong> IE10+ and all modern browsers. The <code>-webkit-</code> prefixed property is most likely no longer necessary for your keyframe animations. <a href="http://caniuse.com/#feat=css-animation" rel="noreferrer">Check the browser compatibility chart over here on caniuse.com</a></p> <h2>Working Example</h2> <p>I have added the <code>cubic-bezier(.2,.6,.8,.4)</code> <a href="https://stackoverflow.com/a/29740828/2930477">which is explained in @ChrisSpittles answer</a>. It provides a neat effect!</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#banner { width: 300px; height: 300px; position: relative; background: #000; border-radius: 50%; overflow: hidden; } #banner::before { content: ''; position: absolute; background: #04ACFF; width: 100%; bottom: 0; animation: wipe 5s cubic-bezier(.2,.6,.8,.4) forwards; } @keyframes wipe { 0% { height: 0; } 100% { height: 100%; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="banner"&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
32,504,778
How to import huge CSV file with 200,00 rows to MySQL (asynchronous and fast)?
<p>I have to write a PHP script that will import data from a given CSV file into MySQL database. The given CSV file can contain up to 200,000 rows. I tried the following but problems arise : </p> <ol> <li>LOAD DATA LOCAL INFILE : I cannot use LOAD DATA LOCAL INFILE statement because I wanted to do some validations first BEFORE uploading the rows, also, our DB admin doesn't want me to use that statement and I don't know why.</li> <li>FOR LOOP : Inserting line by line inside FOR loop will take too much time resulting to Connection Timeout.</li> </ol> <p>Now, I am thinking of a solution by splitting the CSV file into smaller chunks, then inserting them asynchronously. I am already done with the splitting of CSV, but I currently have no idea how to asynchronously insert into my database for quick and safe way. But I heard that I will be using Ajax here.</p> <p>Any solution you can recommend? Thanks a lot in advance!</p>
32,546,417
4
4
null
2015-09-10 14:32:57.273 UTC
10
2016-04-27 12:45:58.947 UTC
2015-09-10 14:56:09.483 UTC
null
5,295,021
null
5,295,021
null
1
8
php|mysql|ajax|csv|asynchronous
28,280
<p>Thanks to everyone who gave answers to this question. I have discovered a solution! Just wanted to share it, in case someone needs to create a PHP script that will import a huge CSV file into MySQL database (asynchronously and fast!) I have tested my code with 400,000 rows and the importing is done in seconds. I believe it would work with larger files, you just have to modify maximum upload file size.</p> <p>In this example, I will be importing a CSV file that contains two columns (name, contact_number) into a MySQL DB that contains the same columns.</p> <p>Your CSV file should look like this : </p> <p>Ana, 0906123489</p> <p>John, 0908989199</p> <p>Peter, 0908298392</p> <p>...</p> <p>...</p> <p>So, here's the solution.</p> <p>First, create your table</p> <pre><code>CREATE TABLE `testdb`.`table_test` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(100) NOT NULL , `contact_number` VARCHAR(100) NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB; </code></pre> <p>Second, I have 4 PHP files. All you have to do is place this into a single folder. PHP files are as follows : </p> <p><strong>index.php</strong></p> <pre><code>&lt;form action="upload.php" method="post" enctype="multipart/form-data"&gt; &lt;input type="file" name="csv" value="" /&gt; &lt;input type="submit" name="submit" value="Save" /&gt;&lt;/form&gt; </code></pre> <p><strong>connect.php</strong></p> <pre><code>&lt;?php //modify your connections here $servername = "localhost"; $username = "root"; $password = ""; $dbname = "testDB"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } ?&gt; </code></pre> <p><strong>senddata.php</strong></p> <pre><code>&lt;?php include('connect.php'); $data = $_POST['file']; $handle = fopen($data, "r"); $test = file_get_contents($data); if ($handle) { $counter = 0; //instead of executing query one by one, //let us prepare 1 SQL query that will insert all values from the batch $sql ="INSERT INTO table_test(name,contact_number) VALUES "; while (($line = fgets($handle)) !== false) { $sql .= "($line),"; $counter++; } $sql = substr($sql, 0, strlen($sql) - 1); if ($conn-&gt;query($sql) === TRUE) { } else { } fclose($handle); } else { } //unlink CSV file once already imported to DB to clear directory unlink($data); ?&gt; </code></pre> <p><strong>upload.php</strong></p> <pre><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.1/jquery.js"&gt;&lt;/script&gt; &lt;script&gt; //Declaration of function that will insert data into database function senddata(filename){ var file = filename; $.ajax({ type: "POST", url: "senddata.php", data: {file}, async: true, success: function(html){ $("#result").html(html); } }) } &lt;/script&gt; &lt;?php $csv = array(); $batchsize = 1000; //split huge CSV file by 1,000, you can modify this based on your needs if($_FILES['csv']['error'] == 0){ $name = $_FILES['csv']['name']; $ext = strtolower(end(explode('.', $_FILES['csv']['name']))); $tmpName = $_FILES['csv']['tmp_name']; if($ext === 'csv'){ //check if uploaded file is of CSV format if(($handle = fopen($tmpName, 'r')) !== FALSE) { set_time_limit(0); $row = 0; while(($data = fgetcsv($handle)) !== FALSE) { $col_count = count($data); //splitting of CSV file : if ($row % $batchsize == 0): $file = fopen("minpoints$row.csv","w"); endif; $csv[$row]['col1'] = $data[0]; $csv[$row]['col2'] = $data[1]; $min = $data[0]; $points = $data[1]; $json = "'$min', '$points'"; fwrite($file,$json.PHP_EOL); //sending the splitted CSV files, batch by batch... if ($row % $batchsize == 0): echo "&lt;script&gt; senddata('minpoints$row.csv'); &lt;/script&gt;"; endif; $row++; } fclose($file); fclose($handle); } } else { echo "Only CSV files are allowed."; } //alert once done. echo "&lt;script&gt; alert('CSV imported!') &lt;/script&gt;"; } ?&gt; </code></pre> <p>That's it! You already have a pure PHP script that can import multiple number of rows in seconds! :) (Thanks to my partner who taught and gave me an idea on how to use ajax)</p>
34,551,560
Can a PNG image contain multiple pages?
<p>On OSX I converted a multi-page PDF file to PNG and (somehow) it created a multi-page PNG file.</p> <p><a href="https://i.stack.imgur.com/3LLYk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3LLYk.png" alt="enter image description here"></a></p> <p>Is there an extension to the PNG format that allows this? Or is this not something I can validly create?</p> <p>~~~~</p> <p>To clarify, this is a PNG file, per the builtin <code>file</code> command and the <code>identify</code> command from imagemagick.</p> <pre><code>$ file algorithms-combined-print.png algorithms-combined-print.png: PNG image data, 1275 x 1650, 8-bit/color RGBA, non-interlaced $ identify algorithms-combined-print.png algorithms-combined-print.png PNG 1275x1650 1275x1650+0+0 8-bit sRGB 3.537MB 0.000u 0:00.000 </code></pre> <p>And here is a pastebin of the command <code>identify -verbose algorithms-combined-print.png</code>: <a href="http://pastebin.com/hw1yuRKa" rel="noreferrer">http://pastebin.com/hw1yuRKa</a></p> <p>What is notable from that output is that the pixel count is <code>Number pixels: 2.104M</code> which corresponds to one page. However, the file size is 3.537MB, which is clearly sufficient to hold all the pages.</p> <p>Per request, here is the output of <code>pngcheck</code>: <a href="http://pastebin.com/aCRMEd9L" rel="noreferrer">http://pastebin.com/aCRMEd9L</a></p>
34,556,162
1
4
null
2015-12-31 21:02:02.467 UTC
1
2021-05-06 10:51:41.337 UTC
2016-01-02 08:33:57.517 UTC
null
300,224
null
300,224
null
1
28
macos|png
19,012
<p>PNG does not support &quot;multipage&quot; images.</p> <p><a href="http://www.libpng.org/pub/mng/" rel="nofollow noreferrer">MNG</a> is a PNG variant that supports multiple images - mostly for animations, but it's not a real PNG image (diffent signature/header), and has never become popular.</p> <p><a href="https://en.wikipedia.org/wiki/APNG" rel="nofollow noreferrer">APNG</a> is a similar attempt, but more focused on animations - it's more popular and alive, though it's less official - it's also PNG compatible (a standard PNG viewer, unaware of APNG, will display it as a single PNG image).</p> <p>Another possible explanation is that your image is actually a TIFF image with a wrong <code>.png</code> extension, and the viewer ignores it.</p> <p>The only way to know for sure is to look inside the image file itself (at least to the first bytes)</p> <p>Update: given the pngcheck output, it seems to be a APNG file.</p>
39,623,889
Is there any way to print **kwargs in Python
<p>I am just curious about <code>**kwargs</code>. I am just started learning it, So while going through all the question on stackoverflow and video tutorials I notice we can do like this </p> <pre><code>def print_dict(**kwargs): print(kwargs) print_dict(x=1,y=2,z=3) </code></pre> <p>Which gives output as :<code>{'y': 2, 'x': 1, 'z': 3}</code> So I figures why not do the reverse and print the like <code>x=1,y=2,z=3</code></p> <p>So I tried this:</p> <pre><code>mydict = {'x':1,'y':2,'z':3} print(**mydict) </code></pre> <p>But I got an error like : <code>TypeError: 'z' is an invalid keyword argument for this function</code>(sometimes it shows 'y' is an invalid keyword).</p> <p>I also tried like assign it to the variable and then print it but again i got an error (<code>SyntaxError: invalid syntax</code>):</p> <pre><code>mydict = {'x':1,'y':2,'z':3} var = **mydict print(var) </code></pre> <p>See this is working:</p> <pre><code>def print_dict(**this): print(this) mydict = {'x':1,'y':2,'z':3} print_dict(**mydict) </code></pre> <p>But instead of <code>print(this)</code> if i do <code>print(**this)</code> it gives the error.</p> <p>As we can print <code>*arg</code> as I try this code:</p> <pre><code>def num(*tuple_num): print(tuple_num) print(*tuple_num) num(1,2,3,4) </code></pre> <p>It run perfectly and gives output as:</p> <pre><code>(1, 2, 3, 4) 1 2 3 4 </code></pre> <p>So I want to know is there any possible solution/way to print <code>**kwargs</code> ?</p>
39,623,954
4
1
null
2016-09-21 18:23:04.687 UTC
6
2021-08-11 19:37:40.593 UTC
2016-09-21 20:20:35.06 UTC
null
100,297
null
6,742,808
null
1
35
python
38,868
<p>The syntax <code>callable(**dictionary)</code> <em>applies</em> the dictionary as if you used separate keyword arguments.</p> <p>So your example:</p> <pre><code>mydict = {'x':1,'y':2,'z':3} print(**mydict) </code></pre> <p>Is internally translated to:</p> <pre><code>print(x=1, y=2, z=3) </code></pre> <p>where the exact ordering depends on the current random hash seed. Since <code>print()</code> doesn't support those keyword arguments the call fails.</p> <p>The other <code>print()</code> call succeeds, because you passed in the values as separate <em>positional</em> arguments:</p> <pre><code>tuple_num = (1, 2, 3, 4) print(*tuple_num) </code></pre> <p>is effectively the same as:</p> <pre><code>print(1, 2, 3, 4) </code></pre> <p>and the <code>print()</code> function supports separate arguments by writing them out one by one with the <code>sep</code> value in between (which is a space by default).</p> <p>The <code>**dictionary</code> is not valid syntax outside of a call. Since <code>callable(**dictionary)</code> is part of the call syntax, and not an object, there is <em>nothing to print</em>.</p> <p>At most, you can <em>format</em> the dictionary to look like the call:</p> <pre><code>print(', '.join(['{}={!r}'.format(k, v) for k, v in mydict.items()])) </code></pre>
39,656,433
How to download outlook attachment from Python Script?
<p>I need to download incoming attachment without past attachment from mail using Python Script.</p> <p>For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments.</p> <p>Please anyone help me to download attachment using python script or java.</p>
39,872,935
4
2
null
2016-09-23 08:42:59.03 UTC
6
2022-03-10 00:07:51.26 UTC
2020-04-02 15:12:09.983 UTC
null
8,424,404
null
5,693,776
null
1
12
python|email|outlook
62,040
<pre><code>import email import imaplib import os class FetchEmail(): connection = None error = None mail_server=&quot;host_name&quot; username=&quot;outlook_username&quot; password=&quot;password&quot; self.save_attachment(self,msg,download_folder) def __init__(self, mail_server, username, password): self.connection = imaplib.IMAP4_SSL(mail_server) self.connection.login(username, password) self.connection.select(readonly=False) # so we can mark mails as read def close_connection(self): &quot;&quot;&quot; Close the connection to the IMAP server &quot;&quot;&quot; self.connection.close() def save_attachment(self, msg, download_folder=&quot;/tmp&quot;): &quot;&quot;&quot; Given a message, save its attachments to the specified download folder (default is /tmp) return: file path to attachment &quot;&quot;&quot; att_path = &quot;No attachment found.&quot; for part in msg.walk(): if part.get_content_maintype() == 'multipart': continue if part.get('Content-Disposition') is None: continue filename = part.get_filename() att_path = os.path.join(download_folder, filename) if not os.path.isfile(att_path): fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() return att_path def fetch_unread_messages(self): &quot;&quot;&quot; Retrieve unread messages &quot;&quot;&quot; emails = [] (result, messages) = self.connection.search(None, 'UnSeen') if result == &quot;OK&quot;: for message in messages[0].split(' '): try: ret, data = self.connection.fetch(message,'(RFC822)') except: print &quot;No new emails to read.&quot; self.close_connection() exit() msg = email.message_from_string(data[0][1]) if isinstance(msg, str) == False: emails.append(msg) response, data = self.connection.store(message, '+FLAGS','\\Seen') return emails self.error = &quot;Failed to retrieve emails.&quot; return emails </code></pre> <p>Above code works for me to download attachment. Hope this really helpful for any one.</p>
26,609,922
MAVEN_HOME, MVN_HOME or M2_HOME
<p>What's the correct Maven environment variable name: <code>MAVEN_HOME</code>, <code>MVN_HOME</code> or <code>M2_HOME</code>? </p> <p>I've found some details about <code>MAVEN_HOME</code> and <code>M2_HOME</code> <a href="https://stackoverflow.com/questions/17136324/what-is-the-difference-between-m2-home-and-maven-home">here</a>. But I also have seen <code>MVN_HOME</code> around.</p>
26,610,326
8
1
null
2014-10-28 13:42:44.107 UTC
24
2022-08-30 18:53:54.373 UTC
2017-07-27 08:18:30.043 UTC
null
1,426,227
null
1,426,227
null
1
103
java|maven|maven-2|maven-3
233,360
<p>I've personally never found it useful to set <code>M2_HOME</code>.</p> <p>What counts is your $PATH environment. Hijacking part of the answer from Danix, all you need is:</p> <pre><code>export PATH=/Users/xxx/sdk/apache-maven-3.0.5/bin:$PATH </code></pre> <p>The <code>mvn</code> script computes <code>M2_HOME</code> for you anyway for what it's worth.</p>
7,395,216
How to make image button
<p>I was wondering how could I do this. I know I can use the button component but it has the little gray stuff around it when I give it a image. With image button how could I show another image for the hover effect</p>
7,395,315
4
2
null
2011-09-12 23:30:28.27 UTC
1
2020-03-30 08:11:43.223 UTC
2011-09-12 23:37:09.83 UTC
null
511,438
null
894,291
null
1
13
c#|winforms
74,868
<p>You want to create a button with no border but displays different images when the user hovers over it with the mouse? Here's how you can do it:</p> <ol> <li><p>Add an <code>ImageList</code> control to your form at add two images, one for the button's normal appearance and one for when the mouse is hovering over.</p></li> <li><p>Add your button and set the following properties:<br> <code>FlatStyle</code> = Flat<br> <code>FlatAppearance.BorderColor</code> (and maybe <code>MouseOverBackColor</code> &amp; <code>MouseDownBackColor</code>) to your form's background color<br> <code>ImageList</code> = the ImageList you added to the form<br> <code>ImageIndex</code> to the index value of your normal image</p></li> </ol> <p>Code the MouseHover and MouseLeave events for the button like this:</p> <pre><code>// ImageList index value for the hover image. private void button1_MouseHover(object sender, EventArgs e) =&gt; button1.ImageIndex = 1; // ImageList index value for the normal image. private void button1_MouseLeave(object sender, EventArgs e) =&gt; button1.ImageIndex = 0; </code></pre> <p>I believe that will give you the visual effect you're looking for.</p>
23,965,911
nodejs express middleware function return value
<p>I'm using NodeJS and Express, I have the following route and the middleware function isMobile. If I don't use return next(); in the isMobile function, the app gets stuck because NodeJS does not move over to the next function. </p> <p>But I need the isMobile function to return a value so I can process accordingly in the app.get. Any ideas?</p> <pre><code>app.get('/', isMobile, function(req, res){ // do something based on isMobile return value }); function isMobile(req, res, next) { var MobileDetect = require('mobile-detect'); md = new MobileDetect(req.headers['user-agent']); //return md.phone(); // need this value back return next(); } </code></pre> <p>Thanks.</p>
23,965,964
1
2
null
2014-05-31 02:47:26.407 UTC
10
2020-05-23 16:49:14.217 UTC
2019-09-19 11:02:13.843 UTC
null
1,940,895
null
3,658,423
null
1
28
node.js|express
29,226
<p>You have a couple of choices:</p> <ol> <li><p>Attach the value to the <code>req</code> object:</p> <pre><code>app.get('/', isMobile, function(req, res){ // Now in here req.phone is md.phone. You can use it: req.phone.makePrankCall(); }); function isMobile(req, res, next) { var MobileDetect = require('mobile-detect'); md = new MobileDetect(req.headers['user-agent']); req.phone = md.phone(); next();// No need to return anything. } </code></pre> <p>This is how many of express/connect middlewares pass values. Like bodyParser which attaches body property to request object, or session middleware which attaches session property to request object.</p></li> </ol> <p>Though note that you have to be careful that no other library uses that property, so there's no conflicts.</p> <ol start="2"> <li><p>Don't make it a middleware, just use the function directly. If it's not asynchronous like above, and not gonna be used globally for all routes(not gonna have something like this: <code>app.use(isMobile)</code>), this also a good solution:</p> <pre><code>app.get('/', function(req, res){ var phone = isMobile(req); phone.makePrankCall(); }); function isMobile(req) { var MobileDetect = require('mobile-detect'); md = new MobileDetect(req.headers['user-agent']); return md.phone(); } </code></pre></li> </ol> <p>If it's expensive to compute, and you might use it in more than one middleware you can cache it with a WeakMap(<a href="https://github.com/danielnaab/weakmap-memoize/blob/master/index.js" rel="noreferrer">or use a module that does it for you</a>):</p> <pre><code> app.get('/', function(req, res){ var phone = isMobile(req); phone.makePrankCall(); }); var cache = new WeakMap() function isMobile(req) { var MobileDetect = require('mobile-detect'); result = cache.get(req); if (result) { return result; } else { md = new MobileDetect(req.headers['user-agent']).phone(); cache.set(req, md); return md; } } </code></pre>
7,744,454
How can I implement multiple URL parameters in a Tornado route?
<p>I'm trying to figure out how to implement a URL with up to 3 (optional) url parameters.</p> <p>I figured out how to do this in ASP.NET MVC 3, but the constraints of the current project eliminated it. So, here's what I'm looking for:</p> <p><code>base/{param1}/{param2}/{param3}</code> where param2 and param3 are optional. Is this simply a regex pattern in the <code>handlers</code> section?</p>
7,759,671
1
0
null
2011-10-12 18:04:38.94 UTC
8
2012-01-10 01:42:59.633 UTC
null
null
null
null
251,174
null
1
14
python|routing|tornado
15,639
<p>I'm not sure if there is a <i>nice</i> way to do it, but this should work:</p> <pre><code>import tornado.web import tornado.httpserver class TestParamsHandler(tornado.web.RequestHandler): def get(self, param1, param2, param3): param2 = param2 if param2 else 'default2' param3 = param3 if param3 else 'default3' self.write( { 'param1': param1, 'param2': param2, 'param3': param3 } ) # My initial answer is above, but I think the following is better. class TestParamsHandler2(tornado.web.RequestHandler): def get(self, **params): self.write(params) application = tornado.web.Application([ (r"/test1/(?P&lt;param1&gt;[^\/]+)/?(?P&lt;param2&gt;[^\/]+)?/?(?P&lt;param3&gt;[^\/]+)?", TestParamsHandler), (r"/test2/(?P&lt;param1&gt;[^\/]+)/?(?P&lt;param2&gt;[^\/]+)?/?(?P&lt;param3&gt;[^\/]+)?", TestParamsHandler2) ]) http_server = tornado.httpserver.HTTPServer(application) http_server.listen(8080) tornado.ioloop.IOLoop.instance().start() </code></pre>
21,709,095
How to disable "This Connection is Untrusted" Certificate in FireFox?
<p>I have some 700+ links to check and they are a long links from sites. They are trusted but FireFox doesn't recognize them as trusted. So how do I disable "This Connection is Untrusted" or add a bulk of links fast to trusted ?</p>
21,709,855
2
2
null
2014-02-11 17:40:53.82 UTC
null
2016-05-06 19:27:19.53 UTC
null
null
null
null
1,452,141
null
1
6
firefox
48,193
<p>Try this addon, it should do what you want: <a href="https://addons.mozilla.org/en-US/firefox/addon/skip-cert-error/" rel="noreferrer">https://addons.mozilla.org/en-US/firefox/addon/skip-cert-error/</a></p>
2,001,475
How can I find the most dense regions in an image?
<p>Consider a black and white image like <a href="http://img13.imageshack.us/img13/7401/10416827.jpg" rel="nofollow noreferrer">this</a></p> <p><img src="https://i.stack.imgur.com/HNyUF.jpg" alt="alt text"></p> <p>What I am trying to do is to find the region where the white points are most dense. In this case there are 20-21 such dense regions (i.e. the clusters of points makes a dense region).</p> <p>Can anyone give me any hint on how this can be achieved? </p>
2,002,202
4
1
null
2010-01-04 19:06:08.37 UTC
9
2017-07-08 04:38:57.34 UTC
2015-06-21 02:34:44.19 UTC
null
5,032,383
null
230,736
null
1
13
algorithm|matlab|image-processing
7,153
<p>If you have access to the <a href="https://www.mathworks.com/help/images/" rel="nofollow noreferrer">Image Processing Toolbox</a>, you can take advantage of a number of filtering and morphological operations it contains. Here's one way you could approach your problem, using the functions <a href="https://www.mathworks.com/help/images/ref/imfilter.html" rel="nofollow noreferrer"><code>imfilter</code></a>, <a href="https://www.mathworks.com/help/images/ref/imclose.html" rel="nofollow noreferrer"><code>imclose</code></a>, and <a href="https://www.mathworks.com/help/images/ref/imregionalmax.html" rel="nofollow noreferrer"><code>imregionalmax</code></a>:</p> <pre><code>% Load and plot the image data: imageData = imread('lattice_pic.jpg'); % Load the lattice image subplot(221); imshow(imageData); title('Original image'); % Gaussian-filter the image: gaussFilter = fspecial('gaussian', [31 31], 9); % Create the filter filteredData = imfilter(imageData, gaussFilter); subplot(222); imshow(filteredData); title('Gaussian-filtered image'); % Perform a morphological close operation: closeElement = strel('disk', 31); % Create a disk-shaped structuring element closedData = imclose(filteredData, closeElement); subplot(223); imshow(closedData); title('Closed image'); % Find the regions where local maxima occur: maxImage = imregionalmax(closedData); maxImage = imdilate(maxImage, strel('disk', 5)); % Dilate the points to see % them better on the plot subplot(224); imshow(maxImage); title('Maxima locations'); </code></pre> <p>And here's the image the above code creates:</p> <p><a href="https://i.stack.imgur.com/4JSRd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4JSRd.jpg" alt="enter image description here"></a></p> <p>To get things to look good I just kept trying a few different combinations for the parameters for the Gaussian filter (created using <a href="https://www.mathworks.com/help/images/ref/fspecial.html" rel="nofollow noreferrer"><code>fspecial</code></a>) and the structuring element (created using <a href="https://www.mathworks.com/help/images/ref/strel-class.html" rel="nofollow noreferrer"><code>strel</code></a>). However, that little bit of trial and error gave a very nice result.</p> <p><strong>NOTE:</strong> The image returned from <a href="https://www.mathworks.com/help/images/ref/imregionalmax.html" rel="nofollow noreferrer"><code>imregionalmax</code></a> doesn't always have just single pixels set to 1 (to indicate a maxima). The output image often contains clusters of pixels because neighboring pixels in the input image can have equal values, and are therefore both counted as maxima. In the code above I also dilated these points with <a href="https://www.mathworks.com/help/images/ref/imdilate.html" rel="nofollow noreferrer"><code>imdilate</code></a> just to make them easier to see in the image, which makes an even bigger cluster of pixels centered on the maxima. If you want to reduce the cluster of pixels to a single pixel, you should remove the dilation step and modify the image in other ways (add noise to the result or filter it, then find the new maxima, etc.).</p>
2,066,068
What permissions are required for subprocess.Popen?
<p>The following code:</p> <pre><code>gb = self.request.form['groupby'] typ = self.request.form['type'] tbl = self.request.form['table'] primary = self.request.form.get('primary', None) if primary is not None: create = False else: create = True mdb = tempfile.NamedTemporaryFile() mdb.write(self.request.form['mdb'].read()) mdb.seek(0) csv = tempfile.TemporaryFile() conversion = subprocess.Popen(("/Users/jondoe/development/mdb-export", mdb.name, tbl,),stdout=csv) </code></pre> <p>Causes the this error when calling the last line i.e. 'conversion =' in OS X.</p> <pre><code>Traceback (innermost last): Module ZPublisher.Publish, line 119, in publish Module ZPublisher.mapply, line 88, in mapply Module ZPublisher.Publish, line 42, in call_object Module circulartriangle.mdbtoat.mdb, line 62, in __call__ Module subprocess, line 543, in __init__ Module subprocess, line 975, in _execute_child OSError: [Errno 13] Permission denied </code></pre> <p>I've tried <code>chmod 777 /Users/jondoe/development/mdb-export</code> - what else might be required? </p>
2,094,311
4
0
null
2010-01-14 17:20:14.227 UTC
null
2010-01-19 15:13:58.09 UTC
2010-01-19 15:13:58.09 UTC
null
161,525
null
161,525
null
1
13
python|macos|subprocess|popen
43,497
<p>It seems the 'Permissions denied error' was orginally coming from Popen trying to execute mdb-export from the wrong location (and to compound things, with the wrong permissions). </p> <p>If mdbtools is installed, the following works fine and inherits the correct permissions without the need for sudo etc.</p> <pre><code>subprocess.Popen(("mdb-export", mdb.name, tbl,),stdout=csv) </code></pre> <p>(Worth noting, I got myself into a muddle for a while, having forgotten that Popen is for opening executables, not folders or non-exectable files in folders)</p> <p>Thanks for all your responses, they all made for interesting reading regardless :)</p>
1,792,604
Html.ImageGetter
<p>Can any one help me out how to use Html.ImageGetter to dispaly images using html image src tag ? and example or good tutorial</p>
4,821,151
4
0
null
2009-11-24 20:08:24.993 UTC
12
2017-06-12 09:29:18.493 UTC
null
null
null
null
216,431
null
1
16
html|android
21,016
<p>To get images from the application resources first in the text file one inserts an html image tag like this:</p> <pre><code>&lt;img src="my_image"&gt; </code></pre> <p>Note that "my_image" is just a name of a drawable not a path. Then use this code to diplay the text with images in TextView</p> <pre><code>myTextView.setText(Html.fromHtml(myText, new ImageGetter() { @Override public Drawable getDrawable(String source) { Drawable drawFromPath; int path = myActivity.this.getResources().getIdentifier(source, "drawable", "com.package..."); drawFromPath = myActivity.this.getResources().getDrawable(path); drawFromPath.setBounds(0, 0, drawFromPath.getIntrinsicWidth(), drawFromPath.getIntrinsicHeight()); return drawFromPath; } }, null)); </code></pre> <p>If the source in the img tag is misspelled the applicaiton will crash because the method will fail to find the drawable, so more code can be added to prevent this...</p>
26,054,119
input-group-addon with bootstrap-select
<p>I tried to use <em>Label 2</em> with <em>bootstrap-select</em>, but it looks different to the <em>bootstrap</em> (<em>Label 1</em>) one. How is it possible to get the two labels in the code below look the same?</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"&gt; &lt;meta name="description" content=""&gt; &lt;meta name="author" content=""&gt; &lt;link rel="shortcut icon" href="../../docs-assets/ico/favicon.png"&gt; &lt;title&gt;Test&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" &gt; &lt;link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.2/css/bootstrap-select.min.css"&gt; &lt;link href="http://getbootstrap.com/examples/non-responsive/non-responsive.css" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="col-lg-6"&gt; &lt;div class="input-group"&gt; &lt;span class="input-group-addon"&gt;Labe 1&lt;/span&gt; &lt;input type="text" class="form-control" name="snpid" placeholder="Test"&gt; &lt;span class="input-group-btn"&gt; &lt;button class="btn btn-default" type="submit"&gt;GO!&lt;/button&gt; &lt;/span&gt; &lt;/div&gt;&lt;!-- /input-group --&gt; &lt;/div&gt;&lt;!-- /.col-lg-6 --&gt; &lt;div&gt; &lt;BR/&gt; &lt;HR&gt; &lt;div class="container"&gt; &lt;form class="form-inline"&gt; &lt;div class="form-group"&gt; &lt;span class="input-group-addon"&gt;Label 2&lt;/span&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;select id="lunch" class="selectpicker" data-live-search="true" title="Please select a lunch ..."&gt; &lt;option&gt;Hot Dog, Fries and a Soda&lt;/option&gt; &lt;option&gt;Burger, Shake and a Smile&lt;/option&gt; &lt;option&gt;Sugar, Spice and all things nice&lt;/option&gt; &lt;option&gt;Baby Back Ribs&lt;/option&gt; &lt;option&gt;A really really long option made to illustrate an issue with the live search in an inline form&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/form&gt; &lt;div&gt; &lt;script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="//netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.2/js/bootstrap-select.min.js"&gt;&lt;/script&gt; &lt;script&gt; $('.selectpicker').selectpicker(); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
26,054,469
3
1
null
2014-09-26 07:20:30.827 UTC
4
2017-05-23 16:06:26.437 UTC
2014-12-30 18:56:39.413 UTC
null
1,366,033
null
977,828
null
1
30
jquery|twitter-bootstrap|twitter-bootstrap-3|bootstrap-select
95,473
<p>From Bootstrap <a href="http://getbootstrap.com/components/#input-groups">docs</a>:</p> <blockquote> <p>Extend form controls by adding text or buttons before, after, or on both sides of any text-based <code>&lt;input&gt;</code>. Use <code>.input-group</code> with an <code>.input-group-addon</code> or <code>.input-group-btn</code> to prepend or append elements to a single <code>.form-control</code>.</p> </blockquote> <p>You need to wrap the <code>select</code> and <code>.input-group-addon</code> in a <code>.input-group</code>:</p> <pre><code>&lt;div class="input-group"&gt; &lt;span class="input-group-addon"&gt;Label 2&lt;/span&gt; &lt;select id="lunch" class="selectpicker form-control" data-live-search="true" title="Please select a lunch ..."&gt; &lt;option&gt;Hot Dog, Fries and a Soda&lt;/option&gt; &lt;option&gt;Burger, Shake and a Smile&lt;/option&gt; &lt;option&gt;Sugar, Spice and all things nice&lt;/option&gt; &lt;option&gt;Baby Back Ribs&lt;/option&gt; &lt;option&gt;A really really long option made to illustrate an issue with the live search in an inline form&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>Check it out: <div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"&gt; &lt;div class="container"&gt; &lt;div class="col-lg-6"&gt; &lt;div class="input-group"&gt; &lt;span class="input-group-addon"&gt;Labe 1&lt;/span&gt; &lt;input type="text" class="form-control" name="snpid" placeholder="Test"&gt; &lt;span class="input-group-btn"&gt; &lt;button class="btn btn-default" type="submit"&gt;GO!&lt;/button&gt; &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;br&gt; &lt;hr&gt; &lt;div class="container"&gt; &lt;form class="form-inline"&gt; &lt;div class="input-group"&gt; &lt;span class="input-group-addon"&gt;Label 2&lt;/span&gt; &lt;select id="lunch" class="selectpicker form-control" data-live-search="true" title="Please select a lunch ..."&gt; &lt;option&gt;Hot Dog, Fries and a Soda&lt;/option&gt; &lt;option&gt;Burger, Shake and a Smile&lt;/option&gt; &lt;option&gt;Sugar, Spice and all things nice&lt;/option&gt; &lt;option&gt;Baby Back Ribs&lt;/option&gt; &lt;option&gt;A really really long option made to illustrate an issue with the live search in an inline form&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
7,060,727
How to deal with IntelliJ IDEA project files under Git source control constantly changing?
<p>Everyone on our team uses IntelliJ IDEA, and we find it useful to put its project files (.ipr and .iml) into source control so that we can share build configurations, settings, and inspections. Plus, we can then use those inspection settings on our continuous integration server with TeamCity. (We have the per-user workspace .iws file in the .gitignore file and not in source control.)</p> <p>However, those files change in little ways when you do just about anything in IDEA. There's an issue in IDEA's issue database for it (<a href="https://youtrack.jetbrains.com/issue/IDEA-64312" rel="noreferrer">IDEA-64312</a>), so perhaps one might consider this a bug in IDEA, but it's one we'll need to live with for the foreseeable future.</p> <p>Up until recently, we were using Subversion, but we recently switched to Git. We had each just gotten used to having a change list of project files that we ignored and didn't check in unless there were project file changes that we wanted to share with others. But with Git, the real power seems to be (from what we're exploring) the continuous branching that it encourages, and switching between branches is a pain with the project files always having been modified. Often it can just merge in the changes somehow, and tries to deal with the project file changes now being applied to the new branch. However, if the new branch has changed project files (such as the branch is working on a new module that isn't in the other branches yet), git just throws an error that it doesn't make any sense to merge in the files when both the branch has changes and you have changes locally, and I can rather understand its point. From the command line, one can use &quot;-f&quot; on the &quot;git checkout&quot; command to force it to throw out the local changes and use the branch's instead, but (1) the Git Checkout GUI command in IDEA (10.5.1) doesn't seem to have that as an option that we can find, so we'd need to switch to the command line on a regular basis, and (2) We're not sure we want to be in the habit of using that flag and telling Git to throw out our local changes.</p> <p>So, here are some thoughts we have on options we have to deal with this:</p> <ol> <li>Take the project files out of source control entirely. Put them in the .gitignore, and distribute them to each person and TeamCity via some other means, maybe by putting them in source control somewhere else or under other names. Our team's small enough this option is feasible enough to consider, but it doesn't seem great.</li> <li>Continue living with it, trying to be sure to manage which files we have on which branches at a given time. As part of this, we might encourage each developer to have more than one copy of each project on their system, so they can have each checked out to a different branch with possibly different sets of project files.</li> <li>Try having just the project (.ipr) in source control, with the module (.iml) files not in source control and in the .gitignore file. The main thing that seems to switch around on its own in the .ipr on a regular basis is the order of the shared build configurations, but maybe we can just share the information separately on how to set those up. I'm not quite sure how IDEA deals with this kind of thing of only having some of its files though, especially on a new checkout.</li> </ol> <p>I guess I'm hoping there's some obvious (or non-obvious) solution we've missed, perhaps dealing with the huge customizability that Git and IDEA both seem to have. But it seems like we couldn't possibly be the only team having this problem. Questions that are kind of similar on Stack Overflow include <a href="https://stackoverflow.com/questions/3495181/need-a-strategy-to-put-intellij-idea-project-files-in-git">3495191</a>, <a href="https://stackoverflow.com/questions/1000512/merges-on-intellij-idea-ipr-and-iws-files">1000512</a>, and <a href="https://stackoverflow.com/questions/3873872/best-practices-for-using-git-with-intellij-idea">3873872</a>, but I don't know as they're exactly the same issue, and maybe someone can come up with the pros and cons for the various approaches I've outlined, approaches listed in the answers to those questions, or approaches that they recommend.</p>
7,062,277
6
3
null
2011-08-15 00:34:40.15 UTC
38
2020-07-16 08:14:52.583 UTC
2020-07-16 08:14:52.583 UTC
null
1,402,846
user65839
null
null
1
161
git|version-control|intellij-idea
72,679
<p>You can use IDEA's <a href="https://www.jetbrains.com/help/idea/2017.1/directory-based-versioning-model.html" rel="noreferrer">directory-based project structure</a>, where the settings are stored in .idea directory instead of .ipr file. It gives more <a href="https://intellij-support.jetbrains.com/hc/en-us/articles/206544839-How-to-manage-projects-under-Version-Control-Systems" rel="noreferrer">fine-grained control</a> over what is stored in version control. The .iml files will still be around, so it doesn't solve the random changes in them (maybe keep them out of source control?), but sharing things such as code style and inspection profiles is easy, since each of them will be in its own file under the .idea directory. </p>
7,506,163
Rules engine for .NET
<p>We have a business requirement to let power users edit rules for insurance rates and enrollments. We need a web ui that lets them say "this product is only for people &lt;55 unless they are from Texas and own a poodle" or whatever. Edit for clarification: Insurance is insane. The rules differ from product to product, state to state and change constantly.</p> <p>We looked at a couple of rules engines but the commercial ones are 100K+ and the open source ones don't seem um, finished. Windows Workflow works if we create the rules ahead of time, but building them at runtime seems to require bypassing code access security. That's scary.</p> <p>Are we nuts to reinvent this wheel? Is there a better alternative for .net?</p>
7,506,899
7
8
null
2011-09-21 20:24:01.507 UTC
15
2015-06-19 01:21:15.043 UTC
2011-09-21 20:39:46.023 UTC
null
95,506
null
95,506
null
1
26
c#|rules|drools
17,975
<p>I do not think that the evaluation of the rules will be the challenge. I think that the greater challenge is to <em>parse</em> the rules that the user can enter. For parsing the rules you should consider to create some DSL. Martin Fowler has some thoughts about this <a href="http://martinfowler.com/bliki/RulesEngine.html">here</a>. Then maybe <a href="http://www.antlr.org/">ANTLR</a> then might be worth a look.</p> <p>For the evaluation part: I work in the finance industry and there are also complicated rules, but I never had to use a rule engine. The means of an imperative programming language (in my case C#) were (until now) sufficient. For some occasions I was considering a rules engine, but the technological risks(*) of a rule engine were always higher than the expected benefits. The rules were (until now) never that complicated, that declarative programming model was needed.</p> <p>If you are using a object oriented language you can try to apply the <a href="http://en.wikipedia.org/wiki/Specification_pattern">Specification Pattern</a>. Eric Evans and Martin Fowler have written a more detailed explanation, which you can find <a href="http://www.martinfowler.com/apsupp/spec.pdf">here</a>. Alternatively you can write your own simple rule engine.</p> <p>(*) Footnote: Somehow you will need to embed the rule engine into your application which is very likely written in some object oriented language. So there are some technological boundaries, which you have to bridge. Every such bridge is a technological risk. I had once witnessed a Java web application using a rule engine written in C. At the beginning the C program sometimes produced core dumps and tore down the whole web application.</p>
7,571,917
Adding image to Toast?
<p>Is it possible to programmatically add an image to a toast popup?</p>
7,578,806
8
2
null
2011-09-27 15:44:47.88 UTC
30
2020-10-12 19:18:15.923 UTC
2013-10-24 10:11:59.57 UTC
null
2,065,587
null
940,096
null
1
63
android|android-toast
41,441
<p><strong>Yes</strong>, you can add imageview or any view into the toast notification by using setView() method, using this method you can customize the Toast as per your requirement.</p> <p>Here i have created a Custom layout file to be inflated into the Toast notification, and then i have used this layout in Toast notification by using setView() method.</p> <p><strong>cust_toast_layout.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/relativeLayout1" android:background="@android:color/white"&gt; &lt;TextView android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="PM is here" android:gravity="center" android:textColor="@android:color/black"&gt; &lt;/TextView&gt; &lt;ImageView android:layout_height="wrap_content" android:layout_width="fill_parent" android:src="@drawable/new_logo" android:layout_below="@+id/textView1" android:layout_margin="5dip" android:id="@+id/imageView1"&gt; &lt;/ImageView&gt; &lt;TextView android:id="@+id/textView2" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="This is the demo of Custom Toast Notification" android:gravity="center" android:layout_below="@+id/imageView1" android:textColor="@android:color/black"&gt; &lt;/TextView&gt; &lt;/RelativeLayout&gt; </code></pre> <p><strong>CustomToastDemoActivity.java</strong></p> <pre><code>LayoutInflater inflater = getLayoutInflater(); View view = inflater.inflate(R.layout.cust_toast_layout, (ViewGroup)findViewById(R.id.relativeLayout1)); Toast toast = new Toast(this); toast.setView(view); toast.show(); </code></pre>
14,013,223
How to replace multiple keywords by corresponding keywords with the `replace` method?
<p>I want to make a content editable div in which I replace explicit words with asterisks. This is my JavaScript code:</p> <pre class="lang-js prettyprint-override"><code>function censorText(){ var explicit = document.getElementById(&quot;textbox&quot;).innerHTML; var clean = explicit.replace(/&quot;badtext1&quot;,&quot;cleantext1&quot;|&quot;badtext2&quot;,&quot;cleantext2&quot;/); document.getElementById(&quot;textbox&quot;).innerHTML = clean; } </code></pre> <p>Here’s the HTML for my <code>&lt;div contenteditable&gt;</code>:</p> <pre class="lang-html prettyprint-override"><code>&lt;div contenteditable=&quot;true&quot; onkeyup=&quot;censorText()&quot; id=&quot;textbox&quot;&gt;Hello!&lt;/div&gt; </code></pre> <p>As you can see, I tried using a regex operator to replace multiple strings at once, but it doesn’t work. It doesn’t replace <code>badtext2</code> with <code>cleantext2</code>, and it replaces <code>badtext1</code> with <code>0</code>. How can I make a single <code>.replace()</code> statement replace multiple strings?</p>
14,013,325
3
0
null
2012-12-23 17:50:39.317 UTC
6
2021-05-04 04:50:31.917 UTC
2021-05-04 04:50:31.917 UTC
null
4,642,212
null
1,543,403
null
1
23
javascript|regex|string|replace
42,342
<p>use <code>/.../g</code> to indicate a global replace.</p> <pre><code>var clean = explicit.replace(/badtext1/g,"cleantext2"/).replace(/cleantext1/g,"cleantext2"/).replace(/badtext2/g,"cleantext2"/); </code></pre>
14,108,400
how to align text vertically center in android
<p>I have arabic text, therefore I set gravity to right in order to start text from right side. Text starts from right now. But another issue is text starts to render from the top of the page. But I need to vertically center the text. Although I tried several variations I couldnt make it vertically center.</p> <p>Here is the sample of my xml file.</p> <pre><code>&lt;LinearLayout android:id="@+id/linearLayout5" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="right" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginBottom="23dp" android:gravity="right" android:padding="@dimen/padding_maintextview" android:text="@string/text" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="20sp" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>Problem is with above textview.</p> <p>Here I have put whole xml file.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/page1background" android:paddingRight="@dimen/padding_large" &gt; &lt;TextView android:id="@+id/textView1" android:layout_width="196dp" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:gravity="center_horizontal" android:paddingTop="@dimen/padding_Title_Top" android:text="@string/text" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="20sp" /&gt; &lt;LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textView1" android:gravity="center_horizontal" android:orientation="vertical" &gt; &lt;View android:id="@+id/view1" android:layout_width="fill_parent" android:layout_height="5dp" /&gt; &lt;/LinearLayout&gt; &lt;ScrollView android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_above="@id/linearLayout2" android:layout_below="@id/linearLayout1" android:layout_gravity="center" android:padding="@dimen/padding_maintextview" &gt; &lt;LinearLayout android:id="@+id/linearLayout5" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="right" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginBottom="23dp" android:gravity="right" android:padding="@dimen/padding_maintextview" android:text="@string/text" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="20sp" /&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; &lt;LinearLayout android:id="@+id/linearLayout2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" &gt; &lt;View android:id="@+id/view2" android:layout_width="fill_parent" android:layout_height="100dp" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/linearLayout3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" &gt; &lt;ImageButton android:id="@+id/back_arrow" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_marginBottom="30dp" android:layout_marginRight="45dp" android:layout_weight=".5" android:background="@drawable/backbut" android:contentDescription="@string/Description" android:onClick="onClickBtn" android:src="@drawable/backarrowpress" /&gt; &lt;ImageButton android:id="@+id/copyButton" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_marginLeft="45dp" android:layout_weight=".5" android:background="@drawable/copy" android:contentDescription="@string/Description" android:onClick="onClickBtn" /&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Can anybody show me where I have done the mistake? I think problem is clear. If not tell me in comments.</p> <p>Herewith I have appended updated code after review your answers.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/page1background" android:paddingRight="@dimen/padding_large" &gt; &lt;TextView android:id="@+id/textView1" android:layout_width="196dp" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:gravity="center_horizontal" android:paddingTop="@dimen/padding_Title_Top" android:text="@string/text" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="20sp" /&gt; &lt;LinearLayout android:id="@+id/linearLayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/textView1" android:gravity="center_horizontal" android:orientation="vertical" &gt; &lt;View android:id="@+id/view1" android:layout_width="fill_parent" android:layout_height="5dp" /&gt; &lt;/LinearLayout&gt; &lt;ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_above="@id/linearLayout2" android:layout_below="@id/linearLayout1" android:layout_gravity="center" android:layout_centerInParent="true" android:padding="@dimen/padding_maintextview" &gt; &lt;LinearLayout android:id="@+id/linearLayout5" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="right" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/textView2" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center_vertical" android:layout_marginBottom="23dp" android:gravity="center_vertical|right" android:padding="@dimen/padding_maintextview" android:text="@string/text" android:textAppearance="?android:attr/textAppearanceMedium" android:textSize="20sp" /&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; &lt;LinearLayout android:id="@+id/linearLayout2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" &gt; &lt;View android:id="@+id/view2" android:layout_width="fill_parent" android:layout_height="100dp" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:id="@+id/linearLayout3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" &gt; &lt;ImageButton android:id="@+id/back_arrow" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_marginBottom="30dp" android:layout_marginRight="45dp" android:layout_weight=".5" android:background="@drawable/backbut" android:contentDescription="@string/Description" android:onClick="onClickBtn" android:src="@drawable/backarrowpress" /&gt; &lt;ImageButton android:id="@+id/copyButton" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_marginLeft="45dp" android:layout_weight=".5" android:background="@drawable/copy" android:contentDescription="@string/Description" android:onClick="onClickBtn" /&gt; &lt;/LinearLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p>But I am in same situation. No text is vertically centered</p>
14,108,418
5
0
null
2013-01-01 06:30:18.31 UTC
7
2016-03-20 11:44:54.173 UTC
2013-01-01 07:05:17.103 UTC
null
1,578,356
null
1,578,356
null
1
51
android|android-layout|text
114,798
<p>Your TextView Attributes need to be something like,</p> <pre><code>&lt;TextView ... android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical|right" ../&gt; </code></pre> <p>Now, Description why these need to be done,</p> <pre><code> android:layout_width="match_parent" android:layout_height="match_parent" </code></pre> <p>Makes your TextView to <code>match_parent</code> or <code>fill_parent</code> if You don't want to be it like, <code>match_parent</code> you have to give some specified values to <code>layout_height</code> so it get space for vertical center gravity. <code>android:layout_width="match_parent"</code> necessary because it align your TextView in Right side so you can recognize respect to Parent Layout of TextView.</p> <p>Now, its about <code>android:gravity</code> which makes the content of Your TextView alignment. <code>android:layout_gravity</code> makes alignment of TextView respected to its Parent Layout. </p> <p><strong>Update:</strong></p> <p>As below comment says use <code>fill_parent</code> instead of <code>match_parent</code>. (Problem in some device.)</p>
9,199,670
CQRS without Event Sourcing - what are the drawbacks?
<p>Besides missing some of the benefits of Event Sourcing, are there any other drawbacks to adapting an existing architecture to CQRS without the Event Sourcing piece?</p> <p>I'm working on large application and the developers should be able to handle separating the existing architecture into Commands and Queries over the next few months, but asking them to also add in the Event Sourcing at this stage would be a HUGE problem from a resourcing perspective. Am I committing sacrilege by not including Event Sourcing?</p>
9,217,461
6
1
null
2012-02-08 18:56:41.35 UTC
16
2021-03-28 16:28:01.84 UTC
null
null
null
null
36,590
null
1
46
cqrs|event-sourcing|ncqrs
13,639
<p>Event Sourcing is optional and in most cases complicates things more than it helps if introduced too early. Especially when transitioning from a legacy architecture and even more when the team has no experience with CQRS.</p> <p>Most of the advantages being attributed to ES can be obtained by storing your events in a simple Event Log. You don't have to drop your state-based persistence, (but in the long run you probably will, because at some point it will become the logical next step).</p> <p>My recommendation: Simplicity is the key. Do one step at a time, especially when introducing such a dramatic paradigm shift. Start with simple CQRS, then introduce an Event Log when you (and your team) have become used to the new concepts. Then, if at all required, change your persistence to Event Sourcing and fire the DBA ;-)</p>
34,169,602
why we need both std::promise and std::future?
<p>I am wondering why we need both std::promise and std::future ? why c++11 standard divided get and set_value into two separate classes std::future and std::promise? In the answer of this <a href="https://stackoverflow.com/questions/12620186/futures-vs-promises">post</a>, it mentioned that :</p> <blockquote> <p>The reason it is separated into these two separate "interfaces" is to hide the "write/set" functionality from the "consumer/reader".</p> </blockquote> <p>I don't understand the benefit of hiding here. But isn't it simpler if we have only one class "future"? For example: promise.set_value can be replaced by future.set_value.</p>
34,169,913
2
5
null
2015-12-09 02:08:39.493 UTC
9
2016-05-16 00:39:10.29 UTC
2017-05-23 12:10:08.013 UTC
null
-1
null
440,403
null
1
15
c++|c++11
4,978
<p>The problem that promise/future exist to solve is to shepherd a value from one thread to another. It may also transfer an exception instead.</p> <p>So the source thread must have some object that it can talk to, in order to send the desired value to the other thread. Alright... who <em>owns</em> that object? If the source has a pointer to something that the destination thread owns, how does the source know if the destination thread has deleted the object? Maybe the destination thread no longer cares about the value; maybe something changed such that it decided to just drop your thread on the floor and forget about it.</p> <p>That's entirely legitimate code in some cases.</p> <p>So now the question becomes why the source doesn't own the promise and simply give the destination a pointer/reference to it? Well, there's a good reason for that: the promise is owned by the source thread. Once the source thread terminates, the promise <em>will be destroyed.</em> Thus leaving the destination thread with a reference to a destroyed promise.</p> <p>Oops.</p> <p>Therefore, the only viable solution is to have two full-fledged objects: one for the source and one for the destination. These objects share ownership of the value that gets transferred. Of course, that doesn't mean that they couldn't be the same <em>type</em>; you could have something like <code>shared_ptr&lt;promise&gt;</code> or somesuch. After all, promise/future must have some shared storage of some sort internally, correct?</p> <p>However, consider the interface of promise/future as they currently stand.</p> <p><a href="http://en.cppreference.com/w/cpp/thread/promise/promise" rel="noreferrer"><code>promise</code> is non-copyable</a>. You can <em>move</em> it, but you can't copy it. <code>future</code> is also non-copyable, but a <code>future</code> can become a <code>shared_future</code> that is copyable. So you can have multiple destinations, but only one <em>source</em>.</p> <p><code>promise</code> can only set the value; it can't even get it back. <code>future</code> can only get the value; it cannot set it. Therefore, you have an asymmetric interface, which is entirely appropriate to this use case. You don't want the destination to be able to set the value and the source to be able to retrieve it. That's backwards code logic.</p> <p>So that's why you want two objects. You have an asymmetric interface, and that's best handled with two related but separate types and objects.</p>
52,082,939
Type hints when unpacking a tuple?
<p>Is it possible to use type hinting when unpacking a tuple? I want to do this, but it results in a <code>SyntaxError</code>:</p> <pre><code>from typing import Tuple t: Tuple[int, int] = (1, 2) a: int, b: int = t # ^ SyntaxError: invalid syntax </code></pre>
52,083,314
1
6
null
2018-08-29 17:16:30.91 UTC
8
2021-10-06 16:42:19.17 UTC
2021-10-06 16:42:19.17 UTC
null
13,990,016
null
2,883,198
null
1
100
python|python-3.x|type-hinting|python-typing|iterable-unpacking
14,344
<p>According to <a href="https://www.python.org/dev/peps/pep-0526/#global-and-local-variable-annotations" rel="noreferrer">PEP-0526</a>, you should annotate the types first, then do the unpacking</p> <pre><code>a: int b: int a, b = t </code></pre>
80,609
Merge XML documents
<p>I need to "merge" two XML documents, overwriting the overlapsed attributes and elements. For instance if I have <strong>document1</strong>:</p> <pre><code>&lt;mapping&gt; &lt;key value="assigned"&gt; &lt;a/&gt; &lt;/key&gt; &lt;whatever attribute="x"&gt; &lt;k/&gt; &lt;j/&gt; &lt;/whatever&gt; &lt;/mapping&gt; </code></pre> <p>and <strong>document2</strong>:</p> <pre><code>&lt;mapping&gt; &lt;key value="identity"&gt; &lt;a/&gt; &lt;b/&gt; &lt;/key&gt; &lt;/mapping&gt; </code></pre> <p>I want to merge the two like this:</p> <pre><code>&lt;mapping&gt; &lt;key value="identity"&gt; &lt;a/&gt; &lt;b/&gt; &lt;/key&gt; &lt;whatever attribute="x"&gt; &lt;k/&gt; &lt;j/&gt; &lt;/whatever&gt; &lt;/mapping&gt; </code></pre> <p>I prefer <strong>Java</strong> or <strong>XSLT</strong>-based solutions, <strong>ant</strong> will do fine, but if there's an easy way to do that in <strong>Rake</strong>, <strong>Ruby</strong> or <strong>Python</strong> please don't be shy :-)</p> <p><strong>EDIT:</strong> actually I find I'd rather use an automated tool/script, even <a href="http://web.archive.org/web/20100818203850/http://stackoverflow.com:80/questions/58640/great-programming-quotes" rel="nofollow noreferrer">writing it by myself</a>, because manually merging some 30 XML files is a bit unwieldy... :-(</p>
174,071
5
2
null
2008-09-17 06:50:01.667 UTC
4
2019-09-26 15:38:13.867 UTC
2018-10-15 18:03:01.55 UTC
Manrico Corazzi
9,780,149
Manrico Corazzi
4,690
null
1
23
xml
62,575
<p>If you like XSLT, there's a nice merge script I've used before at: <a href="http://web.archive.org/web/20160809092524/http://www2.informatik.hu-berlin.de/~obecker/XSLT/" rel="nofollow noreferrer">Oliver's XSLT page</a></p>
945,427
C# WPF IsEnabled using multiple bindings?
<p>I have a WPF xaml file describing a section of a GUI and I'd like the enabling/disabling of a particular control to be dependent on two others. The code looks something like this at the moment:</p> <pre><code>&lt;ComboBox Name="MyComboBox" IsEnabled="{Binding ElementName=SomeCheckBox, Path=IsChecked}"/&gt; </code></pre> <p>But I'd like it to be dependant on another checkbox as well so something like:</p> <pre><code>&lt;ComboBox Name="MyComboBox" IsEnabled="{Binding ElementName=SomeCheckBox&amp;AnotherCheckbox, Path=IsChecked}"/&gt; </code></pre> <p>What's the best way to go about that? I can't help feeling I'm missing something obvious or going about this the wrong way?</p>
945,453
5
0
null
2009-06-03 15:32:38.653 UTC
8
2022-08-31 13:14:01.713 UTC
2013-08-05 05:28:18.823 UTC
null
2,176,945
null
15,369
null
1
54
c#|wpf|binding|combobox|isenabled
54,378
<p>I believe you may have to use a MultiBinding with a MultiValueConverter. See here: <a href="http://www.developingfor.net/wpf/multibinding-in-wpf.html" rel="noreferrer">http://www.developingfor.net/wpf/multibinding-in-wpf.html</a> </p> <p>Here is a directly related example: <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/5b9cd042-cacb-4aaa-9e17-2d615c44ee22" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/5b9cd042-cacb-4aaa-9e17-2d615c44ee22</a></p>
835,753
Convert grayscale value to RGB representation?
<p>How can I convert a grayscale value (0-255) to an RGB value/representation? It is for using in an SVG image, which doesn't seem to come with a grayscale support, only RGB...</p> <p>Note: this is not RGB -> grayscale, which is already answered in another question, e.g. <a href="https://stackoverflow.com/questions/687261/converting-rgb-to-grayscale-intensity">Converting RGB to grayscale/intensity</a>)</p>
835,780
6
0
null
2009-05-07 16:37:38.9 UTC
11
2020-04-08 08:26:25.347 UTC
2017-05-23 12:08:44.5 UTC
null
-1
null
50,899
null
1
25
colors|rgb|grayscale
110,954
<p>The quick and dirty approach is to repeat the grayscale intensity for each component of RGB. So, if you have grayscale 120, it translates to RGB (120, 120, 120).</p> <p>This is quick and dirty because the effective luminance you get depends on the actual luminance of the R, G and B subpixels of the device that you're using.</p>
1,151,625
INT vs Unique-Identifier for ID field in database
<p>I am creating a new database for a web site using SQL Server 2005 (possibly SQL Server 2008 in the near future). As an application developer, I've seen many databases that use an <code>integer</code> (or <code>bigint</code>, etc.) for an ID field of a table that will be used for relationships. But lately I've also seen databases that use the <code>unique identifier</code> (<code>GUID</code>) for an ID field.</p> <p>My question is whether one has an advantage over the other? Will <code>integer</code> fields be faster for querying and joining, etc.?</p> <p><strong>UPDATE:</strong> To make it clear, this is for a primary key in the tables.</p>
1,151,733
6
3
null
2009-07-20 03:43:12.543 UTC
10
2021-07-23 21:27:03.633 UTC
2016-03-05 07:20:33.443 UTC
null
41,956
null
54,727
null
1
33
sql|sql-server|tsql|uniqueidentifier
24,885
<p>GUIDs are problematic as clustered keys because of the high randomness. This issue was addressed by Paul Randal in the last Technet Magazine Q&amp;A column: <a href="http://technet.microsoft.com/en-us/magazine/dd776512.aspx" rel="noreferrer">I'd like to use a GUID as the clustered index key, but the others are arguing that it can lead to performance issues with indexes. Is this true and, if so, can you explain why?</a> </p> <p>Now bear in mind that the discussion is specifically about <strong>clustered</strong> indexes. You say you want to use the column as 'ID', that is unclear if you mean it as clustered key or just primary key. Typically the two overlap, so I'll assume you want to use it as clustered index. The reasons why that is a poor choice are explained in the link to the article I mentioned above.</p> <p>For non clustered indexes GUIDs still have some issues, but not nearly as big as when they are the leftmost clustered key of the table. Again, the randomness of GUIDs introduces page splits and fragmentation, be it at the non-clustered index level only (a much smaller problem).</p> <p>There are many urban legends surrounding the GUID usage that condemn them based on their size (16 bytes) compared to an int (4 bytes) and promise horrible performance doom if they are used. This is slightly exaggerated. A key of size 16 can be a very peformant key still, on a properly designed data model. While is true that being 4 times as big as a int results in more a <em>lower density non-leaf pages</em> in indexes, this is not a real concern for the vast majority of tables. The b-tree structure is a naturally well balanced tree and the <em>depth</em> of tree traversal is seldom an issue, so seeking a value based on GUID key as opposed to a INT key is similar in performance. A leaf-page traversal (ie. a table scan) does not look at the non-leaf pages, and the impact of GUID size on the page size is typically quite small, as the record itself is significantly larger than the extra 12 bytes introduced by the GUID. So I'd take the hear-say advice based on 'is 16 bytes vs. 4' with a, rather large, grain of salt. Analyze on individual case by case and decide if the size impact makes a real difference: how many <em>other</em> columns are in the table (ie. how much impact has the GUID size on the leaf pages) and how many references are using it (ie. how many <em>other</em> tables will increase because of the fact they need to store a larger foreign key).</p> <p>I'm calling out all these details in a sort of makeshift defense of GUIDs because they been getting a lot of bad press lately and some is undeserved. They have their merits and are indispensable in any distributed system (the moment you're talking data movement, be it via replication or sync framework or whatever). I've seen bad decisions being made out based on the GUID bad reputation when they were shun without proper consideration. But is true, <strong>if you have to use a GUID as clustered key, make sure you address the randomness issue: use sequential guids</strong> when possible.</p> <p>And finally, to answer your question: <strong>if you don't have a <em>specific</em> reason to use GUIDs, use INTs.</strong></p>
42,182,389
How to remove all data from a Firebase database?
<p>I started using a code that using <a href="https://firebase.google.com/" rel="noreferrer">Firebase</a> realtime database. I implemented it to my solution. Connection and control was perfect, so I used it for the production environment.</p> <p>After a while I was doing upgrade and I need remove all data again - but wait, there are no delete buttons in <a href="https://console.firebase.google.com/" rel="noreferrer">console</a> anymore at highest root level and only allowed in one selected item at once:</p> <pre><code>https://console.firebase.google.com/project/{{project_name}}/database/data </code></pre> <p>In last update shown only this message and no steps what next:</p> <blockquote> <p>Read-only &amp; non-realtime mode activated to improve browser performance Select a key with fewer records to edit or view in realtime</p> </blockquote> <p>Q how can I remove all data at once?</p>
42,182,390
9
3
null
2017-02-11 23:20:05.253 UTC
4
2022-03-07 23:25:53.84 UTC
2017-02-12 00:33:55.89 UTC
null
1,347,601
null
1,347,601
null
1
28
firebase|firebase-realtime-database|firebase-console
29,711
<h2><strong>Why missing Firebase remove button ?</strong></h2> <p>Alvin from <a href="https://firebase.google.com/support/" rel="nofollow noreferrer">Firebase Support</a> :</p> <blockquote> <p>Record or node has too much data, which makes the data viewer switch to a read-only/non real time mode to increase the browser's performance.</p> </blockquote> <hr /> <h2>Remove all data from Firebase from command line</h2> <p>Firebase documentation show <a href="https://firebase.google.com/docs/database/rest/save-data" rel="nofollow noreferrer">Removing Data</a> - just they don't show how remove all data.</p> <p>For remove all data you can use <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" rel="nofollow noreferrer">REST</a> command - which remove whole <a href="https://en.wikipedia.org/wiki/JSON" rel="nofollow noreferrer">JSON</a> output on that node level</p> <pre><code>curl -X DELETE &quot;https://{{project_id}}.firebaseio.com/.json&quot; </code></pre> <p>so you can do this on every generated &quot;<a href="https://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow noreferrer">URL</a> node in console&quot; by adding JSON extension</p> <pre><code>https://{{project_id}}.firebaseio.com/{{path}}/{{path}}/{{path}}/.json </code></pre>
42,197,729
App getting crash when click on GoogleSignIn button
<p>I am using Google Sign-In SDK 4.0.1. When I press googleSignInButton then app will be crash. And gave below error, how to fix this:</p> <pre><code>Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Your app is missing support for the following URL schemes: com.googleusercontent.apps.107731993306-6s44u18onibp6gi0ddj94si1aifshhg6' *** First throw call stack: ( 0 CoreFoundation 0x0000000101ac0d4b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x000000010110121e objc_exception_throw + 48 2 CoreFoundation 0x0000000101b2a2b5 +[NSException raise:format:] + 197 3 xxxxx 0x000000010084b3cb -[GIDSignIn signInWithOptions:] + 246 4 xxxxx 0x000000010084efc2 -[GIDSignInButton pressed] + 242 5 UIKit 0x00000001028f78bc -[UIApplication sendAction:to:from:forEvent:] + 83 6 UIKit 0x0000000102a7dc38 -[UIControl sendAction:to:forEvent:] + 67 7 UIKit 0x0000000102a7df51 -[UIControl _sendActionsForEvents:withEvent:] + 444 8 UIKit 0x0000000102a7ce4d -[UIControl touchesEnded:withEvent:] + 668 9 UIKit 0x0000000102965545 -[UIWindow _sendTouchesForEvent:] + 2747 10 UIKit 0x0000000102966c33 -[UIWindow sendEvent:] + 4011 11 UIKit 0x00000001029139ab -[UIApplication sendEvent:] + 371 12 UIKit 0x000000010310072d __dispatchPreprocessedEventFromEventQueue + 3248 13 UIKit 0x00000001030f9463 __handleEventQueue + 4879 14 CoreFoundation 0x0000000101a65761 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 15 CoreFoundation 0x0000000101a4a98c __CFRunLoopDoSources0 + 556 16 CoreFoundation 0x0000000101a49e76 __CFRunLoopRun + 918 17 CoreFoundation 0x0000000101a49884 CFRunLoopRunSpecific + 420 18 GraphicsServices 0x00000001074cfa6f GSEventRunModal + 161 19 UIKit 0x00000001028f5c68 UIApplicationMain + 159 20 xxxxxxxx 0x00000001007c449f main + 111 21 libdyld.dylib 0x0000000104d5368d start + 1 22 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException` </code></pre> <p>My AppDelegate.Swift is</p> <pre><code>class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate { public func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) { if (error == nil) { let userId:NSString = user.userID as NSString; // For client-side use only! let idToken: NSString = user.authentication.idToken as NSString; // Safe to send to the server let fullName:NSString = user.profile.name as NSString; let givenName:NSString = user.profile.givenName as NSString; let familyName:NSString = user.profile.familyName as NSString; let email:NSString = user.profile.email as NSString; print(userId) print(userId,idToken,fullName,givenName,familyName,email) } else { print("\(error.localizedDescription)") } } var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -&gt; Bool { let kclientID:NSString = "107731993306-xxxxxxxxxxxxxxxxx.apps.googleusercontent.com" GIDSignIn.sharedInstance().clientID = kclientID as String! GIDSignIn.sharedInstance().delegate = self return true } func application(application: UIApplication, openURL url: NSURL, options: [String: AnyObject], annotation:Any, sourceApplication:String?) -&gt; Bool { return GIDSignIn.sharedInstance().handle(url as URL!, sourceApplication:sourceApplication, annotation: annotation) } </code></pre> <blockquote> <p>Please give me the solution. Why it is crashed?</p> </blockquote>
42,198,735
12
3
null
2017-02-13 06:17:05.817 UTC
10
2022-08-23 21:57:26.263 UTC
2017-02-13 08:45:48.523 UTC
null
1,142,743
null
7,534,266
null
1
96
ios|swift|google-signin
72,550
<p>As the error clearly says, your app is missing support for the url schemes.</p> <p>Add the following schemes to your info.plist</p> <pre><code>&lt;key&gt;CFBundleURLTypes&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;CFBundleTypeRole&lt;/key&gt; &lt;string&gt;Editor&lt;/string&gt; &lt;key&gt;CFBundleURLSchemes&lt;/key&gt; &lt;array&gt; &lt;string&gt;***Your bundle ID***&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;dict&gt; &lt;key&gt;CFBundleTypeRole&lt;/key&gt; &lt;string&gt;Editor&lt;/string&gt; &lt;key&gt;CFBundleURLSchemes&lt;/key&gt; &lt;array&gt; &lt;string&gt;com.googleusercontent.apps.107731993306-6s44u18onibp6gi0ddj94si1aifshhg6&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;dict&gt; &lt;key&gt;CFBundleTypeRole&lt;/key&gt; &lt;string&gt;Editor&lt;/string&gt; &lt;key&gt;CFBundleURLSchemes&lt;/key&gt; &lt;array&gt; &lt;string&gt;***Something here***&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/array&gt; </code></pre> <p>Check this url for your id => <a href="https://developers.google.com/identity/sign-in/ios/start-integrating" rel="noreferrer">https://developers.google.com/identity/sign-in/ios/start-integrating</a></p> <p>Your info.plist should look like -> </p> <p><a href="https://i.stack.imgur.com/eSbun.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eSbun.png" alt="enter image description here"></a></p>
42,315,202
Understanding TensorBoard (weight) histograms
<p>It is really straightforward to see and understand the scalar values in TensorBoard. However, it's not clear how to understand histogram graphs. </p> <p>For example, they are the histograms of my network weights.</p> <p><a href="https://i.stack.imgur.com/IttNH.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/RVOA5.jpg" alt="enter image description here"></a></p> <p>(After fixing a bug thanks to sunside) <a href="https://i.stack.imgur.com/IttNH.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/IttNH.jpg" alt="enter image description here"></a> What is the best way to interpret these? Layer 1 weights look mostly flat, what does this mean?</p> <p>I added the network construction code here.</p> <pre><code>X = tf.placeholder(tf.float32, [None, input_size], name="input_x") x_image = tf.reshape(X, [-1, 6, 10, 1]) tf.summary.image('input', x_image, 4) # First layer of weights with tf.name_scope("layer1"): W1 = tf.get_variable("W1", shape=[input_size, hidden_layer_neurons], initializer=tf.contrib.layers.xavier_initializer()) layer1 = tf.matmul(X, W1) layer1_act = tf.nn.tanh(layer1) tf.summary.histogram("weights", W1) tf.summary.histogram("layer", layer1) tf.summary.histogram("activations", layer1_act) # Second layer of weights with tf.name_scope("layer2"): W2 = tf.get_variable("W2", shape=[hidden_layer_neurons, hidden_layer_neurons], initializer=tf.contrib.layers.xavier_initializer()) layer2 = tf.matmul(layer1_act, W2) layer2_act = tf.nn.tanh(layer2) tf.summary.histogram("weights", W2) tf.summary.histogram("layer", layer2) tf.summary.histogram("activations", layer2_act) # Third layer of weights with tf.name_scope("layer3"): W3 = tf.get_variable("W3", shape=[hidden_layer_neurons, hidden_layer_neurons], initializer=tf.contrib.layers.xavier_initializer()) layer3 = tf.matmul(layer2_act, W3) layer3_act = tf.nn.tanh(layer3) tf.summary.histogram("weights", W3) tf.summary.histogram("layer", layer3) tf.summary.histogram("activations", layer3_act) # Fourth layer of weights with tf.name_scope("layer4"): W4 = tf.get_variable("W4", shape=[hidden_layer_neurons, output_size], initializer=tf.contrib.layers.xavier_initializer()) Qpred = tf.nn.softmax(tf.matmul(layer3_act, W4)) # Bug fixed: Qpred = tf.nn.softmax(tf.matmul(layer3, W4)) tf.summary.histogram("weights", W4) tf.summary.histogram("Qpred", Qpred) # We need to define the parts of the network needed for learning a policy Y = tf.placeholder(tf.float32, [None, output_size], name="input_y") advantages = tf.placeholder(tf.float32, name="reward_signal") # Loss function # Sum (Ai*logp(yi|xi)) log_lik = -Y * tf.log(Qpred) loss = tf.reduce_mean(tf.reduce_sum(log_lik * advantages, axis=1)) tf.summary.scalar("Q", tf.reduce_mean(Qpred)) tf.summary.scalar("Y", tf.reduce_mean(Y)) tf.summary.scalar("log_likelihood", tf.reduce_mean(log_lik)) tf.summary.scalar("loss", loss) # Learning train = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss) </code></pre>
42,318,280
2
5
null
2017-02-18 12:35:35.013 UTC
97
2021-01-19 08:05:59.33 UTC
2017-02-19 02:08:58.46 UTC
null
364,772
null
364,772
null
1
159
tensorflow|histogram|tensorboard
54,312
<p>It appears that the network hasn't learned anything in the layers one to three. The last layer does change, so that means that there either may be something wrong with the gradients (if you're tampering with them manually), you're constraining learning to the last layer by optimizing only its weights or the last layer really 'eats up' all error. It could also be that only biases are learned. The network appears to learn something though, but it might not be using its full potential. More context would be needed here, but playing around with the learning rate (e.g. using a smaller one) might be worth a shot.</p> <p>In general, histograms display the number of occurrences of a value relative to each other values. Simply speaking, if the possible values are in a range of <code>0..9</code> and you see a spike of amount <code>10</code> on the value <code>0</code>, this means that 10 inputs assume the value <code>0</code>; in contrast, if the histogram shows a plateau of <code>1</code> for all values of <code>0..9</code>, it means that for 10 inputs, each possible value <code>0..9</code> occurs <em>exactly</em> once. You can also use histograms to visualize probability distributions when you normalize all histogram values by their total sum; if you do that, you'll intuitively obtain the likelihood with which a certain value (on the x axis) will appear (compared to other inputs).</p> <p>Now for <code>layer1/weights</code>, the plateau means that:</p> <ul> <li>most of the weights are in the range of -0.15 to 0.15</li> <li>it is (mostly) equally likely for a weight to have any of these values, i.e. they are (almost) uniformly distributed</li> </ul> <p>Said differently, almost the same number of weights have the values <code>-0.15</code>, <code>0.0</code>, <code>0.15</code> and everything in between. There are some weights having slightly smaller or higher values. So in short, this simply looks like the weights have been initialized using a uniform distribution with zero mean and value range <code>-0.15..0.15</code> ... give or take. If you do indeed use uniform initialization, then this is typical when the network has not been trained yet.</p> <p>In comparison, <code>layer1/activations</code> forms a bell curve (gaussian)-like shape: The values are centered around a specific value, in this case <code>0</code>, but they may also be greater or smaller than that (equally likely so, since it's symmetric). Most values appear close around the mean of <code>0</code>, but values do range from <code>-0.8</code> to <code>0.8</code>. I assume that the <code>layer1/activations</code> is taken as the distribution over all layer outputs in a batch. You can see that the values do change over time.</p> <p>The layer 4 histogram doesn't tell me anything specific. From the shape, it's just showing that some weight values around <code>-0.1</code>, <code>0.05</code> and <code>0.25</code> tend to be occur with a higher probability; a reason <em>could</em> be, that different parts of each neuron there actually pick up the same information and are basically redundant. This can mean that you could actually use a smaller network or that your network has the potential to learn more distinguishing features in order to prevent overfitting. These are just assumptions though.</p> <p>Also, as already stated in the comments below, do add bias units. By leaving them out, you are forcefully constraining your network to a possibly invalid solution.</p>
17,997,990
SQL Get all records older than 30 days
<p>Now I've found a lot of similar SO questions including an old one of mine, but what I'm trying to do is get any record older than 30 days but my table field is unix_timestamp. All other examples seem to use DateTime fields or something. Tried some and couldn't get them to work.</p> <p>This definitely doesn't work below. Also I don't want a date between a between date, I want all records after 30 days from a unix timestamp stored in the database. I'm trying to prune inactive users.</p> <p>simple examples.. doesn't work. </p> <pre><code>SELECT * from profiles WHERE last_login &lt; UNIX_TIMESTAMP(NOW(), INTERVAL 30 DAY) </code></pre> <p>And tried this</p> <pre><code>SELECT * from profiles WHERE UNIX_TIMESTAMP(last_login - INTERVAL 30 DAY) </code></pre> <p>Not too strong at complex date queries. Any help is appreciate. </p>
17,998,488
3
3
null
2013-08-01 15:15:35.717 UTC
11
2019-03-22 02:50:51.433 UTC
2019-03-22 02:50:51.12 UTC
null
3,975,214
null
330,987
null
1
82
sql|postgresql
102,197
<p>Try something like:</p> <pre><code>SELECT * from profiles WHERE to_timestamp(last_login) &lt; NOW() - INTERVAL '30 days' </code></pre> <p>Quote from the manual:</p> <blockquote> <p>A single-argument to_timestamp function is also available; it accepts a double precision argument and converts from Unix epoch (seconds since 1970-01-01 00:00:00+00) to timestamp with time zone. (Integer Unix epochs are implicitly cast to double precision.)</p> </blockquote>
16,614,246
Eclipse: how/where to include a text file in a Java project?
<p>I'm using Eclipse (SDK v4.2.2) to develop a Java project (Java SE, v1.6) that currently reads information from external .txt files as part of methods used many times in a single pass. I would like to include these files in my project, making them "native" to make the project independent of external files. I don't know where to add the files into the project or how to add them so they can easily be used by the appropriate method.</p> <p>Searching on Google has not turned up any solid guidance, nor have I found any similar questions on this site. If someone knows how to do add files and where they should go, I'd greatly appreciate any advice or even a point in the right direction. Also, if any additional information about the code or the .txt files is required, I'll be happy to provide as much detail as possible.</p> <p>UPDATE 5/20/2013: I've managed to get the text files into the classpath; they're located in a package under a folder called 'resc' (per dharam's advice), which is on the same classpath level as the 'src' folder in which my code is packaged. Now I just need to figure out how to get my code to read these files properly. Specifically, I want to read a selected file into a two-dimensional array, reading line-by-line and splitting each line by a delimiter. Prior to packaging the files directly within the workspace, I used a BufferedReader to do this:</p> <pre><code>public static List&lt;String[]&gt; fileRead(String d) { // Initialize File 'f' with path completed by passed-in String 'd'. File f = new File("&lt;incomplete directory path goes here&gt;" + d); // Initialize some variables to be used shortly. String s = null; List&lt;String&gt; a = new ArrayList&lt;String&gt;(); List&lt;String[]&gt; l = new ArrayList&lt;String[]&gt;(); try { // Use new BufferedReader 'in' to read in 'f'. BufferedReader in = new BufferedReader(new FileReader(f)); // Read the first line into String 's'. s = in.readLine(); // So long as 's' is NOT null... while(s != null) { // Split the current line, using semi-colons as delimiters, and store in 'a'. // Convert 'a' to array 'aSplit', then add 'aSplit' to 'l'. a = Arrays.asList(s.split("\\s*;\\s*")); String[] aSplit = a.toArray(new String[2]); l.add(aSplit); // Read next line of 'f'. s = in.readLine(); } // Once finished, close 'in'. in.close(); } catch (IOException e) { // If problems occur during 'try' code, catch exception and include StackTrace. e.printStackTrace(); } // Return value of 'l'. return l; } </code></pre> <p>If I decide to use the methods described in the link provided by Pangea (using getResourceAsStream to read in the file as an InputStream), I'm not sure how I would be able to achieve the same results. Would someone be able to help me find a solution on this same question, or should I ask about that issue into a different question to prevent headaches?</p>
16,614,326
4
2
null
2013-05-17 16:51:19.533 UTC
1
2015-05-03 08:26:31.877 UTC
2015-05-03 08:26:31.877 UTC
null
2,083,854
null
2,240,234
null
1
3
java|eclipse
38,171
<p>You can put them anywhere you wish, but depends on what you want to achieve through putting the file.</p> <p>A general practice is to create a folder with name resc/resource and put files in it. Include the folder in classpath.</p>
2,260,105
Simple Python Regex Find pattern
<p>I have a sentence. I want to find all occurrences of a word that start with a specific character in that sentence. I am very new to programming and Python, but from the little I know, this sounds like a Regex question.</p> <p>What is the pattern match code that will let me find all words that match my pattern?</p> <p>Many thanks in advance,</p> <p>Brock</p>
2,260,117
5
0
null
2010-02-14 04:08:53.257 UTC
6
2010-02-14 04:20:26.743 UTC
null
null
null
null
155,406
null
1
13
python|regex
50,586
<pre><code>import re print re.findall(r'\bv\w+', thesentence) </code></pre> <p>will print every word in the sentence that starts with <code>'v'</code>, for example.</p> <p>Using the <code>split</code> method of strings, as another answer suggests, would not identify <em>words</em>, but space-separated chunks that may include punctuation. This <code>re</code>-based solution <em>does</em> identify words (letters and digits, net of punctuation).</p>
2,068,159
Could not load file or assembly 'Microsoft.mshtml ... Strong name validation failed
<p>I made a WPF/C# program and I am using the internet control for WYSIWYG HTML editing.</p> <p>it is a regular Executable program.</p> <p>it works on most computers however some computers are giving me the following error.</p> <blockquote> <p>Could not load file or assembly 'Microsoft.mshtml, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Strong name validation failed.</p> </blockquote> <p>The 'Microsoft.mshtml.dll' file is distributed with the program. It is with all of the other required dlls in the same folder as the exe file.</p> <hr> <p>Here is the output from <code>Fuslogvw</code></p> <pre><code>*** Assembly Binder Log Entry (1/14/2010 @ 6:36:51 PM) *** The operation failed. Bind result: hr = 0x80070002. The system cannot find the file specified. Assembly manager loaded from: c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll Running under executable C:\Documents and Settings\office\Desktop\Database\DATABASE.exe --- A detailed error log follows. === Pre-bind state information === LOG: User = CAMPUSREMOTE\office LOG: DisplayName = Microsoft.mshtml, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a (Fully-specified) LOG: Appbase = file:///C:/Documents and Settings/office/Desktop/Database/ LOG: Initial PrivatePath = NULL LOG: Dynamic Base = NULL LOG: Cache Base = NULL LOG: AppName = DATABASE.exe Calling assembly : ChabadOnCampusMainFrontEnd, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null. === LOG: Start binding of native image Microsoft.mshtml, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. WRN: No matching native image found. </code></pre> <p>Thanks</p>
2,408,325
5
0
null
2010-01-14 22:56:59.68 UTC
7
2022-01-17 08:22:43.257 UTC
2010-05-05 20:47:44.587 UTC
null
41,956
null
200,669
null
1
21
c#|interop|mshtml
51,157
<p>Verify that the 'Microsoft.mshtml.dll' file, distributed with the program is the PIA file and not an Office file. Some sites claims that the Office files are "delay signed" and the PIA file (installed with the VS installation) is a signed copy. on my computer I have 3 different versions of 'Microsoft.mshtml.dll' file, (same file-size, but different content):</p> <ol> <li><p>"c:\Program Files\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office11\Microsoft.mshtml.dll" </p></li> <li><p>"c:\Program Files\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office12\Microsoft.mshtml.dll"</p></li> <li><p>"c:\Program Files\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll" </p></li> </ol> <p>Remove "Microsoft.mshtml.dll" reference from the project. Use "Add Reference", ".Net" tab, select the PIA file, use "copy loacal" option. (It worked for me . . .)</p> <p>Atara</p>
1,681,449
What do you monitor with JMX in your production Java application?
<p>This question is not about how JMX works or what JMX does. This question is about applications of JMX in a standard application server environment in production. It is not for specific server either. </p> <p>What do you monitor with JMX in production environment that runs standard stack of Java EE services: database access (JDBC and JPA), session EJBs, JMS, web server, web services, AJAX-enabled services?</p>
4,261,634
5
0
null
2009-11-05 15:53:06.187 UTC
23
2016-03-07 20:22:43.363 UTC
2016-03-07 20:22:43.363 UTC
null
63,550
null
59,470
null
1
32
java|performance|jakarta-ee|monitoring|jmx
9,965
<p>At the <strong>JVM</strong> level, I monitor the garbage collection duration per minute,</p> <p>At the <strong>Servlet Container</strong> level, I monitor the number of requests, number of exceptions (4xx &amp; 5xx codes) , sum of request duration per minute,</p> <p>At the <strong>SOAP</strong> level, I monitor the number of invocations, number of exceptions &amp; sum of invocations per operation and per minute,</p> <p>At the <strong>Web MVC Framework</strong> level, I monitor the number of invocations, number of exceptions &amp; sum of invocations per action and per minute,</p> <p>For the pools (<strong>datasource,thread pool / executor service</strong>), I monitor the active count,</p> <p>For the <strong>JMS</strong> connections, I monitor the number of sent &amp; received messages per minute, and the number of active receivers,</p> <p>For <strong>EhCache</strong>, I monitor the number of entries in the cache, the number of hits &amp; miss per minute,</p> <p>At the <strong>business application</strong> level, I developped an @Profiled annotation to monitor the number of invocations, number of exceptions and total duration per minute.</p> <p>If you are interested in such kind of metrics, we developed many JMX extras (dbcp, util.concurrent, jms, @profiled annotation) and packaged all this with Spring XML namespace based configuration, Hyperic HQ plugins, monitoring jsp pages, etc</p> <p>The details are here : <a href="http://code.google.com/p/xebia-france/wiki/XebiaManagementExtras" rel="noreferrer">http://code.google.com/p/xebia-france/wiki/XebiaManagementExtras</a> .</p> <p>All this code is licensed under the business friendly Open Source Apache Software License 2, deployed on Maven Central Repository, downloadable as a jar and available on a Google Code Subversion server to be integrated the way you want.</p> <p>Hope this helps,</p> <p>Cyrille (Xebia)</p>
1,768,023
How to use "\" in a string without making it an escape sequence - C#?
<p>I'm sure this is something really basic that I don't know but how do I make it not recognize "\" as an escape sequence inside a string</p> <p>I'm trying to type in a path and it thinks it is an escape sequence</p>
1,768,041
6
1
null
2009-11-20 02:53:29.503 UTC
6
2014-06-01 14:25:05.053 UTC
null
null
null
null
185,292
null
1
16
c#|escaping
52,864
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/ms228362.aspx" rel="noreferrer">Verbatim String Literals</a>:</p> <pre><code>//Initialize with a regular string literal. string oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0"; // Initialize with a verbatim string literal. string newPath = @"c:\Program Files\Microsoft Visual Studio 9.0"; ↑ </code></pre>
2,046,761
What is object graph in java?
<p>Whenever I study Garbage Collector I hear the term object Graph. What does it mean exactly?</p>
2,046,774
6
0
null
2010-01-12 04:44:58.977 UTC
8
2016-07-04 06:53:47.187 UTC
2014-09-18 03:39:37.407 UTC
null
512,251
null
240,698
null
1
34
java
24,373
<p>Objects have references to other objects which may in turn have references to more objects including the starting object. This creates a graph of objects, useful in reachability analysis. For instance, if the starting object is reachable (say it's in a thread's local stack) then all objects in the graph are reachable and an exact garbage collector cannot harvest any of these objects. Similarly, starting with a set of live objects (roots) if we create a list of all reachable objects, all other objects are garbage - fair game for collection.</p>
2,176,675
Visual studio - precompile - dotless
<p>I wonder if there is a way to precompile <code>*.less</code> files(<a href="http://www.dotlesscss.org/" rel="nofollow noreferrer">http://www.dotlesscss.org/</a>) with visual studio. </p> <p>The site gives me a <code>dotless.compiler.exe</code> but I am not sure how to hook this up to visual studio. I am looking for a solution for both Webforms and ASP.NET MVC.</p>
2,181,543
7
0
null
2010-02-01 12:47:34.06 UTC
13
2013-08-30 22:26:01.38 UTC
2013-08-30 22:26:01.38 UTC
null
422,353
null
145,117
null
1
26
asp.net-mvc|visual-studio-2008|less|dotless
12,387
<p>Depending on your build environment, you can kick off <code>dotless.Compiler.exe</code> as a build task.</p> <p>For example, using a Pre-Build task in Visual Studio (all 1 line):</p> <pre><code>$(SolutionDir)Tools\dotLess\dotless.compiler.exe -m $(ProjectDir)content\css\site.less $(ProjectDir)content\css\site.css </code></pre> <p>The macros (<code>$(SolutionDir)</code>, etc) allow a bit of flexibility to project and file locations. Rather than using the standard <code>.less</code> files, simply reference the new <code>.css</code> files in your markup.</p>
2,016,433
C# GUI programming for beginners: Where to start?
<p>I'm a C++/Java developer and have no idea about .Net or GUIs. I need to develop a windows app for 2000/XP/Vista/7.</p> <p>I think I've come to conclusion that C# is the best and the fastest way to go (please correct me if I'm wrong). What do you recommend? Which GUI approach should I learn? (Forms? Any other stuff?)</p> <p>Is it the best way to compile in .Net 2.0 mode? It's going to be an application for the public to download.</p>
2,016,508
9
0
null
2010-01-06 21:35:27.797 UTC
9
2016-09-17 14:15:04.307 UTC
2016-09-17 14:15:04.307 UTC
null
3,980,929
null
63,898
null
1
23
c#|wpf|winforms|user-interface
89,185
<p>In my personal development experience Windows Forms is just about as easy as it gets when it comes to rapidly deploying a GUI application on Windows. WPF is of course another option, but using it would likely require you spend some time familiarizing yourself with XAML. Windows Forms look and feel like a lot of the available GUI options for Java, it's just much better than the majority of them, in my opinion.</p> <p>If you want the fastest possible GUI development time in .NET, Windows Forms is it.</p>
1,933,210
C++/CLI: why should I use it?
<p>I'm pretty familiar with C++, so I considered learning .NET and all its derivatives (especially C#).</p> <p>Along the way I bumped into C++/CLI, and I want to know if there is any specific use for that language? Is it just suppose to be a intermediate language for transforming from native C++ to C#?</p> <p>Another question that popped to my head is why are there still so many programming languages in .NET framework? (VB, C++/CLI, C#...)</p>
1,933,259
9
4
null
2009-12-19 15:35:34.9 UTC
13
2022-05-12 16:07:29.527 UTC
2015-02-24 16:36:57.993 UTC
null
3,204,551
null
215,769
null
1
61
c#|.net|c++-cli
32,262
<p>Yes, C++/CLI has a very specific target usage, the language (and its compiler, most of all) makes it very easy to write code that needs to interop with unmanaged code. It has built-in support for marshaling between managed and unmanaged types. It used to be called IJW (It Just Works), nowadays called C++ Interop. Other languages need to use the P/Invoke marshaller which can be inefficient and has limited capabilities compared to what C++/CLI can do.</p> <p>If you need to interop with native C++, classes that have instance functions and need the new and delete keywords to create/destroy an instance of the class then you have no choice but use C++/CLI. Pinvoke cannot do that, only the C++ compiler knows how much memory to allocate and how to correctly thunk the <code>this</code> pointer for an instance function.</p> <p>The .NET framework contains code that was written in C++/CLI, notably in System.Data and WPF's PresentationCore. If you don't have unmanaged interop needs or don't have to work with a legacy code base then there are few reasons to select C++/CLI. C# or VB.NET are the better choices. C++/CLI's feature set got frozen around 2005, it has no support for more recent additions like lambdas or Linq syntax. Nor does the IDE support many of the bells and whistles available in the C# and VB.NET IDEs. Notable is that VS2010 will initially ship without IntelliSense support for C++/CLI. A bit of a kiss-of-death there.</p> <p>UPDATE: revived in VS2012, IntelliSense support is back. Not in the least thanks to C++/CX, a language extension that simplifies writing WinRT apps in C++. Its syntax is very similar to C++/CLI. The Windows Forms project templates were removed, the designer however still works. The new debugging engine in VS2012 doesn't support C++/CLI, you have to turn on the "Managed Compatibility Mode" option in Tools + Options, Debugging, General.</p>
1,954,426
Javascript equivalent of PHP's list()
<p>Really like that function.</p> <pre><code>$matches = array('12', 'watt'); list($value, $unit) = $matches; </code></pre> <p>Is there a Javascript equivalent of that?</p>
1,954,453
9
12
null
2009-12-23 18:11:52.677 UTC
7
2019-12-05 00:39:29.97 UTC
2011-06-15 20:18:22.723 UTC
null
271,577
null
138,023
null
1
71
php|javascript|list|phpjs
40,397
<p>There is, in 'newer' versions of Javascript: <a href="https://developer.mozilla.org/en/New_in_JavaScript_1.7#Destructuring_assignment" rel="noreferrer">Destructuring assignment - Javascript 1.7</a>. It's probably only supported in Mozilla-based browsers, and maybe in Rhino.</p> <pre><code>var a = 1; var b = 3; [a, b] = [b, a]; </code></pre> <p>EDIT: <del>actually it wouldn't surprise me if the V8 Javascript library (and thus Chrome) supports this. But don't count on it either </del> Now <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Browser_compatibility" rel="noreferrer">supported</a> in all modern browsers(<strong>except IE</strong>, of course).</p>
2,076,398
Unit testing large blocks of code (mappings, translation, etc)
<p>We unit test most of our business logic, but are stuck on how best to test some of our large service tasks and import/export routines. For example, consider the export of payroll data from one system to a 3rd party system. To export the data in the format the company needs, we need to hit ~40 tables, which creates a nightmare situation for creating test data and mocking out dependencies.</p> <p>For example, consider the following (a subset of ~3500 lines of export code):</p> <pre><code>public void ExportPaychecks() { var pays = _pays.GetPaysForCurrentDate(); foreach (PayObject pay in pays) { WriteHeaderRow(pay); if (pay.IsFirstCheck) { WriteDetailRowType1(pay); } } } private void WriteHeaderRow(PayObject pay) { //do lots more stuff } private void WriteDetailRowType1(PayObject pay) { //do lots more stuff } </code></pre> <p>We only have the one public method in this particular export class - ExportPaychecks(). That's really the only action that makes any sense to someone calling this class ... everything else is private (~80 private functions). We could make them public for testing, but then we'd need to mock them to test each one separately (i.e. you can't test ExportPaychecks in a vacuum without mocking the WriteHeaderRow function. This is a huge pain too.</p> <p>Since this is a single export, for a single vendor, moving logic into the Domain doesn't make sense. The logic has no domain significance outside of this particular class. As a test, we built out unit tests which had close to 100% code coverage ... but this required an insane amount of test data typed into stub/mock objects, plus over 7000 lines of code due to stubbing/mocking our many dependencies. </p> <p>As a maker of HRIS software, we have hundreds of exports and imports. Do other companies REALLY unit test this type of thing? If so, are there any shortcuts to make it less painful? I'm half tempted to say "no unit testing the import/export routines" and just implement integration testing later.</p> <p><strong>Update</strong> - thanks for the answers all. One thing I'd love to see is an example, as I'm still not seeing how someone can turn something like a large file export into an easily testable block of code without turning the code into a mess.</p>
2,129,862
10
1
null
2010-01-16 06:15:59.697 UTC
11
2010-01-25 02:21:38.887 UTC
2010-01-18 06:45:11.127 UTC
null
72,536
null
72,536
null
1
28
c#|unit-testing|etl
3,718
<p>This is one of those areas where the concept of mocking everything falls over. Certainly testing each method in isolation would be a "better" way of doing things, but compare the effort of making test versions of all your methods to that of pointing the code at a test database (reset at the start of each test run if necessary).</p> <p>That is the approach I'm using with code that has a lot of complex interactions between components, and it works well enough. As each test will run more code, you are more likely to need to step through with the debugger to find exactly where something went wrong, but you get the primary benefit of unit tests (knowing that something went wrong) without putting in significant additional effort.</p>
1,654,846
In C#, how can I know the file type from a byte[]?
<p>I have a byte array filled from a file uploaded. But, in another part of the code, I need to know this file type uploaded from the byte[] so I can render the correct content-type to browser!</p> <p>Thanks!!</p>
1,654,870
10
0
null
2009-10-31 16:25:42.827 UTC
11
2022-07-20 08:21:07.773 UTC
null
null
null
null
60,286
null
1
39
asp.net-mvc|c#-3.0|bytearray|content-type
81,686
<p>Not sure, but maybe you should investigate about <a href="http://www.garykessler.net/library/file_sigs.html" rel="noreferrer">magic numbers</a>. </p> <p><strong>Update:</strong> Reading about it, I don't think it's very reliable though.</p>
2,265,922
How to check if an object is not an array?
<p>So i have a function that needs to check if an argument is an object, but this fails because:</p> <pre><code>typeof [] // returns 'object' </code></pre> <p>This is a classic javascript gotcha, but i cant remember what to do to actually accept objects, but not arrays.</p>
2,265,941
10
1
null
2010-02-15 12:38:53.72 UTC
4
2022-08-24 13:07:16.313 UTC
null
null
null
null
269,620
null
1
48
javascript|types|typeof
58,267
<p>Try something like this :</p> <pre><code>obj.constructor.toString().indexOf("Array") != -1 </code></pre> <p>or (even better)</p> <pre><code>obj instanceof Array </code></pre>
2,335,813
How to inflate one view with a layout
<p>I have a layout defined in XML. It contains also: </p> <pre><code>&lt;RelativeLayout android:id="@+id/item" android:layout_width="fill_parent" android:layout_height="wrap_content" /&gt; </code></pre> <p>I would like to inflate this RelativeView with other XML layout file. I may use different layouts depending on a situation. How should I do it? I was trying different variations of </p> <pre><code>RelativeLayout item = (RelativeLayout) findViewById(R.id.item); item.inflate(...) </code></pre> <p>But none of them worked fine.</p>
2,336,047
15
0
null
2010-02-25 16:47:51.28 UTC
54
2022-04-02 09:27:59.81 UTC
2017-06-20 07:49:30.207 UTC
null
7,214,631
null
58,862
null
1
241
android|android-layout|layout-inflater|android-inflate
447,688
<p>I'm not sure I have followed your question- are you trying to attach a child view to the RelativeLayout? If so you want to do something along the lines of:</p> <pre><code>RelativeLayout item = (RelativeLayout)findViewById(R.id.item); View child = getLayoutInflater().inflate(R.layout.child, null); item.addView(child); </code></pre>
17,839,989
"Expression must evaluate to a node-set."
<p>I have a problem</p> <p>My XML File is here:</p> <pre><code>&lt;altinkaynak&gt; &lt;DOVIZ&gt; &lt;ADI&gt;Tarih&lt;/ADI&gt; &lt;ALIS&gt;24.07.2013 18:59:45&lt;/ALIS&gt; &lt;SATIS/&gt; &lt;/DOVIZ&gt; &lt;DOVIZ&gt; &lt;ADI&gt;USD&lt;/ADI&gt; &lt;ALIS&gt;1.9120&lt;/ALIS&gt; &lt;SATIS&gt;1.9220&lt;/SATIS&gt; &lt;/DOVIZ&gt; &lt;DOVIZ&gt; &lt;ADI&gt;EUR&lt;/ADI&gt; &lt;ALIS&gt;2.5280&lt;/ALIS&gt; &lt;SATIS&gt;2.5430&lt;/SATIS&gt; &lt;/DOVIZ&gt; &lt;/altinkaynak&gt; </code></pre> <p>How am I parse this XML file </p> <p>I coded that way but I got a parse error message;</p> <pre><code>if (tip == DövizKuruTipi2.Alış) Line 44: return Decimal.Parse(doc.SelectNodes("//ALTINKAYNAK/DOVIZ/ADI=" + dovizKuru2 + "/ALIS")[0].InnerText.Replace('.', ',')); </code></pre> <blockquote> <p>Expression must evaluate to a node-set</p> </blockquote>
17,840,143
4
0
null
2013-07-24 16:40:48.433 UTC
3
2021-07-23 09:14:08.93 UTC
2020-05-05 13:10:51.123 UTC
null
465,053
null
2,615,526
null
1
17
c#|xml|xpath
59,063
<p><strong>Reason for the Error</strong></p> <p>As per the error message, <code>.SelectNodes()</code> requires that the <code>xpath</code> string parameter evaluates to a node set, e.g. this xpath will return an <code>XmlNodeList</code> containing 3 nodes:</p> <pre><code>var nodeSet = document.SelectNodes("/altinkaynak/DOVIZ"); </code></pre> <p>Supplying an <code>xpath</code> which returns a single node is also acceptable - the returned <code>XmlNodeList</code> will just have a single node:</p> <pre><code>var nodeSet = document.SelectNodes("(/altinkaynak/DOVIZ)[1]"); </code></pre> <p>However, it is not possible to return non-node values, such as scalar expressions:</p> <pre><code>var nodeSet = document.SelectNodes("count(/altinkaynak/DOVIZ)"); </code></pre> <blockquote> <p>Error: Expression must evaluate to a node-set.</p> </blockquote> <p>Instead for <code>XmlDocument</code>, you would need to create a navigator, compile an expression, and evaluate it:</p> <pre><code> var navigator = document.CreateNavigator(); var expr = navigator.Compile("count(/altinkaynak/DOVIZ)"); var count = navigator.Evaluate(expr); // 3 (nodes) </code></pre> <p>If you switch your Xml parsing stack from using <code>XmlDocument</code> to a <code>Linq to Xml</code> <code>XDocument</code> there is a <a href="https://stackoverflow.com/a/27583026/314291">much more concise way</a> to evaluate scalar expressions:</p> <pre><code>var count = xele.XPathEvaluate("count(/altinkaynak/DOVIZ)"); </code></pre> <p><strong>Badly formed Xpath</strong></p> <p>This same error (<code>Expression must evaluate to a node-set</code>) is also frequently returned for <code>xpath</code>s which are invalid altogether</p> <pre><code> var nodeSet = document.SelectNodes("{Insert some really badly formed xpath here!}"); </code></pre> <blockquote> <p>Error: Expression must evaluate to a node-set.</p> </blockquote> <p><strong>OP's Question</strong> </p> <p>You have an error in your Xpath. What you probably want is this:</p> <pre><code>doc.SelectNodes("//ALTINKAYNAK/DOVIZ[ADI='" + dovizKuru2 + "']/ALIS") // ... </code></pre> <p>which will return the <code>ALIS</code> child of the <code>DOVIZ</code> element which has an <code>ADI</code> child with a value of <code>dovizKuru2</code> (which is presumably a variable for currency such as <code>USD</code>)</p>
18,011,902
Pass a parameter to a fixture function
<p>I am using py.test to test some DLL code wrapped in a python class MyTester. For validating purpose I need to log some test data during the tests and do more processing afterwards. As I have many test_... files I want to reuse the tester object creation (instance of MyTester) for most of my tests.</p> <p>As the tester object is the one which got the references to the DLL's variables and functions I need to pass a list of the DLL's variables to the tester object for each of the test files (variables to be logged are the same for a test_... file). The content of the list is used to log the specified data.</p> <p>My idea is to do it somehow like this:</p> <pre><code>import pytest class MyTester(): def __init__(self, arg = [&quot;var0&quot;, &quot;var1&quot;]): self.arg = arg # self.use_arg_to_init_logging_part() def dothis(self): print &quot;this&quot; def dothat(self): print &quot;that&quot; # located in conftest.py (because other test will reuse it) @pytest.fixture() def tester(request): &quot;&quot;&quot; create tester object &quot;&quot;&quot; # how to use the list below for arg? _tester = MyTester() return _tester # located in test_...py # @pytest.mark.usefixtures(&quot;tester&quot;) class TestIt(): # def __init__(self): # self.args_for_tester = [&quot;var1&quot;, &quot;var2&quot;] # # how to pass this list to the tester fixture? def test_tc1(self, tester): tester.dothis() assert 0 # for demo purpose def test_tc2(self, tester): tester.dothat() assert 0 # for demo purpose </code></pre> <p>Is it possible to achieve it like this or is there even a more elegant way?</p> <p>Usually I could do it for each test method with some kind of setup function (xUnit-style). But I want to gain some kind of reuse. Does anyone know if this is possible with fixtures at all?</p> <p>I know I can do something like this: (from the docs)</p> <pre><code>@pytest.fixture(scope=&quot;module&quot;, params=[&quot;merlinux.eu&quot;, &quot;mail.python.org&quot;]) </code></pre> <p>But I need to the parametrization directly in the test module. <strong>Is it possible to access the params attribute of the fixture from the test module?</strong></p>
28,570,677
9
0
null
2013-08-02 08:11:46.26 UTC
67
2021-12-14 20:05:07.6 UTC
2021-12-14 20:05:07.6 UTC
null
1,824,781
null
1,504,082
null
1
207
python|fixtures|pytest
189,597
<p><strong>Update:</strong> Since this the accepted answer to this question and still gets upvoted sometimes, I should add an update. Although my original answer (below) was the only way to do this in older versions of pytest as <a href="https://stackoverflow.com/a/33879151/982257">others</a> have <a href="https://stackoverflow.com/a/60148972/982257">noted</a> pytest now supports indirect parametrization of fixtures. For example you can do something like this (via @imiric):</p> <pre><code># test_parameterized_fixture.py import pytest class MyTester: def __init__(self, x): self.x = x def dothis(self): assert self.x @pytest.fixture def tester(request): """Create tester object""" return MyTester(request.param) class TestIt: @pytest.mark.parametrize('tester', [True, False], indirect=['tester']) def test_tc1(self, tester): tester.dothis() assert 1 </code></pre> <pre><code>$ pytest -v test_parameterized_fixture.py ================================================================================= test session starts ================================================================================= platform cygwin -- Python 3.6.8, pytest-5.3.1, py-1.8.0, pluggy-0.13.1 -- /usr/bin/python3 cachedir: .pytest_cache rootdir: . collected 2 items test_parameterized_fixture.py::TestIt::test_tc1[True] PASSED [ 50%] test_parameterized_fixture.py::TestIt::test_tc1[False] FAILED </code></pre> <p>However, although this form of indirect parametrization is explicit, as @Yukihiko Shinoda <a href="https://stackoverflow.com/a/60148972/982257">points out</a> it now supports a form of implicit indirect parametrization (though I couldn't find any obvious reference to this in the official docs):</p> <pre><code># test_parameterized_fixture2.py import pytest class MyTester: def __init__(self, x): self.x = x def dothis(self): assert self.x @pytest.fixture def tester(tester_arg): """Create tester object""" return MyTester(tester_arg) class TestIt: @pytest.mark.parametrize('tester_arg', [True, False]) def test_tc1(self, tester): tester.dothis() assert 1 </code></pre> <pre><code>$ pytest -v test_parameterized_fixture2.py ================================================================================= test session starts ================================================================================= platform cygwin -- Python 3.6.8, pytest-5.3.1, py-1.8.0, pluggy-0.13.1 -- /usr/bin/python3 cachedir: .pytest_cache rootdir: . collected 2 items test_parameterized_fixture2.py::TestIt::test_tc1[True] PASSED [ 50%] test_parameterized_fixture2.py::TestIt::test_tc1[False] FAILED </code></pre> <p>I don't know exactly what are the semantics of this form, but it seems that <code>pytest.mark.parametrize</code> recognizes that although the <code>test_tc1</code> method does not take an argument named <code>tester_arg</code>, the <code>tester</code> fixture that it's using does, so it passes the parametrized argument on through the <code>tester</code> fixture.</p> <hr> <p>I had a similar problem--I have a fixture called <code>test_package</code>, and I later wanted to be able to pass an optional argument to that fixture when running it in specific tests. For example:</p> <pre><code>@pytest.fixture() def test_package(request, version='1.0'): ... request.addfinalizer(fin) ... return package </code></pre> <p>(It doesn't matter for these purposes what the fixture does or what type of object the returned <code>package</code>) is.</p> <p>It would then be desirable to somehow use this fixture in a test function in such a way that I can also specify the <code>version</code> argument to that fixture to use with that test. This is currently not possible, though might make a nice feature.</p> <p>In the meantime it was easy enough to make my fixture simply return a <em>function</em> that does all the work the fixture previously did, but allows me to specify the <code>version</code> argument:</p> <pre><code>@pytest.fixture() def test_package(request): def make_test_package(version='1.0'): ... request.addfinalizer(fin) ... return test_package return make_test_package </code></pre> <p>Now I can use this in my test function like:</p> <pre><code>def test_install_package(test_package): package = test_package(version='1.1') ... assert ... </code></pre> <p>and so on.</p> <p>The OP's attempted solution was headed in the right direction, and as @hpk42's <a href="https://stackoverflow.com/a/18098713/982257">answer</a> suggests, the <code>MyTester.__init__</code> could just store off a reference to the request like:</p> <pre><code>class MyTester(object): def __init__(self, request, arg=["var0", "var1"]): self.request = request self.arg = arg # self.use_arg_to_init_logging_part() def dothis(self): print "this" def dothat(self): print "that" </code></pre> <p>Then use this to implement the fixture like:</p> <pre><code>@pytest.fixture() def tester(request): """ create tester object """ # how to use the list below for arg? _tester = MyTester(request) return _tester </code></pre> <p>If desired the <code>MyTester</code> class could be restructured a bit so that its <code>.args</code> attribute can be updated after it has been created, to tweak the behavior for individual tests.</p>
41,951,978
AmazonS3Client(credentials) is deprecated
<p>I'm trying to read the files available on Amazon S3, as the question explains the problem. I couldn't find an alternative call for the deprecated constructor.</p> <p>Here's the code:</p> <pre><code>private String AccessKeyID = "xxxxxxxxxxxxxxxxxxxx"; private String SecretAccessKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; private static String bucketName = "documentcontainer"; private static String keyName = "test"; //private static String uploadFileName = "/PATH TO FILE WHICH WANT TO UPLOAD/abc.txt"; AWSCredentials credentials = new BasicAWSCredentials(AccessKeyID, SecretAccessKey); void downloadfile() throws IOException { // Problem lies here - AmazonS3Client is deprecated AmazonS3 s3client = new AmazonS3Client(credentials); try { System.out.println("Downloading an object..."); S3Object s3object = s3client.getObject(new GetObjectRequest( bucketName, keyName)); System.out.println("Content-Type: " + s3object.getObjectMetadata().getContentType()); InputStream input = s3object.getObjectContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); while (true) { String line = reader.readLine(); if (line == null) break; System.out.println(" " + line); } System.out.println(); } catch (AmazonServiceException ase) { //do something } catch (AmazonClientException ace) { // do something } } </code></pre> <p>Any help? If more explanation is needed please mention it. I have checked on the sample code provided in .zip file of SDK, and it's the same.</p>
41,952,575
7
5
null
2017-01-31 07:31:36.923 UTC
12
2022-07-25 21:21:21.517 UTC
2019-02-25 07:42:17.233 UTC
null
1,192,381
null
5,730,203
null
1
73
java|amazon-web-services|amazon-s3|aws-sdk|deprecated
62,202
<p>You can either use <a href="http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/AmazonS3ClientBuilder.html" rel="nofollow noreferrer">AmazonS3ClientBuilder</a> or <a href="http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/client/builder/AwsClientBuilder.html" rel="nofollow noreferrer">AwsClientBuilder</a> as alternatives.</p> <p>For S3, simplest would be with <code>AmazonS3ClientBuilder</code>.</p> <pre><code>BasicAWSCredentials creds = new BasicAWSCredentials(&quot;access_key&quot;, &quot;secret_key&quot;); AmazonS3 s3Client = AmazonS3ClientBuilder .standard() .withCredentials(new AWSStaticCredentialsProvider(creds)) .build(); </code></pre>
6,674,667
How to customize date picker's width and height in android
<p>Can anybody tell me how to customize the date picker's width and height in android?</p>
7,082,983
3
0
null
2011-07-13 05:59:56.077 UTC
5
2015-12-30 13:11:09.553 UTC
2014-05-09 10:00:39.003 UTC
null
3,338,050
null
426,344
null
1
20
android
43,982
<p>In your layout's <em>XML</em> file, change the <code>android:layout_height</code> and <code>android:layout_width</code> attributes. I am assuming you are currently using either <em>fill_parent</em> or <em>wrap_content</em> for the values of these attributes, however you can be more specific - defining the exact or scaled pixel value.</p> <p>For example, <code>android:layout_width="15dp"</code> will set the width at a scalable value of 15. You can change 15 to whatever you want. If you want to set a specific pixel size, you can use, for example, <code>15px</code>.</p>
6,827,299
R apply function with multiple parameters
<p>I have a function <code>f(var1, var2)</code> in R. Suppose we set <code>var2 = 1</code> and now I want to apply the function <code>f()</code> to the list <code>L</code>. Basically I want to get a new list L* with the outputs </p> <pre><code>[f(L[1],1),f(L[2],1),...,f(L[n],1)] </code></pre> <p>How do I do this with either <code>apply</code>, <code>mapply</code> or <code>lapply</code>? </p>
6,827,519
3
1
null
2011-07-26 08:33:21.477 UTC
59
2022-01-24 03:45:23.3 UTC
2016-05-17 13:18:06.73 UTC
null
792,066
null
851,530
null
1
161
r
272,783
<p>Just pass var2 as an extra argument to one of the apply functions.</p> <pre><code>mylist &lt;- list(a=1,b=2,c=3) myfxn &lt;- function(var1,var2){ var1*var2 } var2 &lt;- 2 sapply(mylist,myfxn,var2=var2) </code></pre> <p>This passes the same <code>var2</code> to every call of <code>myfxn</code>. If instead you want each call of <code>myfxn</code> to get the 1st/2nd/3rd/etc. element of both <code>mylist</code> and <code>var2</code>, then you're in <code>mapply</code>'s domain.</p>
15,666,258
Phonegap build - Open external page in InAppBrowser or childbrowser with no toolbar and close it?
<ol> <li><p>I want to open an external page in the InAppBrowser or childbrowser, where I don't show any toolbar and where I can have a button in my externalpage that closes the browser and returns to the app from where I opened the browser. So how to close when you don ́t have a DONE button? I have seen that if I have var ref = window.open(encodeURI(url), '_self', 'location=yes'); then it is possible to close the browser with ref.close(); but if I use that in the externalpage that I opened it doesn't work, it is not closing the browser? </p></li> <li><p>Is there any way to autorotate any of them if I have set the orientation to portrait in the config file? I know that you can autorotate the child browser if you do it manually, not through the build service. Or do I have to set the orientation to both? </p></li> <li><p>I have tested all different ways to open the ChildBrowser and the InAppBrowser and I cant really see any big difference between them? Can the InAppBrowser use native feature wile the ChildBrowser can't or?</p></li> </ol>
15,701,122
2
0
null
2013-03-27 18:09:54.437 UTC
8
2014-10-08 05:51:24.827 UTC
null
null
null
null
354,901
null
1
9
childbrowser|phonegap-build|inappbrowser
22,621
<p>OK, problem 1 to close is solved. This is what I use to open an external page in the InAppBrowser. From the page that I load in the InAppBrowser, I can close the InAppBrowser itself, returning to my app from where I opened the browser.</p> <p>Create a page on your server - closeInAppBrowser.html that is just an empty html page, it doesn´t do anything</p> <p>I open the browser with this:</p> <pre><code>&lt;a href="#" onclick="openInAppBrowserBlank('http://www.mypage.asp?userId=1');"&gt;open InAppBrowser&lt;/a&gt; var ref = null; function openInAppBrowserBlank(url) { try { ref = window.open(encodeURI(url),'_blank','location=no'); //encode is needed if you want to send a variable with your link if not you can use ref = window.open(url,'_blank','location=no'); ref.addEventListener('loadstop', LoadStop); ref.addEventListener('exit', Close); } catch (err) { alert(err); } } function LoadStop(event) { if(event.url == "http://www.mypage.com/closeInAppBrowser.html"){ // alert("fun load stop runs"); ref.close(); } } function Close(event) { ref.removeEventListener('loadstop', LoadStop); ref.removeEventListener('exit', Close); } </code></pre> <p>And to close the InAppBrowser from the page that I opened in the browser(<a href="http://www.mypage.asp">http://www.mypage.asp</a>) I have a button-link like this.</p> <pre><code>&lt;a href="http://www.mypage.com/closeInAppBrowser.html"&gt;&lt;/a&gt; </code></pre> <p>I hope it helps somebody else!</p>
5,329,661
Is there any way to accelerate the mousemove event?
<p>I wrote a little drawing script (canvas) for this website: <a href="http://scri.ch/" rel="noreferrer">http://scri.ch/</a></p> <p>When you click on the document, every <code>mousemove</code> event basically executes the following:<br> - Get coordinates.<br> - <code>context.lineTo()</code> between this point and the previous one<br> - <code>context.stroke()</code> the line</p> <p>As you can see, if you move the cursor very fast, the event isn’t triggering enough (depending on your CPU / Browser / etc.), and a straight line is traced.</p> <p>In pseudocode:</p> <pre><code>window.addEventListener('mousemove', function(e){ myContext.lineTo(e.pageX, e.pageY); myContext.stroke(); }, false); </code></pre> <p>This is a known problem, and the solution is fine, but I would like to optimize that.</p> <p>So instead of <code>stroke()</code> each time a mousemove event is triggered, I put the new coordinates inside an array queue, and regularly draw / empty it with a timer.</p> <p>In pseudocode:</p> <pre><code>var coordsQueue = []; window.addEventListener('mousemove', function(e){ coordsQueue.push([e.pageX, e.pageY]); }, false); function drawLoop(){ window.setTimeout(function(){ var coords; while (coords = coordsQueue.shift()) { myContext.lineTo(coords[0], coords[1]); } myContext.stroke(); drawLoop(); }, 1000); // For testing purposes } </code></pre> <p>But it did not improve the line. So I tried to only draw a point on <code>mousemove</code>. Same result: too much space between the points.</p> <p>It made me realize that the first code block is efficient enough, it is just the <code>mousemove</code> event that is triggering too slowly.</p> <p>So, after having myself spent some time to implement a useless optimization, it’s your turn: is there a way to optimize the <code>mousemove</code> triggering speed in DOM scripting?</p> <p>Is it possible to “request” the mouse position at any time?</p> <p>Thanks for your advices!</p>
5,329,939
2
1
null
2011-03-16 18:02:24.52 UTC
9
2015-03-30 13:31:46.903 UTC
2015-03-30 13:31:46.903 UTC
null
292,500
null
292,500
null
1
16
javascript|dom|mousemove
6,780
<p>If you want to increase the reporting frequency, I'm afraid you're out of luck. Mice only report their position to the operating system <em>n</em> times per second, and I think <em>n</em> is usually less than 100. (If anyone can confirm this with actual specs, feel free to add them!)</p> <p>So in order to get a smooth line, you'll have to come up with some sort of interpolation scheme. There's a whole lot of literature on the topic; I recommend <a href="http://en.wikipedia.org/wiki/Monotone_cubic_interpolation">monotone cubic interpolation</a> because it's local, simple to implement, and very stable (no overshoot).</p> <p>Then, once you've computed the spline, you can approximate it with line segments short enough so that it looks smooth, or you can go all-out and write your own <a href="http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm">Bresenham</a> algorithm to draw it.</p> <p>If all this is worth it for a simple drawing application... that's for you to decide, of course.</p>
5,115,088
Turn off Eclipse formatter for selected code area?
<p>When I <kbd>ctrl</kbd>+<kbd>shift</kbd>+<kbd>f</kbd> up the project code, its doing its job just fine, everywhere.</p> <p>But its messing the CSS, specially those filter parts and adding bunch of spaces.</p> <p>Also how do I specify some portion of Java code to not be formated by that command ?</p>
5,115,143
2
2
null
2011-02-25 08:27:58.3 UTC
4
2018-03-10 21:10:02.527 UTC
2011-02-25 08:31:17.423 UTC
null
40,342
user562350
null
null
1
30
java|eclipse|code-formatting
31,314
<p>To prevent specific portions of Java code from being formatted, go to "Window > Preferences > Java > Code Style > Formatter". Click the "Edit..." button, go to the "Off/On Tags" tab and enable the tags. Afterwards, you can simply embed those tags in Java code to disable the formatting in-between them. If you don't change the default tags, something like this will do :</p> <pre><code>//@formatter:off this. portion.of(code ); // will not be touched by the formatter //@formatter:on but this will be reformatted. </code></pre> <p>IIRC, this option only exists since Eclipse 3.6.</p> <p>As for css code, if you have installed Eclipse WTP, go to "Window > Preferences > Web > CSS Files > Editor" and you will find some basic formatting options there.</p>
16,509,020
Uncaught TypeError: Cannot read property 'width' of null
<p>I actually don't know what's happened because it was working last night. Anyway, I'm trying to make a drawing application with html5 and javascript. This is the first time I've properly looked at JS and created something with it so I've got my code from various tutorials and help from other friends a.k.a I'm a n00b. I used the following:</p> <ol> <li>github.com/jaseemkp/paint-app-with-save-facility</li> <li>codetheory.in/different-tools-for-our-sketching-application/</li> <li>HTML5 Canvas Cookbook - Chapter 6: Interacting with the Canvas: Attaching Event Listeners to Shapes and Regions - Creating a drawing application. (I got the save feature from this)</li> </ol> <p>When I test my work in chrome I get the error </p> <blockquote> <p>"Uncaught TypeError: Cannot read property 'width' of null"</p> </blockquote> <p>which refers to line 4 of my script file which is</p> <pre><code>var b_width = canvas.width, b_height = canvas.height; </code></pre> <p>I was trying to fiddle around with it to add a text feature but just couldn't get it to work so I just undone everything and now it's producing this error.</p> <p>Full script:</p> <pre><code>var canvas = document.getElementById("realCanvas"); var tmp_board = document.getElementById("tempCanvas"); var b_width = canvas.width, b_height = canvas.height; var ctx = canvas.getContext("2d"); var tmp_ctx = tmp_board.getContext("2d"); var x, y; var saved = false, hold = false, fill = false, stroke = true, tool = 'rectangle'; var data = {"rectangle": [], "circle": [], "line": []}; function curr_tool(selected){tool = selected;} function attributes(){ if (document.getElementById("fill").checked) fill = true; else fill = false; if (document.getElementById("outline").checked) stroke = true; else stroke = false; } function clears(){ ctx.clearRect(0, 0, b_width, b_height); tmp_ctx.clearRect(0, 0, b_width, b_height); data = {"rectangle": [], "circle": [], "line": []}; } //colour function function color(scolor){ tmp_ctx.strokeStyle = scolor; if (document.getElementById("fill").checked) tmp_ctx.fillStyle = scolor; } //line tmp_board.onmousedown = function(e) { attributes(); hold = true; x = e.pageX - this.offsetLeft; y = e.pageY -this.offsetTop; begin_x = x; begin_y = y; tmp_ctx.beginPath(); tmp_ctx.moveTo(begin_x, begin_y); } tmp_board.onmousemove = function(e) { if (x == null || y == null) { return; } if(hold){ x = e.pageX - this.offsetLeft; y = e.pageY - this.offsetTop; Draw(); } } tmp_board.onmouseup = function(e) { ctx.drawImage(tmp_board,0, 0); tmp_ctx.clearRect(0, 0, tmp_board.width, tmp_board.height); end_x = x; end_y = y; x = null; y = null; Draw(); hold = false; } //draw function function Draw(){ //rectangle if (tool == 'rectangle'){ if(!x &amp;&amp; !y){ data.rectangle.push({"x": begin_x, "y": begin_y, "width": end_x-begin_x, "height": end_y-begin_y, "stroke": stroke, "strk_clr": tmp_ctx.strokeStyle, "fill": fill, "fill_clr": tmp_ctx.fillStyle }); return; } tmp_ctx.clearRect(0, 0, b_width, b_height); tmp_ctx.beginPath(); if(stroke) tmp_ctx.strokeRect(begin_x, begin_y, x-begin_x, y-begin_y); tmp_ctx.lineWidth = $('#selWidth').val(); if(fill) tmp_ctx.fillRect(begin_x, begin_y, x-begin_x, y-begin_y); tmp_ctx.closePath(); } //line if (tool == 'line'){ if(!x &amp;&amp; !y){ data.line.push({"x": begin_x, "y": begin_y, "width": end_x-begin_x, "height": end_y-begin_y, "stroke": stroke, "strk_clr": tmp_ctx.strokeStyle,}); return; } tmp_ctx.beginPath(); if(stroke) tmp_ctx.strokeRect(begin_x, begin_y, x-begin_x, y-begin_y); tmp_ctx.clearRect(0, 0, tmp_board.width, tmp_board.height); tmp_ctx.beginPath(); tmp_ctx.moveTo(begin_x, begin_y); tmp_ctx.lineTo(x, y); tmp_ctx.lineWidth = $('#selWidth').val(); tmp_ctx.stroke(); tmp_ctx.closePath(); } //circle else if (tool == 'circle'){ if(!x &amp;&amp; !y){ data.circle.push({"x": begin_x, "y": begin_y, "radius": end_x-begin_x, "stroke": stroke, "strk_clr": tmp_ctx.strokeStyle, "fill": fill, "fill_clr": tmp_ctx.fillStyle }); return; } tmp_ctx.clearRect(0, 0, b_width, b_height); tmp_ctx.beginPath(); tmp_ctx.arc(begin_x, begin_y, Math.abs(x-begin_x), 0 , 2 * Math.PI, false); if(stroke) tmp_ctx.stroke(); tmp_ctx.lineWidth = $('#selWidth').val(); if(fill) tmp_ctx.fill(); tmp_ctx.closePath(); } } //save function //set up image of canvas function getCanvasImg(canvas){ var img = new Image(); img.src = canvas.toDataURL(); return img; } //get image of canvas window.onload = function (){ var events = new Events("tempCanvas"); var canvas = events.getCanvas(); var context = events.getContext(); } //open image of canvas in new window in click of button document.getElementById("saveButton").addEventListener("click", function(evt){ //open new window with saved image, right click and save window.open(canvas.toDataURL()); }, false); </code></pre> <p>Full HTML</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;LogoMakr&lt;/title&gt; &lt;link rel="stylesheet" href="style.css" type="text/css"&gt; &lt;script src="jquery.min.js"&gt;&lt;/script&gt; &lt;script src="script.js"&gt; &lt;/script&gt; &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="tools"&gt; &lt;button type="button" id="saveButton" value="Save"&gt;Save&lt;/button&gt; &lt;button type="button" onclick="clears()"&gt;CLEAR&lt;/button&gt; &lt;button type="button" onclick="curr_tool('rectangle')"&gt;Rectangle&lt;/button&gt; &lt;button type="button" onclick="curr_tool('circle')"&gt;Circle&lt;/button&gt; &lt;button type="button" onclick="curr_tool('line')"&gt;Line&lt;/button&gt; &lt;/div&gt; &lt;table id="table1" &gt; &lt;tr&gt; &lt;tr&gt; &lt;td&gt;&lt;button onclick="color('black')" style="background-color: black; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button onclick="color('white')" style="background-color: white; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button onclick="color('green')" style="background-color: green; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button onclick="color('blue')" style="background-color: blue; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button onclick="color('yellow')" style="background-color: yellow; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button onclick="color('red')" style="background-color: red; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button onclick="color('#ff6600')" style="background-color: #ff6600; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button onclick="color('#663300')" style="background-color: #663300; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button onclick="color('grey')" style="background-color: grey; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button onclick="color('#FF6699')" style="background-color: #FF6699; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;button onclick="color('#8b00ff')" style="background-color: #8b00ff; height: 20px; width: 20px;"&gt;&lt;/button&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="checkbox" id="fill"/&gt;Fill&lt;/td&gt; &lt;td&gt;&lt;input type="checkbox" id="outline" checked="checked"/&gt;Outline&lt;/td&gt; &lt;td&gt;Line Width:&lt;/td&gt; &lt;td&gt;&lt;select id="selWidth"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="5" selected="selected"&gt;5 &lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="9" &gt;9&lt;/option&gt; &lt;option value="11"&gt;11&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div&gt; &lt;canvas id="realCanvas" width="680" height="460" style=" background-color: #ffffff; z-index: 0" &gt;&lt;/canvas&gt; &lt;canvas id="tempCanvas" width="680" height="460" style="z-index: 1"&gt;&lt;/canvas&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS</p> <pre><code>#realCanvas, #tempCanvas { position: absolute; left:280px; top:50px; border: 5px solid; cursor: crosshair; } #table1{ position: absolute; left:400px; top:5px; } </code></pre> <p>When I've uploaded it to a <a href="http://logomakr.bugs3.com/" rel="noreferrer">free server</a>, I've got different errors though. Oh I'm so confused, I hope there's someone out there that can make sense of it all :/</p> <p>Thanks in advance!</p>
16,509,031
2
0
null
2013-05-12 15:38:41.45 UTC
1
2018-08-26 18:01:54.28 UTC
null
null
null
user2375124
null
null
1
10
javascript|html|canvas
43,900
<p>You're importing your script <strong>before</strong> the browser has had a chance to parse the document body. As such, the <code>&lt;canvas&gt;</code> element doesn't exist at the point you seek it by its "id" value.</p> <p>Since you're importing jQuery anyway, you can employ a "ready" handler, but then you'll have some issues with the way you're attaching event handlers. Your attribute-based event handlers rely on those handler functions being global, which they won't be if you put them in a "ready" handler.</p> <p>Much simpler, however, would be to simply move your <code>&lt;script&gt;</code> tag (or both of them) to the very end of the <code>&lt;body&gt;</code>. That way the DOM will be parsed and your <code>getElementById()</code> calls should work. Lots of people advise that putting scripts at the end of the <code>&lt;body&gt;</code> should be considered a best practice anyway.</p> <p>Failing that, I suppose what you could do is something like this, changing the declarations at the top of your script: </p> <pre><code>$(function() { $.extend(window, { canvas: document.getElementById("realCanvas"), tmp_board: document.getElementById("tempCanvas"), b_width: canvas.width, b_height = canvas.height, ctx: canvas.getContext("2d"), tmp_ctx: tmp_board.getContext("2d"), x: undefined, y: undefined, saved: false, hold: false, fill: false, stroke: true, tool: 'rectangle', data: {"rectangle": [], "circle": [], "line": []} }); }); </code></pre> <p>It'd be better to either adopt jQuery fully and use it to assign event handlers, or else just don't bother importing it.</p>
174,730
What is the best way to validate a credit card in PHP?
<p>Given a credit card number and no additional information, what is the best way in PHP to determine whether or not it is a valid number?</p> <p>Right now I need something that will work with American Express, Discover, MasterCard, and Visa, but it might be helpful if it will also work with other types.</p>
174,750
8
0
null
2008-10-06 15:21:39.2 UTC
49
2020-06-01 20:22:14.057 UTC
2008-10-06 15:26:14.51 UTC
Rich B
5,640
lencioni
18,986
null
1
73
php|validation|e-commerce|numbers|credit-card
80,982
<p>There are three parts to the validation of the card number:</p> <ol> <li><strong>PATTERN</strong> - does it match an issuers pattern (e.g. VISA/Mastercard/etc.)</li> <li><strong>CHECKSUM</strong> - does it actually check-sum (e.g. not just 13 random numbers after "34" to make it an AMEX card number)</li> <li><strong>REALLY EXISTS</strong> - does it actually have an associated account (you are unlikely to get this without a merchant account)</li> </ol> <h2>Pattern</h2> <ul> <li>MASTERCARD Prefix=51-55, Length=16 (Mod10 checksummed)</li> <li>VISA Prefix=4, Length=13 or 16 (Mod10)</li> <li>AMEX Prefix=34 or 37, Length=15 (Mod10)</li> <li>Diners Club/Carte Prefix=300-305, 36 or 38, Length=14 (Mod10)</li> <li>Discover Prefix=6011,622126-622925,644-649,65, Length=16, (Mod10)</li> <li>etc. (<a href="http://en.wikipedia.org/wiki/Bank_card_number#Issuer_identification_number_.28IIN.29" rel="noreferrer">detailed list of prefixes</a>)</li> </ul> <h2>Checksum</h2> <p>Most cards use the Luhn algorithm for checksums:</p> <p><a href="http://en.wikipedia.org/wiki/Luhn_algorithm" rel="noreferrer">Luhn Algorithm described on Wikipedia</a></p> <p>There are links to many implementations on the Wikipedia link, including PHP:</p> <pre><code>&lt;? /* Luhn algorithm number checker - (c) 2005-2008 shaman - www.planzero.org * * This code has been released into the public domain, however please * * give credit to the original author where possible. */ function luhn_check($number) { // Strip any non-digits (useful for credit card numbers with spaces and hyphens) $number=preg_replace('/\D/', '', $number); // Set the string length and parity $number_length=strlen($number); $parity=$number_length % 2; // Loop through each digit and do the maths $total=0; for ($i=0; $i&lt;$number_length; $i++) { $digit=$number[$i]; // Multiply alternate digits by two if ($i % 2 == $parity) { $digit*=2; // If the sum is two digits, add them together (in effect) if ($digit &gt; 9) { $digit-=9; } } // Total up the digits $total+=$digit; } // If the total mod 10 equals 0, the number is valid return ($total % 10 == 0) ? TRUE : FALSE; } ?&gt; </code></pre>