id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,124,699 | Difference between a git commit and the working directory? | <p>The git-diff manual pages says that git diff is used to </p>
<blockquote>
<p>Show changes between the working tree and the index or a tree, changes
between the index and a tree, changes between two trees, or changes
between two files on disk.</p>
</blockquote>
<p>But what about if you want to show the difference between a commit prior to HEAD and the working directory? Is that possible?</p> | 18,124,981 | 2 | 0 | null | 2013-08-08 11:20:34.357 UTC | 12 | 2019-06-04 11:19:25.973 UTC | 2013-08-08 14:45:12.243 UTC | null | 1,070,480 | null | 1,070,480 | null | 1 | 50 | git-diff | 29,613 | <p>Yes, but it depends a bit on your definition on what the “current project state” is. The manual for git diff goes on.</p>
<p>If you are interested in comparing with the <em>staged</em> changes:</p>
<blockquote>
<pre><code>git diff [--options] --cached [<commit>] [--] [<path>...]
</code></pre>
<p>This form is to view the changes you staged for the next commit relative to the named <code><commit></code>. Typically you would want comparison with the latest commit, so if you do not give <code><commit></code>, it defaults to HEAD. If HEAD does not exist (e.g. unborned branches) and <code><commit></code> is not given, it shows all staged changes. <code>--staged</code> is a synonym of <code>--cached</code>.</p>
</blockquote>
<p>If you are interested in comparing with the <em>unstaged</em> changes:</p>
<blockquote>
<pre><code>git diff [--options] <commit> [--] [<path>...]
</code></pre>
<p>This form is to view the changes you have in your working tree relative to the named <code><commit></code>. You can use HEAD to compare it with the latest commit, or a branch name to compare with the tip of a different branch.</p>
</blockquote>
<p>Or if you are just interested in comparing <em>any</em> two commits (one could be HEAD):</p>
<blockquote>
<pre><code>git diff [--options] <commit> <commit> [--] [<path>...]
</code></pre>
<p>This is to view the changes between two arbitrary <code><commit></code>s.</p>
</blockquote>
<p>So you might want to run <code>git diff someOldCommit HEAD</code> to see the differences between <code>someOldCommit</code> and the current HEAD.</p> |
21,298,097 | Library not found for -lfl | <p>I was using <code>flex</code> and <code>bison</code> to build a simple calculator project I cloned from Github.</p>
<p>But after I typed <code>make</code> in terminal, I got the following message:</p>
<pre><code>gcc -o calc calc.tab.c lex.yy.c -lfl
calc.y:48:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main() {
^~~~
1 warning generated.
ld: library not found for -lfl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [calc] Error 1
</code></pre>
<p>How could I resolve this problem?</p> | 21,298,308 | 2 | 2 | null | 2014-01-23 02:18:11.163 UTC | 12 | 2018-05-19 21:15:02.113 UTC | 2016-09-05 21:12:34.903 UTC | null | 510,036 | null | 2,644,869 | null | 1 | 23 | c++|macos|flexc++ | 11,131 | <p>let me guess, trying to use flex on OS/X?</p>
<p>Try -ll instead of -lfl</p>
<p><a href="http://linux-digest.blogspot.com/2013/01/using-flex-on-os-x.html">Using Flex on OS/X</a></p>
<p>So yea, the flex library name on OS/X is just arbitrarily different for some reason. OS/X is not exactly Linux, but it's pretty close. You have some options here.</p>
<ol>
<li><p>You can just simply have a separate build system and source files for OS/X. Certainly Apple might like that with their pushing XCode, objective-C and not much interoperability. </p></li>
<li><p>You can build vs Linux and then engage with <a href="http://www.macports.org/">Mac Ports</a> and <a href="http://brew.sh/">Homebrew</a>.</p></li>
<li><p>You can create your project using <a href="http://www.gnu.org/software/automake/manual/html_node/Autotools-Introduction.html">autotools</a>. That's not an awesome link, learning this system is rough going, but it's a standard thing for Linux for sure. This will actually work, I find if you have the patience for it, OS/X is close enough that autotools based builds will work on it.</p></li>
<li><p>Lately, I've been turned on to <a href="http://cocoapods.org/">Cocoapods</a>, which I believe to be an attempt to join the open source community and XCode. It's kind of half 1 and 3 sorta with an emphasis on modularizing the external source and getting it compiled into a .app (via Xcode).</p></li>
</ol> |
41,000,428 | Python TypeError: cannot convert the series to <class 'int'> when trying to do math on dataframe | <p>I have a data frame that looks something like this:</p>
<pre><code>defaultdict(<class 'list'>, {'XYF': TimeUS GyrX GyrY GyrZ AccX \
0 207146570 0.000832914 0.001351716 -0.0004189798 -0.651183
1 207186671 0.001962787 0.001242457 -0.0001859666 -0.6423497
2 207226791 9.520243E-05 0.001076498 -0.0005664826 -0.6360412
3 207246474 0.0001093059 0.001616917 0.0003615251 -0.6342875
4 207286244 0.001412051 0.0007565815 -0.0003780428 -0.637755
[103556 rows x 12 columns], 'DAR': TimeUS RSSI RemRSSI TxBuf Noise RemNoise RxErrors Fixed
0 208046965 159 161 79 25 29 0 0
1 208047074 159 161 79 25 29 0 0
2 208927455 159 159 91 28 28 0 0
3 208927557 159 159 91 28 28 0 0
[4136 rows x 8 columns], 'NK2': TimeUS IVN IVE IVD IPN IPE IPD IMX IMY IMZ IYAW \
0 207147350 -0.02 0.02 0.00 -0.02 0.01 0.20 0 0 0 1.94
1 207187259 -0.02 0.02 0.00 -0.02 0.01 0.20 0 0 0 1.94
2 207227559 -0.02 0.02 0.00 -0.02 0.01 0.14 0 0 0 1.77
3 207308304 0.02 0.02 0.00 -0.01 0.01 -0.05 0 0 0 1.77
4 207347766 0.02 0.02 0.00 -0.01 0.01 -0.05 0 0 0 0.82
</code></pre>
<p>I first separated the column I want to do math with:</p>
<pre><code>new_time = dfs['XYF']['TimeUS']
</code></pre>
<p>Then I have tried several things to do some math on it but I had no luck.
First I just treated it like a list. so</p>
<pre><code>new_time_F = new_time / 1000000
</code></pre>
<p>That didn't work, gave me a float error of:</p>
<pre><code>TypeError: unsupported operand type(s) for /: 'str' and 'int'
</code></pre>
<p>so I did this:</p>
<pre><code>new_time_F = float (new_time) / 1000000
</code></pre>
<p>This give me an error:</p>
<pre><code>TypeError: cannot convert the series to <class 'float'>
</code></pre>
<p>I have no idea where to go from here. </p> | 41,002,511 | 3 | 2 | null | 2016-12-06 16:39:23.903 UTC | 4 | 2018-10-30 11:25:09.77 UTC | 2016-12-06 16:41:31.83 UTC | null | 704,848 | null | 7,253,039 | null | 1 | 21 | python|pandas | 159,120 | <p>What if you do this (as was suggested earlier):</p>
<pre><code>new_time = dfs['XYF']['TimeUS'].astype(float)
new_time_F = new_time / 1000000
</code></pre> |
28,180,449 | Using custom font for entire iOS app swift | <p>I know that to set a custom font of an element on the screen I can simply do<code>someLabel.font=UIFont(name: "Exo 2.0", size: 15)</code>. </p>
<p>I was wondering how one could set it for an entire app using swift. (A hack would be to do what I know for every single element of the app but that is just going to be a maintainability nightmare)</p>
<p>I see that this question has already been asked with an objective-C tag, <a href="https://stackoverflow.com/questions/11907761/how-to-set-a-custom-font-for-entire-ios-app-without-specifying-size">How to set a custom font for entire iOS app without specifying size</a> but I'm not familiar enough with objective-C enough to port the code to swift</p> | 28,180,645 | 5 | 1 | null | 2015-01-27 21:34:37.393 UTC | 11 | 2020-09-08 10:16:59.23 UTC | 2017-05-23 12:34:12.413 UTC | null | -1 | null | 1,304,357 | null | 1 | 29 | ios|swift|fonts | 33,113 | <p>You can set the appearance of the UILabel and other UIViews:</p>
<pre><code>UILabel.appearance().font = UIFont(name: "yourFont", size: yourSize)
</code></pre>
<p>More General:</p>
<pre><code>AnyUIView.appearance().font = UIFont(name: "yourFont", size: yourSize)
</code></pre> |
1,372,016 | Django models, custom functions | <p>I am creating simple application with django. Also, I realized that I am doing some kind of operations very often. For example I often need to get all Article objects which have isPublick = True. So I am thinking is that possible to define get_published function in model?</p>
<p>if models looks like this (simplified)</p>
<pre><code>class Article(models.Model):
title = models.CharField(...)
isPublished = models.BooleandField()
def get_active(self):
return Article.objects.filter(isPublicshed = 1)
</code></pre>
<p>But it doesn't work this way</p>
<p>Can you suggest a way of implementing the function?</p> | 1,372,048 | 3 | 0 | null | 2009-09-03 07:56:47.723 UTC | 16 | 2020-04-01 09:21:46.09 UTC | null | null | null | null | 126,545 | null | 1 | 32 | django-models | 44,186 | <p>What you probably want is a <a href="https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers" rel="noreferrer">custom manager</a></p>
<p>From the django docs:</p>
<pre><code> # An example of a custom manager called "objects".
class PersonManager(models.Manager):
def get_fun_people(self):
return self.filter(fun=True)
class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
fun = models.BooleanField()
objects = PersonManager()
def __unicode__(self):
return u"%s %s" % (self.first_name, self.last_name)
</code></pre>
<p>which then allows you to do something like:</p>
<pre><code>>>> p1 = Person(first_name='Bugs', last_name='Bunny', fun=True)
>>> p1.save()
>>> p2 = Person(first_name='Droopy', last_name='Dog', fun=False)
>>> p2.save()
>>> Person.objects.get_fun_people()
[<Person: Bugs Bunny>]
</code></pre> |
1,858,434 | Build NSIS script as a MSI package | <p>Is there any way to compile the Nullsoft Installer Script (NSI) setup as a MSI package instead of an EXE?</p> | 1,863,053 | 3 | 0 | null | 2009-12-07 07:40:28.747 UTC | 11 | 2015-09-08 07:16:43.19 UTC | 2013-07-21 13:29:04.78 UTC | null | 214,914 | null | 214,914 | null | 1 | 35 | windows-installer|installation|nsis | 32,982 | <p>Unfortunately, No.</p>
<p><a href="http://nsis.sf.net" rel="noreferrer">NSIS</a> lets you create scriptable, procedural installation packages. It's simple, easy to use and has a number of features not present in Windows Installer. </p>
<p><a href="http://msdn.microsoft.com/en-us/library/cc185688(VS.85).aspx" rel="noreferrer">Windows Installer</a> (MSI) creates database driven, transactional installation packages. When written properly a Windows Installer package is very robust, a file gets corrupted/deleted and it will be automatically reinstalled. Windows Installer is aware of UAC and only elevates when required, basically if you're creating software for the corporate market, you will need to provide an MSI.</p>
<p>Check out <a href="https://rads.stackoverflow.com/amzn/click/com/1590592972" rel="noreferrer" rel="nofollow noreferrer">The Definitive Guide to Windows Installer</a> for a good introduction to understanding MSI.</p> |
1,995,847 | Desktop shortcut to restart a windows service | <p>Is it possible to create a windows desktop shortcut that will restart a windows service?</p>
<p>I'd like a button to restart my apache service after I have made changes to the config file.</p> | 1,995,852 | 3 | 0 | null | 2010-01-03 18:43:54.833 UTC | 10 | 2018-08-21 15:47:07.47 UTC | null | null | null | null | 42,106 | null | 1 | 38 | windows|windows-services|shortcut-file | 57,527 | <p>You can do this in a batch file, then make a shortcut to it.</p>
<p>Create a text file with the following content, but save it with the file extension .bat</p>
<pre><code>net stop "Service Name"
net start "Service Name"
</code></pre>
<p>Once the file exists, you can create a shortcut to it, and even assign a keyboard shortcut too if deemed necessary.</p> |
8,772,692 | Semantic search with NLP and elasticsearch | <p>I am experimenting with elasticsearch as a search server and my task is to build a "semantic" search functionality. From a short text phrase like "I have a burst pipe" the system should infer that the user is searching for a plumber and return all plumbers indexed in elasticsearch. </p>
<p>Can that be done directly in a search server like elasticsearch or do I have to use a natural language processing (NLP) tool like e.g. Maui Indexer. What is the exact terminology for my task at hand, text classification? Though the given text is very short as it is a search phrase.</p> | 8,774,917 | 8 | 1 | null | 2012-01-07 20:08:53.427 UTC | 43 | 2022-05-23 10:31:58.12 UTC | 2012-01-07 23:37:17.25 UTC | null | 795,158 | null | 1,089,363 | null | 1 | 66 | search|nlp | 34,134 | <p>There may be several approaches with different implementation complexity. </p>
<p>The easiest one is to create <strong>list of topics</strong> (like plumbing), attach <strong>bag of words</strong> (like "pipe"), identify search request by majority of keywords and search only in specified topic (you can add field <code>topic</code> to your elastic search documents and set it as mandatory with <code>+</code> during search). </p>
<p>Of course, if you have lots of documents, manual creation of topic list and bag of words is very time expensive. You can use <strong>machine learning</strong> to automate some of tasks. Basically, it is enough to have distance measure between words and/or documents to automatically discover topics (e.g. by <strong>data clustering</strong>) and <strong>classify</strong> query to one of these topics. Mix of these techniques may also be a good choice (for example, you can manually create topics and assign initial documents to them, but use classification for query assignment). Take a look at Wikipedia's article on <a href="http://en.wikipedia.org/wiki/Latent_semantic_analysis"><strong>latent semantic analysis</strong></a> to better understand the idea. Also pay attention to the 2 linked articles on <a href="http://en.wikipedia.org/wiki/Data_clustering">data clustering</a> and <a href="http://en.wikipedia.org/wiki/Document_classification">document classification</a>. And yes, <a href="http://code.google.com/p/maui-indexer/">Maui Indexer</a> may become good helper tool this way. </p>
<p>Finally, you can try to build an engine that "understands" meaning of the phrase (not just uses terms frequency) and searches appropriate topics. Most probably, this will involve <strong>natural language processing</strong> and <strong>ontology-based knowledgebases</strong>. But in fact, this field is still in active research and without previous experience it will be very hard for you to implement something like this. </p> |
8,548,533 | Any event triggered on autocomplete? | <p>I have a pretty simple form. When the user types in an input field, I want to update what they've typed somewhere else on the page. This all works fine. I've bound the update to the <code>keyup</code>, <code>change</code> and <code>click</code> events.</p>
<p>The only problem is if you select an input from the browser's autocomplete box, it does not update. Is there any event that triggers when you select from autocomplete (it's apparently neither <code>change</code> nor <code>click</code>). Note that if you select from the autocomplete box and the <em>blur</em> the input field, the update will be triggered. I would like for it to be triggered as soon as the autocomplete .</p>
<p>See: <a href="http://jsfiddle.net/pYKKp/" rel="noreferrer">http://jsfiddle.net/pYKKp/</a> (hopefully you have filled out a lot of forms in the past with an input named "email").</p>
<h3>HTML:</h3>
<pre><code><input name="email" />
<div id="whatever">&lt;whatever></div>
</code></pre>
<h3>CSS:</h3>
<pre><code>div {
float: right;
}
</code></pre>
<h3>Script:</h3>
<pre><code>$("input").on('keyup change click', function () {
var v = $(this).val();
if (v) {
$("#whatever").text(v);
}
else {
$("#whatever").text('<whatever>');
}
});
</code></pre> | 8,548,572 | 8 | 1 | null | 2011-12-17 22:54:46.753 UTC | 15 | 2017-08-30 11:04:51.443 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 454,533 | null | 1 | 77 | javascript|jquery|html|autocomplete | 68,473 | <p>I recommending using <code>monitorEvents</code>. It's a function provide by the javascript console in both <a href="http://developer.apple.com/library/safari/#documentation/appleapplications/Conceptual/Safari_Developer_Guide/DebuggingYourWebsite/DebuggingYourWebsite.html" rel="noreferrer">web inspector</a> and <a href="http://getfirebug.com/wiki/index.php/Command_Line_API#monitorEvents.28object.5B.2C_types.5D.29" rel="noreferrer">firebug</a> that prints out all events that are generated by an element. Here's an example of how you'd use it:</p>
<pre><code>monitorEvents($("input")[0]);
</code></pre>
<p>In your case, both Firefox and Opera generate an <a href="https://developer.mozilla.org/en/DOM/window.oninput" rel="noreferrer"><code>input</code></a> event when the user selects an item from the autocomplete drop down. In IE7-8 a <a href="http://msdn.microsoft.com/en-us/library/ms536912(v=vs.85).aspx" rel="noreferrer"><code>change</code></a> event is produced after the user changes focus. The latest Chrome does generate a similar event.</p>
<p>A detailed browser compatibility chart can be found here:<br>
<a href="https://developer.mozilla.org/en-US/docs/Web/Events/input" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/Events/input</a></p> |
492,232 | How do I set a surf to one color (no gradient) in my matlab-plot? | <p>My dataset consists of three vectors (x,y and z). I plot these values as dots in a 3d-plot with plot3(x,y,z), which is fine. I also want to show a plane in the same plot. To get the data of this plot I use linear regression on x and y to get a new z. </p>
<p>This is how it looks:</p>
<p><a href="https://i.stack.imgur.com/udUoD.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/udUoD.gif" alt="alt text"></a><br>
<sub>(source: <a href="https://bildr.no/image/334949.jpeg" rel="nofollow noreferrer">bildr.no</a>)</sub> </p>
<p>I want the surf to be filled with only one color (say light blue or gray) and set the opacity, to make it see-through. How can I do this?</p> | 492,417 | 4 | 0 | null | 2009-01-29 16:03:37.003 UTC | 4 | 2019-07-13 16:09:38.287 UTC | 2019-07-13 16:09:38.287 UTC | null | 4,751,173 | atsjoo | 37,257 | null | 1 | 17 | graphics|matlab | 57,835 | <p>The easiest way to create a surface that has just 1 color and a given transparency value is to set the 'FaceColor' and 'FaceAlpha' properties of the surface object:</p>
<pre><code>hSurface = surf(...your arguments to create the surface object...);
set(hSurface,'FaceColor',[1 0 0],'FaceAlpha',0.5);
</code></pre>
<p>This example sets the surface color to be red and the transparency to 0.5. You can also set the edge properties too (with 'EdgeColor' and 'EdgeAlpha').</p> |
692,184 | Large File uploading to asp.net MVC | <p>I need a way to upload large files (600 mb to 4 gb) in an asp.net mvc website.
Currently I am using <a href="http://blog.codeville.net/2008/11/24/jquery-ajax-uploader-plugin-with-progress-bar/" rel="nofollow noreferrer">swfupload</a>; it works well enough, but it is a huge hit on the webserver because it sends it in one big upload, plus I have to set it in the web.config to allow that huge of a file, which is a huge security risk. In the past when I was doing web forms development I used <a href="http://www.brettle.com/neatupload" rel="nofollow noreferrer">Neatupload</a> which breaks up the file into chunks and uploads them individually. I am looking for a way to upload large files in mvc that uploads via chunking it up. Any ideas on how I could do this?</p> | 765,386 | 4 | 0 | null | 2009-03-28 04:15:35.307 UTC | 20 | 2015-12-03 20:09:03.6 UTC | 2013-11-18 05:20:48.043 UTC | null | 1,038,866 | Solmead | 2,496 | null | 1 | 20 | asp.net|asp.net-mvc|swfupload|chunking|neatupload | 12,613 | <p><a href="http://www.codeplex.com/SilverlightFileUpld" rel="noreferrer">Silverlight File Upload</a></p> |
21,870 | System.Web.Caching vs. Enterprise Library Caching Block | <p>For a .NET component that will be used in both web applications and rich client applications, there seem to be two obvious options for caching: System.Web.Caching or the Ent. Lib. Caching Block.</p>
<ul>
<li>What do you use?</li>
<li>Why?</li>
</ul>
<h2><a href="http://msdn.microsoft.com/en-us/library/system.web.caching.aspx" rel="noreferrer">System.Web.Caching</a></h2>
<p>Is this safe to use outside of web apps? I've seen mixed information, but I think the answer is maybe-kind-of-not-really.</p>
<ul>
<li><a href="http://support.microsoft.com/kb/917411" rel="noreferrer">a KB article warning against 1.0 and 1.1 non web app use</a></li>
<li>The 2.0 page has a <em>comment</em> that indicates it's OK: <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx</a></li>
<li><a href="http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx" rel="noreferrer">Scott Hanselman is creeped out by the notion</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx" rel="noreferrer">The 3.5 page</a> includes a warning against such use</li>
<li>Rob Howard <a href="http://weblogs.asp.net/cschittko/archive/2004/07/04/172684.aspx" rel="noreferrer">encouraged use outside of web apps</a></li>
</ul>
<p>I don't expect to use one of its highlights, <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.sqlcachedependency.aspx" rel="noreferrer">SqlCacheDependency</a>, but the addition of <a href="http://msdn.microsoft.com/en-us/library/system.web.caching.cacheitemupdatecallback.aspx" rel="noreferrer">CacheItemUpdateCallback</a> in .NET 3.5 seems like a Really Good Thing. </p>
<h2><a href="http://msdn.microsoft.com/en-us/library/aa480453.aspx" rel="noreferrer">Enterprise Library Caching Application Block</a></h2>
<ul>
<li>other blocks are already in use so the dependency already exists</li>
<li>cache persistence isn't necessary; regenerating the cache on restart is OK</li>
</ul>
<p>Some cache items should always be available, but be refreshed periodically. For these items, getting a callback <em>after</em> an item has been removed is not very convenient. It looks like a client will have to just sleep and poll until the cache item is repopulated.</p>
<h2><a href="http://jehiah.cz/projects/memcached-win32/" rel="noreferrer">Memcached for Win32</a> + <a href="http://sourceforge.net/projects/memcacheddotnet/" rel="noreferrer">.NET client</a></h2>
<p>What are the pros and cons when you don't need a <em>distributed</em> cache?</p> | 984,076 | 4 | 0 | null | 2008-08-22 06:07:29.487 UTC | 27 | 2013-06-14 14:44:02.807 UTC | 2008-08-31 00:28:23.77 UTC | Mark Biek | 305 | ESV | 150 | null | 1 | 29 | caching|.net-2.0|memcached|enterprise-library | 13,372 | <p>These are the items that I consider for the topic of Caching:</p>
<p>MemCached Win32
Velocity
.net Cache
Enterprise Library Caching Application Block</p>
<p><strong>MemCached Win32:</strong> Up until recently I have used MemCached Win32. This is a akin to a web farm (many servers serving the same content for high availability) but it is a cache farm. This means that you can install it locally on your web server initially if you don't have the resources to go bigger. Then as you go down the road you can scale horizontally (more servers) or vertically (more hardware). This is a product that was ported from the original MemCached to work on Windows. This product has been used extensively in very high traffic sites. <a href="http://lineofthought.com/tools/memcached" rel="nofollow noreferrer">http://lineofthought.com/tools/memcached</a></p>
<p><strong>Velocity:</strong> This is Microsofts answer to products such as MemCached. MemCached has been out for quite some time, Velocity is in CTP mode. I must say that from what I have read so far this product will certainly turn my head once it is out. But I can't bring myself to run big production projects on a CTP product with zero track record. I have started playing with it though as once it gains momentum MemCached won't even compare for those locked in the windows world! <a href="http://blogs.msdn.com/velocity/" rel="nofollow noreferrer">http://blogs.msdn.com/velocity/</a></p>
<p><strong>.NET Cache:</strong> There is no reason to discount the standard .NET Cache. It is built in and ready to use for free and with no (major) set up required. It offers flexibility by way of offering mechanisms for storing items in local memory, a SINGLE state server, or a centralized database. Where Velocity steps in is when you need more than a single state server (cache in memory) and don't want to use a slow database for holding your cache.</p>
<p><strong>Enterprise Application Block:</strong> I stay away from all of the Enterprise Application Blocks. They are heavy frameworks that give more than I generally require! As long as you remember to wrap everything that touches code that is not your own and follow simple rules for coding, stick to any of the other methods over this one! (just my opinion of course - MySpace leverages as much as they can out of Enterprise Application Blocks!)</p>
<p><strong>You don't have to choose up front!</strong> I generally create a cache wrapper that I communicate with in my code for methods such as Get, Set, Exists, Remove, ListKeys, etc. This then points to an underlying level of cache abstraction that can point to MemCached, Velocity, or .NET cache. I use StructureMap (or choose another IoC container) to inject which form of cache I want to use for a given environment. In my local dev box I might use .NET cache in the session. In production I generally use MemCached Win 32. But regardless of how it is set up you can easily swap things around to try each system out to see what works best for you. You just need to make sure that you application knows as little as possible about how things are cached! Once this layer of abstraction is in place you can then do things such as run a compression algorithm (gzip) for all the data that is going in and out of cache which would allow you to store 10 times the amount of data in cache. - <strong>transparently</strong>.</p>
<p>I cover .NET Cache, MemCached Win32, StructureMap, and the appropriate abstractions in my book if you are interested!</p>
<p>ASP.NET 3.5 Social Networking (<a href="https://rads.stackoverflow.com/amzn/click/com/1847194788" rel="nofollow noreferrer" rel="nofollow noreferrer">http://www.amazon.com/ASP-NET-3-5-Social-Networking-Enterprise-ready/dp/1847194788/ref=sr_1_1?ie=UTF8&s=books&qid=1225408005&sr=8-1</a> )
Andrew Siemer www.andrewsiemer.com blog.andrewsiemer.com www.socialnetworkingin.net</p>
<p><strong>Update</strong>
Changed the link that lists sites using memcached. Thank you David for noticing that it was broken!</p> |
1,196,623 | TCP Vs. Http Benchmark | <p>I am having a Web application sitting on IIS, and talking with [remote]Service-Machine.
I am not sure whether to choose TCP or Http, as the main protocol.</p>
<p>more details:</p>
<ol start="2">
<li>i will have more than one service\endpoint</li>
<li>some of them will be one-way</li>
<li>the other will be two-ways</li>
<li>the web pages will work infront of the services</li>
<li>we are talking about hi-scale web-site</li>
</ol>
<p>I know the difference pretty well, but I am looking for a good benchmark, that shows how much faster is the TCP?</p> | 1,217,954 | 4 | 1 | null | 2009-07-28 20:44:45.11 UTC | 33 | 2019-03-26 22:31:16.863 UTC | 2011-09-26 11:25:16.143 UTC | null | 439,189 | null | 47,817 | null | 1 | 56 | http|tcp | 55,926 | <p>HTTP is a layer built ontop of the TCP layer to some what standardize data transmission. So naturally using TCP sockets will be less heavy than using HTTP. If performance is the only thing you care about then plain TCP is the best solution for you.</p>
<p>You may want to consider HTTP because of its ease of use and simplicity which ultimately reduces development time. If you are doing something that might be directly consumed by a browser (through an AJAX call) then you should use HTTP. For a non-modern browser to directly consume TCP connections without HTTP you would have to use Flash or Silverlight and this normally happens for rich content such as video and/or audio. However, many modern browsers now (as of 2013) support API's to access network, audio, and video resources directly via JavaScript. The only thing to consider is the usage rate of modern web browsers among your users; see <a href="http://caniuse.com/" rel="noreferrer">caniuse.com</a> for the latest info regarding browser compatibility.</p>
<p>As for benchmarks, <a href="http://media.techtarget.com/TheServerSideNET/downloads/DotNet-WebSphere_Web_Services_Benchmark.pdf" rel="noreferrer">this</a> is the only thing I found. See page 5, it has the performance graph. Note that it doesn't really compare apples to apples since it compares the TCP/Binary data option with the HTTP/XML data option. Which begs the question: what kind of data are your services outputting? binary (video, audio, files) or text (JSON, XML, HTML)?</p>
<p>In general performance oriented system like those in the military or financial sectors will probably use plain TCP connections. Where as general web focused companies will opt to use HTTP and use IIS or Apache to host their services. </p> |
745,591 | What is the purpose of Decimal.One, Decimal.Zero, Decimal.MinusOne in .Net | <p>Simple question - why does the Decimal type define these constants? Why bother?</p>
<p>I'm looking for a reason why this is defined by the language, not possible uses or effects on the compiler. Why put this in there in the first place? The compiler can just as easily in-line 0m as it could Decimal.Zero, so I'm not buying it as a compiler shortcut.</p> | 745,638 | 4 | 2 | null | 2009-04-13 22:16:13.967 UTC | 10 | 2020-08-18 21:12:20.337 UTC | 2013-02-26 20:04:12.48 UTC | null | 292,060 | null | 5,255 | null | 1 | 75 | c#|.net|vb.net|decimal|constants | 20,620 | <p>Small clarification. They are actually static readonly values and not constants. That has a distinct difference in .Net because constant values are <em>inlined</em> by the various compilers and hence it's impossible to track their usage in a compiled assembly. Static readonly values however are not copied but instead referenced. This is advantageous to your question because it means the use of them can be analyzed.</p>
<p>If you use reflector and dig through the BCL, you'll notice that MinusOne and Zero are only used with in the VB runtime. It exists primarily to serve conversions between Decimal and Boolean values. Why MinusOne is used coincidentally came up on a separate thread just today (<a href="https://stackoverflow.com/questions/745292/convert-boolean-to-integer-in-vb-net/745366#745366">link</a>)</p>
<p>Oddly enough, if you look at the Decimal.One value you'll notice it's used nowhere. </p>
<p>As to why they are explicitly defined ... I doubt there is a hard and fast reason. There <strong>appears</strong> to be no specific performance and only a bit of a convenience measure that can be attributed to their existence. My <em>guess</em> is that they were added by someone during the development of the BCL for their convenience and just never removed. </p>
<p><strong>EDIT</strong></p>
<p>Dug into the <code>const</code> issue a bit more after a comment by @Paleta. The C# definition of <code>Decimal.One</code> uses the <code>const</code> modifier however it is emitted as a <code>static readonly</code> at the IL level. The C# compiler uses a couple of tricks to make this value virtually indistinguishable from a <code>const</code> (inlines literals for example). This would show up in a language which recognize this trick (VB.Net recognizes this but F# does not). </p> |
55,929,417 | How to securely git clone/pip install a private repository into my docker image? | <p>I have a private repo that contains packages I want to pip install. I've spent quite a bit of time reading over various forums and articles about different ways to securely do this. There doesn't seem to be a a consensus on how to best do this (if at all possible). I obviously don't want to expose any ssh keys/secrets in my dockerfile -- I want to be careful about making them available via docker history.</p> | 55,931,932 | 5 | 0 | null | 2019-04-30 22:24:10.203 UTC | 9 | 2021-06-17 01:07:14.47 UTC | null | null | null | null | 11,234,774 | null | 1 | 17 | git|ssh-keys|docker-image | 18,326 | <p>As explained in "<a href="https://medium.com/@amimahloof/securely-build-small-python-docker-image-from-private-git-repos-c3e6d5da4626" rel="noreferrer">Securely build small python docker image from private git repos</a>", you would need to use, with Docker 18.09+</p>
<blockquote>
<ul>
<li><p><strong><code>--ssh</code></strong><br>
You can use the <code>--ssh</code> flag to forward your existing SSH agent key to the builder. Instead of transferring the key data, docker will just notify the builder that such capability is available.<br>
Now when the builder needs access to a remote server through SSH, it will dial back to the client and ask it to sign the specific request needed for this connection.<br>
<strong>The key itself never leaves the client, and as soon as the command that requested the access has completed there is no information on the builder side to reestablish that remote connection later</strong>.</p></li>
<li><p><strong>Secrets</strong>:<br>
Provides a mount option during the build at <code>/var/run/secrets</code> available only for the command that used it and is not included in the created layer.</p></li>
</ul>
</blockquote>
<p>That is:</p>
<pre><code>docker build --ssh github_ssh_key=/path/to/.ssh/git_ssh_id_rsa .
</code></pre>
<blockquote>
<p>only the agent connection is shared with that command, and not the actual content of the private key.<br>
no other commands/steps in the Dockerfile will have access to it.</p>
</blockquote>
<p>The Dockerfile, in a multistage first step, would give a key name <code>github_ssh_key</code> so we can use it when we invoke <code>docker build</code>:</p>
<pre><code>RUN --mount=type=ssh,id=github_ssh_key pip wheel \
--no-cache \
--requirement requirements.txt \
--wheel-dir=/app/wheels
</code></pre>
<hr>
<p>The <a href="https://stackoverflow.com/users/11234774/jesus-garcia">OP Jesus Garcia</a> did report (in the comments) making it work:</p>
<blockquote>
<p>I had to use 2 separate <code>RUN</code> commands. </p>
<p>I'm not sure if it's a limitation of this new feature, or the way I was trying to string together multiple commands in my <code>RUN</code> but I kept getting a publickey permission denied error when I added it as <code>other commands && /bin/sh -c "mount=type=ssh,id=github_ssh_key pip install private-repo"</code> vs <code>RUN --mount=type=ssh,id=github_ssh_key pip install private-repo && more commands ...</code> </p>
</blockquote> |
2,583,347 | C# HttpListener without using netsh to register a URI | <p>My application uses a small webserver to server up some files and have a web interface for administration remotely. Right now the user has to use netsh to register the URI like so </p>
<pre><code>netsh http add urlacl url=http://+:1233/ user=Chris-PC\Chris
</code></pre>
<p>Which is no fun for the average user. I'd like the program to be able to listen on any port specified by the user from my program without the end-user needing to using command prompt. Is there anyway to accomplish this short of just using Process.Start and running command prompt myself?</p> | 10,128,350 | 2 | 3 | null | 2010-04-06 07:46:03.437 UTC | 11 | 2012-08-22 22:33:27.653 UTC | 2010-04-06 07:51:57.527 UTC | null | 50,447 | null | 148,766 | null | 1 | 27 | c#|windows|http|httplistener|netsh | 19,923 | <p>I wrote this to elevate perms and add http ACL entries through <em>netsh</em>. </p>
<p>Users will get prompted to make changes top their system but it's better than nothing. You might want to do this in response to an <em>AddressAccessDeniedException</em></p>
<pre><code>public static class NetAclChecker
{
public static void AddAddress(string address)
{
AddAddress(address, Environment.UserDomainName, Environment.UserName);
}
public static void AddAddress(string address, string domain, string user)
{
string args = string.Format(@"http add urlacl url={0} user={1}\{2}", address, domain, user);
ProcessStartInfo psi = new ProcessStartInfo("netsh", args);
psi.Verb = "runas";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = true;
Process.Start(psi).WaitForExit();
}
}
</code></pre> |
41,051,972 | vue: Uncaught TypeError: Cannot read property ... of undefined | <p>I'm using [email protected] and the <a href="https://github.com/vuejs-templates/webpack" rel="noreferrer">vue official webpack template</a> to build an app.</p>
<p>When developing locally, I often see the warning <code>Uncaught TypeError: Cannot read property ... of undefined</code>, but the HTML can be rendered successfully. However, the HTML can't be rendered when it's deployed to Netlify with <code>npm run build</code> command. So I have to treat this warning seriously.</p>
<p>I learned from <a href="https://forum-archive.vuejs.org/topic/3953/cannot-read-property-warning/2" rel="noreferrer">here</a> that it's because "the data is not complete when the component is rendered, but e.g. loaded from an API." and the solution is to "use <code>v-if</code> to render that part of the template only once the data has been loaded."</p>
<p>There are two questions:</p>
<ol>
<li>I tried wrap <code>v-if</code> around multiple statements that's generating the warning but personal I think this solution is verbose. Is there a neat approach?</li>
<li>"warnings" in local development turn into "fatal errors"(HTML can't be rendered) in production. How to make them the same? e.g. both of them issue warnings or errors?</li>
</ol> | 41,052,023 | 4 | 0 | null | 2016-12-09 01:59:01.077 UTC | 8 | 2021-11-30 04:56:05.477 UTC | null | null | null | null | 2,599,541 | null | 1 | 38 | vue.js|vue-component|netlify | 148,838 | <p>Just use <code>v-if</code> on a common parent to all the elements in your template relying on that AJAX call, not around each one.</p>
<p>So instead of something like:</p>
<pre><code><div>
<h1 v-if="foo.title">{{ foo.title }}</h1>
<p v-if="foo.description">{{ foo.description }}</p>
</div>
</code></pre>
<p>Do</p>
<pre><code><div>
<template v-if="foo">
<h1>{{ foo.title }}</h1>
<p>{{ foo.description }}</p>
</template>
</div>
</code></pre> |
48,708,119 | How to get width of (DOM) Element in Angular 4 after page is loaded | <p>I'm looking for a solution in Angular 4 to get the width of DOM element without taking any action (click or window resize), just after the page is loaded, but before I start to draw the svg. I've found a similar case in <a href="https://stackoverflow.com/questions/43845822/angular-2-get-width-of-a-div">here</a> but it doesn't work for me. I get the same error:</p>
<blockquote>
<p>ERROR TypeError: Cannot read property 'nativeElement' of undefined</p>
</blockquote>
<p>I need to get the width of div container to set veiwbox of svg I'm drawing inside it.</p>
<p>Here is the template:</p>
<pre><code><div id="what-is-the-width" class="svg-chart-container">
<svg [innerHTML]="svg"></svg>
</div>
</code></pre>
<p>and TS file with stuff needed in this case:</p>
<pre><code>import { Component, Input, OnInit, ViewEncapsulation, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
export class SvgChartComponent implements OnInit {
@ViewChild('what-is-the-width') elementView: ElementRef;
constructor() { }
ngAfterViewInit() {
console.log(this.elementView.nativeElement);
}
ngOnInit() {
//this method gets the data from the server and draw the svg
this.getSVGChartData();
}
}
</code></pre>
<p>Does anyone have ideas how to get this working?</p> | 48,708,282 | 1 | 1 | null | 2018-02-09 14:33:27.643 UTC | 1 | 2018-02-09 15:18:18.823 UTC | 2018-02-09 15:18:18.823 UTC | null | 9,338,572 | null | 9,338,572 | null | 1 | 23 | javascript|angular|typescript | 70,478 | <p>You can't have the size of an element before the page is loaded. In case it's not clear enough, if the page isn't loaded, then your HTML element isn't loaded. </p>
<p>If you want to set the viewbox of your SVG according to a div, you will need to wait for the page to load, then change the viewbox. It's perfectly doable.</p>
<p>The fastest way of doing that is : </p>
<pre><code><div #container>Container's width is {{ container.offsetWidth }}</div>
<svg:svg [width]="container.offsetWidth"></svg>
</code></pre>
<p>I'll let you deal with the viewBox attribute, since I don't really know what you want to do with it.</p>
<p>You need to add the <code>svg:</code> prefix to tell angular it's not a custom directive, by the way.</p> |
42,290,811 | How to use Newtonsoft.Json as default in Asp.net Core Web Api? | <p>I am new to <strong>ASP.Net Web Api Core</strong>. I have been using <strong>ASP.Net MVC</strong> for past few years and I always have written an <code>ActionFilter</code> and used <code>JSON.Net</code> for <code>Serializing</code> data into <code>JSON</code>. So, in that way I replaced Microsoft's <code>JavaScript Serializer</code> (which is slower than <code>JSON.Net</code>) with <code>JSON.Net</code> (it is claimed to be 400% faster).</p>
<p>How to do all this in <strong>ASP.Net Web Api Core</strong>? Where to change the <strong>default formattor</strong>?</p>
<p>Note: Please feel free to ask if you have any questions.</p>
<p>Thanks</p> | 59,649,201 | 3 | 0 | null | 2017-02-17 06:24:50.383 UTC | 6 | 2021-05-11 09:53:17.9 UTC | null | null | null | null | 3,710,908 | null | 1 | 49 | json|serialization|asp.net-web-api|asp.net-core|json.net | 47,994 | <p>In .NET Core 3.0+ include the NuGet package <code>Microsoft.AspNetCore.Mvc.NewtonsoftJson</code> and then replace</p>
<pre class="lang-cs prettyprint-override"><code>services.AddControllers();
</code></pre>
<p>in <code>ConfigureServices</code> with</p>
<pre class="lang-cs prettyprint-override"><code>services.AddControllers().AddNewtonsoftJson();
</code></pre>
<p>This is a pre-release NuGet package in .NET Core 3.0 but a full release package in .NET Core 3.1.</p>
<p>I came across this myself, but I've found that the same answer with some additional info is in <a href="https://stackoverflow.com/q/55666826/">this SO question and answer</a>.</p>
<p><strong>Edit:</strong> As a useful update: code with the call to <code>AddNewtonsoftJson()</code> will compile and run even without installing the <code>Microsoft.AspNetCore.Mvc.NewtonsoftJson</code> NuGet package. If you do that, it runs with <em>both</em> converters installed, but defaulting to the <code>System.Text.Json</code> converter which you presumably don't want since you're reading this answer. So you <em>must remember to install the NuGet package</em> for this to work properly (<em>and</em> remember to re-install it if you ever clear down and redo your NuGet dependencies).</p> |
34,955,879 | How to rotate views on orientation change without recreating layout? | <p>This question has been asked before <a href="https://stackoverflow.com/questions/10913248/rotating-views-but-not-layouts-on-screen-orientation-change">here</a> but its answer is incorrect. I would like to rotate some views on screen orientation change, but I want to keep the layout unchanged. They should be rotated 90, 180, 270 or 360 degrees according to the current orientation (<code>SCREEN_ORIENTATION_LANDSCAPE</code>, <code>SCREEN_ORIENTATION_PORTRAIT</code>, <code>SCREEN_ORIENTATION_REVERSE_LANDSCAPE</code>, <code>SCREEN_ORIENTATION_REVERSE_PORTRAIT</code>).</p>
<p>This is what I want to achieve:</p>
<p><a href="https://i.stack.imgur.com/FNWEl.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FNWEl.png" alt="LayoutExample"></a> </p>
<p>The answer in the link I mentioned stated that I should create a new different layout in <code>layout-land</code>. Clearly, this is not what I want. I don't want to recreate the activity or change layout orientation. I only want to rotate some views, and keep other views unchanged on orientation change.</p>
<p><strong>There is a huge difference between <em>rotating</em> specific views and <em>changing or recreating</em> the whole layout (both on orientation change).</strong></p>
<p>Using the answer in this <a href="https://stackoverflow.com/questions/10380989/how-do-i-get-the-current-orientation-activityinfo-screen-orientation-of-an-a">link</a>, I will be able to get the current screen orientation with this method:</p>
<pre><code>public static int getScreenOrientation(Context context) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
int rotation = windowManager.getDefaultDisplay().getRotation();
DisplayMetrics dm = new DisplayMetrics();
windowManager.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
int orientation;
// if the device's natural orientation is portrait:
if ((rotation == Surface.ROTATION_0
|| rotation == Surface.ROTATION_180) && height > width ||
(rotation == Surface.ROTATION_90
|| rotation == Surface.ROTATION_270) && width > height) {
switch (rotation) {
case Surface.ROTATION_0:
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
break;
case Surface.ROTATION_90:
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
break;
case Surface.ROTATION_180:
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
break;
case Surface.ROTATION_270:
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
break;
default:
Log.e("ScreenOrientation", "Unknown screen orientation. Defaulting to " + "portrait.");
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
break;
}
}
// if the device's natural orientation is landscape or if the device
// is square:
else {
switch (rotation) {
case Surface.ROTATION_0:
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
break;
case Surface.ROTATION_90:
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
break;
case Surface.ROTATION_180:
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
break;
case Surface.ROTATION_270:
orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
break;
default:
Log.e("ScreenOrientation", "Unknown screen orientation. Defaulting to " + "landscape.");
orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
break;
}
}
return orientation;
}
</code></pre>
<p>On orientation change, I would like to do something simple like this:</p>
<pre><code>RotateAnimation rotateAnimation = new RotateAnimation(0, getScreenOrientation(getContext()));
rotateAnimation.setDuration(2000);
for (int i = 0; i < 63; i++) {
Button button = (Button) rootView.findViewById(i);
button.startAnimation(rotateAnimation);
}
</code></pre>
<p>Another way to rephrase my question would be "Is there any way to detect orientation change in <code>onConfigurationChanged()</code> method without changing the layout?". The problem is that it will not be able to detect any orientation change if I already disable layout orientation change.</p>
<p>Anyone knows how it is done? I might have totally gone through wrong steps, and I think I will have to use Accelerometer Sensor or something similar to that to achieve what I want, so please guide me through.</p> | 34,970,844 | 2 | 0 | null | 2016-01-22 21:00:51.76 UTC | 11 | 2016-01-24 10:26:14.9 UTC | 2017-05-23 11:47:29.557 UTC | null | -1 | null | 4,843,993 | null | 1 | 18 | android|android-layout|rotation|android-button|android-orientation | 14,221 | <p>Try to use <code>OrientationEventListener</code>. You don't need to use <code>onConfigurationChanged</code> and <code>android:configChanges="orientation|keyboardHidden|screenSize"</code>. <br /><br/>You need set <code>android:screenOrientation="portrait"</code> for the activity in AndroidManifest.xml. Here is my solution with <code>OrientationEventListener</code>:</p>
<pre><code>public class MyActivity extends Activity{
private ImageButton menuButton;
private Animation toLandAnim, toPortAnim;
private OrientationListener orientationListener;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_image_ruler);
menuButton=(ImageButton)findViewById(R.id.menu_button);
toLandAnim= AnimationUtils.loadAnimation(this, R.anim.menubutton_to_landscape);
toPortAnim= AnimationUtils.loadAnimation(this, R.anim.menubutton_to_portrait);
orientationListener = new OrientationListener(this);
}
@Override protected void onStart() {
orientationListener.enable();
super.onStart();
}
@Override protected void onStop() {
orientationListener.disable();
super.onStop();
}
private class OrientationListener extends OrientationEventListener{
final int ROTATION_O = 1;
final int ROTATION_90 = 2;
final int ROTATION_180 = 3;
final int ROTATION_270 = 4;
private int rotation = 0;
public OrientationListener(Context context) { super(context); }
@Override public void onOrientationChanged(int orientation) {
if( (orientation < 35 || orientation > 325) && rotation!= ROTATION_O){ // PORTRAIT
rotation = ROTATION_O;
menuButton.startAnimation(toPortAnim);
}
else if( orientation > 145 && orientation < 215 && rotation!=ROTATION_180){ // REVERSE PORTRAIT
rotation = ROTATION_180;
menuButton.startAnimation(toPortAnim);
}
else if(orientation > 55 && orientation < 125 && rotation!=ROTATION_270){ // REVERSE LANDSCAPE
rotation = ROTATION_270;
menuButton.startAnimation(toLandAnim);
}
else if(orientation > 235 && orientation < 305 && rotation!=ROTATION_90){ //LANDSCAPE
rotation = ROTATION_90;
menuButton.startAnimation(toLandAnim);
}
}
}
}
</code></pre>
<p>This also prevents from too frequent rotations when <code>orientation</code> is about 45, 135... etc.
Hope it helps.</p> |
58,438,300 | entrypoint: "entrypoint.sh" - docker compose | <p>There is no such file by name <code>entrypoint.sh</code> in my workspace.</p>
<p>But below instruction in <code>docker-compose.yml</code> is referring it:</p>
<pre><code>builder:
build: ../../
dockerfile: docker/dev/Dockerfile
volumes:
- ../../target:/wheelhouse
volumes_from:
- cache
entrypoint: "entrypoint.sh"
command: ["pip", "wheel", "--non-index", "-f /build", "."]
</code></pre>
<hr>
<p>where <code>../docker/dev/Dockerfile</code> has</p>
<pre><code># Set defaults for entrypoint and command string
ENTRYPOINT ["test.sh"]
CMD ["python", "manage.py", "test", "--noinput"]
</code></pre>
<hr>
<p>What does <code>entrypoint: "entrypoint.sh"</code> actually do?</p> | 58,439,355 | 3 | 0 | null | 2019-10-17 17:57:57.97 UTC | 4 | 2019-10-18 10:52:04.817 UTC | 2019-10-17 19:37:45.733 UTC | null | 1,264,304 | null | 3,317,808 | null | 1 | 13 | docker|docker-compose|dockerfile|docker-entrypoint|docker-command | 45,598 | <p><code>entrypoint: "entrypoint.sh"</code> overrides <code>ENTRYPOINT ["test.sh"]</code> from Dockerfile.</p>
<p>From the <a href="https://docs.docker.com/compose/compose-file/#entrypoint" rel="noreferrer">docs</a>:</p>
<blockquote>
<p>Setting entrypoint both overrides any default entrypoint set on the
service’s image with the ENTRYPOINT Dockerfile instruction, and clears
out any default command on the image - meaning that if there’s a CMD
instruction in the Dockerfile, it is ignored.</p>
</blockquote>
<ul>
<li><p><code>ENTRYPOINT ["test.sh"]</code> is set in Dockerfile describing docker image</p></li>
<li><p><code>entrypoint: "entrypoint.sh"</code> is set in docker-compose file which describes multicontainer environment while referencing the Dockerfile. </p></li>
<li><p><code>docker-compose build builder</code> will build image and set entrypoint to <code>ENTRYPOINT ["test.sh"]</code> set in Dockerfile.</p></li>
<li><p><code>docker-compose up builder</code> will start container with entrypoint <code>entrypoint.sh pip wheel --no-index '-f /build' .</code> set in docker-compose file</p></li>
</ul> |
20,375,881 | Android Studio SDK Managed Disabled | <p>I just downloaded the Android Studio .dmg for OSX. Per the installation instructions, I've dragged it to the application folder and launched the application. </p>
<p>But the SDK Manager and AVD Manager are greyed out and are impossible to use. </p>
<p>Any ideas on an installation step I may have missed?</p> | 20,376,658 | 9 | 0 | null | 2013-12-04 12:49:37.01 UTC | 7 | 2020-07-02 08:02:53.11 UTC | 2014-07-22 17:43:02.2 UTC | null | 3,063,884 | null | 1,023,019 | null | 1 | 46 | android|android-studio|android-sdk-tools | 53,838 | <p>A project needs to have been loaded at least once for the link to become available.</p>
<p>Found it in :
File / Project Structure...
Then in "Android SDK" provide the path to the SDK folder inside the Android Studio Application Bundle.<br>
Then Make a new project.<br>
Then after the initial setup the elements where finally enabled.</p> |
20,403,870 | CONCAT equivalent in MS Access | <p>I'm doing some work in MS Access and I need to append a prefix to a bunch of fields, I know SQL but it doesn't quite seem to work the same in Access</p>
<p>Basically I need this translated to a command that will work in access:</p>
<pre><code>UPDATE myTable
SET [My Column] = CONCAT ("Prefix ", [My Column])
WHERE [Different Column]='someValue';
</code></pre>
<p>I've searched up and down and can't seem to find a simple translation.</p> | 20,403,933 | 4 | 0 | null | 2013-12-05 15:25:57.043 UTC | 3 | 2019-05-05 05:36:31.63 UTC | 2013-12-05 15:42:21.25 UTC | null | 77,335 | null | 1,899,815 | null | 1 | 7 | sql|ms-access|ms-access-2010 | 42,327 | <pre><code>UPDATE myTable
SET [My Column] = "Prefix " & [My Column]
WHERE [Different Column]='someValue';
</code></pre>
<p>As far as I am aware there is no CONCAT </p> |
53,657,275 | ionic 4 adding side menu | <p>i started a project with tab template which i then later decided to add a side menu. the trouble is the side menu does not appear at all. here is my app.components.html looks like</p>
<pre><code><ion-app>
<ion-split-pane>
<ion-menu side="start">
<ion-header translucent>
<ion-toolbar color="secondary">
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content><ion-list><ion-item>he vik</ion-item></ion-list></ion-content>
</ion-menu>
<ion-router-outlet></ion-router-outlet>
</ion-split-pane>
</ion-app>
</code></pre>
<p>actually after doing above my actual page comes for a brief second and shows a white page due to this. </p>
<p>in the console i see an error</p>
<pre><code>sz7tok82.entry.js:5 Menu: must have a "content" element to listen for drag events on.
</code></pre>
<p>but i already have content element.</p> | 53,671,879 | 2 | 0 | null | 2018-12-06 18:05:05.543 UTC | 1 | 2018-12-07 14:51:46.33 UTC | null | null | null | null | 135,982 | null | 1 | 17 | ionic-framework|ionic4|ion-menu | 40,140 | <p>Sirius2013 is correct, you will need to use the contentId attribute.
See a working example below:<br><br></p>
<p><strong>App.component.html</strong></p>
<pre><code><ion-app>
<ion-menu contentId="content1" side="start">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
menu stuff
</ion-content>
</ion-menu>
<ion-router-outlet id="content1" main></ion-router-outlet>
</ion-app>
</code></pre>
<p><br>
<strong>AnyPage.html</strong></p>
<p>In the page you want to show your side menu, you can use the <em>ion-menu-button</em> tag.
<br>See this example:</p>
<pre><code><ion-header>
<ion-toolbar>
<ion-title>Page Title</ion-title>
<ion-buttons slot="start">
<ion-menu-button autoHide="false"></ion-menu-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
</code></pre>
<p>Set the <em>autoHide</em> tag to <em>false</em>, so you will always see the menu button.</p>
<p>Docs:
<a href="https://beta.ionicframework.com/docs/api/menu-button" rel="noreferrer">https://beta.ionicframework.com/docs/api/menu-button</a></p> |
26,686,850 | Add n tasks to celery queue and wait for the results | <p>I'd add several jobs to the celery queue and wait for the results. I have many ideas about how I would accomplish this using some type of shared storage (memcached, redis, database, etc.), but I think it was something Celery could handle automatically, but I can't find any resources online.</p>
<p><strong>Code example</strong></p>
<pre><code>def do_tasks(b):
for a in b:
c.delay(a)
return c.all_results_some_how()
</code></pre> | 36,466,097 | 3 | 0 | null | 2014-11-01 06:42:07.657 UTC | 8 | 2021-11-30 16:38:18.817 UTC | 2021-11-30 16:38:18.817 UTC | null | 3,907,250 | null | 374,052 | null | 1 | 28 | python|django|celery|django-celery | 20,811 | <p>For <strong>Celery >= 3.0</strong>, TaskSet is <a href="http://docs.celeryproject.org/en/3.0/internals/deprecation.html#taskset" rel="noreferrer">deprecated</a> in favour of <a href="http://docs.celeryproject.org/en/latest/userguide/canvas.html#groups" rel="noreferrer">group</a>.</p>
<pre><code>from celery import group
from tasks import add
job = group([
add.s(2, 2),
add.s(4, 4),
add.s(8, 8),
add.s(16, 16),
add.s(32, 32),
])
</code></pre>
<p>Start the group in the background:</p>
<pre><code>result = job.apply_async()
</code></pre>
<p>Wait:</p>
<pre><code>result.join()
</code></pre> |
39,890,055 | What is 'Vary for Traits' in Xcode 8? | <p>I am using AutoLayout and Size classes, but with release of iOS 10 and new Xcode 8.0, there is one new option <code>Vary for Traits</code>. Is this replacement of Size Classe for different width and height of devices.</p>
<p><a href="https://i.stack.imgur.com/WeXcj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WeXcj.png" alt="enter image description here"></a> </p>
<p>By selection of <code>width</code> checkbox, it displays <code>varying 14 compact width devices</code>.</p>
<p><a href="https://i.stack.imgur.com/PHT7h.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PHT7h.png" alt="enter image description here"></a></p>
<p>By selection of <code>height</code> checkbox, it displays <code>varying 18 compact height devices</code>.</p>
<p><a href="https://i.stack.imgur.com/Ce4Eh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ce4Eh.png" alt="enter image description here"></a></p>
<p>By selection of both checkbox, it displays <code>varying 11 compact width regular height devices</code>.</p>
<p><a href="https://i.stack.imgur.com/QAAuJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QAAuJ.png" alt="enter image description here"></a></p>
<p>How to make use of this options ?
Can we use AutoLayout with size classes as like Xcode7.0 ?
If any one has in depth knowledge then please explain it.</p> | 39,892,473 | 3 | 1 | null | 2016-10-06 07:29:58.197 UTC | 49 | 2018-08-28 18:52:38.307 UTC | 2018-08-28 18:52:38.307 UTC | null | 1,032,372 | null | 3,045,336 | null | 1 | 91 | ios|xcode8|ios10|ios-autolayout | 56,794 | <p>This is just an extension as to how to use "Vary Traits" quickly in your project for adding different layouts for iPad and iPhones.</p>
<p>Please read this for understanding more on the Size classes. </p>
<p><a href="https://developer.apple.com/reference/uikit/uitraitcollection" rel="noreferrer">https://developer.apple.com/reference/uikit/uitraitcollection</a></p>
<p><a href="https://i.stack.imgur.com/LisTT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LisTT.png" alt="enter image description here"></a></p>
<p>If you are skipping the example which follows below, do read the Summary in the end.</p>
<hr>
<ul>
<li><strong>OBJECTIVE :</strong></li>
</ul>
<p><strong><em>You need a button having different widths in iPhone and iPad. The former having width of 80 and latter having a width of 300.</em></strong></p>
<ul>
<li><strong>METHOD 1 :</strong></li>
</ul>
<p><strong><em>Vary for Traits with Multiple Constraints as installed.</em></strong></p>
<ul>
<li><p><strong>STEPS :</strong></p>
<ol>
<li>Add the common constraints first like Center the button horizontally and vertically.</li>
</ol></li>
</ul>
<p><a href="https://i.stack.imgur.com/cyAo2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cyAo2.png" alt="enter image description here"></a></p>
<ol start="2">
<li>Choose VaryForTraits and for iPhone screens as per the size class guidelines , a C*R size class fits the model and this we check the tickmarks of Width & Height in PopUp. Dismiss the pop-up by clicking anywhere on screen.</li>
</ol>
<p><a href="https://i.stack.imgur.com/8tdaQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8tdaQ.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/Vyd1V.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Vyd1V.png" alt="enter image description here"></a></p>
<ol start="3">
<li>Add the width constant and check whether the constraint is added for C*R size-class. After adding constraints, choose Done Varying button.</li>
</ol>
<p><a href="https://i.stack.imgur.com/leoQx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/leoQx.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/VSXU9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VSXU9.png" alt="enter image description here"></a></p>
<ol start="4">
<li>For iPad screens, again select any iPad device and choose VaryForTraits and this time on clicking height-width, it should show R*R variation.</li>
</ol>
<p><a href="https://i.stack.imgur.com/XabTb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XabTb.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/1HnMk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1HnMk.png" alt="enter image description here"></a></p>
<ol start="5">
<li>Again add a width constraint, the last added iPhone width constraint must be unhighlighted as in the screenshot. The value added will be for the size-class R*R this time.</li>
</ol>
<p><a href="https://i.stack.imgur.com/9zCs5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9zCs5.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/YJpei.png" rel="noreferrer"><img src="https://i.stack.imgur.com/YJpei.png" alt="enter image description here"></a></p>
<ol start="6">
<li>Switch back to iPhone layout and it takes 80 as width and iPad will take 300.</li>
</ol>
<p><a href="https://i.stack.imgur.com/i9Qmw.png" rel="noreferrer"><img src="https://i.stack.imgur.com/i9Qmw.png" alt="enter image description here"></a></p>
<p><strong>CONCLUSION :</strong></p>
<p>Please notice that there are total of two constraints added and in both the constraints, the values differ according to the size-class chosen.</p>
<hr>
<ul>
<li><strong>METHOD 2 :</strong></li>
</ul>
<p><strong><em>Vary for Traits with Single Constraint , Multiple Size-Class installed</em></strong> </p>
<ul>
<li><strong>STEPS :</strong>
<ol>
<li>Add the normal width constraint. Then select that constraint and choose the + button besides the Constant value.</li>
</ol></li>
</ul>
<p><a href="https://i.stack.imgur.com/688N0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/688N0.png" alt="enter image description here"></a></p>
<ol start="2">
<li>Add trait variation, and for iPhone we choose C*R and set the constant value as 100.</li>
</ol>
<p><a href="https://i.stack.imgur.com/LqSIn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LqSIn.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/frryS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/frryS.png" alt="enter image description here"></a></p>
<ol start="3">
<li>Again for iPad which follows a trait variation as R*R, we add another variation by clicking again on + button and set the value as 300.</li>
</ol>
<p><a href="https://i.stack.imgur.com/Gogi7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Gogi7.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/ZWehs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZWehs.png" alt="enter image description here"></a></p>
<ol start="4">
<li>Select an iPad and the width will be automatically taken as 300 and coming back to iPhone it takes 100 as value. </li>
</ol>
<p><a href="https://i.stack.imgur.com/zIVdC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zIVdC.png" alt="enter image description here"></a></p>
<p><strong>CONCLUSION :</strong></p>
<p>This seems to be a better option rather than adding two constraints when a single constraint is only required and the constant value differs.</p>
<p><strong>WHEN TO USE, WHAT TO USE :</strong></p>
<p>Both the approaches are basically doing the same thing, setting values to Size-classes.</p>
<p>But, <strong>#Method1</strong> is used when you want to add a constraint specifically for a device or say size-class. For example, in iPhone the button should be from Top 50 pts and in iPad it should be centered horizontally and vertically. In such situations, you need to use VaryForTraits as it opens doors to add constraints for a specific size class.</p>
<p><strong>#Method2</strong> is used when you want different constant values for a same constraint type.</p>
<p><strong>P.S : TO ALL THOSE WHO ARE NOT ABLE TO GET THE EXAMPLE WORKING</strong></p>
<p><em>Please make sure, you are adding only the required constraints as Installed. The checkbox against Installed should only appear for the constraint that you need for a size class. That is the key!</em></p>
<p><a href="https://i.stack.imgur.com/hYgXq.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hYgXq.png" alt="enter image description here"></a></p>
<p><em>Just add a top constraint & a leading to an uiButton in a view. Select the top constraint and uncheck the basic Installed option with Plus sign. Now, by clicking on the Plus sign, add variation to C</em>R and check that option. Now, change the device from iPhone to iPad with various orientation combinations. This constraint will be applied only for C<em>R size class which is iPhone in portrait orientation. If the checkbox against the basic Installed (the one with Plus symbol) was checked that means the constraint should be applied to all size classes.</em></p>
<p><strong>SUMMARY :</strong> </p>
<p><em>Trait Variation is a change to the presentation of your user interface that is based on a device configuration.</em> Trait Variations of the user interface is not just limited to constraints but can be applied to much more. Such as changing the color of the background and other elements when the device is set to a dark style. A variation can apply to an element of the user interface, such removing a constraint, or to a property of a view class or constraint, such as the font for a label. You can vary:</p>
<ul>
<li><p>Size or position of a view</p></li>
<li><p>Installation of a view</p></li>
<li><p>Installation of a constraint</p></li>
<li><p>Constraint constant</p></li>
<li><p>Font</p></li>
<li><p>Color for the font, tint, or background</p></li>
<li><p>Layout margins</p></li>
<li><p>Image file</p></li>
</ul>
<p>The specific set of properties you can vary depends on the class of the element. In the example, we have demonstrated the use of- Installation of a constraint & - Constraint constant . Others, are quite simple and can be easily inferred. </p> |
40,253,332 | Generating random date in a specific range in JAVA | <p>How to generate random dates in a specific range in JAVA? I have seen <a href="https://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range">How do I generate random integers within a specific range in Java?</a> link which is to generate random numbers.Is there similar/other kind of way to generate random date in JAVA? </p> | 40,253,420 | 3 | 2 | null | 2016-10-26 03:39:53.183 UTC | null | 2021-01-18 04:55:06.377 UTC | 2017-05-23 12:02:26.147 UTC | null | -1 | null | 3,151,210 | null | 1 | 10 | java|algorithm|date | 38,123 | <p>Given that your question is unclear, I am expecting you are trying to generate random <code>java.util.Date</code> with given range.</p>
<p>Please note that <code>java.util.Date</code> contains date + time information.</p>
<p><code>Date</code> in Java is represented by milliseconds from EPOCH. Therefore the easiest way to do what you want is, given d1 and d2 is <code>Date</code>, and d1 < d2 (in pseudo-code):</p>
<pre><code>Date randomDate = new Date(ThreadLocalRandom.current()
.nextLong(d1.getTime(), d2.getTime()));
</code></pre>
<hr />
<p>If it is actually a "Date" (without time) that you want to produce, which is usually represented by <code>LocalDate</code> (in Java 8+, or using JODA Time).</p>
<p>It is as easy as, assume d1 and d2 being <code>LocalDate</code>, with <code>d1 < d2</code> (pseudo-code):</p>
<pre><code>int days = Days.daysBetween(d1, d2).toDays();
LocalDate randomDate = d1.addDays(
ThreadLocalRandom.current().nextInt(days+1));
</code></pre> |
21,958,083 | Using Java nio to create a subdirectory and file | <p>I'm creating a simple program that will try to read in "conf/conf.xml" from disk, but if this file or dir doesn't exist will instead create them.</p>
<p>I can do this using the following code:</p>
<pre><code> // create subdirectory path
Path confDir = Paths.get("./conf");
// create file-in-subdirectory path
Path confFile = Paths.get("./conf/conf.xml");
// if the sub-directory doesn't exist then create it
if (Files.notExists(confDir)) {
try { Files.createDirectory(confDir); }
catch (Exception e ) { e.printStackTrace(); }
}
// if the file doesn't exist then create it
if (Files.notExists(confFile)) {
try { Files.createFile(confFile); }
catch (Exception e ) { e.printStackTrace(); }
}
</code></pre>
<p>My questions is if this really the most elegant way to do this? It seems superflous to need to create two Paths simple to create a new file in a new subdirectory.</p> | 21,958,158 | 3 | 2 | null | 2014-02-22 17:54:31.66 UTC | 5 | 2020-05-25 06:25:52.45 UTC | null | null | null | null | 3,341,332 | null | 1 | 31 | java|file|nio | 39,452 | <p>You could declare your <code>confFile</code> as <code>File</code> instead of <code>Path</code>. Then you can use <code>confFile.getParentFile().mkdirs();</code>, see example below:</p>
<pre><code>// ...
File confFile = new File("./conf/conf.xml");
confFile.getParentFile().mkdirs();
// ...
</code></pre>
<p>Or, using your code as is, you can use:</p>
<pre><code>Files.createDirectories(confFile.getParent());
</code></pre> |
37,514,509 | Advantages of using std::make_unique over new operator | <p>What are the advantages of using <code>std::make_unique</code> over the <code>new</code> operator for initializing a <code>std::unique_ptr</code>? </p>
<p>In other words, why is </p>
<pre><code>std::unique_ptr<SomeObject> a = std::make_unique(SomeObject(...))
</code></pre>
<p>better than doing</p>
<pre><code>std::unique_ptr<SomeObject> a = new SomeObject(...)
</code></pre>
<p>I tried looking up a lot online and I do know that it is a good rule of thumb to avoid the operator <code>new</code> in modern C++, but I am not sure what the advantages are in this exact scenario. Does it prevent any kind of memory leaks that might happen? Is it faster to do a <code>std::make_unique</code> than to use <code>new</code>? </p> | 37,514,601 | 2 | 1 | null | 2016-05-29 20:14:48.19 UTC | 57 | 2022-03-07 18:41:22.097 UTC | 2018-04-15 06:20:21.117 UTC | null | 7,328,782 | null | 213,207 | null | 1 | 168 | c++|c++14|unique-ptr | 148,042 | <h2>Advantages</h2>
<ul>
<li><p><code>make_unique</code> teaches users "never say <code>new</code>/<code>delete</code> and
<code>new[]</code>/<code>delete[]</code>" without disclaimers.</p>
</li>
<li><p><code>make_unique</code> shares two advantages with <code>make_shared</code> (excluding the third advantage, increased efficiency). First, <code>unique_ptr<LongTypeName> up(new LongTypeName(args))</code> must mention <code>LongTypeName</code> twice, while <code>auto up = make_unique<LongTypeName>(args)</code> mentions it once.</p>
</li>
<li><p><code>make_unique</code> prevents the unspecified-evaluation-order
leak triggered by expressions like <code>foo(unique_ptr<X>(new X), unique_ptr<Y>(new Y))</code>. (Following the advice "never say <code>new</code>" is simpler than
"never say <code>new</code>, unless you immediately give it to a named <code>unique_ptr</code>".)</p>
</li>
<li><p><code>make_unique</code> is carefully implemented for exception safety and is recommended over directly calling <code>unique_ptr</code> constructors.</p>
</li>
</ul>
<h2>When not to use <code>make_unique</code></h2>
<ul>
<li>Don't use <code>make_unique</code> if you need a custom deleter or are adopting a raw pointer from elsewhere.</li>
</ul>
<h2>Sources</h2>
<ol>
<li><a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3588.txt" rel="noreferrer">Proposal of <code>std::make_unique</code></a>.</li>
<li><a href="https://herbsutter.com/2013/05/29/gotw-89-solution-smart-pointers/" rel="noreferrer">Herb Sutter's GotW #89 Solution: Smart Pointers</a></li>
</ol> |
37,337,728 | TensorFlow: InternalError: Blas SGEMM launch failed | <p>When I run <code>sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})</code> I get <code>InternalError: Blas SGEMM launch failed</code>. Here is the full error and stack trace:</p>
<pre><code>InternalErrorTraceback (most recent call last)
<ipython-input-9-a3261a02bdce> in <module>()
1 batch_xs, batch_ys = mnist.train.next_batch(100)
----> 2 sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
338 try:
339 result = self._run(None, fetches, feed_dict, options_ptr,
--> 340 run_metadata_ptr)
341 if run_metadata:
342 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
562 try:
563 results = self._do_run(handle, target_list, unique_fetches,
--> 564 feed_dict_string, options, run_metadata)
565 finally:
566 # The movers are no longer used. Delete them.
/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
635 if handle is None:
636 return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
--> 637 target_list, options, run_metadata)
638 else:
639 return self._do_call(_prun_fn, self._session, handle, feed_dict,
/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
657 # pylint: disable=protected-access
658 raise errors._make_specific_exception(node_def, op, error_message,
--> 659 e.code)
660 # pylint: enable=protected-access
661
InternalError: Blas SGEMM launch failed : a.shape=(100, 784), b.shape=(784, 10), m=100, n=10, k=784
[[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholder_0/_4, Variable/read)]]
Caused by op u'MatMul', defined at:
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/local/lib/python2.7/dist-packages/ipykernel/__main__.py", line 3, in <module>
app.launch_new_instance()
File "/usr/local/lib/python2.7/dist-packages/traitlets/config/application.py", line 596, in launch_instance
app.start()
File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelapp.py", line 442, in start
ioloop.IOLoop.instance().start()
File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/ioloop.py", line 162, in start
super(ZMQIOLoop, self).start()
File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 883, in start
handler_func(fd_obj, events)
File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
self._handle_recv()
File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 276, in dispatcher
return self.dispatch_shell(stream, msg)
File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
handler(stream, idents, msg)
File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 391, in execute_request
user_expressions, allow_stdin)
File "/usr/local/lib/python2.7/dist-packages/ipykernel/ipkernel.py", line 199, in do_execute
shell.run_cell(code, store_history=store_history, silent=silent)
File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2723, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2825, in run_ast_nodes
if self.run_code(code, result):
File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2885, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-4-d7414c4b6213>", line 4, in <module>
y = tf.nn.softmax(tf.matmul(x, W) + b)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 1036, in matmul
name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 911, in _mat_mul
transpose_b=transpose_b, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 655, in apply_op
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2154, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1154, in __init__
self._traceback = _extract_stack()
</code></pre>
<p>Stack: EC2 g2.8xlarge machine, Ubuntu 14.04</p> | 39,353,693 | 16 | 1 | null | 2016-05-20 04:00:45.673 UTC | 17 | 2020-01-30 05:30:48.177 UTC | null | null | null | null | 1,930,168 | null | 1 | 75 | tensorflow|blas | 61,819 | <p>Old question, but may help others. <br/>
Try to close interactive sessions active in other processes (if IPython Notebook - just restart kernels). This helped me!<br/><br/>
Additionally, I use this code to close local sessions in this kernel during experiments:</p>
<pre><code>if 'session' in locals() and session is not None:
print('Close interactive session')
session.close()
</code></pre> |
20,490,274 | How to reset index in a pandas dataframe? | <p>I have a dataframe from which I remove some rows. As a result, I get a dataframe in which index is something like that: <code>[1,5,6,10,11]</code> and I would like to reset it to <code>[0,1,2,3,4]</code>. How can I do it?</p>
<hr>
<p>The following seems to work:</p>
<pre><code>df = df.reset_index()
del df['index']
</code></pre>
<p>The following does not work:</p>
<pre><code>df = df.reindex()
</code></pre> | 20,491,748 | 3 | 1 | null | 2013-12-10 09:12:55.51 UTC | 134 | 2020-06-28 05:50:04.093 UTC | 2019-12-09 16:01:38.527 UTC | null | 6,361,531 | null | 245,549 | null | 1 | 503 | python|indexing|pandas|dataframe | 830,115 | <p><a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>DataFrame.reset_index</code></a> is what you're looking for. If you don't want it saved as a column, then do:</p>
<pre><code>df = df.reset_index(drop=True)
</code></pre>
<p>If you don't want to reassign:</p>
<pre><code>df.reset_index(drop=True, inplace=True)
</code></pre> |
46,759,801 | How to solve the AttributeError:'list' object has no attribute 'astype'? | <p>I am just wondering how to solve the attribute error in <code>python3.6.</code>
The error is </p>
<blockquote>
<p>'list' object has no attribute 'astype'.</p>
</blockquote>
<p>My related code is as blow.</p>
<pre><code>def _init_mean_std(self, data):
data = data.astype('float32')
self.mean, self.std = np.mean(data), np.std(data)
self.save_meanstd()
return data
</code></pre>
<p>Is there anyone who can advice to me?</p>
<p>Thank you!</p> | 46,760,597 | 1 | 2 | null | 2017-10-15 20:43:57.123 UTC | 5 | 2022-02-10 00:13:42.963 UTC | 2018-05-04 11:25:06.503 UTC | null | 6,529,212 | null | 8,032,125 | null | 1 | 18 | python|numpy|attributes | 76,633 | <p>The root issue is confusion of Python lists and NumPy arrays, which are different data types. NumPy methods that are invoked as <code>np.foo(array)</code> usually won't complain if you give them a Python list, they will convert it to an NumPy array silently. But if you try to invoke a method contained in the object, like <code>array.foo()</code> then of course it has to have the appropriate type already. </p>
<p>I would suggest using </p>
<pre><code>data = np.array(data, dtype=np.float32)
</code></pre>
<p>so that the type of an array is known to NumPy at once. This avoids unnecessary work where you first create an array and then cast it to another type. </p>
<p>NumPy recommends using <a href="https://docs.scipy.org/doc/numpy-1.13.0/user/basics.types.html" rel="noreferrer">dtype objects</a> instead of strings like "float32". </p> |
39,478,018 | Remove an entry from credential manager for all users on Windows | <p>I am currently implementing a "remove settings" for all users in a Windows uninstaller and came over an issue I am not even sure is possible to solve.</p>
<p>The application stores credential entries for the current user using the CredentialManager (<code>keymgr.dll</code>). Let's call the target of the credential "X". On uninstall all credentials with stored with target "X" should be removed on all users. The uninstaller of course requires administrator privileges but still I find it very difficult to accomplish this.</p>
<p>For the current user that command is generally solved via <code>cmdkey /delete=:X</code> from a command prompt. As far as I know <code>cmdkey.exe /list</code> only helps to list entries for the current user and can't remove local entries from another user. </p>
<p>I have learned that the credentials are stored as OS files under the <code>C:\Users\_user_\AppData\Local\Microsoft\Credentials</code> folder, but I can't know which files are the entries I want to delete and removing all would be dangerous for other applications. Also I assume removing OS files will be dangerous and could have limitations (extra UAC prompt?) as well.</p>
<p><code>Runas</code> command is the closest shot I got but because it requires the password of the user it becomes very difficult and not something I would want in the uninstaller. I also would need a way to get the username and domain for each user and iterate them.</p>
<p>I would prefer to use either <code>cmd</code> or <code>powershell</code> for this.</p> | 45,491,094 | 4 | 1 | null | 2016-09-13 19:54:24.31 UTC | 7 | 2022-01-27 18:42:06.837 UTC | null | null | null | null | 2,383,179 | null | 1 | 11 | windows|powershell|cmd|credential-manager | 41,892 | <p>Don't want to necro an old post but I needed to do this myself so I figured I'd add this in case anyone else needs it:</p>
<pre><code>cmdkey /list | ForEach-Object{if($_ -like "*Target:*" -and $_ -like "*microsoft*"){cmdkey /del:($_ -replace " ","" -replace "Target:","")}}
</code></pre>
<p>Powershell one liner that will remove any credentials with Microsoft in the string.</p>
<p>Reference:
<a href="https://gist.github.com/janikvonrotz/7819990" rel="noreferrer">https://gist.github.com/janikvonrotz/7819990</a></p>
<p>I ran this and it purged it locally without needing to run as admin (but I am a local admin)</p> |
39,616,821 | swift 3.0 Data to String? | <pre><code>func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {}
</code></pre>
<p>I want <code>deviceToken</code> to string</p>
<p>but:</p>
<pre><code>let str = String.init(data: deviceToken, encoding: .utf8)
</code></pre>
<p><code>str</code> is <code>nil</code></p>
<p>swift 3.0 </p>
<p>how can I let <code>data</code> to <code>string</code> ?</p>
<p><a href="https://stackoverflow.com/questions/37956482/registering-for-push-notifications-in-xcode-8-swift-3-0">Registering for Push Notifications in Xcode 8/Swift 3.0?</a>
not working and the answer is a few months ago, I had tried it:</p>
<p><a href="https://i.stack.imgur.com/tcqjQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/tcqjQ.png" alt="enter image description here"></a></p>
<p>and print:</p>
<p><a href="https://i.stack.imgur.com/WKD6I.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WKD6I.png" alt="enter image description here"></a></p> | 41,559,862 | 12 | 2 | null | 2016-09-21 12:39:53.073 UTC | 21 | 2020-05-18 07:47:02.24 UTC | 2018-10-19 07:38:01.543 UTC | null | 4,826,457 | null | 5,089,211 | null | 1 | 95 | swift|string | 129,392 | <p>I came looking for the answer to the Swift 3 Data to String question and never got a good answer. After some fooling around I came up with this:</p>
<pre><code>var testString = "This is a test string"
var somedata = testString.data(using: String.Encoding.utf8)
var backToString = String(data: somedata!, encoding: String.Encoding.utf8) as String!
</code></pre> |
20,268,494 | Linux - How to list all users and their UIDs | <p>How to write a script for linux which list all users from /etc/passwd and their UID</p>
<pre><code>User1 uid=0001
User2 uid=0002
...
</code></pre>
<p>the script should use: grep, cut, id, for</p> | 20,268,664 | 4 | 1 | null | 2013-11-28 14:22:03.42 UTC | 4 | 2021-09-09 18:10:43.647 UTC | 2021-09-09 18:10:43.647 UTC | null | 7,487,335 | null | 2,998,059 | null | 1 | 10 | linux|awk|grep|uid | 54,091 | <pre><code>awk -F: '$0=$1 " uid="$3' /etc/passwd
</code></pre>
<p>awk is easier in this case. </p>
<p>-F defines field separator as <code>:</code></p>
<p>so you want is 1st and 3rd colums. so build the <code>$0</code> to provide your output format. </p>
<p>this is very basic usage of powerful awk. you may want to read some tutorials if you faced this kind of problem often.</p>
<p>This time you got fish, if I were you, I am gonna do some research on how to fishing.</p> |
20,045,726 | Skip whitespaces with getline | <p>I'm making a program to make question forms. The questions are saved to a file, and I want to read them and store them in memory (I use a vector for this).
My questions have the form:</p>
<pre><code>1 TEXT What is your name?
2 CHOICE Are you ready for these questions?
Yes
No
</code></pre>
<p>My problem is, when I'm reading these questions from the file, I read a line, using getline, then I turn it into a stringstream, read the number and type of question, and then use getline again, on the stringstream this time, to read the rest of the question.
But what this does is, it also reads a whitespace that's in front of the question and when I save the questions to the file again and run the program again, there are 2 whitespaces in front of the questions and after that there are 3 whitespaces and so on...</p>
<p>Here's a piece of my code:</p>
<pre><code>getline(file, line);
std::stringstream ss(line);
int nmbr;
std::string type;
ss >> nmbr >> type;
if (type == "TEXT") {
std::string question;
getline(ss, question);
Question q(type, question);
memory.add(q);
</code></pre>
<p>Any ideas on how to solve this? Can getline ignore whitespaces?</p> | 20,045,810 | 2 | 2 | null | 2013-11-18 10:41:32.233 UTC | 7 | 2013-11-18 11:03:59.353 UTC | 2013-11-18 11:03:59.353 UTC | null | 1,670,308 | null | 1,833,854 | null | 1 | 8 | c++|string|whitespace|getline|stringstream | 40,481 | <p>Look at <a href="http://www.cplusplus.com/reference/istream/ws/">this</a> and use:</p>
<pre><code>ss >> std::ws;
getline(ss, question);
</code></pre> |
6,405,123 | How do I call a stored procedure with arguments using sqlcmd.exe? | <p>I need to call a stored procedure and pass arguments in from Powershell. I think the best option is to use sqlcmd.exe but I'm not sure how to pass arguments to the stored proc using this tool.</p> | 6,405,239 | 2 | 0 | null | 2011-06-19 21:05:24.053 UTC | 3 | 2015-01-09 16:04:45.613 UTC | null | null | null | null | 13,877 | null | 1 | 13 | sql-server|stored-procedures|powershell|sqlcmd | 44,195 | <p>sqlcmd.exe supports variable substitution and parameters via the <code>/v</code> argument, see <a href="http://msdn.microsoft.com/en-us/library/ms188714.aspx">Using sqlcmd with Scripting Variables</a>. For example:</p>
<pre><code>sqlcmd -E -d <mydb> -Q "exec usp_myproc @variable=$(myparam)" /v myparam=1
</code></pre>
<p>will invoke the procedure passing the value 1 to the script to be substituted for the variable <code>$(myparam)</code>. Note that sqlcmd variable substitution is a string replacement of <code>$(variable)</code> which occurs in sqlcmd, befor the batch (request) is sent to the SQL Server. </p> |
67,210,527 | How to provide an implementation of memcpy | <p>I am trying to write some bare metal code with a <code>memset</code>-style loop in it:</p>
<pre><code>for (int i = 0; i < N; ++i) {
arr[i] = 0;
}
</code></pre>
<p>It is compiled with GCC and GCC is smart enough to turn that into a call to <code>memset()</code>. Unfortunately because it's bare metal I have no <code>memset()</code> (normally in libc) so I get a link error.</p>
<pre><code> undefined reference to `memset'
</code></pre>
<p>It seems like the optimisation that does this transformation is <a href="https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html" rel="noreferrer"><code>-ftree-loop-distribute-patterns</code></a>:</p>
<blockquote>
<p>Perform loop distribution of patterns that can be code generated with calls to a library. This flag is enabled by default at -O2 and higher, and by <code>-fprofile-use</code> and <code>-fauto-profile</code>.</p>
</blockquote>
<p>So <a href="https://www.raspberrypi.org/forums/viewtopic.php?p=597641&sid=aeaf7c139c824cc0772a1620aa85b946#p597641" rel="noreferrer">one person's solution</a> was to just lower the optimisation level. Not very satisfying.</p>
<p>I also found <a href="http://cs107e.github.io/guides/gcc/" rel="noreferrer">this really helpful page</a> that explains that <code>-ffreestanding</code> is not enough to get GCC not to do this, and there's basically no option but to provide your own implementations of <code>memcpy</code>, <code>memmove</code>, <code>memset</code> and <code>memcmp</code>. I'm happy to do that, but how?</p>
<p>If I just write <code>memset</code> the compiler will detect the loop inside it and transform it into a call to memset! In fact in the code provided by the CPU vendor I'm using I actually found this comment:</p>
<pre><code>/*
// This is commented out because the assembly code that the compiler generates appears to be
// wrong. The code would recursively call the memset function and eventually overruns the
// stack space.
void * memset(void *dest, int ch, size_t count)
...
</code></pre>
<p>So I assume that is the issue they ran into.</p>
<p>How do I supply a C implementation of <code>memset</code> without the compiler optimising it to a call to itself and without disabling that optimisation?</p> | 67,210,528 | 2 | 24 | null | 2021-04-22 09:26:34.867 UTC | 4 | 2021-04-22 20:58:41.573 UTC | 2021-04-22 20:48:35.457 UTC | null | 265,521 | null | 265,521 | null | 1 | 37 | c|gcc|memset | 1,541 | <p>Aha I checked in <a href="https://github.com/bminor/glibc/blob/master/string/memset.c#L26" rel="noreferrer">the glibc code</a> and there's a <code>inhibit_loop_to_libcall</code> modifier which sounds like it should do this. It is <a href="https://github.com/bminor/glibc/blob/81cbc3bcaed730aa5d9e5d4ec46a0d4cb9eb6cd5/include/libc-symbols.h#L1040" rel="noreferrer">defined like this</a>:</p>
<pre class="lang-c prettyprint-override"><code>/* Add the compiler optimization to inhibit loop transformation to library
calls. This is used to avoid recursive calls in memset and memmove
default implementations. */
#ifdef HAVE_CC_INHIBIT_LOOP_TO_LIBCALL
# define inhibit_loop_to_libcall \
__attribute__ ((__optimize__ ("-fno-tree-loop-distribute-patterns")))
#else
# define inhibit_loop_to_libcall
#endif
</code></pre> |
7,543,077 | Getting fb.me URL | <p>How do I go about either making, or retrieving facebook short url's (fb.me) from a page, profile, event etc? I want to update my url shortener site - but if the user links to a facebook page I want to just return a fb.me link instead. Does facebook make their short urls on the fly, or does each page automatically already have one?</p> | 8,268,732 | 3 | 0 | null | 2011-09-25 01:34:39.763 UTC | 7 | 2017-01-03 21:04:21.377 UTC | 2011-09-25 07:41:33.263 UTC | null | 265,570 | null | 722,986 | null | 1 | 13 | facebook|url|hyperlink|short | 120,047 | <p>Facebook uses <a href="http://bit.ly/" rel="noreferrer">Bit.ly</a>'s services to shorten links from their site. While pages that have a username turns into "<code>fb.me/<username></code>", other links associated with Facebook turns into "<code>on.fb.me/*****</code>". To you use the on.fb.me service, just use your Bit.ly account. Note that if you change the default link shortener on your Bit.ly account to j.mp from bit.ly this service won't work.</p> |
7,682,714 | Does MongoDB support floating point types? | <p>I am migrating a mysql database to mongodb. But i have read in MongoDb data types and then there is no reference to floating point types like, float, double, decimal.</p>
<p>And how i have some fields with decimal types in my sql schema , how can i do or what can i do?</p> | 7,682,922 | 4 | 1 | null | 2011-10-07 03:18:05.44 UTC | 2 | 2017-07-09 13:24:12.88 UTC | 2017-09-22 18:01:22.247 UTC | null | -1 | null | 491,637 | null | 1 | 34 | mongodb|database|nosql | 51,599 | <p>MongoDB stores data in a binary format called <a href="http://bsonspec.org/#/specification">BSON</a> which supports these numeric data types:</p>
<ul>
<li><code>int32</code> - 4 bytes (32-bit signed integer)</li>
<li><code>int64</code> - 8 bytes (64-bit signed integer)</li>
<li><code>double</code> - 8 bytes (64-bit IEEE 754 floating point)</li>
</ul>
<p>There's no exact value fixed-point equivalent to mySQL's <code>decimal</code> type in MongoDB, but you can store 64-bit floating point numbers in Mongo as a <code>double</code>.</p>
<p>It's worth mentioning that the MongoDB shell - being a JavaScript shell - doesn't recognise the distinction between integer and floating-point values, it treats all numbers the same because JavaScript represents all numbers as 64-bit floating point, regardless of their underlying BSON type.</p>
<p>Most <a href="http://www.mongodb.org/display/DOCS/Drivers">MongoDB language drivers</a>, however, make the distinction between integer and floating point types.</p> |
7,120,813 | AsyncTaskLoader vs AsyncTask | <p>Since <code>Honeycomb</code> and the <code>v4 Compatibility Library</code> it is possible to use <code>AsyncTaskLoader</code>. From what I understand, the <code>AsyncTaskLoader</code> can survive through config changes like screen flips. </p>
<p>Is it recommended to use <code>AsyncTaskLoader</code> instead of <code>AsyncTask</code>? Does <code>LoaderManager</code> get in the picture too?</p>
<p>But I haven't found any good example(s) about how to correctly use the <code>AsyncTaskLoader</code>. The docs also provide no examples. Can anyone provide some good examples.</p> | 7,122,836 | 4 | 0 | null | 2011-08-19 11:20:26.933 UTC | 40 | 2018-02-18 06:30:22.277 UTC | 2012-05-23 04:04:51.567 UTC | null | 844,882 | null | 891,436 | null | 1 | 129 | android|android-asynctask|android-loadermanager | 51,558 | <p>You can have a look at the compatibility library's source code to get more info. What a <code>FragmentActivity</code> does is:</p>
<ul>
<li>keep a list of <code>LoaderManager</code>'s</li>
<li>make sure they don't get destroyed when you flip your phone (or another configuration change occurs) by saving instances using <code>onRetainNonConfigurationInstance()</code></li>
<li>kick the right loader when you call <code>initLoader()</code> in your Activity</li>
</ul>
<p>You need to use the <code>LoaderManager</code> to interface with the loaders, and provide the needed callbacks to create your loader(s) and populate your views with the data they return. </p>
<p>Generally it should be easier than managing <code>AsyncTask</code>'s yourself. However, <code>AsyncTaskLoader</code> is not exactly well documented, so you should study the example in the docs and/or model your code after <code>CursorLoader</code>. </p> |
24,172,111 | Change the Blank Cells to "NA" | <p>Here's the <a href="https://www.dropbox.com/s/ttwiitihjtb7mec/data2.csv">link</a> of my data. </p>
<p>My target is to assign "NA" to all blank cells irrespective of categorical or numerical values. I am using <strong>na.strings=""</strong>. But it's not assigning NA to all blank cells.</p>
<pre><code>## reading the data
dat <- read.csv("data2.csv")
head(dat)
mon hr acc alc sex spd axles door reg cond1 drug1
1 8 21 No Control TRUE F 0 2 2 Physical Impairment (Eyes, Ear, Limb) A
2 7 20 No Control FALSE M 900 2 2 Inattentive D
3 3 9 No Control FALSE F 100 2 2 2004 Normal D
4 1 15 No Control FALSE M 0 2 2 Physical Impairment (Eyes, Ear, Limb) D
5 4 21 No Control FALSE 25 NA NA D
6 4 20 No Control NA F 30 2 4 Drinking Alcohol - Impaired D
inj1 PED_STATE st rac1
1 Fatal <NA> F <NA>
2 Moderate <NA> F <NA>
3 Moderate <NA> M <NA>
4 Complaint <NA> M <NA>
5 Complaint <NA> F <NA>
6 Moderate <NA> M <NA>
## using na.strings
dat2 <- read.csv("data2.csv", header=T, na.strings="")
head(dat2)
mon hr acc alc sex spd axles door reg cond1 drug1
1 8 21 No Control TRUE F 0 2 2 <NA> Physical Impairment (Eyes, Ear, Limb) A
2 7 20 No Control FALSE M 900 2 2 <NA> Inattentive D
3 3 9 No Control FALSE F 100 2 2 2004 Normal D
4 1 15 No Control FALSE M 0 2 2 <NA> Physical Impairment (Eyes, Ear, Limb) D
5 4 21 No Control FALSE 25 NA NA <NA> <NA> D
6 4 20 No Control NA F 30 2 4 <NA> Drinking Alcohol - Impaired D
inj1 PED_STATE st rac1
1 Fatal NA F NA
2 Moderate NA F NA
3 Moderate NA M NA
4 Complaint NA M NA
5 Complaint NA F NA
6 Moderate NA M NA
</code></pre> | 24,172,277 | 14 | 1 | null | 2014-06-11 20:35:06.5 UTC | 52 | 2022-05-02 15:29:34.657 UTC | 2022-05-02 15:29:34.657 UTC | null | 792,066 | null | 2,530,371 | null | 1 | 106 | r | 323,594 | <p>I'm assuming you are talking about row 5 column "sex." It could be the case that in the data2.csv file, the cell contains a space and hence is not considered empty by R.</p>
<p>Also, I noticed that in row 5 columns "axles" and "door", the original values read from data2.csv are string "NA". You probably want to treat those as na.strings as well. To do this, </p>
<pre><code>dat2 <- read.csv("data2.csv", header=T, na.strings=c("","NA"))
</code></pre>
<p>EDIT:</p>
<p>I downloaded your data2.csv. Yes, there is a space in row 5 column "sex". So you want</p>
<pre><code>na.strings=c(""," ","NA")
</code></pre> |
1,427,840 | Looping through rows in a DataView | <p>The <code>DataView</code> object doesn't have a <code>Rows</code> property like <code>DataTable</code>.</p>
<p>How do I loop through the rows of a DataView?</p> | 1,427,841 | 4 | 0 | null | 2009-09-15 15:21:38.273 UTC | 5 | 2019-08-26 14:02:49.513 UTC | 2012-09-12 06:00:17.44 UTC | null | 1,434,734 | null | 6,651 | null | 1 | 60 | .net|loops|dataview | 124,142 | <p>The DataView object itself is used to loop through DataView rows.</p>
<p>DataView rows are represented by the <a href="http://msdn.microsoft.com/en-us/library/system.data.datarowview.aspx" rel="noreferrer">DataRowView</a> object. The <a href="http://msdn.microsoft.com/en-us/library/system.data.datarowview.row.aspx" rel="noreferrer">DataRowView.Row</a> property provides access to the original DataTable row.</p>
<p><strong>C#</strong></p>
<pre><code>foreach (DataRowView rowView in dataView)
{
DataRow row = rowView.Row;
// Do something //
}
</code></pre>
<p><strong>VB.NET</strong></p>
<pre><code>For Each rowView As DataRowView in dataView
Dim row As DataRow = rowView.Row
' Do something '
Next
</code></pre> |
52,817,280 | Problem downloading a PDF blob in JavaScript | <p>I've created a function that takes a <code>blob</code> and <code>fileName</code> which is supposed to download that blob implemented as follows:</p>
<pre><code>const blobToBase64 = (blob, callback) => {
const reader = new FileReader();
reader.onloadend = () => {
const base64 = reader.result;
console.log({ base64 });
callback(base64);
};
reader.readAsDataURL(blob);
};
const downloadFile = (blob, fileName) => () => {
const link = document.createElement('a');
blobToBase64(blob, (base64) => {
link.href = base64;
link.download = fileName;
link.click();
});
};
downloadFile(myBlob, myFileName);
</code></pre>
<p>To try debug this I've made a <code>console.log</code> to log out the value of <code>base64</code> which is created by <code>reader.result</code>.</p>
<p>That <code>base64</code> value is <code>data:application/octet-stream;base64,Mzc4MDY4...</code></p>
<p>My PDF file get's downloaded but it's corrupted. What am I doing wrong in my file download implementation?</p>
<p>Let me know if there are any additional details that might help with this? I'm 100% sure that the blob itself is not a corrupted file. </p> | 52,829,183 | 2 | 6 | null | 2018-10-15 12:54:21.707 UTC | 8 | 2022-08-09 23:02:07.567 UTC | 2018-10-15 13:15:55.007 UTC | null | 2,111,515 | null | 2,111,515 | null | 1 | 18 | javascript|file|download|base64|blob | 50,135 | <p>I can't tell for sure why your code doesn't work, but I can tell for sure that what you are doing is useless at best.</p>
<p><strong>Do not convert a Blob to a dataURI</strong>, 99%* of the time, what you want to do with this dataURI can be done directly with the original Blob and a blobURI.</p>
<p><sup>*The remaining 1% being when you need to create standalone documents that will include binary data, it happens but not that often.</sup></p>
<p>Here, once again what you want to do (set an anchor to point to your Blob's data) can be done with the Blob directly: simply create a blobURI (which is just a pointer to the data in memory) by calling <a href="https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL" rel="noreferrer"><code>URL.createObjectURL(blob)</code></a>.</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>const downloadFile = (blob, fileName) => {
const link = document.createElement('a');
// create a blobURI pointing to our Blob
link.href = URL.createObjectURL(blob);
link.download = fileName;
// some browser needs the anchor to be in the doc
document.body.append(link);
link.click();
link.remove();
// in case the Blob uses a lot of memory
setTimeout(() => URL.revokeObjectURL(link.href), 7000);
};
downloadFile(new Blob(['random data']), "myfile.txt");</code></pre>
</div>
</div>
</p> |
10,609,972 | Nested "CASE when" statement | <p>How can i use a nested form of the 'case' statement in a sql query. i am trying to execute the following query.</p>
<pre><code>SELECT AccessTabF1.Month, AccessTabF1.Year, AccessTabF1.[Entity Number],
case when [Exp Year]= 2010 + 1
then 'Expires in 1 to 5 Years'
else
case when [Exp Year]>2010 + 5
then 'Expires After 5 Years'
else 'No Expiration Year Listed'
end
from AccessTabF1
</code></pre> | 10,609,992 | 1 | 2 | null | 2012-05-15 22:58:40.95 UTC | null | 2012-05-15 23:18:16.4 UTC | 2012-05-15 23:18:16.4 UTC | null | 61,305 | null | 1,319,424 | null | 1 | 2 | sql|sql-server-2008 | 58,268 | <p>In your case you don't need to nest multiple CASE expressions.</p>
<pre><code>SELECT AccessTabF1.Month, AccessTabF1.Year, AccessTabF1.[Entity Number],
case when [Exp Year] = 2010 + 1 -- why not = 2011 ?
then 'Expires in 1 to 5 Years' -- this does not match the logic on line above
when [Exp Year] > 2010 + 5 -- why not > 2015 ?
then 'Expires After 5 Years'
else 'No Expiration Year Listed'
end
from AccessTabF1
</code></pre> |
10,275,348 | What is android:ems attribute in Edit Text? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/7053738/what-means-ems-android-textview">What means Ems? (Android TextView)</a> </p>
</blockquote>
<p>In <code>EditText</code> there is an attribute named <code>android:ems</code>. The description
is "Makes the <code>EditText</code> be exactly this many ems wide"</p>
<p>What does ems mean? </p> | 10,275,385 | 2 | 2 | null | 2012-04-23 05:40:39.02 UTC | 18 | 2012-04-23 05:44:21.02 UTC | 2017-05-23 12:18:22.093 UTC | null | -1 | null | 614,807 | null | 1 | 180 | android | 221,592 | <p>Taken from: <a href="http://www.w3.org/Style/Examples/007/units">http://www.w3.org/Style/Examples/007/units</a>:</p>
<blockquote>
<p>The em is simply the font size. In an element with a 2in font, 1em
thus means 2in. Expressing sizes, such as margins and paddings, in em
means they are related to the font size, and if the user has a big
font (e.g., on a big screen) or a small font (e.g., on a handheld
device), the sizes will be in proportion. Declarations such as
'text-indent: 1.5em' and 'margin: 1em' are extremely common in CSS.</p>
</blockquote>
<p><code>em</code> is basically CSS property for font sizes.</p> |
36,351,496 | Type-safety in C | <p>Is there a way to make C a little more aware of types and assure type-safety?<br>
Consider this:</p>
<pre><code>typedef unsigned cent_t;
typedef unsigned dollar_t;
#define DOLLAR_2_CENT(dollar) ((cent_t)(100*(dollar)))
void calc(cent_t amount) {
// expecting 'amount' to semantically represents cents...
}
int main(int argc, char* argv[]) {
dollar_t amount = 50;
calc(DOLLAR_2_CENT(amount)); // ok
calc(amount); // raise warning
return 0;
}
</code></pre>
<p>Is there a way to make the above code at-least raise warning by the gcc?<br>
I know I can use C-structs to wrap <code>unsigned</code>s and achieve the desired result, I was just wondering if there was a more elegant way to do it.<br>
Can it be a little more than that?</p> | 36,355,331 | 4 | 6 | null | 2016-04-01 08:24:54.47 UTC | 8 | 2016-04-01 16:26:28.65 UTC | 2016-04-01 08:40:05.46 UTC | null | 1,070,117 | null | 2,760,487 | null | 1 | 38 | c|type-safety | 5,867 | <p>You need to use a static analysis tool in your build process to achieve this.</p>
<p>For example, if you run PCLint on your code, it gives this output:</p>
<pre><code> [Warning 632] Assignment to strong type 'cent_t' in context: arg. no. 1
[Warning 633] Assignment from a strong type 'dollar_t' in context: arg. no. 1
</code></pre>
<p><a href="http://www.gimpel.com/html/strong.htm" rel="noreferrer">http://www.gimpel.com/html/strong.htm</a></p> |
49,037,742 | Why does it take ages to install Pandas on Alpine Linux | <p>I've noticed that installing Pandas and Numpy (it's dependency) in a Docker container using the base OS Alpine vs. CentOS or Debian takes much longer. I created a little test below to demonstrate the time difference. Aside from the few seconds Alpine takes to update and download the build dependencies to install Pandas and Numpy, why does the setup.py take around 70x more time than on Debian install?</p>
<p>Is there any way to speed up the install using Alpine as the base image or is there another base image of comparable size to Alpine that is better to use for packages like Pandas and Numpy?</p>
<p><strong>Dockerfile.debian</strong></p>
<pre><code>FROM python:3.6.4-slim-jessie
RUN pip install pandas
</code></pre>
<p><strong>Build Debian image with Pandas & Numpy:</strong></p>
<pre><code>[PandasDockerTest] time docker build -t debian-pandas -f Dockerfile.debian . --no-cache
Sending build context to Docker daemon 3.072kB
Step 1/2 : FROM python:3.6.4-slim-jessie
---> 43431c5410f3
Step 2/2 : RUN pip install pandas
---> Running in 2e4c030f8051
Collecting pandas
Downloading pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl (26.2MB)
Collecting numpy>=1.9.0 (from pandas)
Downloading numpy-1.14.1-cp36-cp36m-manylinux1_x86_64.whl (12.2MB)
Collecting pytz>=2011k (from pandas)
Downloading pytz-2018.3-py2.py3-none-any.whl (509kB)
Collecting python-dateutil>=2 (from pandas)
Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
Collecting six>=1.5 (from python-dateutil>=2->pandas)
Downloading six-1.11.0-py2.py3-none-any.whl
Installing collected packages: numpy, pytz, six, python-dateutil, pandas
Successfully installed numpy-1.14.1 pandas-0.22.0 python-dateutil-2.6.1 pytz-2018.3 six-1.11.0
Removing intermediate container 2e4c030f8051
---> a71e1c314897
Successfully built a71e1c314897
Successfully tagged debian-pandas:latest
docker build -t debian-pandas -f Dockerfile.debian . --no-cache 0.07s user 0.06s system 0% cpu 13.605 total
</code></pre>
<p><strong>Dockerfile.alpine</strong></p>
<pre><code>FROM python:3.6.4-alpine3.7
RUN apk --update add --no-cache g++
RUN pip install pandas
</code></pre>
<p><strong>Build Alpine image with Pandas & Numpy:</strong></p>
<pre><code>[PandasDockerTest] time docker build -t alpine-pandas -f Dockerfile.alpine . --no-cache
Sending build context to Docker daemon 16.9kB
Step 1/3 : FROM python:3.6.4-alpine3.7
---> 4b00a94b6f26
Step 2/3 : RUN apk --update add --no-cache g++
---> Running in 4b0c32551e3f
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/community/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/community/x86_64/APKINDEX.tar.gz
(1/17) Upgrading musl (1.1.18-r2 -> 1.1.18-r3)
(2/17) Installing libgcc (6.4.0-r5)
(3/17) Installing libstdc++ (6.4.0-r5)
(4/17) Installing binutils-libs (2.28-r3)
(5/17) Installing binutils (2.28-r3)
(6/17) Installing gmp (6.1.2-r1)
(7/17) Installing isl (0.18-r0)
(8/17) Installing libgomp (6.4.0-r5)
(9/17) Installing libatomic (6.4.0-r5)
(10/17) Installing pkgconf (1.3.10-r0)
(11/17) Installing mpfr3 (3.1.5-r1)
(12/17) Installing mpc1 (1.0.3-r1)
(13/17) Installing gcc (6.4.0-r5)
(14/17) Installing musl-dev (1.1.18-r3)
(15/17) Installing libc-dev (0.7.1-r0)
(16/17) Installing g++ (6.4.0-r5)
(17/17) Upgrading musl-utils (1.1.18-r2 -> 1.1.18-r3)
Executing busybox-1.27.2-r7.trigger
OK: 184 MiB in 50 packages
Removing intermediate container 4b0c32551e3f
---> be26c3bf4e42
Step 3/3 : RUN pip install pandas
---> Running in 36f6024e5e2d
Collecting pandas
Downloading pandas-0.22.0.tar.gz (11.3MB)
Collecting python-dateutil>=2 (from pandas)
Downloading python_dateutil-2.6.1-py2.py3-none-any.whl (194kB)
Collecting pytz>=2011k (from pandas)
Downloading pytz-2018.3-py2.py3-none-any.whl (509kB)
Collecting numpy>=1.9.0 (from pandas)
Downloading numpy-1.14.1.zip (4.9MB)
Collecting six>=1.5 (from python-dateutil>=2->pandas)
Downloading six-1.11.0-py2.py3-none-any.whl
Building wheels for collected packages: pandas, numpy
Running setup.py bdist_wheel for pandas: started
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: still running...
Running setup.py bdist_wheel for pandas: finished with status 'done'
Stored in directory: /root/.cache/pip/wheels/e8/ed/46/0596b51014f3cc49259e52dff9824e1c6fe352048a2656fc92
Running setup.py bdist_wheel for numpy: started
Running setup.py bdist_wheel for numpy: still running...
Running setup.py bdist_wheel for numpy: still running...
Running setup.py bdist_wheel for numpy: still running...
Running setup.py bdist_wheel for numpy: finished with status 'done'
Stored in directory: /root/.cache/pip/wheels/9d/cd/e1/4d418b16ea662e512349ef193ed9d9ff473af715110798c984
Successfully built pandas numpy
Installing collected packages: six, python-dateutil, pytz, numpy, pandas
Successfully installed numpy-1.14.1 pandas-0.22.0 python-dateutil-2.6.1 pytz-2018.3 six-1.11.0
Removing intermediate container 36f6024e5e2d
---> a93c59e6a106
Successfully built a93c59e6a106
Successfully tagged alpine-pandas:latest
docker build -t alpine-pandas -f Dockerfile.alpine . --no-cache 0.54s user 0.33s system 0% cpu 16:08.47 total
</code></pre> | 49,057,289 | 10 | 6 | null | 2018-02-28 20:10:17.747 UTC | 32 | 2022-07-10 21:09:23.047 UTC | null | null | null | null | 3,089,468 | null | 1 | 153 | pandas|numpy|docker|alpine-linux | 95,876 | <p>Debian based images use only <code>python pip</code> to install packages with <code>.whl</code> format:</p>
<pre><code> Downloading pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl (26.2MB)
Downloading numpy-1.14.1-cp36-cp36m-manylinux1_x86_64.whl (12.2MB)
</code></pre>
<p>WHL format was developed as a quicker and more reliable method of installing Python software than re-building from source code every time. WHL files only have to be moved to the correct location on the target system to be installed, whereas a source distribution requires a build step before installation.</p>
<p>Wheel packages <code>pandas</code> and <code>numpy</code> are not supported in images based on Alpine platform. That's why when we install them using <code>python pip</code> during the building process, we always compile them from the source files in alpine:</p>
<pre><code> Downloading pandas-0.22.0.tar.gz (11.3MB)
Downloading numpy-1.14.1.zip (4.9MB)
</code></pre>
<p>and we can see the following inside container during the image building:</p>
<pre><code>/ # ps aux
PID USER TIME COMMAND
1 root 0:00 /bin/sh -c pip install pandas
7 root 0:04 {pip} /usr/local/bin/python /usr/local/bin/pip install pandas
21 root 0:07 /usr/local/bin/python -c import setuptools, tokenize;__file__='/tmp/pip-build-en29h0ak/pandas/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n
496 root 0:00 sh
660 root 0:00 /bin/sh -c gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DTHREAD_STACK_SIZE=0x100000 -fPIC -Ibuild/src.linux-x86_64-3.6/numpy/core/src/pri
661 root 0:00 gcc -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -DTHREAD_STACK_SIZE=0x100000 -fPIC -Ibuild/src.linux-x86_64-3.6/numpy/core/src/private -Inump
662 root 0:00 /usr/libexec/gcc/x86_64-alpine-linux-musl/6.4.0/cc1 -quiet -I build/src.linux-x86_64-3.6/numpy/core/src/private -I numpy/core/include -I build/src.linux-x86_64-3.6/numpy/core/includ
663 root 0:00 ps aux
</code></pre>
<p>If we modify <code>Dockerfile</code> a little:</p>
<pre><code>FROM python:3.6.4-alpine3.7
RUN apk add --no-cache g++ wget
RUN wget https://pypi.python.org/packages/da/c6/0936bc5814b429fddb5d6252566fe73a3e40372e6ceaf87de3dec1326f28/pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl
RUN pip install pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl
</code></pre>
<p>we get the following error:</p>
<pre><code>Step 4/4 : RUN pip install pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl
---> Running in 0faea63e2bda
pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl is not a supported wheel on this platform.
The command '/bin/sh -c pip install pandas-0.22.0-cp36-cp36m-manylinux1_x86_64.whl' returned a non-zero code: 1
</code></pre>
<p>Unfortunately, the only way to install <code>pandas</code> on an Alpine image is to wait until build finishes.</p>
<p>Of course if you want to use the Alpine image with <code>pandas</code> in CI for example, the best way to do so is to compile it once, push it to any registry and use it as a base image for your needs.</p>
<p><strong>EDIT:</strong>
If you want to use the Alpine image with <code>pandas</code> you can pull my <a href="https://hub.docker.com/r/nickgryg/alpine-pandas/" rel="noreferrer">nickgryg/alpine-pandas</a> docker image. It is a python image with pre-compiled <code>pandas</code> on the Alpine platform. It should save your time.</p> |
7,499,248 | How do I run a shell script as root (sudo)? | <p>I have a SVN repository server that runs under the repository user. I want to run a script after every post-commit action. I wrote a shell script that runs from the hook after every commit. It needs to be run as root. This is why I used sudo in the script, but it didn't work. <strong>Is there any way to run the script as root?</strong></p>
<pre><code>sudo su
echo "password"
svn export --force file:///home/repository/trunk/ /home/memarexweb/public_html/devel/
chmod -R 777 /home/memarexweb/public_html/devel/
</code></pre> | 8,144,503 | 5 | 3 | null | 2011-09-21 11:50:36.147 UTC | 4 | 2020-04-06 20:40:40.003 UTC | 2011-11-16 05:05:36.503 UTC | null | 3,619 | null | 956,867 | null | 1 | 10 | svn|shell|sudo | 81,835 | <p>I was searching around and found this useful solution: </p>
<p>Edit your <code>sudoers</code> file to allow running certain commands without a password.</p>
<p>It's best to split your <code>post-commit</code> script into two parts, one of which will be run through <code>sudo</code>.</p>
<ul>
<li><p>entry in <code>/etc/sudoers</code>:</p>
<pre><code>loqman ALL=(root) NOPASSWD: /usr/local/bin/svn-postcommit-export
</code></pre></li>
<li><p>Your post-commit hook:</p>
<pre><code>#!/bin/sh
sudo /usr/local/bin/svn-postcommit-export
</code></pre></li>
<li><p>Script <code>/usr/local/bin/svn-postcommit-export</code>:</p>
<pre><code>#!/bin/sh
svn export --force file:///home/repository/trunk/ /home/memarexweb/public_html/devel/
chmod -R 777 /home/memarexweb/public_html/devel/
</code></pre>
<p>(You can choose any name and put the script anywhere; I just suggested <code>svn-postcommit-export</code> as an example, and <code>/usr/local/bin</code> as a common location.)</p></li>
</ul> |
7,097,921 | Devise - how to change setting so that email addresses don't need to be unique | <p>I set up Devise to log in with a username instead of email address because a significant number of our users share the same email address with their spouse. It is a unique market that we serve. But each spouse needs separate accounts to record personality instrument results.</p>
<p>The database no longer requires a unique email address so it will accept the same email addy for two accounts. However, Devise is still requiring a unique email address for each account. Is there a setting or a work around that i can use to change this?</p> | 7,098,114 | 5 | 0 | null | 2011-08-17 18:53:22.777 UTC | 12 | 2019-06-20 03:29:19.65 UTC | 2011-08-18 14:49:01.223 UTC | null | 293,686 | null | 488,856 | null | 1 | 20 | ruby-on-rails|ruby|ruby-on-rails-3|devise | 21,236 | <p>Look in the <code>config/initializers/devise.rb</code>. You can change the default authentication key, which by default is <code>:email</code> to be anything you want, for example:</p>
<p><code>config.authentication_keys = [ :username ]</code></p> |
7,378,382 | Select div (or other element) that class contains "grap" (o other specified word) for example | <p>First of all; example of HTML code:</p>
<pre><code><div class"grap1"> some conetent</div>
<div class"grap2"> some conetent</div>
<div class"grap3"> some conetent</div>
<div class"blabla">some content></div>
</code></pre>
<p>And now i want to select divs that class contains "grap" word somewhere is class name (so in this case first three divs). How can i achieve that ?</p>
<p>This is not working: <a href="http://api.jquery.com/attribute-contains-word-selector/" rel="noreferrer">http://api.jquery.com/attribute-contains-word-selector/</a></p> | 7,378,426 | 5 | 2 | null | 2011-09-11 13:09:15.89 UTC | 1 | 2011-09-11 13:19:12.6 UTC | null | null | null | null | 931,067 | null | 1 | 22 | jquery|class|attributes|word|contains | 44,910 | <p>Use the <a href="http://api.jquery.com/attribute-contains-selector/">attribute contains selector</a>:</p>
<pre><code>$('div[class*="grap"]')
</code></pre> |
7,134,723 | Hadoop on OSX "Unable to load realm info from SCDynamicStore" | <p>I am getting this error on startup of Hadoop on OSX 10.7:</p>
<blockquote>
<p>Unable to load realm info from SCDynamicStore
put: org.apache.hadoop.hdfs.server.namenode.SafeModeException: Cannot create directory /user/travis/input/conf. Name node is in safe mode.</p>
</blockquote>
<p>It doesn't appear to be causing any issues with the functionality of Hadoop.</p> | 7,851,395 | 7 | 1 | null | 2011-08-20 21:13:04.803 UTC | 30 | 2013-11-19 21:19:39.997 UTC | null | null | null | null | 881,306 | null | 1 | 57 | macos|hadoop|osx-lion | 42,312 | <p>Matthew Buckett's suggestion in HADOOP-7489 worked for me. Add the following to your hadoop-env.sh file:</p>
<pre><code>export HADOOP_OPTS="-Djava.security.krb5.realm=OX.AC.UK -Djava.security.krb5.kdc=kdc0.ox.ac.uk:kdc1.ox.ac.uk"
</code></pre> |
7,405,438 | Why if (n & -n) == n then n is a power of 2? | <p><a href="http://developer.classpath.org/doc/java/util/Random-source.html#line.294">Line 294 of java.util.Random source</a> says</p>
<pre><code>if ((n & -n) == n) // i.e., n is a power of 2
// rest of the code
</code></pre>
<p>Why is this?</p> | 7,405,512 | 7 | 5 | null | 2011-09-13 16:44:36.003 UTC | 40 | 2012-09-27 11:13:21.783 UTC | 2012-08-20 16:29:47.973 UTC | null | 20,394 | null | 407,315 | null | 1 | 84 | java|logic|bit-manipulation | 7,404 | <p>The description is not entirely accurate because <code>(0 & -0) == 0</code> but 0 is not a power of two. A better way to say it is</p>
<p><code>((n & -n) == n)</code> when n is a power of two, or the negative of a power of two, or zero.</p>
<p>If n is a power of two, then n in binary is a single 1 followed by zeros.
-n in two's complement is the inverse + 1 so the bits lines up thus</p>
<pre><code> n 0000100...000
-n 1111100...000
n & -n 0000100...000
</code></pre>
<p>To see why this work, consider two's complement as inverse + 1, <code>-n == ~n + 1</code></p>
<pre><code>n 0000100...000
inverse n 1111011...111
+ 1
two's comp 1111100...000
</code></pre>
<p>since you carry the one all the way through when adding one to get the two's complement.</p>
<p>If n were anything other than a power of two† then the result would be missing a bit because the two's complement would not have the highest bit set due to that carry.</p>
<p>† - or zero or a negative of a power of two ... as explained at the top.</p> |
7,559,608 | median of three values strategy | <p>What is the median of three strategy to select the pivot value in quick sort?</p>
<p>I am reading it on the web, but I couldn't figure it out what exactly it is? And also how it is better than the randomized quick sort.</p> | 7,560,859 | 8 | 1 | null | 2011-09-26 18:34:41.72 UTC | 20 | 2021-09-27 12:57:19.4 UTC | 2016-09-19 04:10:38.877 UTC | null | 77,764 | null | 226,161 | null | 1 | 36 | algorithm|sorting|quicksort | 113,102 | <p>The median of three has you look at the first, middle and last elements of the array, and choose the median of those three elements as the pivot.</p>
<p>To get the "full effect" of the median of three, it's also important to <em>sort</em> those three items, not just use the median as the pivot -- this doesn't affect what's chosen as the pivot in the current iteration, but can/will affect what's used as the pivot in the next recursive call, which helps to limit the bad behavior for a few initial orderings (one that turns out to be particularly bad in many cases is an array that's sorted, except for having the smallest element at the high end of the array (or largest element at the low end). For example:</p>
<p>Compared to picking the pivot randomly:</p>
<ol>
<li>It ensures that one common case (fully sorted data) remains optimal.</li>
<li>It's more difficult to manipulate into giving the worst case.</li>
<li>A PRNG is often relatively slow.</li>
</ol>
<p>That second point probably bears a bit more explanation. If you used the obvious (<code>rand()</code>) random number generator, it's fairly easy (for many cases, anyway) for somebody to arrange the elements so it'll continually choose poor pivots. This can be a serious concern for something like a web server that may be sorting data that's been entered by a potential attacker, who could mount a DoS attack by getting your server to waste a lot of time sorting the data. In a case like this, you <em>could</em> use a truly random seed, or you could include your own PRNG instead of using rand() -- or you use use Median of three, which also has the other advantages mentioned.</p>
<p>On the other hand, if you use a sufficiently random generator (e.g., a hardware generator or encryption in counter mode) it's probably <em>more</em> difficult to force a bad case than it is for a median of three selection. At the same time, achieving that level of randomness typically has quite a bit of overhead of its own, so unless you really expect to be attacked in this case, it's probably not worthwhile (and if you do, it's probably worth at least considering an alternative that guarantees O(N log N) worst case, such as a merge sort or heap sort.</p> |
7,625,421 | minimize app to system tray | <p>I have a Windows forms app powered by C# and Visual Studio 2010.</p>
<p>How can I minimize my app to system tray (not taskbar), then bring it back when doubled click in the system tray? any idea? also, how can I make some menu in the icon in system tray and when I right click it, it shows a menu like Login, Disconnect, Connect, something like that.
Also, are there any methods to show like a baloon popping up from the system tray?</p>
<p>PS: I already added a notifyIcon, but I do not know how to use it.</p> | 7,625,426 | 9 | 2 | null | 2011-10-02 08:52:13.633 UTC | 38 | 2021-10-17 01:54:34.4 UTC | 2017-10-16 14:14:51.457 UTC | null | 3,885,376 | null | 963,499 | null | 1 | 122 | c#|windows|winforms | 220,129 | <ul>
<li><a href="http://alperguc.blogspot.com/2008/11/c-system-tray-minimize-to-tray-with.html" rel="noreferrer">C# System Tray Minimize To Tray With NotifyIcon</a></li>
<li><a href="http://www.codeproject.com/KB/dialog/Minimize_To_Tray.aspx" rel="noreferrer">Minimize window to system tray</a></li>
</ul>
<blockquote>
<p>Handle the form’s Resize event. In this handler, you override the
basic functionality of the Resize event to make the form minimize to
the system tray and not to the taskbar. This can be done by doing the
following in your form’s Resize event handler: Check whether the
form’s WindowState property is set to FormWindowState.Minimized. If
yes, hide your form, enable the NotifyIcon object, and show the
balloon tip that shows some information. Once the WindowState becomes
FormWindowState.Normal, disable the NotifyIcon object by setting its
Visible property to false. Now, you want the window to reappear when
you double click on the NotifyIcon object in the taskbar. For this,
handle the NotifyIcon’s MouseDoubleClick event. Here, you show the
form using the Show() method.</p>
</blockquote>
<pre><code>private void frmMain_Resize(object sender, EventArgs e)
{
if (FormWindowState.Minimized == this.WindowState)
{
mynotifyicon.Visible = true;
mynotifyicon.ShowBalloonTip(500);
this.Hide();
}
else if (FormWindowState.Normal == this.WindowState)
{
mynotifyicon.Visible = false;
}
}
</code></pre> |
7,397,207 | JSON.NET Error Self referencing loop detected for type | <p>I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used</p>
<pre class="lang-cs prettyprint-override"><code>JsonConvert.SerializeObject
</code></pre>
<p>I got the following error:</p>
<blockquote>
<p>Error Self referencing loop detected for type System.data.entity occurs.</p>
</blockquote>
<p>How do I solve this problem?</p> | 18,223,985 | 26 | 4 | null | 2011-09-13 05:25:25.523 UTC | 147 | 2022-06-18 18:54:07.24 UTC | 2021-01-28 21:24:31.237 UTC | null | 6,270,590 | null | 867,153 | null | 1 | 588 | c#|json|serialization|json.net | 441,692 | <p>That was the best solution
<a href="https://docs.microsoft.com/en-us/archive/blogs/hongyes/loop-reference-handling-in-web-api" rel="noreferrer">https://docs.microsoft.com/en-us/archive/blogs/hongyes/loop-reference-handling-in-web-api</a></p>
<h1>Fix 1: Ignoring circular reference globally</h1>
<p><em>(I have chosen/tried this one, as have many others)</em></p>
<p>The json.net serializer has an option to ignore circular references. Put the following code in <code>WebApiConfig.cs</code> file:</p>
<pre><code> config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Ignore;
</code></pre>
<p>The simple fix will make serializer to ignore the reference which will cause a loop. However, it has limitations:</p>
<ul>
<li>The data loses the looping reference information</li>
<li>The fix only applies to JSON.net</li>
<li>The level of references can't be controlled if there is a deep reference chain</li>
</ul>
<p>If you want to use this fix in a non-api ASP.NET project, you can add the above line to <code>Global.asax.cs</code>, but first add:</p>
<pre><code>var config = GlobalConfiguration.Configuration;
</code></pre>
<p>If you want to use this in <strong>.Net Core</strong> project, you can change <code>Startup.cs</code> as:</p>
<pre><code> var mvc = services.AddMvc(options =>
{
...
})
.AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
</code></pre>
<h1>Fix 2: Preserving circular reference globally</h1>
<p>This second fix is similar to the first. Just change the code to:</p>
<pre><code>config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Serialize;
config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling
= Newtonsoft.Json.PreserveReferencesHandling.Objects;
</code></pre>
<p>The data shape will be changed after applying this setting.</p>
<pre><code>[
{
"$id":"1",
"Category":{
"$id":"2",
"Products":[
{
"$id":"3",
"Category":{
"$ref":"2"
},
"Id":2,
"Name":"Yogurt"
},
{
"$ref":"1"
}
],
"Id":1,
"Name":"Diary"
},
"Id":1,
"Name":"Whole Milk"
},
{
"$ref":"3"
}
]
</code></pre>
<p>The $id and $ref keeps the all the references and makes the object graph level flat, but the client code needs to know the shape change to consume the data and it only applies to JSON.NET serializer as well.</p>
<h1>Fix 3: Ignore and preserve reference attributes</h1>
<p>This fix is decorate attributes on model class to control the serialization behavior on model or property level. To ignore the property:</p>
<pre><code> public class Category
{
public int Id { get; set; }
public string Name { get; set; }
[JsonIgnore]
[IgnoreDataMember]
public virtual ICollection<Product> Products { get; set; }
}
</code></pre>
<p>JsonIgnore is for JSON.NET and IgnoreDataMember is for XmlDCSerializer.
To preserve reference:</p>
<pre><code> // Fix 3
[JsonObject(IsReference = true)]
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
// Fix 3
//[JsonIgnore]
//[IgnoreDataMember]
public virtual ICollection<Product> Products { get; set; }
}
[DataContract(IsReference = true)]
public class Product
{
[Key]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public virtual Category Category { get; set; }
}
</code></pre>
<p><code>JsonObject(IsReference = true)] </code>is for JSON.NET and <code>[DataContract(IsReference = true)]</code> is for XmlDCSerializer. Note that: after applying <code>DataContract</code> on class, you need to add <code>DataMember</code> to properties that you want to serialize.</p>
<p>The attributes can be applied on both json and xml serializer and gives more controls on model class.</p> |
14,110,721 | How to change Pandas dataframe index value? | <p>I have a <code>df</code>:</p>
<pre><code>>>> df
sales cash
STK_ID RPT_Date
000568 20120930 80.093 57.488
000596 20120930 32.585 26.177
000799 20120930 14.784 8.157
</code></pre>
<p>And want to change first row's index value from <code>('000568','20120930')</code> to <code>('000999','20121231')</code>. Final result will be:</p>
<pre><code>>>> df
sales cash
STK_ID RPT_Date
000999 20121231 80.093 57.488
000596 20120930 32.585 26.177
000799 20120930 14.784 8.157
</code></pre>
<p>How to achieve this?</p> | 14,110,955 | 1 | 0 | null | 2013-01-01 13:05:42.883 UTC | 3 | 2017-11-10 02:45:54.593 UTC | 2017-11-10 02:45:54.593 UTC | null | 7,579,547 | null | 1,072,888 | null | 1 | 18 | python|pandas | 49,053 | <p>With this setup:</p>
<pre><code>import pandas as pd
import io
text = '''\
STK_ID RPT_Date sales cash
000568 20120930 80.093 57.488
000596 20120930 32.585 26.177
000799 20120930 14.784 8.157
'''
df = pd.read_csv(io.BytesIO(text), delimiter = ' ',
converters = {0:str})
df.set_index(['STK_ID','RPT_Date'], inplace = True)
</code></pre>
<p>The index, <code>df.index</code> can be reassigned to a new <code>MultiIndex</code> like this:</p>
<pre><code>index = df.index
names = index.names
index = [('000999','20121231')] + df.index.tolist()[1:]
df.index = pd.MultiIndex.from_tuples(index, names = names)
print(df)
# sales cash
# STK_ID RPT_Date
# 000999 20121231 80.093 57.488
# 000596 20120930 32.585 26.177
# 000799 20120930 14.784 8.157
</code></pre>
<p>Or, the index could be made into columns, the values in the columns could be then reassigned, and then the columns returned to indices:</p>
<pre><code>df.reset_index(inplace = True)
df.ix[0, ['STK_ID', 'RPT_Date']] = ('000999','20121231')
df = df.set_index(['STK_ID','RPT_Date'])
print(df)
# sales cash
# STK_ID RPT_Date
# 000999 20121231 80.093 57.488
# 000596 20120930 32.585 26.177
# 000799 20120930 14.784 8.157
</code></pre>
<hr>
<p>Benchmarking with IPython <code>%timeit</code> suggests reassigning the index (the first method, above) is significantly faster than resetting the index, modifying column values, and then setting the index again (the second method, above):</p>
<pre><code>In [2]: %timeit reassign_index(df)
10000 loops, best of 3: 158 us per loop
In [3]: %timeit reassign_columns(df)
1000 loops, best of 3: 843 us per loop
</code></pre> |
13,914,317 | Assigning a null value to an int | <p>If the following code is possible:</p>
<pre><code>Integer a = null;
int b = a;
</code></pre>
<p>Does it mean that a function returning a possible <code>null</code> value for an integer is a bad practice?</p>
<p>Edit 1:
There are several different opinions in these answers. I am not enough confident to choose one or another.</p> | 13,914,344 | 10 | 3 | null | 2012-12-17 12:37:31.007 UTC | 2 | 2020-05-01 20:40:18.073 UTC | 2012-12-17 12:46:42.43 UTC | null | 324,853 | null | 324,853 | null | 1 | 24 | java | 61,312 | <p>That code will give a <code>NullPointerException</code> when you run it. It's basically equivalent to:</p>
<pre><code>Integer a = null;
int b = a.intValue();
</code></pre>
<p>... which makes it clearer that it will indeed fail.</p>
<p>You're not <em>really</em> assigning a null value to an <code>int</code> - you're trying and failing.</p>
<p>It's fine to use <code>null</code> as a value for an <code>Integer</code>; indeed often <code>Integer</code> is used instead of <code>int</code> precisely as a "nullable equivalent`.</p> |
14,015,319 | Where do I mark a lambda expression async? | <p>I've got this code:</p>
<pre><code>private async void ContextMenuForGroupRightTapped(object sender, RightTappedRoutedEventArgs args)
{
CheckBox ckbx = null;
if (sender is CheckBox)
{
ckbx = sender as CheckBox;
}
if (null == ckbx)
{
return;
}
string groupName = ckbx.Content.ToString();
var contextMenu = new PopupMenu();
// Add a command to edit the current Group
contextMenu.Commands.Add(new UICommand("Edit this Group", (contextMenuCmd) =>
{
Frame.Navigate(typeof(LocationGroupCreator), groupName);
}));
// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", (contextMenuCmd) =>
{
SQLiteUtils slu = new SQLiteUtils();
slu.DeleteGroupAsync(groupName); // this line raises Resharper's hackles, but appending await raises err msg. Where should the "async" be?
}));
// Show the context menu at the position the image was right-clicked
await contextMenu.ShowAsync(args.GetPosition(this));
}
</code></pre>
<p>...that Resharper's inspection complained about with, "<em>Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call</em>" (on the line with the comment).</p>
<p>And so, I prepended an "await" to it but, of course, I then need to add an "async" somewhere, too - but where?</p> | 14,015,355 | 3 | 2 | null | 2012-12-23 22:48:30.917 UTC | 19 | 2021-11-15 15:46:33.7 UTC | null | null | null | null | 875,317 | null | 1 | 281 | c#|lambda|resharper|windows-store-apps|async-await | 205,103 | <p>To mark a lambda async, simply prepend <code>async</code> before its argument list:</p>
<pre><code>// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
SQLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupName);
}));
</code></pre> |
13,979,961 | How do you force your Javascript event to run first, regardless of the order in which the events were added? | <p>I have Javascript that people are including in their page. In my Javascript I have a version of jQuery (1.8 for sake of easy reference) that is sectioned off into its own namespace, and referenced via a global variable (but not one of the two default vars of "$" or "jQuery"). This allows users to have jQuery in their page and have it not interfere with the stuff I'm doing internally in my functions.</p>
<p>So we have one page that has jQuery already (1.4), and everything works fine, except that the user and my code are both listening to "click" events on elements, and theirs is going first, so on the few events they do that return false, jQuery stops propagation and my event never gets triggered. I need my event to go first. The user is expecting my <code>onClick</code> functionality to still work.</p>
<p>Now I know that jQuery keeps its own order of events internally through the <code>_data()</code> object, and through this it is possible to unbind existing events, bind my event, then rebind the existing events, but that only applies to objects bound through that instance of jQuery. I'd rather not just blindly look for the jQuery object in hopes that the conflict was introduced by a user's own version of jQuery. After all what happens when a user binds the event not through jQuery? Trying to manipulate the existing jQuery object in the page isn't a good solution.</p>
<p>I know that, depending on browser, they are using <code>addEventListener</code>/<code>removeEventListener</code> or <code>attachEvent</code>/<code>detachEvent</code>. If only I could get a listing of the already added events, I could rebind them in the order I wanted, but I can't find out how. Looking through the DOM via Chrome inspect I don't see <code>onclick</code> bound anywhere (not on the object, not on window or document either).</p>
<p>I'm having the darndest time trying to figure out just exactly where jQuery binds its listening. To be able to control the order of its own events, jQuery must blanketly listen somewhere and then fire off its own functions right? If I could figure out where that's done I might get some insight into how to ensure my event is always first. Or maybe there's some Javascript API I haven't been able to find on Google.</p>
<p>Any suggestions?</p> | 14,071,760 | 7 | 7 | null | 2012-12-20 20:26:56.5 UTC | 6 | 2021-06-05 09:34:49.78 UTC | 2020-11-16 23:17:08.33 UTC | null | 4,370,109 | null | 1,615,039 | null | 1 | 30 | javascript|jquery|dom-events | 37,028 | <p>As Bergi and Chris Heald said in the comments, it turns out there's no way to get at the existing events from the DOM, and no method to insert events "first". They are fired in the order they were inserted by design, and hidden by design. As a few posters mentioned you have access to the ones added through the same instance of jQuery that you're using via jQuery's data, but that's it.</p>
<p>There is one other case where you can run before an event that was bound before your code ran, and that's if they used the "onclick" HTML attribute. In that case you can write a wrapper function, as nothingisnecessary pointed out in a rather over-the-top toned comment below. While this wouldn't help in the instance of the original question I asked, and it's now <em>very</em> rare for events to be bound this way (most people and frameworks use addEvent or attachEventListener underneath now), it is one scenario in which you can solve the issue of "running first", and since a lot of people visit this question looking for answers now, I thought I'd make sure the answer is complete.</p> |
14,243,397 | What are git's merge strategies? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/366860/when-would-you-use-the-different-git-merge-strategies">When would you use the different git merge strategies?</a> </p>
</blockquote>
<p>When git merges files I'm working on, I see:</p>
<pre><code>Merge made by the 'recursive' strategy
</code></pre>
<p>What exactly is the recursive strategy? What other strategies are there (if any)? And what would be the benefit of using one over the other? Do different strategies have different performances? Or could two different strategies result in different merge results?</p> | 14,243,441 | 1 | 5 | null | 2013-01-09 17:53:01.483 UTC | 8 | 2013-01-09 17:55:12.69 UTC | 2017-05-23 11:53:55.527 UTC | null | -1 | null | 732,539 | null | 1 | 55 | git | 38,715 | <p>From <code>git help merge</code>:</p>
<pre><code> The merge mechanism (git-merge and git-pull commands) allows the
backend merge strategies to be chosen with -s option. Some strategies
can also take their own options, which can be passed by giving
-X<option> arguments to git-merge and/or git-pull.
resolve
This can only resolve two heads (i.e. the current branch and
another branch you pulled from) using a 3-way merge algorithm. It
tries to carefully detect criss-cross merge ambiguities and is
considered generally safe and fast.
recursive
This can only resolve two heads using a 3-way merge algorithm. When
there is more than one common ancestor that can be used for 3-way
merge, it creates a merged tree of the common ancestors and uses
that as the reference tree for the 3-way merge. This has been
reported to result in fewer merge conflicts without causing
mis-merges by tests done on actual merge commits taken from Linux
2.6 kernel development history. Additionally this can detect and
handle merges involving renames. This is the default merge strategy
when pulling or merging one branch.
The recursive strategy can take the following options:
ours
This option forces conflicting hunks to be auto-resolved
cleanly by favoring our version. Changes from the other tree
that do not conflict with our side are reflected to the merge
result.
This should not be confused with the ours merge strategy, which
does not even look at what the other tree contains at all. It
discards everything the other tree did, declaring our history
contains all that happened in it.
theirs
This is opposite of ours.
subtree[=path]
This option is a more advanced form of subtree strategy, where
the strategy makes a guess on how two trees must be shifted to
match with each other when merging. Instead, the specified path
is prefixed (or stripped from the beginning) to make the shape
of two trees to match.
octopus
This resolves cases with more than two heads, but refuses to do a
complex merge that needs manual resolution. It is primarily meant
to be used for bundling topic branch heads together. This is the
default merge strategy when pulling or merging more than one
branch.
ours
This resolves any number of heads, but the resulting tree of the
merge is always that of the current branch head, effectively
ignoring all changes from all other branches. It is meant to be
used to supersede old development history of side branches. Note
that this is different from the -Xours option to the recursive
merge strategy.
subtree
This is a modified recursive strategy. When merging trees A and B,
if B corresponds to a subtree of A, B is first adjusted to match
the tree structure of A, instead of reading the trees at the same
level. This adjustment is also done to the common ancestor tree.
</code></pre> |
13,864,077 | How to force an exception while debugging in Visual Studio? | <p>I am running my application in debug mode, and I would like to manually throw an exception (i.e. not from within the code). Is there any way to do this?</p>
<p>Of course, running <code>throw new Exception("My forced exception");</code> in the Command or Immediate window doesn't work.</p>
<p>EDIT: I want the exception to be caught by the try-catch statement that surrounds the code I'm debugging.</p> | 13,864,080 | 4 | 2 | null | 2012-12-13 16:23:07.63 UTC | 4 | 2018-02-21 15:53:06.8 UTC | 2012-12-19 15:39:23.72 UTC | null | 370,671 | null | 370,671 | null | 1 | 59 | c#|.net|visual-studio | 31,518 | <p>One possible way is to break on a line and manually change a nullable variable in the code path to <code>null</code> just before an operation on it occurs. This will cause a <code>NullReferenceException</code> to be thrown.</p> |
30,068,298 | Git : fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists | <p>I am getting this error - </p>
<pre><code>D:\Projects\wamp\www\REPO [master]> git pull origin master
Warning: Permanently added 'github.com,192.30.252.128' (RSA) to the list of known hosts.
ERROR: Repository not found.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
</code></pre>
<p>The output of <strong>git remote -v</strong></p>
<pre><code>D:\Projects\wamp\www\REPO [master]> git remote -v
origin [email protected]:username/repo.git (fetch)
origin [email protected]:username/repo.git (push)
</code></pre>
<p>Final message of <strong>ssh -Tv [email protected]</strong> command - </p>
<pre><code>Hi [My Username]! You've successfully authenticated, but GitHub does not provide shell access.
</code></pre>
<p>How can I solve it?</p> | 30,069,271 | 19 | 11 | null | 2015-05-06 05:33:41.65 UTC | 27 | 2021-11-16 15:56:46.297 UTC | 2015-05-06 05:46:14.07 UTC | null | 1,949,676 | null | 1,949,676 | null | 1 | 90 | git|github | 394,367 | <p>I asked <a href="https://chat.stackoverflow.com/rooms/77061/discussion-between-napster-and-vonc">in the discussion</a>:</p>
<blockquote>
<blockquote>
<p>does <code>ssh -T [email protected]</code> ouput the same username (<code>in Hi [My Username]!</code>) as in the one used for the ssh url of your repo (<code>[email protected]:username/repo.git</code>)?</p>
</blockquote>
<p>Sorry It not showing same name</p>
</blockquote>
<p>That means somehow the credentials have changed.</p>
<p>One solution would be to at least copy <code>%HOME%\.ssh\id_rsa.pub</code> in <a href="https://help.github.com/articles/generating-ssh-keys/#step-4-add-your-ssh-key-to-your-account" rel="noreferrer">the SSH keys section of the right GitHub account</a></p>
<p>The OP adds:</p>
<blockquote>
<blockquote>
<p>I am working on private repo. So In [email protected]:username/repo.git,</p>
</blockquote>
</blockquote>
<p>I replied:</p>
<blockquote>
<p>If you were able to clone/push to that repo whose username is not your own GitHub account, that must be because you had your previous public ssh key added as a contributor to that repo by the repo's owner.</p>
<p>What next is to ask that same repo owner to add your current public ssh key <code>%HOME%\.ssh\id_rsa.pub</code> to the repo contributor list.<br />
So check with the owner that you (meaning your public ssh key) are declared as a contributor.</p>
</blockquote> |
9,554,544 | Python, running command line tools in parallel | <p>I am using Python as a script language to do some data processing and call command-line tools for number crunching. I wish to run command-line tools in parallel since they are independent with each other. When one command-line tool is finished, I can collect its results from the output file. So I also need some synchronization mechanism to notify my main Python program that one task is finished so that the result could be parsed into my main program. </p>
<p>Currently, I use <code>os.system()</code>, which works fine for one-thread, but cannot be parallelized. </p>
<p>Thanks!</p> | 9,555,046 | 2 | 1 | null | 2012-03-04 11:35:47.867 UTC | 9 | 2019-01-08 09:46:08.837 UTC | 2012-03-04 15:27:21.397 UTC | null | 42,973 | null | 183,828 | null | 1 | 17 | python|shell|command-line|parallel-processing | 29,355 | <p>Use the <code>Pool</code> object from the <code>multiprocessing</code> module. You can then use e.g. <code>Pool.map()</code> to do parallel processing. An example would be my markphotos script (see below), where a function is called multiple times in parallel to each process a picture.</p>
<pre><code>#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Adds my copyright notice to photos.
#
# Author: R.F. Smith <[email protected]>
# $Date: 2012-10-28 17:00:24 +0100 $
#
# To the extent possible under law, Roland Smith has waived all copyright and
# related or neighboring rights to markphotos.py. This work is published from
# the Netherlands. See http://creativecommons.org/publicdomain/zero/1.0/
import sys
import subprocess
from multiprocessing import Pool, Lock
from os import utime, devnull
import os.path
from time import mktime
globallock = Lock()
def processfile(name):
"""Adds copyright notice to the file.
Arguments:
name -- file to modify
"""
args = ['exiftool', '-CreateDate', name]
createdate = subprocess.check_output(args)
fields = createdate.split(":") #pylint: disable=E1103
year = int(fields[1])
cr = "R.F. Smith <[email protected]> http://rsmith.home.xs4all.nl/"
cmt = "Copyright © {} {}".format(year, cr)
args = ['exiftool', '-Copyright="Copyright (C) {} {}"'.format(year, cr),
'-Comment="{}"'.format(cmt), '-overwrite_original', '-q', name]
rv = subprocess.call(args)
modtime = int(mktime((year, int(fields[2]), int(fields[3][:2]),
int(fields[3][3:]), int(fields[4]), int(fields[5]),
0,0,-1)))
utime(name, (modtime, modtime))
globallock.acquire()
if rv == 0:
print "File '{}' processed.".format(name)
else:
print "Error when processing file '{}'".format(name)
globallock.release()
def checkfor(args):
"""Make sure that a program necessary for using this script is
available.
Arguments:
args -- list of commands to pass to subprocess.call.
"""
if isinstance(args, str):
args = args.split()
try:
with open(devnull, 'w') as f:
subprocess.call(args, stderr=subprocess.STDOUT, stdout=f)
except:
print "Required program '{}' not found! exiting.".format(args[0])
sys.exit(1)
def main(argv):
"""Main program.
Arguments:
argv -- command line arguments
"""
if len(argv) == 1:
binary = os.path.basename(argv[0])
print "Usage: {} [file ...]".format(binary)
sys.exit(0)
checkfor(['exiftool', '-ver'])
p = Pool()
p.map(processfile, argv[1:])
p.close()
if __name__ == '__main__':
main(sys.argv)
</code></pre> |
24,585,261 | nvm keeps "forgetting" node in new terminal session | <h2>Upon using a new terminal session in OS X, <code>nvm</code> forgets the node version and defaults to nothing:</h2>
<p><code>$ nvm ls</code>:</p>
<pre><code> .nvm
v0.11.12
v0.11.13
</code></pre>
<p>I have to keep hitting <code>nvm use v.0.11.13</code> in every session:</p>
<pre><code> .nvm
v0.11.12
-> v0.11.13
</code></pre>
<p>I've tried both the <code>brew</code> install, as well as the official installation script.</p>
<p>My <strong><code>.profile</code></strong> for the brew version:</p>
<pre><code>#nvm
export NVM_DIR=~/.nvm
source $(brew --prefix nvm)/nvm.sh
</code></pre>
<p>And for the install.sh script:</p>
<p><code>$ curl https://raw.githubusercontent.com/creationix/nvm/v0.10.0/install.sh | bash</code></p>
<pre><code>#nvm
export NVM_DIR="/Users/farhad/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm
</code></pre>
<h2>Any clue to what I'm doing wrong?</h2> | 24,587,177 | 25 | 2 | null | 2014-07-05 10:05:25.937 UTC | 151 | 2022-07-26 22:37:50.133 UTC | 2015-11-09 13:41:07.28 UTC | null | 735,926 | null | 2,491,198 | null | 1 | 723 | node.js|macos|npm|homebrew|nvm | 213,402 | <p>Try <code>nvm alias default</code>. For example:</p>
<p><code>$ nvm alias default 0.12.7</code></p>
<p>This sets the default node version in your shell. Then verify that the change persists by closing the shell window, opening a new one, then:
<code>node --version</code> </p> |
623,518 | msysgit on windows -- what should I be aware of, if any? | <p>This is related to another <a href="https://stackoverflow.com/questions/623018/git-without-bash-cygwin">question I asked</a> recently.</p>
<p>When installing msysgit, the installer presents 3 options related to system path:</p>
<ol>
<li><p>Never change windows environment. With this option, you have to use the "bash" shell to work with git.</p></li>
<li><p>Add the git\bin directory to the PATH environment variable, but without overriding some builtin windows tools. Fellow stackoverflow-ian Gabe Moothart <a href="https://stackoverflow.com/questions/623018/git-without-bash-cygwin/623169#623169">told me in a comment</a> that this option will make some git operations fail! What are these operations? Should I worry about them?</p></li>
<li><p>Same as 2 but override some default system tools. What are these tools? What parts of windows depend on them? and will this hurt in practice?</p></li>
</ol>
<p>Another issue has come to my mind, unrelated to the system PATH.</p>
<p>What if I have symbolic links and hard links inside my project directory? Does git know how to deal with these? or, will it suffer from infinite recursion, if say, the directory structure was such that some folder was actually a symbolic link to one of its parents?</p> | 647,636 | 5 | 0 | null | 2009-03-08 12:46:06.697 UTC | 21 | 2012-04-21 05:08:15.79 UTC | 2017-05-23 11:54:22.647 UTC | hasen j | -1 | hasen j | 35,364 | null | 1 | 41 | windows|git|version-control|msysgit | 21,957 | <p>You get <code>bash</code> regardless of which option you pick, the latter options just add methods for using Git outside it.</p>
<p>For the latter options, <strong>msysgit</strong> adds Windows builds of common Linux utilities to <strong><code>PATH</code></strong>. This includes <strong><code>find</code></strong>, <strong><code>kill</code></strong> and <strong><code>sort</code></strong>, as well as <strong><code>cp</code></strong>, <strong><code>ls</code></strong>, <strong><code>rm</code></strong>, and about 20-30 others.</p>
<p>The problem with the first 3 (and similar) is that they exist in both OSs and function differently in each.</p>
<p>Not a huge ordeal if you know which one you'll be using, but any applications developed expecting one and getting the other will surely throw a fit.</p>
<hr>
<p>To prevent the conflict, while still having Git work as expected, you can create a simple batch script that adjusts <code>PATH</code> only for the session. (e.g., <code>readygit.bat</code>)</p>
<pre><code>@echo off
setlocal
set PATH=C:\Git\bin;%PATH%
cmd
</code></pre>
<p>Adjust <code>C:\Git\bin</code> accordingly. But, just run this and use Git within the <code>cmd</code>.</p>
<p>With this, you can use install option 3 and safely remove <code>C:\Git\bin</code> from your system's <code>PATH</code>, removing any confusion for Windows apps without confusing Git.</p>
<p>I currently use a similar script with <a href="https://sourceforge.net/projects/gnuwin32/" rel="noreferrer"><strong>GnuWin</strong></a> apps, including <strong><code>find</code></strong>.</p> |
44,961 | What are the primary differences between Haskell and F#? | <p>I've searched on the Internet for comparisons between <a href="http://en.wikipedia.org/wiki/F_Sharp_%28programming_language%29" rel="noreferrer">F#</a> and <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29" rel="noreferrer">Haskell</a> but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other?</p> | 44,995 | 5 | 2 | null | 2008-09-04 23:24:51.883 UTC | 42 | 2014-05-21 21:22:55.553 UTC | 2014-05-21 21:22:55.553 UTC | jolson | 2,963,652 | kronoz | 3,394 | null | 1 | 135 | haskell|f#|functional-programming|language-comparisons | 31,826 | <p>Haskell is a "pure" functional language, where as F# has aspects of both imperative/OO and functional languages. Haskell also has lazy evaluation, which is fairly rare amongst functional languages.</p>
<p>What do these things mean? A pure functional language, means there are no side effects (or changes in shared state, when a function is called) which means that you are guaranteed that if you call f(x), nothing else happens besides returning a value from the function, such as console output, database output, changes to global or static variables.. and although Haskell can have non pure functions (through monads), it must be 'explicitly' implied through declaration.</p>
<p>Pure functional languages and 'No side effect' programming has gained popularity recently as it lends itself well to multi core concurrency, as it is much harder to get wrong with no shared state, rather than myriad locks & semaphores.</p>
<p>Lazy evaluation is where a function is NOT evaluated until it is absolutely necessary required. meaning that many operation can be avoided when not necessary. Think of this in a basic C# if clause such as this:</p>
<pre><code>if(IsSomethingTrue() && AnotherThingTrue())
{
do something;
}
</code></pre>
<p>If <code>IsSomethingTrue()</code> is false then <code>AnotherThingTrue()</code> method is never evaluated.</p>
<p>While Haskell is an amazing language, the major benefit of F# (for the time being), is that it sits on top of the CLR. This lends it self to polyglot programming. One day, you may write your web UI in ASP.net MVC, your business logic in C#, your core algorithms in F# and your unit tests in Ironruby.... All amongst the the .Net framework.</p>
<p>Listen to the Software Engineering radio with Simon Peyton Jones for more info on Haskell: <a href="http://www.se-radio.net/2008/08/episode-108-simon-peyton-jones-on-functional-programming-and-haskell/" rel="noreferrer">Episode 108: Simon Peyton Jones on Functional Programming and Haskell</a></p> |
459,083 | How do you run your own code alongside Tkinter's event loop? | <p>My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move <em>every moment</em>.</p>
<p>Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing <code>root.mainloop()</code> runs, runs, and keeps running, and the only thing it runs is the event handlers.</p>
<p>Is there a way to have his code run alongside the mainloop (without multithreading, it's confusing and this should be kept simple), and if so, what is it?</p>
<p>Right now, he came up with an ugly hack, tying his <code>move()</code> function to <code><b1-motion></code>, so that as long as he holds the button down and wiggles the mouse, it works. But there's got to be a better way.</p> | 459,131 | 5 | 0 | null | 2009-01-19 20:40:39.66 UTC | 67 | 2019-04-02 03:56:08.023 UTC | 2012-09-16 15:55:06.503 UTC | null | 1,288 | null | 56,805 | null | 1 | 151 | python|events|tkinter | 199,857 | <p>Use the <code>after</code> method on the <code>Tk</code> object:</p>
<pre><code>from tkinter import *
root = Tk()
def task():
print("hello")
root.after(2000, task) # reschedule event in 2 seconds
root.after(2000, task)
root.mainloop()
</code></pre>
<p>Here's the declaration and documentation for the <code>after</code> method:</p>
<pre><code>def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
</code></pre> |
833,490 | Gridview row editing - dynamic binding to a DropDownList | <p>I'm trying to get an ASP.NET 3.5 GridView to show a selected value as string when being displayed, and to show a DropDownList to allow me to pick a value from a given list of options when being edited. Seems simple enough?</p>
<p>My gridview looks like this (simplified):</p>
<pre><code><asp:GridView ID="grvSecondaryLocations" runat="server"
DataKeyNames="ID" OnInit="grvSecondaryLocations_Init"
OnRowCommand="grvSecondaryLocations_RowCommand"
OnRowCancelingEdit="grvSecondaryLocations_RowCancelingEdit"
OnRowDeleting="grvSecondaryLocations_RowDeleting"
OnRowEditing="grvSecondaryLocations_RowEditing"
OnRowUpdating="grvSecondaryLocations_RowUpdating" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblPbxTypeCaption" runat="server"
Text='<%# Eval("PBXTypeCaptionValue") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="ddlPBXTypeNS" runat="server"
Width="200px"
DataTextField="CaptionValue"
DataValueField="OID" />
</EditItemTemplate>
</asp:TemplateField>
</asp:GridView>
</code></pre>
<p>The grid gets displayed OK when not in editing mode - the selected PBX type shows its value in the asp:Label control. No surprise there.</p>
<p>I load the list of values for the DropDownList into a local member called <code>_pbxTypes</code> in the <code>OnLoad</code> event of the form. I verified this - it works, the values are there.</p>
<p>Now my challenge is: when the grid goes into editing mode for a particular row, I need to bind the list of PBX's stored in <code>_pbxTypes</code>. </p>
<p>Simple enough, I thought - just grab the drop down list object in the <code>RowEditing</code> event and attach the list:</p>
<pre><code>protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
grvSecondaryLocations.EditIndex = e.NewEditIndex;
GridViewRow editingRow = grvSecondaryLocations.Rows[e.NewEditIndex];
DropDownList ddlPbx = (editingRow.FindControl("ddlPBXTypeNS") as DropDownList);
if (ddlPbx != null)
{
ddlPbx.DataSource = _pbxTypes;
ddlPbx.DataBind();
}
.... (more stuff)
}
</code></pre>
<p>Trouble is - I never get anything back from the <code>FindControl</code> call - seems like the <code>ddlPBXTypeNS</code> doesn't exist (or can't be found).</p>
<p>What am I missing?? Must be something really stupid.... but so far, all my Googling, reading up on GridView controls, and asking buddies hasn't helped.</p>
<p>Who can spot the missing link? ;-)</p> | 833,555 | 6 | 0 | null | 2009-05-07 08:34:19.653 UTC | 8 | 2013-02-27 18:58:07.767 UTC | 2012-08-11 07:54:22.203 UTC | null | 13,302 | null | 13,302 | null | 1 | 23 | asp.net|gridview|drop-down-menu|dynamic-binding | 149,484 | <p>Quite easy... You're doing it wrong, because by that event the control is not there:</p>
<pre><code>protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
// Here you will get the Control you need like:
DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
}
}
</code></pre>
<p>That is, it will only be valid for a <code>DataRow</code> (the actually row with data), and if it's in <strong>Edit</strong> mode... because you only edit one row at a time. The <code>e.Row.FindControl("ddlPBXTypeNS")</code> will only find the control that you want.</p> |
110,477 | Anyone know of any (free / open source) VI integration for Visual Studio? | <p>vi is for cool kids.</p> | 110,484 | 6 | 2 | null | 2008-09-21 07:27:07.01 UTC | 25 | 2010-08-31 18:17:34.693 UTC | 2008-09-27 22:17:22.877 UTC | sontek | 17,176 | Haoest | 10,088 | null | 1 | 38 | visual-studio|vim|add-in|vi | 6,825 | <ol>
<li><a href="http://www.viemu.com/" rel="noreferrer">ViEmu</a> - Not Free but great Vim emulation.</li>
<li><a href="http://www.vim.org/scripts/script.php?script_id=864" rel="noreferrer">Visual_Studio.vim</a> - Allows you to manage visual studio from Vim.</li>
<li><a href="http://vim.wikia.com/wiki/Calling_gvim_from_MS_Visual_Studio" rel="noreferrer">Using GVim as the Visual Studio Editor</a></li>
</ol> |
1,176,986 | High Frequency Trading | <p>Over the last couple of weeks i have come across lots of articles about high frequency trading. They all talk about how important computers and software is to this but since they are all written from a financial point of view there is no detail about what does software do?</p>
<p>Can anyone explain from a programmers point of view what is high frequency trading? and why is computer/software so important in this field?</p> | 1,279,831 | 6 | 6 | null | 2009-07-24 11:05:57.677 UTC | 67 | 2012-10-26 06:48:30.903 UTC | 2010-06-01 18:42:44.597 UTC | null | 349,990 | null | 89,904 | null | 1 | 62 | finance|hft | 19,480 | <p>To expand on what Paul said:</p>
<p>The server executing HFT or UHFT are almost always collocated in the exchange's data center. This minimizes latency and also allows the algos use Flash orders (which might be banned soon) to get first look at order flow before the order is broadcast into the market. many algo's will evaluate an order in just a few milliseconds and this is a game where milliseconds matter. Trading groups have been known to pull out all the stops including hiring kernel developers to build custom OS components to better optimize the time between when an order hits the NIC and when the resulting action is taken.</p>
<p>There are a couple of large buckets of strategies which are being commonly used today:</p>
<p>The first is trading in front of large block orders. To use Paul's example of buying a million shares of IBM, HFT algo's will be looking for buying pressure. A firms computers at different exchanges and dark pools will need to share information since the order will be divided up and typically executed across multiple exchanges and dark pools. An HFT algo will use statistical/machine learned models to predict the size of the buying pressure and if it determines that there is enough it will also accumulate shares from across markets and attempt to sell them for a slightly higher price.</p>
<p>The second is liquidity rebate trading where exchanges will pay market participants to add liquidity. (<a href="http://directedge.com/Default.aspx?AspxAutoDetectCookieSupport=1" rel="noreferrer">See Direct Edge Pricing</a>) Shares that are bought or sold may only be held for a very short period of time. The goal is just to collect the rebate and break even on everything else.</p>
<p>In both of these strategy types the idea is to make pennies (or fractions) on a trade and do this many times per day. </p>
<p>As you may have noticed there are a lot of HFT jobs available and thus the trades are becoming more crowded. I see this as kind of like stat arb from the early 2000s and eventually the trade will not be very profitable since so many players are trying to make it.</p>
<p>As for why software is important: milliseconds matter. Latency is super important and the code needs to be tight, fast and rock solid stable. Having an algo crash and being caught with shares when the market moves against you is not very profitable. Engineering for these requirements is necessarily different and requires different skills. Crunching the full order book in real time does requires some horsepower and good algorithms. It is fun and interesting though.</p> |
1,041,597 | How to run a script file remotely using SSH | <p>I want to run a script remotely. But the system doesn't recognize the path. It complains that "no such file or directory". Am I using it right?</p>
<pre><code>ssh kev@server1 `./test/foo.sh`
</code></pre> | 1,041,606 | 6 | 2 | null | 2009-06-25 00:18:17.593 UTC | 27 | 2019-04-15 01:25:30.91 UTC | 2019-04-15 01:21:31.08 UTC | null | 63,550 | null | 67,129 | null | 1 | 70 | scripting|ssh | 185,061 | <p>Backticks will run the command on the local shell and put the results on the command line. What you're saying is 'execute ./test/foo.sh and then pass the output as if I'd typed it on the commandline here'.</p>
<p>Try the following command, and make sure that thats the path from your home directory on the remote computer to your script.</p>
<pre><code>ssh kev@server1 './test/foo.sh'
</code></pre>
<p>Also, the script has to be on the remote computer. What this does is essentially log you into the remote computer with the listed command as your shell. You can't run a local script on a remote computer like this (unless theres some fun trick I don't know).</p> |
31,049,544 | How to set first N elements of array to zero? | <p>I have a long array:</p>
<pre><code>x= ([2, 5, 4, 7, ...])
</code></pre>
<p>for which I need to set the first <code>N</code> elements to <code>0</code>. So for <code>N = 2</code>, the desired output would be:</p>
<pre><code>x = ([0, 0, 4, 7, ...])
</code></pre>
<p>Is there an easy way to do this in Python? Some <code>numpy</code> function?</p> | 31,049,595 | 2 | 3 | null | 2015-06-25 11:50:14.323 UTC | 3 | 2018-09-27 23:01:30.683 UTC | 2015-06-25 11:54:10.393 UTC | null | 3,001,761 | null | 3,059,201 | null | 1 | 19 | python|arrays|numpy | 72,228 | <p>Pure python:</p>
<pre><code>x[:n] = [0] * n
</code></pre>
<p>with numpy:</p>
<pre><code>y = numpy.array(x)
y[:n] = 0
</code></pre>
<p>also note that <code>x[:n] = 0</code> does <strong>not</strong> work if <code>x</code> is a python list (instead of a numpy array).</p>
<p>It is also a bad idea to use <code>[{some object here}] * n</code> for anything mutable, because the list will not contain n different objects but n references to the same object:</p>
<pre><code>>>> a = [[],[],[],[]]
>>> a[0:2] = [["a"]] * 2
>>> a
[['a'], ['a'], [], []]
>>> a[0].append("b")
>>> a
[['a', 'b'], ['a', 'b'], [], []]
</code></pre> |
56,139,760 | Why is the finalize() method deprecated in Java 9? | <p>(This question is different from <a href="https://stackoverflow.com/questions/158174/why-would-you-ever-implement-finalize">Why would you ever implement finalize()?</a> This question is about deprecation from the Java platform, and the other question is about whether one should use this mechanism in applications.)</p>
<p>Why is the <code>finalize()</code> method deprecated in Java 9?</p>
<p>Yes it could be used in wrong way (like save an object from garbage collecting [only one time though] or try to close some native resources within it [it's better than don't close at all though]) as well as many other methods could be used wrongly.</p>
<p>So is <code>finalize()</code> really so dangerous or absolutely useless that it's necessary to kick it out of Java?</p> | 56,454,348 | 1 | 15 | null | 2019-05-14 23:08:58.34 UTC | 10 | 2022-04-04 22:48:43.287 UTC | 2021-09-17 05:38:45.437 UTC | null | 1,441,122 | null | 10,894,456 | null | 1 | 29 | java|java-9|finalizer|finalize|finalization | 16,116 | <p>Although the question was asking about the <code>Object.finalize</code> method, the subject really is about the <em>finalization</em> mechanism as a whole. This mechanism includes not only the surface API <code>Object.finalize</code>, but it also includes specifications of the programming language about the life cycle of objects, and practical impact on garbage collector implementations in JVMs.</p>
<p>Much has been written about why finalization is difficult to use from the application's point of view. See the questions <a href="https://stackoverflow.com/questions/158174/why-would-you-ever-implement-finalize">Why would you ever implement finalize()?</a> and <a href="https://stackoverflow.com/questions/52879761/should-java-9-cleaner-be-preferred-to-finalization">Should Java 9 Cleaner be preferred to finalization?</a> and their answers. See also <em>Effective Java, 3rd edition</em> by Joshua Bloch, Item 8.</p>
<p>Briefly, some points about the problems associated with using finalizers are:</p>
<ul>
<li><p>they are notoriously difficult to program correctly</p>
</li>
<li><p>in particular, they can be run unexpectedly when an object
becomes unreachable unexpectedly (but correctly); for example,
see <a href="https://stackoverflow.com/a/26645534/1441122">my answer to this question</a></p>
</li>
<li><p>finalization can easily break subclass/superclass relationships</p>
</li>
<li><p>there is no ordering among finalizers</p>
</li>
<li><p>a given object's <code>finalize</code> method is invoked at most once by the JVM, even if that object is "resurrected"</p>
</li>
<li><p>there are no guarantees about timeliness of finalization or
even that it will run at all</p>
</li>
<li><p>there is no explicit registration or deregistration mechanism</p>
</li>
</ul>
<p>The above are difficulties with the use of finalization. Anyone who is considering using finalization should reconsider, given the above list of issues. But are these issues sufficient to deprecate finalization in the Java platform? There are several additional reasons explained in the sections below.</p>
<p><strong>Finalization Potentially Makes Systems Fragile</strong></p>
<p>Even if you write an object that uses finalization correctly, it can cause problems when your object is integrated into a larger system. Even if you don't use finalization at all, being integrated into a larger system, some parts of which use finalization, can result in problems. The general issue is that worker threads that create garbage need to be in balance with the garbage collector. If the garbage collector falls behind, at least some collectors can "stop the world" and do a full collection to catch up. Finalization complicates this interaction. Even if the garbage collector is keeping up with application threads, finalization can introduce bottlenecks and slow down the system, or it can cause delays in freeing resources that result in exhaustion of those resources. This is a <em>systems</em> problem. Even if the actual code that uses finalization is correct, problems can still occur in correctly programmed systems.</p>
<p>(Edit 2021-09-16: <a href="https://stackoverflow.com/q/64264807/1441122">this question</a> describes a problem where a system works fine under low load but fails under high load, likely because the relative rate of allocation outstrips the rate of finalization under high load.)</p>
<p><strong>Finalization Contributes to Security Issues</strong></p>
<p>The <em>SEI CERT Oracle Coding Standard for Java</em> has a rule <a href="https://wiki.sei.cmu.edu/confluence/display/java/MET12-J.+Do+not+use+finalizers" rel="nofollow noreferrer">MET12-J: Do not use finalizers</a>. (Note, this is a site about secure coding.) In particular, it says</p>
<blockquote>
<p>Improper use of finalizers can result in resurrection of garbage-collection-ready objects and result in denial-of-service vulnerabilities.</p>
</blockquote>
<p>Oracle's <a href="https://www.oracle.com/technetwork/java/seccodeguide-139067.html" rel="nofollow noreferrer"><em>Secure Coding Guidelines for Java SE</em></a> is more explicit about potential security issues that can arise using finalization. In this case it is not a problem with code that uses finalization. Instead, finalization can be used <em>by an attacker</em> to attack sensitive code that hasn't properly defended itself. In particular, <em>Guideline 7-3 / OBJECT-3</em> states in part,</p>
<blockquote>
<p>Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected <code>finalize</code> method in a subclass and attempts to create a new instance of that subclass. This attempt fails ... but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious <code>finalize</code> method implementation is invoked, giving the attacker access to <code>this</code>, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it....</p>
</blockquote>
<p>Thus, the presence of the finalization mechanism in the platform imposes a burden on programmers who are trying to write high assurance code.</p>
<p><strong>Finalization Adds Complexity to Specifications</strong></p>
<p>The Java Platform is defined by several specifications, including specifications for the language, the virtual machine, and the class library APIs. Impact of finalization is spread thinly across all of these, but it repeatedly makes its presence felt. For example, finalization has a very subtle interaction with object creation (which is already complicated enough). Finalization also has appeared Java's public APIs, meaning that evolution of those APIs has (up to now) been required to remain compatible with previously specified behaviors. Evolving these specifications is made more costly the presence of finalization.</p>
<p><strong>Finalization Adds Complexity to Implementations</strong></p>
<p>This is mainly about garbage collectors. There are several garbage collection implementations, and all are required to pay the cost of implementing finalization. The implementations are quite good at minimizing the runtime overhead if finalization isn't used. However, the implementation still needs to be there, and it needs to be correct and well tested. This is an ongoing development and maintenance burden.</p>
<p><strong>Summary</strong></p>
<p>We've seen elsewhere that it's not recommended for programmers to use finalization. However, if something is not useful, it doesn't necessarily follow that it should be deprecated. The points above illustrate the fact that even if finalization isn't used, the mere presence of the mechanism in the platform imposes ongoing specification, development, and maintenance costs. Given the lack of usefulness of the mechanism and the costs it imposes, it makes sense to deprecate it. Eventually, getting rid of finalization will benefit everyone.</p>
<p>As of this writing (2019-06-04) there is no concrete plan to remove finalization from Java. However, it is certainly the intent to do so. We've deprecated the <code>Object.finalize</code> method, but have not marked it for removal. This is a formal recommendation that programmers stop using this mechanism. It's been known informally that finalization shouldn't be used, but of course it's necessary to take a formal step. In addition, certain <code>finalize</code> methods in library classes (for example, <a href="https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/zip/ZipFile.html#finalize()" rel="nofollow noreferrer"><code>ZipFile.finalize</code></a>) have been deprecated "for removal" which means that the finalization behavior of these classes may be removed from a future release. Eventually, we hope to disable finalization in the JVM (perhaps first optionally, and then later by default), and at some point in the future actually remove the finalization implementation from garbage collectors.</p>
<p>(Edit 2021-11-03: <a href="https://openjdk.java.net/jeps/421" rel="nofollow noreferrer">JEP 421</a> has just been posted, which proposes to deprecate finalization for removal. At this writing it's in the "candidate" state but I expect it will move forward. The deprecations added by this JEP are a formal notification that finalization will be removed at some point in a subsequent Java release. Perhaps not surprisingly, there's a fair overlap between the material in this answer and in the JEP, though the JEP is more precise and describes a moderate evolution in our thinking on the topic.)</p>
<p>(Edit 2022-04-04: <a href="https://openjdk.java.net/jeps/421" rel="nofollow noreferrer">JEP 421</a> <em>Deprecate Finalization for Removal</em> has been integrated and delivered in JDK 18.)</p> |
17,769,011 | How does cookie based authentication work? | <p>Can someone give me a step by step description of how cookie based authentication works? I've never done anything involving either authentication or cookies. What does the browser need to do? What does the server need to do? In what order? How do we keep things secure?</p>
<p>I've been reading about different types of authentication and about cookies but I would like a basic description of how to use the two together- I've only read that they are often used together but could not find a description of how.</p> | 17,769,061 | 3 | 1 | null | 2013-07-21 04:21:47.043 UTC | 98 | 2022-04-25 18:30:40.117 UTC | null | null | null | null | 2,325,773 | null | 1 | 269 | authentication|cookies|browser | 172,037 | <p>A cookie is basically just an item in a dictionary. Each item has a key and a value. For authentication, the key could be something like 'username' and the value would be the username. Each time you make a request to a website, your browser will include the cookies in the request, and the host server will check the cookies. So authentication can be done automatically like that.</p>
<p>To set a cookie, you just have to add it to the response the server sends back after requests. The browser will then add the cookie upon receiving the response. </p>
<p>There are different options you can configure for the cookie server side, like expiration times or encryption. An encrypted cookie is often referred to as a signed cookie. Basically the server encrypts the key and value in the dictionary item, so only the server can make use of the information. So then cookie would be secure.</p>
<p>A browser will save the cookies set by the server. In the HTTP header of every request the browser makes to that server, it will add the cookies. It will only add cookies for the domains that set them. Example.com can set a cookie and also add options in the HTTP header for the browsers to send the cookie back to subdomains, like sub.example.com. It would be unacceptable for a browser to ever sends cookies to a different domain.</p> |
47,051,485 | Angular Material 2 Table Mat Row Click event also called with button click in Mat Cell | <p>I am new to material 2 and I have implemented <a href="https://material.angular.io/components/table/overview" rel="noreferrer">mat table</a> and in which I have click event on row to open dialog and there is also a menu button in last column "Action" but on clicking on button it also open dialog box instead of opening menu.</p>
<p><strong>Table</strong></p>
<pre><code> <mat-table #table [dataSource]="dataSource" matSort (matSortChange)="sortData($event)">
<ng-container matColumnDef="id">
<mat-header-cell *matHeaderCellDef > No. </mat-header-cell>
<mat-cell *matCellDef="let element">
<mat-checkbox checked='true'></mat-checkbox>
</mat-cell>
</ng-container>
<ng-container matColumnDef="unit_num">
<mat-header-cell *matHeaderCellDef mat-sort-header="unit_num"> Unit No. </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.unit_num}} </mat-cell>
</ng-container>
<ng-container matColumnDef="unit_type">
<mat-header-cell *matHeaderCellDef mat-sort-header="unit_type"> Unit Type </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.unit_type}} </mat-cell>
</ng-container>
<ng-container matColumnDef="shares">
<mat-header-cell *matHeaderCellDef mat-sort-header="shares"> Shares </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.shares}} </mat-cell>
</ng-container>
<ng-container matColumnDef="sections">
<mat-header-cell *matHeaderCellDef>Section </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.sections.section_type}} </mat-cell>
</ng-container>
<ng-container matColumnDef="buildings">
<mat-header-cell *matHeaderCellDef >Building </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.buildings.buildingname}} </mat-cell>
</ng-container>
<ng-container matColumnDef="_id">
<mat-header-cell *matHeaderCellDef> Action </mat-header-cell>
<mat-cell *matCellDef="let element">
<button mat-button [matMenuTriggerFor]="menu"><mat-icon>more_vert</mat-icon>
</button>
<mat-menu #menu="matMenu">
<button mat-menu-item (click)="edit(element._id)">Edit</button>
<button mat-menu-item (click)="gotoFamily(element)">Go to current family</button>
<button mat-menu-item (click)="createNewFam(element)">Create new family</button>
<button mat-menu-item (click)="openDeleteDialog(element._id)">Delete</button>
</mat-menu>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns; let index=index;" mat-ripple style="position:relative;" (click)="edit(row._id,$event)"></mat-row>
</mat-table>
<mat-paginator [length]="count"
[pageSize]="pageSize"
[pageSizeOptions]="pageSizeOptions"
(page)="pageSide($event)">
</mat-paginator>
</code></pre>
<p><a href="https://i.stack.imgur.com/bhX6W.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bhX6W.png" alt="it open **Dialog box** and action buttons are hidden"></a></p>
<p><strong>It should actually open only menu</strong></p>
<p><a href="https://i.stack.imgur.com/kwRqx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kwRqx.png" alt="only action, dialog box disabled"></a></p> | 48,991,794 | 2 | 6 | null | 2017-11-01 09:11:45.95 UTC | 7 | 2020-02-02 07:21:51.32 UTC | 2020-02-02 07:21:51.32 UTC | null | 6,782,707 | null | 7,912,447 | null | 1 | 32 | angular|angular-material2|angular-cdk|xmltable|onrowclick | 57,106 | <p>I've just had the same issue and have solved it using Will's comment to the original post, adding a click handler with <code>$event.stopPropagation</code> to the cell as the direct parent to the button. I'll add it here as a solution in case anyone else comes here looking for the same answer.</p>
<p>I have a Material data table where the row has a click event to take you through to an edit mode and the last column contains a button with a delete action. Obviously you don't want to be triggering delete and edit at the same time!</p>
<p>Here's the structure I've used that resolves the issue:</p>
<p><strong>Snippet</strong></p>
<pre><code>// Row definition containing a click event
<mat-row *matRowDef="let row; columns: displayedColumns;" (click)="onEdit(row.id)"></mat-row>
// Definition for the cell containing the button
<ng-container matColumnDef="buttons">
<mat-header-cell *matHeaderCellDef></mat-header-cell>
<mat-cell *matCellDef="let group" (click)="$event.stopPropagation()">
<button mat-button (click)="onDelete(group.id)">
<mat-icon>delete</mat-icon>
</button>
</mat-cell>
</ng-container>
</code></pre>
<p><strong>Full Table Code</strong></p>
<pre><code><mat-table #table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef mat-sort-header>Name</mat-header-cell>
<mat-cell *matCellDef="let group">{{ group.name }}</mat-cell>
</ng-container>
<ng-container matColumnDef="description">
<mat-header-cell *matHeaderCellDef>Description</mat-header-cell>
<mat-cell *matCellDef="let group">{{ group.description }}</mat-cell>
</ng-container>
<ng-container matColumnDef="buttons">
<mat-header-cell *matHeaderCellDef></mat-header-cell>
<mat-cell *matCellDef="let group" (click)="$event.stopPropagation()">
<button mat-button (click)="onDelete(group.id)">
<mat-icon>delete</mat-icon>
</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;" (click)="onEdit(row.id)"></mat-row>
</mat-table>
</code></pre>
<p>Again, full credit to Will Howell for this solution.</p> |
47,339,698 | How to convert csv file to text file using python? | <p>I want to convert a couple of .csv files to .txt files using python. In my .csv files, I have hundreds of lines of data like the bellow:
<a href="https://i.stack.imgur.com/ZDITZ.png" rel="noreferrer">image of the csv file</a></p>
<pre><code>Value Date Time
919 4/15/2016 19:41:02
551 4/15/2016 19:46:51
717 4/15/2016 19:49:48
2679 4/15/2016 19:52:49
2890 4/15/2016 19:55:43
2897 4/15/2016 19:58:38
1790 4/15/2016 21:39:14
2953 4/15/2016 21:42:10
2516 4/15/2016 21:45:04
2530 4/15/2016 21:47:58
2951 4/15/2016 21:51:02
2954 4/15/2016 21:53:56
2537 4/15/2016 21:56:52
2523 4/15/2016 21:59:45
2536 4/15/2016 22:02:49
2727 4/15/2016 22:05:43
</code></pre>
<p>I use the bellow code for this purpose.</p>
<pre><code>csv_file = input('Enter the name of your input file: ')
txt_file = input('Enter the name of your output file: ')
text_list = []
with open(csv_file, "r") as my_input_file:
for line in my_input_file:
line = line.split(",", 2)
text_list.append(" ".join(line))
with open(txt_file, "w") as my_output_file:
my_output_file.write("#1\n")
my_output_file.write("double({},{})\n".format(len(text_list), 2))
for line in text_list:
my_output_file.write(" " + line)
print('File Successfully written.')
</code></pre>
<p>My first problem is that when the name of the input file is (for example) "DFW002_0330PM_Thursday_November_16_2017", I get the bellow error:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Behzad/Desktop/run/UTA/cvstotext.py", line 1, in <module>
csv_file = input('Enter the name of your input file: ')
File "<string>", line 1, in <module>
NameError: name 'DFW000_0330PM_Thursday_November_16_2017' is not defined
</code></pre>
<p>But, when I change the name of the code to (for example) "11", the code defines the file and goes to the next steps, but again it returns the bellow error:</p>
<pre><code>Traceback (most recent call last):
File "C:/Users/Behzad/Desktop/run/UTA/cvstotext.py", line 6, in <module>
with open(csv_file, "r") as my_input_file:
TypeError: coercing to Unicode: need string or buffer, int found
</code></pre>
<p>Would you please help me handle these problems?</p> | 47,340,240 | 1 | 10 | null | 2017-11-16 21:50:37.847 UTC | 4 | 2017-11-16 22:39:15.343 UTC | 2017-11-16 22:04:58.693 UTC | null | 8,917,756 | null | 8,917,756 | null | 1 | 6 | python|csv|text | 61,813 | <p>Using <code>csv</code> it's very easy to iterate over the csv lines: </p>
<pre><code>import csv
csv_file = raw_input('Enter the name of your input file: ')
txt_file = raw_input('Enter the name of your output file: ')
with open(txt_file, "w") as my_output_file:
with open(csv_file, "r") as my_input_file:
[ my_output_file.write(" ".join(row)+'\n') for row in csv.reader(my_input_file)]
my_output_file.close()
</code></pre> |
21,101,492 | Automatically pass $event with ng-click? | <p>I know that I can get access to the click event from <code>ng-click</code> if I pass in the <code>$event</code> object like so:</p>
<pre><code><button ng-click="myFunction($event)">Give me the $event</button>
<script>
function myFunction (event) {
typeof event !== "undefined" // true
}
</script>
</code></pre>
<p>It's a little bit annoying having to pass <code>$event</code> explicitly every time. Is it possible to set <code>ng-click</code> to somehow pass it to the function by default?</p> | 21,101,719 | 4 | 13 | null | 2014-01-13 21:14:39.147 UTC | 10 | 2019-12-15 12:27:10.643 UTC | 2019-12-15 12:27:10.643 UTC | null | 4,370,109 | null | 2,026,098 | null | 1 | 73 | javascript|angularjs|angularjs-directive|dom-events|angularjs-ng-click | 151,343 | <p>Take a peek at the <code>ng-click</code> directive source:</p>
<pre><code>...
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
</code></pre>
<p><a href="https://github.com/angular/angular.js/blob/v1.2.8/src/ng/directive/ngEventDirs.js#L50">It shows</a> how the <code>event</code> object is being <em>passed on</em> to the <code>ng-click</code> expression, using <code>$event</code> as a name of the parameter. This is done by the $parse service, which doesn't allow for the parameters to <em>bleed into</em> the target scope, which means <strong>the answer is no</strong>, you can't access the <code>$event</code> object any other way but through the callback parameter.</p> |
23,113,494 | Double Progress Bar in Python | <p>Is there a way to create a double progress bar in Python?
I want to run two loops inside each other. For each loop I want to have a progress bar. My program looks like:</p>
<pre><code>import time
for i1 in range(5):
for i2 in range(300):
# do something, e.g. sleep
time.sleep(0.01)
# update upper progress bar
# update lower progress bar
</code></pre>
<p>The output somewhere in the middle should look something like</p>
<pre><code>50%|############################ |ETA: 0:00:02
80%|################################################## |ETA: 0:00:04
</code></pre>
<p>The already existing really cool <a href="http://code.google.com/p/python-progressbar/">progressbar</a> module doesn't seem to support that.</p> | 38,489,852 | 11 | 2 | null | 2014-04-16 15:14:41.687 UTC | 19 | 2022-06-11 17:55:19.547 UTC | null | null | null | null | 1,551,501 | null | 1 | 80 | python|progress-bar | 76,902 | <p>Use the <a href="https://github.com/tqdm/tqdm#nested-progress-bars" rel="noreferrer">nested progress bars feature of tqdm</a>, an extremely low overhead, very customisable progress bar library:</p>
<pre class="lang-bash prettyprint-override"><code>$ pip install -U tqdm
</code></pre>
<p>Then:</p>
<pre class="lang-py prettyprint-override"><code>from tqdm import tqdm
# from tqdm.auto import tqdm # notebook compatible
import time
for i1 in tqdm(range(5)):
for i2 in tqdm(range(300), leave=False):
# do something, e.g. sleep
time.sleep(0.01)
</code></pre>
<p>(The <code>leave=False</code> is optional - needed to discard the nested bars upon completion.)</p>
<p>You can also use <code>from tqdm import trange</code> and then replace <code>tqdm(range(...))</code> with <code>trange(...)</code>. You can also get it <a href="https://github.com/tqdm/tqdm#ipython-jupyter-integration" rel="noreferrer">working in a notebook</a>.</p>
<p>Alternatively if you want just one bar to monitor everything, you can use <code>tqdm</code>'s version of <code>itertools.product</code>:</p>
<pre class="lang-py prettyprint-override"><code>from tqdm.contrib import itertools
import time
for i1, i2 in itertools.product(range(5), range(300)):
# do something, e.g. sleep
time.sleep(0.01)
</code></pre> |
1,354,581 | COM Interop without regasm | <p>I'm a limited user, and I need to write an Outlook macro that exposes a C# library in Outlook 2003 and 2007. </p>
<p>I do not have any admin privilges at all, not even at install time, so I can't run RegAsm and I can't (I assume) write a managed add-in.</p>
<p>Is there any way to call .Net code from VBA in this scenario, or are there any other solutions?</p>
<p>This is for personal use only, so an ugly hack is perfectly acceptable (so long as it works)</p> | 1,613,018 | 5 | 0 | null | 2009-08-30 18:42:56.153 UTC | 11 | 2014-04-15 23:07:51.597 UTC | 2009-09-04 02:04:56.307 UTC | null | 34,397 | null | 34,397 | null | 1 | 19 | .net|vba|outlook|com-interop|limited-user | 9,139 | <p>I solved this by running <code>regasm</code> with the <code>/regfile</code> option, and replacing HKLM with HKCU in the resulting <code>.reg</code> file.</p> |
1,951,584 | If condition in batch files | <pre><code>@echo off
SET var1="Yes"
SET var2="No"
SET var3="Yes"
if %var1%=="Yes"
echo Var1 set
if %var2%=="Yes"
echo Var2 set
if %var3%=="Yes"
echo Var3 set
</code></pre>
<p>If I run the above script I get the following error. Can anyone pls help?</p>
<blockquote>
<p>The syntax of the command is
incorrect.</p>
</blockquote>
<p>Thanks.</p> | 1,951,593 | 5 | 0 | null | 2009-12-23 09:18:02.693 UTC | 3 | 2020-07-08 02:38:07.113 UTC | null | null | null | null | 139,909 | null | 1 | 25 | windows|batch-file | 101,483 | <p>The echo needs to either be at the end of the if statement:</p>
<pre><code>if %var1%=="Yes" echo Var1 set
</code></pre>
<p>or of the following form:</p>
<pre><code>if %var1%=="Yes" (
echo Var1 set
)
</code></pre>
<p>I tend to use the former for very simple conditionals and the latter for multi-command ones and primitive <code>while</code> statements:</p>
<pre><code>:while1
if %var1%=="Yes" (
:: Do something that potentially changes var1
goto :while1
)
</code></pre>
<p>What your particular piece of code is doing is trying to execute the command <code>if %var1%=="Yes"</code> which is not valid in and of itself.</p> |
1,519,272 | MySQL "NOT IN" query | <p>I wanted to run a simple query to throw up all the rows of <code>Table1</code> where a principal column value is not present in a column in another table (<code>Table2</code>).</p>
<p>I tried using:</p>
<pre><code>SELECT * FROM Table1 WHERE Table1.principal NOT IN Table2.principal
</code></pre>
<p>This is instead throwing a syntax error. Google search led me to forums where people were saying that MySQL does not support <code>NOT IN</code> and something extremely complex needs to be used. Is this true? Or am I making a horrendous mistake?</p> | 1,519,296 | 5 | 1 | null | 2009-10-05 10:24:32 UTC | 49 | 2019-10-17 10:55:46.333 UTC | 2009-10-05 10:26:22.223 UTC | null | 20,972 | null | 140,970 | null | 1 | 199 | sql|mysql | 539,682 | <p>To use IN, you must have a set, use this syntax instead:</p>
<pre><code>SELECT * FROM Table1 WHERE Table1.principal NOT IN (SELECT principal FROM table2)
</code></pre> |
1,456,664 | Connection Pool Strategy: Good, Bad or Ugly? | <p>I'm in charge of developing and maintaining a group of Web Applications that are centered around similar data. The architecture I decided on at the time was that each application would have their own database and web-root application. Each application maintains a connection pool to its own database and a central database for shared data (logins, etc.)</p>
<p>A co-worker has been positing that this strategy will not scale because having so many different connection pools will not be scalable and that we should refactor the database so that all of the different applications use a single central database and that any modifications that may be unique to a system will need to be reflected from that one database and then use a single pool powered by Tomcat. He has posited that there is a lot of "meta data" that goes back and forth across the network to maintain a connection pool. </p>
<p>My understanding is that with proper tuning to use only as many connections as necessary across the different pools (low volume apps getting less connections, high volume apps getting more, etc.) that the number of <em>pools</em> doesn't matter compared to the number of <em>connections</em> or more formally that the difference in overhead required to maintain 3 pools of 10 connections is negligible compared to 1 pool of 30 connections.</p>
<p>The reasoning behind initially breaking the systems into a one-app-one-database design was that there are likely going to be differences between the apps and that each system could make modifications on the schema as needed. Similarly, it eliminated the possibility of system data bleeding through to other apps.</p>
<p>Unfortunately there is not strong leadership in the company to make a hard decision. Although my co-worker is backing up his worries only with vagueness, I want to make sure I understand the ramifications of multiple small databases/connections versus one large database/connection pool.</p> | 1,456,731 | 6 | 1 | null | 2009-09-21 20:28:33.333 UTC | 10 | 2012-07-18 17:35:43.6 UTC | 2010-12-23 02:52:52.567 UTC | null | 166,339 | null | 67,521 | null | 1 | 26 | java|mysql|database|tomcat|connection-pooling | 9,652 | <p>Your original design is based on sound principles. If it helps your case, this strategy is known as <a href="http://en.wikipedia.org/wiki/Shard_(database_architecture)" rel="noreferrer">horizontal partitioning or sharding</a>. It provides:</p>
<p>1) Greater scalability - because each shard can live on separate hardware if need be. </p>
<p>2) Greater availability - because the failure of a single shard doesn't impact the other shards</p>
<p>3) Greater performance - because the tables being searched have fewer rows and therefore smaller indexes which yields faster searches.</p>
<p>Your colleague's suggestion moves you to a single point of failure setup.</p>
<p>As for your question about 3 connection pools of size 10 vs 1 connection pool of size 30, the best way to settle that debate is with a benchmark. Configure your app each way, then do some stress testing with ab (Apache Benchmark) and see which way performs better. I suspect there won't be a significant difference but do the benchmark to prove it.</p> |
1,857,346 | python optparse, how to include additional info in usage output? | <p>Using python's optparse module I would like to add extra example lines below the regular usage output. My current help_print() output looks like this:</p>
<pre><code>usage: check_dell.py [options]
options:
-h, --help show this help message and exit
-s, --storage checks virtual and physical disks
-c, --chassis checks specified chassis components
</code></pre>
<p>I would like it to include usage examples for the less *nix literate users at my work. Something like this:</p>
<pre><code>usage: check_dell.py [options]
options:
-h, --help show this help message and exit
-s, --storage checks virtual and physical disks
-c, --chassis checks specified chassis components
Examples:
check_dell -c all
check_dell -c fans memory voltage
check_dell -s
</code></pre>
<p>How would I accomplish this? What optparse options allow for such? Current code:</p>
<pre><code>import optparse
def main():
parser = optparse.OptionParser()
parser.add_option('-s', '--storage', action='store_true', default=False, help='checks virtual and physical disks')
parser.add_option('-c', '--chassis', action='store_true', default=False, help='checks specified chassis components')
(opts, args) = parser.parse_args()
</code></pre> | 1,857,374 | 6 | 1 | null | 2009-12-07 01:48:08.497 UTC | 10 | 2014-10-01 10:35:44.48 UTC | 2014-09-16 21:35:05.397 UTC | null | 1,783,619 | null | 226,030 | null | 1 | 26 | python|optparse | 17,110 | <pre><code>parser = optparse.OptionParser(epilog="otherstuff")
</code></pre>
<p>The default <code>format_epilog</code> strips the newlines (uses textwrap), so you would need to override <code>format_epilog</code> in your parser like this.</p>
<pre><code>def main():
class MyParser(optparse.OptionParser):
def format_epilog(self, formatter):
return self.epilog
parser =MyParser(epilog=
"""Examples:
check_dell -c all
check_dell -c fans memory voltage
check_dell -s
""")
...
</code></pre>
<p>Here's a bit more detail.<br>
If you look in <code>optparse.py</code> in the class <code>OptionParser</code> there is a method called <code>format_epilog</code> which is called by <code>format_help</code> </p>
<p>here is the snippet from optparse.py</p>
<pre><code>def format_epilog(self, formatter):
return formatter.format_epilog(self.epilog)
def format_help(self, formatter=None):
if formatter is None:
formatter = self.formatter
result = []
if self.usage:
result.append(self.get_usage() + "\n")
if self.description:
result.append(self.format_description(formatter) + "\n")
result.append(self.format_option_help(formatter))
result.append(self.format_epilog(formatter))
return "".join(result)
</code></pre>
<p>The default behaviour of <code>formatter.format_epilog</code> is to use <code>textwrap.fill</code> which amongst other things, strips the newlines from the epilog. Since we want the newlines to be preserved, we subclass <code>OptionParser</code> and change the behaviour of <code>format_epilog</code></p> |
1,375,113 | Java exception not caught | <p>Why are some exceptions in Java not caught by <code>catch (Exception ex)</code>? This is code is completely failing out with an unhandled exception. (Java Version 1.4).</p>
<pre><code>public static void main(String[] args) {
try {
//Code ...
} catch (Exception ex) {
System.err.println("Caught Exception");
ex.printStackTrace();
exitCode = app.FAILURE_EXIT_CODE;
}
finally {
app.shutdown();
}
System.exit(exitCode);
}
</code></pre>
<p>I get a <code>Exception in thread "main" java.lang.NoSuchMethodError</code></p>
<p>But this works</p>
<pre><code>public static void main(String[] args) {
int exitCode = app.SUCCESS_EXIT_CODE;
try {
//Code ...
} catch (java.lang.NoSuchMethodError mex){
System.err.println("Caught NoSuchMethodError");
mex.printStackTrace();
exitCode = app.FAILURE_EXIT_CODE;
} catch (Exception ex) {
System.err.println("Caught Exception");
ex.printStackTrace();
exitCode = app.FAILURE_EXIT_CODE;
}
finally {
app.shutdown();
}
System.exit(exitCode);
}
</code></pre>
<p>I get <code>Caught NoSuchMethodError java.lang.NoSuchMethodError:</code></p>
<p>I thought catching exceptions would catch all exceptions? How can I catch all exceptions in java?</p> | 1,375,121 | 7 | 0 | null | 2009-09-03 18:25:53.223 UTC | 11 | 2018-07-05 22:30:11.977 UTC | 2017-05-15 10:19:37.913 UTC | null | 1,717,552 | null | 16,487 | null | 1 | 53 | java|exception|try-catch | 51,923 | <p>Because some exceptions don't derive from <code>Exception</code> - e.g. <code>Throwable</code> and <code>Error</code>.</p>
<p>Basically the type hierarchy is:</p>
<pre><code> Object
|
Throwable
/ \
Exception Error
</code></pre>
<p>Only <code>Throwables</code> and derived classes can be thrown, so if you catch <code>Throwable</code>, that really will catch everything.</p>
<p><code>Throwable</code>, <code>Exception</code> and any exception deriving from <code>Exception</code> <em>other</em> than those derived from <code>RuntimeException</code> count as <em>checked exceptions</em> - they're the ones that you have to declare you'll throw, or catch if you call something that throws them.</p>
<p>All told, the Java exception hierarchy is a bit of a mess...</p> |
1,753,070 | How do I configure git to ignore some files locally? | <p>Can I ignore files locally without polluting the global git config for everyone else? I have untracked files that are spam in my git status but I don't want to commit git config changes for every single little random untracked file I have in my local branches.</p> | 1,753,078 | 13 | 0 | null | 2009-11-18 01:36:47.597 UTC | 620 | 2022-07-08 12:31:19.723 UTC | 2019-06-23 22:49:36.313 UTC | null | 66,475 | null | 66,475 | null | 1 | 1,691 | git|ignore|gitignore | 569,587 | <p>From <a href="http://git-scm.com/docs/gitignore" rel="noreferrer">the relevant Git documentation</a>:</p>
<blockquote>
<p>Patterns which are specific to a particular repository but which do not need to be shared with other related repositories (e.g., auxiliary files that live inside the repository but are specific to one user's workflow) should go into the <code>$GIT_DIR/info/exclude</code> file.</p>
</blockquote>
<p>The <code>.git/info/exclude</code> file has the same format as any <code>.gitignore</code> file. Another option is to set <code>core.excludesFile</code> to the name of a file containing global patterns.</p>
<p>Note, if you already have unstaged changes you must run the following after editing your ignore-patterns:</p>
<pre><code>git update-index --assume-unchanged <file-list>
</code></pre>
<p><em>Note on <code>$GIT_DIR</code></em>: This is a notation used <a href="https://git-scm.com/docs/git-rev-parse#_options_for_files" rel="noreferrer">all over</a> the git manual simply to indicate the path to the git repository. If the environment variable is set, then it will override the location of whichever repo you're in, which probably isn't what you want.</p>
<hr>
<p><strong>Edit</strong>: Another way is to use:</p>
<pre><code>git update-index --skip-worktree <file-list>
</code></pre>
<p>Reverse it by:</p>
<pre><code>git update-index --no-skip-worktree <file-list>
</code></pre> |
8,441,991 | How to Build PDFBox for .Net | <p>I've seen examples for extracting text from pdf files that either use ITextSharp or PDFBox. PDFBox seems to be the most "reliable" method for extracting text, but it requires many additional steps. </p>
<p>I've tried to build the dll's using the instructions found <a href="http://pdfbox.apache.org/userguide/dot_net.html">here</a>, but I have no idea how to correctly build the required files for .Net.</p>
<p>I'm pretty lost, could someone provide a "Include PDFBox in your .Net application for Dummies" step by step?</p> | 8,454,097 | 1 | 2 | null | 2011-12-09 06:43:55.557 UTC | 15 | 2015-09-02 14:53:44.35 UTC | 2011-12-10 03:17:52.093 UTC | null | 244,236 | null | 244,236 | null | 1 | 9 | c#|java|.net|visual-studio|lucene | 18,445 | <p>I finally got it to work. I've outlined the steps I followed to get a working example. I hope someone finds this helpful.</p>
<p>Download the <a href="http://www.oracle.com/technetwork/java/javase/downloads/index.html">Java JDK</a>
<br/>
Download <a href="http://sourceforge.net/projects/ikvm/files/ikvm/0.42.0.6/">IKVM 0.42.0.6</a>
<br/>
Download <a href="http://pdfbox.apache.org/download.html">PDFBox 1.6.0-src.zip</a></p>
<p>The <a href="http://ant.apache.org/manual/index.html">Ant Manual</a> was helpful.</p>
<p>I renamed the Ant and PDFBox folders to shorten their names and moved them my C: drive</p>
<p>You have to setup your environment Variables. (Windows 7)
Right-click My Computer->Properties->Advanced System Settings->Environment Variables </p>
<p>I used the settings below, but yours will vary depending on where you installed Java and where you put the Ant and PDF Box folders.</p>
<pre>
Variable Value
ANT_HOME C:\apache-ant\
JAVA_HOME C:\Program Files (x86)\Java\jdk1.7.0_01
Path ;C:\apache-ant\bin\ (Append semi-colon and path)
</pre>
<p>Once the above it done, type in “ant” in a command window, you should get a “build.xml does not exist!” message if everything is setup correctly.</p>
<p>Edit the build.xml file inside the ”pdfbox-1.6.0\pdfbox” folder.
Find the line that has
Replace “.” with “Your IKVM Folder Path”.</p>
<p>I moved IKVM to “C:\IKVM" so mine looks like:
</p>
<p>Open a command window and cd to “C:\pdfbox-1.6.0\pdfbox “ and type “ant”</p>
<p>…and then a miracle occurs.</p>
<p>A bunch of new folders should now exist in the pdfbox folder. The required dll’s are in the bin folder. I don’t know why, but I got a “-SNAPSHOT” and the end of all my files (pdfbox-1.6.0-SNAPSHOT.dll).</p>
<p>IKVM.GNU.Classpath (Also called IKVM.OpenJDK.Classpath) no longer exists, it was modularized since the 0.40 release. It is now available in the form of several IKVM.OpenJDK dll’s. You only need a few of them.</p>
<p>Create a new project in Visual Studio C#</p>
<p>Copy these files from the pdfBox bin folder to the bin folder of your Visual C# project bin folder:</p>
<pre>
pdfbox-1.6.0-SNAPSHOT.dll
fontbox-1.6.0-SNAPSHOT.dll
commons-logging.dll
</pre>
<p>Copy these files from the ikvm bin folder to the bin folder of your Visual C# project bin folder:</p>
<pre>
IKVM.OpenJDK.Core.dll
IKVM.OpenJDK.SwingAWT.dll
IKVM.OpenJDK.Text.dll
IKVM.OpenJDK.Util.dll
IKVM.Runtime.dll
</pre>
<p>Add References to the IKVM dll’s above and build your project.</p>
<p>Add a Reference to the pdfbox dll and build your project again.</p>
<p>You are now ready to write some code. The simple example below produced a nice text file from the input pdf.</p>
<pre><code>using System;
using System.IO;
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.util;
namespace testPDF
{
class Program
{
static void Main()
{
PDFtoText pdf = new PDFtoText();
string pdfText = pdf.parsePDF(@"C:\Sample.pdf");
using (StreamWriter writer = new StreamWriter(@"C:\Sample.txt"))
{ writer.Write(pdfText); }
}
class PDFtoText
{
public string parsePDF(string filepath)
{
PDDocument document = PDDocument.load(filepath);
PDFTextStripper stripper = new PDFTextStripper();
return stripper.getText(document);
}
}
}
}
</code></pre> |
46,418,652 | `docker pull` returns `denied: access forbidden` from private gitlab registry | <p>I have a <code>Dockerfile</code> which is going to be implemented <code>FROM</code> a private registry's image. I build this file without any problem with <code>Docker version 1.12.6, build 78d1802</code> and <code>docker-compose version 1.8.0, build unknown</code>, but in another machine which has <code>Docker version 17.06.1-ce, build 874a737</code> and <code>docker-compose version 1.16.1, build 6d1ac21</code>, the <code>docker-compose build</code> returns:</p>
<pre><code>FROM my.private.gitlab.registry:port/image:tag
http://my.private.gitlab.registry:port/v2/docker/image/manifests/tag: denied: access forbidden
</code></pre>
<p><code>docker pull my.private.gitlab.registry:port/image:tag</code> returns the same. </p>
<p>Notice that I tried to get <code>my.private.registry:port/image:tag</code> and <code>http://my.private.registry:port/v2/docker/image/manifests/tag</code> has been catched.</p> | 46,422,186 | 4 | 6 | null | 2017-09-26 05:46:11.39 UTC | 5 | 2022-03-13 13:11:24.347 UTC | 2020-07-06 09:34:09.797 UTC | null | 100,297 | null | 1,626,977 | null | 1 | 38 | docker|docker-compose|gitlab|dockerfile | 73,416 | <p>If this is an authenticated registry, then you need to run <code>docker login <registryurl></code> on the machine where you are building this.</p>
<p>This only needs to be done once per host. The command then caches the auth in a file</p>
<pre><code>$ cat ~/.docker/config.json
{
"auths": {
"https://index.docker.io/v1/": {
"auth": "......="
}
}
}
</code></pre> |
18,122,592 | How to set process ID in Linux for a specific program | <p>I was wondering if there is some way to force to use some specific process ID to Linux to some application before running it. I need to know in advance the process ID.</p> | 24,224,902 | 6 | 5 | null | 2013-08-08 09:35:17.353 UTC | 9 | 2019-05-30 17:00:59.15 UTC | 2018-08-24 01:55:52.493 UTC | null | 33,204 | null | 1,730,820 | null | 1 | 26 | linux|process|set | 41,882 | <p>Actually, there is a way to do this. Since kernel 3.3 with CONFIG_CHECKPOINT_RESTORE set(which is set in most distros), there is /proc/sys/kernel/ns_last_pid which contains last pid generated by kernel. So, if you want to set PID for forked program, you need to perform these actions:</p>
<ol>
<li>Open /proc/sys/kernel/ns_last_pid and get fd</li>
<li>flock it with LOCK_EX</li>
<li>write PID-1</li>
<li>fork</li>
</ol>
<p>Voilà! Child will have PID that you wanted.
Also, don't forget to unlock (flock with LOCK_UN) and close ns_last_pid.</p>
<p>You can checkout C code at my blog <a href="http://efiop-notes.blogspot.com/2014/06/how-to-set-pid-using-nslastpid.html" rel="noreferrer">here</a>.</p> |
6,446,961 | When to use FragmentManager::putFragment and getFragment | <p>I've got an application that uses fragments and I was playing around with how to use the same fragment in an Activity with a dual pane and an Activity as a stand alone. Still not sure on the best method for completing this but I noticed the FragmentManager has a putFragment and getFragment function. What confuses me is that you have to provide a Bundle as parameter to both get and put functions. How can separate Activities have the same Bundle? Obviously you could pass the Bundle as a parameter but at that point I feel like you're just making a mess of things. </p>
<p>So what is a good scenario for using getFragment and putFragment? Please include the Bundle parameter explanation.</p> | 6,542,596 | 3 | 3 | null | 2011-06-22 21:48:32.98 UTC | 18 | 2012-12-25 13:02:43.317 UTC | null | null | null | null | 618,551 | null | 1 | 43 | android|android-fragments | 28,313 | <p>The basic answer:</p>
<p>These are only useful when implementing onSaveInstanceState() and restoring that state in onCreate(). If you are not implementing onSaveInstanceState(), you can forget about these methods and pretend like they don't exist.</p>
<p>The problem they are solving: if you want to save a reference to a fragment in your "saved instance state," you can't just put an object reference in there. First because well you can't put plain object in a Bundle. :) And the reason for this is that the point of that saved state is for it to be copied out of your process, so if your process needs to be killed, it can later be copied back in to a new process for you to re-initialize your activity/fragment from. A raw object is only meaningful in the context of the process it is running in, so it isn't possible to correctly copy the reference to such an object out of your current process and in to another.</p>
<p>So what putFragment()/getFragment() do is place a piece of data in the given Bundle that can identify that fragment across to a new instance of your activity/fragment in another process. Exactly what this representation is, is not defined, but in the current implementation it is the internal integer identifier for that fragment, which will be used later when the FragmentManager needs to re-create that fragment from a previously saved state... it is re-created with that same identifier, so when you then call getFragment() it can retrieve the integer, and use that to determine the correct Fragment object to return to the caller that corresponds to the one that was previously saved.</p> |
6,748,569 | c++ compiler error "was not declared in this scope" | <p>I'm getting a bizarre compiler error when trying to compile a c++ UDP client program.</p>
<blockquote>
<p>g++ -o client Udp.cpp ClientMain.c -I. -lpthread</p>
<p>In file included from ClientMain.c:1:0:</p>
<p>Udp.h: In destructor ‘CUdpMsg::~CUdpMsg()’:</p>
<p>Udp.h:103:43: error: ‘free’ was not declared in this scope</p>
<p>Udp.h: In member function ‘void CUdpMsg::Add(in_addr_t, const void*, size_t)’:</p>
<p>Udp.h:109:34: error: ‘malloc’ was not declared in this scope</p>
<p>Udp.h:109:41: error: ‘memcpy’ was not declared in this scope</p>
<p>ClientMain.c: In function ‘int main(int, char**)’:</p>
<p>ClientMain.c:28:57: error: ‘memcpy’ was not declared in this scope</p>
<p>ClientMain.c:29:61: error: ‘printf’ was not declared in this scope</p>
<p>ClientMain.c:30:17: error: ‘stdout’ was not declared in this scope</p>
<p>ClientMain.c:30:23: error: ‘fflush’ was not declared in this scope</p>
<p>ClientMain.c:34:68: error: ‘printf’ was not declared in this scope</p>
<p>ClientMain.c:35:17: error: ‘stdout’ was not declared in this scope</p>
<p>ClientMain.c:35:23: error: ‘fflush’ was not declared in this scope</p>
<p>ClientMain.c:37:30: error: ‘usleep’ was not declared in this scope</p>
</blockquote>
<p>I have the following declared at the beginning of my cpp file.</p>
<pre><code>#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <cstdlib>
#include <string>
#include <stdlib.h>
#include <cstring>
#include <errno.h>
</code></pre>
<p>functions like 'memcpy' should be declared in string.h... I have it (and string and cstring) all declared, and I'm still getting these compiler errors. Does anyone have a clue why this is happening? Thanks.</p> | 6,748,653 | 4 | 5 | null | 2011-07-19 14:13:07.343 UTC | 4 | 2011-07-19 14:44:10.147 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,597,051 | null | 1 | 7 | c++|g++|compiler-errors | 100,209 | <p>If you have multiple files, then you need the appropriate includes in each file. Also maybe its not within namespace? </p> |
35,857,266 | Using wget to download a ZIP file | <p>I'm having trouble using wget for my Debian 7.0 VPS server hosted by OVH.</p>
<p>I'm trying to download a ZIP file from MediaFire, and when I connected via SSH I typed,</p>
<pre><code>wget http://download1472.mediafire.com/5ndlsskkyfmg/dgx7zbbdbxawbwd/Vhalar-GGJ16.zip
</code></pre>
<p>Then, this is my output,</p>
<pre><code>--2016-03-07 20:17:52-- http://download1472.mediafire.com/5ndlsskkyfmg/dgx7zbbd bxawbwd/Vhalar-GGJ16.zip
Resolving download1472.mediafire.com (download1472.mediafire.com)... 205.196.123 .160
Connecting to download1472.mediafire.com (download1472.mediafire.com)|205.196.12 3.160|:80... connected.
HTTP request sent, awaiting response... 302 Found
Location: http://www.mediafire.com/?dgx7zbbdbxawbwd [following]
--2016-03-07 20:17:52-- http://www.mediafire.com/?dgx7zbbdbxawbwd
Resolving www.mediafire.com (www.mediafire.com)... 205.196.120.6, 205.196.120.8
Connecting to www.mediafire.com (www.mediafire.com)|205.196.120.6|:80... connect ed.
HTTP request sent, awaiting response... 301
Location: /download/dgx7zbbdbxawbwd/Vhalar-GGJ16.zip [following]
--2016-03-07 20:17:52-- http://www.mediafire.com/download/dgx7zbbdbxawbwd/Vhala r-GGJ16.zip
Connecting to www.mediafire.com (www.mediafire.com)|205.196.120.6|:80... connect ed.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: `Vhalar-GGJ16.zip'
[ <=> ] 94,265 440K/s in 0.2s
2016-03-07 20:17:52 (440 KB/s) - `Vhalar-GGJ16.zip' saved [94265]
</code></pre>
<p>The download took less than 1 second, and it's a 280MB zip file. Also, it seems to say "440 KB/s", and that math just doesn't add up.</p>
<p>I'm confused as to why I can't download this zip file to my server via SSH, instead of downloading it to my computer, then re-uploading it to the server.</p>
<p>Does anyone see a flaw I'm making in my command?</p> | 35,857,326 | 4 | 2 | null | 2016-03-08 01:23:09.323 UTC | 2 | 2022-09-16 15:12:01.863 UTC | null | null | null | null | 5,051,160 | null | 1 | 10 | ssh|server|wget|vps | 41,204 | <p>Look at the contents of the 94kb file that you downloaded in something like vi. Odds are it's not a zip file, but a html file, telling you what went wrong, and what you need to do to download the file.</p>
<p>A browser would have known this (the mime type would tell it that it is being served HTML, and it would display it to you rather than download it).</p>
<p>It is likely that this is a measure by Mediafire to prevent automated downloads of their files. It's possible that spoofing the user-agent header might help, but unlikely.</p> |
15,696,190 | Permission denied when cloning git repository | <p>So I just setup an Amazon EC2 instance. And installed git..</p>
<pre><code>sudo yum install git
</code></pre>
<p>I then set up my ssh key with github. Now when I try to clone my repo into /var/www/html folder i get this error..</p>
<pre><code>fatal: could not create work tree dir 'example.com'.: Permission denied
</code></pre>
<p>and when I run as root...</p>
<pre><code>Cloning into 'example.com'...
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
</code></pre>
<p>But I made sure that my github public key matches my ~/.ssh/id_rsa.pub key. Is there something that I'm missing here?</p> | 15,696,244 | 5 | 0 | null | 2013-03-29 01:53:51.73 UTC | 5 | 2020-01-21 00:45:37.16 UTC | null | null | null | null | 1,680,682 | null | 1 | 9 | linux|git|github|amazon-ec2|git-clone | 103,050 | <p>Your first error is because your user does not have access to write to /var/www/html . You could give your user permissions to do so.</p>
<p>Your second error when running as root, is likely that you have your ssh keys in your user home directory, not in /root/.ssh/ , or that your .ssh directory or the ~/.ssh/id_rsa.pub key file have improber permissions. ~/.ssh/ should have the permission bits 0700 , and should have ~/.ssh/id_rsa.pub e.g. 0600</p> |
15,800,565 | Spring MVC : large files for download, OutOfMemoryException | <p>How to provide large files for download through spring controller ? I followed few discussions on similar topic :</p>
<p><a href="https://stackoverflow.com/questions/5673260/downloading-a-file-from-spring-controllers">Downloading a file from spring controllers</a></p>
<p>but those solutions fails for large files ~ 300mb - 600mb.
I am getting OutOfMemoryException on the last line :</p>
<pre><code>@RequestMapping(value = "/file/{dummyparam}.pdf", method = RequestMethod.GET, produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody byte[] getFile(@PathVariable("dummyparam") String dummyparam, HttpServletResponse response) {
.
.
InputStream is = new FileInputStream(resultFile);
response.setHeader("Content-Disposition", "attachment; filename=\"dummyname " + dummyparam + ".pdf\"");
.
.
return IOUtils.toByteArray(is);
</code></pre>
<p>My (naive) assumption was that IOUtils will handle even large files but this is not obviously happening. Is there any way how to split file into chunks as download is in progress ? Files are usually around 300 - 600mb large. Max number of concurrent downloads is estimated to 10. </p>
<p>Easy way would be to link files as static content in the webserver directory but we would like to try do it in within our Spring app.</p> | 15,800,625 | 2 | 0 | null | 2013-04-04 00:26:42.72 UTC | 10 | 2019-06-22 12:39:18.81 UTC | 2017-05-23 12:00:10.983 UTC | null | -1 | null | 1,111,253 | null | 1 | 9 | java|spring-mvc|download | 21,746 | <p>It is because you are reading the entire file into memory, use a buffered read and write instead.</p>
<pre><code>@RequestMapping(value = "/file/{dummyparam}.pdf", method = RequestMethod.GET, produces=MediaType.APPLICATION_OCTET_STREAM_VALUE)
public void getFile(@PathVariable("dummyparam") String dummyparam, HttpServletResponse response) {
InputStream is = new FileInputStream(resultFile);
response.setHeader("Content-Disposition", "attachment; filename=\"dummyname " + dummyparam + ".pdf\"");
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
</code></pre> |
51,508,321 | How to remove all whitespace of a string in Dart? | <p>Using <code>trim()</code> to eliminate white space in Dart and it doesn't work.
What am I doing wrong or is there an alternative?</p>
<pre><code> String product = "COCA COLA";
print('Product id is: ${product.trim()}');
</code></pre>
<p>Console prints: <code>Product id is: COCA COLA</code></p> | 51,508,420 | 9 | 6 | null | 2018-07-24 22:19:27.977 UTC | 6 | 2022-02-10 20:06:05.2 UTC | 2021-04-16 00:48:22.11 UTC | user10563627 | null | null | 6,526,237 | null | 1 | 45 | string|flutter|dart|whitespace | 57,786 | <p>Try this</p>
<pre><code>String product = "COCA COLA";
print('Product id is: ${product.replaceAll(new RegExp(r"\s+\b|\b\s"), "")}');
</code></pre>
<p>Update:</p>
<pre><code>String name = '4 ever 1 k g @@ @';
print(name.replaceAll(RegExp(r"\s+"), ""));
</code></pre>
<p>Another easy solution:</p>
<pre><code>String name = '4 ever 1 k g @@ @';
print(name.replaceAll(' ', '');
</code></pre> |
41,030,429 | `brew upgrade` hangs on El Capitan | <p>I can't run <code>brew upgrade</code> without it hanging indefinitely. I'm using El Capitan OS. Here's the input/output: </p>
<pre><code>>>$ brew upgrade
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 2 taps (homebrew/core, homebrew/science).
==> Updated Formulae
artifactory dovecot node@4 scamper
chromedriver node-build openvpn
==> Deleted Formulae
pdksh
==> Upgrading 10 outdated packages, with result:
gcc 6.2.0, gdbm 1.12, libtiff 4.0.7, openssl 1.0.2j, pkg-config 0.29.1_2, python 2.7.12_2, homebrew/science/r 3.3.2, readline 7.0.1, sqlite 3.15.2, yara 3.5.0_1
==> Upgrading gcc
Warning: Building gcc from source:
The bottle needs the Xcode CLT to be installed.
==> Using the sandbox
==> Downloading https://ftpmirror.gnu.org/gcc/gcc-6.2.0/gcc-6.2.0.tar.bz2
Already downloaded: /Users/r8t/Library/Caches/Homebrew/gcc-6.2.0.tar.bz2
==> Downloading https://raw.githubusercontent.com/Homebrew/formula-patches/e9e0e
Already downloaded: /Users/r8t/Library/Caches/Homebrew/gcc--patch-863957f90a934ee8f89707980473769cff47ca0663c3906992da6afb242fb220.patch
==> Patching
==> Applying 6.1.0-jit.patch
patching file gcc/jit/Make-lang.in
==> ../configure --build=x86_64-apple-darwin15.6.0 --prefix=/usr/local/Cellar/gc
==> make bootstrap
</code></pre>
<p>And then nothing. </p> | 41,030,599 | 4 | 4 | null | 2016-12-08 01:43:25.667 UTC | 6 | 2019-08-24 14:51:41.407 UTC | null | null | null | null | 2,487,607 | null | 1 | 43 | homebrew|osx-elcapitan | 50,160 | <ul>
<li><code>ctrl + c</code> to exit the hanging upgrade. </li>
<li>Run <code>brew doctor</code>. It prompted me to </li>
<li>run <code>brew cleanup</code> to clean up false symlinks. Then I</li>
<li>ran <code>brew doctor</code> again and it prompted me </li>
<li>to install xcode CLT via
the command <code>sudo xcode-select --install</code>. </li>
<li>Finally <code>brew update</code>
worked.</li>
</ul> |
5,530,473 | how do I restart an activity in android? | <p>in an app that I am writing, there is a part of it that allows you to change a curtain setting. the problem is, that this setting won't take effect until the activity is recreated. is there a way to tell the app to restart using the onResume() method (hopefully allowing it to save everything in the onSaveInstanceState())?</p> | 5,530,500 | 2 | 6 | null | 2011-04-03 15:19:43.653 UTC | 3 | 2016-05-09 18:46:16.077 UTC | null | null | null | null | 599,402 | null | 1 | 9 | android|android-activity|restart|onresume | 40,269 | <p>This has been <a href="https://stackoverflow.com/questions/1397361/android-restart-activity">posted before</a>:</p>
<pre><code>Intent intent = getIntent();
finish();
startActivity(intent);
</code></pre>
<p>As of API level 11, you can also just call an activity's <a href="http://developer.android.com/reference/android/app/Activity.html#recreate()" rel="nofollow noreferrer"><code>recreate()</code></a> method. Not only is this cleaner because it is less code, it avoids issues that may arise if your activity was launched by an implicit intent.</p> |
5,033,246 | Android, Autocomplettextview, force text to be from the entry list | <p>Is there a way to force the entry in an autocompletetextview to be one of the elements in the entrylist?</p>
<p>I've found a method called "performValidation" but im not sure what it actually does, and i havent been able to find much documentation or any examples.</p> | 5,033,834 | 2 | 0 | null | 2011-02-17 18:53:45.257 UTC | 11 | 2019-01-29 16:02:21.123 UTC | null | null | null | null | 587,650 | null | 1 | 19 | android|validation|autocompletetextview | 17,002 | <p>The <code>AutoCompleteTextView</code> has a method called <code>setValidator()</code> that takes an instance of the interface <code>AutoCompleteTextView.Validator</code> as parameter. <code>AutoCompleteTextView.Validator</code> contains <code>isValid()</code> with which you can check the value that has been entered, and you can "fix" this string by implementing <code>fixText()</code>.</p>
<p>Seems this is the best you can get with <code>AutoCompleteTextView</code>, as the documentation for <code>AutoCompleteTextView.Validator</code> states the following:</p>
<blockquote>
<p>"Since there is no foolproof way to
prevent the user from leaving this
View with an incorrect value in it,
all we can do is try to fix it
ourselves when this happens."</p>
</blockquote>
<p>If your list of elements is not too long, you are probably better off using a Spinner.</p>
<p><strong>****** Edit: ******</strong></p>
<p>I wipped together a quick example of how you can use this, hope it helps!</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<AutoCompleteTextView
android:id="@+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Focus me to validate above text"/>
</LinearLayout>
</code></pre>
<p>-</p>
<pre><code>public class AutoCompleteTextViewActivity extends Activity {
String[] validWords = new String[]{"", "snowboard", "bobsleigh", "slalom"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AutoCompleteTextView view = (AutoCompleteTextView)findViewById(R.id.input);
view.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, validWords));
view.setValidator(new Validator());
view.setOnFocusChangeListener(new FocusListener());
}
class Validator implements AutoCompleteTextView.Validator {
@Override
public boolean isValid(CharSequence text) {
Log.v("Test", "Checking if valid: "+ text);
Arrays.sort(validWords);
if (Arrays.binarySearch(validWords, text.toString()) > 0) {
return true;
}
return false;
}
@Override
public CharSequence fixText(CharSequence invalidText) {
Log.v("Test", "Returning fixed text");
/* I'm just returning an empty string here, so the field will be blanked,
* but you could put any kind of action here, like popping up a dialog?
*
* Whatever value you return here must be in the list of valid words.
*/
return "";
}
}
class FocusListener implements View.OnFocusChangeListener {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.v("Test", "Focus changed");
if (v.getId() == R.id.input && !hasFocus) {
Log.v("Test", "Performing validation");
((AutoCompleteTextView)v).performValidation();
}
}
}
}
</code></pre> |
16,237,001 | Calling a method from within an if/if else statement | <p>Is it possible to call a method within an if statement, and then a separate method in an if else statement?</p>
<p>I have created a scanner than reads keyboard input, and based on the option the user gives, a different method will be called. Can I say something along the lines of:</p>
<pre><code>Scanner in = new Scanner (System.in);
char choice = in.next().charAt(0);
if(choice == 1)
{
private static void doAddStudent(Student aStudent)
{
this.theRegistry.addStudent(aStudent);
}
}
</code></pre>
<p>any help would be much appreciated</p> | 16,237,061 | 5 | 3 | null | 2013-04-26 12:54:22.29 UTC | null | 2015-02-16 15:50:55.81 UTC | 2013-04-26 12:59:37.493 UTC | null | 69,875 | null | 1,883,754 | null | 1 | 3 | java|if-statement|methods|call | 55,027 | <p>You can of course call a method within an if or else block. But what you tried in your snippet is DECLARING a method within a block which is impossible.</p>
<p>fixed snippet:</p>
<pre><code>Scanner in = new Scanner (System.in);
char choice = in.next().charAt(0);
if(choice == 1)
{
this.theRegistry.addStudent(aStudent);
}
</code></pre>
<p><strong>EDIT:</strong></p>
<p>I think the code you want looks something like this:</p>
<pre><code>public static void main(String[] args) {
//some code
Scanner in = new Scanner (System.in);
char choice = in.next().charAt(0);
if(choice == 1)
{
RegistryInterface.doAddStdent(student);
}
//some code
}
</code></pre>
<p>The RegistryInterface.java</p>
<pre><code>public class RegistryInterface {
private static void doAddStudent(Student aStudent) {
this.theRegistry.addStudent(aStudent);
}
}
</code></pre> |
16,320,375 | Convert MATLAB char array to string | <p>Starting with the MATLAB char array, A:</p>
<pre><code>A(1,1) = 'A'
A(1,2) = 'P'
A(1,3) = 'R'
A(2,1) = 'M'
A(2,2) = 'A'
A(2,3) = 'Y'
</code></pre>
<p>How can this be converted to a cell of strings, B, such that:</p>
<pre><code>B{1} = 'APR'
B{2} = 'MAY'
</code></pre>
<p>Edit:
A is a cell and using the function cellstr gives the error</p>
<pre><code>Error using cellstr (line 23)
S must be 2-D.
</code></pre> | 16,320,433 | 2 | 6 | null | 2013-05-01 14:47:22.003 UTC | 1 | 2017-01-06 20:48:55.647 UTC | 2017-01-06 20:48:55.647 UTC | null | 7,221,965 | null | 2,186,160 | null | 1 | 10 | string|matlab|char | 84,439 | <p>Use the following function: <a href="http://www.mathworks.com/help/matlab/ref/cellstr.html">http://www.mathworks.com/help/matlab/ref/cellstr.html</a></p>
<pre><code>>> B = cellstr(A)
B =
'APR'
'MAY'
>> B{1}
ans =
APR
</code></pre> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.