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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,839,769 | The max product of consecutive elements in an array | <p>I was asked this algorithm question during my onsite interview. Since I was not asked to sign NDA, I post it here for an answer. </p>
<p>Given an array of <strong>REAL</strong> numbers that does not contain 0, find the consecutive elements that yield max product. The algorithm should run in linear time </p>
<p>I have considered the following approach:
Use two arrays. First one is to use DP idea to record the current max <strong>absolute value</strong> product, the second array to record the number of negative elements met so far. The final result should be the largest max absolute value and the number of negative numbers be even.</p>
<p>I thought my method will work, but was interrupted during coding saying it will not work.
Please let me know what is missing in the above approach.</p> | 18,840,236 | 9 | 12 | null | 2013-09-17 01:10:24.89 UTC | 21 | 2021-11-25 15:34:45.127 UTC | 2013-10-14 19:56:17.893 UTC | null | 805,923 | null | 1,955,773 | null | 1 | 22 | algorithm | 11,495 | <p>The algorithm is indeed O(n). When iterating the array, use a variable to store the max value found so far, a variable to store the max value of subarray that ends at a[i], and another variable to store minimum value that ends at a[i] to treat negative values.</p>
<pre><code>float find_maximum(float arr[], int n) {
if (n <= 0) return NAN;
float max_at = arr[0]; // Maximum value that ends at arr[i]
float min_at = arr[0]; // Minimum value that ends at arr[i]
float max_value = max_at;
for (int i = 1; i < n; i++) {
float prev_max_at = max_at, prev_min_at = min_at;
max_at = max(arr[i], arr[i] * prev_min_at, arr[i] * prev_max_at);
min_at = min(arr[i], arr[i] * prev_min_at, arr[i] * prev_max_at);
max_value = max(max_value, max_at);
}
return max_value;
}
</code></pre> |
8,838,777 | ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'db' | <p>I want to begin writing queries in MySQL.</p>
<p><code>show grants</code> shows:</p>
<pre><code>+--------------------------------------+
| Grants for @localhost |
+--------------------------------------+
| GRANT USAGE ON *.* TO ''@'localhost' |
+--------------------------------------+
</code></pre>
<p>I do not have any user-id but when I want to make a user I don't have privilleges, also I don't know how to make privileges when even I don't have one user!</p>
<pre><code>mysql> CREATE USER 'parsa'@'localhost' IDENTIFIED BY 'parsa';
ERROR 1227 (42000): Access denied; you need (at least one of) the CREATE USER pr
ivilege(s) for this operation
</code></pre>
<p>I tried to sign in as root:</p>
<pre><code>mysql> mysql -u root -p;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'mysql
-u root -p' at line 1
mysql> mysql -u root -p root;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'mysql
-u root -p root' at line 1
</code></pre> | 8,839,017 | 12 | 12 | null | 2012-01-12 16:44:00.207 UTC | 68 | 2022-04-06 15:08:33.437 UTC | 2012-10-20 21:43:14.24 UTC | null | 128,421 | null | 974,380 | null | 1 | 192 | mysql | 855,056 | <p>No, you should run <code>mysql -u root -p</code> in bash, not at the MySQL command-line.
If you are in mysql, you can exit by typing <strong>exit</strong>.</p> |
20,625,582 | How to deal with SettingWithCopyWarning in Pandas | <h2>Background</h2>
<p>I just upgraded my Pandas from 0.11 to 0.13.0rc1. Now, the application is popping out many new warnings. One of them like this:</p>
<pre class="lang-none prettyprint-override"><code>E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE
</code></pre>
<p>I want to know what exactly it means? Do I need to change something?</p>
<p>How should I suspend the warning if I insist to use <code>quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE</code>?</p>
<h2>The function that gives errors</h2>
<pre><code>def _decode_stock_quote(list_of_150_stk_str):
"""decode the webpage and return dataframe"""
from cStringIO import StringIO
str_of_all = "".join(list_of_150_stk_str)
quote_df = pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64}
quote_df.rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True)
quote_df = quote_df.ix[:,[0,3,2,1,4,5,8,9,30,31]]
quote_df['TClose'] = quote_df['TPrice']
quote_df['RT'] = 100 * (quote_df['TPrice']/quote_df['TPCLOSE'] - 1)
quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE
quote_df['TAmt'] = quote_df['TAmt']/TAMT_SCALE
quote_df['STK_ID'] = quote_df['STK'].str.slice(13,19)
quote_df['STK_Name'] = quote_df['STK'].str.slice(21,30)#.decode('gb2312')
quote_df['TDate'] = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10])
return quote_df
</code></pre>
<h2>More error messages</h2>
<pre class="lang-none prettyprint-override"><code>E:\FinReporter\FM_EXT.py:449: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
quote_df['TVol'] = quote_df['TVol']/TVOL_SCALE
E:\FinReporter\FM_EXT.py:450: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
quote_df['TAmt'] = quote_df['TAmt']/TAMT_SCALE
E:\FinReporter\FM_EXT.py:453: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
quote_df['TDate'] = quote_df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10])
</code></pre> | 20,627,316 | 20 | 5 | null | 2013-12-17 03:48:02.57 UTC | 436 | 2022-09-21 16:06:52.823 UTC | 2022-09-21 15:27:21.043 UTC | null | 63,550 | null | 1,072,888 | null | 1 | 1,220 | python|pandas|dataframe|chained-assignment | 1,676,151 | <p>The <code>SettingWithCopyWarning</code> was created to flag potentially confusing "chained" assignments, such as the following, which does not always work as expected, particularly when the first selection returns a <em>copy</em>. [see <a href="https://github.com/pydata/pandas/pull/5390" rel="noreferrer">GH5390</a> and <a href="https://github.com/pydata/pandas/issues/5597" rel="noreferrer">GH5597</a> for background discussion.]</p>
<pre><code>df[df['A'] > 2]['B'] = new_val # new_val not set in df
</code></pre>
<p>The warning offers a suggestion to rewrite as follows:</p>
<pre><code>df.loc[df['A'] > 2, 'B'] = new_val
</code></pre>
<p>However, this doesn't fit your usage, which is equivalent to:</p>
<pre><code>df = df[df['A'] > 2]
df['B'] = new_val
</code></pre>
<p>While it's clear that you don't care about writes making it back to the original frame (since you are overwriting the reference to it), unfortunately this pattern cannot be differentiated from the first chained assignment example. Hence the (false positive) warning. The potential for false positives is addressed in the <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy" rel="noreferrer">docs on indexing</a>, if you'd like to read further. You can safely disable this new warning with the following assignment.</p>
<pre><code>import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
</code></pre>
<hr />
<h2>Other Resources</h2>
<ul>
<li><a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html" rel="noreferrer">pandas User Guide: Indexing and selecting data</a></li>
<li><a href="https://jakevdp.github.io/PythonDataScienceHandbook/03.02-data-indexing-and-selection.html" rel="noreferrer">Python Data Science Handbook: Data Indexing and Selection</a></li>
<li><a href="https://realpython.com/pandas-settingwithcopywarning/" rel="noreferrer">Real Python: SettingWithCopyWarning in Pandas: Views vs Copies</a></li>
<li><a href="https://www.dataquest.io/blog/settingwithcopywarning/" rel="noreferrer">Dataquest: SettingwithCopyWarning: How to Fix This Warning in Pandas</a></li>
<li><a href="https://towardsdatascience.com/explaining-the-settingwithcopywarning-in-pandas-ebc19d799d25" rel="noreferrer">Towards Data Science: Explaining the SettingWithCopyWarning in pandas</a></li>
</ul> |
20,828,907 | The new syntax "= default" in C++11 | <p>I don't understand why would I ever do this:</p>
<pre><code>struct S {
int a;
S(int aa) : a(aa) {}
S() = default;
};
</code></pre>
<p>Why not just say:</p>
<pre><code>S() {} // instead of S() = default;
</code></pre>
<p>why bring in a new syntax for that?</p> | 20,828,970 | 6 | 6 | null | 2013-12-29 19:01:59.383 UTC | 74 | 2022-09-17 21:45:30.223 UTC | 2019-07-14 00:36:13.043 UTC | null | 9,716,597 | null | 3,111,311 | null | 1 | 188 | c++|c++11 | 98,721 | <p>A defaulted default constructor is specifically defined as being the same as a user-defined default constructor with no initialization list and an empty compound statement.</p>
<blockquote>
<p><em>§12.1/6 [class.ctor]</em> A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used to create an object of its class type or when it is explicitly defaulted after its first declaration. The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no ctor-initializer (12.6.2) and an empty compound-statement. [...]</p>
</blockquote>
<p>However, while both constructors will behave the same, providing an empty implementation does affect some properties of the class. Giving a user-defined constructor, even though it does nothing, makes the type not an <em>aggregate</em> and also not <em>trivial</em>. If you want your class to be an aggregate or a trivial type (or by transitivity, a POD type), then you need to use <code>= default</code>.</p>
<blockquote>
<p><em>§8.5.1/1 [dcl.init.aggr]</em> An aggregate is an array or a class with no user-provided constructors, [and...]</p>
</blockquote>
<blockquote>
<p><em>§12.1/5 [class.ctor]</em> A default constructor is trivial if it is not user-provided and [...]</p>
<p><em>§9/6 [class]</em> A trivial class is a class that has a trivial default constructor and [...]</p>
</blockquote>
<p>To demonstrate:</p>
<pre><code>#include <type_traits>
struct X {
X() = default;
};
struct Y {
Y() { };
};
int main() {
static_assert(std::is_trivial<X>::value, "X should be trivial");
static_assert(std::is_pod<X>::value, "X should be POD");
static_assert(!std::is_trivial<Y>::value, "Y should not be trivial");
static_assert(!std::is_pod<Y>::value, "Y should not be POD");
}
</code></pre>
<p>Additionally, explicitly defaulting a constructor will make it <code>constexpr</code> if the implicit constructor would have been and will also give it the same exception specification that the implicit constructor would have had. In the case you've given, the implicit constructor would not have been <code>constexpr</code> (because it would leave a data member uninitialized) and it would also have an empty exception specification, so there is no difference. But yes, in the general case you could manually specify <code>constexpr</code> and the exception specification to match the implicit constructor.</p>
<p>Using <code>= default</code> does bring some uniformity, because it can also be used with copy/move constructors and destructors. An empty copy constructor, for example, will not do the same as a defaulted copy constructor (which will perform member-wise copy of its members). Using the <code>= default</code> (or <code>= delete</code>) syntax uniformly for each of these special member functions makes your code easier to read by explicitly stating your intent.</p> |
11,193,983 | Android save List<String> | <p>Is there anyway I can save a List variable to the Androids phone internal or external memory? I know I can save primitive data, yet not sure about this one.</p>
<p>Thanks in advance.</p> | 11,194,200 | 3 | 3 | null | 2012-06-25 17:10:56.34 UTC | 8 | 2022-05-22 17:12:14.727 UTC | null | null | null | null | 1,297,445 | null | 1 | 15 | android|list|save | 78,067 | <p>Yes exactly you can only save primitives so you could something like this:</p>
<pre><code>List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
StringBuilder csvList = new StringBuilder();
for(String s : list){
csvList.append(s);
csvList.append(",");
}
sharedPreferencesEditor.put("myList", csvList.toString());
</code></pre>
<p>Then to create your <code>list</code> again you would:</p>
<pre><code>String csvList = sharedPreferences.getString("myList");
String[] items = csvList.split(",");
List<String> list = new ArrayList<String>();
for(int i=0; i < items.length; i++){
list.add(items[i]);
}
</code></pre>
<p>You could encapsulate this "serializing" into your own class wrapping a list to keep it nice and tidy. Also you could look at converting your <code>list</code> to <code>JSON</code>.</p> |
10,943,033 | Why are strings in C++ usually terminated with '\0'? | <p>In many code samples, people usually use <code>'\0'</code> after creating a new char array like this: </p>
<pre><code>string s = "JustAString";
char* array = new char[s.size() + 1];
strncpy(array, s.c_str(), s.size());
array[s.size()] = '\0';
</code></pre>
<p>Why should we use <code>'\0'</code> here? </p> | 10,943,040 | 5 | 7 | null | 2012-06-08 04:22:05.94 UTC | 11 | 2022-04-12 13:59:25.367 UTC | 2022-04-12 13:59:25.367 UTC | null | 995,714 | null | 972,671 | null | 1 | 20 | c++|c|string|null-terminated | 62,309 | <p>The title of your question references C strings. C++ <code>std::string</code> objects are handled differently than <em>standard C</em> strings. <code>\0</code> is important when using C strings, and when I use the term <em>string</em> in this answer, I'm referring to <em>standard C strings</em>.</p>
<p><code>\0</code> acts as a string terminator in C. It is known as the <em>null character</em>, or <em>NUL</em>, and standard C strings are <em>null-terminated</em>. This terminator signals code that processes strings - standard libraries but also your own code - where the end of a string is. A good example is <code>strlen</code> which returns the length of a string: <code>strlen</code> works using the assumption that it operates on strings that are terminated using <code>\0</code>.</p>
<p>When you declare a constant string with:</p>
<pre><code>const char *str = "JustAString";
</code></pre>
<p>then the <code>\0</code> is appended automatically for you. In other cases, where you'll be managing a non-constant string as with your array example, you'll sometimes need to deal with it yourself. The <a href="http://en.cppreference.com/w/c/string/byte/strncpy" rel="nofollow noreferrer">docs for strncpy</a>, which is used in your example, are a good illustration: <code>strncpy</code> copies over the null terminator character <strong>except</strong> in the case where the specified length is reached before the entire string is copied. Hence you'll often see <code>strncpy</code> combined with the <em>possibly redundant</em> assignment of a null terminator. <code>strlcpy</code> and <code>strcpy_s</code> were designed to address the potential problems that arise from neglecting to handle this case.</p>
<p>In your particular example, <code>array[s.size()] = '\0';</code> is one such redundancy: since <code>array</code> is of size <code>s.size() + 1</code>, and <code>strncpy</code> is copying <code>s.size()</code> characters, the function will append the <code>\0</code>.</p>
<p>The documentation for standard C string utilities will indicate when you'll need to be careful to include such a null terminator. But read the documentation carefully: as with <code>strncpy</code> the details are easily overlooked, leading to potential buffer overflows.</p> |
11,006,634 | Any VI like editor under windows? | <p>I am wondering whether there is a vi like editor under windows command line?</p> | 11,006,648 | 2 | 4 | null | 2012-06-13 00:18:52.24 UTC | 3 | 2015-07-03 02:05:59.467 UTC | 2014-01-16 12:48:20.75 UTC | user146043 | null | null | 1,136,700 | null | 1 | 25 | windows|vim|windows-7|vi | 75,471 | <p>Just download vim for windows from <a href="http://www.vim.org" rel="noreferrer">http://www.vim.org</a> -- on the installation it will ask if you want to create shortcuts for calling it from the command line. Then you can just <code>vim <filename></code>.</p> |
11,223,868 | How to create ByteArrayInputStream from a file in Java? | <p>I have a file that can be any thing like ZIP, RAR, txt, CSV, doc etc. I would like to create a <em>ByteArrayInputStream</em> from it.<br>
I'm using it to upload a file to FTP through <em>FTPClient</em> from Apache Commons Net.</p>
<p><strong>Does anybody know how to do it?</strong></p>
<p>For example:</p>
<pre><code>String data = "hdfhdfhdfhd";
ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
</code></pre>
<p>My code:</p>
<pre><code>public static ByteArrayInputStream retrieveByteArrayInputStream(File file) {
ByteArrayInputStream in;
return in;
}
</code></pre> | 11,223,955 | 5 | 7 | null | 2012-06-27 10:12:56.817 UTC | 8 | 2019-09-01 12:01:50.147 UTC | 2017-09-05 09:18:00.96 UTC | null | 6,256,127 | null | 1,092,450 | null | 1 | 31 | java|arrays|bytebuffer|bytearrayinputstream | 109,543 | <p>Use the <a href="http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html#readFileToByteArray%28java.io.File%29" rel="noreferrer"><code>FileUtils#readFileToByteArray(File)</code></a> from <a href="http://commons.apache.org/io" rel="noreferrer">Apache Commons IO</a>, and then create the <code>ByteArrayInputStream</code> using the <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/io/ByteArrayInputStream.html#ByteArrayInputStream%28byte[]%29" rel="noreferrer"><code>ByteArrayInputStream(byte[])</code></a> constructor.</p>
<pre><code>public static ByteArrayInputStream retrieveByteArrayInputStream(File file) {
return new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
}
</code></pre> |
11,074,671 | adb pull multiple files | <p>What is the best way to pull multiple files using</p>
<pre><code>adb pull
</code></pre>
<p>I have on my <code>/sdcard/</code> 25 files with following name:</p>
<pre><code>gps1.trace
gps2.trace
...
gps25.trace
</code></pre>
<p>Wildcard does not work:</p>
<pre><code>adb pull /sdcard/gps*.trace .
</code></pre> | 11,250,068 | 13 | 3 | null | 2012-06-17 20:47:32.327 UTC | 33 | 2021-09-07 14:44:00.023 UTC | 2018-12-31 07:03:37.61 UTC | null | 223,386 | null | 223,386 | null | 1 | 95 | android|adb | 102,954 | <p>You can use <code>xargs</code> and the result of the <code>adb shell ls</code> command which accepts wildcards. This allows you to copy multiple files. Annoyingly the output of the <code>adb shell ls</code> command includes line-feed control characters that you can remove using <code>tr -d '\r'</code>.</p>
<p>Examples:</p>
<pre><code># Using a relative path
adb shell 'ls sdcard/gps*.trace' | tr -d '\r' | xargs -n1 adb pull
# Using an absolute path
adb shell 'ls /sdcard/*.txt' | tr -d '\r' | sed -e 's/^\///' | xargs -n1 adb pull
</code></pre> |
13,142,419 | General way of solving Error: Stack around the variable 'x' was corrupted | <p>I have a program which prompts me the error in VS2010, in debug : </p>
<pre><code>Error: Stack around the variable 'x' was corrupted
</code></pre>
<p>This gives me the function where a stack overflow likely occurs, but I can't visually see where the problem is.</p>
<p>Is there a general way to debug this error with VS2010? Would it be possible to indentify which write operation is overwritting the incorrect stack memory?
thanks</p> | 13,143,133 | 9 | 6 | null | 2012-10-30 15:32:18.033 UTC | 7 | 2021-02-01 09:36:03.293 UTC | null | null | null | null | 875,295 | null | 1 | 26 | c++|visual-studio-2010|debugging | 70,533 | <blockquote>
<p>Is there a general way to debug this error with VS2010?</p>
</blockquote>
<p>No, there isn't. What you have done is to somehow invoke undefined behavior. The reason these behaviors are undefined is that the general case is very hard to detect/diagnose. Sometimes it is provably impossible to do so.</p>
<p>There are however, a somewhat smallish number of things that typically cause your problem:</p>
<ul>
<li>Improper handling of memory:
<ul>
<li>Deleting something twice,</li>
<li>Using the wrong type of deletion (<code>free</code> for something allocated with <code>new</code>, etc.),</li>
<li>Accessing something after it's memory has been deleted.</li>
</ul></li>
<li>Returning a pointer or reference to a local.</li>
<li>Reading or writing past the end of an array.</li>
</ul> |
13,170,493 | Build once and deploy to multiple environments with msdeploy & Visual Studio 2012 | <p>Working on centralizing configurations, app settings and connection strings, for multiple solutions, while also switching over to use msdeploy from command line to deploy web apps. Ideally I would want to build the packages once, and get up-to-date configurations as the packages are deployed to each environment. I need some advice on the best approach to take. </p>
<ol>
<li>Use Parameters.xml and SetParameters.xml file to dynamically swap out settings and connection strings. See <a href="http://vishaljoshi.blogspot.com/2010/07/web-deploy-parameterization-in-action.html" rel="noreferrer">http://vishaljoshi.blogspot.com/2010/07/web-deploy-parameterization-in-action.html</a></li>
<li>Use machine.config or server level web.config files to store common app settings and connection strings.</li>
<li>Use packageweb NuGet package from <a href="https://github.com/sayedihashimi/package-web" rel="noreferrer">https://github.com/sayedihashimi/package-web</a> which enables using web.config transforms with msdeploy.</li>
<li>Use file or configSource attributes along with SetParameters to point to different config files, but must be relative from web root.</li>
<li>Use publish profiles. See
<a href="https://stackoverflow.com/questions/11683243/deploying-an-existing-package-using-publish-profiles">Deploying an existing package using publish profiles</a></li>
</ol>
<p>Thanks</p> | 13,258,269 | 4 | 0 | null | 2012-11-01 03:21:01.84 UTC | 18 | 2014-10-15 23:16:01.447 UTC | 2017-05-23 12:31:59.927 UTC | null | -1 | null | 753,279 | null | 1 | 39 | msbuild|msdeploy | 22,243 | <p>We use option #1 and it works out well enough. We deploy to about 30-40 sites and applications using this approach. </p>
<p>I think option #2 will cause headaches for either you or the developers. You'll either have to make sure the sections with settings are removed from the config on deployment, or lock them on the server so that the local config can't add them.</p>
<p>For option #3 you will have to do multiple builds to get the transformed config files. It also isn't very feasible if you have a large number of sites to deploy.</p>
<p>Option #4 could work, but you might run into limitations here. It's either the whole section is in a separate file or its all in the main file so there's no in-between.</p>
<p>Option #5 looks interesting, but I haven't used it so I can't say much about it.</p> |
16,582,107 | Android studio doesn't start | <p>I just download Android Studio for Windows 7, the wizard went ok up to the end but now when I click on the shortcut or on the .exe to start the program nothing happens, no error, no new window, it's seems like it is doing nothing. Do you have any suggestion?</p> | 16,582,314 | 16 | 4 | null | 2013-05-16 08:07:15.333 UTC | 2 | 2020-12-16 01:45:04.593 UTC | null | null | null | null | 1,012,909 | null | 1 | 29 | windows-7|android-studio | 35,025 | <p>It's a bug of Android Studio 0.1v</p>
<p>You should add <code>JAVA_HOME</code> to the system environment variables.</p>
<p><a href="http://tools.android.com/knownissues#as0.1" rel="noreferrer">http://tools.android.com/knownissues#as0.1</a></p>
<ul>
<li>Open Start menu > computer > System Properties > Advanced System
Properties </li>
<li>In the Advanced tab > Environment Variables, add new system
variable <code>JAVA_HOME</code> that points to your JDK folder, for example <code>C:\Program Files\Java\jdk1.7.0_21</code></li>
</ul> |
26,906,630 | Django Rest Framework - Authentication credentials were not provided | <p>I'm developing an API using Django Rest Framework. I'm trying to list or create an "Order" object, but when i'm trying to access the console gives me this error:</p>
<pre><code>{"detail": "Authentication credentials were not provided."}
</code></pre>
<p><strong>Views:</strong></p>
<pre><code>from django.shortcuts import render
from rest_framework import viewsets
from django.contrib.auth.models import User
from rest_framework.renderers import JSONRenderer, YAMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from order.models import *
from API.serializers import *
from rest_framework.permissions import IsAuthenticated
class OrderViewSet(viewsets.ModelViewSet):
model = Order
serializer_class = OrderSerializer
permission_classes = (IsAuthenticated,)
</code></pre>
<p><strong>Serializer:</strong></p>
<pre><code>class OrderSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Order
fields = ('field1', 'field2')
</code></pre>
<p><strong>And my URLs:</strong></p>
<pre><code># -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.contrib import admin
from django.utils.functional import curry
from django.views.defaults import *
from rest_framework import routers
from API.views import *
admin.autodiscover()
handler500 = "web.views.server_error"
handler404 = "web.views.page_not_found_error"
router = routers.DefaultRouter()
router.register(r'orders', OrdersViewSet)
urlpatterns = patterns('',
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token'),
url(r'^api/', include(router.urls)),
)
</code></pre>
<p>And then I'm using this command in the console:</p>
<pre><code>curl -X GET http://127.0.0.1:8000/api/orders/ -H 'Authorization: Token 12383dcb52d627eabd39e7e88501e96a2sadc55'
</code></pre>
<p>And the error say:</p>
<pre><code>{"detail": "Authentication credentials were not provided."}
</code></pre> | 26,907,225 | 15 | 4 | null | 2014-11-13 10:27:45.653 UTC | 47 | 2022-06-09 05:40:03.197 UTC | 2014-11-13 10:48:19.387 UTC | null | 1,967,886 | null | 1,967,886 | null | 1 | 141 | python|django|django-rest-framework | 169,463 | <p>Solved by adding "DEFAULT_AUTHENTICATION_CLASSES" to my settings.py</p>
<pre><code>REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAdminUser'
),
}
</code></pre> |
41,432,852 | Why would I want to use an ExpressionVisitor? | <p>I know from the MSDN's article about <a href="https://msdn.microsoft.com/en-us/library/mt654266.aspx" rel="noreferrer">How to: Modify Expression Trees</a> what an <code>ExpressionVisitor</code> is supposed to do. It should modify expressions. </p>
<p>Their example is however pretty unrealistic so I was wondering why would I need it? Could you name some real-world cases where it would make sense to modify an expression tree? Or, why does it have to be modified at all? From what to what?</p>
<p>It has also many overloads for visiting all kinds of expressions. How do I know when I should use any of them and what should they return? I saw people using <code>VisitParameter</code> and returning <code>base.VisitParameter(node)</code> the other on the other hand were returning <code>Expression.Parameter(..)</code>.</p> | 41,653,475 | 4 | 8 | null | 2017-01-02 20:21:52.467 UTC | 8 | 2018-04-13 23:30:11.467 UTC | 2017-01-02 20:35:51.31 UTC | null | 235,671 | null | 235,671 | null | 1 | 33 | c#|expression-trees|expressionvisitor | 13,135 | <blockquote>
<p>Could you name some real-world cases where it would make sense to modify an expression tree?</p>
</blockquote>
<p>Strictly speaking, we never modify an expression tree, as they are immutable (as seen from the outside, at least, there's no promise that it doesn't internally memoise values or otherwise have mutable private state). It's precisely because they are immutable and hence we can't just change a node that the visitor pattern makes a lot of sense if we want to create a new expression tree that is based on the one we have but different in some particular way (the closest thing we have to modifying an immutable object).</p>
<p>We can find a few within Linq itself.</p>
<p>In many ways the simplest Linq provider is the linq-to-objects provider that works on enumerable objects in memory.</p>
<p>When it receives enumerables directly as <code>IEnumerable<T></code> objects it's pretty straight-forward in that most programmers could write an unoptimised version of most of the methods pretty quickly. E.g. <code>Where</code> is just:</p>
<pre><code>foreach (T item in source)
if (pred(item))
yield return item;
</code></pre>
<p>And so on. But what about <code>EnumerableQueryable</code> implementing the <code>IQueryable<T></code> versions? Since the <code>EnumerableQueryable</code> wraps an <code>IEnumerable<T></code> we could do the desired operation on the one or more enumerable objects involved, but we have an expression describing that operation in terms of <code>IQueryable<T></code> and other expressions for selectors, predicates, etc, where what we need is a description of that operation in terms of <code>IEnumerable<T></code> and delegates for selectors, predicates, etc.</p>
<p><a href="https://github.com/dotnet/corefx/blob/master/src/System.Linq.Queryable/src/System/Linq/EnumerableRewriter.cs" rel="noreferrer"><code>System.Linq.EnumerableRewriter</code></a> is an implementation of <code>ExpressionVisitor</code> does exactly such a re-write, and the result can then simply be compiled and executed.</p>
<p>Within <code>System.Linq.Expressions</code> itself there are a few implementations of <code>ExpressionVisitor</code> for different purposes. One example is that the interpreter form of compilation can't handle hoisted variables in quoted expressions directly, so it uses a visitor to rewrite it into working on indices into a a dictionary.</p>
<p>As well as producing another expression, an <code>ExpressionVisitor</code> can produce another result. Again <code>System.Linq.Expressions</code> has internal examples itself, with debug strings and <code>ToString()</code> for many expression types working by visiting the expression in question.</p>
<p>This can (though it doesn't have to be) be the approach used by a database-querying linq provider to turn an expression into a SQL query.</p>
<blockquote>
<p>How do I know when I should use any of them and what should they return? </p>
</blockquote>
<p>The default implementation of these methods will:</p>
<ol>
<li>If the expression can have no child expressions (e.g. the result of <code>Expression.Constant()</code>) then it will return the node back again.</li>
<li>Otherwise visit all the child expressions, and then call <code>Update</code> on the expression in question, passing the results back. <code>Update</code> in turn will either return a new node of the same type with the new children, or return the same node back again if the children weren't changed.</li>
</ol>
<p>As such, if you don't know you need to explicitly operate on a node for whatever your purposes are, then you probably don't need to change it. It also means that <code>Update</code> is a convenient way to get a new version of a node for a partial change. But just what "whatever your purposes are" means of course depends on the use case. The most common cases are probably go to one extreme or the other, with either just one or two expression types needing an override, or all or nearly all needing it.</p>
<p>(One caveat is if you are examining the children of those nodes that have children in a <code>ReadOnlyCollection</code> such as <code>BlockExpression</code> for both its steps and variables or <code>TryExpression</code> for its catch-blocks, and you will only sometimes change those children then if you haven't changed you are best to check for this yourself as a flaw [recently fixed, but not in any released version yet] means that if you pass the same children to <code>Update</code> in a different collection to the original <code>ReadOnlyCollection</code> then a new expression is created needlessly which has effects further up the tree. This is normally harmless, but it wastes time and memory).</p> |
9,826,699 | ASP.NET - Passing a C# variable to HTML | <p>I am trying to pass variables declared in C# to html. The variables have all been declared as public in the code-behind.</p>
<p>This is the HTML code I am using:</p>
<pre><code><asp:TextBox ID="TextBoxChildID" Text='<%= Child_ID %>' runat="server" Enabled="false"></asp:TextBox>
</code></pre>
<p>The problem is that when the page loads, the text '<%= Child_ID %>' appears in the textbox instead of the value in the variable.</p>
<p>What is wrong please?</p> | 9,826,732 | 4 | 0 | null | 2012-03-22 16:41:29.88 UTC | null | 2019-10-31 21:17:46.36 UTC | 2019-10-31 21:17:46.36 UTC | null | 1,839,439 | null | 1,124,249 | null | 1 | 9 | c#|asp.net | 51,812 | <p>All of this is assuming that this is just a textbox somewhere on your page, rather than in a DataBound control. If the textbox is part of an itemTemplate in a repeater, and Child_ID is something that differes by data row, then all of this is incorrect.</p>
<p>Do this instead:</p>
<pre><code><asp:TextBox ID="TextBoxChildID" runat="server" Enabled="false"><%= Child_ID %></asp:TextBox>
</code></pre>
<p>In short, you're making the same mistake I was making when I asked this question: <a href="https://stackoverflow.com/questions/1531586/why-works-in-one-situation-but-not-in-another">Why <%= %> works in one situation but not in another</a></p>
<hr>
<p>Alternatively, in code-behind, you can have this in your ASPX:</p>
<pre><code><asp:TextBox ID="TextBoxChildID" runat="server" Enabled="false"></asp:TextBox>
</code></pre>
<p>and this in your Code-Behind:</p>
<pre><code>TextBoxChildID.Text = Child_ID;
</code></pre> |
10,199,863 | How to execute the dex file in android with command? | <p>Can any body please share the method to execute the dex file in android with command?</p>
<p>This is just to understand.</p> | 10,200,822 | 1 | 1 | null | 2012-04-17 22:03:25.007 UTC | 18 | 2018-08-06 07:09:20.97 UTC | null | null | null | null | 1,015,097 | null | 1 | 19 | android|dex | 14,365 | <p>Let's say you have a the following code in file HelloWorld.java:</p>
<pre><code>public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
</code></pre>
<p>To run it on an android device:</p>
<pre><code>javac HelloWorld.java
dx --dex --output=classes.dex HelloWorld.class
zip HelloWorld.zip classes.dex
adb push HelloWorld.zip /sdcard/
</code></pre>
<p>For GB or earlier, you should be able to simply do:</p>
<pre><code>adb shell dalvikvm -cp /sdcard/HelloWorld.zip HelloWorld
</code></pre>
<p>For ICS+:</p>
<pre><code>adb shell mkdir /sdcard/dalvik-cache
adb shell ANDROID_DATA=/sdcard dalvikvm -cp /sdcard/HelloWorld.zip HelloWorld
</code></pre> |
9,795,051 | When to use R, when to use SQL? | <p>I have a moderate sized database with many joins and lookup tables.</p>
<p>I am more familiar with R than with SQL, and I am using MySQL. </p>
<h2>My Question:</h2>
<p>At what point is it beneficial to stop increasing the complexity of an SQL statement in favor of the data subsetting functionality in R (e.g., <code>merge</code>, <code>*apply</code>, <code>maply</code>, <code>dlply</code>, etc.)in R.</p>
<p>On one hand, SQL's join is easier than selecting all contents of each table and using the R <code>merge</code> function to join them. Also, doing the conditional selects in SQL would reduce the amount of data that has to be imported to R; but the speed difference is not significant. </p>
<p>On the other hand, a big join with a complex where clause becomes less easy to understand than the R syntax.</p>
<p>Below I have some <em>untested</em> code for illustrative purposes: I am asking this question at before having working code, and the answer to my question doesn't require working code (although this is always appreciated) - the "most elegant approach", "fewest lines", or "amazing implementation of X" are always appreciated, but what I am particularly interested in is the "most sensible / practical / canonical / based on first principles" rationale. </p>
<p>I am interested in the general answer of which steps should use a SQL <code>where</code> clause and which steps would be easier to accomplish using R.</p>
<h2>Illustration:</h2>
<h3>Database description</h3>
<p>there are three tables: <code>a</code>, <code>ab</code>, and <code>b</code>. Tables <code>a</code> and <code>b</code> each have a primary key <code>id</code>. They have a many-many relationship that is represented by a lookup table, <code>ab</code>, which contains fields <code>ab.a_id</code> and <code>ab.b_id</code> that join to <code>a.id</code> and <code>b.id</code>, respectively. Both tables have a <code>time</code> field, and a has a <code>group</code> field.</p>
<h3>Goal:</h3>
<p>Here is a minimal example of the join and subsetting that I want to do;</p>
<p>(MySQL naming of elements, e.g. <code>a.id</code> is equivalent to <code>a$id</code> in R)</p>
<ol>
<li><p>Join tables <code>a</code> and <code>b</code> using <code>ab</code>, appending multiple values of <code>b.time</code> associated with each <code>a.id</code> as a new column;</p>
<pre><code>select a_time, b.time, a.id, b.id from
a join ab on a.id = ab.a_id
join b on b.id = ab.b_id and then append b.time for distinct values of b.id;
</code></pre></li>
<li><p>I don't need repeated values of b.time, I only need a value of <code>b.max</code>: for repeated values of <code>b.time</code> joined to each <code>a.id</code>, <code>b.max</code> is the value of <code>b.time</code> closest to but not greater than <code>a.time</code></p>
<pre><code>b.max <- max(b.time[b.time < a.time))
</code></pre></li>
<li>append the value <code>dt <- a.time - b.max</code> to the table, for example, in R, </li>
<li><p>for each distinct value in <code>a.group</code>, select which(min(x.dt)))</p>
<pre><code>x.dt <- a.time - b.max
</code></pre></li>
</ol> | 9,796,652 | 2 | 1 | null | 2012-03-20 21:13:00.63 UTC | 9 | 2015-12-04 13:37:28.227 UTC | 2015-12-04 13:37:28.227 UTC | null | 4,370,109 | null | 199,217 | null | 1 | 29 | sql|r|database|data.table | 19,295 | <p>I usually do the data manipulations in SQL
until the data I want is in a single table,
and then, I do the rest in R.
Only when there is a performance issue
do I start to move some of the computations to the database.
This is already what you are doing.</p>
<p>Computations involving timestamps often
become unreadable in SQL
(the "<a href="http://en.wikipedia.org/wiki/Select_%28SQL%29#Window_function">analytic functions</a>", similar to <code>ddply</code>,
are supposed to simplify this,
but I think they are not available in MySQL).</p>
<p>However, your example can probably be written entirely in SQL as follows (not tested).</p>
<pre><code>-- Join the tables and compute the maximum
CREATE VIEW t1 AS
SELECT a.id AS a_id,
a.group AS a_group,
b.id AS b_id,
a.time AS a_time,
a.time - MAX(b.time) AS dt
FROM a, b, ab
WHERE a.id = ab.a_id AND b.id = ab.b_id
AND b.time < a.time
GROUP BY a.id, a.group, b.id;
-- Extract the desired rows
CREATE VIEW t2 AS
SELECT t1.*
FROM t1, (SELECT group, MIN(dt) AS min_dt FROM t1) X
WHERE t1.a_id = X.a_id
AND t1.b_id = X.b_id
AND t1.a_group = X.a.group;
</code></pre> |
7,918,270 | How to purge all tasks of a specific queue with celery in python? | <p>How to purge all scheduled and running tasks of a specific que with celery in python? The questions seems pretty straigtforward, but to add I am not looking for the command line code</p>
<p>I have the following line, which defines the que and would like to purge that que to manage tasks:</p>
<pre><code>CELERY_ROUTES = {"socialreport.tasks.twitter_save": {"queue": "twitter_save"}}
</code></pre>
<p>At 1 point in time I wanna purge all tasks in the que twitter_save with python code, maybe with a broadcast function? I couldn't find the documentation about this. Is this possible?</p> | 20,410,181 | 3 | 0 | null | 2011-10-27 15:23:28.837 UTC | 9 | 2016-07-14 13:04:26.17 UTC | 2014-06-05 22:05:52.777 UTC | null | 402,884 | null | 376,445 | null | 1 | 18 | python|django|celery | 15,265 | <p>just to update @Sam Stoelinga answer for celery 3.1, now it can be done like this on a terminal:</p>
<pre><code>celery amqp queue.purge <QUEUE_NAME>
</code></pre>
<p>For Django be sure to start it from the manage.py file:</p>
<pre><code>./manage.py celery amqp queue.purge <QUEUE_NAME>
</code></pre>
<p>If not, be sure celery is able to point correctly to the broker by setting the <code>--broker=</code> flag.</p> |
11,689,155 | Basic MVC (PHP) Structure | <p>I have the following data flow for a simple login form.</p>
<p>User access controller PHP file. Controller includes model.php and view.php</p>
<p>User submits form, controller sends POST data to model methods, and gets a result back. </p>
<p>User is logged in, and forwarded to a different view (login success message) by the controller.</p>
<p>Currently my views are static HTML (no PHP), so here is my question. What is the correct way to then pass the user a welcome message, e.g "Hello, Craig!"?</p>
<p>Is the view allowed PHP snippets, e.g </p>
<pre><code><?php echo $username; ?>
</code></pre>
<p>since the model is loaded before it in the controller file?</p>
<p>Thanks!</p>
<p><strong>Edit:</strong> Is it better practice then to allow the view to access specific class methods e.g </p>
<pre><code><?php $user->getUsername(); ?>
</code></pre>
<p>as opposed to just variables? </p>
<hr>
<p>Based on other answers, I have found a very useful article, which you may also be interested in.</p>
<p><a href="http://www.nathandavison.com/posts/view/7/custom-php-mvc-tutorial-part-5-views" rel="noreferrer">http://www.nathandavison.com/posts/view/7/custom-php-mvc-tutorial-part-5-views</a></p> | 11,689,228 | 2 | 3 | null | 2012-07-27 13:49:51.16 UTC | 12 | 2019-07-22 08:32:22 UTC | 2013-02-20 18:55:57.833 UTC | null | 2,598 | null | 1,504,434 | null | 1 | 9 | php|model-view-controller | 24,398 | <p>You can really put anything in a view that you'd like, but to better adhere to the MVC way of doing things you should restrict PHP in the view to simple <code>echo</code>s or <code>print</code>s (possibly really small loops as well, although even those can be pre-calculated in the controller/model). Since that is the only way to get dynamic content, it would be a little silly to say that they are not allowed.</p>
<p>The idea of the view is to let it have a more HTML look-and-feel, so that front-end developers or people who don't know PHP can easily be able to work with the file without getting confused.</p>
<p><strong>Update</strong></p>
<p>To learn more about MVC in general, you can see any of these (there's a ton of tutorials out there):</p>
<p><a href="http://blog.iandavis.com/2008/12/09/what-are-the-benefits-of-mvc/" rel="noreferrer">http://blog.iandavis.com/2008/12/09/what-are-the-benefits-of-mvc/</a></p>
<p><a href="http://php-html.net/tutorials/model-view-controller-in-php/" rel="noreferrer">http://php-html.net/tutorials/model-view-controller-in-php/</a></p>
<p><a href="http://www.tonymarston.net/php-mysql/model-view-controller.html" rel="noreferrer">http://www.tonymarston.net/php-mysql/model-view-controller.html</a></p>
<p>To see concrete examples of PHP using MVC, I suggest downloading some of the more prevelant frameworks (such as <a href="http://codeigniter.com/" rel="noreferrer">CodeIgniter</a>, <a href="http://www.symfony-project.org/" rel="noreferrer">Symfony</a> or <a href="http://www.drupal.org/" rel="noreferrer">Drupal</a>) and just looking through the code. Try to figure out how it works and then recreate the functionality for a simple article-based system.</p> |
11,910,147 | Trouble with importing annotations | <p>I'm working on a CodeIgniter project in which I'm using Doctrine2 and the Symfony2 Validator component. </p>
<p>All my Doctrine2 entities <code>use Doctrine\ORM\Mapping</code> and the entity manager recognizes them. My entity annotation looks like this:</p>
<pre><code>/**
* @Entity(repositoryClass = "UserRepository")
* @Table(name = "user")
* @HasLifecycleCallbacks()
*/
</code></pre>
<p>At this point, I'm able to persist entities without any trouble. The first problem arises when I try to use the Symfony2 Validator component. When I try to validate a <code>User</code> object, I get this error:</p>
<blockquote>
<p>[Semantical Error] The annotation "@Entity" in class Entity\User was never imported. Did you maybe forget to add a "use" statement for this annotation?</p>
</blockquote>
<p>The only "fix" to this issue is through <code>use Doctrine\Mapping\Entity</code>, but I have to do that for <em>every</em> annotation being used by my entity (Table, Column, ManyToOne, etc.). I'm trying to figure out why I need to explicitely <code>use</code> each annotation class instead of them being automatically recognized (shouldn't <code>use Doctrine\ORM\Mapping</code> grant me access to all the classes within that namespace?).</p>
<p>So, I then tried <code>use Doctrine\ORM\Mapping as ORM</code> and prefacing all my annotations with <code>ORM\</code>. Ex: <code>@ORM\Entity()</code>. The Symfony2 validator stops complaining, but now Doctrine2 complains that <code>Class Entity\User is not a valid entity or mapped super class.</code> I have no idea why this method works for the Validator, but not Doctrine2. If I run the console command <code>doctrine:orm:info</code>, my <code>User</code> entity is not recognized.</p>
<p>Because this is a CodeIgniter app, I'm autoloading the Symfony2 and Doctrine2 libraries. My autoload code is as follows:</p>
<pre><code># Symfony2 ClassLoader component
require_once __DIR__ . '/application/libraries/symfony/src/Symfony/Component/ClassLoader/UniversalClassLoader.php';
$loader = new \Symfony\Component\ClassLoader\UniversalClassLoader();
$loader->register();
$loader->registerNamespace('Symfony', __DIR__ . '/application/libraries/symfony/src');
$loader->registerNamespace('Doctrine', __DIR__ . '/application/libraries/doctrine/lib');
# Doctrine2
require_once __DIR__ . '/application/libraries/doctrine/lib/Doctrine/Common/Annotations/AnnotationRegistry.php';
use Doctrine\Common\Annotations\AnnotationRegistry;
AnnotationRegistry::registerLoader(function($class) use ($loader) {
$loader->loadClass($class);
$classExists = class_exists($class, false);
return $classExists;
});
AnnotationRegistry::registerFile(__DIR__ . '/application/libraries/doctrine/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');
</code></pre>
<p>I don't care if I have to preface everything with <code>ORM\</code> or not, I just want to find a solution that the Symfony2 Validator and Doctrine2 will both work with. Any ideas?</p> | 13,389,576 | 8 | 0 | null | 2012-08-10 22:40:29.58 UTC | 1 | 2022-03-04 16:44:49.203 UTC | null | null | null | null | 155,175 | null | 1 | 12 | php|doctrine-orm | 39,513 | <p>I had a similar issue when using Silex, Doctrine2 and the Symfony-Validator. </p>
<p>The solution was to avoid using the SimpleAnnotationsReader and instead using the normal AnnotationReader (have a look at <a href="http://www.doctrine-project.org/api/orm/2.3/class-Doctrine.ORM.Configuration.html#_newDefaultAnnotationDriver" rel="noreferrer">Doctrine\ORM\Configuration::newDefaultAnnotationDriver</a>). You can then preface every entity with <code>ORM\</code> (and of course inserting <code>use Doctrine\ORM\Mapping as ORM;</code> in every entity).</p> |
11,759,040 | Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: | <p>I am creating web application using Spring, Hibernate, Struts, and Maven. </p>
<p>I get the below error when I run <code>mvn clean install</code> command:</p>
<pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.project.action.PasswordHintActionTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.project.action.PasswordHintAction com.project.action.PasswordHintActionTest.action; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.project.action.PasswordHintAction] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
</code></pre>
<p>The following is the class that has the Autowired dependency: </p>
<pre><code>import com.opensymphony.xwork2.Action;
import org.project.model.User;
import org.proejct.service.UserManager;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.subethamail.wiser.Wiser;
import static org.junit.Assert.*;
public class PasswordHintActionTest extends BaseActionTestCase {
@Autowired
private PasswordHintAction action;
@Autowired
private UserManager userManager;
@Test
public void testExecute() throws Exception {
// start SMTP Server
Wiser wiser = new Wiser();
wiser.setPort(getSmtpPort());
wiser.start();
action.setUsername("user");
assertEquals("success", action.execute());
assertFalse(action.hasActionErrors());
// verify an account information e-mail was sent
wiser.stop();
assertTrue(wiser.getMessages().size() == 1);
// verify that success messages are in the request
assertNotNull(action.getSession().getAttribute("messages"));
}
}
</code></pre>
<p>My <code>applicationcontext.xml</code></p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
default-lazy-init="true">
<!-- Activates scanning of @Autowired -->
<context:annotation-config/>
<!-- Activates scanning of @Repository and @Service -->
<context:component-scan base-package="com.project"/>
<!-- Compass Search Section -->
<!-- Compass Bean, automatically scanning for searchable classes within the model -->
<!-- Hooks into Spring transaction management and stores the index on the file system -->
<bean id="compass" class="org.compass.spring.LocalCompassBean">
<property name="mappingScan" value="org.project"/>
<property name="postProcessor" ref="compassPostProcessor"/>
<property name="transactionManager" ref="transactionManager" />
<property name="settings">
<map>
<entry key="compass.engine.connection" value="target/test-index" />
</map>
</property>
</bean>
</code></pre>
<p>I have added to my context configuration to scan Autowired dependencies. But I am not sure why it is still giving this exception.</p>
<p>I tried adding it in following way also but I still get the same exception</p>
<pre><code><context:component-scan base-package="com.project.*"/>
</code></pre>
<p>UPDATE: </p>
<p>following is the password hint action</p>
<pre><code>import org.project.model.User;
import com.project.webapp.util.RequestUtil;
import org.springframework.mail.MailException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class PasswordHintAction extends BaseAction {
private static final long serialVersionUID = -4037514607101222025L;
private String username;
/**
* @param username The username to set.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Execute sending the password hint via e-mail.
*
* @return success if username works, input if not
*/
public String execute() {
List<Object> args = new ArrayList<Object>();
// ensure that the username has been sent
if (username == null) {
log.warn("Username not specified, notifying user that it's a required field.");
args.add(getText("user.username"));
addActionError(getText("errors.requiredField", args));
return INPUT;
}
if (log.isDebugEnabled()) {
log.debug("Processing Password Hint...");
}
// look up the user's information
try {
User user = userManager.getUserByUsername(username);
String hint = user.getPasswordHint();
if (hint == null || hint.trim().equals("")) {
log.warn("User '" + username + "' found, but no password hint exists.");
addActionError(getText("login.passwordHint.missing"));
return INPUT;
}
StringBuffer msg = new StringBuffer();
msg.append("Your password hint is: ").append(hint);
msg.append("\n\nLogin at: ").append(RequestUtil.getAppURL(getRequest()));
mailMessage.setTo(user.getEmail());
String subject = '[' + getText("webapp.name") + "] " + getText("user.passwordHint");
mailMessage.setSubject(subject);
mailMessage.setText(msg.toString());
mailEngine.send(mailMessage);
args.add(username);
args.add(user.getEmail());
saveMessage(getText("login.passwordHint.sent", args));
} catch (UsernameNotFoundException e) {
log.warn(e.getMessage());
args.add(username);
addActionError(getText("login.passwordHint.error", args));
getSession().setAttribute("errors", getActionErrors());
return INPUT;
} catch (MailException me) {
addActionError(me.getCause().getLocalizedMessage());
getSession().setAttribute("errors", getActionErrors());
return INPUT;
}
return SUCCESS;
}
}
</code></pre>
<p>Update 2:</p>
<p>applicationContext-struts.xml:</p>
<pre><code><bean id="passwordHintAction" class="com.project.action.PasswordHintAction" scope="prototype">
<property name="userManager" ref="userManager"/>
<property name="mailEngine" ref="mailEngine"/>
<property name="mailMessage" ref="mailMessage"/>
</bean>
</code></pre> | 11,759,225 | 3 | 3 | null | 2012-08-01 12:18:04.617 UTC | 7 | 2020-12-31 10:47:19.61 UTC | 2016-05-17 14:54:31.643 UTC | null | 5,183,619 | null | 187,922 | null | 1 | 20 | java|spring|hibernate|spring-mvc|struts | 180,697 | <p>Use component scanning as given below, if <code>com.project.action.PasswordHintAction</code> is annotated with stereotype annotations</p>
<pre><code><context:component-scan base-package="com.project.action"/>
</code></pre>
<p><strong>EDIT</strong></p>
<p>I see your problem, in <code>PasswordHintActionTest</code> you are autowiring <code>PasswordHintAction</code>. But you did not create bean configuration for <code>PasswordHintAction</code> to autowire. Add one of stereotype annotation(<code>@Component, @Service, @Controller</code>) to <code>PasswordHintAction</code> like</p>
<pre><code>@Component
public class PasswordHintAction extends BaseAction {
private static final long serialVersionUID = -4037514607101222025L;
private String username;
</code></pre>
<p>or create xml configuration in <code>applicationcontext.xml</code> like</p>
<pre><code><bean id="passwordHintAction" class="com.project.action.PasswordHintAction" />
</code></pre> |
11,575,943 | Parse file name from URL before downloading the file | <p>I'm downloading an ePub file from a URL.</p>
<p>Now I want to implement a mechanism by which if user tries to re-download the same file, he should get warning/error message and that file <strong>should not be</strong> downloaded again.</p>
<p>To implement this, I need to check the name of the file present in my library with the name of the file user is trying to download.</p>
<p>But I just have <a href="http://dl.dropbox.com/u/1177388/flagship_july_4_2010_flying_island_press.epub">this download link</a>, and not the file name.</p>
<p>How to get the name of the file before download in order to compare it with the existing file?</p> | 11,576,046 | 6 | 0 | null | 2012-07-20 08:46:32.083 UTC | 13 | 2021-06-06 10:39:09.213 UTC | 2012-07-20 09:27:27.823 UTC | null | 1,061,728 | null | 1,061,728 | null | 1 | 41 | android|download | 43,441 | <p>In android you can use <a href="https://developer.android.com/reference/android/webkit/URLUtil.html#guessFileName(java.lang.String,%20java.lang.String,%20java.lang.String)" rel="noreferrer">the guessFileName() method</a>:</p>
<pre><code>URLUtil.guessFileName(url, null, null)
</code></pre>
<p>Alternatively, a <strong><em>simplistic solution</em></strong> in Java could be:</p>
<pre><code>String fileName = url.substring(url.lastIndexOf('/') + 1);
</code></pre>
<p>(Assuming your url is in the format: <code>http://xxxxxxxxxxxxx/filename.ext</code>)</p>
<p><strong>UPDATE March 23, 2018</strong></p>
<p>This question is getting lots of hits and someone commented my 'simple' solution does not work with certain urls so I felt the need to improve the answer.</p>
<p>In case you want to handle more complex url pattern, I provided a sample solution below. It gets pretty complex quite quickly and I'm pretty sure there are some odd cases my solution still can't handle but nevertheless here it goes:</p>
<pre><code>public static String getFileNameFromURL(String url) {
if (url == null) {
return "";
}
try {
URL resource = new URL(url);
String host = resource.getHost();
if (host.length() > 0 && url.endsWith(host)) {
// handle ...example.com
return "";
}
}
catch(MalformedURLException e) {
return "";
}
int startIndex = url.lastIndexOf('/') + 1;
int length = url.length();
// find end index for ?
int lastQMPos = url.lastIndexOf('?');
if (lastQMPos == -1) {
lastQMPos = length;
}
// find end index for #
int lastHashPos = url.lastIndexOf('#');
if (lastHashPos == -1) {
lastHashPos = length;
}
// calculate the end index
int endIndex = Math.min(lastQMPos, lastHashPos);
return url.substring(startIndex, endIndex);
}
</code></pre>
<p>This method can handle these type of input:</p>
<pre><code>Input: "null" Output: ""
Input: "" Output: ""
Input: "file:///home/user/test.html" Output: "test.html"
Input: "file:///home/user/test.html?id=902" Output: "test.html"
Input: "file:///home/user/test.html#footer" Output: "test.html"
Input: "http://example.com" Output: ""
Input: "http://www.example.com" Output: ""
Input: "http://www.example.txt" Output: ""
Input: "http://example.com/" Output: ""
Input: "http://example.com/a/b/c/test.html" Output: "test.html"
Input: "http://example.com/a/b/c/test.html?param=value" Output: "test.html"
Input: "http://example.com/a/b/c/test.html#anchor" Output: "test.html"
Input: "http://example.com/a/b/c/test.html#anchor?param=value" Output: "test.html"
</code></pre>
<p>You can find the whole source code here: <a href="https://ideone.com/uFWxTL" rel="noreferrer">https://ideone.com/uFWxTL</a></p> |
11,803,482 | How to automatically FTP files that I am editing | <p>I'm trying to figure out how to autoftp with Filezilla. Are there any other programs that do this right off the bat?</p> | 11,803,537 | 7 | 7 | null | 2012-08-03 21:23:13.347 UTC | 11 | 2020-07-28 22:30:14.44 UTC | 2017-02-15 13:37:33.997 UTC | null | 4,477,659 | null | 1,549,397 | null | 1 | 42 | windows|ftp|filezilla | 91,811 | <p>If by "autoftp" you mean "update the file on the server whenever I save it" and you're working with code, then I'd recommend the wonderful <a href="http://notepad-plus-plus.org/">Notepad++</a></p> |
11,738,823 | Explicitly calling return in a function or not | <p>A while back <a href="https://stackoverflow.com/questions/10412720/rserve-return-type-in-case-of-multiple-statements/10413020#10413020">I got rebuked</a> by Simon Urbanek from the R core team (I believe) for recommending a user to explicitly calling <code>return</code> at the end of a function (his comment was deleted though):</p>
<pre><code>foo = function() {
return(value)
}
</code></pre>
<p>instead he recommended:</p>
<pre><code>foo = function() {
value
}
</code></pre>
<p>Probably in a situation like this it is required:</p>
<pre><code>foo = function() {
if(a) {
return(a)
} else {
return(b)
}
}
</code></pre>
<p>His comment shed some light on why not calling <code>return</code> unless strictly needed is a good thing, but this was deleted. </p>
<p>My question is: Why is not calling <code>return</code> faster or better, and thus preferable?</p> | 11,834,490 | 9 | 4 | null | 2012-07-31 11:12:55.697 UTC | 63 | 2020-07-23 11:22:35.037 UTC | 2017-05-23 11:54:51.513 UTC | null | -1 | null | 1,033,808 | null | 1 | 225 | r | 116,297 | <p><strong>Question was: Why is not (explicitly) calling return faster or better, and thus preferable?</strong></p>
<p>There is no statement in R documentation making such an assumption.<br>
The main page ?'function' says:</p>
<pre><code>function( arglist ) expr
return(value)
</code></pre>
<p><strong>Is it faster without calling return?</strong> </p>
<p>Both <code>function()</code> and <code>return()</code> are primitive functions and the <code>function()</code> itself returns last evaluated value even without including <code>return()</code> function.</p>
<p>Calling <code>return()</code> as <code>.Primitive('return')</code> with that last value as an argument will do the same job but needs one call more. So that this (often) unnecessary <code>.Primitive('return')</code> call can draw additional resources.
Simple measurement however shows that the resulting difference is very small and thus can not be the reason for not using explicit return. The following plot is created from data selected this way:</p>
<pre><code>bench_nor2 <- function(x,repeats) { system.time(rep(
# without explicit return
(function(x) vector(length=x,mode="numeric"))(x)
,repeats)) }
bench_ret2 <- function(x,repeats) { system.time(rep(
# with explicit return
(function(x) return(vector(length=x,mode="numeric")))(x)
,repeats)) }
maxlen <- 1000
reps <- 10000
along <- seq(from=1,to=maxlen,by=5)
ret <- sapply(along,FUN=bench_ret2,repeats=reps)
nor <- sapply(along,FUN=bench_nor2,repeats=reps)
res <- data.frame(N=along,ELAPSED_RET=ret["elapsed",],ELAPSED_NOR=nor["elapsed",])
# res object is then visualized
# R version 2.15
</code></pre>
<p><img src="https://i.stack.imgur.com/qNjIS.png" alt="Function elapsed time comparison"></p>
<p>The picture above may slightly difffer on your platform.
Based on measured data, the size of returned object is not causing any difference, the number of repeats (even if scaled up) makes just a very small difference, which in real word with real data and real algorithm could not be counted or make your script run faster.</p>
<p><strong>Is it better without calling return?</strong> </p>
<p><code>Return</code> is good tool for clearly designing "leaves" of code where the routine should end, jump out of the function and return value.</p>
<pre><code># here without calling .Primitive('return')
> (function() {10;20;30;40})()
[1] 40
# here with .Primitive('return')
> (function() {10;20;30;40;return(40)})()
[1] 40
# here return terminates flow
> (function() {10;20;return();30;40})()
NULL
> (function() {10;20;return(25);30;40})()
[1] 25
>
</code></pre>
<p>It depends on strategy and programming style of the programmer what style he use, he can use no return() as it is not required.</p>
<p>R core programmers uses both approaches ie. with and without explicit return() as it is possible to find in sources of 'base' functions.</p>
<p>Many times only return() is used (no argument) returning NULL in cases to conditially stop the function.</p>
<p>It is not clear if it is better or not as standard user or analyst using R can not see the real difference.</p>
<p>My opinion is that the question should be: <em>Is there any danger in using explicit return coming from R implementation?</em></p>
<p>Or, maybe better, user writing function code should always ask: <em>What is the effect in <strong>not</strong> using explicit return (or placing object to be returned as last leaf of code branch) in the function code?</em></p> |
20,147,081 | Javascript - catch access to property of object | <p>Is it possible to capture when a (any) property of an object is accessed, or attempting to be accessed? </p>
<p>Example:</p>
<p>I have created custom object <code>Foo</code></p>
<pre><code>var Foo = (function(){
var self = {};
//... set a few properties
return self;
})();
</code></pre>
<p>Then there is some action against <code>Foo</code> - someone tries to access property <code>bar</code></p>
<pre><code>Foo.bar
</code></pre>
<p>Is there way (prototype, perhaps) to capture this? <code>bar</code> may be undefined on <code>Foo</code>. I could suffice with capturing any attempted access to undefined properties. </p>
<p>For instance, if <code>bar</code> is undefined on <code>Foo</code>, and <code>Foo.bar</code> is attempted, something like:</p>
<pre><code>Foo.prototype.undefined = function(){
var name = this.name; //name of property they attempted to access (bar)
Foo[name] = function(){
//...do something
};
return Foo[name];
}
</code></pre>
<p>But functional, unlike my example.</p>
<p><strong>Concept</strong> </p>
<pre><code>Foo.* = function(){
}
</code></pre>
<p><strong>Background</strong></p>
<p>If I have a custom function, I can listen for every time this function is called (see below). Just wondering if it's possible with property access.</p>
<pre><code>Foo = function(){};
Foo.prototype.call = function(thisArg){
console.log(this, thisArg);
return this;
}
</code></pre> | 20,147,219 | 5 | 5 | null | 2013-11-22 14:19:00.357 UTC | 10 | 2019-09-24 06:52:12.877 UTC | 2013-11-22 14:27:42.673 UTC | null | 1,750,282 | null | 1,750,282 | null | 1 | 27 | javascript|object-properties | 12,453 | <p>Yes, this is possible in ES2015+, using the <a href="http://wiki.ecmascript.org/doku.php?id=harmony:direct_proxies" rel="noreferrer">Proxy</a>. It's not possible in ES5 and earlier, not even with polyfills.</p>
<p>It took me a while, but I finally found <a href="https://stackoverflow.com/questions/7891937/is-it-possible-to-implement-dynamic-getters-setters-in-javascript/7891968#7891968">my previous answer</a> to this question. See that answer for all the details on proxies and such.</p>
<p>Here's the proxy example from that answer:</p>
<pre><code>const obj = new Proxy({}, {
get: function(target, name, receiver) {
if (!(name in target)) {
console.log("Getting non-existant property '" + name + "'");
return undefined;
}
return Reflect.get(target, name, receiver);
},
set: function(target, name, value, receiver) {
if (!(name in target)) {
console.log("Setting non-existant property '" + name + "', initial value: " + value);
}
return Reflect.set(target, name, value, receiver);
}
});
console.log("[before] obj.foo = " + obj.foo);
obj.foo = "bar";
console.log("[after] obj.foo = " + obj.foo);
obj.foo = "baz";
console.log("[after] obj.foo = " + obj.foo);
</code></pre>
<p>Live Copy:</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict";
const obj = new Proxy({}, {
get: function(target, name, receiver) {
if (!(name in target)) {
console.log("Getting non-existant property '" + name + "'");
return undefined;
}
return Reflect.get(target, name, receiver);
},
set: function(target, name, value, receiver) {
if (!(name in target)) {
console.log("Setting non-existant property '" + name + "', initial value: " + value);
}
return Reflect.set(target, name, value, receiver);
}
});
console.log("[before] obj.foo = " + obj.foo);
obj.foo = "bar";
console.log("[after] obj.foo = " + obj.foo);
obj.foo = "baz";
console.log("[after] obj.foo = " + obj.foo);</code></pre>
</div>
</div>
</p>
<p>When run, that outputs:</p>
<pre>Getting non-existant property 'foo'
[before] obj.foo = undefined
Setting non-existant property 'foo', initial value: bar
[after] obj.foo = bar
[after] obj.foo = baz</pre> |
19,997,146 | Kitkat kills: Not allowed to load local resource: file:///android_asset/webkit/android-weberror.png | <p>I have an app that uses WebViews. I've changed my targetAPI from 18 to 19 and I'm currently testing on the new 4.4. For some reason I'm getting this error: <code>Not allowed to load local resource: file:///android_asset/webkit/android-weberror.png</code> on 4.4 but not on 4.3, does somebody have clue why?</p>
<p>Since I don't really know where to start looking I can't give the complete code. It might have something to do with the <code>shouldInterceptRequest(Webview, String)</code> method in the WebViewClient but I'm not really sure. If I know more, I'll update the question.</p> | 20,003,398 | 9 | 5 | null | 2013-11-15 09:01:27.803 UTC | 10 | 2022-09-15 05:55:44.527 UTC | null | null | null | null | 1,388,116 | null | 1 | 27 | android|android-webview | 47,835 | <p>"Not allowed to load local resource" is a security origin error. The KitKat WebView has stronger security restrictions and it seems like these are kicking in. FWIW I tried just loading a file:///android_asset URL and it worked fine.</p>
<p>Did you call any of the file-related WebSettings APIs (like setAllowFileAccess(false)) by any chance? Are you trying to load the resource from an https: URL?</p> |
3,730,053 | How to delete all databases on Postgres? | <p>I take daily backs of our postgres development box using:
pg_dumpall -h 127.0.0.1 -U user -w | gzip blah.gz</p>
<p>Since 9.0 is now a release candidate I would like to restore this daily backup on a daily basis to a postgres9.0rc1 box for testing, however I'm not sure how to script it repeatedly. Is there some directory I can nuke to do this?</p> | 58,735,470 | 5 | 0 | null | 2010-09-16 19:28:20.293 UTC | 10 | 2022-07-11 09:48:15.353 UTC | null | null | null | null | 160,208 | null | 1 | 27 | postgresql | 67,780 | <p>Granted the question is 9 years old at this point, but it's still the second google result for deleting all databases. If you just want to go from N DBs to 0 without jacking with your config and also having rummage through the file system, this is a much better answer:</p>
<p><a href="https://stackoverflow.com/a/24548640/3499424">https://stackoverflow.com/a/24548640/3499424</a></p>
<p>From the answer, the following script will generate N <code>drop database</code> commands, one for each non-template DB:</p>
<pre class="lang-sql prettyprint-override"><code>select 'drop database "'||datname||'";'
from pg_database
where datistemplate=false;
</code></pre>
<p>From there, you can edit and run manually, or pipe further along into a script. Here's a somewhat verbose one-liner:</p>
<p><code>echo \pset pager off \copy (select 'drop database "'||datname||'";' from pg_database where datistemplate=false) to STDOUT; | psql -U <user> -d postgres | <appropriate grep> | psql -U <user> -d postgres</code></p>
<p>Explanation:</p>
<ol>
<li>This is a series of pipes</li>
<li><code>echo \pset pager off \copy (select 'drop database "'||datname||'";' from pg_database where datistemplate=false) to STDOUT;</code> generates a string for psql to execute
<ol>
<li><code>\pset pager off</code> ensures you get all records instead of that (54 rows) crap</li>
<li><code>\copy (select 'drop database "'||datname||'";' from pg_database where datistemplate=false) to STDOUT;</code> executes the aforementioned query, sending the result to STDOUT. We have to do this since we lead with <code>\pset</code>.</li>
</ol></li>
<li><code>| psql -U <user> -d postgres</code> pipes said string into psql, which executes it. Replace <code><user></code> with the user you want to use</li>
<li><code>| <appropriate grep></code> is for stripping out the "Pager usage is off" line
<ol>
<li>Windows users can use <code>findstr /v "Pager"</code> or <code>findstr /b "drop"</code></li>
<li>*nix users can use <code>grep 'drop'</code></li>
</ol></li>
<li><code>| psql -U <user> -d postgres</code> pipes the resulting set of <code>drop database</code> commands into psql again, which executes them, thus dropping all the databases</li>
<li>WARNING: Without any additional filtering, this <em>will</em> also drop the <code>postgres</code> database. You can strip it either in the <code>SELECT</code> or the grep if you don't want that to happen.</li>
</ol> |
3,461,869 | Plot a plane based on a normal vector and a point in Matlab or matplotlib | <p>How would one go plotting a plane in matlab or matplotlib from a normal vector and a point? </p> | 3,461,941 | 5 | 0 | null | 2010-08-11 19:05:03.433 UTC | 19 | 2017-04-17 09:00:14.973 UTC | 2017-02-17 08:30:40.697 UTC | null | 656,804 | null | 319,988 | null | 1 | 38 | matlab|matplotlib|plot|scipy | 70,218 | <p>For Matlab:</p>
<pre><code>point = [1,2,3];
normal = [1,1,2];
%# a plane is a*x+b*y+c*z+d=0
%# [a,b,c] is the normal. Thus, we have to calculate
%# d and we're set
d = -point*normal'; %'# dot product for less typing
%# create x,y
[xx,yy]=ndgrid(1:10,1:10);
%# calculate corresponding z
z = (-normal(1)*xx - normal(2)*yy - d)/normal(3);
%# plot the surface
figure
surf(xx,yy,z)
</code></pre>
<p><img src="https://i.stack.imgur.com/E80Ov.png" alt="enter image description here"></p>
<p>Note: this solution only works as long as normal(3) is not 0. If the plane is parallel to the z-axis, you can rotate the dimensions to keep the same approach:</p>
<pre><code>z = (-normal(3)*xx - normal(1)*yy - d)/normal(2); %% assuming normal(3)==0 and normal(2)~=0
%% plot the surface
figure
surf(xx,yy,z)
%% label the axis to avoid confusion
xlabel('z')
ylabel('x')
zlabel('y')
</code></pre> |
3,654,144 | Direct "rate in iTunes" link in my app? | <p>I've seen posts here on Stackoverflow that describe how to allow users to be directed to apps on the app store. </p>
<p>Is there a way to link <em>directly</em> to the <em>rating and comments form</em> in the App Store?</p> | 20,788,267 | 5 | 5 | null | 2010-09-06 20:31:52.393 UTC | 46 | 2018-09-04 12:40:06.64 UTC | 2010-09-06 21:19:23.733 UTC | null | 224,988 | null | 224,988 | null | 1 | 58 | iphone|ios|hyperlink|rating|itunes-store | 33,170 | <p>Answers here are outdated.</p>
<p>This works on my end (Xcode 5 - iOS 7 - <strong>works only on Device, not simulator</strong>!):</p>
<pre><code>itms-apps://itunes.apple.com/app/idYOUR_APP_ID
</code></pre>
<p>For versions lower than iOS 7 use the old one:</p>
<pre><code>itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=YOUR_APP_ID
</code></pre> |
3,545,183 | How to add an object into another Object set | <p>I have two classes. One(Person) for getters and setters, and another(People) for compute the data. What is my situation is, I get the data from the DB using <code>ResultSet</code>, then created a person Object to store the row data. Then i created people Object to store all persons.</p>
<p>Each Object created as SET. </p>
<pre><code>while(rs.next())
{
Set<People> people = new HashSet<people>();
Person person = new Person();
String name = rs.getString(2);
person.setName(name);
int id = rs.getInt(1);
person.setId(id);
String dept = rs.getString(4);
person.setDept(dept);
int age = rs.getInt(3);
person.setAge(age);
people.add(person);
}
return people;
</code></pre>
<p>Now the problem is the last line in the While Loop <code>people.add(person);</code></p>
<p>It says</p>
<blockquote>
<p>The method add(People) in the type Set is not applicable for the arguments (Person)</p>
</blockquote>
<p>How can i overcome this problem?</p>
<p>Thanks.</p> | 3,545,247 | 6 | 0 | null | 2010-08-23 06:34:43.293 UTC | 1 | 2018-02-18 14:35:37.057 UTC | 2010-08-23 06:43:08.093 UTC | null | 105,224 | user405398 | null | null | 1 | 4 | java|object|set | 41,607 | <p>My understandig from your design is that you have a <strong>People has-many Person</strong> relation, so the <code>People</code> class holds a collection of <code>Person</code> objects. Then I'd expect something like this:</p>
<pre><code>public class Person {
private String name;
private Date dateOfBirth;
// .. more attributes
// getters and setters
// overrides of equals, hashcode and toString
}
public class People implements Set<Person> {
private Set<Person> persons = new HashSet<Person>();
public boolean add(Person person) {
return persons.add(person);
}
// more methods for remove, contains, ...
}
</code></pre>
<p>So in your database related code you wouldn't need to create another set, because <code>People</code> already has the one you need:</p>
<pre><code>People people = new People(); // or get it, if it's already created
while(rs.next())
{
Person person = new Person();
String name = rs.getString(2);
person.setName(name);
int id = rs.getInt(1);
person.setId(id);
String dept = rs.getString(4);
person.setDept(dept);
int age = rs.getInt(3);
person.setAge(age);
people.add(person);
}
return people;
</code></pre> |
3,366,529 | Wrap every 3 divs in a div | <p>Is it possible to use <code>nth-child</code> selectors to wrap 3 divs using <code>.wrapAll</code>? I can't seem to work out the correct equation.</p>
<p>so...</p>
<pre><code><div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</code></pre>
<p>becomes...</p>
<pre><code><div>
<div class="new">
<div></div>
<div></div>
<div></div>
</div>
<div class="new">
<div></div>
<div></div>
<div></div>
</div>
</div>
</code></pre> | 3,366,539 | 6 | 1 | null | 2010-07-29 20:09:11.187 UTC | 37 | 2016-03-17 09:10:26.133 UTC | 2016-03-17 09:10:26.133 UTC | null | 1,287,812 | null | 392,402 | null | 1 | 87 | jquery|css-selectors|wrapall | 64,965 | <p>You can do it with <a href="http://api.jquery.com/slice/" rel="noreferrer"><code>.slice()</code></a>, like this:</p>
<pre><code>var divs = $("div > div");
for(var i = 0; i < divs.length; i+=3) {
divs.slice(i, i+3).wrapAll("<div class='new'></div>");
}
</code></pre>
<p><a href="http://jsfiddle.net/nick_craver/vmdaM/" rel="noreferrer">You can try out a demo here</a>, all we're doing here is getting the elements you want to wrap and looping through them, doing a <a href="http://api.jquery.com/wrapAll/" rel="noreferrer"><code>.wrapAll()</code></a> in batches of 3 then moving to the next 3, etc. It will wrap 3 at a time and however many are left at the end, e.g. 3, 3, 3, 2 if that's the case.</p> |
3,827,567 | How to get the path of the batch script in Windows? | <p>I know that <code>%0</code> contains the full path of the batch script, e.g. <code>c:\path\to\my\file\abc.bat</code></p>
<p>I would <code>path</code> to be equal to <code>c:\path\to\my\file</code></p>
<p>How could I achieve that ?</p> | 3,827,582 | 7 | 4 | null | 2010-09-30 03:46:52.24 UTC | 84 | 2020-11-09 09:00:14.357 UTC | 2017-03-07 09:40:25.963 UTC | null | 27,423 | null | 247,243 | null | 1 | 406 | windows|batch-file | 416,150 | <p><code>%~dp0</code> will be the directory. <a href="https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/call#batch-parameters" rel="noreferrer">Here's some documentation on all of the path modifiers</a>. Fun stuff :-)</p>
<p>To remove the final backslash, you can use the <code>:n,m</code> substring syntax, like so:</p>
<pre><code>SET mypath=%~dp0
echo %mypath:~0,-1%
</code></pre>
<p>I don't believe there's a way to combine the <code>%0</code> syntax with the <code>:~n,m</code> syntax, unfortunately.</p> |
3,559,419 | Is there any Rails function to check if a partial exists? | <p>When I render a partial which does not exists, I get an Exception. I'd like to check if a partial exists before rendering it and in case it doesn't exist, I'll render something else. I did the following code in my .erb file, but I think there should be a better way to do this:</p>
<pre><code> <% begin %>
<%= render :partial => "#{dynamic_partial}" %>
<% rescue ActionView::MissingTemplate %>
Can't show this data!
<% end %>
</code></pre> | 8,180,410 | 8 | 1 | null | 2010-08-24 17:51:32.407 UTC | 17 | 2021-09-21 22:08:42.25 UTC | null | null | null | null | 105,514 | null | 1 | 102 | ruby-on-rails|partial | 33,610 | <p>Currently, I'm using the following in my Rails 3/3.1 projects:</p>
<pre><code>lookup_context.find_all('posts/_form').any?
</code></pre>
<p>The advantage over other solutions I've seen is that this will look in all view paths instead of just your rails root. This is important to me as I have a lot of rails engines. </p>
<p>This also works in Rails 4.</p> |
8,028,737 | how to do a relative path redirection using javascript? | <p>I'm working on javascript/jquery in a php based site, and I have to redirect the page upon an event in the page.</p>
<p>lets say, on clicking the button "click me" in <code>"page1.php"</code>, the page should be redirected to "<code>page2.php</code>". This redirection has to be done using javascript/ jquery. Both pages are in the same folder, and the redirection code should use <strong>'RELATIVE LINKS'</strong>.</p>
<p>Now, I am able to redirect if I give the absolute link to <code>page2.php</code>, but could someone let me know how to do the same with a relative link?</p>
<p>something like: </p>
<pre><code>window.location.href = 'page2.php';
</code></pre>
<p>thanks.</p> | 8,028,848 | 4 | 5 | null | 2011-11-06 17:07:45.293 UTC | 4 | 2014-05-06 20:00:01.117 UTC | 2011-11-06 17:27:32.043 UTC | null | 592,495 | null | 743,243 | null | 1 | 23 | javascript|jquery | 91,652 | <pre><code>window.location.href = "page2.php";
</code></pre>
<p>this worked. Infact, relative and absolute works in the same way:</p>
<pre><code>window.location.href = "http://www.google.com";
// or
window.location.href = "page2.html";
</code></pre> |
7,883,916 | Django filter the model on ManyToMany count? | <p>Suppose I have something like this in my models.py:</p>
<pre><code>class Hipster(models.Model):
name = CharField(max_length=50)
class Party(models.Model):
organiser = models.ForeignKey()
participants = models.ManyToManyField(Profile, related_name="participants")
</code></pre>
<p>Now in my views.py I would like to do a query which would fetch a party for the user where there are more than 0 participants. </p>
<p>Something like this maybe:</p>
<pre><code>user = Hipster.get(pk=1)
hip_parties = Party.objects.filter(organiser=user, len(participants) > 0)
</code></pre>
<p>What's the best way of doing it? </p> | 7,884,061 | 5 | 0 | null | 2011-10-25 02:01:26.817 UTC | 8 | 2022-06-14 23:26:50.34 UTC | null | null | null | null | 672,226 | null | 1 | 82 | django|django-models|django-queryset | 24,394 | <p>If this works this is how I would do it.</p>
<p>Best way can mean a lot of things: best performance, most maintainable, etc. Therefore I will not say this is the best way, but I like to stick to the ORM features as much as possible since it seems more maintainable. </p>
<pre><code>from django.db.models import Count
user = Hipster.objects.get(pk=1)
hip_parties = (Party.objects.annotate(num_participants=Count('participants'))
.filter(organiser=user, num_participants__gt=0))
</code></pre> |
14,549,489 | How to fix pure virtual function called runtime error? | <p>I understand why I am getting the error I am getting (pure virtual function called). I am trying to call pure virtual functions from within the destructor of my base class shown below. However, I do not know how to rework my code to prevent this from happening. Here are the base and derived classes (the relevant portions anyway):</p>
<p>Base class:</p>
<pre><code>TailFileManager::TailFileManager(const std::string &filename, const int fileOpenPeriod_ms)
: m_Stop(false)
{
m_WorkerThread.reset(new boost::thread(boost::bind(&TailFileManager::TailFile, this, filename, fileOpenPeriod_ms)));
}
TailFileManager::~TailFileManager()
{
m_Stop = true;
m_WorkerThread->join();
}
void TailFileManager::TailFile(const std::string &filename, const int fileOpenPeriod_ms)
{
std::ifstream ifs(filename.c_str());
while (! ifs.is_open())
{
boost::this_thread::sleep(boost::posix_time::milliseconds(fileOpenPeriod_ms));
ifs.open(filename.c_str());
}
ifs.seekg(0, std::ios::end);
while (! m_Stop)
{
ifs.clear();
std::string line;
while (std::getline(ifs, line))
{
OnLineAdded(line);
}
OnEndOfFile();
}
ifs.close();
}
</code></pre>
<p>Derived class:</p>
<pre><code>ETSLogTailFileManager::ETSLogTailFileManager(const std::string &filename, const int heartbeatPeriod_ms)
: TailFileManager(filename, heartbeatPeriod_ms),
m_HeartbeatPeriod_ms(heartbeatPeriod_ms),
m_FoundInboundMessage(false),
m_TimeOfLastActivity(0)
{
}
ETSLogTailFileManager::~ETSLogTailFileManager()
{
}
void ETSLogTailFileManager::OnLineAdded(const std::string &line)
{
// do stuff...
}
void ETSLogTailFileManager::OnEndOfFile()
{
// do stuff...
}
</code></pre> | 14,549,689 | 4 | 13 | null | 2013-01-27 16:34:08.49 UTC | 2 | 2021-10-27 10:45:28.417 UTC | 2015-03-07 10:30:27.043 UTC | null | 3,235,496 | null | 834,594 | null | 1 | 4 | c++|pure-virtual | 38,659 | <p>You shouldn't call virtual functions during construction or destruction, because the calls won't do what you think, and if they did, you'd still be unhappy. If you're a recovering Java or C# programmer, pay close attention to this Item, because this is a place where those languages zig, while C++ zags.</p>
<p>Re-work your design i.e you may call some cleanup function before object get destroyed, idea is just avoid virtual function during const/dest (if there are any!), if you are working with C++...</p>
<p>The rules for virtual invocation are different. C++ 2003, section 12.7 "Construction and Destruction", says:</p>
<p>Lets refresh some old memories ...</p>
<p>Member functions, including virtual functions (10.3), can be called during construction or destruction (12.6.2). When a virtual function is called directly or indirectly from a constructor (including from the mem-initializer for a data member) or from a destructor, and the object to which the call applies is the object under construction or destruction, the function called is the one defined in the constructor or destructorâs own class or in one of its bases, but not a function overriding it in a class derived from the constructor or destructorâs class, or overriding it in one of the other base classes of the most derived object (1.8). If the virtual function call uses an explicit class member access (5.2.5) and the object-expression refers to the object under construction or destruction but its type is neither the constructor or destructorâs own class or one of its bases, the result of the call is undefined.</p>
<p><strong>Because of this difference in behavior, it is recommended that you never invoke an object's virtual function while it is being constructed or destroyed.</strong></p>
<p><strong>Never Call Virtual Functions during Construction or Destruction
An Excerpt from Effective C++, Third Edition
by Scott Meyers</strong>
June 6, 2005</p>
<p><a href="http://www.artima.com/cppsource/nevercall.html" rel="noreferrer">http://www.artima.com/cppsource/nevercall.html</a></p> |
14,739,537 | Convert plain text in to HTML | <p>I have a script with which at a certain point I'm getting HTML(data) with Ajax call. I have to turn this HTML in to plain text like this:</p>
<pre><code>$("#div").text(data);
</code></pre>
<p>I now want to turn this around and make the text HTML again. I there an easy Jquery method of doing this? I tried:</p>
<pre><code>$("#div").text(data).end().html();
</code></pre>
<p>No luck.</p> | 14,739,598 | 5 | 9 | null | 2013-02-06 21:52:57.79 UTC | 3 | 2016-03-21 07:04:09.35 UTC | null | null | null | null | 647,909 | null | 1 | 6 | jquery|text | 54,863 | <p>You would need to hold onto the original response to do this...</p>
<pre><code>$("#hiddendiv").html(data);
$("#div").text(data);
</code></pre>
<p>Then you could get it back out...</p>
<pre><code>var html = $("#hiddendiv").html();
</code></pre>
<p><strong>Update based on comment...</strong></p>
<p>You can remove that element before you display it...</p>
<pre><code>var html = $(data);
$('#cookiediv', html).hide();
$('#div').html(html);
</code></pre>
<p>Where the cookie message has <code>id="cookiediv"</code> - you may need to adjust the selector to get to this div, but it is almost certainly possible to grab it.</p> |
4,378,455 | What is the complexity of regular expression? | <p>What is the complexity with respect to the string length that takes to perform a regular expression comparison on a string?</p> | 4,378,626 | 4 | 3 | null | 2010-12-07 15:38:56.67 UTC | 23 | 2019-03-21 15:11:04.427 UTC | null | null | null | null | 132,640 | null | 1 | 85 | regex|complexity-theory|big-o | 47,258 | <p>The answer depends on what exactly you mean by "regular expressions." Classic regexes can be <a href="http://lambda.uta.edu/cse5317/spring01/notes/node9.html" rel="noreferrer">compiled</a> into <a href="http://en.wikipedia.org/wiki/Deterministic_finite-state_machine" rel="noreferrer">Deterministic Finite Automata</a> that can match a string of length <code>N</code> in <code>O(N)</code> time. Certain extensions to the regex language change that for the worse.</p>
<p>You may find the following document of interest: <a href="http://swtch.com/~rsc/regexp/regexp1.html" rel="noreferrer">Regular Expression Matching Can Be Simple And Fast</a>.</p> |
4,582,562 | How can I add commas to numbers in PHP | <p>I would like to know how can I add comma's to numbers. To make my question simple.</p>
<p>I would like to change this:</p>
<pre><code>1210 views
</code></pre>
<p>To:</p>
<pre><code>1,210 views
</code></pre>
<p>and :</p>
<pre><code>14301
</code></pre>
<p>to</p>
<pre><code>14,301
</code></pre>
<p>and so on for larger numbers. Is it possible with a php function?</p> | 4,582,575 | 6 | 0 | null | 2011-01-03 06:49:01.96 UTC | 10 | 2022-05-12 08:07:21.877 UTC | 2011-03-26 00:10:03.443 UTC | null | 385,273 | null | 77,762 | null | 1 | 72 | php | 103,881 | <p>from the php manual <a href="http://php.net/manual/en/function.number-format.php" rel="noreferrer">http://php.net/manual/en/function.number-format.php</a></p>
<p>I'm assuming you want the english format.</p>
<pre><code><?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation with a decimal point and without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
</code></pre>
<p>my 2 cents</p> |
4,100,022 | php validate integer | <p>I`m wonder why this not working</p>
<pre><code> echo gettype($_GET['id']); //returns string
if(is_int($_GET['id']))
{
echo 'Integer';
}
</code></pre>
<p>How to validate data passing from GET/POST if it is integer ?</p> | 4,100,065 | 7 | 0 | null | 2010-11-04 18:37:51.163 UTC | 8 | 2015-01-19 17:58:59.73 UTC | null | null | null | null | 497,577 | null | 1 | 20 | php | 40,917 | <p>The <a href="http://php.net/manual/en/function.is-int.php" rel="noreferrer"><strong>manual</strong></a> says:</p>
<blockquote>
<p>To test if a variable is a number or a
numeric string (such as form input,
which is always a string), you must
use is_numeric().</p>
</blockquote>
<p>Alternative you can use the regex based test as:</p>
<pre><code>if(preg_match('/^\d+$/',$_GET['id'])) {
// valid input.
} else {
// invalid input.
}
</code></pre> |
4,742,210 | implementing debounce in Java | <p>For some code I'm writing I could use a nice general implementation of <code>debounce</code> in Java.</p>
<pre><code>public interface Callback {
public void call(Object arg);
}
class Debouncer implements Callback {
public Debouncer(Callback c, int interval) { ... }
public void call(Object arg) {
// should forward calls with the same arguments to the callback c
// but batch multiple calls inside `interval` to a single one
}
}
</code></pre>
<p>When <code>call()</code> is called multiple times in <code>interval</code> milliseconds with the same argument the callback function should be called exactly once.</p>
<p>A visualization:</p>
<pre><code>Debouncer#call xxx x xxxxxxx xxxxxxxxxxxxxxx
Callback#call x x x (interval is 2)
</code></pre>
<ul>
<li>Does (something like) this exist already in some Java standard library?</li>
<li>How would you implement that?</li>
</ul> | 20,978,973 | 9 | 2 | null | 2011-01-20 00:10:10.453 UTC | 11 | 2021-06-04 09:26:15.343 UTC | null | null | null | null | 55,534 | null | 1 | 29 | java|algorithm | 24,372 | <p>Please consider the following thread safe solution. Note that the lock granularity is on the key level, so that only calls on the same key block each other. It also handles the case of an expiration on key K which occurs while call(K) is called.</p>
<pre><code>public class Debouncer <T> {
private final ScheduledExecutorService sched = Executors.newScheduledThreadPool(1);
private final ConcurrentHashMap<T, TimerTask> delayedMap = new ConcurrentHashMap<T, TimerTask>();
private final Callback<T> callback;
private final int interval;
public Debouncer(Callback<T> c, int interval) {
this.callback = c;
this.interval = interval;
}
public void call(T key) {
TimerTask task = new TimerTask(key);
TimerTask prev;
do {
prev = delayedMap.putIfAbsent(key, task);
if (prev == null)
sched.schedule(task, interval, TimeUnit.MILLISECONDS);
} while (prev != null && !prev.extend()); // Exit only if new task was added to map, or existing task was extended successfully
}
public void terminate() {
sched.shutdownNow();
}
// The task that wakes up when the wait time elapses
private class TimerTask implements Runnable {
private final T key;
private long dueTime;
private final Object lock = new Object();
public TimerTask(T key) {
this.key = key;
extend();
}
public boolean extend() {
synchronized (lock) {
if (dueTime < 0) // Task has been shutdown
return false;
dueTime = System.currentTimeMillis() + interval;
return true;
}
}
public void run() {
synchronized (lock) {
long remaining = dueTime - System.currentTimeMillis();
if (remaining > 0) { // Re-schedule task
sched.schedule(this, remaining, TimeUnit.MILLISECONDS);
} else { // Mark as terminated and invoke callback
dueTime = -1;
try {
callback.call(key);
} finally {
delayedMap.remove(key);
}
}
}
}
}
</code></pre>
<p>and callback interface:</p>
<pre><code>public interface Callback<T> {
public void call(T t);
}
</code></pre> |
4,749,585 | What is the meaning of XOR in x86 assembly? | <p>I'm getting into assembly and I keep running into xor, for example:</p>
<pre><code>xor ax, ax
</code></pre>
<p>Does it just clear the register's value?</p> | 4,749,620 | 11 | 2 | null | 2011-01-20 16:14:22.763 UTC | 13 | 2016-02-01 06:25:45.047 UTC | 2015-07-08 15:08:56.12 UTC | null | 895,245 | null | 362,857 | null | 1 | 51 | assembly|xor | 112,422 | <p><code>A XOR B</code> in english would be translated as "are A and B not equal". So <code>xor ax, ax</code> will set <code>ax</code> to zero since ax is always equal to itself.</p>
<pre><code>A B | A XOR B
0 0 | 0
1 0 | 1
0 1 | 1
1 1 | 0
</code></pre> |
14,695,805 | How to print everything from an struct array in c++? | <p>I have a structured a data type called bookStruct and books is the name of the variable associated with the bookStruct data type. book[10] is the array that is 10 characters long and has 4 characters of data, meaning book[0] to book [3] have datas in them when the rest are empty (o values). Now I want to print the datas that are availabe already in the array and not print the ones that are empty otherwise 0. I tried the below code, with no luck.What am I doing wrong here?</p>
<pre><code>for (int i=0;i<MAX_BOOKS && books[i]!='\0';i++)
{
cout << "Book Title: " << books[i].bookTitle << endl;
cout << "Total Pages: " << books[i].bookPageN << endl;
cout << "Book Review: " << books[i].bookReview << endl;
cout << "Book Price: " << books[i].bookPrice<< "\n\n" << endl;
}
</code></pre>
<p>here is the declaration for book struct</p>
<pre><code>struct bookStruct
{
string bookTitle;
int bookPageN;
int bookReview;
float bookPrice;
};
bookStruct books[10];
</code></pre> | 14,695,932 | 3 | 14 | null | 2013-02-04 21:16:52.04 UTC | 2 | 2022-07-28 06:00:09.88 UTC | 2013-02-04 21:25:10.903 UTC | user2017078 | null | user2017078 | null | null | 1 | 8 | c++|struct | 47,399 | <p>It's a little hard to tell what's being asked here. You see, it's quite easy to just keep count of how many books you have stored:</p>
<pre><code>int numBooks = 0;
</code></pre>
<p>When you add a book, you increment <code>numBooks</code> up until <code>MAX_BOOKS</code>.</p>
<pre><code>for( int i=0; i<numBooks; i++ ) ...
</code></pre>
<p>If you don't want to do that, you certainly can't test <code>books[i] != '\0'</code> because that is testing the struct against a single character.</p>
<p>Instead, you might want to test <code>books[i].bookTitle.size() != 0</code></p>
<p>(or indeed <code>!books[i].bookTitle.empty()</code>).</p>
<pre><code>for( int i=0; i<MAX_BOOKS && !books[i].bookTitle.empty(); i++ ) ...
</code></pre>
<p>Another alternative is to store books in a <code>vector</code> instead of an array, so you don't have to worry about maximum counts and current counts. The vector can shrink and grow for you.</p>
<pre><code>vector<bookStruct> books;
...
for( int i = 0; i < books.size(); i++ ) ...
</code></pre> |
14,601,430 | How to run a c program in bash script and give it 2 arguments? | <p>I have a program in C, which takes 2 arguments, filename and text. I want to write a script in bash, which also take 2 arguments, path and file extension, will iterate through all files in given path and give to my program in C as argument files with the givenextension only and text.</p>
<p>Heres my program in C, nothing special really:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if(argc < 3)
{
fprintf(stderr, "Give 2 args!\n");
exit(-1);
}
char *arg1 = argv[1];
char *arg2 = argv[2];
fprintf(stdout, "You gave: %s, %s\n", arg1, arg2);
return 0;
}
</code></pre>
<p>and my bash script:</p>
<pre><code>#!/bin/bash
path=$1
ext=$2
text=$3
for file in $path/*.$ext
do
./app |
{
echo $file
echo $text
}
done
</code></pre>
<p>I use it like this: <code>./script /tmp txt hello</code> and it should give as arguments all <code>txt</code> files from <code>/tmp</code> and 'hello' as text to my C program. No it only shows <code>Give 2 args!</code> :( Please, help. </p> | 14,601,483 | 3 | 0 | null | 2013-01-30 10:13:23.583 UTC | 1 | 2013-01-30 10:15:57.037 UTC | null | null | null | null | 1,612,090 | null | 1 | 8 | c|bash|shell | 42,300 | <p>Right now you're not actually passing any arguments to the program in your script.</p>
<p>Just pass the arguments normally:</p>
<pre><code>./app "$file" "$text"
</code></pre>
<p>I put the arguments in double-quotes to make the shell see the variables as single arguments, in case they contain spaces.</p> |
14,446,951 | How to intercept and manipulate a Internet Explorer popup with VBA | <p><strong>Language/Software:</strong></p>
<p>The language is VBA. The application is Access 2003 (I also can use Excel) and Internet Explorer (on Windows XP/Seven).</p>
<p><strong>The problem:</strong></p>
<p>I'm developing a Access macro which opens and manipulates a intranet site of the enterprise where I work. </p>
<p>I can create new IE windows and fill data in the forms, but I need to be able of intercept and manipulate other IE windows, such as popups, which opens when I click on a link, when I choose an option of a select element or when the page is loaded.</p> | 14,470,224 | 1 | 4 | null | 2013-01-21 20:47:46.08 UTC | 8 | 2017-06-19 13:05:45.37 UTC | 2014-02-07 09:15:25.86 UTC | null | 2,060,725 | null | 1,720,294 | null | 1 | 10 | internet-explorer|vba|dom|automation|popup | 33,617 | <p>Here's some code I use to get an IE window from it's title. It's split into two functions because one of my users was having an extremely odd problem where an error was not being caught properly. You might (probably will) be able to move the body of the private function into the public function. </p>
<p>Additionally, you'll need to set a reference to Microsoft Internet Controls (this is either shdocvw.dll or ieframe.dll, depending on your version of Windows) and I'd recommend setting a reference to Microsoft HTML Object Library to make it easier to traverse the DOM once you have your IE object.</p>
<pre><code>Function oGetIEWindowFromTitle(sTitle As String, _
Optional bCaseSensitive As Boolean = False, _
Optional bExact As Boolean = False) As SHDocVw.InternetExplorer
Dim objShellWindows As New SHDocVw.ShellWindows
Dim found As Boolean
Dim startTime As Single
found = False
'Loop through shell windows
For Each oGetIEWindowFromTitle In objShellWindows
found = oGetIEWindowFromTitleHandler(oGetIEWindowFromTitle, sTitle, bCaseSensitive, bExact)
If found Then Exit For
Next
'Check whether a window was found
If Not found Then
Set oGetIEWindowFromTitle = Nothing
Else
pauseUntilIEReady oGetIEWindowFromTitle
End If
End Function
Private Function oGetIEWindowFromTitleHandler(win As SHDocVw.InternetExplorer, _
sTitle As String, _
bCaseSensitive As Boolean, _
bExact As Boolean) As Boolean
oGetIEWindowFromTitleHandler = False
On Error GoTo handler
'If the document is of type HTMLDocument, it is an IE window
If TypeName(win.Document) = "HTMLDocument" Then
'Check whether the title contains the passed title
If bExact Then
If (win.Document.title = sTitle) Or ((Not bCaseSensitive) And (LCase(sTitle) = LCase(win.Document.title))) Then oGetIEWindowFromTitleHandler = True
Else
If InStr(1, win.Document.title, sTitle) Or ((Not bCaseSensitive) And (InStr(1, LCase(win.Document.title), LCase(sTitle), vbTextCompare) <> 0)) Then oGetIEWindowFromTitleHandler = True
End If
End If
handler:
'We assume here that if an error is raised it's because
'the window is not of the correct type. Therefore we
'simply ignore it and carry on.
End Function
</code></pre>
<p>Use the above code as follows:</p>
<pre><code>Sub test()
Dim ie As SHDocVw.InternetExplorer
Dim doc As HTMLDocument 'If you have a reference to the HTML Object Library
'Dim doc as Object 'If you do not have a reference to the HTML Object Library
' Change the title here as required
Set ie = oGetIEWindowFromTitle("My popup window")
Set doc = ie.Document
Debug.Print doc.getElementsByTagName("body").Item(0).innerText
End Sub
</code></pre>
<p>You can find a window from almost any property of the window, or it's document contents. If you're struggling with this, please comment :).</p> |
14,413,404 | C# for loop increment by 2 trouble | <p>This algorithm is about to store strings from Array A to Array B by storing "A", "B" to Index 8 and Index 9
I really initiate to make the array size of B to be 10 because later I will put some other things there.</p>
<p>My partial code:</p>
<pre><code>string[] A = new string[]{"A","B"}
string[] B = new string[10];
int count;
for(count = 0; count < A.length; count++)
{
B[count] = A[count]
}
</code></pre> | 14,413,535 | 2 | 3 | null | 2013-01-19 10:33:06.763 UTC | 1 | 2016-07-27 16:18:22.723 UTC | 2016-07-27 16:18:22.723 UTC | null | 2,256,028 | null | 1,944,787 | null | 1 | 13 | c#-4.0 | 81,931 | <p>So you want to increment every index with 2:</p>
<pre><code>string[] A = new string[] { "A", "B", "C", "D" };
string[] B = new string[A.Length + 2];
for (int i = 0; i < A.Length; i++)
{
B[i + 2] = A[i];
}
</code></pre>
<p><a href="http://ideone.com/8brFRU"><strong>Demo</strong></a></p>
<pre><code>Index: 0 Value:
Index: 1 Value:
Index: 2 Value: A
Index: 3 Value: B
Index: 4 Value: C
Index: 5 Value: D
</code></pre>
<p><strong>Edit</strong>: So you want to start with index 0 in B and always leave a gap?</p>
<pre><code>string[] A = new string[] { "A", "B", "C", "D" };
string[] B = new string[A.Length * 2 + 2]; // you wanted to add something other as well
for (int i = 0; i/2 < A.Length; i+=2)
{
B[i] = A[i / 2];
}
</code></pre>
<p><a href="http://ideone.com/fZy4yz"><strong>Demo</strong></a></p>
<pre><code>Index: 0 Value: A
Index: 1 Value:
Index: 2 Value: B
Index: 3 Value:
Index: 4 Value: C
Index: 5 Value:
Index: 6 Value: D
Index: 7 Value:
Index: 8 Value:
Index: 9 Value:
</code></pre>
<p><strong>Update</strong> " Is there any alternative coding aside from this?"</p>
<p>You can use Linq, although it would be less readable and efficient than a simple loop:</p>
<pre><code>String[] Bs = Enumerable.Range(0, A.Length * 2 + 2) // since you want two empty places at the end
.Select((s, i) => i % 2 == 0 && i / 2 < A.Length ? A[i / 2] : null)
.ToArray();
</code></pre>
<p>Final <strong>Update</strong> according to your last comment(<em>start with index 1 in B</em>):</p>
<pre><code>for (int i = 1; (i-1) / 2 < A.Length; i += 2)
{
B[i] = A[(i-1) / 2];
}
</code></pre>
<p><a href="http://ideone.com/OWkZyz"><strong>Demo</strong></a></p>
<pre><code>Index: 0 Value:
Index: 1 Value: A
Index: 2 Value:
Index: 3 Value: B
Index: 4 Value:
Index: 5 Value: C
Index: 6 Value:
Index: 7 Value: D
Index: 8 Value:
Index: 9 Value
</code></pre> |
14,746,497 | How to add attributes to a label generated with Zend/Form in Zend framework 2 | <p>I'm adding forms to my page using Zend/Form.</p>
<p>I'm adding elements by defining them as follows: </p>
<pre><code> $this->add(array(
'name' => 'value',
'attributes' => array(
'type' => 'text',
'id' => 'value',
'autocomplete' => 'off',
'placeholder' => 'Cost',
),
'options' => array(
'label' => 'Cost',
),
));
</code></pre>
<p>As you can see there is a 'label' => 'cost' node, this generated a label to go with the input element. </p>
<p>How do I add classes, attributes to this label ? </p> | 14,746,670 | 4 | 0 | null | 2013-02-07 08:14:45.703 UTC | 8 | 2017-10-24 20:14:50.463 UTC | 2017-10-24 20:14:50.463 UTC | null | 2,883,328 | null | 1,141,800 | null | 1 | 24 | php|forms|zend-framework2|label|zend-form2 | 23,486 | <p>Please try this, i haven't tested or used this, but going by the source it should function properly:</p>
<pre><code>$this->add(array(
'name' => 'value',
'attributes' => array(),
'options' => array(
'label_attributes' => array(
'class' => 'mycss classes'
),
// more options
),
));
</code></pre>
<p>If this does not function, please leave me a comment. If it won't function, it is not possible using this approach, since the <code>FormLabel</code> restricts the <code>validAttributes</code> quite a bit:</p>
<pre><code>protected $validTagAttributes = array(
'for' => true,
'form' => true,
);
</code></pre> |
14,414,832 | Why use initializer_list instead of vector in parameters? | <p>What is the actual benefit and purpose of <code>initializer_list</code>, for unknown number of parameters? Why not just use <code>vector</code> and be done with it?</p>
<p>In fact, it sounds like just a <code>vector</code> with another name. Why bother?</p>
<p>The only "benefit" I see of <code>initializer_list</code> is that it has <code>const</code> elements, but that doesn't seem to be a reason enough to invent this whole new type. (You can just use a <code>const vector</code> after all.)</p>
<p>So, what am I mising?</p> | 14,414,905 | 3 | 7 | null | 2013-01-19 13:26:13.83 UTC | 20 | 2015-09-17 15:59:43.61 UTC | null | null | null | null | 1,859,852 | null | 1 | 50 | c++ | 20,169 | <p>It is a sort of contract between the programmer and the compiler. The programmer says <code>{1,2,3,4}</code>, and the compiler creates an object of type <code>initializer_list<int></code> out of it, containing the same sequence of elements in it. This contract is a requirement imposed by the language specification on the compiler implementation.</p>
<p>That means, it is not the programmer who creates manually such an object but it is the compiler which creates the object, and pass that object to function which takes <code>initializer_list<int></code> as argument. </p>
<p>The <code>std::vector</code> implementation takes advantage of this contract, and therefore it defines a constructor which takes <code>initializer_list<T></code> as argument, so that it could initialize itself with the elements in the initializer-list.</p>
<p>Now <strong>suppose for a while</strong> that the <code>std::vector</code> doesn't have any constructor that takes <code>std::initializer_list<T></code> as argument, then you would get this:</p>
<pre><code> void f(std::initializer_list<int> const &items);
void g(std::vector<int> const &items);
f({1,2,3,4}); //okay
g({1,2,3,4}); //error (as per the assumption)
</code></pre>
<p>As per the assumption, since <code>std::vector</code> doesn't have constructor that takes <code>std::initializer_list<T></code> as argument, which <em>implies</em> you cannot pass <code>{1,2,3,4}</code> as argument to <code>g()</code> as shown above, because the compiler <em>cannot</em> create an instance of <code>std::vector</code> out of the expression <code>{1,2,3,4}</code> <strong>directly</strong>. It is because no such contract is ever made between programmer and the compiler, and imposed by the language. It is <em>through</em> <code>std::initializer_list</code>, the <code>std::vector</code> is able to create itself out of expression <code>{1,2,3,4}</code>. </p>
<p>Now you will understand that <code>std::initializer_list</code> can be used wherever you need an expression of the form of <code>{value1, value2, ...., valueN}</code>. It is why other containers from the Standard library also define constructor that takes <code>std::initializer_list</code> as argument. In this way, no container depends on any other container for construction from expressions of the form of <code>{value1, value2, ...., valueN}</code>.</p>
<p>Hope that helps.</p> |
14,693,100 | Pass args for script when going thru pipe | <p>I have this example shell script:</p>
<pre><code>echo /$1/
</code></pre>
<p>So I may call</p>
<pre><code>$ . ./script 5
# output: /5/
</code></pre>
<p>I want to pipe the script into sh(ell), but can I pass the arg too ?</p>
<pre><code>cat script | sh
# output: //
</code></pre> | 14,693,303 | 3 | 0 | null | 2013-02-04 18:28:46.137 UTC | 9 | 2021-05-27 20:54:15.033 UTC | null | null | null | null | 114,226 | null | 1 | 53 | bash | 19,768 | <p>You can pass arguments to the shell using the <code>-s</code> option:</p>
<pre><code>cat script | bash -s 5
</code></pre> |
14,374,726 | postgresql - can't create database - OperationalError: source database "template1" is being accessed by other users | <p>I logged in to source database template1 and now I can't create database.
When I try to create database, I get this error:</p>
<pre><code>OperationalError: source database "template1" is being accessed by other users
DETAIL: There are 5 other session(s) using the database.
</code></pre>
<p>Every time I login to template1, I use 'exit' command to logout, but as you can see it does not logout and number of sessions increases everytime I login. Is there a way to force disconnect every connection to template1 that logged in now?</p> | 14,375,832 | 19 | 3 | null | 2013-01-17 08:18:04.85 UTC | 7 | 2022-08-17 22:53:32.947 UTC | null | null | null | null | 1,455,384 | null | 1 | 59 | postgresql|postgresql-8.4 | 67,271 | <p>This helped me solve my problem:</p>
<pre><code>SELECT *, pg_terminate_backend(procpid)
FROM pg_stat_activity
WHERE usename='username';
--Use pid if PostgreSQL version 9.2 or above.
</code></pre>
<p>I terminated all active connections to template1 and could create database normally</p> |
14,588,727 | Can not deserialize instance of java.util.ArrayList out of VALUE_STRING | <p>I have a REST service built with Jersey and deployed in the AppEngine. The REST service implements the verb PUT that consumes an <code>application/json</code> media type. The data binding is performed by Jackson.</p>
<p>The verb consumes an enterprise-departments relation represented in JSON as </p>
<pre><code>{"name":"myEnterprise", "departments":["HR","IT","SC"]}
</code></pre>
<p>On the client side, I use gson to convert the JSON representation into a java object. Then, I pass the object to my REST service and it works fine.</p>
<p><strong>Problem:</strong></p>
<p>When my JSON representation has only one item in the collection</p>
<pre><code>{"name":"myEnterprise", "departments":["HR"]}
</code></pre>
<p>the service cannot deserialize the object.</p>
<pre><code>ATTENTION: /enterprise/enterprise: org.codehaus.jackson.map.JsonMappingException:
Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token at
[Source: org.mortbay.jetty.HttpParser$Input@5a9c5842; line: 1, column: 2
</code></pre>
<p>As reported by other users, the solution is to add the flag <code>ACCEPT_SINGLE_VALUE_AS_ARRAY</code> (e.g., <a href="https://stackoverflow.com/questions/14319573/jersey-can-not-deserialize-instance-of-arraylist-out-of-string">Jersey: Can not deserialize instance of ArrayList out of String</a>). Nevertheless, I am not controlling an <code>ObjectMapper</code> because in the service side it is transparently made by Jackson.</p>
<p><strong>Question:</strong></p>
<p>Is there a way to configure the <code>ObjectMapper</code> on the service side to enable <code>ACCEPT_SINGLE_VALUE_AS_ARRAY</code>? annotations? <code>web.xml</code>?</p>
<p><strong>Code details</strong></p>
<p>Java object:</p>
<pre><code>@XmlRootElement
public class Enterprise {
private String name;
private List<String> departments;
public Enterprise() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getDepartments() {
return departments;
}
public void setDepartments(List<String> departments) {
this.departments = departments;
}
}
</code></pre>
<p>The REST service side:</p>
<pre><code> @PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/enterprise")
public Response putEnterprise(Enterprise enterprise,
@Context HttpServletRequest req){
...
}
</code></pre>
<p>Client side:</p>
<pre><code>...
String jsonString = "{\"name\":\"myEnterprise\", \"departments\":[\"HR\"]}";
Enterprise enterprise = gson.fromJson(jsonString, Enterprise.class);
System.out.println(gson.toJson(enterprise));
response = webResource
.type(MediaType.APPLICATION_JSON)
.put(ClientResponse.class,enterprise);
if (response.getStatus() >= 400) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
...
</code></pre> | 16,071,898 | 5 | 2 | null | 2013-01-29 17:30:16.827 UTC | 10 | 2020-09-20 07:55:27.303 UTC | 2019-11-08 08:40:00.427 UTC | null | 3,657,460 | null | 2,022,175 | null | 1 | 68 | java|json|arraylist|jackson|json-deserialization | 227,616 | <p>This is the solution for my old question:</p>
<p>I implemented my own <code>ContextResolver</code> in order to enable the <code>DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY</code> feature.</p>
<pre><code>package org.lig.hadas.services.mapper;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
@Produces(MediaType.APPLICATION_JSON)
@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper>
{
ObjectMapper mapper;
public ObjectMapperProvider(){
mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
}
@Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}
</code></pre>
<p>And in the <code>web.xml</code> I registered my package into the servlet definition...</p>
<pre><code><servlet>
<servlet-name>...</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>...;org.lig.hadas.services.mapper</param-value>
</init-param>
...
</servlet>
</code></pre>
<p>... all the rest is transparently done by jersey/jackson.</p> |
14,684,913 | Disabling animation in ViewPager | <p>I'd like to disable all the animations for the transitions in my custom <code>ViewPager</code>.
This view pager contains four tabs -and each tab loads a <code>Fragment</code>- and what the view pager does is to switch the tabs: for example first tab is the index, second is map, etc.</p>
<p>The problem is that if, being the first tab chosen, I click on the fourth tab, I can see how the <code>ViewPager</code> goes through the second and third tab and stops on the fourth, and I don't want that to happen.</p>
<p>I tried to disable all the animations for this <code>ViewPager</code> trying to use a <code>setAnimation</code> to <code>null</code> every time the user chooses a new tab to be displayed, but it still doesn't work.</p>
<p>Any idea to achieve this, please?
Thanks a lot in advance!</p>
<p>EDIT: I also tried to override <code>onCreateAnimation</code> for each <code>Fragment</code> but still not working</p> | 14,685,515 | 5 | 3 | null | 2013-02-04 10:36:25.337 UTC | 11 | 2022-03-30 05:26:29.06 UTC | null | null | null | null | 257,948 | null | 1 | 69 | android|animation|android-viewpager | 40,942 | <p>I finally found out: the issue can be solved by just calling the <code>mViewPager.setCurrentItem(position)</code> with an extra parameter to <code>false</code>, which is the smooth scroll for the <code>ViewPager</code>.
After this, the scroll will be done without any smoothing and thus the animations won't be seen.</p> |
14,436,155 | how to create inline style with :before and :after | <p>I generated a bubble chat thingy from <a href="http://www.ilikepixels.co.uk/drop/bubbler/">http://www.ilikepixels.co.uk/drop/bubbler/</a></p>
<p>In my page I put a number inside of it</p>
<pre><code>.bubble {
position: relative;
width: 20px;
height: 15px;
padding: 0;
background: #FFF;
border: 1px solid #000;
border-radius: 5px;
}
.bubble:after {
content: "";
position: absolute;
top: 4px;
left: -4px;
border-style: solid;
border-width: 3px 4px 3px 0;
border-color: transparent #FFF;
display: block;
width: 0;
z-index: 1;
}
.bubble:before {
content: "";
position: absolute;
top: 4px;
left: -5px;
border-style: solid;
border-width: 3px 4px 3px 0;
border-color: transparent #000;
display: block;
width: 0;
z-index: 0;
}
</code></pre>
<p>I want the <code>background-color</code> of the bubble to change according to the number inside of it via <code>rgb</code></p>
<p>so if my div is</p>
<pre><code><div class="bubble" style="background-color: rgb(100,255,255);"> 100 </div>
</code></pre>
<p>I want the color to be <code>rgb(100,255,255)</code></p>
<p>The thing is this doesn't affect the triangle.</p>
<p>How do I write the inline css so it will include the :before and :after?</p> | 14,436,745 | 5 | 0 | null | 2013-01-21 09:59:01.523 UTC | 19 | 2021-06-08 23:08:28.203 UTC | 2013-01-21 10:27:31.043 UTC | null | 1,574,198 | null | 972,789 | null | 1 | 101 | css|inline | 164,313 | <p>You can't. With inline styles you are targeting the element directly. You can't use other selectors there.</p>
<p>What you can do however is define different classes in your stylesheet that define different colours and then add the class to the element.</p> |
2,437,010 | How to get objects to react to touches in Cocos2D? | <p>Alright, so I'm starting to learn more about Coco2D, but I'm kinda frusterated. A lot of the tutorials I have found are for outdated versions of the code, so when I look through and see how they do certain things, I can't translate it into my own program, because a lot has changed. With that being said, I am working in the latest version of Coco2d, version 0.99.</p>
<p>What I want to do is create a sprite on the screen (Done) and then when I touch that sprite, I can have "something" happen. For now, let's just make an alert go off. Now, I got this code working with the help of a friend. Here is the header file:</p>
<pre><code>// When you import this file, you import all the cocos2d classes
#import "cocos2d.h"
// HelloWorld Layer
@interface HelloWorld : CCLayer
{
CGRect spRect;
}
// returns a Scene that contains the HelloWorld as the only child
+(id) scene;
@end
</code></pre>
<p>And here is the implementation file:</p>
<pre><code>//
// cocos2d Hello World example
// http://www.cocos2d-iphone.org
//
// Import the interfaces
#import "HelloWorldScene.h"
#import "CustomCCNode.h"
// HelloWorld implementation
@implementation HelloWorld
+(id) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorld *layer = [HelloWorld node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
// on "init" you need to initialize your instance
-(id) init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init] )) {
// create and initialize a Label
CCLabel* label = [CCLabel labelWithString:@"Hello World" fontName:@"Times New Roman" fontSize:64];
// ask director the the window size
CGSize size = [[CCDirector sharedDirector] winSize];
// position the label on the center of the screen
label.position = ccp( size.width /2 , size.height/2 );
// add the label as a child to this Layer
[self addChild: label];
CCSprite *sp = [CCSprite spriteWithFile:@"test2.png"];
sp.position = ccp(300,200);
[self addChild:sp];
float w = [sp contentSize].width;
float h = [sp contentSize].height;
CGPoint aPoint = CGPointMake([sp position].x - (w/2), [sp position].y - (h/2));
spRect = CGRectMake(aPoint.x, aPoint.y, w, h);
CCSprite *sprite2 = [CCSprite spriteWithFile:@"test3.png"];
sprite2.position = ccp(100,100);
[self addChild:sprite2];
//[self registerWithTouchDispatcher];
self.isTouchEnabled = YES;
}
return self;
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
// in case you have something to dealloc, do it in this method
// in this particular example nothing needs to be released.
// cocos2d will automatically release all the children (Label)
// don't forget to call "super dealloc"
[super dealloc];
}
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
//CGPoint location = [[CCDirector sharedDirector] convertCoordinate:[touch locationInView:touch.view]];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
if (CGRectContainsPoint(spRect, location)) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Win"
message:@"testing"
delegate:nil cancelButtonTitle:@"okay"
otherButtonTitles:nil];
[alert show];
[alert release];
NSLog(@"TOUCHES");
}
NSLog(@"Touch got");
}
</code></pre>
<p>However, this only works for 1 object, the sprite which I create the CGRect for. I can't do it for 2 sprites, which I was testing. So my question is this: How can I have all sprites on the screen react to the same event when touched?</p>
<p>For my program, the same event needs to be run for all objects of the same type, so that should make it a tad easier. I tried making a subclass of CCNode and over write the method, but that just didn't work at all... so I'm doing something wrong. Help would be appreciated!</p>
<p>Going through the "Touches" project in cocos2D and seeing if I see how they did it. It looks like they made a subclass and overwrote the methods:</p>
<pre><code>- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
</code></pre>
<p>So now I get to figure out why mine doesn't work... hmm...</p> | 2,437,108 | 2 | 0 | null | 2010-03-13 02:14:41.16 UTC | 9 | 2014-04-06 09:46:21.29 UTC | 2014-04-06 09:46:21.29 UTC | null | 3,275,134 | null | 200,567 | null | 1 | 8 | ios|iphone|objective-c|cocoa-touch|cocos2d-iphone | 19,160 | <p>I got it. I had to add some more code to the custom class:</p>
<p>Header File:</p>
<pre><code>//
// CustomCCNode.h
// Coco2dTest2
//
// Created by Ethan Mick on 3/11/10.
// Copyright 2010 Wayfarer. All rights reserved.
//
#import "cocos2d.h"
@interface CustomCCNode : CCSprite <CCTargetedTouchDelegate> {
}
@property (nonatomic, readonly) CGRect rect;
@end
</code></pre>
<p>Implementation:</p>
<pre><code>//
// CustomCCNode.m
// Coco2dTest2
//
// Created by Ethan Mick on 3/11/10.
// Copyright 2010 Wayfarer. All rights reserved.
//
#import "CustomCCNode.h"
#import "cocos2d.h"
@implementation CustomCCNode
- (CGRect)rect
{
CGSize s = [self.texture contentSize];
return CGRectMake(-s.width / 2, -s.height / 2, s.width, s.height);
}
- (BOOL)containsTouchLocation:(UITouch *)touch
{
return CGRectContainsPoint(self.rect, [self convertTouchToNodeSpaceAR:touch]);
}
- (void)onEnter
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
[super onEnter];
}
- (void)onExit
{
[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
[super onExit];
}
- (BOOL)ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
NSLog(@"ccTouchBegan Called");
if ( ![self containsTouchLocation:touch] ) return NO;
NSLog(@"ccTouchBegan returns YES");
return YES;
}
- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
CGPoint touchPoint = [touch locationInView:[touch view]];
touchPoint = [[CCDirector sharedDirector] convertToGL:touchPoint];
NSLog(@"ccTouch Moved is called");
}
- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
NSLog(@"ccTouchEnded is called");
}
@end
</code></pre> |
2,438,065 | How can I invoke a method with an out parameter? | <p>I want expose WebClient.DownloadDataInternal method like below:</p>
<pre><code>[ComVisible(true)]
public class MyWebClient : WebClient
{
private MethodInfo _DownloadDataInternal;
public MyWebClient()
{
_DownloadDataInternal = typeof(WebClient).GetMethod("DownloadDataInternal", BindingFlags.NonPublic | BindingFlags.Instance);
}
public byte[] DownloadDataInternal(Uri address, out WebRequest request)
{
_DownloadDataInternal.Invoke(this, new object[] { address, out request });
}
}
</code></pre>
<p>WebClient.DownloadDataInternal has a out parameter, I don't know how to invoke it.
Help! </p> | 2,438,081 | 2 | 0 | null | 2010-03-13 10:51:57.163 UTC | 11 | 2017-10-29 18:12:57.23 UTC | 2017-10-29 18:12:57.23 UTC | null | 107,625 | null | 285,996 | null | 1 | 48 | c#|reflection|out-parameters | 28,488 | <pre><code>public class MyWebClient : WebClient
{
delegate byte[] DownloadDataInternal(Uri address, out WebRequest request);
DownloadDataInternal downloadDataInternal;
public MyWebClient()
{
downloadDataInternal = (DownloadDataInternal)Delegate.CreateDelegate(
typeof(DownloadDataInternal),
this,
typeof(WebClient).GetMethod(
"DownloadDataInternal",
BindingFlags.NonPublic | BindingFlags.Instance));
}
public byte[] DownloadDataInternal(Uri address, out WebRequest request)
{
return downloadDataInternal(address, out request);
}
}
</code></pre> |
2,440,729 | How can I emulate a get request exactly like a web browser? | <p>There are websites that when I open specific ajax request on browser, I get the resulted page. But when I try to load them with curl, I receive an error from the server.</p>
<p>How can I properly emulate a get request to the server that will simulate a browser?</p>
<p>That is what I am doing:</p>
<pre><code>$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
ini_set('user_agent', 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT
5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
print $result;
</code></pre> | 2,440,753 | 2 | 3 | null | 2010-03-14 00:41:37.46 UTC | 14 | 2020-12-22 16:47:34.743 UTC | 2020-12-22 16:47:34.743 UTC | null | 1,783,163 | null | 80,932 | null | 1 | 58 | php|curl | 121,857 | <p>Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at <a href="http://docs.php.net/function.curl-setopt" rel="noreferrer">http://docs.php.net/function.curl-setopt</a>.<br>
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.</p>
<p>edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.</p>
<pre><code>$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);
</code></pre> |
1,535,443 | EF Query With Conditional Include | <p>I have two tables: a WorkItem table, and a WorkItemNote table. How do I return a WorkItem and all of the WorkItemNotes that meet a certain criteria?</p>
<p>I think this should be simple, almost like a conditional "Include", right?</p> | 1,535,618 | 1 | 0 | null | 2009-10-08 03:18:47.603 UTC | 18 | 2013-08-29 09:12:01.327 UTC | 2013-08-29 09:12:01.327 UTC | null | 96,780 | null | 781 | null | 1 | 22 | entity-framework | 8,596 | <p>I've been planning on writing <a href="http://blogs.msdn.com/alexj/archive/2009/03/26/index-of-tips.aspx" rel="noreferrer">a tip</a> on this but your question beat me to the punch.</p>
<p>Assuming a <code>WorkItem</code> has many <code>WorkItemNotes</code></p>
<p>you can do this:</p>
<pre><code>var intermediary = (from item in ctx.WorkItems
from note in item.Notes
where note.SomeProp == SomeValue
select new {item, note}).AsEnumerable();
</code></pre>
<p>This produces an anonymous element for each <code>WorkItemNote</code> that matches, and holds the corresponding <code>WorkItem</code> too.</p>
<p>EF identity resolution insures that the same <code>WorkItem</code> (by reference) is returned multiple times if it has multiple <code>WorkItemNotes</code> that match the criteria.</p>
<p>I assume that next you want to just get back to just the <code>WorkItems</code>, like this:</p>
<pre><code>var workItems = intermediary.Select(x => x.item).Distinct().ToList();
</code></pre>
<p>Then if you now do this:</p>
<pre><code>foreach(var workItem in workItems)
{
Console.WriteLine(workItem.Notes.Count)
}
</code></pre>
<p>You will see that <code>WorkItemNotes</code> that match the original filter have been added to the Notes collection of each <code>workItem</code>. </p>
<p>This is because of something called Relationship Fixup.</p>
<p>I.e. this gives you what you want conditional include.</p>
<p>Hope this helps</p>
<p><a href="http://twitter.com/adjames" rel="noreferrer">Alex</a></p> |
49,807,952 | How to generate UUIDs in JS or React? | <p>In my <code>React</code> app, I want to do optimistic updates to create a responsive experience for my users.</p>
<p>Having said that I want to send a user entry to my backend with an ID that will be used so that there won't be a different Id for the user's entry next time he/she uses the app. For example, if the user enters a comment, I want to assign its ID with a real <code>UUID</code> and then send it to my API.</p>
<p>I understand <code>JavaScript</code> or <code>React</code> don't really have a built-in way to generate <code>UUID</code>/<code>GUID</code> values. I've seen many articles that produce randomized values that look like <code>UUID</code>/<code>GUID</code>'s but they really are not and I don't want to use them as ID's for user entries.</p>
<p>How do I get real <code>UUID</code>/<code>GUID</code> values in my frontend? Do I call my backend API to get them? I can create an endpoint in my API that spits out 10 or 20 <code>GUID</code>'s at a time and I can store them for future use in my frontend but this sounds a bit absurd.</p>
<p>I don't want to reinvent the wheel here as I'm not the first person to face this scenario. How do I get real <code>UUID</code> values on my frontend?</p> | 49,808,036 | 2 | 3 | null | 2018-04-13 01:20:27.633 UTC | 4 | 2019-12-07 23:03:38.6 UTC | 2019-12-07 23:03:38.6 UTC | null | 3,257,186 | null | 1,705,266 | null | 1 | 22 | javascript|reactjs | 85,822 | <p>You can use the <a href="https://www.npmjs.com/package/uuid" rel="noreferrer">uuid npm package</a>. You probably want to use a v4 UUID. (Previous UUID versions use things like a timestamp or network card MAC address as seeds to the random generator). </p> |
31,405,627 | ui-select multiselect is very slow in displaying the choices | <p>I ran into this problem, and I don't know how to solve it. I have used a <a href="https://github.com/angular-ui/ui-select">ui-select multiselect</a> in my page. First, a http.get request is made to a url which gets the data, then the ui-select choices are populated. The data is big - the length of the data is 2100. This data is to be shown as choices. (The data is fetched at the beginning during the loading of the page and is stored in an array)</p>
<p>But the problem is each time I click on the multiselect to select a choice, it takes 4-5 seconds to populate the list and the page becomes very slow. What do I do to reduce this time?</p>
<p>The choices data is stored in an array, the datatype is array of strings.</p>
<pre><code> <ui-select multiple ng-model="selectedFields.name" style="width: 100%;">
<ui-select-match placeholder="Select fields...">{{$item}}</ui-select-match>
<ui-select-choices repeat="fields in availableFields | filter:$select.search">
{{fields}}
</ui-select-choices>
</ui-select>
</code></pre>
<p>in the controller, </p>
<pre><code>$scope.selectedFields = {};
$scope.selectedFields.name = [];
$scope.init = function() {
$http.get(url)
.success( function(response, status, headers, config) {
availableFields = response;
})
.error( function(err) {
});
};
$scope.init();
</code></pre>
<p>If not this way, is there any other options/choice I can work with which doesn't delay showing the select-choices?</p> | 31,445,605 | 4 | 0 | null | 2015-07-14 11:43:37.81 UTC | 9 | 2017-05-12 08:48:54.223 UTC | 2015-07-15 05:48:23.317 UTC | null | 3,449,335 | null | 3,449,335 | null | 1 | 20 | angularjs|angular-ui|ui-select | 16,189 | <p>This is a known issue in ui-select. I tried the following ways, both work</p>
<p>1) There is a workaround for this - use </p>
<pre><code>| limitTo: 100
</code></pre>
<p>This limits the choice display to 100 but all the choices can be selected. Look at <a href="https://github.com/angular-ui/ui-select/issues/88">this thread</a> for more details.</p>
<p>2) Since some of the time, there is a need to display the entire list in the choices, 1) is not a viable option. I used a different library - <a href="http://angular-js.in/selectize-js/">selectize.js</a>. Here's a <a href="http://plnkr.co/edit/X2YYPX?p=preview">plunker</a> demo given in the page</p> |
31,318,881 | How do you stop Ansible from creating .retry files in the home directory? | <p>When Ansible has problems running plays against a host, it will output the name of the host into a file in the user's home directory ending in '.retry'. These are often not used and just cause clutter, is there a way to turn them off or put them in a different directory?</p> | 31,318,882 | 5 | 0 | null | 2015-07-09 13:25:42.857 UTC | 13 | 2020-12-10 15:01:53.2 UTC | 2020-12-10 15:01:53.2 UTC | null | 213,269 | null | 144,876 | null | 1 | 159 | ansible | 49,783 | <p>There are two options that you can add to the [defaults] section of the ansible.cfg file that will control whether or not .retry files are created and where they are created.</p>
<pre><code>[defaults]
...
retry_files_enabled = True # Create them - the default
retry_files_enabled = False # Do not create them
retry_files_save_path = "~/" # The directory they will go into
# (home directory by default)
</code></pre> |
40,438,784 | Read JSON file with Swift 3 | <p>I have a JSON file called <em>points.json</em>, and a read function like:</p>
<pre><code>private func readJson() {
let file = Bundle.main.path(forResource: "points", ofType: "json")
let data = try? Data(contentsOf: URL(fileURLWithPath: file!))
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
print(jsonData)
}
</code></pre>
<p>It does not work, any help?</p> | 40,438,849 | 2 | 1 | null | 2016-11-05 13:28:09.987 UTC | 9 | 2019-07-06 13:46:37.323 UTC | 2016-11-05 13:42:47.367 UTC | null | 2,227,743 | null | 3,235,247 | null | 1 | 40 | json|swift3 | 46,428 | <p>Your problem here is that you force unwrap the values and in case of an error you can't know where it comes from. </p>
<p>Instead, you should handle errors and safely unwrap your optionals.</p>
<p>And as @vadian rightly notes in his comment, you should use <code>Bundle.main.url</code>.</p>
<pre><code>private func readJson() {
do {
if let file = Bundle.main.url(forResource: "points", withExtension: "json") {
let data = try Data(contentsOf: file)
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [String: Any] {
// json is a dictionary
print(object)
} else if let object = json as? [Any] {
// json is an array
print(object)
} else {
print("JSON is invalid")
}
} else {
print("no file")
}
} catch {
print(error.localizedDescription)
}
}
</code></pre>
<p>When coding in Swift, usually, <code>!</code> is a code smell. Of course there's exceptions (IBOutlets and others) but try to not use force unwrapping with <code>!</code> yourself and always unwrap safely instead.</p> |
27,599,965 | Java better way to delete file if exists | <p>We need to call <code>file.exists()</code> before <code>file.delete()</code> before we can delete a file E.g.</p>
<pre><code> File file = ...;
if (file.exists()){
file.delete();
}
</code></pre>
<p>Currently in all our project we create a static method in some util class to wrap this code. Is there some other way to achieve the same , so that we not need to copy our utils file in every other project.</p> | 27,600,014 | 11 | 0 | null | 2014-12-22 09:35:58.98 UTC | 10 | 2021-05-01 07:04:12.08 UTC | 2014-12-22 09:41:44.567 UTC | null | 4,384,615 | null | 4,384,615 | null | 1 | 73 | java | 141,373 | <p>Starting from Java 7 you can use <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#deleteIfExists%28java.nio.file.Path%29" rel="noreferrer">deleteIfExists</a> that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via <code>toPath</code> method . E.g. <br/></p>
<pre><code>File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block
</code></pre> |
30,140,044 | Deliver the first item immediately, 'debounce' following items | <p>Consider the following use case:</p>
<ul>
<li>need to deliver first item as soon as possible</li>
<li>need to <em>debounce</em> following events with 1 second timeout</li>
</ul>
<p>I ended up implementing custom operator based on <code>OperatorDebounceWithTime</code> then using it like this</p>
<pre><code>.lift(new CustomOperatorDebounceWithTime<>(1, TimeUnit.SECONDS, Schedulers.computation()))
</code></pre>
<p><code>CustomOperatorDebounceWithTime</code> delivers the first item immediately then uses <code>OperatorDebounceWithTime</code> operator's logic to <em>debounce</em> later items.</p>
<p>Is there an easier way to achieve described behavior? Let's skip the <code>compose</code> operator, it doesn't solve the problem. I'm looking for a way to achieve this without implementing custom operators.</p> | 30,145,789 | 15 | 0 | null | 2015-05-09 12:40:11.173 UTC | 6 | 2022-07-30 18:49:00.83 UTC | null | null | null | null | 1,675,568 | null | 1 | 46 | rx-java|rx-android | 17,697 | <p>Update:<br>
From @lopar's comments a better way would be:</p>
<pre><code>Observable.from(items).publish(publishedItems -> publishedItems.limit(1).concatWith(publishedItems.skip(1).debounce(1, TimeUnit.SECONDS)))
</code></pre>
<p>Would something like this work:</p>
<pre><code>String[] items = {"one", "two", "three", "four", "five", "six", "seven", "eight"};
Observable<String> myObservable = Observable.from(items);
Observable.concat(myObservable.first(), myObservable.skip(1).debounce(1, TimeUnit.SECONDS))
.subscribe(s -> System.out.println(s));
</code></pre> |
35,946,868 | Adding custom jars to pyspark in jupyter notebook | <p>I am using the <strong>Jupyter notebook with Pyspark</strong> with the following <strong>docker image</strong>: <a href="https://github.com/jupyter/docker-stacks/tree/master/all-spark-notebook" rel="noreferrer">Jupyter all-spark-notebook</a></p>
<p>Now I would like to write a <strong>pyspark streaming application which consumes messages from Kafka</strong>. In the <a href="http://spark.apache.org/docs/latest/streaming-kafka-integration.html" rel="noreferrer">Spark-Kafka Integration guide</a> they describe how to deploy such an application using spark-submit (it requires linking an external jar - explanation is in <em>3. Deploying</em>). But since I am using Jupyter notebook I never actually run the <code>spark-submit</code> command, I assume it gets run in the back if I press execute.</p>
<p>In the <code>spark-submit</code> command you can specify some parameters, one of them is <code>-jars</code>, but it is not clear to me how I can set this parameter from the notebook (or externally via environment variables?). I am assuming I can link this external jar dynamically via the <code>SparkConf</code> or the <code>SparkContext</code> object. Has anyone experience on how to perform the linking properly from the notebook?</p> | 36,295,208 | 5 | 0 | null | 2016-03-11 17:58:55.75 UTC | 11 | 2020-02-06 03:39:19.573 UTC | 2016-03-29 21:21:34.82 UTC | null | 2,299,864 | null | 2,299,864 | null | 1 | 26 | python-3.x|apache-kafka|pyspark|spark-streaming|jupyter-notebook | 28,475 | <p>I've managed to get it working from within the jupyter notebook which is running form the all-spark container. </p>
<p>I start a python3 notebook in jupyterhub and overwrite the PYSPARK_SUBMIT_ARGS flag as shown below. The Kafka consumer library was downloaded from the maven repository and put in my home directory /home/jovyan:</p>
<pre><code>import os
os.environ['PYSPARK_SUBMIT_ARGS'] =
'--jars /home/jovyan/spark-streaming-kafka-assembly_2.10-1.6.1.jar pyspark-shell'
import pyspark
from pyspark.streaming.kafka import KafkaUtils
from pyspark.streaming import StreamingContext
sc = pyspark.SparkContext()
ssc = StreamingContext(sc,1)
broker = "<my_broker_ip>"
directKafkaStream = KafkaUtils.createDirectStream(ssc, ["test1"],
{"metadata.broker.list": broker})
directKafkaStream.pprint()
ssc.start()
</code></pre>
<p><strong>Note:</strong> Don't forget the pyspark-shell in the environment variables!</p>
<p><strong>Extension:</strong> If you want to include code from spark-packages you can use the --packages flag instead. An example on how to do this in the all-spark-notebook can be found <a href="https://gist.github.com/parente/c95fdaba5a9a066efaab" rel="noreferrer">here</a></p> |
29,720,783 | Projection of mongodb subdocument using C# .NET driver 2.0 | <p>I have the following structure:</p>
<pre><code>public class Category
{
[BsonElement("name")]
public string CategoryName { get; set; }
[BsonDateTimeOptions]
[BsonElement("dateCreated")]
public DateTime DateStamp { get; set; }
[BsonElement("tasks")]
public List<TaskTracker.Task> Task { get; set; }
}
public class Task
{
[BsonElement("name")]
public string TaskName { get; set; }
[BsonElement("body")]
public string TaskBody { get; set; }
}
</code></pre>
<p>I am trying to query a <code>Category</code> to get all the <code>TaskName</code> values and then return them to a list to be displayed in a list box. </p>
<p>I have tried using this query:</p>
<pre><code>var getTasks = Categories.Find<Category>(x => x.CategoryName == catName)
.Project(Builders<Category>.Projection
.Include("tasks.name")
.Exclude("_id"))
.ToListAsync()
.Result;
</code></pre>
<p>But what get returned is: <code>{"tasks": [{"name: "test"}]}</code>. </p>
<p>Is there anyway to just return the string value?</p> | 29,722,097 | 2 | 0 | null | 2015-04-18 17:52:37.287 UTC | 3 | 2019-01-23 09:49:08.233 UTC | 2015-04-18 18:17:30.047 UTC | null | 918,624 | null | 4,578,699 | null | 1 | 15 | c#|.net|mongodb|mongodb-.net-driver | 38,996 | <p>As Avish said, you have to use the aggregation API to get the resulting document to look like you are wanting. However, the driver can make some of that disappear for you if you use the expression tree API for project as you have done for Find. For instance, I believe the following should work for you:</p>
<pre><code>var taskNames = await Categores.Find(x => x.CategoryName == catName)
.Project(x => x.Tasks.Select(y => y.Name))
.ToListAsync();
</code></pre>
<p>This should just bring back an enumerable of strings (<code>tasks.name</code>) for each category. The driver will be inspecting this projection and only pull back the <code>tasks.name</code> field.</p> |
36,607,979 | How to get around property does not exist on 'Object' | <p>I'm new to Typescript, and not sure how to word this question. </p>
<p>I need to access two "possible" properties on an object that is passed in the constructor. I know im missing some checks to see if they are defined, but Typescript is throwing me a "Property does not exist on 'Object'" message. The message appears on the <strong>selector</strong> and <strong>template</strong> returns.</p>
<pre><code>class View {
public options:Object = {};
constructor(options:Object) {
this.options = options;
}
selector ():string {
return this.options.selector;
}
template ():string {
return this.options.template;
}
render ():void {
}
}
</code></pre>
<p>I'm sure its fairly simple, but Typescript is new to me.</p> | 36,608,015 | 2 | 0 | null | 2016-04-13 19:36:29.59 UTC | 8 | 2020-03-21 20:06:21.65 UTC | 2017-07-13 22:18:08.96 UTC | null | 4,409,409 | null | 5,812,315 | null | 1 | 72 | object|typescript | 99,072 | <p>If you use the <code>any</code> type instead of <code>Object</code>, you can access any property without compile errors.</p>
<p>However, I would advise to create an interface that marks the possible properties for that object:</p>
<pre><code>interface Options {
selector?: string
template?: string
}
</code></pre>
<p>Since all of the fields use <code>?:</code>, it means that they might or might not be there. So this works:</p>
<pre><code>function doStuff(o: Options) {
//...
}
doStuff({}) // empty object
doStuff({ selector: "foo" }) // just one of the possible properties
doStuff({ selector: "foo", template: "bar" }) // all props
</code></pre>
<p>If something comes from javascript, you can do something like this:</p>
<pre><code>import isObject from 'lodash/isObject'
const myOptions: Options = isObject(somethingFromJS) // if an object
? (somethingFromJS as Options) // cast it
: {} // else create an empty object
doStuff(myOptions) // this works now
</code></pre>
<p>Of course this solution only works as expected if you are only unsure about the presence of a property not of it's type.</p> |
3,130,911 | tcpdump: localhost to localhost | <p>I write a program that send TCP packets from localhost to localhost. And I want to use tcpdump to capture the packets. But nothing is captured.
My command in Ubuntu:</p>
<pre><code>sudo tcpdump
</code></pre>
<p>What argument shall I add? Thanks!</p> | 3,130,925 | 1 | 1 | null | 2010-06-28 08:15:42.027 UTC | 24 | 2021-12-17 23:56:08.023 UTC | null | null | null | null | 343,606 | null | 1 | 118 | linux|localhost|tcpdump | 92,518 | <pre><code>sudo tcpdump -i lo
</code></pre>
<h3>Notes</h3>
<ul>
<li>If you get <code>tcpdump: lo: No such device exists</code>, get the name by coping it from the output of</li>
</ul>
<pre><code>sudo tcpdump -D
</code></pre>
<p>For example, if the output is as below you need <code>lo0</code> (which is reusult <code>9.</code> here:</p>
<pre><code>1.en0 [Up, Running]
2.p2p0 [Up, Running]
3.awdl0 [Up, Running]
4.llw0 [Up, Running]
5.utun0 [Up, Running]
6.utun1 [Up, Running]
7.utun2 [Up, Running]
8.utun3 [Up, Running]
9.lo0 [Up, Running, Loopback]
</code></pre> |
38,556,579 | Is it possible to type-hint a compiled regex in python? | <p>I would like to use autocompletion for a pre-compiled and stored list of regular expressions, but it doesn't appear that I can import the _sre.SRE_Pattern class, and I can't programmatically feed the obtained type from type() to a comment of the format # type: classname or use it for a return -> classname style hint</p>
<p>Is there a way to explicitly import a class from the _sre.c thing?</p> | 38,935,153 | 1 | 2 | null | 2016-07-24 20:41:47.95 UTC | 1 | 2021-04-08 21:16:28.01 UTC | 2021-04-08 21:16:28.01 UTC | null | 1,698,431 | null | 551,577 | null | 1 | 45 | python|regex|type-hinting | 10,693 | <p>You should use <a href="https://docs.python.org/3/library/typing.html#typing.Pattern" rel="noreferrer"><code>typing.Pattern</code> and <code>typing.Match</code></a> which were specifically added to the typing module to accommodate this use case.</p>
<p>Example:</p>
<pre><code>from typing import Pattern, Match
import re
my_pattern = re.compile("[abc]*") # type: Pattern[str]
my_match = re.match(my_pattern, "abbcab") # type: Match[str]
print(my_match)
</code></pre> |
58,791,938 | C# 8 understanding await using syntax | <p>I have next method:</p>
<pre><code>public async Task<IEnumerable<Quote>> GetQuotesAsync()
{
using var connection = new SqlConnection(_connectionString);
var allQuotes = await connection.QueryAsync<Quote>(@"SELECT [Symbol], [Bid], [Ask], [Digits] FROM [QuoteEngine].[RealtimeData]");
return allQuotes;
}
</code></pre>
<p>Everything fine and clear, connection will be disposed at the end of scope.</p>
<p>But resharper suggests to change it to:</p>
<pre><code>public async Task<IEnumerable<Quote>> GetQuotesAsync()
{
await using var connection = new SqlConnection(_connectionString);
var allQuotes = await connection.QueryAsync<Quote>(@"SELECT [Symbol], [Bid], [Ask], [Digits] FROM [QuoteEngine].[RealtimeData]");
return allQuotes;
}
</code></pre>
<p>It adds await before using and code is compiled successfully. What does it mean and when do we need to do that?</p> | 58,792,016 | 2 | 0 | null | 2019-11-10 18:56:01.473 UTC | 9 | 2021-12-05 17:15:52.163 UTC | 2020-04-09 16:07:52.063 UTC | null | 4,728,685 | null | 1,017,161 | null | 1 | 104 | c#|async-await|resharper|using|c#-8.0 | 41,542 | <p>Similar as <code>using (...)</code> uses <code>IDisposable</code> to clean up resources, <code>await using (...)</code> uses <a href="https://docs.microsoft.com/en-us/dotnet/api/system.iasyncdisposable?view=dotnet-plat-ext-3.0" rel="noreferrer">IAsyncDisposable</a>.
This allows to perform also time-consuming tasks (e.g involving I/O) on cleanup without blocking.</p> |
5,960,731 | Strange behavior of select/dropdown's onchange() JS event when using 'Next' on Mobile Safari Dropdown list item select box | <p>This is a hard one to articulate and I am new to mobile web development so please bear with me:</p>
<p><strong>On my webpage,</strong> I have 3 Nested dropdown lists (Area, Town, Street).</p>
<p>Nested as in, each dropdown's items are modified when the selection in the dropdown above it changes. e.g selecting an <em>Area</em> changes the <em>Town</em> and <em>Street</em> lists and selecting a <em>Town</em> changes the <em>Street</em> list.</p>
<p>I use XMLHTTPRequests in the onchange() javascript event of the dropdowns to fetch and populate the other downdowns. This works fine on Android and Desktop browsers.</p>
<p><strong>On Mobile Safari</strong>, when a drowdown is touched, a list is shown where the user can select items. In addition the selection box has the "Previous/Next/Autofill/Done" buttons to navigate to other form elements.</p>
<p>So the user touches the first dropdown, selects a value and presses the Next button. This causes two problems: </p>
<p><strong>First</strong>, On this action the first dropdown's oncange() event is not triggered reliably! Sometimes it fires sometimes not. </p>
<p>If after selecting an Area, the user touches somewhere else on the webpage or presses the "Done" button then the onchange() is fired normally and the Towns and Streets are populated normally.</p>
<p><strong>Second</strong>, the element that comes into focus when pressing then "Next" button is the dropdown whos elements need to be changed after being fetched. When the onchange() of the previous dropdown does get fired then, either the list is no updated or the items in the select box turn blue and all of them have a tick mark showing that they are all selected..</p>
<p>From what i can tell the problem would be solved if i can disable the Next/Previous buttons in the selection box or somehow fix how the onchange() is fired and the next in focus dropdown's list items are repopulated while it is in focus.</p>
<p>Here is the code (simplified):</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no" />
<title></title>
</head>
<body onload="AppStart();">
<form action="#">
Area:
<select id="ddlArea">
<option value="">-- Select Area -- </option>
<option value="1">Area 1</option>
<option value="2">Area 2</option>
<option value="3">Area 3</option>
<option value="4">Area 4</option>
<option value="5">Area 5</option>
</select>
<br />
Town:
<select id="ddlTown">
<option value="">Please wait ...</option>
</select>
<br />
Street:
<select id="ddlStreet">
<option value="">-- Select Area or Town -- </option>
</select>
<br />
Unit:
<select id="ddlUnit">
<option value="">-- No Street Selected -- </option>
</select>
<script type="text/javascript">
var ddlArea, ddlTown, ddlStreet, ddlUnit;
function AppStart() {
ddlArea = document.getElementById("ddlArea");
ddlTown = document.getElementById("ddlTown");
ddlStreet = document.getElementById("ddlStreet");
ddlUnit = document.getElementById("ddlUnit");
ddlArea.onchange = areaChanged;
ddlTown.onchange = townChanged;
ddlStreet.onchange = streetChanged;
setTimeout(function() { updateTown(""); }, 250);
}
var areaId = "", townId = "", streetId = "", unitId = "";
function areaChanged(e) {
areaId = ddlArea.options[ddlArea.selectedIndex].value
ddlClear(ddlTown, createOption("Please Wait...", ""));
ddlClear(ddlStreet, createOption("Please Wait...", ""));
ddlClear(ddlUnit, createOption("-- No Street Selected --", ""));
setTimeout(function() { updateTown(areaId); }, 500);
setTimeout(function() { updateStreet(areaId, ""); }, 700);
}
function townChanged(e) {
townId = ddlTown.options[ddlTown.selectedIndex].value
ddlClear(ddlStreet, createOption("Please Wait...", ""));
ddlClear(ddlUnit, createOption("-- No Street Selected --", ""));
setTimeout(function() { updateStreet(areaId, townId); }, 400);
}
function streetChanged(e) {
streetId = ddlStreet.options[ddlStreet.selectedIndex].value
ddlClear(ddlUnit, createOption("Please Wait...", ""));
setTimeout(function() { updateUnit(streetId); }, 600);
}
function updateTown(areaID) {
ddlClear(ddlTown, createOption("-- Select Town --", ""));
var items = isNaN(parseInt(areaID)) ? 10 : parseInt(areaID);
if (areaID == "") areaID = "ALL";
for (var i = 0; i < items; i++) {
ddlTown.appendChild(createOption("Town " + (i+1) + ", Area " + areaID, i));
}
}
function updateStreet(areaID, townID) {
ddlClear(ddlStreet, createOption("-- Select Street --", ""));
var items1 = isNaN(parseInt(areaID)) ? 10 : parseInt(areaID);
var items2 = isNaN(parseInt(townID)) ? 10 : parseInt(townID);
var items = items1 + items2;
if (areaID == "") areaID = "ALL";
if (townID = "") townId = "ALL";
for (var i = 0; i < items; i++) {
ddlStreet.appendChild(createOption("Street " + (i + 1) + ", Area " + areaID + ", Town " + townID, i));
}
}
function updateUnit(streetID) {
ddlClear(ddlUnit, createOption("-- Select Unit --", ""));
var items = isNaN(parseInt(streetID)) ? 10 : parseInt(streetID);
if (streetID == "") streetID = "ALL";
for (var i = 0; i < items; i++) {
ddlUnit.appendChild(createOption("Unit " + (i + 1) + ", Street " + streetID, i));
}
}
function ddlClear(Dropdown, option) {
while (Dropdown.options.length > 0) {
try { Dropdown.options[0] = null; } catch (e) { };
}
if (option != null) {
Dropdown.appendChild(option);
}
}
function createOption(text, value) {
var oOption = document.createElement("OPTION");
oOption.innerHTML = text;
oOption.value = value;
return oOption;
}
</script>
</form>
</body>
</html>
</code></pre>
<p>Help. :/</p> | 7,284,325 | 1 | 0 | null | 2011-05-11 07:31:09.86 UTC | 10 | 2011-10-14 19:31:58.233 UTC | 2011-05-11 10:40:50.037 UTC | null | 187,025 | null | 187,025 | null | 1 | 14 | javascript|iphone|web-applications|mobile-safari|mobile-website | 26,885 | <p>I had the same problem on my site. I was able to fix it by manually polling the <code>selectedIndex</code> property on the select control. That way it fires as soon as you "check" the item in the list. Here's a jQuery plugin I wrote to do this:</p>
<pre><code>$.fn.quickChange = function(handler) {
return this.each(function() {
var self = this;
self.qcindex = self.selectedIndex;
var interval;
function handleChange() {
if (self.selectedIndex != self.qcindex) {
self.qcindex = self.selectedIndex;
handler.apply(self);
}
}
$(self).focus(function() {
interval = setInterval(handleChange, 100);
}).blur(function() { window.clearInterval(interval); })
.change(handleChange); //also wire the change event in case the interval technique isn't supported (chrome on android)
});
};
</code></pre>
<p>You use it just like you would use the "change" event. For instance: </p>
<pre><code>$("#mySelect1").quickChange(function() {
var currVal = $(this).val();
//populate mySelect2
});
</code></pre>
<p><strong>Edit</strong>: Android does not focus the select when you tap it to select a new value, but it also does not have the same problem that iphone does. So fix it by also wiring the old <code>change</code> event.</p> |
54,398,579 | Example for transactions in mongodb with GoLang | <p>I need an example to implement transactions in MongoDB with GoLang.</p>
<p>I'm using this golang driver for mongodb </p>
<p><a href="https://github.com/mongodb/mongo-go-driver" rel="noreferrer">https://github.com/mongodb/mongo-go-driver</a></p>
<p>There is no clear documentation for how to implement transactions.</p>
<p>Can anyone help me?</p> | 54,401,731 | 2 | 0 | null | 2019-01-28 09:08:23.85 UTC | 12 | 2021-05-27 13:24:31.523 UTC | null | null | null | null | 2,481,981 | null | 1 | 10 | mongodb|go|transactions | 12,656 | <p>It can be confusing. Below is a simple example.</p>
<pre><code>if session, err = client.StartSession(); err != nil {
t.Fatal(err)
}
if err = session.StartTransaction(); err != nil {
t.Fatal(err)
}
if err = mongo.WithSession(ctx, session, func(sc mongo.SessionContext) error {
if result, err = collection.UpdateOne(sc, bson.M{"_id": id}, update); err != nil {
t.Fatal(err)
}
if result.MatchedCount != 1 || result.ModifiedCount != 1 {
t.Fatal("replace failed, expected 1 but got", result.MatchedCount)
}
if err = session.CommitTransaction(sc); err != nil {
t.Fatal(err)
}
return nil
}); err != nil {
t.Fatal(err)
}
session.EndSession(ctx)
</code></pre>
<p>You can view full <a href="https://github.com/simagix/mongo-go-examples/blob/master/examples/transaction_test.go" rel="noreferrer">examples here</a>.</p> |
25,247,218 | Servlet Filter: How to get all the headers from servletRequest? | <p>Here is how my <code>WebFilter</code> looks like </p>
<pre><code>@WebFilter("/rest/*")
public class AuthTokenValidatorFilter implements Filter {
@Override
public void init(final FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse, final FilterChain filterChain) throws IOException, ServletException {
final Enumeration<String> attributeNames = servletRequest.getAttributeNames();
while (attributeNames.hasMoreElements()) {
System.out.println("{attribute} " + servletRequest.getParameter(attributeNames.nextElement()));
}
final Enumeration<String> parameterNames = servletRequest.getParameterNames();
while (parameterNames.hasMoreElements()) {
System.out.println("{parameter} " + servletRequest.getParameter(parameterNames.nextElement()));
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
</code></pre>
<p>I tried to find out online as to how to get values for <code>HTTP headers</code> coming from request. </p>
<p>I did not find anything, so I tried to enumerate on <code>servletRequest.getAttributeNames()</code> and <code>servletRequest.getParameterNames()</code> without knowing anything, but I do not get any headers.</p>
<p><strong>Question</strong><br>
How can I get all the headers coming from the request?</p> | 25,247,239 | 4 | 0 | null | 2014-08-11 15:44:18.557 UTC | 15 | 2022-07-24 01:08:50.823 UTC | null | null | null | null | 379,235 | null | 1 | 84 | java|jakarta-ee|servlets|servlet-filters | 142,446 | <p>Typecast <code>ServletRequest</code> into <code>HttpServletRequest</code> (only if <code>ServletRequest request</code> is an <code>instanceof</code> <code>HttpServletRequest</code>).</p>
<p>Then you can use <code>HttpServletRequest.getHeader()</code> and <code>HttpServletRequest.getHeaderNames()</code> method.</p>
<p>Something like this:</p>
<pre><code>@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
Enumeration<String> headerNames = httpRequest.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
System.out.println("Header: " + httpRequest.getHeader(headerNames.nextElement()));
}
}
//doFilter
chain.doFilter(httpRequest, response);
}
</code></pre> |
51,947,791 | Javadoc "cannot find symbol" error when using Lombok's @Builder annotation | <p>I have a class looking as below : </p>
<pre><code>@Data
@Builder
public class Foo {
private String param;
/** My custom builder.*/
public static FooBuilder builder(String _param){
return builder().param(_param);
}
}
</code></pre>
<p>I get the following error : </p>
<blockquote>
<p>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.10.4:javadoc (default-cli) on project foo: An error has occurred in JavaDocs report generation:<br>
[ERROR] Exit code: 1 - /home/workspace/foo/src/main/java/com/foo/Foo.java:34: error: cannot find symbol<br>
[ERROR] public static FooBuilder builder(String _param)<br>
[ERROR] ^<br>
[ERROR] symbol: class FooBuilder<br>
[ERROR] location: class Foo</p>
</blockquote> | 51,947,792 | 3 | 0 | null | 2018-08-21 11:32:39.447 UTC | 7 | 2022-03-19 18:39:45.883 UTC | 2019-10-17 08:18:32.433 UTC | null | 1,746,118 | null | 3,817,953 | null | 1 | 30 | java|maven|javadoc|lombok|maven-javadoc-plugin | 12,299 | <p>In order to solve this issue, I have to use Lombok's <code>delombok</code> feature (cf : <a href="https://projectlombok.org/features/delombok" rel="noreferrer">https://projectlombok.org/features/delombok</a>).</p>
<blockquote>
<p>lombok doesn't cover all tools. For example, lombok cannot plug into javadoc ... which run on java sources. Delombok still allows you to use lombok with these tools by preprocessing your java code into java code with all of lombok's transformations already applied. </p>
</blockquote>
<p>I did this using Maven by adding the following plugins : </p>
<pre><code><plugin>
<groupId>org.projectlombok</groupId>
<artifactId>lombok-maven-plugin</artifactId>
<version>1.18.0.0</version>
<configuration>
<sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
<outputDirectory>${delombok.output}</outputDirectory>
<addOutputDirectory>false</addOutputDirectory>
</configuration>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>delombok</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.9</version>
<configuration>
<sourcepath>${delombok.output}</sourcepath>
</configuration>
</plugin>
</code></pre> |
2,450,373 | Set global hotkeys using C# | <p>I need to capture a key press when my program is not in focus. (ie. <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>J</kbd>) and trigger an event in my program.</p>
<p>Thus far i have found this dll that appears to be the correct path"</p>
<pre><code>[DllImport("user32.dll")]private static extern int RegisterHotKey(IntPtr hwnd, int id,int fsModifiers, int vk);
[DllImport("user32.dll")] private static extern int UnregisterHotKey(IntPtr hwnd, int id);
</code></pre> | 27,309,185 | 3 | 4 | 2010-06-19 00:39:31.11 UTC | 2010-03-15 20:47:39.22 UTC | 52 | 2020-12-22 16:53:22.62 UTC | 2017-01-01 09:43:00.56 UTC | null | 1,033,581 | null | 72,136 | null | 1 | 87 | c#|.net|hotkeys | 97,653 | <p>Please note that this code <strong>will not trigger events in console application projects</strong>. You have to use WinForms project for events to fire.</p>
<p>This is the correct code:</p>
<pre><code>public sealed class KeyboardHook : IDisposable
{
// Registers a hot key with Windows.
[DllImport("user32.dll")]
private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);
// Unregisters the hot key with Windows.
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
/// <summary>
/// Represents the window that is used internally to get the messages.
/// </summary>
private class Window : NativeWindow, IDisposable
{
private static int WM_HOTKEY = 0x0312;
public Window()
{
// create the handle for the window.
this.CreateHandle(new CreateParams());
}
/// <summary>
/// Overridden to get the notifications.
/// </summary>
/// <param name="m"></param>
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
// check if we got a hot key pressed.
if (m.Msg == WM_HOTKEY)
{
// get the keys.
Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);
ModifierKeys modifier = (ModifierKeys)((int)m.LParam & 0xFFFF);
// invoke the event to notify the parent.
if (KeyPressed != null)
KeyPressed(this, new KeyPressedEventArgs(modifier, key));
}
}
public event EventHandler<KeyPressedEventArgs> KeyPressed;
#region IDisposable Members
public void Dispose()
{
this.DestroyHandle();
}
#endregion
}
private Window _window = new Window();
private int _currentId;
public KeyboardHook()
{
// register the event of the inner native window.
_window.KeyPressed += delegate(object sender, KeyPressedEventArgs args)
{
if (KeyPressed != null)
KeyPressed(this, args);
};
}
/// <summary>
/// Registers a hot key in the system.
/// </summary>
/// <param name="modifier">The modifiers that are associated with the hot key.</param>
/// <param name="key">The key itself that is associated with the hot key.</param>
public void RegisterHotKey(ModifierKeys modifier, Keys key)
{
// increment the counter.
_currentId = _currentId + 1;
// register the hot key.
if (!RegisterHotKey(_window.Handle, _currentId, (uint)modifier, (uint)key))
throw new InvalidOperationException("Couldn’t register the hot key.");
}
/// <summary>
/// A hot key has been pressed.
/// </summary>
public event EventHandler<KeyPressedEventArgs> KeyPressed;
#region IDisposable Members
public void Dispose()
{
// unregister all the registered hot keys.
for (int i = _currentId; i > 0; i--)
{
UnregisterHotKey(_window.Handle, i);
}
// dispose the inner native window.
_window.Dispose();
}
#endregion
}
/// <summary>
/// Event Args for the event that is fired after the hot key has been pressed.
/// </summary>
public class KeyPressedEventArgs : EventArgs
{
private ModifierKeys _modifier;
private Keys _key;
internal KeyPressedEventArgs(ModifierKeys modifier, Keys key)
{
_modifier = modifier;
_key = key;
}
public ModifierKeys Modifier
{
get { return _modifier; }
}
public Keys Key
{
get { return _key; }
}
}
/// <summary>
/// The enumeration of possible modifiers.
/// </summary>
[Flags]
public enum ModifierKeys : uint
{
Alt = 1,
Control = 2,
Shift = 4,
Win = 8
}
</code></pre>
<p>to use (i had to edit the modifier keys to cast them (modifier)1 (modifier)2 etc</p>
<pre><code>public partial class Form1 : Form
{
KeyboardHook hook = new KeyboardHook();
public Form1()
{
InitializeComponent();
// register the event that is fired after the key press.
hook.KeyPressed +=
new EventHandler<KeyPressedEventArgs>(hook_KeyPressed);
// register the control + alt + F12 combination as hot key.
hook.RegisterHotKey(ModifierKeys.Control | ModifierKeys.Alt,
Keys.F12);
}
void hook_KeyPressed(object sender, KeyPressedEventArgs e)
{
// show the keys pressed in a label.
label1.Text = e.Modifier.ToString() + " + " + e.Key.ToString();
}
}
</code></pre> |
36,378,751 | Services depending on each other | <p>In my Angular 2 app, I have two services that depend on each other (service A calling methods from service B and vice versa).</p>
<p>Here are the relevant code:</p>
<p><code>app.component.ts</code>:</p>
<pre><code>import {Component} from 'angular2/core';
import {TempService} from '../services/tmp';
import {Temp2Service} from '../services/tmp2';
@Component({
selector: 'my-app',
templateUrl: 'app/app/app.component.html',
providers: [TempService, Temp2Service]
})
export class AppComponent { (...) }
</code></pre>
<p>Service 1:</p>
<pre><code>import {Injectable} from 'angular2/core';
import {Temp2Service} from './tmp2';
@Injectable()
export class TempService {
constructor (private _sessionService: Temp2Service) {}
}
</code></pre>
<p>Service 2:</p>
<pre><code>import {Injectable} from 'angular2/core';
import {TempService} from './tmp';
@Injectable()
export class Temp2Service {
constructor (private _sessionService: TempService) {}
}
</code></pre>
<p>Running the app leads to the following error:</p>
<blockquote>
<p>EXCEPTION: Cannot resolve all parameters for
'Temp2Service'(undefined). Make sure that all the parameters are
decorated with Inject or have valid type annotations and that
'Temp2Service' is decorated with Injectable</p>
</blockquote>
<p>When commenting the constructor in one of the services, the app runs fine. So my guess is that the "cross-reference" of the two services is causing the problem.</p>
<p>Do you have an idea what is going wrong here? Or is my approach already wrong?</p> | 36,378,859 | 12 | 1 | null | 2016-04-02 21:12:39.003 UTC | 11 | 2021-11-23 22:04:02.003 UTC | 2019-06-28 21:34:31.883 UTC | null | 3,345,644 | null | 1,313,884 | null | 1 | 82 | angular | 76,290 | <p>This is a called circular dependency. It is not an issue with Angular2 itself. It is not allowed in any language I am aware of. </p>
<p>You will need to refactor your code to remove this circular dependency. Likely you will need to breakup one of these services into new service.</p>
<p>If you follow the single responsibility principle you will find you won't get into circular dependency trap. </p> |
52,631,057 | How to delete existing text from input using Puppeteer? | <p>I'm trying to test amending text in an editable input which contains the title of the current record - and I want to able to test editing such text, replacing it with something else.</p>
<p>I know I can use <code>await page.type('#inputID', 'blah');</code> to insert "blah" into the textbox (which in my case, having existing text, only appends "blah"), however, I cannot find any page methods<a href="https://pptr.dev/#?product=Puppeteer&version=v1.8.0&show=api-class-page" rel="noreferrer">1</a> that allow deleting or replacing existing text.</p> | 52,633,235 | 9 | 1 | null | 2018-10-03 15:49:57.303 UTC | 13 | 2022-09-20 05:03:08.727 UTC | 2018-10-03 18:52:22.287 UTC | null | 4,283,581 | null | 8,215,719 | null | 1 | 55 | javascript|node.js|google-chrome-devtools|puppeteer|headless-browser | 57,402 | <p>You can use <code>page.evaluate</code> to manipulate DOM as you see fit:</p>
<pre><code>await page.evaluate( () => document.getElementById("inputID").value = "")
</code></pre>
<p>However sometimes just manipulating a given field might not be enough (a target page could be an SPA with event listeners), so emulating real keypresses is preferable. The examples below are from <a href="https://github.com/GoogleChrome/puppeteer/issues/761" rel="nofollow noreferrer">the informative issue</a> in puppeteer's Github concerning this task.</p>
<p>Here we press <code>Backspace</code> as many times as there are characters in that field:</p>
<pre><code>const inputValue = await page.$eval('#inputID', el => el.value);
// focus on the input field
await page.click('#inputID');
for (let i = 0; i < inputValue.length; i++) {
await page.keyboard.press('Backspace');
}
</code></pre>
<p>Another interesting solution is to click the target field 3 times so that the browser would select all the text in it and then you could just type what you want:</p>
<pre><code>const input = await page.$('#inputID');
await input.click({ clickCount: 3 })
await input.type("Blah");
</code></pre> |
51,415,784 | How to add my own function as a custom stage in a ML pyspark Pipeline? | <p>The sample code from Florian</p>
<pre><code>-----------+-----------+-----------+
|ball_column|keep_the |hall_column|
+-----------+-----------+-----------+
| 0| 7| 14|
| 1| 8| 15|
| 2| 9| 16|
| 3| 10| 17|
| 4| 11| 18|
| 5| 12| 19|
| 6| 13| 20|
+-----------+-----------+-----------+
</code></pre>
<p>The first part of the code drops columns name in the banned list</p>
<pre><code>#first part of the code
banned_list = ["ball","fall","hall"]
condition = lambda col: any(word in col for word in banned_list)
new_df = df.drop(*filter(condition, df.columns))
</code></pre>
<p>So the above piece of code should drop the <code>ball_column</code> and <code>hall_column</code>.</p>
<p>The second part of the code buckets specific columns in the list. For this example, we will bucket the only one remaining, <code>keep_column</code>.</p>
<pre><code>bagging =
Bucketizer(
splits=[-float("inf"), 10, 100, float("inf")],
inputCol='keep_the',
outputCol='keep_the')
</code></pre>
<p>Now bagging the columns using pipeline was as follows</p>
<pre><code>model = Pipeline(stages=bagging).fit(df)
bucketedData = model.transform(df)
</code></pre>
<p>How can I add the first block of the code (<code>banned list</code>, <code>condition</code>, <code>new_df</code>) to the ml pipeline as a stage?</p> | 51,417,421 | 1 | 0 | null | 2018-07-19 06:30:44.877 UTC | 10 | 2018-08-29 21:00:16.743 UTC | 2018-07-21 07:50:13.99 UTC | null | 10,020,360 | null | 10,020,360 | null | 1 | 11 | python|apache-spark|pyspark|apache-spark-sql | 8,419 | <p>I believe this does what you want. You can create a custom <code>Transformer</code>, and add that to the stages in the <code>Pipeline</code>. Note that I slightly changed your functions because we do not have access to all variables you mentioned, but the concept remains the same.</p>
<p>Hope this helps!</p>
<pre><code>import pyspark.sql.functions as F
from pyspark.ml import Pipeline, Transformer
from pyspark.ml.feature import Bucketizer
from pyspark.sql import DataFrame
from typing import Iterable
import pandas as pd
# CUSTOM TRANSFORMER ----------------------------------------------------------------
class ColumnDropper(Transformer):
"""
A custom Transformer which drops all columns that have at least one of the
words from the banned_list in the name.
"""
def __init__(self, banned_list: Iterable[str]):
super(ColumnDropper, self).__init__()
self.banned_list = banned_list
def _transform(self, df: DataFrame) -> DataFrame:
df = df.drop(*[x for x in df.columns if any(y in x for y in self.banned_list)])
return df
# SAMPLE DATA -----------------------------------------------------------------------
df = pd.DataFrame({'ball_column': [0,1,2,3,4,5,6],
'keep_the': [6,5,4,3,2,1,0],
'hall_column': [2,2,2,2,2,2,2] })
df = spark.createDataFrame(df)
# EXAMPLE 1: USE THE TRANSFORMER WITHOUT PIPELINE -----------------------------------
column_dropper = ColumnDropper(banned_list = ["ball","fall","hall"])
df_example = column_dropper.transform(df)
# EXAMPLE 2: USE THE TRANSFORMER WITH PIPELINE --------------------------------------
column_dropper = ColumnDropper(banned_list = ["ball","fall","hall"])
bagging = Bucketizer(
splits=[-float("inf"), 3, float("inf")],
inputCol= 'keep_the',
outputCol="keep_the_bucket")
model = Pipeline(stages=[column_dropper,bagging]).fit(df)
bucketedData = model.transform(df)
bucketedData.show()
</code></pre>
<p>Output:</p>
<pre><code>+--------+---------------+
|keep_the|keep_the_bucket|
+--------+---------------+
| 6| 1.0|
| 5| 1.0|
| 4| 1.0|
| 3| 1.0|
| 2| 0.0|
| 1| 0.0|
| 0| 0.0|
+--------+---------------+
</code></pre>
<hr>
<p>Also, note that if your custom method requires to be fitted (e.g. a custom <code>StringIndexer</code>), you should also create a custom <code>Estimator</code>:</p>
<pre><code>class CustomTransformer(Transformer):
def _transform(self, df) -> DataFrame:
class CustomEstimator(Estimator):
def _fit(self, df) -> CustomTransformer:
</code></pre> |
38,168,391 | Cross-platform file name handling in .NET Core | <p>How to handle file name in <code>System.IO</code> classes in a cross-platform manner to make it work on Windows and Linux?</p>
<p>For example, I write this code that works perfectly on Windows, however it doesn't create a file on Ubuntu Linux:</p>
<pre><code>var tempFilename = $@"..\Data\uploads\{filename}";
using (FileStream fs = System.IO.File.Create(tempFilename))
{
file.CopyTo(fs);
fs.Flush();
}
</code></pre> | 38,168,532 | 9 | 0 | null | 2016-07-03 09:03:32.693 UTC | 5 | 2022-08-12 07:20:24.683 UTC | 2017-03-01 17:01:35.417 UTC | null | 240,733 | null | 2,000,124 | null | 1 | 52 | c#|linux|.net-core | 51,096 | <p>Windows using Backslash. Linux using Slash. Path.Combine set the right symbol :<br>
<a href="https://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.110).aspx" rel="noreferrer">Path.Combine Method - MSDN</a></p> |
629,617 | How to convert string to "iso-8859-1"? | <p>How can i convert an UTF-8 string into an ISO-8859-1 string?</p> | 629,629 | 2 | 1 | null | 2009-03-10 10:36:04.31 UTC | 1 | 2009-03-10 10:39:49.307 UTC | 2009-03-10 10:38:28.157 UTC | Ólafur Waage | 22,459 | Tom | 20,979 | null | 1 | 13 | c#|asp.net | 41,009 | <p>Try:</p>
<pre><code> System.Text.Encoding iso_8859_1 = System.Text.Encoding.GetEncoding("iso-8859-1");
System.Text.Encoding utf_8 = System.Text.Encoding.UTF8;
// Unicode string.
string s_unicode = "abcéabc";
// Convert to ISO-8859-1 bytes.
byte[] isoBytes = iso_8859_1.GetBytes(s_unicode);
// Convert to UTF-8.
byte[] utf8Bytes = System.Text.Encoding.Convert(iso_8859_1, utf_8, isoBytes);
</code></pre> |
1,134,770 | How to end / Force a close to a program (in Clojure) | <p>I am a pretty decent programmer in Java, however I am new to programming in Clojure.</p>
<p>In Java, to force an exit of a program, the code used is <code>System.exit(0)</code>. Is there any equivalent to this code is Clojure?</p> | 1,134,778 | 2 | 0 | null | 2009-07-16 00:10:39.047 UTC | 4 | 2016-05-23 16:38:33.743 UTC | 2016-05-23 16:37:21.36 UTC | null | 206,720 | Hank | null | null | 1 | 34 | clojure|exit | 13,814 | <p>Given that part of the attractiveness of Clojure is that you can use Java class libraries, why not just do:</p>
<pre><code>(System/exit 0)
</code></pre> |
1,119,849 | How do I use Optional Parameters in an ASP.NET MVC Controller | <p>I have a set of drop down controls on a view that are linked to two lists.</p>
<pre><code>//control
ViewData["Countries"] = new SelectList(x.getCountries().ToList(), "key","value",country);
ViewData["Regions"] = new SelectList(x.getRegions(country).ToList(), "id", "name", regions);
/*
on the view
*/
<% using (Html.BeginForm("","", FormMethod.Get))
{ %>
<ol>
<li>
<%= MvcEasyA.Helpers.LabelHelper.Label("Country", "Country:")%>
<%= Html.DropDownList("Country", ViewData["Countries"] as SelectList) %>
<input type="submit" value="countryGO" class="ddabtns" />
</li>
<li>
<%= MvcEasyA.Helpers.LabelHelper.Label("Regions", "Regions:")%>
<%= Html.DropDownList("Regions", ViewData["Regions"] as SelectList,"-- Select One --") %>
<input type="submit" value="regionsGO" class="ddabtns" />
</li>
</ol>
<br />
<input type="submit" value="go" />
<% } %>
</code></pre>
<p>So its sending a query to the same page (as its only really there to provide an alternative way of setting/updating the appropriate dropdowns, this is acceptable as it will all be replaced with javascript).</p>
<p>The url on clicking is something like...</p>
<pre><code>http://localhost:1689/?country=FRA&regions=117
</code></pre>
<p>Regions is dependent on the country code.</p>
<p>I'm trying to achieve this bit without bothering with routing as there's no real point with regards this function.</p>
<p>So the Controller has the following method.</p>
<pre><code>public ActionResult Index(string country, int regions)
</code></pre> | 1,119,951 | 2 | 0 | null | 2009-07-13 14:40:02.56 UTC | 4 | 2018-09-19 05:24:22.443 UTC | 2016-03-17 15:20:07.47 UTC | null | 3,688,464 | null | 52,912 | null | 1 | 45 | c#|asp.net-mvc|c#-3.0 | 106,935 | <p>The string should be ok, as it'll get passed as an empty string. For int, make it nullable:</p>
<pre><code>public ActionResult Index(string Country, int? Regions)
</code></pre>
<p>Also, you'll note I capitalized it in the same was as your querystring.</p>
<p><strong>Edit</strong></p>
<p>Note that ASP.NET now allows you to define default parameters. E.g.:</p>
<pre><code>public ActionResult Index(string Country, int Regions = 2)
</code></pre>
<p>However, IMHO I'd recommend that you only use the default where it makes semantic sense. For example, if the purpose of the Regions parameter were to set the # of regions in a country, and most countries have 2 regions (North and South) then setting a default makes sense. I wouldn't use a "magic number" that signifies a lack of input (e.g., 999 or -1) -- at that point you should just use <code>null</code>.</p> |
2,799,017 | Is it possible to bind a List to a ListView in WinForms? | <p>I'd like to bind a ListView to a <code>List<string></code>. I'm using this code:</p>
<pre><code>somelistview.DataBindings.Add ("Items", someclass, "SomeList");
</code></pre>
<p>I'm getting this exception: <em>Cannot bind to property 'Items' because it is read-only.</em></p>
<p>I don't know how I should bind if the Items property is readonly?</p> | 2,799,161 | 5 | 0 | null | 2010-05-09 20:12:55.393 UTC | 2 | 2022-03-01 20:57:17.963 UTC | null | null | null | null | 39,590 | null | 1 | 19 | c#|winforms|data-binding | 65,979 | <p>The ListView class does not support design time binding. An alternative is presented in <a href="http://www.codeproject.com/KB/list/ListView_DataBinding.aspx" rel="noreferrer">this project</a>.</p> |
2,912,054 | Lazy Load images on Listview in android(Beginner Level)? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/541966/android-how-do-i-do-a-lazy-load-of-images-in-listview">Android - How do I do a lazy load of images in ListView</a> </p>
</blockquote>
<p>I am working on the listview with the custom adapter. I want to load the images and text view on it. The images are load from the internet urls. I just want to show the images which are visible list item to hte user. I refered the <a href="http://code.google.com/p/shelves/source/browse/trunk/Shelves/src/org/curiouscreature/android/shelves/activity/BooksAdapter.java" rel="noreferrer">Shelves opensource project example from romainguy</a>, but its to complicated to understand the code. For a beginner level, I just want to know how to handle the tag between the adapter and activity. From the <a href="http://www.androidguys.com/2008/07/22/fancy-listviews-part-three/" rel="noreferrer">commonsware</a> <a href="http://github.com/commonsguy/cwac-thumbnail/tree" rel="noreferrer">example</a> I can set the tag on adapter, but can't show the corresponding image at the idle state of the listview. Please help me with your ideas. Sample codes are more understandable. </p>
<p>Thanks.</p>
<p>EDIT:</p>
<p>The combination of <a href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html" rel="noreferrer">Efficient</a> and <a href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List13.html" rel="noreferrer">Slow</a> Adapter in ApiDemos is more helpful to understand.</p>
<p>changes done on efficient adapter example like this:</p>
<pre><code>public class List14 extends ListActivity implements ListView.OnScrollListener {
// private TextView mStatus;
private static boolean mBusy = false;
static ViewHolder holder;
public static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Bitmap mIcon1;
private Bitmap mIcon2;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
// Icons bound to the rows.
mIcon1 = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon48x48_1);
mIcon2 = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon48x48_2);
}
/**
* The number of items in the list is determined by the number of
* speeches in our array.
*
* @see android.widget.ListAdapter#getCount()
*/
public int getCount() {
return DATA.length;
}
/**
* Since the data comes from an array, just returning the index is
* sufficent to get at the data. If we were using a more complex data
* structure, we would return whatever object represents one row in the
* list.
*
* @see android.widget.ListAdapter#getItem(int)
*/
public Object getItem(int position) {
return position;
}
/**
* Use the array index as a unique id.
*
* @see android.widget.ListAdapter#getItemId(int)
*/
public long getItemId(int position) {
return position;
}
/**
* Make a view to hold each row.
*
* @see android.widget.ListAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid
// unneccessary calls
// to findViewById() on each row.
// When convertView is not null, we can reuse it directly, there is
// no need
// to reinflate it. We only inflate a new View when the convertView
// supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_icon_text,
null);
// Creates a ViewHolder and store references to the two children
// views
// we want to bind data to.
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
if (!mBusy) {
holder.icon.setImageBitmap(mIcon1);
// Null tag means the view has the correct data
holder.icon.setTag(null);
} else {
holder.icon.setImageBitmap(mIcon2);
// Non-null tag means the view still needs to load it's data
holder.icon.setTag(this);
}
holder.text.setText(DATA[position]);
// Bind the data efficiently with the holder.
// holder.text.setText(DATA[position]);
return convertView;
}
static class ViewHolder {
TextView text;
ImageView icon;
}
}
private Bitmap mIcon1;
private Bitmap mIcon2;
@Override
public void onCreate(Bundle savedInstanceState) {
mIcon1 = BitmapFactory.decodeResource(this.getResources(),
R.drawable.icon48x48_1);
mIcon2 = BitmapFactory.decodeResource(this.getResources(),
R.drawable.icon48x48_2);
super.onCreate(savedInstanceState);
setListAdapter(new EfficientAdapter(this));
getListView().setOnScrollListener(this);
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case OnScrollListener.SCROLL_STATE_IDLE:
mBusy = false;
int first = view.getFirstVisiblePosition();
int count = view.getChildCount();
for (int i = 0; i < count; i++) {
holder.icon = (ImageView) view.getChildAt(i).findViewById(
R.id.icon);
if (holder.icon.getTag() != null) {
holder.icon.setImageBitmap(mIcon1);
holder.icon.setTag(null);
}
}
// mStatus.setText("Idle");
break;
case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
mBusy = true;
// mStatus.setText("Touch scroll");
break;
case OnScrollListener.SCROLL_STATE_FLING:
mBusy = true;
// mStatus.setText("Fling");
break;
}
}
private static final String[] DATA = { "Abbaye de Belloc",
"Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu"};
}
</code></pre>
<p>It works fine now. But when the scrolling state its not reloading the image properly. some interval of items not shows the images2. that is the correct order of the images are loading. But not in all items of list. Mismatches happening between solid item intervals.
how to correct it?</p> | 2,923,196 | 5 | 0 | null | 2010-05-26 10:26:09.707 UTC | 28 | 2012-07-18 00:14:37.417 UTC | 2017-05-23 12:10:09.08 UTC | null | -1 | null | 267,269 | null | 1 | 54 | android|listview|android-lazyadapter|android-lazyloading | 47,100 | <p>Praveen - </p>
<p>As you already found my blog post on this, I just wanted to push it back to Stackoverflow so that others can use it.</p>
<p>Here's the basic discussion:
<a href="http://ballardhack.wordpress.com/2010/04/05/loading-remote-images-in-a-listview-on-android/" rel="noreferrer">http://ballardhack.wordpress.com/2010/04/05/loading-remote-images-in-a-listview-on-android/</a></p>
<p>And there's a class I documented later that uses a thread and a callback to load the images:</p>
<p><a href="http://ballardhack.wordpress.com/2010/04/10/loading-images-over-http-on-a-separate-thread-on-android/" rel="noreferrer">http://ballardhack.wordpress.com/2010/04/10/loading-images-over-http-on-a-separate-thread-on-android/</a></p>
<p><strong>Update:</strong> To address your specific exception, I think that view returned in the list from <code>getChildAt</code> is not an <code>ImageView</code> -- it's whatever layout view you are using to hold the image and text. </p>
<p><strong>Update to include relevant code</strong>: (Per @george-stocker's recommendation)</p>
<p>Here is the adapter I was using:</p>
<pre><code>public class MediaItemAdapter extends ArrayAdapter<MediaItem> {
private final static String TAG = "MediaItemAdapter";
private int resourceId = 0;
private LayoutInflater inflater;
private Context context;
private ImageThreadLoader imageLoader = new ImageThreadLoader();
public MediaItemAdapter(Context context, int resourceId, List<MediaItem> mediaItems) {
super(context, 0, mediaItems);
this.resourceId = resourceId;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
TextView textTitle;
TextView textTimer;
final ImageView image;
view = inflater.inflate(resourceId, parent, false);
try {
textTitle = (TextView)view.findViewById(R.id.text);
image = (ImageView)view.findViewById(R.id.icon);
} catch( ClassCastException e ) {
Log.e(TAG, "Your layout must provide an image and a text view with ID's icon and text.", e);
throw e;
}
MediaItem item = getItem(position);
Bitmap cachedImage = null;
try {
cachedImage = imageLoader.loadImage(item.thumbnail, new ImageLoadedListener() {
public void imageLoaded(Bitmap imageBitmap) {
image.setImageBitmap(imageBitmap);
notifyDataSetChanged(); }
});
} catch (MalformedURLException e) {
Log.e(TAG, "Bad remote image URL: " + item.thumbnail, e);
}
textTitle.setText(item.name);
if( cachedImage != null ) {
image.setImageBitmap(cachedImage);
}
return view;
}
}
</code></pre> |
2,429,819 | Why is the W3C box model considered better? | <p>Why do most developers consider the W3C <a href="https://en.wikipedia.org/wiki/CSS_box_model" rel="nofollow noreferrer">box model</a> to be better than the box model used by Internet Explorer?</p>
<p>It's very frustrating developing pages that look the way you want them on Internet Explorer, but I find the W3C box model counterintuitive. For example, if margins, padding, and border were factored into the width, I could assign width values to all my columns without worrying about the number of columns, and any changes I make to their padding and margins.</p>
<p>With W3C's box model I have to worry about the number of columns I have, and develop something akin to a mathematical formula to calculate the correct width values when modifying margins and padding. Changing their values would be difficult, especially for complex layouts. Consider this small frame-work I wrote:</p>
<pre><code>#content {
margin:0 auto 30px auto;
padding:0 30px 30px 30px;
width: 900px;
}
#content .column {
float: left;
margin:0 20px 20px 20px;
}
#content .first {
margin-left: 0;
}
#content .last {
margin-right: 0;
}
.width_1-4 {
width: 195px;
}
.width_1-3 {
width: 273px;
}
.width_1-2 {
width: 430px;
}
.width_3-4 {
width: 645px;
}
.width_1-1 {
width: 900px;
}
</code></pre>
<p>The values I assigned here will falter unless there are three columns, and thus margins at <code>0+20+20+20+20+0</code>. It would be difficult to modify padding and margins; my entire widths would have to be recalculated. If column width incorporated padding and margins, all I would need to do is change the width and I have my layout. I'm less criticizing the box model and more hoping to understand why it's considered better as I'm finding it difficult to work with.</p>
<p>Am I doing this thing wrong? It just seems counterintuitive to use W3C's box model.</p> | 2,429,849 | 6 | 3 | null | 2010-03-12 01:02:36.05 UTC | 14 | 2020-05-09 14:23:42.29 UTC | 2020-05-09 14:23:42.29 UTC | null | 63,550 | null | 276,959 | null | 1 | 38 | layout|css | 11,852 | <p>One word answer - <code>-box-sizing</code></p>
<p><a href="http://www.quirksmode.org/css/box.html" rel="noreferrer">You choose how you want your box model to work</a>.</p> |
3,211,991 | Does IE 8 have a limit on number of stylesheets per page? | <p>In <a href="https://stackoverflow.com/questions/3211885/is-there-any-limit-on-css-file-size/3211946#3211946">an answer about CSS</a>, a user said:</p>
<blockquote>
<p>Internet Explorer <strike>has</strike> is said to have a limit of 4096 CSS <em>rules</em> per file. <a href="http://msdn.microsoft.com/en-us/library/aa358796(VS.85).aspx" rel="nofollow noreferrer">Reference</a> </p>
<p>Also, it has a limit on the number of style sheets you can embed in a single document. I think it is 20.</p>
</blockquote>
<p>While the <a href="http://msdn.microsoft.com/en-us/library/aa358796(VS.85).aspx" rel="nofollow noreferrer">reference on MSDN</a> seems to confirm this (and there's <a href="http://joshua.perina.com/africa/gambia/fajara/post/internet-explorer-css-file-size-limit" rel="nofollow noreferrer">a blog post</a> which confirms this in IE7), is this still the case for IE8?</p> | 3,212,065 | 6 | 13 | null | 2010-07-09 11:05:03.98 UTC | 9 | 2015-03-27 09:46:06.327 UTC | 2017-05-23 11:45:38.073 UTC | null | -1 | null | 19,746 | null | 1 | 40 | css|internet-explorer|internet-explorer-8 | 15,615 | <p>Yes, IE8 (and even IE9 apparently) limit the number of style sheets to 31 per page.</p>
<p>Telerik has <a href="http://blogs.telerik.com/aspnetmvcteam/posts/10-05-03/internet-explorer-css-limits.aspx" rel="noreferrer">an article</a> and <a href="http://demos.telerik.com/testcases/BrokenTheme.aspx" rel="noreferrer">test page</a> which demonstrate the issue. According to comments in the same article, the 4096 rules per file limitation has been marked as Won't Fix in Microsoft Connect but I've been unable to verify that.</p> |
2,651,632 | How to check if an Object is a Collection Type in Java? | <p>By using java reflection, we can easily know if an object is an array. What's the easiest way to tell if an object is a collection(Set,List,Map,Vector...)?</p> | 2,651,644 | 6 | 0 | null | 2010-04-16 08:40:06.16 UTC | 19 | 2015-12-30 12:46:04.02 UTC | null | null | null | null | 241,824 | null | 1 | 84 | java | 122,375 | <pre><code>if (x instanceof Collection<?>){
}
if (x instanceof Map<?,?>){
}
</code></pre> |
2,389,846 | Python Decimals format | <p>WHat is a good way to format a python decimal like this way? </p>
<p>1.00 --> '1'<br>
1.20 --> '1.2'<br>
1.23 --> '1.23'<br>
1.234 --> '1.23'<br>
1.2345 --> '1.23'</p> | 2,390,047 | 6 | 1 | null | 2010-03-05 20:51:59.863 UTC | 19 | 2022-09-02 15:57:07.277 UTC | 2010-03-05 21:15:31.543 UTC | null | 190,597 | null | 124,503 | null | 1 | 89 | python|decimal | 218,149 | <p>If you have Python 2.6 or newer, use <a href="http://docs.python.org/library/string.html#format-string-syntax" rel="noreferrer"><code>format</code></a>:</p>
<pre><code>'{0:.3g}'.format(num)
</code></pre>
<p>For Python 2.5 or older:</p>
<pre><code>'%.3g'%(num)
</code></pre>
<p>Explanation:</p>
<p><code>{0}</code>tells <code>format</code> to print the first argument -- in this case, <code>num</code>.</p>
<p>Everything after the colon (:) specifies the <code>format_spec</code>.</p>
<p><code>.3</code> sets the precision to 3.</p>
<p><code>g</code> removes insignificant zeros. See
<a href="http://en.wikipedia.org/wiki/Printf#fprintf" rel="noreferrer">http://en.wikipedia.org/wiki/Printf#fprintf</a></p>
<p>For example:</p>
<pre><code>tests=[(1.00, '1'),
(1.2, '1.2'),
(1.23, '1.23'),
(1.234, '1.23'),
(1.2345, '1.23')]
for num, answer in tests:
result = '{0:.3g}'.format(num)
if result != answer:
print('Error: {0} --> {1} != {2}'.format(num, result, answer))
exit()
else:
print('{0} --> {1}'.format(num,result))
</code></pre>
<p>yields</p>
<pre><code>1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23
</code></pre>
<hr>
<p>Using Python 3.6 or newer, you could use <a href="https://www.python.org/dev/peps/pep-0498/#code-equivalence" rel="noreferrer"><code>f-strings</code></a>:</p>
<pre><code>In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'
</code></pre> |
2,989,829 | How to create a menu tree using HTML | <p>I need to create a menu tree using HTML. I had a search on Google, but they are providing some software to download in order to create this. But I need some script and HTML tags to do this.
Can anyone help me solve this problem.
Thanks in advance.</p> | 2,989,890 | 7 | 3 | null | 2010-06-07 13:18:05.68 UTC | 1 | 2014-02-20 19:30:29.343 UTC | 2010-06-07 13:23:13.987 UTC | null | 339,850 | null | 360,453 | null | 1 | 10 | javascript|jquery|html | 48,184 | <p>Here is something very simple to start with.</p>
<p><a href="http://www.dynamicdrive.com/dynamicindex1/navigate1.htm" rel="noreferrer">http://www.dynamicdrive.com/dynamicindex1/navigate1.htm</a></p>
<h2><strong>EDIT</strong></h2>
<p>Implementing what I learned from @sushil bharwani.
Here is how I found the above URL i.e. at the courtesy of @sushil bharwani
<a href="http://www.google.co.in/search?q=Menu+Tree+using+UL+L&qscrl=1" rel="noreferrer">http://www.google.co.in/search?q=Menu+Tree+using+UL+L&qscrl=1</a></p> |
2,672,975 | Django BigInteger auto-increment field as primary key? | <p>I'm currently building a project which involves a lot of collective intelligence. Every user visiting the web site gets created a unique profile and their data is later used to calculate best matches for themselves and other users.</p>
<p>By default, Django creates an INT(11) <code>id</code> field to handle models primary keys. I'm concerned with this being overflown very quickly (i.e. ~2.4b devices visiting the page without prior cookie set up). How can I change it to be represented as BIGINT in MySQL and long() inside Django itself?</p>
<p>I've found I could do the following (<a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#bigintegerfield" rel="noreferrer">http://docs.djangoproject.com/en/dev/ref/models/fields/#bigintegerfield</a>):</p>
<pre><code>class MyProfile(models.Model):
id = BigIntegerField(primary_key=True)
</code></pre>
<p>But is there a way to make it autoincrement, like usual <code>id</code> fields? Additionally, can I make it unsigned so that I get more space to fill in?</p>
<p>Thanks!</p> | 70,112,662 | 7 | 0 | null | 2010-04-20 06:19:55.99 UTC | 19 | 2021-11-25 14:19:00.947 UTC | null | null | null | null | 275,725 | null | 1 | 35 | python|django|primary-key|auto-increment|biginteger | 28,821 | <p>Since Django 3.2 the type of implicit primary key can be controlled with the <code>DEFAULT_AUTO_FIELD</code> setting (<a href="https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field" rel="nofollow noreferrer">documentation</a>). So, there is no need anymore to override primary keys in all your models.</p>
<pre><code>#This setting will change all implicitly added primary keys to BigAutoField
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
</code></pre>
<p>Note that starting with Django 3.2 new projects are generated with <code>DEFAULT_AUTO_FIELD</code> set to <code>BigAutoField</code> (<a href="https://docs.djangoproject.com/en/3.2/releases/3.2/#customizing-type-of-auto-created-primary-keys" rel="nofollow noreferrer">release notes</a>).</p> |
2,346,011 | How do I scroll to an element within an overflowed Div? | <p>I have 20 list items inside of a div that can only show 5 at a time. What is a good way to scroll to item #10, and then item #20? I know the height of all the items.</p>
<p>The <code>scrollTo</code> plugin does this, but its source is not super easy to understand without really getting into it. <strong>I don't want to use this plugin.</strong></p>
<p>Let's say I have a function that takes 2 elements <code>$parentDiv</code>, <code>$innerListItem</code>, neither <code>$innerListItem.offset().top</code> nor <code>$innerListItem.positon().top</code> gives me the correct scrollTop for $parentDiv.</p> | 5,267,018 | 7 | 7 | null | 2010-02-27 02:28:22.19 UTC | 47 | 2020-08-20 12:20:43.933 UTC | 2016-04-14 16:47:30.54 UTC | null | 1,694,962 | null | 26,188 | null | 1 | 170 | jquery | 151,931 | <p>The <code>$innerListItem.position().top</code> is actually relative to the <code>.scrollTop()</code> of its first positioned ancestor. So the way to calculate the correct <code>$parentDiv.scrollTop()</code> value is to begin by making sure that <code>$parentDiv</code> is positioned. If it doesn't already have an explicit <code>position</code>, use <code>position: relative</code>. The elements <code>$innerListItem</code> and all its ancestors up to <code>$parentDiv</code> need to have no explicit position. Now you can scroll to the <code>$innerListItem</code> with:</p>
<pre><code>// Scroll to the top
$parentDiv.scrollTop($parentDiv.scrollTop() + $innerListItem.position().top);
// Scroll to the center
$parentDiv.scrollTop($parentDiv.scrollTop() + $innerListItem.position().top
- $parentDiv.height()/2 + $innerListItem.height()/2);
</code></pre> |
10,758,471 | pass php array to jquery function | <p>I got a page with a form to fill it with custormers info. I got previous custormers data stored in a php array. With a dropdownlist users can fill the form with my stored data.</p>
<p>what i have is a jquery function that triggers when the value changes and inside that function i whould like to update the form values with my stored data (in my php array).</p>
<p>Problem is that i dont know how to pass my php array to the jquery function, any idea ?? </p>
<p>this is how i fill the array:</p>
<pre><code>$contador_acompanantes = 0;
foreach ($acompanantes->Persona as $acomp)
{
$numero = $acomp->Numero;
$apellidos = $acomp->Apellidos;
$nombre = $acomp->Nombre;
$ACOMPANANTES[$contador_acompanantes] = $ficha_acomp;
$contador_acompanantes++;
}
</code></pre>
<p>got my select object:</p>
<pre><code><select name="acompanante_anterior" id="acompanante_anterior">
<option value="1" selected>Acompañante</option>
<option value="2">acompanante1</option>
<option value="2">acompanante2</option>
</select>
</code></pre>
<p>and this is my code for the jquery function (it is in the same .php page)</p>
<pre><code><script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
});
});
</script>
</code></pre> | 10,758,535 | 3 | 0 | null | 2012-05-25 16:55:35.22 UTC | 3 | 2012-05-25 17:17:37.96 UTC | null | null | null | null | 1,361,401 | null | 1 | 6 | php|jquery|arrays | 38,042 | <pre><code>var arrayFromPHP = <?php echo json_encode($phpArray); ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
</code></pre> |
10,556,556 | Insert all data of a datagridview to database at once | <p>I have a datagridview which is created by various action and user's manipulation of data.
I want to insert all the data of the gridview to the database at once, I know I could try a code similar to this: </p>
<pre><code>for(int i=0; i< dataGridView1.Rows.Count;i++)
{
string StrQuery= @"INSERT INTO tableName VALUES (" + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand(StrQuery, conn))
{
conn.Open();
comm.ExecuteNonQuery();
}
}
}
</code></pre>
<p>But will it be fair to create a new connection every time a record is inserted? The datagrid may contain many rows... Is there any way to take off all the data to the server at once and loop inside in sql to insert all the data?</p> | 10,556,681 | 8 | 0 | null | 2012-05-11 18:16:34.903 UTC | 8 | 2021-11-03 09:06:46.293 UTC | 2014-04-11 20:30:01.543 UTC | null | 258,113 | null | 1,330,837 | null | 1 | 9 | c#|sql-server|winforms | 133,472 | <p>If you move your for loop, you won't have to make multiple connections. Just a quick edit to your code block (by no means completely correct):</p>
<pre><code>string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= @"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
</code></pre>
<p>As to executing multiple SQL commands at once, please look at this link:
<a href="https://stackoverflow.com/questions/3149469/multiple-statements-in-single-sqlcommand">Multiple statements in single SqlCommand</a></p> |
10,436,231 | Tooltips with Twitter Bootstrap | <p>I am using Twitter Bootstrap--and I am not a frontend developer! However, it's making the process almost--dare I say--fun!</p>
<p>I'm a bit confused about tooltips. They are <a href="http://getbootstrap.com/javascript/#tooltips">covered in the documentation</a> but Twitter assumes some knowledge. For example, they say to trigger the tooltip with the following JavaScript code.</p>
<pre><code>$('#example').tooltip(options)
</code></pre>
<p>After poking around on their source, I realized that fields with tooltips need to be in a class and have the following code run.</p>
<pre><code>$('.tooltipclass').tooltip(options)
</code></pre>
<p>But now my question is, why doesn't Twitter Bootstrap provide such a class <code>tooltip</code>? Just to allow greater configuration? Is it better to add the individual elements with tooltips to <code>tooltipclass</code>, or should I add the surrounding area to <code>tooltipclass</code>? Does it matter if I use a class identifier (<code>.class</code>) instead of a name identifier (<code>#name</code>)?</p> | 10,437,711 | 7 | 0 | null | 2012-05-03 17:13:50.683 UTC | 27 | 2015-09-29 20:07:19.413 UTC | 2013-12-19 11:31:15.677 UTC | null | 397,598 | null | 568,393 | null | 1 | 71 | javascript|twitter-bootstrap | 103,684 | <p>I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:</p>
<pre><code><a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>
</code></pre>
<p>Then you can trigger all links with the <code>.link</code> class attached as tooltips like so:</p>
<pre><code>$('.link').tooltip()
</code></pre>
<p>Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the <code>rel</code> attribute. With this attribute you can target all links or elements with the <code>rel</code> property set to <code>tooltip</code>, like so:</p>
<pre><code>$('[rel=tooltip]').tooltip()
</code></pre>
<p>And your links would look like something like this:</p>
<pre><code><a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>
</code></pre>
<p>Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:</p>
<pre><code>$('#example').tooltip({
selector: "a[rel=tooltip]"
})
</code></pre>
<p>This selector will target all of your tooltips with the <code>rel</code> attribute "within" your <code>#example</code> div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.</p> |
5,728,885 | How do I draw an image based on a simple polygon? | <p>I'd like to copy a roughly rectangular area to a rectangular area. Example:</p>
<p><img src="https://i.stack.imgur.com/S99Hf.png" alt=""></p>
<p>Both areas are defined by their corner points. The general direction is kept (no flipping etc).</p>
<p>Simply rotating the source image does not work since opposing sides may be of different length.</p>
<p>So far I found no way to do this in pure C# (except manual pixel copying), so I guess I have to resort to the Windows API or some 3rd party library?</p> | 5,730,761 | 2 | 0 | null | 2011-04-20 10:31:34.81 UTC | 10 | 2013-07-17 03:45:36.33 UTC | null | null | null | null | 39,590 | null | 1 | 13 | c#|.net|image-manipulation | 6,229 | <p>Generally speaking, what you want to do is map the destination coordinates to the source coordinates through a transform function:</p>
<pre><code>for (int y = 0; y < destHeight; y++) {
for (x=0; x < destWidth; x++) {
Color c = Transform(x, y, sourceImage, sourceTransform);
SetPixel(destImage, x, y, c);
}
}
</code></pre>
<p>Let's assume that sourceTransform is an object that encapsulates a transformation from source to dest coordinates (and vice versa).</p>
<p>Working in dest coordinates will make it easier to avoid that curve in your retransformed source image and will allow you to better antialias, as you can map the corners of the dest pixel to the source image and sample within it and interpolate/extrapolate.</p>
<p>In your case you're going to have a set of linear equations that do the mapping - in this case this is known as quadrilateral warping - <a href="https://stackoverflow.com/questions/2992264/extracting-a-quadrilateral-image-to-a-rectangle">see this previous question</a>.</p> |
33,326,699 | Passing (laravel) Array in Javascript | <p>I want to pass/store Laravel array in JavaScript variable. I used <code>->all()</code> so I get the result like this rather than object:</p>
<pre><code>array:83 [▼
0 => 1
1 => 11
2 => 12
...
]
</code></pre>
<p>I can access this in view using <code>{{ $theArray }}</code>. </p>
<p>However whatever I tried, I couldn't make this to javascript array.</p>
<p>I tried </p>
<p><code>var array = {{ $theArray }};</code></p>
<p><code>var array = {{{ $theArray }}};</code></p>
<p>I feel like I'm close but I couldn't figure it out</p> | 48,648,482 | 10 | 0 | null | 2015-10-25 05:58:19.427 UTC | 12 | 2022-05-25 02:24:43.57 UTC | 2015-10-25 06:03:23.597 UTC | null | 3,037,257 | null | 4,705,339 | null | 1 | 42 | javascript|php|jquery|arrays|laravel | 57,266 | <pre><code>var app = @json($array);
</code></pre>
<p>Works like a charm</p> |
30,901,174 | How to show/hide hidden HTML table rows using JavaScript (no jQuery) | <p><strong>Edit:</strong> This has been answered below.</p>
<p>I would like to have an HTML table that has hidden rows between each row with more information about the top level rows. When clicking an expand/collapse image link in the first column, the hidden row's visibility will toggle from display:none; to display:table-row;. I have not written JavaScript in a while and need to be able to do this strictly in JavaScript and cannot use the jQuery toggle() method. </p>
<p>How can I use JavaScript to find the sibling with class="subRow" of the with class="parentRow" that the button is located in within the table and then toggle the visibility of that sibling row?</p>
<h2>HTML</h2>
<pre><code><table style="width:50%">
<caption>Test Table</caption>
<thead>
<tr align="center">
<th><span class="offscreen">State Icon</span></th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tbody>
<tr align="center" class="parentRow">
<td><a href="#" onclick="toggleRow();"><img alt="Expand row" height="20px;" src="expand.png"></a></td>
<td>test cell</td>
<td>test cell</td>
<td>test cell</td>
<td>test cell</td>
</tr>
<tr style="display: none;" class="subRow">
<td colspan="5"><p>Lorem ipsum dolor sit amet...</p></td>
</tr>
....
</tbody>
</table>
</code></pre>
<h2>CSS</h2>
<pre><code>.offscreen {
position: absolute;
left: -1000px;
top: 0px;
overflow:hidden;
width:0;
}
.subRow {
background-color: #CFCFCF;
}
</code></pre>
<h2>JavaScript</h2>
<pre><code>function toggleRow() {
var rows = document.getElementsByClassName("parentRow").nextSibling;
rows.style.display = rows.style.display == "none" ? "table-row" : "none";
}
</code></pre> | 30,901,515 | 3 | 0 | null | 2015-06-17 19:55:17.067 UTC | 1 | 2015-06-17 20:22:21.333 UTC | 2015-06-17 20:22:21.333 UTC | null | 1,609,347 | null | 1,609,347 | null | 1 | 4 | javascript|html|css|toggle|html-table | 50,066 | <p>Pass your event handler a reference to the row that is clicked using <code>this</code>:</p>
<pre><code><td><a href="#" onclick="toggleRow(this);"><img alt="Expand row" height="20px;" src="expand.png"></a></td>
</code></pre>
<p>Then update your toggleRow function as follows:</p>
<pre><code>function toggleRow(e){
var subRow = e.parentNode.parentNode.nextElementSibling;
subRow.style.display = subRow.style.display === 'none' ? 'table-row' : 'none';
}
</code></pre>
<p>You may want to consider creating a general-purpose function to navigate up the DOM tree (so that this function won't break when/if you change your HTML). </p> |
34,350,406 | How rails database connection pool works | <p>I am learning rails database connection pool concept. In rails application I have defined pool size of 5.</p>
<p>my understanding about connection pool size is as below.</p>
<ol>
<li><p>When server start rails automatically creates n number of connection defined in the database.yml file. In my case it will create 5 connection since pool size is 5.</p></li>
<li><p>On every http request if there is need to access database then rails will use available connection from the connection pool to serve the request.</p></li>
</ol>
<p>But my question is if I hit 1000 request at a time then most of the request will not get access to database connection because my connection pool size is only 5.</p>
<p>Is my above understanding about rails connection pool is right??</p>
<p>Thanks,</p> | 34,351,364 | 2 | 0 | null | 2015-12-18 07:25:05.867 UTC | 5 | 2020-07-28 10:21:30.63 UTC | 2018-11-26 09:21:35.217 UTC | null | 3,090,068 | null | 2,274,074 | null | 1 | 29 | mysql|ruby-on-rails|ruby|ruby-on-rails-3|connection-pooling | 21,471 | <p>Purpose: <br />
Database connections are not thread safe; so ActiveRecord uses separate database connection for each thread.</p>
<p>Limiting factor: <br />
Total database connections is limited by the database server you use (e.g Posgres: <a href="https://www.postgresql.org/docs/current/runtime-config-connection.html" rel="noreferrer">default is typically 100 or lesser</a>), by your app server's configuration (number of processes/threads available) and Active Record's configuration : <a href="https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html" rel="noreferrer">Connection Pool</a> defaults to 5 .</p>
<p>Pool size:<br />
Active Record's pool size is for a single process. A thread uses a connection from this pool and releases it automatically afterwards. (unless you spawn a thread yourself, then you'll have to manually release it). If your application is running on multiple processes, you will have 5 database connections for each of them. If your server is hit by 1000 requests concurrently, it will distribute the requests among these connections, when it gets full, rest of the requests wait for their turn.</p>
<p>Read more at:<br />
<a href="https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html" rel="noreferrer">https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html</a></p> |
17,731,477 | Python mock class instance variable | <p>I'm using Python's <code>mock</code> library. I know how to mock a class instance method by following the <a href="http://www.voidspace.org.uk/python/mock/getting-started.html#mocking-classes" rel="noreferrer">document</a>:</p>
<pre><code>>>> def some_function():
... instance = module.Foo()
... return instance.method()
...
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... result = some_function()
... assert result == 'the result'
</code></pre>
<p>However, tried to mock a class instance variable but doesn't work (<code>instance.labels</code> in the following example):</p>
<pre><code>>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... instance.labels = [1, 1, 2, 2]
... result = some_function()
... assert result == 'the result'
</code></pre>
<p>Basically I want <code>instance.labels</code> under <code>some_function</code> get the value I want. Any hints?</p> | 17,731,909 | 1 | 0 | null | 2013-07-18 18:42:47.507 UTC | 9 | 2013-07-18 21:52:20.373 UTC | null | null | null | null | 477,865 | null | 1 | 21 | python|unit-testing|mocking | 70,804 | <p>This version of <code>some_function()</code> prints mocked <code>labels</code> property:</p>
<pre><code>def some_function():
instance = module.Foo()
print instance.labels
return instance.method()
</code></pre>
<p>My <code>module.py</code>:</p>
<pre><code>class Foo(object):
labels = [5, 6, 7]
def method(self):
return 'some'
</code></pre>
<p>Patching is the same as yours:</p>
<pre><code>with patch('module.Foo') as mock:
instance = mock.return_value
instance.method.return_value = 'the result'
instance.labels = [1,2,3,4,5]
result = some_function()
assert result == 'the result
</code></pre>
<p>Full console session:</p>
<pre><code>>>> from mock import patch
>>> import module
>>>
>>> def some_function():
... instance = module.Foo()
... print instance.labels
... return instance.method()
...
>>> some_function()
[5, 6, 7]
'some'
>>>
>>> with patch('module.Foo') as mock:
... instance = mock.return_value
... instance.method.return_value = 'the result'
... instance.labels = [1,2,3,4,5]
... result = some_function()
... assert result == 'the result'
...
...
[1, 2, 3, 4, 5]
>>>
</code></pre>
<p>For me your code <em>is</em> working.</p> |
35,565,278 | SSL Localhost Privacy error | <p>I setup ssl on localhost (wamp), I made the ssl crt with GnuWIn32.</p>
<p>When I try to login with fb <strong>in Chrome</strong> I get the following message:</p>
<p>URL:</p>
<pre><code>https://localhost/ServerSide/fb-callback.php?code=.....#_=_
</code></pre>
<p>Error:</p>
<blockquote>
<p>Your connection is not private.<br>
Attackers might be trying to steal your information from localhost (for example, passwords, messages, or credit cards). NET::ERR_CERT_INVALID.
localhost normally uses encryption to protect your information. When Chrome tried to connect to localhost this time, the website sent back unusual and incorrect credentials. This may happen when an attacker is trying to pretend to be localhost, or a Wi-Fi sign-in screen has interrupted the connection. Your information is still secure because Chrome stopped the connection before any data was exchanged.</p>
<p>You cannot visit localhost right now because the website sent scrambled credentials that Chrome cannot process. Network errors and attacks are usually temporary, so this page will probably work later.</p>
</blockquote>
<p>My SSL Config:</p>
<pre><code>Listen 443
SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5
SSLPassPhraseDialog builtin
SSLSessionCache "shmcb:c:/wamp/www/ssl/logs/ssl_scache(512000)"
SSLSessionCacheTimeout 300
<VirtualHost *:443>
DocumentRoot "c:/wamp/www"
ServerName localhost:443
ServerAdmin [email protected]
ErrorLog "c:/wamp/logs/error.log"
TransferLog "c:/wamp/logs/access.log"
SSLEngine on
SSLCertificateFile "c:/wamp/www/ssl/ia.crt"
SSLCertificateKeyFile "c:/wamp/www/ssl/ia.key"
<FilesMatch "\.(cgi|shtml|phtml|php)$">
SSLOptions +StdEnvVars
</FilesMatch>
<Directory "c:/Apache24/cgi-bin">
SSLOptions +StdEnvVars
</Directory>
BrowserMatch "MSIE [2-5]" nokeepalive ssl-unclean-shutdown \
downgrade-1.0 force-response-1.0
CustomLog "c:/wamp/logs/ssl_request.log" \
"%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>
</code></pre>
<p>My question is how to setup valid SSL certificate on localhost? or do I need to edit my configuration?</p> | 41,020,281 | 3 | 0 | null | 2016-02-22 22:33:22.477 UTC | 16 | 2022-09-13 16:46:33.417 UTC | 2016-12-07 14:42:12.477 UTC | null | 2,788,896 | null | 5,052,909 | null | 1 | 56 | google-chrome|ssl|localhost|wamp|self-signed | 51,127 | <p>In Chrome (including version <code>Version 105</code>), <em>browse url:</em></p>
<blockquote>
<p><code>chrome://flags/#allow-insecure-localhost</code></p>
</blockquote>
<p>and select <code>Enabled</code> to <strong>allow insecure localhost</strong>.</p>
<p><a href="https://i.stack.imgur.com/DNYWM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DNYWM.png" alt="allow insecure localhost in chrome settings" /></a></p>
<p>Refer to <a href="https://stackoverflow.com/questions/7580508/getting-chrome-to-accept-self-signed-localhost-certificate">this Stack Overflow</a> for more information.</p>
<hr />
<p>This works, too:</p>
<ol>
<li>See <em>"Your connection is not private. <em>blah-bla-blah</em>"</em>...</li>
<li>Type "thisisunsafe" <em>(key listeners pick it up)</em>.</li>
</ol> |
36,740,533 | What are forward and backward passes in neural networks? | <p>What is the meaning of <em>forward pass</em> and <em>backward pass</em> in neural networks?</p>
<p>Everybody is mentioning these expressions when talking about backpropagation and epochs. </p>
<p>I understood that forward pass and backward pass together form an epoch.</p> | 48,319,902 | 1 | 1 | null | 2016-04-20 10:10:19.927 UTC | 12 | 2021-03-29 10:28:54.597 UTC | 2017-10-17 19:33:23.287 UTC | null | 3,924,118 | null | 5,343,790 | null | 1 | 39 | neural-network|backpropagation|conv-neural-network | 46,899 | <p>The <strong>"forward pass"</strong> refers to calculation process, values of the output layers from the inputs data. It's traversing through all neurons from first to last layer.</p>
<p>A loss function is calculated from the output values.</p>
<p>And then <strong>"backward pass"</strong> refers to process of counting changes in weights (de facto <em>learning</em>), using gradient descent algorithm (or similar). Computation is made from last layer, backward to the first layer.</p>
<p>Backward and forward pass makes together one <strong>"iteration"</strong>.</p>
<hr />
<p>During one iteration, you usually pass a subset of the data set, which is called <strong>"mini-batch"</strong> or <strong>"batch"</strong> (however, "batch" can also mean an entire set, hence the prefix "mini")</p>
<p><strong>"Epoch"</strong> means passing the entire data set in batches.<br> One epoch contains <em>(number_of_items / batch_size)</em> iterations</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.