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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
34,948,627 | Does it make any difference to use unsafe inside or outside a loop? | <p>I never needed to use unsafe in the past, but now I need it to work with a pointer manipulating a bitmap.</p>
<p>I couldn't find any documentation that indicates otherwise, but I would like to understand better how unsafe works and if it makes any difference to use it inside or outside a loop.</p>
<p>Is it better to do:</p>
<pre><code>unsafe
{
for (int x = 0; x < maxX; x++)
{
for (int y = 0; y < maxY; y++)
{
//Unsafe pointer operations here.
}
}
}
</code></pre>
<p>Or to do?:</p>
<pre><code>for (int x = 0; x < maxX; x++)
{
for (int y = 0; y < maxY; y++)
{
unsafe
{
//Unsafe pointer operations here.
}
}
}
</code></pre> | 34,948,949 | 2 | 5 | null | 2016-01-22 14:06:50.693 UTC | 2 | 2016-01-29 04:17:27.537 UTC | 2016-01-29 04:17:27.537 UTC | null | 256,431 | null | 752,842 | null | 1 | 65 | c#|unsafe | 2,251 | <p><code>unsafe</code> keyword is a marker that you use to tell the compiler that you know what you are doing. Its main purpose is similar to documenting your code: <code>unsafe</code> block shows parts of your code that you designate as unmanaged territory; there is no impact on the actual <em>execution</em> of code.</p>
<p>With this in mind, it makes sense to reduce the size of this unsafe territory as much as possible, which means that your second approach is better than the first one.</p>
<p>It is worth mentioning that two other alternatives, i.e. marking the method and marking the class with <code>unsafe</code>, are also inferior to the approach when the unsafe block is placed around the smallest possible portion of the code.</p> |
41,194,200 | Django-filter with DRF - How to do 'and' when applying multiple values with the same lookup? | <p>This is a slightly simplified example of the filterset I'm using, which I'm using with the DjangoFilterBackend for Django Rest Framework. I'd like to be able to send a request to <code>/api/bookmarks/?title__contains=word1&title__contains=word2</code> and have results returned that contain both words, but currently it ignores the first parameter and only filters for word2. </p>
<p>Any help would be very appreciated!</p>
<pre><code>class BookmarkFilter(django_filters.FilterSet):
class Meta:
model = Bookmark
fields = {
'title': ['startswith', 'endswith', 'contains', 'exact', 'istartswith', 'iendswith', 'icontains', 'iexact'],
}
class BookmarkViewSet(viewsets.ModelViewSet):
serializer_class = BookmarkSerializer
permission_classes = (IsAuthenticated,)
filter_backends = (DjangoFilterBackend,)
filter_class = BookmarkFilter
ordering_fields = ('title', 'date', 'modified')
ordering = '-modified'
page_size = 10
</code></pre> | 41,230,820 | 3 | 5 | null | 2016-12-17 00:22:02.487 UTC | 10 | 2021-03-15 11:40:51.84 UTC | 2016-12-17 09:19:22.34 UTC | null | 4,566,267 | null | 4,566,267 | null | 1 | 11 | python|django|django-rest-framework|django-filter|django-filters | 14,179 | <p>The main problem is that you need a filter that understands how to operate on multiple values. There are basically two options:</p>
<ul>
<li>Use <code>MultipleChoiceFilter</code> (not recommended for this instance)</li>
<li>Write a custom filter class</li>
</ul>
<p><strong>Using <code>MultipleChoiceFilter</code></strong></p>
<pre class="lang-py prettyprint-override"><code>class BookmarkFilter(django_filters.FilterSet):
title__contains = django_filters.MultipleChoiceFilter(
name='title',
lookup_expr='contains',
conjoined=True, # uses AND instead of OR
choices=[???],
)
class Meta:
...
</code></pre>
<p>While this retains your desired syntax, the problem is that you have to construct a list of choices. I'm not sure if you can simplify/reduce the possible choices, but off the cuff it seems like you would need to fetch all titles from the database, split the titles into distinct words, then create a set to remove duplicates. This seems like it would be expensive/slow depending on how many records you have. </p>
<p><strong>Custom <code>Filter</code></strong></p>
<p>Alternatively, you can create a custom filter class - something like the following:</p>
<pre class="lang-py prettyprint-override"><code>class MultiValueCharFilter(filters.BaseCSVFilter, filters.CharFilter):
def filter(self, qs, value):
# value is either a list or an 'empty' value
values = value or []
for value in values:
qs = super(MultiValueCharFilter, self).filter(qs, value)
return qs
class BookmarkFilter(django_filters.FilterSet):
title__contains = MultiValueCharFilter(name='title', lookup_expr='contains')
class Meta:
...
</code></pre>
<p>Usage (notice that the values are comma-separated):</p>
<pre><code>GET /api/bookmarks/?title__contains=word1,word2
</code></pre>
<p>Result:</p>
<pre><code>qs.filter(title__contains='word1').filter(title__contains='word2')
</code></pre>
<p>The syntax is changed a bit, but the CSV-based filter doesn't need to construct an unnecessary set of choices. </p>
<p>Note that it isn't really possible to support the <code>?title__contains=word1&title__contains=word2</code> syntax as the widget can't render a suitable html input. You would either need to use <code>SelectMultiple</code> (which again, requires choices), or use javascript on the client to add/remove additional text inputs with the same <code>name</code> attribute.</p>
<hr>
<p>Without going into too much detail, filters and filtersets are just an extension of Django's forms. </p>
<ul>
<li>A <code>Filter</code> has a form <code>Field</code>, which in turn has a <code>Widget</code>.</li>
<li>A <code>FilterSet</code> is composed of <code>Filter</code>s. </li>
<li>A <code>FilterSet</code> generates an inner form based on its filters' fields.</li>
</ul>
<p>Responsibilities of each filter component:</p>
<ul>
<li>The widget retrieves the raw value from the <code>data</code> <a href="https://docs.djangoproject.com/en/1.10/ref/request-response/#django.http.QueryDict" rel="noreferrer"><code>QueryDict</code></a>. </li>
<li>The field validates the raw value. </li>
<li>The filter constructs the <code>filter()</code> call to the queryset, using the validated value. </li>
</ul>
<p>In order to apply multiple values for the same filter, you would need a filter, field, and widget that understand how to operate on multiple values. </p>
<hr>
<p>The custom filter achieves this by mixing in <code>BaseCSVFilter</code>, which in turn mixes in a "comma-separation => list" functionality into the composed field and widget classes. </p>
<p>I'd recommend looking at the source code for the CSV mixins, but in short:</p>
<ul>
<li>The <a href="https://github.com/carltongibson/django-filter/blob/1.0.1/django_filters/widgets.py#L142-L170" rel="noreferrer">widget</a> splits the incoming value into a list of values.</li>
<li>The <a href="https://github.com/carltongibson/django-filter/blob/1.0.1/django_filters/widgets.py#L142-L170" rel="noreferrer">field</a> validates the entire list of values by validating individual values on the 'main' field class (such as <code>CharField</code> or <code>IntegerField</code>). The field also derives the mixed in widget. </li>
<li>The <a href="https://github.com/carltongibson/django-filter/blob/1.0.1/django_filters/filters.py#L519-L561" rel="noreferrer">filter</a> simply derives the mixed in field class.</li>
</ul>
<p>The CSV filter was intended to be used with <code>in</code> and <code>range</code> lookups, which accept a list of values. In this case, <code>contains</code> expects a single value. The <code>filter()</code> method fixes this by iterating over the values and chaining together individual filter calls. </p> |
5,055,625 | Image Warping - Bulge Effect Algorithm | <p>Can any point to image warping algorithms? Specifically for bulge effect?</p> | 5,055,736 | 2 | 1 | null | 2011-02-20 06:28:22.217 UTC | 18 | 2015-10-21 02:47:59.223 UTC | 2014-04-19 07:36:24.187 UTC | null | 321,731 | null | 193,545 | null | 1 | 19 | image|algorithm|image-processing | 12,972 | <p>See if I understood what you want. Suppose your image coordinates go from 0 to 1. </p>
<p>If you do: </p>
<pre><code>r = Sqrt[(x - .5)^2 + (y - .5)^2]
a = ArcTan[x - .5, y - .5]
rn = r^2.5/.5
</code></pre>
<p>And then remap your pixels according to: </p>
<pre><code> x -> rn*Cos[a] + .5
y -> rn*Sin[a] + .5
</code></pre>
<p>You get: </p>
<p><a href="https://i.stack.imgur.com/uCmT4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/uCmT4.png" alt="enter image description here"></a></p>
<p>You may adjust the parameters to get bigger or smaller bulges. </p>
<p><strong>Edit</strong> </p>
<p>Let's see if I understood your comment about warping. The following images are generated using </p>
<pre><code>rn = r^k {k: 1 ... 2}:
</code></pre>
<p><a href="https://i.stack.imgur.com/Dms0m.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/Dms0m.gif" alt="enter image description here"></a></p> |
591,503 | I have a Rails task: should I use script/runner or rake? | <p>For <em>ad hoc</em> Rails tasks we have a few implementation alternatives, chief among which would seem to be:</p>
<pre><code>script/runner some_useful_thing
</code></pre>
<p>and:</p>
<pre><code>rake some:other_useful_thing
</code></pre>
<p>Which option should I prefer? If there's a clear favourite then when, if ever, should I consider using the other? If never, then why would you suppose it's still present in the framework without deprecation warnings?</p> | 591,912 | 8 | 0 | null | 2009-02-26 17:16:07.007 UTC | 18 | 2013-09-09 22:31:49.96 UTC | 2013-09-09 22:29:32.293 UTC | null | 128,421 | Mike Woodhouse | 1,060 | null | 1 | 71 | ruby-on-rails|ruby|rake | 34,377 | <p>The difference between them is that <code>script/runner</code> boots Rails whereas a Rake task doesn't unless you tell it to by making the task depend on <code>:environment</code>, like this:</p>
<pre><code>task :some_useful_task => :environment do
# do some useful task
end
</code></pre>
<p>Since booting Rails is expensive, it might be worth skipping if you can avoid it. </p>
<p>Other than that, they are roughly equivalent. I use both, but lately I've used <code>script/runner</code> executing a script separately more.</p> |
304,883 | What do I use on linux to make a python program executable | <p>I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.</p> | 304,896 | 8 | 4 | null | 2008-11-20 10:27:57.65 UTC | 20 | 2022-08-19 11:13:35.27 UTC | 2012-06-16 09:05:00.38 UTC | ΤΖΩΤΖΙΟΥ | 667,810 | clinton | null | null | 1 | 107 | python|linux|file-permissions | 230,902 | <p>Just put this in the first line of your script :</p>
<pre><code>#!/usr/bin/env python
</code></pre>
<p>Make the file executable with</p>
<pre><code>chmod +x myfile.py
</code></pre>
<p>Execute with</p>
<pre><code>./myfile.py
</code></pre> |
194,157 | C# - How to get Program Files (x86) on Windows 64 bit | <p>I'm using:</p>
<pre><code>FileInfo(
System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ProgramFiles)
+ @"\MyInstalledApp"
</code></pre>
<p>In order to determine if a program is detected on a users machine (it's not ideal, but the program I'm looking for is a right old kludge of a MS-DOS application, and I couldn't think of another method).</p>
<p>On Windows XP and 32-bit versions of Windows Vista this works fine. However, on x64 Windows Vista the code returns the x64 Program Files folder, whereas the application is installed in Program Files x86. Is there a way to programatically return the path to Program Files x86 without hard wiring "C:\Program Files (x86)"?</p> | 194,223 | 8 | 1 | null | 2008-10-11 14:53:12.563 UTC | 50 | 2019-12-25 12:14:50.373 UTC | 2016-09-29 21:23:49.737 UTC | null | 3,506,362 | null | 1,293,123 | null | 1 | 153 | c#|windows|file|64-bit | 153,574 | <p>The function below will return the x86 <code>Program Files</code> directory in all of these three Windows configurations:</p>
<ul>
<li>32 bit Windows</li>
<li>32 bit program running on 64 bit Windows</li>
<li>64 bit program running on 64 bit windows</li>
</ul>
<p> </p>
<pre><code>static string ProgramFilesx86()
{
if( 8 == IntPtr.Size
|| (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
</code></pre> |
962,729 | Is it possible to disable jsessionid in tomcat servlet? | <p>Is it possible to turnoff jsessionid in the url in tomcat? the jsessionid seems not too search engine friendly.</p> | 962,757 | 9 | 0 | null | 2009-06-07 20:17:23.637 UTC | 39 | 2022-04-07 08:41:11.48 UTC | 2017-09-05 16:50:23.473 UTC | null | 4,823,977 | null | 101,890 | null | 1 | 69 | java|tomcat|servlets|jsessionid | 80,427 | <p>You can disable for just search engines using this filter, but I'd advise <strong>using it for all responses</strong> as it's worse than just search engine unfriendly. It exposes the session ID which can be used for certain security exploits (<a href="http://randomcoder.com/articles/jsessionid-considered-harmful" rel="noreferrer">more info</a>).</p>
<p><strong>Tomcat 6 (pre 6.0.30)</strong></p>
<p>You can use the <a href="http://tuckey.org/urlrewrite/" rel="noreferrer">tuckey rewrite filter</a>.</p>
<p><a href="http://urlrewritefilter.googlecode.com/svn/trunk/src/doc/manual/3.2/guide.html" rel="noreferrer">Example config</a> for Tuckey filter:</p>
<pre><code><outbound-rule encodefirst="true">
<name>Strip URL Session ID's</name>
<from>^(.*?)(?:\;jsessionid=[^\?#]*)?(\?[^#]*)?(#.*)?$</from>
<to>$1$2$3</to>
</outbound-rule>
</code></pre>
<p><strong>Tomcat 6 (6.0.30 and onwards)</strong></p>
<p>You can use <a href="http://tomcat.apache.org/tomcat-6.0-doc/config/context.html" rel="noreferrer">disableURLRewriting</a> in the context configuration to disable this behaviour.</p>
<p><strong>Tomcat 7 and Tomcat 8</strong></p>
<p>From <a href="http://andrius.miasnikovas.lt/2010/07/whats-new-in-tomcat-7/" rel="noreferrer">Tomcat 7 onwards</a> you can add the following in the session config.</p>
<pre><code><session-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
</code></pre> |
933,212 | Is it possible to guess a user's mood based on the structure of text? | <p>I assume a natural language processor would need to be used to parse the text itself, but what suggestions do you have for an algorithm to detect a user's mood based on text that they have written? I doubt it would be very accurate, but I'm still interested nonetheless.</p>
<p>EDIT: I am by no means an expert on linguistics or natural language processing, so I apologize if this question is too general or stupid.</p> | 959,162 | 10 | 12 | null | 2009-06-01 00:43:30.14 UTC | 59 | 2017-07-28 20:13:04.323 UTC | 2009-06-01 01:23:17.643 UTC | null | 31,516 | null | 31,516 | null | 1 | 56 | algorithm|nlp | 14,290 | <p>This is the basis of an area of natural language processing called <a href="http://en.wikipedia.org/wiki/Sentiment_analysis" rel="noreferrer">sentiment analysis</a>. Although your question is general, it's certainly not stupid - this sort of research is done by Amazon on the text in product reviews for example.</p>
<p>If you are serious about this, then a simple version could be achieved by -</p>
<ol>
<li><p><strong>Acquire a corpus of positive/negative sentiment</strong>. If this was a professional project you may take some time and manually annotate a corpus yourself, but if you were in a hurry or just wanted to experiment this at first then I'd suggest looking at the <a href="http://www.cs.cornell.edu/People/pabo/movie-review-data/" rel="noreferrer">sentiment polarity corpus</a> from Bo Pang and Lillian Lee's research. The issue with using that corpus is it is not tailored to your domain (specifically, the corpus uses movie reviews), but it should still be applicable.</p></li>
<li><p><strong>Split your dataset into sentences either Positive or Negative</strong>. For the sentiment polarity corpus you could split each review into it's composite sentences and then apply the overall sentiment polarity tag (positive or negative) to all of those sentences. Split this corpus into two parts - 90% should be for training, 10% should be for test. If you're using Weka then it can handle the splitting of the corpus for you.</p></li>
<li><p><strong>Apply a machine learning algorithm</strong> (such as SVM, Naive Bayes, Maximum Entropy) to the training corpus at a word level. This model is called a <a href="http://en.wikipedia.org/wiki/Bag_of_words" rel="noreferrer">bag of words model</a>, which is just representing the sentence as the words that it's composed of. This is the same model which many spam filters run on. For a nice introduction to machine learning algorithms there is an application called <a href="http://www.cs.waikato.ac.nz/ml/weka/" rel="noreferrer">Weka</a> that implements a range of these algorithms and gives you a GUI to play with them. You can then test the performance of the machine learned model from the errors made when attempting to classify your test corpus with this model.</p></li>
<li><p><strong>Apply this machine learning algorithm to your user posts</strong>. For each user post, separate the post into sentences and then classify them using your machine learned model.</p></li>
</ol>
<p>So yes, if you are serious about this then it is achievable - even without past experience in computational linguistics. It would be a fair amount of work, but even with word based models good results can be achieved. </p>
<p>If you need more help feel free to contact me - I'm always happy to help others interested in NLP =]</p>
<hr>
<p><em>Small Notes</em> - </p>
<ol>
<li>Merely splitting a segment of text into sentences is a field of NLP - called <a href="http://en.wikipedia.org/wiki/Sentence_boundary_disambiguation" rel="noreferrer">sentence boundary detection</a>. There are a number of tools, OSS or free, available to do this, but for your task a simple split on whitespaces and punctuation should be fine.</li>
<li><a href="http://svmlight.joachims.org/" rel="noreferrer">SVMlight</a> is also another machine learner to consider, and in fact their inductive SVM does a similar task to what we're looking at - trying to classify which Reuter articles are about "corporate acquisitions" with 1000 positive and 1000 negative examples.</li>
<li>Turning the sentences into features to classify over may take some work. In this model each word is a feature - this requires tokenizing the sentence, which means separating words and punctuation from each other. Another tip is to lowercase all the separate word tokens so that "I HATE you" and "I hate YOU" both end up being considered the same. With more data you could try and also include whether capitalization helps in classifying whether someone is angry, but I believe words should be sufficient at least for an initial effort.</li>
</ol>
<hr>
<p><strong>Edit</strong></p>
<p>I just discovered LingPipe that in fact has a <a href="http://alias-i.com/lingpipe/demos/tutorial/sentiment/read-me.html" rel="noreferrer">tutorial on sentiment analysis</a> using the Bo Pang and Lillian Lee Sentiment Polarity corpus I was talking about. If you use Java that may be an excellent tool to use, and even if not it goes through all of the steps I discussed above.</p> |
1,200,214 | How can I measure the speed of code written in PHP? | <p>How can I say which class of many (which all do the same job) execute faster? is there a software to measure that?</p> | 1,202,746 | 10 | 1 | null | 2009-07-29 13:20:45.783 UTC | 71 | 2019-12-24 19:59:53.86 UTC | 2014-11-11 21:01:50.16 UTC | null | 146,197 | null | 146,197 | null | 1 | 125 | php|testing|performance|measurement | 98,840 | <p>You have <em>(at least)</em> two solutions :</p>
<p>The quite "naïve" one is using microtime(true) tobefore and after a portion of code, to get how much time has passed during its execution ; other answers said that and gave examples already, so I won"t say much more.</p>
<p>This is a nice solution if you want to benchmark a couple of instructions ; like compare two types of functions, for instance -- it's better if done thousands of times, to make sure any "perturbating element" is averaged.</p>
<p>Something like this, so, if you want to know how long it take to serialize an array :</p>
<pre><code>$before = microtime(true);
for ($i=0 ; $i<100000 ; $i++) {
serialize($list);
}
$after = microtime(true);
echo ($after-$before)/$i . " sec/serialize\n";
</code></pre>
<p>Not perfect, but useful, and it doesn't take much time to set up.</p>
<p><br></p>
<hr>
<p>The other solution, that works quite nice if you want to identify which function takes lots of time in an entire script, is to use :</p>
<ul>
<li>The <a href="http://xdebug.org/" rel="noreferrer">Xdebug</a> extension, to generate profiling data for the script</li>
<li>Software that read the profiling data, and presents you something readable. I know three of those :
<ul>
<li><a href="https://github.com/jokkedk/webgrind" rel="noreferrer">Webgrind</a> ; web interface ; should work on any Apache+PHP server</li>
<li><a href="http://sourceforge.net/projects/wincachegrind/" rel="noreferrer">WinCacheGrind</a> ; only on windows</li>
<li><a href="https://kcachegrind.github.io/html/Home.html" rel="noreferrer">KCacheGrind</a> ; probably only Linux and linux-like ; That's the one I prefer, btw</li>
</ul></li>
</ul>
<p>To get profiling files, you have to install and configure Xdebug ; take a look at the <a href="http://xdebug.org/docs/profiler" rel="noreferrer">Profiling PHP Scripts</a> page of the documentation.</p>
<p>What I generally do is not enable the profiler by default <em>(it generates quite big files, and slows things down)</em>, but use the possibility to send a parameter called <code>XDEBUG_PROFILE</code> as GET data, to activate profiling just for the page I need.
<br>The profiling-related part of my php.ini looks like this :</p>
<pre><code>xdebug.profiler_enable = 0 ; Profiling not activated by default
xdebug.profiler_enable_trigger = 1 ; Profiling activated when requested by the GET parameter
xdebug.profiler_output_dir = /tmp/ouput_directory
xdebug.profiler_output_name = files_names
</code></pre>
<p><em>(Read the documentation for more informations)</em></p>
<p>This screenshot is from a C++ program in KcacheGrind : <a href="https://i.stack.imgur.com/lB2NU.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/lB2NU.gif" alt="http://kcachegrind.sourceforge.net/html/pics/KcgShot3Large.gif"></a><br>
<sub>(source: <a href="http://kcachegrind.sourceforge.net/html/pics/KcgShot3Large.gif" rel="noreferrer">sourceforge.net</a>)</sub><br>
<br>You'll get exactly the same kind of thing with PHP scripts ;-)
<br><em>(With KCacheGrind, I mean ; WinCacheGrind is not as good as KCacheGrind...)</em></p>
<p>This allows you to get a nice view of what takes time in your application -- and it sometimes definitly helps to locate <strong>the</strong> function that is slowing everything down ^^</p>
<p>Note that Xdebug counts the CPU time spent by PHP ; when PHP is waiting for an answer from a Database (for instance), it is not working ; only waiting. So Xdebug will think the DB request doesn't take much time !
<br>This should be profiled on the SQL server, not PHP, so...</p>
<p><br>
Hope this is helpful :-)
<br>Have fun !</p> |
14,008 | Genetic Programming in C# | <p>I've been looking for some good genetic programming examples for C#. Anyone knows of good online/book resources? Wonder if there is a C# library out there for Evolutionary/Genetic programming?</p> | 1,030,053 | 12 | 0 | null | 2008-08-17 23:25:45.733 UTC | 37 | 2017-08-03 09:33:35.573 UTC | 2010-05-17 03:14:49.027 UTC | eed3si9n | 164,901 | Mac | 877 | null | 1 | 60 | c#|genetic-algorithm|genetic-programming|evolutionary-algorithm | 33,347 | <p>After developing <a href="http://code.google.com/p/evo-lisa-clone/" rel="noreferrer">my own Genetic Programming didactic application</a>, I found a complete Genetic Programming Framework called <a href="http://code.google.com/p/aforge/source/browse/#svn/trunk/Sources/Genetic" rel="noreferrer">AForge.NET Genetics</a>. It's a part of the <a href="http://code.google.com/p/aforge/" rel="noreferrer">Aforge.NET library</a>. It's licensed under LGPL.</p> |
473,782 | Inline functions in C#? | <p>How do you do "inline functions" in C#? I don't think I understand the concept. Are they like anonymous methods? Like lambda functions?</p>
<p><strong>Note</strong>: The answers almost entirely deal with the ability to <a href="http://en.wikipedia.org/wiki/Inline_expansion" rel="noreferrer">inline functions</a>, i.e. "a manual or compiler optimization that replaces a function call site with the body of the callee." If you are interested in <a href="http://en.wikipedia.org/wiki/Anonymous_function" rel="noreferrer">anonymous (a.k.a. lambda) functions</a>, see <a href="https://stackoverflow.com/a/473813/116891">@jalf's answer</a> or <a href="https://stackoverflow.com/questions/1085875/what-is-this-lambda-everyone-keeps-speaking-of/1086347#1086347">What is this 'Lambda' everyone keeps speaking of?</a>.</p> | 8,746,128 | 14 | 2 | null | 2009-01-23 17:31:07.343 UTC | 58 | 2021-11-03 07:04:57.383 UTC | 2017-05-23 12:10:48.753 UTC | null | -1 | Dinah | 356 | null | 1 | 297 | c#|optimization|inline | 208,139 | <p>Finally in .NET 4.5, the CLR allows one to hint/suggest<sup>1</sup> method inlining using <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions%28v=VS.110%29.aspx" rel="noreferrer"><code>MethodImplOptions.AggressiveInlining</code></a> value. It is also available in the Mono's trunk (committed today).</p>
<pre><code>// The full attribute usage is in mscorlib.dll,
// so should not need to include extra references
using System.Runtime.CompilerServices;
...
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void MyMethod(...)
</code></pre>
<p><strong>1</strong>. Previously "force" was used here. I'll try to clarify the term. As in the comments and the documentation, <code>The method should be inlined if possible.</code> Especially considering Mono (which is open), there are some mono-specific technical limitations considering inlining or more general one (like virtual functions). Overall, yes, this is a hint to compiler, but I guess that is what was asked for.</p> |
252,703 | What is the difference between Python's list methods append and extend? | <p>What's the difference between the list methods <code>append()</code> and <code>extend()</code>?</p> | 252,711 | 20 | 0 | null | 2008-10-31 05:55:36.407 UTC | 762 | 2022-08-26 02:01:17.767 UTC | 2019-05-21 17:18:17.983 UTC | null | 42,223 | Claudiu | 15,055 | null | 1 | 3,113 | python|list|data-structures|append|extend | 3,204,409 | <p><a href="https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types" rel="noreferrer"><code>append</code></a> appends a specified object at the end of the list:</p>
<pre><code>>>> x = [1, 2, 3]
>>> x.append([4, 5])
>>> print(x)
[1, 2, 3, [4, 5]]
</code></pre>
<p><a href="https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types" rel="noreferrer"><code>extend</code></a> extends the list by appending elements from the specified iterable:</p>
<pre><code>>>> x = [1, 2, 3]
>>> x.extend([4, 5])
>>> print(x)
[1, 2, 3, 4, 5]
</code></pre> |
1,340,434 | Get to UIViewController from UIView? | <p>Is there a built-in way to get from a <code>UIView</code> to its <code>UIViewController</code>? I know you can get from <code>UIViewController</code> to its <code>UIView</code> via <code>[self view]</code> but I was wondering if there is a reverse reference?</p> | 1,340,470 | 29 | 1 | null | 2009-08-27 11:22:45.347 UTC | 88 | 2021-09-07 19:43:20.03 UTC | 2015-05-17 22:24:25.81 UTC | null | 106,435 | null | 101,438 | null | 1 | 198 | ios|objective-c|cocoa-touch|uiview|uiviewcontroller | 150,245 | <p>Since this has been the accepted answer for a long time, I feel I need to rectify it with a better answer.</p>
<p>Some comments on the need:</p>
<ul>
<li>Your view should not need to access the view controller directly.</li>
<li>The view should instead be independent of the view controller, and be able to work in different contexts.</li>
<li>Should you need the view to interface in a way with the view controller, the recommended way, and what Apple does across Cocoa is to use the delegate pattern.</li>
</ul>
<p>An example of how to implement it follows:</p>
<pre><code>@protocol MyViewDelegate < NSObject >
- (void)viewActionHappened;
@end
@interface MyView : UIView
@property (nonatomic, assign) MyViewDelegate delegate;
@end
@interface MyViewController < MyViewDelegate >
@end
</code></pre>
<p>The view interfaces with its delegate (as <code>UITableView</code> does, for instance) and it doesn't care if its implemented in the view controller or in any other class that you end up using.</p>
<p>My original answer follows: <em>I don't recommend this, neither the rest of the answers where direct access to the view controller is achieved</em></p>
<p>There is no built-in way to do it. While you can get around it by adding a <code>IBOutlet</code> on the <code>UIView</code> and connecting these in Interface Builder, this is not recommended. The view should not know about the view controller. Instead, you should do as @Phil M suggests and create a protocol to be used as the delegate.</p> |
203,090 | How do I get current date/time on the Windows command line in a suitable format for usage in a file/folder name? | <p>Update: Now that it's 2016 I'd use PowerShell for this unless there's a really compelling backwards-compatible reason for it, particularly because of the regional settings issue with using <code>date</code>. See @npocmaka's <a href="https://stackoverflow.com/a/19799236/8479">https://stackoverflow.com/a/19799236/8479</a></p>
<hr>
<p>What's a Windows command line statement(s) I can use to get the current datetime in a format that I can put into a filename?</p>
<p>I want to have a .bat file that zips up a directory into an archive with the current date and time as part of the name, for example, <code>Code_2008-10-14_2257.zip</code>. Is there any easy way I can do this, independent of the regional settings of the machine?</p>
<p>I don't really mind about the date format, ideally it'd be yyyy-mm-dd, but anything simple is fine.</p>
<p>So far I've got this, which on my machine gives me <code>Tue_10_14_2008_230050_91</code>:</p>
<pre><code>rem Get the datetime in a format that can go in a filename.
set _my_datetime=%date%_%time%
set _my_datetime=%_my_datetime: =_%
set _my_datetime=%_my_datetime::=%
set _my_datetime=%_my_datetime:/=_%
set _my_datetime=%_my_datetime:.=_%
rem Now use the timestamp by in a new ZIP file name.
"d:\Program Files\7-Zip\7z.exe" a -r Code_%_my_datetime%.zip Code
</code></pre>
<p>I can live with this, but it seems a bit clunky. Ideally it'd be briefer and have the format mentioned earlier.</p>
<p>I'm using Windows Server 2003 and Windows XP Professional. I don't want to install additional utilities to achieve this (although I realise there are some that will do nice date formatting).</p> | 203,116 | 30 | 3 | null | 2008-10-14 22:25:34.303 UTC | 227 | 2022-09-24 16:57:17.717 UTC | 2020-11-26 19:53:53.723 UTC | Vlion | 5,047,996 | Rory | 8,479 | null | 1 | 607 | windows|datetime|batch-file|cmd | 1,588,576 | <p>See <em><a href="http://www.tech-recipes.com/rx/956/windows-batch-file-bat-to-get-current-date-in-mmddyyyy-format/" rel="noreferrer">Windows Batch File (.bat) to get current date in MMDDYYYY format</a></em>:</p>
<pre><code>@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ('time /t') do (set mytime=%%a%%b)
echo %mydate%_%mytime%
</code></pre>
<p>If you prefer the time in 24 hour/military format, you can replace the second FOR line with this:</p>
<pre><code>For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)
</code></pre>
<blockquote>
<p>C:> .\date.bat <br />
2008-10-14_0642</p>
</blockquote>
<p>If you want the date independently of the region day/month order, you can use "WMIC os GET LocalDateTime" as a source, since it's in ISO order:</p>
<pre><code>@echo off
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set ldt=%%j
set ldt=%ldt:~0,4%-%ldt:~4,2%-%ldt:~6,2% %ldt:~8,2%:%ldt:~10,2%:%ldt:~12,6%
echo Local date is [%ldt%]
</code></pre>
<blockquote>
<p>C:>test.cmd<br />
Local date is [2012-06-19 10:23:47.048]</p>
</blockquote> |
273,209 | Are memory leaks ever ok? | <p>Is it ever acceptable to have a <a href="http://en.wikipedia.org/wiki/Memory_leak" rel="noreferrer">memory leak</a> in your C or C++ application?</p>
<p>What if you allocate some memory and use it until the very last line of code in your application (for example, a global object's destructor)? As long as the memory consumption doesn't grow over time, is it OK to trust the OS to free your memory for you when your application terminates (on Windows, Mac, and Linux)? Would you even consider this a real memory leak if the memory was being used continuously until it was freed by the OS.</p>
<p>What if a third party library forced this situation on you? Would refuse to use that third party library no matter how great it otherwise might be?</p>
<p>I only see one practical disadvantage, and that is that these benign leaks will show up with memory leak detection tools as false positives.</p> | 273,287 | 50 | 5 | 2008-11-16 07:36:03.74 UTC | 2008-11-07 19:01:52.867 UTC | 77 | 2018-05-24 01:35:56.857 UTC | 2011-10-02 15:00:10.367 UTC | luke | 743,214 | Imbue | 3,175 | null | 1 | 238 | c++|c|memory-leaks | 37,505 | <p>No.</p>
<p>As professionals, the question we should not be asking ourselves is, "Is it ever OK to do this?" but rather "Is there ever a <em>good</em> reason to do this?" And "hunting down that memory leak is a pain" isn't a good reason.</p>
<p>I like to keep things simple. And the simple rule is that my program should have no memory leaks.</p>
<p>That makes my life simple, too. If I detect a memory leak, I eliminate it, rather than run through some elaborate decision tree structure to determine whether it's an "acceptable" memory leak.</p>
<p>It's similar to compiler warnings – will the warning be fatal to my particular application? Maybe not. </p>
<p>But it's ultimately a matter of professional discipline. Tolerating compiler warnings and tolerating memory leaks is a bad habit that will ultimately bite me in the rear.</p>
<p>To take things to an extreme, would it ever be acceptable for a surgeon to leave some piece of operating equipment inside a patient?</p>
<p>Although it is possible that a circumstance could arise where the cost/risk of removing that piece of equipment exceeds the cost/risk of leaving it in, and there could be circumstances where it was harmless, if I saw this question posted on SurgeonOverflow.com and saw any answer other than "no," it would seriously undermine my confidence in the medical profession.</p>
<p>–</p>
<p>If a third party library forced this situation on me, it would lead me to seriously suspect the overall quality of the library in question. It would be as if I test drove a car and found a couple loose washers and nuts in one of the cupholders – it may not be a big deal in itself, but it portrays a lack of commitment to quality, so I would consider alternatives.</p> |
6,777,910 | SQL performance on LEFT OUTER JOIN vs NOT EXISTS | <p>If I want to find a set of entries in table A but not in table B, I can use either LEFT OUTER JOIN or NOT EXISTS. I've heard SQL Server is geared towards ANSI and in some case LEFT OUTER JOINs are far more efficient than NOT EXISTS. Will ANSI JOIN perform better in this case? and are join operators more efficient than NOT EXISTS in general on SQL Server? </p> | 6,778,034 | 4 | 1 | null | 2011-07-21 14:43:02.903 UTC | 14 | 2017-07-27 15:58:20.857 UTC | null | null | null | null | 329,913 | null | 1 | 56 | sql|sql-server | 72,842 | <p>Joe's link is a good starting point. <a href="http://explainextended.com/2009/09/15/not-in-vs-not-exists-vs-left-join-is-null-sql-server/" rel="noreferrer">Quassnoi covers this too.</a></p>
<p><strong>In general,</strong> if your fields are properly indexed, OR if you expect to filter out more records (i.e. have a lots of rows <strong><code>EXIST</code></strong> in the subquery) <code>NOT EXISTS</code> will perform better.</p>
<p><code>EXISTS</code> and <code>NOT EXISTS</code> both short circuit - as soon as a record matches the criteria it's either included or filtered out and the optimizer moves on to the next record.</p>
<p><code>LEFT JOIN</code> will join <strong>ALL RECORDS</strong> regardless of whether they match or not, then filter out all non-matching records. If your tables are large and/or you have multiple <code>JOIN</code> criteria, this can be very very resource intensive.</p>
<p>I normally try to use <code>NOT EXISTS</code> and <code>EXISTS</code> where possible. For SQL Server, <code>IN</code> and <code>NOT IN</code> are semantically equivalent and may be easier to write. <strong>These are among the only operators you will find in SQL Server that are guaranteed to short circuit.</strong></p> |
6,385,243 | Is it possible to add index to a temp table? And what's the difference between create #t and declare @t | <p>I need to do a very complex query.
At one point, this query must have a join to a view that cannot be indexed unfortunately.
This view is also a complex view joining big tables.</p>
<p>View's output can be simplified as this:</p>
<pre><code>PID (int), Kind (int), Date (date), D1,D2..DN
</code></pre>
<p>where PID and Date and Kind fields are not unique (there may be more than one row having same combination of pid,kind,date), but are those that will be used in join like this</p>
<pre><code>left join ComplexView mkcs on mkcs.PID=q4.PersonID and mkcs.Date=q4.date and mkcs.Kind=1
left join ComplexView mkcl on mkcl.PID=q4.PersonID and mkcl.Date=q4.date and mkcl.Kind=2
left join ComplexView mkco on mkco.PID=q4.PersonID and mkco.Date=q4.date and mkco.Kind=3
</code></pre>
<p>Now, if I just do it like this, execution of the query takes significant time because the complex view is ran three times I assume, and out of its huge amount of rows only some are actually used (like, out of 40000 only 2000 are used)</p>
<p>What i did is declare @temptable, and insert into @temptable select * from ComplexView where Date... - one time per query I select only the rows I am going to use from my ComplexView, and then I am joining this @temptable. </p>
<p>This reduced execution time significantly.</p>
<p>However, I noticed, that if I make a table in my database, and add a clustered index on PID,Kind,Date (non-unique clustered) and take data from this table, then doing delete * from this table and insert into this table from complex view takes some seconds (3 or 4), and then using this table in my query (left joining it three times) take down query time to half, from 1 minute to 30 seconds! </p>
<p>So, my question is, first of all - is it possible to create indexes on declared @temptables.
And then - I've seen people talk about "create #temptable" syntax. Maybe this is what i need? Where can I read about what's the difference between declare @temptable and create #temptable? What shall I use for a query like mine? (this query is for MS Reporting Services report, if it matters).</p> | 6,385,272 | 5 | 0 | null | 2011-06-17 11:43:18.82 UTC | 2 | 2022-09-20 10:19:20.9 UTC | 2022-09-20 10:19:20.9 UTC | null | 799,759 | null | 787,287 | null | 1 | 25 | sql|sql-server|tsql|indexing|temp-tables | 137,443 | <p>It's not a complete answer but #table will create a temporary table that you need to drop or it will persist in your database. @table is a table variable that will not persist longer than your script.</p>
<p>Also, I think this post will answer the other part of your question.</p>
<p><a href="https://stackoverflow.com/questions/886050/sql-server-creating-an-index-on-a-table-variable">Creating an index on a table variable</a></p> |
6,911,603 | Disassemble Java JIT compiled native bytecode | <p>Is there any way to do an assembly dump of the native code generated by the Java just-in-time compiler?</p>
<p>And a related question: Is there any way to use the JIT compiler without running the JVM to compile my code into native machine code?</p> | 6,911,796 | 5 | 4 | null | 2011-08-02 11:52:43.477 UTC | 5 | 2015-10-04 12:34:39.12 UTC | 2011-08-02 11:54:03.507 UTC | null | 276,052 | null | 811,001 | null | 1 | 29 | java|compiler-construction|jvm|jit | 3,801 | <p>Yes, <a href="https://wiki.openjdk.java.net/display/HotSpot/PrintAssembly" rel="nofollow">there is a way</a> to print the generated native code (requires OpenJDK 7).</p>
<p>No, there is no way to compile your Java bytecode to native code using the JDK's JIT and save it as a native executable.</p>
<p>Even if this were possible, it would probably not as useful as you think. The JVM does some very sophisticated optimizations, and it can even de-optimize code on the fly if necessary. In other words, it's not as simple as the JIT compiles your code to native machine language, and then that native machine language will remain unchanged while the program is running. Also, this would not let you make a native executable that is independent of the JVM and runtime library.</p> |
6,792,275 | How to create custom window chrome in wpf? | <p>How can I create a basic custom window chrome for a WPF window, that doesn't include the close button and still a moveable and resizeable window?</p> | 6,792,677 | 5 | 3 | null | 2011-07-22 15:26:15.443 UTC | 42 | 2022-01-17 21:32:15.367 UTC | 2015-10-19 05:42:19.21 UTC | null | 2,771,704 | null | 416,056 | null | 1 | 45 | wpf|xaml|window | 76,400 | <p>You set your Window's <code>WindowStyle="None"</code>, then build your own window interface. You need to build in your own Min/Max/Close/Drag event handlers, but Resizing is still maintained.</p>
<p>For example:</p>
<pre><code><Window
WindowState="Maximized"
WindowStyle="None"
WindowStartupLocation="CenterScreen"
MaxWidth="{Binding Source={x:Static SystemParameters.WorkArea}, Path=Width}"
MaxHeight="{Binding Source={x:Static SystemParameters.WorkArea}, Path=Height}"
>
<DockPanel x:Name="RootWindow">
<DockPanel x:Name="TitleBar" DockPanel.Dock="Top">
<Button x:Name="CloseButton" Content="X"
Click="CloseButton_Click"
DockPanel.Dock="Right" />
<Button x:Name="MaxButton" Content="Restore"
Click="MaximizeButton_Click"
DockPanel.Dock="Right" />
<Button x:Name="MinButton" Content="Min"
Click="MinimizeButton_Click"
DockPanel.Dock="Right" />
<TextBlock HorizontalAlignment="Center">Application Name</TextBlock>
</DockPanel>
<ContentControl Content="{Binding CurrentPage}" />
</DockPanel>
</Window>
</code></pre>
<p>And here's some example code-behind for common window functionality</p>
<pre class="lang-cs prettyprint-override"><code>/// <summary>
/// TitleBar_MouseDown - Drag if single-click, resize if double-click
/// </summary>
private void TitleBar_MouseDown(object sender, MouseButtonEventArgs e)
{
if(e.ChangedButton == MouseButton.Left)
if (e.ClickCount == 2)
{
AdjustWindowSize();
}
else
{
Application.Current.MainWindow.DragMove();
}
}
/// <summary>
/// CloseButton_Clicked
/// </summary>
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
}
/// <summary>
/// MaximizedButton_Clicked
/// </summary>
private void MaximizeButton_Click(object sender, RoutedEventArgs e)
{
AdjustWindowSize();
}
/// <summary>
/// Minimized Button_Clicked
/// </summary>
private void MinimizeButton_Click(object sender, RoutedEventArgs e)
{
this.WindowState = WindowState.Minimized;
}
/// <summary>
/// Adjusts the WindowSize to correct parameters when Maximize button is clicked
/// </summary>
private void AdjustWindowSize()
{
if (this.WindowState == WindowState.Maximized)
{
this.WindowState = WindowState.Normal;
MaxButton.Content = "1";
}
else
{
this.WindowState = WindowState.Maximized;
MaxButton.Content = "2";
}
}
</code></pre> |
6,417,055 | Download files and store them locally with Phonegap/jQuery Mobile Android and iOS Apps | <p>I wrote an jQuery Mobile app and packaged it with Phonegap to iOS and Android apps.</p>
<p>At this point I am using locally stored json files to read data.</p>
<p>I would like to update these json files from time to time by downloading newer json files from a server.</p>
<p>How can I get the json from the server and store the json files to the local file system of Android and iOS?</p>
<p>Cheers
Johe</p> | 8,278,760 | 6 | 1 | null | 2011-06-20 20:26:40.833 UTC | 30 | 2017-02-22 07:12:24.493 UTC | null | null | null | null | 268,125 | null | 1 | 43 | android|ios|cordova|jquery-mobile | 96,173 | <p>This is how I solved it. First set the file paths, wich are different for Android and iOS</p>
<pre><code>var file_path;
function setFilePath() {
if(detectAndroid()) {
file_path = "file:///android_asset/www/res/db/";
//4 Android
} else {
file_path = "res//db//";
//4 apache//iOS/desktop
}
}
</code></pre>
<p>Then I load my JSON files, wich are prepackaged with the app, into the local browser storage. Like this:</p>
<pre><code>localStorage["my_json_data"] = loadJSON(file_path + "my_json_data.json");
function loadJSON(url) {
return jQuery.ajax({
url : url,
async : false,
dataType : 'json'
}).responseText;
}
</code></pre>
<p>If I wanna update my data. I get the new JSON Data from the server and push it into the local storage. If the server is on a different domain, which is the case most of the time, you have to make a JSONP call (check jQuery's docs on <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">JSONP</a>).
I did it kinda like this:</p>
<pre><code>$.getJSON(my_host + 'json.php?function=' + my_json_function + '&callback=?', function (json_data) {
//write to local storage
localStorage["my_json_data"] = JSON.stringify(json_data);
});
</code></pre> |
6,598,945 | Detect if function is native to browser | <p>I am trying to iterate over all the globals defined in a website, but in doing so I am also getting the native browser functions. </p>
<pre><code>var numf=0; var nump=0; var numo=0;
for(var p in this) {
if(typeof(this[p]) === "function"){
numf+=1;
console.log(p+"()");
} else if(typeof p != 'undefined'){
nump+=1;
console.log(p);
} else {
numo+=1;
console.log(p);
}
}
</code></pre>
<p>Is there a way to determine if a function is native to the browser or created in a script?</p> | 6,599,105 | 7 | 0 | null | 2011-07-06 15:26:38.227 UTC | 8 | 2022-08-02 08:29:02.117 UTC | null | null | null | null | 143,074 | null | 1 | 29 | javascript|global-variables | 8,221 | <p>You can call the inherited <code>.toString()</code> function on the methods and check the outcome. Native methods will have a block like <code>[native code]</code>.</p>
<pre><code>if( this[p].toString().indexOf('[native code]') > -1 ) {
// yep, native in the browser
}
</code></pre>
<hr>
<p>Update because a lot of commentators want some clarification and people really have a requirement for such a detection. To make this check really save, we should probably use a line line this:</p>
<pre><code>if( /\{\s+\[native code\]/.test( Function.prototype.toString.call( this[ p ] ) ) ) {
// yep, native
}
</code></pre>
<p>Now we're using the <code>.toString</code> method from the <code>prototype</code> of <code>Function</code> which makes it very unlikely if not impossible some other script has overwritten the <code>toString</code> method. Secondly we're checking with a regular expression so we can't get fooled by comments within the function body.</p> |
6,700,717 | ArrayIndexOutOfBoundsException when using the ArrayList's iterator | <p>Right now, I have a program containing a piece of code that looks like this:</p>
<pre><code>while (arrayList.iterator().hasNext()) {
//value is equal to a String value
if( arrayList.iterator().next().equals(value)) {
// do something
}
}
</code></pre>
<p>Am I doing that right, as far as iterating through the ArrayList goes?</p>
<p>The error I am getting is:</p>
<pre><code>java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.get(Unknown Source)
at main1.endElement(main1.java:244)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at main1.traverse(main1.java:73)
at main1.traverse(main1.java:102)
at main1.traverse(main1.java:102)
at main1.main(main1.java:404)
</code></pre>
<p>I would show the rest of the code, but it's pretty extensive, and if I am not doing the iteration correctly, I would assume the only possibility is that I am not initializing the <code>ArrayList</code> properly.</p> | 6,700,737 | 8 | 1 | null | 2011-07-14 22:29:32.347 UTC | 27 | 2016-02-18 00:30:06.7 UTC | 2016-02-18 00:30:06.7 UTC | null | 1,079,354 | null | 810,860 | null | 1 | 102 | java|arraylist|iterator|indexoutofboundsexception | 393,896 | <blockquote>
<p>Am I doing that right, as far as iterating through the Arraylist goes?</p>
</blockquote>
<p>No: by calling <code>iterator</code> twice in each iteration, you're getting new iterators all the time.</p>
<p>The easiest way to write this loop is using the <a href="http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html">for-each</a> construct:</p>
<pre><code>for (String s : arrayList)
if (s.equals(value))
// ...
</code></pre>
<p>As for</p>
<blockquote>
<p><code>java.lang.ArrayIndexOutOfBoundsException: -1</code></p>
</blockquote>
<p>You just tried to get element number <code>-1</code> from an array. Counting starts at zero.</p> |
38,376,351 | No module named 'pandas' in Pycharm | <p>I read all the topics about, but I cannot solve my problem:</p>
<pre><code> Traceback (most recent call last):
File "/home/.../.../.../reading_data.py", line 1, in <module>
import pandas as pd
ImportError: No module named pandas
</code></pre>
<p>This is my environment:</p>
<p>Ubuntu 14.04</p>
<p>Pycharm version: 2016.1.4</p>
<p>Python version: 2.7.10</p>
<p>Pandas version: 0.18.1</p>
<p>Pandas works in Anaconda, in Jupyter too. How to fix the problem?</p> | 38,382,116 | 4 | 1 | null | 2016-07-14 14:03:48.05 UTC | 1 | 2022-08-04 09:58:19.78 UTC | 2022-08-04 09:58:19.78 UTC | null | 4,685,471 | null | 6,478,396 | null | 1 | 15 | python|pandas|module|pycharm|sklearn-pandas | 88,930 | <p>Have you select the project interpreter for your current project?
<a href="https://www.jetbrains.com/help/pycharm/2016.1/configuring-python-interpreter-for-a-project.html" rel="noreferrer">https://www.jetbrains.com/help/pycharm/2016.1/configuring-python-interpreter-for-a-project.html</a></p>
<p>follow this link, check whether pandas listed in the packages.</p> |
15,887,885 | Converting a one-item list to an integer | <p>I've been asked to accept a list of integers (x), add the first value and the last value in the list, and then return an integer with the sum. I've used the following code to do that, but the problem I have is that when I try to evaluate the sum it's actually a one-item list instead of an integer. I've tried to cast it to an int but I can't seem to get it to work. </p>
<pre><code>def addFirstAndLast(x):
lengthOfList = len(x)
firstDigit = x[0:1]
lastDigit = x[lengthOfList:lengthOfList-1]
sum = firstDigit + lastDigit
return sum
</code></pre> | 15,887,903 | 4 | 1 | null | 2013-04-08 20:01:45.957 UTC | 3 | 2019-11-05 23:06:04.643 UTC | 2013-04-08 20:02:18.817 UTC | null | 830,012 | null | 1,883,103 | null | 1 | 16 | python | 48,357 | <h1>Use indexes</h1>
<p>You're slicing the list, which return lists. Here, you should use indexes instead:</p>
<pre><code>firstDigit = x[0]
lastDigit = x[-1]
</code></pre>
<hr>
<h1>Why is slicing wrong for you:</h1>
<p>When you do <code>x[0:1]</code>, you're taking the <strong>list of items</strong> from the beginning of the list to the first interval.</p>
<pre><code> item0, item1, item2, item3
^ interval 0
^ interval 1
^ interval 2
^ interval 3
</code></pre>
<p>Doing <code>x[0:2]</code>, for example, would return items 0 and 1.</p> |
16,013,545 | How do I erase elements from STL containers? | <p>How do I erase elements from STL containers, having a specified <em>value</em>, or satisfying some <em>condition</em>?</p>
<p>Is there a single common or uniform way of doing that for different kinds of containers?</p> | 16,013,546 | 1 | 3 | null | 2013-04-15 11:03:13.68 UTC | 29 | 2014-06-14 10:11:42.84 UTC | 2014-02-10 11:00:55.34 UTC | null | 1,629,821 | null | 1,629,821 | null | 1 | 41 | c++|c++11|stl|std | 10,581 | <p>Unfortunately, there isn't a single <em>uniform</em> interface or pattern for erasing elements from STL containers.
But three behaviors emerge:</p>
<h2>std::vector Pattern</h2>
<p>To erase elements that fulfill a certain condition from a <strong><code>std::vector</code></strong>, a common technique is the so called <a href="http://en.wikipedia.org/wiki/Erase-remove_idiom" rel="noreferrer"><strong>erase-remove idiom</strong></a>. </p>
<p>If <code>v</code> is an instance of <code>std::vector</code>, and we want to erase elements with value <code>x</code> from the vector, code like this can be used:</p>
<pre><code>// Erase elements having value "x" from vector "v"
v.erase( std::remove(v.begin(), v.end(), x), v.end() );
</code></pre>
<p>If the criterion to be fulfilled for erasing elements is more complex than the simple <em>"element to be erased == x"</em>, the <code>std::remove_if()</code> algorithm can be used instead of <code>std::remove()</code>:</p>
<pre><code>// Erase elements matching "erasing_condition" from vector "v"
v.erase( std::remove_if(v.begin(), v.end(), erasing_condition), v.end() );
</code></pre>
<p>where <code>erasing_condition</code> is a unary predicate, that can be expressed in several forms: e.g. it can be a <strong><code>bool</code>-returning function</strong> taking vector element type as input (so if the returned value is <code>true</code>, the element will be erased from the vector; if it's <code>false</code>, it won't); or it can be expressed <em>in-line</em> as a <strong>lambda</strong>; it can be a <a href="https://stackoverflow.com/questions/356950/c-functors-and-their-uses"><strong>functor</strong></a>; etc.</p>
<p>(Both <code>std::remove()</code> and <code>std::remove_if()</code> are generic algorithms from <code><algorithm></code> header.)</p>
<p>Here is a clear explanation <a href="http://en.wikipedia.org/wiki/Erase-remove_idiom" rel="noreferrer">from Wikipedia</a>:</p>
<blockquote>
<p>The <code>algorithm</code> library provides the <code>remove</code> and <code>remove_if</code>
algorithms for this. Because these algorithms operate on a range of
elements denoted by two forward iterators, they have no knowledge of
the underlying container or collection. Thus, no elements are actually
removed from the container. Rather, all elements which don't fit the
remove criteria are brought together to the front of the range, in the
same relative order. The remaining elements are left in a valid, but
unspecified state. When this is done, <code>remove</code> returns an iterator
pointing one past the last unremoved element.</p>
<p>To actually eliminate elements from the container, <code>remove</code> is combined
with the container's <code>erase</code> member function, hence the name
"erase-remove idiom".</p>
</blockquote>
<p>Basically, <code>std::remove()</code> and <code>std::remove_if()</code> compact the elements that do <em>not</em> satisfy the erasing criteria to the front of the range (i.e. to the beginning of the <code>vector</code>), and then <code>erase()</code> actually eliminates the remaining elements from the container.</p>
<p>This pattern applies also to other containers like <strong><code>std::deque</code></strong>.</p>
<h2>std::list Pattern</h2>
<p>To erase elements from a <strong><code>std::list</code></strong>, simple <strong><code>remove()</code> and <code>remove_if()</code> methods</strong> are available:</p>
<pre><code>// Erase elements having value "x" from list "l"
l.remove( x )
// Erase elements satisfying "erasing_condition" from list "l"
l.remove_if( erasing_condition );
</code></pre>
<p>(Where <code>erasing_condition</code> is a unary predicate, with the same characteristics discussed for <code>std::remove_if()</code> in the above section.)</p>
<p>The same pattern can be applied to similar containers, like <strong><code>std::forward_list</code></strong>. </p>
<h2>Associative Containers (e.g. std::map, std::set, ...) Pattern</h2>
<p><em>Associative containers</em> like <strong><code>std::map</code></strong>, <strong><code>std::set</code></strong>, <strong><code>std::unordered_map</code></strong>, etc. follow the common pattern described here:</p>
<ol>
<li><p>If the erasing condition is a simple key-matching (i.e. <em>"erase the element
having key x"</em>), then a simple <strong><code>erase()</code> method</strong> can be called:</p>
<pre><code>// Erase element having key "k" from map "m":
m.erase( k );
</code></pre></li>
<li><p>If the erasing condition is more complex, and is expressed by some custom
unary predicate (e.g. <em>"erase all odd elements"</em>), then a <code>for</code> loop can be used
(with an explicit erasing condition checking in loop body, and call to <code>erase(iterator)</code> method):</p>
<pre><code>//
// Erase all elements from associative container "c", satisfying "erasing_condition":
//
for (auto it = c.begin(); it != c.end(); /* "it" updated inside loop body */ )
{
if ( erasing_condition(*it) )
{
// Erase the element matching the specified condition
// from the associative container.
it = c.erase(it);
// Note:
// erase() returns an iterator to the element
// that follows the last element removed,
// so we can continue the "for" loop iteration from that position.
}
else
{
// Current element does _not_ satisfy erasing condition,
// so we can just move on to the next element.
++it;
}
}
</code></pre></li>
</ol>
<h2>The Need for a Unified Approach</h2>
<p>As it can be noted from the above analysis, unfortunately there isn't a uniform common approach for erasing elements from STL containers.</p>
<p>The following table summarizes the aforementioned patterns:</p>
<blockquote>
<pre><code>----------------+------------------------------------------
Container | Erasing Pattern
----------------+------------------------------------------
|
vector | Use erase-remove idiom.
deque |
|
----------------+------------------------------------------
|
list | Call remove()/remove_if() methods.
forward_list |
|
----------------+------------------------------------------
|
map | Simple erase(key) method call,
set | or
unordered_map | loop through the container,
multimap | and call erase(iterator) on matching
| condition.
... |
|
----------------+------------------------------------------
</code></pre>
</blockquote>
<p>Writing different specific code based on the particular container is error-prone, hard to maintain, hard to read, etc.</p>
<p>However, it's possible to write function templates with common names (e.g. <code>erase()</code> and <code>erase_if()</code>) <em>overloaded</em> for different container types, and embed the aforementioned pattern implementations in those functions.<br>
So, the client can simply call those <code>erase()</code> and <code>erase_if()</code> generic functions, and the compiler will dispatch the call to proper implementation (at <em>compile time</em>), based on container type.</p>
<p>A more elegant approach, using a template meta-programming technique, is presented <a href="http://channel9.msdn.com/Series/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-/C9-Lectures-Stephan-T-Lavavej-Standard-Template-Library-STL-3-of-n#c634173340820000000" rel="noreferrer">by <strong>Stephan T. Lavavej</strong> here</a>.</p> |
16,037,165 | Displaying a number in Indian format using Javascript | <p>I have the following code to display in Indian numbering system. </p>
<pre><code> var x=125465778;
var res= x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
</code></pre>
<p>Am getting this output :<code>125,465,778</code>.</p>
<p>I need output like this: <code>12,54,65,778</code>.</p>
<p>Please help me to sort out this problem .</p> | 16,037,650 | 15 | 4 | null | 2013-04-16 12:32:32.073 UTC | 20 | 2021-12-24 11:00:58.087 UTC | 2016-06-08 08:36:08.043 UTC | null | 4,029,525 | null | 1,343,736 | null | 1 | 54 | javascript|jquery|number-systems | 78,000 | <p>For Integers:</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> var x=12345678;
x=x.toString();
var lastThree = x.substring(x.length-3);
var otherNumbers = x.substring(0,x.length-3);
if(otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree;
alert(res);</code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/XBtaw/" rel="noreferrer">Live Demo</a></p>
<p>For float:</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> var x=12345652457.557;
x=x.toString();
var afterPoint = '';
if(x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'),x.length);
x = Math.floor(x);
x=x.toString();
var lastThree = x.substring(x.length-3);
var otherNumbers = x.substring(0,x.length-3);
if(otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
alert(res);</code></pre>
</div>
</div>
</p>
<p><a href="http://jsfiddle.net/XBtaw/1/" rel="noreferrer">Live Demo</a></p> |
36,236,181 | How to remove title bar from the android activity? | <p>Can someone please help me with the issue.I want my activity as full screen and want to remove title from the screen.I have tried several ways but not able to remove it.</p>
<p>Activity Code :</p>
<pre><code>public class welcomepage extends Activity {
private Button btn;
EditText userName,passWord;
DatabaseHandler dbHandler;
Context ctx =this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_welcomepage);
}
}
</code></pre>
<p>And Activity.xml </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:background="@drawable/pic1"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.edkul.vimal.edkul.welcomepage">
</RelativeLayout>
</code></pre>
<p>I want to remove the title bar displayed in blue color .Please find the image for the reference :</p>
<p><a href="https://i.stack.imgur.com/aT6wr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aT6wr.png" alt="enter image description here"></a></p>
<p>AndroidManifest.xml</p>
<pre><code><application
android:minSdkVersion="3"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.NoActionBar">
<activity
android:name=".welcomepage"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</code></pre> | 46,709,914 | 8 | 9 | null | 2016-03-26 14:04:28.083 UTC | 23 | 2022-06-04 18:53:46.2 UTC | 2019-03-22 12:42:47.013 UTC | null | 6,296,561 | null | 3,959,477 | null | 1 | 62 | android|android-layout | 135,657 | <p>Try this: </p>
<p><strong><em>this.getSupportActionBar().hide();</em></strong></p>
<pre><code>@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
this.getSupportActionBar().hide();
}
catch (NullPointerException e){}
setContentView(R.layout.activity_main);
}
</code></pre> |
10,276,074 | WPF - choose startup window based on some condition | <p>When running my program by clicking <code>Run</code> or pressing <code>Ctrl + F5</code>, is it possible to open different windows based on some check condition?</p>
<p>I.e if some condition is satisfied I wish to open a particular window, but if its not I want to open another window.</p>
<p>It should be like before opening any window it should first check for the condition like</p>
<pre><code>if(File.Exists(<path-to-file>)
Open Window 1
else
Open Window 2
</code></pre>
<p>Is this possible?</p> | 10,276,293 | 4 | 3 | null | 2012-04-23 06:57:26.73 UTC | 9 | 2020-07-11 07:22:55.257 UTC | 2016-10-13 17:33:19.75 UTC | null | 4,671,754 | null | 942,533 | null | 1 | 36 | c#|.net|wpf|wpf-controls | 33,198 | <p>look into App.xaml</p>
<p>remove <code>StartupUri="MainWindow.xaml"</code></p>
<p>add <code>Startup="Application_Startup"</code> new event Handler</p>
<pre><code><Application x:Class="YourProject.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="Application_Startup">
</code></pre>
<p>form code behind App.xaml.cs create Application_Startup like...</p>
<pre><code> private void Application_Startup(object sender, StartupEventArgs e)
{
//add some bootstrap or startup logic
var identity = AuthService.Login();
if (identity == null)
{
LoginWindow login = new LoginWindow();
login.Show();
}
else
{
MainWindow mainView = new MainWindow();
mainView.Show();
}
}
</code></pre> |
10,704,444 | Get File Path of A File In Your Current Project | <p>How do I programmically get the File Path of a File In my project?</p>
<pre><code> string fileContent = File.ReadAllText(LocalConstants.EMAIL_PATH);
</code></pre>
<p>The EMAIL_PATH I added to my project as a text file. This line of code throws an exception because by default it is looking in the system32 folder for some reason. I need to set it to the projects directory.</p> | 10,704,508 | 3 | 4 | null | 2012-05-22 14:48:49.883 UTC | 1 | 2016-01-06 21:22:40.643 UTC | null | null | null | null | 245,926 | null | 1 | 16 | c# | 54,896 | <p>You could use <a href="http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx"><code>Path.Combine</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.basedirectory.aspx"><code>AppDomain.CurrentDomain.BaseDirectory</code></a>:</p>
<pre><code>string fileName = "SampleFile.txt";
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, LocalConstants.EMAIL_PATH, fileName);
</code></pre>
<p>Returns in a test project in debug mode this path(when <code>LocalConstants.EMAIL_PATH="Emails"</code>):</p>
<pre><code>C:\****\****\Documents\Visual Studio 2010\Projects\WindowsApplication1\WindowsFormsApplication1\bin\Debug\Emails\SampleFile.txt
</code></pre> |
10,396,552 | Do I need to re-use the same Akka ActorSystem or can I just create one every time I need one? | <p>Akka 2.x requires many commands to reference an <code>ActorSystem</code>. So, to create an instance of an actor <code>MyActor</code> you might say:</p>
<pre class="lang-scala prettyprint-override"><code>val system = ActorSystem()
val myActor = system.actorOf(Props[MyActor])
</code></pre>
<p>Because of the frequent need for an <code>ActorSystem</code>: many code examples omit the creation from the code and assume that the reader knows where a <code>system</code> variable has come from. </p>
<p>If your code produces actors in different places, you could duplicate this code, possibly creating additional <code>ActorSystem</code> instances, or you could try to share the same <code>ActorSystem</code> instance by referring to some global or by passing the <code>ActorSystem</code> around.</p>
<p>The Akka documentation provides a <a href="http://doc.akka.io/docs/akka/2.0.1/general/actor-systems.html">general overview of systems of actors</a> under the heading 'Actor Systems', and there is <a href="http://doc.akka.io/api/akka/2.0.1/#akka.actor.ActorSystem">documentation of the <code>ActorSystem</code> class</a>. But neither of these help a great deal in explaining why a user of Akka can't just rely on Akka to manage this under-the-hood.</p>
<h2>Question(s)</h2>
<ul>
<li><p>What are the implications of sharing the same <code>ActorSystem</code> object or creating a new one each time?</p></li>
<li><p>What are the best practices here? Passing around an <code>ActorSystem</code> all the time seems surprisingly heavy-handed.</p></li>
<li><p>Some examples give the <code>ActorSystem</code> a name: <code>ActorSystem("MySystem")</code> others just call <code>ActorSystem()</code>. What difference does this make, and what if you use the same name twice?</p></li>
<li><p>Does <code>akka-testkit</code> require that you share a common <code>ActorSystem</code> with the one you pass to the <code>TestKit</code> constructor?</p></li>
</ul> | 10,397,403 | 2 | 4 | null | 2012-05-01 10:39:00.887 UTC | 18 | 2016-03-19 04:33:52.133 UTC | null | null | null | null | 67,159 | null | 1 | 62 | scala|akka | 13,956 | <p>Creating an ActorSystem is very expensive, so you want to avoid creating a new one each time you need it. Also your actors should run in the same ActorSystem, unless there is a good reason for them not to. The name of the ActorSystem is also part the the path to the actors that run in it. E.g. if you create an actor in a system named <code>MySystem</code> it will have a path like <code>akka://MySystem/user/$a</code>. If you are in an actor context, you always have a reference to the ActorSystem. In an Actor you can call <code>context.system</code>. I don't know what akka-testkit expects, but you could take a look at the akka tests. </p>
<p>So to sum it up, you should always use the same system, unless there is a good reason not to do so.</p> |
31,839,754 | How to change the check box (tick box) color to white in android XML | <p>Is there any way to change the check box (tick box) color to white in android XML. (I need white color tick box which contain black tick, as the preview I got in android studio inside my real device)</p>
<p>Here is my code for check box </p>
<pre><code><CheckBox
android:textSize="15sp"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Loging "
android:id="@+id/checkBox"
android:layout_below="@id/PasswordeditText"
android:checked="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:buttonTint="#fff" />
</code></pre>
<p>When I add <code>android:buttonTint="#fff"</code> preview show the change I need, but it doesn't work in real device</p>
<p>Design preview </p>
<p><a href="https://i.stack.imgur.com/HAsIU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HAsIU.png" alt="enter image description here"></a></p>
<p>Real Device </p>
<p><a href="https://i.stack.imgur.com/xDESd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xDESd.png" alt="enter image description here"></a></p>
<p>Is there any attribute like <code>android:buttonTint</code> which I can use to achieve the changes in real device. </p> | 31,840,734 | 7 | 2 | null | 2015-08-05 18:06:55.123 UTC | 1 | 2021-04-17 08:09:11.263 UTC | 2017-09-30 10:33:38.197 UTC | null | 5,650,328 | null | 1,528,623 | null | 1 | 20 | android|xml | 58,594 | <p>Set the <code>colorAccent</code> to your desired color:</p>
<pre><code><style name="AppTheme" parent="Theme.AppCompat">
<item name="colorAccent">#fff</item>
</style>
</code></pre>
<p>Or if you don't want to change your main theme, create a new theme and apply it only to the checkbox:</p>
<pre><code><style name="WhiteCheck">
<item name="colorAccent">#fff</item>
</style>
</code></pre>
<hr>
<pre><code><CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:theme="@style/WhiteCheck"/>
</code></pre> |
33,279,680 | What are the disadvantages of using Event sourcing and CQRS? | <p>Event sourcing and CQRS is great because it gets rids developers being stuck with one pre-modelled database which the developer has to work with for the lifetime of the application unless there is a big data migration project. CQRS and ES also has other benefits like scaling eventstore, audit log etc. that are already all over the internet.</p>
<p><strong>But what are the disadvantages ?</strong></p>
<p>Here are some disadvantages that I can think of after researching and writing small demo apps</p>
<ol>
<li><strong>Complex:</strong> Some people say ES is complex. But I'd say having a complex application is better than a complex database model on which you can only run very restricted queries using a query language (multiple joins, indexes etc). I mean some programming languages like Scala have very rich collection library that is very flexible to produce some seriously complex aggregations and also there is Apache Spark which makes it easy query distributed collections. But databases will always be restricted to it's query language capabilities and distributing databases are harder then distributed application code <em>(Just deploy another instance on another machine!)</em>. </li>
<li><strong>High disk space usage</strong>: Event store might end up using a lot of disk space to store events. But we can schedule a clean up every few weeks and creating snapshot and may be we can store historical events locally on an external HD just incase we need old events in the future ? </li>
<li><strong>High memory usage</strong>: State of every domain object is stored in memory which might increase RAM usage and we all how expensive RAM is. <strong>BIG PROBLEM!!</strong> because I'm poor! any solution to this ? May be use Sqlite instead of storing state in memory ? Am I making things more complex by introducing multiple Sqlite instances in my application ? </li>
<li><strong>Longer bootup time</strong>: On failure or software upgrade bootup is slow depending on the number of events. But we can use snapshots to solve this ?</li>
<li><strong>Eventual consistency</strong>: Problem for some applications. Imagine if Facebook used Event sourcing with CQRS for storing posts and considering how busy facebook's system is and if I posted a post I would see my fb post the next day :)</li>
<li><strong>Serialized events in Event store</strong>: Event stores store events as serialized objects which means we can't query the content of events in the event store which is discouraged anyway. And we won't be able to add another attribute to the event in the future. Solution would be to store events as JSON objects instead of Serialized events ? But is that a good idea ? Or add more Events to support the change to orignal event object ? </li>
</ol>
<p>Can someone please comment on the disadvantages I brought up here and correct me if I am wrong and suggest any other I may have missed out ? </p> | 33,305,980 | 5 | 9 | null | 2015-10-22 11:14:06.633 UTC | 23 | 2021-07-22 20:00:06.91 UTC | 2015-10-22 11:36:48.373 UTC | null | 1,378,771 | null | 1,378,771 | null | 1 | 58 | cqrs|event-sourcing | 19,643 | <p>Here is my take on this.</p>
<ol>
<li><p>CQRS + ES can make things a lot simpler in complex software systems by having rich domain objects, simple data models, history tracking, more visibility into concurrency problems, scalability and much more. It does require a different way thinking about the systems so it could be difficult to find qualified developers. But CQRS makes it simpler to separate responsibilities across developers. For example, a junior developer can work purely with the read side without having to touch business logic.</p></li>
<li><p>Copies of data will require more disk space for sure. But storage is relatively cheap these days. It may require the IT support team to do more backups and planning how to restore the system in a case in things go wrong. However, server virtualization these days makes it a more streamlined workflow. Also, it is much easier to create redundancy in the system without a monolithic database.</p></li>
<li><p>I do not consider higher memory usage a problem. Business object hydration should be done on demand. Objects should not keep references to events that have already been persisted. And event hydration should happen only when persisting data. On the read side you do not have Entity -> DTO -> ViewModel conversions that usually happened in tiered systems, and you would not have any kind of object change tracking that full featured ORMs usually do. Most systems perform significantly more reads than writes.</p></li>
<li><p>Longer boot up time can be a slight problem if you are using multiple heterogeneous databases due to initialization of various data contexts. However, if you are using something simple like ADO .NET to interact with the event store and a micro-ORM for the read side, the system will "cold start" faster than any full featured ORM. The important thing here is not to over-complicate how you access the data. That is actually a problem CQRS is supposed to solve. And as I said before, the read side should be modeled for the views and not have any overhead of re-mapping data.</p></li>
<li><p>Two-phase commit can work well for systems that do not need to scale for thousands of users in my experience. You would need to choose databases that would work well with the distributed transaction coordinator. PostgreSQL can work well for read and write separate models, for example. If the system needs to scale for a high number of concurrent users, it would have to be designed with eventual consistency in mind. There are cases where you would have aggregate roots or context boundaries that do not use CQRS to avoid eventual consistency. It makes sense for non-collaborative parts of the domain.</p></li>
<li><p>You can query events in serialized a format like JSON or XML, if you choose the right database for the event store. And that should be only done for purposes of analytics. Nothing inside the system should query event store by anything other than the aggregate root id and the event type. That data would be indexed and live outside the serialized event.</p></li>
</ol> |
56,661,844 | Error in Postman 500 Internal server error api | <p>i'm building an api using flask for a web
i already have a database and the GET request works but when i try POST it gives me This error</p>
<blockquote>
<p>500 INTERNAL SERVER ERROR</p>
</blockquote>
<p>This is the code i wrote</p>
<pre><code>#User_schema
class UserSchema(ma.Schema):
class Mata:
fields = ('id', 'name', 'Email', 'Pass', 'Phone', 'Department', 'Major')
#init_schema
user_schema = UserSchema()
users_schema = UserSchema(many=True)
#create user
@app.route('/user', methods=['POST'])
def add_User():
#id = request.json['id']
name = request.json['name']
Email = request.json['Email']
Pass = request.json['Pass']
#Phone = request.json['Phone']
Department = request.json['Department']
Major = request.json['Major']
new_user = User(name, Email, Pass, Department, Major)
db.session.add(new_user)
db.session.commit()
return user_schema.jsonify(new_user)
</code></pre>
<p>this is the request i added on post man</p>
<pre><code>{
"name": "User 1",
"Email": "[email protected]",
"Pass": "qq1",
"Phone": "0551",
"Department": "IT 1",
"Major": "IT 1"
}
</code></pre>
<p>i'm also using a local server
i looked at other links and everyone is asking for the logs and if i'm not wrong i think i get them from</p>
<blockquote>
<p>View > Developer > Show DevTools > Console</p>
</blockquote>
<p>and this is a screenshot of the log: (i think)</p>
<p><a href="https://i.stack.imgur.com/x0HhH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x0HhH.jpg" alt="enter image description here"></a></p>
<p>what exactly is the problem here i don't get it</p>
<p>EDIT: Here is the full code:</p>
<pre><code>from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import os
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.db'
app.config['SQLALCHEMY_TRACK_MODIFICATION'] = False
db = SQLAlchemy(app)
ma = Marshmallow(app)
class User (db.Model):
id = db.Column(db.Integer,primary_key=True)
name = db.Column(db.String(30))
Email = db.Column(db.String(30))
Pass = db.Column(db.String(30))
Phone = db.Column(db.Integer)
Department = db.Column(db.String(30))
Major = db.Column(db.String(30))
meeting = db.relationship('Meeting', backref='creator')
meetingroom = db.relationship('MeetingRoom', backref='reserver')
def _init_(self, name, Email, Pass, Phone, Department, Major):
self.name = name
self.Email = Email
self.Pass = Pass
self.Phone = Phone
self.Department = Department
self.Major = Major
class MeetingRoom (db.Model):
mrid = db.Column(db.Integer,primary_key=True)
reserver_id = db.Column(db.Integer, db.ForeignKey('user.id'))
#meetingm = db.relationship('Meeting', backref='roomno')
mid = db.Column(db.Integer, db.ForeignKey('meeting.Mid'))
class Meeting (db.Model):
Mid = db.Column(db.Integer,primary_key=True)
Mname = db.Column(db.String(100))
Des = db.Column(db.String(100))
Date = db.Column(db.String(20))
creator_id = db.Column(db.Integer, db.ForeignKey('user.id'))
meetingroomm = db.relationship('MeetingRoom', backref='mroom')
#roomno_id = db.Column(db.Integer, db.ForeignKey('meetingroom.mrid')
##json
@app.route('/users', methods=['GET'])
def getuser():
users = User.query.all()
output = []
for user in users:
user_data = {}
user_data['id'] = user.id
user_data['name'] = user.name
user_data['Email'] = user.Email
user_data['Pass'] = user.Pass
user_data['Phone'] = user.Phone
user_data['Department'] = user.Department
user_data['Major'] = user.Major
output.append(user_data)
return jsonify({'users' : output})
#User_schema
class UserSchema(ma.Schema):
class Mata:
fields = ('id', 'name', 'Email', 'Pass', 'Phone', 'Department', 'Major')
#init_schema
user_schema = UserSchema()
users_schema = UserSchema(many=True)
#create user
@app.route('/user', methods=['POST'])
def add_User():
#id = request.json['id']
name = request.json['name']
Email = request.json['Email']
Pass = request.json['Pass']
#Phone = request.json['Phone']
Department = request.json['Department']
Major = request.json['Major']
new_user = User(name, Email, Pass, Department, Major)
db.session.add(new_user)
db.session.commit()
return user_schema.jsonify(new_user)
#meeting_schema
class MeetingSchema(ma.Schema):
class Mata:
fields = ('Mid', 'Mname', 'Des', 'Date', 'creator_id')
#init_schema
meeting_schema = MeetingSchema()
meetings_schema = MeetingSchema(many=True)
#create meeting
@app.route('/meeting', methods=['POST'])
def add_meeting():
Mname = request.json['Mname']
Des = request.json['Des']
Date = request.json['Date']
new_meeting = Meeting(Mname, Des, Date)
db.session.add(new_meeting)
db.session.commit()
return user_schema.jsonify(new_meeting)
if __name__ == '__main__':
app.run(debug=True)
</code></pre>
<p><a href="https://i.stack.imgur.com/UxvD6.jpg" rel="nofollow noreferrer">2nd EDIT: the console log</a></p>
<p>after adding def error:</p>
<pre><code>cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) database is locked
[SQL: INSERT INTO user (name, "Email", "Pass", "Phone", "Department", "Major") VALUES (?, ?, ?, ?, ?, ?)]
[parameters: ('User 1', '[email protected]', 'qq1', '0551', 'IT 1', 'IT 1')]
(Background on this error at: http://sqlalche.me/e/e3q8)
</code></pre> | 56,662,965 | 2 | 15 | null | 2019-06-19 07:03:54.643 UTC | null | 2021-03-05 10:08:04.013 UTC | 2019-06-19 08:41:40.913 UTC | null | 11,635,626 | null | 11,635,626 | null | 1 | 1 | python|json|api|flask|postman | 68,030 | <p>As shown in console the problem is that you are initializing a <code>User</code> object using constructor but in <code>User</code> class you have not defined any constructor.</p>
<p>Define a constructor like this</p>
<pre><code>class User(db.Model): ...
....
def __init__(self, username, email):
self.username = username
self.email = email
# all your attributes
</code></pre> |
13,392,241 | How can I check if a localstorage variable is null or undefined? | <p>I have this code:</p>
<pre><code>var sideBar = localStorage.getItem('Sidebar');
</code></pre>
<p>I want to check if sideBar is defined and not null in an if statement. I am a bit confused I know there's a: <code>sideBar == undefined</code> and <code>sideBar != null</code> </p>
<p>but is there a good way for me to do this test for both of these inside an if:</p>
<pre><code>if (??)
</code></pre> | 13,392,335 | 7 | 1 | null | 2012-11-15 05:55:17.997 UTC | 5 | 2022-01-01 10:23:30.523 UTC | null | null | null | user1679941 | null | null | 1 | 21 | javascript | 52,318 | <p>best practice for checking if a variable is defined and not null:</p>
<pre><code>if (typeof sideBar !== 'undefined' && sideBar !== null)
</code></pre>
<p><strong>edited</strong> realized you're not checking if something is undefined, you're checking that it's defined, so edited again to answer your request more accurately</p> |
13,567,078 | What's wrong with single segment namespaces? | <p>I have read in several places that single segment namespaces are discouraged in clojure.</p>
<p>Indeed almost every library I've seen has (require 'lib.core) instead of (require 'lib).</p>
<p>Why?</p>
<hr>
<p>Edit: I am a bit stupid. Extra credit will be given for a concise example of how a single segment namespace might be a bad thing.</p> | 13,568,185 | 2 | 1 | null | 2012-11-26 14:40:40.017 UTC | 6 | 2012-11-26 15:42:40.93 UTC | 2012-11-26 15:28:34.367 UTC | null | 254,837 | null | 254,837 | null | 1 | 28 | clojure|namespaces | 3,056 | <p>Java discourages the use of the default package because you can't refer to anything in it from any other package. If you pre-compile a one-segment Clojure namespace, you'll get a Java class in the default package. If anyone at any time wants to use your library from Java, he will be stopped dead by this triviality. As there is no good reason in favor of using a single-segment namespace, and there is this one well-defined reason not to, it is fair to say that single-segment namespaces should be a discouraged practice in Clojure.</p> |
13,655,792 | How to stop (and restart) the Rails Server? | <p>I'm following the instructions here <a href="http://railsinstaller.org/mac">http://railsinstaller.org/mac</a> to get up and running with Rails on a Mac running OS X 10.8.2</p>
<p>At step 8 I'm asked to restart Rails server but how?</p>
<p>I'm assuming via a command line, but from within the already open ruby terminal window or a new one?</p> | 13,655,800 | 6 | 0 | null | 2012-12-01 02:31:15.07 UTC | 10 | 2021-09-23 09:30:45.73 UTC | 2012-12-01 02:36:29.583 UTC | null | 249,543 | null | 1,837,174 | null | 1 | 32 | ruby-on-rails|command-line|terminal|restart | 113,639 | <p>Press <code>Ctrl+C</code></p>
<p>When you start the server it mentions this in the startup text.</p> |
3,392,956 | SQL - How to transpose? | <p>I have something similar to the following table:</p>
<pre><code>================================================
| Id | UserId | FieldName | FieldValue |
=====+========+===============+================|
| 1 | 100 | Username | John Doe |
|----+--------+---------------+----------------|
| 2 | 100 | Password | pass123! |
|----+--------+---------------+----------------|
| 3 | 102 | Username | Jane |
|----+--------+---------------+----------------|
| 4 | 102 | Password | $ecret |
|----+--------+---------------+----------------|
| 5 | 102 | Email Address | [email protected] |
------------------------------------------------
</code></pre>
<p>I need a query that will give me a result like this:</p>
<pre><code>==================================================
| UserId | Username | Password | Email Address |
=========+===========+===========================|
| 100 | John Doe | pass123! | |
|--------+-----------+----------+----------------|
| 102 | Jane | $ecret | [email protected] |
|--------+-----------+----------+----------------|
</code></pre>
<p>Note that the values in FieldName are not limited to Username, Password, and Email Address. They can be anything as they are user defined.</p>
<p>Is there a way to do this in SQL?</p> | 3,392,962 | 2 | 1 | null | 2010-08-03 01:15:42.127 UTC | 11 | 2010-08-03 01:26:40 UTC | 2010-08-03 01:18:16.297 UTC | null | 135,152 | null | 253,976 | null | 1 | 30 | sql|mysql|database|pivot | 50,254 | <p>MySQL doesn't support ANSI PIVOT/UNPIVOT syntax, so that leave you to use:</p>
<pre><code> SELECT t.userid
MAX(CASE WHEN t.fieldname = 'Username' THEN t.fieldvalue ELSE NULL END) AS Username,
MAX(CASE WHEN t.fieldname = 'Password' THEN t.fieldvalue ELSE NULL END) AS Password,
MAX(CASE WHEN t.fieldname = 'Email Address' THEN t.fieldvalue ELSE NULL END) AS Email
FROM TABLE t
GROUP BY t.userid
</code></pre>
<p>As you can see, the CASE statements need to be defined per value. To make this dynamic, you'd need to use <a href="http://rpbouman.blogspot.com/2005/11/mysql-5-prepared-statement-syntax-and.html" rel="noreferrer">MySQL's Prepared Statement (dynamic SQL) syntax</a>.</p> |
9,188,447 | Visual Studio 2010 Service Pack 1 is not installing | <p>While installing Visual Studio 2010 Service Pack 1, I am getting this error:</p>
<blockquote>
<p>Installation did not succeed.
Microsoft Visual Studio 2010 Service Pack 1 has not been installed because: <br/>
Generic Trust Failure.</p>
</blockquote>
<p>How can I install Service Pack 1? I am using Windows 7 32 bit.</p>
<p>Here is the log file:</p>
<pre><code>OS Version = 6.1.7600, Platform 2
OS Description = Windows 7 - x86 Enterprise Edition
CommandLine = "D:\Softwares\Programming\Visual Studio 10 Service Pack 1\Setup.exe"
Using Simultaneous Download and Install mechanism
Operation: Installing
Package Name = Microsoft Visual Studio 2010 Service Pack 1
Package Version = 10.0.40219
User Experience Data Collection Policy: UserControlled
Number of applicable items: 22
Summary Information:
SetupUtility
Service Pack 1 Package
Microsoft Team Foundation Server 2010 Object Model - ENU
Microsoft Visual Studio 2010 Performance Collection Tools - ENU
Microsoft Visual Studio 2010 Ultimate - ENU
Microsoft Visual Studio 2010 ADO.NET Entity Framework Tools
Dotfuscator Software Services - Community Edition
Microsoft SQL Server Data-tier Application Framework 1.1
Microsoft SQL Server 2008 R2 Data-Tier Application Project
Microsoft SQL Server 2008 R2 Transact-SQL Language Service
Microsoft SQL Server 2008 R2 Management Objects
Microsoft SQL Server System CLR Types
Microsoft F# Redist 2.0
VSTO 4.0 Runtime x86
Visual Studio Tools for Office
Help Viewer v1.1
Microsoft SharePoint Developer Tools
Microsoft Visual C++ 2010 x86 Runtime - 10.0.40219
Microsoft Visual C++ Compilers 2010 Standard x86 - 10.0.40219
NDP40-KB2468871.exe
Possible transient lock. WinVerifyTrust failed with error: 2148204800
Possible transient lock. WinVerifyTrust failed with error: 2148204800
D:\Softwares\Programming\Visual Studio 10 Service Pack 1\VS10sp1-KB983509-Pro.msp -
Signature verification for file VS10sp1-KB983509-Pro.msp
(D:\Softwares\Programming\Visual Studio 10 Service Pack 1\VS10sp1-KB983509-Pro.msp)
failed with error 0x800b0100 (No signature was present in the subject.)
No FileHash provided. Cannot perform FileHash verification for VS10sp1-KB983509-Pro.msp
File VS10sp1-KB983509-Pro.msp (D:\Softwares\Programming\Visual Studio 10 Service Pack
1\VS10sp1-KB983509-Pro.msp), failed authentication. (Error = -2146762496). It is
recommended that you delete this file and retry setup again.
Exe (D:\Softwares\Programming\Visual Studio 10 Service Pack 1\SetupUtility.exe)
succeeded.
Exe Log File: dd_SetupUtility.txt
MSI (D:\Softwares\Programming\Visual Studio 10 Service Pack 1\VS10sp1_x86.msi)
Installation succeeded. Msi Log: Microsoft Visual Studio 2010 Service Pack
1_20120208_111135435-MSI_VS10sp1_x86.msi.txt
Final Result: Installation failed with error code: (0x800B010B), "Generic trust failure. " (Elapsed time: 0 00:01:59).
</code></pre> | 9,188,485 | 2 | 2 | null | 2012-02-08 05:51:20.66 UTC | 1 | 2016-09-15 21:41:32.107 UTC | 2015-07-31 16:22:50.987 UTC | null | 63,550 | null | 1,106,615 | null | 1 | 9 | visual-studio-2010|failed-installation | 45,039 | <p>This is the kind of error that can usually be fixed by the <a href="http://support.microsoft.com/kb/947821" rel="nofollow">System Update Readiness Tool</a>. Give it a shot and see if it solves it.</p> |
9,508,426 | How to connect from a VMware guest machine to the server installed on a Windows 7 host machine? | <p>How to connect from a VMware guest (virtual) machine to the server installed on the host (physical) machine? Things like typing "localhost" in the address bar of a browser in a guest machine don't work. My host machine's OS is Windows 7 64 bit with WMware Workstation installed on it, if it matters.</p>
<p>EDIT: The Bridged network connection in combination with referring to 192.168.0.10* from the guest machine did work (replace * with a digit starting from 0 until it works).</p> | 9,508,536 | 4 | 2 | null | 2012-02-29 23:38:26.943 UTC | 5 | 2016-02-09 05:21:26.037 UTC | 2012-03-01 00:29:22.913 UTC | null | 944,687 | null | 944,687 | null | 1 | 11 | vmware|virtualization|virtual-machine|vmware-workstation | 58,995 | <p>If you use "Bridged" Network Connection (see Virtual Machine Settings: Network Adapter), your VM will be given an IP address on the same LAN as your host machine. At that point, you can just HTTP to your host's IP address, eg. <code>http://192.168.0.100</code></p>
<p>You can also do that with the other options, but with NAT and Host-only (if I recall correctly) your host machine will appear to your guest machine to have a different IP address than its real LAN address. So Bridged is the easiest and is likely your best bet, unless you have some specific needs.</p> |
9,099,469 | MySQL SELECT LIKE or REGEXP to match multiple words in one record | <p>The field <code>table</code>.<code>name</code> contains 'Stylus Photo 2100' and with the following query</p>
<pre><code>SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus 2100%'
</code></pre>
<p>I get no results. Of course i would if i searched</p>
<pre><code>SELECT `name` FROM `table` WHERE `name` LIKE '%Photo 2100%'
</code></pre>
<p>How can I select the record by searching 'Stylus 2100' ?</p>
<p>Thanks </p> | 9,099,540 | 7 | 2 | null | 2012-02-01 16:31:10.773 UTC | 20 | 2019-06-27 14:13:13.427 UTC | 2014-04-11 07:28:40.69 UTC | null | 1,835,606 | null | 953,788 | null | 1 | 79 | mysql|regex|select|sql-like | 200,666 | <p>Well if you know the order of your words.. you can use:</p>
<pre><code>SELECT `name` FROM `table` WHERE `name` REGEXP 'Stylus.+2100'
</code></pre>
<p>Also you can use:</p>
<pre><code>SELECT `name` FROM `table` WHERE `name` LIKE '%Stylus%' AND `name` LIKE '%2100%'
</code></pre> |
16,545,262 | Python: NameError: free variable 're' referenced before assignment in enclosing scope | <p>I have a strange NameError in Python 3.3.1 (win7).</p>
<p>The code:</p>
<pre><code>import re
# ...
# Parse exclude patterns.
excluded_regexps = set(re.compile(regexp) for regexp in options.exclude_pattern)
# This is line 561:
excluded_regexps |= set(re.compile(regexp, re.I) for regexp in options.exclude_pattern_ci)
</code></pre>
<p>The error:</p>
<pre><code>Traceback (most recent call last):
File "py3createtorrent.py", line 794, in <module>
sys.exit(main(sys.argv))
File "py3createtorrent.py", line 561, in main
excluded_regexps |= set(re.compile(regexp, re.I) for regexp in options.exclude_pattern_ci)
File "py3createtorrent.py", line 561, in <genexpr>
excluded_regexps |= set(re.compile(regexp, re.I) for regexp in options.exclude_pattern_ci)
NameError: free variable 're' referenced before assignment in enclosing scope
</code></pre>
<p>Note that line 561, where the error occurs, is the <em>second</em> line in the code above. In other words: <code>re</code> is <em>not</em> a free variable. It is simply the regular expression module and it can be referenced perfectly fine in the <em>first</em> line.</p>
<p>It seems to me that the reference to <code>re.I</code> is causing the problem, but I don't see how.</p> | 16,545,619 | 3 | 3 | null | 2013-05-14 14:00:09.563 UTC | null | 2019-01-10 03:12:42.92 UTC | 2013-05-14 14:05:29.363 UTC | null | 623,685 | null | 623,685 | null | 1 | 20 | python | 41,796 | <p>Most likely, you are assigning to <code>re</code> (presumably inadvertently) at some point <em>below</em> line 561, but in the same function. This reproduces your error:</p>
<pre><code>import re
def main():
term = re.compile("foo")
re = 0
main()
</code></pre> |
16,535,630 | Sum values in foreach loop php | <pre><code>foreach($group as $key=>$value)
{
echo $key. " = " .$value. "<br>";
}
</code></pre>
<p>For example:</p>
<blockquote>
<p>doc1 = 8</p>
<p>doc2 = 7</p>
<p>doc3 = 1</p>
</blockquote>
<p>I want to count $value, so the result is 8+7+1 = 16. What should i do?</p>
<p>Thanks.</p> | 16,535,758 | 5 | 1 | null | 2013-05-14 05:17:58.31 UTC | 16 | 2013-05-14 07:06:28.01 UTC | 2013-05-14 05:44:03.22 UTC | null | 1,444,140 | null | 2,338,965 | null | 1 | 29 | php|foreach|count | 201,791 | <pre><code>$sum = 0;
foreach($group as $key=>$value)
{
$sum+= $value;
}
echo $sum;
</code></pre> |
16,504,231 | What is the meaning of "ReentrantLock" in Java? | <p>Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.</p>
<p>Since an intrinsic lock is held by a thread, doesn't it mean that a thread run once equals an invocation basis?</p>
<p>Thank you, it seems mean that: in a thread,if I get a lock <code>lockA</code> when process function <code>doA</code> which call function <code>doB</code>, and <code>doB</code> also need a lock <code>lockA</code>,then there wil be a reentrancy. In Java, this phenomenon is acquired per thread, so I needn't consider deadlocks?</p> | 16,504,266 | 6 | 4 | null | 2013-05-12 04:34:02.947 UTC | 24 | 2020-04-11 07:10:40.343 UTC | 2019-09-15 22:20:21.45 UTC | null | 801,894 | null | 1,059,465 | null | 1 | 46 | java|reentrancy | 17,419 | <blockquote>
<p>Reentrancy means that locks are acquired on a per-thread rather than per-invocation basis.</p>
</blockquote>
<p>That is a misleading definition. It is true (sort of), but it misses the real point.</p>
<p>Reentrancy means (in general CS / IT terminology) that you do something, and while you are still doing it, you do it again. In the case of locks it means you do something like this <em>on a single thread</em>:</p>
<ol>
<li>Acquire a lock on "foo".</li>
<li>Do something</li>
<li>Acquire a lock on "foo". Note that we haven't released the lock that we previously acquired.</li>
<li>...</li>
<li>Release lock on "foo"</li>
<li>...</li>
<li>Release lock on "foo"</li>
</ol>
<p>With a reentrant lock / locking mechanism, the attempt to acquire the same lock will succeed, and will increment an internal counter belonging to the lock. The lock will only be released when the current holder of the lock has released it twice.</p>
<p>Here's a example in Java using primitive object locks / monitors ... which are reentrant:</p>
<pre><code>Object lock = new Object();
...
synchronized (lock) {
...
doSomething(lock, ...)
...
}
public void doSomething(Object lock, ...) {
synchronized (lock) {
...
}
}
</code></pre>
<p>The alternative to reentrant is non-reentrant locking, where it would be an error for a thread to attempt to acquire a lock that it already holds.</p>
<p>The advantage of using reentrant locks is that you don't have to worry about the possibility of failing due to accidentally acquiring a lock that you already hold. The downside is that you can't assume that nothing you call will change the state of the variables that the lock is designed to protect. However, that's not usually a problem. Locks are generally used to protect against concurrent state changes made by <em>other</em> threads.</p>
<hr>
<blockquote>
<p>So I needn't consider deadlocks?</p>
</blockquote>
<p>Yes you do.</p>
<p>A thread won't deadlock against itself (if the lock is reentrant). However, you could get a deadlock if there are other threads that might have a lock on the object you are trying to lock.</p> |
21,483,999 | Using atan2 to find angle between two vectors | <p>I understand that:</p>
<p><code>atan2(vector.y, vector.x)</code> = the angle between the <strong>vector and the X axis</strong>.</p>
<p>But I wanted to know how to get the angle between <strong>two vectors</strong> using atan2. So I came across this solution:</p>
<pre><code>atan2(vector1.y - vector2.y, vector1.x - vector2.x)
</code></pre>
<p>My question is very simple:</p>
<p>Will the two following formulas produce the same number?</p>
<ul>
<li><p><code>atan2(vector1.y - vector2.y, vector1.x - vector2.x)</code></p></li>
<li><p><code>atan2(vector2.y - vector1.y, vector2.x - vector1.x)</code></p></li>
</ul>
<p>If not: <strong>How do I know what vector comes first in the subtractions?</strong></p> | 21,484,228 | 10 | 3 | null | 2014-01-31 15:41:40.033 UTC | 45 | 2022-07-20 08:45:18.407 UTC | 2019-08-05 19:34:49.363 UTC | null | 3,924,118 | null | 3,150,201 | null | 1 | 75 | math|vector|geometry | 141,814 | <pre><code> atan2(vector1.y - vector2.y, vector1.x - vector2.x)
</code></pre>
<p>is the angle between the <em>difference vector</em> (connecting vector2 and vector1) and the x-axis,
which is problably not what you meant.</p>
<p>The (directed) angle from vector1 to vector2 can be computed as</p>
<pre><code>angle = atan2(vector2.y, vector2.x) - atan2(vector1.y, vector1.x);
</code></pre>
<p>and you may want to normalize it to the range [0, 2 π):</p>
<pre><code>if (angle < 0) { angle += 2 * M_PI; }
</code></pre>
<p>or to the range (-π, π]:</p>
<pre><code>if (angle > M_PI) { angle -= 2 * M_PI; }
else if (angle <= -M_PI) { angle += 2 * M_PI; }
</code></pre> |
17,275,334 | What is a correct way to filter different loggers using python logging? | <h1>My purpose is to do a multi-module logging with hierarchical filtering</h1>
<p>the way it is proposed by <em>logging</em> author Vinay Sajip, at least as far as I guess ;-)</p>
<p>You can skip to "<strong>How I want it to work</strong>"</p>
<p><em>Unfortunately, I learned very quickly that working with logging facilities is much more sophisticated than most of my other experience with the language and I already did a lot of common (design) mistakes, e.g. trying to achieve a centralized single Logger class logging for multiple modules or even schemes like (<a href="https://stackoverflow.com/questions/7447382/using-python-logger-class-to-generate-multiple-logs-for-different-log-levels">using Python logger class to generate multiple logs for different log levels</a>). But apparently there is room for better design, and it might be worse spending time finding and learning it. So, right now I hope I am on the right track. Otherwise Vinaj will have to clarify the rest ;-)</em></p>
<p>I arrange my logging as this:</p>
<ul>
<li>Each python module has its <a href="https://stackoverflow.com/questions/401277/naming-python-loggers">own logger</a></li>
<li>Each logger has a name same as the module where it is defined, e.g. <code>logger = logging.getLogger(__name__)</code></li>
<li>Like this, code inside each module can use its own (locally defined) logger to send logging messages (logging.LogRecord) to handlers (logging.Handler)</li>
<li>Use <a href="http://docs.python.org/2.7/library/logging.config.html#logging.config.dictConfig" rel="noreferrer"><em>logging.config</em></a> to achieve full flexibility in configuring of the logging (Note: in the code below I just start with <em>basicConfig</em>)</li>
</ul>
<p>Such approach is a recommended approach and I agree with its possible advantages. For example I can turn on/off DEBUG of external libraries using fully qualified module names (the naming hierarchy which already exists in the code).</p>
<p>Now to have a greater level of control I want to use logging.Filter class, to be able to filter (allow) only a selected subtree within the hierarchy of loggers.</p>
<p>This is all fine, but the filtering as described here</p>
<blockquote>
<pre><code>Filter instances are used to perform arbitrary filtering of LogRecords.
Loggers and Handlers can optionally use Filter instances to filter
records as desired. The base filter class only allows events which are
below a certain point in the logger hierarchy. For example, a filter
initialized with "A.B" will allow events logged by loggers "A.B",
"A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If
initialized with the empty string, all events are passed.
</code></pre>
</blockquote>
<p>is still not working for me. </p>
<p>My guess is that my lack of understanding the details behind LogRecords propagation is the source of the problem. Before jumping to code I want to show here a flow chart (from the <a href="http://docs.python.org/2.7/howto/logging.html#logging-advanced-tutorial" rel="noreferrer">cookbook tutorial</a> which at first I somehow failed to immediately discover):
<img src="https://i.stack.imgur.com/dpYyh.png" alt="logging flow-chart"></p>
<h1>Example code</h1>
<p>I start with two modules example, each uses it own named logger:</p>
<p><em>bar.py:</em></p>
<pre><code>import logging
logger = logging.getLogger(__name__)
def bar():
logger.info('hello from ' + __name__)
</code></pre>
<p><em>foo.py:</em></p>
<pre><code>import logging
from bar import bar, logger as bar_logger
logger = logging.getLogger('foo')
def foo():
logger.info('hello from foo')
if __name__ == '__main__':
# Trivial logging setup.
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(name)-20s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M'
)
# Do some work.
foo()
bar()
</code></pre>
<p>Logging is first constructed with logging.basicConfig (root logger, which was created after <code>import logging</code> by <code>__main__</code> gets a stream handler attached to it, so that we have a console), is enabled (respective Logger.disabled=False) and both module loggers <em>bar</em> and <em>foo</em> propagate to the root logger (so we have three loggers in total).</p>
<pre><code>print logger
print bar_logger
print logging.root
# Prints
#<logging.Logger object at 0x7f0cfd520790>
#<logging.Logger object at 0x7f0cfd55d710>
#<logging.RootLogger object at 0x7f0cfd520550>
</code></pre>
<p>The actual usecase is when bar is an external library that I want to silence (filter out).</p>
<h1>How it works, but "me" don't like it</h1>
<pre><code># Don't like it
bar_logger.addFilter(logging.Filter('foo'))
# Do some work.
foo()
bar()
</code></pre>
<p>prints only </p>
<pre><code>06-24 14:08 foo INFO hello from foo
</code></pre>
<h1>How I want it to work</h1>
<p>I want to filter it out centrally, i.e. at my root logger w/o the need to import all the loggers of all the external modules out there.</p>
<pre><code>logging.root.addFilter(logging.Filter('foo'))
</code></pre>
<p>prints</p>
<pre><code>06-24 14:17 foo INFO hello from foo
06-24 14:17 bar INFO hello from bar
</code></pre>
<p>There must be some obvious/stupid mistake that I miss: I don't want any messages from <strong>bar</strong> logger. Hey, but what is a better way to find it than summarizing all on SO, folks? ;-)</p>
<p>I will try to find out the way for bar_logger to wait for decision from the root logger, before emitting anything. I just hope that this is indeed how it is supposed to work in the first place.</p> | 17,276,457 | 1 | 2 | null | 2013-06-24 12:19:58.52 UTC | 19 | 2016-08-29 15:28:34.75 UTC | 2017-05-23 12:02:27.713 UTC | null | -1 | null | 544,463 | null | 1 | 34 | python|logging|filter | 25,051 | <p><strong>Solution</strong></p>
<p>Add the filter to the handler rather than the logger:</p>
<pre><code>handler.addFilter(logging.Filter('foo'))
</code></pre>
<hr>
<p><strong>Explanation</strong></p>
<p>In the flow chart diagram you posted, notice there are two diamonds:</p>
<ul>
<li>Does a filter attached to <strong>logger</strong> reject the record?</li>
<li>Does a filter attached to <strong>hander</strong> reject the record?</li>
</ul>
<p>Thus, you get two swings at rejecting a LogRecord. If you attach the filter to the root logger, but initiate the LogRecord through, say, the foo or bar loggers, then the LogRecord does not get filtered because the LogRecord passes through the foo or bar loggers freely and the root logger filter never enters into play. (Look at the flow chart again.)</p>
<p>In contrast, the StreamHandler defined by <code>basicConfig</code> is capable of filtering any LogRecord passes to it.</p>
<p>So: add the filter to the handler rather than the logger:</p>
<pre><code># foo.py
import logging
import bar
logger = logging.getLogger('foo')
def foo():
logger.info('hello from foo')
if __name__ == '__main__':
# Trivial logging setup.
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(name)-20s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M')
for handler in logging.root.handlers:
handler.addFilter(logging.Filter('foo'))
foo()
bar.bar()
</code></pre>
<p>yields</p>
<pre><code>06-24 09:17 foo INFO hello from foo
</code></pre>
<hr>
<p>If you want to allow logging from loggers whose name begins with <code>foo</code> or <code>bar</code>, but not from any other loggers, you could create a whitelist filter like this:</p>
<pre><code>import logging
foo_logger = logging.getLogger('foo')
bar_logger = logging.getLogger('bar')
baz_logger = logging.getLogger('baz')
class Whitelist(logging.Filter):
def __init__(self, *whitelist):
self.whitelist = [logging.Filter(name) for name in whitelist]
def filter(self, record):
return any(f.filter(record) for f in self.whitelist)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(name)-20s %(levelname)-8s %(message)s',
datefmt='%m-%d %H:%M')
for handler in logging.root.handlers:
handler.addFilter(Whitelist('foo', 'bar'))
foo_logger.info('hello from foo')
# 06-24 09:41 foo INFO hello from foo
bar_logger.info('hello from bar')
# 06-24 09:41 bar INFO hello from bar
baz_logger.info('hello from baz')
# No output since Whitelist filters if record.name not begin with 'foo' or 'bar'
</code></pre>
<hr>
<p>And similarly, you could blacklist logger names with this:</p>
<pre><code>class Blacklist(Whitelist):
def filter(self, record):
return not Whitelist.filter(self, record)
</code></pre> |
12,291,523 | open new window with php code after form submits results | <p>here is the script that i been working on , it is supposed to integrate user and pass when opened</p>
<pre><code><?php
$name = $_POST['name']; // contain name of person
$pass = $_POST['pass']; // Email address of sender
$link = window.open(https://secure.brosix.com/webclient/?nid=4444&user=$name&pass=$pass&hideparams=1 'width=710,height=555,left=160,top=170');
echo $link;
?>
</code></pre>
<p>am i doing this right, i want to open a pop up windows after the user submits the form to the php code but i always get an error.</p> | 12,291,541 | 4 | 2 | null | 2012-09-06 00:34:50.137 UTC | 2 | 2022-02-05 15:25:17.723 UTC | null | null | null | null | 1,626,986 | null | 1 | 3 | php|forms|validation|popup|window | 97,150 | <p>Change your code to this</p>
<pre><code><?php
$name = $_POST['name']; // contain name of person
$pass = $_POST['pass']; // Email address of sender
$link = "<script>window.open('https://secure.brosix.com/webclient/? nid=4510&user=$name&pass=$pass&hideparams=1', 'width=710,height=555,left=160,top=170')</script>";
echo $link;
?>
</code></pre>
<p><strong>Additional Note</strong></p>
<p>You should consider using <a href="http://fancybox.net/">fancybox</a> which can load webpages as a whole in a popup window using iframes. There are other options as well feel free to explore!</p> |
5,214,543 | What is "stringification" in Perl? | <p>In the documentation for the CPAN module <a href="http://search.cpan.org/~drolsky/DateTime-0.66/lib/DateTime.pm#Formatters_And_Stringification" rel="noreferrer">DateTime</a> I found the following:</p>
<blockquote>
<p>Once you set the formatter, the
overloaded stringification method will
use the formatter.</p>
</blockquote>
<p>It seems there is some Perl concept called "stringification" that I somehow missed. Googling has not clarified it much. What is this "stringification"?</p> | 5,214,672 | 3 | 0 | null | 2011-03-07 00:24:49.123 UTC | 10 | 2014-01-08 13:07:54.987 UTC | 2014-01-08 13:07:54.987 UTC | null | 63,550 | null | 16,012 | null | 1 | 28 | perl | 10,590 | <p>"stringification" happens any time that perl needs to convert a value into a string. This could be to print it, to concatenate it with another string, to apply a regex to it, or to use any of the other string manipulation functions in Perl.</p>
<pre><code>say $obj;
say "object is: $obj";
if ($obj =~ /xyz/) {...}
say join ', ' => $obj, $obj2, $obj3;
if (length $obj > 10) {...}
$hash{$obj}++;
...
</code></pre>
<p>Normally, objects will stringify to something like <code>Some::Package=HASH(0x467fbc)</code> where perl is printing the package it is blessed into, and the type and address of the reference. </p>
<p>Some modules choose to override this behavior. In Perl, this is done with the <a href="http://perldoc.perl.org/overload.html" rel="noreferrer">overload</a> pragma. Here is an example of an object that when stringified produces its sum:</p>
<pre><code>{package Sum;
use List::Util ();
sub new {my $class = shift; bless [@_] => $class}
use overload fallback => 1,
'""' => sub {List::Util::sum @{$_[0]}};
sub add {push @{$_[0]}, @_[1 .. $#_]}
}
my $sum = Sum->new(1 .. 10);
say ref $sum; # prints 'Sum'
say $sum; # prints '55'
$sum->add(100, 1000);
say $sum; # prints '1155'
</code></pre>
<p>There are several other ifications that <code>overload</code> lets you define:</p>
<pre><code>'bool' Boolification The value in boolean context `if ($obj) {...}`
'""' Stringification The value in string context `say $obj; length $obj`
'0+' Numification The value in numeric context `say $obj + 1;`
'qr' Regexification The value when used as a regex `if ($str =~ /$obj/)`
</code></pre>
<p>Objects can even behave as different types:</p>
<pre><code>'${}' Scalarification The value as a scalar ref `say $$obj`
'@{}' Arrayification The value as an array ref `say for @$obj;`
'%{}' Hashification The value as a hash ref `say for keys %$obj;`
'&{}' Codeification The value as a code ref `say $obj->(1, 2, 3);`
'*{}' Globification The value as a glob ref `say *$obj;`
</code></pre> |
4,999,144 | Aspect Oriented Programing (AOP) solutions for C# (.Net) and their features | <p>I would like to ask for 3 information here:</p>
<ol>
<li><p>There is <strong>no integrated solution</strong> for Aspect Oriented Programing (AOP) in C# (.Net) <strong>from Microsoft</strong> is that correct ? Is there any such solution under development or planned ?</p>
</li>
<li><p><strong>What solutions are there</strong> that allow Aspect Oriented Programing (AOP) to be used in C# (.Net) ? What are they <strong>advantages/disadvantages</strong> ? I haven't find any comprihensive list that would contain all avatable options and some information for me to decide which is the one to use. The closest is <a href="http://csharp-source.net/open-source/aspect-oriented-frameworks" rel="noreferrer">this list</a>.</p>
</li>
<li><p>What is (in your opinion) <strong>the best AOP</strong> solution <strong>for C#(.Net)</strong> considering following <strong>criteria:</strong></p>
<ol>
<li>it schould work similar to AspectJ and has similar syntax</li>
<li>simplicity of use: no XML configuration should be needed - just write some regular classes, some aspect classes and compile to weave it all together, then run.</li>
<li>should include all features of AspectJ. Support for generics.</li>
<li>solution should be stable, widely used and mainteined.</li>
<li>should offer weaving of binaries (so could be used ) or C# source code.</li>
<li>GUI tool for visualising (or even better - plugin to VS) is an advantage.</li>
</ol>
</li>
</ol>
<p>I think that if something fullfils most of criteria in 3. then it is a candidate for a generaly used solution. And I cannot find anywhere if some of existing solutions fits to my needs.</p> | 5,004,509 | 3 | 7 | null | 2011-02-15 01:35:35.663 UTC | 6 | 2014-07-31 12:59:54.537 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 311,865 | null | 1 | 30 | c#|.net|aop | 10,213 | <p>As Adam Rackis points out, Post# is the way to go, it is as close you will get to AspectJ on the .NET platform.</p>
<p>Main differences is obviously that AspecJ has language support for aspects while Post# is a post compile weaver for .NET assemblies.
(thus no language integration)</p>
<p>However, Post# can use join points such as field access, try catch blocks, both calls and functions (that is, caller and callee)</p>
<ol>
<li><p>No not even close, AspectJ is a language, Post# can use custom pointcuts but the most common is to use attributes to decorate methods to be pointcutted(eh..grammar?)</p></li>
<li><p>check</p></li>
<li><p>everything but language support </p></li>
<li><p>check</p></li>
<li><p>check - it is a post compile weaver</p></li>
<li><p>limited, the weaver will generate intellisense information and show what methods have been affected</p></li>
</ol>
<p>If you want a .NET language that supports aspects, check out <a href="http://aspectsharpcomp.sourceforge.net/samples.htm" rel="nofollow noreferrer">http://aspectsharpcomp.sourceforge.net/samples.htm</a></p>
<p>Regarding different approaches, there are a few:</p>
<ol>
<li><p>Post compile weaving , this is what Post# does.
It simply mangles the .NET assembly and injects the aspect code.</p></li>
<li><p>Real Proxy / MarshallByRefObject.
Based on remoting infrastructure.
Requires your classes to inherit from a base class.
Extremely bad performance and no "self interception"</p></li>
<li><p>Dynamic Proxy.
This is what my old library NAspect used.
you use a factory to create a subclass of the type on which you want to apply aspects.
The subclass will add mixin code using interfaces and override virtual methods and inject interceptor code.</p></li>
<li><p>Source code weaving.
As the name implies, it transforms your source code before compilation.</p></li>
</ol>
<p>[edit] I forgot to add this one to the list:</p>
<ol start="5">
<li>Interface proxies
Similar to Dynamic Proxy, but instead of applying the interception code to a subclass, the interception code is added to a runtime generated interface proxy.
That is, you get an object that implements a given interface, this object then delegates each call to any of the interface methods first to the AOP interception code and then it delegates the call to the real object.
That is, you have two objects at play here, the proxy and the subject(your real object).</li>
</ol>
<p><code>Client -> Interface Proxy -> AOP interception -> Target/Subject</code></p>
<p>This is AFAIK what Spring does.</p>
<p>1) and 3) are the most common.
They both have pros and cons:</p>
<p>Post Compilation:</p>
<p>Pros:</p>
<ul>
<li>Can point cut pretty much everything, static , sealed, private</li>
<li>Objects can still be created using "new"</li>
</ul>
<p>Cons:</p>
<ul>
<li><p>Can not apply aspects based on context, that is , if a type is affected, it will be affected for the entire application.</p></li>
<li><p>Pointcutting private, static, sealed constructs may lead to confusion since it breaks fundamental OO rules.</p></li>
</ul>
<p>Dynamic Proxy:</p>
<p>Pros:</p>
<ul>
<li><p>Contextual, one typ can have different aspects applied based on context.</p></li>
<li><p>Easy to use, no configuration or build steps.</p></li>
</ul>
<p>Cons:</p>
<ul>
<li><p>Limited pointcuts, only interface members and virtual members can be intercepted</p></li>
<li><p>must use factory to create objects</p></li>
</ul> |
25,515,166 | Redis Daemon not creating a PID file | <p>The Redis startup script is supposed to create a pid file at startup, but I've confirmed all the settings I can find, and no pid file is ever created.</p>
<p>I installed redis by: </p>
<pre><code>$ yum install redis
$ chkconfig redis on
$ service redis start
</code></pre>
<p>In my config file (/etc/redis.conf) I checked to make sure these were enabled: </p>
<pre><code>daemonize yes
pidfile /var/run/redis/redis.pid
</code></pre>
<p>And in the startup script (/etc/init.d/redis) there is:</p>
<pre><code>exec="/usr/sbin/$name"
pidfile="/var/run/redis/redis.pid"
REDIS_CONFIG="/etc/redis.conf"
[ -e /etc/sysconfig/redis ] && . /etc/sysconfig/redis
lockfile=/var/lock/subsys/redis
start() {
[ -f $REDIS_CONFIG ] || exit 6
[ -x $exec ] || exit 5
echo -n $"Starting $name: "
daemon --user ${REDIS_USER-redis} "$exec $REDIS_CONFIG"
retval=$?
echo
[ $retval -eq 0 ] && touch $lockfile
return $retval
}
stop() {
echo -n $"Stopping $name: "
killproc -p $pidfile $name
retval=$?
echo
[ $retval -eq 0 ] && rm -f $lockfile
return $retval
}
</code></pre>
<p>These are the settings that came by default with the install. Any idea why no pid file is created? I need to use it for Monit.
(The system is RHEL 6.4 btw)</p> | 25,529,443 | 11 | 2 | null | 2014-08-26 21:08:03.833 UTC | 15 | 2022-08-04 22:15:00.427 UTC | 2022-08-04 22:15:00.427 UTC | null | 9,431,571 | null | 2,456,552 | null | 1 | 43 | redis|centos|pid|monit|rhel6 | 64,708 | <p>Problem was that the user redis did not have permission to create the pid file (or directory it was in). Fix:</p>
<pre><code>sudo mkdir /var/run/redis
sudo chown redis /var/run/redis
</code></pre>
<p>Then I killed and restarted redis and sure enough, there was redis.pid</p> |
25,934,586 | Finding the amount of characters of all words in a list in Python | <p>I'm trying to find the total number of characters in the list of words, specifically this list:</p>
<pre><code>words = ["alpha","omega","up","down","over","under","purple","red","blue","green"]
</code></pre>
<p>I've tried doing: </p>
<pre><code>print "The size of the words in words[] is %d." % len(words)
</code></pre>
<p>but that just tells me how many words are in the list, which is 10. </p>
<p>Any help would be appreciated!</p>
<p>Sorry, I meant to mention that the class I'm doing this for is on the topic of for loops, so I was wondering if I had to implement a forloop to give me an answer, which is why the for loop tags are there.</p> | 25,934,600 | 3 | 3 | null | 2014-09-19 13:02:58.803 UTC | 3 | 2021-03-27 21:18:08.453 UTC | 2017-08-18 17:22:58.613 UTC | null | 7,992,467 | null | 4,056,643 | null | 1 | 8 | python|list | 55,453 | <p>You can use the <code>len</code> function within a list comprehension, which will create a list of lengths</p>
<pre><code>>>> words = ["alpha","omega","up","down","over","under","purple","red","blue","green"]
>>> [len(i) for i in words]
[5, 5, 2, 4, 4, 5, 6, 3, 4, 5]
</code></pre>
<p>Then simply <code>sum</code> using a generator expression</p>
<pre><code>>>> sum(len(i) for i in words)
43
</code></pre>
<p>If you really have your heart set on <code>for</code> loops.</p>
<pre><code>total = 0
for word in words:
total += len(word)
>>> print total
43
</code></pre> |
25,466,030 | Make QWidget transparent | <p>I have a <code>QWidget</code>-based overlay widget which should paint some text and take place over the central widget of my application. The problem is that I can't set background of overlay widget to be transparent. What I already tried:</p>
<ol>
<li><code>setPalette(Qt::transparent);</code></li>
<li><code>setAttribute( Qt::WA_TranslucentBackground, true );</code></li>
<li><code>setAttribute( Qt::WA_OpaquePaintEvent, true );</code></li>
<li><code>setAutoFillBackground(false);</code></li>
<li><code>setStyleSheet("QWidget{background-color: transparent;}");</code></li>
<li><code>setAttribute(Qt::WA_NoSystemBackground);</code></li>
</ol> | 25,468,160 | 3 | 3 | null | 2014-08-23 20:23:24.28 UTC | 6 | 2017-12-01 11:53:13.973 UTC | null | null | null | null | 275,221 | null | 1 | 25 | c++|qt|qt4 | 41,983 | <p>My best guess to show an overlay widget, is convert the widget to a window, resize it to it's contents and move them to the desired position manually.</p>
<p>MainWindow Example, showing the overlay widget in the center of the video widget:</p>
<pre><code>Mwindow::Mwindow()
{
widget = new Widget(this);
}
void Mwindow::widgetSizeMove()
{
if (widget->width() <= videoWidget->width() && widget->height() <= videoWidget->height())
{
widget->setWindowOpacity(1); // Show the widget
QPoint p = videoWidget->mapToGlobal(videoWidget->pos());
int x = p.x() + (videoWidget->width() - widget->width()) / 2;
int y = p.y() + (videoWidget->height() - widget->height()) / 2;
widget->move(x, y);
widget->raise();
}
else
{
widget->setWindowOpacity(0); // Hide the widget
}
}
bool Mwindow::event(QEvent *event)
{
switch (event->type())
{
case QEvent::Show:
widget->show();
QTimer::singleShot(50, this, SLOT(widgetSizeMove()));
//Wait until the Main Window be shown
break;
case QEvent::WindowActivate:
case QEvent::Resize:
case QEvent::Move:
widgetSizeMove();
break;
default:
break;
}
return QMainWindow::event(event);
}
</code></pre>
<p>Widget Example:</p>
<pre><code>Widget::Widget(QWidget *parent) : QWidget(parent)
{
setWindowFlags(Qt::Window | Qt::FramelessWindowHint);
setAttribute(Qt::WA_NoSystemBackground);
setAttribute(Qt::WA_TranslucentBackground);
setAttribute(Qt::WA_PaintOnScreen);
setAttribute(Qt::WA_TransparentForMouseEvents);
}
void Widget::paintEvent(QPaintEvent*)
{
QPainter p(this);
QString text = "Some foo goes here";
QFontMetrics metrics(p.font());
resize(metrics.size(0, text));
p.drawText(rect(), Qt::AlignCenter, text);
}
</code></pre>
<p>Example when showing a video with LibVLC:</p>
<p><img src="https://i.stack.imgur.com/ozKVp.png" alt="VLC based player"></p> |
9,212,797 | How to get CSS selectors to work in the Developer Tools for Chrome 17? | <p>It appears that the search window of the Dev Tools in Chrome 17 no longer matches CSS selectors. Boo. I know I can use the JS console but it really, really helps me to see the matches within the context of the DOM. If anyone knows how I can still achieve this or alternatively, how to revert to a previous (i.e. the one I had yesterday) version of chrome I would appreciate it. </p> | 9,212,970 | 4 | 4 | null | 2012-02-09 14:36:54.44 UTC | 12 | 2018-01-17 13:58:28.83 UTC | 2012-02-10 14:20:36.1 UTC | null | 106,224 | null | 1,025,695 | null | 1 | 38 | css|google-chrome|css-selectors|google-chrome-devtools | 49,948 | <p><del>I haven't been able to find any workaround to get CSS selectors working in the search bar again.</del> <a href="https://stackoverflow.com/a/10640999/106224">Rejoice, for they have returned!</a></p>
<p>In any case, you can still use <code>document.querySelectorAll()</code> with a selector in the JS console, then right-click on any of the matched elements and choose <strong>Reveal in Elements Panel</strong> and it'll show you where it is in the DOM, just as with previous versions.</p> |
9,362,286 | Why is the Fibonacci series used in agile planning poker? | <p>When estimating the relative size of user stories in agile software development the members of the team are supposed to estimate the size of a user story as being 1, 2, 3, 5, 8, 13, ... . So the estimated values should resemble the Fibonacci series. But I wonder, why?</p>
<p>The description of <a href="http://en.wikipedia.org/wiki/Planning_poker" rel="noreferrer">http://en.wikipedia.org/wiki/Planning_poker</a> on Wikipedia holds the mysterious sentence:</p>
<blockquote>
<p>The reason for using the Fibonacci sequence is to reflect the inherent
uncertainty in estimating larger items.</p>
</blockquote>
<p>But why should there be inherent uncertainty in larger items? Isn't the uncertainty higher, if we make fewer measurement, meaning if fewer people estimate the same story?
And even if the uncertainty is higher in larger stories, why does that imply the use of the Fibonacci sequence? Is there a mathematical or statistical reason for it?
Otherwise using the Fibonacci series for estimation feels like CargoCult science to me.</p> | 24,885,067 | 6 | 4 | null | 2012-02-20 13:55:01.487 UTC | 32 | 2016-01-26 13:10:05.343 UTC | null | null | null | null | 179,014 | null | 1 | 96 | math|statistics|agile|agile-project-management | 132,073 | <p>The Fibonacci series is just one example of an exponential estimation scale. The reason an exponential scale is used comes from Information Theory.</p>
<p><strong>The information that we obtain out of estimation grows much slower than the precision of estimation. In fact it grows as a logarithmic function.</strong> This is the reason for the higher uncertainty for larger items.</p>
<p>Determining the most optimal base of the exponential scale (normalization) is difficult in practise. The base corresponding to the Fibonacci scale may or may not be optimal.</p>
<p>Here is a more detailed explanation of the mathematical justification: <a href="http://www.yakyma.com/2012/05/why-progressive-estimation-scale-is-so.html">http://www.yakyma.com/2012/05/why-progressive-estimation-scale-is-so.html</a></p> |
9,104,706 | How can I convert spaces to tabs in Vim or Linux? | <p>I've looked over several questions on Stack Overflow for how to convert spaces to tabs without finding what I need. There seem to be more questions about how to convert tabs to spaces, but I'm trying to do the opposite.</p>
<p>In <code>Vim</code> I've tried <code>:retab</code> and <code>:retab!</code> without luck, but I believe those are actually for going from tabs to spaces anyways.</p>
<p>I tried both <code>expand</code> and <code>unexpand</code> at the command prompt without any luck.</p>
<p>Here is the file in question:</p>
<p><a href="http://gdata-python-client.googlecode.com/hg-history/a9ed9edefd61a0ba0e18c43e448472051821003a/samples/docs/docs_v3_example.py">http://gdata-python-client.googlecode.com/hg-history/a9ed9edefd61a0ba0e18c43e448472051821003a/samples/docs/docs_v3_example.py</a></p>
<p>How can I convert <strong>leading</strong> spaces to tabs using either <code>Vim</code> or the shell?</p> | 9,105,889 | 10 | 4 | null | 2012-02-01 23:02:22.337 UTC | 116 | 2022-01-03 23:03:53.097 UTC | 2018-04-01 12:01:04.81 UTC | null | 3,772,866 | null | 288,032 | null | 1 | 216 | linux|vim|tabs|spaces | 165,159 | <p>Using Vim to expand all <em>leading</em> spaces (wider than <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#%27tabstop%27" rel="noreferrer"><code>'tabstop'</code></a>), you were right to use <a href="http://vimdoc.sourceforge.net/htmldoc/change.html#:retab" rel="noreferrer"><code>retab</code></a> but first ensure <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#%27expandtab%27" rel="noreferrer"><code>'expandtab'</code></a> is reset (<code>:verbose set ts? et?</code> is your friend). <code>retab</code> takes a <em>range</em>, so I usually specify <a href="http://vimdoc.sourceforge.net/htmldoc/cmdline.html#:%25" rel="noreferrer"><code>%</code></a> to mean "the whole file".</p>
<pre><code>:set tabstop=2 " To match the sample file
:set noexpandtab " Use tabs, not spaces
:%retab! " Retabulate the whole file
</code></pre>
<p>Before doing anything like this (particularly with Python files!), I usually set <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#%27list%27" rel="noreferrer"><code>'list'</code></a>, so that I can <strong>see</strong> the whitespace and change. </p>
<p>I have the following mapping in <a href="https://github.com/johnsyweb/dotfiles/blob/e2289d90acd1f6e6df1c7cbe762ee39bd68ed3c6/.vimrc#L330" rel="noreferrer">my <code>.vimrc</code></a> for this:</p>
<pre><code>nnoremap <F2> :<C-U>setlocal lcs=tab:>-,trail:-,eol:$ list! list? <CR>
</code></pre> |
18,337,536 | Android Overriding onBackPressed() | <p>Is it possible to override <code>onBackPressed()</code> for only one activity ? </p>
<p>On back button click I want to call a dialog on a specific Activity, but in all other activities i want it to work as it worked before (going to previous activities).</p>
<p><strong>EDITED</strong></p>
<p>Thank you everyone for your answers, I already had everything like you told me, but my problem was that when i was clicking back button on another Activity, I was going to my previous Activity (The one where i had back button Overridden) and i thought that it wasn't working, i thought it was overriding <code>onBackPressed()</code> in whole Application, now i got it.</p> | 18,337,567 | 8 | 1 | null | 2013-08-20 14:23:45.593 UTC | 17 | 2019-08-02 09:14:18.753 UTC | 2019-04-14 23:34:52.303 UTC | null | 8,464,442 | null | 2,219,052 | null | 1 | 69 | android|android-intent|event-handling|overriding | 189,838 | <p>Yes. Only override it in that one <code>Activity</code> with</p>
<pre><code>@Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
}
</code></pre>
<p>don't put this code in any other <code>Activity</code></p> |
27,556,504 | Why is operator""s hidden in a namespace? | <p>In order to use <code>operator""s</code> for <code>std::string</code> you have to do <code>using namespace std::string_literals</code>. But user-defined literals that don't begin with <code>_</code> are reserved, so possible conflict can't be an excuse. The other <code>operator""s</code> is from <code>std::chrono</code> but that's for int literals, so there's no conflict there either.</p>
<p>What's the reason for this?</p> | 27,556,595 | 1 | 5 | null | 2014-12-18 22:04:07.987 UTC | 5 | 2015-02-18 18:16:48.76 UTC | null | null | null | null | 4,375,981 | null | 1 | 28 | c++|c++14 | 3,138 | <p>There are actually two reasons why literals are put into namespaces:</p>
<ol>
<li>It is considered undesirable that users would use <code>using namespace std;</code> just to get hold of the corresponding literals. Having the literals declared in namespaces specific to these doesn't cause the problem.</li>
<li>Depending on the domain it may be desirable to use <code>s</code> as the suffix for something else. There is already another suffix <code>s</code> to mean seconds but they don't really conflict.</li>
</ol>
<p>In the <a href="http://youtube.com/watch?v=dTeKf5Oek2c" rel="noreferrer">video of STL's CppCon 2014 talk</a> (posted by remyable in a comment) Stephan T. Lavavej explains the overall design of the literals in C++14 and its pretty clear that they are <em>not</em> supposed to be in the global namespace! Instead, the literal suffixes in the standard library live in a hierarchy of <code>inline</code> namespaces giving users fine-grained control over the literals being made available. For example, the literal suffix for strings is declared like this (21.3 [string.classes] paragraph 1):</p>
<pre><code>namespace std {
inline namespace literals {
inline namespace string_literals {
string operator"" s(char const* str, size_t len);
}
}
}
</code></pre>
<p>This hierarchy of <code>inline</code> namespaces makes it possible for users to get the appropriate choice of literal suffixes:</p>
<ul>
<li><code>using namespace std;</code> - you get everything in the standard C++ library, including the literal suffixes, without any qualification.</li>
<li><code>using namespace std::literals;</code> - you get all literal suffixes defined in the standard C++ library.</li>
<li><code>using namespace std::string_literals;</code> - you get all literal suffixes applicable to strings.</li>
<li><code>using namespace std::literals::string_literals;</code> - yes, you can do that but you really shouldn't: that's equivalent to <code>using namespace std::string_literals;</code>.</li>
</ul>
<p>Clearly, the committee wouldn't have gone to that much effort if it had considered the idea viable to just pollute the global namespace with literal suffixes, although they can't even conflict with any user literal suffixes.</p> |
15,040,838 | MVC JsonResult camelCase serialization | <p>I am trying to make my action return a JsonResult where all its properties are in camelCase. </p>
<p>I have a simply model:</p>
<pre><code>public class MyModel
{
public int SomeInteger { get; set; }
public string SomeString { get; set; }
}
</code></pre>
<p>And a simple controller action:</p>
<pre><code>public JsonResult Index()
{
MyModel model = new MyModel();
model.SomeInteger = 1;
model.SomeString = "SomeString";
return Json(model, JsonRequestBehavior.AllowGet);
}
</code></pre>
<p>Calling this action method now returns a JsonResult containing the following data:</p>
<pre><code>{"SomeInteger":1,"SomeString":"SomeString"}
</code></pre>
<p>For my uses i need the action return the data in camelCase, somehow like this:</p>
<pre><code>{"someInteger":1,"someString":"SomeString"}
</code></pre>
<p>Is there any elegant way to do this?</p>
<p>I was looking into possible solutions around here and found <a href="https://stackoverflow.com/questions/7260924/mvc3-json-serialization-how-to-control-the-property-names">MVC3 JSON Serialization: How to control the property names?</a> where they set DataMember definitions to every property of the model, but I do not really want to do this. </p>
<p>Also I found a link where they say that it is possible to solve exactly this kind of issue: <a href="http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_camelcasing" rel="noreferrer">http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization#json_camelcasing</a>. It says: </p>
<p><strong>To write JSON property names with camel casing, without changing your data model, set the CamelCasePropertyNamesContractResolver on the serializer:</strong></p>
<pre><code>var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
</code></pre>
<p>One entry on this blog <a href="http://frankapi.wordpress.com/2012/09/09/going-camelcase-in-asp-net-mvc-web-api/" rel="noreferrer">http://frankapi.wordpress.com/2012/09/09/going-camelcase-in-asp-net-mvc-web-api/</a> also mentiones this solution and states you can simply add it to the <strong>RouteConfig.RegisterRoutes</strong> to fix this issue. I tried it, but I couldn't make it work.</p>
<p>Do you guys have any idea where I was doing something wrong?</p> | 15,086,346 | 2 | 4 | null | 2013-02-23 13:03:46.047 UTC | 3 | 2022-03-17 14:17:25.927 UTC | 2022-03-17 14:17:25.927 UTC | null | 37,055 | null | 1,432,368 | null | 1 | 36 | json|asp.net-mvc|asp.net-mvc-3|serialization|camelcasing | 30,456 | <p>The Json functions of the Controller are just wrappers for creating JsonResults:</p>
<pre><code>protected internal JsonResult Json(object data)
{
return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}
protected internal JsonResult Json(object data, string contentType)
{
return Json(data, contentType, null /* contentEncoding */, JsonRequestBehavior.DenyGet);
}
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding)
{
return Json(data, contentType, contentEncoding, JsonRequestBehavior.DenyGet);
}
protected internal JsonResult Json(object data, JsonRequestBehavior behavior)
{
return Json(data, null /* contentType */, null /* contentEncoding */, behavior);
}
protected internal JsonResult Json(object data, string contentType, JsonRequestBehavior behavior)
{
return Json(data, contentType, null /* contentEncoding */, behavior);
}
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
</code></pre>
<p>JsonResult internally uses JavaScriptSerializer, so you don't have control about the serialisation process:</p>
<pre><code>public class JsonResult : ActionResult
{
public JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.DenyGet;
}
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonRequestBehavior JsonRequestBehavior { get; set; }
/// <summary>
/// When set MaxJsonLength passed to the JavaScriptSerializer.
/// </summary>
public int? MaxJsonLength { get; set; }
/// <summary>
/// When set RecursionLimit passed to the JavaScriptSerializer.
/// </summary>
public int? RecursionLimit { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
if (MaxJsonLength.HasValue)
{
serializer.MaxJsonLength = MaxJsonLength.Value;
}
if (RecursionLimit.HasValue)
{
serializer.RecursionLimit = RecursionLimit.Value;
}
response.Write(serializer.Serialize(Data));
}
}
}
</code></pre>
<p>You have to create your own JsonResult and write your own Json Controller functions (if you need / want that). You can create new ones or overwrite existing ones, it is up to you. This <a href="http://yobriefca.se/blog/2010/11/20/better-json-serialisation-for-asp-dot-net-mvc/" rel="noreferrer">link</a> might also interest you.</p> |
8,320,153 | How do I hide axes and ticks in matlab without hiding everything else | <p>I draw images to axes in my matlab UI, but I don't want the axes and ticks to be visible how do I prevent that, and also where do I make this call?</p>
<p>I do this</p>
<pre><code>imagesc(myImage,'parent',handles.axesInGuide);
</code></pre> | 8,320,276 | 2 | 0 | null | 2011-11-30 01:42:28.51 UTC | 0 | 2019-03-20 15:02:44.053 UTC | 2011-11-30 02:22:10.05 UTC | null | 261,842 | null | 261,842 | null | 1 | 19 | matlab | 101,074 | <pre><code>axis off;
</code></pre>
<p>Is this what you are looking for?</p>
<p>This is definitely somewhere else on this website and in the matlab documentation. Try typing </p>
<p><code>help plot</code></p>
<p>Or using the documentation on plotting!</p>
<p>edit: Now that you have shown what you are doing. (You don't need the handles, I just always write them in to clutter my workspace)</p>
<pre><code>myImage = yurbuds0x2Dironman; # don't ask
fH = figure;
iH = imagesc(myImage);
set(gca,'xtick',[],'ytick',[])
</code></pre>
<p>Are you able to do it like this?</p> |
8,798,745 | How to get html elements from an object tag? | <p>I'm using the object tag to load an html snippet within an html page.</p>
<p>My code looks something along these lines:</p>
<p><code><html><object data="/html_template"></object></html></code></p>
<p>As expected after the page is loaded some elements are added between the object tags.
I want to get those elements but I can't seem to access them.</p>
<p>I've tried the following
<code>$("object").html()</code> <code>$("object").children()</code> <code>$("object")[0].innerHTML</code></p>
<p>None of these seem to work. Is there another way to get those elements?</p>
<p>EDIT:</p>
<p>A more detailed example:</p>
<p>consider this</p>
<p><code><html><object data="http://www.YouTube.com/v/GGT8ZCTBoBA?fs=1&hl=en_US"></object></html></code></p>
<p>If I try to get the html within the object I get an empty string.</p>
<p><a href="http://jsfiddle.net/wwrbJ/1/" rel="noreferrer">http://jsfiddle.net/wwrbJ/1/</a></p> | 46,527,064 | 8 | 3 | null | 2012-01-10 04:58:01.927 UTC | 4 | 2022-07-28 22:57:30.55 UTC | 2012-01-10 06:30:45.73 UTC | null | 421,323 | null | 421,323 | null | 1 | 30 | javascript|jquery|html | 71,743 | <p>No , it's not possible to get access to a cross-origin frame !</p> |
8,900,166 | What's the difference between lists enclosed by square brackets and parentheses in Python? | <pre><code>>>> x=[1,2]
>>> x[1]
2
>>> x=(1,2)
>>> x[1]
2
</code></pre>
<p>Are they both valid? Is one preferred for some reason?</p> | 8,900,189 | 7 | 3 | null | 2012-01-17 19:02:34.433 UTC | 64 | 2021-10-04 17:11:21.593 UTC | 2020-11-16 08:19:38.48 UTC | null | 7,878,602 | null | 1,150,778 | null | 1 | 206 | python|list|tuples | 201,631 | <p>Square brackets are <a href="http://docs.python.org/tutorial/datastructures.html#more-on-lists" rel="noreferrer">lists</a> while parentheses are <a href="https://docs.python.org/tutorial/datastructures.html#tuples-and-sequences" rel="noreferrer">tuples</a>.</p>
<p>A list is mutable, meaning you can change its contents:</p>
<pre><code>>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
</code></pre>
<p>while tuples are not:</p>
<pre><code>>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
</code></pre>
<p>The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:</p>
<pre><code>>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
</code></pre>
<hr>
<p>Note that, as many people have pointed out, you can add tuples together. For example:</p>
<pre><code>>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
</code></pre>
<p>However, <strong>this does not mean tuples are mutable</strong>. In the example above, a <em>new</em> tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:</p>
<pre><code>>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
</code></pre>
<p>Whereas, if you were to construct this same example with a list, <code>y</code> would also be updated:</p>
<pre><code>>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]
</code></pre> |
8,560,501 | android - save image into gallery | <p>i have an app with a gallery of images and i want that the user can save it into his own gallery.
I've created an option menu with a single voice "save" to allow that but the problem is...how can i save the image into the gallery?</p>
<p>this is my code:</p>
<pre><code>@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menuFinale:
imgView.setDrawingCacheEnabled(true);
Bitmap bitmap = imgView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
</code></pre>
<p>i'm not sure of this part of code:</p>
<pre><code>File root = Environment.getExternalStorageDirectory();
File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg");
</code></pre>
<p>is it correct to save into the gallery?
unfortunately the code doesn't work :(</p> | 8,722,494 | 12 | 4 | null | 2011-12-19 11:15:18.603 UTC | 62 | 2022-01-11 20:31:42.41 UTC | 2022-01-11 20:31:42.41 UTC | null | 1,889,720 | null | 345,812 | null | 1 | 111 | java|android|imageview|gallery|save-image | 225,246 | <pre><code>MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
</code></pre>
<p>The former code will add the image at the end of the gallery. If you want to modify the date so it appears at the beginning or any other metadata, see the code below (Cortesy of S-K, <em>samkirton</em>):</p>
<p><a href="https://gist.github.com/samkirton/0242ba81d7ca00b475b9" rel="noreferrer">https://gist.github.com/samkirton/0242ba81d7ca00b475b9</a></p>
<pre><code>/**
* Android internals have been modified to store images in the media folder with
* the correct date meta data
* @author samuelkirton
*/
public class CapturePhotoUtils {
/**
* A copy of the Android internals insertImage method, this method populates the
* meta data with DATE_ADDED and DATE_TAKEN. This fixes a common problem where media
* that is inserted manually gets saved at the end of the gallery (because date is not populated).
* @see android.provider.MediaStore.Images.Media#insertImage(ContentResolver, Bitmap, String, String)
*/
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F,Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
/**
* A copy of the Android internals StoreThumbnail method, it used with the insertImage to
* populate the android.provider.MediaStore.Images.Media#insertImage with all the correct
* meta data. The StoreThumbnail method is private so it must be duplicated here.
* @see android.provider.MediaStore.Images.Media (StoreThumbnail private method)
*/
private static final Bitmap storeThumbnail(
ContentResolver cr,
Bitmap source,
long id,
float width,
float height,
int kind) {
// create the matrix to scale it
Matrix matrix = new Matrix();
float scaleX = width / source.getWidth();
float scaleY = height / source.getHeight();
matrix.setScale(scaleX, scaleY);
Bitmap thumb = Bitmap.createBitmap(source, 0, 0,
source.getWidth(),
source.getHeight(), matrix,
true
);
ContentValues values = new ContentValues(4);
values.put(Images.Thumbnails.KIND,kind);
values.put(Images.Thumbnails.IMAGE_ID,(int)id);
values.put(Images.Thumbnails.HEIGHT,thumb.getHeight());
values.put(Images.Thumbnails.WIDTH,thumb.getWidth());
Uri url = cr.insert(Images.Thumbnails.EXTERNAL_CONTENT_URI, values);
try {
OutputStream thumbOut = cr.openOutputStream(url);
thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
thumbOut.close();
return thumb;
} catch (FileNotFoundException ex) {
return null;
} catch (IOException ex) {
return null;
}
}
}
</code></pre> |
30,794,083 | Android Navigation Bar covering viewpager content | <p>I can't stop the Systems Navigation Bar from covering up my content!</p>
<p><img src="https://i.stack.imgur.com/7XxMD.png" alt="enter image description here"></p>
<p>I am scrolled to the very bottom of the recyclerview but its getting hidden behind the navigation bar. Here is my XML layout.</p>
<pre><code><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<include layout="@layout/toolbar"/>
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:fitsSystemWindows="true"
android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />
<com.melnykov.fab.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"
app:fab_colorNormal="@color/accent"
app:fab_colorPressed="@color/accent_dark" />
</code></pre>
<p></p>
<p>Here is the fragments layout which you are seeing in the picture.</p>
<pre><code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="8dp">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"/>
</FrameLayout>
</code></pre>
<p>Ive tried adding android:fitsSystemWindows="true" into every piece of layout I could but that did not work. Other threads mention adding margin calculated from the bar, but that doesn't seem like the proper solution. I grabbed this layout directly from Google's CheesSquare app demo'ing the appbarlayout, and that one looks like its working fine.</p> | 34,644,745 | 7 | 7 | null | 2015-06-12 01:40:33.043 UTC | 2 | 2019-04-12 11:47:39.013 UTC | null | null | null | null | 3,352,901 | null | 1 | 29 | android|android-fragments|android-viewpager|navigationbar | 10,661 | <p>I Figured it out. In my particular situation each of my fragments manage their own toolbar instance. I was calling setSupportActionBar() in the onViewCreated() method on my fragments. Moving this functionality into onCreateView() solved it. </p>
<pre><code> @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_my_account, container, false);
setupToolbar((Toolbar) view.findViewById(R.id.toolbar));
return view;
}
private void setupToolbar(Toolbar toolbar) {
toolbarController.registerToolbar(toolbar);
toolbarController.setActivityTitle("My Account");
}
</code></pre>
<p>(registerToolbar() calls setSupportActionBar() inside the hosting activity).</p>
<p>Hope this helps everyone!</p> |
4,941,606 | Changing gradient background colors on Android at runtime | <p>I'm experimenting with Drawable backgrounds and have had no problems so far.</p>
<p>I'm now trying to change the gradient background color at runtime.</p>
<p>Unfortunately, there's no API to change it at runtime, it seems. Not even by trying to mutate() the drawable, as explained here: <a href="http://android-developers.blogspot.com/2009/05/drawable-mutations.html" rel="noreferrer">Drawable mutations</a></p>
<p>The sample XML looks like this. It works, as expected.</p>
<pre><code><shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#330000FF"
android:endColor="#110000FF"
android:angle="90"/>
</shape>
</code></pre>
<p>Sadly, I want a list with various colors, and they'd have to be programatically altered at runtime.</p>
<p>Is there another way to create this gradient background at runtime? Perhaps even not using XML altogether?</p> | 4,943,888 | 5 | 0 | null | 2011-02-09 05:23:19.69 UTC | 15 | 2022-01-25 04:49:53.447 UTC | null | null | null | null | 215,768 | null | 1 | 28 | android|background|gradient|drawable | 34,348 | <p>Yes! Found a way!</p>
<p>Had to forget about XML, but here's how I did it:</p>
<p>On my getView() overloaded function (ListAdapter) I just had to:</p>
<pre><code> int h = v.getHeight();
ShapeDrawable mDrawable = new ShapeDrawable(new RectShape());
mDrawable.getPaint().setShader(new LinearGradient(0, 0, 0, h, Color.parseColor("#330000FF"), Color.parseColor("#110000FF"), Shader.TileMode.REPEAT));
v.setBackgroundDrawable(mDrawable);
</code></pre>
<p>And that gave me the same result as the XML background above. Now I can programmatically set the background color.</p> |
5,047,798 | Which MinGW file to use as a C++ compiler | <p>I have just installed MinGW and in the bin folder I can see 7 .exe files that compile my program:</p>
<ol>
<li>c++.exe</li>
<li>g++.exe</li>
<li>mingw32-c++.exe</li>
<li>mingw32-g++.exe</li>
<li>gcc.exe</li>
<li>mingw32-gcc.exe</li>
<li>mingw32-gcc-4.4.1.exe</li>
</ol>
<p>My small program (testprog.cpp) compiles correctly with each of them; the <code>a.exe</code> file is generated in the bin folder and it runs correctly.</p>
<p>What's the difference between them and which one should I use?
Also, what can I do to change the name of the output file from a.exe to testprog.exe automatically upon each successful compile?</p> | 5,047,814 | 5 | 1 | null | 2011-02-18 23:54:03.967 UTC | 5 | 2022-06-28 15:19:53.91 UTC | 2012-12-01 04:46:41.82 UTC | null | 4,714 | null | 4,714 | null | 1 | 28 | c++|c|compiler-construction|mingw | 14,275 | <p>It's quite possible that they are all the same; either exact copies or symbolic links to one another. Try using the <code>--version</code> flag on each to see what you've got. On my MingGW installation here, each of those binaries differs (checked with <code>diff</code>), but they all output the same version information (with the exception of the first bit, which is the filename):</p>
<pre><code>gcc.exe (GCC) 3.4.5 (mingw-vista special r3)
Copyright (C) 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
</code></pre>
<p>Use the <code>-o</code> flag to change the output file name:</p>
<pre><code>gcc -o testprog.exe testprog.cpp
</code></pre> |
5,141,431 | Get input value after keydown/keypress | <p>I have an <code><input type="text"></code>, and I need to call a function after the text in the text box was changed (inluding actions performed during jQuery's keydown and keypress handlers).</p>
<p>If I call my function from the jQuery handler, I see the value (<code>e.target.value</code>) as it was before the input was added. As I don't want to manually add the input onto the value every time, how I can call my function and have it use the updated value?</p> | 5,141,458 | 6 | 0 | null | 2011-02-28 11:36:10.727 UTC | 4 | 2020-01-21 11:32:36.197 UTC | 2019-08-20 16:36:52.697 UTC | null | 4,370,109 | null | 275,109 | null | 1 | 25 | javascript|jquery|jquery-events | 68,701 | <p>If I understand you right then something like this is the way u can do it</p>
<pre><code>$('input').bind('change keydown keyup',function (){
/// do your thing here.
// use $(this).val() instead e.target.value
});
</code></pre>
<p><strong>Updated</strong>: 03/05/13</p>
<p><strong>Please note</strong>: that you are better off to use <code>.on()</code> as oppose to <code>.bind()</code></p>
<blockquote>
<p>As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().</p>
</blockquote>
<p>For more information <a href="http://api.jquery.com/bind/#bind-events" rel="noreferrer">jQuery Bind</a></p> |
5,327,668 | Calling toString on a javascript function returns source code | <p>I just found out that when you call toString() on a javascript function, as in <code>myFunction.toString()</code>, the source code of that function is returned.</p>
<p>If you try it in the Firebug or Chrome console it will even go as far as formatting it nicely for you, even for minimized javascript files.<br>
I don't know what is does for obfuscated files.</p>
<p>What's the use of such a toString implementation?</p> | 5,328,782 | 6 | 2 | null | 2011-03-16 15:33:55.87 UTC | 9 | 2021-06-28 10:42:51.987 UTC | 2011-03-22 19:18:53.407 UTC | null | 93,356 | null | 93,356 | null | 1 | 37 | javascript|tostring | 46,631 | <p>It has some use for debugging, since it lets you see the code of the function. You can check if a function has been overwritten, and if a variable points to the right function.</p>
<p>It has some uses for obfuscated javascript code. If you want to do hardcore obfuscation in javascript, you can transform your whole code into a bunch of special characters, and leave no numbers or letters. This technique relies heavily on being able to access most letters of the alphabet by forcing the toString call on everything with <code>+""</code></p>
<p>example: <code>(![]+"")[+[]]</code> is <code>f</code> since <code>(![]+"")</code> evaluates to the string <code>"false"</code> and <code>[+[]]</code> evaluates to <code>[0]</code>, thus you get <code>"false"[0]</code> which extracts the first letter <code>f</code>.</p>
<p>Some letters like <code>v</code> can only be accessed by calling toString on a native function like <code>[].sort</code>. The letter <code>v</code> is important for obfuscated code, since it lets you call <code>eval</code>, which lets you execute anything, even loops, without using any letters. <a href="https://codegolf.stackexchange.com/questions/88/obfuscated-fizzbuzz-golf/100#100">Here is an example of this</a>.</p> |
5,417,727 | Get date object for the first/last day of the current year | <p>I need to get <code>date</code> objects for the first and last day in the current year.</p>
<p>Currently I'm using this code which works fine, but I'm curious if there's a nicer way to do it; e.g. without having to specify the month/day manually.</p>
<pre><code>from datetime import date
a = date(date.today().year, 1, 1)
b = date(date.today().year, 12, 31)
</code></pre> | 5,417,911 | 6 | 8 | null | 2011-03-24 10:28:18.47 UTC | 10 | 2021-08-17 11:42:17.297 UTC | 2015-11-10 15:16:15.273 UTC | null | 298,479 | null | 298,479 | null | 1 | 65 | python|date | 55,262 | <p>The only real improvement that comes to mind is to give your variables more descriptive names than <code>a</code> and <code>b</code>.</p> |
5,323,818 | Condensed matrix function to find pairs | <p>For a set of observations:</p>
<pre><code>[a1,a2,a3,a4,a5]
</code></pre>
<p>their pairwise distances</p>
<pre><code>d=[[0,a12,a13,a14,a15]
[a21,0,a23,a24,a25]
[a31,a32,0,a34,a35]
[a41,a42,a43,0,a45]
[a51,a52,a53,a54,0]]
</code></pre>
<p>Are given in a condensed matrix form (upper triangular of the above, calculated from <code>scipy.spatial.distance.pdist</code> ):</p>
<pre><code>c=[a12,a13,a14,a15,a23,a24,a25,a34,a35,a45]
</code></pre>
<p>The question is, given that I have the index in the condensed matrix is there a function (in python preferably) <strong>f</strong> to quickly give which two observations were used to calculate them?</p>
<pre><code>f(c,0)=(1,2)
f(c,5)=(2,4)
f(c,9)=(4,5)
...
</code></pre>
<p>I have tried some solutions but none worth mentioning :(</p> | 5,323,902 | 7 | 0 | null | 2011-03-16 10:16:57.647 UTC | 11 | 2021-06-09 00:21:09.463 UTC | 2011-03-16 14:56:19.167 UTC | null | 188,368 | null | 188,368 | null | 1 | 10 | python|algorithm|math|statistics|scipy | 3,172 | <p>You may find <a href="http://docs.scipy.org/doc/numpy-1.5.x/reference/generated/numpy.triu_indices.html#numpy.triu_indices" rel="nofollow noreferrer">triu_indices</a> useful. Like,</p>
<pre><code>In []: ti= triu_indices(5, 1)
In []: r, c= ti[0][5], ti[1][5]
In []: r, c
Out[]: (1, 3)
</code></pre>
<p>Just notice that indices starts from 0. You may adjust it as you like, for example:</p>
<pre><code>In []: def f(n, c):
..: n= ceil(sqrt(2* n))
..: ti= triu_indices(n, 1)
..: return ti[0][c]+ 1, ti[1][c]+ 1
..:
In []: f(len(c), 5)
Out[]: (2, 4)
</code></pre> |
5,001,488 | Zend Framework 1.11 with Doctrine 2 Integration | <p>Could someone explain in detail how to integrate Doctrine 2 and Zend Framework 1.11?</p> | 5,002,011 | 7 | 1 | null | 2011-02-15 08:53:30.6 UTC | 11 | 2014-05-27 11:37:54.057 UTC | 2011-02-15 09:22:33.123 UTC | null | 11,568 | null | 264,990 | null | 1 | 19 | php|zend-framework|orm|doctrine | 21,089 | <p>There is a great video by Jon Lebensold about integrating D2 and ZF: <a href="http://www.zendcasts.com/unit-testing-doctrine-2-entities/2011/02/">Unit Testing Doctrine 2</a> - don't be misleaded by the title :)</p> |
5,427,454 | How do I pipe or redirect the output of curl -v? | <p>For some reason the output always gets printed to the terminal, regardless of whether I redirect it via 2> or > or |. Is there a way to get around this? Why is this happening?</p> | 5,427,484 | 9 | 1 | null | 2011-03-25 01:03:47.363 UTC | 37 | 2022-05-12 12:39:41.623 UTC | null | null | null | null | 329,781 | null | 1 | 144 | linux|unix|curl | 266,020 | <p>add the <code>-s</code> (silent) option to remove the progress meter, then redirect stderr to stdout to get verbose output on the same fd as the response body</p>
<pre><code>curl -vs google.com 2>&1 | less
</code></pre> |
16,610,607 | Store XML Data in a mongodb collection | <p>I am still relatively new to NoSQL databases like mongodb, so excuse my ignorance.</p>
<p><strong>Background:</strong></p>
<p>Right now, I have a system that does the following:</p>
<ol>
<li>gathers system data from clients</li>
<li>outputs that info into an xml document</li>
<li>a perl script takes the data in the xml tags and puts it in a mySQL db.</li>
<li>an apache/php powered website displays the data.</li>
</ol>
<p>The purpose of this system is to act as an inventory for servers/chassis/network devices/etc.</p>
<p>This has been an okay system, but I have decided to go to a non-relational database because of the advantages I see in using that for the type of data I am storing. </p>
<p><strong>Question:</strong></p>
<ol>
<li>Is it very simple to extract information from xml documents with mongodb? </li>
<li>Should I rewrite the scripts I have to output a JSON/BSON file instead of XML? </li>
<li>How do you take the information from files and put it into a mongodb database?</li>
</ol> | 16,613,296 | 4 | 0 | null | 2013-05-17 13:43:17.053 UTC | 2 | 2015-10-26 09:39:45.753 UTC | 2013-05-17 19:07:22.42 UTC | null | 843,443 | null | 843,443 | null | 1 | 7 | xml|mongodb | 46,554 | <p>When moving to a NoSQL document DB, the decision is highly influenced by <strong>how the data is read or used by the client/user</strong> as the data is mostly pre-aggregated/pre-joined based on the usage patterns. So, technically you can move to mongodb "technically" by just converting the data to json/bson instead of xml while importing the data.</p> |
17,121,706 | using map(int, raw_input().split()) | <p>Though I like python very much, When I need to get multiple integer inputs in the same line, I prefer C/C++. If I use python, I use:</p>
<pre><code>a = map(int, raw_input().split())
</code></pre>
<p>Is this the only way or is there any pythonic way to do it? And does this cost much as far as time is considered? </p> | 17,121,719 | 4 | 4 | null | 2013-06-15 08:35:09.073 UTC | 8 | 2018-09-06 13:59:41.597 UTC | 2013-06-15 08:46:09.837 UTC | null | 1,971,805 | null | 2,046,858 | null | 1 | 10 | python|map|raw-input | 90,485 | <p>If you're using map with built-in function then it can be slightly faster than LC:</p>
<pre><code>>>> strs = " ".join(str(x) for x in xrange(10**5))
>>> %timeit [int(x) for x in strs.split()]
1 loops, best of 3: 111 ms per loop
>>> %timeit map(int, strs.split())
1 loops, best of 3: 105 ms per loop
</code></pre>
<p>With user-defined function:</p>
<pre><code>>>> def func(x):
... return int(x)
>>> %timeit map(func, strs.split())
1 loops, best of 3: 129 ms per loop
>>> %timeit [func(x) for x in strs.split()]
1 loops, best of 3: 128 ms per loop
</code></pre>
<p>Python 3.3.1 comparisons:</p>
<pre><code>>>> strs = " ".join([str(x) for x in range(10**5)])
>>> %timeit list(map(int, strs.split()))
10 loops, best of 3: 59 ms per loop
>>> %timeit [int(x) for x in strs.split()]
10 loops, best of 3: 79.2 ms per loop
>>> def func(x):
return int(x)
...
>>> %timeit list(map(func, strs.split()))
10 loops, best of 3: 94.6 ms per loop
>>> %timeit [func(x) for x in strs.split()]
1 loops, best of 3: 92 ms per loop
</code></pre>
<p>From <a href="http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Loops" rel="nofollow">Python performance tips</a> page:</p>
<blockquote>
<p>The only restriction is that the "loop body" of map must be a function
call. Besides the syntactic benefit of list comprehensions, they are
often as fast or faster than equivalent use of map.</p>
</blockquote> |
12,097,726 | Ruby classes: initialize self vs. @variable | <p>Can someone explain the difference between initializing "self" and having @variables when defining classes?</p>
<p>Here's an example</p>
<pre><code>class Child < Parent
def initialize(self, stuff):
self.stuff = stuff
super()
end
end
</code></pre>
<p>So in this case, wouldn't I be able to replace <code>self.stuff</code> with <code>@stuff</code>? What's the difference? Also, the <code>super()</code> just means whatever is in the Parent initialize method the Child should just inherit it right?</p> | 12,097,864 | 2 | 2 | null | 2012-08-23 18:15:19.117 UTC | 9 | 2012-08-23 21:40:09.77 UTC | 2012-08-23 18:17:49.303 UTC | null | 458,137 | null | 1,555,312 | null | 1 | 14 | ruby | 12,459 | <p>In general, no, <code>self.stuff = stuff</code> and <code>@stuff = stuff</code> are different. The former makes a method call to <code>stuff=</code> on the object, whereas the latter directly sets an instance variable. The former invokes a method which may be public (unless specifically declared private in the class), whereas the latter is always setting a private instance variable.</p>
<p>Usually, they look the same because it is common to define <code>attr_accessor :stuff</code> on classes. <code>attr_accessor</code> is roughly equivalent to the following:</p>
<pre><code>def stuff
@stuff
end
def stuff=(s)
@stuff = s
end
</code></pre>
<p>So in that case, they are functionally identical. However, it is possible to define the public interface to allow for different results and side-effects, which would make those two "assignments" clearly different:</p>
<pre><code>def stuff
@stuff_called += 1 # Keeps track of how often this is called, a side effect
return @stuff
end
def stuff=(s)
if s.nil? # Validation, or other side effect. This is not triggered when setting the instance variable directly
raise "Argument should not be nil"
end
@stuff = s
end
</code></pre> |
12,135,793 | Generating API tokens using node | <p>I am writing an app that will expose an API. The application allows people to create workspaces and add users to them. Each user will have a unique token. When they make an API call, they will use that token (which will identify them as that user using that workspace.</p>
<p>At the moment I am doing this:</p>
<pre><code>var w = new Workspace(); // This is a mongoose model
w.name = req.body.workspace;
w.activeFlag = true;
crypto.randomBytes(16, function(err, buf) {
if(err){
next(new g.errors.BadError503("Could not generate token") );
} else {
var token = buf.toString('hex');
// Access is the list of users who can access it. NOTE that
// the token is all they will pass when they use the API
w.access = { login: req.session.login, token:token, isOwner: true };
w.save( function(err){
if(err){
next(new g.errors.BadError503("Database error saving workspace") );
</code></pre>
<p>Is this a good way to generate API tokens?</p>
<p>Since the token is name+workspace, maybe I should do something like md5(username+workspace+secret_string) ...?</p> | 12,135,990 | 4 | 0 | null | 2012-08-27 03:05:38.1 UTC | 8 | 2021-09-13 00:40:36.597 UTC | 2017-07-02 18:22:04.93 UTC | null | 2,311,366 | null | 829,771 | null | 1 | 20 | node.js | 34,778 | <p>If you using mongodb just use ObjectId, othewise I recommend substack's <a href="https://github.com/substack/node-hat">hat</a> module.</p>
<p>To generate id is simple as </p>
<pre><code>var hat = require('hat');
var id = hat();
console.log(id); // 1c24171393dc5de04ffcb21f1182ab28
</code></pre> |
12,406,750 | Find an item in a generic list by specifying multiple conditions | <p>Most often we find generic list with code like:</p>
<pre><code>CartItem Item = Items.Find(c => c.ProductID == ProductID);
Item.Quantity = Quantity;
Item.Price = Price;
</code></pre>
<p>So the above code finds and updates with other data, but if I want to find by multiple conditions, then how do I write the code?</p>
<p>I want to write code like:</p>
<pre><code>CartItem Item = Items.Find(c => c.ProductID == ProductID and c.ProductName == "ABS001");
</code></pre>
<p>Please guide me for multiple conditions when we find generic list.</p> | 12,406,785 | 5 | 2 | null | 2012-09-13 12:54:07.01 UTC | 8 | 2018-05-23 10:54:31.16 UTC | 2016-10-20 09:01:38.267 UTC | null | 63,550 | null | 508,127 | null | 1 | 22 | c#|linq|lambda | 89,180 | <p>Try this: </p>
<pre><code>CartItem Item = Items.Find(c => (c.ProductID == ProductID) && (c.ProductName == "ABS001"));
</code></pre> |
12,603,425 | Expand and collapse with angular js | <p>I am trying to figure out a way to do an expand and collapse using angular js. I haven't been able to find an elegant way to do this without manipulating dom objects in the controller (which is not the angular way). Currently I have a nice way to do it for a one layer expand and collapse. However when I start nesting, things get complicated and don't work the way I want it to (expanding and collapsing multiple areas when they shouldn't be). The problem comes in by me not knowing how to send a unique identifier with an ng-click to only expand/collapse the right content. I should mention that these items are in an ng-repeat so I can necessarily customize parameters being sent.</p>
<p>I was able to use this <a href="http://jsfiddle.net/rur_d/tNZAm/" rel="noreferrer">jsfiddle</a> to help me get a one layer expand and collapse to work. However this is a toggle way to do it and I want the user to be able to keep things expanded while expanding others. So what I did to fix this was use an array of and every time something is clicked the index of that clicked item would be added to the array and the class expanded. When the user clicked again the index was removed from the array and the area was collapsed.</p>
<p>Another way I found that you can do it is by using directives. But I can't really find any exampled to wrap my head around how directives work. I am not sure how to even start when it comes to writing directives.</p>
<p>My current set up is this:</p>
<pre><code>function Dexspander($scope) {
$scope.ExpandArray = [];
//Push or pop necessary elements for tracking
$scope.DespopulatArray = function (identifier, element) {
if (_.indexOf($scope.ExpandArray, identifier + element) != -1) {
$scope.ExpandArray.splice(_.indexOf($scope.ExpandArray, identifier + element), 1);
} else {
$scope.ExpandArray.push(identifier + element);
}
}
//Change class of necessary elements
$scope.Dexspand = function (identifier, element) {
if (_.indexOf($scope.ExpandArray, identifier + element) != -1) {
return "expand";
} else {
return "collapse";
}
}
}
<div class="user-header" ng-repeat="user in users">
<h1 ng-click="DespopulatArray('user', $index)">Expand</h1>
</div>
<div class="user-content" ng:class="Dexspand('user', $index)">
<div class="content">
<div class="user-information">
<div class="info-header">
<h1 ng-click="DespopulatArray('info', $index)>Some Information</h1>
</div>
<div class="info-contents" ng:class="Dexspand('info', $index)">
stuff stuff stuff stuff...
</div>
</div>
</div>
</div>
</code></pre>
<p>The issue with this setup is that if I have to parent divs expanded and those both have something under them to expand, clicking the expand text will expand them in both areas as they are not unique.</p> | 14,296,257 | 6 | 1 | null | 2012-09-26 13:57:23.723 UTC | 10 | 2017-12-06 10:57:11.83 UTC | 2012-09-27 16:04:26.17 UTC | null | 21,217 | null | 692,197 | null | 1 | 23 | javascript|expand|collapse|angularjs | 130,375 | <blockquote>
<p>The problem comes in by me not knowing how to send a unique identifier with an ng-click to only expand/collapse the right content.</p>
</blockquote>
<p>You can pass <code>$event</code> with ng-click (ng-dblclick, and ng- mouse events), then you can determine which element caused the event:</p>
<pre><code><a ng-click="doSomething($event)">do something</a>
</code></pre>
<p>Controller:</p>
<pre><code>$scope.doSomething = function(ev) {
var element = ev.srcElement ? ev.srcElement : ev.target;
console.log(element, angular.element(element))
...
}
</code></pre>
<hr>
<p>See also <a href="http://angular-ui.github.com/bootstrap/#/accordion" rel="noreferrer">http://angular-ui.github.com/bootstrap/#/accordion</a></p> |
12,084,015 | iOS Push Notification - How to get the notification data when you click on the app icon instead of notification | <p>Similar to this question: <a href="https://stackoverflow.com/questions/6732427/how-do-i-access-remote-push-notification-data-on-applicationdidbecomeactive">How do I access remote push notification data on applicationDidBecomeActive?</a></p>
<p>But the different is how can you access the notification data when you are in<code>applicationDidBecomeActive</code> and <strong>if you have clicked on the app icon instead of the push notification.</strong></p>
<p>The flow is: If you click on the <code>push notification</code> then <code>didReceiveRemoteNotification</code> will be triggered, but if you click on the original app icon, only <code>applicationDidBecomeActive</code> will be triggered and <code>didReceiveRemoteNotification</code> will not be called.</p>
<p>I am looking for the later case so how can I access the push notification data.</p>
<p>(Both case assuming the app is in background and not killed yet.)</p> | 12,084,129 | 4 | 2 | null | 2012-08-23 02:37:22.18 UTC | 20 | 2016-08-30 19:59:36.32 UTC | 2017-05-23 11:54:18.733 UTC | null | -1 | null | 365,256 | null | 1 | 37 | iphone|ios|xcode|push-notification|apple-push-notifications | 18,359 | <p>You can't get remote push payload by launching app from homescreen.</p>
<p>If the push data is important for app use, load it from your server after app launched.</p> |
12,600,214 | contentView not indenting in iOS 6 UITableViewCell prototype cell | <p>I am configuring a custom <code>UITableViewCell</code> using a prototype cell in a Storyboard. However, all the <code>UILabel</code>s (and other UI elements) do not seem to be added to the cell's <code>contentView</code>, instead being added to the <code>UITableViewCell</code> view directly. This creates issues when the cell is put into editing mode, as the content is not automatically shifted/indented (which it would do, if they were inside the <code>contentView</code>).</p>
<p>Is there any way to add the UI elements to the <code>contentView</code> when laying out the cell using Interface Builder/Storyboard/prototype cells? The only way I have found is to create everything in code and use <code>[cell.contentView addSubView:labelOne]</code> which wouldn't be great, as it is much easier to layout the cell graphically.</p> | 12,657,891 | 6 | 2 | null | 2012-09-26 11:00:00.747 UTC | 33 | 2013-12-06 16:55:46.623 UTC | 2012-09-30 01:18:22.853 UTC | null | 257,314 | null | 257,314 | null | 1 | 40 | ios|uitableview|ios6 | 20,080 | <p>On further investigation (viewing the subview hierarchy of the cell) Interface Builder does place subviews within the cell's <code>contentView</code>, it just doesn't look like it.</p>
<p>The root cause of the issue was iOS 6 autolayout. When the cell is placed into editing mode (and indented) the <code>contentView</code> is also indented, so it stands to reason that all subviews within the <code>contentView</code> will move (indent) by virtue of being within the <code>contentView</code>. However, all the autolayout constraints applied by Interface Builder seem to be relative to the <code>UITableViewCell</code> itself, rather than the <code>contentView</code>. This means that even though the <code>contentView</code> indents, the subviews contained within do not - the constraints take charge.</p>
<p>For example, when I placed a <code>UILabel</code> into the cell (and positioned it 10 points from the left-hand side of the cell) IB automatically applied a constraint "Horizontal Space (10)". However, this constraint is relative to the <code>UITableViewCell</code> NOT the <code>contentView</code>. This means that when the cell is indented, and the <code>contentView</code> moves, the label stays put as it is complying with the constraint to remain 10 points from the left-hand side of the <code>UITableViewCell</code>.</p>
<p>Unfortunately (as far as I am aware) there is no way to remove these IB created constraints from within IB itself, so here is how I solved the problem.</p>
<p>Within the <code>UITableViewCell</code> subclass for the cell, I created an <code>IBOutlet</code> for that constraint called <code>cellLabelHSpaceConstraint</code>. You also need an <code>IBOutlet</code> for the label itself, which I called <code>cellLabel</code>. I then implemented the <code>-awakeFromNib</code> method as per below:</p>
<pre><code>- (void)awakeFromNib {
// -------------------------------------------------------------------
// We need to create our own constraint which is effective against the
// contentView, so the UI elements indent when the cell is put into
// editing mode
// -------------------------------------------------------------------
// Remove the IB added horizontal constraint, as that's effective
// against the cell not the contentView
[self removeConstraint:self.cellLabelHSpaceConstraint];
// Create a dictionary to represent the view being positioned
NSDictionary *labelViewDictionary = NSDictionaryOfVariableBindings(_cellLabel);
// Create the new constraint
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"|-10-[_cellLabel]" options:0 metrics:nil views:labelViewDictionary];
// Add the constraint against the contentView
[self.contentView addConstraints:constraints];
}
</code></pre>
<p>In summary, the above will remove the horizontal spacing constraint which IB automatically added (as is effective against the <code>UITableViewCell</code> rather than the <code>contentView</code>) and we then define and add our own constraint to the <code>contentView</code>.</p>
<p>In my case, all the other <code>UILabels</code> in the cell were positioned based upon the position of the <code>cellLabel</code> so when I fixed up the constraint/positioning of this element all the others followed suit and positioned correctly. However, if you have a more complex layout then you may need to do this for other subviews as well. </p> |
12,276,957 | Are there any non-twos-complement implementations of C? | <p><a href="https://stackoverflow.com/questions/3952123/representation-of-negative-numbers-in-c/3952262#3952262">As we all no doubt know</a>, the ISO C standard (and C++ as well, I think, though I'm more interested on the C side) allows three underlying representations of signed numbers:</p>
<ul>
<li>two's complement;</li>
<li>ones' complement; and</li>
<li>sign/magnitude.</li>
</ul>
<p>Wikipedia's entry states that sign/magnitude is used on the IBM 7090 from the 60s, and that ones' complement is used by the PDP-1, CDC 160A and UNIVAC 1100, all of which date back to the 60s as well.</p>
<p>Are there any other implementations of C (or underlying hardware) with these alternative representations, that have come out a little more recently than fifty years ago (and what are they)?</p>
<p>It seems a little wasteful to keep something in a standard for machines no longer in existence.</p> | 12,277,974 | 2 | 6 | null | 2012-09-05 07:58:52.633 UTC | 14 | 2016-11-10 08:56:24.593 UTC | 2017-05-23 12:09:57.707 UTC | null | -1 | null | 14,860 | null | 1 | 48 | c|language-lawyer|iso|negative-number|representation | 5,157 | <p>The most recent example I can find is the <a href="http://en.wikipedia.org/wiki/UNIVAC_1100/2200_series#UNISYS_2200_series" rel="noreferrer">UNISYS 2200</a> series, based on UNIVAC, with ones-complement arithmetic. The various models were produced between 1986 and 1997 but the OS was still in active development <a href="http://en.wikipedia.org/wiki/Unisys_OS_2200_operating_system" rel="noreferrer">as late as 2015</a>. They also had a C compiler, as seen <a href="http://en.wikipedia.org/wiki/Unisys_OS_2200_programming_languages" rel="noreferrer">here</a>.</p>
<p>It seems likely that they may still be in use today.</p> |
19,058,530 | change format from wav to mp3 in memory stream in NAudio | <p>Hi there iam trying to convert text to speech (wav) in the memorystream convert it to mp3 and then play it on the users page.so need i help what to do next? </p>
<p>here is my asmx code :</p>
<pre><code>[WebMethod]
public byte[] StartSpeak(string Word)
{
MemoryStream ms = new MemoryStream();
using (System.Speech.Synthesis.SpeechSynthesizer synhesizer = new System.Speech.Synthesis.SpeechSynthesizer())
{
synhesizer.SelectVoiceByHints(System.Speech.Synthesis.VoiceGender.NotSet, System.Speech.Synthesis.VoiceAge.NotSet, 0, new System.Globalization.CultureInfo("en-US"));
synhesizer.SetOutputToWaveStream(ms);
synhesizer.Speak(Word);
}
return ms.ToArray();
}
</code></pre>
<p>Thanks.</p> | 19,110,254 | 6 | 3 | null | 2013-09-27 19:21:10.463 UTC | 11 | 2021-06-01 06:59:39.54 UTC | null | null | null | null | 2,431,114 | null | 1 | 14 | c#|asp.net|audio|naudio | 33,780 | <p>You need an MP3 compressor library. I use Lame via the Yeti Lame wrapper. You can find code and a sample project <a href="http://www.codeproject.com/Articles/5901/C-MP3-Compressor" rel="nofollow noreferrer">here</a>.</p>
<p>Steps to get this working:</p>
<ol>
<li><p>Copy the following files from <code>MP3Compressor</code> to your project:</p>
<ul>
<li><code>AudioWriters.cs</code></li>
<li><code>Lame.cs</code></li>
<li><code>Lame_enc.dll</code></li>
<li><code>Mp3Writer.cs</code></li>
<li><code>Mp3WriterConfig.cs</code></li>
<li><code>WaveNative.cs</code></li>
<li><code>WriterConfig.cs</code></li>
</ul>
<br/>
</li>
<li><p>In the project properties for <code>Lame_enc.dll</code> set the <code>Copy to Output</code> property to <code>Copy if newer</code> or <code>Copy always</code>.</p>
</li>
<li><p>Edit <code>Lame.cs</code> and replace all instances of:</p>
<pre><code>[DllImport("Lame_enc.dll")]
</code></pre>
<p>with:</p>
<pre><code>[DllImport("Lame_enc.dll", CallingConvention = CallingConvention.Cdecl)]
</code></pre>
</li>
<li><p>Add the following code to your project:</p>
<pre><code>public static Byte[] WavToMP3(byte[] wavFile)
{
using (MemoryStream source = new MemoryStream(wavFile))
using (NAudio.Wave.WaveFileReader rdr = new NAudio.Wave.WaveFileReader(source))
{
WaveLib.WaveFormat fmt = new WaveLib.WaveFormat(rdr.WaveFormat.SampleRate, rdr.WaveFormat.BitsPerSample, rdr.WaveFormat.Channels);
// convert to MP3 at 96kbit/sec...
Yeti.Lame.BE_CONFIG conf = new Yeti.Lame.BE_CONFIG(fmt, 96);
// Allocate a 1-second buffer
int blen = rdr.WaveFormat.AverageBytesPerSecond;
byte[] buffer = new byte[blen];
// Do conversion
using (MemoryStream output = new MemoryStream())
{
Yeti.MMedia.Mp3.Mp3Writer mp3 = new Yeti.MMedia.Mp3.Mp3Writer(output, fmt, conf);
int readCount;
while ((readCount = rdr.Read(buffer, 0, blen)) > 0)
mp3.Write(buffer, 0, readCount);
mp3.Close();
return output.ToArray();
}
}
}
</code></pre>
</li>
<li><p>Either add a reference to <code>System.Windows.Forms</code> to your project (if it's not there already), or edit <code>AudioWriter.cs</code> and <code>WriterConfig.cs</code> to remove the references. Both of these have a <code>using System.Windows.Forms;</code> that you can remove, and <code>WriterConfig.cs</code> has a <code>ConfigControl</code> declaration that needs to be removed/commented out.</p>
</li>
</ol>
<p>Once all of that is done you should have a functional in-memory wave-file to MP3 converter that you can use to convert the WAV file that you are getting from the <code>SpeechSynthesizer</code> into an MP3.</p> |
24,001,410 | PHP: json_decode not working | <p>This does <strong>not</strong> work:</p>
<pre><code>$jsonDecode = json_decode($jsonData, TRUE);
</code></pre>
<p>However if I copy the string from <code>$jsonData</code> and put it inside the decode function manually it does work. </p>
<p>This <strong>works</strong>:</p>
<pre><code>$jsonDecode = json_decode('{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}', TRUE);
</code></pre>
<p>I did output <code>$jsonData</code> copied it and put in like above in the decode function. Then it worked. However if I put <code>$jsonData</code> directly in the decode function it does not.</p>
<p><code>var_dump($jsonData)</code> shows:</p>
<pre><code>string(144) "{"id":"0","bid":"918","url":"http:\/\/www.google.com","md5":"6361fbfbee69f444c394f3d2fa062f79","time":"2014-06-02 14:20:21"}"
</code></pre>
<p>The <code>$jsonData</code> comes from a encrypted <code>$_GET</code> variable. To encrypt it I use this:</p>
<pre><code>$key = "SOME KEY";
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$enc = mcrypt_encrypt(MCRYPT_BLOWFISH, $key, $data, MCRYPT_MODE_ECB, $iv);
$iv = rawurlencode(base64_encode($iv));
$enc = rawurlencode(base64_encode($enc));
//To Decrypt
$iv = base64_decode(rawurldecode($_GET['i']));
$enc = base64_decode(rawurldecode($_GET['e']));
$data = mcrypt_decrypt(MCRYPT_BLOWFISH, $key, $enc, MCRYPT_MODE_ECB, $iv);
</code></pre> | 24,001,627 | 17 | 7 | null | 2014-06-02 18:57:52.943 UTC | 3 | 2022-09-19 13:40:10.697 UTC | 2014-06-02 19:20:18.207 UTC | null | 3,630,453 | null | 3,630,453 | null | 1 | 30 | php|json | 89,751 | <p>Most likely you need to strip off the padding from your decrypted data. There are 124 visible characters in your string but <code>var_dump</code> reports 144. Which means 20 characters of padding needs to be removed (a series of "\0" bytes at the end of your string).</p>
<p>Probably that's 4 "\0" bytes at the end of a block + an empty 16-bytes block (to mark the end of the data).</p>
<p>How are you currently decrypting/encrypting your string?</p>
<p><strong>Edit</strong>:</p>
<p>You need to add this to trim the zero bytes at the end of the string:</p>
<pre><code>$jsonData = rtrim($jsonData, "\0");
</code></pre> |
3,594,143 | Dynamically set a hyperlink control's NavigateUrl property inline | <p>How can I dynamically set a stand alone(not in gridview) hyperlink control's NavigateUrl property inline in the aspx page?</p>
<p>I have tried to do the following, but it did not work.</p>
<pre><code><asp:HyperLink id="MyLink"
NavigateUrl="../mypage.aspx?id=<%= pageid %>"
runat="server">My Page</asp:HyperLink>
</code></pre> | 3,594,162 | 3 | 0 | null | 2010-08-29 08:51:54.467 UTC | 3 | 2018-06-25 07:23:16.983 UTC | 2018-06-25 07:23:16.983 UTC | null | 584,518 | null | 32,892 | null | 1 | 15 | asp.net|.net|hyperlink|webforms | 80,544 | <p>You could do this in the codebehind:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string pageid = "123";
MyLink.NavigateUrl = string.Format("../mypage.aspx?id={0}", pageid);
}
}
</code></pre>
<hr>
<p>UPDATE:</p>
<p>Now that @Marko Ivanovski pointed me in the comments that this hyperlink is inside a <code>GridView</code> which I didn't notice in the beginning the easiest would be to use databinding (<code><%#</code> syntax):</p>
<pre><code><asp:TemplateColumn>
<ItemTemplate>
<asp:HyperLink
id="MyLink"
NavigateUrl='<%# Eval("pageid", "~/mypage.aspx?id={0}") %>'
runat="server">
My Page
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateColumn>
</code></pre>
<p>In this case <code>pageid</code> is a property of the data source.</p>
<hr>
<p>UPDATE 2:</p>
<p>Do you really need a server side control? How about: </p>
<pre><code><a href="<%= this.ResolveUrl("~/mypage.aspx?id=" + pageid) %>">
My Page
</a>
</code></pre> |
3,935,900 | How to commit and rollback transaction in sql server? | <p>I have a huge script for creating tables and porting data from one server. So this sceipt basically has - </p>
<ol>
<li>Create statements for tables.</li>
<li>Insert for porting the data to these newly created tables.</li>
<li>Create statements for stored procedures. </li>
</ol>
<p>So I have this code but it does not work basically @@ERROR is always zero I think..</p>
<pre><code>BEGIN TRANSACTION
--CREATES
--INSERTS
--STORED PROCEDURES CREATES
-- ON ERROR ROLLBACK ELSE COMMIT THE TRANSACTION
IF @@ERROR != 0
BEGIN
PRINT @@ERROR
PRINT 'ERROR IN SCRIPT'
ROLLBACK TRANSACTION
RETURN
END
ELSE
BEGIN
COMMIT TRANSACTION
PRINT 'COMMITTED SUCCESSFULLY'
END
GO
</code></pre>
<p>Can anyone help me write a transaction which will basically rollback on error and commit if everything is fine..Can I use <a href="http://msdn.microsoft.com/en-us/library/ms178592.aspx" rel="noreferrer">RaiseError</a> somehow here..</p> | 3,937,541 | 3 | 0 | null | 2010-10-14 17:36:10.387 UTC | 9 | 2014-10-15 17:10:26.57 UTC | 2010-10-14 17:54:01.263 UTC | null | 316,959 | null | 316,959 | null | 1 | 15 | sql-server-2008|transactions | 148,296 | <p>Don't use <code>@@ERROR</code>, use <code>BEGIN TRY/BEGIN CATCH</code> instead. See this article: <a href="http://rusanu.com/2009/06/11/exception-handling-and-nested-transactions/" rel="noreferrer">Exception handling and nested transactions</a> for a sample procedure:</p>
<pre><code>create procedure [usp_my_procedure_name]
as
begin
set nocount on;
declare @trancount int;
set @trancount = @@trancount;
begin try
if @trancount = 0
begin transaction
else
save transaction usp_my_procedure_name;
-- Do the actual work here
lbexit:
if @trancount = 0
commit;
end try
begin catch
declare @error int, @message varchar(4000), @xstate int;
select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
if @xstate = -1
rollback;
if @xstate = 1 and @trancount = 0
rollback
if @xstate = 1 and @trancount > 0
rollback transaction usp_my_procedure_name;
raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
return;
end catch
end
</code></pre> |
20,877,813 | Auto refresh images in HTML | <p>I am using following code</p>
<pre><code><html>
<script>
var newImage = new Image();
function updateImage() {
if(newImage.complete) {
newImage.src = document.getElementById("img").src;
var temp = newImage.src;
document.getElementById("img").src = newImage.src;
newImage = new Image();
newImage.src = temp+"?" + new Date().getTime();
}
setTimeout(updateImage, 1000);
};
</script>
<body onload="updateImage();">
<img id="img" src="http://cameraURI" style="position:absolute;top:0;left:0;height:50%;width:50%"/>
</body>
</html>
</code></pre>
<p>But my image is not getting refreshed. Note that for my application purpose, I cant use any url in script.</p>
<p>I know I need to remove <code>newImage.src = document.getElementById("img").src;</code> and need to place over <code>function updateImage()</code> in same file but if I do this, I am getting error as <code>document.getElementById(" ").src is set to NULL</code> and I cant use auto-refresh HTML page. So any help on this file??</p> | 20,877,972 | 4 | 5 | null | 2014-01-02 06:53:28.037 UTC | 9 | 2021-12-12 01:18:04.233 UTC | 2014-01-02 07:00:26.857 UTC | null | 2,919,232 | null | 2,919,232 | null | 1 | 13 | javascript|html | 70,659 | <p>try this</p>
<pre><code>function refresh(node)
{
var times = 3000; // gap in Milli Seconds;
(function startRefresh()
{
var address;
if(node.src.indexOf('?')>-1)
address = node.src.split('?')[0];
else
address = node.src;
node.src = address+"?time="+new Date().getTime();
setTimeout(startRefresh,times);
})();
}
window.onload = function()
{
var node = document.getElementById('img');
refresh(node);
// you can refresh as many images you want just repeat above steps
}
</code></pre> |
11,184,169 | Nested if else in Crystal Reports | <p>I want to nest if-else statements in Crystal Reports, but I don't know the necessary syntax. How can I arrange something like this:</p>
<pre><code>if table1.id <> "1" then
if table1.name <> "a" then
var1 := "Hello"
else
var1 := "Hi"
else
var1 := "Bye"
</code></pre> | 11,184,448 | 2 | 0 | null | 2012-06-25 06:06:31.377 UTC | 1 | 2022-03-24 00:31:52.927 UTC | 2015-09-25 17:15:42.023 UTC | null | 1,464,444 | null | 1,369,235 | null | 1 | 14 | syntax|if-statement|crystal-reports | 62,273 | <p>You can use parenthesises to avoid ambiguity within nested <code>if..else</code> structures:</p>
<pre><code>if {table1.id} <> 1 then
(if {table1.name} <> "a" then
var1 := "Hello"
else
var1 := "Hi";)
else
var1 := "Bye";
</code></pre> |
10,928,387 | Check file extension in Java | <p>I have to import data from an Excel file to database and to do this, I would like to check the extension of the chosen file.</p>
<p>This is my code:</p>
<pre><code>String filename = file.getName();
String extension = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
String excel = "xls";
if (extension != excel) {
JOptionPane.showMessageDialog(null, "Choose an excel file!");
}
else {
String filepath = file.getAbsolutePath();
JOptionPane.showMessageDialog(null, filepath);
String upload = UploadPoData.initialize(null, filepath);
if (upload == "OK") {
JOptionPane.showMessageDialog(null, "Upload Successful!");
}
}
</code></pre>
<p>But I always get:</p>
<blockquote>
<p>Choose an excel file!</p>
</blockquote>
<p>I can't find what is wrong with my code, could someone please help.</p> | 10,928,411 | 8 | 4 | null | 2012-06-07 08:37:29.577 UTC | 4 | 2017-01-19 14:10:20.32 UTC | 2016-04-18 12:08:01.11 UTC | null | 183,704 | null | 1,441,689 | null | 1 | 28 | java|string|if-statement | 54,136 | <p>following</p>
<pre><code>extension != excel
</code></pre>
<p>should be</p>
<pre><code>!excel.equals(extension)
</code></pre>
<p>or </p>
<pre><code>!excel.equalsIgnoreCase(extension)
</code></pre>
<hr>
<p><strong>See also</strong></p>
<ul>
<li><a href="https://stackoverflow.com/questions/767372/java-string-equals-versus">String <code>equals()</code> versus <code>==</code></a></li>
</ul> |
48,116,753 | How to use Kotlin to find whether a string is numeric? | <p>I'd like to use a <code>when()</code> expression in Kotlin to return different values from a function. The input is a <code>String</code>, but it might be parsable to an <code>Int</code>, so I'd like to return the parsed <code>Int</code> if possible, or a <code>String</code> if it is not. Since the input is a <code>String</code>, I cannot use the is type check expression.</p>
<p>Is there any idiomatic way to achieve that?</p>
<p>My problem is what the <code>when()</code> expression should look like, not about the return type.</p> | 48,116,988 | 7 | 9 | null | 2018-01-05 15:36:49.847 UTC | 5 | 2022-09-16 19:14:58.563 UTC | 2022-09-16 19:14:58.563 UTC | null | 2,756,409 | null | 1,041,282 | null | 1 | 47 | kotlin|types | 44,023 | <p><strong>Version 1 (using <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-int-or-null.html" rel="noreferrer"><code>toIntOrNull</code></a> and <code>when</code> when as requested)</strong></p>
<pre><code>fun String.intOrString(): Any {
val v = toIntOrNull()
return when(v) {
null -> this
else -> v
}
}
"4".intOrString() // 4
"x".intOrString() // x
</code></pre>
<p><strong>Version 2 (using <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/to-int-or-null.html" rel="noreferrer"><code>toIntOrNull</code></a> and the elvis operator <code>?:</code>)</strong></p>
<p><code>when</code> is actually not the optimal way to handle this, I only used <code>when</code> because you explicitely asked for it. This would be more appropriate:</p>
<pre><code>fun String.intOrString() = toIntOrNull() ?: this
</code></pre>
<p><strong>Version 3 (using exception handling):</strong></p>
<pre><code>fun String.intOrString() = try { // returns Any
toInt()
} catch(e: NumberFormatException) {
this
}
</code></pre> |
12,862,637 | Perfect square or not? | <p>This is a code to check if a number is perfect square or not. Why does it work ?</p>
<pre><code>static bool IsSquare(int n)
{
int i = 1;
for (; ; )
{
if (n < 0)
return false;
if (n == 0)
return true;
n -= i;
i += 2;
}
}
</code></pre> | 12,862,677 | 1 | 0 | null | 2012-10-12 15:43:37.283 UTC | 15 | 2018-10-11 08:07:43.457 UTC | 2018-10-11 08:07:43.457 UTC | null | 1,033,581 | null | 1,170,733 | null | 1 | 12 | algorithm|perfect-square | 10,159 | <p>Because all perfect squares are sums of consecutive odd numbers:</p>
<ul>
<li>1 = 1</li>
<li>4 = 1 + 3</li>
<li>9 = 1 + 3 + 5</li>
<li>16 = 1 + 3 + 5 + 7</li>
</ul>
<p>and so on. Your program attempts to subtract consecutive odd numbers from <code>n</code>, and see if it drops to zero or goes negative.</p>
<p>You can make an informal proof of this by drawing squares with sides of <code>{1,2,3,4,...}</code> and observe that constructing a square <code>k+1</code> from square <code>k</code> requires adding <code>2k+1</code> unit squares.</p> |
13,023,405 | What is the difference between: Handle, Pointer and Reference | <p>How does a handle differ from a pointer to an object and also why can't we have a reference to a reference?</p> | 13,023,487 | 4 | 4 | null | 2012-10-23 04:03:38.83 UTC | 20 | 2012-10-23 04:16:38.327 UTC | null | null | null | null | 854,183 | null | 1 | 30 | c++|oop|pointers|reference|handle | 28,739 | <p>A handle is usually an <em>opaque</em> reference to an object. The type of the handle is unrelated to the element referenced. Consider for example a file descriptor returned by <code>open()</code> system call. The type is <code>int</code> but it represents an entry in the open files table. The actual data stored in the table is unrelated to the <code>int</code> that was returned by <code>open()</code> freeing the implementation from having to maintain compatibility (i.e. the actual table can be refactored transparently without affecting user code. Handles can only be used by functions in the same library interface, that can remap the handle back to the actual object.</p>
<p>A pointer is the combination of an address in memory and the type of the object that resides in that memory location. The value is the address, the type of the pointer tells the compiler what operations can be performed through that pointer, how to interpret the memory location. Pointers are <em>transparent</em> in that the object referenced has a concrete type that is present from the pointer. Note that in some cases a pointer can serve as a handle (a <code>void*</code> is fully opaque, a pointer to an empty interface is just as opaque).</p>
<p>References are <em>aliases</em> to an object. That is why you cannot have a reference to a reference: you can have multiple aliases for an object, but you cannot have an alias of an alias. As with pointers references are typed. In some circumstances, references can be implemented by the compiler as pointers that are automatically dereferenced on use, in some other cases the compiler can have references that have no actual storage. The important part is that they are <em>aliases</em> to an object, they must be initialized with an object and cannot be reseated to refer to a different object after they are initialized. Once they are initialized, all uses of the reference are uses of the real object.</p> |
12,810,346 | Alternative to using LIMIT keyword in a SubQuery in MYSQL | <p>I have a table TEST with the following columns : </p>
<pre><code>code_ver (VARCHAR)
suite (VARCHAR)
date (DATE)
</code></pre>
<p>Now I want to select 10 rows with a distinct value of c<code>ode_ver & code_ver NOT LIKE '%DevBld%' sorted by date desc.</code></p>
<p>So I wrote the following query:</p>
<pre><code>select *
from test
where code_ver IN (select DISTINCT code_ver
from test
where code_ver NOT LIKE '%DevBld%'
ORDER by date DESC LIMIT 10);
</code></pre>
<p>This query should ideally work, but my version of MySQL says : </p>
<blockquote>
<p>This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME
subquery'</p>
</blockquote>
<p>Can someone suggest me an alternative to this query?</p> | 12,811,825 | 6 | 1 | null | 2012-10-10 00:34:51.683 UTC | 4 | 2022-07-18 08:34:06.25 UTC | 2018-03-28 07:12:15.44 UTC | null | 3,876,565 | null | 1,450,521 | null | 1 | 36 | mysql|sql|database | 73,789 | <p>The error you are getting is not exactly because of the version of MySQL. I think all versions support that. You have to change the LIMIT 10 place and place it after ")". Let me know if it works for you. I ran the bellow one on mine and it works.</p>
<p>E.g.</p>
<pre><code>SELECT * FROM test where name IN (
SELECT DISTINCT name
FROM projects
WHERE name NOT LIKE "%DevBld%"
ORDER by date_created DESC
) LIMIT 10;
</code></pre>
<p>Update: Try the one below, this way order would work:</p>
<pre><code> SELECT * FROM automation.e2e_projects WHERE name IN (
SELECT DISTINCT name
FROM automation.e2e_projects
WHERE name NOT LIKE "%DevBld%"
) ORDER by date_created DESC LIMIT 10;
</code></pre> |
13,054,797 | How to prevent a webkit-scrollbar from pushing over the contents of a div? | <p>I'm using webkit-scrollbar and am running into styling issues as the webkit scrollbar is pushing the contents of a div to the left which causes the contents to overflow.</p>
<p>Notice</p>
<ul>
<li>1st box uses the default browser scrollbar and does not overflow (good)</li>
<li>2nd box uses the webkit scrollbar which ends up breaking the layout. (bad/problem)</li>
</ul>
<p><a href="http://jsfiddle.net/ryeah/1/">http://jsfiddle.net/ryeah/1/</a></p>
<p>Any ideas what I'm doing wrong with webkit scrollbar to cause the div to/overflow. How can we fix the 2nd box? Thanks</p>
<p><strong>Webkit Scrollbar Code:</strong></p>
<pre><code>.box2::-webkit-scrollbar {
height: 16px;
overflow: visible;
width: 16px;
}
.box2::-webkit-scrollbar-thumb {
background-color: rgba(0, 0, 0, .2);
background-clip: padding-box;
border: solid transparent;
border-width: 1px 1px 1px 6px;
min-height: 28px;
padding: 100px 0 0;
box-shadow: inset 1px 1px 0 rgba(0, 0, 0, .1),inset 0 -1px 0 rgba(0, 0, 0, .07);
}
.box2::-webkit-scrollbar-button {
height: 0;
width: 0;
}
.box2::-webkit-scrollbar-track {
background-clip: padding-box;
border: solid transparent;
border-width: 0 0 0 4px;
}
.box2::-webkit-scrollbar-corner {
background: transparent;
}
</code></pre> | 13,470,337 | 4 | 1 | null | 2012-10-24 17:46:02.12 UTC | 4 | 2021-02-01 17:42:16.68 UTC | null | null | null | null | 149,080 | null | 1 | 36 | html|css|webkit | 38,258 | <p>Hm.. I can't think of a way to get the webkit scrollbar in overlay. One solution to stop the line breaking is to hide the scrollbar with </p>
<pre><code>.box2::-webkit-scrollbar {
height: 16px;
overflow: visible;
width: 16px;
display: none;
}
</code></pre>
<p>other you can set the width of your UL to the same as the box so it makes use of the overflow function and displays under the scrollbar</p>
<pre><code>.box ul {
width: 149px;
}
</code></pre> |
12,654,013 | How to make g++ search for header files in a specific directory? | <p>I have a project (a library) that is subdivided into a few directories with code in them. I'd like to to have g++ search for header files in the project's root directory, so I can avoid different include paths for same header files across multiple source files.</p>
<p>Mainly, the <code>root/</code> directory has sub-directories <code>A/</code>, <code>B/</code> and <code>C/</code>, all of which have <code>.hpp</code> and <code>.cpp</code> files inside. If some source file in A wanted to include <code>file.hpp</code>, which was in B, it would have to do it like this: <code>#include "../B/file.hpp"</code>. Same for another source file that was in C. But, if A itself had sub-directories with files that needed <code>file.hpp</code>, then, it would be inconsistent and would cause errors if I decided to move files (because the include path would be <code>"../../B/file.hpp"</code>).</p>
<p>Also, this would need to work from other projects as well, which reside outside of <code>root/</code>. I already know that there is an option to manually copy all my header files into a default-search directory, but I'd like to do this the way I described.</p>
<p><strong>Edit:</strong> all programs using the library must compile only with <code>g++ prog.cpp lib.a -o prog</code>. That means <em>permanently</em> setting the include path for g++!</p> | 12,654,056 | 4 | 1 | null | 2012-09-29 15:29:56.227 UTC | 26 | 2022-06-17 04:10:21.743 UTC | 2018-03-14 10:07:40.967 UTC | null | 719,263 | null | 924,313 | null | 1 | 56 | directory|g++|header-files|include-path | 151,469 | <p>A/code.cpp</p>
<pre><code>#include <B/file.hpp>
</code></pre>
<p>A/a/code2.cpp</p>
<pre><code>#include <B/file.hpp>
</code></pre>
<p>Compile using:</p>
<pre><code>g++ -I /your/source/root /your/source/root/A/code.cpp
g++ -I /your/source/root /your/source/root/A/a/code2.cpp
</code></pre>
<p>Edit:</p>
<p>You can use environment variables to change the path g++ looks for header files. From man page:</p>
<blockquote>
<p>Some additional environments variables affect the behavior of the
preprocessor.</p>
<pre><code> CPATH
C_INCLUDE_PATH
CPLUS_INCLUDE_PATH
OBJC_INCLUDE_PATH
</code></pre>
<p>Each variable's value is a list of directories separated by a special character, much like PATH, in which to look for header
files. The special character, "PATH_SEPARATOR", is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it
is a semicolon, and for almost all other targets it is a colon.</p>
<p>CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the
command line. This
environment variable is used regardless of which language is being preprocessed.</p>
<p>The remaining environment variables apply only when preprocessing the particular language indicated. Each specifies a
list of directories to be
searched as if specified with -isystem, but after any paths given with -isystem options on the command line.</p>
<p>In all these variables, an empty element instructs the compiler to search its current working directory. Empty elements can
appear at the beginning
or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I.
-I/special/include.</p>
</blockquote>
<p>There are many ways you can change an environment variable. On bash prompt you can do this:</p>
<pre><code>$ export CPATH=/your/source/root
$ g++ /your/source/root/A/code.cpp
$ g++ /your/source/root/A/a/code2.cpp
</code></pre>
<p>You can of course add this in your Makefile etc.</p> |
13,219,634 | Easiest way to check for an index or a key in an array? | <p>Using:</p>
<pre><code>set -o nounset
</code></pre>
<ol>
<li><p>Having an indexed array like:</p>
<pre><code>myArray=( "red" "black" "blue" )
</code></pre>
<p>What is the shortest way to check if element 1 is set?<br>
I sometimes use the following:</p>
<pre><code>test "${#myArray[@]}" -gt "1" && echo "1 exists" || echo "1 doesn't exist"
</code></pre>
<p>I would like to know if there's a preferred one.</p>
</li>
<li><p>How to deal with non-consecutive indexes?</p>
<pre><code>myArray=()
myArray[12]="red"
myArray[51]="black"
myArray[129]="blue"
</code></pre>
<p>How to quick check that <code>51</code> is already set for example?</p>
</li>
<li><p>How to deal with associative arrays?</p>
<pre><code>declare -A myArray
myArray["key1"]="red"
myArray["key2"]="black"
myArray["key3"]="blue"
</code></pre>
<p>How to quick check that <code>key2</code> is already used for example?</p>
</li>
</ol> | 13,221,491 | 11 | 0 | null | 2012-11-04 14:57:04.413 UTC | 31 | 2022-09-02 00:10:01.897 UTC | 2020-08-29 18:59:10 UTC | null | 4,518,341 | null | 1,032,370 | null | 1 | 112 | arrays|bash|indexing|key | 108,484 | <p>To check if the element is set (applies to both indexed and associative array)</p>
<pre><code>[ "${array[key]+abc}" ] && echo "exists"
</code></pre>
<p>Basically what <code>${array[key]+abc}</code> does is</p>
<ul>
<li>if <code>array[key]</code> is set, return <code>abc</code></li>
<li>if <code>array[key]</code> is not set, return nothing</li>
</ul>
<hr>
References:
<ol>
<li>See <a href="http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion" rel="noreferrer">Parameter Expansion</a> in Bash manual and the little note</li>
</ol>
<blockquote>
<p>if the colon is omitted, the operator tests only for existence [of <em>parameter</em>]</p>
</blockquote>
<ol start="2">
<li>This answer is actually adapted from the answers for this SO question: <a href="https://stackoverflow.com/questions/228544/how-to-tell-if-a-string-is-not-defined-in-a-bash-shell-script">How to tell if a string is not defined in a bash shell script</a>?</li>
</ol>
<hr>
<p>A wrapper function:</p>
<pre><code>exists(){
if [ "$2" != in ]; then
echo "Incorrect usage."
echo "Correct usage: exists {key} in {array}"
return
fi
eval '[ ${'$3'[$1]+muahaha} ]'
}
</code></pre>
<p>For example</p>
<pre><code>if ! exists key in array; then echo "No such array element"; fi
</code></pre> |
12,686,927 | How to assert a type of an HTMLElement in TypeScript? | <p>I'm trying to do this:</p>
<pre><code>var script:HTMLScriptElement = document.getElementsByName("script")[0];
alert(script.type);
</code></pre>
<p>but it's giving me an error:</p>
<pre><code>Cannot convert 'Node' to 'HTMLScriptElement': Type 'Node' is missing property 'defer' from type 'HTMLScriptElement'
(elementName: string) => NodeList
</code></pre>
<p>I can't access the 'type' member of the script element unless I cast it to the correct type, but I don't know how to do this. I searched the docs & samples, but I couldn't find anything.</p> | 12,687,137 | 14 | 2 | null | 2012-10-02 08:33:05.02 UTC | 34 | 2021-05-15 23:42:06.907 UTC | 2021-05-15 22:45:26.703 UTC | null | 11,407,695 | null | 204,555 | null | 1 | 226 | typescript|type-assertion|typescript-types|typescript-lib-dom | 240,023 | <p>TypeScript uses '<>' to surround casts, so the above becomes:</p>
<pre><code>var script = <HTMLScriptElement>document.getElementsByName("script")[0];
</code></pre>
<p>However, unfortunately you cannot do:</p>
<pre><code>var script = (<HTMLScriptElement[]>document.getElementsByName(id))[0];
</code></pre>
<p>You get the error</p>
<pre><code>Cannot convert 'NodeList' to 'HTMLScriptElement[]'
</code></pre>
<p>But you can do : </p>
<pre><code>(<HTMLScriptElement[]><any>document.getElementsByName(id))[0];
</code></pre> |
17,128,904 | Styling Twitter's Bootstrap 3.x Buttons | <p><a href="http://www.getbootstrap.com/" rel="nofollow noreferrer">Twitter's Bootstrap 3</a> buttons are limited in colors. By default there will be <strike>5</strike> 7 colors (default primary, error, warning, info, success and link) See:</p>
<p><img src="https://i.stack.imgur.com/5099C.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/i8EwH.png" alt="Twitter's Bootstrap Buttons"></p>
<p>Every button got 3 state (default, active and disabled)</p>
<p>How to add more colors or create custom buttons? This question is already answered for Twitter's Bootstrap 2.x: <a href="https://stackoverflow.com/questions/10659070/styling-twitter-bootstrap-buttons">Styling twitter bootstrap buttons</a>. Bootstrap 3 is not backwards compatible. There will be lot of changes in the less and css files. Support for IE7 will be dropped. TB3 is mobile first. Markup codes will be changed too.</p> | 17,128,905 | 6 | 0 | null | 2013-06-15 23:35:01.413 UTC | 17 | 2015-03-23 12:06:06.75 UTC | 2017-05-23 12:02:05.063 UTC | null | -1 | null | 1,596,547 | null | 1 | 37 | css|twitter-bootstrap|less|twitter-bootstrap-3 | 66,995 | <p>Add extra colors to your less files and recompile. Also see <a href="https://stackoverflow.com/questions/10451317/twitter-bootstrap-customization-best-practices">Twitter Bootstrap Customization Best Practices</a>.
<strong>update</strong></p>
<p>As mentioned by @ow3n since v3.0.3 use:</p>
<pre><code>.btn-custom {
.button-variant(@btn-default-color; @btn-default-bg; @btn-default-border);
}
</code></pre>
<p>Note in the above <code>@btn-default-color</code> sets the font color,<code>@btn-default-bg</code> the background color and @btn-default-border the color of the border. Colors for states like active, hover and disabled are calculated based on of these parameters.</p>
<p>For example:</p>
<pre><code>.btn-custom {
.button-variant(blue; red; green);
}
</code></pre>
<p>will result in:</p>
<p><img src="https://i.stack.imgur.com/gUEGr.png" alt="enter image description here"></p>
<p>For who want to use the CSS direct, replace the colors in this code:</p>
<pre><code>.btn-custom {
color: #0000ff;
background-color: #ff0000;
border-color: #008000;
}
.btn-custom:hover,
.btn-custom:focus,
.btn-custom:active,
.btn-custom.active,
.open .dropdown-toggle.btn-custom {
color: #0000ff;
background-color: #d60000;
border-color: #004300;
}
.btn-custom:active,
.btn-custom.active,
.open .dropdown-toggle.btn-custom {
background-image: none;
}
.btn-custom.disabled,
.btn-custom[disabled],
fieldset[disabled] .btn-custom,
.btn-custom.disabled:hover,
.btn-custom[disabled]:hover,
fieldset[disabled] .btn-custom:hover,
.btn-custom.disabled:focus,
.btn-custom[disabled]:focus,
fieldset[disabled] .btn-custom:focus,
.btn-custom.disabled:active,
.btn-custom[disabled]:active,
fieldset[disabled] .btn-custom:active,
.btn-custom.disabled.active,
.btn-custom[disabled].active,
fieldset[disabled] .btn-custom.active {
background-color: #ff0000;
border-color: #008000;
}
.btn-custom .badge {
color: #ff0000;
background-color: #0000ff;
}
</code></pre>
<p><strong>end update</strong></p>
<p>To generate a custom button:</p>
<pre><code>.btn-custom {
.btn-pseudo-states(@yourColor, @yourColorDarker);
}
</code></pre>
<p>The above will generate the following css:</p>
<pre><code>.btn-custom {
background-color: #1dcc00;
border-color: #1dcc00;
}
.btn-custom:hover,
.btn-custom:focus,
.btn-custom:active,
.btn-custom.active {
background-color: #19b300;
border-color: #169900;
}
.btn-custom.disabled:hover,
.btn-custom.disabled:focus,
.btn-custom.disabled:active,
.btn-custom.disabled.active,
.btn-custom[disabled]:hover,
.btn-custom[disabled]:focus,
.btn-custom[disabled]:active,
.btn-custom[disabled].active,
fieldset[disabled] .btn-custom:hover,
fieldset[disabled] .btn-custom:focus,
fieldset[disabled] .btn-custom:active,
fieldset[disabled] .btn-custom.active {
background-color: #1dcc00;
border-color: #1dcc00;
}
</code></pre>
<p>In the above #1dcc00 will be your custom color and #19b300 your darker color. In stead of the less solution you also can add this css direct to your html files (after the bootstrap css).</p>
<p>Or get your css code direct from <a href="http://twitterbootstrap3buttons.w3masters.nl/" rel="nofollow noreferrer">Twitter's Bootstrap 3 Button Generator</a></p> |
17,060,039 | Split string at nth occurrence of a given character | <p>Is there a Python-way to split a string after the nth occurrence of a given delimiter?</p>
<p>Given a string:</p>
<pre><code>'20_231_myString_234'
</code></pre>
<p>It should be split into (with the delimiter being '_', after its second occurrence):</p>
<pre><code>['20_231', 'myString_234']
</code></pre>
<p>Or is the only way to accomplish this to count, split and join?</p> | 17,060,409 | 8 | 2 | null | 2013-06-12 07:36:01.2 UTC | 10 | 2021-08-26 07:32:01.847 UTC | 2013-06-12 07:47:40.727 UTC | null | 1,219,006 | null | 1,183,106 | null | 1 | 52 | python|string|split | 53,715 | <pre><code>>>> n = 2
>>> groups = text.split('_')
>>> '_'.join(groups[:n]), '_'.join(groups[n:])
('20_231', 'myString_234')
</code></pre>
<p>Seems like this is the most readable way, the alternative is regex)</p> |
17,089,250 | Difference com.sun.jersey and org.glassfish.jersey | <p>What is the difference between <code>com.sun.jersey</code> and <code>org.glassfish.jersey</code>?</p>
<p>Currently I have my REST service working on <code>com.sun.jersey</code> and I want to write tests, but I can't find a good tutorial for this (nothing seems to work). However, I can find good documentation about the <code>org.glassfish.jersey</code> tests.</p> | 17,089,685 | 1 | 0 | null | 2013-06-13 14:09:39.15 UTC | 19 | 2015-09-23 09:37:22.5 UTC | 2015-09-23 09:37:22.5 UTC | null | 1,487,809 | null | 1,226,868 | null | 1 | 85 | java|glassfish|jersey|sun | 29,374 | <p>The only difference between com.sun.jersey and org.glassfish.jersey is that the package name was changed because Jersey team is now part of another organization (Glassfish).
Versions below 2 use package com.sun.jersey, versions above 2 use org.glassfish.jersey.
And yes, there are some differences between 1.x and 2.x. </p> |
50,681,027 | Do Spring prototype beans need to be destroyed manually? | <p>I noticed that the <code>@PreDestroy</code> hooks of my prototype scoped Spring beans were not getting executed.</p>
<p>I have since read <a href="https://docs.spring.io/spring/docs/4.3.9.RELEASE/spring-framework-reference/html/beans.html#beans-factory-scopes-prototype" rel="noreferrer">here</a> that this is actually by design. The Spring container will destroy singleton beans but will not destroy prototype beans. It is unclear to me why. If the Spring container will create my prototype bean and execute its <code>@PostConstruct</code> hook, why will it not destroy my bean as well, when the container is closed? Once my Spring container has been closed, does it even make sense to continue using any of its beans? I cannot see a scenario where you would want to close a container before you have finished with its beans. Is it even possible to continue using a prototype Spring bean after its container has been closed?</p>
<p>The above describes the puzzling background to my primary question which is: If the Spring container is not destroying prototype beans, does that mean a memory leak could occur? Or will the prototype bean get garbage-collected at some point?</p>
<p>The Spring documentations states:</p>
<blockquote>
<p>The client code must clean up prototype-scoped objects and release
expensive resources that the prototype bean(s) are holding. To get the
Spring container to release resources held by prototype-scoped beans,
try using a custom bean post-processor, which holds a reference to
beans that need to be cleaned up.</p>
</blockquote>
<p>What does that mean? The text suggests to me that I, as the programmer am responsible for explicitly (manually) destroying my prototype beans. Is this correct? If so, how do I do that?</p> | 50,686,240 | 2 | 6 | null | 2018-06-04 12:48:25.853 UTC | 11 | 2018-08-01 17:26:45.557 UTC | 2018-06-07 14:08:05.35 UTC | null | 5,618,307 | null | 5,618,307 | null | 1 | 33 | java|spring|garbage-collection|spring-bean|predestroy | 17,782 | <p>For the benefit of others, I will present below what I have gathered from my investigations:</p>
<p>As long as the prototype bean does not itself hold a reference to another resource such as a database connection or a session object, it will get garbage collected as soon as all references to the object have been removed or the object goes out of scope. It is therefore usually not necessary to explicitly destroy a prototype bean.</p>
<p>However, in the case where a memory leak may occur as described above, prototype beans can be destroyed by creating a singleton bean post-processor whose destruction method explicitly calls the destruction hooks of your prototype beans. Because the post-processor is itself of singleton scope, its destruction hook <em>will</em> get invoked by Spring:</p>
<ol>
<li><p>Create a bean post processor to handle the destruction of all your prototype beans. This is necessary because Spring does not destroy prototype beans and so any @PreDestroy hooks in your code will never get called by the container. </p></li>
<li><p>Implement the following interfaces:</p>
<p>1.<strong>BeanFactoryAware</strong><br>
This interface provides a callback method which receives a Beanfactory object. This BeanFactory object is used in the post-processor class to identify all prototype beans via its BeanFactory.isPrototype(String beanName) method.
<br>
<br>2. <strong>DisposableBean</strong><br>
This interface provides a Destroy() callback method invoked by the Spring container. We will call the Destroy() methods of all our prototype beans from within this method.
<br>
<br>3. <strong>BeanPostProcessor</strong><br>
Implementing this interface provides access to post-process callbacks from within which, we prepare an internal List<> of all prototype objects instantiated by the Spring container. We will later loop through this List<> to destroy each of our prototype beans.</p></li>
</ol>
<p><br> 3. Finally implement the DisposableBean interface in each of your prototype beans, providing the Destroy() method required by this contract.</p>
<p>To illustrate this logic, I provide some code below taken from this <a href="http://iryndin.net/post/spring_destroy_prototype_beans/" rel="noreferrer">article</a>: </p>
<pre><code>/**
* Bean PostProcessor that handles destruction of prototype beans
*/
@Component
public class DestroyPrototypeBeansPostProcessor implements BeanPostProcessor, BeanFactoryAware, DisposableBean {
private BeanFactory beanFactory;
private final List<Object> prototypeBeans = new LinkedList<>();
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (beanFactory.isPrototype(beanName)) {
synchronized (prototypeBeans) {
prototypeBeans.add(bean);
}
}
return bean;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
@Override
public void destroy() throws Exception {
synchronized (prototypeBeans) {
for (Object bean : prototypeBeans) {
if (bean instanceof DisposableBean) {
DisposableBean disposable = (DisposableBean)bean;
try {
disposable.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
prototypeBeans.clear();
}
}
}
</code></pre> |
10,016,475 | Create NSScrollView Programmatically in an NSView - Cocoa | <p>I have an NSView class which takes care of a Custom View created in the nib file. </p>
<p>Now I want to add an NSScrollView to the custom view, but I need to do it programmatically and not using Interface Builder (Embed Into Scroll View).</p>
<p>I have found this code:</p>
<pre><code>NSView *windowContentView = [mainWindow contentView];
NSRect windowContentBounds = [windowContentView bounds];
scrollView = [[NSScrollView alloc] init];
[scrollView setBorderType:NSNoBorder];
[scrollView setHasVerticalScroller:YES];
[scrollView setBounds: windowContentBounds];
[windowContentView addSubview:scrollView];
</code></pre>
<p>Assuming I declare as IBOutlets the variables 'mainWindow' and 'scrollView' above, how would I go about connecting them to the proper components in Interface Builder? Does it make any sense to do it this way? </p>
<p>Or is there a better way to add a scroll view programmatically?</p>
<p>P.S. I cannot connect them in the usual way because I cannot create an NSObject Object from Interface Builder, or use the File Owner..</p> | 10,023,346 | 4 | 2 | null | 2012-04-04 17:42:20.987 UTC | 9 | 2021-11-27 12:26:40.637 UTC | 2019-01-21 11:54:11.673 UTC | null | 1,033,581 | null | 1,214,040 | null | 1 | 12 | objective-c|cocoa|nsscrollview | 11,006 | <p>This code fragment should demonstrate how to create an NSScrollView programmatically and use it to display any view, whether from a nib or from code. In the case of a nib generated view, you simply need to load the nib file to your custom view prior, and have an outlet to your custom view (outletToCustomViewLoadedFromNib) made to File's Owner.</p>
<pre><code>NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:[[mainWindow contentView] frame]];
// configure the scroll view
[scrollView setBorderType:NSNoBorder];
[scrollView setHasVerticalScroller:YES];
// embed your custom view in the scroll view
[scrollView setDocumentView:outletToCustomViewLoadedFromNib];
// set the scroll view as the content view of your window
[mainWindow setContentView:scrollView];
</code></pre>
<p>Apple has a guide on the subject, which I won't link to as it requires Apple Developer Connection access and their links frequently break. It is titled "Creating and Configuring a Scroll View" and can currently be found by searching for its title using Google.</p> |
9,781,214 | Parse output of spawned node.js child process line by line | <p>I have a PhantomJS/CasperJS script which I'm running from within a node.js script using <code>process.spawn()</code>. Since CasperJS doesn't support <code>require()</code>ing modules, I'm trying to print commands from CasperJS to <code>stdout</code> and then read them in from my node.js script using <code>spawn.stdout.on('data', function(data) {});</code> in order to do things like add objects to redis/mongoose (convoluted, yes, but seems more straightforward than setting up a web service for this...) The CasperJS script executes a series of commands and creates, say, 20 screenshots which need to be added to my database.</p>
<p>However, I can't figure out how to break the <code>data</code> variable (a <code>Buffer</code>?) into lines... I've tried converting it to a string and then doing a replace, I've tried doing <code>spawn.stdout.setEncoding('utf8');</code> but nothing seems to work...</p>
<p>Here is what I have right now</p>
<pre><code>var spawn = require('child_process').spawn;
var bin = "casperjs"
//googlelinks.js is the example given at http://casperjs.org/#quickstart
var args = ['scripts/googlelinks.js'];
var cspr = spawn(bin, args);
//cspr.stdout.setEncoding('utf8');
cspr.stdout.on('data', function (data) {
var buff = new Buffer(data);
console.log("foo: " + buff.toString('utf8'));
});
cspr.stderr.on('data', function (data) {
data += '';
console.log(data.replace("\n", "\nstderr: "));
});
cspr.on('exit', function (code) {
console.log('child process exited with code ' + code);
process.exit(code);
});
</code></pre>
<p><a href="https://gist.github.com/2131204">https://gist.github.com/2131204</a></p> | 9,781,295 | 7 | 1 | null | 2012-03-20 04:06:49.377 UTC | 15 | 2022-05-03 19:07:00.05 UTC | 2012-12-26 01:41:31.873 UTC | null | 527,702 | null | 1,150,652 | null | 1 | 23 | node.js|phantomjs | 27,116 | <p>Try this:</p>
<pre class="lang-javascript prettyprint-override"><code>cspr.stdout.setEncoding('utf8');
cspr.stdout.on('data', function(data) {
var str = data.toString(), lines = str.split(/(\r?\n)/g);
for (var i=0; i<lines.length; i++) {
// Process the line, noting it might be incomplete.
}
});
</code></pre>
<p>Note that the "data" event might not necessarily break evenly between lines of output, so a single line might span multiple data events.</p> |