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
26,358,684
Converting BufferedReader to JSONObject or Map
<p>My code sends a GET request to a server,</p> <pre><code> URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("User-Agent", USER_AGENT); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); </code></pre> <p>I get a BufferedReader object that prints,</p> <pre><code>{ "status": "ERROR", "errorCode": "MISSING_PARAMS", "errorMessage": null, "requestId": "20141014181739_11625805172", "downstreamModuleErrorCode": null, "object": [ "activity_code", "activity_name", "points", "frequency", "strategy", "vsa_app_access_token" ] } </code></pre> <p>I want to get a JSONOBject or a Map from this. I tried converting this into a String and manipulating it. But it's not that easy to do. Please help.</p>
26,358,942
5
3
null
2014-10-14 10:36:28.83 UTC
6
2020-05-14 12:52:51.537 UTC
2014-10-14 10:55:07.247 UTC
null
2,413,303
null
4,079,056
null
1
12
java|json|map|httprequest
44,332
<p>First do it as string. you can use custom librarys for that like</p> <pre><code> String message = org.apache.commons.io.IOUtils.toString(rd); </code></pre> <p>or a StringBuilder</p> <pre><code> StringBuilder sb = new StringBuilder(); String line; br = new BufferedReader(new InputStreamReader(is)); while ((line = br.readLine()) != null) { sb.append(line); } </code></pre> <p>Then you can parse it. Since it's an object because of the "{" (array begin and ends with []) you need to create an JSONObject.</p> <pre><code>JSONObject json = new JSONObject(sb.toString()); </code></pre> <p>then you can access your elements with</p> <pre><code>//{ "status": "ERROR", "errorCode": "MISSING_PARAMS", "errorMessage": null, "requestId": "20141014181739_11625805172", "downstreamModuleErrorCode": null, "object": [ "activity_code", "activity_name", "points", "frequency", "strategy", "vsa_app_access_token" ]} json.getString("status"); </code></pre> <p>or the array with</p> <pre><code>JSONArray jsonArray = new JSONArray(json.getString("object")); </code></pre> <p>or you use the method getJSONArray()</p> <pre><code>JSONArray jsonArray = json.getJSONArray("object"); </code></pre>
23,207,168
A semantics for Bash scripts?
<p>More than any other language I know, I've "learned" Bash by Googling every time I need some little thing. Consequently, I can patchwork together little scripts that appear to work. However, I don't <em>really</em> know what's going on, and I was hoping for a more formal introduction to Bash as a programming language. For example: What is the evaluation order? what are the scoping rules? What is the typing discipline, e.g. is everything a string? What is the state of the program -- is it a key-value assignment of strings to variable names; is there more than that, e.g. the stack? Is there a heap? And so on.</p> <p>I thought to consult the GNU Bash manual for this kind of insight, but it doesn't seem to be what I want; it's more of a laundry list of syntactic sugar rather than an explanation of the core semantic model. The million-and-one "bash tutorials" online are only worse. Perhaps I should first study <code>sh</code>, and understand Bash as a syntactic sugar on top of this? I don't know if this is an accurate model, though.</p> <p>Any suggestions?</p> <p><strong>EDIT:</strong> I've been asked to provide examples of what ideally I'm looking for. A rather extreme example of what I would consider a "formal semantics" is <a href="http://cs.brown.edu/~sk/Publications/Papers/Published/gsk-essence-javascript/paper.pdf" rel="noreferrer">this paper on "the essence of JavaScript"</a>. Perhaps a slightly less formal example is the <a href="http://www.haskell.org/definition/haskell2010.pdf" rel="noreferrer">Haskell 2010 report</a>.</p>
23,208,014
3
9
null
2014-04-21 22:32:11.817 UTC
50
2021-02-22 20:28:34.2 UTC
2021-02-22 20:28:34.2 UTC
null
3,650,362
null
229,792
null
1
90
bash
3,764
<p>A shell is an interface for the operating system. It is usually a more-or-less robust programming language in its own right, but with features designed to make it easy to interact specifically with the operating system and filesystem. The POSIX shell's (hereafter referred to just as "the shell") semantics are a bit of a mutt, combining some features of LISP (s-expressions have a lot in common with shell <a href="http://mywiki.wooledge.org/WordSplitting" rel="noreferrer">word splitting</a>) and C (much of the shell's <a href="http://mywiki.wooledge.org/ArithmeticExpression" rel="noreferrer">arithmetic syntax</a> semantics comes from C).</p> <p>The other root of the shell's syntax comes from its upbringing as a mishmash of individual UNIX utilities. Most of what are often builtins in the shell can actually be implemented as external commands. It throws many shell neophytes for a loop when they realize that <code>/bin/[</code> exists on many systems.</p> <pre><code>$ if '/bin/[' -f '/bin/['; then echo t; fi # Tested as-is on OS X, without the `]` t </code></pre> <p>wat?</p> <p>This makes a lot more sense if you look at how a shell is implemented. Here's an implementation I did as an exercise. It's in Python, but I hope that's not a hangup for anyone. It's not terribly robust, but it is instructive:</p> <pre><code>#!/usr/bin/env python from __future__ import print_function import os, sys '''Hacky barebones shell.''' try: input=raw_input except NameError: pass def main(): while True: cmd = input('prompt&gt; ') args = cmd.split() if not args: continue cpid = os.fork() if cpid == 0: # We're in a child process os.execl(args[0], *args) else: os.waitpid(cpid, 0) if __name__ == '__main__': main() </code></pre> <p>I hope the above makes it clear that the execution model of a shell is pretty much:</p> <pre><code>1. Expand words. 2. Assume the first word is a command. 3. Execute that command with the following words as arguments. </code></pre> <p>Expansion, command resolution, execution. All of the shell's semantics are bound up in one of these three things, although they're far richer than the implementation I wrote above.</p> <p>Not all commands <code>fork</code>. In fact, there are a handful of commands that don't make <a href="https://unix.stackexchange.com/questions/50058/what-is-the-point-of-the-cd-external-command">a ton of sense</a> implemented as externals (such that they would have to <code>fork</code>), but even those are often available as externals for strict POSIX compliance.</p> <p>Bash builds upon this base by adding new features and keywords to enhance the POSIX shell. It is nearly compatible with sh, and bash is so ubiquitous that some script authors go years without realizing that a script may not actually work on a POSIXly strict system. (I also wonder how people can care so much about the semantics and style of one programming language, and so little for the semantics and style of the shell, but I diverge.)</p> <h2>Order of evaluation</h2> <p>This is a bit of a trick question: Bash interprets expressions in its primary syntax from left to right, but in its arithmetic syntax it follows C precedence. Expressions differ from <em>expansions</em>, though. From the <code>EXPANSION</code> section of the bash manual:</p> <blockquote> <p>The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and pathname expansion.</p> </blockquote> <p>If you understand wordsplitting, pathname expansion and parameter expansion, you are well on your way to understanding most of what bash does. Note that pathname expansion coming after wordsplitting is critical, because it ensures that a file with whitespace in its name can still be matched by a glob. This is why good use of glob expansions is better than <a href="http://mywiki.wooledge.org/ParsingLs" rel="noreferrer">parsing commands</a>, in general.</p> <h2>Scope</h2> <h3>Function scope</h3> <p>Much like old ECMAscript, the shell has dynamic scope unless you explicitly declare names within a function.</p> <pre><code>$ foo() { echo $x; } $ bar() { local x; echo $x; } $ foo $ bar $ x=123 $ foo 123 $ bar $ … </code></pre> <h3>Environment and process "scope"</h3> <p>Subshells inherit the variables of their parent shells, but other kinds of processes don't inherit unexported names.</p> <pre><code>$ x=123 $ ( echo $x ) 123 $ bash -c 'echo $x' $ export x $ bash -c 'echo $x' 123 $ y=123 bash -c 'echo $y' # another way to transiently export a name 123 </code></pre> <p>You can combine these scoping rules:</p> <pre><code>$ foo() { &gt; local -x bar=123 # Export foo, but only in this scope &gt; bash -c 'echo $bar' &gt; } $ foo 123 $ echo $bar $ </code></pre> <h2>Typing discipline</h2> <p>Um, types. Yeah. Bash really doesn't have types, and everything expands to a string (or perhaps a <em>word</em> would be more appropriate.) But let's examine the different types of expansions.</p> <h3>Strings</h3> <p>Pretty much anything can be treated as a string. Barewords in bash are strings whose meaning depends entirely on the expansion applied to it.</p> No expansion <p>It may be worthwhile to demonstrate that a bare word really is just a word, and that quotes change nothing about that.</p> <pre><code>$ echo foo foo $ 'echo' foo foo $ "echo" foo foo </code></pre> Substring expansion <pre><code>$ fail='echoes' $ set -x # So we can see what's going on $ "${fail:0:-2}" Hello World + echo Hello World Hello World </code></pre> <p>For more on expansions, read the <code>Parameter Expansion</code> section of the manual. It's quite powerful.</p> <h3>Integers and arithmetic expressions</h3> <p>You can imbue names with the integer attribute to tell the shell to treat the right hand side of assignment expressions as arithmetic. Then, when the parameter expands it will be evaluated as integer math before expanding to … a string.</p> <pre><code>$ foo=10+10 $ echo $foo 10+10 $ declare -i foo $ foo=$foo # Must re-evaluate the assignment $ echo $foo 20 $ echo "${foo:0:1}" # Still just a string 2 </code></pre> <h3>Arrays</h3> Arguments and Positional Parameters <p>Before talking about arrays it might be worth discussing positional parameters. The arguments to a shell script can be accessed using numbered parameters, <code>$1</code>, <code>$2</code>, <code>$3</code>, etc. You can access all these parameters at once using <code>"$@"</code>, which expansion has many things in common with arrays. You can set and change the positional parameters using the <code>set</code> or <code>shift</code> builtins, or simply by invoking the shell or a shell function with these parameters:</p> <pre><code>$ bash -c 'for ((i=1;i&lt;=$#;i++)); do &gt; printf "\$%d =&gt; %s\n" "$i" "${@:i:1}" &gt; done' -- foo bar baz $1 =&gt; foo $2 =&gt; bar $3 =&gt; baz $ showpp() { &gt; local i &gt; for ((i=1;i&lt;=$#;i++)); do &gt; printf '$%d =&gt; %s\n' "$i" "${@:i:1}" &gt; done &gt; } $ showpp foo bar baz $1 =&gt; foo $2 =&gt; bar $3 =&gt; baz $ showshift() { &gt; shift 3 &gt; showpp "$@" &gt; } $ showshift foo bar baz biz quux xyzzy $1 =&gt; biz $2 =&gt; quux $3 =&gt; xyzzy </code></pre> <p>The bash manual also sometimes refers to <code>$0</code> as a positional parameter. I find this confusing, because it doesn't include it in the argument count <code>$#</code>, but it is a numbered parameter, so meh. <code>$0</code> is the name of the shell or the current shell script.</p> Arrays <p>The syntax of arrays is modeled after positional parameters, so it's mostly healthy to think of arrays as a named kind of "external positional parameters", if you like. Arrays can be declared using the following approaches:</p> <pre><code>$ foo=( element0 element1 element2 ) $ bar[3]=element3 $ baz=( [12]=element12 [0]=element0 ) </code></pre> <p>You can access array elements by index:</p> <pre><code>$ echo "${foo[1]}" element1 </code></pre> <p>You can slice arrays:</p> <pre><code>$ printf '"%s"\n' "${foo[@]:1}" "element1" "element2" </code></pre> <p>If you treat an array as a normal parameter, you'll get the zeroth index.</p> <pre><code>$ echo "$baz" element0 $ echo "$bar" # Even if the zeroth index isn't set $ … </code></pre> <p>If you use quotes or backslashes to prevent wordsplitting, the array will maintain the specified wordsplitting:</p> <pre><code>$ foo=( 'elementa b c' 'd e f' ) $ echo "${#foo[@]}" 2 </code></pre> <p>The main difference between arrays and positional parameters are:</p> <ol> <li>Positional parameters are not sparse. If <code>$12</code> is set, you can be sure <code>$11</code> is set, too. (It could be set to the empty string, but <code>$#</code> will not be smaller than 12.) If <code>"${arr[12]}"</code> is set, there's no guarantee that <code>"${arr[11]}"</code> is set, and the length of the array could be as small as 1.</li> <li>The zeroth element of an array is unambiguously the zeroth element of that array. In positional parameters, the zeroth element is not the <em>first argument</em>, but the name of the shell or shell script.</li> <li>To <code>shift</code> an array, you have to slice and reassign it, like <code>arr=( "${arr[@]:1}" )</code>. You could also do <code>unset arr[0]</code>, but that would make the first element at index 1.</li> <li>Arrays can be shared implicitly between shell functions as globals, but you have to explicitly pass positional parameters to a shell function for it to see those.</li> </ol> <p>It's often convenient to use pathname expansions to create arrays of filenames:</p> <pre><code>$ dirs=( */ ) </code></pre> <h3>Commands</h3> <p>Commands are key, but they're also covered in better depth than I can by the manual. Read the <code>SHELL GRAMMAR</code> section. The different kinds of commands are:</p> <ol> <li>Simple Commands (e.g. <code>$ startx</code>)</li> <li>Pipelines (e.g. <code>$ yes | make config</code>) (lol)</li> <li>Lists (e.g. <code>$ grep -qF foo file &amp;&amp; sed 's/foo/bar/' file &gt; newfile</code>)</li> <li>Compound Commands (e.g. <code>$ ( cd -P /var/www/webroot &amp;&amp; echo "webroot is $PWD" )</code>)</li> <li>Coprocesses (Complex, no example)</li> <li>Functions (A named compound command that can be treated as a simple command)</li> </ol> <h2>Execution Model</h2> <p>The execution model of course involves both a heap and a stack. This is endemic to all UNIX programs. Bash also has a call stack for shell functions, visible via nested use of the <code>caller</code> builtin. </p> <p>References:</p> <ol> <li>The <code>SHELL GRAMMAR</code> section of the bash manual</li> <li>The <a href="http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html" rel="noreferrer">XCU Shell Command Language</a> documentation</li> <li>The <a href="http://mywiki.wooledge.org/BashGuide" rel="noreferrer">Bash Guide</a> on Greycat's wiki.</li> <li><a href="http://www.apuebook.com/" rel="noreferrer">Advanced Programming in the UNIX Environment</a></li> </ol> <p>Please make comments if you want me to expand further in a specific direction.</p>
31,683,788
Android manifest attribute not allowed here
<p>I have several manifest errors regarding some attributes . I have not made any changes to the manifest the application generated automatically yet i get several errors. *( I'm using Android Studio 1.2.2)</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.iustinian.girlfriendsolver" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="14" android:targetSdkVersion="22" /&gt; &lt;application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name="com.example.iustinian.girlfriendsolver.MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>-For the xmlns:android attribute i get "URL not registered " -For android versionCode , versionName , allowBackup , label and theme I get "attribute not allowed here " </p> <p>I took a look at the manifest documentation and couldn't find an answer . For example the allowBackup attribute is placed exactly like the documentation specifies .</p> <p>Edit: after looking around some more I found that at android:theme "@style/AppTheme" I get a no resource matches the given name . This is the only thing that shows up in the Gradle Build . I have cleaned and rebuilt the project several times .</p>
36,805,891
13
6
null
2015-07-28 17:57:14.157 UTC
2
2022-05-31 02:48:32.37 UTC
2015-07-28 19:23:30.473 UTC
null
3,652,652
null
3,652,652
null
1
29
android|xml|android-studio|manifest
76,433
<p>Just Close your manifest file and reopen it. It worked for me.</p>
4,963,919
What to keep in mind when developing a multi-tenant asp.net MVC application?
<p>Good afternoon - I have a pretty general question today - I've been tasked with creating a web application to manage some basic information on customers. It's a very simple application, but what I don't know is what to keep in mind to develop the site around supporting multiple users at their own domains or subdomains of our url?</p> <p>How would I restrict users from logging in to each others portion of the app?</p> <p>I've seen mention of database scoping in similar questions on Stack Overflow, could anybody elaborate on best practices for an implementation like this?</p> <p>Are there any new features in MVC3 to support multi-tenancy? I am facing this issue with MVC2 and my eCommerce site where we decided we wanted it white-labeled and customizable for multiple shop owners, and don't know where to begin in implementing these features in an existing application. Any input is appreciated.</p> <p><em>edit</em></p> <p>To elaborate on multi-tenancy, what I mean - in the context of a store for example, multiple users sign up for their own store at www.mystore.com and are each given a unique subdomain to access their own instance of the store, at user1.mystore.com, user2.mystore.com etc. Each store would have customers with order histories, and those customers would have logins. I would need to restrict customers of user1.mystore.com from logging in at user2.mystore.com without a new account, and likewise prevent user2.mystore.com from accessing user1.mystore.com's customer history.</p>
4,964,194
3
0
null
2011-02-10 23:30:57.63 UTC
12
2012-07-19 17:45:32.537 UTC
2011-02-18 19:46:24.713 UTC
null
387,199
null
387,199
null
1
10
c#|asp.net-mvc|asp.net-mvc-2
5,304
<p>I implemented a complete MVC multi-tennant app. Here are some links I found handy and some sample apps:</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa479086.aspx">http://msdn.microsoft.com/en-us/library/aa479086.aspx</a></p> <p><a href="http://codeofrob.com/archive/2010/02/14/multi-tenancy-in-asp.net-mvc-controller-actions-part-i.aspx">http://codeofrob.com/archive/2010/02/14/multi-tenancy-in-asp.net-mvc-controller-actions-part-i.aspx</a></p> <p><a href="http://www.developer.com/design/article.php/10925_3801931_2/Introduction-to-Multi-Tenant-Architecture.htm">http://www.developer.com/design/article.php/10925_3801931_2/Introduction-to-Multi-Tenant-Architecture.htm</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/aa479086.aspx#mlttntda_cc">http://msdn.microsoft.com/en-us/library/aa479086.aspx#mlttntda_cc</a></p> <p><a href="http://lukesampson.com/post/303245177/subdomains-for-a-single-application-with-asp-net-mvc">http://lukesampson.com/post/303245177/subdomains-for-a-single-application-with-asp-net-mvc</a></p> <p><a href="http://code.google.com/p/multimvc/">http://code.google.com/p/multimvc/</a></p> <p><a href="http://www.paulstovell.com/widgets">http://www.paulstovell.com/widgets</a></p> <p><a href="http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate/">http://www.agileatwork.com/bolt-on-multi-tenancy-in-asp-net-mvc-with-unity-and-nhibernate/</a></p> <p><a href="http://ayende.com/blog/3530/multi-tenancy-approaches-and-applicability">http://ayende.com/blog/3530/multi-tenancy-approaches-and-applicability</a></p> <p><a href="http://weblogs.asp.net/zowens/archive/tags/Multi-tenancy/default.aspx">http://weblogs.asp.net/zowens/archive/tags/Multi-tenancy/default.aspx</a></p> <p><a href="http://cloudsamurai.codeplex.com/">http://cloudsamurai.codeplex.com/</a></p> <p><a href="http://cloudninja.codeplex.com/">http://cloudninja.codeplex.com/</a></p> <p><a href="http://msdn.microsoft.com/en-us/library/hh534484.aspx">http://msdn.microsoft.com/en-us/library/hh534484.aspx</a></p> <p><a href="http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx">http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx</a></p> <p><a href="http://blog.tonywilliams.me.uk/asp-net-mvc-2-routing-subdomains-to-areas">http://blog.tonywilliams.me.uk/asp-net-mvc-2-routing-subdomains-to-areas</a></p> <p>Even starting from scratch, you are in for a world of hurt. The MVC framework does very little to help you address the issues.</p>
5,056,385
When to use `save` vs `save!` in model?
<p>According to <a href="http://robots.thoughtbot.com/post/159807850/save-bang-your-head-active-record-will-drive-you-mad" rel="noreferrer">save bang your head, active record will drive you mad</a>, we should avoid using <code>save!</code> and <code>rescue</code> idiom for exceptional situations. Given that, say a model needs to <code>@post.mark_rejected</code>.</p> <p>If the code in <code>mark_rejected</code> fails due to one of the below problems, should an exception be thrown? :</p> <ul> <li>if there is a validation problem</li> <li>if a non-nullable-field was being assigned a null</li> <li>if there was a connection loss to database</li> </ul> <p>If we do not throw an exception, then:</p> <ul> <li>controller action would have to check for return value of <code>mark_rejected</code> and do it's thing</li> <li>we are not expecting an exception from that method call, so we do not write a <code>rescue</code> clause in the controller action, thus the exception bubbles up to (..wherever..) and will probably show up as some (500 HTTP?) error</li> </ul> <p>Example code:</p> <pre><code>def mark_rejected ... save! end </code></pre> <p>or </p> <pre><code>def mark_rejected ... save end </code></pre>
5,056,428
3
1
null
2011-02-20 10:16:21.557 UTC
15
2018-03-14 00:43:50.627 UTC
null
null
null
null
382,818
null
1
78
ruby-on-rails-3
81,435
<p>There's more overhead in an exception, so there is a performance issue, especially when it can be expected that it will likely be thrown often, as is the case with <code>save</code>.</p> <p>It is fewer lines of code to check if the return value is false than rescue an exception, so I don't see how it's a problem having to check for the return value if you already have to rescue the exception. How often would an exception thrown by <code>save!</code> ever have to bubble-up the call stack in practice? Rarely, if ever, in my experience.</p> <p>If there is an exception thrown when calling <code>save</code> as opposed to <code>save!</code> you should want it to show a 500 error page because that's what happened: an unrecoverable, unknown, unexpected internal server error.</p>
5,287,252
how to put Image on JPanel using Netbeans
<p>And how do I put Image on a JPanel using Netbeans?</p>
5,287,521
4
0
null
2011-03-13 03:43:46.3 UTC
null
2015-06-25 17:45:55.043 UTC
2015-06-25 17:45:55.043 UTC
null
95,674
null
472,034
null
1
2
java|swing|netbeans|imageicon
60,903
<p>Have a look at this tutorial: <a href="http://netbeans.org/kb/docs/java/gui-image-display.html" rel="noreferrer">Handling Images in a Java GUI Application</a></p> <p>At the same time you could code as well:</p> <pre><code>JPanel panel = new JPanel(); ImageIcon icon = new ImageIcon("image.jpg"); JLabel label = new JLabel(); label.setIcon(icon); panel.add(label); </code></pre>
61,919,141
Read JSON file in Github Actions
<p>I want to read a JSON file and use a property in a string in a Github Actions YAML file. How do I do this? (I want the version of the <code>package.json</code>)</p>
61,919,791
7
3
null
2020-05-20 17:22:42.993 UTC
5
2022-09-08 07:56:57.413 UTC
null
null
null
null
10,438,436
null
1
17
json|yaml|github-actions
38,342
<p>Use the built-in <code>fromJson(value)</code> (see here: <a href="https://docs.github.com/en/actions/learn-github-actions/expressions#fromjson" rel="noreferrer">https://docs.github.com/en/actions/learn-github-actions/expressions#fromjson</a>)</p> <p>Reading a file depends on the shell you're using. Here's an example for <code>sh</code>:</p> <pre class="lang-yaml prettyprint-override"><code>name: Test linux job on: push jobs: testJob: name: Test runs-on: ubuntu-latest steps: - id: set_var run: | content=`cat ./path/to/package.json` # the following lines are only required for multi line json content=&quot;${content//'%'/'%25'}&quot; content=&quot;${content//$'\n'/'%0A'}&quot; content=&quot;${content//$'\r'/'%0D'}&quot; # end of optional handling for multi line json echo &quot;::set-output name=packageJson::$content&quot; - run: | echo &quot;${{fromJson(steps.set_var.outputs.packageJson).version}}&quot; </code></pre> <p>Multi line JSON handling as per <a href="https://github.community/t5/GitHub-Actions/set-output-Truncates-Multiline-Strings/td-p/37870" rel="noreferrer">https://github.community/t5/GitHub-Actions/set-output-Truncates-Multiline-Strings/td-p/37870</a></p> <p>GitHub issue about <code>set-env</code> / <code>set-output</code> multi line handling: <a href="https://github.com/actions/toolkit/issues/403" rel="noreferrer">https://github.com/actions/toolkit/issues/403</a></p>
9,143,345
How to use responsive features of bootstrap 2.0
<p>I'm using bootstrap 2.0 from twitter and unsure how to make it responsive.</p> <ul> <li>How can I remove elements when in mobile/small screen mode?</li> <li>How can I replace elements (i.e replace a big picture with a smaller one)?</li> <li>Change a <code>&lt;h2&gt;</code> to be <code>&lt;h5&gt;</code>? etc.</li> </ul>
9,146,590
5
3
null
2012-02-04 18:35:31.413 UTC
35
2014-03-28 15:16:20.623 UTC
2012-10-04 14:52:33.003 UTC
user212218
null
null
66,975
null
1
26
html|css|twitter-bootstrap
49,153
<h1>Hiding Elements</h1> <p>You can hide elements with:</p> <pre><code>display: none; visibility: hidden; </code></pre> <p>Hopefully you're using LESS or SASS so you can just specify:</p> <pre><code>@mixin hidden { display: none; visibility: hidden; } </code></pre> <p>And then easily mix it in when necessary:</p> <pre><code>footer { @include hidden; } </code></pre> <p>Just apply them to any selector in the relevant media query. Also, understand that media queries cascade onto smaller media queries. If you hide an element in a wide media query (tablet sized), then the element will remain hidden as the website shrinks.</p> <h1>Replacing Images</h1> <p>Bootstrap doesn't offer image resizing as the screen shrinks, but you can manually change the dimensions of images with CSS in media queries.</p> <p>But a particular solution I like is from this blog post: <a href="http://unstoppablerobotninja.com/entry/fluid-images/" rel="nofollow noreferrer">http://unstoppablerobotninja.com/entry/fluid-images/</a></p> <pre><code>/* You could instead use ".flexible" and give class="flexible" only to images you want to have this property */ img { max-width: 100%; } </code></pre> <p>Now images will only appear in their full dimensions if they don't exceed their parent container, but they'll shrink fluidly as their parent element (like the <code>&lt;div&gt;</code> they're in) shrinks.</p> <p>Here's a demo: <a href="http://unstoppablerobotninja.com/demos/resize/" rel="nofollow noreferrer">http://unstoppablerobotninja.com/demos/resize/</a></p> <p>To actually replace images, you could swap the background image with CSS. If <code>.logo</code> has <code>background: url("logo.png");</code>, then you can just specify a new background image in a media query with <code>.logo { background: url("small-logo.png");</code></p> <h1>Change h2 to h5</h1> <p>If this is because you want to change the size of the heading, don't do this. H2 has semantic value: It's not as important as H1 and more important than H3.</p> <p>Instead, just specify new sizes for your h1-h6 elements in media queries as your website gets smaller.</p> <pre><code>@media (max-width: 480px) { h1, h2, h3, h4, h5, h6 { font-size: 80%; } } </code></pre>
9,104,908
Random geographic coordinates (on land, avoid ocean)
<p>Any clever ideas on how to generate random coordinates (latitude / longitude) of places on Earth? Latitude / Longitude. Precision to 5 points and avoid bodies of water. </p> <pre><code> double minLat = -90.00; double maxLat = 90.00; double latitude = minLat + (double)(Math.random() * ((maxLat - minLat) + 1)); double minLon = 0.00; double maxLon = 180.00; double longitude = minLon + (double)(Math.random() * ((maxLon - minLon) + 1)); DecimalFormat df = new DecimalFormat("#.#####"); log.info("latitude:longitude --&gt; " + df.format(latitude) + "," + df.format(longitude)); </code></pre> <p>Maybe i'm living in a dream world and the water topic is unavoidable ... but hopefully there's a nicer, cleaner and more efficient way to do this?</p> <p><strong>EDIT</strong></p> <p>Some fantastic answers/ideas -- however, at scale, let's say I need to generate 25,000 coordinates. Going to an external service provider may not be the best option due to latency, cost and a few other factors. </p>
9,334,575
16
3
null
2012-02-01 23:21:20.787 UTC
9
2022-07-18 17:07:08.833 UTC
2014-10-14 00:27:09.713 UTC
null
82,180
null
615,282
null
1
33
java|gis|geocoding
27,365
<p>To deal with the body of water problem is going to be largely a data issue, e.g. do you just want to miss the oceans or do you need to also miss small streams. Either you need to use a service with the quality of data that you need, or, you need to obtain the data yourself and run it locally. From your edit, it sounds like you want to go the local data route, so I'll focus on a way to do that.</p> <p>One method is to obtain a shapefile for either land areas or water areas. You can then generate a random point and determine if it intersects a land area (or alternatively, does not intersect a water area).</p> <p>To get started, you might get some low resolution data <a href="https://web.archive.org/web/20150713210113/http://aprsworld.net:80/gisdata/world/" rel="nofollow noreferrer">here</a> and then get higher resolution data <a href="https://www.soest.hawaii.edu/pwessel/gshhs/index.html" rel="nofollow noreferrer">here</a> for when you want to get better answers on coast lines or with lakes/rivers/etc. You mentioned that you want precision in your points to 5 decimal places, which is a little over 1m. Do be aware that if you get data to match that precision, you will have one giant data set. And, if you want really good data, be prepared to pay for it.</p> <p>Once you have your shape data, you need some tools to help you determine the intersection of your random points. <a href="https://geotools.org/" rel="nofollow noreferrer">Geotools</a> is a great place to start and probably will work for your needs. You will also end up looking at opengis code (docs under geotools site - not sure if they consumed them or what) and <a href="https://web.archive.org/web/20160818123229/http://www.vividsolutions.com:80/Jts/JTSHome.htm" rel="nofollow noreferrer">JTS</a> for the geometry handling. Using this you can quickly open the shapefile and start doing some intersection queries.</p> <pre><code> File f = new File ( &quot;world.shp&quot; ); ShapefileDataStore dataStore = new ShapefileDataStore ( f.toURI ().toURL () ); FeatureSource&lt;SimpleFeatureType, SimpleFeature&gt; featureSource = dataStore.getFeatureSource (); String geomAttrName = featureSource.getSchema () .getGeometryDescriptor ().getLocalName (); ResourceInfo resourceInfo = featureSource.getInfo (); CoordinateReferenceSystem crs = resourceInfo.getCRS (); Hints hints = GeoTools.getDefaultHints (); hints.put ( Hints.JTS_SRID, 4326 ); hints.put ( Hints.CRS, crs ); FilterFactory2 ff = CommonFactoryFinder.getFilterFactory2 ( hints ); GeometryFactory gf = JTSFactoryFinder.getGeometryFactory ( hints ); Coordinate land = new Coordinate ( -122.0087, 47.54650 ); Point pointLand = gf.createPoint ( land ); Coordinate water = new Coordinate ( 0, 0 ); Point pointWater = gf.createPoint ( water ); Intersects filter = ff.intersects ( ff.property ( geomAttrName ), ff.literal ( pointLand ) ); FeatureCollection&lt;SimpleFeatureType, SimpleFeature&gt; features = featureSource .getFeatures ( filter ); filter = ff.intersects ( ff.property ( geomAttrName ), ff.literal ( pointWater ) ); features = featureSource.getFeatures ( filter ); </code></pre> <p>Quick explanations:</p> <ol start="0"> <li>This assumes the shapefile you got is polygon data. Intersection on lines or points isn't going to give you what you want.</li> <li>First section opens the shapefile - nothing interesting</li> <li>you have to fetch the geometry property name for the given file</li> <li>coordinate system stuff - you specified lat/long in your post but GIS can be quite a bit more complicated. In general, the data I pointed you at is <a href="https://spatialreference.org/ref/epsg/4326/" rel="nofollow noreferrer">geographic, wgs84</a>, and, that is what I setup here. However, if this is not the case for you then you need to be sure you are dealing with your data in the correct coordinate system. If that all sounds like gibberish, google around for a tutorial on GIS/coordinate systems/datum/ellipsoid.</li> <li>generating the coordinate geometries and the filters are pretty self-explanatory. The resulting set of features will either be empty, meaning the coordinate is in the water if your data is land cover, or not empty, meaning the opposite.</li> </ol> <p>Note: if you do this with a really random set of points, you are going to hit water pretty often and it could take you a while to get to 25k points. You may want to try to scope your point generation better than truly random (like remove big chunks of the Atlantic/Pacific/Indian oceans).</p> <p>Also, you may find that your intersection queries are too slow. If so, you may want to look into creating a quadtree index (qix) with a tool like <a href="https://gdal.org/" rel="nofollow noreferrer">GDAL</a>. I don't recall which index types are supported by geotools, though.</p>
18,655,295
Adding value to input field with jQuery
<p>I want to add some value in an input field with jQuery. The problem is with the ID of the input field. I am using the id such as <code>options[input2]</code>. In that case my code does not work. If I use ID like <code>input2</code>, then it works fine. I need to use <code>options[input2]</code>, how can I fix the code?</p> <p><strong>HTML:</strong></p> <pre><code>&lt;div&gt; &lt;h3&gt;Working&lt;/h3&gt; &lt;input id="input1" type="text" value="" /&gt; &lt;input class="button" type="button" value="Add value" /&gt; &lt;/div&gt; &lt;div&gt; &lt;h3&gt;Not working&lt;/h3&gt; &lt;input id="options[input2]" type="text" value="" /&gt; &lt;input class="button" type="button" value="Add value" /&gt; &lt;/div&gt; </code></pre> <p><strong>jQuery:</strong></p> <pre><code>$('.button').click(function(){ var fieldID = $(this).prev().attr("id"); $('#' + fieldID).val("hello world"); }); </code></pre> <p><strong>Demo:</strong></p> <p><a href="http://jsfiddle.net/4XR8M/" rel="noreferrer">http://jsfiddle.net/4XR8M/</a></p>
18,655,344
5
1
null
2013-09-06 10:12:57.9 UTC
4
2021-11-30 01:26:57.297 UTC
null
null
null
null
966,582
null
1
9
javascript|jquery|html
150,682
<p>You can do it as below.</p> <pre><code>$(this).prev('input').val("hello world"); </code></pre> <p><a href="http://jsfiddle.net/4XR8M/2/"><strong>Live Demo</strong></a></p>
18,746,064
Using Reflection to create a DataTable from a Class?
<p>I've just learned about Generics and I'm wondering whether I can use it to dynamically build datatables from my classes.</p> <p>Or I might be missing the point here. Here is my code, what I'm trying to do is create a datatable from my existing class and populate it. However I'm getting stuck in my thought process.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Data; namespace Generics { public class Dog { public string Breed { get; set; } public string Name { get; set; } public int legs { get; set; } public bool tail { get; set; } } class Program { public static DataTable CreateDataTable(Type animaltype) { DataTable return_Datatable = new DataTable(); foreach (PropertyInfo info in animaltype.GetProperties()) { return_Datatable.Columns.Add(new DataColumn(info.Name, info.PropertyType)); } return return_Datatable; } static void Main(string[] args) { Dog Killer = new Dog(); Killer.Breed = "Maltese Poodle"; Killer.legs = 3; Killer.tail = false; Killer.Name = "Killer"; DataTable dogTable = new DataTable(); dogTable = CreateDataTable(Dog); //How do I continue from here? } } } </code></pre> <p>Now At the <code>DataTable</code> point it errors. Also, being new to reflection and Generics, how will I actually populate the data with the Killer class?</p>
24,131,656
9
4
null
2013-09-11 16:02:51.197 UTC
26
2021-03-31 16:39:43.287 UTC
2013-09-11 16:12:56.877 UTC
null
1,195,080
null
392,687
null
1
44
c#|.net|oop|reflection
98,148
<p>Building up on all the previous answers, here is a version that creates a DataTable from any collection:</p> <pre><code>public static DataTable CreateDataTable&lt;T&gt;(IEnumerable&lt;T&gt; list) { Type type = typeof(T); var properties = type.GetProperties(); DataTable dataTable = new DataTable(); dataTable.TableName = typeof(T).FullName; foreach (PropertyInfo info in properties) { dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType)); } foreach (T entity in list) { object[] values = new object[properties.Length]; for (int i = 0; i &lt; properties.Length; i++) { values[i] = properties[i].GetValue(entity); } dataTable.Rows.Add(values); } return dataTable; } </code></pre>
15,124,398
How to Install DebugKit on CakePHP
<p>I'm learning how to work with <code>CakePHP</code> and I configured everything allright, but now, I get this warning: </p> <p><code>DebugKit is not installed. It will help you inspect and debug different aspects of your application. You can install it from github</code></p> <p>I already clicked on that link, and downloaded that app, but I have no idea where to place these folders... I'm using <strong>EasyPhp</strong> as my web host.<br> Also <a href="https://github.com/cakephp/debug_kit" rel="noreferrer">Here</a> I followed the steps,<br> and there is: </p> <pre><code>`Ensure the plugin is loaded in app/Config/bootstrap.php by calling CakePlugin::load('DebugKit');` </code></pre> <p>But I don't know how to <code>call</code> something here, is there a prompt ?</p>
15,124,425
3
0
null
2013-02-27 23:14:00.313 UTC
11
2017-04-18 20:14:41.397 UTC
2015-10-12 22:28:54.69 UTC
null
2,394,204
null
2,054,434
null
1
23
cakephp
46,071
<p><strong><em>How to Install DebugKit for CakePHP (in just 4 easy steps!):</em></strong></p> <p><strong>STEP 1 (option A): The traditional / download method:</strong></p> <p>Create a <code>DebugKit</code> folder within your <code>app/Plugin</code> directory, and put the contents of the download into it (not the top-level folder - the stuff within it). If you know how to clone from github, that works fine also.</p> <hr> <p><strong>STEP 1 (option B): The Composer method</strong></p> <p>This seems to currently be the most popular option (and for good reason). If you're already using <a href="http://getcomposer.org/">Composer [find out more about it here]</a>, then adding DebugKit is crazy-simple. If you haven't used Composer before, don't worry - just use "option A" above. The end-result is the same, and it's easy too.</p> <blockquote> <p>Ensure require is present in composer.json. This will install the plugin into Plugin/DebugKit:</p> </blockquote> <pre><code>{ "require": { "cakephp/debug_kit": "2.2.*" } } </code></pre> <hr> <p><strong>STEP 2:</strong></p> <p>Then, in your <code>app/Config/bootstrap.php</code>, add (or un-comment) the following line:</p> <pre><code>CakePlugin::load('DebugKit'); </code></pre> <p>Lastly, in your <code>app/Controller/AppController.php</code> file (within the class), add:</p> <pre><code>public $components = array( 'DebugKit.Toolbar' ); </code></pre> <p>(If you already have a <code>$components</code> array, then just add to it - don't re-set it.)</p> <hr> <p><strong>STEP 3: Ensure debug is 1 or more</strong></p> <p>In your <code>Config/core.php</code> file, make sure this line:</p> <pre><code>Configure::write('debug', 2); </code></pre> <p>has a value of 1 or 2. <a href="http://book.cakephp.org/2.0/en/deployment.html#update-core-php">(read more about debug mode here)</a></p> <hr> <p><strong>STEP 4: Remove <code>sql_dump</code>:</strong></p> <p>In your layout file, remove the 'sql_dump' element (at the bottom of the default layout)</p> <hr> <p><strong>According to the "Installation" section on the <a href="https://github.com/cakephp/debug_kit">debugKit page</a>:</strong></p> <ul> <li>Clone/Copy the files in this directory into app/Plugin/DebugKit</li> <li>Ensure the plugin is loaded in app/Config/bootstrap.php by calling CakePlugin::load('DebugKit');</li> <li>Include the toolbar component in your AppController.php: public $components = array('DebugKit.Toolbar');</li> <li>Set debug mode to at least 1.</li> <li>Make sure to remove the 'sql_dump' element from your layout if you want to experience the awesome that is the debug kit SQL log.</li> </ul> <hr> <p><strong>How do I know if it's working?</strong></p> <p>You should see a small icon on a gray square in the upper right corner of your site. Click on this to expand the options, then click on an option to start being awesome.</p>
15,188,219
Rulesets for cppcheck
<p>Cppcheck allows you to create your own rules files, but I don't know how much of cppcheck's functionality is exposed.</p> <p>Is anyone working on a set that would enforce <a href="http://www.stroustrup.com/JSF-AV-rules.pdf" rel="nofollow noreferrer">JSF</a> or <a href="http://www.misra-cpp.com/" rel="nofollow noreferrer">MISRA</a> rules?</p>
24,918,676
3
2
null
2013-03-03 17:08:14.48 UTC
7
2018-09-01 06:12:19.56 UTC
2016-11-20 23:29:23.33 UTC
null
4,070,000
null
10,897
null
1
35
c++|testing|static-code-analysis|cppcheck|safety-critical
10,118
<p>You won't be able to implement all MISRA/JSF rules and directives as cppcheck rules, mostly only the straightforward ones restricting certain C language features and constructions or that are style-related (some that come to mind: spaces before/after ./->, # of arguments on a single line, use of unions to provide different methods of accessing memory, presence of unsigned/signed before char, etc).</p> <p>User <a href="https://stackoverflow.com/users/120163/ira-baxter">Ira Baxter</a> pretty much nailed it in a <a href="https://stackoverflow.com/questions/11966613/why-does-cppcheck-not-find-this-obvious-array-out-of-bounds-error#comment15968165_11976058">comment</a> on another question touching cppcheck: not everything can be represented/simplified as a pattern. Relying on patterns <strong>for custom rules</strong> makes it difficult to handle and detect higher level issues, related for example to <strong>types</strong> <em>(e.g. sizeof() on types; you would have to parse and collect tokens (typedefs, enums) used as a type representation)</em>, <strong>inheritance</strong> <em>(e.g. classes, incl. derived ones, used both as virtual and non-virtual)</em>, and <strong>scope</strong>. Those need to be hard-coded into cppcheck (you could always fork cppcheck...)</p> <p>In any case, have you touched MISRA (or JSF) rules? Is this a requirement for a project? If not, you could grab a copy of the MISRA guidelines (you already have the JSF ones) and check the ones you can implement using PCRE patterns. If it is a requirement, I suggest you "invest" in a commercial product that does check for MISRA/JSF guidelines and use both tools.</p> <p>A final note: you don't need all the MISRA/JSF rules, and many tools leave a small percentage of those out.</p>
15,322,371
PHP wait for input from command line
<p>I want to be able to let a PHP program wait for user's input. For example:</p> <ol> <li>Script requests authorization code from server (this code will be sent via e-mail)</li> <li>Script waits for user to enter authorization code</li> <li>Script continues</li> </ol> <p>How should I do step 2? (Is it possible?)</p>
15,322,457
1
5
null
2013-03-10 12:46:00.453 UTC
13
2016-03-09 10:35:50.423 UTC
null
null
null
user1544337
null
null
1
88
php|command-line
88,690
<p>The php man page for the cli has a <a href="http://www.php.net/manual/en/features.commandline.php#94924" rel="noreferrer">comment here</a> detailing a solution, (copied here for anyone else looking)</p> <pre><code>&lt;?php echo "Are you sure you want to do this? Type 'yes' to continue: "; $handle = fopen ("php://stdin","r"); $line = fgets($handle); if(trim($line) != 'yes'){ echo "ABORTING!\n"; exit; } fclose($handle); echo "\n"; echo "Thank you, continuing...\n"; ?&gt; </code></pre>
15,451,958
Simple way to create matrix of random numbers
<p>I am trying to create a matrix of random numbers, but my solution is too long and looks ugly</p> <pre><code>random_matrix = [[random.random() for e in range(2)] for e in range(3)] </code></pre> <p>this looks ok, but in my implementation it is</p> <pre><code>weights_h = [[random.random() for e in range(len(inputs[0]))] for e in range(hiden_neurons)] </code></pre> <p>which is extremely unreadable and does not fit on one line.</p>
15,451,996
13
0
null
2013-03-16 16:52:38.893 UTC
19
2020-11-25 07:07:58.123 UTC
2015-04-30 14:51:40.773 UTC
null
2,062,965
null
2,173,836
null
1
125
python|random|coding-style
286,479
<p>Take a look at <a href="https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.random.rand.html" rel="noreferrer">numpy.random.rand</a>:</p> <blockquote> <p>Docstring: rand(d0, d1, ..., dn)</p> <p>Random values in a given shape.</p> <p>Create an array of the given shape and propagate it with random samples from a uniform distribution over <code>[0, 1)</code>.</p> </blockquote> <hr> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.random.rand(2,3) array([[ 0.22568268, 0.0053246 , 0.41282024], [ 0.68824936, 0.68086462, 0.6854153 ]]) </code></pre>
8,162,152
Disable a parameter input at selection screen
<p>I have screen filter at selection screen like this</p> <pre><code>SELECTION-SCREEN BEGIN OF BLOCK a WITH FRAME. PARAMETERS s_werks like resb-werks DEFAULT 'X' . SELECT-OPTIONS: s_aufnr FOR in_param-aufnr, s_matnr FOR in_param-matnr, s_bldat FOR in_param-bldat. SELECTION-SCREEN END OF BLOCK a. </code></pre> <p>and I want to disable just <code>s_werks</code> parameter but <code>SELECT-OPTIONS</code>.</p> <p>I want to disable it because it'll be exact value which is filled from table depends on the <code>sy-uname</code> :)</p> <p>How to achieve that?</p>
8,166,581
2
0
null
2011-11-17 04:32:48.273 UTC
null
2020-12-25 21:16:19.833 UTC
2020-12-25 21:16:19.833 UTC
null
9,150,270
null
640,790
null
1
5
abap|sap-selection-screens
67,172
<p>You can use the <code>OUTPUT</code> selection screen event for this. Add the following code:</p> <pre><code>AT SELECTION-SCREEN OUTPUT. LOOP AT SCREEN. IF screen-name = 'S_WERKS'. screen-input = 0. MODIFY SCREEN. ENDIF. ENDLOOP. </code></pre> <p>Changing the <code>input</code> value to <code>0</code> for this screen element will disable input and makes the input field appear as grayed out.</p>
8,309,974
Django - Deployment for a newbie
<p>I have finished my first Django/Python Project and now I need to put the things working in a real production webserver.</p> <p>I have read some papers over the Internet and I'm inclined to choose Ngix, Gunicorn and Git but the documentation that I found is not very complete and I have many doubs if this is the best option.</p> <p>What do you think about this subject? I need a simple way to put my Django Project on-line but the website is still very buggy, I will need to change the code many times in the production server in the times ahead.</p> <p>Please give me some clues about what I should do. I'm kind of lost...</p> <p>Best Regards,</p>
8,311,021
2
2
null
2011-11-29 11:28:17.333 UTC
8
2014-09-28 11:05:46.263 UTC
null
null
null
null
488,735
null
1
16
django|deployment
9,509
<p>This is a good <a href="http://rogueleaderr.com/post/65157477648/the-idiomatic-guide-to-deploying-django-in-production" rel="noreferrer">blog entry</a> that covers deploying Django using Nginx and Gunicorn. I'll give you a quick rundown of what makes all the different technologies important:</p> <h3>Git</h3> <p>Git, or any other version control system, is certainly not required. Why it lends itself to deploying Django projects is that your usually distributing your application by source, i.e. your not compiling it or packaging it as an egg. Usually you'll organize your Git repository as such that updating your application on the server only requires you to do a checkout of the latest sources--nothing else.</p> <h3>virtualenv and pip</h3> <p>This, again, is not a strict requirement, but I'd strongly suggest you take the time to familiarize yourself with virtualenv and pip if you already haven't done so, since it's going to make deploying your Python applications across different runtime environments, local or remote, a breeze.</p> <p>Basically, your project will need to have at least Django and Gunicorn available on the Python path, possibly even a database driver. What that means is that every time you try to deploy your application somewhere you'll have to install Python and do the <code>easy_install</code> dance all over.</p> <p>virtualenv will redistribute a Python installation, which in turn means that the new Python instance will, by default, have it's very own Python path configuration relative to the installation. pip is like <code>easy_install</code> on steroids, since it supports checking out Python dependencies directly from code repositories and supports a requirements file format with which you can install and configure all of your dependencies in one fell swoop.</p> <p>With virtualenv and pip, all you'd need to do is have a simple text file with all your dependencies that can be parsed with pip and an installed Python distribution on the machine. From there you just do <code>git checkout repo /app/path; easy_install virtualenv; virtualenv /app/path; ./app/path/scripts/activate; pip install -r /app/path/requirements.txt</code>. Voila, Gunicorn, Django and all other dependencies are then installed and available immediately. When you run the Gunicorn Django script with the Python instance in <code>/app/path/scripts</code>, then the script will immediately have access to the Gunicorn sources and it will be able to locate your Django project which will have access to Django and other dependencies as well.</p> <h3>Nginx</h3> <p>Web servers will primarily be used to server static media. Everything else gets proxied to your Gunicorn instance that manages your Django instance, since it's primary purpose is to host Python WSGI applications and not to act as a general purpose Web server and conversely your Web server doesn't need to be able to handle Python applications.</p> <p>Why Nginx is often used is that it's lightweight and exactly suited for serving static media and proxying requests. It comes with way less bells and whistles than, say, Apache, which makes it all the more easier to configure and maintain, least to mention it's going to be more resource effective if your already strained.</p> <h3>Gunicorn</h3> <p>This is the actual Python application that will manage your Django instance and provide an HTTP interface that exposes it to HTTP clients. It'll start several worker processes which will all be distinct Python virtual machines loaded with the sources of your application and it's dependencies. The main Gunicorn process will in turn take charge of managing which worker processes manage which requests for maximum throughput.</p> <h3>The basic principle of wiring Nginx and Gunicorn</h3> <p>The most important thing to observe is that Nginx and Gunicorn are separate processes that you manage independently.</p> <p>The Nginx Web server will be publicly exposed, i.e. it will be directly accessible over the internet. For requests to static media, such as actual images, CSS stylesheets, JavaScript sources and PDF files accessible via the filesystem, Nginx will take charge of returning them in the response body to HTTP clients if you configure it to look for files on the path where you configured your project to collect static media.</p> <p>Any other request should be proxied to your Gunicorn instance. It will be configured to listen to HTTP requests on a certain port on the loopback interface, so you'll using Nginx as a revers proxy to <code>http://127.0.0.1:8080</code> for requests to your Django instance.</p> <p>This is the basic rundown for deploying your Django projects into production that should satisfy the needs of 95% Django projects running out there. While I did reference Nginx and Gunicorn, it's the usual approach when it comes to setting up any Web server to act as a reverse-proxy to a Python WSGI server.</p>
7,761,556
Restore already bought in-app-purchases on iPhone?
<p>I got so far: After a reinstall, a user needs to click "buy feature", then he gets scared with the $0.99 question, then has to login and then gets told the feature is already bought and he gets it for free. </p> <p>I know apple is a religion and users are strong believers, but isn't there a better way? :-) What I want is to check for the feature without actually buying it. Letting the user enter his account info seems to be neccessary, maybe buy a $0.00 feature? or is there a method somewhere that does this?</p> <p>I'm using MKStoreKit for the whole In-App-Purchase, but any solution would be great. </p> <hr> <p><strong>UPDATE</strong></p> <p>thanx to darvids0n, your method solved my problem! here's some working code for others trying the same:</p> <pre><code>- (void)removePreviousPurchases { //just for sandbox testing [[MKStoreManager sharedManager] removeAllKeychainData]; } - (void)restorePreviousPurchases { //needs account info to be entered if([SKPaymentQueue canMakePayments]) { [[MKStoreManager sharedManager] restorePreviousTransactionsOnComplete:^(void) { NSLog(@"Restored."); /* update views, etc. */ } onError:^(NSError *error) { NSLog(@"Restore failed: %@", [error localizedDescription]); /* update views, etc. */ }]; } else { NSLog(@"Parental control enabled"); /* show parental control warning */ } } </code></pre>
7,761,623
2
0
null
2011-10-13 23:23:31.117 UTC
15
2015-02-27 16:50:33.793 UTC
2012-05-15 18:37:42.52 UTC
null
308,315
null
994,486
null
1
40
ios|in-app-purchase|restore
28,797
<p>If the $0.99 item is non-consumable, then you should provide a "Restore Purchases" button (or similar) which calls</p> <pre><code>[[SKPaymentQueue defaultQueue] restoreCompletedTransactions]; </code></pre> <p>Assuming you've added a transaction observer already, and implemented the <a href="http://developer.apple.com/library/ios/#documentation/StoreKit/Reference/SKPaymentTransactionObserver_Protocol/Reference/Reference.html" rel="noreferrer">protocol</a> including a case to handle a restored transaction (with state <code>SKPaymentTransactionStateRestored</code>) this will work.</p>
8,111,120
Integral operators quot vs. div
<p>Type class Integral has two operations <code>quot</code> and <code>div</code>, yet in the Haskell 2010 Language Report it is not specified what they're supposed to do. Assuming that <code>div</code> is integral division, what does <code>quot</code> differently, or what is the purpose of <code>quot</code>? When do you use one, and when the other?</p>
8,111,203
2
1
null
2011-11-13 11:08:40.56 UTC
16
2018-03-09 22:42:40.483 UTC
null
null
null
null
86,604
null
1
58
haskell
17,798
<p>To quote section 6.4.2 from the Haskell report:</p> <p>The <code>quot</code>, <code>rem</code>, <code>div</code>, and <code>mod</code> class methods satisfy these laws if y is non-zero:</p> <pre><code>(x `quot` y)*y + (x `rem` y) == x (x `div` y)*y + (x `mod` y) == x </code></pre> <p><code>quot</code> is integer division truncated toward zero, while the result of <code>div</code> is truncated toward negative infinity.</p> <p>The <code>div</code> function is often the more natural one to use, whereas the <code>quot</code> function corresponds to the machine instruction on modern machines, so it's somewhat more efficient.</p>
7,840,088
Debugging Spring configuration
<p>I am working on a Java application that uses Spring and Hibernate and runs on a Websphere. I have run into a problem, where I expect Spring to load a Dao into my object, but for some reason that doesn't happen. (Another Dao that is specified in much the same way is loaded fine.)</p> <p>The question is - how can I debug how Spring decides what to load in? Can I turn on logging for Spring, and where?</p>
7,840,693
2
0
null
2011-10-20 17:56:05.62 UTC
28
2018-09-22 08:53:43.993 UTC
2014-02-21 18:51:07.443 UTC
null
254,477
null
315,820
null
1
71
java|hibernate|spring|configuration|websphere
143,369
<p>Yes, Spring framework logging is very detailed, You did not mention in your post, if you are already using a logging framework or not. If you are using log4j then just add spring appenders to the log4j config (i.e to log4j.xml or log4j.properties), If you are using log4j xml config you can do some thing like this</p> <pre><code>&lt;category name="org.springframework.beans"&gt; &lt;priority value="debug" /&gt; &lt;/category&gt; </code></pre> <p>or</p> <pre><code>&lt;category name="org.springframework"&gt; &lt;priority value="debug" /&gt; &lt;/category&gt; </code></pre> <p>I would advise you to test this problem in isolation using JUnit test, You can do this by using <a href="http://blog.springsource.com/2011/06/21/spring-3-1-m2-testing-with-configuration-classes-and-profiles/" rel="noreferrer">spring testing module</a> in conjunction with <a href="http://www.junit.org/" rel="noreferrer">Junit</a>. If you use spring test module it will do the bulk of the work for you it loads context file based on your context config and starts container so you can just focus on testing your business logic. I have a small example here</p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:springContext.xml"}) @Transactional public class SpringDAOTest { @Autowired private SpringDAO dao; @Autowired private ApplicationContext appContext; @Test public void checkConfig() { AnySpringBean bean = appContext.getBean(AnySpringBean.class); Assert.assertNotNull(bean); } } </code></pre> <h2>UPDATE</h2> <p>I am not advising you to change the way you load logging but try this in your dev environment, Add this snippet to your web.xml file</p> <pre><code>&lt;context-param&gt; &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/log4j.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt; &lt;/listener&gt; </code></pre> <p><strong>UPDATE log4j config file</strong></p> <hr> <p>I tested this on my local tomcat and it generated a lot of logging on application start up. I also want to make a correction: use <strong>debug</strong> not <strong>info</strong> as @Rayan Stewart mentioned.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"&gt; &lt;log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false"&gt; &lt;appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"&gt; &lt;param name="Threshold" value="debug" /&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d{HH:mm:ss} %p [%t]:%c{3}.%M()%L - %m%n" /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name="springAppender" class="org.apache.log4j.RollingFileAppender"&gt; &lt;param name="file" value="C:/tomcatLogs/webApp/spring-details.log" /&gt; &lt;param name="append" value="true" /&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d{MM/dd/yyyy HH:mm:ss} [%t]:%c{5}.%M()%L %m%n" /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;category name="org.springframework"&gt; &lt;priority value="debug" /&gt; &lt;/category&gt; &lt;category name="org.springframework.beans"&gt; &lt;priority value="debug" /&gt; &lt;/category&gt; &lt;category name="org.springframework.security"&gt; &lt;priority value="debug" /&gt; &lt;/category&gt; &lt;category name="org.springframework.beans.CachedIntrospectionResults"&gt; &lt;priority value="debug" /&gt; &lt;/category&gt; &lt;category name="org.springframework.jdbc.core"&gt; &lt;priority value="debug" /&gt; &lt;/category&gt; &lt;category name="org.springframework.transaction.support.TransactionSynchronizationManager"&gt; &lt;priority value="debug" /&gt; &lt;/category&gt; &lt;root&gt; &lt;priority value="debug" /&gt; &lt;appender-ref ref="springAppender" /&gt; &lt;!-- &lt;appender-ref ref="STDOUT"/&gt; --&gt; &lt;/root&gt; &lt;/log4j:configuration&gt; </code></pre>
8,884,679
foreach mysql row from query echo out html with row values
<p>So basicly what I'm trying to accomplish is that foreach row in mysql query it prints out the html with the data from that row. Here's what I have, it keeps giving me an error on my foreach.</p> <pre><code>&lt;?php $shots = mysql_query("SELECT * FROM shots") or die(mysql_error()); while($row=mysql_fetch_array($shots)) $data[]=$row; foreach($shots as $data) if (!empty($data)){ $id = $data["id"]; $shotby = $data["shot"]; $passby = $data["pass"]; $time = $data["time"]; ?&gt; &lt;div class="feedbody"&gt; &lt;div class="title"&gt;&lt;?php echo $shotby; ?&gt;&lt;/div&gt; &lt;div class="feed-data"&gt;: gets a pass from &lt;span&gt;&lt;?php echo $passby; ?&lt;/span&gt; and he takes a shot!&lt;/div&gt; &lt;img class="dot" src="images/dot.png" /&gt; &lt;/div&gt; &lt;?php } } ?&gt; </code></pre> <p>Or something like that. Can anybody help point me in the right direction. I've been trying to find the answer.</p> <p><strong>EDIT:</strong> adding the error as requested.</p> <pre><code>Warning: Invalid argument supplied for foreach() in /home/content/93/7527593/html/fusionboard/includes/feed.php on line 7 </code></pre>
8,884,775
5
3
null
2012-01-16 18:37:28.733 UTC
1
2012-01-16 19:10:27.34 UTC
2012-01-16 18:45:02.677 UTC
null
710,827
null
710,827
null
1
2
php|mysql
69,655
<p><strike>First, if you want to access the data by name (instead of index), you need to include <code>MYSQL_ASSOC</code> as a second parameter to mysql_fetch_array, or use mysql_fetch_assoc.</strike></p> <p>Not really sure why you were copying the MySQL results to a second array just to loop through that later - you can loop through the results directly:</p> <pre><code>&lt;?php $shots = mysql_query("SELECT * FROM shots") or die(mysql_error()); while($row = mysql_fetch_assoc($shots)) { ?&gt; &lt;div class="feedbody"&gt; &lt;div class="title"&gt;&lt;?php echo $row["shot"]; ?&gt;&lt;/div&gt; &lt;div class="feed-data"&gt;: gets a pass from &lt;span&gt;&lt;?php echo $row["pass"]; ?&gt;&lt;/span&gt; and he takes a shot!&lt;/div&gt; &lt;img class="dot" src="images/dot.png" /&gt; &lt;/div&gt; &lt;?php } ?&gt; </code></pre> <p><strong>Update after you posted the error message:</strong> the error from your original code was that you first went through and copied each result row into <code>$data</code>, but then in your foreach you tried to loop on <code>$shots</code> (again) and have it call each item <code>$data</code>.</p> <p>What you probably wanted to do was have <code>foreach ($data as $item)</code> and then copy the properties from <code>$item</code>.</p>
5,022,397
Scale an entire WPF window
<p>I have a WPF application that I am going to be demoing to an audience on a large, high-resolution projector, and I am worried that the application will be too small to see from afar.</p> <p>Is there a simple way to make the ENTIRE application bigger (like the zoom slider in the WPF designer, that lets you zoom in?) I tried adding a layout transform to the Window in XAML, like so:</p> <pre><code>&lt;Window.LayoutTransform&gt; &lt;ScaleTransform ScaleX="1.5" ScaleY="1.5" CenterX=".5" CenterY=".5" /&gt; &lt;/Window.LayoutTransform&gt; </code></pre> <p>which makes the window look bigger in the designer, but seems to have no effect on the running application.</p> <p>I figure this should be dead simple with WPF's "resolution independence", high-tech text rendering, vector graphics, etc.</p> <p>(I know I can use a screen zooming tool, but that's lame since it makes everything fuzzy, and always makes me dizzy when the presenter pans around the screen.) </p>
5,022,808
4
3
null
2011-02-16 21:34:20.807 UTC
4
2020-04-07 10:45:23.197 UTC
null
null
null
null
172,387
null
1
24
.net|wpf|resolution-independence
41,431
<p>I posted a fairly detailed example of scaling the main element <a href="https://stackoverflow.com/questions/3193339/tips-on-developing-resolution-independent-application/5000120#5000120">in another question</a>. Perhaps it would be of some use to you.</p>
5,449,502
HTML5 and CSS3 for IE7 and IE8
<p>I inherited a web application where the front end uses new HTML5 tags (header, nav, section tags) and new CSS3 style attributes (rounded borders). The website looks amazing in Google Chrome and Safari.</p> <p>However, the client now complains the website is broken for IE7 and IE8. Everything is out of alignment and most of the styles do not render.</p> <p>What is the easiest way to make this website work in IE7 and IE8? Do I have to: a) Apply some hack to make IE browsers accept the new HTML5 and CSS3 features? b) A complete rewrite of the front end?</p>
5,449,515
6
0
null
2011-03-27 13:28:14.657 UTC
13
2016-07-20 11:38:36.503 UTC
null
null
null
null
27,305
null
1
17
html|internet-explorer-8|internet-explorer-7|css
45,084
<p><a href="http://code.google.com/p/html5shiv/" rel="noreferrer" title="go for it">Try this lovely script (.js)</a> :)<br> And for rounded corners i use <a href="http://code.google.com/p/curved-corner/" rel="noreferrer" title="curved corner">an other script (.htc)</a></p> <p>use the 1st:</p> <pre><code>&lt;!--[if lt IE 9]&gt; &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; </code></pre> <p>use the 2nd like:</p> <pre><code>-moz-border-radius: 4px; -webkit-border-radius: 4px; -khtml-border-radius: 4px; border-radius: 4px; behavior: url(border-radius.htc); </code></pre> <p>Happy sitebuilding :)</p> <p>The original link is no longer active and HTML5shiv has moved.</p> <p>Now available on GitHub</p> <p><a href="https://github.com/aFarkas/html5shiv" rel="noreferrer">https://github.com/aFarkas/html5shiv</a></p>
5,181,405
Best way to iterate folders and subfolders
<p>What's the best way to iterate folders and subfolders to get file size, total number of files, and total size of folder in each folder starting at a specified location?</p>
5,181,424
6
4
null
2011-03-03 13:35:27.303 UTC
12
2020-11-23 23:21:36.13 UTC
2012-05-21 09:35:30.977 UTC
null
505,893
null
139,698
null
1
45
c#|directory|subdirectory
95,261
<p>Use <a href="http://msdn.microsoft.com/en-us/library/07wt70x2.aspx" rel="noreferrer">Directory.GetFiles()</a>. The bottom of that page includes an example that's fully recursive.</p> <p><strong>Note:</strong> Use Chris Dunaway's answer below for a more modern approach when using .NET 4 and above.</p> <pre><code>// For Directory.GetFiles and Directory.GetDirectories // For File.Exists, Directory.Exists using System; using System.IO; using System.Collections; public class RecursiveFileProcessor { public static void Main(string[] args) { foreach(string path in args) { if(File.Exists(path)) { // This path is a file ProcessFile(path); } else if(Directory.Exists(path)) { // This path is a directory ProcessDirectory(path); } else { Console.WriteLine(&quot;{0} is not a valid file or directory.&quot;, path); } } } // Process all files in the directory passed in, recurse on any directories // that are found, and process the files they contain. public static void ProcessDirectory(string targetDirectory) { // Process the list of files found in the directory. string [] fileEntries = Directory.GetFiles(targetDirectory); foreach(string fileName in fileEntries) ProcessFile(fileName); // Recurse into subdirectories of this directory. string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory); foreach(string subdirectory in subdirectoryEntries) ProcessDirectory(subdirectory); } // Insert logic for processing found files here. public static void ProcessFile(string path) { Console.WriteLine(&quot;Processed file '{0}'.&quot;, path); } } </code></pre>
5,188,914
How to show the first commit by 'git log'?
<p>I have a Git project which has a long history. I want to show the first commit.</p> <p>How do I do this?</p>
5,189,296
7
2
null
2011-03-04 02:07:57.34 UTC
60
2022-05-21 18:02:46.297 UTC
2022-05-21 18:02:46.297 UTC
null
74,089
null
400,275
null
1
408
git
152,258
<h2>Short answer</h2> <pre><code>git rev-list --max-parents=0 HEAD </code></pre> <p><sub>(from <a href="https://stackoverflow.com/questions/5188914/how-to-show-first-commit-by-git-log#comment19763574_5189296" title="tiho&#39;s comment">tiho's comment</a>. As <a href="https://stackoverflow.com/questions/5188914/how-to-show-first-commit-by-git-log#comment19774504_5189296" title="Chris Johnsen&#39;s remark">Chris Johnsen notices</a>, <code>--max-parents</code> was introduced after this answer was posted.)</sub></p> <h2>Explanation</h2> <p>Technically, there may be more than one root commit. This happens when multiple previously independent histories are merged together. It is common when a project is integrated via a <a href="http://www.kernel.org/pub/software/scm/git/docs/howto/using-merge-subtree.html" rel="noreferrer">subtree merge</a>.</p> <p>The <code>git.git</code> repository has six root commits in its history graph (one each for Linus’s initial commit, <em>gitk</em>, some initially separate tools, <em>git-gui</em>, <em>gitweb</em>, and <em>git-p4</em>). In this case, we know that <code>e83c516</code> is the one we are probably interested in. It is both the earliest commit and a root commit.</p> <p>It is not so simple in the general case.</p> <p>Imagine that <em>libfoo</em> has been in development for a while and keeps its history in a Git repository (<code>libfoo.git</code>). Independently, the “bar” project has also been under development (in <code>bar.git</code>), but not for as long <em>libfoo</em> (the commit with the earliest date in <code>libfoo.git</code> has a date that precedes the commit with the earliest date in <code>bar.git</code>). At some point the developers of “bar” decide to incorporate <em>libfoo</em> into their project by using a subtree merge. Prior to this merge it might have been trivial to determine the “first” commit in <code>bar.git</code> (there was probably only one root commit). After the merge, however, there are multiple root commits and the earliest root commit actually comes from the history of <em>libfoo</em>, not “bar”.</p> <p>You can find all the root commits of the history DAG like this:</p> <pre><code>git rev-list --max-parents=0 HEAD </code></pre> <p>For the record, if <code>--max-parents</code> weren't available, this does also work:</p> <pre><code>git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$" </code></pre> <p>If you have useful tags in place, then <code>git name-rev</code> might give you a quick overview of the history:</p> <pre><code>git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$" | git name-rev --stdin </code></pre> <h2>Bonus</h2> <p>Use this often? Hard to remember? Add a git alias for quick access</p> <pre><code>git config --global alias.first "rev-list --max-parents=0 HEAD" </code></pre> <p>Now you can simply do</p> <pre><code>git first </code></pre>
5,280,347
Autoload classes from different folders
<p>This is how I autoload all the classes in my <code>controllers</code> folder,</p> <pre><code># auto load controller classes function __autoload($class_name) { $filename = 'class_'.strtolower($class_name).'.php'; $file = AP_SITE.'controllers/'.$filename; if (file_exists($file) == false) { return false; } include ($file); } </code></pre> <p>But I have classes in <code>models</code> folder as well and I want to autoload them too - what should I do? Should I duplicate the autoload above and just change the path to <code>models/</code> (but isn't this repetitive??)?</p> <p>Thanks.</p> <p><strong>EDIT:</strong></p> <p>these are my classes file names in the controller folder:</p> <pre><code>class_controller_base.php class_factory.php etc </code></pre> <p>these are my classes file names in the model folder:</p> <pre><code>class_model_page.php class_model_parent.php etc </code></pre> <p>this is how I name my controller classes class usually (I use underscores and lowcaps),</p> <pre><code>class controller_base { ... } class controller_factory { ... } </code></pre> <p>this is how I name my model classes class usually (I use underscores and lowcaps),</p> <pre><code>class model_page { ... } class model_parent { ... } </code></pre>
5,280,353
12
1
null
2011-03-12 03:26:18.94 UTC
42
2017-10-20 13:47:08.917 UTC
2011-03-12 04:05:34.897 UTC
null
413,225
null
413,225
null
1
45
php|oop|autoload
83,987
<p>You should name your classes so the underscore (<code>_</code>) translates to the directory separator (<code>/</code>). A few PHP frameworks do this, such as Zend and Kohana.</p> <p>So, you name your class <code>Model_Article</code> and place the file in <code>classes/model/article.php</code> and then your autoload does...</p> <pre><code>function __autoload($class_name) { $filename = str_replace('_', DIRECTORY_SEPARATOR, strtolower($class_name)).'.php'; $file = AP_SITE.$filename; if ( ! file_exists($file)) { return FALSE; } include $file; } </code></pre> <p>Also note you can use <a href="http://php.net/manual/en/function.spl-autoload-register.php" rel="nofollow noreferrer"><code>spl_autoload_register()</code></a> to make any function an autoloading function. It is also more flexible, allowing you to define multiple autoload type functions.</p> <blockquote> <p>If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.</p> </blockquote> <p><strong>Edit</strong></p> <blockquote> <p><strong>Note :</strong> <em>__autoload</em> has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged. Please refer to PHP documentation for more details. <a href="http://php.net/manual/en/function.autoload.php" rel="nofollow noreferrer">http://php.net/manual/en/function.autoload.php</a></p> </blockquote>
4,934,806
How can I find script's directory?
<p>Consider the following Python code:</p> <pre><code>import os print os.getcwd() </code></pre> <p>I use <code>os.getcwd()</code> to <a href="http://www.faqs.org/docs/diveintopython/regression_path.html" rel="noreferrer">get the script file's directory location</a>. When I run the script from the command line it gives me the correct path whereas when I run it from a script run by code in a Django view it prints <code>/</code>.</p> <p>How can I get the path to the script from within a script run by a Django view?</p> <p><strong>UPDATE:</strong><br> Summing up the answers thus far - <code>os.getcwd()</code> and <code>os.path.abspath()</code> both give the current working directory which may or may not be the directory where the script resides. In my web host setup <code><code>__file__</code></code> gives only the filename without the path.</p> <p>Isn't there any way in Python to (always) be able to receive the path in which the script resides?</p>
9,350,788
12
6
null
2011-02-08 15:14:48.217 UTC
107
2021-02-18 00:45:29.463 UTC
2021-02-18 00:45:29.463 UTC
null
355,230
null
348,545
null
1
631
python|directory|django-views|getcwd
623,712
<p>You need to call <code>os.path.realpath</code> on <code>__file__</code>, so that when <code>__file__</code> is a filename without the path you still get the dir path:</p> <pre><code>import os print(os.path.dirname(os.path.realpath(__file__))) </code></pre>
41,512,237
How to execute a shell command before the ENTRYPOINT via the dockerfile
<p>I have the following file for my nodejs project</p> <pre><code>FROM node:boron # Create app directory RUN mkdir -p /usr/src/app WORKDIR /usr/src/app # Install app dependencies COPY package.json /usr/src/app/ RUN npm install # Bundle app source COPY . /usr/src/app # Replace with env variable RUN envsubs &lt; fil1 &gt; file2 EXPOSE 8080 CMD [ "npm", "start" ] </code></pre> <p>I run the docker container with the -e flag providing the environment variable</p> <p>But I do not see the replacement. Will the Run ccommand be excuted when the env variable is available?</p>
41,518,225
4
4
null
2017-01-06 18:44:41.72 UTC
16
2022-05-07 21:23:49.92 UTC
2017-01-06 22:58:29.657 UTC
null
3,987,161
null
3,987,161
null
1
40
javascript|node.js|docker|environment-variables
60,561
<h2>Images are immutable</h2> <p>Dockerfile defines the build process for an image. Once built, the image is immutable (cannot be changed). Runtime variables are not something that would be baked into this immutable image. So Dockerfile is the wrong place to address this.</p> <h2>Using an entrypoint script</h2> <p>What you probably want to to do is override the default <code>ENTRYPOINT</code> with your own script, and have that script do something with environment variables. Since the entrypoint script would execute at runtime (when the container starts), this is the correct time to gather environment variables and do something with them.</p> <p>First, you need to adjust your Dockerfile to know about an entrypoint script. While Dockerfile is not directly involved in handling the environment variable, it still needs to know about this script, because the script will be baked into your image.</p> <p><strong>Dockerfile:</strong></p> <pre class="lang-none prettyprint-override"><code>COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh ENTRYPOINT [&quot;/entrypoint.sh&quot;] CMD [&quot;npm&quot;, &quot;start&quot;] </code></pre> <p>Now, write an entrypoint script which does whatever setup is needed <em>before</em> the command is run, and at the end, <code>exec</code> the command itself.</p> <p><strong>entrypoint.sh:</strong></p> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh # Where $ENVSUBS is whatever command you are looking to run $ENVSUBS &lt; file1 &gt; file2 npm install # This will exec the CMD from your Dockerfile, i.e. &quot;npm start&quot; exec &quot;$@&quot; </code></pre> <p>Here, I have included <code>npm install</code>, since you asked about this in the comments. I will note that this will run <code>npm install</code> <em>on every run</em>. If that's appropriate, fine, but I wanted to point out it will run every time, which will add some latency to your startup time.</p> <p>Now rebuild your image, so the entrypoint script is a part of it.</p> <h2>Using environment variables at runtime</h2> <p>The entrypoint script knows how to use the environment variable, but you still have to tell Docker to import the variable at runtime. You can use the <code>-e</code> flag to <code>docker run</code> to do so.</p> <pre class="lang-none prettyprint-override"><code>docker run -e &quot;ENVSUBS=$ENVSUBS&quot; &lt;image_name&gt; </code></pre> <p>Here, Docker is told to define an environment variable <code>ENVSUBS</code>, and the value it is assigned is the value of <code>$ENVSUBS</code> from the current shell environment.</p> <h2>How entrypoint scripts work</h2> <p>I'll elaborate a bit on this, because in the comments, it seemed you were a little foggy on how this fits together.</p> <p>When Docker starts a container, it executes one (and only one) command inside the container. This command becomes PID 1, just like <code>init</code> or <code>systemd</code> on a typical Linux system. This process is responsible for running any other processes the container needs to have.</p> <p>By default, the <code>ENTRYPOINT</code> is <code>/bin/sh -c</code>. You can override it in Dockerfile, or docker-compose.yml, or using the docker command.</p> <p>When a container is started, Docker runs the entrypoint command, and passes the command (<code>CMD</code>) to it as an argument list. Earlier, we defined our own <code>ENTRYPOINT</code> as <code>/entrypoint.sh</code>. That means that in your case, this is what Docker will execute in the container when it starts:</p> <pre class="lang-none prettyprint-override"><code>/entrypoint.sh npm start </code></pre> <p>Because <code>[&quot;npm&quot;, &quot;start&quot;]</code> was defined as the command, that is what gets passed as an argument list to the entrypoint script.</p> <p>Because we defined an environment variable using the <code>-e</code> flag, this entrypoint script (and its children) will have access to that environment variable.</p> <p>At the end of the entrypoint script, we run <code>exec &quot;$@&quot;</code>. Because <code>$@</code> expands to the argument list passed to the script, this will run</p> <pre class="lang-none prettyprint-override"><code>exec npm start </code></pre> <p>And because <code>exec</code> runs its arguments as a command, <em>replacing</em> the current process with itself, when you are done, <code>npm start</code> becomes PID 1 in your container.</p> <h2>Why you can't use multiple CMDs</h2> <p>In the comments, you asked whether you can define multiple <code>CMD</code> entries to run multiple things.</p> <p>You can only have one <code>ENTRYPOINT</code> and one <code>CMD</code> defined. These are not used at all during the build process. Unlike <code>RUN</code> and <code>COPY</code>, they are not executed during the build. They are added as metadata items to the image once it is built.</p> <p>It is only later, when the image is run as a container, that these metadata fields are read, and used to start the container.</p> <p>As mentioned earlier, the entrypoint is what is really run, and it is passed the <code>CMD</code> as an argument list. The reason they are separate is partly historical. In early versions of Docker, <code>CMD</code> was the only available option, and <code>ENTRYPOINT</code> was fixed as being <code>/bin/sh -c</code>. But due to situations like this one, Docker eventually allowed <code>ENTRYPOINT</code> to be defined by the user.</p>
12,459,635
d3dx11.h not in Windows 8.0 kit
<p>My development platform is windows 7 x64. I have installed VS2012 and I'd like to compile a project that includes some Dx11 code.</p> <p>Specifically, it includes the following files:</p> <pre><code>#include &lt;d3dx11.h&gt; #include &lt;d3dx10.h&gt; </code></pre> <p>and links to </p> <pre><code>#pragma comment (lib, "d3dx11.lib") #pragma comment (lib, "d3dx10.lib") </code></pre> <p>I already have VS2011 installed on my development machine, but I wanted to try the unit testing facilities in VS2012 for native C++.</p> <p>Due to having VS2011 installed and working on DirectShow code, I have the Windows 7.1 SDK installed.</p> <p>VS2012 picked this up and had references to the 7.1 SDK, but compilation of my project under VS2012 with the 7.1 SDK referenced gave errors:</p> <pre><code>"warning C4005: '__useHeader' : macro redefinition" </code></pre> <p>I googled this and found <a href="http://social.msdn.microsoft.com/Forums/sv-SE/vcgeneral/thread/a7fd6119-825a-4d9a-9570-7b9cf6ed1bc6">a query like mine on social.msdn.microsoft.com</a>. and the solution recommended linking with the Windows 8 kit instead of the 7.1 SDK in order to solve this problem.</p> <p>The Windows 8 kit includes headers like d3d11.h, but not d3dx11.h. </p> <p>How can I include d3dx11 (from the Dx SDK) along with the windows 8 kit, but without getting multiple "macro redefinition" errors?</p>
12,459,951
1
0
null
2012-09-17 12:54:29.197 UTC
10
2014-01-16 22:48:25.51 UTC
null
null
null
null
1,350,092
null
1
15
windows-8|directx|visual-studio-2012|winapi
15,817
<p>I found the following rather annoying quote in <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ee663275%28v=vs.85%29.aspx" rel="noreferrer">this MSDN page</a>.</p> <blockquote> <p>D3DX is not considered the canonical API for using Direct3D in Windows 8 and therefore isn't included with the corresponding Windows SDK. Investigate alternate solutions for working with the Direct3D API. </p> <p>For legacy projects, such as the Windows 7 (and earlier) DirectX SDK samples, the following steps are necessary to build applications with D3DX using the DirectX SDK:</p> <hr> <p>Modify the project’s VC++ directories as follows to use the right order for SDK headers and libraries.</p> <p>i. Open Properties for the project and select the VC++ Directories page.<br> ii. Select All Configurations and All Platforms.<br> iii. Set these directories as follows:</p> <blockquote> <blockquote> <p>Executable Directories: (On right-side drop-down) </p> <p>Include Directories: $(IncludePath);$(DXSDK_DIR)Include </p> <p>Include Library Directories: $(LibraryPath);$(DXSDK_DIR)Lib\x86</p> </blockquote> </blockquote> <p>iv. Click Apply.<br> v. Choose the x64 Platform. vi. Set the Library directory as follows: </p> <blockquote> <blockquote> <p>Library Directories: $(LibraryPath);$(DXSDK_DIR)Lib\x64</p> </blockquote> </blockquote> <p>Wherever "d3dx9.h", "d3dx10.h", or "d3dx11.h" are included in your project, be sure to explicitly include "d3d9.h", "d3d10.h" and "dxgi.h", or "d3d11.h" and "dxgi.h" first to ensure you are picking up the newer version. </p> <p>You can disable warning C4005 if needed; however, this warning indicates you are using the older version of these headers.</p> <p>Remove all references to DXGIType.h in your project. This header doesn't exist in the Windows SDK, and the DirectX SDK version conflicts with the new winerror.h.</p> <p>All D3DX DLLs are installed onto your development computer by the DirectX SDK installation. Ensure that the necessary D3DX dependencies are redistributed with any sample or with your application if it is moved to another machine.</p> <p>Be aware that replacement technologies for current uses of D3DX11 include DirectXTex and DirectXTK. D3DXMath is replaced by DirectXMath.</p> </blockquote> <p>FFS Microsoft, please don't change the API's mid-version like this!!!</p>
12,313,961
Hidden TextArea
<p>In html for textbox it can be hidden by using <code>&lt;input type="hidden" name="hide"/&gt;</code> but for TextArea if I want to hide how should I use?</p> <p>Anyone help me please,</p> <p>Thanks,</p>
12,313,981
5
1
null
2012-09-07 07:53:02.777 UTC
5
2019-06-17 17:34:52.857 UTC
2012-09-07 08:02:24.5 UTC
null
1,084,437
null
1,606,816
null
1
32
html|css
127,991
<p>Set CSS <code>display</code> to <code>none</code> for textarea</p> <pre><code>&lt;textarea name="hide" style="display:none;"&gt;&lt;/textarea&gt; </code></pre>
12,269,733
What is the difference between "Module Dependencies" and "Libraries" in IntelliJ IDEA?
<p>What is the difference between "Module Dependencies" and "Libraries" in IntelliJ IDEA when you want to add a <code>.jar</code> library to your project? Also, What is the "Export" check box when you are adding your <code>.jar</code> library to the "Module Dependencies" in IntelliJ IDEA? </p> <p>In each of these ways, how are the classes and code inside the included <code>.jar</code> library integrated into your final project (code) when creating the newly generated <code>.jar</code> file?</p>
12,271,315
4
1
null
2012-09-04 18:59:15.353 UTC
13
2019-04-25 13:34:42.353 UTC
2016-03-25 23:29:25.433 UTC
null
2,841,459
null
774,437
null
1
38
java|jar|module|intellij-idea|dependencies
22,284
<p>Module dependencies are classes, archives, libraries and resources that your module files references. While a library is a set of class files stored in an archive or directory. </p> <p>Export check means if checked then this library will be implicitly added to the other module that references this one.</p> <p>To create a <em>.jar</em> file you need create an artifact. Artifact is a placeholder of the building output. There's predefined templates for creating <em>.jar</em>, <em>.war</em>, <em>.ear</em> archives. You can choose jar to build a jar artifact. By default it's defined empty and you need to define content of the artifact. You can drag-n-drop compiled output to it but don't do it with library archives. Because libraries in this case will be packaged inside the <em>.jar</em> file and you will be required to create a separate classloader to load them before your application start. Instead you change the artifact type to <em>Other</em> and drag <em>.jar</em> and dependent libraries into <em>output root</em>. This way library archives will be copied along with created <em>.jar</em>. You also need to create a MANIFEST.MF and specify <em>Class-Path</em> there for dependent libraries. All files will be stored in the directory you specify for building the artifact. You can build it using <em>Build Artifact</em> menu. </p>
43,992,806
How to get datatypes of all columns using a single command [ Python - Pandas ]?
<p>I want to see the datatype of all columns stored in my dataframe without iterating over them. What is the way?</p>
43,992,862
2
2
null
2017-05-16 04:57:20.43 UTC
7
2020-10-20 03:20:30.297 UTC
null
null
null
null
2,966,617
null
1
25
python|pandas
46,075
<p><a href="http://pandas.pydata.org/pandas-docs/stable/10min.html" rel="noreferrer">10 min to pandas</a> has nice example for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dtypes.html" rel="noreferrer"><code>DataFrame.dtypes</code></a>:</p> <pre><code>df2 = pd.DataFrame({ 'A' : 1., 'B' : pd.Timestamp('20130102'), 'C' : pd.Series(1,index=list(range(4)),dtype='float32'), 'D' : np.array([3] * 4,dtype='int32'), 'E' : pd.Categorical(["test","train","test","train"]), 'F' : 'foo' }) print (df2) A B C D E F 0 1.0 2013-01-02 1.0 3 test foo 1 1.0 2013-01-02 1.0 3 train foo 2 1.0 2013-01-02 1.0 3 test foo 3 1.0 2013-01-02 1.0 3 train foo print (df2.dtypes) A float64 B datetime64[ns] C float32 D int32 E category F object dtype: object </code></pre> <p>But with <code>dtypes=object</code> it is a bit complicated (generally, obviously it is <code>string</code>):</p> <p>Sample:</p> <pre><code>df = pd.DataFrame({'strings':['a','d','f'], 'dicts':[{'a':4}, {'c':8}, {'e':9}], 'lists':[[4,8],[7,8],[3]], 'tuples':[(4,8),(7,8),(3,)], 'sets':[set([1,8]), set([7,3]), set([0,1])] }) print (df) dicts lists sets strings tuples 0 {'a': 4} [4, 8] {8, 1} a (4, 8) 1 {'c': 8} [7, 8] {3, 7} d (7, 8) 2 {'e': 9} [3] {0, 1} f (3,) </code></pre> <p>All values have same <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dtypes.html" rel="noreferrer"><code>dtypes</code></a>:</p> <pre><code>print (df.dtypes) dicts object lists object sets object strings object tuples object dtype: object </code></pre> <p>But <code>type</code> is different, if need check it by loop:</p> <pre><code>for col in df: print (df[col].apply(type)) 0 &lt;class 'dict'&gt; 1 &lt;class 'dict'&gt; 2 &lt;class 'dict'&gt; Name: dicts, dtype: object 0 &lt;class 'list'&gt; 1 &lt;class 'list'&gt; 2 &lt;class 'list'&gt; Name: lists, dtype: object 0 &lt;class 'set'&gt; 1 &lt;class 'set'&gt; 2 &lt;class 'set'&gt; Name: sets, dtype: object 0 &lt;class 'str'&gt; 1 &lt;class 'str'&gt; 2 &lt;class 'str'&gt; Name: strings, dtype: object 0 &lt;class 'tuple'&gt; 1 &lt;class 'tuple'&gt; 2 &lt;class 'tuple'&gt; Name: tuples, dtype: object </code></pre> <p>Or first value of columns with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iat.html" rel="noreferrer"><code>iat</code></a>:</p> <pre><code>print (type(df['strings'].iat[0])) &lt;class 'str'&gt; print (type(df['dicts'].iat[0])) &lt;class 'dict'&gt; print (type(df['lists'].iat[0])) &lt;class 'list'&gt; print (type(df['tuples'].iat[0])) &lt;class 'tuple'&gt; print (type(df['sets'].iat[0])) &lt;class 'set'&gt; </code></pre>
18,945,669
How to run a script at a certain time on Linux?
<p>I have a <strong>text file containing a specific date and time.</strong> I want to be able to <strong>run a script at the time specified in that file.</strong> How would you achieve that? Create another script that runs in background (sort of a deamon) and checks every second if the current time is matching the time in the file? Is there another way? The machine is a <strong>linux</strong> server , Debian wheezy. Thanks in advance</p>
18,945,782
4
4
null
2013-09-22 15:47:40.743 UTC
31
2018-06-19 16:47:42.583 UTC
2018-06-19 16:47:42.583 UTC
null
6,862,601
null
1,596,746
null
1
96
linux|bash|scripting|debian
198,171
<p>Look at the following:</p> <pre><code>echo "ls -l" | at 07:00 </code></pre> <p>This code line executes "ls -l" at a specific time. This is an example of executing something (a command in my example) at a specific time. "at" is the command you were really looking for. You can read the specifications here:</p> <p><a href="http://manpages.ubuntu.com/manpages/precise/en/man1/at.1posix.html" rel="noreferrer">http://manpages.ubuntu.com/manpages/precise/en/man1/at.1posix.html</a> <a href="http://manpages.ubuntu.com/manpages/xenial/man1/at.1posix.html" rel="noreferrer">http://manpages.ubuntu.com/manpages/xenial/man1/at.1posix.html</a></p> <p>Hope it helps!</p>
3,344,863
Include row number in query result (SQL Server)
<p>I think each row in sql server is given a unique number. How can I include that in my SQL query results?</p>
3,344,910
3
1
null
2010-07-27 14:51:46.91 UTC
2
2016-05-18 16:43:01.097 UTC
2016-05-18 16:43:01.097 UTC
null
122,139
null
260,594
null
1
12
sql|sql-server
76,624
<p>If you are referring to the row number provided by Management Studio when you run a query, there is no way to get that because it does not really exist. Management Studio generates that on the fly. You can however, recreate a sequential number using the <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx" rel="noreferrer">ROW_NUMBER</a> ranking function if you are using SQL Server 2005 or later. Note you should never assume the database will return the rows in a specified order unless you include an Order By statement. So your query might look like:</p> <pre><code>Select .... , Row_Number() Over ( Order By T.SomeColumn ) As Num From Table As T Order By T.SomeColumn </code></pre> <p>The Order By in the Over clause is used to determine the order for creating the sequential numbers. The Order By clause at the end of the query is used to determine the order of the rows in the output (i.e. the order for the sequence number and the order of the rows can be different).</p>
3,414,592
Disable or speed up DLTK indexing in Eclipse PDT?
<p>I am using Eclipse PDT Helios with Aptana Studio on Windows XP SP3. Very often, my workflow is interrupted because Eclipse starts a <code>DLTK</code> indexing process that lasts 30 seconds, sometimes up to 2 minutes - which is annoying.</p> <p>I wonder if there is any way to:</p> <ul> <li>Either turn that off or</li> <li>Run the DLTK indexing process less frequently.</li> </ul> <p>I didn't find any possibility to change regarding parameters in Window > Preferences. </p>
3,415,828
3
0
null
2010-08-05 12:20:44.697 UTC
11
2012-12-17 14:37:35.267 UTC
2011-06-27 23:44:10.9 UTC
null
283,854
null
283,854
null
1
26
php|eclipse|indexing|eclipse-pdt|helios
33,094
<p>PDT 2.2 (the one in Helios) is using a local database engine, H2, to store information. I wrote a <a href="http://www.nwiresoftware.com/blogs/nwire/2010/09/five-tips-speeding-eclipse-pdt-and-nwire" rel="noreferrer">post highlighting how to improve the performance of the new indexer</a>. </p> <p>There might be another way, but it's requires hacking and I haven't tried it myself since the early builds of PDT 2.2 so YMMV: use a newer version of H2. You see, PDT 2.2 uses H2 version 1.1.117. The current version is 1.2.140. Basically, it involves downloading a newer version from the <a href="http://h2database.com/html/main.html" rel="noreferrer">h2 site</a>, and replacing the current H2 JAR in the plugins folder with this Jar. I should really write a blog post about it. I just need to find some time...</p>
36,776,606
Cross-Domain OWIN Authentication for Multi-Tenanted ASP.NET MVC Application
<p>I am using OWIN Authentication for a Multi-Tenant ASP.NET MVC application.</p> <p>The application and authentication sits on one server in a single application but can be accessed via many domains and subdomains. For instance:</p> <pre><code>www.domain.com site1.domain.com site2.domain.com site3.domain.com www.differentdomain.com site4.differentdomain.com site5.differentdomain.com site6.differentdomain.com </code></pre> <p>I would like to allow a user to login on any of these domains and have their authentication cookie work regardless of which domain is used to access the application.</p> <p>This is how I have my authentication setup:</p> <pre><code>public void ConfigureAuthentication(IAppBuilder Application) { Application.CreatePerOwinContext&lt;RepositoryManager&gt;((x, y) =&gt; new RepositoryManager(new SiteDatabase(), x, y)); Application.UseCookieAuthentication(new CookieAuthenticationOptions { CookieName = "sso.domain.com", CookieDomain = ".domain.com", LoginPath = new PathString("/login"), AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity&lt;UserManager, User, int&gt;( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentityCallback: (manager, user) =&gt; user.GenerateClaimsAsync(manager), getUserIdCallback: (claim) =&gt; int.Parse(claim.GetUserId())) } }); Application.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); } </code></pre> <p>I have also explicitly set a Machine Key for my application in the root web.config of my application:</p> <pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;machineKey decryption="AES" decryptionKey="&lt;Redacted&gt;" validation="&lt;Redacted&gt;" validationKey="&lt;Redacted&gt;" /&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <h2>Update</h2> <p>This setup works as expected when I navigate between domain.com and site1.domain.com, but now it is not letting me login to differentdomain.com.</p> <p>I understand that cookies are tied to a single domain. But what is the easiest way of persisting a login across multiple domains? Is there a way for me to read a cookie from a different domain, decrypt it, and recreate a new cookie for the differentdomain.com?</p>
37,098,110
4
17
null
2016-04-21 17:26:27.38 UTC
9
2016-05-09 06:58:21.267 UTC
2016-05-05 04:31:30.713 UTC
null
907,734
null
907,734
null
1
9
c#|asp.net|asp.net-mvc|owin|multi-tenant
7,557
<p>Since you need something simple, consider this. In your particular setup, where you really have just one app accessible by multiple domain names, you can make simple "single sign on". First you have to choose single domain name which is responsible for initial authentication. Let's say that is <code>auth.domain.com</code> (remember it's just domain name - all your domains still point to single application). Then:</p> <ol> <li>Suppose user is on <code>domain1.com</code> and you found he is not logged-in (no cookie). You direct him to <code>auth.domain.com</code> login page.</li> <li><p>Suppose you are logged-in there already. You see that request came from <code>domain1.com</code> (via Referrer header, or you can pass domain explicitly). You verify that is your trusted domain (important), and generate auth token like this:</p> <pre><code>var token = FormsAuthentication.Encrypt( new FormsAuthenticationTicket(1, "username", DateTime.Now, DateTime.Now.AddHours(8), true, "some relevant data")); </code></pre> <p>If you do not use forms authentication - just protect some data with machine key:</p> <pre><code>var myTicket = new MyTicket() { Username = "username", Issued = DateTime.Now, Expires = DateTime.Now.AddHours(8), TicketExpires = DateTime.Now.AddMinutes(1) }; using (var ms = new MemoryStream()) { new BinaryFormatter().Serialize(ms, myTicket); var token = Convert.ToBase64String(MachineKey.Protect(ms.ToArray(), "auth")); } </code></pre> <p>So basically you generate your token in the same way asp.net does. Since your sites are all in the same app - no need to bother about different machine keys.</p></li> <li><p>You redirect user back to <code>domain1.com</code>, passing encrypted token in query string. See <a href="https://security.stackexchange.com/a/17733">here</a> for example about security implications of this. Of course I suppose you use https, otherwise no setup (be it "single sign on" or not) is secure anyway. This is in some ways similar to asp.net "cookieless" authentication.</p></li> <li><p>On <code>domain1.com</code> you see that token and verify:</p> <pre><code>var ticket = FormsAuthentication.Decrypt(token); var userName = ticket.Name; var expires = ticket.Expiration; </code></pre> <p>Or with:</p> <pre><code>var unprotected = MachineKey.Unprotect(Convert.FromBase64String(token), "auth"); using (var ms = new MemoryStream(unprotected)) { var ticket = (MyTicket) new BinaryFormatter().Deserialize(ms); var user = ticket.Username; } </code></pre></li> <li>You create cookie on <code>domain1.com</code> using information you received in token and redirect user back to the location he came from initially.</li> </ol> <p>So there is a bunch of redirects but at least user have to type his password just once. </p> <p>Update to answer your questions.</p> <ol> <li><p>Yes if you find that user is authenticated on domain1.com you redirect to auth.domain.com. But after auth.domain.com redirects back with token - you create a cookie at domain1.com as usual and user becomes logged-in a domain1.com. So this redirect happens just once per user (just as with usual log in).</p></li> <li><p>You can make request to auth.domain.com with javascript (XmlHttpRequest, or just jquery.get\post methods). But note you have to configure CORS to allow that (see <a href="http://benfoster.io/blog/aspnet-webapi-cors" rel="nofollow noreferrer">here</a> for example). What is CORS in short? When siteB is requested via javascript from siteA (another domain) - browser will first ask siteB if it trusts siteA to make such requests. It does so with adding special headers to request and it wants to see some special headers in response. Those headers you need to add to allow domain1.com to request auth.domain.com via javascript. When this is done - make such request from domain1.com javascript to auth.domain.com and if logged in - auth.domain.com will return you token as described above. Then make a query (again with javascript) to domain1.com with that token so that domain1.com can set a cookie in response. Now you are logged in at domain1.com with cookie and can continue. Why we need all this at all, even if we have one application just reachable from different domains? Because browser does not know that and treats them completely different. In addition to that - http protocol is stateless and every request is not related to any other, so our server also needs confirmation that request A and B made by the same user, hence those tokens.</p></li> <li><p>Yes, <code>HttpServerUtility.UrlTokenEncode</code> is perfectly fine to use here, even better than just <code>Convert.ToBase64String</code>, because you need to url encode it anyway (you pass it in query string). But if you will not pass token in query string (for example you would use javascript way above - you won't need to url encode it, so don't use <code>HttpServerUtility.UrlTokenEncode</code> in that case.</p></li> </ol>
18,892,281
Most optimized way of concatenation in strings
<p>We always came across many situation on daily basis wherein we have to do tedious and very many string operations in our code. We all know that string manipulations are expensive operations. I would like to know which is the least expensive among the available versions. </p> <p>The most common operations is concatenation(This is something that we can control to some extent). What is the best way to concatenate std::strings in C++ and various workarounds to speed up concatenation?</p> <p>I mean,</p> <pre><code>std::string l_czTempStr; 1).l_czTempStr = "Test data1" + "Test data2" + "Test data3"; 2). l_czTempStr = "Test data1"; l_czTempStr += "Test data2"; l_czTempStr += "Test data3"; 3). using &lt;&lt; operator 4). using append() </code></pre> <p>Also, do we get any advantage of using CString over std::string?</p>
18,892,355
9
11
null
2013-09-19 10:31:21.653 UTC
47
2022-02-18 10:18:18.693 UTC
2016-10-08 00:07:14.24 UTC
null
6,410,484
null
2,067,419
null
1
85
c++|string|concatenation
67,502
<p>Here is a small test suite:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;chrono&gt; #include &lt;sstream&gt; int main () { typedef std::chrono::high_resolution_clock clock; typedef std::chrono::duration&lt;float, std::milli&gt; mil; std::string l_czTempStr; std::string s1="Test data1"; auto t0 = clock::now(); #if VER==1 for (int i = 0; i &lt; 100000; ++i) { l_czTempStr = s1 + "Test data2" + "Test data3"; } #elif VER==2 for (int i = 0; i &lt; 100000; ++i) { l_czTempStr = "Test data1"; l_czTempStr += "Test data2"; l_czTempStr += "Test data3"; } #elif VER==3 for (int i = 0; i &lt; 100000; ++i) { l_czTempStr = "Test data1"; l_czTempStr.append("Test data2"); l_czTempStr.append("Test data3"); } #elif VER==4 for (int i = 0; i &lt; 100000; ++i) { std::ostringstream oss; oss &lt;&lt; "Test data1"; oss &lt;&lt; "Test data2"; oss &lt;&lt; "Test data3"; l_czTempStr = oss.str(); } #endif auto t1 = clock::now(); std::cout &lt;&lt; l_czTempStr &lt;&lt; '\n'; std::cout &lt;&lt; mil(t1-t0).count() &lt;&lt; "ms\n"; } </code></pre> <p>On <a href="http://coliru.stacked-crooked.com/a/c37127be5cf87ac6" rel="noreferrer">coliru</a>:</p> <p>Compile with the following:</p> <blockquote> <p>clang++ -std=c++11 -O3 -DVER=1 -Wall -pedantic -pthread main.cpp</p> </blockquote> <p>21.6463ms</p> <blockquote> <p>-DVER=2</p> </blockquote> <p>6.61773ms</p> <blockquote> <p>-DVER=3</p> </blockquote> <p>6.7855ms</p> <blockquote> <p>-DVER=4</p> </blockquote> <p>102.015ms</p> <p>It looks like <code>2)</code>, <code>+=</code> is the winner.</p> <p>(Also compiling with and without <code>-pthread</code> seems to affect the timings)</p>
8,677,805
Formatting numbers (decimal places, thousands separators, localization, etc) with CSS
<p>Is it possible to format numbers with CSS? That is: decimal places, decimal separator, thousands separator, etc.</p>
52,729,623
14
6
null
2011-12-30 09:01:53.893 UTC
20
2022-07-29 09:17:18.113 UTC
2022-05-05 13:58:45.103 UTC
null
5,318,303
null
463,621
null
1
167
css|number-formatting
226,510
<p>Unfortunately, it's not possible with CSS currently, but you can use <code>Number.prototype.toLocaleString()</code>. It can also format for other number formats, e.g. latin, arabic, etc.</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString</a></p>
20,477,823
<select> HTML element with height
<p>Does anyone know of a way to style an HTML select element so that it has a certain height and looks good across browsers? I've tried simply setting height in CSS but the text inside the box is vertically off-center in Firefox.</p> <pre><code>&lt;select style="height:1.8em;"&gt; </code></pre> <p>This is not a duplicate question. The other question asks about the height of the drop-down box that appears when you click on a select element. My question is about the height of the unclicked select element.</p>
20,477,988
2
5
null
2013-12-09 18:23:03.363 UTC
14
2013-12-10 16:43:28.65 UTC
2013-12-10 16:43:28.65 UTC
null
2,225,632
null
2,225,632
null
1
44
html|css
176,033
<p>I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE. </p> <p><strong><em>For Safari/Chrome</em></strong>, set the <code>height</code> and <code>line-height</code> you want for your <code>&lt;select /&gt;</code>.</p> <p><strong><em>For Firefox</em></strong>, we're going to <em>kill</em> Firefox's default padding and border, then set our own. Set padding to whatever you like.</p> <p><strong><em>For IE 8+</em></strong>, just like Chrome, we've set the <code>height</code> and <code>line-height</code> properties. These two <code>media queries</code> can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.</p> <p><strong>Please note</strong>, for the <code>height/line-height</code> property to work in Chrome/Safari OSX, you must set the <code>background</code> to a custom value. I changed the color in my example.</p> <p>Here's a jsFiddle of the below: <a href="http://jsfiddle.net/URgCB/4/" rel="noreferrer">http://jsfiddle.net/URgCB/4/</a></p> <p><strong>For the non-hack route, why not use a custom select plug-in via jQuery? Check out this:</strong> <a href="http://codepen.io/wallaceerick/pen/ctsCz" rel="noreferrer">http://codepen.io/wallaceerick/pen/ctsCz</a></p> <p><strong>HTML:</strong></p> <pre><code>&lt;select&gt; &lt;option&gt;Here's one option&lt;/option&gt; &lt;option&gt;here's another option&lt;/option&gt; &lt;/select&gt; </code></pre> <p><strong>CSS:</strong></p> <pre><code>@media screen and (-webkit-min-device-pixel-ratio:0) { /*safari and chrome*/ select { height:30px; line-height:30px; background:#f4f4f4; } } select::-moz-focus-inner { /*Remove button padding in FF*/ border: 0; padding: 0; } @-moz-document url-prefix() { /* targets Firefox only */ select { padding: 15px 0!important; } } @media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */ select { height:30px; line-height:30px; } } </code></pre>
20,562,860
How do I vertically center an H1 in a div?
<p>First of all, my apologies. I know there are various solutions posted for this issue here, but for the life of me I can't get any of them to work. </p> <p>For a responsive website I'm trying to center an h1 in a div. </p> <p>Centering horizontally is not an issue, but I'm having problems getting it centered vertically. Presumably I'm doing something wrong or misunderstanding the explanations I found here (or maybe both).</p> <p>So as I'm probably interpreting earlier solutions given the wrong way, could someone please explain what exactly I have to add to the code beneath to get the h1 to center vertically? </p> <p>(To make this question relevant to as much people as possible, I've already stripped the code of all my previous attempts to do so myself.) </p> <p>CSS: </p> <pre><code>html, body { height: 100%; margin: 0; } #section1 { min-height: 90%; text-align:center } </code></pre> <p>HTML: </p> <pre><code>&lt;div class="section" id="section1"&gt; &lt;h1&gt;Lorem ipsum&lt;/h1&gt; &lt;/div&gt; </code></pre>
20,563,075
6
7
null
2013-12-13 09:17:32.573 UTC
19
2021-07-02 13:08:45.67 UTC
null
null
null
null
2,987,068
null
1
60
html|css|responsive-design
136,257
<p>you can achieve vertical aligning with <code>display:table-cell</code>:</p> <pre class="lang-css prettyprint-override"><code>#section1 { height: 90%; text-align:center; display:table; width:100%; } #section1 h1 {display:table-cell; vertical-align:middle} </code></pre> <p><a href="http://jsfiddle.net/CMHx4/">Example</a></p> <p><strong>Update - CSS3</strong></p> <p>For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:</p> <pre class="lang-css prettyprint-override"><code>#section1 { height: 90%; width:100%; display:flex; align-items: center; justify-content: center; } </code></pre> <p><a href="http://jsfiddle.net/peteng/CMHx4/24/">Updated fiddle</a></p>
25,948,963
Xcode 6.0.1 not displaying memory usage
<p>I've upgraded to Xcode 6.0.1 from 5.1 and when I'm running my app, I can't see memory usage in debug navigator:</p> <p><img src="https://i.stack.imgur.com/9bHLn.png" alt="enter image description here"></p> <p>I'm getting memory warnings. Yes, I could profile my app instruments without debugging, but seeing direct memory usage simply while debugging helps me a lot. How can I re-enable this functionality? I've restarted Xcode, rebuilt my project etc but I still can't see memory usage. The problem is present both when debugging on device or on the simulator. When I click the memory tab, I also get this weird "zeroed out" dashboard:</p> <p><img src="https://i.stack.imgur.com/Xxpf9.png" alt="enter image description here"></p>
25,992,910
1
6
null
2014-09-20 12:52:15.67 UTC
6
2015-06-12 17:37:36.357 UTC
2014-09-21 13:01:34.167 UTC
null
811,405
null
811,405
null
1
57
ios|xcode|debugging|ios8|xcode6
11,611
<p>I have resolved disabling Memory Guard diagnostic in the Scheme. From Xcode: Menu Product -> Scheme -> Edit Scheme... -> Diagnostic Tab -> uncheck all Guard options</p> <p><strong>If still doesn't work, try to disable (if enabled) the "Enable Zombie Object" checkbox.</strong></p>
26,266,525
Move the string out of a std::ostringstream
<p>If I construct a string made of a list of space separated floating point values using <code>std::ostringstream</code>:</p> <pre><code>std::ostringstream ss; unsigned int s = floatData.size(); for(unsigned int i=0;i&lt;s;i++) { ss &lt;&lt; floatData[i] &lt;&lt; " "; } </code></pre> <p>Then I get the result in a <code>std::string</code>:</p> <pre><code>std::string textValues(ss.str()); </code></pre> <p>However, this will cause an unnecessary deep copy of the string contents, as <code>ss</code> will not be used anymore.</p> <p>Is there any way to construct the string without copying the entire content?</p>
26,291,586
6
20
null
2014-10-08 21:11:23.683 UTC
6
2021-06-11 23:15:24.33 UTC
2017-05-08 21:17:17.61 UTC
null
3,002,139
null
2,042,388
null
1
32
c++|c++11|move-semantics|ostringstream
7,062
<p><code>std::ostringstream</code> offers no public interface to access its in-memory buffer unless it non-portably supports <code>pubsetbuf</code> (but even then your buffer is fixed-size, see <a href="http://en.cppreference.com/w/cpp/io/basic_stringbuf/setbuf" rel="noreferrer">cppreference example</a>)</p> <p>If you want to torture some string streams, you could access the buffer using the protected interface:</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;vector&gt; struct my_stringbuf : std::stringbuf { const char* my_str() const { return pbase(); } // pptr might be useful too }; int main() { std::vector&lt;float&gt; v = {1.1, -3.4, 1/7.0}; my_stringbuf buf; std::ostream ss(&amp;buf); for(unsigned int i=0; i &lt; v.size(); ++i) ss &lt;&lt; v[i] &lt;&lt; ' '; ss &lt;&lt; std::ends; std::cout &lt;&lt; buf.my_str() &lt;&lt; '\n'; } </code></pre> <p>The standard C++ way of directly accessing an auto-resizing output stream buffer is offered by <code>std::ostrstream</code>, deprecated in C++98, but still standard C++14 and counting. </p> <pre><code>#include &lt;iostream&gt; #include &lt;strstream&gt; #include &lt;vector&gt; int main() { std::vector&lt;float&gt; v = {1.1, -3.4, 1/7.0}; std::ostrstream ss; for(unsigned int i=0; i &lt; v.size(); ++i) ss &lt;&lt; v[i] &lt;&lt; ' '; ss &lt;&lt; std::ends; const char* buffer = ss.str(); // direct access! std::cout &lt;&lt; buffer &lt;&lt; '\n'; ss.freeze(false); // abomination } </code></pre> <p>However, I think the cleanest (and the fastest) solution is <a href="http://www.boost.org/doc/libs/release/libs/spirit/doc/html/spirit/karma.html" rel="noreferrer">boost.karma</a></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;boost/spirit/include/karma.hpp&gt; namespace karma = boost::spirit::karma; int main() { std::vector&lt;float&gt; v = {1.1, -3.4, 1/7.0}; std::string s; karma::generate(back_inserter(s), karma::double_ % ' ', v); std::cout &lt;&lt; s &lt;&lt; '\n'; // here's your string } </code></pre>
11,291,845
Plot the results of a multivariate logistic regression model in R
<p>I would like to plot the results of a multivariate logistic regression analysis (GLM) for a specific independent variables adjusted (i.e. independent of the confounders included in the model) relationship with the outcome (binary).</p> <p>I have seen posts that recommend the following method using the <code>predict</code> command followed by <code>curve</code>, here's an example;</p> <pre><code>x &lt;- data.frame(binary.outcome, cont.exposure) model &lt;- glm(binary.outcome ~ cont.exposure, family=binomial, data=x) plot(cont.exposure, binary.outcome, xlab="Temperature",ylab="Probability of Response") curve(predict(model, data.frame(cont.exposure=x), type="resp"), add=TRUE, col="red") </code></pre> <p>However this does not seem to work for multivariate regression models. I get the following error when I add 'age' (arbitrary - could be any variable of same length) as a confounding variable;</p> <pre><code>&gt; x &lt;- data.frame(binary.outcome, cont.exposure, age) &gt; model &lt;- glm(binary.outcome ~ cont.exposure + age, family=binomial, data=x) &gt; plot(cont.exposure, binary.outcome, xlab="Temperature",ylab="Probability of Response") &gt; curve(predict(model, data.frame(cont.exposure=x), type="resp"), add=TRUE, col="red") Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) : variable lengths differ (found for 'age') In addition: Warning message: 'newdata' had 101 rows but variable(s) found have 698 rows </code></pre> <hr> <p>The above model is a simplified version of the models I'd like to run, but the principle is the same; <strong>I would like to plot the relationship between a binary outcome variable and a continuous exposure, independent of confounding factors.</strong>.</p> <p>It would be great to get either a workaround for the above, or an alternative way to view the relationship I am interested in. Many thanks.</p>
11,293,034
1
6
null
2012-07-02 10:25:32.99 UTC
11
2021-10-04 10:53:51.433 UTC
2012-07-02 13:25:17.88 UTC
null
1,495,718
null
1,495,718
null
1
7
r|plot|regression
19,908
<pre><code>set.seed(12345) dataset &lt;- expand.grid(Temp = rnorm(30), Age = runif(10)) dataset$Truth &lt;- with(dataset, plogis(2 * Temp - 3 * Age)) dataset$Sample &lt;- rbinom(nrow(dataset), size = 1, prob = dataset$Truth) model &lt;- glm(Sample ~ Temp + Age, data = dataset, family = binomial) newdata &lt;- expand.grid( Temp = pretty(dataset$Temp, 20), Age = pretty(dataset$Age, 5)) newdata$Sample &lt;- predict(model, newdata = newdata, type = "response") library(ggplot2) ggplot(newdata, aes(x = Temp, y = Sample)) + geom_line() + facet_wrap(~Age) </code></pre> <p><img src="https://i.stack.imgur.com/WRLRJ.png" alt="enter image description here"></p> <pre><code>ggplot(newdata, aes(x = Temp, y = Sample, colour = Age, group = Age)) + geom_line() </code></pre> <p><img src="https://i.stack.imgur.com/xpDw1.png" alt="enter image description here"></p>
10,930,866
Auto Format Phone Number in Jquery
<p>I have one textbox for phone number. My phone number should be XXX-XXX-XXX like this format.</p> <p>I got the solution for XXX-XXX-XXX format, but i don't know how to modify that code.</p> <pre><code>$('#ssn').keyup(function() { var val = this.value.replace(/\D/g, ''); var newVal = ''; while (val.length &gt; 3) { newVal += val.substr(0, 3) + '-'; val = val.substr(3); } newVal += val; this.value = newVal; }); </code></pre> <p><a href="http://jsfiddle.net/ssthil/nY2QT/" rel="noreferrer">http://jsfiddle.net/ssthil/nY2QT/</a></p>
10,931,017
6
3
null
2012-06-07 11:24:42.613 UTC
6
2020-06-08 12:22:32.267 UTC
2016-08-25 16:53:03.503 UTC
null
2,840,103
null
1,330,809
null
1
12
javascript|jquery
69,363
<p>Since you're using jQuery you can try jquery <a href="http://digitalbush.com/projects/masked-input-plugin/" rel="noreferrer">masked-input-plugin</a>. </p> <p>There's a jsFiddle for you <a href="http://jsfiddle.net/vandalo/7Q6gx/" rel="noreferrer">here</a> where you can see how it works.</p> <p>The source code for the project on GitHub can be found <a href="https://github.com/digitalBush/jquery.maskedinput" rel="noreferrer">here</a>.</p> <p>The implementation is more than simple:</p> <p>HTML:</p> <pre><code>&lt;input id="ssn"/&gt; </code></pre> <p>javascript:</p> <pre><code>$("#ssn").mask("999-999-999"); </code></pre> <p><strong>UPDATE</strong>:</p> <p>Another good one can be found <a href="http://igorescobar.github.io/jQuery-Mask-Plugin/" rel="noreferrer">here</a>.</p>
11,253,653
Configuration data in Scala -- should I use the Reader monad?
<p>How do I create a properly functional configurable object in Scala? I have watched Tony Morris' video on the <code>Reader</code> monad and I'm still unable to connect the dots. </p> <p>I have a hard-coded list of <code>Client</code> objects: </p> <pre><code>class Client(name : String, age : Int){ /* etc */} object Client{ //Horrible! val clients = List(Client("Bob", 20), Client("Cindy", 30)) } </code></pre> <p>I want <code>Client.clients</code> to be determined at runtime, with the flexibility of either reading it from a properties file or from a database. In the Java world I'd define an interface, implement the two types of source, and use DI to assign a class variable:</p> <pre><code>trait ConfigSource { def clients : List[Client] } object ConfigFileSource extends ConfigSource { override def clients = buildClientsFromProperties(Properties("clients.properties")) //...etc, read properties files } object DatabaseSource extends ConfigSource { /* etc */ } object Client { @Resource("configuration_source") private var config : ConfigSource = _ //Inject it at runtime val clients = config.clients } </code></pre> <p>This seems like a pretty clean solution to me (not a lot of code, clear intent), but that <code>var</code> <em>does</em> jump out (OTOH, it doesn't seem to me <em>really</em> troublesome, since I know it <em>will</em> be injected once-and-only-once). </p> <p>What would the <code>Reader</code> monad look like in this situation and, explain it to me like I'm 5, what are its advantages? </p>
11,255,753
1
7
null
2012-06-28 22:11:20.183 UTC
22
2012-07-26 04:11:49.047 UTC
2012-06-29 00:06:07.183 UTC
null
10,116
null
10,116
null
1
33
scala|configuration|monads|reader-monad
5,429
<p>Let's start with a simple, superficial difference between your approach and the <code>Reader</code> approach, which is that you no longer need to hang onto <code>config</code> anywhere at all. Let's say you define the following vaguely clever type synonym:</p> <pre><code>type Configured[A] = ConfigSource =&gt; A </code></pre> <p>Now, if I ever need a <code>ConfigSource</code> for some function, say a function that gets the <em>n</em>'th client in the list, I can declare that function as "configured":</p> <pre><code>def nthClient(n: Int): Configured[Client] = { config =&gt; config.clients(n) } </code></pre> <p>So we're essentially pulling a <code>config</code> out of thin air, any time we need one! Smells like dependency injection, right? Now let's say we want the ages of the first, second and third clients in the list (assuming they exist):</p> <pre><code>def ages: Configured[(Int, Int, Int)] = for { a0 &lt;- nthClient(0) a1 &lt;- nthClient(1) a2 &lt;- nthClient(2) } yield (a0.age, a1.age, a2.age) </code></pre> <p>For this, of course, you need some appropriate definition of <code>map</code> and <code>flatMap</code>. I won't get into that here, but will simply say that Scalaz (or <a href="http://www.youtube.com/watch?v=ZasXwtTRkio">Rúnar's awesome NEScala talk</a>, or <a href="http://vimeo.com/20674558">Tony's</a> which you've seen already) gives you all you need.</p> <p>The important point here is that the <code>ConfigSource</code> dependency and its so-called injection are mostly hidden. The only "hint" that we can see here is that <code>ages</code> is of type <code>Configured[(Int, Int, Int)]</code> rather than simply <code>(Int, Int, Int)</code>. We didn't need to explicitly reference <code>config</code> anywhere.</p> <blockquote> <blockquote> <p><strong>As an aside</strong>, this is the way I almost always like to think about monads: they <strong>hide their effect</strong> so it's not polluting the flow of your code, while <strong>explicitly declaring the effect</strong> in the type signature. In other words, you needn't repeat yourself too much: you say "hey, this function deals with <em>effect X</em>" in the function's return type, and don't mess with it any further.</p> <p>In this example, of course the effect is to read from some fixed environment. Another monadic effect you might be familiar with include error-handling: we can say that <code>Option</code> hides error-handling logic while making the possibility of errors explicit in your method's type. Or, sort of the opposite of reading, the <code>Writer</code> monad hides the thing we're writing to while making its presence explicit in the type system.</p> </blockquote> </blockquote> <p>Now finally, just as we normally need to bootstrap a DI framework (somewhere outside our usual flow of control, such as in an XML file), we also need to bootstrap this curious monad. Surely we'll have some logical entry point to our code, such as:</p> <pre><code>def run: Configured[Unit] = // ... </code></pre> <p>It ends up being pretty simple: since <code>Configured[A]</code> is just a type synonym for the function <code>ConfigSource =&gt; A</code>, we can just apply the function to its "environment":</p> <pre><code>run(ConfigFileSource) // or run(DatabaseSource) </code></pre> <p>Ta-da! So, contrasting with the traditional Java-style DI approach, we don't have any "magic" occurring here. The only magic, as it were, is encapsulated in the definition of our <code>Configured</code> type and the way it behaves as a monad. Most importantly, <strong>the type system keeps us honest</strong> about which "realm" dependency injection is occurring in: anything with type <code>Configured[...]</code> is in the DI world, and anything without it is not. We simply don't get this in old-school DI, where <em>everything</em> is potentially managed by the magic, so you don't really know which portions of your code are safe to reuse outside of a DI framework (for example, within your unit tests, or in some other project entirely).</p> <hr> <p><strong>update:</strong> I wrote up a <a href="http://mergeconflict.com/reading-your-future">blog post</a> which explains <code>Reader</code> in greater detail.</p>
10,992,005
PHP: Get the key from an array in a foreach loop
<p>print_r($samplearr) prints the following for my array containing 3 items:</p> <pre><code>Array ( [4722] =&gt; Array ( [value1] =&gt; 52 [value2] =&gt; 46 ) Array ( [4922] =&gt; Array ( [value1] =&gt; 22 [value2] =&gt; 47 ) Array ( [7522] =&gt; Array ( [value1] =&gt; 47 [value2] =&gt; 85 ) </code></pre> <p>I want to put these into an HTML table so I was doing a foreach but its not doing what I expected:</p> <pre><code>foreach($samplearr as $item){ print "&lt;tr&gt;&lt;td&gt;" . key($item) . "&lt;/td&gt;&lt;td&gt;" . $samplearr['value1'] . "&lt;/td&gt;&lt;td&gt;" . $samplearr['value2'] . "&lt;/td&gt;&lt;/tr&gt;"; } </code></pre> <p>Which is returning:</p> <pre><code>&lt;tr&gt;&lt;td&gt;value1&lt;/td&gt;&lt;td&gt;52&lt;/td&gt;&lt;td&gt;46&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>This would be the first output I am wanting:</p> <pre><code>&lt;tr&gt;&lt;td&gt;4722&lt;/td&gt;&lt;td&gt;52&lt;/td&gt;&lt;td&gt;46&lt;/td&gt;&lt;/tr&gt; </code></pre> <p>What function do I need to be using instead of key($item) to get the 4722?</p>
10,992,012
3
0
null
2012-06-12 07:13:43.923 UTC
9
2017-08-24 06:42:05.673 UTC
null
null
null
null
532,606
null
1
35
php|arrays|foreach
139,153
<p>Try this:</p> <pre><code>foreach($samplearr as $key =&gt; $item){ print "&lt;tr&gt;&lt;td&gt;" . $key . "&lt;/td&gt;&lt;td&gt;" . $item['value1'] . "&lt;/td&gt;&lt;td&gt;" . $item['value2'] . "&lt;/td&gt;&lt;/tr&gt;"; } </code></pre>
11,008,469
Are JSON web services vulnerable to CSRF attacks?
<p>I am building a web service that exclusively uses JSON for its request and response content (i.e., no form encoded payloads).</p> <p><strong>Is a web service vulnerable to CSRF attack if the following are true?</strong></p> <ol> <li><p>Any <code>POST</code> request without a top-level JSON object, e.g., <code>{"foo":"bar"}</code>, will be rejected with a 400. For example, a <code>POST</code> request with the content <code>42</code> would be thus rejected.</p></li> <li><p>Any <code>POST</code> request with a content-type other than <code>application/json</code> will be rejected with a 400. For example, a <code>POST</code> request with content-type <code>application/x-www-form-urlencoded</code> would be thus rejected.</p></li> <li><p>All GET requests will be <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="noreferrer">Safe</a>, and thus not modify any server-side data.</p></li> <li><p>Clients are authenticated via a session cookie, which the web service gives them after they provide a correct username/password pair via a POST with JSON data, e.g. <code>{"username":"[email protected]", "password":"my password"}</code>.</p></li> </ol> <p>Ancillary question: Are <code>PUT</code> and <code>DELETE</code> requests ever vulnerable to CSRF? I ask because it seems that most (all?) browsers disallow these methods in HTML forms.</p> <p>EDIT: Added item #4.</p> <p>EDIT: Lots of good comments and answers so far, but no one has offered a specific CSRF attack to which this web service is vulnerable.</p>
11,024,387
5
7
null
2012-06-13 05:03:51.48 UTC
32
2020-09-30 18:43:46.723 UTC
2012-06-13 13:09:47.297 UTC
null
839,558
null
839,558
null
1
93
http|security|csrf
39,483
<p>Forging arbitrary CSRF requests with arbitrary media types is effectively only possible with XHR, because a <a href="http://www.w3.org/TR/html5/attributes-common-to-form-controls.html#attr-fs-method" rel="noreferrer">form’s method is limited to GET and POST</a> and a <a href="http://www.w3.org/TR/html5/attributes-common-to-form-controls.html#attr-fs-enctype" rel="noreferrer">form’s POST message body is also limited to the three formats <code>application/x-www-form-urlencoded</code>, <code>multipart/form-data</code>, and <code>text/plain</code></a>. However, <a href="https://stackoverflow.com/q/10788538/53114">with the form data encoding <code>text/plain</code> it is still possible to forge requests containing valid JSON data</a>.</p> <p>So the only threat comes from XHR-based CSRF attacks. And those will only be successful if they are from the same origin, so basically from your own site somehow (e. g. XSS). Be careful not to mistake disabling CORS (i.e. not setting Access-Control-Allow-Origin: *) as a protection. CORS simply prevents clients from reading the response. The whole request is still sent and processed by the server.</p>
11,064,786
Get pixel's RGB using PIL
<p>Is it possible to get the RGB color of a pixel using PIL? I'm using this code:</p> <pre><code>im = Image.open("image.gif") pix = im.load() print(pix[1,1]) </code></pre> <p>However, it only outputs a number (e.g. <code>0</code> or <code>1</code>) and not three numbers (e.g. <code>60,60,60</code> for R,G,B). I guess I'm not understanding something about the function. I'd love some explanation.</p> <p>Thanks a lot.</p>
11,064,935
5
0
null
2012-06-16 15:32:25.113 UTC
33
2021-06-22 12:45:55.383 UTC
2012-06-16 16:39:05.56 UTC
null
1,209,279
null
1,460,652
null
1
119
python|image|python-imaging-library|rgb|pixel
253,220
<p>Yes, this way:</p> <pre><code>im = Image.open('image.gif') rgb_im = im.convert('RGB') r, g, b = rgb_im.getpixel((1, 1)) print(r, g, b) (65, 100, 137) </code></pre> <p>The reason you were getting a single value before with <code>pix[1, 1]</code> is because GIF pixels refer to one of the 256 values in the GIF color palette.</p> <p>See also this SO post: <a href="https://stackoverflow.com/questions/5800009/python-and-pil-pixel-values-different-for-gif-and-jpeg">Python and PIL pixel values different for GIF and JPEG</a> and this <a href="http://effbot.org/imagingbook/image.htm" rel="noreferrer">PIL Reference page</a> contains more information on the <code>convert()</code> function.</p> <p>By the way, your code would work just fine for <code>.jpg</code> images.</p>
12,684,709
connect iPhone to Android's Wifi Direct soft AP
<p>I know that Wifi Direct works by creating a Soft AP (software access point) in one of the devices. I also know that many Androids support Wifi Direct, but iPhones do not.</p> <p>My question is: is it possible to create a device-to-device wifi link that is Wifi Direct on the Android side, but regular wifi on the iPhone side? Where the Android's Wifi Direct would be presenting a soft AP, which the iPhone would see as indistinguishable from a regular AP and be able to associate to.</p> <p>Imagine that this is out in the wilderness where no router AP is available. Also, neither user has a tethering plan.</p> <p>This link would be used by a Bump-like app to transfer files.</p>
12,896,547
1
4
null
2012-10-02 04:50:16.403 UTC
9
2012-10-20 12:21:04.017 UTC
2012-10-02 05:25:07.123 UTC
null
402,807
null
402,807
null
1
16
android|iphone|networking|wifi|wifi-direct
47,326
<p>Depending on your phone you can just set up your Android phone as a portable hotspot and connect to that with the iPhone. From there it would be application specific to get data transferred. </p> <p>However you can also use the Androids WiFi-Direct libraries. In that case you would use them to set up the Android phone to create a "Group owner", which basically is the same as it being a portable hotspot. Check out:</p> <p><a href="http://developer.android.com/guide/topics/connectivity/wifip2p.html">http://developer.android.com/guide/topics/connectivity/wifip2p.html</a></p> <p>I'll give you a code example to help you get started. </p> <pre><code>public class WifiDirectAPtestActivity extends Activity { private WifiP2pManager manager; private boolean isWifiP2pEnabled = false; private boolean retryChannel = false; private final IntentFilter intentFilter = new IntentFilter(); private Channel channel; private BroadcastReceiver receiver = null; public void setIsWifiP2pEnabled(boolean isWifiP2pEnabled) { this.isWifiP2pEnabled = isWifiP2pEnabled; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // add necessary intent values to be matched. intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); manager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); channel = manager.initialize(this, getMainLooper(), null); } /** register the BroadcastReceiver with the intent values to be matched */ @Override public void onResume() { super.onResume(); receiver = new WiFiDirectBroadcastReceiver(manager, channel, this); registerReceiver(receiver, intentFilter); createGroup(); } @Override public void onPause() { super.onPause(); unregisterReceiver(receiver); manager.removeGroup(channel, new ActionListener() { @Override public void onFailure(int reasonCode) { Log.d("WifiDirectAptestActivity", "Disconnect failed. Reason :" + reasonCode); } @Override public void onSuccess() { Log.d("WifiDirectAptestActivity", "Should have been sucessfully removed"); } }); } public void createGroup() { manager.createGroup(channel, new ActionListener() { @Override public void onSuccess() { // WiFiDirectBroadcastReceiver will notify us. Ignore for now. Log.d("WifiDirectAPtestActivity", "Group creating request successfully send"); } @Override public void onFailure(int reason) { Toast.makeText(WifiDirectAPtestActivity.this, "Connect failed. Retry.", Toast.LENGTH_SHORT).show(); } }); } </code></pre> <p>In addition you'll need the broadcast receiver, look at the WiFi-Direct demo and it should be clear to you. </p> <p>Note that line manager.createGroup(channel, new ActionListener() is the codeline of interest, it is this line that actually sets up the device as a portable hotspot. </p> <p>Hope this clarifies things, I don't really know how detailed explanation you need. Comment if some things are not clear.</p>
13,216,976
How to use the initialize method in Ruby
<p>I'm trying to wrap my head around the purpose of using the <code>initialize</code> method. In Hartl's tutorial, he uses the example:</p> <pre><code>def initialize(attributes = {}) @name = attributes[:name] @email = attributes[:email] end </code></pre> <p>Is <code>initialize</code> setting the instance variables <code>@name</code> and <code>@email</code> to the attributes, and, if so, why do we have the argument <code>attributes = {}</code>?</p>
13,216,991
1
0
null
2012-11-04 07:46:38.587 UTC
8
2021-09-28 18:11:04.383 UTC
2021-09-28 18:11:04.383 UTC
null
128,421
null
1,509,401
null
1
31
ruby-on-rails|attributes
31,479
<p>Ruby uses the <code>initialize</code> method as an object's constructor. It is part of the Ruby language, not specific to the Rails framework. It is invoked when you instanstiate a new object such as:</p> <pre><code>@person = Person.new </code></pre> <p>Calling the <code>new</code> class level method on a <code>Class</code> allocates a type of that class, and then invokes the object's <code>initialize</code> method:</p> <p><a href="http://www.ruby-doc.org/core-1.9.3/Class.html#method-i-new" rel="noreferrer">http://www.ruby-doc.org/core-1.9.3/Class.html#method-i-new</a></p> <p>All objects have a default <code>initialize</code> method which accepts no parameters (you don't need to write one - you get it automagically). If you want your object to do something different in the <code>initialize</code> method, you need to define your own version of it.</p> <p>In your example, you are passing a hash to the <code>initialize</code> method which can be used to set the default value of <code>@name</code> and <code>@email</code>.</p> <p>You use this such as:</p> <pre><code>@person = Person.new({name: 'John Appleseed', email: '[email protected]'}) </code></pre> <p>The reason the initializer has a default value for attributes (<code>attributes = {}</code> sets the default value to an ampty hash - <code>{}</code>) is so that you can also call it without having to pass an argument. If you dont' specify an argument, then <code>attributes</code> will be an empty hash, and thus both <code>@name</code> and <code>@email</code> will be <code>nil</code> values as no value exists for those keys (<code>:name</code> and <code>:email</code>).</p>
12,675,092
How to find the size of the L1 cache line size with IO timing measurements?
<p>As a school assignment, I need to find a way to get the L1 data cache line size, without reading config files or using api calls. Supposed to use memory accesses read/write timings to analyze &amp; get this info. So how might I do that? </p> <p>In an incomplete try for another part of the assignment, to find the levels &amp; size of cache, I have: </p> <pre><code>for (i = 0; i &lt; steps; i++) { arr[(i * 4) &amp; lengthMod]++; } </code></pre> <p>I was thinking maybe I just need vary line 2, <code>(i * 4)</code> part? So once I exceed the cache line size, I might need to replace it, which takes sometime? But is it so straightforward? The required block might already be in memory somewhere? Or perpahs I can still count on the fact that if I have a large enough <code>steps</code>, it will still work out quite accurately? </p> <p><strong>UPDATE</strong></p> <p><strong><a href="https://github.com/jiewmeng/cs3210-assign1/blob/master/cache-l1-line.cpp" rel="noreferrer">Heres an attempt on GitHub</a></strong> ... main part below</p> <pre><code>// repeatedly access/modify data, varying the STRIDE for (int s = 4; s &lt;= MAX_STRIDE/sizeof(int); s*=2) { start = wall_clock_time(); for (unsigned int k = 0; k &lt; REPS; k++) { data[(k * s) &amp; lengthMod]++; } end = wall_clock_time(); timeTaken = ((float)(end - start))/1000000000; printf("%d, %1.2f \n", s * sizeof(int), timeTaken); } </code></pre> <p>Problem is there dont seem to be much differences between the timing. FYI. since its for L1 cache. I have SIZE = 32 K (size of array)</p>
12,675,717
8
7
null
2012-10-01 14:19:09.187 UTC
18
2018-05-12 14:27:24.563 UTC
2017-03-16 07:55:44.39 UTC
null
895,245
null
292,291
null
1
39
c++|c|performance|caching|cpu-architecture
18,499
<p>Allocate a BIG <code>char</code> array (make sure it is too big to fit in L1 <em>or</em> L2 cache). Fill it with random data.</p> <p>Start walking over the array in steps of <code>n</code> bytes. Do something with the retrieved bytes, like summing them.</p> <p>Benchmark and calculate how many bytes/second you can process with different values of <code>n</code>, starting from 1 and counting up to 1000 or so. Make sure that your benchmark prints out the calculated sum, so the compiler can't possibly optimize the benchmarked code away.</p> <p>When <code>n</code> == your cache line size, <em>each access</em> will require reading a new line into the L1 cache. So the benchmark results should get slower quite sharply at that point.</p> <p>If the array is big enough, by the time you reach the end, the data at the beginning of the array will already be out of cache again, which is what you want. So after you increment <code>n</code> and start again, the results will not be affected by having needed data already in the cache.</p>
12,841,803
Best way to show a loading/progress indicator?
<p>What is the best way to show a loading spinner while the app is waiting for a response from the server?</p> <p>Can this be done programmatically? So that I don't have to add the load spinner in the xml file?</p>
12,842,387
5
0
null
2012-10-11 14:23:25.907 UTC
42
2020-08-16 00:42:29.463 UTC
2017-02-16 21:59:24.197 UTC
null
2,245,264
null
1,356,613
null
1
167
android|android-spinner
213,073
<p><strong><a href="https://developer.android.com/reference/android/app/ProgressDialog.html" rel="noreferrer">ProgressDialog</a> is deprecated from Android Oreo. Use <a href="https://developer.android.com/reference/android/widget/ProgressBar" rel="noreferrer">ProgressBar</a> instead</strong></p> <pre><code>ProgressDialog progress = new ProgressDialog(this); progress.setTitle("Loading"); progress.setMessage("Wait while loading..."); progress.setCancelable(false); // disable dismiss by tapping outside of the dialog progress.show(); // To dismiss the dialog progress.dismiss(); </code></pre> <p><strong>OR</strong></p> <pre><code>ProgressDialog.show(this, "Loading", "Wait while loading..."); </code></pre> <p><a href="http://developer.android.com/reference/android/app/ProgressDialog.html" rel="noreferrer">Read more here.</a></p> <p>By the way, <strong>Spinner</strong> has a different meaning in Android. (It's like the select dropdown in HTML)</p>
16,608,086
Git and Bitbucket without SSH
<p>I've set up a local git repository on my computer, and I'm trying to push that to a newly created Bitbucket account. </p> <p>The problem is that Bitbucket gives me an <code>ssh</code> url to push to, but the network I'm on (university) has the ssh port blocked for external ssh. So that fails, and if I try to replace <code>ssh://</code> with <code>https://</code> it keeps telling me that authentication has failed.</p> <p>Is there a way to push to bitbucket without using <code>ssh</code>?</p>
16,608,377
3
0
null
2013-05-17 11:39:49.293 UTC
7
2014-11-05 17:47:12.7 UTC
2013-05-17 11:47:46.8 UTC
null
1,765,768
null
1,765,768
null
1
28
git|bitbucket
23,526
<p>You can connect to GitHub and Bitbucket repositories via HTTPS. Both will also let you push.</p> <p>These are the typical URLs for HTTPS access:</p> <pre><code>https://[email protected]/username/repository.git https://github.com/username/repository.git </code></pre> <p>Note that Git will prompt you for your password whenever you want to communicate with the remote.</p>
16,788,731
Grunt: Watch multiple files, Compile only Changed
<p>I'm new to Grunt, and so far I'm enjoying it very much. I want Grunt to compile only the changed files when running <code>grunt watch</code></p> <p>In my Grunfile.coffee I currently have (relevant parts).<br> <em>Note: assets/javascript/app.coffee and assets/javascript/app.js are directories</em> </p> <pre><code> coffee: default: expand: true cwd: "assets/javascript/app.coffee" src: ["*.coffee"] dest: "assets/javascript/app.js" ext: ".js" uglify: dev: options: beautify: true compress: false mangle: false preserveComments: 'all' files: "js/app.js": "assets/javascript/app.js/*.js" "js/libs.js": "assets/javascript/libs/*.js" watch: coffeescript: files: 'assets/javascript/**/*.coffee' tasks: ["coffee"] javascript: files: "assets/**/*.js" tasks: ["uglify:dev"] livereload: files: ["Gruntfile.coffee", "js/*.js", "*.php", "css/*.css", "images/**/*.{png,jpg,jpeg,gif,webp,svg}", "js/*.js", ] options: livereload: true </code></pre> <p>There is probably a shorter way around, but I'm compiling app.coffee to app.js first, so that after I distribute my work, people who aren't comfortable with Coffeescript can browse the code in somewhat reasonable manner.</p> <p>The problem with all this is that now that I save a Coffeescript file, I get too many steps ( I think ):</p> <pre><code>&gt;&gt; File "assets/javascript/app.coffee/browse.coffee" changed. Running "coffee:default" (coffee) task File assets/javascript/app.js/browse.js created. File assets/javascript/app.js/filters.js created. Done, without errors. Completed in 0.837s at Tue May 28 2013 12:30:18 GMT+0300 (EEST) - Waiting... OK &gt;&gt; File "assets/javascript/app.js/browse.js" changed. &gt;&gt; File "assets/javascript/app.js/filters.js" changed. Running "uglify:dev" (uglify) task File "js/app.js" created. File "js/libs.js" created. Done, without errors. Completed in 0.831s at Tue May 28 2013 12:30:19 GMT+0300 (EEST) - Waiting... OK &gt;&gt; File "js/app.js" changed. &gt;&gt; File "js/libs.js" changed. Completed in 0.000s at Tue May 28 2013 12:30:19 GMT+0300 (EEST) - Waiting... </code></pre> <p>Currently I'm just setting up my project, but I will have a lot more Coffeescript files, and I don't want Coffeescript to recompile all of the files, on each file change.</p> <p>Furthermore, libs.js has no part in all of this at all, but I guess it is still compiled, because it also matches the "assets/*<em>/</em>.js" pattern.</p> <p>Is there a way to make Grunt compile only the files that have changed ?</p>
19,722,900
4
1
null
2013-05-28 09:39:52.417 UTC
8
2014-10-23 13:40:29.263 UTC
2013-05-28 09:46:39.347 UTC
null
853,685
null
853,685
null
1
42
node.js|coffeescript|gruntjs
20,936
<p><strong>I've finally found a real solution!</strong> And it's super simple too!</p> <p><code>npm install grunt-newer --save-dev</code></p> <p>Then in your Gruntfile (after loading the task in grunt):</p> <pre><code>watch: coffeescript: files: 'assets/javascript/**/*.coffee' tasks: ["newer:coffee"] </code></pre> <p>And that's it! <a href="https://github.com/tschaub/grunt-newer">The Awesome <strong>grunt-newer</strong> is awesome!</a></p>
16,990,573
How to bind bootstrap popover on dynamic elements
<p>I'm using Twitter Bootstrap's popover on the dynamic list. The list item has a button, when I click the button, it should show up popover. It works fine when I tested on non-dynamic. </p> <p>this is my JavaScript for non-dynamic list</p> <pre><code>$("button[rel=popover]").popover({ placement : 'right', container : 'body', html : true, //content:" &lt;div style='color:red'&gt;This is your div content&lt;/div&gt;" content: function() { return $('#popover-content').html(); } }) .click(function(e) { e.preventDefault(); }); </code></pre> <p>However, It doesn't work well on dynamic list. It can show up when I click the button "twice" and only show up one of list items I click fist time. </p> <p>MY html: </p> <pre><code> &lt;ul id="project-list" class="nav nav-list"&gt; &lt;li class='project-name'&gt; &lt;a &gt;project name 1 &lt;button class="pop-function" rel="popover" &gt;&lt;/button&gt; &lt;/a&gt; &lt;/li&gt; &lt;li class='project-name'&gt; &lt;a&gt;project name 2 &lt;button class="pop-function" rel="popover" &gt;&lt;/button&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div id="popover-content" style="display:none"&gt; &lt;button class="pop-sync"&gt;&lt;/button&gt; &lt;button class="pop-delete"&gt;&lt;/button&gt; &lt;/div&gt; </code></pre> <p>My JavaScript for dynamic:</p> <pre><code>$(document).on("click", "#project-list li" , function(){ var username = $.cookie("username"); var projectName = $(this).text() $("li.active").removeClass("active"); $(this).addClass("active"); console.log("username: " +username + " project name: "+projectName ); }); $(document).on("click", "button[rel=popover]", function(){ $(this).popover({ placement : 'right', container : 'body', html : true, content: function() { return $('#popover-content').html(); } }).click(function(e){ e.preventDefault(); }) }); //for close other popover when one popover button click $(document).on("click", "button[rel=popover]" , function(){ $("button[rel=popover]").not(this).popover('hide'); }); </code></pre> <p>I have searched similar problems, but I still can't find the one to solve my problem. If anyone has some ideas, please let me know. Thanks your help. </p>
16,991,216
6
1
null
2013-06-07 18:21:40.793 UTC
32
2021-11-15 17:09:36.957 UTC
2020-08-25 07:12:51.03 UTC
null
295,783
null
2,150,267
null
1
61
javascript|jquery|twitter-bootstrap|dom|bootstrap-popover
123,202
<p><strong>Update</strong></p> <p>If your popover is going to have a selector that is consistent then you can make use of <code>selector</code> property of popover constructor.</p> <pre><code>var popOverSettings = { placement: 'bottom', container: 'body', html: true, selector: '[rel=&quot;popover&quot;]', //Sepcify the selector here content: function () { return $('#popover-content').html(); } } $('body').popover(popOverSettings); </code></pre> <p><strong><a href="http://jsfiddle.net/RRGnb/" rel="noreferrer">Demo</a></strong></p> <p>Other ways:</p> <ol> <li>(<strong>Standard Way</strong>) Bind the popover again to the new items being inserted. Save the popoversettings in an external variable.</li> <li>Use <code>Mutation Event</code>/<code>Mutation Observer</code> to identify if a particular element has been inserted on to the <code>ul</code> or an element.</li> </ol> <h3>Source</h3> <pre><code>var popOverSettings = { //Save the setting for later use as well placement: 'bottom', container: 'body', html: true, //content:&quot; &lt;div style='color:red'&gt;This is your div content&lt;/div&gt;&quot; content: function () { return $('#popover-content').html(); } } $('ul').on('DOMNodeInserted', function () { //listed for new items inserted onto ul $(event.target).popover(popOverSettings); }); $(&quot;button[rel=popover]&quot;).popover(popOverSettings); $('.pop-Add').click(function () { $('ul').append(&quot;&lt;li class='project-name'&gt; &lt;a&gt;project name 2 &lt;button class='pop-function' rel='popover'&gt;&lt;/button&gt; &lt;/a&gt; &lt;/li&gt;&quot;); }); </code></pre> <p>But it is not recommended to use <a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-type-DOMNodeInserted" rel="noreferrer">DOMNodeInserted</a> Mutation Event for performance issues as well as support. This has been <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Mutation_events?redirectlocale=en-US&amp;redirectslug=DOM%2FMutation_events" rel="noreferrer">deprecated</a> as well. So your best bet would be to save the setting and bind after you update with new element.</p> <h3><a href="http://jsfiddle.net/re29p/" rel="noreferrer">Demo</a></h3> <p>Another recommended way is to use <a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver" rel="noreferrer">MutationObserver</a> instead of MutationEvent according to MDN, but again support in some browsers are unknown and performance a concern.</p> <pre><code>MutationObserver = window.MutationObserver || window.WebKitMutationObserver; // create an observer instance var observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { $(mutation.addedNodes).popover(popOverSettings); }); }); // configuration of the observer: var config = { attributes: true, childList: true, characterData: true }; // pass in the target node, as well as the observer options observer.observe($('ul')[0], config); </code></pre> <h3><a href="http://jsfiddle.net/zJnqx/" rel="noreferrer">Demo</a></h3>
16,890,723
List all liquibase sql types
<p>I try to find documentation on the supported types that can be used in change log files. But cannot find it. Is there any document, site or something similar where I can find all types-specific issues. For example clob type is supported in databases with different types. And I have to use something like:</p> <pre><code>&lt;property name="clob.type" value="clob" dbms="oracle,h2,hsqldb"/&gt; &lt;property name="clob.type" value="longtext" dbms="mysql"/&gt; &lt;column name="clob1" type="${clob.type}"&gt; &lt;constraints nullable="true"/&gt; &lt;/column&gt; </code></pre> <p>I hope there is a resource where all liquibase types are described.</p>
28,626,825
4
0
null
2013-06-03 05:55:27.847 UTC
87
2019-09-12 09:07:58.26 UTC
null
null
null
null
511,804
null
1
110
java|liquibase
139,096
<p>This is a comprehensive list of all liquibase datatypes and how they are converted for different databases:</p> <pre><code>boolean MySQLDatabase: BIT(1) SQLiteDatabase: BOOLEAN H2Database: BOOLEAN PostgresDatabase: BOOLEAN UnsupportedDatabase: BOOLEAN DB2Database: SMALLINT MSSQLDatabase: [bit] OracleDatabase: NUMBER(1) HsqlDatabase: BOOLEAN FirebirdDatabase: SMALLINT DerbyDatabase: SMALLINT InformixDatabase: BOOLEAN SybaseDatabase: BIT SybaseASADatabase: BIT tinyint MySQLDatabase: TINYINT SQLiteDatabase: TINYINT H2Database: TINYINT PostgresDatabase: SMALLINT UnsupportedDatabase: TINYINT DB2Database: SMALLINT MSSQLDatabase: [tinyint] OracleDatabase: NUMBER(3) HsqlDatabase: TINYINT FirebirdDatabase: SMALLINT DerbyDatabase: SMALLINT InformixDatabase: TINYINT SybaseDatabase: TINYINT SybaseASADatabase: TINYINT int MySQLDatabase: INT SQLiteDatabase: INTEGER H2Database: INT PostgresDatabase: INT UnsupportedDatabase: INT DB2Database: INTEGER MSSQLDatabase: [int] OracleDatabase: INTEGER HsqlDatabase: INT FirebirdDatabase: INT DerbyDatabase: INTEGER InformixDatabase: INT SybaseDatabase: INT SybaseASADatabase: INT mediumint MySQLDatabase: MEDIUMINT SQLiteDatabase: MEDIUMINT H2Database: MEDIUMINT PostgresDatabase: MEDIUMINT UnsupportedDatabase: MEDIUMINT DB2Database: MEDIUMINT MSSQLDatabase: [int] OracleDatabase: MEDIUMINT HsqlDatabase: MEDIUMINT FirebirdDatabase: MEDIUMINT DerbyDatabase: MEDIUMINT InformixDatabase: MEDIUMINT SybaseDatabase: MEDIUMINT SybaseASADatabase: MEDIUMINT bigint MySQLDatabase: BIGINT SQLiteDatabase: BIGINT H2Database: BIGINT PostgresDatabase: BIGINT UnsupportedDatabase: BIGINT DB2Database: BIGINT MSSQLDatabase: [bigint] OracleDatabase: NUMBER(38, 0) HsqlDatabase: BIGINT FirebirdDatabase: BIGINT DerbyDatabase: BIGINT InformixDatabase: INT8 SybaseDatabase: BIGINT SybaseASADatabase: BIGINT float MySQLDatabase: FLOAT SQLiteDatabase: FLOAT H2Database: FLOAT PostgresDatabase: FLOAT UnsupportedDatabase: FLOAT DB2Database: FLOAT MSSQLDatabase: [float](53) OracleDatabase: FLOAT HsqlDatabase: FLOAT FirebirdDatabase: FLOAT DerbyDatabase: FLOAT InformixDatabase: FLOAT SybaseDatabase: FLOAT SybaseASADatabase: FLOAT double MySQLDatabase: DOUBLE SQLiteDatabase: DOUBLE H2Database: DOUBLE PostgresDatabase: DOUBLE PRECISION UnsupportedDatabase: DOUBLE DB2Database: DOUBLE MSSQLDatabase: [float](53) OracleDatabase: FLOAT(24) HsqlDatabase: DOUBLE FirebirdDatabase: DOUBLE PRECISION DerbyDatabase: DOUBLE InformixDatabase: DOUBLE PRECISION SybaseDatabase: DOUBLE SybaseASADatabase: DOUBLE decimal MySQLDatabase: DECIMAL SQLiteDatabase: DECIMAL H2Database: DECIMAL PostgresDatabase: DECIMAL UnsupportedDatabase: DECIMAL DB2Database: DECIMAL MSSQLDatabase: [decimal](18, 0) OracleDatabase: DECIMAL HsqlDatabase: DECIMAL FirebirdDatabase: DECIMAL DerbyDatabase: DECIMAL InformixDatabase: DECIMAL SybaseDatabase: DECIMAL SybaseASADatabase: DECIMAL number MySQLDatabase: numeric SQLiteDatabase: NUMBER H2Database: NUMBER PostgresDatabase: numeric UnsupportedDatabase: NUMBER DB2Database: numeric MSSQLDatabase: [numeric](18, 0) OracleDatabase: NUMBER HsqlDatabase: numeric FirebirdDatabase: numeric DerbyDatabase: numeric InformixDatabase: numeric SybaseDatabase: numeric SybaseASADatabase: numeric blob MySQLDatabase: LONGBLOB SQLiteDatabase: BLOB H2Database: BLOB PostgresDatabase: BYTEA UnsupportedDatabase: BLOB DB2Database: BLOB MSSQLDatabase: [varbinary](MAX) OracleDatabase: BLOB HsqlDatabase: BLOB FirebirdDatabase: BLOB DerbyDatabase: BLOB InformixDatabase: BLOB SybaseDatabase: IMAGE SybaseASADatabase: LONG BINARY function MySQLDatabase: FUNCTION SQLiteDatabase: FUNCTION H2Database: FUNCTION PostgresDatabase: FUNCTION UnsupportedDatabase: FUNCTION DB2Database: FUNCTION MSSQLDatabase: [function] OracleDatabase: FUNCTION HsqlDatabase: FUNCTION FirebirdDatabase: FUNCTION DerbyDatabase: FUNCTION InformixDatabase: FUNCTION SybaseDatabase: FUNCTION SybaseASADatabase: FUNCTION UNKNOWN MySQLDatabase: UNKNOWN SQLiteDatabase: UNKNOWN H2Database: UNKNOWN PostgresDatabase: UNKNOWN UnsupportedDatabase: UNKNOWN DB2Database: UNKNOWN MSSQLDatabase: [UNKNOWN] OracleDatabase: UNKNOWN HsqlDatabase: UNKNOWN FirebirdDatabase: UNKNOWN DerbyDatabase: UNKNOWN InformixDatabase: UNKNOWN SybaseDatabase: UNKNOWN SybaseASADatabase: UNKNOWN datetime MySQLDatabase: datetime SQLiteDatabase: TEXT H2Database: TIMESTAMP PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE UnsupportedDatabase: datetime DB2Database: TIMESTAMP MSSQLDatabase: [datetime] OracleDatabase: TIMESTAMP HsqlDatabase: TIMESTAMP FirebirdDatabase: TIMESTAMP DerbyDatabase: TIMESTAMP InformixDatabase: DATETIME YEAR TO FRACTION(5) SybaseDatabase: datetime SybaseASADatabase: datetime time MySQLDatabase: time SQLiteDatabase: time H2Database: time PostgresDatabase: TIME WITHOUT TIME ZONE UnsupportedDatabase: time DB2Database: time MSSQLDatabase: [time](7) OracleDatabase: DATE HsqlDatabase: time FirebirdDatabase: time DerbyDatabase: time InformixDatabase: INTERVAL HOUR TO FRACTION(5) SybaseDatabase: time SybaseASADatabase: time timestamp MySQLDatabase: timestamp SQLiteDatabase: TEXT H2Database: TIMESTAMP PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE UnsupportedDatabase: timestamp DB2Database: timestamp MSSQLDatabase: [datetime] OracleDatabase: TIMESTAMP HsqlDatabase: TIMESTAMP FirebirdDatabase: TIMESTAMP DerbyDatabase: TIMESTAMP InformixDatabase: DATETIME YEAR TO FRACTION(5) SybaseDatabase: datetime SybaseASADatabase: timestamp date MySQLDatabase: date SQLiteDatabase: date H2Database: date PostgresDatabase: date UnsupportedDatabase: date DB2Database: date MSSQLDatabase: [date] OracleDatabase: date HsqlDatabase: date FirebirdDatabase: date DerbyDatabase: date InformixDatabase: date SybaseDatabase: date SybaseASADatabase: date char MySQLDatabase: CHAR SQLiteDatabase: CHAR H2Database: CHAR PostgresDatabase: CHAR UnsupportedDatabase: CHAR DB2Database: CHAR MSSQLDatabase: [char](1) OracleDatabase: CHAR HsqlDatabase: CHAR FirebirdDatabase: CHAR DerbyDatabase: CHAR InformixDatabase: CHAR SybaseDatabase: CHAR SybaseASADatabase: CHAR varchar MySQLDatabase: VARCHAR SQLiteDatabase: VARCHAR H2Database: VARCHAR PostgresDatabase: VARCHAR UnsupportedDatabase: VARCHAR DB2Database: VARCHAR MSSQLDatabase: [varchar](1) OracleDatabase: VARCHAR2 HsqlDatabase: VARCHAR FirebirdDatabase: VARCHAR DerbyDatabase: VARCHAR InformixDatabase: VARCHAR SybaseDatabase: VARCHAR SybaseASADatabase: VARCHAR nchar MySQLDatabase: NCHAR SQLiteDatabase: NCHAR H2Database: NCHAR PostgresDatabase: NCHAR UnsupportedDatabase: NCHAR DB2Database: NCHAR MSSQLDatabase: [nchar](1) OracleDatabase: NCHAR HsqlDatabase: CHAR FirebirdDatabase: NCHAR DerbyDatabase: NCHAR InformixDatabase: NCHAR SybaseDatabase: NCHAR SybaseASADatabase: NCHAR nvarchar MySQLDatabase: NVARCHAR SQLiteDatabase: NVARCHAR H2Database: NVARCHAR PostgresDatabase: VARCHAR UnsupportedDatabase: NVARCHAR DB2Database: NVARCHAR MSSQLDatabase: [nvarchar](1) OracleDatabase: NVARCHAR2 HsqlDatabase: VARCHAR FirebirdDatabase: NVARCHAR DerbyDatabase: VARCHAR InformixDatabase: NVARCHAR SybaseDatabase: NVARCHAR SybaseASADatabase: NVARCHAR clob MySQLDatabase: LONGTEXT SQLiteDatabase: TEXT H2Database: CLOB PostgresDatabase: TEXT UnsupportedDatabase: CLOB DB2Database: CLOB MSSQLDatabase: [varchar](MAX) OracleDatabase: CLOB HsqlDatabase: CLOB FirebirdDatabase: BLOB SUB_TYPE TEXT DerbyDatabase: CLOB InformixDatabase: CLOB SybaseDatabase: TEXT SybaseASADatabase: LONG VARCHAR currency MySQLDatabase: DECIMAL SQLiteDatabase: REAL H2Database: DECIMAL PostgresDatabase: DECIMAL UnsupportedDatabase: DECIMAL DB2Database: DECIMAL(19, 4) MSSQLDatabase: [money] OracleDatabase: NUMBER(15, 2) HsqlDatabase: DECIMAL FirebirdDatabase: DECIMAL(18, 4) DerbyDatabase: DECIMAL InformixDatabase: MONEY SybaseDatabase: MONEY SybaseASADatabase: MONEY uuid MySQLDatabase: char(36) SQLiteDatabase: TEXT H2Database: UUID PostgresDatabase: UUID UnsupportedDatabase: char(36) DB2Database: char(36) MSSQLDatabase: [uniqueidentifier] OracleDatabase: RAW(16) HsqlDatabase: char(36) FirebirdDatabase: char(36) DerbyDatabase: char(36) InformixDatabase: char(36) SybaseDatabase: UNIQUEIDENTIFIER SybaseASADatabase: UNIQUEIDENTIFIER </code></pre> <p>For reference, this is the groovy script I've used to generate this output:</p> <pre><code>@Grab('org.liquibase:liquibase-core:3.5.1') import liquibase.database.core.* import liquibase.datatype.core.* def datatypes = [BooleanType,TinyIntType,IntType,MediumIntType,BigIntType,FloatType,DoubleType,DecimalType,NumberType,BlobType,DatabaseFunctionType,UnknownType,DateTimeType,TimeType,TimestampType,DateType,CharType,VarcharType,NCharType,NVarcharType,ClobType,CurrencyType,UUIDType] def databases = [MySQLDatabase, SQLiteDatabase, H2Database, PostgresDatabase, UnsupportedDatabase, DB2Database, MSSQLDatabase, OracleDatabase, HsqlDatabase, FirebirdDatabase, DerbyDatabase, InformixDatabase, SybaseDatabase, SybaseASADatabase] datatypes.each { def datatype = it.newInstance() datatype.finishInitialization("") println datatype.name databases.each { println "$it.simpleName: ${datatype.toDatabaseDataType(it.newInstance())}"} println '' } </code></pre>
25,770,119
iOS 8 UITableView separator inset 0 not working
<p>I have an app where the <code>UITableView</code>'s separator inset is set to custom values - Right <code>0</code>, Left <code>0</code>. This works perfectly in <code>iOS 7.x</code>, however in <code>iOS 8.0</code> I see that the separator inset is set to the default of <code>15</code> on the right. Even though in the xib files it set to <code>0</code>, it still shows up incorrectly.</p> <p>How do I remove the <code>UITableViewCell</code> separator margins?</p>
25,877,725
43
4
null
2014-09-10 16:05:38.62 UTC
249
2020-04-29 16:49:43.177 UTC
2017-05-25 18:12:02.693 UTC
null
3,400,991
null
3,570,727
null
1
680
ios|objective-c|swift|uitableview|ios8
186,763
<p><strong>iOS 8.0 introduces the layoutMargins property on cells AND table views.</strong></p> <p>This property isn't available on iOS 7.0 so you need to make sure you check before assigning it!</p> <p>The easy fix is to subclass your cell and override the layout margins property as suggested by @user3570727. However you will lose any system behavior like inheriting margins from the Safe Area so I do not recommend the below solution:</p> <p>(ObjectiveC)</p> <pre><code>-(UIEdgeInsets)layoutMargins { return UIEdgeInsetsZero // override any margins inc. safe area } </code></pre> <p>(swift 4.2):</p> <pre><code>override var layoutMargins: UIEdgeInsets { get { return .zero } set { } } </code></pre> <p>If you don't want to override the property, or need to set it conditionally, keep reading.</p> <hr> <p>In addition to the <code>layoutMargins</code> property, Apple has added a <strong>property</strong> to your cell that will prevent it from inheriting your Table View's margin settings. When this property is set, your cells are allowed to configure their own margins independently of the table view. Think of it as an override.</p> <p>This property is called <code>preservesSuperviewLayoutMargins</code>, and setting it to <code>NO</code> will allow the cell's <code>layoutMargin</code> setting to override whatever <code>layoutMargin</code> is set on your TableView. It both saves time (<strong>you don't have to modify the Table View's settings</strong>), and is more concise. Please refer to Mike Abdullah's answer for a detailed explanation.</p> <p><em>NOTE: what follows is a clean implementation for a <strong>cell-level margin setting</strong>, as expressed in Mike Abdullah's answer. Setting your cell's <code>preservesSuperviewLayoutMargins=NO</code> will ensure that your Table View does not override the cell settings. If you actually want your entire table view to have consistent margins, please adjust your code accordingly.</em></p> <p><strong>Setup your cell margins:</strong></p> <pre><code>-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { // Remove seperator inset if ([cell respondsToSelector:@selector(setSeparatorInset:)]) { [cell setSeparatorInset:UIEdgeInsetsZero]; } // Prevent the cell from inheriting the Table View's margin settings if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) { [cell setPreservesSuperviewLayoutMargins:NO]; } // Explictly set your cell's layout margins if ([cell respondsToSelector:@selector(setLayoutMargins:)]) { [cell setLayoutMargins:UIEdgeInsetsZero]; } } </code></pre> <p><strong>Swift 4:</strong></p> <pre><code>func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { // Remove seperator inset if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) { cell.separatorInset = .zero } // Prevent the cell from inheriting the Table View's margin settings if cell.responds(to: #selector(setter: UITableViewCell.preservesSuperviewLayoutMargins)) { cell.preservesSuperviewLayoutMargins = false } // Explictly set your cell's layout margins if cell.responds(to: #selector(setter: UITableViewCell.layoutMargins)) { cell.layoutMargins = .zero } } </code></pre> <p>Setting the <code>preservesSuperviewLayoutMargins</code> property on your cell to NO <strong>should</strong> prevent your table view from overriding your cell margins. In some cases, it seems to not function properly.</p> <p><strong>If all fails, you may brute-force your Table View margins:</strong></p> <pre><code>-(void)viewDidLayoutSubviews { [super viewDidLayoutSubviews]; // Force your tableview margins (this may be a bad idea) if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) { [self.tableView setSeparatorInset:UIEdgeInsetsZero]; } if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) { [self.tableView setLayoutMargins:UIEdgeInsetsZero]; } } </code></pre> <p><strong>Swift 4:</strong></p> <pre><code>func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // Force your tableview margins (this may be a bad idea) if tableView.responds(to: #selector(setter: UITableView.separatorInset)) { tableView.separatorInset = .zero } if tableView.responds(to: #selector(setter: UITableView.layoutMargins)) { tableView.layoutMargins = .zero } } </code></pre> <p>...and there you go! This should work on iOS 7 and 8.</p> <hr> <p><strong>EDIT:</strong> <strong>Mohamed Saleh brought to my attention a possible change in iOS 9.</strong> You may need to set the Table View's <code>cellLayoutMarginsFollowReadableWidth</code> to <code>NO</code> if you want to customize insets or margins. Your mileage may vary, this is not documented very well.</p> <p>This property only exists in iOS 9 so be sure to check before setting.</p> <pre><code>if([myTableView respondsToSelector:@selector(setCellLayoutMarginsFollowReadableWidth:)]) { myTableView.cellLayoutMarginsFollowReadableWidth = NO; } </code></pre> <p><strong>Swift 4:</strong></p> <pre><code>if myTableView.responds(to: #selector(setter: self.cellLayoutMarginsFollowReadableWidth)) { myTableView.cellLayoutMarginsFollowReadableWidth = false } </code></pre> <p>(above code from <a href="https://stackoverflow.com/questions/25770119/ios-8-uitableview-separator-inset-0-not-working/32860532#32860532">iOS 8 UITableView separator inset 0 not working</a>)</p> <p><strong>EDIT: Here's a pure Interface Builder approach:</strong></p> <p><a href="https://i.stack.imgur.com/QLjGB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QLjGB.png" alt="TableViewAttributesInspector"></a> <a href="https://i.stack.imgur.com/pbgBU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pbgBU.png" alt="TableViewCellSizeInspector"></a></p> <p><em>NOTE: iOS 11 changes &amp; simplifies much of this behavior, an update will be forthcoming...</em></p>
4,165,213
Tuning mod_wsgi in daemon mode
<p>I'm running wsgi application on apache mod_wsgi in daemon mode. I have these lines in the configuration</p> <pre><code>WSGIDaemonProcess app processes=2 threads=3 display-name=%{GROUP} WSGIProcessGroup app </code></pre> <p>How do I find the optimal combination/tuning of processes and threads?</p> <p><strong>EDIT</strong>: This link [given in answer bellow] was quite usefull: <a href="https://serverfault.com/questions/145617/apache-2-2-mpm-worker-more-threads-or-more-processes/146382#146382">https://serverfault.com/questions/145617/apache-2-2-mpm-worker-more-threads-or-more-processes/146382#146382</a></p> <p>Now, my question is this: If my server gives quite good performance for my needs, should I reduce the number of threads to increase stability / reliability? Can I even set it to 1?</p>
4,170,445
2
0
null
2010-11-12 13:43:59.44 UTC
13
2010-11-13 22:05:39.04 UTC
2017-04-13 12:13:41.637 UTC
null
-1
null
505,165
null
1
20
python|apache|mod-wsgi|wsgi
11,481
<p>You might get more information on ServerFault as well. For example: <a href="https://serverfault.com/questions/145617/apache-2-2-mpm-worker-more-threads-or-more-processes">https://serverfault.com/questions/145617/apache-2-2-mpm-worker-more-threads-or-more-processes</a></p> <p>This is another good resource for the topic: <a href="http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading#The_mod_wsgi_Daemon_Processes" rel="nofollow noreferrer">http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading#The_mod_wsgi_Daemon_Processes</a> which briefly describes the options -- including setting threads = 1.</p> <p>I haven't done this yet but it sounds like it doesn't much matter. Supporting multiple threads as well as multiple processors are both well supported. But for my experience level (and probably yours) its worthwhile to eliminate threading as an extra source of concern -- even if it is theoretically rock solid.</p>
4,495,000
Multi-threading in MATLAB
<p>I have read MATLAB's info on multi-threading and how it is in-built in certain functions. However, my requirement is different. Say, I have 3 functions: fun1(data1), fun2(data2), fun3(data3).... Can I implement multi-threading between these functions? I actually have 300+ functions using a lot of data. Multi-threading may help me cut down a lot of the time. Please suggest a command or something which I can further research on. Thanks!</p>
4,495,746
2
1
null
2010-12-20 23:27:11.963 UTC
11
2016-10-10 13:13:24.273 UTC
2010-12-21 02:20:59.05 UTC
null
459,640
null
339,644
null
1
20
multithreading|matlab
24,538
<p>If you want to run a batch of different functions on different processors, you can use the Parallel Computing Toolbox, more specifically, a <a href="http://www.mathworks.com/help/toolbox/distcomp/brb2x2l-1.html" rel="noreferrer">parfor</a> loop, but you need to pass the functions as a list of handles.</p> <pre><code>funList = {@fun1,@fun2,@fun3}; dataList = {data1,data2,data3}; %# or pass file names matlabpool open parfor i=1:length(funList) %# call the function funList{i}(dataList{i}); end </code></pre> <p><strong>Edit:</strong> Starting with R2015a <code>matlabpool</code> function <a href="http://www.mathworks.com/help/distcomp/release-notes.html?searchHighlight=matlabpool" rel="noreferrer">has been removed</a> from Matlab, you need to call <code>parpool</code> instead.</p>
4,666,347
Create text Stroke for UILabel iphone
<p>I was wondering how can I create text stroke for UILabel in iOS4 ? I need some suggestion . I want something like this :</p> <p><img src="https://i.stack.imgur.com/3rg5V.jpg" alt="alt text"></p> <p>EDITED :</p> <pre><code>UIFont *font = [UIFont fontWithName:@"Arial" size:222]; CGPoint point = CGPointMake(0,0); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.7); CGContextSetRGBStrokeColor(context, 2, 2, 2, 1.0); CGContextSetTextDrawingMode(context, kCGTextFillStroke); CGContextSaveGState(context); // I change it to my outlet [label.text drawAtPoint:point withFont:font]; CGContextRestoreGState(context); </code></pre>
4,666,426
2
1
null
2011-01-12 07:39:57.203 UTC
13
2015-02-19 17:31:04.643 UTC
2011-06-09 09:46:33.51 UTC
null
491,980
null
319,097
null
1
30
iphone|ios4
13,584
<pre><code>UIFont *font = [UIFont fontWithName:@"Arial" size:14]; CGPoint point = CGPointMake(0,0); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.7); CGContextSetRGBStrokeColor(context, 0.0, 0.0, 0.0, 1.0); CGContextSetTextDrawingMode(context, kCGTextFillStroke); CGContextSaveGState(context); [@"Label" drawAtPoint:point withFont:font]; CGContextRestoreGState(context); </code></pre> <p>you can look here:</p> <p><a href="http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_text/dq_text.html">http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_text/dq_text.html</a></p> <p>and in the example code here: <a href="http://developer.apple.com/library/ios/#samplecode/QuartzDemo/Introduction/Intro.html%23//apple_ref/doc/uid/DTS40007531">http://developer.apple.com/library/ios/#samplecode/QuartzDemo/Introduction/Intro.html%23//apple_ref/doc/uid/DTS40007531</a></p>
10,085,856
Java Mail Exception Error;
<p>MyCode:</p> <pre><code>import java.util.Properties; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; public class SendMailTLS { public static void main(String[] args) { final String username = "[email protected]"; final String password = "myemailpassword"; Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("[email protected]")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]")); message.setSubject("Testing Subject"); message.setText("Dear Mail Crawler,"+ "\n\n No spam to my email,please!"); Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } } </code></pre> <p>My Error:</p> <blockquote> <blockquote> <p>Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: <br>Unknown SMTP host: smtp.gmail.com;<br> nested exception is:<br> java.net.UnknownHostException: smtp.gmail.com<br> at Mail.SendMailTLS.main(SendMailTLS.java:56)<br> Caused by: javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;<br> nested exception is:<br> java.net.UnknownHostException: smtp.gmail.com<br> at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1970)<br> at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)<br> at javax.mail.Service.connect(Service.java:317)<br> at javax.mail.Service.connect(Service.java:176)<br> at javax.mail.Service.connect(Service.java:125)<br> at javax.mail.Transport.send0(Transport.java:194)<br> at javax.mail.Transport.send(Transport.java:124)<br> at Mail.SendMailTLS.main(SendMailTLS.java:51)<br> Caused by: java.net.UnknownHostException: smtp.gmail.com<br> at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:177)<br> at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)<br> at java.net.Socket.connect(Socket.java:525)<br> at java.net.Socket.connect(Socket.java:475)<br> at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:319)<br> at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)<br> at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1938)<br> ... 7 more<br> Java Result: 1<br></p> </blockquote> </blockquote> <p><strong>I am having the Local proxy as 172.17.0.4:8080</strong> with username as :<strong>user1</strong>, password as: <strong>user2</strong> <Br> Solutions pls??</p>
10,086,843
6
4
null
2012-04-10 09:03:53.35 UTC
6
2021-09-29 04:59:51.933 UTC
2012-04-10 09:34:02.623 UTC
null
197,532
null
1,162,072
null
1
12
java|jakarta-mail
42,411
<p>If you are under a proxy I think you can't use Java Mail.</p> <p>From : <a href="http://www.oracle.com/technetwork/java/faq-135477.html#proxy" rel="nofollow noreferrer">oracle.com</a></p> <blockquote> <p>Q: How do I configure JavaMail to work through my proxy server?</p> <p>A: JavaMail does not currently support accessing mail servers through a web proxy server. One of the major reasons for using a proxy server is to allow HTTP requests from within a corporate network to pass through a corporate firewall. The firewall will typically block most access to the Internet, but will allow requests from the proxy server to pass through. In addition, a mail server inside the corporate network will perform a similar function for email, accepting messages via SMTP and forwarding them to their ultimate destination on the Internet, and accepting incoming messages and sending them to the appropriate internal mail server.</p> </blockquote> <hr /> <p>Update</p> <blockquote> <p>Q: How do I configure JavaMail to work through my proxy server? [updated!]</p> </blockquote> <blockquote> <p>A: Starting with JavaMail 1.6.0, JavaMail supports accessing mail servers through a web proxy server. Set the &quot;mail.protocol.proxy.host&quot; and &quot;mail.protocol.proxy.port&quot; properties for the proxy server. Proxy server BASIC authentication is supported by setting the &quot;mail.protocol.proxy.user&quot; and &quot;mail.protocol.proxy.password&quot; properties.</p> </blockquote> <blockquote> <p>In addition, if your proxy server supports the SOCKS V4 or V5 protocol (<a href="http://www.socks.nec.com/aboutsocks.html" rel="nofollow noreferrer">http://www.socks.nec.com/aboutsocks.html</a>, RFC1928) and allows anonymous connections, and you're using JDK 1.5 or newer and JavaMail 1.4.5 or newer, you can configure a SOCKS proxy on a per-session, per-protocol basis by setting the &quot;mail.smtp.socks.host&quot; property as described in the javadocs for the com.sun.mail.smtp package. Similar properties exist for the &quot;imap&quot; and &quot;pop3&quot; protocols. Authentication for SOCKS servers is supported by the JDK by setting the &quot;java.net.socks.username&quot; and &quot;java.net.socks.password&quot; System properties (and thus apply to all SOCKS connections) as describe in the JDK Networking Properties documentation.</p> </blockquote> <blockquote> <p>If you're using older versions of the JDK or JavaMail, you can tell the Java runtime to direct all TCP socket connections to the SOCKS server. See the Networking Properties guide for the latest documentation of the socksProxyHost and socksProxyPort properties. These are system-level properties, not JavaMail session properties. They can be set from the command line when the application is invoked, for example: java -DsocksProxyHost=myproxy .... This facility can be used to direct the SMTP, IMAP, and POP3 communication from JavaMail to the SOCKS proxy server. Note that setting these properties directs all TCP sockets to the SOCKS proxy, which may have negative impact on other aspects of your application.</p> </blockquote> <blockquote> <p>When using older versions of JavaMail, and without such a SOCKS server, if you want to use JavaMail to access mail servers outside the firewall indirectly, you might be able to use a program such as connect to tunnel TCP connections through an HTTP proxy server. Configure JavaMail to use the connect instance as the SOCKS server.</p> </blockquote>
9,825,796
How to make text vertically and horizontally center in an HTML page
<p>I have some experience with Java , C , databases , networking etc..But anything related with Html I am a begginer.The only thing that I am looking for is to center two words in the middle of the page(This page will have only those two words).</p> <pre><code> WORD1 WORDWORDWORDWORD2 </code></pre> <p>I have tried some WYSIWYG software like KompoZer, but when I looked to the source code, it had generated a horrible static code with a lot of <code>&lt;br&gt;</code> to achieve the vertically center of the page.Anybody could help me finding a good solution to this problem</p>
9,826,008
7
3
null
2012-03-22 15:48:11.657 UTC
2
2021-04-03 21:15:42.663 UTC
2013-12-10 06:53:57.823 UTC
null
43,140
null
371,730
null
1
15
html|css|text-alignment
55,034
<p>Centering horizontally is easy - centering vertically is a bit tricky in css as it's not really supported (besides table cells <code>&lt;td&gt;</code>, which is bad style for layouting unless a table is really needed as - well - a table). But you can use semantically correct html tags and apply table display properties to it.</p> <p>That's one possible solution - there are many approaches, <a href="http://www.vanseodesign.com/css/vertical-centering/">here is a good article on that</a>.</p> <p>In your case something like that should be sufficient:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="de"&gt; &lt;head&gt; &lt;title&gt;Hello World&lt;/title&gt; &lt;style&gt; html, body { height: 100%; margin: 0; padding: 0; width: 100%; } body { display: table; } .my-block { text-align: center; display: table-cell; vertical-align: middle; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="my-block"&gt; WORD1&lt;br /&gt; WORDWORDWORDWORD2 &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
10,154,950
Height of outer div not expanding with inner div
<p>I have a bodyMain div of 100% width. Inside it is a body div 800px with auto margin(can I use 'body' as id ?). Inside this are two divs bodyLeft and bodyRight 200px and 600px wide respectively. When I add content to inner divs neither bodyMain nor body expands in height . All heights are auto.</p> <p>Here is the code: <a href="http://jsfiddle.net/TqxHq/18/">http://jsfiddle.net/TqxHq/18/</a></p> <p>HTML:</p> <pre><code>&lt;body&gt; &lt;div id="bodyMain"&gt; &lt;div id="body"&gt; &lt;div id="bodyLeft"&gt; left text goes here&lt;br /&gt; &lt;/div&gt; &lt;div id="bodyRight"&gt;Right text goes here &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>CSS:</p> <pre><code>#bodyMain{ border:1px solid red; width:100%; height:auto; } #body{ border:1px solid green; width:804px; height:auto; margin:auto; } #bodyLeft{ border:1px solid blue; float:left; width:200PX; height:auto; } #bodyRight{ border:1px solid orange; float:right; width:600PX; height:auto; } </code></pre>
10,154,965
5
0
null
2012-04-14 15:49:55.547 UTC
5
2016-07-05 07:28:57.03 UTC
2012-04-14 16:06:25.937 UTC
null
383,904
null
1,199,222
null
1
18
html|css
41,039
<p>You must add </p> <pre><code>&lt;div style="clear:both;"&gt;&lt;/div&gt; </code></pre> <p>at the end of floating div to fix this issue. see <a href="http://jsfiddle.net/TqxHq/20/" rel="noreferrer">here</a></p> <p>Problem happens when a floated element is within a container box and element does not automatically force the container’s height adjust to the floated element. When an element is floated, its parent no longer contains it because the float is removed from the flow. You can use 2 methods to fix it:</p> <pre><code>clear:both clearfix </code></pre>
10,112,376
How to consume OData service with Html/Javascript?
<p>Our project currently uses Silverlight to consume an Odata service. This has made life pretty simple since we can just reference the OData service thus giving us generated service reference/entities.</p> <p>However there is some discussion on whether we should move to Html (html5). I'd like to know what to expect if we make this change. We'd be leveraging a framework like jQuery of course. </p> <ul> <li>My main concern is how to consume the same OData service via JavaScript/jQuery. </li> <li>How are we suppose to deserialize/serialize entities returned from this OData service?</li> <li>Is our data contract supposed to be hard-coded (if so, this is really unacceptable for us)?</li> </ul> <p>Thanks!</p>
10,112,548
4
0
null
2012-04-11 19:11:37.897 UTC
13
2019-09-27 13:53:28.98 UTC
2012-12-07 07:48:38.673 UTC
null
200,253
null
158,103
null
1
19
javascript|jquery|odata|breeze|jaydata
37,564
<p><a href="http://www.odata.org/developers/protocols/json-format">OData sources can return data as JSON</a> so your web pages can XHR your data and receive it as JSON which gets de-serialized back into a Javascript object for you to pick apart and act-upon or display.</p> <p>Here are some additional links to get you started:</p> <ul> <li><a href="http://blogs.msdn.com/b/astoriateam/archive/2011/02/08/new-javascript-library-for-odata-and-beyond.aspx">New Javascript OData Library [MSDN]</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ff478141.aspx">OData protocol by example [MSDN]</a></li> <li><a href="http://codesmartinc.com/2011/01/31/leveraging-odata-end-points-in-json-format-with-jquery/">Leveraging OData end-points in JSON format with JQuery</a></li> <li><a href="http://jaydata.org/tutorials/how-to-build-a-simple-odata-based-ajax-application">Consume an OData service with JayData</a></li> <li><a href="http://www.breezejs.com/">Consume an OData service with BreezeJS</a></li> </ul> <p>HTH.</p>
9,739,806
Can 'this' ever be null in Javascript
<p>I have a function along the lines of the following:</p> <pre><code> doSomething: function () { var parent = null; if (this === null) { parent = 'some default value'; } else { parent = this.SomeValue(); } } </code></pre> <p><strong>Could parent ever be set to 'some default value'</strong> or is the check for null superfluous?</p> <p>Alternatively, what if I used the less restrictive:</p> <pre><code> doSomething: function () { var parent = this ? this.SomeValue() : 'some default value'; } </code></pre> <p><strong>Could parent ever be set to 'some default value' in this case?</strong></p>
9,739,856
6
0
null
2012-03-16 15:12:00.59 UTC
9
2012-03-16 15:33:30.12 UTC
null
null
null
null
98,357
null
1
34
javascript|null|this
10,117
<p>In non-strict mode, <code>this</code> has undergone an <code>Object(this)</code> transformation, so it's always truthy. The exceptions are <code>null</code> and <code>undefined</code> which map to the global object. So <code>this</code> is never <code>null</code> and always truthy, making both checks superfluous.</p> <p>In strict mode, however, <code>this</code> can be anything so in that case you'd have to watch out. But then again you have to opt in for strict mode yourself, so if you don't do that there are no worries.</p> <pre><code>(function() { return this; }).call(null); // global object (function() { "use strict"; return this; }).call(null); // null </code></pre> <p>The <a href="http://es5.github.com/#x15.3.4.4" rel="noreferrer">specification</a> of ES5 says:</p> <blockquote> <p>The thisArg value is passed <strong>without modification</strong> as the this value. This is a change from Edition 3, where a undefined or null thisArg is replaced with <strong>the global object</strong> and <strong>ToObject</strong> is applied to all other values and that result is passed as the this value.</p> </blockquote>
9,891,065
Scale image keeping its aspect ratio in background drawable
<p>How do I make a background image fit the view but keep its aspect ratio when using <code>&lt;bitmap /&gt;</code> as a background drawable XML? None of <code>&lt;bitmap&gt;</code>'s <code>android:gravity</code> values gives the desired effect.</p>
9,891,929
9
3
null
2012-03-27 13:59:34.44 UTC
11
2020-05-05 08:14:27.407 UTC
2018-08-16 13:29:12.437 UTC
null
271,200
null
376,926
null
1
71
android|scaling|android-drawable|android-bitmap|android-background
96,464
<p>It is impossible to achieve manipulating background attribute within xml-files only. There are two options:</p> <ol> <li><p>You cut/scale the bitmap programmatically with <a href="http://developer.android.com/reference/android/graphics/Bitmap.html#createScaledBitmap%28android.graphics.Bitmap,%20int,%20int,%20boolean%29"><code>Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)</code></a> and set it as some <code>View</code>'s background.</p></li> <li><p>You use <code>ImageView</code> instead of background placing it as the first layout's element and specify <a href="http://developer.android.com/reference/android/widget/ImageView.html#attr_android:scaleType"><code>android:scaleType</code></a> attribute for it:</p> <pre><code>&lt;RelativeLayout android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/backgrnd" android:scaleType="centerCrop" /&gt; ... rest layout components here ... &lt;/RelativeLayout&gt; </code></pre></li> </ol>
9,847,244
What are the parameters sent to .fail in jQuery?
<p>I can’t find the documentation on what the names of the three parameters are when <code>$.ajax</code> fails.</p> <p>Right now, I’m just using:</p> <pre class="lang-js prettyprint-override"><code>.fail(function(A, B, C) { </code></pre>
9,847,328
2
1
null
2012-03-23 22:23:43.78 UTC
4
2016-06-11 20:07:32.24 UTC
2016-06-11 20:07:32.24 UTC
null
2,083,613
null
111,665
null
1
121
jquery|ajax
65,747
<p>According to <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">http://api.jquery.com/jQuery.ajax/</a> the <code>fail</code> callback should be getting: </p> <p><code>jqXHR, textStatus, errorThrown</code></p> <p>same as <code>error</code>, but <code>error</code> is deprecated: </p> <blockquote> <p>Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.</p> </blockquote>
8,098,615
Extending a java ArrayList
<p>I'd like to extend ArrayList to add a few methods for a specific class whose instances would be held by the extended ArrayList. A simplified illustrative code sample is below.</p> <p>This seems sensible to me, but I'm very new to Java and I see other questions which discourage extending ArrayList, for example <a href="https://stackoverflow.com/questions/6524711/extending-arraylist-and-creating-new-methods">Extending ArrayList and Creating new methods</a>. I don't know enough Java to understand the objections.</p> <p>In my prior attempt, I ending up creating a number of methods in ThingContainer that were essentially pass-throughs to ArrayList, so extending seemed easier.</p> <p>Is there a better way to do what I'm trying to do? If so, how should it be implemented?</p> <pre><code>import java.util.*; class Thing { public String name; public int amt; public Thing(String name, int amt) { this.name = name; this.amt = amt; } public String toString() { return String.format("%s: %d", name, amt); } public int getAmt() { return amt; } } class ThingContainer extends ArrayList&lt;Thing&gt; { public void report() { for(int i=0; i &lt; size(); i++) { System.out.println(get(i)); } } public int total() { int tot = 0; for(int i=0; i &lt; size(); i++) { tot += ((Thing)get(i)).getAmt(); } return tot; } } public class Tester { public static void main(String[] args) { ThingContainer blue = new ThingContainer(); Thing a = new Thing("A", 2); Thing b = new Thing("B", 4); blue.add(a); blue.add(b); blue.report(); System.out.println(blue.total()); for (Thing tc: blue) { System.out.println(tc); } } } </code></pre>
8,098,644
3
6
null
2011-11-11 18:56:02.39 UTC
10
2011-11-12 16:06:21.613 UTC
2017-05-23 11:54:43.49 UTC
null
-1
null
173,922
null
1
18
java|arraylist|extend
45,064
<p>Nothing in that answer discourages extending ArrayList; there was a syntax issue. Class extension exists so we may re-use code.</p> <p>The normal objections to extending a class is the <a href="http://en.wikipedia.org/wiki/Composition_over_inheritance" rel="noreferrer">"favor composition over inheritance"</a> discussion. Extension isn't always the preferred mechanism, but it depends on what you're actually doing.</p> <p><em>Edit for composition example as requested.</em></p> <pre><code>public class ThingContainer implements List&lt;Thing&gt; { // Or Collection based on your needs. List&lt;Thing&gt; things; public boolean add(Thing thing) { things.add(thing); } public void clear() { things.clear(); } public Iterator&lt;Thing&gt; iterator() { things.iterator(); } // Etc., and create the list in the constructor } </code></pre> <p>You wouldn't necessarily <em>need</em> to expose a full list interface, just collection, or none at all. Exposing none of the functionality greatly reduces the general usefulness, though.</p> <p>In Groovy you can just use the <code>@Delegate</code> annotation to build the methods automagically. Java can use <a href="http://projectlombok.org/" rel="noreferrer">Project Lombok</a>'s <code>@Delegate</code> annotation to do the same thing. I'm not sure how Lombok would expose the interface, or if it does.</p> <p>I'm with glowcoder, I don't see anything fundamentally wrong with extension in this case--it's really a matter of which solution fits the problem better.</p> <p><em>Edit for details regarding how inheritance can violate encapsulation</em></p> <p>See Bloch's Effective Java, Item 16 for more details.</p> <p>If a subclass relies on superclass behavior, and the superclass's behavior changes, the subclass may break. If we don't control the superclass, this can be bad.</p> <p>Here's a concrete example, lifted from the book (sorry Josh!), in pseudo-code, and heavily paraphrased (all errors are mine).</p> <pre><code>class CountingHashSet extends HashSet { private int count = 0; boolean add(Object o) { count++; return super.add(o); } boolean addAll(Collection c) { count += c.size(); return super.addAll(c); } int getCount() { return count; } } </code></pre> <p>Then we use it:</p> <pre><code>s = new CountingHashSet(); s.addAll(Arrays.asList("bar", "baz", "plugh"); </code></pre> <p>And it returns... three? Nope. Six. Why?</p> <p><code>HashSet.addAll()</code> is implemented on <code>HashSet.add()</code>, but that's an internal implementation detail. Our subclass <code>addAll()</code> adds three, calls <code>super.addAll()</code>, which invokes <code>add()</code>, which also increments count.</p> <p>We could remove the subclass's <code>addAll()</code>, but now we're relying on superclass implementation details, which could change. We could modify our <code>addAll()</code> to iterate and call <code>add()</code> on each element, but now we're reimplementing superclass behavior, which defeats the purpose, and might not always be possible, if superclass behavior depends on access to private members.</p> <p>Or a superclass might implement a new method that our subclass doesn't, meaning a user of our class could unintentionally bypass intended behavior by directly calling the superclass method, so we have to track the superclass API to determine when, and if, the subclass should change.</p>
7,844,403
How to get the number of columns in a matrix?
<p>Suppose I specify a matrix <code>A</code> like</p> <pre><code>A = [1 2 3; 4 5 6; 7 8 9] </code></pre> <p>how can I query <code>A</code> <strong>(without using <code>length(A)</code>)</strong> to find out it has 3 columns?</p>
7,844,417
3
0
null
2011-10-21 02:39:42.167 UTC
8
2015-02-16 19:58:44.027 UTC
2014-02-22 03:32:02.083 UTC
null
2,778,484
null
45,963
null
1
34
matlab
157,609
<p>Use the <a href="http://www.mathworks.com/help/matlab/ref/size.html"><code>size()</code></a> function.</p> <pre><code>&gt;&gt; size(A,2) Ans = 3 </code></pre> <p>The second argument specifies the dimension of which number of elements are required which will be '2' if you want the number of columns.</p> <p><a href="http://in.mathworks.com/help/matlab/ref/size.html">Official documentation.</a></p>
11,504,997
Symfony2 datetime best way to store timestamps?
<p>I don't know which is the best way to store a timestamp in the database. I want to store the entire date with hours minutes and seconds but it only stores the date ( for instance 2012-07-14 ) and i want to store 2012-07-14 HH:MM:SS. I am using the dateTime object. Here is the code:</p> <p><strong>In the controller:</strong></p> <pre><code>$user-&gt;setCreated(new \DateTime()); </code></pre> <p><strong>In the entity:</strong></p> <pre><code>/** * @var date $created * * @ORM\Column(name="created", type="date") */ private $created; </code></pre> <p>Is it better to store the date and the the time separately in the database ? or better to store all together like YYYY-MM-DD HH:MM:SS ? I will have then to compare dates and calculate the remaining times, so that is important in order to simplify the operations later. So what do you think ? can somebody help me?</p>
11,505,475
4
1
null
2012-07-16 13:06:55.37 UTC
5
2014-03-18 17:29:51.503 UTC
2013-11-05 07:21:00.56 UTC
null
1,933,347
null
1,451,739
null
1
12
php|datetime|symfony|doctrine-orm|timestamp
41,431
<p>The best way to store a timestamp in the database is obviously to use the timestamp column if your database supports that type. And since you can set that column to autoupdate on create, you dont even have to provide a setter for it.</p> <p>There is a <a href="https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/timestampable.md">Timestampable behavior extension for Doctrine 2</a> which does exactly that from the userland side as well:</p> <blockquote> <p>Timestampable behavior will automate the update of date fields on your Entities or Documents. It works through annotations and can update fields on creation, update or even on specific property value change.</p> <p><strong>Features:</strong></p> <ul> <li>Automatic predifined date field update on creation, update and even on record property changes</li> <li>ORM and ODM support using same listener</li> <li>Specific annotations for properties, and no interface required</li> <li>Can react to specific property or relation changes to specific value</li> <li>Can be nested with other behaviors</li> <li>Annotation, Yaml and Xml mapping support for extensions</li> </ul> </blockquote> <p>With this behavior, all you need to do is change your annotation to </p> <pre><code>/** * @var datetime $created * * @Gedmo\Timestampable(on="create") * @ORM\Column(type="datetime") */ private $created; </code></pre> <p>Then you dont need to call <code>setCreated</code> in your code. The field will be set automatically when the Entity is created for the first time.</p>
12,009,832
How to concatenate string when setting a parameter in Transact-SQL
<p>First question here and is the following. I wrote the following code and everything works fine:</p> <pre><code>DECLARE @subject NVARCHAR(100) SET @subject = 'Report executed on ' + CONVERT(VARCHAR(12), GETDATE(), 107) SELECT @subject </code></pre> <p>Result: Report executed on Aug 17, 2012</p> <p>but when trying to concatenate the previous string while setting the parameter of msdb.dbo.sp_send_dbmail procedure, it fails</p> <pre><code>EXEC msdb.dbo.sp_send_dbmail @profile_name='XXX', @recipients='[email protected]', @subject = 'Report executed on ' + CONVERT(VARCHAR(12), GETDATE(), 107), @body= @tableHTML, @body_format = 'HTML'; </code></pre> <p>I know I could declare and send a variable to the parameter but I would like to understand why it fails when concatenating directly in the parameter. thank you for your time and knowledge</p>
12,009,948
2
0
null
2012-08-17 16:46:36.293 UTC
1
2014-12-15 12:25:00.677 UTC
null
null
null
null
1,607,443
null
1
27
sql-server|tsql
52,704
<p>Parameter values to T-SQL stored procedures cannot be expressions. They need to be either a constant or a variable.</p> <p>From <a href="http://msdn.microsoft.com/en-us/library/ms189260.aspx">MSDN - Specify Parameters</a>:</p> <blockquote> <p>The parameter values supplied with a procedure call must be constants or a variable; a function name cannot be used as a parameter value. Variables can be user-defined or system variables such as @@spid.</p> </blockquote>
11,796,985
Java regular expression to remove all non alphanumeric characters EXCEPT spaces
<p>I'm trying to write a regular expression in Java which removes all non-alphanumeric characters from a paragraph, except the spaces between the words.</p> <p>This is the code I've written:</p> <pre><code>paragraphInformation = paragraphInformation.replaceAll("[^a-zA-Z0-9\s]", ""); </code></pre> <p>However, the compiler gave me an error message pointing to the s saying it's an illegal escape character. The program compiled OK before I added the \s to the end of the regular expression, but the problem with that was that the spaces between words in the paragraph were stripped out.</p> <p>How can I fix this error?</p>
11,797,051
5
0
null
2012-08-03 13:44:13.917 UTC
7
2014-08-13 13:41:42.49 UTC
null
null
null
null
790,668
null
1
32
java|regex
64,216
<p>You need to double-escape the <code>\</code> character: <code>"[^a-zA-Z0-9\\s]"</code></p> <p>Java will interpret <code>\s</code> as a Java String escape character, which is indeed an invalid Java escape. By writing <code>\\</code>, you escape the <code>\</code> character, essentially sending a single <code>\</code> character to the regex. This <code>\</code> then becomes part of the regex escape character <code>\s</code>.</p>
11,625,096
How to clone a JPA entity
<p>I have a JPA entity already persisted in the database.<br> I would like to have a copy of it (with a different id), with some fields modified.</p> <p>What is the easiest way to do this? Like:</p> <ul> <li>setting it's <code>@Id</code> field to <code>null</code> and persisting it will work?</li> <li>will I have to create a clone method for the entity (copying all fields except the <code>@Id</code>)?</li> <li>is there any other approach (like using a cloning framework)?</li> </ul>
11,625,136
8
2
null
2012-07-24 06:11:04.38 UTC
18
2021-01-10 13:19:51.993 UTC
2020-12-07 11:31:47.04 UTC
null
1,025,118
null
714,862
null
1
55
java|jpa|orm|entity|clone
63,459
<p>Use <code>EntityManager.detach</code>. It makes the bean no longer linked to the EntityManager. Then set the Id to the new Id (or null if automatic), change the fields that you need and persist.</p>
19,945,411
How can I parse a local JSON file from assets folder into a ListView?
<p>I'm currently developing a physics app that is supposed to show a list of formulas and even solve some of them (the only problem is the <code>ListView</code>)</p> <p><strong>This is my main layout</strong></p> <pre><code> &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="wrap_content" android:measureWithLargestChild="false" android:orientation="vertical" tools:context=".CatList" &gt; &lt;RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/titlebar" &gt; &lt;TextView android:id="@+id/Title1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/app_name" android:textAppearance="?android:attr/textAppearanceLarge" android:textColor="#ff1c00" android:textIsSelectable="false" /&gt; &lt;/RelativeLayout&gt; &lt;ListView android:id="@+id/listFormulas" android:layout_width="match_parent" android:layout_height="wrap_content" &gt; &lt;/ListView&gt; &lt;/LinearLayout&gt; </code></pre> <p><strong>And this is my main activity</strong></p> <pre><code>package com.wildsushii.quickphysics; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.view.Menu; import android.widget.ListView; public class CatList extends Activity { public static String AssetJSONFile (String filename, Context context) throws IOException { AssetManager manager = context.getAssets(); InputStream file = manager.open(filename); byte[] formArray = new byte[file.available()]; file.read(formArray); file.close(); return new String(formArray); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_cat_list); ListView categoriesL = (ListView)findViewById(R.id.listFormulas); ArrayList&lt;HashMap&lt;String, String&gt;&gt; formList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); Context context = null; try { String jsonLocation = AssetJSONFile("formules.json", context); JSONObject formArray = (new JSONObject()).getJSONObject("formules"); String formule = formArray.getString("formule"); String url = formArray.getString("url"); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } //My problem is here!! } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.cat_list, menu); return true; } } </code></pre> <p>I actually know I can make this without using JSON but I need more practice parsing JSON. By the way, this is the JSON</p> <pre><code> { "formules": [ { "formule": "Linear Motion", "url": "qp1" }, { "formule": "Constant Acceleration Motion", "url": "qp2" }, { "formule": "Projectile Motion", "url": "qp3" }, { "formule": "Force", "url": "qp4" }, { "formule": "Work, Power, Energy", "url": "qp5" }, { "formule": "Rotary Motion", "url": "qp6" }, { "formule": "Harmonic Motion", "url": "qp7" }, { "formule": "Gravity", "url": "qp8" }, { "formule": "Lateral and Longitudinal Waves", "url": "qp9" }, { "formule": "Sound Waves", "url": "qp10" }, { "formule": "Electrostatics", "url": "qp11" }, { "formule": "Direct Current", "url": "qp12" }, { "formule": "Magnetic Field", "url": "qp13" }, { "formule": "Alternating Current", "url": "qp14" }, { "formule": "Thermodynamics", "url": "qp15" }, { "formule": "Hydrogen Atom", "url": "qp16" }, { "formule": "Optics", "url": "qp17" }, { "formule": "Modern Physics", "url": "qp18" }, { "formule": "Hydrostatics", "url": "qp19" }, { "formule": "Astronomy", "url": "qp20" } ] } </code></pre> <p>I have tried a lot of things and even delete the entire project to make a new one :(</p>
19,945,484
9
5
null
2013-11-13 04:38:21.627 UTC
92
2022-08-04 09:32:49.82 UTC
2020-09-24 09:01:43.43 UTC
null
4,685,471
null
2,967,747
null
1
214
java|android|json|android-listview|local
314,153
<p>As Faizan describes in <a href="https://stackoverflow.com/questions/13814503/reading-a-json-file-in-android/13814551#13814551">their answer here</a>:</p> <p>First of all read the Json File from your assests file using below code.</p> <p>and then you can simply read this string return by this function as</p> <pre><code>public String loadJSONFromAsset() { String json = null; try { InputStream is = getActivity().getAssets().open("yourfilename.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; } </code></pre> <p>and use this method like that</p> <pre><code> try { JSONObject obj = new JSONObject(loadJSONFromAsset()); JSONArray m_jArry = obj.getJSONArray("formules"); ArrayList&lt;HashMap&lt;String, String&gt;&gt; formList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); HashMap&lt;String, String&gt; m_li; for (int i = 0; i &lt; m_jArry.length(); i++) { JSONObject jo_inside = m_jArry.getJSONObject(i); Log.d("Details--&gt;", jo_inside.getString("formule")); String formula_value = jo_inside.getString("formule"); String url_value = jo_inside.getString("url"); //Add your values in your `ArrayList` as below: m_li = new HashMap&lt;String, String&gt;(); m_li.put("formule", formula_value); m_li.put("url", url_value); formList.add(m_li); } } catch (JSONException e) { e.printStackTrace(); } </code></pre> <p>For further details regarding JSON <a href="http://www.vogella.com/articles/AndroidJSON/article.html" rel="noreferrer">Read HERE</a></p>
3,870,707
Use jQuery to change value of a label
<p>I have a label, costLabel. </p> <p>What I want to be able to do is change the value of this label depending on the selected value of a dropdownlist.</p> <p>This is my HTML:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td width="343"&gt;Package*&lt;/td&gt; &lt;td colspan="4"&gt; &lt;select class="purple" name="package"&gt; &lt;option value="standard"&gt;Standard - &amp;euro;55 Monthly&lt;/option&gt; &lt;option value="standardAnn"&gt;Standard - &amp;euro;49 Monthly&lt;/option&gt; &lt;option value="premium"&gt;Premium - &amp;euro;99 Monthly&lt;/option&gt; &lt;option value="premiumAnn" selected="selected"&gt;Premium - &amp;euro;89 Monthly&lt;/option&gt; &lt;option value="platinum"&gt;Platinum - &amp;euro;149 Monthly&lt;/option&gt; &lt;option value="platinumAnn"&gt;Platinum - &amp;euro;134 Monthly&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;tr&gt; &lt;td width="343"&gt; &lt;p&gt;We bills quarterly/annually in advance&lt;/p&gt; &lt;p&gt;See &lt;a href="#dialog" name="modal"&gt;Pricing&lt;/a&gt; for more details&lt;/p&gt; &lt;/td&gt; &lt;td colspan="4"&gt;&lt;label id="costlabel" name="costlabel"&gt;Total Cost:&lt;/label&gt;&lt;/td&gt; &lt;tr&gt; &lt;/table&gt; </code></pre> <p>The values that go into the cost label are</p> <ul> <li>Standard = "€165 Quarterly"</li> <li>StandardAnn = "€588 Annually"</li> <li>Premium = "€297 Quarterly"</li> <li>PremiumAnn = "€1068 Annually"</li> <li>Platinum = "€447 Quarterly"</li> <li>PlatinumAnn = "€1608 Annually"</li> </ul> <p>I did have the following code in place which calculated the cost depending on the dropdown menu, but the registration form has since changed to be more simpler(i.e. discountselection is not gone), and I'm having a bit of trouble adapting the jQuery. Can someone help?</p> <pre><code>$(function() { $("#discountselection, select[name=package], input[name=discount]"). change(function() { var selected_value = $("#discountselection").val(), discount = [12, 24, 36], package = $("select[name=package]").val(), package_prices = {'standard': 49, 'premium': 85, 'platinum': 134 }, cost = package_prices[package] * discount[selected_value-1]; $("#costlabel").val(cost); }); }); </code></pre>
3,870,789
4
3
null
2010-10-06 08:31:04.96 UTC
2
2015-07-02 21:53:14.767 UTC
2010-10-06 09:01:00.43 UTC
null
376,083
null
376,083
null
1
20
jquery|drop-down-menu
107,733
<p>I seem to have a blind spot as regards your html structure, but I <em>think</em> that this is what you're looking for. It should find the currently-selected option from the <code>select</code> input, assign its text to the <code>newVal</code> variable and <em>then</em> apply that variable to the <code>value</code> attribute of the <code>#costLabel</code> label:</p> <h3>jQuery</h3> <pre><code>$(document).ready( function() { $('select[name=package]').change( function(){ var newText = $('option:selected',this).text(); $('#costLabel').text('Total price: ' + newText); } ); } ); </code></pre> <h3>html:</h3> <pre><code> &lt;form name=&quot;thisForm&quot; id=&quot;thisForm&quot; action=&quot;#&quot; method=&quot;post&quot;&gt; &lt;fieldset&gt; &lt;select name=&quot;package&quot; id=&quot;package&quot;&gt; &lt;option value=&quot;standard&quot;&gt;Standard - &amp;euro;55 Monthly&lt;/option&gt; &lt;option value=&quot;standardAnn&quot;&gt;Standard - &amp;euro;49 Monthly&lt;/option&gt; &lt;option value=&quot;premium&quot;&gt;Premium - &amp;euro;99 Monthly&lt;/option&gt; &lt;option value=&quot;premiumAnn&quot; selected=&quot;selected&quot;&gt;Premium - &amp;euro;89 Monthly&lt;/option&gt; &lt;option value=&quot;platinum&quot;&gt;Platinum - &amp;euro;149 Monthly&lt;/option&gt; &lt;option value=&quot;platinumAnn&quot;&gt;Platinum - &amp;euro;134 Monthly&lt;/option&gt; &lt;/select&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;label id=&quot;costLabel&quot; name=&quot;costLabel&quot;&gt;Total price: &lt;/label&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>Working demo of the above at: <a href="http://jsbin.com/oyuxa4/4/" rel="noreferrer">JS Bin</a></p>
3,850,749
Does realloc overwrite old contents?
<p>When we reallocate memory via <code>realloc()</code>, are the previous contents over-written? I am trying to make a program which reallocates memory each time we enter the data into it. </p> <p>Please tell me about memory allocation via realloc, is it compiler dependent for example?</p>
3,850,798
4
0
null
2010-10-03 17:18:00.857 UTC
19
2010-10-03 17:37:10.147 UTC
2010-10-03 17:37:10.147 UTC
null
141,661
user379888
null
null
1
40
c|realloc
36,669
<p>Don't worry about the old contents.</p> <p>The correct way to use <code>realloc</code> is to use a specific pointer for the reallocation, test that pointer and, if everything worked out ok, change the old pointer</p> <pre><code>int *oldpointer = malloc(100); /* ... */ int *newpointer = realloc(oldpointer, 1000); if (newpointer == NULL) { /* problems!!!! */ /* tell the user to stop playing DOOM and retry */ /* or free(oldpointer) and abort, or whatever */ } else { /* everything ok */ /* `newpointer` now points to a new memory block with the contents of oldpointer */ /* `oldpointer` points to an invalid address */ oldpointer = newpointer; /* oldpointer points to the correct address */ /* the contents at oldpointer have been copied while realloc did its thing */ /* if the new size is smaller than the old size, some data was lost */ } /* ... */ /* don't forget to `free(oldpointer);` at some time */ </code></pre>
3,458,571
jQuery - Click event on <tr> elements with in a table and getting <td> element values
<p>I have the following HTML in a <a href="http://en.wikipedia.org/wiki/JavaServer_Pages" rel="noreferrer">JSP</a> file:</p> <pre><code>&lt;div class="custList"&gt; &lt;table class="dataGrid"&gt; &lt;c:forEach var="cust" items="${custList}"&gt; &lt;tr&gt; &lt;td&gt;${cust.number}&lt;/td&gt; &lt;td&gt;${cust.description}&lt;/td&gt; &lt;td&gt;${cust.type}&lt;/td&gt; &lt;td&gt;${cust.status}&lt;/td&gt; &lt;/tr&gt; &lt;/c:forEach&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>I need to be able to trigger a <code>'click'</code> event on each of the dynamically created <code>&lt;tr&gt;</code> tags and also be able to access the values of the <code>&lt;td&gt;</code> tags (of the clicked <code>&lt;tr&gt;</code>) from within the JavaScript function. I have this function already, but sadly it doesn't seem to be working.</p> <pre><code>$(document).ready(function() { $("div.custList &gt; table &gt; tr").live('click', function() { alert("You clicked my &lt;tr&gt;!"); //get &lt;td&gt; element values here!!?? }); }); </code></pre> <hr> <p><strong>Update (Jan 2016)</strong>: jQuery.live is deprecated (as noted here:<a href="http://api.jquery.com/live/" rel="noreferrer">http://api.jquery.com/live/</a>) </p> <blockquote> <p>As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.</p> </blockquote>
3,458,596
7
0
null
2010-08-11 13:08:04.723 UTC
8
2017-06-22 20:46:19.603 UTC
2016-02-03 22:40:27.08 UTC
null
1,229,624
null
355,957
null
1
38
javascript|jquery|jquery-selectors
143,477
<p>Unless otherwise definied (<code>&lt;tfoot&gt;</code>, <code>&lt;thead&gt;</code>), browsers put <code>&lt;tr&gt;</code> <em>implicitly</em> in a <code>&lt;tbody&gt;</code>.</p> <p>You need to put a <code>&gt; tbody</code> in between <code>&gt; table</code> and <code>&gt; tr</code>:</p> <pre><code>$("div.custList &gt; table &gt; tbody &gt; tr") </code></pre> <p>Alternatively, you can also be less strict in selecting the rows (the <code>&gt;</code> denotes the <em>immediate</em> child):</p> <pre><code>$("div.custList table tr") </code></pre> <hr> <p>That said, you can get the immediate <code>&lt;td&gt;</code> children there by <a href="http://api.jquery.com/children/" rel="noreferrer"><code>$(this).children('td')</code></a>.</p>
3,379,471
php: number only hash?
<p>In php is there a way to give a unique hash from a string, but that the hash was made up from numbers only?</p> <p>example:</p> <pre><code>return md5(234); // returns 098f6bcd4621d373cade4e832627b4f6 </code></pre> <p>but I need</p> <pre><code>return numhash(234); // returns 00978902923102372190 (20 numbers only) </code></pre> <p>the problem here is that I want the hashing to be short.</p> <p><strong>edit:</strong> OK let me explain the back story here. I have a site that has a ID for every registered person, also I need a ID for the person to use and exchange (hence it can't be too long), so far the ID numbering has been 00001, 00002, 00003 etc...</p> <ol> <li>this makes some people look more important</li> <li>this reveals application info that I don't want to reveal.</li> </ol> <p>To fix point 1 and 2 I need to "hide" the number while keeping it unique.</p> <h2>Edit + SOLUTION:</h2> <p>Numeric hash function based on the code by <a href="https://stackoverflow.com/a/23679870/175071">https://stackoverflow.com/a/23679870/175071</a></p> <pre><code>/** * Return a number only hash * https://stackoverflow.com/a/23679870/175071 * @param $str * @param null $len * @return number */ public function numHash($str, $len=null) { $binhash = md5($str, true); $numhash = unpack('N2', $binhash); $hash = $numhash[1] . $numhash[2]; if($len &amp;&amp; is_int($len)) { $hash = substr($hash, 0, $len); } return $hash; } // Usage numHash(234, 20); // always returns 6814430791721596451 </code></pre>
23,679,870
7
2
null
2010-07-31 19:15:23.337 UTC
10
2018-09-26 09:05:34.58 UTC
2018-07-25 09:48:28.677 UTC
null
175,071
null
175,071
null
1
51
php|hash|md5|numbers|short
52,666
<p>There are some good answers but for me the approaches seem silly.<br> They first force php to create a Hex number, then convert this back (<code>hexdec</code>) in a BigInteger and then cut it down to a number of letters... this is much work!</p> <p>Instead why not</p> <p>Read the hash as binary:</p> <pre><code>$binhash = md5('[input value]', true); </code></pre> <p>then using </p> <pre><code>$numhash = unpack('N2', $binhash); //- or 'V2' for little endian </code></pre> <p>to cast this as two <code>INT</code>s (<code>$numhash</code> is an array of two elements). Now you can reduce the number of bits in the number simply using an <code>AND</code> operation. e.g:</p> <pre><code>$result = $numhash[1] &amp; 0x000FFFFF; //- to get numbers between 0 and 1048575 </code></pre> <p><strong>But be warned of collisions!</strong> Reducing the number means increasing the probability of two different [input value] with the same output. </p> <p>I think that the much better way would be the use of "ID-Crypting" with a Bijectiv function. So no collisions could happen! For the simplest kind just use an <a href="http://en.wikipedia.org/wiki/Affine_cipher" rel="noreferrer">Affine_cipher</a></p> <p>Example with max input value range from 0 to 25:</p> <pre><code>function numcrypt($a) { return ($a * 15) % 26; } function unnumcrypt($a) { return ($a * 7) % 26; } </code></pre> <p>Output:</p> <pre><code>numcrypt(1) : 15 numcrypt(2) : 4 numcrypt(3) : 19 unnumcrypt(15) : 1 unnumcrypt(4) : 2 unnumcrypt(19) : 3 </code></pre> <p>e.g.</p> <pre><code>$id = unnumcrypt($_GET('userid')); ... do something with the ID ... echo '&lt;a href="do.php?userid='. numcrypt($id) . '"&gt; go &lt;/a&gt;'; </code></pre> <p>of course this is not secure, but if no one knows the method used for your encryption then there are no security reasons then this way is faster and collision safe.</p>
3,404,421
Password masking console application
<p>I tried the following code... </p> <pre><code>string pass = ""; Console.Write("Enter your password: "); ConsoleKeyInfo key; do { key = Console.ReadKey(true); // Backspace Should Not Work if (key.Key != ConsoleKey.Backspace) { pass += key.KeyChar; Console.Write("*"); } else { Console.Write("\b"); } } // Stops Receving Keys Once Enter is Pressed while (key.Key != ConsoleKey.Enter); Console.WriteLine(); Console.WriteLine("The Password You entered is : " + pass); </code></pre> <p>But this way the backspace functionality doesn't work while typing the password. Any suggestion?</p>
3,404,522
17
3
null
2010-08-04 09:59:24 UTC
77
2021-08-03 12:18:18.097 UTC
2012-02-07 18:55:51.51 UTC
null
847,363
null
301,459
null
1
236
c#|passwords|console-application|user-input|masking
172,277
<p><code>Console.Write(&quot;\b \b&quot;);</code> will delete the asterisk character from the screen, but you do not have any code within your <code>else</code> block that removes the previously entered character from your <code>pass</code> string variable.</p> <p>Here's the relevant working code that should do what you require:</p> <pre><code>var pass = string.Empty; ConsoleKey key; do { var keyInfo = Console.ReadKey(intercept: true); key = keyInfo.Key; if (key == ConsoleKey.Backspace &amp;&amp; pass.Length &gt; 0) { Console.Write(&quot;\b \b&quot;); pass = pass[0..^1]; } else if (!char.IsControl(keyInfo.KeyChar)) { Console.Write(&quot;*&quot;); pass += keyInfo.KeyChar; } } while (key != ConsoleKey.Enter); </code></pre>
3,951,903
How to make a progress bar
<p>How would one go about making a progress bar in html/css/javascript. I don't really want to use Flash. Something along the lines of what can be found here: <a href="http://dustincurtis.com/about.html" rel="noreferrer">http://dustincurtis.com/about.html</a></p> <p>All I really want is a 'progress bar' that changes to the values I give in PHP. What would be your though process? Are there any good tutorials on this?</p>
3,951,924
19
0
null
2010-10-17 03:32:09.37 UTC
14
2021-10-28 22:09:41.243 UTC
2013-05-24 23:38:46.13 UTC
null
2,156,756
null
403,912
null
1
37
javascript|html|css|progress-bar
157,690
<p>You can do it by controlling the width of a div via css. Something roughly along these lines:</p> <pre><code>&lt;div id="container" style="width:100%; height:50px; border:1px solid black;"&gt; &lt;div id="progress-bar" style="width:50%;/*change this width */ background-image:url(someImage.png); height:45px;"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>That width value can be sent in from php if you so desire.</p>
8,310,227
Using PHP in <script> tag?
<p>I'm trying to create an object in javascript with PHP. This is my script:</p> <pre><code> &lt;script&gt; $(document).ready(function(){ var genres = [ &lt;?php $last = count($userGenres) - 1; $i = 0; foreach($userGenres as $a){ $i++; echo '{"value":"'.$a['genre'].'", "name":"'.$a['name'].'"}'; if($i &lt; $last){ echo ','; } } ?&gt; ]; }); &lt;/script&gt; </code></pre> <p>When I check the generated source, it creates a valid object, but the whole script in that tag doesn't work now. How would fix this, without JSON?</p> <p>Thanks</p>
10,358,278
4
10
null
2011-11-29 11:52:03.467 UTC
1
2012-04-27 21:46:23.263 UTC
2011-11-29 11:58:38.377 UTC
null
954,930
null
954,930
null
1
7
php|javascript|json|object
48,867
<p>As the comment says you should consider using (php function)json_encode instead, which will turn...</p> <pre><code>php: $a = array( array("gender"=&gt; "male", "name"=&gt; "Bob"), array("gender"=&gt; "female", "name"=&gt; "Annie") ); Into json: [ {gender:"male", name:"Bob"}, {gender:"female", name:"Annie"} ] </code></pre> <p>Echoing json_encode($a) would output it just like that.</p>
7,880,850
How do I make an Event in the Usercontrol and have it handled in the Main Form?
<p>I have a custom usercontrol and I want to do something relatively simple.</p> <p>When ever a numeric up down in that usercontrol's value changes, have the main form update a display window.</p> <p>This is not a problem if the NUD was not in a usercontrol but I can't seem to figure out how to have the event handled by the mainform and not the usercontrol.</p>
7,880,901
5
1
null
2011-10-24 19:28:18.613 UTC
34
2020-04-17 17:01:53.093 UTC
2018-04-05 02:09:44.953 UTC
null
1,033,581
null
72,136
null
1
84
c#|winforms|user-controls|event-handling
150,680
<p>You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form. </p> <p>When clicking <code>Button1</code> on the UserControl, i'll fire <code>Button1_Click</code> which triggers <code>UserControl_ButtonClick</code> on the form:</p> <p>User control:</p> <pre><code>[Browsable(true)] [Category("Action")] [Description("Invoked when user clicks button")] public event EventHandler ButtonClick; protected void Button1_Click(object sender, EventArgs e) { //bubble the event up to the parent if (this.ButtonClick!= null) this.ButtonClick(this, e); } </code></pre> <p>Form:</p> <pre><code>UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick); protected void UserControl_ButtonClick(object sender, EventArgs e) { //handle the event } </code></pre> <p><strong>Notes:</strong> </p> <ul> <li><p>Newer Visual Studio versions suggest that instead of <code>if (this.ButtonClick!= null) this.ButtonClick(this, e);</code> you can use <code>ButtonClick?.Invoke(this, e);</code>, which does essentially the same, but is shorter. </p></li> <li><p>The <code>Browsable</code> attribute makes the event visible in Visual Studio's designer (events view), <code>Category</code> shows it in the "Action" category, and <code>Description</code> provides a description for it. You can omit these attributes completely, but making it available to the designer it is much more comfortable, since VS handles it for you.</p></li> </ul>
8,356,501
Python format tabular output
<p>Using python2.7, I'm trying to print to screen tabular data.</p> <p>This is roughly what my code looks like:</p> <pre><code>for i in mylist: print "{}\t|{}\t|".format (i, f(i)) </code></pre> <p>The problem is that, depending on the length of <code>i</code> or <code>f(i)</code> the data won't be aligned.</p> <p>This is what I'm getting:</p> <pre><code>|foo |bar | |foobo |foobar | </code></pre> <p>What I want to get:</p> <pre><code>|foo |bar | |foobo |foobar | </code></pre> <p>Are there any modules that permit doing this?</p>
8,356,620
6
0
null
2011-12-02 12:44:03.887 UTC
7
2017-02-28 08:13:05.77 UTC
null
null
null
null
403,401
null
1
24
python
85,778
<p>It's not really hard to roll your own formatting function:</p> <pre><code>def print_table(table): col_width = [max(len(x) for x in col) for col in zip(*table)] for line in table: print "| " + " | ".join("{:{}}".format(x, col_width[i]) for i, x in enumerate(line)) + " |" table = [(str(x), str(f(x))) for x in mylist] print_table(table) </code></pre>
8,002,455
How to easily initialize a list of Tuples?
<p>I love <a href="http://msdn.microsoft.com/en-us/library/system.tuple.aspx" rel="noreferrer">tuples</a>. They allow you to quickly group relevant information together without having to write a struct or class for it. This is very useful while refactoring very localized code.</p> <p>Initializing a list of them however seems a bit redundant.</p> <pre class="lang-cs prettyprint-override"><code>var tupleList = new List&lt;Tuple&lt;int, string&gt;&gt; { Tuple.Create( 1, &quot;cow&quot; ), Tuple.Create( 5, &quot;chickens&quot; ), Tuple.Create( 1, &quot;airplane&quot; ) }; </code></pre> <p>Isn't there a better way? I would love a solution along the lines of the <a href="http://msdn.microsoft.com/en-us/library/bb531208.aspx" rel="noreferrer">Dictionary initializer</a>.</p> <pre class="lang-cs prettyprint-override"><code>Dictionary&lt;int, string&gt; students = new Dictionary&lt;int, string&gt;() { { 111, &quot;bleh&quot; }, { 112, &quot;bloeh&quot; }, { 113, &quot;blah&quot; } }; </code></pre> <p>Can't we use a similar syntax?</p>
43,011,006
8
4
null
2011-11-03 22:01:45.193 UTC
79
2021-02-11 08:38:01.757 UTC
2021-02-11 08:38:01.757 UTC
null
11,186,795
null
590,790
null
1
373
c#|list|collections|.net-4.0|tuples
387,317
<p>c# 7.0 lets you do this:</p> <pre><code> var tupleList = new List&lt;(int, string)&gt; { (1, "cow"), (5, "chickens"), (1, "airplane") }; </code></pre> <p>If you don't need a <code>List</code>, but just an array, you can do:</p> <pre><code> var tupleList = new(int, string)[] { (1, "cow"), (5, "chickens"), (1, "airplane") }; </code></pre> <p>And if you don't like "Item1" and "Item2", you can do:</p> <pre><code> var tupleList = new List&lt;(int Index, string Name)&gt; { (1, "cow"), (5, "chickens"), (1, "airplane") }; </code></pre> <p>or for an array:</p> <pre><code> var tupleList = new (int Index, string Name)[] { (1, "cow"), (5, "chickens"), (1, "airplane") }; </code></pre> <p>which lets you do: <code>tupleList[0].Index</code> and <code>tupleList[0].Name</code></p> <p><strong>Framework 4.6.2 and below</strong></p> <p>You must install <a href="https://www.nuget.org/packages/System.ValueTuple/" rel="noreferrer"><code>System.ValueTuple</code></a> from the Nuget Package Manager.</p> <p><strong>Framework 4.7 and above</strong></p> <p>It is built into the framework. Do <em>not</em> install <code>System.ValueTuple</code>. In fact, remove it <strong>and</strong> delete it from the bin directory.</p> <p><em>note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.</em></p>
8,185,593
Jenkins, specifying JAVA_HOME
<p>I installed openjdk-6-jdk on my ubuntu box using apt-get.</p> <p>In system info jenkins is telling me Java.Home is <code>/usr/lib/jvm/java-6-openjdk/jre</code></p> <p>However when I specify that directory as <code>JAVA_HOME</code> in Jenkins : "configure system", it returns error message saying that directory does not look like a jdk directory.</p> <p>it is also failing to pick up my maven install.</p> <p>Am I missing something obvious ?</p>
8,185,849
14
0
null
2011-11-18 16:26:39.3 UTC
4
2020-10-06 23:47:34.587 UTC
2013-03-14 09:15:03.813 UTC
null
342,473
null
106,261
null
1
24
java|ubuntu|jenkins|java-home
139,437
<p>Your JAVA_HOME variable must be set to /usr/lib/jvm/java-6-openjdk and it must be available for the user that starts Jenkins.</p> <p><strong><em>From Kyle Strand comment:</em></strong></p> <p><em>As of April 2015 (I think), Jenkins requires Java7. Also note that the java binary path (JAVA) must be set to the correct version if the system default is still Java 6. Finally, for anyone wondering where these variables are set, it's in a config file listed with the installation instructions on the Jenkins webpage (e.g. for Debian it's /etc/default/jenkins).</em></p>
8,059,719
Unable to execute dex: Multiple dex files define
<p>I know this question has been asked here a few times before. But i haven't seen any possible solution yet. Before i make the project 'Run as Android Application' , if i do not clean it, i receive the following error and have to restart Eclipse ... and clean again.</p> <pre><code>Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/jstun/core/attribute/MessageAttributeInterface; </code></pre> <p>com.jstun.core... is a part of my src folder, of course i can't remove it. And even if i remove that package, another package will show up as an error like:</p> <pre><code>Unable to execute dex: Multiple dex files define Landroid/support/v4/app/ActivityCompatHoneycomb; </code></pre> <p>I've seen this error since updating to ADT 15, i'm using Eclipse Galileo on Ubuntu Do you have any idea? Thanks for any reply!</p>
8,071,713
31
3
null
2011-11-09 02:33:12.9 UTC
28
2018-08-14 08:47:51.68 UTC
2015-09-13 23:08:47.607 UTC
null
179,850
null
1,008,698
null
1
125
java|android
193,185
<p><strong>This is a build path issue.</strong></p> <ul> <li><p>Make sure your bin folder is not included in your build path.</p> </li> <li><p>Right click on your project -&gt; go to properties -&gt; Build Path.</p> </li> <li><p>Make sure that Honeycomb library is in your <code>libs/</code> folder and not in your source folder.</p> </li> <li><p>Include the libraries in <code>libs/</code> individually in the build path.</p> <p>BTW, you may want to bring in the <code>android-support-v4</code> library to get Ice Cream Sandwich support instead of the Honeycomb support library.</p> </li> </ul>
4,597,228
How to statically link a library when compiling a python module extension
<p>I would like to modify a setup.py file such that the command "python setup.py build" compiles a C-based extension module that is statically (rather than dynamically) linked to a library.</p> <p>The extension is currently dynamically linked to a number of libraries. I would like to leave everything unchanged except for statically linking to just one library. I have successfully done this by manually modifying the call to gcc that distutils runs, although it required that I explicitly listed the dependent libraries.</p> <p>Perhaps this is too much information, but for clarity this is the final linking command that was executed during the "python setup.py build" script:</p> <pre><code>gcc -pthread -shared -L/system/lib64 -L/system/lib/ -I/system/include build/temp.linux-x86_64-2.7/src/*.o -L/system/lib -L/usr/local/lib -L/usr/lib -ligraph -o build/lib.linux-x86_64-2.7/igraph/core.so </code></pre> <p>And this is my manual modification:</p> <pre><code>gcc -pthread -shared -L/system/lib64 -L/system/lib/ -I/system/include build/temp.linux-x86_64-2.7/src/*.o -L/system/lib -L/usr/local/lib -L/usr/lib /system/lib/libigraph.a -lxml2 -lz -lgmp -lstdc++ -lm -ldl -o build/lib.linux-x86_64-2.7/igraph/core.so </code></pre> <p>Section 2.3.4 of <a href="http://docs.python.org/distutils/index.html" rel="noreferrer">Distributing Python Modules</a> discusses the specification of libraries, but only "library_dirs" is appropriate and those libraries are dynamically linked.</p> <p>I'm using a Linux environment for development but the package will also be compiled and installed on Windows, so a portable solution is what I'm after.</p> <p>Can someone tell me where to look for instructions, or how to modify the setup.py script? (Thanks in advance!)</p> <p>I'm new to StackOverflow, so my apologies if I haven't correctly tagged this question, or if I have made some other error in this posting.</p>
4,600,466
3
0
null
2011-01-04 18:53:04.743 UTC
12
2021-06-02 13:45:19.523 UTC
null
null
null
null
562,930
null
1
35
python|static|compilation
27,642
<p>If all else fails, there's always the little-documented <a href="http://docs.python.org/distutils/setupscript.html#other-options" rel="noreferrer"><code>extra_compile_args</code></a> and <code>extra_link_args</code> options to the <a href="http://docs.python.org/distutils/setupscript.html#describing-extension-modules" rel="noreferrer"><code>Extension</code></a> builder. (See also <a href="http://docs.python.org/distutils/apiref.html" rel="noreferrer">here</a>.)</p> <p>You might need to hack in some OS-dependent code to get the right argument format for a particular platform though.</p>
4,383,388
How to play movie with a URL using a custom NSURLProtocol?
<p>As you know,play a movie with MPMoviePlayerController object using </p> <pre><code>[[MPMoviePlayerController alloc] initWithContentURL: aURL]; </code></pre> <p>now ,i want to achieve a custom NSURLProtocol in which i will decrypt a movie source that had be encrypt by AlgorithmDES. Is that possibility? thanks for giving any ideas.need you help~</p>
4,706,439
4
1
null
2010-12-08 01:27:52.167 UTC
11
2016-11-29 07:51:26.78 UTC
2014-06-03 17:39:51.807 UTC
null
3,140,927
null
352,586
null
1
8
ios|url|mpmovieplayercontroller|nsurlprotocol
8,503
<p><strong>UPDATE:</strong> I spoke to Apple about this and it's not possible to use MPMoviePlayerController with a NSURLProtocol subclass at the moment!</p> <hr> <p>Hej,</p> <p>I am not sure but it could be possible. I am currently working on something similar but haven't got it fully working. What I have found out is that MPMoviePlayerController interacts with my custom NSURLProtocol subclass BUT it seems to be important to take the HTTPHeaders of the NSURLRequest into account because they define a range of bytes the MPMoviePlayerController needs.</p> <p>If you dump them in your NSURLProtocol subclass you will get something like this twice for the start:</p> <pre><code>2011-01-16 17:00:47.287 iPhoneApp[1177:5f03] Start loading from request: { Range = "bytes=0-1"; </code></pre> <p>}</p> <p>So my GUESS is that as long as you can provide the correct range and return a mp4 file that can be played by the MPMoviePlayerController it should be possible!</p> <p>EDIT: Here is a interesting link: <a href="http://aptogo.co.uk/2010/07/protecting-resources/">Protecting resources in iPhone and iPad apps</a></p>
4,192,948
Remove www site-wide, force https on certain directories and http on the rest?
<p>Firstly, I would like to remove the www. from my domain name</p> <p><a href="http://www.example.com" rel="noreferrer">http://www.example.com</a> => <a href="http://example.com" rel="noreferrer">http://example.com</a></p> <p>I would also like for certain directories to be secure (https), while the rest remain http</p> <p><a href="http://example.com/login" rel="noreferrer">http://example.com/login</a> => <a href="https://example.com/login" rel="noreferrer">https://example.com/login</a></p> <p>Obviously it needs to work for all conditions, for example if someone types in:</p> <p><a href="http://www.example.com/login" rel="noreferrer">http://www.example.com/login</a> => <a href="https://example.com/login" rel="noreferrer">https://example.com/login</a></p> <p>Also when people navigate away from the login page it returns to http. Currently in the .htaccess is the following which is done automatically by the software I am using and I suppose needs to be there for it to work:</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* ./index.php </code></pre> <p>Any ideas on how I can achieve <strike>dream control</strike> all these things?</p> <p>Thanks in advance!</p> <p>===================</p> <p>@Gumbo Following your advice this is my complete .htaccess</p> <pre><code>RewriteEngine On # remove www from host RewriteCond %{HTTP_HOST} ^www\.(.+) RewriteCond %{HTTPS}s/%1 ^(on(s)|offs)/(.+) RewriteRule ^ http%2://%3%{REQUEST_URI} [L,R=301] # force HTTPS RewriteCond %{HTTPS} =off RewriteRule ^(login)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # force HTTP RewriteCond %{HTTPS} =on RewriteRule !^(login)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule .* ./index.php Options -Indexes </code></pre> <p>Navigating to <a href="http://example/login" rel="noreferrer">http://example/login</a> still goes to <a href="http://example/index.php" rel="noreferrer">http://example/index.php</a> when it should go to <a href="https://example/login" rel="noreferrer">https://example/login</a> Do I have the order wrong? </p>
4,195,388
4
2
null
2010-11-16 10:01:51.53 UTC
11
2018-02-13 07:10:44.043 UTC
2015-02-22 18:20:38.033 UTC
null
1,482,673
null
437,806
null
1
14
.htaccess|mod-rewrite|ssl|https|no-www
21,559
<p>Try these rules:</p> <pre><code># remove www from host RewriteCond %{HTTP_HOST} ^www\.(.+) RewriteCond %{HTTPS}s/%1 ^(on(s)|offs)/(.+) RewriteRule ^ http%2://%3%{REQUEST_URI} [L,R=301] # force HTTPS RewriteCond %{HTTPS} =off RewriteRule ^(login|foo|bar|…)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # force HTTP RewriteCond %{HTTPS} =on RewriteRule !^(login|foo|bar|…)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] </code></pre> <p>You also might want to add some additional conditions to only change the protocol on GET and HEAD requests but not on POST requests.</p>
4,330,072
Pass R variable to RODBC's sqlQuery?
<p>Is there any way to pass a variable defined within R to the sqlQuery function within the RODBC package?</p> <p>Specifically, I need to pass such a variable to either a scalar/table-valued function, a stored procedure, and/or perhaps the WHERE clause of a SELECT statement.</p> <p>For example, let:</p> <pre><code>x &lt;- 1 ## user-defined </code></pre> <p>Then,</p> <pre><code>example &lt;- sqlQuery(myDB,"SELECT * FROM dbo.my_table_fn (x)") </code></pre> <p>Or...</p> <pre><code>example2 &lt;- sqlQuery(myDB,"SELECT * FROM dbo.some_random_table AS foo WHERE foo.ID = x") </code></pre> <p>Or...</p> <pre><code>example3 &lt;- sqlQuery(myDB,"EXEC dbo.my_stored_proc (x)") </code></pre> <p>Obviously, none of these work, but I'm thinking that there's something that enables this sort of functionality.</p>
4,330,140
4
1
null
2010-12-01 23:08:16.373 UTC
15
2017-10-30 20:06:47.747 UTC
2016-11-11 07:39:52.05 UTC
null
680,068
null
489,426
null
1
23
sql|r|rodbc
33,798
<p>Build the string you intend to pass. So instead of</p> <pre><code>example &lt;- sqlQuery(myDB,"SELECT * FROM dbo.my_table_fn (x)") </code></pre> <p>do</p> <pre><code>example &lt;- sqlQuery(myDB, paste("SELECT * FROM dbo.my_table_fn (", x, ")", sep="")) </code></pre> <p>which will fill in the value of <code>x</code>.</p>
4,473,023
SQL Finding the size of query result
<p>So basically I'm doing a SQL select query, but I want to know how much data I am pulling back (how many kilobytes), any way?</p>
4,473,099
4
0
null
2010-12-17 17:14:34.21 UTC
7
2010-12-17 17:24:18.117 UTC
null
null
null
null
355,730
null
1
26
sql|sql-server|tsql
39,168
<p>Actually, "<a href="http://blog.sqlauthority.com/2009/10/01/sql-server-sql-server-management-studio-and-client-statistics/">Show Client Statistics</a>" within SSMS query Editor Window will return the resultset size, Bytes Received from Server, etc</p>
4,528,712
What is a IRepository and what is it used for?
<p>What is a IRepository? Why is it used, brief and simple examples won't hurt.</p>
4,535,781
4
1
null
2010-12-24 23:28:22.25 UTC
24
2019-07-22 17:54:10.363 UTC
null
null
null
null
68,438
null
1
46
c#|asp.net-mvc|vb.net
47,613
<p>MVC promotes separation of concerns, but that doesn't stop at the M V C level.</p> <p>Data Access is a concern in itself. It should be done in the M bit of MVC, ie the model. How you structure your model is up to you, but people usually follow tried and tested patterns (why reinvent the wheel?). The Repository Pattern is the current standard. Don't expect a simple formula, however, because the variations are as many as there are developers, almost.</p> <p>IRepository is just an interface that you create (it is not part of MVC or ASP.NET or .NET). It allows you to "decouple" your repositories from real implementations. Decoupling is good because it means your code...:</p> <ol> <li>Your code is much more reusable. This is just plain good.</li> <li>Your code can use Inversion of Control (or Dependency Injection). This is good to keep your concerns well separated. It is especially good because this allows Unit Testing...</li> <li>Your code can be Unit Tested. This is especially good in large projects with complex algorithms. It is good everywhere because it increases your understanding of the technologies you are working with and the domains you are trying to model in software.</li> <li>Your code becomes built around best practices, following a common pattern. This is good because it makes maintenance much easier.</li> </ol> <p>So, having sold you decoupling, the answer to your question is that IRepository is an interface that you create and that you make your Repositories inherit from. It gives you a reliable class hierarchy to work with.</p> <p>I generally use a generic IRepository:</p> <p>IRepository</p> <p>Where TEntity is, well, an entity. The code I use is:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Wingspan.Web.Mvc { public interface IRepository&lt;TEntity&gt; where TEntity : class { List&lt;TEntity&gt; FetchAll(); IQueryable&lt;TEntity&gt; Query {get;} void Add(TEntity entity); void Delete(TEntity entity); void Save(); } } </code></pre> <p>A concrete implementation of this interface would be:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Linq; using Wingspan.Web.Mvc; namespace ES.eLearning.Domain { public class SqlRepository&lt;T&gt; : IRepository&lt;T&gt; where T : class { DataContext db; public SqlRepository(DataContext db) { this.db = db; } #region IRepository&lt;T&gt; Members public IQueryable&lt;T&gt; Query { get { return db.GetTable&lt;T&gt;(); } } public List&lt;T&gt; FetchAll() { return Query.ToList(); } public void Add(T entity) { db.GetTable&lt;T&gt;().InsertOnSubmit(entity); } public void Delete(T entity) { db.GetTable&lt;T&gt;().DeleteOnSubmit(entity); } public void Save() { db.SubmitChanges(); } #endregion } } </code></pre> <p>This allows me to write:</p> <pre><code>SqlRepository&lt;UserCourse&gt; UserCoursesRepository = new SqlRepository&lt;UserCourse&gt;(db); </code></pre> <p>Where db is a DataContext instance injected into, say, a Service.</p> <p>With UserCoursesRepository I can now write methods in my Service class like:</p> <pre><code>public void DeleteUserCourse(int courseId) { var uc = (UserCoursesRepository.Query.Where(x =&gt; x.IdUser == UserId &amp;&amp; x.IdCourse == courseId)).Single(); UserCoursesRepository.Delete(uc); UserCoursesRepository.Save(); } </code></pre> <p>And now in my controllers, I can just write:</p> <pre><code>MyService.DeleteUserCourse(5); MyService.Save(); </code></pre> <p>With this pattern the development of your app becomes more of an assembly line that leads up to a VERY simple controller. Every piece of the assembly line can be tested independently of everything else, so bugs are nipped in the bud.</p> <p>If this is a long, unwieldy answer it is because the real answer is:</p> <p>Buy <a href="https://rads.stackoverflow.com/amzn/click/com/1430228865" rel="noreferrer" rel="nofollow noreferrer">Steven Sanderson's book Pro ASP.NET MVC 2 Framework</a> and learn to think in MVC.</p>
4,154,409
How to spec a private method
<p>I got a model with a private method I'd like to spec with RSpec,<br> how do you usually do ? Do you only test the method calling the private one ?<br> or also spec the private one ? if so, how do you do ?</p>
4,154,550
4
0
null
2010-11-11 12:32:11.24 UTC
22
2022-04-26 11:19:45.73 UTC
2010-11-11 12:41:42.11 UTC
null
143,148
null
143,148
null
1
58
ruby-on-rails|rspec
22,917
<p>I always take this approach: <em>I want to test the public API my class exposes.</em></p> <p>If you have private methods, you only call them from the public methods you expose to other classes. Hence, if you test that those public methods work as expected under all conditions, you have also proven that the private methods they use work as well. </p> <p>I'll admit that I've come across some especially complex private methods. In that extreme case you want to test them, you can do this:</p> <pre><code>@obj.send(:private_method) </code></pre>
4,304,917
How to print last two columns using awk
<p>All I want is the last two columns printed.</p>
4,304,949
6
4
null
2010-11-29 14:59:22.61 UTC
40
2020-08-06 23:21:11.31 UTC
2018-03-24 16:55:54.893 UTC
null
6,862,601
null
149,045
null
1
118
awk
217,851
<p>You can make use of variable <code>NF</code> which is set to the total number of fields in the input record:</p> <pre><code>awk '{print $(NF-1),"\t",$NF}' file </code></pre> <p>this assumes that you have at least 2 fields.</p>
4,331,336
How to step back in Eclipse debugger?
<p>Is it possible to do reverse execution in Eclipse debugger? The current project I'm working on requires a minimum of 5 seconds to read and initialize data from a file before anything can be done. If I overstep in the debugger, I have to terminate the program and restart, and this takes a fair bit of time.</p>
4,331,497
6
0
null
2010-12-02 03:18:49.957 UTC
57
2020-04-30 14:38:12.837 UTC
2017-03-09 07:07:42.627 UTC
null
895,245
null
214,892
null
1
132
eclipse|debugging
104,434
<p>You can use Eclipse's <a href="https://help.eclipse.org/2019-12/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fviews%2Fdebug%2Fref-droptoframe.htm" rel="nofollow noreferrer">drop to frame</a> command to re-enter the current method from the top. But it won't unroll any state changes that have happened, so it may not work depending on the sort of method you're in.</p> <p>Another really cool tool that actually does let you step back and forward in time is the <a href="http://omniscientdebugger.github.io/" rel="nofollow noreferrer">Omniscient Debugger</a>. It works by instrumenting classes as they're loaded in the classloader, so it can record everything that your code does. It can do very cool things, like answer "when, where, and why was this field assigned its current value?". The UI is rather clunky, and it can have a hard time handling large code bases, but for some cases it can really save a lot of time.</p> <p><strong>Update</strong>: <a href="http://chrononsystems.com/" rel="nofollow noreferrer">Chronon</a> provides a commercial product that it describes as a "DVR for Java", which appears to do a lot of the same things as the ODB.</p>
4,806,637
Continue processing after closing connection
<p>Is there a way in PHP to close the connection (essentially tell a browser than there's no more data to come) but continue processing. The specific circumstance I'm thinking of is that I would want to serve up cached data, then if the cache had expired, I would still serve the cached data for a fast response, close the connection, but continue processing to regenerate and cache new data. Essentially the only purpose is to make a site appear more responsive as there wouldn't be the occasional delay while a user waits for content to be regenerated.</p> <p>UPDATE:</p> <p>PLuS has the closest answer to what I was looking for. To clarify for a couple of people I'm looking for something that enables the following steps:</p> <ol> <li>User requests page</li> <li>Connection opens to server</li> <li>PHP checks if cache has expired, if still fresh, serve cache and close connection (END HERE). If expired, continue to 4.</li> <li>Serve expired cache</li> <li>Close connection so browser knows it's not waiting for more data.</li> <li>PHP regenerates fresh data and caches it.</li> <li>PHP shuts down.</li> </ol> <p>UPDATE:</p> <p>This is important, it must be a purely PHP solution. Installing other software is not an option.</p>
4,856,241
8
2
null
2011-01-26 15:54:41.09 UTC
12
2018-04-20 04:32:55.06 UTC
2011-01-26 16:42:54.067 UTC
null
432,193
null
432,193
null
1
35
php
28,469
<p>I finally found a solution (thanks to Google, I just had to keep trying different combinations of search terms). Thanks to the comment from arr1 on <a href="http://php.net/manual/en/features.connection-handling.php" rel="noreferrer">this page</a> (it's about two thirds of the way down the page).</p> <pre><code>&lt;?php ob_end_clean(); header("Connection: close"); ignore_user_abort(true); ob_start(); echo 'Text the user will see'; $size = ob_get_length(); header("Content-Length: $size"); ob_end_flush(); // All output buffers must be flushed here flush(); // Force output to client // Do processing here sleep(30); echo('Text user will never see'); </code></pre> <p>I have yet to actually test this but, in short, you send two headers: one that tells the browser exactly how much data to expect then one to tell the browser to close the connection (which it will only do after receiving the expected amount of content). I haven't tested this yet.</p>
4,111,475
How to do a logical OR operation for integer comparison in shell scripting?
<p>I am trying to do a simple condition check, but it doesn't seem to work.</p> <p>If <code>$#</code> is equal to <code>0</code> or is greater than <code>1</code> then say hello.</p> <p>I have tried the following syntax with no success:</p> <pre><code>if [ "$#" == 0 -o "$#" &gt; 1 ] ; then echo "hello" fi if [ "$#" == 0 ] || [ "$#" &gt; 1 ] ; then echo "hello" fi </code></pre>
4,111,510
8
5
null
2010-11-06 01:48:33.717 UTC
72
2021-02-23 13:04:53.673 UTC
2021-02-23 13:04:53.673 UTC
null
1,718,491
null
170,365
null
1
590
bash|unix|if-statement|sh
1,023,564
<p>This should work:</p> <pre><code>#!/bin/bash if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then echo "hello" fi </code></pre> <p>I'm not sure if this is different in other shells but if you wish to use &lt;, >, you need to put them inside double parenthesis like so: </p> <pre><code>if (("$#" &gt; 1)) ... </code></pre>
4,279,319
Is there a plugin that allows me to automatically unminify the Javascript included on a site?
<p>Is there a plugin, add-on, Greasemonkey script or something similar (at worst, an easy to use proxy?) that automatically <strong>unminifies</strong> the Javascript files included on a site?</p> <p>I know about e.g. <a href="http://jsbeautifier.org/" rel="noreferrer">jsbeautifier.org</a> but doing this externally doesn't allow me to set breakpoints in the unminified code, for example.</p> <p>Typical use cases for me:</p> <ul> <li>Analysing and learning from complex web frontends.</li> <li>Debugging Greasemonkey scripts which interact with the existing code.</li> </ul> <p>I'm primarily interested in a solution that works with Firebug, but if there's something for the dev tools of Chrome or Opera, I'd like to hear about it as well.</p>
7,466,333
9
2
null
2010-11-25 16:55:01.56 UTC
10
2015-11-17 10:02:45.097 UTC
null
null
null
null
6,278
null
1
58
javascript|firebug|minify
12,418
<p>In chrome 13+, there is 'pretty print'. </p> <ol> <li>Right click 'inspect element'</li> <li>Go to Script tab</li> <li>Click the curly braces in the bottom right.</li> </ol> <p><img src="https://i.stack.imgur.com/qBqcD.png" alt="Screenshot"></p>
4,217,820
Convert HTML to NSAttributedString in iOS
<p>I am using a instance of <code>UIWebView</code> to process some text and color it correctly, it gives the result as HTML but rather than displaying it in the <code>UIWebView</code> I want to display it using <code>Core Text</code> with a <code>NSAttributedString</code>. </p> <p>I am able to create and draw the <code>NSAttributedString</code> but I am unsure how I can convert and map the HTML into the attributed string.</p> <p>I understand that under Mac OS X <code>NSAttributedString</code> has a <code>initWithHTML:</code> method but this was a Mac only addition and is not available for iOS.</p> <p>I also know that there is a similar question to this but it had no answers, I though I would try again and see whether anyone has created a way to do this and if so, if they could share it.</p>
18,886,718
17
1
null
2010-11-18 17:38:34.77 UTC
86
2022-02-18 09:07:41.66 UTC
null
null
null
null
92,714
null
1
163
iphone|objective-c|cocoa-touch|core-text|nsattributedstring
122,485
<p>In iOS 7, UIKit added an <a href="https://developer.apple.com/documentation/foundation/nsattributedstring/1524613-initwithdata" rel="noreferrer"><code>initWithData:options:documentAttributes:error:</code></a> method which can initialize an <code>NSAttributedString</code> using HTML, eg:</p> <pre><code>[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} documentAttributes:nil error:nil]; </code></pre> <p>In Swift:</p> <pre><code>let htmlData = NSString(string: details).data(using: String.Encoding.unicode.rawValue) let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html] let attributedString = try? NSMutableAttributedString(data: htmlData ?? Data(), options: options, documentAttributes: nil) </code></pre>
14,580,595
IEqualityComparer and Contains method
<p>I have this simple class with those 2 enum fields, I'm trying to find one item of this object in a collection (<code>List&lt;T&gt;</code>) but the Contains methods doesn't works correctly</p> <pre><code>public class Calculator : IEqualityComparer&lt;Calculator&gt; { public DashboardsComputationMode ComputationMode { get; set; } public Modes Mode { get; set; } public Calculator(DashboardsComputationMode dashboardsComputationMode, Modes mode) { ComputationMode = dashboardsComputationMode; Mode = mode; } public bool Equals(Calculator x, Calculator y) { return (x.ComputationMode.Equals(y.ComputationMode) &amp;&amp; x.Mode.Equals(y.Mode)); } public int GetHashCode(Calculator obj) { return obj.ComputationMode.GetHashCode() ^ obj.Mode.GetHashCode(); } } public enum DashboardsComputationMode { Weighted = 0, Aggregated = 1, PR = 2, CurrentValue = 3, EquivalentHours = 4, AggregatedCorrected = 5, PRCorrected = 6 } public enum Modes { InstantaneousMode = 0, DailyMode = 1, MonthlyMode = 2, YearlyMode = 5, Undefined = 4, } </code></pre> <p>Why could be that this test doesn't works </p> <pre><code>[TestMethod] public void TestMethod1() { var list = new List&lt;Calculator&gt;() { new Calculator(DashboardsComputationMode.PR, Modes.DailyMode), new Calculator(DashboardsComputationMode.CurrentValue, Modes.YearlyMode), new Calculator(DashboardsComputationMode.PRCorrected, Modes.MonthlyMode) }; var item = new Calculator(DashboardsComputationMode.CurrentValue, Modes.YearlyMode); Assert.IsTrue(list[1].Equals(item)); Assert.IsTrue(list.Contains(item)); } </code></pre> <p>The first assert works fine</p> <pre><code>Assert.IsTrue(list[1].Equals(item)) </code></pre> <p>but the second doesn't</p> <pre><code>Assert.IsTrue(list.Contains(item)); </code></pre>
14,581,073
2
1
null
2013-01-29 10:21:56.35 UTC
4
2013-01-29 10:52:48.553 UTC
2013-01-29 10:52:48.553 UTC
null
54,981
null
1,682,588
null
1
18
c#|.net|ienumerable
43,504
<p><a href="http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx"><code>List&lt;T&gt;.Contains</code></a> determines equality by using the default equality comparer (the one returned by the <a href="http://msdn.microsoft.com/en-us/library/ms224763.aspx"><code>EqualityComparer&lt;T&gt;.Default</code></a>).</p> <p>Here's the MSDN explanation on how <a href="http://msdn.microsoft.com/en-us/library/ms224763.aspx"><code>EqualityComparer&lt;T&gt;.Default</code></a> works:</p> <blockquote> <p>The Default property checks whether type T implements the <a href="http://msdn.microsoft.com/en-us/library/ms131187.aspx">System.IEquatable</a> interface and, if so, returns an <a href="http://msdn.microsoft.com/en-us/library/ms132123.aspx">EqualityComparer</a> that uses that implementation. Otherwise, it returns an <a href="http://msdn.microsoft.com/en-us/library/ms132123.aspx">EqualityComparer</a> that uses the overrides of <a href="http://msdn.microsoft.com/en-us/library/system.object.equals.aspx">Object.Equals</a> and <a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx">Object.GetHashCode</a> provided by T.</p> </blockquote> <p>In other words, your <code>Calculator</code> class should either implement the <a href="http://msdn.microsoft.com/en-us/library/ms131187.aspx">System.IEquatable</a> (<strong>not</strong> the <code>System.IEqualityComparer</code>!) interface or override the <a href="http://msdn.microsoft.com/en-us/library/system.object.equals.aspx">Object.Equals</a> and <a href="http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx">Object.GetHashCode</a> methods.</p>