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
39,494,473
Is there any basis for this alternative 'for' loop syntax?
<p>I came across <a href="https://www.fefe.de/c++/c%2B%2B-talk.pdf" rel="noreferrer">a set of slides</a> for a <strike>rant</strike> talk on C++. There were some interesting tidbits here and there, but slide 8 stood out to me. Its contents were, approximately:</p> <blockquote> <h2>Ever-changing styles</h2> <h3>Old and busted:</h3> <pre><code>for (int i = 0; i &lt; n; i++) </code></pre> <h3>New hotness:</h3> <pre><code>for (int i(0); i != n; ++i) </code></pre> </blockquote> <p>I'd never seen a <code>for</code> loop using the second form before, so the claim that it was the &quot;New hotness&quot; interested me. I can see some rationale for it:</p> <ol> <li>Direct initialization using a constructor vs copy initialization</li> <li><code>!=</code> could be faster in hardware than <code>&lt;</code></li> <li><code>++i</code> doesn't require the compiler to keep the old value of <code>i</code> around, which is what <code>i++</code> would do.</li> </ol> <p>I'd imagine that this is premature optimization, though, as modern optimizing compilers would compile the two down to the same instructions; if anything, the latter is worse because it isn't a &quot;normal&quot; <code>for</code> loop. Using <code>!=</code> instead of <code>&lt;</code> is also suspicious to me, because it makes the loop semantically different than the original version, and can lead to some rare, but interesting, bugs.</p> <p>Was there any point where the &quot;New hotness&quot; version of the <code>for</code> loop was popular? Is there any reason to use that version these days (2016+), e.g. unusual loop variable types?</p>
39,494,777
7
26
null
2016-09-14 15:35:11.113 UTC
1
2016-09-15 14:19:21.617 UTC
2020-06-20 09:12:55.06 UTC
user719662
-1
null
3,580,294
null
1
45
c++|for-loop
4,345
<ol> <li><blockquote> <p>Direct initialization using a constructor vs copy initialization</p> </blockquote> <p>These are exactly identical for <code>int</code>s and will generate identical code. Use whichever one you prefer to read or what your code policies are, etc.</p></li> <li><blockquote> <p><code>!=</code> could be faster in hardware than <code>&lt;</code></p> </blockquote> <p>The generated code won't actually be <code>i &lt; n</code> vs <code>i != n</code>, it'll be like <code>i - n &lt; 0</code> vs <code>i - n == 0</code>. That is, you'll get a <code>jle</code> in the first case and a <code>je</code> in the second case. All the <code>jcc</code> instructions have identical performance (see <a href="http://www.intel.com/content/www/us/en/processors/architectures-software-developer-manuals.html" rel="nofollow noreferrer">instruction set reference</a> and <a href="http://www.intel.com/content/www/us/en/architecture-and-technology/64-ia-32-architectures-optimization-manual.html" rel="nofollow noreferrer">optionization reference</a>, which just list all the <code>jcc</code> instructions together as having throughput 0.5).</p> <p>Which is better? For <code>int</code>s, probably doesn't matter performance-wise. </p> <p>Strictly safer to do <code>&lt;</code> in case you want to skip elements in the middle, since then you don't have to worry about ending up with an infinite/undefined loop. But just write the condition that makes the most sense to write with the loop that you're writing. Also take a look at <a href="https://stackoverflow.com/a/39494757/2069064">dasblinkenlight's answer</a>.</p></li> <li><blockquote> <p><code>++i</code> doesn't require the compiler to keep the old value of <code>i</code> around, which is what <code>i++</code> would do.</p> </blockquote> <p>Yeah that's nonsense. If your compiler can't tell that you don't need the old value and just rewrite the <code>i++</code> to <code>++i</code>, then get a new compiler. Those definitely will compile to the same code with identical performance.</p> <p>That said, it's a good guideline to just use the right thing. You want to increment <code>i</code>, so that's <code>++i</code>. Only use post-increment when you need to use post-increment. Full stop.</p></li> </ol> <hr /> <p>That said, the real "new hotness" would definitely be:</p> <pre><code>for (int i : range(n)) { ... } </code></pre>
21,660,249
How do I make one particular line of a batch file a different color then the others?
<p>I'm working on a program which generates the day's weather for D&amp;D games. I want the program to display a warning in red text when a storm is generated so the DM is aware that this weather is not typical. To reduce the number of keystrokes, it must do this on the same screen as the text detailing the weather itself.</p> <p>Currently for a storm's entry I have this:</p> <pre><code>:des4a cls type c:\AutoDM\WeatherGen\data\forcast1.txt color 0c echo There is an Ashstorm! color 0a echo. echo It is %temp% degrees and the sky is invisible threw the thick echo billowing clouds of ash. echo. echo # Survival checks to light a fire are at +15. echo # Small unprotected flames will be snuffed out. echo # Non-firearm ranged attacks are at a -8 to hit. echo # Preception checks take a -10 for every 10 feet of distance. echo # Survival checks to get along in the wild are at +15. echo # Stealth checks are at a +5. echo. echo SPECIAL! echo. set /a die=6 set /a inches=%random%%%die+1 echo # The ashstorm will deposit %inches% inches of ash durring its echo durration. echo # Tracking a target after an ashstorm is at a +15. type c:\AutoDM\WeatherGen\data\forcast2.txt echo. echo. pause goto menu </code></pre> <p>The type commands are calling text documents which contain a header and footer for each entry to help the program look professional and provide a border to assist with word wrap. Thy cannot be removed. DO not suggest something which would make me unable to use the type commands as they currently exist please. Please understand that this red text line will be added to a lot of different parts of the program, each time there is a storm for each and every biome in the generator. I would prefer it to not be more then just 2 or 3 lines of code (But if there is only one way to do it well...)</p> <p>Can I have the one line in red and the rest in green? Or should I have the program beep to call attention to the fact? Do you have a better and simpler idea? How do I do this?</p>
21,666,354
4
10
null
2014-02-09 14:26:25.29 UTC
7
2018-11-21 16:47:32.903 UTC
2017-03-09 15:14:50.18 UTC
null
1,033,581
null
2,195,713
null
1
16
batch-file
55,124
<p>I was having the same problem yesterday, I did some research and <em>this</em> worked for me. EDIT: This is <strong>NOT</strong> the same code as the other one.</p> <pre><code>@Echo Off SETLOCAL EnableDelayedExpansion for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# &amp; echo on &amp; for %%b in (1) do rem"') do ( set "DEL=%%a" ) call :colorEcho 0a "This is colored green with a black background!" echo. call :colorEcho a0 "This is colored black with a green background!" echo. pause exit :colorEcho echo off &lt;nul set /p ".=%DEL%" &gt; "%~2" findstr /v /a:%1 /R "^$" "%~2" nul del "%~2" &gt; nul 2&gt;&amp;1i </code></pre> <p>it does this: <img src="https://i.stack.imgur.com/MC6vX.png" alt="Output"></p> <p>All you need to do to fit this is put the part from <code>SETLOCAL EnableDel</code>... to <code>)</code> to the beginning of your code (If your code starts with @echo off then put it under that) and also put the part from <code>:colorEcho</code> to <code>del %~2</code> at the exact bottom of your script (<em>NOTHING UNDERNEATH!</em>)</p> <p>Now between you notice</p> <pre><code>call :colorEcho 0a "This is colored green with a black background!" echo. call :colorEcho a0 "This is colored black with a green background!" echo. pause exit </code></pre> <p>Explained line by line: First line (<code>call :colorEcho 0a "This is colored green with a black background!"</code>): This is a <code>colored</code> echo, it suprisingly says <code>This is colored green with a black background!</code> in <code>0a</code> (Black Bg, Green Text) Second line (<code>echo.</code>) prints a newline, since our colored echo doesn't print one.</p> <p>SO</p> <p>Let's say you wanted to say "Hello World" in <code>Hello</code> being yellow and <code>World</code> being green. Example!</p> <pre><code>@Echo Off SETLOCAL EnableDelayedExpansion for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# &amp; echo on &amp; for %%b in (1) do rem"') do ( set "DEL=%%a" ) call :colorEcho 0e "Hello " call :colorEcho 0a " World" pause exit :colorEcho echo off &lt;nul set /p ".=%DEL%" &gt; "%~2" findstr /v /a:%1 /R "^$" "%~2" nul del "%~2" &gt; nul 2&gt;&amp;1i </code></pre> <p>This is what it does: <img src="https://i.stack.imgur.com/CE3KY.png" alt="Output"> I hope this is understandable!</p> <p>EDIT: Make sure the program <code>exit</code>s before it could reach <code>:colorEcho</code></p>
17,575,392
How do I test for an empty string in a Bash case statement?
<p>I have a Bash script that performs actions based on the value of a variable. The general syntax of the case statement is:</p> <pre><code>case ${command} in start) do_start ;; stop) do_stop ;; config) do_config ;; *) do_help ;; esac </code></pre> <p>I'd like to execute a default routine if no command is provided, and <code>do_help</code> if the command is unrecognized. I tried omitting the case value thus:</p> <pre><code>case ${command} in ) do_default ;; ... *) do_help ;; esac </code></pre> <p>The result was predictable, I suppose:</p> <pre><code>syntax error near unexpected token `)' </code></pre> <p>Then I tried using a regex:</p> <pre><code>case ${command} in ^$) do_default ;; ... *) do_help ;; esac </code></pre> <p>With this, an empty <code>${command}</code> falls through to the <code>*</code> case.</p> <p>Am I trying to do the impossible?</p>
17,575,693
3
1
null
2013-07-10 15:56:02.44 UTC
11
2020-03-01 21:41:27.56 UTC
2020-03-01 21:41:27.56 UTC
null
6,862,601
null
770,123
null
1
102
string|bash|null|case
50,767
<p>The <code>case</code> statement uses globs, not regexes, and insists on exact matches.</p> <p>So the empty string is written, as usual, as <code>""</code> or <code>''</code>:</p> <pre><code>case "$command" in "") do_empty ;; something) do_something ;; prefix*) do_prefix ;; *) do_other ;; esac </code></pre>
18,360,225
elastic search, is it possible to update nested objects without updating the entire document?
<p>I'm indexing a set of documents (imagine them as forum posts) with a nested object which is the user related to that post. My problem is that the user fields might be updated, but since the posts do not change they are not reindexed and the user nested objects become outdated. Is there a way to update the nested objects without reindexing the whole document again? Or the only solution would be to reindex all the related posts of a user everytime that the user changes?</p>
18,361,387
3
0
null
2013-08-21 14:29:40.757 UTC
13
2022-04-28 18:29:39.823 UTC
2016-12-13 09:05:55.387 UTC
null
4,723,795
null
693,628
null
1
41
elasticsearch
40,788
<p>You can use the Update API. </p> <pre><code>curl -XPOST localhost:9200/docs/posts/post/_update -d '{ "script" : "ctx._source.nested_user = updated_nested_user", "params" : { "updated_nested_user" : {"field": "updated"} } }' </code></pre> <p>See this <a href="https://stackoverflow.com/questions/15722197/updating-indexed-document-in-elasticsearch">SO answer</a> for full detail.</p> <p>Note that update scripts support conditional logic, as shown <a href="http://www.elastic.co/guide/en/elasticsearch/reference/current/docs-update.html" rel="noreferrer">here</a>. So you could tag forum posts when the user changes, then iterate over the posts to update only posts with changed users.</p> <pre><code>curl -XPOST 'localhost:9200/docs/posts/post/_update' -d '{ "script" : "ctx._source.tags.contains(tag) ? "ctx._source.nested_user = updated_nested_John" : ctx.op = "none"", "params" : { "tag": "updated_John_tag", "updated_nested_John" : {"field": "updated"} } }' </code></pre> <p><em>UPDATED</em></p> <p>Perhaps my ternary operator example was incomplete. This was not mentioned in the question, but assuming that users change their info in a separate part of the app, it would be nice to apply those changes to the forum posts in one script. Instead of using tags, try checking the user field directly for changes:</p> <pre><code>curl -XPOST 'localhost:9200/docs/posts/post/_update' -d '{ "script" : "ctx._source.nested_user.contains(user) ? "ctx._source.nested_user = updated_nested_John" : ctx.op = "none"", "params" : { "user": "John", "updated_nested_John" : {"field": "updated"} } }' </code></pre> <p>As mentioned, though, this may be a slower operation than reindexing the full posts.</p>
18,684,579
How do I change the highlight color for selected text with Emacs / deftheme?
<p>I'm using Emacs 24; I've installed the <strong>zenburn</strong> theme, which is great, except I cannot see the selection highlight easily with the highlight color provided by <strong>zenburn</strong>:</p> <p><img src="https://i.stack.imgur.com/pZwnZ.png" alt="enter image description here"></p> <p>By <strong>"selection"</strong> color, I mean the color of text that I've selected by setting a mark (<code>C-space</code> and moving the cursor to select text).</p> <p>For the life of me, I cannot figure out how to change it. I've tried changing every combination of <code>highlight</code>, <code>selection</code>, etc.. that I can think of in <code>zenburn-theme.el</code>, but nothing seems to change it. </p> <p>**For sanity's sake, I've tried changing other colors in the theme to make sure Emacs is loading the file properly - it is - those changes work.*</p> <p>I would have especially thought that changing <code>highlight</code> would work, but no customizations to the <code>highlight</code> line seem to work:</p> <pre><code>;;;; Built-in ;;;;; basic coloring ... `(highlight ((t (:background ,zenburn-bg-05 :foreground ,zenburn-yellow)))) </code></pre> <p>How can I change the selection color?</p>
18,685,171
3
0
null
2013-09-08 14:03:48.857 UTC
9
2017-01-24 22:32:28.507 UTC
2013-09-08 14:09:07.677 UTC
null
18,505
null
18,505
null
1
69
emacs
20,830
<p>What you're looking for is the <code>region</code> face. For example:</p> <pre><code>(set-face-attribute 'region nil :background "#666") </code></pre>
25,952,348
Laravel: Run migrations on another database
<p>In my app every user has its own database that created when user registered. Connection and database data (database name, username, password) are saved in a table in default database.</p> <pre><code>try{ DB::transaction(function() { $website = new Website(); $website-&gt;user_id = Auth::get()-&gt;id; $website-&gt;save(); $database_name = 'website_'.$website-&gt;id; DB::statement(DB::raw('CREATE DATABASE ' . $database_name)); $websiteDatabase = new WebsiteDatabase(); $websiteDatabase-&gt;website_id = $website-&gt;id; $websiteDatabase-&gt;database_name = $database_name; $websiteDatabase-&gt;save(); }); } catch(\Exception $e) { echo $e-&gt;getMessage(); } </code></pre> <p>Now I want to run some migrations on new user's database after its creation.</p> <p>Is it possible?</p> <p>thanks</p>
60,374,390
8
2
null
2014-09-20 19:08:13.703 UTC
7
2020-02-24 10:55:00.713 UTC
2014-09-21 17:36:02.27 UTC
null
1,953,536
null
1,953,536
null
1
33
laravel|laravel-4|database-migration|multi-tenant
52,681
<p>If you mean using different database connection, it exists in the docs:</p> <pre><code>Schema::connection('foo')-&gt;create('users', function (Blueprint $table) { $table-&gt;bigIncrements('id'); }); </code></pre>
12,507,244
How to check value length with using Javascript?
<p>Hello everyone I would like to ask how to check value's length from textbox ?</p> <p>Here is my code :</p> <pre><code>@*&lt;script&gt; function validateForm() { var x = document.forms["frm"]["txtCardNumber"].value; if (x == null || x == "" ) { alert("First name must be filled out"); return false; } } &lt;/script&gt;*@ </code></pre> <p>When I run my script yeap I got alert message but I'm trying to add property which control the texbox' input length.</p>
12,507,258
2
0
null
2012-09-20 06:40:46.013 UTC
null
2012-09-20 06:45:51.513 UTC
null
null
null
null
1,682,416
null
1
3
javascript
46,084
<p>You could use <code>x.length</code> to get the length of the string:</p> <pre><code>if (x.length &lt; 5) { alert('please enter at least 5 characters'); return false; } </code></pre> <p>Also I would recommend you using the <a href="https://developer.mozilla.org/en-US/docs/DOM/document.getElementById" rel="noreferrer"><code>document.getElementById</code></a> method instead of <code>document.forms["frm"]["txtCardNumber"]</code>.</p> <p>So if you have an input field:</p> <pre><code>&lt;input type="text" id="txtCardNumber" name="txtCardNumber" /&gt; </code></pre> <p>you could retrieve its value from the id:</p> <pre><code>var x = document.getElementById['txtCardNumber'].value; </code></pre>
51,620,139
ImportError: No module named 'flask_sqlalchemy' w/ 2 Versions of Python Installed
<p>Tried running a file with the following imports:</p> <pre><code>from flask_sqlalchemy import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker </code></pre> <p>Received the following error:</p> <pre><code>ImportError: No module named 'flask_sqlalchemy' </code></pre> <p>SQLAlchemy is installed. Still, I tried to reinstall into the directory in which it will be used. I got this:</p> <pre><code>The directory '/Users/_/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/Users/_/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Requirement already satisfied: Flask-SQLAlchemy in /Library/Python/2.7/site-packages (2.3.2) Requirement already satisfied: Flask&gt;=0.10 in /Library/Python/2.7/site-packages (from Flask-SQLAlchemy) (1.0.2) Requirement already satisfied: SQLAlchemy&gt;=0.8.0 in /Library/Python/2.7/site-packages (from Flask-SQLAlchemy) (1.2.10) Requirement already satisfied: Jinja2&gt;=2.10 in /Library/Python/2.7/site-packages (from Flask&gt;=0.10-&gt;Flask-SQLAlchemy) (2.10) Requirement already satisfied: itsdangerous&gt;=0.24 in /Library/Python/2.7/site-packages (from Flask&gt;=0.10-&gt;Flask-SQLAlchemy) (0.24) Requirement already satisfied: Werkzeug&gt;=0.14 in /Library/Python/2.7/site-packages (from Flask&gt;=0.10-&gt;Flask-SQLAlchemy) (0.14.1) Requirement already satisfied: click&gt;=5.1 in /Library/Python/2.7/site-packages (from Flask&gt;=0.10-&gt;Flask-SQLAlchemy) (6.7) Requirement already satisfied: MarkupSafe&gt;=0.23 in /Library/Python/2.7/site-packages (from Jinja2&gt;=2.10-&gt;Flask&gt;=0.10-&gt;Flask-SQLAlchemy) (1.0) </code></pre> <p>The bit about me not owning the directory is incorrect. I'm the only one on this machine. I own everything. </p> <p>Anyway, I go back to rerun the file and get the same error message. So, it's installed, but not installed or, at the very least, not available to me. </p> <p>One error message I saw when I commented out one of the import statements read as follows:</p> <pre><code>File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/sqlalchemy/engine/strategies.py </code></pre> <p>I have no clue how to fix this and get SQLAlchemy up and running. I've burned over 1.5 hours on it. The last error listed suggests having 2 versions of python may have something to do with it. </p> <p>Your thoughts on a remedy would be appreciated. </p>
60,438,611
14
19
null
2018-07-31 18:46:41.123 UTC
1
2022-06-17 23:48:59.627 UTC
null
null
null
null
3,828,443
null
1
8
python|sqlalchemy|flask-sqlalchemy
39,257
<p>Ultimately, I resolved this issue ages after I posted the above question. </p> <p>The fix was to run all package updates and installs thru Anaconda and do my work in Spyder. </p> <p>The lesson learned was simple: Once you start using Anaconda as your go-to environment for all things Python, all updates -- made via conda install or pip -- will be orchestrated and placed in your system by Anaconda by default.</p>
5,000,213
How to Set the Checkbox on the right side of the text
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/3156781/how-to-show-android-checkbox-at-right-side">How to show android checkbox at right side?</a> </p> </blockquote> <p>In my android application, I have a checkbox and some text associate with it. By default the texts are in the right side and the checkbox in left side. But I want to put the checkbox on the right side. Help me please.</p>
5,000,285
3
1
null
2011-02-15 05:31:40.47 UTC
3
2015-09-14 10:06:37.8 UTC
2017-05-23 10:27:45.9 UTC
null
-1
null
595,543
null
1
27
android|checkbox
47,316
<p>I dont know whether it is possible or not by styling ,</p> <p>But here is a solution for you</p> <p>Use <code>""</code> as the value of the <code>CheckBox</code> ,then add a <code>TextView</code> to the left of the <code>CheckBox</code> with your desired text.</p>
5,013,163
How can I check/upgrade Proguard version when using it in Eclipse for Android development?
<p>The documentation on this is extremely poor. I understand that ProGuard can be enabled by manually editing "default.properties" in the project's rot directory. And all the settings go into the "proguard.cfg" file in the same place, but I'd like to know which version of ProGuard is being used (I'm using Eclise Indigo). I would also like to be able to upgrade it to the latest versions whenever the are released. But I can't find any reference on how to do it.</p>
5,023,215
3
0
null
2011-02-16 06:24:51.123 UTC
10
2020-12-27 11:29:05.08 UTC
2020-12-27 11:29:05.08 UTC
null
1,127,485
null
496,854
null
1
32
android|eclipse|obfuscation|proguard
16,006
<p>The ProGuard jar is located inside the Android SDK: android-sdk/tools/proguard/lib/proguard.jar</p> <p>You can print out its version number with</p> <pre><code>java -jar android-sdk/tools/proguard/lib/proguard.jar </code></pre> <p>(with the proper path). If necessary, you can <strong>replace the jar</strong> (actually, the entire <code>proguard</code> subdirectory) with the latest version from the <a href="http://proguard.sourceforge.net/downloads.html" rel="noreferrer">download page</a> at the official ProGuard site.</p>
5,116,296
How to drop multiple databases in SQL Server
<p>Just to clarify, ths isn't really a question, more some help for people like me who were looking for an answer.<br> A lot of applications create temp tables and the like, but I was surprised when Team Foundation Server created 80+ databases on my test SQL Server. TFS didn't install correctly, and kindly left me to clear up after it. Since each database had a naming convention, rather than delete each database by hand, I remembered how to use cursors and have written what I view to be the most unwise piece of T-SQL ever:</p> <pre><code> CREATE TABLE #databaseNames (name varchar(100) NOT NULL, db_size varchar(50), owner varchar(50), dbid int, created date, status text, compatibility_level int); INSERT #databaseNames exec sp_helpdb; DECLARE dropCur CURSOR FOR SELECT name FROM #databaseNames WHERE name like '_database_name_%'; OPEN dropCur; DECLARE @dbName nvarchar(100); FETCH NEXT FROM dropCur INTO @dbName; DECLARE @statement nvarchar(200); WHILE @@FETCH_STATUS = 0 BEGIN SET @statement = 'DROP DATABASE ' + @dbName; EXEC sp_executesql @statement; FETCH NEXT FROM dropCur INTO @dbName; END CLOSE dropCur; DEALLOCATE dropCur; DROP TABLE #databaseNames; </code></pre> <p>It goes without saying that using cursors like this is probably really dangerous, and should be used with extreme caution. This worked for me, and I haven't seen any further damage to my database yet, but I disclaim: use this code at your own risk, and back up your vital data first!<br> Also, if this should be deleted because it's not a question, I understand. Just wanted to post this somewhere people would look.</p>
8,791,560
3
1
null
2011-02-25 10:49:10.49 UTC
11
2019-07-31 04:58:04.63 UTC
2014-03-25 00:39:19.997 UTC
null
881,229
null
419,426
null
1
33
database|tsql|sql-drop
41,844
<p>this is easy...</p> <pre><code>use master go declare @dbnames nvarchar(max) declare @statement nvarchar(max) set @dbnames = '' set @statement = '' select @dbnames = @dbnames + ',[' + name + ']' from sys.databases where name like 'name.of.db%' if len(@dbnames) = 0 begin print 'no databases to drop' end else begin set @statement = 'drop database ' + substring(@dbnames, 2, len(@dbnames)) print @statement exec sp_executesql @statement end </code></pre>
43,331,510
How to train an SVM classifier on a satellite image using Python
<p>I am using <code>scikit-learn</code> library to perform a supervised classification (Support Vector Machine classifier) on a satellite image. My main issue is how to train my SVM classifier. I have watched many videos on youtube and have read a few tutorials on how to train an SVM model in <code>scikit-learn</code>. All the tutorials I have watched, they used the famous Iris datasets. In order to perform a supervised SVM classification in <code>scikit-learn</code> we need to have labels. For Iris datasets we have the <code>Iris.target</code> which is the labels ('setosa', 'versicolor', 'virginica') we are trying to predict. The procedure of training is straightforward by reading the <code>scikit-learn</code> documentation.</p> <p>In my case, I have to train a SAR satellite image captured over an urban area and I need to classify the urban area, roads, river and vegetation (4 classes). This image has two bands but I do not have label data for each class I am trying to predict such as the Iris data. </p> <p>So, my question is, do I have to manually create vector data (for the 4 classes) in order to train the SVM model? Is there an easier way to train the model than manually creating vector data? What do we do in this case?</p> <p>I am bit confused to be honest. I would appreciate any help</p>
43,453,194
2
4
null
2017-04-10 19:29:23.733 UTC
10
2021-05-07 13:38:11.053 UTC
2017-04-17 15:01:10.56 UTC
null
6,160,119
null
7,133,523
null
1
4
python|machine-learning|scikit-learn|svm|k-means
6,937
<p>Here's a complete example that should get you on the right track. For the sake of simplicity, let us assume that your goal is that of classifying the pixels on the three-band image below into three different categories, namely building, vegetation and water. Those categories will be displayed in red, green and blue color, respectively.</p> <p><a href="https://i.stack.imgur.com/TFOv7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TFOv7.png" alt="New York"></a></p> <p></p> <p>We start off by reading the image and defining some variables that will be used later on.</p> <pre><code>import numpy as np from skimage import io img = io.imread('https://i.stack.imgur.com/TFOv7.png') rows, cols, bands = img.shape classes = {'building': 0, 'vegetation': 1, 'water': 2} n_classes = len(classes) palette = np.uint8([[255, 0, 0], [0, 255, 0], [0, 0, 255]]) </code></pre> <h2>Unsupervised classification</h2> <p>If you don't wish to manually label some pixels then you need to detect the underlying structure of your data, i.e. you have to split the image pixels into <code>n_classes</code> partitions, for example through <a href="https://en.wikipedia.org/wiki/K-means_clustering" rel="noreferrer">k-means clustering</a>:</p> <pre><code>from sklearn.cluster import KMeans X = img.reshape(rows*cols, bands) kmeans = KMeans(n_clusters=n_classes, random_state=3).fit(X) unsupervised = kmeans.labels_.reshape(rows, cols) io.imshow(palette[unsupervised]) </code></pre> <p><a href="https://i.stack.imgur.com/pqm5T.png" rel="noreferrer"><img src="https://i.stack.imgur.com/pqm5T.png" alt="unsupervised classification"></a></p> <h2>Supervised classification</h2> <p>Alternatively, you could assign labels to some pixels of known class (the set of labeled pixels is usually referred to as <em>ground truth</em>). In this toy example the ground truth is made up of three hardcoded square regions of 20&times;20 pixels shown in the following figure:</p> <p><a href="https://i.stack.imgur.com/W9oUY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/W9oUY.png" alt="ground truth"></a></p> <pre><code>supervised = n_classes*np.ones(shape=(rows, cols), dtype=np.int) supervised[200:220, 150:170] = classes['building'] supervised[40:60, 40:60] = classes['vegetation'] supervised[100:120, 200:220] = classes['water'] </code></pre> <p>The pixels of the ground truth (training set) are used to fit a support vector machine. </p> <pre><code>y = supervised.ravel() train = np.flatnonzero(supervised &lt; n_classes) test = np.flatnonzero(supervised == n_classes) from sklearn.svm import SVC clf = SVC(gamma='auto') clf.fit(X[train], y[train]) y[test] = clf.predict(X[test]) supervised = y.reshape(rows, cols) io.imshow(palette[supervised]) </code></pre> <p>After the training stage, the classifier assigns class labels to the remaining pixels (test set). The classification results look like this:</p> <p><a href="https://i.stack.imgur.com/kPuK5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kPuK5.png" alt="supervised classification"></a></p> <h2>Final remarks</h2> <p>Results seem to suggest that unsupervised classification is more accurate than its supervised counterpart. However, supervised classification generally outperforms unsupervised classification. It is important to note that in the analyzed example accuracy could be dramatically improved by adjusting the parameters of the SVM classifier. Further improvement could be achieved by enlarging and refining the ground truth, since the train/test ratio is very small and the red and green patches actually contain pixels of different classes. Finally, one can reasonably expect that utilizing more sophisticated features such as ratios or indices computed from the intensity levels (for instance <a href="https://en.wikipedia.org/wiki/Normalized_difference_vegetation_index" rel="noreferrer">NDVI</a>) would boost performance.</p>
43,388,893
What is the difference between [ngFor] and [ngForOf] in angular2?
<p>As per my understanding, <em>Both are doing the same</em> functions. But,</p> <ul> <li><p><code>ngFor</code> would be works like as <a href="https://www.tutorialspoint.com/csharp/csharp_collections.htm" rel="noreferrer">collections</a>?.</p></li> <li><p><code>ngForOf</code> would be works like as <a href="https://www.tutorialspoint.com/csharp/csharp_generics.htm" rel="noreferrer">generics</a>?.</p></li> </ul> <hr> <blockquote> <p><strong>Is my understanding is correct? or Could you please share more difference's(details) about <code>ngFor</code> and <code>ngForOf</code>?</strong></p> </blockquote>
43,389,260
5
4
null
2017-04-13 09:47:34.547 UTC
7
2020-01-04 11:35:57.377 UTC
2019-10-09 08:48:05.597 UTC
null
2,218,635
null
2,218,635
null
1
59
angular|typescript|ngfor
45,270
<p><code>ngFor</code> and <code>ngForOf</code> are not two distinct things - they are actually the selectors of the NgForOf directive.</p> <p>If you examine the <a href="https://github.com/angular/angular/blob/master/packages/common/src/directives/ng_for_of.ts" rel="noreferrer">source</a>, you'll see that the NgForOf directive has as its selector: <code>[ngFor][ngForOf]</code> , meaning that both attributes need to be present on an element for the directive to 'activate' so to speak.</p> <p>When you use <code>*ngFor</code>, the Angular compiler de-sugars that syntax into its cannonical form which has both attributes on the element.</p> <p>So,</p> <pre><code> &lt;div *ngFor="let item of items"&gt;&lt;/div&gt; </code></pre> <p>desugars to:</p> <pre><code> &lt;template [ngFor]="let item of items"&gt; &lt;div&gt;&lt;/div&gt; &lt;/template&gt; </code></pre> <p>This first de-sugaring is due to the '*'. The next de-sugaring is because of the micro syntax: "let item of items". The Angular compiler de-sugars that to:</p> <pre><code> &lt;template ngFor let-item="$implicit" [ngForOf]="items"&gt; &lt;div&gt;...&lt;/div&gt; &lt;/template&gt; </code></pre> <p><em>(where you can think of $implicit as an internal variable that the directive uses to refer to the current item in the iteration).</em></p> <p>In its canonical form, the ngFor attribute is just a marker, while the ngForOf attribute is actually an input to the directive that points to the the list of things you want to iterate over.</p> <p>You can check out the <a href="https://angular.io/docs/ts/latest/guide/structural-directives.html#!#microsyntax" rel="noreferrer">Angular microsyntax guide</a> to learn more.</p>
18,583,881
Changing Persistence Unit dynamically - JPA
<p>Persistence units in persistence.xml are created during building the application. As I want to change the database url at runtime, is there any way to modify the persistence unit at runtime? I supposed to use different database other than pre-binded one after distributed.</p> <p>I'm using EclipseLink (JPA 2.1)</p>
18,733,128
4
2
null
2013-09-03 04:01:48.933 UTC
13
2020-08-13 13:20:11.12 UTC
null
null
null
null
2,264,512
null
1
18
java|jpa|persistence.xml
19,080
<p>Keep the persistence unit file (Persistence.xml) as it's. You can override the properties in it as follows.</p> <pre><code>EntityManagerFactory managerFactory = null; Map&lt;String, String&gt; persistenceMap = new HashMap&lt;String, String&gt;(); persistenceMap.put("javax.persistence.jdbc.url", "&lt;url&gt;"); persistenceMap.put("javax.persistence.jdbc.user", "&lt;username&gt;"); persistenceMap.put("javax.persistence.jdbc.password", "&lt;password&gt;"); persistenceMap.put("javax.persistence.jdbc.driver", "&lt;driver&gt;"); managerFactory = Persistence.createEntityManagerFactory("&lt;current persistence unit&gt;", persistenceMap); manager = managerFactory.createEntityManager(); </code></pre>
18,683,421
why do I get "Invalid appsecret_proof provided in the API argument"
<p>Since the latest change on Facebook, regarding the appsecret_proof: <a href="https://developers.facebook.com/docs/reference/api/securing-graph-api/">https://developers.facebook.com/docs/reference/api/securing-graph-api/</a>, we are still unable to download performance reports even after enabling/disabling features from Advanced Settings in our app, or apply the code as described in their document.</p> <p>We are constantly getting this error:</p> <blockquote> <p>{"error":{"message":"Invalid appsecret_proof provided in the API argument","type":"GraphMethodException","code":100}}</p> </blockquote> <p>and I've open a confidential bug but no one returns to me with an answer.</p> <p>I really don't know what more could we try? </p>
18,690,810
15
0
null
2013-09-08 11:58:03.46 UTC
3
2021-07-29 10:12:08.067 UTC
2013-09-08 12:45:33.127 UTC
null
1,343,690
null
1,508,682
null
1
52
facebook|facebook-graph-api|app-secret
82,050
<p>The error is (based on my experience) almost certainly correct; it means you're proving an invalid appsecret_proof with your API call</p> <p>Assuming you're using the standard PHP SDK without modifications, the most likely reasons for this are:</p> <ul> <li>You configured the wrong app ID in the SDK code</li> <li>You configured the wrong app secret in the SDK code</li> <li>You're trying to use an access token from the wrong / another app</li> </ul>
14,992,879
Node.js mysql query syntax issues UPDATE WHERE
<p>I trying to update some info in MYSQL DB, but I'm not sure of how to do it with in node.js. This is the mysql driver I'm using <a href="https://github.com/felixge/node-mysql" rel="noreferrer">https://github.com/felixge/node-mysql</a></p> <p>What I have so far</p> <pre><code>connection.query('SELECT * FROM users WHERE UserID = ?', [userId], function(err, results) { if (results[0]) { if (results[0].Name!=name) { console.log(results[0].Name); connection.query('UPDATE users SET ? WHERE UserID = ?', [userId], {Name: name}); } console.log(results[0].UserID); } }); </code></pre> <p>Everything works except...</p> <pre><code>connection.query('UPDATE users SET ? WHERE UserID = ?', [userId], {Name: name}); </code></pre> <p>In PHP I would have this...</p> <pre><code>mysql_query("UPDATE users SET Name='".$_GET["name"]."' WHERE UserID='".$row['UserID']."'"); </code></pre> <p>I'm not sure what I'm doing wrong, But I'm positive that the issue is here</p> <pre><code>connection.query('UPDATE users SET ? WHERE UserID = ?', [userId], {Name: name}); </code></pre>
14,993,148
5
0
null
2013-02-21 01:03:32.587 UTC
12
2021-04-16 02:59:44.173 UTC
2017-09-15 08:59:20.387 UTC
null
125,816
null
2,073,984
null
1
26
mysql|node.js
75,769
<p>[<strong>Note (added 2016-04-29):</strong> This answer was accepted, but it turns out that there <em>is</em> a reasonable way to use <code>SET ?</code>. For details, see Bala Clark's answer on this same page. <em>&mdash;ruakh</em>]</p> <hr> <p>From <a href="https://github.com/felixge/node-mysql/blob/master/lib/Connection.js" rel="noreferrer">the code for <code>Connection.prototype.query()</code> and <code>Connection.createQuery()</code></a>, it's clear that you can only pass in a <em>single</em> values object. I don't see where the code for the special <code>SET ?</code> behavior is defined &mdash; it's clearly not in <a href="https://github.com/felixge/node-mysql/blob/master/lib/protocol/SqlString.js#L61" rel="noreferrer"><code>SqlString.formatQuery()</code></a> &mdash; but if it uses <a href="https://github.com/felixge/node-mysql/blob/master/lib/protocol/SqlString.js#L110" rel="noreferrer"><code>SqlString.objectToValues()</code></a>, then I guess there's no way to use it together with another <code>?</code>.</p> <p>I think the best approach is to just dispense with the neat <code>SET ?</code> feature, and write either of these:</p> <pre><code>connection.query('UPDATE users SET Name = ? WHERE UserID = ?', [name, userId]) </code></pre> <pre><code>connection.query('UPDATE users SET Name = :Name WHERE UserID = :UserID', {UserID: userId, Name: name}) </code></pre> <p>but if you really want to use <code>SET ?</code>, I suppose you could write this:</p> <pre><code>connection.query('UPDATE users SET ? WHERE UserID = :UserID', {UserID: userId, Name: name}) </code></pre> <p>which would update both <code>UserID</code> and <code>Name</code>; unless you have a trigger, this <em>should</em> be O.K., in that it's updating <code>UserID</code> to the value it already had anyway. But it's kind of disconcerting, and I don't recommend it.</p>
15,031,386
How do I disable proguard for building my Android app?
<p>It used to be that proguard was controlled by project.properties, but that's no longer the case, and the Android documentation has not been updated. The project.properties file now clearly states that the it is generated by Android Tools and changes will be erased. I've tried commenting out the proguard.config line, but when I compile, it rewrites the project.properties, and continues to use proguard. What is the current method of disabling proguard? Thanks!</p> <pre><code># This file is automatically generated by Android Tools. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must be checked in Version Control Systems. # # To customize properties used by the Ant build system edit # "ant.properties", and override values to adapt the script to your # project structure. # # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt:proguard-google-api-client.txt # Project target. target=android-17 android.library.reference.1=../../../../android-sdk-linux/extras/google/google_play_services/libproject/google-play-services_lib </code></pre>
15,031,801
6
5
null
2013-02-22 19:03:51.673 UTC
2
2022-05-17 11:01:37.733 UTC
2013-02-22 19:24:00.02 UTC
null
528,934
null
528,934
null
1
29
android
55,930
<p>Try to delete the proguard directory in your project. So proguard will forget its mapping.</p>
15,268,953
How to install Python package from GitHub?
<p>I want to use a new feature of httpie. This feature is in the github repo <a href="https://github.com/jkbr/httpie" rel="noreferrer">https://github.com/jkbr/httpie</a> but not in the release on the python package index <a href="https://pypi.python.org/pypi/httpie" rel="noreferrer">https://pypi.python.org/pypi/httpie</a> </p> <p>How can I install the httpie package from the github repo? I tried</p> <pre><code>pip install https://github.com/jkbr/httpie </code></pre> <p>But I got an error 'could not unpack'</p> <hr> <p>In Nodejs, I can install packages from github like this</p> <pre><code>npm install git+https://github.com/substack/node-optimist.git </code></pre>
15,268,990
2
1
null
2013-03-07 10:39:33.68 UTC
132
2021-09-16 23:37:30.927 UTC
null
null
null
null
284,795
null
1
312
python|pip
426,477
<p>You need to use the proper git URL:</p> <pre><code>pip install git+https://github.com/jkbr/httpie.git#egg=httpie </code></pre> <p>Also see the <a href="https://pip.pypa.io/en/stable/topics/vcs-support/" rel="noreferrer"><em>VCS Support</em> section</a> of the pip documentation.</p> <p>Don’t forget to include the <code>egg=&lt;projectname&gt;</code> part to <a href="https://pip.pypa.io/en/stable/cli/pip_install/#working-out-the-name-and-version" rel="noreferrer">explicitly name the project</a>; this way pip can track metadata for it without having to have run the setup.py script.</p>
8,007,993
In Android, check if sqlite database exists fails from time to time
<p>In Android I use the following method to see if the sqlite database exist and if I can open it and use it. </p> <p>If it fail this test I copy the database file from the assets (this should only happen once, when the user first start the app).</p> <pre><code>/* * Check if the database already exist to avoid re-copying the file each time you open the application. * @return true if it exists, false if it doesn't */ private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH + DB_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } catch(SQLiteException e) { //database does't exist yet. } if(checkDB != null){ checkDB.close(); } return checkDB != null ? true : false; } </code></pre> <p>The problem is that I get reports from users saying that their data has been wiped out and when investigating I can see that the database is replaced with the database from the assets. So for some reason even if the user already has a database file sometimes the SQLiteDatabase.openDatabase() throws an error. I haven't been able to reproduce the issue myself but it seems to happen for some users.</p> <p>Anyone have an idea what the problem might be here? Is there a better way to do this test?</p>
8,011,264
2
1
null
2011-11-04 10:37:29.047 UTC
10
2014-01-26 08:35:05.773 UTC
null
null
null
null
611,494
null
1
8
android|database|sqlite
23,708
<p>How about just checking the filesystem to see if the database exists instead of trying to open it first? </p> <p>You could be trying to open a database that is already open and that will throw an error causing you to think it does not exist.</p> <pre><code>File database=getApplicationContext().getDatabasePath("databasename.db"); if (!database.exists()) { // Database does not exist so copy it from assets here Log.i("Database", "Not Found"); } else { Log.i("Database", "Found"); } </code></pre>
9,200,268
invalid conversion from ‘const char*’ to ‘char*’ [-fpermissive]
<pre><code>int :: cadena calculatelenght(const cadena&amp; a, const char* cad) { cadena c; int lenght = 0; char* punt; punt = cad; while(*punt){ lenght++; punt++; } return lenght; } </code></pre> <p>I have this problem, I want to calculate the length of a C string without using functions like <code>strlen</code>, in other methods of my cadena class I can because is not const char*, but now I don't know what to do.</p>
9,200,337
2
13
null
2012-02-08 19:42:17.91 UTC
2
2012-11-23 00:38:24.07 UTC
2012-02-08 21:27:47.34 UTC
null
53,974
null
646,565
null
1
9
c++|c|string
60,852
<p>You can declare <code>punt</code> to be of the correct type:</p> <pre><code>const char * punt = cad; </code></pre>
8,708,632
Passing Objects By Reference or Value in C#
<p>In C#, I have always thought that non-primitive variables were passed by reference and primitive values passed by value.</p> <p>So when passing to a method any non-primitive object, anything done to the object in the method would effect the object being passed. (C# 101 stuff)</p> <p>However, I have noticed that when I pass a System.Drawing.Image object, that this does not seem to be the case? If I pass a system.drawing.image object to another method, and load an image onto that object, then let that method go out of scope and go back to the calling method, that image is not loaded on the original object?</p> <p>Why is this?</p>
8,708,674
9
3
null
2012-01-03 06:19:54.33 UTC
112
2021-09-28 17:36:59.353 UTC
2016-10-13 05:55:21.823 UTC
null
661,933
null
902,012
null
1
308
c#|parameter-passing|pass-by-reference|pass-by-value
302,112
<p><em>Objects</em> aren't passed at all. By default, the argument is evaluated and its <em>value</em> is passed, by value, as the initial value of the parameter of the method you're calling. Now the important point is that the value is a reference for reference types - a way of getting to an object (or null). Changes to that object will be visible from the caller. However, changing the value of the parameter to refer to a different object will <em>not</em> be visible when you're using pass by value, which is the default for <em>all</em> types.</p> <p>If you want to use pass-by-reference, you <em>must</em> use <code>out</code> or <code>ref</code>, whether the parameter type is a value type or a reference type. In that case, effectively the variable itself is passed by reference, so the parameter uses the same storage location as the argument - and changes to the parameter itself are seen by the caller.</p> <p>So:</p> <pre><code>public void Foo(Image image) { // This change won't be seen by the caller: it's changing the value // of the parameter. image = Image.FromStream(...); } public void Foo(ref Image image) { // This change *will* be seen by the caller: it's changing the value // of the parameter, but we're using pass by reference image = Image.FromStream(...); } public void Foo(Image image) { // This change *will* be seen by the caller: it's changing the data // within the object that the parameter value refers to. image.RotateFlip(...); } </code></pre> <p>I have an <a href="http://pobox.com/~skeet/csharp/parameters.html" rel="noreferrer">article which goes into a lot more detail in this</a>. Basically, "pass by reference" doesn't mean what you think it means.</p>
8,702,603
Merging two objects in C#
<p>I have an object model <code>MyObject</code> with various properties. At one point, I have two instances of these <code>MyObject</code>: instance A and instance B. I'd like to copy and replace the properties in instance A with those of instance B if instance B has non-null values.</p> <p>If I only had 1 class with 3 properties, no problem, I could easily hard code it (which is what I started doing). But I actually have 12 different object models with about 10 properties each.</p> <p>What's good way to do this?</p>
8,702,650
7
5
null
2012-01-02 15:36:19.54 UTC
12
2022-09-12 22:44:44.607 UTC
2022-09-12 22:44:44.607 UTC
null
11,178,549
null
565,968
null
1
60
c#|.net
107,725
<p><strong>Update</strong> Use <a href="https://github.com/AutoMapper/AutoMapper" rel="noreferrer">AutoMapper</a> instead if you need to invoke this method a lot. Automapper builds dynamic methods using <code>Reflection.Emit</code> and will be much faster than reflection.'</p> <p>You could copy the values of the properties using reflection:</p> <pre><code>public void CopyValues&lt;T&gt;(T target, T source) { Type t = typeof(T); var properties = t.GetProperties().Where(prop =&gt; prop.CanRead &amp;&amp; prop.CanWrite); foreach (var prop in properties) { var value = prop.GetValue(source, null); if (value != null) prop.SetValue(target, value, null); } } </code></pre> <p>I've made it generic to ensure type safety. If you want to include private properties you should use an override of <a href="http://msdn.microsoft.com/en-us/library/system.type.getproperties.aspx" rel="noreferrer">Type.GetProperties()</a>, specifying binding flags.</p>
5,507,026
before_filter with parameters
<p>I have a method that does something like this:</p> <pre><code>before_filter :authenticate_rights, :only =&gt; [:show] def authenticate_rights project = Project.find(params[:id]) redirect_to signin_path unless project.hidden end </code></pre> <p>I also want to use this method in some other Controllers, so i copied the method to a helper that is included in the application_controller.</p> <p>the problem is, that in some controllers, the id for the project isn't the <code>:id</code> symbol but f.e. <code>:project_id</code> (and also a <code>:id</code> is present (for another model)</p> <p>How would you solve this problem? is there an option to add a parameter to the before_filter action (to pass the right param)?</p>
5,507,401
5
0
null
2011-03-31 22:17:50.233 UTC
18
2016-05-18 05:40:58.663 UTC
2015-11-07 15:01:29.69 UTC
null
2,202,702
null
253,288
null
1
85
ruby-on-rails|ruby|ruby-on-rails-3|before-filter
44,493
<p>I'd do it like this:</p> <pre><code>before_filter { |c| c.authenticate_rights correct_id_here } def authenticate_rights(project_id) project = Project.find(project_id) redirect_to signin_path unless project.hidden end </code></pre> <p>Where <code>correct_id_here</code> is the relevant id to access a <code>Project</code>.</p>
5,300,047
JPA TemporalType.Date giving wrong date
<p>I have a class that has a date field representing a "valid from" date for a piece of data. It is defined like this:</p> <pre><code>@Temporal( TemporalType.DATE ) private Date validFrom; </code></pre> <p>All seems to be working fine right up the the point where I pull the date from the database and display it. If I select the date 18-Sep-2003 in the front end then save it when I check in the database sure enough that is the date held (database is MySQL 5.5.9 column type is DATE). However when I pull up a list records the date shown is 17 Sep 2003 - one day earlier.</p> <p>If I choose a date early or late in the year like 26 Mar 2003 or 25 Dec 2003 everything is fine so I guessing this is something to do with daylight saving but where is the error creeping in? Since the database appears to be holding the correct date I'm guessing it must be when JPA is converting back into a java.util.Date - is java.util.Date the best class to use for a date? I've seen a few examples where people use Calendar but that seems pretty heavy weight and I'm not sure how well it will work with a JSF based front end. </p>
5,300,958
6
1
null
2011-03-14 14:36:52.83 UTC
14
2020-06-29 11:14:32.533 UTC
null
null
null
null
333,842
null
1
16
java|mysql|jpa
43,381
<p>After much experimenting and searching I'm pretty sure I've found the cause of the problem. The date is held in a java.util.Date which comes with all the baggage of time and a timezone. It would seem that JPA is reading the date 18 Sep 2003 from the database and then populating the date like this: "Thu Sep 18 00:00:00 BST 2003" - notice the timezone has been set to BST probably because it wasn't explicitly set by the database. Anyway, it is necessary to format the output in the JSF page if you only want to see the date like this:</p> <pre><code>&lt;h:outputText value="#{t.validFrom}"&gt; &lt;f:convertDateTime pattern="dd MMM yyyy"/&gt; &lt;/h:outputText&gt; </code></pre> <p>This, however, assumes that the timezone is whatever is currently in force on the machine. In my case the timezone is currently GMT (because it's winter) so when presented with the date "Thu Sep 18 00:00:00 BST 2003" it converts it to GMT by subtracting one hour leaving the display showing 17 Sep 2003.</p>
5,418,856
NuGet for solutions with multiple projects
<p>Suppose I have a solution with 3 projects:</p> <ul> <li>Core</li> <li>UI</li> <li>Tests</li> </ul> <p>Some of the NuGet packages I use will apply to all 3 projects. Some will just apply to UI and Tests, and some will just apply to Tests (like NUnit).</p> <p>What is the <strong>right</strong> way to set this up using NuGet? </p> <ol> <li>Should I use "Add Library Package Reference" on all three projects any time I need a reference? </li> <li>Should I use "Add Library Package Reference" the first time I need a package, and then use Add Reference->Browse for subsequent usages?</li> </ol> <p>In either case, how many <em>packages.config</em> files should I have?</p>
8,653,312
6
0
null
2011-03-24 12:09:09.177 UTC
40
2019-10-15 10:52:13.123 UTC
null
null
null
null
57,132
null
1
158
.net|nuget
52,999
<p>For anybody stumbling across this, now there is the following option :</p> <blockquote> <p>Right-click your solution > Manage NuGet Packages for Solution...</p> </blockquote> <p>... Or:</p> <blockquote> <p>Tools > Library Package Manager > Manage NuGet Packages for Solution...</p> </blockquote> <p>And if you go to the Installed packages area you can 'Manage' a single package across every project in the solution.</p>
5,537,622
Dynamically loading css file using javascript with callback without jQuery
<p>I am trying to load a css file dynamically using javascript and cannot use any other js library (eg jQuery).</p> <p>The css file loads but I can't seem to get a callback to work for it. Below is the code I am using</p> <pre><code>var callbackFunc = function(){ console.log('file loaded'); }; var head = document.getElementsByTagName( "head" )[0]; var fileref=document.createElement("link"); fileref.setAttribute("rel", "stylesheet"); fileref.setAttribute("type", "text/css"); fileref.setAttribute("href", url); fileref.onload = callbackFunc; head.insertBefore( fileref, head.firstChild ); </code></pre> <p>Using the following code to add a script tag to load a js file works and fires a callback:</p> <pre><code>var callbackFunc = function(){ console.log('file loaded'); }; var script = document.createElement("script"); script.setAttribute("src",url); script.setAttribute("type","text/javascript"); script.onload = callbackFunc ; head.insertBefore( script, head.firstChild ); </code></pre> <p>Am I doing something wrong here? Any other method that can help me achieve this would be much appreciated?</p>
5,537,911
7
2
null
2011-04-04 11:09:52.58 UTC
17
2020-10-14 14:44:44.56 UTC
2011-04-04 11:26:35.077 UTC
null
246,616
null
624,934
null
1
32
javascript|css|callback|loading
46,008
<p>Unfortunately there is no onload support for stylesheets in most modern browsers. There is a solution I found with a little Googling.</p> <p><strong>Cited from:</strong> <a href="http://thudjs.tumblr.com/post/637855087/stylesheet-onload-or-lack-thereof" rel="noreferrer">http://thudjs.tumblr.com/post/637855087/stylesheet-onload-or-lack-thereof</a></p> <h3>The basics</h3> <p>The most basic implementation of this can be done in a measely 30 lines of — framework independent — JavaScript code:</p> <pre><code>function loadStyleSheet( path, fn, scope ) { var head = document.getElementsByTagName( 'head' )[0], // reference to document.head for appending/ removing link nodes link = document.createElement( 'link' ); // create the link node link.setAttribute( 'href', path ); link.setAttribute( 'rel', 'stylesheet' ); link.setAttribute( 'type', 'text/css' ); var sheet, cssRules; // get the correct properties to check for depending on the browser if ( 'sheet' in link ) { sheet = 'sheet'; cssRules = 'cssRules'; } else { sheet = 'styleSheet'; cssRules = 'rules'; } var interval_id = setInterval( function() { // start checking whether the style sheet has successfully loaded try { if ( link[sheet] &amp;&amp; link[sheet][cssRules].length ) { // SUCCESS! our style sheet has loaded clearInterval( interval_id ); // clear the counters clearTimeout( timeout_id ); fn.call( scope || window, true, link ); // fire the callback with success == true } } catch( e ) {} finally {} }, 10 ), // how often to check if the stylesheet is loaded timeout_id = setTimeout( function() { // start counting down till fail clearInterval( interval_id ); // clear the counters clearTimeout( timeout_id ); head.removeChild( link ); // since the style sheet didn't load, remove the link node from the DOM fn.call( scope || window, false, link ); // fire the callback with success == false }, 15000 ); // how long to wait before failing head.appendChild( link ); // insert the link node into the DOM and start loading the style sheet return link; // return the link node; } </code></pre> <p>This would allow you to load a style sheet with an onload callback function like this:</p> <pre><code>loadStyleSheet( '/path/to/my/stylesheet.css', function( success, link ) { if ( success ) { // code to execute if the style sheet was loaded successfully } else { // code to execute if the style sheet failed to successfully } } ); </code></pre> <p>Or if you want to your callback to maintain its scope/ context, you could do something kind of like this:</p> <pre><code>loadStyleSheet( '/path/to/my/stylesheet.css', this.onComplete, this ); </code></pre>
5,060,465
Get variables from the outside, inside a function in PHP
<p>I'm trying to figure out how I can use a variable that has been set outside a function, inside a function. Is there any way of doing this? I've tried to set the variable to "global" but it doesn't seems to work out as expected.</p> <p>A simple example of my code</p> <pre><code>$var = '1'; function() { $var + 1; return $var; } </code></pre> <p>I want this to return the value of 2.</p>
5,060,486
8
1
null
2011-02-20 22:19:34.35 UTC
6
2021-02-27 22:10:10.44 UTC
2020-05-23 11:37:22.28 UTC
null
2,332,721
null
621,855
null
1
37
php|function|variables|global-variables
84,816
<p>You'll need to use the global keyword <em>inside</em> your function. <a href="http://php.net/manual/en/language.variables.scope.php">http://php.net/manual/en/language.variables.scope.php</a></p> <p><em>EDIT</em> (embarrassed I overlooked this, thanks to the commenters)</p> <p>...and store the result somewhere</p> <pre><code>$var = '1'; function() { global $var; $var += 1; //are you sure you want to both change the value of $var return $var; //and return the value? } </code></pre>
4,971,206
select TOP (all)
<pre><code>declare @t int set @t = 10 if (o = 'mmm') set @t = -1 select top(@t) * from table </code></pre> <p>What if I want generally it resulted with 10 rows, but rarely all of them.</p> <p>I know I can do this through "SET ROWCOUNT". But is there some variable number, like -1, that causing TOP to result all elements.</p>
4,971,263
9
0
null
2011-02-11 16:00:03.483 UTC
5
2022-04-28 16:22:31.487 UTC
null
null
null
null
40,789
null
1
28
sql-server
27,450
<p>The largest possible value that can be passed to <code>TOP</code> is <code>9223372036854775807</code> so you could just pass that. </p> <p>Below I use the binary form for max signed bigint as it is easier to remember as long as you know the basic pattern and that bigint is 8 bytes.</p> <pre><code>declare @t bigint = case when some_condition then 10 else 0x7fffffffffffffff end; select top(@t) * From table </code></pre> <p>If you dont have an order by clause the top 10 will just be any 10 and optimisation dependant.</p> <p>If you do have an order by clause to define the top 10 and an index to support it then the plan for the query above should be fine for either possible value.</p> <p>If you don't have a supporting index and the plan shows a sort you should consider splitting into two queries.</p>
5,596,484
ASP.NET using Bind/Eval in .aspx in If statement
<p>in my .aspx I'm looking to add in an If statement based on a value coming from the bind. I have tried the following:</p> <pre><code>&lt;% if(bool.Parse(Eval("IsLinkable") as string)){ %&gt; monkeys!!!!!! (please be aware there will be no monkeys, this is only for humour purposes) &lt;%} %&gt; </code></pre> <p>IsLinkable is a bool coming from the Binder. I get the following error:</p> <pre><code>InvalidOperationException Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control. </code></pre>
5,596,576
11
0
null
2011-04-08 14:21:20.53 UTC
1
2019-11-19 12:02:03.563 UTC
null
null
null
null
545,877
null
1
19
c#|if-statement|eval|bind|webforms
73,036
<p>You need to add your logic to the <code>ItemDataBound</code> event of ListView. In the aspx you cannot have an if-statement in the context of a DataBinder: <code>&lt;%# if() %&gt;</code> doesn't work.</p> <p>Have a look here: <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemdatabound.aspx</a></p> <p>The event will be raised for each item that will be bound to your ListView and therefore the context in the event is related to the item.</p> <p>Example, see if you can adjust it to your situation:</p> <pre><code>protected void ListView_ItemDataBound(object sender, ListViewItemEventArgs e) { if (e.Item.ItemType == ListViewItemType.DataItem) { Label monkeyLabel = (Label)e.Item.FindControl("monkeyLabel"); bool linkable = (bool)DataBinder.Eval(e.Item.DataItem, "IsLinkable"); if (linkable) monkeyLabel.Text = "monkeys!!!!!! (please be aware there will be no monkeys, this is only for humour purposes)"; } } </code></pre>
16,627,441
Excel VBA using FileSystemObject to list file last date modified
<p>this is my first time asking question so hopefully I'm following protocol. This is in reference to "get list of subdirs in vba" <a href="https://stackoverflow.com/questions/9827715/get-list-of-subdirs-in-vba">get list of subdirs in vba</a>.</p> <p>I found Brett's example #1 - Using FileScriptingObject most helpful. But there's one more data element (DateLastModified) I need in results. I tried to modify the code but keep getting invalid qualifier error. Here are code modifications I made:</p> <ol> <li>Range("A1:C1") = Array("File Name", "Path", "Date Last Modified").</li> <li>Do While loop added this => Cells(i, 3) = myFile.DateLastModified.</li> </ol> <p>Will appreciate help to include the "Date Last Modified".</p> <p>Santosh here is complete code with comments indicating modifications. </p> <pre><code>Public Arr() As String Public Counter As Long Sub LoopThroughFilePaths() Dim myArr Dim i As Long Dim j As Long Dim MyFile As String Const strPath As String = "c:\temp\" myArr = GetSubFolders(strPath) Application.ScreenUpdating = False 'Range("A1:B1") = Array("text file", "path")' &lt;= orig code Range("A1:C1") = Array("text file", "path", "Date Last Modified") ' &lt;= modified code For j = LBound(Arr) To UBound(Arr) MyFile = Dir(myArr(j) &amp; "\*.txt") Do While Len(MyFile) &lt;&gt; 0 i = i + 1 Cells(i, 1) = MyFile Cells(i, 2) = myArr(j) Cells(i, 3) = MyFile.DateLastModified ' &lt;= added to modify code MyFile = Dir Loop Next j Application.ScreenUpdating = True End Sub Function GetSubFolders(RootPath As String) Dim fso As Object Dim fld As Object Dim sf As Object Dim myArr Set fso = CreateObject("Scripting.FileSystemObject") Set fld = fso.GetFolder(RootPath) For Each sf In fld.SubFolders Counter = Counter + 1 ReDim Preserve Arr(Counter) Arr(Counter) = sf.Path myArr = GetSubFolders(sf.Path) Next GetSubFolders = Arr Set sf = Nothing Set fld = Nothing Set fso = Nothing End Function </code></pre>
16,627,924
1
2
null
2013-05-18 18:13:02.177 UTC
2
2016-12-05 10:51:22.567 UTC
2017-05-23 12:10:13.95 UTC
null
-1
null
2,397,403
null
1
4
vba
47,561
<p>Try this code :</p> <pre><code>Sub ListFilesinFolder() Dim FSO As Scripting.FileSystemObject Dim SourceFolder As Scripting.Folder Dim FileItem As Scripting.File SourceFolderName = "C:\Users\Santosh" Set FSO = New Scripting.FileSystemObject Set SourceFolder = FSO.GetFolder(SourceFolderName) Range("A1:C1") = Array("text file", "path", "Date Last Modified") i = 2 For Each FileItem In SourceFolder.Files Cells(i, 1) = FileItem.Name Cells(i, 2) = FileItem Cells(i, 3) = FileItem.DateLastModified i = i + 1 Next FileItem Set FSO = Nothing End Sub </code></pre>
29,465,096
How to send an e-mail with C# through Gmail
<p>I am getting an error when trying to send an e-mail through my web service. I have tried enabling access to less secure apps disabling 2-step verification and logging into the account via a web browser. None of the solutions on SO have worked for me. I am still getting:</p> <blockquote> <p>Error: System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.</p> </blockquote> <p>What can I do to fix this issue?</p> <pre><code>namespace EmailService { public class Service1 : IService1 { public string SendEmail(string inputEmail, string subject, string body) { string returnString = ""; try { MailMessage email = new MailMessage(); SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.gmail.com"; // set up the Gmail server smtp.EnableSsl = true; smtp.Port = 587; smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword"); smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.UseDefaultCredentials = false; // draft the email MailAddress fromAddress = new MailAddress("[email protected]"); email.From = fromAddress; email.To.Add(inputEmail); email.Subject = body; email.Body = body; smtp.Send(email); returnString = "Success! Please check your e-mail."; } catch(Exception ex) { returnString = "Error: " + ex.ToString(); } return returnString; } } } </code></pre>
29,465,275
1
5
null
2015-04-06 03:50:36.32 UTC
10
2017-01-14 10:33:02.86 UTC
2015-04-06 22:31:02.457 UTC
null
1,817,121
null
1,817,121
null
1
15
c#|smtp|gmail|smtpclient
48,718
<p>Just Go here : <a href="https://www.google.com/settings/security/lesssecureapps">Less secure apps</a> , Log on using your Email and Password which use for sending mail in your c# code , and choose <code>Turn On</code>.</p> <p>Also please go to this link and click on <strong>Continue</strong> <a href="https://accounts.google.com/DisplayUnlockCaptcha">Allow access to your Google account </a></p> <p>also I edit it little bit :</p> <pre><code>public string sendit(string ReciverMail) { MailMessage msg = new MailMessage(); msg.From = new MailAddress("[email protected]"); msg.To.Add(ReciverMail); msg.Subject = "Hello world! " + DateTime.Now.ToString(); msg.Body = "hi to you ... :)"; SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = true; client.Host = "smtp.gmail.com"; client.Port = 587; client.EnableSsl = true; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Credentials = new NetworkCredential("[email protected]", "YourPassword"); client.Timeout = 20000; try { client.Send(msg); return "Mail has been successfully sent!"; } catch (Exception ex) { return "Fail Has error" + ex.Message; } finally { msg.Dispose(); } } </code></pre> <p>If the above code don't work , try to change it like the following code :</p> <pre><code> SmtpClient client = new SmtpClient(); client.Host = "smtp.gmail.com"; client.Port = 587; client.EnableSsl = true; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.UseDefaultCredentials = false; client.Credentials = new NetworkCredential("[email protected]", "YourPassword"); </code></pre>
41,267,553
Powershell - Test-Connection failed due to lack of resources
<p>Test-connection intermittently fails with a lack of resources error:</p> <pre><code>test-connection : Testing connection to computer 'SOMESERVER' failed: Error due to lack of resources At line:1 char:45 + ... ($server in $ServersNonProd.Name) { test-connection $server -Count 1} + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (SOMESERVER:String) [Test-Connection], PingException + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand </code></pre> <p>As a result, it's not reliable and fairly useless when you need to test a list of computers in a loop. Is there a fix, alternative, or workaround to get this functionality reliably?</p> <p>This is my current solution, but it's still not sufficiently reliable (sometimes they still fail 5 times in a row) and it takes forever because of all the delays and retries.</p> <pre><code>$Servers = Import-CSV -Path C:\Temp\Servers.csv $result = foreach ($Name in $Servers.FQDN) { $IP = $null if ( Resolve-DNSName $Name -ErrorAction SilentlyContinue ) { $IP = (Test-Connection -Count 1 -ComputerName $Name -ErrorAction SilentlyContinue).IPv4Address if ( $IP -eq $null ) { Start-Sleep -Milliseconds 100 $IP = (Test-Connection -Count 1 -ComputerName $Name -ErrorAction SilentlyContinue).IPv4Address } if ( $IP -eq $null ) { Start-Sleep -Milliseconds 200 $IP = (Test-Connection -Count 1 -ComputerName $Name -ErrorAction SilentlyContinue).IPv4Address } if ( $IP -eq $null ) { Start-Sleep -Milliseconds 300 $IP = (Test-Connection -Count 1 -ComputerName $Name -ErrorAction SilentlyContinue).IPv4Address } if ( $IP -eq $null ) { Start-Sleep -Milliseconds 400 $IP = (Test-Connection -Count 1 -ComputerName $Name -ErrorAction SilentlyContinue).IPv4Address } } new-object psobject -Property @{FQDN = $Name; "IP Address" = $IP} } </code></pre> <p>A normal ping (ping.exe) works every time, so if there's a good way to parse that with powershell (host up or down, what IP is responding), that seems like the ideal solution, but I just need something that works, so I'm open to ideas.</p>
41,268,361
6
4
null
2016-12-21 16:30:47.357 UTC
3
2021-11-01 19:34:38.503 UTC
null
null
null
null
2,137,461
null
1
26
powershell|ping
48,568
<p>In newer versions of PowerShell, the <code>-Quiet</code> parameter on <code>Test-Connection</code> does seem to always return either <code>True</code> or <code>False</code>. It didn't seem to work consistently on older versions, but either I'm doing something differently now or they've improved it:</p> <pre><code>$Ping = Test-Connection -ComputerName $ComputerName -Count 1 -Quiet </code></pre> <p>I haven't tested it recently when the network is simply unavailable, however.</p> <hr /> <p>Older answer:</p> <p><code>Test-Connection</code> doesn't respond well when DNS doesn't respond with an address or when the network is unavailable. That is, if the cmdlet decides it can't send the ping at all, it errors in unpleasant ways that are difficult to trap or ignore. <code>Test-Connection</code> is only useful, then, when you can guarantee that DNS will resolve the name to an address, and that the network will always be present.</p> <p>I tend to use CIM Pings (Powershell v3+):</p> <pre><code>$Ping2 = Get-CimInstance -ClassName Win32_PingStatus -Filter &quot;Address='$ComputerName' AND Timeout=1000&quot;; </code></pre> <p>Or WMI pings (Powershell v1 or v2):</p> <pre><code>$Ping = Get-WmiObject -Class Win32_PingStatus -Filter &quot;Address='$ComputerName' AND Timeout=1000&quot;; </code></pre> <p>Either of which are basically the same, but return slightly different formats for things. Note that <code>Get-WmiObject</code> is not available at all beginning in Powershell v6 because <code>Get-CimInstance</code> was designed to supersede it.</p> <p>The main disadvantage here is that you have to resolve the status code yourself:</p> <pre><code>$StatusCodes = @{ [uint32]0 = 'Success'; [uint32]11001 = 'Buffer Too Small'; [uint32]11002 = 'Destination Net Unreachable'; [uint32]11003 = 'Destination Host Unreachable'; [uint32]11004 = 'Destination Protocol Unreachable'; [uint32]11005 = 'Destination Port Unreachable'; [uint32]11006 = 'No Resources'; [uint32]11007 = 'Bad Option'; [uint32]11008 = 'Hardware Error'; [uint32]11009 = 'Packet Too Big'; [uint32]11010 = 'Request Timed Out'; [uint32]11011 = 'Bad Request'; [uint32]11012 = 'Bad Route'; [uint32]11013 = 'TimeToLive Expired Transit'; [uint32]11014 = 'TimeToLive Expired Reassembly'; [uint32]11015 = 'Parameter Problem'; [uint32]11016 = 'Source Quench'; [uint32]11017 = 'Option Too Big'; [uint32]11018 = 'Bad Destination'; [uint32]11032 = 'Negotiating IPSEC'; [uint32]11050 = 'General Failure' }; $StatusCodes[$Ping.StatusCode]; $StatusCodes[$Ping2.StatusCode]; </code></pre> <p>Alternately, I've used .Net Pings like @BenH described, too, which does a lot of that work for you. There was a reason I stopped using them in favor of WMI and CIM, but I can no longer remember what that reason was.</p>
12,589,758
@font-face doesn't work
<p>I downloaded a font <code>inlove-light-wf.ttf</code>, in order to use the rule <code>@font-face</code>.</p> <p>I have in my folder: <code>home.html</code> and <code>inlove-light-wf.ttf</code>.</p> <p>In my CSS I have :</p> <pre><code>@font-face { font-family: 'Inlove'; src: url('inlove-light-wf.ttf'); font-weight: normal; font-style: normal; } #definicao{ text-align:center; color:#0080C0; font-family:'Inlove'; font-size:24px; margin-top:20px; border-top:solid #999 thin; padding: 20px 40px 3px 40px; height:290px; background-color:#EFEFEF; } #definicao{ text-align:center; color:#0080C0; font-family:'Inlove'; font-size:24px; margin-top:20px; border-top:solid #999 thin; padding: 20px 40px 3px 40px; height:290px; background-color:#EFEFEF; } </code></pre> <p>But it doesn't work.</p>
12,590,144
3
3
null
2012-09-25 19:26:33.713 UTC
2
2015-06-23 21:58:24.27 UTC
2012-12-24 20:28:28.24 UTC
null
299,509
null
1,257,304
null
1
8
css|font-face
42,933
<p>One source of the problem could be if your css is in a separate file that isn't in the root folder. For example, if you keep all of your css files in a 'css' folder, you'll need to modify the font url to be relative to that file, not to the root folder. In this example it would be <code>src: url('../inlove-light-wf.ttf');</code></p> <p>Furthermore, not all browsers can use .ttf font files. You have to declare alternative font formats in the <code>@font-face</code> css.</p> <p>Here's a modified <code>@font-face</code> declaration to get you started. I would also recommend reading more <a href="http://www.fontspring.com/blog/fixing-ie9-font-face-problems" rel="noreferrer">here</a> and <a href="http://sixrevisions.com/css/font-face-guide/" rel="noreferrer">here</a>.</p> <pre><code>@font-face { font-family: 'Inlove'; src: url('inlove-light-wf.eot'); /* IE9 Compat Modes */ src: url('inlove-light-wf.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('inlove-light-wf.woff') format('woff'), /* Modern Browsers */ url('inlove-light-wf.ttf') format('truetype'), /* Safari, Android, iOS */ url('inlove-light-wf.svg#svgFontName') format('svg'); /* Legacy iOS */ } </code></pre>
12,291,199
Example showing how to override TabExpansion2 in Windows PowerShell 3.0
<p>Does anyone have an example showing how to override the TabExpansion2 function in Windows PowerShell 3.0? I know how to override the old TabExpansion function, but I want to provide a list of items for the intellisense in PowerShell ISE. I looked at the definition of TabExpansion2 and it wasn't easily understandable how I inject my own code in the the tab expansion process.</p>
13,326,286
2
0
null
2012-09-05 23:41:21.64 UTC
10
2016-07-23 15:21:29.903 UTC
null
null
null
null
45,459
null
1
17
powershell|windows-8|powershell-3.0|tabexpansion
2,783
<p>I think this example should give you a good starting point: <a href="https://books.google.com/books?id=78w1953mptUC&amp;lpg=PA56&amp;ots=z0ssmJ1_RJ&amp;dq=powershell%20cookbook%20tabexpansion2&amp;pg=PA56#v=onepage&amp;q=powershell%20cookbook%20tabexpansion2&amp;f=false" rel="noreferrer">Windows Powershell Cookbook: Sample implementation of TabExpansion2</a>. The example code shows that you can add code both before and after the default calls to <code>[CommandCompletion]::CompleteInput</code>.</p> <p>For instance, you can add an entry to the <code>$options</code> hashtable named CustomArgumentCompleters to get custom completion for command arguments. The entry should be a hashtable where the keys are argument names (e.g. "ComputerName" or "Get-ChildItem:Filter") and the values are arrays of values that could be used to complete that parameter. Powertheshell.com also has an article about this: <a href="http://www.powertheshell.com/dynamicargumentcompletion/" rel="noreferrer">Dynamic Argument Completion</a>. You can also specify custom completions for native executables, using the NativeArgumentCompleters option (again, keys are command names and values are arrays of possible completions).</p> <p>Once<code>CompleteInput</code> has returned, you can store the result in <code>$result</code> for further analysis. The result is an instance of the <a href="http://msdn.microsoft.com/en-us/library/system.management.automation.commandcompletion%28v=vs.85%29.aspx" rel="noreferrer"><code>CommandCompletion</code></a> class. If the default completion didn't find any matches, you can add your own <a href="http://msdn.microsoft.com/en-us/library/system.management.automation.completionresult.completionresult%28v=vs.85%29.aspx" rel="noreferrer"><code>CompletionResult</code></a> entries to the list of matches:</p> <pre><code>$result.CompletionMatches.Add( (New-Object Management.Automation.CompletionResult "my completion string") ) </code></pre> <p>Don't forget to return <code>$result</code> from the function so the completion actually happens.</p> <p>Finally, a note on troubleshooting: the code that calls <code>TabCompletion2</code> seems to squelch all console-based output (not surprisingly), so if you want to write debugging messages for yourself, you might try writing them to a separate text file. For instance, you could change the <code>End</code> function in <code>TabCopmletion2</code> to look like this:</p> <pre><code>$result = [System.Management.Automation.CommandCompletion]::CompleteInput( $inputScript, $cursorColumn, $options) $result | Get-Member | Add-Content "c:\TabCompletionLog.txt" $result </code></pre>
12,613,926
SQLite query, 'LIKE'
<p>I am trying to retrieve information from my database.<br> I have words like <code>Lim Won Mong</code> and <code>Limited</code>.</p> <p>If I do my query, <code>SELECT name FROM memberdb WHERE name LIKE '%LIM%'</code>, it displays both <code>Lim Won Mong</code> and <code>Limited</code> and I only want data from <code>Lim Won Mong</code>.</p> <p>How should I rewrite my query?</p>
12,613,978
3
2
null
2012-09-27 04:06:12.2 UTC
6
2013-12-07 05:04:33.107 UTC
2013-12-07 05:04:33.107 UTC
null
210,916
null
1,425,002
null
1
18
sql|sqlite|sql-like
52,312
<p>Execute following Query:</p> <pre><code>select name from memberdb where name like '% LIM %' OR name like "LIM %" OR name like "% LIM" OR name like "LIM" </code></pre>
12,053,627
How can I stop Entity Framework 5 migrations adding dbo. into key names?
<p>I started a project using Entity Framework 4.3 Code First with manual migrations and SQL Express 2008 and recently updated to EF5 (in VS 2010) and noticed that now when I change something like a foreign key constraint, the migrations code adds the "dbo." to the start of the table name and hence the foreign key name it constructs is incorrect for existing constraints (and in general now seem oddly named).</p> <p>Original migration script in EF 4.3 (note <strong>ForeignKey("Products", t => t.Product_Id)</strong>): </p> <pre class="lang-cs prettyprint-override"><code> CreateTable( "Products", c =&gt; new { Id = c.Int(nullable: false, identity: true), ProductName = c.String(), }) .PrimaryKey(t =&gt; t.Id); CreateTable( "KitComponents", c =&gt; new { Id = c.Int(nullable: false, identity: true), Component_Id = c.Int(), Product_Id = c.Int(), }) .PrimaryKey(t =&gt; t.Id) .ForeignKey("Products", t =&gt; t.Component_Id) .ForeignKey("Products", t =&gt; t.Product_Id) .Index(t =&gt; t.Component_Id) .Index(t =&gt; t.Product_Id); </code></pre> <p>Foreign Key names generated: FK_KitComponents_Products_Product_Id FK_KitComponents_Products_Component_Id</p> <p>If I then upgrade to EF5 and change the foreign key the migration code looks something like (note the <strong>"dbo.KitComponents" and "dbo.Products"</strong> as opposed to just <strong>"KitComponents" and "Products"</strong>):</p> <pre class="lang-cs prettyprint-override"><code>DropForeignKey("dbo.KitComponents", "Product_Id", "dbo.Products"); DropIndex("dbo.KitComponents", new[] { "Product_Id" }); </code></pre> <p>and the update-database fails with the message: '<strong>FK_dbo.KitComponents_dbo.Products_Product_Id</strong>' is not a constraint. Could not drop constraint. See previous errors.</p> <p>so it seems as of EF5 the constraint naming has changed from FK_KitComponents_Products_Product_Id to FK_dbo.KitComponents_dbo.Products_Product_Id (with dbo. prefix)</p> <p>How can I get EF5 to behave as it was in EF 4.3 so I don't have to alter every piece of new migration code it spits out?</p> <p>I haven't been able to find any release notes about why this changed and what to do about it :(</p>
12,060,958
4
1
null
2012-08-21 11:13:54.277 UTC
11
2015-03-23 05:37:09.95 UTC
2012-08-21 11:52:20.313 UTC
null
625,113
null
625,113
null
1
30
entity-framework|entity-framework-5
10,758
<p>You can customize the generated code by sub-classing the <a href="http://msdn.microsoft.com/en-us/library/system.data.entity.migrations.design.csharpmigrationcodegenerator" rel="noreferrer"><code>CSharpMigrationCodeGenerator</code></a> class:</p> <pre><code>class MyCodeGenerator : CSharpMigrationCodeGenerator { protected override void Generate( DropIndexOperation dropIndexOperation, IndentedTextWriter writer) { dropIndexOperation.Table = StripDbo(dropIndexOperation.Table); base.Generate(dropIndexOperation, writer); } // TODO: Override other Generate overloads that involve table names private string StripDbo(string table) { if (table.StartsWith("dbo.")) { return table.Substring(4); } return table; } } </code></pre> <p>Then set it in your migrations configuration class:</p> <pre><code>class Configuration : DbMigrationsConfiguration&lt;MyContext&gt; { public Configuration() { CodeGenerator = new MyCodeGenerator(); } } </code></pre>
12,087,905
Pythonic way to sorting list of namedtuples by field name
<p>I want to sort a list of named tuples without having to remember the index of the fieldname. My solution seems rather awkward and was hoping someone would have a more elegant solution.</p> <pre><code>from operator import itemgetter from collections import namedtuple Person = namedtuple('Person', 'name age score') seq = [ Person(name='nick', age=23, score=100), Person(name='bob', age=25, score=200), ] # sort list by name print(sorted(seq, key=itemgetter(Person._fields.index('name')))) # sort list by age print(sorted(seq, key=itemgetter(Person._fields.index('age')))) </code></pre> <p>Thanks, Nick</p>
12,087,992
5
2
null
2012-08-23 08:44:13.68 UTC
12
2021-10-13 09:46:58.34 UTC
2016-08-08 04:07:47.443 UTC
null
1,219,006
null
1,619,135
null
1
80
python|sorting|namedtuple|field-names
33,345
<pre><code>from operator import attrgetter from collections import namedtuple Person = namedtuple('Person', 'name age score') seq = [Person(name='nick', age=23, score=100), Person(name='bob', age=25, score=200)] </code></pre> <p>Sort list by name</p> <pre><code>sorted(seq, key=attrgetter('name')) </code></pre> <p>Sort list by age</p> <pre><code>sorted(seq, key=attrgetter('age')) </code></pre>
12,050,393
How to force the Y axis to only use integers in Matplotlib
<p>I'm plotting a histogram using the matplotlib.pyplot module and I am wondering how I can force the y-axis labels to only show integers (e.g. 0, 1, 2, 3 etc.) and not decimals (e.g. 0., 0.5, 1., 1.5, 2. etc.). </p> <p>I'm looking at the guidance notes and suspect the answer lies somewhere around <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.ylim">matplotlib.pyplot.ylim</a> but so far I can only find stuff that sets the minimum and maximum y-axis values. </p> <pre><code>def doMakeChart(item, x): if len(x)==1: return filename = "C:\Users\me\maxbyte3\charts\\" bins=logspace(0.1, 10, 100) plt.hist(x, bins=bins, facecolor='green', alpha=0.75) plt.gca().set_xscale("log") plt.xlabel('Size (Bytes)') plt.ylabel('Count') plt.suptitle(r'Normal Distribution for Set of Files') plt.title('Reference PUID: %s' % item) plt.grid(True) plt.savefig(filename + item + '.png') plt.clf() </code></pre>
12,051,323
3
1
null
2012-08-21 07:48:30.597 UTC
16
2022-06-22 00:51:22.073 UTC
2022-06-22 00:51:22.073 UTC
null
7,758,804
null
1,191,626
null
1
117
python|matplotlib|axis-labels
142,123
<p>If you have the y-data </p> <pre><code>y = [0., 0.5, 1., 1.5, 2., 2.5] </code></pre> <p>You can use the maximum and minimum values of this data to create a list of natural numbers in this range. For example,</p> <pre><code>import math print range(math.floor(min(y)), math.ceil(max(y))+1) </code></pre> <p>yields</p> <pre><code>[0, 1, 2, 3] </code></pre> <p>You can then set the y tick mark locations (and labels) using <a href="http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.yticks" rel="noreferrer">matplotlib.pyplot.yticks</a>:</p> <pre><code>yint = range(min(y), math.ceil(max(y))+1) matplotlib.pyplot.yticks(yint) </code></pre>
12,384,704
The Ruby %r{ } expression
<p>In a model there is a field</p> <pre><code>validates :image_file_name, :format =&gt; { :with =&gt; %r{\.(gif|jpg|jpeg|png)$}i </code></pre> <p>It looks pretty odd for me. I am aware that this is a regular expression. But I would like:</p> <ul> <li>to know what exactly it means. Is <code>%r{value}</code> equal to <code>/value/</code> ?</li> <li>be able to replace it with normal Ruby regex operator <code>/some regex/</code> or <code>=~</code>. Is this possible?</li> </ul>
12,384,762
5
0
null
2012-09-12 09:06:27.447 UTC
24
2022-08-10 19:32:40.413 UTC
2022-08-10 19:32:40.413 UTC
null
17,581,828
null
468,345
null
1
152
ruby-on-rails|ruby
61,615
<p><code>%r{}</code> is equivalent to the <code>/.../</code> notation, but allows you to have '/' in your regexp without having to escape them:</p> <pre><code>%r{/home/user} </code></pre> <p>is equivalent to:</p> <pre><code>/\/home\/user/ </code></pre> <p>This is only a syntax commodity, for legibility.</p> <p>Edit:</p> <p>Note that you can use almost any non-alphabetic character pair instead of '{}'. These variants work just as well:</p> <pre><code>%r!/home/user! %r'/home/user' %r(/home/user) </code></pre> <p>Edit 2:</p> <p>Note that the <code>%r{}x</code> variant ignores whitespace, making complex regexps more readable. Example from <a href="https://github.com/github/rubocop-github/blob/master/STYLEGUIDE.md#regular-expressions" rel="noreferrer">GitHub's Ruby style guide</a>:</p> <pre class="lang-rb prettyprint-override"><code>regexp = %r{ start # some text \s # white space char (group) # first group (?:alt1|alt2) # some alternation end }x </code></pre>
43,080,505
c# 7.0: switch on System.Type
<p>No existing question has an answer to this question.</p> <p>In c# 7, can I switch directly on a <code>System.Type</code>?</p> <p>When I try:</p> <pre><code> switch (Type) { case typeof(int): break; } </code></pre> <p>it tells me that <code>typeof(int)</code> needs to be a constant expression.</p> <p>Is there some syntatic sugar that allows me to avoid <code>case nameof(int):</code> and directly compare the types for equality? <code>nameof(T)</code> in a case statement is not completely good because namespaces. So although name collision is probably not be applicable for <code>int</code>, it will be applicable for other comparisons.</p> <p>In other words, I'm trying to be more type-safe than this:</p> <pre><code> switch (Type.Name) { case nameof(Int32): case nameof(Decimal): this.value = Math.Max(Math.Min(0, Maximum), Minimum); // enforce minimum break; } </code></pre>
43,080,709
10
15
null
2017-03-28 21:43:59.807 UTC
11
2022-07-30 00:47:14.567 UTC
2020-07-01 16:31:53.667 UTC
null
1,045,881
null
1,045,881
null
1
87
c#
70,083
<p>The (already linked) new pattern matching feature allows this.</p> <p>Ordinarily, you'd switch on a value:</p> <pre><code>switch (this.value) { case int intValue: this.value = Math.Max(Math.Min(intValue, Maximum), Minimum); break; case decimal decimalValue: this.value = Math.Max(Math.Min(decimalValue, Maximum), Minimum); break; } </code></pre> <p>But you can use it to switch on a type, if all you have is a type:</p> <pre><code>switch (type) { case Type intType when intType == typeof(int): case Type decimalType when decimalType == typeof(decimal): this.value = Math.Max(Math.Min(this.value, Maximum), Minimum); break; } </code></pre> <p>Note that this is not what the feature is intended for, it becomes less readable than a traditional <code>if</code>...<code>else if</code>...<code>else if</code>...<code>else</code> chain, and the traditional chain is what it compiles to anyway. I do not recommend using pattern matching like this.</p>
8,917,885
Which version of Python do I have installed?
<p>I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter?</p> <p>I was thinking of updating to the latest version of Python.</p>
8,917,907
27
6
null
2012-01-18 21:43:13.277 UTC
68
2022-08-01 03:56:36.97 UTC
2019-11-24 16:58:39.44 UTC
null
63,550
null
275,510
null
1
543
python|version|windows-server
1,500,351
<pre><code>python -V </code></pre> <p><a href="http://docs.python.org/using/cmdline.html#generic-options">http://docs.python.org/using/cmdline.html#generic-options</a></p> <p><code>--version</code> may also work (introduced in version 2.5)</p>
8,414,552
Java: String - add character n-times
<p>Is there a simple way to add a character or another String n-times to an existing String? I couldn’t find anything in <code>String</code>, <code>Stringbuilder</code>, etc.</p>
47,451,056
15
7
null
2011-12-07 11:27:31.36 UTC
3
2019-04-24 17:10:39.07 UTC
2015-01-23 19:50:04.68 UTC
null
905,686
null
905,686
null
1
44
java|string
157,846
<p>You are able to do this using Java 8 stream APIs. The following code creates the string <code>"cccc"</code> from <code>"c"</code>:</p> <pre><code>String s = "c"; int n = 4; String sRepeated = IntStream.range(0, n).mapToObj(i -&gt; s).collect(Collectors.joining("")); </code></pre>
8,840,319
Build a tree from a flat array in PHP
<p>I've looked around the internet and haven't quite found what I'm looking for. I have a flat array with each element containing an 'id' and a 'parent_id'. Each element will only have ONE parent, but may have multiple children. If the parent_id = 0, it is considered a root level item. I'm trying to get my flat array into a tree. The other samples I have found only only copy the element to the parent, but the original still exists.</p> <p><strong>EDIT</strong></p> <p>Each element of the starting array is read from a separate XML file. The file itself will have '0' as the value for parent_id if it doesn't have a parent. The keys are actually strings.</p> <p>I'm sorry for the confusion earlier. Hopefully this is more clear:</p> <p><strong>/EDIT</strong></p> <p>My starting array:</p> <pre> Array ( [_319_] => Array ( [id] => 0 [parent_id] => 0 ) [_320_] => Array ( [id] => _320_ [parent_id] => 0 ) [_321_] => Array ( [id] => _321_ [parent_id] => _320_ ) [_322_] => Array ( [id] => _322_ [parent_id] => _321_ ) [_323_] => Array ( [id] => _323_ [parent_id] => 0 ) [_324_] => Array ( [id] => _324_ [parent_id] => _323_ ) [_325_] => Array ( [id] => _325_ [parent_id] => _320_ ) )</pre> <p>The resulting array after the tree is made:</p> <pre> Array ( [_319_] => Array ( [id] => _319_ [parent_id] => 0 ) [_320_] => Array ( [id] => _320_ [parent_id] => 0 [children] => Array ( [_321_] => Array ( [id] => _321_ [parent_id] => _320_ [children] => Array ( [_322_] => Array ( [id] => _322_ [parent_id] => _321_ ) ) ) [_325_] => Array ( [id] => _325_ [parent_id] => _320_ ) ) [_323_] => Array ( [id] => _323_ [parent_id] => 0 [children] => Array ( [_324_] => Array ( [id] => _324_ [parent_id] => _323_ ) ) ) </pre> <p>Any help / guidance is greatly appreciated!</p> <p>Some code I have so far:</p> <pre> function buildTree(array &$elements, $parentId = 0) { $branch = array(); foreach ($elements as $element) { if ($element['parent_id'] == $parentId) { $children = $this->buildTree($elements, $element['id']); if ($children) { $element['children'] = $children; } $branch[] = $element; } } return $branch; } </pre>
8,841,921
14
8
null
2012-01-12 18:28:19.96 UTC
23
2022-03-30 08:52:55.217 UTC
2012-01-12 18:55:57.103 UTC
null
467,362
null
467,362
null
1
55
php|arrays|tree|flat
68,839
<p>You forgot the <code>unset()</code> in there bro.</p> <pre><code>function buildTree(array &amp;$elements, $parentId = 0) { $branch = array(); foreach ($elements as $element) { if ($element['parent_id'] == $parentId) { $children = buildTree($elements, $element['id']); if ($children) { $element['children'] = $children; } $branch[$element['id']] = $element; unset($elements[$element['id']]); } } return $branch; } </code></pre>
11,201,262
How to read data from a file in Lua
<p>I was wondering if there was a way to read data from a file or maybe just to see if it exists and return a <code>true</code> or <code>false</code></p> <pre><code>function fileRead(Path,LineNumber) --..Code... return Data end </code></pre>
11,204,889
4
1
null
2012-06-26 05:32:27.85 UTC
12
2022-01-26 19:09:41.123 UTC
2015-08-06 14:01:29.99 UTC
user1465457
1,009,479
user1465457
null
null
1
43
lua
150,810
<p>Try this:</p> <pre><code>-- http://lua-users.org/wiki/FileInputOutput -- see if the file exists function file_exists(file) local f = io.open(file, &quot;rb&quot;) if f then f:close() end return f ~= nil end -- get all lines from a file, returns an empty -- list/table if the file does not exist function lines_from(file) if not file_exists(file) then return {} end local lines = {} for line in io.lines(file) do lines[#lines + 1] = line end return lines end -- tests the functions above local file = 'test.lua' local lines = lines_from(file) -- print all line numbers and their contents for k,v in pairs(lines) do print('line[' .. k .. ']', v) end </code></pre>
11,088,909
Expire cache on require.js data-main
<p>I'm using require.js and r.js to package my AMD modules. I'm using jquery &amp; requirejs via the following syntax:</p> <pre><code>&lt;script data-main="/js/client" src="/js/external/require-jquery.js"&gt;&lt;/script&gt; </code></pre> <p>This all works great pre &amp; post packaging, but I run into issues a lot where chrome &amp; mobile safari hold on to the cached version of client.js. I'd like to add a cachebuster to client.js, but I can't seem to figure out how to do it using the above syntax.</p> <p>I tried some variations of:</p> <pre><code>&lt;script data-main="js/client.js?b=busted" src="/js/external/require-jquery.js"&gt;&lt;/script&gt; </code></pre> <p>but now require tries to get client.js from <code>/</code>, not <code>/js</code>, so it 404s.</p> <p>I also tried adding</p> <pre><code>urlArgs : "bust="+new Date().getTime() </code></pre> <p>to <code>require.config</code>, but it appears to have no effect.</p> <p>I also tried adding the same value to <code>app.build.js</code>, but when it's in there, r.js no longer concatenates my js files, just uglifies them.</p> <p>What is the proper syntax to bust a require.js data-main script cache?</p>
11,724,555
2
1
null
2012-06-18 18:34:25.887 UTC
14
2017-01-09 10:02:11.503 UTC
null
null
null
null
77,011
null
1
43
javascript|caching|requirejs|browser-cache|amd
20,932
<p>How are you defining your require.config? I think for it to take effect before you import require.js, you need to code it like this:</p> <pre><code>&lt;script type="text/javascript"&gt; var require = { baseUrl: "/scripts/", waitSeconds: 15, urlArgs : "bust="+new Date().getTime() }; &lt;/script&gt; &lt;script data-main="app/main" src="/scripts/require.js"&gt;&lt;/script&gt; </code></pre> <p>Specifically, a an object named 'require' must be constructed before you import require.js.</p> <p><strong>UPDATE</strong></p> <p>As Jesse points out in the comments below, there are a few enhancements you should apply to your require{} object for production use. The above example is cribbed from the RequireJS documentation and modified as little as possible to answer this question.</p> <p>Here are a few things to consider for production use: </p> <ul> <li>Instead of using the current date-time as your cache-busting variable, you should use a build number from your development environment. This allows your clients to cache the Javascript between releases but will cause them to refresh their cache whenever you do a software update.</li> <li>Jesse also uses the require{}'s ability to specify dependencies instead of using the data-main attribute of the script. I don't know if that is strictly <em>better</em>, but I think it is cleaner looking.</li> <li>Adjust the waitSeconds based on your needs. I used the example value from the RequireJS documentation, but you should adjust the value or omit it, based on your needs.</li> </ul> <p>So if you apply these techniques, your code might look like:</p> <pre><code>&lt;script type="text/javascript"&gt; var require = { baseUrl: "/scripts/", waitSeconds: 15, urlArgs : "bust="+{{buildNumber}}, deps : ['app/main'] }; &lt;/script&gt; &lt;script src="/scripts/require.js?bust={{buildNumber}}"&gt;&lt;/script&gt; </code></pre> <p>Note, in this case {{buildNumber}} is a value supplied by the server.</p> <p><strong>UPDATE 2</strong></p> <p>The urlArgs cache bust solution has problems. Unfortunately you cannot control all proxy servers that might be between you and your user's web browser. Some of these proxy servers can be unfortunately configured to ignore URL parameters when caching files. If this happens, the wrong version of your JS file will be delivered to your user.</p> <p>I would recommend using a <code>buildNumber</code> <em>in</em> your Javascript filename request, like <code>buildNumber.myModule.js</code> (prefix) or myModule.buildNumber.js (postfix). You can use the prefix style by modifying the baseUrl:</p> <pre><code>baseUrl: "/scripts/buildNumber", </code></pre> <p>Note the lack of a '/' at the end of the baseUrl.</p> <p>You will need to use a modified version of require.js to use the postfix solution. You can read more about this here: <a href="https://stackoverflow.com/a/21619359/1017787">https://stackoverflow.com/a/21619359/1017787</a></p> <p>Obviously in either case you will want to use some solution to replace <code>buildNumber</code> with some type of version number that changes with each release.</p>
13,115,053
scala anonymous function missing parameter type error
<p>I wrote the following</p> <pre><code>def mapFun[T, U](xs: List[T], f: T =&gt; U): List[U] = (xs foldRight List[U]())( f(_)::_ ) </code></pre> <p>and when I did</p> <pre><code>def f(x: Int):Int=x*x mapFun(List(1,2,3), f) </code></pre> <p>It worked fine. However, I really wanted to make the following work too</p> <pre><code>mapFun(List(1,2,3), x=&gt;x*x) </code></pre> <p>It complains about "missing parameter type". I know that I could use currying, but is there any way to still use anonymous function for non-currying def I had above?</p>
13,115,105
2
0
null
2012-10-29 02:01:55.19 UTC
4
2014-08-18 13:42:21.05 UTC
2012-10-29 06:30:34.047 UTC
null
745,188
null
534,617
null
1
28
scala
26,115
<p>It seems to me that because "f" is in the same parameter list as "xs", you're required to give some information regarding the type of x so that the compiler can solve it.</p> <p>In your case, this will work:</p> <pre><code>mapFun(List(1,2,3) , (x: Int) =&gt; x * x) </code></pre> <p>Do you see how I'm informing the compiler that x is an Int?</p> <p>A "trick" that you can do is currying f. If you don't know what currying is check this out: <a href="http://www.codecommit.com/blog/scala/function-currying-in-scala">http://www.codecommit.com/blog/scala/function-currying-in-scala</a></p> <p>You will end up with a mapFun like this:</p> <pre><code>def mapFun[T, U](xs: List[T])(f: T =&gt; U): List[U] = (xs foldRight List[U]())( f(_)::_ ) </code></pre> <p>And this will work:</p> <pre><code>mapFun(List(1,2,3))(x =&gt; x * x) </code></pre> <p>In the last call, the type of x is resolved when the compiler checks the first parameter list.</p> <p><strong>EDIT:</strong></p> <p>As Dominic pointed out, you could tell the compiler what your types are. Leading to:</p> <pre><code>mapFun[Int, Int](List(1,2,3), x =&gt; x * x) </code></pre> <p>Cheers!</p>
13,004,226
How to interact with leaflet marker layer from outside the map?
<p>I have a leaflet map showing points for public art pieces, rendered from <a href="http://geojson.org/" rel="noreferrer">GeoJSON</a>. Next to the map, I created a list of the pieces from the same <a href="http://geojson.org/" rel="noreferrer">GeoJSON</a> data and want to be able to click on an item from the list outside of the map and have the related marker's popup come up on the map.</p> <p>How can I link the list of items to their respective markers through a click event?</p> <p>My map.js file looks like this:</p> <pre class="lang-js prettyprint-override"><code>var map; var pointsLayer; $(document).ready(function () { map = new L.Map('mapContainer'); var url = 'http://{s}.tiles.mapbox.com/v3/mapbox.mapbox-streets/{z}/{x}/{y}.png'; var copyright = 'Map data &amp;copy; 2011 OpenStreetMap contributors, Imagery &amp;copy; 2011 CloudMade'; var tileLayer = new L.TileLayer(url, { attribution: copyright }); var startPosition = new L.LatLng(41.883333, - 87.633333); map.on('load', function (e) { requestUpdatedPoints(e.target.getBounds()) }); map.setView(startPosition, 13).addLayer(tileLayer); map.on('moveend', function (e) { requestUpdatedPoints(e.target.getBounds()) }) }); function requestUpdatedPoints(bounds) { $.ajax({ type: 'GET', url: '/SeeAll', dataType: 'json', data: JSON.stringify(bounds), contentType: 'application/json; charset=utf-8', success: function (result) { parseNewPoints(result); addToList(result) }, error: function (req, status, error) { alert('what happen? did you lose conn. to server ?') } }) } function addToList(data) { for (var i = 0; i &lt; data.features.length; i++) { var art = data.features[i]; $('div#infoContainer').append('&lt;a href="#" class="list-link" title="' + art.properties.descfin + '"&gt;&lt;div class="info-list-item"&gt;' + '&lt;div class="info-list-txt"&gt;' + '&lt;div class="title"&gt;' + art.properties.wrknm + '&lt;/div&gt;' + '&lt;br /&gt;' + art.properties.location + '&lt;/div&gt;' + '&lt;div class="info-list-img"&gt;' + art.properties.img_src + '&lt;/div&gt;' + '&lt;br /&gt;' + '&lt;/div&gt;&lt;/a&gt;') } $('a.list-link').click(function (e) { alert('now you see what happens when you click a list item!'); e.preventDefault() }) } function parseNewPoints(data) { if (pointsLayer != undefined) { map.removeLayer(pointsLayer) } pointsLayer = new L.GeoJSON(); var geojsonMarkerOptions = { radius: 8, fillColor: "#FF6788", color: "YELLOW", weight: 1, opacity: 1, fillOpacity: 0.5 }; L.geoJson(data, { pointToLayer: function (feature, latlng) { return L.circleMarker(latlng, geojsonMarkerOptions) }, onEachFeature: function (feature, pointsLayer) { pointsLayer.bindPopup(feature.properties.img_src + "&lt;br /&gt;" + feature.properties.wrknm + "&lt;br /&gt;" + feature.properties.artist + "&lt;br /&gt;" + feature.properties.location + '&lt;div class="description"&gt;' + feature.properties.descfin + '&lt;/div&gt;') } }).addTo(map) } </code></pre>
13,012,714
2
1
null
2012-10-22 02:16:17.5 UTC
22
2016-06-08 12:50:03.05 UTC
2016-06-06 22:06:12.753 UTC
null
128,421
null
340,648
null
1
30
javascript|jquery|leaflet|geojson
31,738
<p>Felix Kling is right but I'll expand on his comment a little bit... </p> <p>Since L.LayerGroup and L.FeatureGroup (which L.GeoJSON extends from) don't have methods to retrieve individual layers you will need to either extend from L.GeoJSON and add such a method or keep your own seperate mapping from unique ID to CircleMarker from GeoJSON.</p> <p>GeoJSON does not require a unique ID but I'll assume that markers in your feed have a unique ID attribute called "id". You will need to add this unique ID to the links that the user can click on so that the links can select the right marker on the map. Then you'll need to store a map of ids to markers in order to retrieve the marker to select it on the map.</p> <pre><code>markerMap = {}; // a global variable unless you extend L.GeoJSON // Add the marker id as a data item (called "data-artId") to the "a" element function addToList(data) { for (var i = 0; i &lt; data.features.length; i++) { var art = data.features[i]; $('div#infoContainer').append('&lt;a href="#" class="list-link" data-artId=\"'+art.id+'\" title="' + art.properties.descfin + '"&gt;&lt;div class="info-list-item"&gt;' + '&lt;div class="info-list-txt"&gt;' + '&lt;div class="title"&gt;' + art.properties.wrknm + '&lt;/div&gt;' + '&lt;br /&gt;' + art.properties.location + '&lt;/div&gt;' + '&lt;div class="info-list-img"&gt;' + art.properties.img_src + '&lt;/div&gt;' + '&lt;br /&gt;' + '&lt;/div&gt;&lt;/a&gt;') } $('a.list-link').click(function (e) { alert('now you see what happens when you click a list item!'); //Get the id of the element clicked var artId = $(this).data( 'artId' ); var marker = markerMap[artId]; //since you're using CircleMarkers the OpenPopup method requires //a latlng so I'll just use the center of the circle marker.openPopup(marker.getLatLng()); e.preventDefault() }) } </code></pre> <p>You need to build the markerMap when you get the data from the server. Your pointToLayer method could be modified to do that:</p> <pre><code>L.geoJson(data, { pointToLayer: function (feature, latlng) { var marker = new L.CircleMarker( latlng, geojsonMarkerOptions ); markerMap[feature.id] = marker; return marker; },... </code></pre>
12,906,789
Preventing an image from being draggable or selectable without using JS
<p>Does anyone know of a way to make an image not draggable and not selectable -- at the same time -- in Firefox, without resorting to Javascript? Seems trivial, but here's the issue:</p> <ol> <li><p>Can be dragged and highlighted in Firefox:</p> </li> <li><p>So we add this, but image can still be highlighted while dragging:</p> </li> <li><p>So we add this, to fix the highlighting issue, but then counterintuitively, <strong>the image become draggable again.</strong> Weird, I know! Using FF 16.0.1</p> </li> </ol> <p>So, does anyone know why adding <code>-moz-user-select: none</code>, would somehow trump and disable <code>draggable=false</code>? Of course, webkit works as expected. Nothing is out there on the Interwebs about this...It would be great if we could shine some light on this together.</p> <p><strong>Edit:</strong> <em>This is about keeping UI elements from being inadvertently dragged and improving usability - not some lame attempt at a copy protection scheme.</em></p>
12,906,840
10
3
null
2012-10-16 02:40:20.097 UTC
65
2022-07-21 07:55:41.71 UTC
2020-10-10 06:42:42.94 UTC
user7437719
null
null
1,741,860
null
1
176
css|html|firefox|draggable
199,911
<p>Set the following CSS properties to the image:</p> <pre class="lang-css prettyprint-override"><code>.selector { user-drag: none; -webkit-user-drag: none; user-select: none; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; } </code></pre>
16,970,803
Correct naming structure for CodeIgniter
<p>I'm starting my 1st CodeIgniter project and want to get some advice before i start. I'm a little confused with how the name of the controller and models work.</p> <p>If i want the url to my company page to be <a href="http://example.com/Company/view" rel="noreferrer">http://example.com/Company/view</a></p> <p>the controller needs to be called Company.php correct? inside the company controller it would look like this:</p> <pre><code>public function viewAll() { $this-&gt;load-&gt;model('Companymodel'); $this-&gt;load-&gt;view('templates/header'); $data['result'] = $this-&gt;Companymodel-&gt;viewAll(); $this-&gt;load-&gt;view('company/viewAll', $data); $this-&gt;load-&gt;view('templates/footer'); } </code></pre> <p>ok im confused here, on line 4 above: </p> <pre><code>$this-&gt;load-&gt;model('Companymodel'); </code></pre> <p>this call to the company model page needs to have 1st letter capital with the rest lower case?</p> <p>if that's correct, does the model file need to be called Companymodel.php and placed inside the application/models folder?</p> <p>is it bad practice to call the controller and model the same</p> <p>example: Company.php and place it inside /application/controller/ and then have the model called Company.php and place it inside the application/model or should the model be called Companymodel.php</p> <p>I guess my ultimate question is the naming convention of the controller and model files, and whether they can be upper case or not.</p>
16,972,966
2
3
null
2013-06-06 19:42:29.593 UTC
15
2018-04-05 02:06:33.463 UTC
2018-04-05 02:06:33.463 UTC
null
1,033,581
null
2,457,994
null
1
14
codeigniter
34,102
<h3>URLs</h3> <p>Your URLs should typically be all lowercase letters. If you expect capital letters, there's a chance you could accidentally exclude their lowercase counterparts, even though they're the same URL. Example: <code>www.example.com/controller/method/param</code></p> <h3>Controllers</h3> <p>Controller class names should be all lowercase, except the first letter.</p> <ul> <li>If your URL is <code>www.example.com/gallery</code>, the controller name is <code>Gallery</code>.</li> <li>If your URL is <code>www.example.com/admin_folder</code>, the controller name is <code>Admin_folder</code>.</li> </ul> <p>Controller file names should match the class name, but be all lowercase.</p> <ul> <li>Gallery :: <code>gallery.php</code></li> <li>Admin_folder :: <code>admin_folder.php</code></li> </ul> <p>Controller methods should be all lowercase as well. There is some flexibility with uppercase, but similar to URLs, there are opportunities where it can goof something up (<a href="https://stackoverflow.com/questions/16738179/codeigniter-2-callback-function-in-my-controller">here's an example</a> where capital letters interfered with a form validation callback method).</p> <h3>Models</h3> <p>Models follow most of the same conventions as controllers. The only difference is with model method names, which can use your preference of capitalization. Since these methods are not tied to URLs, and are called using normal PHP OOP, you can name them as you please.</p> <p>It is recommended to load models using the all lowercase version. While it is not required by CI, it can confuse some users if they load it with a capital letter, but then attempt to access it as all lowercase (this is due to native PHP being case sensitive with class properties [and variables in general], not CodeIgniter).</p> <ul> <li>Model class name: <code>Users_model</code> (the <code>_model</code> suffix is also not required, but some people may use it as a personal preference, or to prevent naming conflicts with a <code>Users</code> controller).</li> <li>Model file name: <code>users_model.php</code></li> <li>Model loading: <code>$this-&gt;load-&gt;model('users_model')</code></li> <li>Model method names (all okay): <code>$this-&gt;users-&gt;getAll()</code>, <code>$this-&gt;users-&gt;find_by_name($name)</code>, etc.</li> </ul> <h3>Libraries</h3> <p>Libraries follow the same conventions <strong>except</strong> for the file name. In their case, file names should match the class name.</p> <p>Similar to models, it's recommended to load libraries using the lowercase name.</p> <p>These rules are the same for CI's libraries (located in <code>application/core</code> and <code>application/libraries</code>, as well as custom or third-party libraries.</p> <p><strong>Special note:</strong> when extending default CI libraries, the prefix as defined in <code>application/config.php</code> comes into play. This prefix typically should be all uppercase, followed by an underscore. The default is <code>MY_</code>.</p> <ul> <li>Library class name: <code>Photos</code></li> <li>Library file name: <code>Photos.php</code>,</li> <li>Library load: <code>$this-&gt;load-&gt;library('photos')</code></li> </ul> <h3>Helpers</h3> <p>Helper names and loading are all lowercase. The filename consists of the helper name with <code>_helper</code> appended after.</p> <ul> <li>Helper name: <code>url</code></li> <li>Helper file name: <code>url_helper.php</code></li> <li>Helper load: <code>$this-&gt;load-&gt;helper('url')</code></li> </ul> <h3>Notes</h3> <p>CodeIgniter is somewhat inconsistent in their naming conventions, but there really aren't too many rules, so they are easy to get used to and memorize. I very rarely have issues with naming and loading in CI, and when I do, it's usually because I was just working on a Composer-related project so I got into a different habit.</p> <p>The rules in this answer are for CodeIgniter 2.1.x as of this writing. There is discussion on Github for 3.0 to <a href="https://github.com/EllisLab/CodeIgniter/issues/1805" rel="noreferrer">better and add more consistency to naming conventions</a>, which you can read about and contribute to if you'd like.</p>
17,070,101
Why I cannot link the Mac framework file with CMake?
<p>I have a question related to CMake in MAC. I make sure that the executable program will link the framework and libraries correctly with the following codes:</p> <pre><code>link_directories(directory_to_framework_and_libs) add_executable(program ${FILE_LIST}) target_link_libraries(program framework_name lib1 lib2) </code></pre> <p>In the first line code, I denote the location where the executable program can search for the framework and libraries. In the third line code, the framework and the libraries will link to the executable program. However, when I compile the xcode.project created from the cmake file with Xcode 4, the project keeps complaining that it cannot find <code>-lframework_name</code>: <code>ld: library not found -lframework_name</code> Any ideas will be appreciated. </p>
17,073,875
5
1
null
2013-06-12 15:59:05.563 UTC
8
2022-03-27 23:11:44.747 UTC
null
null
null
null
1,264,018
null
1
17
cmake
29,607
<p>You can't link to a framework this way, you have to use <a href="https://cmake.org/cmake/help/latest/command/find_library.html" rel="noreferrer"><code>find_library</code></a> as it includes some special handling for frameworks on OSX.</p> <p>Also, don't use <a href="https://cmake.org/cmake/help/latest/command/link_directories.html" rel="noreferrer"><code>link_directories</code></a>, CMake use full paths to libraries and it's not needed.</p> <p>Here's some simple example with AudioUnit:</p> <pre><code>find_library(AUDIO_UNIT AudioUnit) if (NOT AUDIO_UNIT) message(FATAL_ERROR "AudioUnit not found") endif() add_executable(program ${program_SOURCES}) target_link_libraries(program ${AUDIO_UNIT}) </code></pre>
16,961,021
How to get span to take up the full height of the containing td
<p>I have a table, and in the left column I want to add an indicator for the row. I'm using a span to render the indicator, but I can't get the span to take up the full height:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td style="padding:0px;"&gt;&lt;span style="height:100%; width:5px; background-color:pink;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/td&gt; &lt;td&gt;Some content&lt;/td&gt; &lt;td&gt;Some more content&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>The table has a padding of 15px, so for the indicator col I remove the padding, and set the span to height:100%:</p> <pre><code>td {padding:15px;} table {background-color: yellow;} </code></pre> <p><a href="http://jsfiddle.net/mNjsb/">This fiddle</a> shows it currently running - that pink bar needs to span the whole height of the containing td.</p> <p>How do I do this? Note that I can't set the styling on the td instead of the span because that causes other issues with the rendering (it offsets the <code>border-bottom</code> of the <code>th</code> rows if I do that).</p>
16,961,177
9
5
null
2013-06-06 11:32:01.293 UTC
3
2021-09-17 03:41:15.697 UTC
null
null
null
null
24,109
null
1
21
html|css
51,308
<p>Should add overflow:auto to the span (and display:block of course)</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td style="padding:0px;"&gt;&lt;span style="height:100%; width:5px; background-color:pink;display:block;overflow:auto"&gt;&amp;nbsp;&lt;/span&gt;&lt;/td&gt; &lt;td&gt;Some content&lt;/td&gt; &lt;td&gt;Some more content&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
16,725,392
Share a single service between multiple angular.js apps
<p>I'm building an ecommerce site (based on shopify) and I'm using multiple small angularjs apps to handle things such as a quick shopping cart, wishlists, filtering products and a few other smaller items. I initially used one big application (that had routing and everything), but it was a bit to restrictive when I didn't have a full REST API.</p> <p>There are a couple of services that I would like to share between the angular apps (the cart service, so I can have a quick add button that will reflect in the mini-cart and such), but I'm not sure of the best way (if there is a way) to go about this. Just sharing a module with the service doesn't keep the same state across the apps.</p> <p>I tried my hand at it, but I it doesn't seem to update state between both apps. The following is the javascript I tried using. It's also on jsfiddle with accompanying html: <a href="http://jsfiddle.net/k9KM7/1/" rel="noreferrer">http://jsfiddle.net/k9KM7/1/</a></p> <pre><code>angular.module('test-service', []) .service('TestService', function($window){ var text = 'Initial state'; if (!!$window.sharedService){ return $window.sharedService; } $window.sharedService = { change: function(newText){ text = newText; }, get: function(){ return text; } } return $window.sharedService; }); angular.module('app1', ['test-service']) .controller('App1Ctrl', function($scope, TestService){ $scope.text = function(){ return TestService.get() } $scope.change = function(){ TestService.change('app 1 activated') } }); angular.module('app2', ['test-service']) .controller('App2Ctrl', function($scope, TestService){ $scope.text = function(){ return TestService.get() } $scope.change = function(){ TestService.change('app 2 activated') } }); var app1El = document.getElementById('app1'); var app2El = document.getElementById('app2'); angular.bootstrap(app1El, ['app1', 'test-service']); angular.bootstrap(app2El, ['app2', 'test-service']); </code></pre> <p>Any help would be appreciated</p>
16,725,874
2
0
null
2013-05-23 23:13:14.44 UTC
16
2014-09-05 10:10:24.197 UTC
null
null
null
null
334,133
null
1
34
javascript|angularjs
18,966
<p>The <code>sharedService</code> is being shared, but one angular app doesn't know that something updated in the other app so it doesn't kick off a <code>$digest</code>. You have to manually tell the <code>$rootScope</code> of each application to start a <code>$digest</code> by calling <code>$rootscope.$apply()</code></p> <p>Fiddle: <a href="http://jsfiddle.net/pvtpenguin/k9KM7/3/">http://jsfiddle.net/pvtpenguin/k9KM7/3/</a></p> <pre><code> angular.module('test-service', []) .service('TestService', function($rootScope, $window){ var text = 'Initial state'; $window.rootScopes = $window.rootScopes || []; $window.rootScopes.push($rootScope); if (!!$window.sharedService){ return $window.sharedService; } $window.sharedService = { change: function(newText){ text = newText; angular.forEach($window.rootScopes, function(scope) { if(!scope.$$phase) { scope.$apply(); } }); }, get: function(){ return text; } } return $window.sharedService; }); </code></pre>
16,768,930
Implementations of Emoji (Emoticon) View/Keyboard Layouts
<p>I am trying to figure out how the emoji (emoticon) selections are implemented on the <code>Facebook</code> app and the Google <code>Hangouts</code> app. I looked into the <code>SoftKeyboard</code> Demo app in the Android API Samples but the display of these emoji views does not look like a <code>SoftKeyboard</code>. It looks and behaves more like a custom <code>Dialog</code> view. Does anyone have an idea of how these are implemented?</p> <h2>Facebook App</h2> <p><img src="https://i.stack.imgur.com/7pFwS.png" alt="Facebook" /></p> <h2>Google Hangouts app</h2> <p><img src="https://i.stack.imgur.com/WVUst.png" alt="Hangouts" /></p> <p>Also, is <a href="http://apps.timwhitlock.info/emoji/tables/unicode" rel="noreferrer">Unicode</a> the best way to send emoticons or is there an alternative? I noticed that some <code>Unicode</code> sequences like <code>\u1F601</code> don't render the corresponding emoticon and instead that sequence just shows up as <code>1</code> :</p> <pre><code>EditText messageInput = (EditText) findViewById(R.id.message_input); messageInput.getText().append(&quot;\u1F601&quot;); </code></pre>
17,014,940
6
2
null
2013-05-27 08:12:58.537 UTC
47
2018-07-11 21:05:07.283 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
502,671
null
1
61
android|android-softkeyboard|emoji|emoticons
96,074
<p>I found a very useful <a href="https://github.com/chiragjain/Emoticons-Keyboard" rel="noreferrer">Emoticon Keyboard</a>. This keyboard is not using Unicode sequences but rather just local image assets. I am thinking that this type of keyboard can only be useful within this app and not with other apps or Operating Systems.</p> <p>So instead I am replacing the <code>ImageView</code> containing an asset with a <code>TextView</code> containing a Unicode sequence.</p> <p>After cross referencing <a href="http://apps.timwhitlock.info/emoji/tables/unicode#note1" rel="noreferrer">Supported Unicode Sequences</a> as well as the <a href="http://www.charbase.com/1F601" rel="noreferrer">Visual Unicode Database</a> I realized that <code>\u1F601</code> was a 32 bit Unicode representation, and the 16bit representation can be set like :</p> <pre><code>EditText messageInput = (EditText) findViewById(R.id.message_input); messageInput.getText().append("\ud83d\ude01"); </code></pre>
20,502,860
Scroll View not functioning IOS 7
<p>I have a scrollview inside which i have 20 UItextviews. The scrollview is not working. I have set the following in viewdidload.</p> <pre><code>self.MainScroll.contentSize = CGSizeMake(320, 1800); </code></pre> <p>Still it doesn't scroll. However, if i give bounce vertically, it just bounces. My scrollview is a child of the main UIview of dimension 320*600. Please guide how to enable the scroll!!</p> <p><img src="https://i.stack.imgur.com/q9Kkx.png" alt="" /></p>
20,503,513
2
8
null
2013-12-10 18:51:18.94 UTC
26
2017-06-28 15:23:26.7 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
2,150,969
null
1
28
iphone|uiscrollview|ios7
21,991
<p>There are two ways you can get the scrolling to work.</p> <p><strong>Approach 1 (with code):</strong></p> <p>1) Pin <code>UIScrollView</code> to the sides of its parent view, as mentioned below.</p> <p><img src="https://i.stack.imgur.com/ugYxG.png" alt="enter image description here"></p> <p>2) Set content size of your scroll view in <code>viewDidLayoutSubviews</code>:</p> <pre><code>- (void)viewDidLayoutSubviews { self.MainScroll.contentSize = CGSizeMake(320, 1800); } </code></pre> <p><strong>Approach 2 (pure IB, no code required):</strong></p> <p>1) Setting <code>contentSize</code> is not required if using <code>AutoLayout</code>. You need to pin your <code>UIScrollView</code> to the parent view as mentioned below:</p> <p><img src="https://i.stack.imgur.com/ugYxG.png" alt="enter image description here"></p> <p>2) Then add another <code>UIView</code> inside UIScrollView to act as a content view and pin it to the UIScrollView and move all controls inside this content view:</p> <p><img src="https://i.stack.imgur.com/Lc1fv.png" alt="enter image description here"></p> <p>3) Pin content view to its parent scroll view as mentioned below:</p> <p><img src="https://i.stack.imgur.com/ugYxG.png" alt="enter image description here"></p> <p>4) Set your UIViewController's Simulated Metrics to Freeform (this is important):</p> <p><img src="https://i.stack.imgur.com/FZeI0.png" alt="enter image description here"></p> <p>5) Size your content <code>UIView</code> to your desired height (obviously important too):</p> <p><img src="https://i.stack.imgur.com/mD8VB.png" alt="enter image description here"></p> <blockquote> <p>Apple article explaining UIScrollView and AutoLayouts: <a href="https://developer.apple.com/library/content/technotes/tn2154/_index.html" rel="nofollow noreferrer">https://developer.apple.com/library/content/technotes/tn2154/_index.html</a></p> </blockquote>
25,787,555
LINQ performance Count vs Where and Count
<pre><code>public class Group { public string Name { get; set; } } </code></pre> <p>Test: </p> <pre><code>List&lt;Group&gt; _groups = new List&lt;Group&gt;(); for (int i = 0; i &lt; 10000; i++) { var group = new Group(); group.Name = i + "asdasdasd"; _groups.Add(group); } Stopwatch _stopwatch2 = new Stopwatch(); _stopwatch2.Start(); foreach (var group in _groups) { var count = _groups.Count(x =&gt; x.Name == group.Name); } _stopwatch2.Stop(); Console.WriteLine(_stopwatch2.ElapsedMilliseconds); Stopwatch _stopwatch = new Stopwatch(); _stopwatch.Start(); foreach (var group in _groups) { var count = _groups.Where(x =&gt; x.Name == group.Name).Count(); } _stopwatch.Stop(); Console.WriteLine(_stopwatch.ElapsedMilliseconds); </code></pre> <p>Result: First: 2863, Second 2185</p> <p>Can someone explain me why first approach is slower than second? Second should return enumerator and invoke count on it and first just invoke count. First approach should be a little faster.</p> <p>EDIT: I removed counter lists to prevent using GC and changed order to check if ordering has meaning. Results are almost the same.</p> <p>EDIT2: This performance problem is not related only with Count. It's related with First(),FirstOrDefault(), Any(), etc.. Where + Method is always faster than Method.</p>
25,789,631
6
14
null
2014-09-11 12:32:29.56 UTC
10
2014-09-12 08:42:55.643 UTC
2014-09-12 08:42:43.81 UTC
null
1,411,104
null
1,411,104
null
1
36
c#|linq
6,176
<p>The crucial thing is in the implementation of <code>Where()</code> where it casts the <code>IEnumerable</code> to a <code>List&lt;T&gt;</code> if it can. Note the cast where <code>WhereListIterator</code> is constructed (this is from .Net source code obtained via reflection):</p> <pre><code>public static IEnumerable&lt;TSource&gt; Where&lt;TSource&gt;(this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate) { if (source is List&lt;TSource&gt;) return new WhereListIterator&lt;TSource&gt;((List&lt;TSource&gt;)source, predicate); return new WhereEnumerableIterator&lt;TSource&gt;(source, predicate); } </code></pre> <p>I have verified this by copying (and simplifying where possible) the .Net implementations.</p> <p>Crucially, I implemented two versions of <code>Count()</code> - one called <code>TestCount()</code> where I use <code>IEnumerable&lt;T&gt;</code>, and one called <code>TestListCount()</code> where I cast the enumerable to <code>List&lt;T&gt;</code> before counting the items.</p> <p>This gives the same speedup as we see for the <code>Where()</code> operator which (as shown above) also casts to <code>List&lt;T&gt;</code> where it can.</p> <p>(This should be tried with a release build without a debugger attached.)</p> <p>This demonstrates that it is faster to use <code>foreach</code> to iterate over a <code>List&lt;T&gt;</code> compared to the same sequence represented via a <code>IEnumerable&lt;T&gt;</code>.</p> <p>Firstly, here's the complete test code:</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace Demo { public class Group { public string Name { get; set; } } internal static class Program { static void Main() { int dummy = 0; List&lt;Group&gt; groups = new List&lt;Group&gt;(); for (int i = 0; i &lt; 10000; i++) { var group = new Group(); group.Name = i + "asdasdasd"; groups.Add(group); } Stopwatch stopwatch = new Stopwatch(); for (int outer = 0; outer &lt; 4; ++outer) { stopwatch.Restart(); foreach (var group in groups) dummy += TestWhere(groups, x =&gt; x.Name == group.Name).Count(); Console.WriteLine("Using TestWhere(): " + stopwatch.ElapsedMilliseconds); stopwatch.Restart(); foreach (var group in groups) dummy += TestCount(groups, x =&gt; x.Name == group.Name); Console.WriteLine("Using TestCount(): " + stopwatch.ElapsedMilliseconds); stopwatch.Restart(); foreach (var group in groups) dummy += TestListCount(groups, x =&gt; x.Name == group.Name); Console.WriteLine("Using TestListCount(): " + stopwatch.ElapsedMilliseconds); } Console.WriteLine("Total = " + dummy); } public static int TestCount&lt;TSource&gt;(IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate) { int count = 0; foreach (TSource element in source) { if (predicate(element)) count++; } return count; } public static int TestListCount&lt;TSource&gt;(IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate) { return testListCount((List&lt;TSource&gt;) source, predicate); } private static int testListCount&lt;TSource&gt;(List&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate) { int count = 0; foreach (TSource element in source) { if (predicate(element)) count++; } return count; } public static IEnumerable&lt;TSource&gt; TestWhere&lt;TSource&gt;(IEnumerable&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate) { return new WhereListIterator&lt;TSource&gt;((List&lt;TSource&gt;)source, predicate); } } class WhereListIterator&lt;TSource&gt;: Iterator&lt;TSource&gt; { readonly Func&lt;TSource, bool&gt; predicate; List&lt;TSource&gt;.Enumerator enumerator; public WhereListIterator(List&lt;TSource&gt; source, Func&lt;TSource, bool&gt; predicate) { this.predicate = predicate; this.enumerator = source.GetEnumerator(); } public override bool MoveNext() { while (enumerator.MoveNext()) { TSource item = enumerator.Current; if (predicate(item)) { current = item; return true; } } Dispose(); return false; } } abstract class Iterator&lt;TSource&gt;: IEnumerable&lt;TSource&gt;, IEnumerator&lt;TSource&gt; { internal TSource current; public TSource Current { get { return current; } } public virtual void Dispose() { current = default(TSource); } public IEnumerator&lt;TSource&gt; GetEnumerator() { return this; } public abstract bool MoveNext(); object IEnumerator.Current { get { return Current; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IEnumerator.Reset() { throw new NotImplementedException(); } } } </code></pre> <p>Now here's the IL generated for the two crucial methods, <code>TestCount():</code> and <code>testListCount()</code>. Remember that the only difference between these is that <code>TestCount()</code> is using the <code>IEnumerable&lt;T&gt;</code> and <code>testListCount()</code> is using the same enumerable, but cast to its underlying <code>List&lt;T&gt;</code> type:</p> <pre><code>TestCount(): .method public hidebysig static int32 TestCount&lt;TSource&gt;(class [mscorlib]System.Collections.Generic.IEnumerable`1&lt;!!TSource&gt; source, class [mscorlib]System.Func`2&lt;!!TSource, bool&gt; predicate) cil managed { .maxstack 8 .locals init ( [0] int32 count, [1] !!TSource element, [2] class [mscorlib]System.Collections.Generic.IEnumerator`1&lt;!!TSource&gt; CS$5$0000) L_0000: ldc.i4.0 L_0001: stloc.0 L_0002: ldarg.0 L_0003: callvirt instance class [mscorlib]System.Collections.Generic.IEnumerator`1&lt;!0&gt; [mscorlib]System.Collections.Generic.IEnumerable`1&lt;!!TSource&gt;::GetEnumerator() L_0008: stloc.2 L_0009: br L_0025 L_000e: ldloc.2 L_000f: callvirt instance !0 [mscorlib]System.Collections.Generic.IEnumerator`1&lt;!!TSource&gt;::get_Current() L_0014: stloc.1 L_0015: ldarg.1 L_0016: ldloc.1 L_0017: callvirt instance !1 [mscorlib]System.Func`2&lt;!!TSource, bool&gt;::Invoke(!0) L_001c: brfalse L_0025 L_0021: ldloc.0 L_0022: ldc.i4.1 L_0023: add.ovf L_0024: stloc.0 L_0025: ldloc.2 L_0026: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() L_002b: brtrue.s L_000e L_002d: leave L_003f L_0032: ldloc.2 L_0033: brfalse L_003e L_0038: ldloc.2 L_0039: callvirt instance void [mscorlib]System.IDisposable::Dispose() L_003e: endfinally L_003f: ldloc.0 L_0040: ret .try L_0009 to L_0032 finally handler L_0032 to L_003f } testListCount(): .method private hidebysig static int32 testListCount&lt;TSource&gt;(class [mscorlib]System.Collections.Generic.List`1&lt;!!TSource&gt; source, class [mscorlib]System.Func`2&lt;!!TSource, bool&gt; predicate) cil managed { .maxstack 8 .locals init ( [0] int32 count, [1] !!TSource element, [2] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator&lt;!!TSource&gt; CS$5$0000) L_0000: ldc.i4.0 L_0001: stloc.0 L_0002: ldarg.0 L_0003: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator&lt;!0&gt; [mscorlib]System.Collections.Generic.List`1&lt;!!TSource&gt;::GetEnumerator() L_0008: stloc.2 L_0009: br L_0026 L_000e: ldloca.s CS$5$0000 L_0010: call instance !0 [mscorlib]System.Collections.Generic.List`1/Enumerator&lt;!!TSource&gt;::get_Current() L_0015: stloc.1 L_0016: ldarg.1 L_0017: ldloc.1 L_0018: callvirt instance !1 [mscorlib]System.Func`2&lt;!!TSource, bool&gt;::Invoke(!0) L_001d: brfalse L_0026 L_0022: ldloc.0 L_0023: ldc.i4.1 L_0024: add.ovf L_0025: stloc.0 L_0026: ldloca.s CS$5$0000 L_0028: call instance bool [mscorlib]System.Collections.Generic.List`1/Enumerator&lt;!!TSource&gt;::MoveNext() L_002d: brtrue.s L_000e L_002f: leave L_0042 L_0034: ldloca.s CS$5$0000 L_0036: constrained [mscorlib]System.Collections.Generic.List`1/Enumerator&lt;!!TSource&gt; L_003c: callvirt instance void [mscorlib]System.IDisposable::Dispose() L_0041: endfinally L_0042: ldloc.0 L_0043: ret .try L_0009 to L_0034 finally handler L_0034 to L_0042 } </code></pre> <p>I think that the important lines here is where it calls <code>IEnumerator::GetCurrent()</code> and <code>IEnumerator::MoveNext()</code>.</p> <p>In the first case it is:</p> <pre><code>callvirt instance !0 [mscorlib]System.Collections.Generic.IEnumerator`1&lt;!!TSource&gt;::get_Current() callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext() </code></pre> <p>And in the second case it is:</p> <pre><code>call instance !0 [mscorlib]System.Collections.Generic.List`1/Enumerator&lt;!!TSource&gt;::get_Current() call instance bool [mscorlib]System.Collections.Generic.List`1/Enumerator&lt;!!TSource&gt;::MoveNext() </code></pre> <p>Importantly, in the second case a non-virtual call is being made - which can be significantly faster than a virtual call if it is in a loop (which it is, of course).</p>
63,067,555
How to make an import shortcut/alias in create-react-app?
<p>How to set import shortcuts/aliases in create-react-app? From this:</p> <pre><code>import { Layout } from '../../Components/Layout' </code></pre> <p>to this:</p> <pre><code>import { Layout } from '@Components/Layout' </code></pre> <p>I have a <code>webpack</code> 4.42.0 version. I don't have a webpack.config.js file in the root directory. I've tried to create one myself with this code inside:</p> <pre><code>const path = require('path') module.exports = { resolve: { alias: { '@': path.resolve(__dirname, 'src/'), } } }; </code></pre> <p>But it doesn't seem to work. I've seen the <code>NODE_PATH=.</code> variant in <code>.env</code> file. But I believe, it is deprecated - better not to use. And also, I have a <code>posstcss.config.js</code> file. Because I've installed the TailwindCss and I import the CSS library there. I've tried to paste the same code there, but it also didn't work.</p>
63,068,531
5
5
null
2020-07-24 05:46:03.943 UTC
13
2022-09-08 05:46:25.163 UTC
2020-07-24 07:10:17.083 UTC
null
7,882,470
null
12,355,067
null
1
57
javascript|reactjs|webpack|alias|create-react-app
57,093
<h2>NOTE FOR CONFUSING TERMS</h2> <pre><code>// Absolute path: paths which are relative to a specific path import Input from 'components' // src/components import UsersUtils from 'page/users/utils' // src/page/users/utils // Alias path: other naming to specific path import Input from '@components' // src/components import UsersUtils from '@userUtils' // src/page/users/utils </code></pre> <p>In order for webpack's <strong>aliases</strong> to work, you need to configure the default <code>webpack.config.js</code> of <code>create-react-app</code>.</p> <p>The <strong>official way</strong> is <a href="https://create-react-app.dev/docs/alternatives-to-ejecting" rel="noreferrer">to use the <code>eject</code> script</a>.</p> <p>But the <strong>recommended way</strong> is to use a library without ejecting, like <a href="https://github.com/gsoft-inc/craco" rel="noreferrer"><code>craco</code></a>.</p> <p>After following the <a href="https://github.com/gsoft-inc/craco/blob/master/packages/craco/README.md#installation" rel="noreferrer">installation</a>, add <code>craco.config.js</code> to your root folder with the desired configuration.</p> <p>My example:</p> <pre><code>// craco.config.js const path = require(`path`); const alias = require(`./src/config/aliases`); const SRC = `./src`; const aliases = alias(SRC); const resolvedAliases = Object.fromEntries( Object.entries(aliases).map(([key, value]) =&gt; [key, path.resolve(__dirname, value)]), ); module.exports = { webpack: { alias: resolvedAliases, }, }; </code></pre> <p>Where <code>aliases.js</code> (<code>./src/config/aliases</code>) exports a helper function:</p> <pre><code>const aliases = (prefix = `src`) =&gt; ({ '@atoms': `${prefix}/components/atoms`, '@molecules': `${prefix}/components/molecules`, '@organisms': `${prefix}/components/organisms`, '@templates': `${prefix}/components/templates`, '@components': `${prefix}/components`, '@config': `${prefix}/config`, '@enums': `${prefix}/enums`, '@hooks': `${prefix}/hooks`, '@icons': `${prefix}/components/atoms/Icons`, '@styles': `${prefix}/styles`, '@utils': `${prefix}/utils`, '@state': `${prefix}/state`, '@types': `${prefix}/types`, '@storybookHelpers': `../.storybook/helpers`, }); module.exports = aliases; </code></pre> <h3>VSCode IntelliSense</h3> <p>In addition, you should add <code>jsconfig.json</code> file for path IntelliSense in VSCode (or <code>tsconfig.json</code>), <a href="https://stackoverflow.com/questions/58249053/how-to-intellisense-alias-module-path-in-vscode">see followup question</a>.</p> <p>Now such code with IntelliSense will work:</p> <pre><code>// NOTE THAT THOSE ARE ALIASES, NOT ABSOLUTE PATHS // AutoComplete and redirection works import {ColorBox} from '@atoms'; import {RECOIL_STATE} from '@state'; </code></pre>
41,351,739
main.jsbundle, Foundation and Security missing in the project, causing error
<p>I've noticed that file <code>main.jsbundle</code> file is missing from the project and am not sure of how to fix it, should I delete the file / is there a step I can perform to fix it?</p> <p>Here is a screenshot of where it is in the project:</p> <p><a href="https://i.stack.imgur.com/5RKO0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5RKO0.png" alt="enter image description here"></a></p> <p><strong>Update:</strong></p> <p>Similar issue appears with following frameworks as well</p> <p><a href="https://i.stack.imgur.com/6az5G.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6az5G.png" alt="enter image description here"></a></p>
41,444,682
4
7
null
2016-12-27 20:22:35.67 UTC
10
2018-11-29 11:46:59.383 UTC
null
null
null
null
911,930
null
1
16
javascript|ios|xcode|reactjs|react-native
12,983
<p>The problem can be resolved as follows</p> <ul> <li>By using the <code>react native</code> command line</li> <li><code>$ react-native bundle --entry-file ./index.ios.js --platform ios --bundle-output ios/main.jsbundle</code> using this in the <em>root of the react native project</em></li> <li>When the <code>main.jsbundle</code> file is generated add it back to the <code>Add Files to Project</code> option</li> <li>Just verify that the file is included in the <em>build phase</em> and <code>re-build</code></li> </ul> <p><strong>Update</strong> For the asset destination to be set <em>they have to be in same folder</em>.</p> <p>Try this,it would create the asset folder</p> <pre><code>$ react-native bundle --entry-file ./index.ios.js --platform ios --bundle-output ios/main.jsbundle --assets-dest ./ios </code></pre>
9,716,779
How to Read a TXT file in Java Server Page Directory
<p>I'd like to create an app that requires to read a <code>.txt</code> file on my project directory. </p> <p>This is my code of my <code>index.jsp</code>: </p> <pre><code>&lt;%@page import="java.io.FileReader"%&gt; &lt;%@page import="java.io.BufferedReader"%&gt; &lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;Read Text&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;% BufferedReader reader = new BufferedReader(new FileReader("aFile.txt")); StringBuilder sb = new StringBuilder(); String line; while((line = reader.readLine())!= null){ sb.append(line+"\n"); } out.println(sb.toString()); %&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When I execute the above code, my browser tells me that <code>aFile.txt</code> cannot be found. Then, I've put <code>aFile.txt</code> in the same directory as this web page runs (<code>index.jsp</code>). I wonder, what should I write to locate the directory of <code>aFile.txt</code></p> <p>And this is how my problem was solved. Thanks Ahmad hasem</p> <pre><code>&lt;%@page import="java.io.File"%&gt; &lt;%@page import="java.io.InputStreamReader"%&gt; &lt;%@page import="java.net.URL"%&gt; &lt;%@page import="java.io.FileReader"%&gt; &lt;%@page import="java.io.BufferedReader"%&gt; &lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;Read Text&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;% String jspPath = session.getServletContext().getRealPath("/res"); String txtFilePath = jspPath+ "/aFile.txt"; BufferedReader reader = new BufferedReader(new FileReader(txtFilePath)); StringBuilder sb = new StringBuilder(); String line; while((line = reader.readLine())!= null){ sb.append(line+"\n"); } out.println(sb.toString()); %&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
9,716,945
5
0
null
2012-03-15 09:13:48.923 UTC
null
2017-02-08 03:24:26.23 UTC
2014-12-20 20:03:28.507 UTC
user1733583
4,818,540
null
1,052,070
null
1
5
java|jsp|web
49,651
<p>Try to locate it from application's root path.</p> <p><a href="http://www.java2s.com/Code/Java/JSP/ReadingBinaryData.htm" rel="nofollow">http://www.java2s.com/Code/Java/JSP/ReadingBinaryData.htm</a></p>
10,038,673
Using Eclipse with Play Framework 2.0
<p>I am new to Framework 2.0. In Play 1.0, after you Eclipsify your project, you have have a *.launch file that you can use to launch your project.</p> <p>After you eclipsify in Play 2.0, you don't seem to have anything similar. Is there a way to control your launching and to debug Play 2.0, using Eclipse?</p> <p>A similar question: <a href="https://stackoverflow.com/questions/9778849/debug-playframework-2-0-in-eclipse">Debug Playframework 2.0 in Eclipse</a></p> <p>The answer to that question did not have specific enough instructions for me to know how to follow.</p>
10,040,676
1
0
null
2012-04-06 03:09:21.043 UTC
8
2012-04-06 07:49:14.19 UTC
2017-05-23 12:29:34.01 UTC
null
-1
null
953,068
null
1
11
eclipse|playframework-2.0
14,948
<p>Question 1:</p> <p>After you have eclipsified, open Eclipse and choose <code>File -&gt; Import... -&gt; Existing Projects into Workspace</code>. A dialog will open, choose your Play Framework 2.0 project folder and click <code>Finish</code>.</p> <p>Question 2:</p> <ol> <li><p>Start your Play Framework application using <code>play debug run</code>. You will see something like this:</p> <p>Listening for transport dt_socket at address: 9999 ...</p></li> <li><p>In Eclipse, right-click on your project in <code>Project Explorer</code> and choose <code>Debug As -&gt; Debug Configurations...</code>. </p></li> <li><p>A new dialog called <code>Debug Configurations</code> will open. Double-click on <code>Remote Java Application</code> and a new window will appear on the right side. Change the <code>Connection properties</code> so that the point to host <code>localhost</code> and port <code>9999</code>. Confirm by clicking the <code>Debug</code> button.</p></li> <li><p>Put a breakpoint in your Application in Eclipse. </p></li> <li><p>Try your application as normal in a web-browser. If it hits a breakpoint then Eclipse will be brought as frontmost and let you debug.</p></li> </ol>
10,095,225
Tracking Individual Users with Google Analytics Custom Variables
<p>I've been working on a support center for my company and we need to track individual users when they login. If possible we would like to track details as well such as pages visited and time spent on the site as well. I'm able to track how many people login to the site using a custom variable, but I am unable to track individual users. Here is the code I've been using to try to grab the individual user id:</p> <pre><code> $(document).ready( function() { var welcomeEmail = document.getElementById('welcome_email').innerHTML; var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-30086012-1']); var welcomeEmail; if( $('#welcome_email').length > 0 ) { //This block of logic makes sure that the welcome_email element actually exists, it will not exist if a user is not logged in yet welcomeEmail = document.getElementById('welcome_email').innerHTML; } _gaq.push(['_setCustomVar',1,'UserEmail',welcomeEmail,1]); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </code></pre> <p>What am I missing/doing incorrectly. Appreciate any feedback.</p>
10,097,412
5
0
null
2012-04-10 19:35:04.973 UTC
8
2014-08-16 08:55:10.177 UTC
2012-10-02 10:43:23.27 UTC
null
140,938
null
1,324,805
null
1
22
google-analytics|userid
20,390
<p>That is a violation of <a href="http://www.google.com/analytics/tos.html" rel="noreferrer">Google Analytics terms of service</a>. See number 7 PRIVACY.</p> <blockquote> <p>7.PRIVACY . You will not (and will not allow any third party to) use the Service to track or collect personally identifiable information of Internet users, nor will You (or will You allow any third party to) associate any data gathered from Your website(s) (or such third parties' website(s)) with any personally identifying information from any source as part of Your use (or such third parties' use) of the Service. You will have and abide by an appropriate privacy policy and will comply with all applicable laws relating to the collection of information from visitors to Your websites. You must post a privacy policy and that policy must provide notice of your use of a cookie that collects anonymous traffic data. </p> </blockquote> <p>And</p> <blockquote> <p>While the username or user ID is not directly PII, if it is used to tie to a person from a backend system…that’s a violation of the Terms of Service.</p> </blockquote> <p>Google Analytics is not the tool to use for this type of tracking. A custom backend solution that is hosted on your own servers is the better way to go.</p>
10,109,788
Callback after the DOM was updated in Meteor.js
<p>I have this Meteor project: <a href="https://github.com/jfahrenkrug/code_buddy" rel="noreferrer">https://github.com/jfahrenkrug/code_buddy</a> </p> <p>It's basically a tool with a big textarea and a pre area that lets you enter source code snippets that automatically get pushed to all connected clients. </p> <p>I'd like to automatically run the highlightSyntax function when the code was changed, but it doesn't really work.</p> <p>I've tried query.observe, but that didn't work too well: The syntax highlight flashed up once and then disappeared again.</p> <p>So my question is: How do I run code after the DOM was updated?</p>
10,119,993
9
0
null
2012-04-11 16:10:44.95 UTC
19
2016-01-19 16:03:10.28 UTC
null
null
null
null
171,933
null
1
35
meteor
14,388
<p>A hacky way to do it is:</p> <p><strong>foo.html</strong></p> <pre><code>&lt;template name="mytemplate"&gt; &lt;div id="my-magic-div"&gt; .. stuff goes here .. {{add_my_special_behavior}} &lt;/div&gt; &lt;/template&gt; </code></pre> <p><strong>foo.js</strong></p> <pre><code>Template.mytemplate.add_my_special_behavior = function () { Meteor.defer(function () { // find #my-magic-div in the DOM // do stuff to it }); // return nothing }; </code></pre> <p>The function will get called whenever the template is rendered (or re-rendered), so you can use it as a hook to do whatever special DOM manipulation you want to do. You need to use Meteor.defer (which does the same thing as settimeout(f, 0)) because at the time the template is being rendered, it isn't in the DOM yet.</p> <p>Keep in mind that you can render a template without inserting it in the DOM! For example, it's totally legal to do this:</p> <pre><code>console.log(Template.mytemplate()) </code></pre> <p>So when a template is rendered, there is not a 100% guarantee that it is going to end up in the DOM. It's up to the user of the template.</p>
9,799,074
How to make ReSharper re-evaluate its assembly reference highlighting
<p>I am creating a Prism Project Template, and the template works great. But after I create a project with the template some of the files look like this:</p> <p><img src="https://i.stack.imgur.com/p10Pt.png" alt="Bad References"></p> <p><strong>Despite appearances, everything is just fine.</strong></p> <p>If I do a <em>Rebuild All</em> I see that the solution builds with no errors:</p> <p><img src="https://i.stack.imgur.com/vkV5N.png" alt="Rebuilt"></p> <p>But the rebuild all does not get rid of the "errors" that are showing in the editor window. (Note that the actual error window does not show any errors.)</p> <p>I can clean, rebuild, close and open files, and it will not fix the highlighting.</p> <p>However, <strong>if I close the solution and re-open it, all is well</strong>:</p> <p><img src="https://i.stack.imgur.com/zvLAZ.png" alt="Works After Reload"></p> <p><strong>My Question:</strong></p> <p>Ideally there would be a way for my template or my IWizard to tell ReSharper to reload the references for the highlighting.</p> <p>I know I can turn ReSharper <a href="https://stackoverflow.com/a/1900927/16241">off and then on again</a> and that will fix it, but I would rather not do that.</p> <p>Is there a ReSharper command that just refreshes this stuff?</p>
17,806,179
15
7
null
2012-03-21 05:29:45.7 UTC
53
2019-04-12 17:05:54.363 UTC
2017-05-23 12:26:32.747 UTC
null
-1
null
16,241
null
1
189
visual-studio|visual-studio-2010|resharper|project-template|visual-studio-extensions
46,910
<p>Except for reinstalling, the only way to successfully clear the caches is to delete the files manually from your AppData directory.</p> <p>Delete the solution folder that's giving you grief in the following locations:</p> <blockquote> <ul> <li><code>%LOCALAPPDATA%\JetBrains\ReSharper\v7.1\SolutionCaches\</code> <br/></li> <li><code>%LOCALAPPDATA%\JetBrains\Transient\ReSharperPlatformVsXX\vXX\SolutionCaches\</code> for newer versions.</li> </ul> </blockquote> <p>Note that the version numbers in the paths may be different depending on the ReSharper version that is installed.</p> <p>The <code>XX</code> in <code>vXX</code> and <code>VsXX</code> represents any number, because there might be multiple folders where the solution cache is stored.</p>
7,935,603
C++ - pointer being freed was not allocated error
<pre><code>malloc: *** error for object 0x10ee008c0: pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug Abort trap: 6 </code></pre> <p>Or I get this when I try and print everything</p> <pre><code>Segmentation fault: 11 </code></pre> <p>I'm doing some homework for an OOP class and I've been stuck for a good hour now. I'm getting this error once I've used keyboard input enough. I am not someone who gets frustrated at all, and here I am getting very frustrated with this. Here are the files:</p> <p>This is the book class. I'm pretty sure this is very solid. But just for reference:</p> <pre><code>//--------------- BOOK.CPP --------------- // The class definition for Book. // #include &lt;iostream&gt; #include "book.h" using namespace std; Book::Book() // { strcpy(title, " "); strcpy(author, " "); type = FICTION; price = 0; } void Book::Set(const char* t, const char* a, Genre g, double p) { strcpy(title, t); strcpy(author, a); type = g; price = p; } const char* Book::GetTitle() const { return title; } const char* Book::GetAuthor() const { return author; } double Book::GetPrice() const { return price; } Genre Book::GetGenre() const { return type; } void Book::Display() const { int i; cout &lt;&lt; GetTitle(); for (i = strlen(title) + 1; i &lt; 32; i++) cout &lt;&lt; (' '); cout &lt;&lt; GetAuthor(); for (i = strlen(author) + 1; i &lt; 22; i++) cout &lt;&lt; (' '); switch (GetGenre()) { case FICTION: cout &lt;&lt; "Fiction "; break; case MYSTERY: cout &lt;&lt; "Mystery "; break; case SCIFI: cout &lt;&lt; "SciFi "; break; case COMPUTER: cout &lt;&lt; "Computer "; break; } cout &lt;&lt; "$"; if (GetPrice() &lt; 1000) cout &lt;&lt; " "; if (GetPrice() &lt; 100) cout &lt;&lt; " "; if (GetPrice() &lt; 10) cout &lt;&lt; " "; /* printf("%.2f", GetPrice());*/ cout &lt;&lt; '\n'; } </code></pre> <p>This is the store class that deals with the array and dynamic allocation. This was working well without input commands, but just using its functions it was working like a champ.</p> <pre><code>//--------------- STORE.CPP --------------- // The class definition for Store. // #include &lt;iostream&gt; #include &lt;cstring&gt; // for strcmp #include "store.h" using namespace std; Store::Store() { maxSize = 5; currentSize = 0; bookList = new Book[maxSize]; } Store::~Store() // This destructor function for class Store // deallocates the Store's list of Books { delete [] bookList; } void Store::Insert(const char* t, const char* a, Genre g, double p) // Insert a new entry into the direrctory. { if (currentSize == maxSize)// If the directory is full, grow it. Grow(); bookList[currentSize++].Set(t, a, g, p); } void Store::Sell(const char* t) // Sell a book from the store. { char name[31]; strcpy(name, t); int thisEntry = FindBook(name);// Locate the name in the directory. if (thisEntry == -1) cout &lt;&lt; *name &lt;&lt; " not found in directory"; else { cashRegister = cashRegister + bookList[thisEntry].GetPrice(); // Shift each succeding element "down" one position in the // Entry array, thereby deleting the desired entry. for (int j = thisEntry + 1; j &lt; currentSize; j++) bookList[j - 1] = bookList[j]; currentSize--;// Decrement the current number of entries. cout &lt;&lt; "Entry removed.\n"; if (currentSize &lt; maxSize - 5)// If the directory is too big, shrink it. Shrink(); } } void Store::Find(const char* x) const // Display the Store's matches for a title or author. { // Prompt the user for a name to be looked up char name[31]; strcpy(name, x); int thisBook = FindBook(name); if (thisBook != -1) bookList[thisBook].Display(); int thisAuthor = FindAuthor(name, true); if ((thisBook == -1) &amp;&amp; (thisAuthor == -1)) cout &lt;&lt; name &lt;&lt; " not found in current directory\n"; } void Store::DisplayGenre(const Genre g) const { double genrePrice = 0; int genreCount = 0; for (int i = 0; i &lt; currentSize; i++)// Look at each entry. { if (bookList[i].GetGenre() == g) { bookList[i].Display(); genrePrice = genrePrice + bookList[i].GetPrice(); genreCount++; } } cout &lt;&lt; "Number of books in this genre: " &lt;&lt; genreCount &lt;&lt; " " &lt;&lt; "Total: $"; if (genrePrice &lt; 1000) cout &lt;&lt; " "; if (genrePrice &lt; 100) cout &lt;&lt; " "; if (genrePrice &lt; 10) cout &lt;&lt; " "; printf("%.2f", genrePrice); } void Store::DisplayStore() const { if (currentSize &gt;= 1) { cout &lt;&lt; "**Title**\t\t" &lt;&lt; "**Author**\t" &lt;&lt; "**Genre**\t" &lt;&lt; "**Price**\n\n"; for (int i = 0; i &lt; currentSize; i++) bookList[i].Display(); } else cout &lt;&lt; "No books currently in inventory\n\n"; cout &lt;&lt; "Total Books = " &lt;&lt; currentSize &lt;&lt; "\nMoney in the register = $"; if (cashRegister &lt; 1000) cout &lt;&lt; " "; if (cashRegister &lt; 100) cout &lt;&lt; " "; if (cashRegister &lt; 10) cout &lt;&lt; " "; printf("%.2f", cashRegister); cout &lt;&lt; '\n'; } void Store::Sort(char type) { Book temp; for(int i = 0; i &lt;= currentSize; i++) { for (int j = i+1; j &lt; currentSize; j++) { if (type == 'A') { if (strcmp(bookList[i].GetTitle(), bookList[j].GetTitle()) &gt; 0) { temp = bookList[i]; bookList[i] = bookList[j]; bookList[j] = temp; } } if (type == 'T') { if (strcmp(bookList[i].GetAuthor(), bookList[j].GetAuthor()) &gt; 0) { temp = bookList[i]; bookList[i] = bookList[j]; bookList[j] = temp; } } } } } void Store::SetCashRegister(double x) // Set value of cash register { cashRegister = x; } void Store::Grow() // Double the size of the Store's bookList // by creating a new, larger array of books // and changing the store's pointer to refer to // this new array. { maxSize = currentSize + 5;// Determine a new size. cout &lt;&lt; "** Array being resized to " &lt;&lt; maxSize &lt;&lt; " allocated slots" &lt;&lt; '\n'; Book* newList = new Book[maxSize];// Allocate a new array. for (int i = 0; i &lt; currentSize; i++)// Copy each entry into newList[i] = bookList[i];// the new array. delete [] bookList;// Remove the old array bookList = newList;// Point old name to new array. } void Store::Shrink() // Divide the size of the Store's bookList in // half by creating a new, smaller array of books // and changing the store's pointer to refer to // this new array. { maxSize = maxSize - 5;// Determine a new size. cout &lt;&lt; "** Array being resized to " &lt;&lt; maxSize &lt;&lt; " allocated slots" &lt;&lt; '\n'; Book* newList = new Book[maxSize];// Allocate a new array. for (int i = 0; i &lt; currentSize; i++)// Copy each entry into newList[i] = bookList[i];// the new array. delete [] bookList;// Remove the old array bookList = newList;// Point old name to new array. } int Store::FindBook(char* name) const // Locate a name in the directory. Returns the // position of the entry list as an integer if found. // and returns -1 if the entry is not found in the directory. { for (int i = 0; i &lt; currentSize; i++)// Look at each entry. if (strcmp(bookList[i].GetTitle(), name) == 0) return i;// If found, return position and exit. return -1;// Return -1 if never found. } int Store::FindAuthor(char* name, const bool print) const // Locate a name in the directory. Returns the // position of the entry list as an integer if found. // and returns -1 if the entry is not found in the directory. { int returnValue; for (int i = 0; i &lt; currentSize; i++)// Look at each entry. if (strcmp(bookList[i].GetAuthor(), name) == 0) { if (print == true) bookList[i].Display(); returnValue = i;// If found, return position and exit. } else returnValue = -1;// Return -1 if never found. return returnValue; } </code></pre> <p>Now this is the guy who needs some work. There may be some stuff blank so ignore that. This one controls all the input, which is the problem I believe. </p> <pre><code>#include &lt;iostream&gt; #include "store.h" using namespace std; void ShowMenu() // Display the main program menu. { cout &lt;&lt; "\n\t\t*** BOOKSTORE MENU ***"; cout &lt;&lt; "\n\tA \tAdd a Book to Inventory"; cout &lt;&lt; "\n\tF \tFind a book from Inventory"; cout &lt;&lt; "\n\tS \tSell a book"; cout &lt;&lt; "\n\tD \tDisplay the inventory list"; cout &lt;&lt; "\n\tG \tGenre summary"; cout &lt;&lt; "\n\tO \tSort inventory list"; cout &lt;&lt; "\n\tM \tShow this Menu"; cout &lt;&lt; "\n\tX \teXit Program"; } char GetAChar(const char* promptString) // Prompt the user and get a single character, // discarding the Return character. // Used in GetCommand. { char response;// the char to be returned cout &lt;&lt; promptString;// Prompt the user cin &gt;&gt; response;// Get a char, response = toupper(response);// and convert it to uppercase cin.get();// Discard newline char from input. return response; } char Legal(char c) // Determine if a particular character, c, corresponds // to a legal menu command. Returns 1 if legal, 0 if not. // Used in GetCommand. { return((c == 'A') || (c == 'F') || (c == 'S') || (c == 'D') || (c == 'G') || (c == 'O') || (c == 'M') || (c == 'X')); } char GetCommand() // Prompts the user for a menu command until a legal // command character is entered. Return the command character. // Calls GetAChar, Legal, ShowMenu. { char cmd = GetAChar("\n\n&gt;");// Get a command character. while (!Legal(cmd))// As long as it's not a legal command, {// display menu and try again. cout &lt;&lt; "\nIllegal command, please try again . . ."; ShowMenu(); cmd = GetAChar("\n\n&gt;"); } return cmd; } void Add(Store s) { char aTitle[31]; char aAuthor[21]; Genre aGenre = FICTION; double aPrice = 10.00; cout &lt;&lt; "Enter title: "; cin.getline(aTitle, 30); cout &lt;&lt; "Enter author: "; cin.getline(aAuthor, 20); /* cout &lt;&lt; aTitle &lt;&lt; " " &lt;&lt; aAuthor &lt;&lt; "\n"; cout &lt;&lt; aGenre &lt;&lt; " " &lt;&lt; aPrice &lt;&lt; '\n'; */ s.Insert(aTitle, aAuthor, aGenre, aPrice); } void Find() { } void Sell() { } void ViewGenre(Store s) { char c; Genre result; do c = GetAChar("Enter Genre - (F)iction, (M)ystery, (S)ci-Fi, or (C)omputer: "); while ((c != 'F') &amp;&amp; (c != 'M') &amp;&amp; (c != 'S') &amp;&amp; (c != 'C')); switch (result) { case 'F': s.DisplayGenre(FICTION); break; case 'M': s.DisplayGenre(MYSTERY); break; case 'S': s.DisplayGenre(SCIFI); break; case 'C': s.DisplayGenre(COMPUTER); break; } } void Sort(Store s) { char c; Genre result; do c = GetAChar("Enter Genre - (F)iction, (M)ystery, (S)ci-Fi, or (C)omputer: "); while ((c != 'A') &amp;&amp; (c != 'T')); s.Sort(c); } void Intro(Store s) { double amount; cout &lt;&lt; "*** Welcome to Bookstore Inventory Manager ***\n" &lt;&lt; "Please input the starting money in the cash register: "; /* cin &gt;&gt; amount; s.SetCashRegister(amount);*/ } int main() { Store mainStore;// Create and initialize a Store. Intro(mainStore);//Display intro &amp; set Cash Regsiter ShowMenu();// Display the menu. /*mainStore.Insert("A Clockwork Orange", "Anthony Burgess", SCIFI, 30.25); mainStore.Insert("X-Factor", "Anthony Burgess", SCIFI, 30.25);*/ char command;// menu command entered by user do { command = GetCommand();// Retrieve a command. switch (command) { case 'A': Add(mainStore); break; case 'F': Find(); break; case 'S': Sell(); break; case 'D': mainStore.DisplayStore(); break; case 'G': ViewGenre(mainStore); break; case 'O': Sort(mainStore); break; case 'M': ShowMenu(); break; case 'X': break; } } while ((command != 'X')); return 0; } </code></pre> <p>Please, any and all help you can offer is amazing. Thank you.</p>
7,935,879
3
5
null
2011-10-28 22:39:54.53 UTC
2
2011-10-28 23:27:12.597 UTC
null
null
null
null
871,111
null
1
10
c++|input|cin
38,445
<p>Welcome to the exciting world of C++!</p> <p>Short answer: you're passing Store as a value. All your menu functions should take a Store&amp; or Store* instead.</p> <p>When you're passing Store as a value then an implicit copy is done (so the mainStore variable is never actually modified). When you return from the function the Store::~Store is called to clean up the copied data. This frees mainStore.bookList without changing the actual pointer value.</p> <p>Further menu manipulation will corrupt memory and do many double frees.</p> <p>HINT: If you're on linux you can run your program under valgrind and it will point out most simple memory errors.</p>
11,523,765
How well does the Android NFC API support Mifare Desfire?
<p>I'm likely to be working on a project where existing Desfire cards (used to access paid services) will be replaced with an NFC-capable mobile device. Can anyone point me to any resources to help me understand what's involved in a) replicating a Desfire card's data onto a mobile device so it can take the place of a card, and b) for the app to deliver NFC data in order to present to the reader as if it were a card. All relevant keys and access will be provided by the card issuer (if the project goes ahead) but I'm keen to understand the process in advance.</p> <p>I also need to understand how well the Android NFC API supports Desfire, because as far as I can see it only properly support Classic. <a href="http://developer.android.com/reference/android/nfc/tech/package-summary.html" rel="noreferrer">http://developer.android.com/reference/android/nfc/tech/package-summary.html</a></p>
11,524,507
4
0
null
2012-07-17 13:40:52.857 UTC
16
2015-04-08 16:18:14.673 UTC
2012-07-17 14:36:52.547 UTC
null
1,202,968
null
477,415
null
1
8
android|nfc|mifare
23,520
<p>MIFARE DESFire is ISO 14443-4 compliant. Support in Android for ISO 14443-4 (and therefore MIFARE DESFire) is done by the <a href="http://developer.android.com/reference/android/nfc/tech/IsoDep.html"><code>IsoDep</code></a> class. You can send any DESFire command using the <code>transceive()</code> method of that class.</p> <p>Besides that, DESFire can be configured to be NFC Forum type 4 Tag compliant. In which case Android will read out automatically any NDEF messages from the tag and dispatch it in an intent. So you can make your app start automatically when a specific tag is scanned. (Android can also format a DESFire chip to contain NDEF and write NDEF data to it.)</p> <p>Replacing a DESFire card by a mobile NFC device is another matter. Card emulation on currently available Android devices is done by an embedded Secure Element connected to the NFC chip. An Android app cannot emulate a card (there is also no API for this) and the Secure Element cannot emulate a DESFire chip. Furthermore, there is no open API to access the Secure Element from an app.</p> <p>The only way an Android NFC app can communicate via NFC to another device (that is not a card) is using <a href="http://developer.android.com/guide/topics/connectivity/nfc/nfc.html#p2p">Android Beam</a>. This is, however, a different protocol than that used between card and reader.</p>
11,592,015
Support for target-densitydpi is removed from WebKit
<p>According to this <a href="https://bugs.webkit.org/show_bug.cgi?id=88047">https://bugs.webkit.org/show_bug.cgi?id=88047</a> WebKit dropped the support for target-densitydpi from viewport params. Unfortunately, the bug description states neither the motivation for the change, nor the workaround. </p> <p>Certain web-pages that wanted to prevent scaling on mobile devices had the following declaration of the viewport:</p> <pre><code>&lt;meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi"/&gt; </code></pre> <p>Now this code outputs an error in Chrome (tested with 21.0.1180.49 beta-m). Please advice what is the supposed way to make a web-page without the error messages and retain the same behavior as before with target-densitydpi=device-dpi"</p>
13,364,025
4
0
null
2012-07-21 12:04:58.34 UTC
21
2022-06-09 23:31:54.553 UTC
null
null
null
null
244,888
null
1
29
google-chrome|webkit
51,095
<p>The webkit-dev mailing list thread <a href="http://lists.webkit.org/pipermail/webkit-dev/2012-May/020847.html" rel="nofollow noreferrer">http://lists.webkit.org/pipermail/webkit-dev/2012-May/020847.html</a> contains a discussion (or at least the background) of the feature removal.</p> <p>In short, WebKit had a few means of scaling the page when rendered on a device, and this was highly confusing (even more so given that each platform relied on its own approach to this.)</p> <p><strong>UPDATE</strong>:</p> <p>According to a comment on the said thread by Adam Barth, the mentioned patch author,</p> <blockquote> <p>There's some concern that target-densitydpi is used by some apps that are bundled with Android, but folks appear willing to deprecate the feature and to migrate those apps to using other mechanisms, such as <strong>responsive images</strong> and <strong>CSS device units</strong>.</p> </blockquote> <p>As you can see, responsive images and CSS device units appear to be the recommended "workarounds" for what the <code>target-densitydpi</code> attribute provided. Also, another comment on the same thread mentioned the fact that even with this attribute in place, web developers would have to reimplement the same page in another way, for browser environments that do not support the attribute.</p> <p>I believe the recently introduced <a href="http://trac.webkit.org/wiki/LayoutUnit" rel="nofollow noreferrer">subpixel layout</a> will become another means of mitigating the attribute removal issue.</p> <p><strong>UPDATE 2</strong></p> <p><a href="http://petelepage.com/blog/2013/02/viewport-target-densitydpi-support-is-being-deprecated" rel="nofollow noreferrer">This blog post</a> suggests an alternative way to laying out your page for Android Chrome. There is NO workaround that will automagically let you "retain the same behavior" of your pages. You just have to re-architecture them a bit.</p>
11,475,885
python .replace() regex
<p>I am trying to do a grab everything after the <code>'&lt;/html&gt;'</code> tag and delete it, but my code doesn't seem to be doing anything. Does <code>.replace()</code> not support regex?</p> <pre><code>z.write(article.replace('&lt;/html&gt;.+', '&lt;/html&gt;')) </code></pre>
11,475,905
4
4
null
2012-07-13 18:03:50.237 UTC
53
2021-01-03 17:08:41.473 UTC
2021-01-03 17:08:41.473 UTC
null
4,100,225
null
1,442,957
null
1
409
python|regex
715,021
<p>No. Regular expressions in Python are handled by the <a href="http://docs.python.org/library/re.html" rel="noreferrer"><code>re</code></a> module.</p> <pre><code>article = re.sub(r'(?is)&lt;/html&gt;.+', '&lt;/html&gt;', article) </code></pre> <p>In general:</p> <pre><code>text_after = re.sub(regex_search_term, regex_replacement, text_before) </code></pre>
20,268,477
IIS Express - increase memory limit
<p>I have a VS project in .NET MVC5 which loads an external dll file that uses a lot of memory. In average it uses from 500-1000MB memory.</p> <p>Now when I try to debug my project with default IIS Express server I almost always get OutOfMemory exception.</p> <p>I know that there is a /3gb flag for normal IIS but what about IIS Express. Are there any settings so I can enable this or is there any other solution to this problem except of installing a full IIS on development PC? </p> <p>PS: Developer PC has Windows 8.1 64x and Visual Studio 2013.</p>
35,814,763
2
6
null
2013-11-28 14:21:09.563 UTC
5
2019-10-26 12:23:28.583 UTC
2019-10-26 12:23:28.583 UTC
null
2,581,562
null
310,080
null
1
38
c#|asp.net|visual-studio|iis|iis-express
18,120
<p>Go to Visual Studio - Tools - Options Menu</p> <p>Choose: - Projects and Solutions, then Web Projects</p> <p>tick the checkbox: "User the 64 bit version of IIS Express for web sites and projects"</p> <p>No Registry edit necessary.</p>
20,354,083
EF6 and multiple configurations (SQL Server and SQL Server Compact)
<p><strong>Update:</strong> Problem solved, see end of this question.</p> <p><strong>The problem</strong>:</p> <p>We are trying to use Entity Framework 6 and code-based configuration in a scenario were we have use both a SQL Server and SQL Server CE in the same <code>AppDomain</code>.</p> <p>This quite simple scenario seems not to be supported "by design". From the EF team:</p> <blockquote> <p>Note: We do not support having multiple configuration classes used in the same AppDomain. If you use this attribute to set different configuration classes for two contexts an exception will be thrown.</p> </blockquote> <p>More information here: <a href="http://entityframework.codeplex.com/wikipage?title=Code-based%20Configuration" rel="noreferrer">Code-based Configuration (Codeplex)</a></p> <p><strong>The question</strong>:</p> <p>How do we move forward from here? Any help would be greatly appreciated! Is there a more flexible way to connect a configuration to a context instead of an <code>AppDomain</code>?</p> <p>(Our context classes are located in different assemblies. We have tried the <code>DbConfigurationType</code> attribute but the problem is EF itself)</p> <p>Configuration files:</p> <p>Configuration for normal SQL server</p> <pre><code>public class EfConfiguration : DbConfiguration { public EfConfiguration() { SetProviderServices( SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance); SetDefaultConnectionFactory(new SqlConnectionFactory()); } } </code></pre> <p>Configuration for SQL Server Compact Edition</p> <pre><code>public class EfCeConfiguration : DbConfiguration { public EfCeConfiguration() { SetProviderServices( SqlCeProviderServices.ProviderInvariantName, SqlCeProviderServices.Instance); SetDefaultConnectionFactory( new SqlCeConnectionFactory(SqlCeProviderServices.ProviderInvariantName)); } } </code></pre> <p><strong>UPDATE:</strong></p> <p>The error which we get is:</p> <blockquote> <p>System.TypeInitializationException : The type initializer for 'MyProject.Repositories.Base.DataContext' threw an exception. ----> System.InvalidOperationException : An instance of 'EfCeConfiguration' was set but this type was not discovered in the same assembly as the 'DataContext' context. Either put the DbConfiguration type in the same assembly as the DbContext type, use DbConfigurationTypeAttribute on the DbContext type to specify the DbConfiguration type, or set the DbConfiguration type in the config file. See <a href="http://go.microsoft.com/fwlink/?LinkId=260883" rel="noreferrer">http://go.microsoft.com/fwlink/?LinkId=260883</a> for more information.</p> </blockquote> <p><strong>UPDATE 2, the solution</strong> As described above, we can only have one configuration. This is a problem since Sql and SqlCe uses different providers. If we use "SetDefaultConnectionFactory" to fit one type of database, the other will fail.</p> <p>Instead, supply the connection into the context as described in the post marked as answer below. Once you always initialize the context with a connection as opposed to a connectionstring you are good to go. You can remove the SetDefaultConnectionFactory call from the configuration. We're using only the code below for configuring the SqlCe Context and no configuration for the Sql Context.</p> <pre><code> public class CommonEfConfiguration : DbConfiguration { public CommonEfConfiguration() { // EF does not know if the ce provider by default, // therefore it is required to be informed about it. // The connection factories are not necessary since the connection // is always created in the UnitOfWork classes SetProviderServices(SqlCeProviderServices.ProviderInvariantName, SqlCeProviderServices.Instance); } } </code></pre>
20,354,462
3
10
null
2013-12-03 14:39:20.04 UTC
11
2017-03-21 16:31:45.55 UTC
2013-12-03 17:14:18.073 UTC
null
259,205
null
259,205
null
1
23
c#|entity-framework|configuration|entity-framework-6
21,305
<p>EDIT: based On Error details: Did you already try tell EF where the config class is found?</p> <pre><code>[DbConfigurationType("MyNamespace.MyDbConfiguration, MyAssemblyFullyQualifiedName")] public class MyContextContext : DbContext { } </code></pre> <p>If that cant be made work, then see alternative</p> <p>Use the Context with constructor DbConnection </p> <pre><code>public class MYDbContext : DbContext { // MIgration parameterless constructor is managed in MyMigrationsContextFactory public MyDbContext(string connectionName) : base(connectionName) { } // no this public MYDbContext(DbConnection dbConnection, bool contextOwnsConnection) // THIS ONE : base(dbConnection, contextOwnsConnection) { } </code></pre> <p>you then need a "DBConnection" connection for each provider. For SQL server</p> <pre><code> public DbConnection GetSqlConn4DbName(string dataSource, string dbName) { var sqlConnStringBuilder = new SqlConnectionStringBuilder(); sqlConnStringBuilder.DataSource = String.IsNullOrEmpty(dataSource) ? DefaultDataSource : dataSource; sqlConnStringBuilder.IntegratedSecurity = true; sqlConnStringBuilder.MultipleActiveResultSets = true; var sqlConnFact = new SqlConnectionFactory(sqlConnStringBuilder.ConnectionString); var sqlConn = sqlConnFact.CreateConnection(dbName); return sqlConn; } </code></pre> <p>repeat for SqlCe factory, it can also generate a DBConnection <a href="http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.sqlceconnectionfactory.createconnection%28v=vs.113%29.aspx" rel="noreferrer">SqlCe connection factor create connection </a></p>
61,306,802
Lombok getter/setter vs Java 14 record
<p>I love project <a href="https://projectlombok.org/" rel="noreferrer">Lombok</a> but in these days I'm reading and trying some of the new features of java 14.</p> <p>Inside the new capability, there is the <a href="https://openjdk.java.net/jeps/359" rel="noreferrer">record</a> keyword that allows creating a class with already built-in the following functionality: constructor, private final fields, accessors, equals/hashCode, getters, toString methods.</p> <p>Now my question is: is better to rely on the feature of Lombok or should we start using the record functionality:</p> <p>Is better to use this:</p> <pre class="lang-java prettyprint-override"><code>record Person (String name, String surname) {} </code></pre> <p>or that:</p> <pre class="lang-java prettyprint-override"><code>@AllArgsConstructor @ToString @EqualsAndHashCode public class Person { @Getter private int name; @Getter private int surname; } </code></pre> <p>What are the pros and cons of the both approach?</p>
61,325,018
6
4
null
2020-04-19 15:20:51.567 UTC
7
2022-02-14 15:25:40.49 UTC
2021-07-03 12:10:04.267 UTC
null
5,945,360
null
5,945,360
null
1
61
java|getter|lombok|java-14|java-record
16,203
<p>Lombok, and the <code>record</code> feature of the Java language, are different tools for different things. There is some superficial overlap, but don't let that distract you.</p> <p>Lombok is largely about <em>syntactic</em> convenience; it is a macro-processor pre-loaded with some known useful patterns of code. It doesn't confer any semantics; it just automates the patterns, according to some knobs you set in the code with annotations. Lombok is purely about the convenience of implementing data-carrying classes. </p> <p>Records are a <em>semantic</em> feature; they are <em>nominal tuples</em>. By making a semantic declaration that <code>Point</code> <em>is</em> a tuple of <code>(int x, int y)</code>, the compiler can derive its representation, as well as construction, declaration, equality, hashing, and string representation protocols, from this state description. Because they carry semantics, readers and frameworks can also reason with higher confidence about the API of records. (This may also be syntactically convenient; if so, that's great.)</p>
3,754,180
adding a column description
<p>Does anyone know how to add a description to a SQL Server column by running a script? I know you can add a description when you create the column using SQL Server Management Studio.</p> <p>How can I script this so when my SQL scripts create the column, a description for the column is also added?</p>
3,754,214
4
2
null
2010-09-20 18:11:52.923 UTC
13
2020-06-17 12:59:01.07 UTC
2010-09-20 18:35:47.353 UTC
null
23,199
null
444,443
null
1
59
sql|sql-server|sql-server-2005
70,253
<p>I'd say you will probably want to do it using the <a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-addextendedproperty-transact-sql?view=sql-server-ver15" rel="noreferrer">sp_addextendedproperty</a> stored proc.</p> <p>Microsoft has some good documentation on it.</p> <p>Try this:</p> <pre><code>EXEC sp_addextendedproperty @name = N'MS_Description', @value = 'Hey, here is my description!', @level0type = N'Schema', @level0name = 'yourschema', @level1type = N'Table', @level1name = 'YourTable', @level2type = N'Column', @level2name = 'yourColumn'; GO </code></pre>
3,242,873
Grep for literal strings
<p>I'm after a grep-type tool to search for purely literal strings. I'm looking for the occurrence of a line of a log file, as part of a line in a seperate log file. The search text can contain all sorts of regex special characters, e.g., <code>[]().*^$-\</code>.</p> <p>Is there a Unix search utility which would not use regex, but just search for literal occurrences of a string?</p>
3,242,906
5
1
null
2010-07-14 02:01:29.43 UTC
14
2016-03-09 11:14:17.867 UTC
2010-07-14 02:23:35.633 UTC
null
14,860
null
26,633
null
1
122
unix|grep
59,203
<p>You can use grep for that, with the -F option.</p> <pre><code>-F, --fixed-strings PATTERN is a set of newline-separated fixed strings </code></pre>
3,877,907
time format in SQL Server
<p>Does anyone know how can I format a select statement datetime value to only display time in SQL Server?</p> <p>example:</p> <pre><code>Table cuatomer id name datetime 1 Alvin 2010-10-15 15:12:54:00 2 Ken 2010-10-08 09:23:56:00 </code></pre> <p>When I select the table I like the result will display as below</p> <pre><code>id name time 1 Alvin 3:12PM 2 Ken 9:23AM </code></pre> <p>Any way that I can do it in mssql?</p>
3,877,918
7
1
null
2010-10-07 00:36:02.843 UTC
null
2020-04-12 12:01:15.28 UTC
2010-10-07 01:41:35.43 UTC
null
334,849
null
52,745
null
1
12
sql-server|tsql|time
78,301
<p>You can use a combination of CONVERT, RIGHT and TRIM to get the desired result:</p> <pre><code>SELECT ltrim(right(convert(varchar(25), getdate(), 100), 7)) </code></pre> <p>The <code>100</code> you see in the function specifies the date format <code>mon dd yyyy hh:miAM (or PM)</code>, and from there we just grab the right characters.</p> <p>You can see more about converting datetimes <a href="http://msdn.microsoft.com/en-us/library/ms187928.aspx" rel="noreferrer">here</a>.</p>
3,998,483
Objective-C Category Causing unrecognized selector
<p>My project has a <code>UIImage</code> category function that I want to call from another class. I properly import the header file for the image category and I get the project to compile with no warning.</p> <p>The problem is that when I call the <code>UIImage</code> category function I seen an unrecognized selector error with a <code>NSInvalidArgumentException</code>. Why am I seeing this if I've properly linked everything?</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface UIImage (DRShare) + (UIImage*) imageNamed:(NSString*)name; @end @implementation UIImage (DRShare) + (UIImage*) imageNamedDR:(NSString*)name{ CGFloat s = 1.0f; if([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){ s = [[UIScreen mainScreen] scale]; } NSString *path = [NSString stringWithFormat:@"%@%@%@.png",kImagesPath,name,s &gt; 1 ? @"@2x":@""]; return [UIImage imageWithContentsOfFile:DRBUNDLE(path)]; } @end </code></pre> <p>file that calls it:</p> <pre><code> backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamedDR:@"Share Popup Background"]]; </code></pre> <p>exception raised:</p> <pre><code>2010-10-22 11:51:02.880 Stuff[11432:207] +[UIImage imageNamedDR:]: unrecognized selector sent to class 0x1f8e938 2010-10-22 11:51:02.883 Stuff[11432:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[UIImage imageNamedDR:]: unrecognized selector sent to class 0x1f8e938' *** Call stack at first throw: ( 0 CoreFoundation 0x02e65b99 __exceptionPreprocess + 185 1 libobjc.A.dylib 0x02fb540e objc_exception_throw + 47 2 CoreFoundation 0x02e6776b +[NSObject(NSObject) doesNotRecognizeSelector:] + 187 3 CoreFoundation 0x02dd72b6 ___forwarding___ + 966 4 CoreFoundation 0x02dd6e72 _CF_forwarding_prep_0 + 50 5 TapTapShare 0x0001291c -[DRShareViewController backgroundView] + 127 6 TapTapShare 0x00012343 -[DRShareViewController loadView] + 639 7 UIKit 0x0044f54f -[UIViewController view] + 56 8 UIKit 0x0044d9f4 -[UIViewController contentScrollView] + 42 9 UIKit 0x0045d7e2 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 48 10 UIKit 0x0045bea3 -[UINavigationController _layoutViewController:] + 43 11 UIKit 0x0045d12d -[UINavigationController _startTransition:fromViewController:toViewController:] + 524 12 UIKit 0x00457ccd -[UINavigationController _startDeferredTransitionIfNeeded] + 266 13 UIKit 0x00574b55 -[UILayoutContainerView layoutSubviews] + 226 14 QuartzCore 0x02616481 -[CALayer layoutSublayers] + 177 15 QuartzCore 0x026161b1 CALayerLayoutIfNeeded + 220 16 QuartzCore 0x026160bd -[CALayer layoutIfNeeded] + 111 </code></pre>
3,998,700
8
5
null
2010-10-22 15:41:05.453 UTC
15
2021-08-09 08:20:05.417 UTC
2017-08-15 10:45:44.607 UTC
null
3,908,884
null
157,894
null
1
69
iphone|objective-c|cocoa|categories
26,862
<p>A couple possibilities:</p> <ol> <li>You did not link <code>UIImage+TTShare.m</code> into your target. So while you have the header, you're not compiling the implementation.</li> <li>If this is part of a static library, you need to add <code>-all_load</code> to the <strong>Other Linker Flags</strong> build setting for the app linking against the library.</li> </ol>
3,599,413
Is there a more elegant way to add nullable ints?
<p>I need to add numerous variables of type nullable int. I used the null coalescing operator to get it down to one variable per line, but I have a feeling there is a more concise way to do this, e.g. can't I chain these statements together somehow, I've seen that before in other code.</p> <pre><code>using System; namespace TestNullInts { class Program { static void Main(string[] args) { int? sum1 = 1; int? sum2 = null; int? sum3 = 3; //int total = sum1 + sum2 + sum3; //int total = sum1.Value + sum2.Value + sum3.Value; int total = 0; total = total + sum1 ?? total; total = total + sum2 ?? total; total = total + sum3 ?? total; Console.WriteLine(total); Console.ReadLine(); } } } </code></pre>
3,599,500
9
1
null
2010-08-30 10:06:03.337 UTC
2
2020-11-18 21:17:04.217 UTC
null
null
null
null
4,639
null
1
43
c#|nullable|null-coalescing-operator
22,141
<pre><code>var nums = new int?[] {1, null, 3}; var total = nums.Sum(); </code></pre> <p>This relies on the <a href="http://msdn.microsoft.com/en-us/library/bb156065.aspx" rel="noreferrer"><code>IEnumerable&lt;Nullable&lt;Int32&gt;&gt;</code>overload </a> of the <a href="http://msdn.microsoft.com/en-us/library/bb345537.aspx" rel="noreferrer"><code>Enumerable.Sum</code></a> Method, which behaves as you would expect.</p> <p>If you have a default-value that is not equal to zero, you can do:</p> <pre><code>var total = nums.Sum(i =&gt; i.GetValueOrDefault(myDefaultValue)); </code></pre> <p>or the shorthand: </p> <p><code>var total = nums.Sum(i =&gt; i ?? myDefaultValue);</code></p>
3,814,145
How can I declare a two dimensional string array?
<pre><code>string[][] Tablero = new string[3][3]; </code></pre> <p>I need to have a 3x3 array arrangement to save information to. How do I declare this in C#?</p>
3,814,164
12
3
null
2010-09-28 15:05:57.37 UTC
10
2021-11-12 15:45:56.003 UTC
2019-10-03 04:29:27.37 UTC
user12031933
null
delete
null
null
1
85
c#|arrays|multidimensional-array|jagged-arrays|array-initialization
268,742
<pre><code>string[,] Tablero = new string[3,3]; </code></pre> <p>You can also instantiate it in the same line with array initializer syntax as follows:</p> <pre><code>string[,] Tablero = new string[3, 3] {{"a","b","c"}, {"d","e","f"}, {"g","h","i"} }; </code></pre>
8,332,222
How to programmatically add a Drop down list in asp.net with specific pre-selected item
<p>I've worked out how to create a DropDownList using the following code:</p> <pre><code>&lt;select id="salesPersonDropList" runat="server"&gt;&lt;/select&gt; </code></pre> <p>In my .aspx page, then my code behind loops through database output running:</p> <pre><code>Dim newListItem As ListItem newListItem = New ListItem("Title", "Value") salesPersonDropList.Items.Add(newListItem ) </code></pre> <p>What I can't figure out is how to programatically set which of the List Items created is the one to be pre-selected in the rendered DropDownList, ie, how to create what I'd write in HTML as:</p> <pre><code>&lt;select&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option selected value="2"&gt;2&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Based on database output. As the code behind loops through the database output it should compare the output to a session variable and if they values match, the ListItem should be the item selected in the rendered DropDown.</p>
8,332,283
4
0
null
2011-11-30 20:03:01.423 UTC
2
2021-06-23 15:25:04.35 UTC
null
null
null
null
956,482
null
1
5
asp.net|vb.net|drop-down-menu
61,397
<p>Set your <code>Selected</code> property of the <code>ListItem</code> to true:</p> <pre><code>Dim newListItem As ListItem newListItem = New ListItem("Title", "Value") newListItem.Selected = True salesPersonDropList.Items.Add(newListItem ) </code></pre>
7,767,427
How to compare hex values using C?
<p>I am working with hex values. Until now I know how to print hex values and also precision thing. Now I want to compare the hex values. For example I am reading data from a file into a char buffer. Now I want to compare the hex value of data in the buffer. Is there anything like this?</p> <pre><code>if hex(buffer[i]) &gt; 0X3F then //do somthing </code></pre> <p>How can I do this?</p>
7,767,450
5
0
null
2011-10-14 12:16:16.743 UTC
1
2018-01-17 00:41:49.623 UTC
2011-10-14 13:05:40.903 UTC
null
287,954
null
621,510
null
1
8
c|hex
49,748
<p>You're nearly there:</p> <pre><code>if (buffer[i] &gt; 0x3f) { // do something } </code></pre> <p>Note that there is no need to "convert" anything to hex - you can just compare character or integer values directly, since a hex constant such as 0x3f is just another way of representing an integer value. 0x3f == 63 (decimal) == ASCII '?'.</p>
7,976,646
PowerShell: Store Entire Text File Contents in Variable
<p>I'd like to use PowerShell to store the <em>entire</em> contents of a text file (including the trailing blank line that may or may not exist) in a variable. I'd also like to know the total number of lines in the text file. What's the most efficient way to do this?</p>
7,976,784
5
0
null
2011-11-02 06:42:20.37 UTC
18
2016-04-18 22:17:31.79 UTC
2016-01-08 00:57:11.707 UTC
null
503,969
null
937,084
null
1
148
powershell
217,085
<p>To get the entire contents of a file:</p> <pre><code>$content = [IO.File]::ReadAllText(".\test.txt") </code></pre> <p>Number of lines:</p> <pre><code>([IO.File]::ReadAllLines(".\test.txt")).length </code></pre> <p>or</p> <pre><code>(gc .\test.ps1).length </code></pre> <p>Sort of hackish to include trailing empty line:</p> <pre><code>[io.file]::ReadAllText(".\desktop\git-python\test.ps1").split("`n").count </code></pre>
8,101,532
Android: Set margins in a FrameLayout programmatically- not working
<p>here is the code-</p> <pre><code>FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) searchPin.getLayoutParams(); params.setMargins(135, 176, 0, 0); //params.leftMargin = 135; // also not worked //params.topMargin = 376; searchPin.setLayoutParams(params); </code></pre> <p>Where ever, from xml its working- </p> <pre><code>android:layout_marginLeft="135dp" </code></pre> <p>what can be the reason? am i missing something!</p> <p>-thnx</p>
11,348,168
6
1
null
2011-11-12 00:32:56.8 UTC
4
2014-01-21 13:42:55.86 UTC
null
null
null
null
515,976
null
1
20
android|android-layout|android-framelayout
45,833
<p>Try this:</p> <pre><code>params.gravity = Gravity.TOP; </code></pre>
8,018,118
Cross-origin image load denied with three.js in chrome
<p>Trying to add material in <code>THREE.js</code> like this</p> <pre><code>var materialWall = new materialClass( { color: 0xffffff, map: THREE.ImageUtils.loadTexture( 'images/a.png' ) } ); </code></pre> <p>It works fine in Chrome, IE, FF, until 3 days ago, after Chrome updated itself to the latest dev version 17.</p> <p>Chrome 17 just doesn't load the image and complains the following</p> <pre><code>Cross-origin image load denied by Cross-Origin Resource Sharing policy. </code></pre> <p>That's insane since the image is clearly in the same domain, so is this an issue of chrome or THREE.js or something else?</p>
8,019,408
7
0
null
2011-11-05 04:04:57.88 UTC
3
2018-05-24 07:47:53.297 UTC
2018-05-24 07:47:53.297 UTC
null
991,295
null
991,295
null
1
20
javascript|google-chrome|cross-domain|three.js
45,283
<p><a href="https://github.com/mrdoob/three.js/issues/687" rel="nofollow noreferrer">https://github.com/mrdoob/three.js/issues/687</a> refers to an issue on three.js' GitHub, which has good list of workarounds, including <a href="https://github.com/mrdoob/three.js/wiki/How-to-run-things-locally" rel="nofollow noreferrer">a link to a wiki page describing how to run locally</a>. There are also some other workarounds in the thread, including adding the following to your scripts:</p> <pre><code>THREE.ImageUtils.crossOrigin = ""; </code></pre> <p>Or, adding CORS headers so that they are specifically allowed. </p> <p><sup>Note that most of this information was added from the already existing link to the issue, which the original author of this answer did not include.</sup></p>
8,100,622
Finding even or odd ID values
<p>I was working on a query today which required me to use the following to find all odd number ID values</p> <pre><code>(ID % 2) &lt;&gt; 0 </code></pre> <p>Can anyone tell me what this is doing? It worked, which is great, but I'd like to know why.</p>
8,100,649
8
1
null
2011-11-11 22:15:09.243 UTC
3
2018-02-21 11:31:42.347 UTC
null
null
null
null
567,269
null
1
74
sql|sql-server-2008
223,820
<p><code>ID % 2</code> is checking what the remainder is if you divide ID by 2. If you divide an even number by 2 it will always have a remainder of 0. Any other number (odd) will result in a non-zero value. Which is what is checking for.</p>
7,782,080
How to print a two dimensional array?
<p>I have a [20][20] two dimensional array that I've manipulated. In a few words I am doing a turtle project with user inputting instructions like pen up = 0 and pen down = 1. When the pen is down the individual array location, for instance [3][4] is marked with a &quot;1&quot;.</p> <p>The last step of my program is to print out the 20/20 array. I can't figure out how to print it and I need to replace the &quot;1&quot; with an &quot;X&quot;. The print command is actually a method inside a class that a parent program will call. I know I have to use a loop.</p> <pre><code>public void printGrid() { System.out.println... } </code></pre>
7,782,111
10
0
null
2011-10-16 03:00:56 UTC
9
2020-08-17 02:19:55.577 UTC
2020-06-23 16:46:36.86 UTC
null
7,910,454
null
997,462
null
1
25
java
170,979
<pre><code>public void printGrid() { for(int i = 0; i &lt; 20; i++) { for(int j = 0; j &lt; 20; j++) { System.out.printf("%5d ", a[i][j]); } System.out.println(); } } </code></pre> <p>And to replace</p> <pre><code>public void replaceGrid() { for (int i = 0; i &lt; 20; i++) { for (int j = 0; j &lt; 20; j++) { if (a[i][j] == 1) a[i][j] = x; } } } </code></pre> <p>And you can do this all in one go:</p> <pre><code>public void printAndReplaceGrid() { for(int i = 0; i &lt; 20; i++) { for(int j = 0; j &lt; 20; j++) { if (a[i][j] == 1) a[i][j] = x; System.out.printf("%5d ", a[i][j]); } System.out.println(); } } </code></pre>
4,122,040
How to make sphinx look for modules in virtualenv while building html?
<p>I want to build html docs using a virtualenv instead of the native environment on my machine. </p> <p>I've entered the virtualenv but when I run <code>make html</code> I get errors saying the module can't be imported - I <em>know</em> the errors are due to the module being unavailable in my native environment. How can I specify which environment should be used when searching for docs (eg the virtualenv)?</p>
4,249,730
3
0
null
2010-11-08 07:42:24.383 UTC
16
2013-08-19 21:41:43.23 UTC
2012-05-08 13:19:17.833 UTC
null
121,725
null
121,725
null
1
54
virtualenv|python-sphinx
10,060
<p>The problem here is that <code>make html</code> uses the <code>sphinx-build</code> command as a normal shell command, which explicitly specifies which Python interpreter to use in the first line of the file (ie. <code>#!/usr/bin/python</code>). If Python gets invoked in this way, it will not use your virtual environment.</p> <p>A quick and dirty way around this is by explicitly calling the <code>sphinx-build</code> Python script from an interpreter. In the <code>Makefile</code>, this can be achieved by changing <code>SPHINXBUILD</code> to the following:</p> <pre><code>SPHINXBUILD = python &lt;absolute_path_to_sphinx-build-file&gt;/sphinx-build </code></pre> <p>If you do not want to modify your <code>Makefile</code> you can also pass this parameter from the command line, as follows:</p> <pre><code>make html SPHINXBUILD='python &lt;path_to_sphinx&gt;/sphinx-build' </code></pre> <p>Now if you execute <code>make build</code> from within your VirtualEnv environment, it should use the Python interpreter from within your environment and you should see Sphinx finding all the goodies it requires.</p> <p>I am well aware that this is not a neat solution, as a <code>Makefile</code> like this should not assume any specific location for the <code>sphinx-build</code> file, so any suggestions for a more suitable solution are warmly welcomed.</p>
4,684,112
How do CDI and EJB compare? interact?
<p>I'm having a tough time understanding how the two interact and where the boundary between them lies. Do they overlap? Are there redundancies between them?</p> <p>I know there are annotations associated with both, but I haven't been able to find a complete list for both with brief descriptions. Not sure if this would help clear up how they differ or where they overlap.</p> <p>Really just confused. I (think I) understand EJB reasonably well, I guess I'm having a hard time understanding exactly what CDI brings to the table and how it supplants or enhances what EJB already offers. </p>
4,684,305
3
1
null
2011-01-13 19:03:35.083 UTC
82
2019-12-03 07:37:52.513 UTC
null
null
null
null
5,284
null
1
110
java|ejb|java-ee-6|cdi
45,443
<p><strong>CDI:</strong> it is about dependency injection. It means that you can inject interface implementation anywhere. This object can be anything, it can be not related to EJB. <a href="http://download.oracle.com/javaee/6/tutorial/doc/gjcxv.html" rel="noreferrer">Here</a> is an example of how to inject random generator using CDI. There is nothing about EJB. You are going to use CDI when you want to inject non-EJB services, different implementations or algorithms (so you don't need EJB there at all).<br /> <strong>EJB:</strong> you do understand, and probably you are confused by <code>@EJB</code> annotation - it allows you to inject implementation into your service or whatever. The main idea is that class, where you inject, should be managed by EJB container. Seems that CDI does understand what EJB is, so in Java EE 6 compliant server, in your servlet you can write both</p> <pre><code>@EJB EJBService ejbService; </code></pre> <p>and</p> <pre><code>@Inject EJBService ejbService; </code></pre> <p>that's what can make you confusing, but that's probably the only thing which is the bridge between EJB and CDI.</p> <p>When we are talking about CDI, you can inject other objects into CDI managed classes (they just should be created by CDI aware frameworks).</p> <p>What else CDI offers... For instance, you use Struts 2 as MVC framework (just example), and you are limited here, even using EJB 3.1 - you can't use <code>@EJB</code> annotation in Struts action, it is not managed by container. But when you add Struts2-CDI plugin, you can write there <code>@Inject</code> annotation for the same thing (so no more JNDI lookup needed). This way it enhances EJB power, but as I mentioned before, what you inject with CDI - it does not matter if it is related to EJB or not, and that's its power.</p> <p>PS. updated link to the example</p>
4,692,311
How do I create my own Scaffold Template in ASP.NET MVC 3?
<p>ASP.NET MVC provides the ability to select a 'Scaffold template' upon which a newly-created view will be based (Add View > Create a strongly-typed view > Scaffold template).</p> <p>Is it possible to create your own Scaffold Template? And if so, how?</p>
4,692,521
5
2
null
2011-01-14 14:53:12.303 UTC
10
2013-07-02 14:20:26.577 UTC
null
null
null
null
1,943
null
1
35
asp.net-mvc|asp.net-mvc-3
16,511
<p>ASP.NET MVC uses T4 templates. <a href="http://blogs.msdn.com/b/joecar/archive/2011/01/06/add-the-asp-net-mvc-3-code-templates-to-your-application-with-nuget.aspx" rel="noreferrer">Here's an overview</a>.</p> <p>Here are the steps:</p> <ol> <li>In the Package Manager Console type: <code>install-package mvc3codetemplatescsharp</code></li> <li>Accept all the warnings</li> <li>The <code>CodeTemplates</code> folder will be added to your project containing the templates</li> </ol> <p>From here you could either modify the existing templates or add new one.</p> <p>Or if you want to modify those globally you could to this in the <code>C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 3\CodeTemplates\</code> folder.</p>
4,315,111
How to do HTTP-request/call with JSON payload from command-line?
<p>What's the easiest way to do a JSON call from the command-line? I have a website that does a JSON call to retrieve additional data.</p> <p>The <strong>Request Payload</strong> as shown in Google Chrome looks like this:</p> <pre><code>{"version": "1.1", "method":"progr","id":2,"params":{"call":...} } </code></pre> <p>It's about doing the call from (preferably) linux command line and retrieving the JSON content, not about parsing the incoming JSON data.</p>
4,315,155
5
0
null
2010-11-30 15:01:01.46 UTC
10
2022-01-26 07:29:59.05 UTC
2010-12-01 09:00:32.91 UTC
null
26,387
null
26,387
null
1
61
linux|json|command-line|web-crawler
117,950
<p>Use curl, assuming the data is POST'ed, something like</p> <pre><code>curl -X POST http://example.com/some/path -d '{"version": "1.1", "method":"progr","id":2,"params":{"call":...} }' </code></pre> <p>If you're just retrieving the data with a GET , and don't need to send anything bar URL parameters, you'd just run <code>curl http://example.com/some/path</code></p>
4,425,681
How can I convert a VBScript to an executable (EXE) file?
<p>I'd looked around for information to convert a VBScript <code>(*.vbs)</code> to an executable and realised that most of the tools available are actually wrapping the script in the executable. Tried a few tools and it didn't worked as well as expected. I tried IExpress (in Windows XP) to create the Win32 self extraction cab file but it didn't invoke properly on Windows 7 machines.</p> <p>So I am looking for a way to compile the vbs into exe. I am trying to port my current script into VB Express 2008 but I have no prior knowledge of Visual Basic here. There are a lot of errors but I am still trying around.</p> <p>Can anyone please advice on how should I proceed from here? I mean, would a <strong>self extracting archive</strong> be the way to go instead of a <strong>standalone executable file</strong>? But say like Winzip I don't know how to make it run the script after extraction.</p> <p>Any ideas?</p>
4,426,499
6
2
null
2010-12-13 03:52:16.657 UTC
9
2018-03-10 09:05:17.723 UTC
2018-03-07 11:06:35.617 UTC
null
5,211,833
null
324,236
null
1
19
vbscript|executable|iexpress
122,327
<p><strong>There is no way to convert a VBScript (.vbs file) into an executable (.exe file) because VBScript is <em>not a compiled language</em>.</strong> The process of converting source code into native executable code is called <a href="http://en.wikipedia.org/wiki/Compiler" rel="noreferrer">"compilation"</a>, and it's not supported by <em>scripting</em> languages like VBScript.</p> <p>Certainly you can add your script to a self-extracting archive using something like WinZip, but all that will do is compress it. It's doubtful that the file size will shrink noticeably, and since it's a plain-text file to begin with, it's really not necessary to compress it at all. The only purpose of a <em>self-extracting</em> archive is that decompression software (like WinZip) is not required on the end user's computer to be able to <em>extract</em> or "decompress" the file. If it isn't compressed in the first place, this is a moot point.</p> <p>Alternatively, as you mentioned, there are ways to wrap VBScript code files in a standalone executable file, but these are just wrappers that automatically execute the script (in its current, uncompiled state) when the user double-clicks on the .exe file. I suppose that can have its benefits, but it doesn't sound like what you're looking for.</p> <p><strong>In order to truly convert your VBScript into an executable file, you're going to have to rewrite it in another language that can be <em>compiled</em>.</strong> <a href="http://en.wikipedia.org/wiki/Visual_Basic" rel="noreferrer">Visual Basic 6</a> (the latest version of VB, before the .NET Framework was introduced) is extremely similar in syntax to VBScript, but does support compiling to native code. If you move your VBScript code to VB 6, you can compile it into a native executable. Running the .exe file will require that the user has the <a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=BA9D7924-4122-44AF-8AB4-7C039D9BF629&amp;displaylang=en" rel="noreferrer">VB 6 Run-time libraries</a> installed, but they come built into most versions of Windows that are found now in the wild. </p> <p>Alternatively, you could go ahead and make the jump to <a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET" rel="noreferrer">Visual Basic .NET</a>, which remains <em>somewhat</em> similar in syntax to VB 6 and VBScript (although it won't be anywhere near a cut-and-paste migration). VB.NET programs will also compile to an .exe file, but they require the .NET Framework runtime to be installed on the user's computer. Fortunately, this has also become commonplace, and it can be easily redistributed if your users don't happen to have it. You mentioned going this route in your question (porting your current script in to VB Express 2008, which uses VB.NET), but that you were getting a lot of errors. That's what I mean about it being far from a cut-and-paste migration. There are some <em>huge</em> differences between VB 6/VBScript and VB.NET, despite some superficial syntactical similarities. If you want help migrating over your VBScript, you could post a question here on Stack Overflow. Ultimately, this is probably the best way to do what you want, but I can't promise you that it will be simple.</p>
4,321,456
'find -exec' a shell function in Linux
<p>Is there a way to get <code>find</code> to execute a function I define in the shell?</p> <p>For example:</p> <pre><code>dosomething () { echo &quot;Doing something with $1&quot; } find . -exec dosomething {} \; </code></pre> <p>The result of that is:</p> <pre><code>find: dosomething: No such file or directory </code></pre> <p>Is there a way to get <code>find</code>'s <code>-exec</code> to see <code>dosomething</code>?</p>
4,321,522
14
0
null
2010-12-01 05:25:34.68 UTC
58
2022-04-08 16:05:35.663 UTC
2021-04-19 15:53:32.567 UTC
null
63,550
null
303,896
null
1
241
linux|bash|shell|find|bsd
96,649
<p>Since only the shell knows how to run shell functions, you have to run a shell to run a function. You also need to mark your function for export with <code>export -f</code>, otherwise the subshell won't inherit them:</p> <pre><code>export -f dosomething find . -exec bash -c 'dosomething "$0"' {} \; </code></pre>
4,530,069
How do I get a value of datetime.today() in Python that is "timezone aware"?
<p>I am trying to subtract one date value from the value of <code>datetime.datetime.today()</code> to calculate how long ago something was. But it complains:</p> <pre class="lang-none prettyprint-override"><code>TypeError: can't subtract offset-naive and offset-aware datetimes </code></pre> <p>The return value from <code>datetime.datetime.today()</code> doesn't seem to be &quot;timezone aware&quot;, while my other date value is. How do I get a return value from <code>datetime.datetime.today()</code> that is timezone aware?</p> <p>The ideal solution would be for it to automatically know the timezone.</p> <p>Right now, it's giving me the time in local time, which happens to be PST, i.e. UTC - 8 hours. Worst case, is there a way I can manually enter a timezone value into the <code>datetime</code> object returned by <code>datetime.datetime.today()</code> and set it to UTC-8?</p>
4,530,166
19
5
null
2010-12-25 10:59:49.863 UTC
74
2022-04-27 00:31:47.04 UTC
2022-04-27 00:31:47.04 UTC
user17242583
null
null
323,874
null
1
439
python|datetime|date|timezone
508,329
<p>In the standard library, there is no cross-platform way to create aware timezones without creating your own timezone class. (<strong>Edit:</strong> Python 3.9 introduces <a href="https://docs.python.org/3/library/zoneinfo.html" rel="noreferrer"><code>zoneinfo</code></a> in the standard library which does provide this functionality.)</p> <p>On Windows, there's <code>win32timezone.utcnow()</code>, but that's part of pywin32. I would rather suggest to use the <a href="http://pytz.sourceforge.net/" rel="noreferrer">pytz library</a>, which has a constantly updated database of most timezones.</p> <p>Working with local timezones can be very tricky (see &quot;Further reading&quot; links below), so you may rather want to use UTC throughout your application, especially for arithmetic operations like calculating the difference between two time points.</p> <p>You can get the current date/time like so:</p> <pre><code>import pytz from datetime import datetime datetime.utcnow().replace(tzinfo=pytz.utc) </code></pre> <p>Mind that <code>datetime.today()</code> and <code>datetime.now()</code> return the <em>local</em> time, not the UTC time, so applying <code>.replace(tzinfo=pytz.utc)</code> to them would not be correct.</p> <p>Another nice way to do it is:</p> <pre><code>datetime.now(pytz.utc) </code></pre> <p>which is a bit shorter and does the same.</p> <hr /> <p>Further reading/watching why to prefer UTC in many cases:</p> <ul> <li><a href="https://pythonhosted.org/pytz/" rel="noreferrer">pytz documentation</a></li> <li><a href="http://web.archive.org/web/20160803154621/http://www.windward.net/blogs/every-developer-know-time/" rel="noreferrer">What Every Developer Should Know About Time</a> – development hints for many real-life use cases</li> <li><a href="https://www.youtube.com/watch?v=-5wpm-gesOY" rel="noreferrer">The Problem with Time &amp; Timezones - Computerphile</a> – funny, eye-opening explanation about the complexity of working with timezones (video)</li> </ul>
14,622,962
What is transaction.commit() in Hibernate?
<p>What does <strong>transaction.commit()</strong> do?</p> <pre><code>Account account = new Account(); account.setId(100); account = (Account) session.get(Account.class, account.getId()); System.out.println("Before Transaction: Balance = " + account.getBalance()); double preBal = account.getBalance(); account.setBalance(50000000); Transaction transaction = session.beginTransaction(); session.update(account); account = (Account) session.get(Account.class, account.getId()); System.out.println("After Transaction: Balance = " + account.getBalance()); // transaction.commit(); account = (Account) session.get(Account.class, account.getId()); System.out.println("Pev-Bal=" + preBal + " Curr-Bal=" + account.getBalance()); </code></pre> <p>This gives me result:</p> <pre><code>Hibernate: select account0_.id as id0_1_, account0_.balance as .......... Before Transaction: Balance = 300.0 After Transaction: Balance = 5.0E7 Pev-Bal=300.0 Curr-Bal=5.0E7 </code></pre> <p>But since I did not call <strong>transaction.commit()</strong> there was no change in Database.</p> <p>Does this means everything was done only on some instance/objects without really changing the Database?</p> <p>I am new to Hibernate, so please help me understand. I am using hibernate 4.</p> <p><strong>UPDATE:</strong> </p> <p>IF I call <strong>transaction.commit()</strong> then the result have this line</p> <pre><code>Hibernate: update account set balance=? where id=? </code></pre> <p>And Database also updated.</p> <p>Does this mean that without calling <strong>transaction.commit()</strong> everything was done only on instance level without really changing the Database?</p>
14,626,510
2
0
null
2013-01-31 09:58:06.563 UTC
7
2015-07-16 21:59:45.343 UTC
2013-01-31 10:25:36.007 UTC
null
1,597,838
null
1,597,838
null
1
10
java|mysql|database|hibernate
41,085
<p><strong>Commit</strong> will make the database commit. The changes to persistent object will be written to database. <strong>Flushing</strong> is the process of <em>synchronizing</em> the underlying persistent store with persistant state held in memory. ie. it will update or insert into your tables in the running transaction, but it <em>may</em> not commit those changes (this depends on your flush mode).</p> <p>When you have a persisted object and you change a value on it, it becomes dirty and hibernate needs to flush these changes to your persistence layer. It may do this automatically for you or you may need to do this manually, that depends on your flush mode(auto or manual) :)</p> <p>So in short: <strong>transaction.commit()</strong> does flush the session, but it also ends the unit of work.</p> <p>There is a similar reference to your problem <a href="https://stackoverflow.com/questions/3931162/will-hibernate-flush-my-updated-persistent-object-when-calling-session-closeu">here</a></p>
14,744,984
Jade/Pug if else condition usage
<p>I'm sending a date to a .jade file from my .js file using <code>Node.js</code>. When the <code>#{date}</code> field is <code>false</code>, it executes the else and print <code>man</code> as it's answer. What could be going wrong?</p> <pre><code>if #{date} == false | #{date} else | man </code></pre>
14,961,069
3
0
null
2013-02-07 06:27:14.553 UTC
5
2017-06-23 04:59:40.347 UTC
2017-06-04 13:21:55.293 UTC
null
1,053,103
null
2,049,614
null
1
18
node.js|pug
44,297
<p>If date is false, do you want to output the string 'man'? If yes, your if and else statements are the wrong way around...</p> <p>How about:</p> <pre><code>if date = date else | man </code></pre> <p>or even:</p> <pre><code>| #{date ? date : 'man'} </code></pre> <p>or simply:</p> <pre><code>| #{date || 'man'} </code></pre>
14,829,190
How to use markdown for maven project site?
<p>How to start with project documentation using maven and markdown markup language? Maven site default is APT, which is uncomfortable to learn just to do thing maven way. (Usually nobody in a team will start writing maven site documentation when they also need to learn one more markup language along the way.)</p> <p>Has anybody tried to use markdown (the same markup language as used on github) for Maven project site documentation? I see from <a href="http://maven.apache.org/doxia/references/index.html">Maven Doxia references</a> that it is possible. Any issues?</p> <p>I am new to maven site generation. I think markdown is better to start with, than others markup languages, that the team has not worked with.</p> <p>UPDATE. Succeeded. See answer below.</p>
14,831,412
2
3
null
2013-02-12 09:22:31.743 UTC
30
2021-05-07 13:10:00.293 UTC
2013-02-12 12:58:45.717 UTC
null
482,717
null
482,717
null
1
48
maven|markdown|maven-site-plugin
14,768
<p>Quote from <a href="http://maven.apache.org/doxia/references/index.html" rel="noreferrer">http://maven.apache.org/doxia/references/index.html</a></p> <p>Add this to <code>pom.xml</code></p> <pre><code> &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-site-plugin&lt;/artifactId&gt; &lt;version&gt;3.2&lt;/version&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.maven.doxia&lt;/groupId&gt; &lt;artifactId&gt;doxia-module-markdown&lt;/artifactId&gt; &lt;version&gt;1.3&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;/plugin&gt; </code></pre> <p>Then start adding pages under <code>src/site/markdown/</code> with <code>.md</code> extension. For every page add menu item like in sniplet below: </p> <pre><code> &lt;body&gt; &lt;!-- http://maven.apache.org/doxia/doxia-sitetools/doxia-decoration-model/decoration.html &lt;item collapse=.. ref=.. name=.. href="README" img=.. position=.. alt=.. border=.. width=.. height=.. target=.. title=.. &gt; --&gt; &lt;menu name="User guide"&gt; &lt;item href="README.html" name="README" /&gt; &lt;/menu&gt; &lt;menu ref="reports" inherit="bottom" /&gt; &lt;/body&gt; </code></pre> <p>Than use <code>mvn site</code> to generate site. Look at <code>target/site</code> to review results.</p> <p><code>mvn site:stage -DstagingDirectory=C:\TEMP\fullsite</code> to get multi-modular project site in one folder. </p> <p>Read more about <a href="http://maven.apache.org/plugins/maven-site-plugin/" rel="noreferrer">maven-site-plugin</a>.</p> <p>I recommend to use <a href="http://maven.apache.org/skins/maven-fluido-skin/" rel="noreferrer">maven-fluido-skin</a>. It is newest style, based on Twitter Bootstrap Add this to site.xml</p> <pre><code>&lt;project name="xxx"&gt; [...] &lt;skin&gt; &lt;groupId&gt;org.apache.maven.skins&lt;/groupId&gt; &lt;artifactId&gt;maven-fluido-skin&lt;/artifactId&gt; &lt;version&gt;1.3.0&lt;/version&gt; &lt;/skin&gt; [...] &lt;/project&gt; </code></pre> <p>See also <a href="https://github.com/winterstein/Eclipse-Markdown-Editor-Plugin" rel="noreferrer">https://github.com/winterstein/Eclipse-Markdown-Editor-Plugin</a></p>
14,492,138
Mime type for .txt files?
<p>I´m trying to share a <code>.txt</code> file with share intent. If I set "text/plain" as mime type, it reads the content like text not like text file, then the options given in the share menu are Whatsapp, Line, etc..</p> <p>Does anybody know how to configure the share intent so that the share options are only the programs that are able to send a <code>.txt</code> file (Gmail, Dropbox, etc.. but not Whatsapp..)? Thanks</p>
25,488,949
2
0
null
2013-01-24 00:55:23.563 UTC
7
2016-01-27 15:15:47.023 UTC
2016-01-27 15:15:47.023 UTC
null
1,736,451
null
1,736,451
null
1
86
android|text-files|share|mime-types
81,385
<p>You can try the specific mime:</p> <pre><code>text/plain </code></pre> <p>or, the more general text mime:</p> <pre><code>text/* </code></pre>
45,326,775
Dagger: IllegalArgumentException: No injector factory bound for Class
<p>I am new to Dagger 2. I have 2 Activities, I want to use injected ViewModel for both. Here is my <strong>ViewModuleFactory</strong> :</p> <pre><code>@Singleton public class ProductViewModelFactory implements ViewModelProvider.Factory { private final Map&lt;Class&lt;? extends ViewModel&gt;, Provider&lt;ViewModel&gt;&gt; creators; @Inject public ProductViewModelFactory(Map&lt;Class&lt;? extends ViewModel&gt;, Provider&lt;ViewModel&gt;&gt; creators) { this.creators = creators; } @SuppressWarnings("unchecked") @Override public &lt;T extends ViewModel&gt; T create(Class&lt;T&gt; modelClass) { Provider&lt;? extends ViewModel&gt; creator = creators.get(modelClass); if (creator == null) { for (Map.Entry&lt;Class&lt;? extends ViewModel&gt;, Provider&lt;ViewModel&gt;&gt; entry : creators.entrySet()) { if (modelClass.isAssignableFrom(entry.getKey())) { creator = entry.getValue(); break; } } } if (creator == null) { throw new IllegalArgumentException("unknown viewmodel class " + modelClass); } try { return (T) creator.get(); } catch (Exception e) { throw new RuntimeException(e); } } } </code></pre> <p>My <strong>ViewModelModule</strong>:</p> <pre><code>@Module abstract class ViewModelModule { @Binds @IntoMap @ViewModelKey(ProductListViewModel.class) abstract ViewModel bindProductListViewModel(ProductListViewModel listViewModel); @Binds @IntoMap @ViewModelKey(ProductDetailsViewModel.class) abstract ViewModel bindProductDetailsViewModel(ProductDetailsViewModel detailsViewModel); @Binds abstract ViewModelProvider.Factory bindViewModelFactory(ProductViewModelFactory factory); } </code></pre> <p>My <strong>ViewModelKey</strong> for mapping:</p> <pre><code>@Documented @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @MapKey @interface ViewModelKey { Class&lt;? extends ViewModel&gt; value(); } </code></pre> <p>My <strong>ActivityModule</strong> :</p> <pre><code>@Module public abstract class ActivityModule { abstract ProductListActivity contributeProductListActivity(); abstract ProductDetailsActivity contributeProductDetailsActivity(); } </code></pre> <p>My <strong>AppModule</strong>:</p> <pre><code>@Module class AppModule { @Provides @Singleton RedMartProductService provideRedMartProductService() { ........ } @Provides @Singleton ProductListRepository provideProductListRepository(ProductListRepository repository) { return repository; } @Provides @Singleton ProductDetailsRepository provideProductDetailsRepository(ProductDetailsRepository repository) { return repository; } } </code></pre> <p>My <strong>AppComponent</strong>:</p> <pre><code>@Singleton @Component(modules = {AndroidInjectionModule.class, ActivityModule.class, AppModule.class}) public interface AppComponent { @Component.Builder interface Builder { @BindsInstance Builder application(Application application); AppComponent build(); } void inject(MartApplication martApp); } </code></pre> <p>My <strong>Application</strong>:</p> <pre><code>public class MartApplication extends Application implements HasActivityInjector { @Inject DispatchingAndroidInjector&lt;Activity&gt; dispatchingAndroidInjector; @Override public void onCreate() { super.onCreate(); } @Override public DispatchingAndroidInjector&lt;Activity&gt; activityInjector() { return dispatchingAndroidInjector; } } </code></pre> <p>In <strong>Activity</strong>: </p> <pre><code>@Inject ViewModelProvider.Factory viewModelFactory; ....... AndroidInjection.inject(activity); // Throwing exception ListViewModel = ViewModelProviders.of(this, viewModelFactory).get(ProductListViewModel.class); </code></pre> <p>It is throwing an exception on inject: </p> <pre><code>java.lang.IllegalArgumentException: No injector factory bound for Class&lt;com.mymart.ui.ProductListActivity&gt; </code></pre> <p>Can anyone help me identify the problem in my code?</p> <p>.......................................................................</p> <p><strong>Edit</strong>: I tried with <code>ContributesAndroidInjector</code> as per @azizbekian, but it resulted following error on build: </p> <pre><code> error: [dagger.android.AndroidInjector.inject(T)] Found a dependency cycle: com.mymart.repository.ProductListRepository is injected at com.mymart.di.AppModule.provideProductListRepository(repository) com.mymart.repository.ProductListRepository is injected at com.mymart.viewmodel.ProductListViewModel.&lt;init&gt;(productListRepository) com.mymart.viewmodel.ProductListViewModel is injected at com.mymart.di.ViewModelModule.bindProductListViewModel(listViewModel) java.util.Map&lt;java.lang.Class&lt;? extends android.arch.lifecycle.ViewModel&gt;,javax.inject.Provider&lt;android.arch.lifecycle.ViewModel&gt;&gt; is injected at com.mymart.viewmodel.ProductViewModelFactory.&lt;init&gt;(creators) com.mymart.viewmodel.ProductViewModelFactory is injected at com.mymart.di.ViewModelModule.bindViewModelFactory(factory) android.arch.lifecycle.ViewModelProvider.Factory is injected at com.mymart.ui.ProductListActivity.viewModelFactory com.mymart.ui.ProductListActivity is injected at dagger.android.AndroidInjector.inject(arg0) </code></pre> <p><strong>Edit 2</strong> After all changes, I am facing again exception:</p> <pre><code>java.lang.RuntimeException: Unable to create application com.kaushik.myredmart.MartApplication: java.lang.IllegalStateException: com.kaushik.myredmart.di.AppModule must be set at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4710) at android.app.ActivityThread.-wrap1(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.IllegalStateException: com.kaushik.myredmart.di.AppModule must be set at com.kaushik.myredmart.di.DaggerAppComponent$Builder.build(DaggerAppComponent.java:180) at com.kaushik.myredmart.di.AppInjector.init(AppInjector.java:30) at com.kaushik.myredmart.MartApplication.onCreate(MartApplication.java:28) at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1013) at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4707) at android.app.ActivityThread.-wrap1(ActivityThread.java)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:148)  at android.app.ActivityThread.main(ActivityThread.java:5417)  at java.lang.reflect.Method.invoke(Native Method) </code></pre>
45,327,464
5
0
null
2017-07-26 12:17:47.753 UTC
6
2022-07-27 13:42:03.437 UTC
2017-07-26 20:05:07.653 UTC
null
525,004
null
525,004
null
1
71
android|dependency-injection|dagger-2|dagger
55,889
<p>I believe you have forgot to put <code>@ContributesAndroidInjector</code> annotation:</p> <pre> <code> @Module public abstract class ActivityModule { @ContributesAndroidInjector abstract ProductListActivity contributeProductListActivity(); @ContributesAndroidInjector abstract ProductDetailsActivity contributeProductDetailsActivity(); } </code> </pre> <p>And include <code>ViewModelModule</code> within <code>AppModule</code>:</p> <pre> <code> @Module(includes = ViewModelModule.class) class AppModule { ... } </code> </pre> <hr> <p>See this code that you have wrote:</p> <pre><code>@Provides @Singleton ProductListRepository provideProductListRepository(ProductListRepository repository) { return repository; } </code></pre> <p>What do you expect to happen? You are telling dagger <em>"hey, dagger, whenever I ask you to provide me <code>ProductListRepository</code> then create(return) that object using <code>ProductListRepository</code>"</em>. That's not gonna work out.</p> <p>Most possibly what you intended was <em>"hey, dagger, whenever I ask you to provide me an implementation of <code>ProductListRepository</code> then create(return) that object using <code>ProductListRepositoryImpl</code>"</em>:</p> <pre><code>@Provides @Singleton ProductListRepository provideProductListRepository(ProductListRepositoryImpl repository) { return repository; } </code></pre> <p>Which may be substituted with following:</p> <pre><code>@Binds @Singleton abstract ProductListRepository provideProductListRepository(ProductListRepositoryImpl repository); </code></pre>
2,749,863
AppleScript Editor, write message to the "Result" window
<p>I am using the Mac OS X Apple Script Editor and (while debugging) instead of writing a lot of <code>display dialog</code> statements, I'd like to write the results of some calculation in the window below, called "Result" (I have the German UI here, so the translation is a guess). So is there a write/print statement that I can use for putting messages in the "standard out" window? I am not asking to put the messages in a logfile on the file system, it is purely temporary.</p>
2,749,931
2
0
null
2010-05-01 12:15:23.1 UTC
8
2017-07-07 11:11:00.767 UTC
2015-04-27 15:53:58.333 UTC
null
253,056
null
317,915
null
1
60
macos|logging|applescript
70,785
<p>You can use the <a href="https://developer.apple.com/library/mac/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html#//apple_ref/doc/uid/TP40000983-CH216-SW49" rel="noreferrer">log</a> command, which puts messages into the <strong>Log History</strong> window, e.g.:</p> <p><br></p> <p><a href="https://i.stack.imgur.com/POV7E.png" rel="noreferrer"><img src="https://i.stack.imgur.com/POV7E.png" alt="enter image description here"></a></p>
39,715,803
What is the difference between mini-batch vs real time streaming in practice (not theory)?
<p>What is the difference between mini-batch vs real time streaming in practice (not theory)? In theory, I understand mini batch is something that batches in the given time frame whereas real time streaming is more like do something as the data arrives but my biggest question is why not have mini batch with epsilon time frame (say one millisecond) or I would like to understand reason why one would be an effective solution than other?</p> <p>I recently came across one example where mini-batch (Apache Spark) is used for Fraud detection and real time streaming (Apache Flink) used for Fraud Prevention. Someone also commented saying mini-batches would not be an effective solution for fraud prevention (since the goal is to prevent the transaction from occurring as it happened) Now I wonder why this wouldn't be so effective with mini batch (Spark) ? <strong>Why is it not effective to run mini-batch with 1 millisecond latency?</strong> Batching is a technique used everywhere including the OS and the Kernel TCP/IP stack where the data to the disk or network are indeed buffered so what is the convincing factor here to say one is more effective than other?</p>
39,719,036
3
0
null
2016-09-27 04:08:21.353 UTC
12
2017-04-09 15:46:56.517 UTC
2017-04-09 15:44:35.1 UTC
null
318,054
null
1,870,400
null
1
24
apache-spark|batch-processing|apache-flink|data-processing|stream-processing
8,555
<p><em>Disclaimer</em>: I'm a committer and PMC member of Apache Flink. I'm familiar with the overall design of Spark Streaming but do not know its internals in detail.</p> <p>The mini-batch stream processing model as implemented by Spark Streaming works as follows: </p> <ul> <li>Records of a stream are collected in a buffer (mini-batch). </li> <li>Periodically, the collected records are processed using a regular Spark job. This means, for each mini-batch a complete distributed batch processing job is scheduled and executed. </li> <li>While the job runs, the records for the next batch are collected.</li> </ul> <p>So, why is it not effective to run a mini-batch every 1ms? Simply because this would mean to schedule a distributed batch job every millisecond. Even though Spark is very fast in scheduling jobs, this would be a bit too much. It would also significantly reduce the possible throughput. Batching techniques used in OSs or TCP do also not work well if their batches become too small.</p>
58,339,005
What is the most common way to authenticate a modern web app?
<p>I'm writing a web app (REST API) using Spring, Spring Security. Right now I have Basic authentication and a really straightforward authorization using username, password and roles. I want to improve the security layer but I have no experience with this.</p> <p>When I had looked at postman for possible authentication methods and searched on google I've seen there are these options:</p> <ul> <li>API key</li> <li>Bearer Token</li> <li>Basic Auth</li> <li>Digest Auth</li> <li>OAuth 1.0</li> <li>OAuth 2.0</li> <li>Hawk Auth</li> <li>AWS Signature</li> <li>NTLM Auth</li> </ul> <p>Digest, Hawk, AWS and NTLM seem to be really specific cases so I omit them.</p> <p>I've heard just some general information about API key, Bearer Token and OAuth 1.0\2.0, but OAuth 1.0 seems to be outdated or something (I mean, there is a reason for version 2.0 to exist).</p> <p>So as a result it seems that I have 3 possible variants:</p> <ul> <li>API Key</li> <li>Bearer Token</li> <li>OAuth 2.0</li> </ul> <p>Is my assumption correct? What is the most widely-used case in modern web apps for security layer?</p> <p>I don't ask for a full description for each case, just general recommendations, maybe some links\resources to look at.</p> <p>What should I concentrate on?</p> <p>What mistakes in my description\explanation do you see?</p>
58,404,641
2
0
null
2019-10-11 10:09:42.027 UTC
13
2021-05-27 08:13:55.357 UTC
2020-12-31 17:55:26.343 UTC
null
11,249,957
null
9,753,003
null
1
31
rest|web-services|security|spring-security|restful-authentication
16,223
<p>As far as web application is concerned web application request should have state, <strong>session</strong> is the most common way to have state.</p> <p>And when we consider <strong>REST API's</strong> requests are preferred to be stateless, but to authenticate and identify user or client there are lot of ways as OP mentioned.</p> <h3>Some of the most common ways of authentication in REST API's are explained below</h3> <h2>1.Basic Auth</h2> <p>In Basic authentication user sends his credential encoded by base64 encoder.<br> Credentials are sent in Authorization header with Basic prefix as given below.<br> <code>"Basic "+ encodeUsingBase64(username+":"+password)</code><br></p> <p>If Your REST API is secured by Basic auth, a user who is not part of application(a user who is not present in database of server) can't access secured resources.<br><br> <sup><strong>Ideally Basic auth is for only application users</strong></sup><br></p> <h2>2. JWT / Bearer token</h2> <p>JSON Web Token (JWT) is an open standard (RFC 7519) where a server shares a digitally signed token with the client, it can be used by both application users and non application users with server side logic which extracts user information from the payload of token and validates with it's database entries for authorization. Here with JWT use case is not limited in some implementation payload can contain authorization information as well. Single Sign On is a feature that widely uses JWT nowadays.</p> <p>Compared to basic authentication </p> <ul> <li><p>Basic authentication is a authentication step where complete credential(including password) will be sent in each request.</p></li> <li><p>JWT is a post authentication step, where a authenticated user receives a signed token which doesn't contains password information.</p></li> </ul> <h2>3. API key</h2> <p>It has no standards, it might be randomly generated string issued to the users of API. Use case will be different for different issuer. It is well discussed <a href="https://stackoverflow.com/q/1453073/2825798">here</a></p> <h2>4. Oauth2.0</h2> <p>Oauth2 is a different category. In one sentense <strong>it is not about securing all application API's but providing access to <code>user resource</code> to the <code>third party applications</code> with the <code>consent of user</code>.</strong></p> <p>it has mainly 4 parts. Lets take example of Facebook<br> 1. Authorization Server [Facebook]<br> 2. Resource server [Facebook and resource will be your profile]<br> 3. Client [Stack overflow, Quora, Candy crush, Subway Surfer etc]<br> 4. Resource owner [You (If Authenticated)]<br></p> <p>Resource server may consists of both secured and unsecured API's. For accessing secured API's Client need access_token which is issued by Authorization server. access_token issued is a random string and is also stored in authorization server database along with the associated user, scope(<code>read</code>, <code>read_profile_info</code>, <code>write</code>).</p> <p>Here Resource owner(You) giving consent to the Authorization server to grant a access_token of scope(<code>read</code>,<code>read-profile</code>,<code>post-to-my-timeline</code> etc) to the Client(<code>Quora</code>,<code>StackOverflow</code>,<code>Candy-Crush</code> etc)</p> <sub><strong>Advantage of oauth2.0</strong></sub><br> <ol> <li>access_token received will have authentication and authorization both. So it will be helpful to provide specific scope to access_token.<br> (Say stack overflow accesses basic profile info, candy crush accesses more information including scope of posting on behalf of you)</li> <li>life span of access_token, grant_type of refresh_token.<br> Access tokens have limited lifetimes. If client application needs access to Resource beyond the lifetime of a single access token, it can obtain a refresh token. A refresh token allows client application to obtain new access tokens.<br> grant types: (authorization code, implicit, password, client credntial, refresh token)<br></li> </ol> <sub><strong>Note:</strong></sub><br> <p>Oauth2 Auth server not only for applications like facebook and Google but also Your application can have oauth2 server set up, and you can provide your clients access_token (to integrate your API with their application) with different scope, lifespan based on subscription/license.</p> <h2>5. Digest auth</h2> <p>I have not worked on digest auth. <a href="https://stackoverflow.com/q/2384230/2825798">Refer this thread for more details</a></p> <hr> <h3>Transport layer security essentials</h3> <sup><strong>SSL</strong></sup><br> <p>Any of the above authentication is concerned transport layer security(SSL) is important to ensure credentials/token you pass in subsequent requests is not captured as plain text.</p> <sub><strong>X.509 (has advantage over SSL)</strong></sub><br> <p>SSL certificate is sent by server to client.(Any client which makes request to server receives SSL copy. There is no restriction, any client can receive SSL certificate). </p> <p>But in case of X.509 client certificate is created using server SSL certificate and it is secretly shared with the client. Client uses X.509 certificate to communicate with server. Here one important point to be noted that for different clients different client certificate will be generated to identify each client. What X.509 ensures is </p> <ul> <li><p>Security(Who don't have client certificate can't access API's)</p></li> <li><p>Identity(server can identify client based on certificate subject)</p></li> </ul>
31,231,696
iOS 9 ATS SSL error with supporting server
<p>I installed Xcode 7 and tried running my app under iOS 9. I'm getting the infamous error: <code>Connection failed! Error - -1200 An SSL error has occurred and a secure connection to the server cannot be made.</code> The thing is my server DOES support TLSv1.2 and I'm using <code>NSURLSession</code>.</p> <p>What could be the problem then?</p>
31,245,309
5
0
null
2015-07-05 15:02:33.367 UTC
14
2018-02-23 16:22:21.997 UTC
2015-08-08 22:37:24.093 UTC
null
1,544,627
null
915,824
null
1
21
ios|objective-c|ssl|nsurlsession|ios9
27,722
<p>Apple has released the full requirements list for the <a href="https://developer.apple.com/library/prerelease/ios/technotes/App-Transport-Security-Technote/">App Transport Security</a>.</p> <p>Turned out that we were working with TLS v1.2 but were missing some of the other requirements.</p> <p><strong>Here's the full check list:</strong></p> <ol> <li>TLS requires at least version 1.2.</li> <li>Connection ciphers are limited to those that provide forward secrecy (see below for the list of ciphers.)</li> <li>The service requires a certificate using at least a SHA256 fingerprint with either a 2048 bit or greater RSA key, or a 256bit or greater Elliptic-Curve (ECC) key.</li> <li>Invalid certificates result in a hard failure and no connection.</li> </ol> <p><strong>The accepted ciphers are:</strong></p> <pre><code>TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA </code></pre>
49,841,324
What does calling fit() multiple times on the same model do?
<p>After I instantiate a scikit model (e.g. <code>LinearRegression</code>), if I call its <code>fit()</code> method multiple times (with different <code>X</code> and <code>y</code> data), what happens? Does it fit the model on the data like if I just re-instantiated the model (i.e. from scratch), or does it keep into accounts data already fitted from the previous call to <code>fit()</code>?</p> <p>Trying with <code>LinearRegression</code> (also looking at its source code) it seems to me that every time I call <code>fit()</code>, it fits from scratch, ignoring the result of any previous call to the same method. I wonder if this true in general, and I can rely on this behavior for all models/pipelines of scikit learn.</p>
49,841,366
3
0
null
2018-04-15 11:19:47.837 UTC
9
2022-09-23 10:40:47.803 UTC
2018-04-15 11:33:39.813 UTC
null
5,741,205
null
4,262,324
null
1
62
python|machine-learning|scikit-learn
31,031
<p>If you will execute <code>model.fit(X_train, y_train)</code> for a second time - it'll overwrite all previously fitted coefficients, weights, intercept (bias), etc.</p> <p>If you want to fit just a portion of your data set and then to improve your model by fitting a new data, then you can use <a href="https://scikit-learn.org/0.15/modules/scaling_strategies.html" rel="noreferrer">estimators, supporting &quot;Incremental learning&quot; (those, that implement <code>partial_fit()</code> method)</a></p>
40,478,018
Pyspark dataframe convert multiple columns to float
<p>I am trying to convert multiple columns of a dataframe from string to float like this</p> <pre><code>df_temp = sc.parallelize([("1", "2", "3.4555"), ("5.6", "6.7", "7.8")]).toDF(("x", "y", "z")) df_temp.select(*(float(col(c)).alias(c) for c in df_temp.columns)).show() </code></pre> <p>but I am getting the error</p> <pre><code>select() argument after * must be a sequence, not generator </code></pre> <p>I cannot understand why this error is being thrown</p>
40,484,961
4
0
null
2016-11-08 02:31:24.557 UTC
1
2021-12-03 18:13:42.283 UTC
2016-11-08 04:25:15.123 UTC
null
399,111
null
399,111
null
1
24
python|apache-spark|pyspark
45,724
<p><code>float()</code> is not a Spark function, you need the function <code>cast()</code>:</p> <pre><code>from pyspark.sql.functions import col df_temp.select(*(col(c).cast("float").alias(c) for c in df_temp.columns)) </code></pre>