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
12,208,946
Simple frequency tables using data.table
<p>I'm looking for a way to do simple aggregates / counts via data.table.</p> <p>Consider the iris data, which has 50 observations per species. To count the observations per species I have to summaries over a column other than species, for example "Sepal.Length".</p> <pre><code>library(data.table) dt = as.data.table(iris) dt[,length(Sepal.Length), Species] </code></pre> <p>I find this confusing because it looks like I'm doing something on Sepal.Length at first glance, when really it's only Species that matters.</p> <p>This is what I would prefer to say, but I don't get valid output:</p> <pre><code>dt[,length(Species), Species] </code></pre> <h2>Correct input and output, but clunky code:</h2> <pre><code>&gt; dt[,length(Sepal.Length), Species] Species V1 1: setosa 50 2: versicolor 50 3: virginica 50 </code></pre> <h2>Incorrect input and output, but nicer code:</h2> <pre><code>&gt; dt[,length(Species), Species] Species V1 1: setosa 1 2: versicolor 1 3: virginica 1 </code></pre> <h3>Is there an elegant way around this?</h3>
12,208,980
1
0
null
2012-08-31 04:31:40.99 UTC
12
2014-11-11 05:52:23.117 UTC
2012-08-31 04:37:22.017 UTC
null
573,778
null
573,778
null
1
34
r|data.table
17,452
<p><code>data.table</code> has a couple of symbols that can be used within the <code>j</code> expression. Notably</p> <ul> <li><code>.N</code> will give you the number of number of rows in each group.</li> </ul> <p>see <code>?data.table</code> under the details for <code>by</code></p> <blockquote> <p>Advanced: When grouping by <code>by</code> or by i, symbols .SD, .BY and .N may be used in the j expression, defined as follows.</p> <p>....</p> <p>.N is an integer, length 1, containing the number of rows in the group.</p> </blockquote> <p>For example:</p> <pre><code>dt[, .N ,by = Species] Species N 1: setosa 50 2: versicolor 50 3: virginica 50 </code></pre>
12,624,391
Very slow tab switching in Xcode 4.5 (Mountain Lion)
<p>I recently updated my MacBook Pro (2.3 GHz Intel Core i5) from Lion to Mountain Lion and simultaneously upgraded Xcode to the latest 4.5 version. I've experienced one very irritating problem. While programming I'm used to have a couple of tabs opened at a time. Ever since I updated, each time I switch tabs, Xcode freezes up for a bit (a couple of seconds). Does anyone have a suggestion to solve this problem?</p> <p>I followed <a href="https://stackoverflow.com/questions/6355667/xcode-4-slow-performance">a tip</a> on deleting project.xcworkspace to improve performance. Which seamed to help, but only for a short period of time.</p>
12,755,512
4
5
null
2012-09-27 15:02:24.163 UTC
7
2016-02-26 16:19:25.94 UTC
2017-05-23 11:45:17.207 UTC
null
-1
null
944,766
null
1
52
xcode|macos|xcode4.5
2,590
<p>It's a common issue and was fixed in XCode 4.5.1.</p> <p><a href="https://devforums.apple.com/thread/167765?tstart=0" rel="noreferrer">https://devforums.apple.com/thread/167765?tstart=0</a></p>
3,300,141
convert any date string to timestamp without timezone
<p>I'm getting xml and rss feeds and putting the data into a database. I've run into two different date formats so far...</p> <pre><code>Wed, 21 Jul 2010 00:28:50 GMT </code></pre> <p>And</p> <pre><code>2010-07-20T17:33:19Z </code></pre> <p>I'm sure there will be more. My postgresql database for the date is timestamp without time zone. Is there an existing function in php or is there a procedure to convert the any date strings to timestamp without time zone (Y-m-d H:i:s)?</p>
3,300,167
3
0
null
2010-07-21 14:11:27.833 UTC
null
2010-07-21 14:39:22.633 UTC
null
null
null
null
398,053
null
1
16
php|sql|datetime|postgresql
43,999
<p>Use <code>date</code> with <a href="http://php.net/manual/en/function.strtotime.php" rel="noreferrer"><code>strtotime</code></a>:</p> <pre><code>$date = date('Y-m-d H:i:s', strtotime('Wed, 21 Jul 2010 00:28:50 GMT')); echo $date; </code></pre> <p>Result:</p> <pre><code>2010-07-21 05:28:50 </code></pre> <p>.</p> <pre><code>$date = date('Y-m-d H:i:s', strtotime('2010-07-20T17:33:19Z')); echo $date; </code></pre> <p>Result:</p> <pre><code>2010-07-20 22:33:19 </code></pre>
3,897,942
How do I check if a sentence contains a certain word in Python and then perform an action?
<p>Let's say that I ask a user for raw input and they said, "This is a message." If that raw input contained the word "message" it would perform an action after that. Could I see how this can be done?</p>
3,897,974
4
1
null
2010-10-09 21:31:03.45 UTC
7
2022-07-31 15:14:14.063 UTC
2010-10-09 21:33:11.337 UTC
null
15,168
null
359,844
null
1
12
python|input
80,955
<p>Going based on the comment by @knitti, the problem is that you need to split up the sentence into words first, then check:</p> <pre><code>term = &quot;message&quot; #term we want to search for input = raw_input() #read input from user words = input.split() #split the sentence into individual words if term in words: #see if one of the words in the sentence is the word we want do_stuff() </code></pre> <p>Otherwise if you had the sentence &quot;That one is a classic&quot; and you tried to check if it contained the word &quot;lass&quot;, it would return True incorrectly.</p> <p>Of course, this still isn't perfect because then you might have to worry about things like stripping out punctuation and what not (like , . etc.) because otherwise the sentence &quot;That one is a classic.&quot; would still return False for a search for &quot;classic&quot; (because of the period at the end). Rather than reinvent the wheel, here's a good post on stripping punctuation from a sentence in Python:</p> <p><a href="https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python">Best way to strip punctuation from a string</a></p> <p>There's case-sensitivity to consider too, so you might want to change the <code>raw_input</code> result and your search term to lowercase before doing a search. You could easily do that by just using the <code>lower()</code> function on the <code>str</code> class.</p> <p>These problems always seem so simple...</p>
38,112,891
Angular 2+ - Set base href dynamically
<p>We have an enterprise app that uses Angular 2 for the client. Each of our customers has their own unique url, ex: <code>https://our.app.com/customer-one</code> and <code>https://our.app.com/customer-two</code>. Currently we are able to set the <code>&lt;base href...&gt;</code> dynamically using <code>document.location</code>. So user hits <code>https://our.app.com/customer-two</code> and <code>&lt;base href...&gt;</code> gets set to <code>/customer-two</code>...perfect!</p> <p>The problem is if the user is for example at <code>https://our.app.com/customer-two/another-page</code> and they refresh the page or try to hit that url directly, the <code>&lt;base href...&gt;</code> gets set to <code>/customer-two/another-page</code> and the resources can't be found.</p> <p>We've tried the following to no avail:</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;script type='text/javascript'&gt; var base = document.location.pathname.split('/')[1]; document.write('&lt;base href="/' + base + '" /&gt;'); &lt;/script&gt; ... </code></pre> <p>Unfortunately we are fresh out of ideas. Any help would be amazing.</p>
39,084,260
15
9
null
2016-06-30 02:14:11.383 UTC
72
2022-06-05 08:48:46.837 UTC
2021-05-05 00:10:29.657 UTC
null
3,509,591
null
4,164,216
null
1
165
angular
199,423
<p>Here's what we ended up doing.</p> <p>Add this to index.html. It should be the first thing in the <code>&lt;head&gt;</code> section</p> <pre><code>&lt;base href="/"&gt; &lt;script&gt; (function() { window['_app_base'] = '/' + window.location.pathname.split('/')[1]; })(); &lt;/script&gt; </code></pre> <p>Then in the <code>app.module.ts</code> file, add <code>{ provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' }</code> to the list of providers, like so:</p> <pre><code>import { NgModule, enableProdMode, provide } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { APP_BASE_HREF, Location } from '@angular/common'; import { AppComponent, routing, appRoutingProviders, environment } from './'; if (environment.production) { enableProdMode(); } @NgModule({ declarations: [AppComponent], imports: [ BrowserModule, HttpModule, routing], bootstrap: [AppComponent], providers: [ appRoutingProviders, { provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' }, ] }) export class AppModule { } </code></pre>
8,761,857
Identifying dependencies of R functions and scripts
<p>I am sifting through a package and scripts that utilize the package, and would like to identify external dependencies. The goal is to modify scripts to specify <code>library(pkgName)</code> and to modify functions in the package to use <code>require(pkgName)</code>, so that these dependencies will be more obvious later.</p> <p>I am revising the code to account for each externally dependent package. As an example, though it is by no means definitive, I am now finding it difficult to identify code that depends on <code>data.table</code>. I could replace <code>data.table</code> with <code>Matrix</code>, <code>ggplot2</code>, <code>bigmemory</code>, <code>plyr</code>, or many other packages, so feel free to answer with examples based on other packages.</p> <p>This search isn't particularly easy. The approaches I have tried so far include:</p> <ul> <li>Search the code for <code>library</code> and <code>require</code> statements</li> <li>Search for mentions of <code>data.table</code> (e.g. <code>library(data.table)</code>)</li> <li>Try running <code>codetools::checkUsage</code> to determine where there may be some issues. For the scripts, my program inserts the script into a local function and applies <code>checkUsage</code> to that function. Otherwise, I use <code>checkUsagePackage</code> for the package.</li> <li>Look for statements that are somewhat unique to <code>data.table</code>, such as <code>:=</code>.</li> <li>Look for where objects' classes may be identified via Hungarian notation, such as <code>DT</code></li> </ul> <p>The essence of my searching is to find:</p> <ul> <li>loading of <code>data.table</code>, </li> <li>objects with names that indicate they are <code>data.table</code> objects,</li> <li>methods that appear to be <code>data.table</code>-specific</li> </ul> <p>The only easy part of this seems to be finding where the package is loaded. Unfortunately, not all functions may explicitly load or require the external package - these may assume it has already been loaded. This is a bad practice, and I am trying to fix it. However, searching for objects and methods seems to be challenging.</p> <p>This (<code>data.table</code>) is just one package, and one with what seems to be limited and somewhat unique usage. Suppose I wanted to look for uses of ggplot functions, where the options are more extensive, and the text of the syntax is not as idiosyncratic (i.e. frequent usage of <code>+</code> is not idiosyncratic, while <code>:=</code> seems to be).</p> <p>I don't think that static analysis will give a perfect answer, e.g. one could pass an argument to a function, which specifies a package to be loaded. Nonetheless: are there any core tools or packages that can improve on this brute force approach, either via static or dynamic analysis?</p> <p>For what it's worth, <code>tools::pkgDepends</code> only addresses dependencies at the package level, not the function or script level, which is the level I'm working at.</p> <hr> <p>Update 1: An example of a dynamic analysis tool that should work is one that reports which packages are loaded during code execution. I don't know if such a capability exists in R, though - it would be like <code>Rprof</code> reporting the output of <code>search()</code> instead of the code stack.</p>
8,777,882
1
6
null
2012-01-06 17:27:29.227 UTC
17
2013-06-19 22:32:13.477 UTC
2012-01-08 20:11:24.957 UTC
null
805,808
null
805,808
null
1
28
r|dependencies|code-analysis
5,113
<p>First, thanks to @mathematical.coffee to putting me on the path of using Mark Bravington's <code>mvbutils</code> package. The <code>foodweb</code> function is more than satisfactory.</p> <p>To recap, I wanted to know about about checking one package, say <code>myPackage</code> versus another, say <code>externalPackage</code>, and about checking scripts against the <code>externalPackage</code>. I'll demonstrate how to do each. In this case, the external package is <code>data.table</code>.</p> <p>1: For <code>myPackage</code> versus <code>data.table</code>, the following commands suffice:</p> <pre><code>library(mvbutils) library(myPackage) library(data.table) ixWhere &lt;- match(c(&quot;myPackage&quot;,&quot;data.table&quot;), search()) foodweb(where = ixWhere, prune = ls(&quot;package:data.table&quot;), descendents = FALSE) </code></pre> <p>This produces an excellent graph showing which functions depend on functions in <code>data.table</code>. Although the graph includes dependencies within <code>data.table</code>, it's not overly burdensome: I can easily see which of my functions depend on <code>data.table</code>, and which functions they use, such as <code>as.data.table</code>, <code>data.table</code>, <code>:=</code>, <code>key</code>, and so on. At this point, one could say the package dependency problem is solved, but <code>foodweb</code> offers so much more, so let's look at that. The cool part is the dependency matrix.</p> <pre><code>depMat &lt;- foodweb(where = ixWhere, prune = ls(&quot;package:data.table&quot;), descendents = FALSE, plotting = FALSE) ix_sel &lt;- grep(&quot;^myPackage.&quot;,rownames(depMat)) depMat &lt;- depMat[ix_sel,] depMat &lt;- depMat[,-ix_sel] ix_drop &lt;- which(colSums(depMat) == 0) depMat &lt;- depMat[,-ix_drop] ix_drop &lt;- which(rowSums(depMat) == 0) depMat &lt;- depMat[-ix_drop,] </code></pre> <p>This is cool: it now shows dependencies of functions in my package, where I'm using verbose names, e.g. <code>myPackage.cleanData</code>, on functions not in my package, namely functions in <code>data.table</code>, and it eliminates rows and columns where there are no dependencies. This is concise, lets me survey dependencies quickly, and I can find the complementary set for my functions quite easily, too, by processing <code>rownames(depMat)</code>.</p> <p>NB: <code>plotting = FALSE</code> doesn't seem to prevent a plotting device from being created, at least the first time that <code>foodweb</code> is called in a sequence of calls. That is annoying, but not terrible. Maybe I'm doing something wrong.</p> <p>2: For scripts versus <code>data.table</code>, this gets a little more interesting. For each script, I need to create a temporary function, and then check for dependencies. I have a little function below that does precisely that.</p> <pre><code>listFiles &lt;- dir(pattern = &quot;myScript*.r&quot;) checkScriptDependencies &lt;- function(fname){ require(mvbutils) rawCode &lt;- readLines(fname) toParse &lt;- paste(&quot;localFunc &lt;- function(){&quot;, paste(rawCode, sep = &quot;\n&quot;, collapse = &quot;\n&quot;), &quot;}&quot;, sep = &quot;\n&quot;, collapse = &quot;&quot;) newFunc &lt;- eval(parse(text = toParse)) ix &lt;- match(&quot;data.table&quot;,search()) vecPrune &lt;- c(&quot;localFunc&quot;, ls(&quot;package:data.table&quot;)) tmpRes &lt;- foodweb(where = c(environment(),ix), prune = vecPrune, plotting = FALSE) tmpMat &lt;- tmpRes$funmat tmpVec &lt;- tmpMat[&quot;localFunc&quot;,] return(tmpVec) } listDeps &lt;- list() for(selFile in listFiles){ listDeps[[selFile]] &lt;- checkScriptDependencies(selFile) } </code></pre> <p>Now, I just need to look at <code>listDeps</code>, and I have the same kind of wonderful little insights that I have from the depMat above. I modified <code>checkScriptDependencies</code> from other code that I wrote that sends scripts to be analyzed by <code>codetools::checkUsage</code>; it's good to have a little function like this around for analyzing standalone code. Kudos to <a href="https://chat.stackoverflow.com/transcript/message/2307138#2307138">@Spacedman</a> and <a href="https://stackoverflow.com/a/8773047/805808">@Tommy</a> for insights that improved the call to <code>foodweb</code>, using <code>environment()</code>.</p> <p>(True hungaRians will notice that I was inconsistent with the order of name and type - tooBad. :) There's a longer reason for this, but this isn't precisely the code I'm using, anyway.)</p> <hr /> <p>Although I've not posted pictures of the graphs produced by <code>foodweb</code> for my code, you can see some nice examples at <a href="http://web.archive.org/web/20120413190726/http://www.sigmafield.org/2010/09/21/r-function-of-the-day-foodweb" rel="nofollow noreferrer">http://web.archive.org/web/20120413190726/http://www.sigmafield.org/2010/09/21/r-function-of-the-day-foodweb</a>. In my case, its output definitely captures data.table's usage of <code>:=</code> and <code>J</code>, along with the standard named functions, like <code>key</code> and <code>as.data.table</code>. It seems to obviate my text searches and is an improvement in several ways (e.g. finding functions that I'd overlooked).</p> <p>All in all, <code>foodweb</code> is an excellent tool, and I encourage others to explore the <code>mvbutils</code> package and some of Mark Bravington's other nice packages, such as <code>debug</code>. If you do install <code>mvbutils</code>, just check out <code>?changed.funs</code> if you think that only you struggle with managing evolving R code. :)</p>
20,812,091
Now() without timezone
<p>I have a column <code>added_at</code> of type <code>timestamp without time zone</code>. I want it's default value to be the current date-time but without time zone. The function <code>now()</code> returns a timezone as well.</p> <p>How do I solve that problem?</p>
20,814,972
4
6
null
2013-12-28 07:21:09.563 UTC
19
2022-03-29 13:59:47.767 UTC
2015-01-03 22:55:26.293 UTC
null
939,860
null
2,813,589
null
1
95
postgresql|timestamp|postgresql-9.2
129,515
<pre><code>SELECT now()::timestamp; </code></pre> <p>The cast converts the <code>timestamptz</code> returned by <code>now()</code> to the corresponding <code>timestamp</code> in your time zone - defined by the <a href="https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-TIMEZONE" rel="noreferrer"><code>timezone</code></a> setting of the session. That's also how the <a href="https://www.postgresql.org/docs/current/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT" rel="noreferrer">standard SQL function <code>LOCALTIMESTAMP</code></a> is implemented in Postgres.</p> <p>If you don't operate in multiple time zones, that works just fine. Else switch to <code>timestamptz</code> for <code>added_at</code>. The difference?</p> <ul> <li><a href="https://stackoverflow.com/questions/9571392/ignoring-timezones-altogether-in-rails-and-postgresql/9576170#9576170">Ignoring time zones altogether in Rails and PostgreSQL</a></li> </ul> <p>BTW, this does <em>exactly</em> the same, just more noisy and expensive:</p> <pre><code>SELECT now() AT TIME ZONE current_setting('timezone'); </code></pre>
25,960,850
Loading initial data with Django 1.7+ and data migrations
<p>I recently switched from Django 1.6 to 1.7, and I began using migrations (I never used South).</p> <p>Before 1.7, I used to load initial data with a <code>fixture/initial_data.json</code> file, which was loaded with the <code>python manage.py syncdb</code> command (when creating the database).</p> <p>Now, I started using migrations, and this behavior is deprecated :</p> <blockquote> <p>If an application uses migrations, there is no automatic loading of fixtures. Since migrations will be required for applications in Django 2.0, this behavior is considered deprecated. If you want to load initial data for an app, consider doing it in a data migration. (<a href="https://docs.djangoproject.com/en/1.7/howto/initial-data/#automatically-loading-initial-data-fixtures" rel="noreferrer">https://docs.djangoproject.com/en/1.7/howto/initial-data/#automatically-loading-initial-data-fixtures</a>)</p> </blockquote> <p>The <a href="https://docs.djangoproject.com/en/1.7/topics/migrations/#data-migrations" rel="noreferrer">official documentation</a> does not have a clear example on how to do it, so my question is :</p> <p>What is the best way to import such initial data using data migrations :</p> <ol> <li>Write Python code with multiple calls to <code>mymodel.create(...)</code>,</li> <li>Use or write a Django function (<a href="https://stackoverflow.com/questions/887627/programmatically-using-djangos-loaddata">like calling <code>loaddata</code></a>) to load data from a JSON fixture file.</li> </ol> <p>I prefer the second option.</p> <p>I don't want to use South, as Django seems to be able to do it natively now.</p>
25,981,899
8
5
null
2014-09-21 15:37:13.787 UTC
48
2022-09-16 08:39:51.287 UTC
2022-09-15 11:37:07 UTC
null
4,720,018
null
2,649,093
null
1
102
python|json|django|migration|data-migration
42,178
<p><em>Update</em>: See @GwynBleidD's comment below for the problems this solution can cause, and see @Rockallite's answer below for an approach that's more durable to future model changes.</p> <hr> <p>Assuming you have a fixture file in <code>&lt;yourapp&gt;/fixtures/initial_data.json</code></p> <ol> <li><p>Create your empty migration:</p> <p>In Django 1.7:</p> <pre><code>python manage.py makemigrations --empty &lt;yourapp&gt; </code></pre> <p>In Django 1.8+, you can provide a name:</p> <pre><code>python manage.py makemigrations --empty &lt;yourapp&gt; --name load_intial_data </code></pre></li> <li><p>Edit your migration file <code>&lt;yourapp&gt;/migrations/0002_auto_xxx.py</code></p> <p>2.1. Custom implementation, inspired by Django' <code>loaddata</code> (initial answer):</p> <pre><code>import os from sys import path from django.core import serializers fixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures')) fixture_filename = 'initial_data.json' def load_fixture(apps, schema_editor): fixture_file = os.path.join(fixture_dir, fixture_filename) fixture = open(fixture_file, 'rb') objects = serializers.deserialize('json', fixture, ignorenonexistent=True) for obj in objects: obj.save() fixture.close() def unload_fixture(apps, schema_editor): "Brutally deleting all entries for this model..." MyModel = apps.get_model("yourapp", "ModelName") MyModel.objects.all().delete() class Migration(migrations.Migration): dependencies = [ ('yourapp', '0001_initial'), ] operations = [ migrations.RunPython(load_fixture, reverse_code=unload_fixture), ] </code></pre> <p>2.2. A simpler solution for <code>load_fixture</code> (per @juliocesar's suggestion):</p> <pre><code>from django.core.management import call_command fixture_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '../fixtures')) fixture_filename = 'initial_data.json' def load_fixture(apps, schema_editor): fixture_file = os.path.join(fixture_dir, fixture_filename) call_command('loaddata', fixture_file) </code></pre> <p><em>Useful if you want to use a custom directory.</em></p> <p>2.3. <strong>Simplest:</strong> calling <code>loaddata</code> with <code>app_label</code> will load fixtures from the <code>&lt;yourapp&gt;</code>'s <code>fixtures</code> dir automatically : </p> <pre><code>from django.core.management import call_command fixture = 'initial_data' def load_fixture(apps, schema_editor): call_command('loaddata', fixture, app_label='yourapp') </code></pre> <p><em>If you don't specify <code>app_label</code>, loaddata will try to load <code>fixture</code> filename from <strong>all</strong> apps fixtures directories (which you probably don't want).</em> </p></li> <li><p>Run it</p> <pre><code>python manage.py migrate &lt;yourapp&gt; </code></pre></li> </ol>
22,383,345
AngularJS: ng-click on img? Manipulating images (kind of gallery-like) with jQuery?
<p>Should ng-click work with img tag ? </p> <pre><code>&lt;img ng-src="img" ng-click="openNewWindow(url)/&gt; </code></pre> <p>myFunction is defined in controller and is $scope available … Nothing gets called; any ideas? </p> <p>(I would like to open a new tab/window when image is clicked, but I don't even get into my function)</p> <p>Thanks for any info</p> <p><strong>EDIT</strong> I probably rushed myself when first asking this question. I know now why it doesn't work in my case: I am manipulating images with jQuery for some kind a 'gallery' effect … (if anyone has an idea how to do that in AngularJS please bring it on). This is the html I am talking about:</p> <pre><code>&lt;div class="commercial-container"&gt; &lt;img class="commercial" ng-src="pathToImageOrImageVar" ng-click="openNewWindow(urlToOpen)" /&gt; &lt;img class="commercial" ng-src="pathToImageOrImageVar" ng-click="openNewWindow(urlToOpen2)" /&gt; &lt;img class="commercial" ng-src="pathToImageOrImageVar" ng-click="openNewWindow(urlToOpen3)" /&gt; &lt;img class="commercial" ng-src="pathToImageOrImageVar" ng-click="openNewWindow(urlToOpen4)" /&gt; &lt;/div&gt; </code></pre> <p>And here the jQuery with which I create fade-in/fade-out effect (showing one image, then the next and so on indefinitely) </p> <pre><code> function fadeInLastImg(){ var backImg = $('.commercial-container img:first'); backImg.hide(); backImg.remove(); $('.commercial-container' ).append( backImg ); backImg.fadeIn(); }; </code></pre> <p>So my real question is this: </p> <ul> <li>How can I get the same behaviour as with my jQuery so that images will be ng-clickable?</li> </ul> <p>You can of course provide a better solution (perhaps AngularJS one) for changing images like this if you know one … </p> <p>Thank you</p>
22,384,840
4
4
null
2014-03-13 15:27:35.237 UTC
3
2017-07-19 21:14:14.86 UTC
2014-03-14 07:06:14.697 UTC
null
1,524,316
null
1,524,316
null
1
16
angularjs|angularjs-ng-click
75,500
<p>Yes, <code>ng-click</code> works on images. </p> <p>Without further code I can't tell you why yours isn't working, but the code you have pasted will call <code>myFunction</code> in the scope of the controller governing that element.</p> <p><strong>EDIT</strong></p> <p>You definitely don't need to use jQuery for this, and it's not really thinking about it in an "angular" mindset if you do. </p> <p>My suggestion is to make a directive to do this. I've <a href="http://plnkr.co/edit/54bWNsZkTJM10V69V9Hd?p=preview" rel="noreferrer">created a plunker</a> with a simple example of what it could look like. </p> <p>Here's a summary:</p> <p>Note: Because animation is important to you, make sure you include the <code>ng-animate</code> src and include it as a dependency in your app module definition. Use the same version of animate as base angular.</p> <p><strong>HTML</strong></p> <p><code>&lt;script src="http://code.angularjs.org/1.2.13/angular.js"&gt;&lt;/script&gt;</code></p> <p><code>&lt;script src="http://code.angularjs.org/1.2.13/angular-animate.js"&gt;&lt;/script&gt;</code></p> <p><strong>Javascript</strong></p> <pre><code>angular.module("gallery", ['ngAnimate']) </code></pre> <p>Now Define a template for your directive:</p> <p><strong>galleryPartial.html</strong></p> <pre><code>&lt;div class="container"&gt; &lt;img ng-src="{{image.url}}" alt="{{image.name}}" ng-repeat="image in images" class="gallery-image fade-animation" ng-click="openInNewWindow($index)" ng-show="nowShowing==$index"&gt; &lt;/div&gt; </code></pre> <p>This template simply says <em>"I want one image for every item listed in the 'images' array from the scope. The <code>src</code> is should be the <code>url</code> property of the image, and the <code>alt</code> text should be the name. When I click an image, run the <code>openInNewWindow</code> function passing the index of that image in the array. Finally, hide images unless the <code>nowShowing</code> variable is set to their index."</em></p> <p>Also note the class <code>fade-animation</code>. This could be called anything, but this is the class we'll use to define the animation in CSS later.</p> <p>Next we write the directive itself. It's pretty simple - it just has to use this template, and then define the <code>openInNewWindow</code> function, as well as iterate <code>nowShowing</code> through the array indexes:</p> <pre><code>.directive('galleryExample', function($interval, $window){ return { restrict: 'A', templateUrl: 'galleryPartial.html', scope: { images: '=' }, link: function(scope, element, attributes){ // Initialise the nowshowing variable to show the first image. scope.nowShowing = 0; // Set an interval to show the next image every couple of seconds. $interval(function showNext(){ // Make sure we loop back to the start. if(scope.nowShowing != scope.images.length - 1){ scope.nowShowing ++; } else{ scope.nowShowing = 0; } }, 2000); // Image click behaviour scope.openInNewWindow = function(index){ $window.open(scope.images[index].url); } } }; }) </code></pre> <p>You will see I have used an <a href="https://egghead.io/lessons/angularjs-understanding-isolate-scope" rel="noreferrer">isolate scope</a> to make this directive reusable and to keep things separated nicely. You don't have to do this, but it's good practice. The html for the directive must therefore also pass the images you want to put in the gallery, like so:</p> <p><strong>index.html</strong></p> <pre><code> &lt;body ng-controller="AppController"&gt; &lt;div gallery-example="" images="imageList"&gt;&lt;/div&gt; &lt;/body&gt; </code></pre> <p>So the last bit of javascript we need to write is to populate that images array in the <code>AppController</code> scope. Normally you'd use a service to get a list of images from a server or something, but in this case we'll hard code it:</p> <pre><code>.controller('AppController', function($scope){ $scope.imageList = [ { url: 'http://placekitten.com/200/200', name: 'Kitten 1' }, { url: 'http://placekitten.com/201/201', name: 'Kitten 2' }, { url: 'http://placekitten.com/201/202', name: 'Kitten 3' }, { url: 'http://placekitten.com/201/203', name: 'Kitten 4' } ] }) </code></pre> <p>Finally, styling. This will also define the animation (note the use of <code>ng-hide</code> classes etc). I strongly recommend you <a href="http://www.yearofmoo.com/2013/08/remastered-animation-in-angularjs-1-2.html#animating-ngshow-and-ng-hide" rel="noreferrer">read up on this here</a> as it is too big a subject to cover in this (already long!) answer:</p> <pre><code>.fade-animation.ng-hide-add, .fade-animation.ng-hide-remove { -webkit-transition:0.5s linear all; -moz-transition: 0.5s linear all; -o-transition: 0.5s linear all; transition:0.5s linear all; display:block !important; opacity:1; } </code></pre> <p><a href="http://plnkr.co/edit/54bWNsZkTJM10V69V9Hd?p=preview" rel="noreferrer">This is your end result</a></p>
11,250,974
How to change existing column type of a table in Sybase?
<p>I searched for a while and can't get an answer.</p> <p>Why this doesn't work? ALTER TABLE mytable ALTER COLUMN price DOUBLE</p>
11,258,522
2
2
null
2012-06-28 18:43:36.493 UTC
3
2014-04-07 08:51:03.807 UTC
null
null
null
null
884,871
null
1
5
sybase|alter-table
48,148
<p>The syntax is incorrect and there is no DOUBLE datatype in Sybase.</p> <p>So, you may try it like this:</p> <pre><code>ALTER TABLE mytable MODIFY price float </code></pre>
11,374,759
Redirect to referer url in codeigniter
<p>In messaging system of my project when you get a message from a user you a email alert saying that the another user has sent a message to view the message click here (i.e the url of message) So if the user is not logged in to system he gets redirect to login page and after login it should get back to the referer url. I have made a basecontoller in core folder and extending the CI_controller the authenticating code is as follows.</p> <pre><code>function authenticate($type = 'user') { if($type == 'user') { if($this-&gt;user_id) { // user is logged in. check for permissions now } else { // user isnt logged in. store the referrer URL in a var. if(isset($_SERVER['HTTP_REFERER'])) { $redirect_to = str_replace(base_url(),'',$_SERVER['HTTP_REFERER']); } else { $redirect_to = $this-&gt;uri-&gt;uri_string(); } redirect('user/login?redirect='.$redirect_to); exit; } } if($type == 'admin') { if($this-&gt;session-&gt;userdata('admin_id') &amp;&amp; $this-&gt;session-&gt;userdata('user_type') ==5) { // Admin is logged in } else { redirect('admin/login'); exit; } } } </code></pre> <p>The referer url is "http://example.com/project/pm/view_conversation?id=11" now the problem is I am getting referer url till view_conversation and not able to get the id part.</p> <p>Any suggestion ?</p> <p>Thank you.</p>
15,991,205
5
0
null
2012-07-07 11:52:01.113 UTC
3
2021-08-05 15:49:01.21 UTC
null
null
null
null
1,396,514
null
1
17
php|codeigniter|http-referer
74,696
<p>This can help:</p> <p>CI 2+ <a href="https://www.codeigniter.com/userguide2/libraries/user_agent.html" rel="nofollow noreferrer">https://www.codeigniter.com/userguide2/libraries/user_agent.html</a></p> <p>CI 3+ <a href="http://www.codeigniter.com/userguide3/libraries/user_agent.html" rel="nofollow noreferrer">http://www.codeigniter.com/userguide3/libraries/user_agent.html</a></p> <p>Below solution is for Codeigniter version 3</p> <pre><code>$this-&gt;load-&gt;library('user_agent'); if ($this-&gt;agent-&gt;is_referral()) { echo $this-&gt;agent-&gt;referrer(); } </code></pre> <p>UPDATE: interesting and useful information on how to obtain referrer information with the same user_agent library<br /> <a href="https://www.tutorialandexample.com/user-agent-class/" rel="nofollow noreferrer">https://www.tutorialandexample.com/user-agent-class/</a></p>
10,865,237
website header hiding behind content when position is fixed
<p>I am designing a website for a school and I want the header of site to be fixed just like facebook has. I tried the fix provided by <a href="https://stackoverflow.com/questions/7573089/page-navigation-with-fixed-header">this</a> question on stackoverflow but it was hardly of any use in the header. I have an image, basically the logo of the school, where I do <code>position: fixed</code>, but the header hides behind the page.</p> <p>HTML:</p> <pre><code>&lt;body&gt; &lt;div id="header" &gt; &lt;img src="images/iesheader_nnew1.jpg" /&gt;&lt;/div&gt; &lt;div id="menu"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="index.html"&gt;&lt;abbr title="Home"&gt;Home&amp;nbsp;&amp;nbsp;&lt;/abbr&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="aboutus.html"&gt; &lt;abbr title="About Us"&gt;About Us&amp;nbsp;&amp;nbsp;&lt;/abbr&gt; &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="acad.html"&gt;&lt;abbr title="Academics"&gt;Academics&lt;/abbr&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="admin.html"&gt;&lt;abbr title="Administration"&gt;Administration&lt;/abbr&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="news.html"&gt;&lt;abbr title="News"&gt;News&lt;/abbr&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="contact.html"&gt;&lt;abbr title="Contact Us"&gt;Contact Us&lt;/abbr&gt; &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="photo.html"&gt;&lt;abbr title="Photo Gallery"&gt;Photo Gallery&lt;/abbr&gt; &lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="cleaner"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS: </p> <pre><code>#header { margin-left: 0px; width: auto; height: 90px; padding: 0px; padding-left:185px; font-size: 35px; color:#FFFFFF; background-color: #f6c491; position: fixed; top: 0; left: 0; right: 0; } #menu { position: relative; clear: both; width: auto; height: 38px; padding: 0; padding-left:185px; background-color:#FFFFFF; margin-bottom: 10px; margin-left:0px; } #menu ul { float: left; width: 960px; margin: 0; padding: 0; list-style: none; } #menu ul li { padding: 0px; margin: 0px; display: inline; } #menu a { float: left; display: block; padding: 8px 20px; font-size: 14px; font-weight: bold; text-align: center; text-decoration: none; color: #000; outline: none; border: none; border-top: 3px solid black; } </code></pre> <p>I tried a number of solutions to that, but whatever I do, the header goes behind the page. I want the menu bar also to be fixed but it also is the same... </p>
10,865,264
6
2
null
2012-06-02 19:23:13.967 UTC
1
2020-08-10 16:25:38.113 UTC
2017-05-23 12:02:20.3 UTC
null
-1
null
1,160,051
null
1
19
css|css-position
87,579
<p>Add z-index:1000 to the #header css, and add padding-top to the body css which should be a bit more than header's height. For example, if the header's height is 40px, put the padding-top: 50px to the body css and it should work.</p>
11,315,204
How to get 2 digit hour and minutes from Rails time class
<p>I am looking at </p> <p><a href="http://corelib.rubyonrails.org/classes/Time.html#M000245" rel="noreferrer">http://corelib.rubyonrails.org/classes/Time.html#M000245</a></p> <p>how can I get two digit hour and minutes from a time object</p> <p>Lets say I do </p> <pre><code>t = Time.now t.hour // this returns 7 I want to get 07 instead of just 7 </code></pre> <p>same for </p> <pre><code>t.min // // this returns 3 I want to get 03 instead of just 3 </code></pre> <p>Thanks</p>
11,315,235
5
0
null
2012-07-03 16:26:24.723 UTC
5
2021-06-08 19:48:05.327 UTC
null
null
null
null
395,842
null
1
22
ruby-on-rails|datetime
42,833
<p>How about using <a href="http://ruby-doc.org/core-1.9.3/String.html#method-i-25" rel="noreferrer">String.format</a> (%) operator? Like this:</p> <pre><code>x = '%02d' % t.hour puts x # prints 07 if t.hour equals 7 </code></pre>
11,255,451
Eclipse and EGit: How to easily review changes to ALL modified files before committing to *local* repository
<p>I'm using Eclipse Indigo SR2 with the (built-in) EGit plugin v.1.3.0.201202151440-r and haven't been able to find any way to easily review all my changes before making a commit.</p> <p>I used Eclipse with SVN for years, and this was always very easy to do. I would typically right-click on my project, select <code>Team-&gt;Synchronize</code>, double-click on the first changed file (in the Team Sync perspective), then hit <kbd>Ctrl</kbd>-<kbd>.</kbd> repeatedly to review all changes in one file, and then proceed to the next file, as I wrote a summary of my changes for the commit message.</p> <p>But of course, git is very different from Subversion, and so my workflow must change. With EGit, "Team Sync" only appears to be useful for reviewing changes between my local files and the remote repository (i.e. before a push to the remote). I need a way to review changes since my last commit to my <em>local</em> repository. I generally don't even care to (re)review changes before a push to remote (and if I did, I'd prefer a simple equivalent of <code>git log</code> to see what commits I'm about to push).</p> <p>If I right-click on my project and select <code>Team-&gt;Commit</code>, I am presented with a window that does <em>almost</em> everything I need to do (select files to stage, commit, write a commit message, amend a previous commit, etc.). What it <em>doesn't</em> allow me to do is quickly and easily review all my changes in a compare editor. I can't believe this capability doesn't exist! It seems I am required to double-click on each individual file, review the changes, close the compare editor, and double-click on the next file. That's ridiculous!</p> <p>TL/DR - I am looking for a simple GUI equivalent (in Eclipse) to do what I am easily able to do from the command line using <code>git vimdiff</code> (where vimdiff is a git alias that uses vimdiff as the "difftool" to cycle through all modified files) followed by <code>git commit</code> (with perhaps a <code>git add</code> or two in between).</p> <p>If no one has a good solution, I am curious about how others handle their commit workflow with EGit. I've been getting along fine committing from the command line (not that Eclipse is happy about that) but I can't believe that EGit is as near-useless as it seems to me. Perhaps my google-fu is not as strong as it once was?</p>
11,256,271
3
1
null
2012-06-29 02:49:20.053 UTC
13
2019-06-26 15:10:05.433 UTC
2015-02-12 23:38:37.157 UTC
null
1,339,923
null
1,339,923
null
1
46
eclipse|git|egit
62,569
<p>Are you aware of the 'Git Staging' view. It keeps track of all the files that have changed and you can review the changes any time. (This can be a bit better than using the commit dialog)</p> <p>An alternative is to commit all changes without reviewing, and then use the history view to compare two commits (Simply select the last top most commits, right click and select 'Compare with each other'). This way you do not have to keep double clicking individual files. If you need to change something you can always 'Amend' the last commit. (I usually follow this approach)</p>
12,865,848
General purpose FromEvent method
<p>Using the new async/await model it's fairly straightforward to generate a <code>Task</code> that is completed when an event fires; you just need to follow this pattern:</p> <pre><code>public class MyClass { public event Action OnCompletion; } public static Task FromEvent(MyClass obj) { TaskCompletionSource&lt;object&gt; tcs = new TaskCompletionSource&lt;object&gt;(); obj.OnCompletion += () =&gt; { tcs.SetResult(null); }; return tcs.Task; } </code></pre> <p>This then allows:</p> <pre><code>await FromEvent(new MyClass()); </code></pre> <p>The problem is that you need to create a new <code>FromEvent</code> method for every event in every class that you would like to <code>await</code> on. That could get really large really quick, and it's mostly just boilerplate code anyway.</p> <p>Ideally I would like to be able to do something like this:</p> <pre><code>await FromEvent(new MyClass().OnCompletion); </code></pre> <p>Then I could re-use the same <code>FromEvent</code> method for any event on any instance. I've spent some time trying to create such a method, and there are a number of snags. For the code above it will generate the following error:</p> <blockquote> <p>The event 'Namespace.MyClass.OnCompletion' can only appear on the left hand side of += or -=</p> </blockquote> <p>As far as I can tell, there won't ever be a way of passing the event like this through code.</p> <p>So, the next best thing seemed to be trying to pass the event name as a string:</p> <pre><code>await FromEvent(new MyClass(), "OnCompletion"); </code></pre> <p>It's not as ideal; you don't get intellisense and would get a runtime error if the event doesn't exist for that type, but it could still be more useful than tons of FromEvent methods.</p> <p>So it's easy enough to use reflection and <code>GetEvent(eventName)</code> to get the <code>EventInfo</code> object. The next problem is that the delegate of that event isn't known (and needs to be able to vary) at runtime. That makes adding an event handler hard, because we need to dynamically create a method at runtime, matching a given signature (but ignoring all parameters) that accesses a <code>TaskCompletionSource</code> that we already have and sets its result.</p> <p>Fortunately I found <a href="http://msdn.microsoft.com/en-us/library/ms228976.aspx#procedureSection1" rel="nofollow noreferrer">this link</a> which contains instructions on how to do [almost] exactly that via <code>Reflection.Emit</code>. Now the problem is that we need to emit IL, and I have no idea how to access the <code>tcs</code> instance that I have.</p> <p>Below is the progress that I've made towards finishing this:</p> <pre><code>public static Task FromEvent&lt;T&gt;(this T obj, string eventName) { var tcs = new TaskCompletionSource&lt;object&gt;(); var eventInfo = obj.GetType().GetEvent(eventName); Type eventDelegate = eventInfo.EventHandlerType; Type[] parameterTypes = GetDelegateParameterTypes(eventDelegate); DynamicMethod handler = new DynamicMethod("unnamed", null, parameterTypes); ILGenerator ilgen = handler.GetILGenerator(); //TODO ilgen.Emit calls go here Delegate dEmitted = handler.CreateDelegate(eventDelegate); eventInfo.AddEventHandler(obj, dEmitted); return tcs.Task; } </code></pre> <p>What IL could I possibly emit that would allow me to set the result of the <code>TaskCompletionSource</code>? Or, alternatively, is there another approach to creating a method that returns a Task for any arbitrary event from an arbitrary type?</p>
12,867,906
4
2
null
2012-10-12 19:31:05.193 UTC
18
2020-03-24 19:12:36.513 UTC
2018-08-06 07:52:58.293 UTC
null
1,016,343
null
1,159,478
null
1
7
c#|async-await|task-parallel-library|cil|reflection.emit
2,788
<p>Here you go:</p> <pre><code>internal class TaskCompletionSourceHolder { private readonly TaskCompletionSource&lt;object[]&gt; m_tcs; internal object Target { get; set; } internal EventInfo EventInfo { get; set; } internal Delegate Delegate { get; set; } internal TaskCompletionSourceHolder(TaskCompletionSource&lt;object[]&gt; tsc) { m_tcs = tsc; } private void SetResult(params object[] args) { // this method will be called from emitted IL // so we can set result here, unsubscribe from the event // or do whatever we want. // object[] args will contain arguments // passed to the event handler m_tcs.SetResult(args); EventInfo.RemoveEventHandler(Target, Delegate); } } public static class ExtensionMethods { private static Dictionary&lt;Type, DynamicMethod&gt; s_emittedHandlers = new Dictionary&lt;Type, DynamicMethod&gt;(); private static void GetDelegateParameterAndReturnTypes(Type delegateType, out List&lt;Type&gt; parameterTypes, out Type returnType) { if (delegateType.BaseType != typeof(MulticastDelegate)) throw new ArgumentException("delegateType is not a delegate"); MethodInfo invoke = delegateType.GetMethod("Invoke"); if (invoke == null) throw new ArgumentException("delegateType is not a delegate."); ParameterInfo[] parameters = invoke.GetParameters(); parameterTypes = new List&lt;Type&gt;(parameters.Length); for (int i = 0; i &lt; parameters.Length; i++) parameterTypes.Add(parameters[i].ParameterType); returnType = invoke.ReturnType; } public static Task&lt;object[]&gt; FromEvent&lt;T&gt;(this T obj, string eventName) { var tcs = new TaskCompletionSource&lt;object[]&gt;(); var tcsh = new TaskCompletionSourceHolder(tcs); EventInfo eventInfo = obj.GetType().GetEvent(eventName); Type eventDelegateType = eventInfo.EventHandlerType; DynamicMethod handler; if (!s_emittedHandlers.TryGetValue(eventDelegateType, out handler)) { Type returnType; List&lt;Type&gt; parameterTypes; GetDelegateParameterAndReturnTypes(eventDelegateType, out parameterTypes, out returnType); if (returnType != typeof(void)) throw new NotSupportedException(); Type tcshType = tcsh.GetType(); MethodInfo setResultMethodInfo = tcshType.GetMethod( "SetResult", BindingFlags.NonPublic | BindingFlags.Instance); // I'm going to create an instance-like method // so, first argument must an instance itself // i.e. TaskCompletionSourceHolder *this* parameterTypes.Insert(0, tcshType); Type[] parameterTypesAr = parameterTypes.ToArray(); handler = new DynamicMethod("unnamed", returnType, parameterTypesAr, tcshType); ILGenerator ilgen = handler.GetILGenerator(); // declare local variable of type object[] LocalBuilder arr = ilgen.DeclareLocal(typeof(object[])); // push array's size onto the stack ilgen.Emit(OpCodes.Ldc_I4, parameterTypesAr.Length - 1); // create an object array of the given size ilgen.Emit(OpCodes.Newarr, typeof(object)); // and store it in the local variable ilgen.Emit(OpCodes.Stloc, arr); // iterate thru all arguments except the zero one (i.e. *this*) // and store them to the array for (int i = 1; i &lt; parameterTypesAr.Length; i++) { // push the array onto the stack ilgen.Emit(OpCodes.Ldloc, arr); // push the argument's index onto the stack ilgen.Emit(OpCodes.Ldc_I4, i - 1); // push the argument onto the stack ilgen.Emit(OpCodes.Ldarg, i); // check if it is of a value type // and perform boxing if necessary if (parameterTypesAr[i].IsValueType) ilgen.Emit(OpCodes.Box, parameterTypesAr[i]); // store the value to the argument's array ilgen.Emit(OpCodes.Stelem, typeof(object)); } // load zero-argument (i.e. *this*) onto the stack ilgen.Emit(OpCodes.Ldarg_0); // load the array onto the stack ilgen.Emit(OpCodes.Ldloc, arr); // call this.SetResult(arr); ilgen.Emit(OpCodes.Call, setResultMethodInfo); // and return ilgen.Emit(OpCodes.Ret); s_emittedHandlers.Add(eventDelegateType, handler); } Delegate dEmitted = handler.CreateDelegate(eventDelegateType, tcsh); tcsh.Target = obj; tcsh.EventInfo = eventInfo; tcsh.Delegate = dEmitted; eventInfo.AddEventHandler(obj, dEmitted); return tcs.Task; } } </code></pre> <p>This code will work for almost all events that return void (regardless of the parameter list).</p> <p>It can be improved to support any return values if necessary.</p> <p>You can see the difference between Dax's and mine methods below:</p> <pre><code>static async void Run() { object[] result = await new MyClass().FromEvent("Fired"); Console.WriteLine(string.Join(", ", result.Select(arg =&gt; arg.ToString()).ToArray())); // 123, abcd } public class MyClass { public delegate void TwoThings(int x, string y); public MyClass() { new Thread(() =&gt; { Thread.Sleep(1000); Fired(123, "abcd"); }).Start(); } public event TwoThings Fired; } </code></pre> <p>Briefly, my code supports <strong>really</strong> any kind of delegate type. You shouldn't (and don't need to) specify it explicitly like <code>TaskFromEvent&lt;int, string&gt;</code>.</p>
12,812,893
Passing 'this' to an onclick event
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/4268085/the-current-element-as-its-event-function-param">The current element as its Event function param</a> </p> </blockquote> <p>Would this work</p> <pre><code>&lt;script type="text/javascript"&gt; var foo = function(param) { param.innerHTML = "Not a button"; }; &lt;/script&gt; &lt;button onclick="foo(this)" id="bar"&gt;Button&lt;/button&gt; </code></pre> <p>rather than this?</p> <pre><code>&lt;script type="text/javascript"&gt; var foo = function() { document.getElementId("bar").innerHTML = "Not a button"; }; &lt;/script&gt; &lt;button onclick="foo()" id="bar"&gt;Button&lt;/button&gt; </code></pre> <p>And would the first method allow me to load the javascript from elsewhere to perform actions on any page element?</p>
12,812,986
4
2
null
2012-10-10 06:00:55.91 UTC
11
2012-10-10 06:25:06.437 UTC
2017-05-23 12:34:33.157 UTC
null
-1
null
1,686,064
null
1
50
javascript|html
149,472
<p>The code that you have would work, but is executed from the global context, which means that <code>this</code> refers to the global object.</p> <pre><code>&lt;script type="text/javascript"&gt; var foo = function(param) { param.innerHTML = "Not a button"; }; &lt;/script&gt; &lt;button onclick="foo(this)" id="bar"&gt;Button&lt;/button&gt; </code></pre> <p>You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from <code>this</code>.</p> <pre><code>&lt;script type="text/javascript"&gt; document.getElementById('bar').onclick = function() { this.innerHTML = "Not a button"; }; &lt;/script&gt; &lt;button id="bar"&gt;Button&lt;/button&gt; </code></pre>
11,312,433
How to alter a column and change the default value?
<p>I got the following error while trying to alter a column's data type and setting a new default value:</p> <pre><code>ALTER TABLE foobar_data ALTER COLUMN col VARCHAR(255) NOT NULL SET DEFAULT '{}'; </code></pre> <blockquote> <p>ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VARCHAR(255) NOT NULL SET DEFAULT '{}'' at line 1</p> </blockquote>
11,312,469
8
1
null
2012-07-03 13:51:43.457 UTC
38
2022-03-29 10:54:53.6 UTC
2012-07-03 13:53:37.207 UTC
null
458,741
null
1,150,778
null
1
247
mysql|sql
403,001
<pre><code>ALTER TABLE foobar_data MODIFY COLUMN col VARCHAR(255) NOT NULL DEFAULT '{}'; </code></pre> <p>A second possibility which does the same (thanks to juergen_d):</p> <pre><code>ALTER TABLE foobar_data CHANGE COLUMN col col VARCHAR(255) NOT NULL DEFAULT '{}'; </code></pre>
10,964,966
Detect IE version (prior to v9) in JavaScript
<p>I want to bounce users of our web site to an error page if they're using a version of <code>Internet Explorer</code> prior to v9. It's just not worth our time and money to support <code>IE pre-v9</code>. Users of all other non-IE browsers are fine and shouldn't be bounced. Here's the proposed code:</p> <pre><code>if(navigator.appName.indexOf("Internet Explorer")!=-1){ //yeah, he's using IE var badBrowser=( navigator.appVersion.indexOf("MSIE 9")==-1 &amp;&amp; //v9 is ok navigator.appVersion.indexOf("MSIE 1")==-1 //v10, 11, 12, etc. is fine too ); if(badBrowser){ // navigate to error page } } </code></pre> <p>Will this code do the trick?</p> <p>To head off a few comments that will probably be coming my way:</p> <ol> <li>Yes, I know that users can forge their <code>useragent</code> string. I'm not concerned.</li> <li>Yes, I know that programming pros prefer sniffing out feature-support instead of browser-type but I don't feel this approach makes sense in this case. I already know that all (relevant) non-IE browsers support the features that I need and that all <code>pre-v9 IE</code> browsers don't. Checking feature by feature throughout the site would be a waste.</li> <li>Yes, I know that someone trying to access the site using <code>IE v1</code> (or >= 20) wouldn't get 'badBrowser' set to true and the warning page wouldn't be displayed properly. That's a risk we're willing to take.</li> <li>Yes, I know that Microsoft has "conditional comments" that can be used for precise browser version detection. IE no longer supports conditional comments as of <code>IE 10</code>, rendering this approach absolutely useless.</li> </ol> <p>Any other obvious issues to be aware of?</p>
10,965,091
37
10
null
2012-06-09 22:13:23.48 UTC
129
2018-10-01 05:20:49.78 UTC
2016-07-20 09:41:21.017 UTC
null
2,306,173
null
1,040,766
null
1
253
javascript|internet-explorer|user-agent|browser-detection
387,824
<p>This is my preferred way of doing it. It gives maximum control. (Note: Conditional statements are only supported in IE5 - 9.)</p> <p>First set up your ie classes correctly</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;!--[if lt IE 7]&gt; &lt;html class="lt-ie9 lt-ie8 lt-ie7"&gt; &lt;![endif]--&gt; &lt;!--[if IE 7]&gt; &lt;html class="lt-ie9 lt-ie8"&gt; &lt;![endif]--&gt; &lt;!--[if IE 8]&gt; &lt;html class="lt-ie9"&gt; &lt;![endif]--&gt; &lt;!--[if gt IE 8]&gt;&lt;!--&gt; &lt;html&gt; &lt;!--&lt;![endif]--&gt; &lt;head&gt; </code></pre> <p>Then you can just use CSS to make style exceptions, or, if you require, you can add some simple JavaScript:</p> <pre><code>(function ($) { "use strict"; // Detecting IE var oldIE; if ($('html').is('.lt-ie7, .lt-ie8, .lt-ie9')) { oldIE = true; } if (oldIE) { // Here's your JS for IE.. } else { // ..And here's the full-fat code for everyone else } }(jQuery)); </code></pre> <p>Thanks to <a href="http://www.paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/">Paul Irish</a>.</p>
16,765,158
"date(): It is not safe to rely on the system's timezone settings..."
<p>I got this error when I requested to update the <a href="http://en.wikipedia.org/wiki/PHP">PHP</a> version from 5.2.17 to PHP 5.3.21 on the server.</p> <pre><code>&lt;div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;"&gt; &lt;h4&gt;A PHP Error was encountered&lt;/h4&gt; &lt;p&gt;Severity: Warning&lt;/p&gt; &lt;p&gt;Message: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EDT/-4.0/DST' instead&lt;/p&gt; &lt;p&gt;Filename: libraries/Log.php&lt;/p&gt; &lt;p&gt;Line Number: 86&lt;/p&gt; &lt;/div&gt; Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EDT/-4.0/DST' instead in /filelocation right here/system/libraries/Log.php on line 86 Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EDT/-4.0/DST' instead in /filelocation right here/system/libraries/Log.php on line 99 &lt;div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;"&gt; &lt;h4&gt;A PHP Error was encountered&lt;/h4&gt; &lt;p&gt;Severity: Warning&lt;/p&gt; &lt;p&gt;Message: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/New_York' for 'EDT/-4.0/DST' instead&lt;/p&gt; &lt;p&gt;Filename: libraries/Log.php&lt;/p&gt; &lt;p&gt;Line Number: 99&lt;/p&gt; &lt;/div&gt; </code></pre>
16,765,214
25
0
null
2013-05-27 01:05:31.163 UTC
66
2021-07-10 10:52:09.35 UTC
2016-01-04 18:26:27.897 UTC
null
1,691,225
null
1,852,837
null
1
382
php|timezone
598,362
<p>You probably need to put the timezone in a configuration line in your <code>php.ini</code> file. You should have a block like this in your php.ini file:</p> <pre><code>[Date] ; Defines the default timezone used by the date functions ; http://php.net/date.timezone date.timezone = America/New_York </code></pre> <p>If not, add it (replacing the timezone by yours). After configuring, make sure to restart httpd (<code>service httpd restart</code>).</p> <p>Here is the <a href="http://www.php.net/manual/en/timezones.php">list of supported timezones</a>.</p>
25,892,417
Caused by: java.lang.ClassCastException: java.sql.Timestamp cannot be cast to java.sql.Date
<p>I am getting the below given error for the following code snippets:</p> <pre><code> try { cRows = new CachedRowSetImpl(); while(cRows.next()) { MyClass myClass = new MyClass(); myClass.setPrevDate(cRows.getDate("PREV_DATE")); // In debug mode, the error was throwing when I press Resume from here. } } </code></pre> <p><strong>Error:</strong></p> <pre><code>Caused by: java.lang.ClassCastException: java.sql.Timestamp cannot be cast to java.sql.Date </code></pre> <p>In the database, the datatype for the column is <code>DATE</code> only. I am not able to figure out where the <code>Timestamp</code> is coming here.</p>
25,915,418
2
5
null
2014-09-17 13:47:45.513 UTC
1
2014-09-19 03:55:55.4 UTC
2014-09-17 13:52:39.42 UTC
null
3,892,259
null
930,544
null
1
3
java|classcastexception|cachedrowset
43,998
<p>I have done a research on this issue and found some useful links. I found this confusion between DATE and TIMESTAMP is JDBC Driver specific. And most of the links suggest the use of <code>-Doracle.jdbc.V8Compatible=true</code>. For my JBoss I have set this in <code>run.bat</code> and the issue got resolved.</p> <ol> <li><p><a href="https://community.oracle.com/thread/68918?start=0&amp;tstart=0" rel="nofollow">https://community.oracle.com/thread/68918?start=0&amp;tstart=0</a></p></li> <li><p><a href="http://www.coderanch.com/t/90891/JBoss/oracle-jdbc-Compatible-true" rel="nofollow">http://www.coderanch.com/t/90891/JBoss/oracle-jdbc-Compatible-true</a></p></li> <li><a href="https://community.oracle.com/message/3613155" rel="nofollow">https://community.oracle.com/message/3613155</a></li> </ol> <p>The oracle doc shares different solutions:</p> <ul> <li><p>Alter your tables to use TIMESTAMP instead of DATE. This is probably rarely possible, but it is the best solution when it is.</p></li> <li><p>Alter your application to use defineColumnType to define the columns as TIMESTAMP rather than DATE. There are problems with this because you really don't want to use defineColumnType unless you have to (see What is defineColumnType and when should I use it? ).</p></li> <li><p>Alter you application to use getTimestamp rather than getObject. This is a good solution when possible, however many applications contain generic code that relies on getObject, so it isn't always possible.</p></li> <li><p>Set the V8Compatible connection property. This tells the JDBC drivers to use the old mapping rather than the new one. You can set this flag either as a connection property or a system property. You set the connection property by adding it to the java.util.Properties object passed to DriverManager.getConnection or to OracleDataSource.setConnectionProperties. You set the system property by including a -D option in your java command line.</p> <p>java -Doracle.jdbc.V8Compatible="true" MyApp</p></li> </ul> <p>Here is the link: <a href="http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-faq-090281.html#08_00" rel="nofollow">http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-faq-090281.html#08_00</a> </p>
25,591,040
Nginx serves .php files as downloads, instead of executing them
<p>I am installing a website in a droplet (Digital Ocean). I have an issue for install NGINX with PHP properly. I did a tutorial <a href="https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-14-04" rel="nofollow noreferrer">https://www.digitalocean.com/community/tutorials/how-to-install-linux-nginx-mysql-php-lemp-stack-on-ubuntu-14-04</a> but when I try to run some .php files it's just downloading it... for example... <code>http://5.101.99.123/info.php</code> it's working but... If I go to the main <code>http://5.101.99.123</code> it's downloading my index.php :/</p> <p>Any idea?</p> <pre><code>-rw-r--r-- 1 agitar_user www-data 418 Jul 31 18:27 index.php -rw-r--r-- 1 agitar_user www-data 21 Aug 31 11:20 info.php </code></pre> <p>My <strong>/etc/nginx/sites-available/default</strong></p> <pre><code>server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /var/www/html; index index.html index.htm index.php; # Make site accessible from http://localhost/ server_name agitarycompartir.com; location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(/.+)$; ## NOTE: You should have &quot;cgi.fix_pathinfo = 0;&quot; in php.ini # # # With php5-cgi alone: # fastcgi_pass 127.0.0.1:9000; # # With php5-fpm: fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } location / { try_files $uri $uri/ =404; # Uncomment to enable naxsi on this location # include /etc/nginx/naxsi.rules } </code></pre> <p>...</p> <p>Other &quot;locations&quot; are commented on...</p> <p>.</p>
26,668,444
29
9
null
2014-08-31 10:24:17.423 UTC
48
2022-09-19 10:38:34.383 UTC
2022-09-19 10:37:40.56 UTC
null
5,409,748
null
3,287,988
null
1
192
php|wordpress|nginx|location|fastcgi
338,956
<p>Try this:</p> <ol> <li><p>Edit <code>/etc/nginx/sites-available/default</code></p> </li> <li><p>Uncomment both listen lines to make Nginx listen on port 80 IPv4 and IPv6.</p> <pre><code> listen 80; ## listen for ipv4; this line is default and implied listen [::]:80 default_server ipv6only=on; ## listen for ipv6 </code></pre> </li> <li><p>Leave <code>server_name</code> alone</p> <pre><code> # Make site accessible (...) server_name localhost; </code></pre> </li> <li><p>Add <code>index.php</code> to the <code>index</code> line</p> <pre><code> root /usr/share/nginx/www; index index.php index.html index.htm; </code></pre> </li> <li><p>Uncomment <code>location ~ \.php$ {}</code></p> <pre><code> # pass the PHP scripts to FastCGI server listening on (...) # location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+?\.php)(/.+)?$; # NOTE: You should have &quot;cgi.fix_pathinfo = 0;&quot; in php.ini # With php5-cgi alone: #fastcgi_pass 127.0.0.1:9000; # With php5-fpm: fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; include fastcgi_params; } </code></pre> </li> <li><p>Edit <code>/etc/php5/fpm/php.ini</code> and make sure <code>cgi.fix_pathinfo</code> is set to <code>0</code></p> </li> <li><p>Restart Nginx and php5-fpm <code>sudo service nginx restart &amp;&amp; sudo service php5-fpm restart</code></p> </li> </ol> <hr /> <p>I just started using Linux a week ago, so I really hope to help you with this. I am using a nano text editor to edit the files. run apt-get install nano if you don't have it. Google it to know more.</p>
57,848,302
How to solve 'command find requires authentication' using Node.js and mongoose?
<p>I need help to fix the error. My ubuntu server 16.04 running:</p> <p>MongoDB shell version v4.0.9</p> <p>Node 11.6</p> <p>mongoose 5.3.4</p> <p>When the security on /etc/mongod.conf is:</p> <p><code>security: authorization: "disabled"</code> I can use :</p> <pre><code>const mongoURI = 'mongodb://writeApp:writeApp9779@127.0.0.1:27017/writeapp'; </code></pre> <p><code>const db = mongoose.connect(mongoURI, { useNewUrlParser: true });</code></p> <p>All database commands work. Even I checked by putting wrong password, It shows auth fail. But as you know mongodb will still work as authorization is disabled.</p> <p>My user data is correct as checked by db.getUsers() from command line:</p> <pre><code>&gt; db.getUsers(); [ { "_id" : "admin.root", "userId" : UUID("8f6c1295-a261-4057-9a29-8a9919437841"), "user" : "root", "db" : "admin", "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] }, { "_id" : "admin.writeApp", "userId" : UUID("ee148506-1860-4739-80db-17352e0e2ccb"), "user" : "writeApp", "db" : "admin", "roles" : [ { "role" : "dbOwner", "db" : "writeapp" }, { "role" : "listDatabases", "db" : "admin" } ], "mechanisms" : [ "SCRAM-SHA-1", "SCRAM-SHA-256" ] } ] </code></pre> <p><strong>The real problem:</strong> so I nano /etc/mongod.conf and changed the authorization:"enabled" after that restarted mongo. When I re run my app, following error occurs:</p> <pre><code>{ MongoError: command find requires authentication ............ ............ ok: 0, errmsg: 'command find requires authentication', code: 13, codeName: 'Unauthorized', name: 'MongoError', [Symbol(mongoErrorContextSymbol)]: {} } </code></pre> <p>After spending long time, I connected using mongo shell:</p> <pre><code>mongo -u "writeApp" -p writeApp9779 --authenticationDatabase "admin" &gt; use writeapp; switched to db writeapp &gt; db.users.find(); { "_id" : ObjectId("5cb63f23755c4469f8f6e2e6"), .......... } </code></pre> <p>It is working in the console but not in the application.I can't find any solution. Really need your kind consideration. By the way here is a sample node.js </p> <pre><code>Category.find(function(err, categories){ if(err) console.log(err); else { app.locals.categories = categories; } }); </code></pre> <p>Model:</p> <pre><code>var mongoose =require('mongoose'); var CategorySchema = mongoose.Schema({ title: { type:String, required:true }, slug: { type:String } }); module.exports = mongoose.model("Category", CategorySchema); </code></pre>
57,877,333
2
5
null
2019-09-09 05:27:42.177 UTC
7
2021-01-22 11:56:20.043 UTC
2019-09-09 06:29:31.803 UTC
null
5,433,806
null
5,433,806
null
1
24
node.js|mongodb|mongoose
68,807
<p><strong>1. How to connect from terminal and mongo:</strong></p> <p>When you install MongoDB the authorization is disabled. So keep it like that for now. Create a root user in admin database:</p> <p>Type: <code>mongod</code> in a terminal to run db, and then in another terminal run command <code>mongo</code> to run access mongo terminal</p> <pre><code>use admin db.createUser( { user: &quot;root&quot;, pwd: &quot;pass123&quot;, roles: [ { role: &quot;userAdminAnyDatabase&quot;, db: &quot;admin&quot; }, &quot;readWriteAnyDatabase&quot; ] } ) </code></pre> <p>Now create a database:</p> <p>Run the <code>use</code> statement. If the database doesn't already exist, it will be created</p> <p>use writeapp</p> <p>To confirm the database created, you must insert some data otherwise it will not be created. <code>db.testcollection.insert({ artist: &quot;Mike&quot; })</code></p> <p>After that you have created root user and a new db. Now change mongodb config</p> <pre><code>nano /etc/mongod.conf </code></pre> <p>Change the line to:</p> <pre><code>security: authorization: &quot;enabled&quot; </code></pre> <p>Now restart the db service from a terminal.</p> <p><code>sudo systemctl restart mongod</code></p> <p>check the status:</p> <p><code>sudo systemctl status mongod</code></p> <p>From now you need password to login to mongo</p> <p><code>mongo -u root -p pass123 --authenticationDatabase admin</code></p> <p>Let now create a user in admin database but also give admin privilege to a specific database like writeapp</p> <pre><code>`use admin` `db.createUser({user:&quot;writetApp&quot;, pwd:&quot;writeApp5299&quot;, roles:[{role:&quot;dbOwner&quot;, db:&quot;writeapp&quot;}]});` </code></pre> <p>To check the user:</p> <pre><code>db.getUsers(); [ { &quot;_id&quot; : &quot;admin.root&quot;, &quot;userId&quot; : UUID(&quot;8f6c1295-a261-4057-9a29-8a9919437841&quot;), &quot;user&quot; : &quot;root&quot;, &quot;db&quot; : &quot;admin&quot;, &quot;roles&quot; : [ { &quot;role&quot; : &quot;userAdminAnyDatabase&quot;, &quot;db&quot; : &quot;admin&quot; } ], &quot;mechanisms&quot; : [ &quot;SCRAM-SHA-1&quot;, &quot;SCRAM-SHA-256&quot; ] }, { &quot;_id&quot; : &quot;admin.writeApp&quot;, &quot;userId&quot; : UUID(&quot;ee148506-1860-4739-80db-17352e0e2ccb&quot;), &quot;user&quot; : &quot;writeApp&quot;, &quot;db&quot; : &quot;admin&quot;, &quot;roles&quot; : [ { &quot;role&quot; : &quot;dbOwner&quot;, &quot;db&quot; : &quot;writeapp&quot; } ], &quot;mechanisms&quot; : [ &quot;SCRAM-SHA-1&quot;, &quot;SCRAM-SHA-256&quot; ] } </code></pre> <p>Exit from mongo and login</p> <pre><code>`mongo -u &quot;writeApp&quot; -p writeApp5299 --authenticationDatabase &quot;admin&quot;` </code></pre> <p>Now if you have created the user in other db rather than admin then <code>--authenticationDatabase &quot;yourdbname&quot;</code></p> <p>Now to execute command from mongo.</p> <pre><code> `use writeapp` ` db.testcollection.find();` </code></pre> <hr /> <p><strong>2. How to connect from node.js:</strong></p> <p>Procedure1:</p> <p><code>const mongoURI = 'mongodb://writeApp:writeApp5299@127.0.0.1:27017/writeapp';</code></p> <p><code>const db = mongoose.connect(mongoURI, { useNewUrlParser: true });</code></p> <p>Procedure2:</p> <p><code>mongoose.connect('mongodb://writeApp:writeApp5299@127.0.0.1:27017/writeapp?auththSource=writeapp&amp;w=1',{ useNewUrlParser: true });</code></p> <p>Both works either you use <code>authSource</code> or not, not a problem at all:</p> <p>The Problem: server.js or app.js runs first in any node.js app or the entry point which loads all modules/middleware/routes etc.<br /> Now if any of the route has another mongodb connect which has issue, the application error simply shows the error that I showed:</p> <pre><code>command find/insert/update requires authentication </code></pre> <p>But the problem is it does not show which file has the issue. So it was time-consuming to look for the issue in each route. So the problem is solved</p>
4,813,728
Change individual markers in google maps directions api V3
<p>I'm looking to change the marker icons when using the DirectionsRender within a google map. I've figured out from <a href="https://stackoverflow.com/questions/4312961/how-do-i-change-the-start-and-end-marker-image-in-google-maps-v3-api-for-directio">here</a> how to change both the markers to the same icon, but I am looking for custom icons on both the start and end points. Any ideas?</p> <p>Edit: I'm looking for how to assign separate icons to the start and end markers. I know how to change it for both, but having different marker icons is proving difficult.</p>
5,199,909
2
0
null
2011-01-27 07:23:52.35 UTC
17
2015-05-30 14:56:55.517 UTC
2017-05-23 12:25:48.28 UTC
null
-1
null
110,313
null
1
34
javascript|google-maps|google-maps-api-3
57,355
<p>For those that need an example like I did, here's a basic one:</p> <pre><code> // Map and directions objects var map = new google.maps.Map( element, options ); var service = new google.maps.DirectionsService(); var directions = new google.maps.DirectionsRenderer({suppressMarkers: true}); // Start/Finish icons var icons = { start: new google.maps.MarkerImage( // URL 'start.png', // (width,height) new google.maps.Size( 44, 32 ), // The origin point (x,y) new google.maps.Point( 0, 0 ), // The anchor point (x,y) new google.maps.Point( 22, 32 ) ), end: new google.maps.MarkerImage( // URL 'end.png', // (width,height) new google.maps.Size( 44, 32 ), // The origin point (x,y) new google.maps.Point( 0, 0 ), // The anchor point (x,y) new google.maps.Point( 22, 32 ) ) }; service.route( { origin: origin, destination: destination }, function( response, status ) { if ( status == google.maps.DirectionsStatus.OK ) { display.setDirections( response ); var leg = response.routes[ 0 ].legs[ 0 ]; makeMarker( leg.start_location, icons.start, "title" ); makeMarker( leg.end_location, icons.end, 'title' ); } }); function makeMarker( position, icon, title ) { new google.maps.Marker({ position: position, map: map, icon: icon, title: title }); } </code></pre> <p>The response from a route request returns a leg(s) depending on the number of stops on your route. I am only doing a A to B route, so just take the first leg, and get the position of where the markers need to go, and create markers for those spots.</p>
9,845,833
Do multiple Solr shards on a single machine improve performance?
<p>Does running multiple Solr shards on a single machine improve performance? I would expect Lucene to be multi-threaded, but it doesn't seem to be using more than a single core on my server with 16 physical cores. I realize this is workload dependent, but any statistics or benchmarks would be very useful!</p>
9,856,105
2
5
null
2012-03-23 20:05:06.607 UTC
8
2012-04-21 17:14:05.157 UTC
2012-04-21 17:14:05.157 UTC
null
968,269
null
968,269
null
1
14
performance|solr|lucene
3,985
<p>I ran some <a href="http://carsabi.com/car-news/2012/03/23/optimizing-solr-7x-your-search-speed/" rel="noreferrer">benchmarks of our search stack</a>, and found that adding more Solr shards (on a single machine, with 16 physical cores) did improve performance up to about 8 shards (where I got a 6.5x speed up). This is on an index with ~1.5million documents, running complex range queries.</p> <p>So, it seems that Solr doesn't take advantage of multiple physical cores, when running queries against a single index.</p>
9,719,078
After postback my JavaScript function doesn't work in ASP.NET
<p>I have common functions and I collapse it on <code>CommonFunctions.js</code> in Scripts folder.</p> <p>I include it on my master page and use it on my pages. When I do any post back on a page, my function doesn't work.</p> <p>My <code>CommonFunctions.js</code>:</p> <pre><code>$(function () { gf(); if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) { gf(); } function gf(){ $('.AddNewGeneralPanel').click(function () { if ($(this).find('.AddNewGeneralPanelStyle').text() == &quot;&quot;) { $(this).find('.AddNewGeneralPanelStyle').text(&quot;( Gizle )&quot;); lastOpenId = $(this).attr(&quot;codeid&quot;); } else $(this).find('.AddNewGeneralPanelStyle').text(&quot;&quot;); $(this).next('.AddNewGeneralAccordionDiv').slideToggle('slow', function () { }); }); } }); </code></pre>
9,719,201
7
4
null
2012-03-15 11:50:39.217 UTC
1
2021-06-10 07:58:33.413 UTC
2021-06-10 07:58:33.413 UTC
null
714,869
null
714,869
null
1
16
c#|jquery|asp.net|postback
49,895
<p>Since you're using an <code>UpdatePanel</code>, the part of the DOM that you've attached your event handler to is getting dropped and recreated after the postback. This has the effect of removing any event handlers that were attached by jQuery when the page first loaded.</p> <p>When you postback only part of the page, the jQuery <code>$(function() {});</code> doesn't fire again, so your handlers never get reattached.</p> <p>Here's a <a href="https://stackoverflow.com/questions/256195/jquery-document-ready-and-updatepanels">related question</a> that shows how to resubscribe your events when the <code>UpdatePanel</code> refreshes.</p>
9,972,769
Start Broadcast Receiver from an activity in android
<p>I would like to start a broadcast receiver from an activity. I have a Second.java file which extends a broadcast receiver and a Main.java file from which I have to initiate the broadcast receiver. I also tried doing everything in Main.java as follows but didn't know how to define in manifest file... </p> <h2>Main.java:</h2> <pre><code>public class Main extends Activity { /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String rec_data = "Nothing Received"; private BroadcastReceiver myReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub if( intent.getStringExtra("send_data")!=null) rec_data = intent.getStringExtra("send_data"); Log.d("Received Msg : ",rec_data); } }; } protected void onResume() { IntentFilter intentFilter = new IntentFilter(); //intentFilter.addDataType(String); registerReceiver(myReceiver, intentFilter); super.onResume(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); this.unregisterReceiver(this.myReceiver); } } </code></pre> <p>If I cannot do everything in one class as above, how can I call the Broadcast Receiver from Main.java? Can anyone please let me know where I'm doing it wrong? Thanks!</p>
9,973,059
4
1
null
2012-04-02 08:01:11.96 UTC
6
2018-01-26 10:50:13.72 UTC
null
null
null
null
1,294,721
null
1
18
android|broadcastreceiver
52,472
<p>use this why to send a custom broadcast:</p> <p>Define an action name:</p> <pre><code>public static final String BROADCAST = "PACKAGE_NAME.android.action.broadcast"; </code></pre> <p>AndroidManifest.xml register receiver :</p> <pre><code>&lt;receiver android:name=".myReceiver" &gt; &lt;intent-filter &gt; &lt;action android:name="PACKAGE_NAME.android.action.broadcast"/&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p>Register Reciver :</p> <pre><code>IntentFilter intentFilter = new IntentFilter(BROADCAST); registerReceiver( myReceiver , intentFilter); </code></pre> <p>send broadcast from your Activity :</p> <pre><code>Intent intent = new Intent(BROADCAST); Bundle extras = new Bundle(); extras.putString("send_data", "test"); intent.putExtras(extras); sendBroadcast(intent); </code></pre> <p>YOUR BroadcastReceiver :</p> <pre><code>private BroadcastReceiver myReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle extras = intent.getExtras(); if (extras != null){ { rec_data = extras.getString("send_data"); Log.d("Received Msg : ",rec_data); } } }; </code></pre> <p>for more information for Custom Broadcast see <a href="http://thinkandroid.wordpress.com/2010/02/02/custom-intents-and-broadcasting-with-receivers/">Custom Intents and Broadcasting with Receivers</a></p>
9,802,736
Maven build [WARNING] we have a duplicate class
<p>Anybody has any idea what happened to my maven build? I am getting a lot of duplicate warnings.</p> <pre><code>[WARNING] We have a duplicate org/apache/commons/logging/impl/LogFactoryImpl$1.class in /home/shengjie/.m2/repository/commons-logging/commons-logging-api/1.0.4/commons-logging-api-1.0.4.jar [WARNING] We have a duplicate org/apache/commons/logging/impl/LogFactoryImpl.class in /home/shengjie/.m2/repository/commons-logging/commons-logging-api/1.0.4/commons-logging-api-1.0.4.jar [WARNING] We have a duplicate org/apache/commons/logging/impl/NoOpLog.class in /home/shengjie/.m2/repository/commons-logging/commons-logging-api/1.0.4/commons-logging-api-1.0.4.jar [WARNING] We have a duplicate org/apache/commons/logging/impl/SimpleLog$1.class in /home/shengjie/.m2/repository/commons-logging/commons-logging-api/1.0.4/commons-logging-api-1.0.4.jar [WARNING] We have a duplicate org/apache/commons/logging/impl/SimpleLog.class in /home/shengjie/.m2/repository/commons-logging/commons-logging-api/1.0.4/commons-logging-api-1.0.4.jar [WARNING] We have a duplicate org/apache/commons/logging/impl/Jdk14Logger.class in /home/shengjie/.m2/repository/commons-logging/commons-logging-api/1.0.4/commons-logging-api-1.0.4.jar </code></pre> <p>I've looked into my local m2 repo, I have two classes there in commons-logging-api jar, LogFactoryImpl.class and LogFactoryImpl$1.class. Same as all the classes mentioned in the warnings.</p> <p>One thing to mention is that I am using shade plugin in my pom.xml.</p> <pre><code> &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-shade-plugin&lt;/artifactId&gt; &lt;version&gt;1.4&lt;/version&gt; &lt;configuration&gt; &lt;createDependencyReducedPom&gt;true&lt;/createDependencyReducedPom&gt; &lt;filters&gt; &lt;filter&gt; &lt;artifact&gt;*:*&lt;/artifact&gt; &lt;excludes&gt; &lt;exclude&gt;META-INF/*.SF&lt;/exclude&gt; &lt;exclude&gt;META-INF/*.DSA&lt;/exclude&gt; &lt;exclude&gt;META-INF/*.RSA&lt;/exclude&gt; &lt;/excludes&gt; &lt;/filter&gt; &lt;/filters&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;shade&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;transformers&gt; &lt;transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" /&gt; &lt;transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"&gt; &lt;mainClass&gt;com.~~~~black out my own main class here~~~~~&lt;/mainClass&gt; &lt;/transformer&gt; &lt;/transformers&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>I noticed that the dependency tree looks like as below</p> <pre><code>[INFO] +- org.apache.cxf:cxf-bundle-jaxrs:jar:2.5.1:compile [INFO] | \- commons-logging:commons-logging:jar:1.1.1:compile [INFO] \- org.apache.hadoop.hive:hive-jdbc:jar:0.7.1-cdh3u3:compile [INFO] \- org.apache.hadoop.hive:hive-common:jar:0.7.1-cdh3u3:compile [INFO] \- commons-logging:commons-logging-api:jar:1.0.4:compile </code></pre> <p>and commons-logging.jar and commons-logging-api.jar both have org/apache/commons/logging/LogFactory.class. </p> <p>somehow Shad plugin is trying to squeeze them in to a big fat jar at the end. then the warning is showing up. It's been said this is ignorable warning. But I am a bit worried, How does the application know what is the exact class should be used if there are two duplicated class with the same name?</p>
9,807,806
8
1
null
2012-03-21 10:30:44.99 UTC
4
2018-09-15 17:13:38.213 UTC
2016-03-18 21:35:55.077 UTC
null
658,663
null
1,275,937
null
1
31
maven|build|maven-shade-plugin|apache-commons-logging
41,845
<p>Take a look at the "Dependency Exclusions" section in the <a href="http://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html" rel="noreferrer">Maven doc</a>.</p> <p>In your provided example, I'll exclude the <code>commons-logging:commons-logging-api:jar:1.0.4:compile</code> dependency from <code>org.apache.hadoop.hive:hive-common:jar:0.7.1-cdh3u3:compile</code>. In your pom.xml :</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;org.apache.hadoop.hive&lt;/groupId&gt; &lt;artifactId&gt;hive-common:jar&lt;/artifactId&gt; &lt;version&gt;0.7.1-cdh3u3&lt;/version&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;commons-logging&lt;/groupId&gt; &lt;artifactId&gt;commons-logging-api&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; </code></pre>
10,095,219
How to test nginx subdomains on localhost
<p>I want to test nginx subdomains before uploading config to the server. Can i test it on localhost? I try</p> <pre><code>server { listen 80; server_name localhost; location / { proxy_pass http://localhost:8080; } } server { listen 80; server_name sub.localhost; location / { proxy_pass http://localhost:8080/sub; } } </code></pre> <p>And it does not work. Shoulld i change my hosts file in order to make it work? Also, after uploading site to the server should i change DNS records and add sub.mydomain.com?</p>
10,409,774
4
0
null
2012-04-10 19:34:26.447 UTC
12
2022-06-14 15:32:48.457 UTC
null
null
null
null
750,510
null
1
37
nginx|subdomain
38,953
<p>Yes, add '127.0.0.1 sub.localhost' to your hosts file. That sub has to be resolved somehow. That should work.</p> <p>Then once you're ready to go to the net, yes, add an a or cname record for the subdomain sub.</p> <p>When I use proxy_pass I also include the proxy.conf from nginx. <a href="http://wiki.nginx.org/HttpProxyModule" rel="noreferrer">http://wiki.nginx.org/HttpProxyModule</a></p>
27,987,048
Shake Animation for UITextField/UIView in Swift
<p>I am trying to figure out how to make the text Field shake on button press when the user leaves the text field blank.</p> <p>I currently have the following code working:</p> <pre><code>if self.subTotalAmountData.text == "" { let alertController = UIAlertController(title: "Title", message: "What is the Sub-Total!", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } else { } </code></pre> <p>But i think it would be much more appealing to just have the text field shake as an alert.</p> <p>I can't find anything to animate the text field.</p> <p>Any ideas?</p> <p>Thanks!</p>
27,988,876
10
4
null
2015-01-16 15:15:25.673 UTC
37
2020-09-28 18:21:52.203 UTC
2015-01-16 17:26:22.843 UTC
null
2,224,577
null
4,454,828
null
1
71
ios|swift|uitextfield
53,446
<p>You can change the <code>duration</code> and <code>repeatCount</code> and tweak it. This is what I use in my code. Varying the <code>fromValue</code> and <code>toValue</code> will vary the distance moved in the shake.</p> <pre><code>let animation = CABasicAnimation(keyPath: "position") animation.duration = 0.07 animation.repeatCount = 4 animation.autoreverses = true animation.fromValue = NSValue(cgPoint: CGPoint(x: viewToShake.center.x - 10, y: viewToShake.center.y)) animation.toValue = NSValue(cgPoint: CGPoint(x: viewToShake.center.x + 10, y: viewToShake.center.y)) viewToShake.layer.add(animation, forKey: "position") </code></pre>
28,042,426
Spring Boot - Error creating bean with name 'dataSource' defined in class path resource
<p>I have Spring Boot web application. It's centered around RESTful approach. All configuration seems in place but for some reason MainController fails to handle request. It results in 404 error. How to fix it?</p> <pre><code>@Controller public class MainController { @Autowired ParserService parserService; @RequestMapping(value=&quot;/&quot;, method= RequestMethod.GET) public @ResponseBody String displayStartPage(){ return &quot;{hello}&quot;; } } </code></pre> <p><strong>Application</strong></p> <pre><code>@Configuration @ComponentScan(basePackages = &quot;&quot;) @EnableAutoConfiguration public class Application extends SpringBootServletInitializer{ public static void main(final String[] args) { SpringApplication.run(Application.class, args); } @Override protected final SpringApplicationBuilder configure(final SpringApplicationBuilder application) { return application.sources(Application.class); } } </code></pre> <p><strong>ParserController</strong></p> <pre><code>@RestController public class ParserController { @Autowired private ParserService parserService; @Autowired private RecordDao recordDao; private static final Logger LOG = Logger.getLogger(ParserController.class); @RequestMapping(value=&quot;/upload&quot;, method= RequestMethod.POST) public @ResponseBody String fileUploadPage( } } </code></pre> <p><strong>UPDATE</strong></p> <p>Seems like MySQL cannot be initialized by Spring....</p> <pre><code> Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. </code></pre> <p><strong>UPDATE2</strong></p> <p><strong>application.properties</strong></p> <pre class="lang-yml prettyprint-override"><code> # Database spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/logparser spring.datasource.username = root spring.datasource.password = root spring.jpa.database = MYSQL spring.jpa.show-sql = true # Hibernate hibernate.dialect: org.hibernate.dialect.MySQL5Dialect hibernate.show_sql: true hibernate.hbm2ddl.auto: update entitymanager.packagesToScan: / </code></pre> <p><strong>UPDATE4</strong></p> <p>Seems lite controllers not responding eventhough <code>@RequestMapping</code> are set. Why might it be?</p> <blockquote> <p>PS. It occurs when I run Maven's lifecycle <code>test</code>. When running in degub mode in IntelliJ there is no error outputted.</p> </blockquote> <p><strong>UPDATE5</strong></p> <p>Also I use this DAO as explained in tutorial....</p> <pre><code>public interface RecordDao extends CrudRepository&lt;Record, Long&gt; { } </code></pre> <p><a href="http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/" rel="noreferrer">http://blog.netgloo.com/2014/10/27/using-mysql-in-spring-boot-via-spring-data-jpa-and-hibernate/</a></p> <p><strong>UPDATE6</strong></p> <p>I did changed my application properties. And tried every single combination but it refuses to work. ;(</p> <p><strong>Maven output:</strong></p> <pre><code>------------------------------------------------------- T E S T S ------------------------------------------------------- Running IntegrationTest Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 2.365 sec &lt;&lt;&lt; FAILURE! - in IntegrationTest saveParsedRecordsToDatabase(IntegrationTest) Time elapsed: 2.01 sec &lt;&lt;&lt; ERROR! java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99) at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109) at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176) at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:264) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124) at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200) at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153) at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration$NonEmbeddedConfiguration.dataSource()] threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. </code></pre>
31,199,853
28
6
null
2015-01-20 09:59:44.7 UTC
26
2022-09-22 12:23:11.8 UTC
2021-10-29 05:57:06.693 UTC
null
1,155,514
null
480,632
null
1
94
java|spring|spring-boot
603,106
<p>Looks like the initial problem is with the auto-config.</p> <p>If you don't need the datasource, simply remove it from the auto-config process:</p> <pre><code>@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) </code></pre> <p>Edit: If using @SpringBootApplication in your main class:</p> <pre><code>@SpringBootApplication(exclude={DataSourceAutoConfiguration.class}) </code></pre>
10,147,455
How to send an email with Gmail as provider using Python?
<p>I am trying to send email (Gmail) using python, but I am getting following error.</p> <pre><code>Traceback (most recent call last): File "emailSend.py", line 14, in &lt;module&gt; server.login(username,password) File "/usr/lib/python2.5/smtplib.py", line 554, in login raise SMTPException("SMTP AUTH extension not supported by server.") smtplib.SMTPException: SMTP AUTH extension not supported by server. </code></pre> <p>The Python script is the following.</p> <pre><code>import smtplib fromaddr = 'user_me@gmail.com' toaddrs = 'user_you@gmail.com' msg = 'Why,Oh why!' username = 'user_me@gmail.com' password = 'pwd' server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(username,password) server.sendmail(fromaddr, toaddrs, msg) server.quit() </code></pre>
10,147,497
16
1
null
2012-04-13 19:54:18.263 UTC
162
2022-07-01 18:12:00.457 UTC
2022-02-06 15:35:32.48 UTC
null
8,172,439
null
869,240
null
1
316
python|email|smtp|gmail|smtp-auth
403,594
<p>You need to say <code>EHLO</code> before just running straight into <code>STARTTLS</code>:</p> <pre><code>server = smtplib.SMTP('smtp.gmail.com:587') server.ehlo() server.starttls() </code></pre> <hr /> <p>Also you should really create <code>From:</code>, <code>To:</code> and <code>Subject:</code> message headers, separated from the message body by a blank line and use <code>CRLF</code> as EOL markers.</p> <p>E.g.</p> <pre><code>msg = &quot;\r\n&quot;.join([ &quot;From: user_me@gmail.com&quot;, &quot;To: user_you@gmail.com&quot;, &quot;Subject: Just a message&quot;, &quot;&quot;, &quot;Why, oh why&quot; ]) </code></pre> <p><strong>Note:</strong></p> <p>In order for this to work you need to enable &quot;Allow less secure apps&quot; option in your gmail account configuration. Otherwise you will get a &quot;critical security alert&quot; when gmail detects that a non-Google apps is trying to login your account.</p>
10,124,679
What happens if I read a map's value where the key does not exist?
<pre><code>map&lt;string, string&gt; dada; dada["dummy"] = "papy"; cout &lt;&lt; dada["pootoo"]; </code></pre> <p>I'm puzzled because I don't know if it's considered undefined behaviour or not, how to know when I request a key which does not exist, do I just use find instead ?</p>
10,124,703
7
0
null
2012-04-12 13:33:31.93 UTC
14
2019-07-08 18:22:15.567 UTC
null
null
null
null
414,063
null
1
116
c++|map
106,962
<p>The <code>map::operator[]</code> searches the data structure for a value corresponding to the given key, and returns a reference to it.</p> <p>If it can't find one it transparently creates a default constructed element for it. (If you do not want this behaviour you can use the <code>map::at</code> function instead.)</p> <p>You can get a full list of methods of std::map here:</p> <p><a href="http://en.cppreference.com/w/cpp/container/map" rel="noreferrer">http://en.cppreference.com/w/cpp/container/map</a></p> <p>Here is the documentation of <code>map::operator[]</code> from the current C++ standard...</p> <h3>23.4.4.3 Map Element Access</h3> <h3><code>T&amp; operator[](const key_type&amp; x);</code></h3> <ol> <li><p>Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.</p></li> <li><p>Requires: key_type shall be CopyConstructible and mapped_type shall be DefaultConstructible.</p></li> <li><p>Returns: A reference to the mapped_type corresponding to x in *this.</p></li> <li><p>Complexity: logarithmic.</p></li> </ol> <h3><code>T&amp; operator[](key_type&amp;&amp; x);</code></h3> <ol> <li><p>Effects: If there is no key equivalent to x in the map, inserts value_type(std::move(x), T()) into the map.</p></li> <li><p>Requires: mapped_type shall be DefaultConstructible.</p></li> <li><p>Returns: A reference to the mapped_type corresponding to x in *this.</p></li> <li><p>Complexity: logarithmic.</p></li> </ol>
10,024,866
Remove Object from Array using JavaScript
<p>How can I remove an object from an array? I wish to remove the object that includes name <code>Kristian</code> from <code>someArray</code>. For example:</p> <pre><code>someArray = [{name:&quot;Kristian&quot;, lines:&quot;2,5,10&quot;}, {name:&quot;John&quot;, lines:&quot;1,19,26,96&quot;}]; </code></pre> <p>I want to achieve:</p> <pre><code>someArray = [{name:&quot;John&quot;, lines:&quot;1,19,26,96&quot;}]; </code></pre>
10,024,926
32
0
null
2012-04-05 08:07:51.663 UTC
164
2022-08-23 08:51:54.817 UTC
2021-01-27 19:33:45.447 UTC
null
860,099
null
1,269,179
null
1
737
javascript|arrays
1,384,555
<p>You can use several methods to remove item(s) from an Array:</p> <pre><code>//1 someArray.shift(); // first element removed //2 someArray = someArray.slice(1); // first element removed //3 someArray.splice(0, 1); // first element removed //4 someArray.pop(); // last element removed //5 someArray = someArray.slice(0, someArray.length - 1); // last element removed //6 someArray.length = someArray.length - 1; // last element removed </code></pre> <p>If you want to remove element at position <code>x</code>, use:</p> <pre><code>someArray.splice(x, 1); </code></pre> <p>Or</p> <pre><code>someArray = someArray.slice(0, x).concat(someArray.slice(-x)); </code></pre> <p>Reply to the comment of <a href="https://stackoverflow.com/users/995721/chill182">@chill182</a>: you can remove one or more elements from an array using <code>Array.filter</code>, or <code>Array.splice</code> combined with <code>Array.findIndex</code> (see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="nofollow noreferrer"><strong>MDN</strong></a>).</p> <p>See this <a href="https://stackblitz.com/edit/web-platform-7qzbck?file=script.js" rel="nofollow noreferrer">Stackblitz project</a> or the snippet below:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// non destructive filter &gt; noJohn = John removed, but someArray will not change let someArray = getArray(); let noJohn = someArray.filter( el =&gt; el.name !== "John" ); log(`let noJohn = someArray.filter( el =&gt; el.name !== "John")`, `non destructive filter [noJohn] =`, format(noJohn)); log(`**someArray.length ${someArray.length}`); // destructive filter/reassign John removed &gt; someArray2 = let someArray2 = getArray(); someArray2 = someArray2.filter( el =&gt; el.name !== "John" ); log("", `someArray2 = someArray2.filter( el =&gt; el.name !== "John" )`, `destructive filter/reassign John removed [someArray2] =`, format(someArray2)); log(`**someArray2.length after filter ${someArray2.length}`); // destructive splice /w findIndex Brian remains &gt; someArray3 = let someArray3 = getArray(); someArray3.splice(someArray3.findIndex(v =&gt; v.name === "Kristian"), 1); someArray3.splice(someArray3.findIndex(v =&gt; v.name === "John"), 1); log("", `someArray3.splice(someArray3.findIndex(v =&gt; v.name === "Kristian"), 1),`, `destructive splice /w findIndex Brian remains [someArray3] =`, format(someArray3)); log(`**someArray3.length after splice ${someArray3.length}`); // if you're not sure about the contents of your array, // you should check the results of findIndex first let someArray4 = getArray(); const indx = someArray4.findIndex(v =&gt; v.name === "Michael"); someArray4.splice(indx, indx &gt;= 0 ? 1 : 0); log("", `someArray4.splice(indx, indx &gt;= 0 ? 1 : 0)`, `check findIndex result first [someArray4] = (nothing is removed)`, format(someArray4)); log(`**someArray4.length (should still be 3) ${someArray4.length}`); // -- helpers -- function format(obj) { return JSON.stringify(obj, null, " "); } function log(...txt) { document.querySelector("pre").textContent += `${txt.join("\n")}\n` } function getArray() { return [ {name: "Kristian", lines: "2,5,10"}, {name: "John", lines: "1,19,26,96"}, {name: "Brian", lines: "3,9,62,36"} ]; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;pre&gt; **Results** &lt;/pre&gt;</code></pre> </div> </div> </p>
11,931,633
CakePHP find condition for a query between two dates
<p>I have a start and an end date in my database and a $date variable from a form field. I am now trying to query all the rows where $date is either = start/end date in the db, or ANY date between those two.</p> <p>It's kind of the opposite of what is described in the docs of how daysAsSql works. I can't figure out how to get it to work. The following line does not work as a find condition in the controller:</p> <pre><code>'? BETWEEN ? AND ?' =&gt; array($date, 'Item.date_start', 'Item.date_end'), </code></pre> <p>Any help is greatly appreciated. This is driving me crazy.</p> <p>Here is the complete Query and corresponding SQL:</p> <pre><code>$conditions = array( 'conditions' =&gt; array( 'and' =&gt; array( '? BETWEEN ? AND ?' =&gt; array($date, 'Item.date_start', 'Item.date_end'), 'Item.title LIKE' =&gt; "%$title%", 'Item.status_id =' =&gt; '1' ))); $this-&gt;set('items', $this-&gt;Item-&gt;find('all', $conditions)); WHERE (('2012-10-06' BETWEEN 'Item.date_start' AND 'Item.date_end') AND (`Item`.`title` LIKE '%%') AND (`Item`.`status_id` = 1)) </code></pre>
11,932,226
6
4
null
2012-08-13 09:38:29.453 UTC
5
2019-03-05 12:37:49.747 UTC
2012-08-13 10:03:33.383 UTC
null
1,456,294
null
1,456,294
null
1
11
cakephp|date|time|between
51,514
<pre><code>$conditions = array( 'conditions' =&gt; array( 'and' =&gt; array( array('Item.date_start &lt;= ' =&gt; $date, 'Item.date_end &gt;= ' =&gt; $date ), 'Item.title LIKE' =&gt; "%$title%", 'Item.status_id =' =&gt; '1' ))); </code></pre> <p>Try the above code and ask if it not worked for you.</p> <p><strong>Edit:</strong> As per @Aryan request, if we have to find users registered between 1 month:</p> <pre><code>$start_date = '2013-05-26'; //should be in YYYY-MM-DD format $this-&gt;User-&gt;find('all', array('conditions' =&gt; array('User.reg_date BETWEEN '.$start_date.' AND DATE_ADD('.$start_date.', INTERVAL 30 DAY)'))); </code></pre>
11,567,176
How do you set up .vimrc
<p>How do you set up a .vimrc file on Ubuntu?</p> <p>This is not helping: <a href="http://vim.wikia.com/wiki/Open_vimrc_file" rel="noreferrer">http://vim.wikia.com/wiki/Open_vimrc_file</a></p> <ol> <li>Where do you create it?</li> <li>Whats the format inside?</li> </ol> <p>I know the stuff I want to put in it, just don't know how.</p>
11,567,239
4
1
null
2012-07-19 18:34:25.393 UTC
16
2018-11-02 20:16:26.913 UTC
2012-07-19 19:23:36.05 UTC
null
275,567
null
693,950
null
1
30
ubuntu|vim
94,836
<p><strong>Where:</strong></p> <p>On UN*X systems your .vimrc belongs in your <em>home directory</em>. At a terminal, type:</p> <pre><code>cd $HOME vim .vimrc </code></pre> <p>This will change to your home directory and open .vimrc using vim. In vim, add the commands that you know you want to put in, then type <code>:wq</code> to save the file.</p> <p>Now open vim again. Once in vim you can just type: <code>:scriptnames</code> to print a list of scripts that have been sourced. The full path to your .vimrc should be in that list. As an additional check that your commands have been executed, you can:</p> <ul> <li>add an <code>echo "MY VIMRC LOADED"</code> command to the .vimrc, and when you run vim again, you should see <em>MY VIMRC LOADED</em> printed in the terminal. Remove the <code>echo</code> command once you've verified that your.vimrc is loading. </li> <li>set a variable in your .vimrc that you can <code>echo</code> once vim is loaded. In the .vimrc add a line like <code>let myvar="MY VIMRC LOADED"</code>. Then once you've opened vim type <code>echo myvar</code> in the command line. You should see your message.</li> </ul> <p><strong>The Format:</strong></p> <p>The format of your .vimrc is that it contains Ex commands: anything that you might type in the vim command-line following <code>:</code>, but in your .vimrc, leave off the <code>:</code>.</p> <p>You've mentioned <code>:set ruler</code>: a .vimrc with only this command looks like:</p> <pre><code>set ruler </code></pre> <p>Search for <em>example vimrc</em> and look over the results. <a href="http://vim.wikia.com/wiki/Example_vimrc" rel="noreferrer">This link</a> is a good starting point.</p>
11,457,670
Where are the headers of the C++ standard library
<p>I wonder where on my file system I find the headers of the C++ Standard library. In particular I am looking for the definition of the vector template. I searched in /usr/include/ and various subdirectories. I also tried 'locate vector.h' which brought up many implementations of vectors, but not the standard one. What am I missing? (The distribution is Gentoo)</p> <p>Background: I'm profiling a library that iterates over vector's most of the time and gprof shows that most of the time is spent in </p> <pre><code>std::vector&lt;int, std::allocator&lt;int&gt; &gt;::_M_insert_aux( __gnu_cxx::__normal_iterator&lt;int*, std::vector&lt; int, std::allocator&lt;int&gt; &gt; &gt;, int const&amp;) </code></pre> <p>Probably this is what happens internally on a std::vector::push_back, but I'm not sure.</p>
11,457,817
6
1
null
2012-07-12 17:52:17.123 UTC
12
2019-12-27 08:23:32.627 UTC
2018-02-20 21:36:18.547 UTC
null
608,639
null
447,839
null
1
37
c++|linux|stl|header-files|c++-standard-library
77,563
<p>GCC typically has the standard C++ headers installed in <code>/usr/include/c++/&lt;version&gt;/</code>. You can run <code>gcc -v</code> to find out which version you have installed.</p> <p>At least in my version, there is no <code>vector.h</code>; the public header is just <code>vector</code> (with no extension), and most of the implementation is in <code>bits/stl_vector.h</code>.</p> <p>That's the case on my Ubuntu distribution; your distribution may differ.</p>
11,944,745
ASP.NET Bundles how to disable minification
<p>I have <code>debug="true"</code> in both my <em>web.config(s)</em>, and I just don't want my bundles minified, but nothing I do seems to disable it. I've tried <code>enableoptimisations=false</code>, here is my code:</p> <pre><code>//Javascript bundles.Add(new ScriptBundle("~/bundles/MainJS") .Include("~/Scripts/regular/lib/mvc/jquery.validate.unobtrusive.js*") .Include("~/Scripts/regular/lib/mvc/jquery.validate*") .Include("~/Scripts/regular/lib/bootstrap.js") .IncludeDirectory("~/Scripts/regular/modules", "*.js", true) .IncludeDirectory("~/Scripts/regular/pages", "*.js", true) .IncludeDirectory("~/Scripts/regular/misc", "*.js", true)); //CSS bundles.Add(new StyleBundle("~/bundles/MainCSS") .Include("~/Content/css/regular/lib/bootstrap.css*") .IncludeDirectory("~/Content/css/regular/modules", "*.css", true) .IncludeDirectory("~/Content/css/regular/pages", "*.css", true)) </code></pre>
11,960,820
14
2
null
2012-08-14 01:55:17.2 UTC
42
2020-12-01 21:14:54.93 UTC
2016-05-09 05:31:36.36 UTC
null
863,110
null
314,963
null
1
201
asp.net|asp.net-mvc|asp.net-mvc-4|bundle|asp.net-optimization
158,657
<p>If you have <code>debug="true"</code> in <em>web.config</em> and are using <code>Scripts/Styles.Render</code> to reference the bundles in your pages, that should turn off both bundling and minification. <code>BundleTable.EnableOptimizations = false</code> will always turn off both bundling and minification as well (irrespective of the debug true/false flag). </p> <p>Are you perhaps not using the <code>Scripts/Styles.Render</code> helpers? If you are directly rendering references to the bundle via <code>BundleTable.Bundles.ResolveBundleUrl()</code> you will always get the minified/bundled content.</p>
19,973,037
Benchmark memory usage in PHP
<p>Let us suppose that we have some problem and at least two solutions for it. And what we want to achieve - is to compare effectiveness for them. How to do this? Obviously, the best answer is: <em>do tests</em>. And I doubt there's a better way when it comes to language-specific questions (for example &quot;what is faster for PHP: <code>echo 'foo', 'bar'</code> or <code>echo('foo'.'bar')</code>&quot;).</p> <p>Ok, now we'll assume that if we want to test some code, it's equal to test some function. Why? Because we can wrap that code to function and pass it's context (if any) as it's parameters. Thus, all we need - is to have, for example, some benchmark function which will do all stuff. Here's very simple one:</p> <pre><code>function benchmark(callable $function, $args=null, $count=1) { $time = microtime(1); for($i=0; $i&lt;$count; $i++) { $result = is_array($args)? call_user_func_array($function, $args): call_user_func_array($function); } return [ 'total_time' =&gt; microtime(1) - $time, 'average_time' =&gt; (microtime(1) - $time)/$count, 'count' =&gt; $count ]; } </code></pre> <p>-this will fit our issue and can be used to do <em>comparative</em> benchmarks. Under <em>comparative</em> I mean that we can use function above for code <code>X</code>, then for code <code>Y</code> and, after that, we can say that code <code>X</code> is <code>Z%</code> faster/slower than code <code>Y</code>.</p> <p><strong>The problem</strong></p> <p>Ok, so we can easily measure time. But what about memory? Our previous assumption <em>&quot;if we want to test some code, it's equal to test some function&quot;</em> seems to be not true here. Why? Because - it's true from formal point, but if we'll hide code inside function, we'll never be able to measure memory after that. Example:</p> <pre><code>function foo($x, $y) { $bar = array_fill(0, $y, str_repeat('bar', $x)); //do stuff } function baz($n) { //do stuff, resulting in $x, $y $bee = foo($x, $y); //do other stuff } </code></pre> <p>-and we want to test <code>baz</code> - i.e. how much memory it will use. By 'how much' I mean <em>'how much will be maximum memory usage during execution of function'</em>. And it is obvious that we can not act like when we were measuring time of execution - because we know nothing about function outside of it - it's a black box. If fact, we even can't be sure that function will be successfully executed (imagine what will happen if somehow <code>$x</code> and <code>$y</code> inside <code>baz</code> will be assigned as 1E6, for example). Thus, may be it isn't a good idea to wrap our code inside function. But what if code itself contains other functions/methods call?</p> <p><strong>My approach</strong></p> <p>My current idea is to create somehow a function, which will measure memory <em>after each input code's line</em>. That means something like this: let we have code</p> <pre><code>$x = foo(); echo($x); $y = bar(); </code></pre> <p>-and after doing some thing, measure function will do:</p> <pre><code>$memory = memory_get_usage(); $max = 0; $x = foo();//line 1 of code $memory = memory_get_usage()-$memory; $max = $memory&gt;$max:$memory:$max; $memory = memory_get_usage(); echo($x);//second line of code $memory = memory_get_usage()-$memory; $max = $memory&gt;$max:$memory:$max; $memory = memory_get_usage(); $y = bar();//third line of code $memory = memory_get_usage()-$memory; $max = $memory&gt;$max:$memory:$max; $memory = memory_get_usage(); //our result is $max </code></pre> <p>-but that looks weird and also it does not answer a question - how to measure function memory usage.</p> <p><strong>Use-case</strong></p> <p>Use-case for this: in most case, complexity-theory can provide at least <code>big-O</code> estimation for certain code. But:</p> <ul> <li>First, code can be huge - and I want to avoid it's manual analysis as long as possible. And that is why my current idea is bad: it can be applied, yes, but it will still manual work with code. And, more, to go deeper in code's structure I will need to apply it recursively: for example, after applying it for top-level I've found that some <code>foo()</code> function takes too much memory. What I will do? Yes, go to this <code>foo()</code> function, and.. repeat my analysis within it. And so on.</li> <li>Second - as I've mentioned, there are some language-specific things that can be resolved only by doing tests. That is why having some automatic way like for time measurement is my goal.</li> </ul> <p>Also, garbage collection is enabled. I am using PHP 5.5 (I believe this matters)</p> <p><strong>The question</strong></p> <p>How can we effectively measure memory usage of certain function? Is it achievable in PHP? May be it's possible with some simple code (like <code>benchmark</code> function for time measuring above)?</p>
19,974,019
5
5
null
2013-11-14 08:41:11.11 UTC
15
2022-08-01 17:41:05.1 UTC
2022-08-01 17:41:05.1 UTC
null
1,839,439
null
2,637,490
null
1
22
php|performance|memory|benchmarking
5,903
<pre><code>declare(ticks=1); // should be placed before any further file loading happens </code></pre> <p>That should say already all what I will say.</p> <p>Use a tick handler and print on every execution the memory usage to a file with the file line with:</p> <pre><code>function tick_handler() { $mem = memory_get_usage(); $bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2)[0]; fwrite($file, $bt["file"].":".$bt["line"]."\t".$mem."\n"); } register_tick_function('tick_handler'); // or in class: ([$this, 'tick_handler']); </code></pre> <p>Then look at the file to see how the memory varies in time, line by line.</p> <p>You also can parse that file later by a separate program to analyse peaks etc.</p> <p>(And to see how the possible peaks are by calling internal functions, you need to store the results into a variable, else it'll be already freed before the tick handler will measure the memory)</p>
3,947,889
MongoDB: Terrible MapReduce Performance
<p>I have a long history with relational databases, but I'm new to MongoDB and MapReduce, so I'm almost positive I must be doing something wrong. I'll jump right into the question. Sorry if it's long.</p> <p>I have a database table in MySQL that tracks the number of member profile views for each day. For testing it has 10,000,000 rows.</p> <pre><code>CREATE TABLE `profile_views` ( `id` int(10) unsigned NOT NULL auto_increment, `username` varchar(20) NOT NULL, `day` date NOT NULL, `views` int(10) unsigned default '0', PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`,`day`), KEY `day` (`day`) ) ENGINE=InnoDB; </code></pre> <p>Typical data might look like this.</p> <pre><code>+--------+----------+------------+------+ | id | username | day | hits | +--------+----------+------------+------+ | 650001 | Joe | 2010-07-10 | 1 | | 650002 | Jane | 2010-07-10 | 2 | | 650003 | Jack | 2010-07-10 | 3 | | 650004 | Jerry | 2010-07-10 | 4 | +--------+----------+------------+------+ </code></pre> <p>I use this query to get the top 5 most viewed profiles since 2010-07-16.</p> <pre><code>SELECT username, SUM(hits) FROM profile_views WHERE day &gt; '2010-07-16' GROUP BY username ORDER BY hits DESC LIMIT 5\G </code></pre> <p>This query completes in under a minute. Not bad!</p> <p>Now moving onto the world of MongoDB. I setup a sharded environment using 3 servers. Servers M, S1, and S2. I used the following commands to set the rig up (Note: I've obscured the IP addys).</p> <pre><code>S1 =&gt; 127.20.90.1 ./mongod --fork --shardsvr --port 10000 --dbpath=/data/db --logpath=/data/log S2 =&gt; 127.20.90.7 ./mongod --fork --shardsvr --port 10000 --dbpath=/data/db --logpath=/data/log M =&gt; 127.20.4.1 ./mongod --fork --configsvr --dbpath=/data/db --logpath=/data/log ./mongos --fork --configdb 127.20.4.1 --chunkSize 1 --logpath=/data/slog </code></pre> <p>Once those were up and running, I hopped on server M, and launched mongo. I issued the following commands:</p> <pre><code>use admin db.runCommand( { addshard : "127.20.90.1:10000", name: "M1" } ); db.runCommand( { addshard : "127.20.90.7:10000", name: "M2" } ); db.runCommand( { enablesharding : "profiles" } ); db.runCommand( { shardcollection : "profiles.views", key : {day : 1} } ); use profiles db.views.ensureIndex({ hits: -1 }); </code></pre> <p>I then imported the same 10,000,000 rows from MySQL, which gave me documents that look like this:</p> <pre><code>{ "_id" : ObjectId("4cb8fc285582125055295600"), "username" : "Joe", "day" : "Fri May 21 2010 00:00:00 GMT-0400 (EDT)", "hits" : 16 } </code></pre> <p>Now comes the real meat and potatoes here... My map and reduce functions. Back on server M in the shell I setup the query and execute it like this.</p> <pre><code>use profiles; var start = new Date(2010, 7, 16); var map = function() { emit(this.username, this.hits); } var reduce = function(key, values) { var sum = 0; for(var i in values) sum += values[i]; return sum; } res = db.views.mapReduce( map, reduce, { query : { day: { $gt: start }} } ); </code></pre> <p>And here's were I run into problems. <strong><em>This query took over 15 minutes to complete!</em></strong> The MySQL query took under a minute. Here's the output:</p> <pre><code>{ "result" : "tmp.mr.mapreduce_1287207199_6", "shardCounts" : { "127.20.90.7:10000" : { "input" : 4917653, "emit" : 4917653, "output" : 1105648 }, "127.20.90.1:10000" : { "input" : 5082347, "emit" : 5082347, "output" : 1150547 } }, "counts" : { "emit" : NumberLong(10000000), "input" : NumberLong(10000000), "output" : NumberLong(2256195) }, "ok" : 1, "timeMillis" : 811207, "timing" : { "shards" : 651467, "final" : 159740 }, } </code></pre> <p>Not only did it take forever to run, but the results don't even seem to be correct.</p> <pre><code>db[res.result].find().sort({ hits: -1 }).limit(5); { "_id" : "Joe", "value" : 128 } { "_id" : "Jane", "value" : 2 } { "_id" : "Jerry", "value" : 2 } { "_id" : "Jack", "value" : 2 } { "_id" : "Jessy", "value" : 3 } </code></pre> <p>I know those value numbers should be much higher.</p> <p>My understanding of the whole MapReduce paradigm is the task of performing this query should be split between all shard members, which should increase performance. I waited till Mongo was done distributing the documents between the two shard servers after the import. Each had almost exactly 5,000,000 documents when I started this query.</p> <p>So I must be doing something wrong. Can anyone give me any pointers?</p> <p>Edit: Someone on IRC mentioned adding an index on the day field, but as far as I can tell that was done automatically by MongoDB.</p>
3,951,871
4
3
null
2010-10-16 06:11:11.603 UTC
28
2017-07-11 09:24:28.73 UTC
2017-09-22 18:01:22.247 UTC
null
-1
null
401,019
null
1
42
mongodb|mapreduce|nosql
26,727
<p>excerpts from MongoDB Definitive Guide from O'Reilly:</p> <blockquote> <p>The price of using MapReduce is speed: group is not particularly speedy, but MapReduce is slower and is not supposed to be used in “real time.” You run MapReduce as a background job, it creates a collection of results, and then you can query that collection in real time.</p> </blockquote> <pre><code>options for map/reduce: "keeptemp" : boolean If the temporary result collection should be saved when the connection is closed. "output" : string Name for the output collection. Setting this option implies keeptemp : true. </code></pre>
3,561,120
Open alternatives to Google-maps?
<p>I'm looking for an alternative to Google-maps with all the richness of their API but more open. Does such a thing exist?</p>
3,561,159
6
2
null
2010-08-24 21:19:16.427 UTC
18
2015-02-10 09:35:42.347 UTC
2010-08-25 10:22:02.33 UTC
null
73,488
null
358,438
null
1
36
google-maps|geolocation|maps|geospatial
22,337
<p><a href="http://www.openstreetmap.org" rel="noreferrer">OpenStreetMap</a> is, of course, the obvious answer. There are various APIs for managing the data in the database, and there are various APIs for getting maps onto your webpages, such as <a href="http://wiki.openstreetmap.org/wiki/OpenLayers" rel="noreferrer">OpenLayers</a>, <a href="http://wiki.openstreetmap.org/wiki/Mapstraction" rel="noreferrer">Mapstraction</a>, or <a href="http://wiki.openstreetmap.org/wiki/Staticmaps" rel="noreferrer">Staticmaps</a>.</p>
3,630,645
How to compare Unicode strings in Javascript?
<p>When I wrote in JavaScript <code>"Ł" &gt; "Z"</code> it returns <code>true</code>. In Unicode order it should be of course <code>false</code>. How to fix this? My site is using UTF-8.</p>
23,618,442
6
8
null
2010-09-02 19:47:08.173 UTC
19
2019-01-23 06:50:01.587 UTC
2015-04-03 11:44:35.427 UTC
null
527,702
null
377,095
null
1
43
javascript|compare|polish
26,335
<p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Collator" rel="noreferrer"><code>Intl.Collator</code></a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare" rel="noreferrer"><code>String.prototype.localeCompare</code></a>, introduced by <a href="http://www.ecma-international.org/ecma-402/1.0/" rel="noreferrer">ECMAScript Internationalization API</a>:</p> <pre><code>"Ł".localeCompare("Z", "pl"); // -1 new Intl.Collator("pl").compare("Ł","Z"); // -1 </code></pre> <p><code>-1</code> means that <code>Ł</code> comes before <code>Z</code>, like you want.</p> <p>Note it only works on latest browsers, though.</p>
3,365,766
php - get numeric index of associative array
<p>I have an associative array and I need to find the numeric position of a key. I could loop through the array manually to find it, but is there a better way build into PHP?</p> <pre><code>$a = array( 'blue' =&gt; 'nice', 'car' =&gt; 'fast', 'number' =&gt; 'none' ); // echo (find numeric index of $a['car']); // output: 1 </code></pre>
3,365,793
7
0
null
2010-07-29 18:22:44.377 UTC
23
2021-10-15 15:33:31.903 UTC
2016-05-30 16:04:09.85 UTC
null
1,207,687
null
276,315
null
1
167
php|arrays
134,302
<pre><code>echo array_search("car",array_keys($a)); </code></pre>
3,524,862
When should I use a TreeMap over a PriorityQueue and vice versa?
<p>Seems they both let you retrieve the minimum, which is what I need for Prim's algorithm, and force me to remove and reinsert a key to update its value. Is there any advantage of using one over the other, not just for this example, but generally speaking?</p>
3,524,893
11
3
null
2010-08-19 18:12:05.07 UTC
19
2022-09-23 12:22:37.86 UTC
null
null
null
null
383,330
null
1
50
java|priority-queue|treemap
24,729
<p>Generally speaking, it is less work to track only the minimum element, using a heap.</p> <p>A tree is more organized, and it requires more computation to maintain that organization. But if you need to access <em>any</em> key, and not just the minimum, a heap will not suffice, and the extra overhead of the tree is justified.</p>
8,019,798
blank white screen after FB login via web app?
<p>I have tried following the FB mobile web "getting started guide" at: <a href="https://developers.facebook.com/docs/guides/mobile/web/" rel="noreferrer">https://developers.facebook.com/docs/guides/mobile/web/</a> for a web app that I open full-screen on my iphone.</p> <p>but when I try to login using the fb login page that opens up, I get a blank white screen after I click the "login" button. The user IS logged in though.. I know this because if I close and reopen my web app, I check the login status and try to get some user info, and it works fine...</p> <p>When I try the same web app in my desktop's chrome or my iphone's safari, the login process is ok... it break only from within the full screen web app.</p> <p>any ideas?? I'm merely following the sample code from FB :-(</p> <p>thanks.</p>
8,067,119
4
1
null
2011-11-05 11:13:36.807 UTC
8
2016-11-10 08:23:31.657 UTC
null
null
null
null
389,023
null
1
11
iphone|facebook|web-applications|mobile|web
20,232
<p>I have found a workaround to the issue... seems there is an undocumented 'redirect_uri' attribute I can use in the login() method, e.g. </p> <pre><code>login({scope:'email', redirect_uri:'where_to_go_when_login_ends'}) </code></pre> <p>It IS documented for fb desktop SDKs, so I gave it a go and it sort of works. When I say "sort of", I mean that on web mobile, it seems ok, but if you try to run it in a desktop browser, the login popup will redirect to the given url within the login popup - not within its parent window.</p> <p>I hope this is good enough and does not cause any side effects, I really can't tell. But this is what I'll use in the meantime for lack of other options :^)</p>
7,775,767
Javascript: Overriding XMLHttpRequest.open()
<p>How would I be able to override the <code>XMLHttpRequest.open()</code> method and then catch and alter it's arguments?</p> <p>I've already tried the proxy method but it didn't work, although removing the open over-rid when <code>XMLHttpRequest()</code> was called: </p> <pre><code>(function() { var proxied = window.XMLHttpRequest.open; window.XMLHttpRequest.open = function() { $('.log').html(arguments[0]); return proxied.apply(this, arguments); }; })(); </code></pre>
7,778,218
4
5
null
2011-10-15 04:34:58.97 UTC
12
2019-11-14 03:27:51.293 UTC
2011-10-15 06:36:55.98 UTC
null
6,992
null
744,319
null
1
23
javascript|ajax|xmlhttprequest|overriding
24,868
<p>You are not modifying the <code>open</code> method inherited by <code>XMLHttpRequest objects</code> but just adding a method to the <code>XMLHttpRequest constructor</code> which is actually never used.</p> <p>I tried this code in facebook and I was able to catch the requests:</p> <pre><code>(function() { var proxied = window.XMLHttpRequest.prototype.open; window.XMLHttpRequest.prototype.open = function() { console.log( arguments ); return proxied.apply(this, [].slice.call(arguments)); }; })(); /* ["POST", "/ajax/chat/buddy_list.php?__a=1", true] ["POST", "/ajax/apps/usage_update.php?__a=1", true] ["POST", "/ajax/chat/buddy_list.php?__a=1", true] ["POST", "/ajax/canvas_ticker.php?__a=1", true] ["POST", "/ajax/canvas_ticker.php?__a=1", true] ["POST", "/ajax/chat/buddy_list.php?__a=1", true] */ </code></pre> <p>So yeah the open method needs to be added to <code>XMLHttpRequest prototype</code> (window.XMLHttpRequest.prototype) not <code>XMLHttpRequest constructor</code> (window.XMLHttpRequest)</p>
7,792,459
canvas vs. webGL vs. CSS 3d -> which to choose?
<p>For basic 3d web application i.e. a few cubes, rotation and translation in 3d space - which is better to choose?</p> <p>CSS 3d seems the easiest, but is not supported on IE9 or on the roadmap for IE10, and offers less control than the other options. Canvas &amp; WebGL seems way more complicated, but I don't know if they are future proof.</p> <p>Why are there so many different techniques for 3D? which is better? which is future proof? </p>
7,792,691
4
3
null
2011-10-17 10:30:23.97 UTC
12
2015-01-30 13:31:41.86 UTC
null
null
null
null
465,401
null
1
32
css|html|canvas|3d|webgl
34,121
<p>The reason there are so many different options for 3D is because the whole thing is still in a state of flux -- 3D in the browser isn't a finished standard, and of the options you listed, the only one that works in all currently available browsers is Canvas.</p> <p>IE in particular is unlikely to give you much joy -- as you say, 3D isn't even slated for IE10 at this point. Having said that, SVG was added to IE9 quite late in the day, so there's always hope. But the reason it's unlikely is that Microsoft have made a point of only supporting features which have been formally ratified as standards.</p> <p>Of the technologies you listed, Canvas is <em>by far</em> the best supported, but Canvas isn't a 3D technology; it's a 2D canvas, and if you want to have 3D effects in it, you need to write them yourself, and they won't be hardware accelerated.</p> <p>I guess the real answer to your question depends on how important the feature is for your site. If it's just eye candy, which users of unsupported browsers could live without, then by all means do it with some 3D CSS. But if you need to make it consistent in all current browsers, then do it with Canvas.</p> <p>I'd tend to recommend not using WebGL for your case, because it sounds like it would be overkill for what you're doing.</p> <p>3D CSS is probably the <em>right</em> answer, but use Canvas for now, until the rest of the browsers add support for 3D CSS.</p>
8,338,241
How we can use @font-face in Less
<p>In <a href="http://lesscss.org/" rel="noreferrer">Less</a>, it seems almost impossible to use <code>@font-face</code> selector. Less gives errors when I try to use </p> <pre><code>font-family: my_font </code></pre> <p>Here is how I try to use it:</p> <pre class="lang-css prettyprint-override"><code>@font-face { font-family: my_font; src: url('http://contest-bg.net/lg.ttf'); } p { font-family: my_font, "Lucida Grande", sans-serif; } </code></pre> <p>There is simple escape in Less using <code>~"..."</code> but can't come up with working code.<br> Had someone used it successfully?</p>
8,810,508
4
3
null
2011-12-01 08:12:46.24 UTC
5
2021-06-11 00:23:13.483 UTC
2016-04-02 02:25:41.553 UTC
null
1,696,030
null
567,897
null
1
38
less|font-face
79,513
<p>Have you tried putting the font family name in single quotes? The following works just fine for me.</p> <pre><code> @font-face { font-family: 'cblockbold'; src: url('assets/fonts/creabbb_-webfont.eot'); src: url('assets/fonts/creabbb_-webfont.eot?#iefix') format('embedded-opentype'), url('assets/fonts/creabbb_-webfont.woff') format('woff'), url('assets/fonts/creabbb_-webfont.ttf') format('truetype'), url('assets/fonts/creabbb_-webfont.svg#CreativeBlockBBBold') format('svg'); font-weight: normal; font-style: normal; } </code></pre> <p>To use font as a mixin, try:</p> <pre><code>.ffbasic() { font-family: ff-basic-gothic-web-pro-1,ff-basic-gothic-web-pro-2, AppleGothic, "helvetica neue", Arial, sans-serif; } </code></pre> <p>then within a style declaration:</p> <pre><code>.your-class { font-size: 14px; .ffbasic(); } </code></pre>
8,020,297
MySQL my.cnf file - Found option without preceding group
<p>I'm trying to connect to my DB in Ubuntu remotely but I receive error message when trying to <code>mysql -u root -p</code>:</p> <blockquote> <p>Found option without preceding group in config file: /etc/mysql/my.cnf at line: 1</p> </blockquote> <p>my.cnf looks like:</p> <pre><code>[mysqld] user = mysql socket = /var/run/mysqld/mysqld.sock port = 3306 basedir = /usr datadir = /var/lib/mysql tmpdir = /tmp bind-address = 0.0.0.0 key_buffer = 16M max_allowed_packet = 16M thread_stack = 192K thread_cache_size = 8 myisam-recover = BACKUP query_cache_limit = 1M query_cache_size = 16M log_error = /var/log/mysql/error.log expire_logs_days = 10 max_binlog_size = 100M [client] port = 3306 socket = /var/run/mysqld/mysqld.sock [mysqld_safe] socket = /var/run/mysqld/mysqld.sock nice = 0 [mysqldump] quick quote-names max_allowed_packet = 16M [mysql] [isamchk] key_buffer = 16M </code></pre>
8,020,319
5
4
null
2011-11-05 12:56:26.417 UTC
17
2020-01-13 18:32:41.96 UTC
2011-11-05 12:58:47.89 UTC
null
23,199
null
660,187
null
1
82
mysql|my.cnf
133,279
<h2>Charset encoding</h2> <p>Check the charset encoding of the file. Make sure that it is in ASCII.</p> <p>Use the <code>od</code> command to see if there is a UTF-8 BOM at the beginning, for example.</p>
7,950,884
How to get a value inside an ArrayList java
<p>I am trying to get a value from with in an ArrayList. Here is a sample of my code: </p> <pre><code>public static void main (String [] args){ Car toyota= new Car("Toyota", "$10000", "300"+ "2003"); Car nissan= new Car("Nissan", "$22000", "300"+ "2011"); Car ford= new Car("Ford", "$15000", "350"+ "2010"); ArrayList&lt;Car&gt; cars = new ArrayList&lt;Car&gt;(); cars.add(toyota); cars.add(nissan); cars.add(ford); } public static void processCar(ArrayList&lt;Car&gt; cars){ // in heare i need a way of getting the total cost of all three cars by calling // computeCars () System.out.println(cars.get()); } </code></pre> <p>revision thanks all for the answers, I should probably add to the code a bit more. in the Car class, i have another method that is calculating the total cost including the tax. </p> <pre><code>class Car { public Car (String name, int price, int, tax, int year){ constructor....... } public void computeCars (){ int totalprice= price+tax; System.out.println (name + "\t" +totalprice+"\t"+year ); } } </code></pre> <p>in the main class </p> <pre><code>public static void processCar(ArrayList&lt;Car&gt; cars){ int totalAmount=0; for (int i=0; i&lt;cars.size(); i++){ cars.get(i).computeCars (); totalAmount=+ ?? // in need to add the computed values of totalprice from the Car class? } } </code></pre> <p>Thanks again</p>
7,950,919
7
0
null
2011-10-31 07:22:46.667 UTC
11
2018-12-21 15:41:41.353 UTC
2015-11-30 19:01:30.4 UTC
null
5,076,266
null
941,748
null
1
12
java
228,072
<p>Assuming your <code>Car</code> class has a getter method for price, you can simply use</p> <pre><code>System.out.println (car.get(i).getPrice()); </code></pre> <p>where <code>i</code> is the index of the element.</p> <p>You can also use</p> <pre><code>Car c = car.get(i); System.out.println (c.getPrice()); </code></pre> <p>You also need to return <code>totalprice</code> from your function if you need to store it</p> <p><strong>main</strong></p> <pre><code>public static void processCar(ArrayList&lt;Car&gt; cars){ int totalAmount=0; for (int i=0; i&lt;cars.size(); i++){ int totalprice= cars.get(i).computeCars (); totalAmount=+ totalprice; } } </code></pre> <p>And change the <code>return</code> type of your function</p> <pre><code>public int computeCars (){ int totalprice= price+tax; System.out.println (name + "\t" +totalprice+"\t"+year ); return totalprice; } </code></pre>
8,197,089
Fatal Error when updating submodule using GIT
<p>I am trying to update the submodules of this git repositary but I keep getting a fatal errors:</p> <pre><code>[root@iptlock ProdigyView]# git submodule update --recursive Cloning into core... Permission denied (publickey). fatal: The remote end hung up unexpectedly Clone of 'git@github.com:ProdigyView/ProdigyView-Core.git' into submodule path 'core' failed </code></pre> <p>Or this way</p> <pre><code>[root@iptlock root]# git clone --recursive https://github.com/ProdigyView/ProdigyView.git Cloning into ProdigyView... remote: Counting objects: 438, done. remote: Compressing objects: 100% (275/275), done. remote: Total 438 (delta 172), reused 394 (delta 128) Receiving objects: 100% (438/438), 8.03 MiB | 5.19 MiB/s, done. Resolving deltas: 100% (172/172), done. Submodule 'core' (git@github.com:ProdigyView/ProdigyView-Core.git) registered for path 'core' Cloning into core... Permission denied (publickey). fatal: The remote end hung up unexpectedly Clone of 'git@github.com:ProdigyView/ProdigyView-Core.git' into submodule path 'core' failed </code></pre> <p>Any ideas of why this is happening withthe submodule? The repo is this one: </p> <p><a href="https://github.com/ProdigyView/ProdigyView" rel="noreferrer">https://github.com/ProdigyView/ProdigyView</a></p> <p>(The submodule is able to be cloned if I do not try to clone it as a submodule.)</p>
8,197,296
8
1
null
2011-11-19 20:33:57.733 UTC
20
2020-05-15 19:20:48.077 UTC
2018-01-21 00:58:36.193 UTC
null
819,340
null
456,850
null
1
55
git|github|ssh|git-submodules
85,049
<p>Figured it out. The path in the .gitmodule files could not download the submodule.</p>
8,212,032
Sql Server replication requires the actual server name to make a connection to the server
<p>I get the following message when I want to create a new publication or Subscription.</p> <p>"Sql Server replication requires the actual server name to make a connection to the server. Connections through a server alias, IP address or any other alternate name are not supported. specify the actual server name"</p> <p>Does anyone know what should I do?</p>
8,223,535
9
1
null
2011-11-21 12:46:41.007 UTC
9
2020-10-12 05:53:56.257 UTC
2017-03-28 05:13:20.777 UTC
null
2,975,396
null
606,480
null
1
46
sql-server|sql-server-2008-r2
94,216
<p>I found the solution in the following link <a href="http://www.cryer.co.uk/brian/sqlserver/replication_requires_actual_server_name.htm" rel="noreferrer">http://www.cryer.co.uk/brian/sqlserver/replication_requires_actual_server_name.htm</a></p> <p>thankful to Brian Cryer for his useful site</p> <p><strong>Quoting from the link to avoid link rot:</strong> </p> <p><strong>Cause:</strong></p> <p>This error has been observed on a server that had been renamed after the original installation of SQL Server, and where the SQL Server configuration function <code>@@SERVERNAME</code> still returned the original name of the server. This can be confirmed by:</p> <pre><code>select @@SERVERNAME go </code></pre> <p>This should return the name of the server. If it does not then follow the procedure below to correct it.</p> <p><strong>Remedy:</strong></p> <p>To resolve the problem the server name needs to be updated. Use the following:</p> <pre><code>sp_addserver 'real-server-name', LOCAL </code></pre> <p>if this gives an error complaining that the name already exists then use the following sequence:</p> <pre><code>sp_dropserver 'real-server-name' go sp_addserver 'real-server-name', LOCAL go </code></pre> <p>If instead the error reported is 'There is already a local server.' then use the following sequence:</p> <pre><code>sp_dropserver old-server-name go sp_addserver real-server-name, LOCAL go </code></pre> <p>Where the "old-server-name" is the name contained in the body of the original error.</p> <p>Stop and restart SQL Server.</p>
4,288,089
Reuse identity value after deleting rows
<p>Is it possible to reuse an identity field value after deleting rows in SQL Server 2008 Express? Here is an example. Suppose I have a table with an Id field as a primary key (identity). If I add five rows, I will have these 5 Ids: 1, 2, 3, 4, 5. If I were to delete these rows, and then add five more, the new rows would have Ids: 6, 7, 8, 9, 10. Is it possible to let it start over at 1 again? </p> <p>Do I have to delete data from another table in order to accomplish this? Thanks for your help.</p>
4,288,110
3
3
null
2010-11-26 19:34:03.613 UTC
6
2010-11-26 19:55:11.817 UTC
2010-11-26 19:55:11.817 UTC
null
135,152
null
369,689
null
1
17
sql|sql-server|tsql|sql-server-2008|identity
38,667
<p>You can use the following to set the IDENTITY value:</p> <pre><code>DBCC CHECKIDENT (orders, RESEED, 999) </code></pre> <p>That means you'll have to run the statement based on every DELETE. That should start to highlight why this is a bad idea...</p> <p>The database doesn't care about sequential values - that's for presentation only.</p>
4,447,563
last Button of actionsheet does not get clicked
<p>I have used an actionsheet in my project and when it appears it show all buttons but last (4th) button does not responds to my click(only it's half part responds)..</p> <p>I know the reason it is because i have used a TabBarController and the present class is inside that tabbar controller.... only that part of the actionsheet is responding which is above the tabs....and my last button is half above and half is on top of tabbar</p> <p>please help</p>
4,447,933
3
3
null
2010-12-15 07:14:37.573 UTC
15
2013-07-03 14:15:04.3 UTC
2011-12-02 08:20:00.093 UTC
null
537,712
null
426,006
null
1
24
iphone|user-interface|uitabbarcontroller|uiactionsheet
6,874
<p>i suggest using this:</p> <pre><code>[actionSheet showInView:[UIApplication sharedApplication].keyWindow]; </code></pre> <p>I had the same problem that you have and using this method to show it worked for me. The TabBar wants to stay key Window what makes your bottom button appear above, but is actually under the tabbar.</p> <p>Hope this does the trick for you..</p> <h1>Edit</h1> <p>If you use landscape mode and the method above doesn't work. You can use the following fix:</p> <p>@Vinh Tran: [sheet showFromTabBar:self.parentViewController.tabBarController.tabBar]</p>
4,310,326
Convert date-time string to class Date
<p>I have a data frame with a character column of date-times.</p> <p>When I use <code>as.Date</code>, most of my strings are parsed correctly, except for a few instances. The example below will hopefully show you what is going on.</p> <pre><code># my attempt to parse the string to Date -- uses the stringr package prods.all$Date2 &lt;- as.Date(str_sub(prods.all$Date, 1, str_locate(prods.all$Date, &quot; &quot;)[1]-1), &quot;%m/%d/%Y&quot;) # grab two rows to highlight my issue temp &lt;- prods.all[c(1925:1926), c(1,8)] temp # Date Date2 # 1925 10/9/2009 0:00:00 2009-10-09 # 1926 10/15/2009 0:00:00 0200-10-15 </code></pre> <p>As you can see, the year of some of the dates is inaccurate. The pattern seems to occur when the day is double digit.</p> <p>Any help you can provide will be greatly appreciated.</p>
4,310,474
4
1
null
2010-11-30 03:40:28.417 UTC
15
2022-02-04 18:09:21.5 UTC
2021-09-26 14:06:33.31 UTC
null
1,851,712
null
155,406
null
1
49
r|date|lubridate|as.date|r-faq
283,290
<p>You may be overcomplicating things, is there any reason you need the stringr package? You can use <code>as.Date</code> and its <code>format</code> argument to specify the <em>input</em> format of your string.</p> <pre><code> df &lt;- data.frame(Date = c(&quot;10/9/2009 0:00:00&quot;, &quot;10/15/2009 0:00:00&quot;)) as.Date(df$Date, format = &quot;%m/%d/%Y %H:%M:%S&quot;) # [1] &quot;2009-10-09&quot; &quot;2009-10-15&quot; </code></pre> <p>Note the <strong>Details</strong> section of <code>?as.Date</code>:</p> <blockquote> <p>Character strings are processed as far as necessary for the format specified: any trailing characters are ignored</p> </blockquote> <p>Thus, this also works:</p> <pre><code>as.Date(df$Date, format = &quot;%m/%d/%Y&quot;) # [1] &quot;2009-10-09&quot; &quot;2009-10-15&quot; </code></pre> <p>All the conversion specifications that can be used to specify the input <code>format</code> are found in the <strong>Details</strong> section in <code>?strptime</code>. Make sure that the <em>order</em> of the conversion specification as well as any <em>separators</em> correspond exactly with the format of your <em>input</em> string.</p> <hr /> <p>More generally and if you need the time component as well, use <code>as.POSIXct</code> or <code>strptime</code>:</p> <pre><code>as.POSIXct(df$Date, &quot;%m/%d/%Y %H:%M:%S&quot;) strptime(df$Date, &quot;%m/%d/%Y %H:%M:%S&quot;) </code></pre> <p>I'm guessing at what your actual data might look at from the partial results you give.</p>
4,765,084
Convert a list of objects to an array of one of the object's properties
<p>Say I have the following class:</p> <pre><code>public class ConfigItemType { public string Name { get; set; } public double SomeOtherThing { get; set; } } </code></pre> <p>and then I make a list of the following classes (<code>List&lt;ConfigItemType&gt; MyList</code>)</p> <p>Now I have a method with the following signature:</p> <pre><code>void AggregateValues(string someUnrelatedValue, params string[] listGoesHere) </code></pre> <p>How can I fit <code>MyList</code> in to the <code>listGoesHere</code> using the value in <code>ConfigItemType.Name</code> as the params string array?</p> <p>I am fairly sure that Linq can do this.... but <code>MyList</code> does not have a <code>select</code> method on it (which is what I would have used).</p>
4,765,090
4
0
null
2011-01-21 23:53:47.863 UTC
22
2015-07-24 06:19:38.257 UTC
null
null
null
null
16,241
null
1
151
c#|linq
145,253
<p>You are looking for</p> <pre><code>MyList.Select(x=&gt;x.Name).ToArray(); </code></pre> <p>Since <code>Select</code> is an Extension method make sure to add that namespace by adding a </p> <p><code>using System.Linq</code> </p> <p>to your file - then it will show up with Intellisense.</p>
4,841,340
What is the use of ByteBuffer in Java?
<p>What are example applications for a <a href="http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html" rel="noreferrer"><code>ByteBuffer</code></a> in Java? Please list any example scenarios where this is used.</p>
4,841,352
5
3
null
2011-01-30 05:26:41.907 UTC
58
2021-08-18 15:38:49.937 UTC
2021-08-18 15:38:49.937 UTC
null
2,039,546
null
568,201
null
1
217
java|buffer|bytebuffer
248,336
<p><a href="http://mindprod.com/jgloss/bytebuffer.html" rel="noreferrer">This</a> is a good description of its uses and shortcomings. You essentially use it whenever you need to do fast low-level I/O. If you were going to implement a TCP/IP protocol or if you were writing a database (DBMS) this class would come in handy.</p>
4,645,456
Get table names from a database
<p>I've searched through a bunch of websites and I have not come across any code or tutorial which has gone through the specifics of obtaining the table names from a single database.</p> <p>Assuming I have 4 databases and I want the names of all the tables within the database called <code>mp21</code>, what query can I use?</p>
4,645,480
7
2
null
2011-01-10 09:50:40.12 UTC
2
2017-06-19 09:15:13.207 UTC
2013-05-13 12:51:47.567 UTC
null
1,563,422
null
559,042
null
1
14
mysql|sql
53,399
<pre><code>SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' </code></pre>
4,286,466
Use a normal link to submit a form
<p>I want to submit a form. But I am not going the basic way of using a input button with submit type but a <strong>a</strong> link. </p> <p>The image below shows why. I am using image links to save/submit the form. Because I have standart css markup for image links I don't want to use input submit buttons.</p> <p>I tried to apply <em>onClick="document.formName.submit()"</em> to the a element but I would prefer a html method.</p> <p><img src="https://i.stack.imgur.com/QKAlE.png" alt="alt text"></p> <p>Any ideas?</p>
4,286,493
7
3
null
2010-11-26 15:20:11.697 UTC
22
2021-04-18 01:26:57.803 UTC
null
null
null
null
401,025
null
1
145
html|css|forms|hyperlink|submit
325,002
<p>Two ways. Either create a button and style it so it looks like a link with css, or create a link and use <code>onclick="this.closest('form').submit();return false;"</code>.</p>
4,048,688
how can I convert day of year to date in javascript?
<p>I want to take a day of the year and convert to an actual date using the Date object. Example: day 257 of 1929, how can I go about doing this?</p>
4,049,020
9
0
null
2010-10-29 03:06:19.793 UTC
6
2020-10-19 07:05:22.96 UTC
2017-11-28 09:50:59.957 UTC
null
344,372
null
344,372
null
1
29
javascript|date
27,136
<blockquote> <p>"I want to take a day of the year and convert to an actual date using the Date object."</p> </blockquote> <p>After re-reading your question, it sounds like you have a year number, and an arbitrary day number (e.g. a number within <code>0..365</code> (or 366 for a leap year)), and you want to get a date from that.</p> <p>For example:</p> <pre><code>dateFromDay(2010, 301); // "Thu Oct 28 2010", today ;) dateFromDay(2010, 365); // "Fri Dec 31 2010" </code></pre> <p>If it's that, can be done easily:</p> <pre><code>function dateFromDay(year, day){ var date = new Date(year, 0); // initialize a date in `year-01-01` return new Date(date.setDate(day)); // add the number of days } </code></pre> <p>You could add also some validation, to ensure that the day number is withing the range of days in the year supplied.</p>
4,517,067
Remove a string from the beginning of a string
<p>I have a string that looks like this:</p> <pre><code>$str = "bla_string_bla_bla_bla"; </code></pre> <p>How can I remove the first <code>bla_</code>; but only if it's found at the beginning of the string?</p> <p>With <code>str_replace()</code>, it removes <em>all</em> <code>bla_</code>'s.</p>
4,517,270
9
1
null
2010-12-23 08:40:40.3 UTC
22
2022-07-20 12:00:35.953 UTC
2013-06-21 03:27:32.833 UTC
null
1,563,422
null
376,947
null
1
176
php|string
167,672
<p>Plain form, without regex:</p> <pre><code>$prefix = 'bla_'; $str = 'bla_string_bla_bla_bla'; if (substr($str, 0, strlen($prefix)) == $prefix) { $str = substr($str, strlen($prefix)); } </code></pre> <p>Takes: <strong>0.0369 ms</strong> (0.000,036,954 seconds)</p> <p>And with:</p> <pre><code>$prefix = 'bla_'; $str = 'bla_string_bla_bla_bla'; $str = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $str); </code></pre> <p>Takes: <strong>0.1749 ms</strong> (0.000,174,999 seconds) the 1st run (compiling), and <strong>0.0510 ms</strong> (0.000,051,021 seconds) after.</p> <p>Profiled on my server, obviously.</p>
4,129,666
How to convert hex to rgb using Java?
<p>How can I convert hex color to RGB code in Java? Mostly in Google, samples are on how to convert from RGB to hex.</p>
4,129,692
21
2
null
2010-11-09 01:20:38.043 UTC
20
2022-08-23 17:21:57.843 UTC
2014-01-15 08:32:23.117 UTC
null
617,450
null
236,501
null
1
116
java|colors
173,433
<p>I guess this should do it:</p> <pre><code>/** * * @param colorStr e.g. "#FFFFFF" * @return */ public static Color hex2Rgb(String colorStr) { return new Color( Integer.valueOf( colorStr.substring( 1, 3 ), 16 ), Integer.valueOf( colorStr.substring( 3, 5 ), 16 ), Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) ); } </code></pre>
14,784,048
create a formula in a data.table environment in R
<p>I would like to run a regression within a <code>data.table</code>. The <code>formula</code> needs to be constructed dynamically. I have tried the following method:</p> <pre><code>x = data.table(a=1:20, b=20:1, id=1:5) &gt; x[,as.list(coef(lm(as.formula("a ~ b")))),by=id] Error in eval(expr, envir, enclos) : object 'a' not found </code></pre> <p>How does one specify the environment to be that of the actual data.table where the evaluation occurs?</p> <p>EDIT: I realize I can do lm(a ~ b). I need the formula to be dynamic so it's built up as a character string. By dynamically I mean the formula can be <code>paste0(var_1, "~", var_2)</code> where <code>var_1 = a</code> and <code>var_2 = b</code></p> <p>Here is one solution thought I think we can do better:</p> <pre><code>txt = parse(text="as.list(coef(lm(a ~ b)))") &gt; x[,eval(txt),by=id] id (Intercept) b 1: 1 21 -1 2: 2 21 -1 3: 3 21 -1 4: 4 21 -1 5: 5 21 -1 </code></pre>
14,784,583
1
2
null
2013-02-09 01:39:49.17 UTC
9
2013-02-09 03:19:01.09 UTC
2013-02-09 01:59:43.997 UTC
null
714,319
null
714,319
null
1
19
r|environment|data.table
2,146
<p><code>lm</code> can accept a character string as the formula so combine that with <code>.SD</code> like this:</p> <pre><code>&gt; x[, as.list(coef(lm("a ~ b", .SD))), by = id] id (Intercept) b 1: 1 21 -1 2: 2 21 -1 3: 3 21 -1 4: 4 21 -1 5: 5 21 -1 </code></pre>
14,483,963
Rails 4.0 Strong Parameters nested attributes with a key that points to a hash
<p>I was playing around with Rails 4.x beta and trying to get nested attributes working with carrierwave. Not sure if what I'm doing is the right direction. After searching around, and then eventually looking at the rails source and strong parameters I found the below notes. </p> <blockquote> <pre><code># Note that if you use +permit+ in a key that points to a hash, # it won't allow all the hash. You also need to specify which # attributes inside the hash should be whitelisted. </code></pre> </blockquote> <p><a href="https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb">https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/strong_parameters.rb</a></p> <p>So its saying you have to specify every single every single attribute within the has, I tried the following:</p> <p>Param's example:</p> <pre><code>{"utf8"=&gt;"✓", "authenticity_token"=&gt;"Tm54+v9DYdBtWJ7qPERWzdEBkWnDQfuAQrfT9UE8VD=", "screenshot"=&gt;{ "title"=&gt;"afs", "assets_attributes"=&gt;{ "0"=&gt;{ "filename"=&gt;#&lt;ActionDispatch::Http::UploadedFile:0x00000004edbe40 @tempfile=#&lt;File:/tmp/RackMultipart20130123-18328-navggd&gt;, @original_filename="EK000005.JPG", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"screenshot[assets_attributes][0][filename]\"; filename=\"EK000005.JPG\"\r\nContent-Type: image/jpeg\r\n"&gt; } } }, "commit"=&gt;"Create Screenshot"} </code></pre> <p>Controller</p> <pre><code>def screenshot_params params.require(:screenshot).permit(:title, :assets_attributes =&gt; [:filename =&gt; [:@tempfile,:@original_filename,:@content_type,:@headers] </code></pre> <p>The above isn't "working" (its not triggering carrierwave) however I am no longer getting errors (Unpermitted parameters: filename) when using the standard nested examples I found ex:</p> <pre><code>def screenshot_params params.require(:screenshot).permit(:title, assets_attributes: :filename) </code></pre> <p>If anyone could help it would be great. I was not able to find a example with nested with a key that points to a hash.</p>
14,486,812
6
0
null
2013-01-23 16:04:58.48 UTC
17
2017-11-02 14:03:23.903 UTC
2013-01-23 16:40:03.13 UTC
null
1,591
null
418,781
null
1
35
ruby-on-rails|ruby|ruby-on-rails-4|strong-parameters
43,773
<p>My other answer was mostly wrong - new answer. </p> <p>in your params hash, :filename is not associated with another hash, it is associated with an ActiveDispatch::Http::UploadedFile object. Your last code line:</p> <pre><code>def screenshot_params params.require(:screenshot).permit(:title, assets_attributes: :filename) </code></pre> <p>is actually correct, however, the filename attribute is not being allowed since it is not one of the permitted <a href="https://github.com/rails/rails/blob/16e0c8816c4c8a9fb5292278bf5753b026c1105c/actionpack/lib/action_controller/metal/strong_parameters.rb#L362">scalar types</a>. If you open up a console, and initialize a params object in this shape:</p> <pre><code>params = ActionController::Parameters.new screenshot: { title: "afa", assets_attributes: {"0" =&gt; {filename: 'a string'}}} </code></pre> <p>and then run it against your last line:</p> <pre><code>p = params.require(:screenshot).permit(:title, assets_attributes: :filename) # =&gt; {"title" =&gt; "afa", "assets_attributes"=&gt;{"0"=&gt;{"filename"=&gt;"abc"}}} </code></pre> <p>However, if you do the same against a params hash with the uploaded file, you get </p> <pre><code>upload = ActionDispatch::Http::UplaodedFile.new tempfile: StringIO.new("abc"), filename: "abc" params = ActionController::Parameters.new screenshot: { title: "afa", assets_attributes: {"0" =&gt; {filename: upload}}} p = params.require(:screenshot).permit(:title, assets_attributes: :filename) # =&gt; {"title" =&gt; "afa", "assets_attributes"=&gt;{"0"=&gt;{}}} </code></pre> <p>So, it is probably worth a bug or pull request to Rails, and in the meantime, you will have to directly access the filename parameter using the raw <code>params</code> object:</p> <pre><code>params[:screenshot][:assets_attributes]["0"][:filename] </code></pre>
14,814,714
Update TextView Every Second
<p>I've looked around and nothing seems to be working from what I've tried so far...</p> <pre><code> @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.deskclock); TextView tvTime = (TextView) findViewById(R.id.tvTime); TextView tvDate = (TextView) findViewById(R.id.tvDate); java.util.Date noteTS = Calendar.getInstance().getTime(); String time = "hh:mm"; // 12:00 tvTime.setText(DateFormat.format(time, noteTS)); String date = "dd MMMMM yyyy"; // 01 January 2013 tvDate.setText(DateFormat.format(date, noteTS)); </code></pre> <p>I basically want the setText methods to update or refresh every second or so, so my clock actually works like it should do. I've seen methods like handlers and run and nothing worked so any help with this would be great thanks. :)</p>
14,814,842
11
1
null
2013-02-11 15:00:45.97 UTC
21
2022-02-01 12:35:13.82 UTC
2016-12-06 06:56:42.883 UTC
null
3,678,528
null
1,888,770
null
1
52
android|date|time|textview|clock
114,284
<p>Add following code in your onCreate() method:</p> <pre><code>Thread thread = new Thread() { @Override public void run() { try { while (!thread.isInterrupted()) { Thread.sleep(1000); runOnUiThread(new Runnable() { @Override public void run() { // update TextView here! } }); } } catch (InterruptedException e) { } } }; thread.start(); </code></pre> <p>This code starts an thread which sleeps 1000 milliseconds every round.</p>
14,787,776
How to pull after a forced git push?
<p>Suppose I pull changes from a git repo. Then the author of the repo force pushes to the central repo. Now I can't pull since the history is rewritten.</p> <p>How can I pull the new commits (and abandon the old ones), assuming that the author force-pushed the correct version?</p> <p>I know this is bad git workflow, but sometimes you can't avoid this.</p>
14,787,801
4
1
null
2013-02-09 11:46:47.247 UTC
19
2021-01-23 18:20:17.03 UTC
null
null
null
null
1,922,239
null
1
65
git
28,441
<h2>Throwing away your local changes</h2> <p>If you want to discard your work, <code>fetch</code> and <code>reset</code>. For example, if you have a remote named <code>origin</code> and a branch named <code>master</code>:</p> <pre><code>$ git fetch origin $ git reset --hard origin/master # Destroys your work </code></pre> <h2>Keeping your local changes</h2> <p>If you don't want to throw away your work, you will have to do a <code>git rebase --onto</code>. Suppose the old <code>origin</code> looks like this:</p> <pre><code>A ---&gt; B ---&gt; C ^ origin/master </code></pre> <p>And you have this:</p> <pre><code>A ---&gt; B ---&gt; C ---&gt; X ---&gt; Y ---&gt; Z ^ ^ | master origin/master </code></pre> <p>Now, the upstream changes change things:</p> <pre><code>A ---&gt; B ---&gt; C ---&gt; X ---&gt; Y ---&gt; Z \ ^ ---&gt; B'---&gt; C' master ^ origin/master </code></pre> <p>You would have to run <code>git rebase --onto origin/master &lt;C&gt; master</code>, where <code>&lt;C&gt;</code> is the SHA-1 of the old <code>origin/master</code> branch before upstream changes. This gives you this:</p> <pre><code>A ---&gt; B ---&gt; C ---&gt; X ---&gt; Y ---&gt; Z \ ---&gt; B'---&gt; C'---&gt; X'---&gt; Y'---&gt; Z' ^ ^ | master origin/master </code></pre> <p>Notice how B, C, X, Y, and Z are now "unreachable". They will eventually be removed from your repository by Git. In the meantime (90 days), Git will keep a copy in the reflog in case it turns out you made a mistake.</p> <h2>Fixing mistakes</h2> <p>If you <code>git reset</code> or <code>git rebase</code> wrong and accidentally lose some local changes, you can find the changes in the reflog.</p> <p>In the comments, a user is suggesting <code>git reflog expire</code> with <code>--expire=now</code> but <strong>DO NOT RUN THIS COMMAND</strong> because this will <strong>DESTROY</strong> your safety net. The whole purpose of having a reflog is so that Git will sometimes save your neck when you run the wrong command.</p> <p>Basically, what this command will do is immediately destroy the B, C, X, Y, and Z commits in the examples above so you can't get them back. There's no real benefit to running this command, except it might save a little bit of disk space, but Git will already purge the data after 90 days so this benefit is short-lived.</p>
2,366,097
What does putting an exclamation point (!) in front of an object reference variable do?
<p>What does putting an exclamation point (<code>!</code>) in front of an object reference variable do in Visual Basic 6.0?</p> <p>For example, I see the following in code:</p> <pre><code> !RelativePath.Value = mstrRelativePath </code></pre> <p>What does the <code>!</code> mean?</p>
2,366,226
2
3
null
2010-03-02 19:33:29.26 UTC
4
2018-07-25 15:52:37.63 UTC
2012-05-03 13:51:07.467 UTC
null
588,306
null
166,258
null
1
29
vb6
17,394
<p>It is almost certainly a statement inside a With block:</p> <pre><code> With blah !RelativePath.Value = mstrRelativePath End With </code></pre> <p>which is syntax sugar for</p> <pre><code> blah("RelativePath").Value = mstrRelativePath </code></pre> <p>which is syntax sugar for</p> <pre><code> blah.DefaultProperty("RelativePath").Value = mstrRelativePath </code></pre> <p>where "DefaultProperty" is a property with dispid zero that's indexed by a string. Like the Fields property of an ADO Recordset object.</p> <p>Somewhat inevitable with sugar is that it produces tooth decay. This is the reason you have to use the <strong>Set</strong> keyword in VB6 and VBA. Because without it the compiler doesn't know whether you meant to copy the object reference or the object's default property value. Eliminated in vb.net.</p>
2,947,440
Foreign Keys vs Joins
<p>Is it better to use foreign keys in tables or can the same results be achieved with joins?</p>
2,947,450
2
5
null
2010-06-01 05:24:09.15 UTC
13
2015-09-16 10:43:52.17 UTC
2010-06-01 09:15:49.04 UTC
null
222,908
null
340,183
null
1
38
sql
28,518
<p><a href="http://en.wikipedia.org/wiki/Foreign_key" rel="noreferrer">Foreign keys</a> are just constraints to enforce <a href="http://en.wikipedia.org/wiki/Referential_integrity" rel="noreferrer">referential integrity</a>. You will still need to use <a href="http://en.wikipedia.org/wiki/Sql_join" rel="noreferrer">JOINs</a> to build your queries. </p> <p>Foreign keys guarantee that a row in a table <code>order_details</code> with a field <code>order_id</code> referencing an <code>orders</code> table will never have an <code>order_id</code> value that doesn't exist in the <code>orders</code> table. Foreign keys aren't required to have a working relational database (in fact <a href="http://en.wikipedia.org/wiki/MyISAM" rel="noreferrer">MySQL's default storage</a> engine doesn't support FKs), but they are definitely essential to avoid broken relationships and orphan rows (ie. referential integrity).</p>
2,924,160
Is it valid to have more than one question mark in a URL?
<p>I came across the following URL today:</p> <pre><code>http://www.sfgate.com/cgi-bin/blogs/inmarin/detail??blogid=122&amp;entry_id=64497 </code></pre> <p>Notice the doubled question mark at the beginning of the query string:</p> <pre><code>??blogid=122&amp;entry_id=64497 </code></pre> <p>My browser didn't seem to have any trouble with it, and running a quick bookmarklet:</p> <pre><code>javascript:alert(document.location.search); </code></pre> <p>just gave me the query string shown above.</p> <p>Is this a valid URL? The reason I'm being so pedantic (assuming that I am) is because I need to parse URLs like this for query parameters, and supporting doubled question marks would require some changes to my code. Obviously if they're in the wild, I'll need to support them; I'm mainly curious if it's my fault for not adhering to URL standards exactly, or if it's in fact a non-standard URL.</p>
2,924,187
2
1
null
2010-05-27 19:19:15.183 UTC
14
2018-06-15 10:33:04.2 UTC
2010-05-27 19:28:44.67 UTC
null
126,562
null
167,911
null
1
109
url|parsing|query-parameters
62,167
<p>Yes, it is valid. Only the <em>first</em> <code>?</code> in a URL has significance, any after it are treated as literal question marks:</p> <blockquote> <p>The query component is indicated by the first question mark (&quot;?&quot;) character and terminated by a number sign (&quot;#&quot;) character or by the end of the URI.</p> </blockquote> <p>...</p> <blockquote> <p>The characters slash (&quot;/&quot;) and question mark (&quot;?&quot;) may represent data within the query component. Beware that some older, erroneous implementations may not handle such data correctly when it is used as the base URI for relative references (Section 5.1), apparently because they fail to distinguish query data from path data when looking for hierarchical separators. However, as query components are often used to carry identifying information in the form of &quot;key=value&quot; pairs and one frequently used value is a reference to another URI, it is sometimes better for usability to avoid percent-encoding those characters.</p> </blockquote> <p><a href="https://www.rfc-editor.org/rfc/rfc3986#section-3.4" rel="noreferrer">https://www.rfc-editor.org/rfc/rfc3986#section-3.4</a></p>
35,136,098
Have sass-lint ignore a certain line?
<p>I'm using <em>sass</em>-lint with Gulp. How can I disable warnings for a particular style in my sass from the lint console output? </p> <p>I've found a similar question but I'm using <strong>sass</strong>-lint, not <strong>scss</strong>-lint: <a href="https://stackoverflow.com/questions/32833542/having-scss-lint-ignore-a-particular-line">Having scss-lint ignore a particular line</a></p> <p>This is the one I'm using: <a href="https://www.npmjs.com/package/gulp-sass-lint" rel="noreferrer">https://www.npmjs.com/package/gulp-sass-lint</a></p> <p>I've tried a few variations based off of the <strong><em>scss</em></strong>-lint project: </p> <pre><code>// scss-lint:disable ImportantRule // sass-lint:disable ImportantRule // sass-lint:disable no-important </code></pre> <p>Just to be clear, I want to disable warnings for a specific style in my SASS, not globally. I will use this when the thing triggering the warning is intentional. For instance I might set multiple background styles so one can be a fallback for older browsers. But currently this is triggering the no-duplicate-properties warning. </p>
35,142,043
4
0
null
2016-02-01 17:00:37.447 UTC
7
2021-03-24 16:41:09.96 UTC
2021-03-24 16:41:09.96 UTC
null
3,448,527
null
467,875
null
1
53
sass|gulp|gulp-sass
39,093
<h2>Disabling through comments</h2> <p><strong>Update per December 2016</strong> according to <a href="https://github.com/sasstools/sass-lint#disabling-linters-via-source">the docs</a> this will now be possible using this syntax:</p> <blockquote> <p><strong>Disable more than 1 rule for entire file</strong></p> <pre><code>// sass-lint:disable border-zero, quotes p { border: none; // No lint reported content: "hello"; // No lint reported } </code></pre> <p><strong>Disable a rule for a single line</strong></p> <pre><code>p { border: none; // sass-lint:disable-line border-zero } </code></pre> <p><strong>Disable all lints within a block (and all contained blocks)</strong></p> <pre><code>p { // sass-lint:disable-block border-zero border: none; // No result reported } </code></pre> </blockquote> <p><sup>New info courtesy of commenter @IanRoutledge.</sup></p> <p><strong>However, <em>before</em></strong>, if you wanted to disable certain rules, but only for specific code blocks and/or pieces of the code. <em>As far as I can <a href="https://github.com/sasstools/sass-lint/search?utf8=%E2%9C%93&amp;q=disable">tell</em> from the underlying source code</a> it would <em>not</em> be possible with sass-lint. I've tried a few other searches as well, and skimmed the code base in general, but found no hint that the feature you're looking for exists.</p> <p>For comparison, <a href="https://github.com/brigade/scss-lint/search?utf8=%E2%9C%93&amp;q=disable">this query for the scss-lint source code</a> clearly shows it <em>is</em> implemented there, in a fashion that doesn't seem to have an analogous solution in the lib you are using.</p> <h2>Disabling through yml configs</h2> <p>You <em>can</em> disable rules in general though. You need to have a <code>.sass-lint.yml</code> file to disable warnings.</p> <p>Suppose you have this <code>gulpfile.js</code>:</p> <pre><code>'use strict'; var gulp = require('gulp'), sassLint = require('gulp-sass-lint'); gulp.task('default', [], function() { gulp.src('sass/*.scss') .pipe(sassLint()) .pipe(sassLint.format()) .pipe(sassLint.failOnError()); }); </code></pre> <p>And this <code>package.json</code>:</p> <pre><code>{ "devDependencies": { "gulp": "^3.9.0", "gulp-sass": "^2.1.1", "gulp-sass-lint": "^1.1.1" } } </code></pre> <p>Running on this <code>styles.scss</code> file:</p> <pre><code>div { dsply: block; } </code></pre> <p>You get this output:</p> <pre class="lang-none prettyprint-override"><code>[23:53:33] Using gulpfile D:\experiments\myfolder\gulpfile.js [23:53:33] Starting 'default'... [23:53:33] Finished 'default' after 8.84 ms sass\styles.scss 1:7 warning Property `dsply` appears to be spelled incorrectly no-misspelled-properties 1:21 warning Files must end with a new line final-newline ??? 2 problems (0 errors, 2 warnings) </code></pre> <p>Now if you add a <code>.sass-lint.yml</code> file next to the gulpfile, with this content:</p> <pre><code>rules: no-misspelled-properties: 0 </code></pre> <p>You'll instead see:</p> <pre class="lang-none prettyprint-override"><code>[23:54:56] Using gulpfile D:\experiments\myfolder\gulpfile.js [23:54:56] Starting 'default'... [23:54:56] Finished 'default' after 9.32 ms sass\styles.scss 1:21 warning Files must end with a new line final-newline ??? 1 problem (0 errors, 1 warning) </code></pre> <p>One of the warnings is now ignored.</p> <p><a href="https://github.com/sasstools/sass-lint/blob/develop/README.md">The sass-lint readme.md</a> links to <a href="https://github.com/sasstools/sass-lint/blob/master/lib/config/sass-lint.yml">the apparent default config</a> which has some more examples.</p>
40,336,155
Binding: Appending to href
<p>In my Angular 2 test app, I am trying to append an <code>id</code> the following as part of my HTML template:</p> <pre><code>&lt;a href="https://www.domainname.com/?q="+{{text.id}}&gt;URL&lt;/a&gt; </code></pre> <p>Not this fails with an error:</p> <blockquote> <p>(Error: Failed to execute 'setAttribute' on 'Element')</p> </blockquote> <p>and I am not sure how to append <code>{{text.id}}</code> to this URL.</p> <p>Do I need to do this in my component, or can it be done somehow inside the HTML template?</p> <p>BTW, as one would expect, this works just fine (but that's not what I want to do, I need to append text.id to url):</p> <pre><code>&lt;a href="https://www.domainname.com/?q="&gt;{{text.id}}&lt;/a&gt; </code></pre> <p>Any suggestions?</p>
40,336,283
4
0
null
2016-10-31 03:23:03.86 UTC
2
2022-06-01 18:32:32.03 UTC
2019-10-01 19:57:23.533 UTC
null
3,345,644
null
998,415
null
1
31
angular|angular2-template
80,227
<p>Use either:</p> <pre class="lang-html prettyprint-override"><code>&lt;a href="https://www.domainname.com/?q={{text.id}}"&gt;URL&lt;/a&gt; </code></pre> <p>or (from the <a href="https://angular.io/guide/ajs-quick-reference#bind-to-the-href-property" rel="noreferrer">official docs</a>):</p> <pre class="lang-html prettyprint-override"><code>&lt;a [href]="'https://www.domainname.com/?q=' + text.id"&gt;URL&lt;/a&gt; </code></pre> <p><br></p> <hr> <p>Regarding the question, it's important to notice: The error message is misleading.</p> <p>When you use <code>{{ expression }}</code>, angular will evaluate the <code>expression</code> and place its value right where the <code>{{}}</code> is. So you don't need to <code>+</code> the result of <code>{{}}</code> to the string as you do. In other words:</p> <pre class="lang-html prettyprint-override"><code>&lt;a href="something="+{{ expression }}&gt; WRONG &lt;/a&gt; &lt;a href="something={{ expression }}"&gt; RIGHT &lt;/a&gt; &lt;a [href]="'something=' + expression"&gt; RIGHT &lt;/a&gt; </code></pre>
2,656,740
Create a class with array of objects
<p>Code below defines a ChargeCustomer class that contains an array of type "customers". I want to be able to create an object with either 1 "customer" or 2 "customers" based on the constructor parameters. Is this the right way to do so in C#:</p> <pre><code>public class ChargeCustomer { private Customer[] customers; public ChargeCustomer( string aName, string bName, int charge ) { customers = new Customer[2]; customers[0] = new Customer(aName, charge); customers[1] = new Customer(bName, charge); } public ChargeCustomer( string bName, int charge ) { customers = new Customer[1]; customers[0] = new Customer( bName, charge ); } </code></pre> <p>}</p> <p>Thanks!</p>
2,656,777
1
2
null
2010-04-17 00:26:22.61 UTC
1
2010-04-17 00:41:39.94 UTC
2010-04-17 00:41:39.94 UTC
null
121,606
null
121,606
null
1
6
c#
104,624
<p><em>Note: This assumes that <code>DropBox</code> was a mis-paste in the original question.</em></p> <p>You can move things around and have 1 constructor using <a href="http://msdn.microsoft.com/en-us/library/w5zay9db.aspx" rel="noreferrer"><code>params</code></a> for any number of names, like this:</p> <pre><code>public class ChargeCustomer { private Customer[] customers; public ChargeCustomer( int charge, params string[] names) { customers = new Customer[names.Length]; for(int i = 0; i &lt; names.Length; i++) { customers[i] = new Customer(names[i], charge); } } } </code></pre> <p>Using this approach you just pass the charge first and any number of customer names, like this:</p> <pre><code>new ChargeCustomer(20, "Bill", "Joe", "Ned", "Ted", "Monkey"); </code></pre> <p>It will create an array the correct size and fill it using the same charge for all, and 1 Customer per name by looping through the names passed in. All that being said, there's probably a much simpler overall solution to your problem, but without making changes outside the Customer class (aside from the constructor calls), this would be the simplest approach/smallest change.</p>
33,925,430
Shiny: plot results in popup window
<p>I am trying to build a web app with shiny and I would like to display the resulting plot of a R function in a popup window rather than in mainPanel. For instance, for the below example (from <a href="http://shiny.rstudio.com/articles/action-buttons.html" rel="noreferrer">http://shiny.rstudio.com/articles/action-buttons.html</a>), clicking on "Go" button would show the same plot but in a popup window.</p> <p>I tried to add some javascript, but I have not succeeded yet... Can anyone help ?</p> <p>Thank you in advance !</p> <pre><code>library(shiny) ui &lt;- fluidPage( actionButton("go", "Go"), numericInput("n", "n", 50), plotOutput("plot") ) server &lt;- function(input, output) { randomVals &lt;- eventReactive(input$go, { runif(input$n) }) output$plot &lt;- renderPlot({ hist(randomVals()) }) } shinyApp(ui, server) </code></pre>
33,933,549
3
0
null
2015-11-25 20:02:13.01 UTC
9
2020-11-11 15:26:26.377 UTC
null
null
null
null
5,107,540
null
1
12
r|shiny
16,730
<p>Look into <code>shinyBS</code> package which offers <code>modal</code> popups. Example below shows the plot upon button click. </p> <p><strong>EDIT - Added a download button to the Modal</strong></p> <pre><code>rm(list = ls()) library(shiny) library(shinyBS) shinyApp( ui = fluidPage( sidebarLayout( sidebarPanel(numericInput("n", "n", 50),actionButton("go", "Go")), mainPanel( bsModal("modalExample", "Your plot", "go", size = "large",plotOutput("plot"),downloadButton('downloadPlot', 'Download')) ) ) ), server = function(input, output, session) { randomVals &lt;- eventReactive(input$go, { runif(input$n) }) plotInput &lt;- function(){hist(randomVals())} output$plot &lt;- renderPlot({ hist(randomVals()) }) output$downloadPlot &lt;- downloadHandler( filename = "Shinyplot.png", content = function(file) { png(file) plotInput() dev.off() }) } ) </code></pre> <p><a href="https://i.stack.imgur.com/LONzo.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/LONzo.jpg" alt="enter image description here"></a></p>
27,612,765
Nested routes in react-router
<p>I'm setting up some nested routes within React-Router (v0.11.6 is what I'm working against) but whenever I try and access one of the nested routes it triggers the parent route.</p> <p>My routes look like this:</p> <pre><code>&lt;Route handler={App}&gt; &lt;Route name="home" path="/" handler={availableRoutes.Splash} /&gt; &lt;DefaultRoute handler={availableRoutes.Splash} /&gt; &lt;Route name="dashboard" handler={availableRoutes.Dashboard}&gt; &lt;Route name="dashboard-child" handler={availableRoutes.DashboardChild} /&gt; &lt;/Route&gt; &lt;NotFoundRoute handler={NotFound} /&gt; &lt;/Route&gt; </code></pre> <p>If I collapse the routes up so it looks like:</p> <pre><code>&lt;Route handler={App}&gt; &lt;Route name="home" path="/" handler={availableRoutes.Splash} /&gt; &lt;DefaultRoute handler={availableRoutes.Splash} /&gt; &lt;Route name="dashboard" handler={availableRoutes.Dashboard} /&gt; &lt;Route name="dashboard-child" path="/dashboard/dashboard-child" handler={availableRoutes.DashboardChild} /&gt; &lt;NotFoundRoute handler={NotFound} /&gt; &lt;/Route&gt; </code></pre> <p>It works fine. The reason I was nesting was because I will have multiple children under the "dashboard" and wanted them all prefixed with <code>dashboard</code> in the URL.</p>
27,670,456
3
0
null
2014-12-23 01:05:41.81 UTC
8
2015-10-21 04:18:18.087 UTC
2015-01-20 16:16:55.603 UTC
null
1,090,839
null
11,388
null
1
29
reactjs|react-router
27,157
<p>The configuration isn't about the routing (despite the name) but more about the layouts driven by paths.</p> <p>So, with this configuration:</p> <pre><code>&lt;Route name="dashboard" handler={availableRoutes.Dashboard}&gt; &lt;Route name="dashboard-child" handler={availableRoutes.DashboardChild} /&gt; &lt;/Route&gt; </code></pre> <p>It is saying that <code>dashboard-child</code> is to be embedded inside <code>dashboard</code>. How this works is that if <code>dashboard</code> has something like this:</p> <pre><code>&lt;div&gt;&lt;h1&gt;Dashboard&lt;/h1&gt;&lt;RouteHandler /&gt;&lt;/div&gt; </code></pre> <p>and <code>dashboard-child</code> has:</p> <pre><code>&lt;h2&gt;I'm a child of dashboard.&lt;/h2&gt; </code></pre> <p>Then for the path <code>dashboard</code> there is no embedded child due to no matching path, resulting in this:</p> <pre><code>&lt;div&gt;&lt;h1&gt;Dashboard&lt;/h1&gt;&lt;/div&gt; </code></pre> <p>And for the path <code>dashboard/dashboard-child</code> the embedded child has a matching path, resulting in this:</p> <pre><code>&lt;div&gt;&lt;h1&gt;Dashboard&lt;/h1&gt;&lt;h2&gt;I'm a child of dashboard.&lt;/h2&gt;&lt;/div&gt; </code></pre>
27,563,402
Work with JSON schema in CouchDB
<p>I would ask about good practicies about JSON schematics in CouchDB. I use pure CouchDB 1.6.1 at this moment. I handle it without any couchapp framework ( I know this is usefull, but I am concerned about it will be functional in future ).</p> <ul> <li><p>Where put schema in CouchDB ? As regular document? Design document ? Or maybe store them as file ? But if I would validate them, especially server-side in validate_doc_update function, they should be stored in design documents.</p></li> <li><p>Is there any library (JavaScript will be best) with works in CouchDB and Client (Web browser) ? Library with I could generate JSONs and validate them automatically ?</p></li> <li><p>I think about how to send data to client, store them in input tags, and then collect somehow and send to serwer. Maybe set input id as path to field, in example:</p> <p>{ "Adress" :{ "Street" : "xxx", "Nr" : "33" } }</p></li> </ul> <p>In that case input could have id = "Adress."Street", but I do not know is this good solution. I should send schema from server and build JSON object using this schema, but no idea how (in case that all fields in JSON had unique names - including hierarchies).</p>
27,605,330
3
0
null
2014-12-19 09:50:29.153 UTC
10
2016-09-07 16:27:48.227 UTC
null
null
null
null
4,252,043
null
1
6
javascript|json|couchdb|schema
4,672
<p>You ask the same question I had for years while exploring the potential advantages of CouchDB in Forms-over-Data use-cases.</p> <p>Initially my hope was to find an approach that enables data validation based on the same JSON schema definition and validation code - server- and client-side. It has turned out that it is not only possible but also some additionally advantages existing.</p> <blockquote> <p>Where put schema in CouchDB ? As regular document? Design document ? Or maybe store them as file ? But if I would validate them, especially server-side in validate_doc_update function, they should be stored in design documents.</p> </blockquote> <p>You are right. The design doc (ddoc) that also includes the validate_doc_update function to execute the validation before the doc update is the most common place to put the schemata in. <code>this</code> in the validate_doc_update function is the ddoc itself - everything included in the ddoc can be accessed from the validation code.</p> <p>I had began to store schemata as JSON object in my general library property/folder for commonjs modules e.g. <code>lib/schemata.json</code>. The <code>type</code> property of my docs specified the key of the schema that the doc update validation should fetch e.g. <code>type: 'adr'</code> -> <code>lib/schemata/adr</code>. A schema could also refer to other schemata per property - a recursive validation function has traversed to the end of any property no matter from what type the nested properties were. It has worked well in the first project.</p> <pre><code>{ "person": { "name": "/type/name", "adr": "/type/adr", ... }, "name": { "forname": { "minlenght": 2, "maxlength": 42, ... }, "surname": { ... } }, "adr": { ... } } </code></pre> <p>But then i wanted to use a subset of that schemata in another project. To simply copy it over and to add/remove some schemata would have been too short-sighted thinking. What if a general schema like for an address have a bug and needs to be updated in every project it is used?</p> <p>At this point my schemata were stored in one file in the repository (i use <a href="https://github.com/benoitc/erica" rel="noreferrer">erica</a> as upload tool for ddocs). Then I realized that when I store every schema in a separated file e.g. <code>adr.json</code>, <code>geo.json</code>, <code>tel.json</code> etc. it results in the same JSON-structure in the servers ddoc as before with the single file approach. But it was more suitable for source code management. Not only that smaller files result in lesser merge conflicts and a cleaner commit history - also schemata dependency management via sub-repositories (submodules) was enabled.</p> <p>Another thought was to use CouchDB itself as schemata storage and management place. But as you have mentioned it by yourself - the schemata have to be accessible in the validate_doc_update function. First I tried an approach with an update handler - every doc update have to pass a validation update handler that fetches the right schema from the CouchDB by itself:</p> <pre><code>POST /_design/validator/_update/doctype/person function (schema, req) { ... //validate req.body against schema "person" return [req.body, {code: 202, headers: ...}] } </code></pre> <p>But that approach doesn't works well with nested schemata. Even worse - for preventing doc updates without the validation through the handler I had to use a proxy in front of CouchDB to hide the direct built-in doc update paths (e.g. POST to/the/doc/_id). I didn't found a way to detect in the validate_doc_update function whether the update handler was involved before or not (Maybe someone else has? I would be glad to read such an solution.).</p> <p>During that investigation the problem of different versions of the same schema shows up on my radar. How should I manage that? Must all docs from the same type be valid against the same schema version (what means to need a db-wide data migration before nearly every schema version change)? Should the type property also include a version number? etc.</p> <p>But wait! What if the schema of a document is attached to the document itself? It:</p> <ul> <li>will provide the compatible version to the doc contents <strong>per doc</strong></li> <li>be accessible in the validate_doc_update function (in <code>oldDoc</code>)</li> <li>can be replicated without administrator access rights (as you need for ddoc updates)</li> <li>will be included in every response for a client-side doc request</li> </ul> <p><strong>That sounded very interesting and it feels to me like the most CouchDB-ish approach until now.</strong> To say it clearly - <em>the schema of a document is attached to the document itself</em> - means to store it in a property of the doc. Both the storage as attachment and the usage of the schema itself as doc structure were not successfully.</p> <p>The most sensitive moment of that approach is the <strong>C</strong> (create) in the CRUD life-circle of a doc. There are many different solutions imaginable to ensure that the attached schema is "correct and acceptable". But it depends on your definition of that terms in your particular project.</p> <blockquote> <p>Is there any library (JavaScript will be best) with works in CouchDB and Client (Web browser) ? Library with I could generate JSONs and validate them automatically ?</p> </blockquote> <p>I had began to implement with the popular <a href="http://jqueryvalidation.org/" rel="noreferrer">JQuery Validation plugin</a>. I could use the schema as configuration and got neat client-side validation automatically. At the server-side I have extracted the validation functions as commonjs module. I expected to find a modular way for code management later that prevents code duplication. </p> <p>It has turned out that most of the existing validation frameworks are very good in pattern matching and single-property-validations but not capable to validate against depend values in the same document. Also the schema definition requirements are often too proprietary. For me the rule of thumb for choosing the right schema definition is: prefer a standardized definition (jsonschema.org, microdata, rdfa, hcard etc.) over own implementation. If you leave the structure and property names as-they-are you will need less documentation, less transformation and sometimes you get compatibility to foreign software your users use too (e.g. calendars, address books etc.) automatically. If you want to implement a HTML presentation for your docs you are well prepared to do it in semantic web-ish and SEO-zed way.</p> <p>And finally - without wishing to sound arrogant - to write a schema validation implementation is not difficult. Maybe you want to read the source code of the JQuery Validation Plugin - i'm sure you find that like me surprising comprehensible. In times where the churn rate of front-end frameworks is increasing it maybe is the most future-proof way to have an own validation function. Also I believe you should have a 100% understanding of the validation implementation - it is a critical part of your application. And if you understand a foreign implementation - you can also write the library by yourself.</p> <p><em>Ok. That is a loooong answer. Sorry. If someone reads this to the end and want to see it detailed in action with example source code - upvote and I will write a blog post and append the URI as comment.</em></p>
29,117,882
Debugging JavaScript in Chromium Embedded Framework
<p>I have a WPF application which uses CEF to display web content. My question is, is there a way to debug the Javascript/Web parts inside a WPF application?</p>
35,560,835
6
0
null
2015-03-18 09:08:49.62 UTC
8
2022-04-13 07:51:35.147 UTC
2015-03-18 13:10:28.48 UTC
null
3,737,039
null
3,737,039
null
1
29
wpf|debugging|chromium-embedded
37,203
<p>You may also use <code>ShowDevTools()</code> extension method (<a href="https://github.com/cefsharp/CefSharp/blob/28f43261b6616d4fe6b8b2d19b76454ba293d9b4/CefSharp/WebBrowserExtensions.cs#L668" rel="noreferrer">source</a>)</p> <pre><code>ChromiumWebBrowser browser = new ChromiumWebBrowser(); browser.ShowDevTools(); // Opens Chrome Developer tools window </code></pre> <p><a href="https://i.stack.imgur.com/PWbm6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PWbm6.png" alt="CEFSharp Developer Tools window"></a></p>
31,977,563
How do you convert a datetime/timestamp from one timezone to another timezone?
<p>Specifically, given the timezone of my server (system time perspective) and a timezone input, how do I calculate the system time as if it were in that new timezone (regardless of daylight savings, etc)?</p> <pre><code>import datetime current_time = datetime.datetime.now() #system time server_timezone = "US/Eastern" new_timezone = "US/Pacific" current_time_in_new_timezone = ??? </code></pre>
31,977,588
3
0
null
2015-08-13 00:23:22.163 UTC
13
2022-04-04 22:34:23.743 UTC
2022-04-04 22:34:23.743 UTC
null
3,001,761
null
2,812,260
null
1
52
python|datetime|timezone|pytz|timedelta
76,817
<p>If you know your origin timezone and the new timezone that you want to convert it to, it turns out to be very straightforward:</p> <ol> <li><p>Make two <code>pytz.timezone</code> objects, one for the current timezone and one for the new timezone e.g. <code>pytz.timezone(&quot;US/Pacific&quot;)</code>. You can find a list of all official timezones in <code>pytz</code> library: <code>import pytz; pytz.all_timezones</code></p> </li> <li><p>Localize the datetime/timestamp of interest to the current timezone e.g.</p> </li> </ol> <pre><code>current_timezone = pytz.timezone(&quot;US/Eastern&quot;) localized_timestamp = current_timezone.localize(timestamp) </code></pre> <ol start="3"> <li>Convert to new timezone using <code>.astimezone()</code> on the newly localized datetime/timestamp from step 2 with the desired timezone's pytz object as input e.g. <code>localized_timestamp.astimezone(new_timezone)</code>.</li> </ol> <p>Done!</p> <p>As a full example:</p> <pre><code>import datetime import pytz # a timestamp I'd like to convert my_timestamp = datetime.datetime.now() # create both timezone objects old_timezone = pytz.timezone(&quot;US/Eastern&quot;) new_timezone = pytz.timezone(&quot;US/Pacific&quot;) # two-step process localized_timestamp = old_timezone.localize(my_timestamp) new_timezone_timestamp = localized_timestamp.astimezone(new_timezone) # or alternatively, as an one-liner new_timezone_timestamp = old_timezone.localize(my_timestamp).astimezone(new_timezone) </code></pre> <p>Bonus: but if all you need is the current time in a specific timezone, you can conveniently pass that timezone directly into datetime.now() to get the current times directly:</p> <pre><code>datetime.datetime.now(new_timezone) </code></pre> <p>When it comes to needing timezones conversions generally, I would strongly advise that one should store all timestamps in your database in UTC, which has no daylight savings time (DST) transition. And as a good practice, one should always choose to enable time zone support (even if your users are all in a single time zone!). This will help you avoid the DST transition problem that plagues so much software today.</p> <p>Beyond DST, time in software can be generally quite tricky. To get a sense of just how difficult it is to deal with time in software in general, here is a potentially enlightening resource: <a href="http://yourcalendricalfallacyis.com" rel="noreferrer">http://yourcalendricalfallacyis.com</a></p> <p>Even a seemingly simple operation as converting a datetime/timestamp into a date can become non-obvious. As <a href="https://django.readthedocs.io/en/2.2.x/topics/i18n/timezones.html" rel="noreferrer">this helpful documentation</a> points out:</p> <blockquote> <p>A datetime represents a <strong>point in time</strong>. It’s absolute: it doesn’t depend on anything. On the contrary, a date is a <strong>calendaring concept</strong>. It’s a period of time whose bounds depend on the time zone in which the date is considered. As you can see, these two concepts are fundamentally different.</p> </blockquote> <p>Understanding this difference is a key step towards avoiding time-based bugs. Good luck.</p>
28,102,173
Redis, how does SCAN cursor "state management" work?
<p>Redis has a SCAN command that may be used to iterate keys matching a pattern etc.</p> <p><a href="http://redis.io/commands/scan" rel="noreferrer">Redis SCAN doc</a></p> <p>You start by giving a cursor value of 0; each call returns a new cursor value which you pass into the next SCAN call. A value of 0 indicates iteration is finished. Supposedly no server or client state is needed (except for the cursor value)</p> <p>I'm wondering how Redis implements the scanning algorithm-wise?</p>
28,104,028
1
0
null
2015-01-23 02:38:12.63 UTC
8
2015-01-23 06:13:11.533 UTC
null
null
null
null
222,593
null
1
15
redis
7,511
<p>You may find answer in redis <a href="https://github.com/antirez/redis/blob/unstable/src/dict.c" rel="noreferrer">dict.c</a> source file. Then I will quote part of it.</p> <p>Iterating works the following way:</p> <ol> <li>Initially you call the function using a cursor (v) value of 0. 2)</li> <li>The function performs one step of the iteration, and returns the<br /> new cursor value you must use in the next call.</li> <li>When the returned cursor is 0, the iteration is complete.</li> </ol> <p>The function guarantees all elements present in the dictionary get returned between the start and end of the iteration. However it is possible some elements get returned multiple times. For every element returned, the callback argument 'fn' is called with 'privdata' as first argument and the dictionary entry'de' as second argument.</p> <h2>How it works</h2> <p>The iteration algorithm was designed by <a href="https://github.com/pietern" rel="noreferrer">Pieter Noordhuis</a>. The main idea is to increment a cursor starting from the higher order bits. That is, instead of incrementing the cursor normally, the bits of the cursor are reversed, then the cursor is incremented, and finally the bits are reversed again.</p> <p>This strategy is needed because the hash table may be resized between iteration calls. <a href="https://github.com/antirez/redis/blob/unstable/src/dict.c" rel="noreferrer">dict.c</a> hash tables are always power of two in size, and they use chaining, so the position of an element in a given table is given by computing the bitwise AND between Hash(key) and SIZE-1 (where SIZE-1 is always the mask that is equivalent to taking the rest of the division between the Hash of the key and SIZE).</p> <p>For example if the current hash table size is 16, the mask is (in binary) 1111. The position of a key in the hash table will always be the last four bits of the hash output, and so forth.</p> <h2>What happens if the table changes in size?</h2> <p>If the hash table grows, elements can go anywhere in one multiple of the old bucket: for example let's say we already iterated with a 4 bit cursor 1100 (the mask is 1111 because hash table size = 16).</p> <p>If the hash table will be resized to 64 elements, then the new mask will be 111111. The new buckets you obtain by substituting in ??1100 with either 0 or 1 can be targeted only by keys we already visited when scanning the bucket 1100 in the smaller hash table.</p> <p>By iterating the higher bits first, because of the inverted counter, the cursor does not need to restart if the table size gets bigger. It will continue iterating using cursors without '1100' at the end, and also without any other combination of the final 4 bits already explored.</p> <p>Similarly when the table size shrinks over time, for example going from 16 to 8, if a combination of the lower three bits (the mask for size 8 is 111) were already completely explored, it would not be visited again because we are sure we tried, for example, both 0111 and 1111 (all the variations of the higher bit) so we don't need to test it again.</p> <h2>Wait... You have <em>TWO</em> tables during rehashing!</h2> <p>Yes, this is true, but we always iterate the smaller table first, then we test all the expansions of the current cursor into the larger table. For example if the current cursor is 101 and we also have a larger table of size 16, we also test (0)101 and (1)101 inside the larger table. This reduces the problem back to having only one table, where the larger one, if it exists, is just an expansion of the smaller one.</p> <h2>Limitations</h2> <p>This iterator is completely stateless, and this is a huge advantage, including no additional memory used. The disadvantages resulting from this design are:</p> <ol> <li>It is possible we return elements more than once. However this is usually easy to deal with in the application level.</li> <li>The iterator must return multiple elements per call, as it needs to always return all the keys chained in a given bucket, and all the expansions, so we are sure we don't miss keys moving during rehashing.</li> <li>The reverse cursor is somewhat hard to understand at first, but this comment is supposed to help.</li> </ol>
27,148,273
What is the logic of binding buffers in webgl?
<p>I sometimes find myself struggling between declaring the buffers (with createBuffer/bindBuffer/bufferdata) in different order and rebinding them in other parts of the code, usually in the draw loop.</p> <p>If I don't rebind the vertex buffer before drawing arrays, the console complains about an attempt to access out of range vertices. My suspect is the the last bound object is passed at the pointer and then to the drawarrays but when I change the order at the beginning of the code, nothing changes. What effectively works is rebinding the buffer in the draw loop. So, I can't really understand the logic behind that. When do you need to rebind? Why do you need to rebind? What is attribute0 referring to?</p>
27,164,577
1
0
null
2014-11-26 11:42:12.207 UTC
13
2022-04-17 01:55:51.917 UTC
null
null
null
user2618518
null
null
1
13
javascript|webgl
8,290
<p>I don't know if this will help. As some people have said, GL/WebGL has a bunch of internal <strong>state</strong>. All the functions you call set up the state. When it's all setup you call <code>drawArrays</code> or <code>drawElements</code> and all of that state is used to draw things</p> <p>This has been explained elsewhere on SO but binding a buffer is just setting 1 of 2 global variables inside WebGL. After that you refer to the buffer by its bind point.</p> <p>You can think of it like this</p> <pre><code>gl = function() { // internal WebGL state let lastError; let arrayBuffer = null; let vertexArray = { elementArrayBuffer: null, attributes: [ { enabled: false, type: gl.FLOAT, size: 3, normalized: false, stride: 0, offset: 0, buffer: null }, { enabled: false, type: gl.FLOAT, size: 3, normalized: false, stride: 0, offset: 0, buffer: null }, { enabled: false, type: gl.FLOAT, size: 3, normalized: false, stride: 0, offset: 0, buffer: null }, { enabled: false, type: gl.FLOAT, size: 3, normalized: false, stride: 0, offset: 0, buffer: null }, { enabled: false, type: gl.FLOAT, size: 3, normalized: false, stride: 0, offset: 0, buffer: null }, ... ], } // these values are used when a vertex attrib is disabled let attribValues = [ [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 0, 1], ... ]; ... // Implementation of gl.bindBuffer. // note this function is doing nothing but setting 2 internal variables. this.bindBuffer = function(bindPoint, buffer) { switch(bindPoint) { case gl.ARRAY_BUFFER; arrayBuffer = buffer; break; case gl.ELEMENT_ARRAY_BUFFER; vertexArray.elementArrayBuffer = buffer; break; default: lastError = gl.INVALID_ENUM; break; } }; ... }(); </code></pre> <p>After that other WebGL functions reference those. For example <code>gl.bufferData</code> might do something like</p> <pre><code> // implementation of gl.bufferData // Notice you don't pass in a buffer. You pass in a bindPoint. // The function gets the buffer one of its internal variable you set by // previously calling gl.bindBuffer this.bufferData = function(bindPoint, data, usage) { // lookup the buffer from the bindPoint var buffer; switch (bindPoint) { case gl.ARRAY_BUFFER; buffer = arrayBuffer; break; case gl.ELEMENT_ARRAY_BUFFER; buffer = vertexArray.elemenArrayBuffer; break; default: lastError = gl.INVALID_ENUM; break; } // copy data into buffer buffer.copyData(data); // just making this up buffer.setUsage(usage); // just making this up }; </code></pre> <p>Separate from those bindpoints there's number of attributes. The attributes are also global state by default. They define how to pull data out of the buffers to supply to your vertex shader. Calling <code>gl.getAttribLocation(someProgram, &quot;nameOfAttribute&quot;)</code> tells you which attribute the vertex shader will look at to get data out of a buffer.</p> <p>So, there's 4 functions that you use to configure how an attribute will get data from a buffer. <code>gl.enableVertexAttribArray</code>, <code>gl.disableVertexAttribArray</code>, <code>gl.vertexAttribPointer</code>, and <code>gl.vertexAttrib??</code>.</p> <p>They're effectively implemented something like this</p> <pre><code>this.enableVertexAttribArray = function(location) { const attribute = vertexArray.attributes[location]; attribute.enabled = true; // true means get data from attribute.buffer }; this.disableVertexAttribArray = function(location) { const attribute = vertexArray.attributes[location]; attribute.enabled = false; // false means get data from attribValues[location] }; this.vertexAttribPointer = function(location, size, type, normalized, stride, offset) { const attribute = vertexArray.attributes[location]; attribute.size = size; // num values to pull from buffer per vertex shader iteration attribute.type = type; // type of values to pull from buffer attribute.normalized = normalized; // whether or not to normalize attribute.stride = stride; // number of bytes to advance for each iteration of the vertex shader. 0 = compute from type, size attribute.offset = offset; // where to start in buffer. // IMPORTANT!!! Associates whatever buffer is currently *bound* to // &quot;arrayBuffer&quot; to this attribute attribute.buffer = arrayBuffer; }; this.vertexAttrib4f = function(location, x, y, z, w) { const attrivValue = attribValues[location]; attribValue[0] = x; attribValue[1] = y; attribValue[2] = z; attribValue[3] = w; }; </code></pre> <p>Now, when you call <code>gl.drawArrays</code> or <code>gl.drawElements</code> the system knows how you want to pull data out of the buffers you made to supply your vertex shader. <a href="http://webglfundamentals.org/webgl/lessons/webgl-how-it-works.html" rel="nofollow noreferrer">See here for how that works</a>.</p> <p>Since the attributes are <strong>global state</strong> that means every time you call <code>drawElements</code> or <code>drawArrays</code> how ever you have the attributes setup is how they'll be used. If you set up attributes #1 and #2 to buffers that each have 3 vertices but you ask to draw 6 vertices with <code>gl.drawArrays</code> you'll get an error. Similarly if you make an index buffer which you bind to the <code>gl.ELEMENT_ARRAY_BUFFER</code> bindpoint and that buffer has an indice that is &gt; 2 you'll get that <code>index out of range</code> error. If your buffers only have 3 vertices then the only valid indices are <code>0</code>, <code>1</code>, and <code>2</code>.</p> <p>Normally, every time you draw something different you rebind all the attributes needed to draw that thing. Drawing a cube that has positions and normals? Bind the buffer with position data, setup the attribute being used for positions, bind the buffer with normal data, setup the attribute being used for normals, now draw. Next you draw a sphere with positions, vertex colors and texture coordinates. Bind the buffer that contains position data, setup the attribute being used for positions. Bind the buffer that contains vertex color data, setup the attribute being used for vertex colors. Bind the buffer that contains texture coordinates, setup the attribute being used for texture coordinates.</p> <p>The only time you don't rebind buffers is if you're drawing the same thing more than once. For example drawing 10 cubes. You'd rebind the buffers, then set the uniforms for one cube, draw it, set the uniforms for the next cube, draw it, repeat.</p> <p>I should also add that there's an extension [<code>OES_vertex_array_object</code>] which is also a feature of WebGL 2.0. A Vertex Array Object is the global state above called <code>vertexArray</code> which includes the <code>elementArrayBuffer</code> and all the attributes.</p> <p>Calling <code>gl.createVertexArray</code> makes new one of those. Calling <code>gl.bindVertexArray</code> sets the global <code>attributes</code> to point to the one in the bound vertexArray.</p> <p>Calling <code>gl.bindVertexArray</code> would then be</p> <pre><code> this.bindVertexArray = function(vao) { vertexArray = vao ? vao : defaultVertexArray; } </code></pre> <p>This has the advantage of letting you set up all attributes and buffers at init time and then at draw time just 1 WebGL call will set all buffers and attributes.</p> <p>Here is a <a href="https://webglfundamentals.org/webgl/lessons/resources/webgl-state-diagram.html" rel="nofollow noreferrer">webgl state diagram</a> that might help visualize this better.</p>
40,378,320
How to include Roboto font in webpack build for Material UI?
<p>For a <em>progressive</em> web app based on <a href="http://www.material-ui.com/" rel="noreferrer">Material UI</a> (React) and built with <strong>Webpack</strong>, how do I properly include Roboto font(s) so that the app does not depend on Google servers and fonts also work <em>offline</em> ?</p> <ul> <li><p>The <a href="http://www.material-ui.com/#/get-started/installation" rel="noreferrer">installation page</a> just references the <a href="http://www.google.com/fonts#UsePlace:use/Collection:Roboto:400,300,500" rel="noreferrer">Google fonts page</a>, but that obviously forces fonts to be downloaded from Google servers.</p></li> <li><p>A similar <a href="https://github.com/callemall/material-ui/issues/4819" rel="noreferrer">Material UI Issue</a> exists regarding Roboto font, but still relies on Google providing the font files.</p></li> <li><p>I found a <a href="https://www.npmjs.com/package/roboto-fontface" rel="noreferrer">NPM package providing the Roboto font files</a>, but I'm not sure how to include those files as lots of styles and font formats are provided and <strong>I don't know what styles Material UI really needs</strong>. Also, importing those font families simply via @import seems to have <a href="https://github.com/callemall/material-ui/issues/104#issue-50455732" rel="noreferrer">performance issues</a>.</p></li> </ul> <p>So, what is a good and simple solution to bundle the <em>right</em> Roboto files with my application?</p>
41,255,971
6
1
null
2016-11-02 11:01:46.16 UTC
24
2021-10-26 15:50:37.583 UTC
null
null
null
null
688,869
null
1
68
webpack|webfonts|material-ui|roboto
66,440
<p>This is how my team went about including the Roboto fonts in our Webpack project:</p> <h1>Download the Roboto fonts and make a CSS file in a font-specific folder</h1> <ul> <li>Create a folder (<code>/fonts</code>).</li> <li>Download all of the Roboto fonts from <a href="https://www.fontsquirrel.com/fonts/roboto" rel="noreferrer">Font Squirrel</a>. Go to the <strong>Webfont Kit</strong> tab, then press the <strong>Download @font-face Kit</strong> button with default settings.</li> <li>Move the fonts into <code>/fonts</code>.</li> <li>Create the CSS file (<code>/fonts/index.css</code>). We got the contents for this file from <a href="https://www.maketecheasier.com/use-google-roboto-font-everywhere/" rel="noreferrer">this tutorial</a>.</li> </ul> <p><strong>index.css:</strong></p> <pre><code>* { font-family: Roboto, sans-serif; } @font-face { font-family: 'Roboto'; src: url('Roboto-Regular-webfont.eot'); src: url('Roboto-Regular-webfont.eot?#iefix') format('embedded-opentype'), url('Roboto-Regular-webfont.woff') format('woff'), url('Roboto-Regular-webfont.ttf') format('truetype'), url('Roboto-Regular-webfont.svg#RobotoRegular') format('svg'); font-weight: normal; font-style: normal; } @font-face { font-family: 'Roboto'; src: url('Roboto-Italic-webfont.eot'); src: url('Roboto-Italic-webfont.eot?#iefix') format('embedded-opentype'), url('Roboto-Italic-webfont.woff') format('woff'), url('Roboto-Italic-webfont.ttf') format('truetype'), url('Roboto-Italic-webfont.svg#RobotoItalic') format('svg'); font-weight: normal; font-style: italic; } @font-face { font-family: 'Roboto'; src: url('Roboto-Bold-webfont.eot'); src: url('Roboto-Bold-webfont.eot?#iefix') format('embedded-opentype'), url('Roboto-Bold-webfont.woff') format('woff'), url('Roboto-Bold-webfont.ttf') format('truetype'), url('Roboto-Bold-webfont.svg#RobotoBold') format('svg'); font-weight: bold; font-style: normal; } @font-face { font-family: 'Roboto'; src: url('Roboto-BoldItalic-webfont.eot'); src: url('Roboto-BoldItalic-webfont.eot?#iefix') format('embedded-opentype'), url('Roboto-BoldItalic-webfont.woff') format('woff'), url('Roboto-BoldItalic-webfont.ttf') format('truetype'), url('Roboto-BoldItalic-webfont.svg#RobotoBoldItalic') format('svg'); font-weight: bold; font-style: italic; } @font-face { font-family: 'Roboto'; src: url('Roboto-Thin-webfont.eot'); src: url('Roboto-Thin-webfont.eot?#iefix') format('embedded-opentype'), url('Roboto-Thin-webfont.woff') format('woff'), url('Roboto-Thin-webfont.ttf') format('truetype'), url('Roboto-Thin-webfont.svg#RobotoThin') format('svg'); font-weight: 200; font-style: normal; } @font-face { font-family: 'Roboto'; src: url('Roboto-ThinItalic-webfont.eot'); src: url('Roboto-ThinItalic-webfont.eot?#iefix') format('embedded-opentype'), url('Roboto-ThinItalic-webfont.woff') format('woff'), url('Roboto-ThinItalic-webfont.ttf') format('truetype'), url('Roboto-ThinItalic-webfont.svg#RobotoThinItalic') format('svg'); (under the Apache Software License). font-weight: 200; font-style: italic; } @font-face { font-family: 'Roboto'; src: url('Roboto-Light-webfont.eot'); src: url('Roboto-Light-webfont.eot?#iefix') format('embedded-opentype'), url('Roboto-Light-webfont.woff') format('woff'), url('Roboto-Light-webfont.ttf') format('truetype'), url('Roboto-Light-webfont.svg#RobotoLight') format('svg'); font-weight: 100; font-style: normal; } @font-face { font-family: 'Roboto'; src: url('Roboto-LightItalic-webfont.eot'); src: url('Roboto-LightItalic-webfont.eot?#iefix') format('embedded-opentype'), url('Roboto-LightItalic-webfont.woff') format('woff'), url('Roboto-LightItalic-webfont.ttf') format('truetype'), url('Roboto-LightItalic-webfont.svg#RobotoLightItalic') format('svg'); font-weight: 100; font-style: italic; } @font-face { font-family: 'Roboto'; src: url('Roboto-Medium-webfont.eot'); src: url('Roboto-Medium-webfont.eot?#iefix') format('embedded-opentype'), url('Roboto-Medium-webfont.woff') format('woff'), url('Roboto-Medium-webfont.ttf') format('truetype'), url('Roboto-Medium-webfont.svg#RobotoMedium') format('svg'); font-weight: 300; font-style: normal; } @font-face { font-family: 'Roboto'; src: url('Roboto-MediumItalic-webfont.eot'); src: url('Roboto-MediumItalic-webfont.eot?#iefix') format('embedded-opentype'), url('Roboto-MediumItalic-webfont.woff') format('woff'), url('Roboto-MediumItalic-webfont.ttf') format('truetype'), url('Roboto-MediumItalic-webfont.svg#RobotoMediumItalic') format('svg'); font-weight: 300; font-style: italic; } </code></pre> <h1>Use the file-loader webpack module to load in the font files so webpack can recognize them</h1> <ul> <li><code>npm install --save file-loader</code> (<a href="https://www.npmjs.com/package/file-loader" rel="noreferrer">https://www.npmjs.com/package/file-loader</a>)</li> <li>In your webpack config, use the loader like so:</li> </ul> <p><strong>webpack.conf.js:</strong></p> <pre><code>loaders: [ ..., { test: /\.(woff|woff2|eot|ttf|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]', outputPath: 'fonts/', } }, ... ] </code></pre> <h1>Import the font css file in the main entry of the app</h1> <p><strong>App.js:</strong></p> <pre><code>import './fonts/index.css'; </code></pre> <p>And that's it. Your application's default font should now be Roboto.</p> <h1>EDIT: Which Roboto Fonts does Material-UI actually use?</h1> <p>Part of this question is determining the <em>right</em> Roboto fonts to include in the project since the entirety of the Roboto fonts is almost 5MB.</p> <p>In the <a href="https://github.com/callemall/material-ui#roboto-font" rel="noreferrer">README</a>, the instructions for including Roboto point to: <a href="https://fonts.google.com/?selection.family=Roboto:300,400,500" rel="noreferrer">fonts.google.com/?selection.family=Roboto:300,400,500</a>. Here, 300 = Roboto-Light, 400 = Roboto-Regular, and 500 = Roboto-Medium. These correspond to the font weights defined in the <a href="https://github.com/callemall/material-ui/blob/master/src/styles/typography.js#L26" rel="noreferrer">typography.js file</a>. While these three font weights account for usage in almost the entirety of the library, there is one reference to Regular-Bold in <a href="https://github.com/callemall/material-ui/blob/master/src/DatePicker/DateDisplay.js#L15" rel="noreferrer">DateDisplay.js</a>. If you are not using the DatePicker, you should probably be safe to omit that. Italics font styling is not used anywhere in the project aside from the GitHub markdown styling.</p> <p>This information is accurate at the time of this writing, but it may change in the future.</p>
2,536,551
Rhino Mocks - Difference between GenerateStub<T> & GenerateMock<T>
<p>Can any of the Rhino experts explain me by giving a suitable example of the difference between the above methods on the <code>MockRepository</code> class (Rhino Mocks framework).</p> <p>Where should one use Stub over Mock method or otherwise?</p>
2,536,570
1
0
null
2010-03-29 08:18:16.087 UTC
13
2012-05-09 09:16:59.11 UTC
2012-05-09 09:16:59.11 UTC
null
97,614
null
31,750
null
1
36
unit-testing|rhino-mocks
15,266
<p>you should use a mock when you are going to verify that something happened on the object, like a method was called. You should use a stub when you just want the object to be involved in the test to return a value but it is not the thing you are testing. A stub which does not have a expectation fulfilled can never fail a test.</p> <p>I think the general rule should be that you should only ever have a single mock object in a test, but may have several stubs which provide information to the mock object. I believe that more than 1 mock in a test is a code smell.</p> <p>Although not a Rhino example <a href="http://martinfowler.com/articles/mocksArentStubs.html#TheDifferenceBetweenMocksAndStubs" rel="noreferrer">Martin Fowler has a description of the difference</a></p> <p>Also <a href="https://stackoverflow.com/questions/477924/rhino-mocks-stub-expect-vs-assertwascalled">this question</a> might be useful as might <a href="https://stackoverflow.com/questions/1288168/when-to-use-stubs-and-mocks">this one</a></p>
10,724,420
Automatically Update Data in Other Excel Sheets of a Workbook
<p>I have VBA code that takes my data on the "master" worksheet and puts it in the other sheets in a workbook. The problem I am having is that the new data doesn't update automatically. I would like to develop code that will automatically update my worksheets. This is the code that I have now. </p> <pre><code>Sub test() Dim LR As Long, i As Long LR = Range("A" &amp; Rows.Count).End(xlUp).Row For i = 2 To LR If Range("B" &amp; i).Value = "AP" Then Rows(i).Copy Destination:=Sheets("AP").Range("A" &amp; Rows.Count).End(xlUp).Offset(1) If Range("B" &amp; i).Value = "*AP" Then Rows(i).Copy Destination:=Sheets(" If Range("B" &amp; i).Value = "CSW" Then Rows(i).Copy Destination:=Sheets("CSW").Range("A" &amp; Rows.Count).End(xlUp).Offset(1) If Range("B" &amp; i).Value = "CO" Then Rows(i).Copy Destination:=Sheets("CO").Range("A" &amp; Rows.Count).End(xlUp).Offset(1) If Range("B" &amp; i).Value = "PSR" Then Rows(i).Copy Destination:=Sheets("PSR").Range("A" &amp; Rows.Count).End(xlUp).Offset(1) Next i End Sub </code></pre> <p>This puts the data in the other sheets, but when I input new data into the "master" worksheet, the data does not update in the other sheets. I've tried other methods to include auto filter, but they haven't worked.</p>
10,724,763
2
0
null
2012-05-23 16:48:34.283 UTC
2
2013-10-23 23:28:53.71 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
1,413,170
null
1
0
excel|vba
40,579
<p>Use the <code>worksheet_change</code> event in your "master" spreadsheet. When data is updated in the "master" sheet, it will raise the <code>worksheet_change</code> event and you can call your code to update the other sheets.</p> <p>You can find detailed instructions on how to use it here: <a href="http://www.ozgrid.com/VBA/run-macros-change.htm" rel="nofollow">http://www.ozgrid.com/VBA/run-macros-change.htm</a></p> <p>I set up a working example with your code. The workbook has 6 sheets ("master", "AP", "All AP", "CSW", "CO", and "PSR"). Row 1 in each sheet is assumed to be a header row. Once you have your workbook set up with the code below, any changes you make on the "master" sheet will raise the worksheet_change event, causing all of the destination sheets in the workbook to get updated with the most current data.</p> <p>Follow these steps to get it to work:</p> <p>Add the following in the code module of the master sheet:</p> <p>_</p> <pre><code>Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) Call UpdateFromMaster End Sub </code></pre> <p>Add these subs into a standard module:</p> <p>_</p> <pre><code>Sub UpdateFromMaster() ' clear whatever you had previously written to the destination sheets Call ResetDestinationSheets ' the code you already had Dim LR As Long, i As Long LR = Range("A" &amp; Rows.Count).End(xlUp).Row For i = 2 To LR If Range("B" &amp; i).Value = "AP" Then Rows(i).Copy Destination:=Sheets("AP").Range("A" &amp; Rows.Count).End(xlUp).Offset(1) If Range("B" &amp; i).Value = "*AP" Then Rows(i).Copy Destination:=Sheets("All AP").Range("A" &amp; Rows.Count).End(xlUp).Offset(1) If Range("B" &amp; i).Value = "CSW" Then Rows(i).Copy Destination:=Sheets("CSW").Range("A" &amp; Rows.Count).End(xlUp).Offset(1) If Range("B" &amp; i).Value = "CO" Then Rows(i).Copy Destination:=Sheets("CO").Range("A" &amp; Rows.Count).End(xlUp).Offset(1) If Range("B" &amp; i).Value = "PSR" Then Rows(i).Copy Destination:=Sheets("PSR").Range("A" &amp; Rows.Count).End(xlUp).Offset(1) Next i End Sub </code></pre> <p>_</p> <pre><code>Sub ResetDestinationSheets() '== not elegant, but will work in your example Call ResetThisSheet("AP") Call ResetThisSheet("ALL AP") ' I didn't know what you called this sheet Call ResetThisSheet("CSW") Call ResetThisSheet("CO") Call ResetThisSheet("PSR") End Sub </code></pre> <p>_</p> <pre><code>Sub ResetThisSheet(ByRef SheetToClear As String) Sheets(SheetToClear).Range("A2:B" &amp; Rows.Count).Clear End Sub </code></pre>
37,347,415
Laravel: Access Model instance in Form Request when using Route/Model binding
<p>I have some route/model binding set up in my project for one of my models, and that works just fine. I'm able to use my binding in my route path and accept an instance of my model as a parameter to the relevant method in my controller.</p> <p>Now I'm trying to do some work with this model, so I have created a method in my controller that accepts a Form Request so I can carry out some validation.</p> <pre><code>public function edit(EditBrandRequest $request, Brand $brand) { // ... </code></pre> <p>Each different instance of my model can be validated differently, so I need to be able to use an instance of the model in order to build a custom set of validation rules.</p> <p><strong>Is there a way of getting the instance of the model, that is injected into the controller from the Form Request?</strong></p> <p>I have tried type-hinting the model instance in the Form Request's constructor</p> <pre><code>class EditBrandRequest extends Request { public function __construct(Brand $brand) { dd($brand); } </code></pre> <p>I have also tried type-hinting the model instance in the Form Request's <code>rules()</code> method.</p> <pre><code>class EditBrandRequest extends Request { // ... public function rules(Brand $brand) { dd($brand); </code></pre> <p>In both instances I am provided an empty/new instance of the model, rather than the instance I am expecting.</p> <p>Of course, I could always get around this by not bothering with Form Requests and just generate the rules in the controller and validate manually - but I would rather do it the <em>Laravel way</em> if it's possible.</p> <p>Thanks</p>
37,347,678
1
0
null
2016-05-20 12:58:59.043 UTC
3
2018-03-09 12:26:00.247 UTC
null
null
null
null
2,244,675
null
1
44
php|laravel|laravel-5
21,332
<p>You can simply access it using the binding key, so for example if you bind <code>Brand</code> model: <code>$router-&gt;model('brand', '\App\Brand')</code> you can get instance of your model with <code>$this-&gt;brand</code>. Here is validation rules example:</p> <pre><code>'slug' =&gt; 'required|unique:brand,slug,' . $this-&gt;brand-&gt;id, </code></pre> <p><strong>EDIT</strong></p> <p>Sometimes you might have an input name that uses the same name as the binding key, for example, if you bind <code>Address</code> model as <code>address</code> then you have an input field <code>address</code> it will make Laravel confuse. For this situation you can use <code>route()</code> method.</p> <pre><code>'address' =&gt; 'required|unique:addresses,address,' . $this-&gt;route('address')-&gt;id, </code></pre>
6,228,960
How to set the "Content-Type ... charset" in the request header using a HTML link
<p>I have a simple HTML-page with a UTF-8 encoded link.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv=&quot;content-type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt; &lt;/head&gt; &lt;body&gt; &lt;a charset='UTF-8' href='http://server/search?q=%C3%BC'&gt;search for &quot;ü&quot;&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>However, I don't get the browser to include <code>Content-Type:application/x-www-form-urlencoded; charset=utf-8</code> into the request header. Therefore I have to configure the web server to assume all requests are UTF-8 encoded (URIEncoding=&quot;UTF-8&quot; in the <a href="https://en.wikipedia.org/wiki/Apache_Tomcat" rel="nofollow noreferrer">Tomcat</a> <em>server.xml</em> file). But of course the admin won't let me do that in the production environment (<a href="https://en.wikipedia.org/wiki/IBM_WebSphere" rel="nofollow noreferrer">WebSphere</a>).</p> <p>I know it's quite easy to achieve using Ajax, but how can I control the request header when using standard HTML links? The <code>charset</code> attribute doesn't seem to work for me (tested in <a href="https://en.wikipedia.org/wiki/Internet_Explorer_8" rel="nofollow noreferrer">Internet Explorer 8</a> and Firefox 3.5)</p> <p>The second part of the required solution would be to set the URL encoding when changing an IFrame's <code>document.location</code> using JavaScript.</p>
6,229,984
1
3
null
2011-06-03 15:13:52.723 UTC
1
2021-08-15 11:41:13.4 UTC
2021-08-15 11:36:21.963 UTC
null
63,550
null
701,753
null
1
22
html|character-encoding|special-characters|urlencode
132,470
<p>This is not possible from HTML on.</p> <p>The closest what you can get is the <code>accept-charset</code> attribute of the <code>&lt;form&gt;</code>. Only Internet Explorer adheres that, but even then it is doing it wrong (e.g., CP-1252 is <em>actually</em> been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the <code>Content-Type</code> header of the response.</p> <p>Setting the character encoding right is basically fully the responsibility of the server side. The client side should just send it back in the same charset as the server has sent the response in.</p> <p>To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit the <code>URIEncoding</code> attribute, someone here on Stack Overflow wrote a (complex) filter: <em><a href="https://stackoverflow.com/questions/2657515/detect-the-uri-encoding-automatically-in-tomcat">Detect the URI encoding automatically in Tomcat</a></em>. You may find it useful as well (note: I haven't tested it).</p> <hr /> <p>Noted should be that the meta tag as given in your question is <strong>ignored</strong> when the content is been transferred over HTTP. Instead, the HTTP response <code>Content-Type</code> header will be used to determine the content type and character encoding. You can determine the HTTP header with for example <a href="http://getfirebug.com" rel="nofollow noreferrer">Firebug</a>, in the <em>Net</em> panel.</p> <p><img src="https://i.stack.imgur.com/diSbx.png" alt="Alt text" /></p>
24,658,007
How can I confirm what version of Jasmine I'm using?
<p>If I recall there is a command in Jasmine that will log the exact version of Jasmine I'm running to the console, but I can't remember what it is. I am positive I have seen this before somewhere, and now that I actually need it I can't find it anywhere. Does anyone know what it is?</p> <hr> <p>Edit: The posted solution of using <code>jasmine.getEnv().versionString()</code> isn't working - to any mods reading this, would fixing that issue be better to start as a new question, or continue here?</p>
24,919,927
5
0
null
2014-07-09 15:38:28.303 UTC
4
2018-09-04 05:08:35.653 UTC
2014-07-09 15:57:59.43 UTC
null
3,392,912
null
3,392,912
null
1
45
unit-testing|version|jasmine|phantomjs|versioning
27,407
<p>To simply log the version number try: </p> <pre><code> if (jasmine.version) { //the case for version 2.0.0 console.log('jasmine-version:' + jasmine.version); } else { //the case for version 1.3 console.log('jasmine-version:' + jasmine.getEnv().versionString()); } </code></pre> <p>I use this little helper function:</p> <pre><code> this.isJasmineV2 = function () { return (jasmine.version &amp;&amp; jasmine.version.charAt(0) === "2"); //version 1.3 uses this syntax: jasmine.getEnv().versionString() }; </code></pre>
27,382,481
Why does Visual Studio tell me that the AddJsonFile() method is not defined?
<p>I'm developing an ASP.NET 5 WebAPI project using VS Ultimate 2015 Preview. I'm trying to configure the app in this way (line numbers are just guides):</p> <pre><code>1 using Microsoft.Framework.ConfigurationModel; 2 3 public IConfiguration Configuration { get; private set; } 4 5 public Startup() 6 { 7 Configuration = new Configuration() 8 .AddJsonFile("config.json") 9 .AddEnvironmentVariables(); 10 } </code></pre> <p>Line 8 gives me an error: 'Configuration' does not contain a definition for 'AddJsonFile'...</p> <p>What is wrong?</p>
27,382,878
4
0
null
2014-12-09 15:20:09.36 UTC
9
2020-06-02 11:45:05.897 UTC
2019-06-20 19:13:36.23 UTC
null
2,574,407
null
3,802,403
null
1
104
c#|configuration|configuration-files|asp.net-core|config.json
78,544
<p>You need to include the <a href="https://www.nuget.org/packages/Microsoft.Extensions.Configuration.Json/" rel="noreferrer"><code>Microsoft.Extensions.Configuration.Json</code></a> NuGet package if you want to call the <code>.AddJsonFile()</code> method.</p> <p>See: <a href="https://github.com/aspnet/Configuration/tree/dev/src/Microsoft.Framework.ConfigurationModel.Json" rel="noreferrer">https://github.com/aspnet/Configuration/tree/dev/src/Microsoft.Framework.ConfigurationModel.Json</a></p> <p>For further reading, here's a nice tutorial: <a href="https://web.archive.org/web/20161225003827/https://whereslou.com/2014/05/23/asp-net-vnext-moving-parts-iconfiguration/" rel="noreferrer">ASP.NET vNext Moving Parts: IConfiguration</a>.</p>
38,879,529
How to route to a Module as a child of a Module - Angular 2 RC 5
<p>I am in the process upgrading an application I'm working on to the latest Angular 2 release candidate. As part of this work I am attempting to use the NgModule spec and migrating all of the parts of my application to modules. For the most part, this has gone very well with the exception of an issue with routing.</p> <pre><code>"@angular/common": "2.0.0-rc.5", "@angular/compiler": "2.0.0-rc.5", "@angular/core": "2.0.0-rc.5", "@angular/forms": "0.3.0", "@angular/http": "2.0.0-rc.5", "@angular/platform-browser": "2.0.0-rc.5", "@angular/platform-browser-dynamic": "2.0.0-rc.5", "@angular/router": "3.0.0-rc.1", </code></pre> <p>My app is built as a composition of modules, with several modules being glued together as children of a parent module. For example, I have an Admin Module that consists of a Notifications Module, a Users Module, and a Telphony Module (for example). The routes to these modules should look like...</p> <pre><code>/admin/notifications/my-notifications /admin/users/new-user /admin/telephony/whatever </code></pre> <p>In the earlier release of the router, this was easy to accomplish using "children"</p> <pre><code>export const AdminRoutes: RouterConfig = [ { path: "Admin", component: AdminComponent, Children: [ ...UserRoutes, ...TelephonyRoutes, ...NotificationRoutes ] } ] </code></pre> <p>In another file, as part of the sub-modules, I'd define the individual module routes as well i.e.</p> <pre><code>export const UserRoutes: RouterConfig = [ { path: "users", component: userComponent, children: [ {path: "new-user", component: newUserComponent} ] } ] </code></pre> <p>This all worked very well. In the process of upgrading to Modules, I moved everything into their own individual routing files instead so now these two look more like this</p> <pre><code>const AdminRoutes: Routes = [ {path: "admin", component: AdminComponent} ] export const adminRouting = RouterModule.forChild(AdminRoutes) </code></pre> <p>and</p> <pre><code>const UserRoutes: Routes = [ path: "users", component: userComponent, children: [ {path: "new-user", component: newUserComponent} ] ] export const userRouting = RouterModule.forChild(UserRoutes) </code></pre> <p>With all of that in place, I have a UsersModule which imports the userRouting, and then an AdminModule that imports the adminRoutes and the UsersModule. My thought was that since UsersModule is a child of AdminModule, the routing would work the way it used to. Unfortunately, it doesn't so I end up with a users route that is just</p> <pre><code>/users/new-user </code></pre> <p>instead of</p> <pre><code>/admin/users/new-user </code></pre> <p>Further, because of this, the new-user component isn't loaded into the router outlet of my admin component which throws off the styling and navigation of my application.</p> <p>I can't for the life of me come up with how to reference the routes of my UserModule as children of my AdminModule. I've tried doing this the old way and get errors about the routes being in two Modules. Obviously since this is newly released, the documentation around some of these cases is a bit limited.</p> <p>Any help anyone can provide would be greatly appreciated!</p>
38,952,908
7
3
null
2016-08-10 17:03:30.537 UTC
33
2017-09-21 08:57:41.81 UTC
2017-09-21 08:57:41.81 UTC
null
8,371,289
null
6,520,765
null
1
70
angular|angular2-routing|angular2-modules|angular2-router3
83,654
<p>Okay, after fiddling around with this for the better part of the weekend I got it running on my end. What worked for me in the end was to do the following:</p> <ul> <li>Export all <code>Routes</code> for every module you want to route. Do not import any of the <code>RouterModule.forChild()</code> in the child modules.</li> <li>Export <em>every</em> component that is visible from the childs route definitions in the childs module definition.</li> <li>Import (meaning the Typescript <code>import</code> keyword) all child routes as usual and use the <code>...</code> operator to incorporate these under the correct path. I couldn't get it to work with the child-module defining the path, but having it on the parent works fine (and is compatible to lazy loading).</li> </ul> <p>In my case I had three levels in a hierarchy like this:</p> <ul> <li>Root (<code>/</code>) <ul> <li>Editor (<code>editor/:projectId</code>) <ul> <li>Query (<code>query/:queryId</code>)</li> <li>Page (<code>page/:pageId</code>)</li> </ul></li> <li>Front (<code>about</code>)</li> </ul></li> </ul> <p>The following definitions work for me for the <code>/editor/:projectId/query/:queryId</code> path:</p> <pre><code>// app.routes.ts import {editorRoutes} from './editor/editor.routes' // Relevant excerpt how to load those routes, notice that the "editor/:projectId" // part is defined on the parent { path: '', children: [ { path: 'editor/:projectId', children: [...editorRoutes] //loadChildren: '/app/editor/editor.module' }, ] } </code></pre> <p>The editor routes look like this:</p> <pre><code>// app/editor/editor.routes.ts import {queryEditorRoutes} from './query/query-editor.routes' import {pageEditorRoutes} from './page/page-editor.routes' { path: "", // Path is defined in parent component : EditorComponent, children : [ { path: 'query', children: [...queryEditorRoutes] //loadChildren: '/app/editor/query/query-editor.module' }, { path: 'page', children: [...pageEditorRoutes] //loadChildren: '/app/editor/page/page-editor.module' } ] } </code></pre> <p>And the final part for the QueryEditor looks like this:</p> <pre><code>// app/editor/query/query-editor.routes.ts { path: "", component : QueryEditorHostComponent, children : [ { path: 'create', component : QueryCreateComponent }, { path: ':queryId', component : QueryEditorComponent } ] } </code></pre> <p>However, to make this work, the general <code>Editor</code> needs to import <strong>and</strong> export the <code>QueryEditor</code> and the <code>QueryEditor</code> needs to export <code>QueryCreateComponent</code> and <code>QueryEditorComponent</code> as these are visible with the import. Failing to do this will get you errors along the lines of <code>Component XYZ is defined in multiple modules</code>.</p> <p>Notice that lazy loading also works fine with this setup, in that case the child-routes shouldn't be imported of course.</p>
22,885,775
What is the difference between Lock and RLock
<p>From the <a href="https://docs.python.org/2/library/threading.html" rel="noreferrer">docs</a>:</p> <blockquote> <p>threading.RLock() -- A factory function that returns a new reentrant lock object. A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a reentrant lock, the same thread may acquire it again without blocking; the thread must release it once for each time it has acquired it.</p> </blockquote> <p>I am not sure why do we need this? what's the difference between <code>Rlock</code> and <code>Lock</code>?</p>
22,885,810
3
0
null
2014-04-05 19:34:28.4 UTC
31
2020-08-06 04:09:36.61 UTC
2018-04-01 22:20:19.253 UTC
null
1,709,587
null
2,495,795
null
1
101
python|multithreading|locking|reentrancy
46,460
<p>The main difference is that a <code>Lock</code> can only be acquired once. It cannot be acquired again, until it is released. (After it's been released, it can be re-acaquired by any thread).</p> <p>An <code>RLock</code> on the other hand, can be acquired multiple times, by the same thread. It needs to be released the same number of times in order to be "unlocked".</p> <p>Another difference is that an acquired <code>Lock</code> can be released by any thread, while an acquired <code>RLock</code> can only be released by the thread which acquired it.</p> <hr> <p>Here's an example demostrating why <code>RLock</code> is useful at times. Suppose you have:</p> <pre><code>def f(): g() h() def g(): h() do_something1() def h(): do_something2() </code></pre> <p>Let's say all of <code>f</code>, <code>g</code>, and <code>h</code> are <em>public</em> (i.e. can be called directly by an external caller), and all of them require syncronization.</p> <p>Using a <code>Lock</code>, you can do something like:</p> <pre><code>lock = Lock() def f(): with lock: _g() _h() def g(): with lock: _g() def _g(): _h() do_something1() def h(): with lock: _h() def _h(): do_something2() </code></pre> <p>Basically, since <code>f</code> cannot call <code>g</code> after acquiring the lock, it needs to call a "raw" version of <code>g</code> (i.e. <code>_g</code>). So you end up with a "synced" version and a "raw" version of each function.</p> <p>Using an <code>RLock</code> elegantly solves the problem:</p> <pre><code>lock = RLock() def f(): with lock: g() h() def g(): with lock: h() do_something1() def h(): with lock: do_something2() </code></pre>
3,019,369
Rails message: ActionView::MissingTemplate
<p>I am getting an error that I cannot figure out:</p> <pre><code>ActionView::MissingTemplate (Missing template cluster/delete_stuff.erb in view path app/views) &lt;...snip trace...&gt; Rendering rescues/layout (internal_server_error) </code></pre> <p>I am "enhancing" others code and am following the convention they set up, where they have have code like:</p> <pre><code>&lt;%= render :partial =&gt; "other_stuff" %&gt; </code></pre> <p>And a file named <strong>_other_stuff.html.erb</strong> and it all works, but when I copy these little snippets, I get the above error. Any ideas? Something is going on here that I need to figure out.</p>
3,025,120
3
0
null
2010-06-10 23:57:33.88 UTC
2
2021-07-09 11:14:24.203 UTC
null
null
null
null
207,605
null
1
19
ruby-on-rails
53,658
<p>Turns out that I did not have a </p> <p><code>render :something</code> </p> <p>in my controller method, so I guess Rails figured that there must be a "delete_stuff.erb" somewhere to know what to do. Added a render and the error message goes away.</p>
2,999,528
Is there a 100% Java alternative to ImageIO for reading JPEG files?
<p>We are using Java2D to resize photos uploaded to our website, but we run into an issue (a seemingly old one, cf.: <a href="http://forums.sun.com/thread.jspa?threadID=5425569" rel="noreferrer">http://forums.sun.com/thread.jspa?threadID=5425569</a>) - a few particular JPEGs raise a <code>CMMException</code> when we try to <code>ImageIO.read()</code> an InputStream containing their binary data:</p> <pre><code>java.awt.color.CMMException: Invalid image format at sun.awt.color.CMM.checkStatus(CMM.java:131) at sun.awt.color.ICC_Transform.&lt;init&gt;(ICC_Transform.java:89) at java.awt.image.ColorConvertOp.filter(ColorConvertOp.java:516) at com.sun.imageio.plugins.jpeg.JPEGImageReader.acceptPixels(JPEGImageReader.java:1114) at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImage(Native Method) at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(JPEGImageReader.java:1082) at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(JPEGImageReader.java:897) at javax.imageio.ImageIO.read(ImageIO.java:1422) at javax.imageio.ImageIO.read(ImageIO.java:1326) ... </code></pre> <p>(snipped the remainder of the stack trace, which is our <code>ImageIO.read()</code> call, servlet code and such)</p> <p>We narrowed it down to photos taken on specific cameras, and I selected a photo that triggers this error: <a href="http://img214.imageshack.us/img214/5121/estacaosp.jpg" rel="noreferrer">http://img214.imageshack.us/img214/5121/estacaosp.jpg</a>. We noticed that this only happens with Sun's JVM (on Linux and Mac, just tested it on 1.6.0_20) - a test machine with OpenJDK reads the same photos without a hitch, possibly due to a different implementation of the JPEG reader.</p> <p>Unfortunately, we are unable to switch JVMs in production, nor to use native-dependent solutions such as ImageMagick ( <a href="http://www.imagemagick.org/" rel="noreferrer">http://www.imagemagick.org/</a> ).</p> <p>Considering that, my question is: Does a replacement for ImageIOs JPEG reader which can handle photos such as the linked one exist? If not, is there another 100% pure Java photo resizing solution which we can use?</p> <p>Thank you!</p>
3,002,383
3
3
null
2010-06-08 17:02:12.813 UTC
12
2019-12-01 07:34:08.573 UTC
null
null
null
null
64,635
null
1
20
java|jpeg|java-2d|javax.imageio|resize-image
19,558
<p>One possibly useful library for you could be the Java Advanced Imaging Library (<a href="https://www.oracle.com/technetwork/java/iio-141084.html" rel="nofollow noreferrer">JAI</a>)</p> <p>Using this library can be quite a bit more complicated than using ImageIO but in a quick test I just ran, it did open and display the problem image file you linked.</p> <pre><code>public static void main(String[] args) { RenderedImage image = JAI.create("fileload", "estacaosp.jpg"); float scale=(float) 0.5; ParameterBlock pb = new ParameterBlock(); pb.addSource(image); pb.add(scale); pb.add(scale); pb.add(1.0F); pb.add(1.0F); pb.add(new InterpolationNearest() );// ;InterpolationBilinear()); image = JAI.create("scale", pb); // Create an instance of DisplayJAI. DisplayJAI srcdj = new DisplayJAI(image); JScrollPane srcScrollPaneImage = new JScrollPane(srcdj); // Use a label to display the image JFrame frame = new JFrame(); frame.getContentPane().add(srcScrollPaneImage, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } </code></pre> <p>After running this code the image seems to load fine. It is then resized by 50% using the ParamaterBlock</p> <p>And finally if you wish to save the file you can just call :</p> <pre><code>String filename2 = new String ("tofile.jpg"); String format = new String ("JPEG"); RenderedOp op = JAI.create ("filestore", image, filename2, format); </code></pre> <p>I hope this helps you out. Best of luck.</p>
2,444,899
insert or update on table violates foreign key constraint
<p>I have two tables: <strong>entitytype</strong> and <strong>project</strong>. Here are the create table statements:</p> <pre><code>Create table project ( pname varchar(20) not null, primary key(pname) ); create table entitytype( entityname varchar(20) not null, toppos char(100), leftpos char(100), pname varchar(20) not null, primary key(entityname), foreign key(pname) references project(pname) on delete cascade on update cascade ); </code></pre> <p>When I try to insert any values into the <strong>entitytype</strong> table, I get the following error:</p> <pre><code>ERROR: insert or update on table "entitytype" violates foreign key constraint "entitytype_pname_fkey" Detail: Key (pname)=(494) is not present in table "project". </code></pre> <p>Can anyone shed some light on what I am doing wrong?</p>
2,444,913
3
0
null
2010-03-15 03:19:42.737 UTC
6
2022-01-07 04:25:38.853 UTC
2011-09-09 01:38:27.227 UTC
null
71,421
null
166,731
null
1
25
sql|database|postgresql
109,656
<p>The error message means you are attempting to add an entityType that does not have a corresponding Project entry. (I don't know your domain or what you are trying to achieve, but that schema design looks wrong to me...)</p>
2,671,503
How to stop debugging (or detach process) without stopping the process?
<p>I often use VS 2008 to debug a .NET C# component of an application. Sometimes, I want to quit debugging and continue running the application. Stop Debugging kills the process I was debugging. </p> <p>How can I achieve my aim? </p> <p>This is not a web app, it's a local process that runs managed and unmanaged code. </p> <p>I found the <strong>"Detach All"</strong> option in the Debug menu, however it is <strong>disabled (grayed out)</strong>.</p>
7,563,072
3
3
null
2010-04-19 23:07:00.917 UTC
7
2015-11-27 23:09:12.473 UTC
2015-11-27 23:09:12.473 UTC
null
294,313
null
107,800
null
1
51
visual-studio|visual-studio-2008|debugging
30,296
<p>You cannot detach a debugger from a process if you are debugging in mixed mode.</p> <p>Make sure you are debugging either in managed or native mode while attaching to the process: either make sure "Enable native code debugging" or "Native Code" is unchecked in your project options, or start the program without debugging, choose "Attach to Process", and select only Managed or only Native.</p>
2,541,401
Pairwise crossproduct in Python
<p>How can I get the list of cross product <em>pairs</em> from a list of arbitrarily long lists in Python?</p> <h2>Example</h2> <pre><code>a = [1, 2, 3] b = [4, 5, 6] </code></pre> <p><code>crossproduct(a,b)</code> should yield <code>[[1, 4], [1, 5], [1, 6], ...]</code>.</p>
2,541,412
3
2
null
2010-03-29 21:27:38.737 UTC
23
2017-02-19 11:26:38.647 UTC
2015-11-28 19:41:54.17 UTC
null
562,769
user248237
null
null
1
135
python|list
99,375
<p>You're looking for <a href="http://docs.python.org/library/itertools.html#itertools.product" rel="noreferrer">itertools.product</a> if you're on (at least) Python 2.6.</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; a=[1,2,3] &gt;&gt;&gt; b=[4,5,6] &gt;&gt;&gt; itertools.product(a,b) &lt;itertools.product object at 0x10049b870&gt; &gt;&gt;&gt; list(itertools.product(a,b)) [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)] </code></pre>
2,362,982
jQuery dynamically create table/tr/td or etc and append attributes
<p>In an example I am having this structure (small example):</p> <pre><code>&lt;table id=example&gt; &lt;tr class="blah test example"&gt;&lt;td&gt;Test1&lt;/td&gt;&lt;td&gt;&lt;a href="url"&gt;LINK&lt;/a&gt;Test11&lt;/td&gt;&lt;/tr&gt; &lt;tr class="blah test example"&gt;&lt;td&gt;Test2&lt;/td&gt;&lt;td&gt;&lt;a href="url"&gt;LINK&lt;/a&gt;Test22&lt;/td&gt;&lt;/tr&gt; &lt;tr class="blah test example"&gt;&lt;td&gt;Test3&lt;/td&gt;&lt;td&gt;&lt;a href="url"&gt;LINK&lt;/a&gt;Test33&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; </code></pre> <p>In jQuery I would create it dynamically like:</p> <pre><code>var test = "&lt;table id=" + someIDVar + "&gt;" + "&lt;tr class=" + classOneVar + classTwoVar + classThreeVar + "&gt;".... </code></pre> <p>and etc etc... (lots of other stuff to write). After I would just append it:</p> <pre><code>$(".somePlaceInHtml").append(test); </code></pre> <p>So is there any other way to write such a structure dynamically with jQuery? This is a problem for me because I am having a big structure, not as small as I showed in the example. The main reason is I want to get better readability for myself and other developers who will maintain this code. </p>
2,363,030
5
0
null
2010-03-02 12:18:13.133 UTC
4
2017-05-23 16:17:52.64 UTC
2017-05-23 16:17:52.64 UTC
null
4,370,109
null
147,953
null
1
9
javascript|jquery|html-table|refactoring
54,401
<p>Can you make a "template" out of your string? If yes, then store it in a "constant" variable (e.g. defined in global scope), containing placeholders for actual variables, like <code>{0}</code>, <code>{1}</code> etc, as you would use it in C#'s <code>string.format()</code> method.</p> <p>So, you would have code like this:</p> <pre><code>var rowTemplate = "&lt;tr&gt;&lt;td&gt;{0}&lt;/td&gt;&lt;td&gt;SomePredefinedText {1}&lt;/td&gt;&lt;/tr&gt;"; var alternateRowTemplate = "&lt;tr&gt;&lt;td class='a'&gt;{0}&lt;/td&gt;&lt;td&gt;SomewhatDifferent {1}&lt;/td&gt;&lt;/tr&gt;"; ...... somewhere deep in your code $("#someElement").append( rowTemplate.format("myvalue1", "myvalue2") ).append( alternateRowTemplate.format("myvalue3", "myvalue4") ); </code></pre> <p>You would then use the string.format implementation as per this answer: <a href="https://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery/1038930#1038930">Equivalent of String.format in jQuery</a></p>
46,421,279
Delete downloads older than 30 days?
<p>I am trying to create a task in automator that moves files in ~/Downloads to the trash if they are older than 30 days.</p> <p>I want this to run every day.</p> <p>It's not working though, Finder just hangs and stops responding and I have to Force Quit it from activity monitor.</p> <pre><code>on run {input, parameters} tell application "Finder" set deleteFileList to (files of entire contents of folder alias "Macintosh HD:Users:George:Downloads" whose modification date is less than ((get current date)) - 30 * days) try repeat with deleteFile in deleteFileList delete deleteFile end repeat end try end tell return input end run </code></pre>
46,428,161
2
0
null
2017-09-26 08:21:10.79 UTC
9
2018-04-21 16:44:50.527 UTC
null
null
null
null
3,310,334
null
1
11
macos|automation|applescript|automator
5,574
<p>I'd take a different approach and use a set of <em>actions</em> available in <strong>Automator</strong> without the use of <strong>AppleScript</strong>.</p> <p>The following <em>workflow</em> will accomplish that you're looking to do.</p> <p>In <strong>Automator</strong>, create a new <strong>Workflow</strong> adding the following actions:</p> <ul> <li>Get Specified Finder Items <ul> <li>Add the Downloads folder to it.</li> </ul></li> <li>Get Folder Contents <ul> <li>[] Repeat for each subfolder found</li> </ul></li> <li>Filter Finder Items <ul> <li>Find files where: <ul> <li>All of the following are true <ul> <li>Date last modified is not in the last 30 days</li> </ul></li> </ul></li> </ul></li> <li>Move Finder Items to Trash</li> </ul> <p>Save the <strong>Workflow</strong> as an <em>Application</em>, e.g.: <strong>Cleanup Downloads.app</strong></p> <p>This should run much faster then <strong>AppleScript</strong> version, it did in my testing.</p> <hr> <p><strong>Apple's</strong> preferred method to schedule something such as this is to use <code>launchd</code> and <code>launchctl</code>.</p> <p>To run <strong>Cleanup Downloads</strong>, daily, I'd do the following:</p> <ol> <li>Add <strong>Cleanup Downloads</strong> to: <strong>System Preferences</strong> > <strong>Security &amp; Privacy</strong> > <strong>Privacy</strong> > <strong>Accessibility</strong></li> <li><p>Create a User LaunchAgent in: <code>~/Library/LaunchAgents/</code></p> <ul> <li><p>Example: <code>com.me.cleanup.downloads.plist</code> as an XML file containing:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;Label&lt;/key&gt; &lt;string&gt;com.me.cleanup.downloads&lt;/string&gt; &lt;key&gt;ProgramArguments&lt;/key&gt; &lt;array&gt; &lt;string&gt;/Applications/Cleanup Downloads.app/Contents/MacOS/Application Stub&lt;/string&gt; &lt;/array&gt; &lt;key&gt;RunAtLoad&lt;/key&gt; &lt;false/&gt; &lt;key&gt;StartCalendarInterval&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;Hour&lt;/key&gt; &lt;integer&gt;10&lt;/integer&gt; &lt;key&gt;Minute&lt;/key&gt; &lt;integer&gt;00&lt;/integer&gt; &lt;/dict&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt; </code></pre></li> <li><p>Set the value for <code>Hours</code> and <code>Minutes</code>, under <code>StartCalendarInterval</code>, as appropriate for your need. The example is set for: 10:00AM</p></li> </ul></li> <li><p>In <strong>Terminal</strong> <em>run</em> the following <em>command</em> to <em>load</em> the LaunchAgent: </p> <pre><code>launchctl load ~/Library/LaunchAgents/com.me.cleanup.downloads.plist </code></pre></li> </ol> <p>Note: See the manual pages for <code>launchd</code> and <code>launchctl</code> in Terminal, e.g. <code>man launchctl</code></p> <p>Or use a third party utility that has a GUI, e.g.: <a href="https://www.peterborgapps.com/lingon/" rel="noreferrer">Lingon X</a></p> <p><sub>Note: I'm not associated with the developer of Lingon X, however I am a satisfied customer.</sub></p> <hr> <p>Some comments on your <strong>AppleScript</strong> <em>code</em>:</p> <p>A <code>repeat</code> <em>statement</em> isn't necessary, just use:</p> <pre><code>move deleteFileList to trash </code></pre> <p>The <code>current date</code> <em>command</em> technically executes under <code>current application</code>, not <code>Finder</code> as <strong>Finder</strong> does not understand the <code>current date</code> <em>command</em> . Therefore, <em>set</em> a <em>variable</em> and use the <em>variable</em> in the command.</p> <pre><code>set thisDate to get (current date) - 30 * days ... whose modification date is less than thisDate </code></pre> <p>Now I'm not proposing you actually use the AppleScript over the <em>workflow</em> I proposed, I'm just pointing out some things in the <em>code</em> I take issue with.</p>
36,342,899
asyncio.ensure_future vs. BaseEventLoop.create_task vs. simple coroutine?
<p>I've seen several basic Python 3.5 tutorials on asyncio doing the same operation in various flavours. In this code:</p> <pre><code>import asyncio async def doit(i): print("Start %d" % i) await asyncio.sleep(3) print("End %d" % i) return i if __name__ == '__main__': loop = asyncio.get_event_loop() #futures = [asyncio.ensure_future(doit(i), loop=loop) for i in range(10)] #futures = [loop.create_task(doit(i)) for i in range(10)] futures = [doit(i) for i in range(10)] result = loop.run_until_complete(asyncio.gather(*futures)) print(result) </code></pre> <p>All the three variants above that define the <code>futures</code> variable achieve the same result; the only difference I can see is that with the third variant the execution is out of order (which should not matter in most cases). Is there any other difference? Are there cases where I can't just use the simplest variant (plain list of coroutines)?</p>
36,415,477
4
0
null
2016-03-31 20:15:20.243 UTC
64
2019-01-02 05:59:45.83 UTC
null
null
null
null
2,660,810
null
1
128
python|python-3.x|python-3.5|coroutine|python-asyncio
87,029
<h2>Actual info:</h2> <p>Starting from Python 3.7 <code>asyncio.create_task(coro)</code> high-level function <a href="https://docs.python.org/3/library/asyncio-task.html#creating-tasks" rel="noreferrer">was added</a> for this purpose. </p> <p>You should use it instead other ways of creating tasks from coroutimes. However if you need to create task from arbitrary awaitable, you should use <code>asyncio.ensure_future(obj)</code>.</p> <hr> <h2>Old info:</h2> <h2><code>ensure_future</code> vs <code>create_task</code></h2> <p><code>ensure_future</code> is a method to create <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.Task" rel="noreferrer"><code>Task</code></a> from <a href="https://docs.python.org/3/library/asyncio-task.html#coroutines" rel="noreferrer"><code>coroutine</code></a>. It creates tasks in different ways based on argument (including using of <code>create_task</code> for coroutines and future-like objects).</p> <p><code>create_task</code> is an abstract method of <code>AbstractEventLoop</code>. Different event loops can implement this function different ways.</p> <p>You should use <code>ensure_future</code> to create tasks. You'll need <code>create_task</code> only if you're going to implement your own event loop type.</p> <p><strong>Upd:</strong></p> <p>@bj0 pointed at <a href="https://github.com/python/asyncio/issues/477" rel="noreferrer">Guido's answer</a> on this topic:</p> <blockquote> <p>The point of <code>ensure_future()</code> is if you have something that could either be a coroutine or a <code>Future</code> (the latter includes a <code>Task</code> because that's a subclass of <code>Future</code>), and you want to be able to call a method on it that is only defined on <code>Future</code> (probably about the only useful example being <code>cancel()</code>). When it is already a <code>Future</code> (or <code>Task</code>) this does nothing; when it is a coroutine it <em>wraps</em> it in a <code>Task</code>.</p> <p>If you know that you have a coroutine and you want it to be scheduled, the correct API to use is <code>create_task()</code>. The only time when you should be calling <code>ensure_future()</code> is when you are providing an API (like most of asyncio's own APIs) that accepts either a coroutine or a <code>Future</code> and you need to do something to it that requires you to have a <code>Future</code>.</p> </blockquote> <p>and later:</p> <blockquote> <p>In the end I still believe that <code>ensure_future()</code> is an appropriately obscure name for a rarely-needed piece of functionality. When creating a task from a coroutine you should use the appropriately-named <code>loop.create_task()</code>. Maybe there should be an alias for that <code>asyncio.create_task()</code>?</p> </blockquote> <p>It's surprising to me. My main motivation to use <code>ensure_future</code> all along was that it's higher-level function comparing to loop's member <code>create_task</code> (discussion <a href="https://github.com/python/asyncio/issues/477#issuecomment-269042731" rel="noreferrer">contains</a> some ideas like adding <code>asyncio.spawn</code> or <code>asyncio.create_task</code>).</p> <p>I can also point that in my opinion it's pretty convenient to use universal function that can handle any <code>Awaitable</code> rather than coroutines only.</p> <p>However, Guido's answer is clear: <strong>"When creating a task from a coroutine you should use the appropriately-named <code>loop.create_task()</code>"</strong></p> <h2>When coroutines should be wrapped in tasks?</h2> <p>Wrap coroutine in a Task - is a way to start this coroutine "in background". Here's example:</p> <pre><code>import asyncio async def msg(text): await asyncio.sleep(0.1) print(text) async def long_operation(): print('long_operation started') await asyncio.sleep(3) print('long_operation finished') async def main(): await msg('first') # Now you want to start long_operation, but you don't want to wait it finised: # long_operation should be started, but second msg should be printed immediately. # Create task to do so: task = asyncio.ensure_future(long_operation()) await msg('second') # Now, when you want, you can await task finised: await task if __name__ == "__main__": loop = asyncio.get_event_loop() loop.run_until_complete(main()) </code></pre> <p>Output:</p> <pre><code>first long_operation started second long_operation finished </code></pre> <p>You can replace <code>asyncio.ensure_future(long_operation())</code> with just <code>await long_operation()</code> to feel the difference.</p>
37,460,600
Is there a way to disconnect USB device from ADB?
<p>I have a lot of scripts that use ADB to debug Android applications via Wi-Fi with emulators. The problem appears when I charge my Android phone via USB from my computer: ADB sees it and sends commands to my phone instead of emulator. <strong>Is there a way to disconnect ADB from phone that charges via USB?</strong> I know I can send commands to emulators only via <code>-e</code> switch, as well as send them to specific device via <code>-s</code> switch. However, it is not OK for me, because I have to rewrite a lot of scripts to add more arguments if I want to implement this device selection feature. I don't need workarounds, I just curious does Google <em>force</em> ADB to debug any phone connected via USB that has USB debugging enabled in settings, or it is possible to remove specific USB connected phone from devices list on ADB side? When I run <code>adb disconnect</code>, USB device remains connected.</p>
37,460,788
5
0
null
2016-05-26 12:15:59.413 UTC
9
2021-03-16 13:45:49.83 UTC
null
null
null
null
1,089,715
null
1
23
android|adb
71,578
<p>USB connection for internal storage and adb connection for debugging are two separate things.</p> <p>To disable adb - you can use <code>adb disconnect</code> or simply turn off <code>usb debugging</code> under <code>developer options</code>.</p> <p>For disconnecting usb connection for internal storage certain ROMS have the option. e.g. CM 13 that i have at the moment allows connecting USB just for charging. Generally on other ROMS and Stock ROM I've not seen this option but you can try this. -> If you connect your device via USB while locked the internal storage will not be available unless you unlock the device once.</p>
2,410,937
delaying actions between keypress in jQuery
<p>How can I delay actions between keypress in jQuery. For example;</p> <p>I have something like this</p> <pre><code> if($(this).val().length &gt; 1){ $.post("stuff.php", {nStr: "" + $(this).val() + ""}, function(data){ if(data.length &gt; 0) { $('#suggestions').show(); $('#autoSuggestionsList').html(data); }else{ $('#suggestions').hide(); } }); } </code></pre> <p>I want to prevent posting data if the user continously typing. So how can I give .5 seconds delay?</p>
2,410,966
5
1
null
2010-03-09 17:08:08.67 UTC
12
2016-03-14 16:35:06.547 UTC
null
null
null
null
256,895
null
1
31
jquery|ajax|delay
24,144
<p>You can use jQuery's data abilities to do this, something like this:</p> <pre><code>$('#mySearch').keyup(function() { clearTimeout($.data(this, 'timer')); var wait = setTimeout(search, 500); $(this).data('timer', wait); }); function search() { $.post("stuff.php", {nStr: "" + $('#mySearch').val() + ""}, function(data){ if(data.length &gt; 0) { $('#suggestions').show(); $('#autoSuggestionsList').html(data); }else{ $('#suggestions').hide(); } }); } </code></pre> <p>The main advantage here is no global variables all over the place, and you could wrap this in an anonymous function in the setTimeout if you wanted, just trying to make the example as clean as possible.</p>
2,767,352
C# convert bit to boolean
<p>I have a Microsoft SQL Server database that contains a data field of <code>BIT</code> type.</p> <p>This field will have either <code>0</code> or <code>1</code> values to represent false and true.</p> <p>I want when I retrieve the data to convert the value I got to <code>false</code> or <code>true</code> without using if-condition to convert the data to <code>false</code> if it is <code>0</code> or <code>true</code> if it is <code>1</code>.</p> <p>I'm wondering if there is a function in C# would do this direct by passing bit values to it?</p>
2,767,375
5
0
null
2010-05-04 17:07:01.38 UTC
3
2020-03-19 10:56:30.06 UTC
2020-03-19 10:56:30.06 UTC
null
2,083,613
null
2,152,275
null
1
35
c#|ado.net
107,565
<p>Depending on how are you performing the SQL queries it may depend. For example if you have a <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx" rel="noreferrer">data reader</a> you could directly <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getboolean(VS.80).aspx" rel="noreferrer">read a boolean value</a>:</p> <pre><code>using (var conn = new SqlConnection(ConnectionString)) using (var cmd = conn.CreateCommand()) { conn.Open(); cmd.CommandText = "SELECT isset_field FROM sometable"; using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { bool isSet = reader.GetBoolean(0); } } } </code></pre>
2,456,954
git encrypt/decrypt remote repository files while push/pull
<p>Is it possible to automatically encrypt files via 'git push' before transferring to a remote repository? And automatically decode them while 'git pull'.</p> <p>I.e, if I have some remote server with shared access with git repository there, and I don't want our project to be stolen without a permission... Maybe there is some special git-hooks before push and after pull?</p>
2,457,006
5
4
null
2010-03-16 18:14:39.987 UTC
21
2019-06-05 21:48:10.593 UTC
2017-07-17 05:59:06.287 UTC
null
586,229
null
225,568
null
1
44
git|encryption
21,972
<p>Yes and no.</p> <p>You could try to depend on hook but that supposes they are installed at the remote locations, and that is not always reliable.</p> <p>Another way to achieve almost the same effect would be by using a <strong><a href="https://stackoverflow.com/questions/2154948/how-can-i-track-system-specific-config-files-in-a-repo-project/2155355#2155355">smudge/clean attribute filter driver</a></strong>, <strong>but not for a full repo</strong>.</p> <p><img src="https://i.stack.imgur.com/4RzLi.png" alt="smudge/clean"></p> <p><sup>(Source: <a href="http://git-scm.com/book/en/v2/" rel="nofollow noreferrer">Pro Git book</a>: <a href="http://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes" rel="nofollow noreferrer">Customizing Git - Git Attributes</a>)</sup></p> <p>That way the smudge script is able decode the files, while the clean script would encode them.<br> Again, that could work for a few sensitive files, <strong>not for a full repo</strong>.</p> <p>Off course, those scripts would not be in the repository itself, and would be managed/communicated by another way. </p> <p>As <a href="https://stackoverflow.com/users/1556338/alkaline">Alkaline</a> points out <a href="https://stackoverflow.com/questions/2456954/git-encrypt-decrypt-remote-repository-files-while-push-pull/2457006#comment54706421_2457006">in the comments</a>, that idea does not scale for a repo, as the main git maintainer <a href="http://article.gmane.org/gmane.comp.version-control.git/113221" rel="nofollow noreferrer">Junio C. Hamano comments back in 2009</a>:</p> <blockquote> <p>As the sole raison d'etre of <code>diff.textconv</code> is to allow potentially lossy conversion (e.g. msword-to-text) applied to the preimage and postimage pair of contents (that are supposed to be "clean") before giving a textual diff to human consumption. </p> <p>The above config may appear to work, but <strong>if you really want an encrypted repository, you should be using an encrypting filesystem.<br> That would give an added benefit that the work tree associated with your repository would also be encrypted</strong>.</p> </blockquote> <hr> <p>Even though it does not scale to a full repo, the idea was implemented (3 years later in 2013) with <strong><a href="https://github.com/AGWA/git-crypt" rel="nofollow noreferrer"><code>git-crypt</code></a></strong>, as detailed in <a href="https://stackoverflow.com/users/1048170/dominic-cerisano">Dominic Cerisano</a>'s <a href="https://stackoverflow.com/a/45047100/6309">answer</a>.<br> <code>git-crypt</code> uses a <strong>content filter driver</strong> (implemented in cpp, with <a href="https://github.com/AGWA/git-crypt/blob/788a6a99f4289745e6bd12fae2ad8014af320a4f/commands.cpp#L149-L168" rel="nofollow noreferrer"><code>commands.cpp</code></a> setting up your <code>.gitattributes</code> with the relevant <code>smudge</code> and <code>clean</code> filter commands).<br> As any content filter driver, you can then limit the application of <code>git-crypt</code> to the set of files you want, in the same <code>.gitattributes</code> file:</p> <pre><code>secretfile filter=git-crypt diff=git-crypt *.key filter=git-crypt diff=git-crypt </code></pre> <p>As <a href="https://github.com/AGWA/git-crypt/blob/788a6a99f4289745e6bd12fae2ad8014af320a4f/README#L93-L102" rel="nofollow noreferrer">mentioned in the <code>README</code></a>:</p> <blockquote> <p><code>git-crypt</code> relies on git filters, which were not designed with encryption in mind. </p> <p>As such, <code>git-crypt</code> is not the best tool for encrypting most or all of the files in a repository.<br> Where <code>git-crypt</code> really shines is where most of your repository is public, but you have a few files (perhaps private keys named <code>*.key</code>, or a file with API credentials) which you need to encrypt. </p> <p>For encrypting an entire repository, consider using a system like <strong><a href="https://spwhitton.name/tech/code/git-remote-gcrypt/" rel="nofollow noreferrer"><code>git-remote-gcrypt</code></a></strong> instead.</p> </blockquote> <p>(see more at <a href="https://spwhitton.name/tech/code/git-remote-gcrypt/" rel="nofollow noreferrer"> spwhitton/ tech/ code/ git-remote-gcrypt</a>, from <strong><a href="https://spwhitton.name/" rel="nofollow noreferrer">Sean Whitton</a></strong>)</p>
2,691,392
Enumerable.Empty<T>() equivalent for IQueryable
<p>When a method returns <code>IEnumerable&lt;T&gt;</code> and I do not have anything to return, we can use <code>Enumerable.Empty&lt;T&gt;()</code>.</p> <p>Is there an equivalent to the above for a method returning <code>IQueryable&lt;T&gt;</code></p>
2,691,437
6
0
null
2010-04-22 13:54:26.033 UTC
7
2022-09-03 08:52:18.457 UTC
2010-05-10 21:36:55.1 UTC
null
309,358
null
309,358
null
1
138
c#|return|iqueryable
27,353
<p>Maybe: </p> <pre><code>Enumerable.Empty&lt;T&gt;().AsQueryable(); </code></pre>