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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
36,959,516 | C++ : How to return the value the iterator of a set is pointing to? | <p>My return value from an iterator over a set gives the memory location instead of the value. How do I access the element the iterator is pointing to?</p>
<p>I used a similar iterator loop before which worked fine, as in returning the value the iterator is pointing to (for both a deque and vector template class).</p>
<p>This question is a follow up on a script I had difficulties with earlier today (<a href="https://stackoverflow.com/questions/36956495/c-adding-an-object-to-a-set">C++ : adding an object to a set</a>).</p>
<p>The script now looks as follows:</p>
<p>header file</p>
<pre><code>#ifndef EMPLOYEE_HH
#define EMPLOYEE_HH
#include <set>
#include <string>
#include <iostream>
using namespace std ;
class Employee {
public:
// Constructor
Employee(const char* name, double salary) :
_name(name),
_salary(salary) {
}
// Accessors
const char* name() const {
return _name.c_str() ;
}
double salary() const {
return _salary ;
}
// Print functions
void businessCard(ostream& os = cout) const {
os << " +--------------------+ " << endl
<< " | ACME Corporation | " << endl
<< " +--------------------+ " << endl
<< " Name: " << name() << endl
<< " Salary: " << salary() << endl ;
}
private:
string _name ;
double _salary ;
} ;
class Manager : public Employee {
public:
//Constructor
Manager(const char* _name, double _salary):
Employee(_name, _salary),
_subordinates() {
}
// Accessors & modifiers
void addSubordinate(Employee& empl) {
_subordinates.insert(&empl);
}
const set<Employee*>& listOfSubordinates() const {
return _subordinates;
}
void businessCard(ostream& os = cout) const {
Employee::businessCard() ;
os << " Function: Manager" << endl ;
set<Employee*>::iterator iter ;
iter = _subordinates.begin() ;
os << " Subordinates:" << endl ;
if(_subordinates.empty()==true) {
os << " Nobody" << endl;
}
while(iter!=_subordinates.end()) {
os << " " << *iter << endl ; // <-- returns the memory location
++iter ;
}
}
private:
set<Employee*> _subordinates ;
} ;
#endif
</code></pre>
<p>Main script</p>
<pre><code>#include <string>
#include <iostream>
#include "Employee.hh"
using namespace std ;
int main() {
Employee emp1("David", 10000) ;
Employee emp2("Ivo", 9000) ;
Manager mgr1("Oscar", 18000) ; // Manager of Ivo and David
Manager mgr2("Jo", 14000) ;
Manager mgr3("Frank", 22000) ; // Manager of Jo and Oscar (and Ivo and David)
mgr1.addSubordinate(emp1) ;
mgr1.addSubordinate(emp2) ;
mgr3.addSubordinate(mgr1) ;
mgr3.addSubordinate(mgr2) ;
cout << '\n' ;
emp1.businessCard() ;
cout << '\n' ;
emp2.businessCard() ;
cout << '\n' ;
mgr1.businessCard() ;
cout << '\n' ;
mgr2.businessCard() ;
cout << '\n' ;
mgr3.businessCard() ;
cout << '\n' ;
return 0;
}
</code></pre>
<p>Any help is much appreciated. </p> | 36,959,578 | 2 | 3 | null | 2016-04-30 19:52:43.84 UTC | null | 2020-04-20 22:40:55.187 UTC | 2017-05-23 10:33:55.017 UTC | null | -1 | null | 6,255,655 | null | 1 | 6 | c++|pointers|memory|iterator | 40,744 | <p>If this: <code>*iter</code> is an address then this: <code>*(*iter)</code>is the value that <code>*iter</code> is pointing to. </p>
<p>This should work in your case:</p>
<pre><code>while(iter != _subordinates.end())
{
os << " " << **iter << endl ; // <-- returns the value which is the set
++iter;
}
</code></pre>
<p><strong>Edit</strong>: This fixed the issue: <code>(*iter)->name()</code></p> |
36,822,224 | What are the pros and cons of parquet format compared to other formats? | <p>Characteristics of Apache Parquet are :</p>
<ul>
<li>Self-describing </li>
<li>Columnar format</li>
<li>Language-independent</li>
</ul>
<p>In comparison to Avro, Sequence Files, RC File etc. I want an overview of the formats. I have already read : <a href="https://www.cloudera.com/documentation/enterprise/5-8-x/topics/impala_file_formats.html" rel="noreferrer">How Impala Works with Hadoop File Formats</a> , it gives some insights on the formats but I would like to know how the access to data & storage of data is done in each of these formats. How parquet has an advantage over the others?</p> | 36,831,549 | 4 | 3 | null | 2016-04-24 10:59:30.06 UTC | 108 | 2020-09-19 14:59:44.907 UTC | 2018-04-18 10:30:03.553 UTC | null | 2,142,994 | null | 2,142,994 | null | 1 | 187 | file|hadoop|hdfs|avro|parquet | 141,753 | <p>I think the main difference I can describe relates to record oriented vs. column oriented formats. Record oriented formats are what we're all used to -- text files, delimited formats like CSV, TSV. AVRO is slightly cooler than those because it can change schema over time, e.g. adding or removing columns from a record. Other tricks of various formats (especially including compression) involve whether a format can be split -- that is, can you read a block of records from anywhere in the dataset and still know it's schema? But here's more detail on columnar formats like Parquet.</p>
<p>Parquet, and other columnar formats handle a common Hadoop situation very efficiently. It is common to have tables (datasets) having many more columns than you would expect in a well-designed relational database -- a hundred or two hundred columns is not unusual. This is so because we often use Hadoop as a place to <em>denormalize</em> data from relational formats -- yes, you get lots of repeated values and many tables all flattened into a single one. But it becomes much easier to query since all the joins are worked out. There are other advantages such as retaining state-in-time data. So anyway it's common to have a boatload of columns in a table. </p>
<p>Let's say there are 132 columns, and some of them are really long text fields, each different column one following the other and use up maybe 10K per record.</p>
<p>While querying these tables is easy with SQL standpoint, it's common that you'll want to get some range of records based on only a few of those hundred-plus columns. For example, you might want all of the records in February and March for customers with sales > $500.</p>
<p>To do this in a row format the query would need to scan every record of the dataset. Read the first row, parse the record into fields (columns) and get the date and sales columns, include it in your result if it satisfies the condition. Repeat. If you have 10 years (120 months) of history, you're reading every single record just to find 2 of those months. Of course this is a great opportunity to use a partition on year and month, but even so, you're reading and parsing 10K of each record/row for those two months just to find whether the customer's sales are > $500.</p>
<p>In a columnar format, each column (field) of a record is stored with others of its kind, spread all over many different blocks on the disk -- columns for year together, columns for month together, columns for customer employee handbook (or other long text), and all the others that make those records so huge all in their own separate place on the disk, and of course columns for sales together. Well heck, date and months are numbers, and so are sales -- they are just a few bytes. Wouldn't it be great if we only had to read a few bytes for each record to determine which records matched our query? Columnar storage to the rescue!</p>
<p>Even without partitions, scanning the small fields needed to satisfy our query is super-fast -- they are all in order by record, and all the same size, so the disk seeks over much less data checking for included records. No need to read through that employee handbook and other long text fields -- just ignore them. So, by grouping columns with each other, instead of rows, you can almost always scan less data. Win!</p>
<p>But wait, it gets better. If your query only needed to know those values and a few more (let's say 10 of the 132 columns) and didn't care about that employee handbook column, once it had picked the right records to return, it would now only have to go back to the 10 columns it needed to render the results, ignoring the other 122 of the 132 in our dataset. Again, we skip a lot of reading.</p>
<p>(Note: for this reason, columnar formats are a lousy choice when doing straight transformations, for example, if you're joining all of two tables into one big(ger) result set that you're saving as a new table, the sources are going to get scanned completely anyway, so there's not a lot of benefit in read performance, and because columnar formats need to remember more about the where stuff is, they use more memory than a similar row format).</p>
<p>One more benefit of columnar: data is spread around. To get a single record, you can have 132 workers each read (and write) data from/to 132 different places on 132 blocks of data. Yay for parallelization!</p>
<p>And now for the clincher: compression algorithms work much better when it can find repeating patterns. You could compress <code>AABBBBBBCCCCCCCCCCCCCCCC</code> as <code>2A6B16C</code> but <code>ABCABCBCBCBCCCCCCCCCCCCCC</code> wouldn't get as small (well, actually, in this case it would, but trust me :-) ). So once again, less reading. And writing too.</p>
<p>So we read a lot less data to answer common queries, it's potentially faster to read and write in parallel, and compression tends to work much better. </p>
<p>Columnar is great when your input side is large, and your output is a filtered subset: from big to little is great. Not as beneficial when the input and outputs are about the same.</p>
<p>But in our case, Impala took our old Hive queries that ran in 5, 10, 20 or 30 minutes, and finished most in a few seconds or a minute.</p>
<p>Hope this helps answer at least part of your question! </p> |
18,338,322 | How to find files recursively by file type and copy them to a directory? | <p>I would like to find all the <code>pdf</code> files in a folder. It contains <code>pdf</code> files inside and more directories that contain more as well. The folder is located on a remote server I have ssh access to. I am using the mac terminal but I believe the server I am connecting to is Centos.</p>
<p>I need to find all the pdfs and copy them all to one directory on the remote server. I've tried about 10 variations with no luck. Both mine and the remote systems do not seem to recognise -exec as a command though exec is fine so thats a problem.</p>
<p>Im not sure what the problem is here but the command does not fail it just sits there and stalls forever so I do not have any useful errors to post.</p>
<pre><code>cp $(find -name "*.pdf" -type f; exec ./pdfsfolder {} \; | sed 1q)
find: ./tcs/u25: Permission denied
find: ./tcs/u68: Permission denied
-bash: /var/www/html/tcs_dev/sites/default/files/pdfsfolder: is a directory
-bash: exec: /var/www/html/tcs_dev/sites/default/files/pdfsfolder: cannot execute: Success
cp: target `./runaways_parents_guide_2013_final.pdf' is not a directory
</code></pre>
<p>This is the last one I tried, I think I can ignore the permission denied errors for now but im not sure about the rest. </p> | 18,339,127 | 3 | 0 | null | 2013-08-20 14:55:46.617 UTC | 28 | 2021-06-07 18:59:36.997 UTC | 2021-06-07 18:59:36.997 UTC | null | 1,575,066 | null | 2,066,039 | null | 1 | 62 | linux|bash|centos | 112,486 | <p>Try this:</p>
<pre><code>find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;
</code></pre> |
18,372,952 | Split tuple items to separate variables | <p>I have tuple in Python that looks like this:</p>
<pre><code>tuple = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')
</code></pre>
<p>and I wanna split it out so I could get every item from tuple independent so I could do something like this:</p>
<pre><code>domain = "sparkbrowser.com"
level = 0
url = "http://facebook.com/sparkbrowser"
text = "Facebook"
</code></pre>
<p>or something similar to that, My need is to have every item separated. I tried with <code>.split(",")</code> on tuple but I've gotten error which says that tuple doesn't have split option.</p> | 18,372,987 | 4 | 1 | null | 2013-08-22 06:15:43.4 UTC | 4 | 2020-12-31 02:07:45.693 UTC | 2020-12-31 02:07:45.693 UTC | null | 68,587 | null | 2,302,821 | null | 1 | 22 | python|tuples|iterable-unpacking | 120,090 | <p>Python can unpack sequences naturally.</p>
<pre><code>domain, level, url, text = ('sparkbrowser.com', 0, 'http://facebook.com/sparkbrowser', 'Facebook')
</code></pre> |
5,466,411 | How to print regexp matches using awk? | <p>Is there a way to print a regexp match (but only the matching string) using <code>awk</code> command in shell?</p> | 5,466,422 | 3 | 0 | null | 2011-03-28 23:58:57.83 UTC | 9 | 2022-07-11 08:50:45.89 UTC | 2022-07-11 08:50:45.89 UTC | null | -1 | null | 127,508 | null | 1 | 40 | bash|shell|awk | 70,657 | <p>Yes, in <code>awk</code> use the <code>match()</code> function and give it the optional array parameter (<code>a</code> in my example). When you do this, the 0-th element will be the part that matched the regex</p>
<pre><code>$ echo "blah foo123bar blah" | awk '{match($2,"[a-z]+[0-9]+",a)}END{print a[0]}'
foo123
</code></pre> |
5,191,487 | Objective-C: Forward Class Declaration | <p>I'm writing a multiview app that utilizes a class called <code>RootViewController</code> to switch between views.</p>
<p>In my <code>MyAppDelegate</code> header, I create an instance of the <code>RootViewController</code> called <code>rootViewController</code>. I've seen examples of such where the @class directive is used as a "forward class declaration," but I'm not quite sure what this means or accomplishes.</p>
<pre><code>#import <UIKit/UIKit.h>
@class RootViewController;
@interface MyAppDelegate
.
.
.
</code></pre> | 5,191,507 | 3 | 1 | null | 2011-03-04 08:44:39.183 UTC | 24 | 2020-05-20 15:53:53.99 UTC | 2016-07-13 18:06:51.497 UTC | null | 4,370,109 | null | 205,926 | null | 1 | 53 | objective-c|c-preprocessor|forward-declaration | 49,435 | <p>It basically tells the compiler that the class <code>RootViewController</code> exists, without specifying what exactly it looks like (ie: its methods, properties, etc). You can use this to write code that includes <code>RootViewController</code> member variables without having to include the full class declaration.</p>
<p>This is particularly useful in resolving circular dependencies - for example, where say <code>ClassA</code> has a member of type <code>ClassB*</code>, and <code>ClassB</code> has a member of type <code>ClassA*</code>. You need to have <code>ClassB</code> declared before you can use it in <code>ClassA</code>, but you also need <code>ClassA</code> declared before you can use it in <code>ClassB</code>. Forward declarations allow you to overcome this by saying to <code>ClassA</code> that <code>ClassB</code> exists, without having to actually specify <code>ClassB's</code> complete specification.</p>
<p>Another reason you tend to find lots of forward declarations is some people adopt a convention of forward declaring classes unless they absolutely must include the full declaration. I don't entirely recall, but possibly that's something that Apple recommends in it's Objective-C guiding style guidlines.</p>
<p>Continuing my above example, if your declarations of <code>ClassA</code> and <code>ClassB</code> are in the files <code>ClassA.h</code> and <code>ClassB.h</code> respectively, you'd need to <code>#import</code> whichever one to use its declaration in the other class. Using forward declaration means you don't need the <code>#import</code>, which makes the code prettier (particularly once you start collecting quite a few classes, each of which would need an `#import where it's used), and increases compiling performance by minimising the amount of code the compiler needs to consider while compiling any given file.</p>
<p>As an aside, although the question is concerned solely with forward declarations in Objective-C, all the proceeding comments also apply equally to coding in C and C++ (and probably many other languages), which also support forward declaration and typically use it for the same purposes.</p> |
25,888,677 | New itunes connect crash logs | <p>How can i find crash logs in the new itunes connect? The documentation on apple, refers to the old itunes connect, but cannot find it nowhere in the new version</p> | 39,398,485 | 1 | 2 | null | 2014-09-17 10:54:22.593 UTC | 2 | 2016-09-08 19:08:35.537 UTC | 2016-07-12 16:40:45.717 UTC | null | 881,229 | null | 533,422 | null | 1 | 34 | app-store-connect | 15,068 | <p>Actually they have integrated it to your XCode organizer. if you open organizer in XCode, and select your app, in the top, you will find archive and crashes tab. </p> |
9,533,258 | What is the maximum number of bytes for a UTF-8 encoded character? | <p>What is the maximum number of bytes for a single UTF-8 encoded character?</p>
<p>I'll be encrypting the bytes of a String encoded in UTF-8 and therefore need to be able to work out the maximum number of bytes for a UTF-8 encoded String.</p>
<p>Could someone confirm the maximum number of bytes for a single UTF-8 encoded character please</p> | 9,533,324 | 4 | 4 | null | 2012-03-02 12:26:12.423 UTC | 17 | 2022-05-03 12:50:50.54 UTC | null | null | null | null | 669,645 | null | 1 | 91 | utf-8|character-encoding|byte|character | 66,412 | <p>The maximum number of bytes per character is 4 according to <a href="https://www.rfc-editor.org/rfc/rfc3629" rel="noreferrer">RFC3629</a> which limited the character table to <code>U+10FFFF</code>:</p>
<blockquote>
<p>In UTF-8, characters from the U+0000..U+10FFFF range (the UTF-16
accessible range) are encoded using sequences of 1 to 4 octets.</p>
</blockquote>
<p>(The original specification allowed for up to six byte character codes for code points past <code>U+10FFFF</code>.)</p>
<p>Characters with a code less than 128 will require 1 byte only, and the next 1920 character codes require 2 bytes only. Unless you are working with an esoteric language, multiplying the character count by 4 will be a significant overestimation.</p> |
18,455,698 | Lightweight memory leak debugging on linux | <p>I looked for existing answers first and saw that <em>Valgrind</em> is everyone’s favorite tool for memory leak debugging on linux. Unfortunately <em>Valgrind</em> does not seem to work for my purposes. I will try to explain why.</p>
<p>Constraints:</p>
<ul>
<li>The leak reproduces only in customer’s environment. Due to certain
legal restrictions we have to work with existing binary. No rebuilds.</li>
<li>In regular environment our application consumes ~10% CPU. Say, we can
tolerate up to 10x CPU usage increase. <em>Valgrind</em> with default <em>memcheck</em>
settings does much worse making our application unresponsive for long
periods of time.</li>
</ul>
<p>What I need is an equivalent of Microsoft’s <em>UMDH</em>: turn on stack tracing for each heap allocation, then at certain point of time dump all allocations grouped by stacks and ordered by allocation count in descending order. Our app ships on both Windows and Linux platforms, so I know that performance on Windows under <em>UMDH</em> is still tolerable.</p>
<p>Here are the tools/methods I considered</p>
<ul>
<li><em>Valgrind</em>'s <em>-memcheck</em> and <em>–massif</em> tools They do much more than needed (like scanning whole process memory for every allocation
pointer), they are too slow, and they still don’t do exactly what I<br>
need (dump callstacks sorted by counts), so I will have to write some
scripts parsing the output</li>
<li><em>dmalloc</em> library (dmalloc.com) requires new binary</li>
<li>LeakTracer (<a href="http://www.andreasen.org/LeakTracer/" rel="noreferrer">http://www.andreasen.org/LeakTracer/</a>) Works only with C++
<em>new/delete</em> (I need <em>malloc/free</em> as well), does not have group-by-stack
and sort functionality</li>
<li>Implementing the tool myself as .so library using LD_PRELOAD
mechanism
(<a href="https://stackoverflow.com/questions/6083337/overriding-malloc-using-the-ld-preload-mechanism">Overriding 'malloc' using the LD_PRELOAD mechanism</a>)
That will take at least a week given my coding-for-Linux skills and it feels
like inventing a bicycle.</li>
</ul>
<p>Did I miss anything? Are there any lightweight <em>Valgrind</em> options or existing LD_PRELOAD tool?</p> | 18,938,060 | 8 | 3 | null | 2013-08-27 01:52:25.48 UTC | 18 | 2019-07-30 22:48:30.413 UTC | 2017-05-23 12:00:28.89 UTC | null | -1 | null | 1,236,546 | null | 1 | 22 | c++|c|linux|valgrind | 30,802 | <p>Surprisingly, I was unable to find anything like Microsoft's UMDH in open-source domain or available for immediate download. (I also looked at <a href="http://google-perftools.googlecode.com/svn/trunk/doc/heap_checker.html" rel="nofollow">Google Heap Leak Checker</a> but it is more like Valgrind rather than to UMDH). So I ended up writing the tool myself using <a href="https://github.com/jtolds/malloc_instrumentation" rel="nofollow">malloc instrumentation</a> project as a reference point: </p>
<p><a href="https://github.com/glagolig/heapwatch" rel="nofollow">https://github.com/glagolig/heapwatch</a></p>
<p>The tool has number of limitations, but it worked just fine for my purposes.</p> |
14,989,397 | How to convert sample rate from AV_SAMPLE_FMT_FLTP to AV_SAMPLE_FMT_S16? | <p>I am decoding aac to pcm with ffmpeg with avcodec_decode_audio3. However it decodes into AV_SAMPLE_FMT_FLTP sample format (PCM 32bit Float Planar) and i need AV_SAMPLE_FMT_S16 (PCM 16 bit signed - S16LE).</p>
<p>I know that ffmpeg can do this easily with -sample_fmt. I want to do the same with the code but i still couldn't figure it out.</p>
<p>audio_resample did not work for: it fails with error message: .... conversion failed.</p> | 15,372,417 | 3 | 1 | null | 2013-02-20 20:35:34.553 UTC | 17 | 2019-12-27 22:56:05.373 UTC | null | null | null | null | 320,801 | null | 1 | 15 | android-ndk|ffmpeg|sample|pcm|libav | 21,253 | <p><strong>EDIT 9th April 2013</strong>: Worked out how to use libswresample to do this... much faster!</p>
<p>At some point in the last 2-3 years FFmpeg's AAC decoder's output format changed from AV_SAMPLE_FMT_S16 to AV_SAMPLE_FMT_FLTP. This means that each audio channel has it's own buffer, and each sample value is a 32-bit floating point value scaled from -1.0 to +1.0.</p>
<p>Whereas with AV_SAMPLE_FMT_S16 the data is in a single buffer, with the samples interleaved, and each sample is a signed integer from -32767 to +32767.</p>
<p>And if you really need your audio as AV_SAMPLE_FMT_S16, then you have to do the conversion yourself. I figured out two ways to do it:</p>
<p><strong>1. Use libswresample</strong> (recommended)</p>
<pre><code>#include "libswresample/swresample.h"
...
SwrContext *swr;
...
// Set up SWR context once you've got codec information
swr = swr_alloc();
av_opt_set_int(swr, "in_channel_layout", audioCodec->channel_layout, 0);
av_opt_set_int(swr, "out_channel_layout", audioCodec->channel_layout, 0);
av_opt_set_int(swr, "in_sample_rate", audioCodec->sample_rate, 0);
av_opt_set_int(swr, "out_sample_rate", audioCodec->sample_rate, 0);
av_opt_set_sample_fmt(swr, "in_sample_fmt", AV_SAMPLE_FMT_FLTP, 0);
av_opt_set_sample_fmt(swr, "out_sample_fmt", AV_SAMPLE_FMT_S16, 0);
swr_init(swr);
...
// In your decoder loop, after decoding an audio frame:
AVFrame *audioFrame = ...;
int16_t* outputBuffer = ...;
swr_convert(&outputBuffer, audioFrame->nb_samples, audioFrame->extended_data, audioFrame->nb_samples);
</code></pre>
<p>And that's all you have to do!</p>
<p><strong>2. Do it by hand in C</strong> (original answer, not recommended)</p>
<p>So in your decode loop, when you've got an audio packet you decode it like this:</p>
<pre><code>AVCodecContext *audioCodec; // init'd elsewhere
AVFrame *audioFrame; // init'd elsewhere
AVPacket packet; // init'd elsewhere
int16_t* outputBuffer; // init'd elsewhere
int out_size = 0;
...
int len = avcodec_decode_audio4(audioCodec, audioFrame, &out_size, &packet);
</code></pre>
<p>And then, if you've got a full frame of audio, you can convert it fairly easily:</p>
<pre><code> // Convert from AV_SAMPLE_FMT_FLTP to AV_SAMPLE_FMT_S16
int in_samples = audioFrame->nb_samples;
int in_linesize = audioFrame->linesize[0];
int i=0;
float* inputChannel0 = (float*)audioFrame->extended_data[0];
// Mono
if (audioFrame->channels==1) {
for (i=0 ; i<in_samples ; i++) {
float sample = *inputChannel0++;
if (sample<-1.0f) sample=-1.0f; else if (sample>1.0f) sample=1.0f;
outputBuffer[i] = (int16_t) (sample * 32767.0f);
}
}
// Stereo
else {
float* inputChannel1 = (float*)audioFrame->extended_data[1];
for (i=0 ; i<in_samples ; i++) {
outputBuffer[i*2] = (int16_t) ((*inputChannel0++) * 32767.0f);
outputBuffer[i*2+1] = (int16_t) ((*inputChannel1++) * 32767.0f);
}
}
// outputBuffer now contains 16-bit PCM!
</code></pre>
<p>I've left a couple of things out for clarity... the clamping in the mono path should ideally be duplicated in the stereo path. And the code can be easily optimized.</p> |
15,241,603 | Formatting kendo numeric text box | <p>I have a kendo numeric box in grid. Only numbers are allowed in it. No decimal places and no comma separators. I tried in different ways but did not succeeded. Any idea ... Please help me... </p>
<p>In data source fields i given like this</p>
<pre><code>seq_no : {type: "number",validation: {min: 1,max: 32767}}
</code></pre>
<p>In column of grid </p>
<pre><code>{ field: "seq_no", width: "50px", title: "Sequence Number", type:"number"}
</code></pre> | 15,242,182 | 4 | 0 | null | 2013-03-06 07:40:28.37 UTC | 3 | 2015-01-14 14:14:57.28 UTC | 2013-03-06 07:52:36.11 UTC | null | 1,940,702 | null | 1,940,702 | null | 1 | 16 | kendo-ui|kendo-grid | 41,517 | <p>Use <a href="http://docs.kendoui.com/api/web/grid#columnsformat-string" rel="noreferrer"><code>format</code></a> with value <code>{0:n0}</code>:</p>
<pre><code>{ field: "seq_no", width: "50px", title: "Sequence Number", type:"number", format: "{0:n0}" }
</code></pre> |
15,026,953 | HttpClient Request like browser | <p>When I calling site www.livescore.com by HttpClient class I always getting error "500".
Probably server blocked request from HttpClients.</p>
<p>1)There is any other method to get html from webpage?</p>
<p>2)How I can set the headers to get html content?</p>
<p>When I set headers like in browser I always get stange encoded content.</p>
<pre><code> http_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
http_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
http_client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
http_client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
</code></pre>
<p>3) How I can slove this problem? Any suggestions?</p>
<p>I using Windows 8 Metro Style App in C# and HttpClientClass</p> | 15,031,536 | 4 | 3 | null | 2013-02-22 14:58:50.897 UTC | 19 | 2019-05-04 08:59:08.373 UTC | null | null | null | null | 1,945,043 | null | 1 | 33 | c#|windows-8|http-headers | 52,203 | <p>Here you go - note you have to decompress the gzip encoded-result you get back <a href="https://stackoverflow.com/a/15031419/3312">as per</a> <a href="https://stackoverflow.com/users/470473/mleroy">mleroy</a>:</p>
<pre><code>private static readonly HttpClient _HttpClient = new HttpClient();
private static async Task<string> GetResponse(string url)
{
using (var request = new HttpRequestMessage(HttpMethod.Get, new Uri(url)))
{
request.Headers.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
request.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
request.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0");
request.Headers.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
using (var response = await _HttpClient.SendAsync(request).ConfigureAwait(false))
{
response.EnsureSuccessStatusCode();
using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
using (var decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress))
using (var streamReader = new StreamReader(decompressedStream))
{
return await streamReader.ReadToEndAsync().ConfigureAwait(false);
}
}
}
}
</code></pre>
<p>call such like:</p>
<pre><code>var response = await GetResponse("http://www.livescore.com/").ConfigureAwait(false); // or var response = GetResponse("http://www.livescore.com/").Result;
</code></pre> |
15,000,544 | How to get the string size in bytes? | <p>As the title implies, my question is how to get the size of a string in <code>C</code>. Is it good to use <code>sizeof</code> if I've declared it (the string) in a function without <code>malloc</code> in it? Or, if I've declared it as a pointer? What if I initialized it with <code>malloc</code>? I would like to have an exhaustive response.</p> | 15,000,609 | 6 | 2 | null | 2013-02-21 11:00:56.387 UTC | 11 | 2022-07-17 11:40:19.663 UTC | 2017-01-03 11:03:33.673 UTC | null | 5,050,060 | null | 232,695 | null | 1 | 34 | c|sizeof|arrays | 211,446 | <p>You can use <a href="http://www.cplusplus.com/reference/cstring/strlen/" rel="noreferrer">strlen</a>. Size is determined by the terminating null-character, so passed string should be valid.</p>
<p>If you want to get size of memory buffer, that contains your string, and you have pointer to it:</p>
<ul>
<li>If it is dynamic array(created with malloc), it is impossible to get
it size, since compiler doesn't know what pointer is pointing at.
(<a href="https://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array">check this</a>)</li>
<li>If it is static array, you can use <code>sizeof</code> to get its size.</li>
</ul>
<p>If you are confused about difference between dynamic and static arrays, check <a href="https://stackoverflow.com/questions/2672085/c-static-array-vs-dynamic-array">this</a>.</p> |
14,930,950 | What are the differences between the different Map implementations in Dart? | <p>Dart has a Map type, with implementations like <a href="https://api.dartlang.org/stable/2.1.0/dart-collection/HashMap-class.html" rel="noreferrer">HashMap</a>, <a href="https://api.dartlang.org/stable/2.1.0/dart-collection/LinkedHashMap-class.html" rel="noreferrer">LinkedHashMap</a>, and <a href="https://api.dartlang.org/stable/2.1.0/dart-collection/SplayTreeMap-class.html" rel="noreferrer">SplayTreeMap</a>. What's the difference between those different Map implementations?</p> | 14,930,951 | 2 | 0 | null | 2013-02-18 06:54:58.73 UTC | 13 | 2020-09-17 14:02:37.817 UTC | 2019-01-15 13:46:42.853 UTC | null | 884,463 | null | 123,471 | null | 1 | 53 | dart | 21,748 | <p>Dart has built-in support for collections like List, Set, and Map. Dart has different Map implementations. Understanding the pros and cons between implementations can help you make an informed decision.</p>
<p>(Note: this is written around the time of Dart M3, so what follows might not match the docs at this moment.)</p>
<h1>What is a Map?</h1>
<p>A Map is an associative container, mapping keys to values. Keys are unique, and can point to one and only one value. A key cannot be null, but a value can be null.</p>
<h1>Map Literals</h1>
<p>Dart supports <a href="https://www.dartlang.org/guides/language/language-tour#maps" rel="noreferrer">Map literals</a>, like this:</p>
<pre class="lang-dart prettyprint-override"><code>var accounts = {'323525': 'John Smith', '588982': 'Alice Jones'};
</code></pre>
<p>The spec says that map literals must maintain insertion order. This means that <code>accounts</code> is an instance of <code>LinkedHashMap</code>.</p>
<p>The spec also says that Map literal keys must be Strings. This might be changed in the future.</p>
<h1>new Map()</h1>
<p>Dart supports factory constructors, so you can create a new instance of Map like this:</p>
<pre class="lang-dart prettyprint-override"><code>var accounts = new Map();
</code></pre>
<p>The <code>Map</code> class is abstract, which means the factory constructor actually creates an instance of a subclass of <code>Map</code>. So what is the actual type of <code>accounts</code> ?</p>
<p>Earlier versions of Dart created a new instance of <code>HashMap</code> from the <code>new Map()</code> constructor. However, <a href="http://code.google.com/p/dart/issues/detail?id=5803" rel="noreferrer">Dart bug 5803</a> states that in order to make <code>{}</code> and <code>new Map</code> return the same type, <code>new Map</code> will soon return an instance of <code>LinkedHashMap</code>.</p>
<h1>LinkedHashMap (or, InsertionOrderedMap)</h1>
<p>A <code>LinkedHashMap</code> iterates through keys and values in the same order they were inserted.</p>
<p><em>Note:</em> LinkedHashMap will probably be renamed to InsertionOrderedMap. Follow <a href="http://code.google.com/p/dart/issues/detail?id=2349" rel="noreferrer">Dart bug 2349</a> for progress.</p>
<p>Here is an example:</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:collection';
main() {
var ordered = new LinkedHashMap();
ordered['32352'] = 'Alice';
ordered['95594'] = 'Bob';
for (var key in ordered.keys) {
print(key);
}
// guaranteed to print 32352, then 95594
}
</code></pre>
<p>Here is the <a href="http://code.google.com/p/dart/source/browse/trunk/dart/sdk/lib/collection/linked_hash_map.dart" rel="noreferrer">source code for LinkedHashMap</a>. (if this link stops working, it's probably because the class was renamed)</p>
<h1>HashMap</h1>
<p>A HashMap has no guarantee of maintaining insertion order. When you iterate through a HashMap's keys or values, you cannot expect a certain order.</p>
<p>A HashMap is implemented using a <a href="http://en.wikipedia.org/wiki/Hash_table" rel="noreferrer">hash table</a>.</p>
<p>Here is an example of creating a new HashMap:</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:collection';
main() {
var accounts = new HashMap();
}
</code></pre>
<p>If you don't care about maintaining insertion order, use HashMap.</p>
<p>Here is the <a href="http://code.google.com/p/dart/source/browse/trunk/dart/sdk/lib/collection/hash_map.dart" rel="noreferrer">source code of HashMap</a>.</p>
<h1>SplayTreeMap</h1>
<p>A splay tree is a self-balancing binary search tree with the additional property that recently accessed elements are quick to access again. It performs basic operations such as insertion, look-up and removal in O(log(n)) amortized time.</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:collection';
main() {
var accounts = new SplayTreeMap();
}
</code></pre>
<p>A SplayTreeMap requires that all keys are of the same type.</p>
<p>A splay tree is a good choice for data that is stored and accessed frequently, like caches. The reason is that they use tree rotations to bring up an element to the root for better frequent accesses. The performance comes from the self-optimization of the tree. That is, frequently accessed elements are moved nearer to the top. If however, the tree is equally often accessed all around, then there's little point of using a splay tree map.</p>
<p>An example case is a modem router that receives network packets at very high rates. The modem has to decide which packet go in which wire. It can use a map implementation where the key is the IP and the value is the destination. A splay tree map is a good choice for this scenario, because most IP addresses will be used more than once and therefore those can be found from the root of the tree.</p> |
38,505,184 | Asp.Net core get RouteData value from url | <p>I'm wokring on a new Asp.Net core mvc app. I defined a route with a custom constraint, which sets current app culture from the url. I'm trying to manage localization for my app by creating a custom <code>IRequestCultureProvider</code> which looks like this :</p>
<pre><code>public class MyCustomRequestCultureProvider : IRequestCultureProvider
{
public Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
var language= httpContext.GetRouteValue("language");
var result = new ProviderCultureResult(language, language);
return Task.FromResult(result);
}
}
</code></pre>
<p>My <code>MyCustomRequestCultureProvider</code> is hit on every request, which is ok. My problem is that in the MVC pipeline, <code>DetermineProviderCultureResult</code> method from my provider is hit before the routing process, so <code>httpContext.GetRouteValue("language")</code> always return null.</p>
<p>In previous version of MVC, I had the possiblity to manually process my url through the routing process by doing this</p>
<pre><code>var wrapper = new HttpContextWrapper(HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(wrapper);
var language = routeData.GetValue("language")
</code></pre>
<p>I can't find a way to do the same thing in the new framewrok right now. Also, I want to use the route data to find out my langugae, analysing my url string with some string functions to find the language is not an option.</p> | 38,939,050 | 3 | 3 | null | 2016-07-21 13:09:34.623 UTC | 5 | 2020-08-31 18:18:38.62 UTC | null | null | null | null | 912,299 | null | 1 | 29 | asp.net-core|asp.net-core-mvc|asp.net-core-1.0 | 21,824 | <p>There isn't an easy way to do this, and the ASP.Net team hasn't decided to implement this functionality yet. <code>IRoutingFeature</code> is only available after MVC has completed the request.</p>
<p>I was able to put together a solution that should work for you though. This will setup the routes you're passing into <code>UseMvc()</code> as well as all attribute routing in order to populate IRoutingFeature. After that is complete, you can access that class via <code>httpContext.GetRouteValue("language");</code>.</p>
<p><strong>Startup.cs</strong></p>
<pre><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// setup routes
app.UseGetRoutesMiddleware(GetRoutes);
// add localization
var requestLocalizationOptions = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture("en-US")
};
requestLocalizationOptions.RequestCultureProviders.Clear();
requestLocalizationOptions.RequestCultureProviders.Add(
new MyCustomRequestCultureProvider()
);
app.UseRequestLocalization(requestLocalizationOptions);
// add mvc
app.UseMvc(GetRoutes);
}
</code></pre>
<p>Moved the routes to a delegate (for re-usability), same file/class:</p>
<pre><code>private readonly Action<IRouteBuilder> GetRoutes =
routes =>
{
routes.MapRoute(
name: "custom",
template: "{language=fr-FR}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
};
</code></pre>
<p><strong>Add new middleware:</strong></p>
<pre><code>public static class GetRoutesMiddlewareExtensions
{
public static IApplicationBuilder UseGetRoutesMiddleware(this IApplicationBuilder app, Action<IRouteBuilder> configureRoutes)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var routes = new RouteBuilder(app)
{
DefaultHandler = app.ApplicationServices.GetRequiredService<MvcRouteHandler>(),
};
configureRoutes(routes);
routes.Routes.Insert(0, AttributeRouting.CreateAttributeMegaRoute(app.ApplicationServices));
var router = routes.Build();
return app.UseMiddleware<GetRoutesMiddleware>(router);
}
}
public class GetRoutesMiddleware
{
private readonly RequestDelegate next;
private readonly IRouter _router;
public GetRoutesMiddleware(RequestDelegate next, IRouter router)
{
this.next = next;
_router = router;
}
public async Task Invoke(HttpContext httpContext)
{
var context = new RouteContext(httpContext);
context.RouteData.Routers.Add(_router);
await _router.RouteAsync(context);
if (context.Handler != null)
{
httpContext.Features[typeof (IRoutingFeature)] = new RoutingFeature()
{
RouteData = context.RouteData,
};
}
// proceed to next...
await next(httpContext);
}
}
</code></pre>
<p>You may have to define this class as well...</p>
<pre><code>public class RoutingFeature : IRoutingFeature
{
public RouteData RouteData { get; set; }
}
</code></pre> |
8,133,505 | django TemplateView and form | <p>I have some problem to figure out how new django views (template view) and forms can works I also can't find good resources, official doc don't explain me how can get request ( I mean get and post) and forms in new django views class</p>
<p>Thanks</p>
<p>added for better explain</p>
<p>for example I have this form :</p>
<pre><code>from django import forms
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
cc_myself = forms.BooleanField(required=False)
</code></pre>
<p>and this is the code for read and print the form (old fashion way):</p>
<pre><code>def contact(request):
if request.method == 'POST': # If the form has been submitted...
form = ContactForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/thanks/') # Redirect after POST
else:
form = ContactForm() # An unbound form
return render_to_response('contact.html', {
'form': form,
})
</code></pre>
<p>well my question is how you can do the same thing with template view thanks</p> | 8,134,262 | 2 | 1 | null | 2011-11-15 08:36:52.04 UTC | 9 | 2014-11-21 05:43:49.71 UTC | 2011-11-15 10:13:53.543 UTC | null | 233,150 | null | 233,150 | null | 1 | 21 | django|forms|django-templates | 36,585 | <p>I would recommend just plodding through the <a href="https://docs.djangoproject.com/en/dev/intro/tutorial01/">official tutorial</a> and I think realization will dawn and enlightenment will come automatically.</p>
<p>Basically:
When you issue a request: '''http://mydomain/myblog/foo/bar'''
Django will:</p>
<ol>
<li>resolve <code>myblog/foo/bar</code> to a function/method call through the patterns defined in urls.py</li>
<li>call that function with the request as parameter, e.g. <code>myblog.views.foo_bar_index(request)</code>.</li>
<li>and just send whatever string that function returns to the browser. Usually that's your generated html code.</li>
</ol>
<p>The view function usually does the following:</p>
<ol>
<li>Fill the context dict for the view</li>
<li>Renders the template using that context</li>
<li>returns the resulting string</li>
</ol>
<p>The template generic view allows you to skip writing that function, and just pass in the context dictionary.</p>
<p>Quoting the django docs:</p>
<pre><code>from django.views.generic import TemplateView
class AboutView(TemplateView):
template_name = "about.html"
</code></pre>
<p>All views.generic.*View classes have views.generic.View as their base. In the <a href="https://docs.djangoproject.com/en/dev/ref/class-based-views/#django.views.generic.base.View">docs</a> to that you find the information you require.
Basically:</p>
<pre><code># urls.py
urlpatterns = patterns('',
(r'^view/$', MyView.as_view(size=42)),
)
</code></pre>
<p>MyView.as_view will generate a callable that calls views.generic.View.dispatch()
which in turn will call MyView.get(), MyView.post(), MyView.update() etc.
which you can override.</p>
<p>To quote the docs:</p>
<blockquote>
<p>class View</p>
<p>dispatch(request, *args, **kwargs)</p>
<p>The view part of the view -- the method that accepts a request
argument plus arguments, and returns a HTTP response. The default
implementation will inspect the HTTP method and attempt to delegate to
a method that matches the HTTP method; a GET will be delegated to
get(), a POST to post(), and so on.</p>
<p>The default implementation also sets request, args and kwargs as
instance variables, so any method on the view can know the full
details of the request that was made to invoke the view.</p>
</blockquote>
<p>The big plusses of the class based views (in my opinion):</p>
<ol>
<li>Inheritance makes them <strong>dry</strong>.</li>
<li>More declarative form of programming</li>
</ol> |
9,083,743 | Is bit shifting O(1) or O(n)? | <p>Are shift operations <code>O(1)</code> or <code>O(n)</code> ?</p>
<p>Does it make sense that computers generally require more operations to shift 31 places instead of shifting 1 place?</p>
<p>Or does it make sense the <em>number of operations</em> required for shifting is <strong>constant</strong> regardless of how many places we need to shift?</p>
<p>PS: wondering if <em>hardware</em> is an appropriate tag..</p> | 9,084,633 | 7 | 10 | null | 2012-01-31 17:05:43.437 UTC | 10 | 2019-05-26 18:34:48.273 UTC | 2017-09-26 03:07:12.857 UTC | null | 3,885,376 | null | 632,951 | null | 1 | 42 | language-agnostic|big-o|cpu|hardware|bit-shift | 16,453 | <p>Some instruction sets are limited to one bit shift per instruction. And some instruction sets allow you to specify any number of bits to shift in one instruction, which usually takes one clock cycle on modern processors (modern being an intentionally vague word). See <a href="https://stackoverflow.com/a/9083865/4098326">dan04's answer</a> about a barrel shifter, a circuit that shifts more than one bit in one operation.</p>
<p>It all boils down to the logic algorithm. Each bit in the result is a logic function based on the input. For a single right shift, the algorithm would be something like:</p>
<ul>
<li>If the instruction is [shift right] and bit 1 of the input is 1, then bit 0 of the result is 1, else bit 0 is 0.</li>
<li>If the instruction is [shift right], then bit 1 = bit 2.</li>
<li>etc. </li>
</ul>
<p>But the logic equation could just as easily be:</p>
<ul>
<li>If the instruction is [shift right] and the amount operand is 1, then result bit 0 = shifted input bit 1.</li>
<li>if the amount is 2 then bit 0 = bit 2.</li>
<li>and so on.</li>
</ul>
<p>The logic gates, being asynchronous, can do all of this in one clock cycle. Yet it is true the single shift allows for a faster clock cycle and less gates to settle, if all you are comparing is these two flavors of an instruction. Or the alternative is making it take longer to settle, so the instruction takes 2 or 3 clocks or whatever, and the logic counts to 3 then latches the result. </p>
<p>The MSP430, for example, only has single bit rotate right instructions (because you can perform a single bit shift or a rotate left with another instruction, which I will leave to the reader to figure out).</p>
<p>The ARM instruction set allows both immediate and register based multi-bit rotates, arithmetic shifts and logical shifts. I think there is only one actual rotate instruction and the other is an alias, because rotate left 1 is the same as a rotate right 32, you only need an one direction barrel shifter to implement a multi bit rotate.</p>
<p>SHL in the x86 allows more than one bit per instruction, but it used to take more than one clock.</p>
<p>and so on, you can easily examine any of the instruction sets out there.</p>
<p>The answer to your question is that it is not fixed. Sometimes it is one operation, one cycle, one instruction. Sometimes it is one instruction multiple clock cycles. Sometimes it is multiple instructions, multiple clock cycles. </p>
<p>The compilers often optimize for these sorts of things. Say you have a 16 bit register instruction set with a swap byte instruction and an AND instruction with immediate, but only a single bit shift. You may think shifting 8 bits would require 8 shift instruction cycles, but you could just swap bytes (one instruction) and then AND the lower half to zeros (which might take two instructions, or might be a variable word length instruction of two words, or it might encode into a single instruction) so it only takes 2 or 3 instruction/clock cycles instead of 8. For a shift of 9 bits, you can do the same thing and add a shift, making it 9 clocks vs 3 or 4. Also, on some architectures, it is faster to multiply by 256 than to shift by 8, etc, etc. Each instruction set has its own limitations and tricks.</p>
<p>It is not even the case that either most instruction sets provide multi bit or most limit to single bit. The processors that fall into the "computer" category, like X86, ARM, PowerPC, and MIPS, would lean toward one operation to shift. Expand to all processors but not necessarily "computers" commonly used today, and it shifts the other way, I would say more of them are single bit than multi bit, so multiple operations are needed to perform a multi-bit shift.</p> |
5,007,575 | How to assign a remote file to Carrierwave? | <p>I have video model with the following definition:</p>
<pre><code>class Video
require 'carrierwave/orm/activerecord'
mount_uploader :attachment, VideoUploader
mount_uploader :attachment_thumbnail, VideoThumbnailUploader
...
end
</code></pre>
<p>When I upload a video file. It also sends the file to our encoding service Zencoder, which encodes the video file and creates a thumbnail for it.</p>
<p>Normally, I could do something like @video.attachment.url, which will return the path of the video file. I'd like to do the same thing with the thumbnail. i.e. @video.attachment_thumbnail.url</p>
<p>However, since the attachment is created by our encoding service, which also uploads it to a specified S3 bucket. How do I assign the attachment to the attachment_thumbnail column for the record?</p>
<p>Can I simply do something like:</p>
<pre><code>@video.update_attributes(
:attachment_thumbnail => 'https://bucket_name.s3.amazonaws.com/uploads/users/1/video/1/thumb.png'
)
</code></pre>
<p>Is it possible to assign files like this to Carrierwave?</p> | 5,007,665 | 4 | 3 | null | 2011-02-15 18:05:13.997 UTC | 13 | 2013-06-26 12:47:31.193 UTC | null | null | null | null | 501,171 | null | 1 | 25 | ruby-on-rails|amazon-s3|carrierwave | 31,493 | <p>You can do the following:</p>
<pre><code>@video.remote_attachment_thumbnail_url = 'https://bucket_name.s3.amazonaws.com/uploads/users/1/video/1/thumb.png'
</code></pre>
<p>But that will cause Carrierwave to download + reprocess the file rather than just make it the thumbnail. If you're not going to use Carrierwave's processing, then it might make more sense to just store the URL to the thumbnail on the model rather than even using Carrierwave.</p> |
5,067,724 | How to limit a generic type parameter to System.Enum | <blockquote>
<p><strong>Possible Duplicates:</strong><br>
<a href="https://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint">Anyone know a good workaround for the lack of an enum generic constraint?</a><br>
<a href="https://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum">Create Generic method constraining T to an Enum</a> </p>
</blockquote>
<p>Is is possible to limit the generic type parameter [I don't know if that's the right name] to an <code>Enum</code>?</p>
<p>For example how do I do something like this?</p>
<pre><code>//VB.NET
Function GetValues(Of T As System.Enum)(ByVal value As T) As IEnumerable(Of T)
Return [Enum].GetValues(value.GetType)
End Function
//C#
public IEnumerable<T> GetValues<T>(T value) where T : System.Enum
{
return Enum.GetValues(value.GetType());
}
</code></pre>
<hr>
<p><strong>Update</strong></p>
<p>I eventually used Jon Skeet's <a href="http://code.google.com/p/unconstrained-melody/" rel="noreferrer" title="Google Code: Unconstrained Melody">Unconstrained Melody</a> for that purpose. Thanks to you all for your contributions.</p> | 5,067,826 | 4 | 4 | null | 2011-02-21 15:23:25.117 UTC | 7 | 2014-01-07 06:20:46.453 UTC | 2017-05-23 12:09:39.44 UTC | null | -1 | null | 117,870 | null | 1 | 28 | c#|.net|vb.net|enums | 18,073 | <p>Unfortunately, you cannot - <a href="http://connect.microsoft.com/VisualStudio/feedback/details/386194/allow-enum-as-generic-constraint-in-c" rel="noreferrer">Microsoft closed this one out as a won't fix item</a>.</p>
<p>You can treat enums as structs and use that as the constraint instead (I think that was how Jon Skeet did it in <a href="http://code.google.com/p/unconstrained-melody/" rel="noreferrer">Unconstrained Melody</a>?) but that is kind of unsightly.</p> |
5,109,058 | WPF: the right way to scale a path? | <p>I have a path (looks like an oval):</p>
<pre><code><Path Data="Bla Bla"/>
</code></pre>
<p>Now I want to scale the path's width and height to whatever I like. I found a way:</p>
<pre><code><Grid Width="400" Height="50">
<Viewbox Stretch="Fill">
<Path Data="Bla Bla"/>
</Viewbox>
</Grid>
</code></pre>
<p>And this works, but I'm wondering if this is the most efficient way to do this? (I had to introduce a grid and viewbox to do this)</p> | 5,109,365 | 4 | 1 | null | 2011-02-24 18:47:48.477 UTC | 6 | 2014-12-29 12:31:29.833 UTC | null | null | null | null | 257,558 | null | 1 | 31 | c#|wpf|xaml | 29,423 | <p>Another way to Scale a Path is to use <code>RenderTransform</code> or <code>LayoutTransform</code></p>
<pre><code><Path Data="Bla Bla"
RenderTransformOrigin="0.5, 0.5">
<Path.RenderTransform>
<ScaleTransform ScaleX="1.5" ScaleY="1.5"/>
</Path.RenderTransform>
</Path>
</code></pre> |
5,377,434 | Does std::map::iterator return a copy of value or a value itself? | <p>I'm trying to create a map inside a map:</p>
<pre><code>typedef map<float,mytype> inner_map;
typedef map<float,inner_map> outer_map;
</code></pre>
<p>Will I be able to put something inside inner map, or does iterator::second returns a copy?</p>
<p><strong>stl_pair.h</strong> suggests the latter:</p>
<pre><code>74: _T2 second; ///< @c second is a copy of the second object
</code></pre>
<p>but my test program run fine with the code like this:</p>
<pre><code>it = my_map.lower_bound(3.1415);
(*it).second.insert(inner_map::value_type(2.71828,"Hello world!");
</code></pre>
<p>So where is the truth? Is this a copy or not?</p> | 5,377,493 | 4 | 0 | null | 2011-03-21 12:15:33.43 UTC | 7 | 2013-03-29 11:12:23.813 UTC | null | null | null | null | 669,398 | null | 1 | 32 | c++|iterator|stdmap | 29,109 | <p>The comment in <code>stl_pair.h</code> is misleading in this specific case.</p>
<p>There will be <em>no</em> copy, since the <code>map::iterator</code> actually refers to the <em>original data</em> inside the map (the <code>value_type</code>, which itself is a <code>pair</code>), it’s not a copy. Thus <code>iterator::second</code> also refers to the original data.</p> |
5,534,324 | How to run multiple programs using batch file | <p>I like to run two programs using batch file, but the condition is, the second program must start only after the first program loaded, so is there any way to control using timer to control when the program starts.</p> | 5,535,154 | 5 | 2 | null | 2011-04-04 03:35:01.637 UTC | 4 | 2021-04-10 09:40:22.12 UTC | null | null | null | null | 276,660 | null | 1 | 23 | batch-file | 104,111 | <p>Basically, you could try this approach (not tested):</p>
<ol>
<li><p>Run the first program using the <code>start</code> command.</p></li>
<li><p>Check the task list in a loop to see if the program has appeared there. </p></li>
<li><p>Impose some time limitation to the said loop.</p></li>
<li><p>Run the next program in case of success, exit with notification otherwise.</p></li>
</ol>
<p>The scripting might look like this:</p>
<pre><code>@ECHO OFF
START program1.exe
FOR /L %%i IN (1,1,100) DO (
(TASKLIST | FIND /I "program.exe") && GOTO :startnext
:: you might add here some <a href="https://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file">delaying</a>
)
ECHO Timeout waiting for program1.exe to start
GOTO :EOF
:startnext
program2.exe
:: or START program2.exe
</code></pre>
<p>Keep in mind that the timing is not precise, especially if you are going to insert delays between the task list checks.</p> |
5,478,109 | Remove focus border of EditText | <p>How can I remove the border with appears when focusing an EditText View?</p>
<p>I need it cause this view has little space in the screen, but without the border it's enough. When running on Emulator an orange border appears, on Device a blue one.</p> | 7,172,466 | 5 | 2 | null | 2011-03-29 19:51:33.993 UTC | 18 | 2018-11-08 09:38:46.753 UTC | null | null | null | null | 558,433 | null | 1 | 83 | android|android-edittext | 89,739 | <p>Have you tried setting the background of the <code>EditText</code> to a transparent colour?</p>
<pre><code><EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="@string/hello"
android:background="#00000000"
/>
</code></pre> |
5,377,070 | C# - R interface | <p>I need to interface R to some C# application. I installed <code>rscproxy_1.3</code> and <code>R_Scilab_DCOM3.0-1B5</code> added COM references to the <code>STATCONNECTORCLNTLib</code>, <code>StatConnectorCommonLib</code> and <code>STATCONNECTORSRVLib</code> but I still cannot get it working. </p>
<p>When I run following test program: </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//COM references
using STATCONNECTORCLNTLib;
using StatConnectorCommonLib;
using STATCONNECTORSRVLib;
namespace R_TESTING
{
class Program
{
static void Main(string[] args)
{
StatConnector sc1 = new STATCONNECTORSRVLib.StatConnectorClass();
sc1.Init("R");
}
}
}
</code></pre>
<p>I get this exception:</p>
<pre><code>Unhandled Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040013
at STATCONNECTORSRVLib.StatConnectorClass.Init(String bstrConnectorName)
</code></pre>
<p>Thanks in advance.</p>
<p><strong>UPDATE:</strong>
Ok, still no luck.
I will try to explain what I did so far.</p>
<blockquote>
<p>Installed R-2.12.2-win.exe from
rproject to the <code>C:\Program
Files\R\R-2.12.2</code></p>
<p>Downloaded rscproxy_1.3-1.zip and
copy/pasted it to the <code>C:\Program
Files\R\R-2.12.2\library</code></p>
<p>Installed R_Scilab_DCOM3.0-1B5.exe to
the <code>C:\Program Files (x86)\R\(D)COM
Server</code></p>
</blockquote>
<p>With Scilab comes a basic test. I tried to run it but I got following error:</p>
<blockquote>
<p>Loading StatConnector Server... Done
Initializing R...Function call failed
Code: -2147221485 Text: installation
problem: unable to load connector
Releasing StatConnector Server...Done</p>
</blockquote>
<p>Than I looked in the PATH/System Variables and found no path/R_HOME/R_USER info. Also, I couldn't find anything R related in the registry. </p>
<p>I guess I am doing something terribly wrong, so I desperately need help from you guys. </p> | 5,389,687 | 6 | 1 | null | 2011-03-21 11:35:48.233 UTC | 10 | 2014-08-03 19:10:21.863 UTC | 2011-03-21 16:41:48.81 UTC | null | 361,455 | null | 361,455 | null | 1 | 22 | c#|r | 35,188 | <p>Ok, I solved it finally.
The problem is that R (D)Com doesn't work with current version of R. I installed 2.11.1 and it worked out of box. </p>
<p>Thanks a lot.</p> |
17,097,348 | why css transition doesn't work | <p>I'm trying to add transition but it doesnt work
I added transition to my links and expect changes on hover state
I used transition alot, but some times this happens to me and I dont know why this property doesnt work</p>
<p>I prefer to know why it doesnt work</p>
<p>this is my code</p>
<pre><code><div class="subNavigation">
<ul>
<li>درباره بانک مهر</li>
<li><a href="javascript:void(0)">درباره بانک مهر 1</a></li>
<li><a href="javascript:void(0)">درباره بانک مهر 2</a></li>
<li><a href="javascript:void(0)">درباره بانک مهر 3</a></li>
<li><a href="javascript:void(0)">درباره بانک مهر 4</a></li>
</ul>
</div>
</code></pre>
<p>and css</p>
<pre><code>.subNavigation {
width: 900px;
height: 274px;
position: absolute;
top: 40px;
right: 0;
padding: 30px 60px 0 0;
}
/* line 126, ../sass/style.scss */
.subNavigation ul {
float: right;
}
/* line 130, ../sass/style.scss */
.subNavigation li {
width: 153px;
*zoom: 1;
margin-top: 4px;
padding-right: 2px;
padding-bottom: 4px;
border-bottom: 1px dotted #b4b4b4;
}
/* line 38, D:/Ruby193/lib/ruby/gems/1.9.1/gems/compass- 0.12.2/frameworks/compass/stylesheets/compass/utilities/general/_clearfix.scss */
.subNavigation li:after {
content: "";
display: table;
clear: both;
}
/* line 138, ../sass/style.scss */
.subNavigation li:first-child {
width: 155px;
height: 24px;
margin-top: 0;
margin-bottom: 14px;
color: #f7931e;
border-bottom: 1px solid #dddddd;
padding-right: 0;
font-size: 16px;
line-height: 24px;
}
/* line 151, ../sass/style.scss */
.subNavigation a {
float: right;
font-size: 13px;
height: 24px;
line-height: 24px;
padding-right: 2px;
color: #222;
-webkit-transition: all, 0.2s, ease-in;
-moz-transition: all, 0.2s, ease-in;
-o-transition: all, 0.2s, ease-in;
transition: all, 0.2s, ease-in;
}
/* line 160, ../sass/style.scss */
.subNavigation a.eng {
font-family: tahoma;
}
/* line 164, ../sass/style.scss */
.subNavigation a:hover {
padding-right: 10px;
border-right: 4px solid #f7941d;
color: #19ae61;
}
</code></pre>
<p><a href="http://jsfiddle.net/X5UBF/" rel="nofollow">The Fiddle</a></p> | 17,097,386 | 2 | 0 | null | 2013-06-13 21:25:02.877 UTC | 1 | 2013-06-13 21:42:01.877 UTC | null | null | null | null | 1,882,864 | null | 1 | 4 | css|css-transitions | 43,191 | <p>One simple error:</p>
<pre><code>-webkit-transition: all, 0.2s, ease-in;
-moz-transition: all, 0.2s, ease-in;
-o-transition: all, 0.2s, ease-in;
transition: all, 0.2s, ease-in;
</code></pre>
<p>Change to:</p>
<pre><code>-webkit-transition: all 0.2s ease-in;
-moz-transition: all 0.2s ease-in;
-o-transition: all 0.2s ease-in;
transition: all 0.2s ease-in;
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/X5UBF/1/" rel="noreferrer">http://jsfiddle.net/X5UBF/1/</a></p>
<p>Transition values are not comma separated. They are a single declaration. If you want to declare multiple transitions, THEN you comma separate them.</p>
<p>See <a href="http://www.w3.org/TR/css3-transitions/#transition-shorthand-property" rel="noreferrer">W3C Docs</a> or/and <a href="http://www.css3.info/preview/css3-transitions/" rel="noreferrer">CSS3.info</a></p>
<pre><code>Value: <single-transition> [ ‘,’ <single-transition> ]*
</code></pre>
<p>Where <code><single-transition></code> is:</p>
<pre><code><single-transition> = <transition-property> <transition-duration> <transition-timing-function> <transition-delay>
</code></pre>
<p>So, a comma separated example would be:</p>
<pre><code>transition: opacity 0.5s ease-in, width 1.5s ease-out;
/* 0.5s for an opacity transform while 1.5s for a width transform */
</code></pre> |
29,680,158 | How to send multipart/form-data with Retrofit? | <p>I want to send an <em>Article</em> from and <em>Android</em> client to a REST server. Here is the <em>Python</em> model from the server:</p>
<pre><code>class Article(models.Model):
author = models.CharField(max_length=256, blank=False)
photo = models.ImageField()
</code></pre>
<p>The following interface describes the former implementation:</p>
<pre><code>@POST("/api/v1/articles/")
public Observable<CreateArticleResponse> createArticle(
@Body Article article
);
</code></pre>
<p>Now I want to send an image with the <em>Article</em> data. The <code>photo</code> is not part of the <em>Article</em> model on the <em>Android</em> client.</p>
<pre><code>@Multipart
@POST("/api/v1/articles/")
public Observable<CreateArticleResponse> createArticle(
@Part("article") Article article,
@Part("photo") TypedFile photo
);
</code></pre>
<p>The API is prepared and successfully tested with <em>cURL</em>.</p>
<pre class="lang-none prettyprint-override"><code>$ curl -vX POST http://localhost:8000/api/v1/articles/ \
-H "Content-Type: multipart/form-data" \
-H "Accept:application/json" \
-F "author=cURL" \
-F "photo=@/home/user/Desktop/article-photo.png"
</code></pre>
<p>When I send data through <code>createArticle()</code> from the <em>Android</em> client I receive an <code>HTTP 400</code> status stating that the <strong>fields are required/missing</strong>.</p>
<pre><code>D <--- HTTP 400 http://192.168.1.1/articles/ (2670ms)
D Date: Mon, 20 Apr 2015 12:00:00 GMT
D Server: WSGIServer/0.1 Python/2.7.8
D Vary: Accept, Cookie
D X-Frame-Options: SAMEORIGIN
D Content-Type: application/json
D Allow: GET, POST, HEAD, OPTIONS
D OkHttp-Selected-Protocol: http/1.0
D OkHttp-Sent-Millis: 1429545450469
D OkHttp-Received-Millis: 1429545453120
D {"author":["This field is required."],"photo":["No file was submitted."]}
D <--- END HTTP (166-byte body)
E 400 BAD REQUEST
</code></pre>
<p>This is what is received as <code>request.data</code> on the server side:</p>
<pre><code>ipdb> print request.data
<QueryDict: {u'article': [u'{"author":"me"}'], \
u'photo': [<TemporaryUploadedFile: IMG_1759215522.jpg \
(multipart/form-data)>]}>
</code></pre>
<p>How can convert the <em>Article</em> object in a multipart conform data type? I read that <a href="http://square.github.io/retrofit/" rel="noreferrer"><em>Retrofit</em></a> might allow to use <a href="https://github.com/square/retrofit/tree/master/retrofit-converters" rel="noreferrer">Converters</a> for this. It should be something that implements a <code>retrofit.mime.TypedOutput</code> as far as I understood for the <a href="http://square.github.io/retrofit/" rel="noreferrer">documentation</a>.</p>
<blockquote>
<p>Multipart parts use the <code>RestAdapter</code>'s converter or they can implement <code>TypedOutput</code> to handle their own serialization.</p>
</blockquote>
<h1>Related</h1>
<ul>
<li><a href="http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2" rel="noreferrer">HTML 4.01 Specification - Form submission - multipart/form-data</a></li>
<li><a href="http://square.github.io/retrofit/javadoc/retrofit/http/Part.html" rel="noreferrer">Retrofit Annotation Type Part documentation</a></li>
<li><a href="https://stackoverflow.com/questions/24165605/upload-multipart-image-data-in-json-with-retrofit-android">Upload multipart image data in JSON with Retrofit?</a></li>
<li><a href="https://stackoverflow.com/questions/9081079/rest-http-post-multipart-with-json">REST - HTTP Post Multipart with JSON</a></li>
<li><a href="https://stackoverflow.com/questions/28348269/retrofit-multipart-upload-image-failed">Retrofit Multipart Upload Image failed</a></li>
<li><a href="https://github.com/square/retrofit/issues/178" rel="noreferrer">Retrofit issue #178: Create manual for sending files with retrofit</a></li>
<li><a href="https://github.com/square/retrofit/issues/531" rel="noreferrer">Retrofit issue #531: Problem uploading file via POST/Multipart</a></li>
<li><a href="https://github.com/square/retrofit/issues/658" rel="noreferrer">Retrofit issue #658: Not able to send string parameters with image when using Multipart</a></li>
<li><a href="https://github.com/square/retrofit/issues/662" rel="noreferrer">Retrofit issue #662: Retrofit Form Encoded and Multipart in single request</a></li>
</ul> | 29,775,189 | 2 | 6 | null | 2015-04-16 16:01:30.643 UTC | 11 | 2016-04-12 09:09:45.577 UTC | 2017-05-23 12:09:58.84 UTC | null | -1 | null | 356,895 | null | 1 | 34 | android|image-uploading|multipartform-data|retrofit | 44,162 | <p>According to your curl request you are trying to create smth like this:</p>
<pre><code>POST http://localhost:8000/api/v1/articles/ HTTP/1.1
User-Agent: curl/7.30.0
Host: localhost
Connection: Keep-Alive
Accept: application/json
Content-Length: 183431
Expect: 100-continue
Content-Type: multipart/form-data; boundary=----------------------------23473c7acabb
------------------------------23473c7acabb
Content-Disposition: form-data; name="author"
cURL
------------------------------23473c7acabb
Content-Disposition: form-data; name="photo"; filename="article-photo.png"
Content-Type: application/octet-stream
‰PNG
<!RAW BYTES HERE!>
M\UUÕ+4qUUU¯°WUUU¿×ß¿þ Naa…k¿ IEND®B`‚
------------------------------23473c7acabb--
</code></pre>
<p>With retrofit adapter this request can be created in a next way:</p>
<pre><code>@Multipart
@POST("/api/v1/articles/")
Observable<Response> uploadFile(@Part("author") TypedString authorString,
@Part("photo") TypedFile photoFile);
</code></pre>
<p>Usage:</p>
<pre><code>TypedString author = new TypedString("cURL");
File photoFile = new File("/home/user/Desktop/article-photo.png");
TypedFile photoTypedFile = new TypedFile("image/*", photoFile);
retrofitAdapter.uploadFile(author, photoTypedFile)
.subscribe(<...>);
</code></pre>
<p>Which creates similar output:</p>
<pre><code>POST http://localhost:8000/api/v1/articles/ HTTP/1.1
Content-Type: multipart/form-data; boundary=32230279-83af-4480-abfc-88a880b21b19
Content-Length: 709
Host: localhost
Connection: Keep-Alive
Accept-Encoding: gzip
User-Agent: okhttp/2.3.0
--32230279-83af-4480-abfc-88a880b21b19
Content-Disposition: form-data; name="author"
Content-Type: text/plain; charset=UTF-8
Content-Length: 4
Content-Transfer-Encoding: binary
cUrl
--32230279-83af-4480-abfc-88a880b21b19
Content-Disposition: form-data; name="photo"; filename="article-photo.png"
Content-Type: image/*
Content-Length: 254
Content-Transfer-Encoding: binary
<!RAW BYTES HERE!>
--32230279-83af-4480-abfc-88a880b21b19--
</code></pre>
<p>The key difference here is that you used POJO <code>Article article</code> as multipart param, which by default is converted by <code>Converter</code> into json. And your server expects plain string instead. With curl you are sending <code>cURL</code>, not <code>{"author":"cURL"}</code>.</p> |
12,363,506 | What is the difference between WCF and WPF? | <p>I am a naive developer and I am building up my concepts, I was asked to create a sample application in wcf, and so I am asking a bit subjective question here.
I want to know the diffrence and functionality of the above two, in which terms we prefer one over other?</p> | 12,363,560 | 7 | 1 | null | 2012-09-11 05:52:47.327 UTC | 12 | 2017-03-23 10:43:03.72 UTC | null | null | null | null | 1,645,095 | null | 1 | 20 | wpf|wcf | 121,697 | <p>WCF = Windows COMMUNICATION Foundation</p>
<p>WPF = Windows PRESENTATION Foundation. </p>
<p>WCF deals with communication (in simple terms - sending and receiving data as well as formatting and serialization involved), WPF deals with presentation (UI)</p> |
12,556,268 | fastest way to create JSON to reflect a tree structure in Python / Django using mptt | <p>What's the fastest way in Python (Django) to create a JSON based upon a Django queryset. Note that parsing it in the template as proposed <a href="https://stackoverflow.com/questions/5072301/how-can-create-a-json-tree-from-django-mptt">here</a> is not an option. </p>
<p>The background is that I created a method which loops over all nodes in a tree, but is already terribly slow when converting about 300 nodes. The first (and probably the worst) idea that came up to my mind is to create the json somehow "manually". See the code below.</p>
<pre><code>#! Solution 1 !!#
def quoteStr(input):
return "\"" + smart_str(smart_unicode(input)) + "\""
def createJSONTreeDump(user, node, root=False, lastChild=False):
q = "\""
#open tag for object
json = str("\n" + indent + "{" +
quoteStr("name") + ": " + quoteStr(node.name) + ",\n" +
quoteStr("id") + ": " + quoteStr(node.pk) + ",\n" +
)
childrenTag = "children"
children = node.get_children()
if children.count() > 0 :
#create children array opening tag
json += str(indent + quoteStr(childrenTag) + ": [")
#for child in children:
for idx, child in enumerate(children):
if (idx + 1) == children.count():
//recursive call
json += createJSONTreeDump(user, child, False, True, layout)
else:
//recursive call
json += createJSONTreeDump(user, child, False, False, layout)
#add children closing tag
json += "]\n"
#closing tag for object
if lastChild == False:
#more children following, add ","
json += indent + "},\n"
else:
#last child, do not add ","
json += indent + "}\n"
return json
</code></pre>
<p>The tree structure to be rendered is a tree build up with <a href="https://github.com/django-mptt/django-mptt/" rel="nofollow noreferrer">mptt</a>, where the call .get_children() returns all children of a node.</p>
<p>The model looks as simply as this, mptt taking care of everything else.</p>
<pre><code>class Node(MPTTModel, ExtraManager):
"""
Representation of a single node
"""
name = models.CharField(max_length=200)
parent = TreeForeignKey('self', null=True, blank=True, related_name='%(app_label)s_%(class)s_children')
</code></pre>
<p>The expected JSON <a href="http://pastebin.com/YrfxJ8kr" rel="nofollow noreferrer">result</a> created like this in the template <code>var root = {{ jsonTree|safe }}</code></p>
<p>Edit:
Based upon <a href="https://stackoverflow.com/questions/5597136/serializing-a-tree-in-django">this</a> answer I created the following code (definitely the better code) but feels only slightly faster.</p>
<p>Solution 2:</p>
<pre><code>def serializable_object(node):
"Recurse into tree to build a serializable object"
obj = {'name': node.name, 'id': node.pk, 'children': []}
for child in node.get_children():
obj['children'].append(serializable_object(child))
return obj
import json
jsonTree = json.dumps(serializable_object(nodeInstance))
</code></pre>
<p>Solution 3: </p>
<pre><code>def serializable_object_List_Comprehension(node):
"Recurse into tree to build a serializable object"
obj = {
'name': node.name,
'id': node.pk,
'children': [serializable_object(ch) for ch in node.get_children()]
}
return obj
</code></pre>
<p>Solution 4:</p>
<pre><code>def recursive_node_to_dict(node):
result = {
'name': node.name, 'id': node.pk
}
children = [recursive_node_to_dict(c) for c in node.get_children()],
if children is not None:
result['children'] = children
return result
from mptt.templatetags.mptt_tags import cache_tree_children
root_nodes = cache_tree_children(root.get_descendants())
dicts = []
for n in root_nodes:
dicts.append(recursive_node_to_dict(root_nodes[0]))
jsonTree = json.dumps(dicts, indent=4)
</code></pre>
<p>Solution 5 (make use of select_related to pre_fetch, whereas not sure if correctly used)</p>
<pre><code>def serializable_object_select_related(node):
"Recurse into tree to build a serializable object, make use of select_related"
obj = {'name': node.get_wbs_code(), 'wbsCode': node.get_wbs_code(), 'id': node.pk, 'level': node.level, 'position': node.position, 'children': []}
for child in node.get_children().select_related():
obj['children'].append(serializable_object(child))
return obj
</code></pre>
<p>Solution 6 (improved solution 4, using caching of child nodes):</p>
<pre><code>def recursive_node_to_dict(node):
return {
'name': node.name, 'id': node.pk,
# Notice the use of node._cached_children instead of node.get_children()
'children' : [recursive_node_to_dict(c) for c in node._cached_children]
}
</code></pre>
<p>Called via:</p>
<pre><code>from mptt.templatetags.mptt_tags import cache_tree_children
subTrees = cache_tree_children(root.get_descendants(include_self=True))
subTreeDicts = []
for subTree in subTrees:
subTree = recursive_node_to_dict(subTree)
subTreeDicts.append(subTree)
jsonTree = json.dumps(subTreeDicts, indent=4)
#optional clean up, remove the [ ] at the beginning and the end, its needed for D3.js
jsonTree = jsonTree[1:len(jsonTree)]
jsonTree = jsonTree[:len(jsonTree)-1]
</code></pre>
<p>Below you can see the profiling results, created using cProfile as suggested by MuMind, setting up a Django view to start the stand-alone method profileJSON(), which in turn calls the different solutions to create the JSON output.</p>
<pre><code>def startProfileJSON(request):
print "startProfileJSON"
import cProfile
cProfile.runctx('profileJSON()', globals=globals(), locals=locals())
print "endProfileJSON"
</code></pre>
<p>Results:</p>
<p><strong>Solution 1:</strong> 3350347 function calls (3130372 primitive calls) in 4.969 seconds (<a href="http://pastebin.com/yKBre5ZC" rel="nofollow noreferrer">details</a>)</p>
<p><strong>Solution 2:</strong> 2533705 function calls (2354516 primitive calls) in 3.630 seconds (<a href="http://pastebin.com/zbcePF74" rel="nofollow noreferrer">details</a>)</p>
<p><strong>Solution 3:</strong> 2533621 function calls (2354441 primitive calls) in 3.684 seconds (<a href="http://pastebin.com/JejGke2z" rel="nofollow noreferrer">details</a>)</p>
<p><strong>Solution 4:</strong> 2812725 function calls (2466028 primitive calls) in 3.840 seconds (<a href="http://pastebin.com/ANu24hSf" rel="nofollow noreferrer">details</a>)</p>
<p><strong>Solution 5:</strong> 2536504 function calls (2357256 primitive calls) in 3.779 seconds (<a href="http://pastebin.com/6gr9k1F7" rel="nofollow noreferrer">details</a>)</p>
<p><strong>Solution 6 (Improved solution 4):</strong> 2593122 function calls (2299165 primitive calls) in 3.663 seconds (<a href="http://pastebin.com/NTu8z0Jm" rel="nofollow noreferrer">details</a>)</p>
<p><strong>Discussion:</strong></p>
<p>Solution 1: own encoding implementation. bad idea</p>
<p>Solution 2 + 3: currently <strong>the fastest</strong>, but still painfully slow</p>
<p>Solution 4: looks promising with caching childs, but does perform similar and currently produces not valid json as childrens are put into double []:</p>
<pre><code>"children": [[]] instead of "children": []
</code></pre>
<p>Solution 5: use of select_related does not make a difference, whereas probably used in the wrong way, as a node always have a ForeignKey to its parent, and we are parsing from root to child.</p>
<p>Update: Solution 6: It looks like the cleanest solution to me, using caching of child nodes. But does only perform similar to solution 2 + 3. Which for me is strange. </p>
<p>Anybody more ideas for performance improvements?</p> | 12,556,693 | 4 | 6 | 2012-09-24 13:15:12.057 UTC | 2012-09-23 21:10:07.353 UTC | 17 | 2020-05-08 00:14:43.743 UTC | 2020-05-08 00:14:43.743 UTC | null | 14,508 | null | 237,690 | null | 1 | 23 | python|django|json|tree|profiling | 14,399 | <p>I suspect by far the biggest slowdown is that this will do 1 database query per node. The json rendering is trivial in comparison to the hundreds of round-trips to your database.</p>
<p>You should cache the children on each node so that those queries can be done all at once.
django-mptt has a <a href="https://github.com/django-mptt/django-mptt/blob/master/mptt/templatetags/mptt_tags.py#L225" rel="noreferrer">cache_tree_children()</a> function you can do this with.</p>
<pre><code>import json
from mptt.templatetags.mptt_tags import cache_tree_children
def recursive_node_to_dict(node):
result = {
'id': node.pk,
'name': node.name,
}
children = [recursive_node_to_dict(c) for c in node.get_children()]
if children:
result['children'] = children
return result
root_nodes = cache_tree_children(Node.objects.all())
dicts = []
for n in root_nodes:
dicts.append(recursive_node_to_dict(n))
print json.dumps(dicts, indent=4)
</code></pre>
<p>Custom json encoding, while it might provide a slight speedup in some scenarios, is something I'd highly discourage, as it will be a lot of code, and it's something that's easy to get <a href="http://trac.osgeo.org/postgis/ticket/1996" rel="noreferrer">very wrong</a>.</p> |
12,073,155 | Recommend a good resource for approaches to concurrent programming? | <p>I've read various bits and pieces on concurrency, but was hoping to find a single resource that details and compares the various approaches. Ideally taking in threads, co-routines, message passing, actors, futures... whatever else that might be new that I don't know about yet!</p>
<p>Would prefer a lay-coders guide than something overtly theoretical / mathematical.</p>
<p>Thank you.</p> | 12,073,369 | 4 | 0 | null | 2012-08-22 12:28:10.583 UTC | 23 | 2019-03-13 20:54:18.853 UTC | null | null | null | null | 200,877 | null | 1 | 29 | concurrency | 14,597 | <p>I recommend <a href="https://rads.stackoverflow.com/amzn/click/com/0123742609" rel="noreferrer" rel="nofollow noreferrer">An Introduction to Parallel Programming</a> by Pacheco. It's clearly written, and a good intro to parallel programming.</p>
<p>If you don't care about something being tied to a language, then <a href="https://rads.stackoverflow.com/amzn/click/com/0321349601" rel="noreferrer" rel="nofollow noreferrer" title="Java Concurrency in Practice">Java Concurrency in Practice</a> is a great resource.</p>
<p>Oracle's <a href="http://docs.oracle.com/javase/tutorial/essential/concurrency/" rel="noreferrer">online tutorial</a> is free, but probably a bit more succinct than what you're looking for.</p>
<hr>
<p>That being said, the best teacher for concurrency is probably experience. I'd try to get some practice, myself. Start out by making a simulation of the <a href="http://en.wikipedia.org/wiki/Dining_philosophers_problem" rel="noreferrer">Dining Philosophers problem</a>. It's a classic.</p> |
12,539,697 | iPhone 5 CSS media query | <p>The iPhone 5 has a longer screen and it's not catching my website's mobile view. What are the new responsive design queries for the iPhone 5 and can I combine with existing iPhone queries?</p>
<p>My current media query is this:</p>
<pre><code>@media only screen and (max-device-width: 480px) {}
</code></pre> | 12,848,217 | 11 | 2 | null | 2012-09-22 00:27:20.103 UTC | 142 | 2017-06-29 00:31:12.537 UTC | 2012-09-22 04:49:59.35 UTC | null | 106,224 | null | 794,996 | null | 1 | 132 | iphone|css|responsive-design|media-queries|iphone-5 | 265,098 | <p>Another useful media feature is <code>device-aspect-ratio</code>.</p>
<p>Note that the <strong>iPhone 5 does not have a 16:9 aspect ratio</strong>. It is in fact 40:71.</p>
<p>iPhone < 5:<br />
<code>@media screen and (device-aspect-ratio: 2/3) {}</code></p>
<p>iPhone 5:<br />
<code>@media screen and (device-aspect-ratio: 40/71) {}</code></p>
<p>iPhone 6:<br />
<code>@media screen and (device-aspect-ratio: 375/667) {}</code></p>
<p>iPhone 6 Plus:<br />
<code>@media screen and (device-aspect-ratio: 16/9) {}</code></p>
<p>iPad:<br />
<code>@media screen and (device-aspect-ratio: 3/4) {}</code></p>
<p>Reference:<br />
<a href="http://www.w3.org/TR/2002/CR-css3-mediaqueries-20020708/">Media Queries @ W3C</a>
<br />
<a href="https://www.apple.com/iphone/compare/">iPhone Model Comparison</a>
<br />
<a href="http://andrew.hedges.name/experiments/aspect_ratio/">Aspect Ratio Calculator</a></p> |
19,233,415 | How to make type="number" to positive numbers only | <p>currently I have the following code</p>
<pre><code><input type="number" />
</code></pre>
<p>it comes out to something like this</p>
<p><img src="https://i.stack.imgur.com/dxgg1.png" alt="enter image description here"></p>
<p>The little selector things on the right allow the number to go into negative. How do I prevent that?</p>
<p>I am having doubts about using <code>type="number"</code>, it is causing more problems than it is solving, I am going to sanity check it anyways, so should I just go back to using <code>type="text"</code>?</p> | 19,233,458 | 22 | 3 | null | 2013-10-07 19:51:27.387 UTC | 54 | 2022-07-04 09:29:41.85 UTC | null | null | null | null | 1,509,580 | null | 1 | 415 | html | 508,628 | <p>Add <a href="http://www.w3.org/TR/html5/forms.html#attr-input-min" rel="noreferrer">a <code>min</code> attribute</a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" min="0"></code></pre>
</div>
</div>
</p> |
19,288,707 | difference between quit and exit in python | <p>Would anybody tell me what is the difference between builtin function exit() and quit().</p>
<p>Please correct me if I am wrong at any point. I have tried to check it but I am not getting anything.</p>
<p>1) When I use help() and type() function for each one, it says that both are object of class Quitter, which is defined in the module <code>site</code>.</p>
<p>2) When I use id() to check the addresses of each one, it returns different addresses i.e. these are two different objects of same class <code>site.Quitter</code>. </p>
<pre><code>>>> id(exit)
13448048
>>> id(quit)
13447984
</code></pre>
<p>3) And since the addresses remains constant over the subsequent calls, i.e. it is not using return wrapper each time. </p>
<pre><code>>>> id(exit)
13448048
>>> id(quit)
13447984
</code></pre>
<p>Would anybody provide me details about the differences between these two and if both are doing the same thing, why we need two different functions.</p> | 19,504,740 | 1 | 5 | null | 2013-10-10 06:35:58.903 UTC | 5 | 2013-10-21 21:25:49.453 UTC | null | null | null | null | 1,852,749 | null | 1 | 30 | python-2.7 | 12,953 | <p><strong>The short answer is</strong>: both <strong>exit()</strong> and <strong>quit()</strong> are instances of the same <strong>Quitter</strong> class, the difference is in naming only, that must be added to increase user-friendliness of the interpreter. </p>
<p><strong>For more details</strong> let's check out the source: <a href="http://hg.python.org/cpython">http://hg.python.org/cpython</a></p>
<p>In <a href="http://hg.python.org/cpython/file/737b79e524aa/Lib/site.py">Lib/site.py (python-2.7)</a> we see the following:</p>
<pre><code>def setquit():
"""Define new builtins 'quit' and 'exit'.
These are objects which make the interpreter exit when called.
The repr of each object contains a hint at how it works.
"""
if os.sep == ':':
eof = 'Cmd-Q'
elif os.sep == '\\':
eof = 'Ctrl-Z plus Return'
else:
eof = 'Ctrl-D (i.e. EOF)'
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
</code></pre>
<p>The same logic we see in python-3.x.</p> |
18,906,988 | What is the iBeacon Bluetooth Profile | <p>I'd like to create my own iBeacon with some Bluetooth Low Energy dev kits. Apple has yet to release a specification for iBeacons, however, a few hardware developers have reverse Engineered the iBeacon from the AirLocate Sample code and started selling iBeacon dev kits.</p>
<p><strong>So what is the iBeacon Bluetooth Profile?</strong></p>
<p>Bluetooth Low Energy uses GATT for LE profile service discovery. So I think we need to know the Attribute Handle, Attribute Type, Attribute Value, and maybe the Attribute Permissions of the iBeacon attribute. So for an iBeacon with a UUID of E2C56DB5-DFFB-48D2-B060-D0F5A71096E0, a major value of 1 and a minor value of 1 what would the Bluetooth GATT profile service be?</p>
<p>Here are some assumptions I've made from the discussion on Apple's forums and through the docs.</p>
<ol>
<li><p>You only need to see the profile service (GATT) of a Bluetooth peripheral to know it is an iBeacon.</p>
</li>
<li><p>The Major and Minor keys are encoded somewhere in this profile service</p>
</li>
</ol>
<p>Heres some companies with iBeacon Dev Kits that seem to have this figure out already:</p>
<ul>
<li><a href="http://redbearlab.com/ibeacon/" rel="nofollow noreferrer">http://redbearlab.com/ibeacon/</a></li>
<li><a href="http://kontakt.io/" rel="nofollow noreferrer">http://kontakt.io/</a></li>
</ul>
<p>Hopefully, in time we will have a profile posted on Bluetooth.org like these: <a href="https://www.bluetooth.org/en-us/specification/adopted-specifications" rel="nofollow noreferrer">https://www.bluetooth.org/en-us/specification/adopted-specifications</a></p> | 19,040,616 | 6 | 7 | null | 2013-09-20 00:13:29.607 UTC | 180 | 2022-03-31 02:49:49.257 UTC | 2020-09-20 11:32:27.92 UTC | null | 4,995,828 | null | 283,460 | null | 1 | 153 | ios|bluetooth|bluetooth-lowenergy|reverse-engineering|ibeacon | 111,860 | <p>For an iBeacon with ProximityUUID <code>E2C56DB5-DFFB-48D2-B060-D0F5A71096E0</code>, major <code>0</code>, minor <code>0</code>, and calibrated Tx Power of <code>-59</code> RSSI, the transmitted BLE advertisement packet looks like this:</p>
<p><code>d6 be 89 8e 40 24 05 a2 17 6e 3d 71 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 52 ab 8d 38 a5</code></p>
<p>This packet can be broken down as follows:</p>
<pre><code>d6 be 89 8e # Access address for advertising data (this is always the same fixed value)
40 # Advertising Channel PDU Header byte 0. Contains: (type = 0), (tx add = 1), (rx add = 0)
24 # Advertising Channel PDU Header byte 1. Contains: (length = total bytes of the advertising payload + 6 bytes for the BLE mac address.)
05 a2 17 6e 3d 71 # Bluetooth Mac address (note this is a spoofed address)
02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 # Bluetooth advertisement
52 ab 8d 38 a5 # checksum
</code></pre>
<p>The key part of that packet is the Bluetooth Advertisement, which can be broken down like this:</p>
<pre><code>02 # Number of bytes that follow in first AD structure
01 # Flags AD type
1A # Flags value 0x1A = 000011010
bit 0 (OFF) LE Limited Discoverable Mode
bit 1 (ON) LE General Discoverable Mode
bit 2 (OFF) BR/EDR Not Supported
bit 3 (ON) Simultaneous LE and BR/EDR to Same Device Capable (controller)
bit 4 (ON) Simultaneous LE and BR/EDR to Same Device Capable (Host)
1A # Number of bytes that follow in second (and last) AD structure
FF # Manufacturer specific data AD type
4C 00 # Company identifier code (0x004C == Apple)
02 # Byte 0 of iBeacon advertisement indicator
15 # Byte 1 of iBeacon advertisement indicator
e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 # iBeacon proximity uuid
00 00 # major
00 00 # minor
c5 # The 2's complement of the calibrated Tx Power
</code></pre>
<p>Any Bluetooth LE device that can be configured to send a specific advertisement can generate the above packet. I have configured a Linux computer using Bluez to send this advertisement, and iOS7 devices running Apple's AirLocate test code pick it up as an iBeacon with the fields specified above. See: <a href="https://stackoverflow.com/questions/16151360/use-bluez-stack-as-a-peripheral-advertiser/19039963#19039963">Use BlueZ Stack As A Peripheral (Advertiser)</a></p>
<p>This <a href="http://www.davidgyoungtech.com/2013/10/01/reverse-engineering-the-ibeacon-profile" rel="nofollow noreferrer">blog</a> has full details about the reverse engineering process.</p> |
23,991,943 | Bootstrap 3 profile image in navbar | <p>How do I get the profile image (see picture) to be say 25/30px without distorting the navbar?</p>
<p>This is what I have now:</p>
<pre><code><li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<img src="http://placehold.it/18x18" class="profile-image img-circle"> Username <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="#"><i class="fa fa-cog"></i> Account</a></li>
<li class="divider"></li>
<li><a href="#"><i class="fa fa-sign-out"></i> Sign-out</a></li>
</ul>
</li>
</code></pre>
<p>this is the result:</p>
<p><img src="https://i.stack.imgur.com/WDtPx.png" alt="small image but no distortion"></p>
<p>But if I change the size of the image to 30x30 this is what happens, how do I prevent the distortion of the navbar:</p>
<p><img src="https://i.stack.imgur.com/d7zwU.png" alt="large image but a distorted navbar"></p>
<p>I tried clearing the margin and paddings on the image but that had no effect.</p>
<p><strong>Update:</strong> Here is a <a href="http://jsfiddle.net/bJcrk/">JSFiddle</a> of the current code.</p> | 23,992,561 | 3 | 6 | null | 2014-06-02 10:02:42.567 UTC | 11 | 2014-06-02 10:49:44.337 UTC | 2014-06-02 10:25:41.95 UTC | null | 1,485,141 | null | 1,485,141 | null | 1 | 21 | html|css|image|twitter-bootstrap | 63,237 | <p>You got it mostly right following what Kooki3 said, there's just more specificity in the Bootstrap stylesheet, so just change your <code>.profile-image</code> to <code>.navbar-nav>li>a.profile-image</code> </p>
<p>Editing your fiddle like this, the nav looks perfect to me:</p>
<pre><code>.navbar-nav>li>a.profile-image {
padding-top: 10px;
padding-bottom: 10px;
}
</code></pre> |
36,780,948 | Seaborn / Matplotlib: How to repress scientific notation in factorplot y-axis | <p>Simple example below for this issue which I just can't solve. </p>
<p>N.B. Some other Seaborn plotting methods seems to have arguments to repress the exponential form but seemingly not <code>factorplots</code>. I tried some Matplotlib solutions including those suggested in this <a href="https://stackoverflow.com/questions/14711655/how-to-prevent-numbers-being-changed-to-exponential-form-in-python-matplotlib-fi">similar question</a> but none work. Also this is not a dupe of <a href="https://stackoverflow.com/questions/33804658/prevent-scientific-notation-in-seaborn-boxplot">this question</a>. I use factorplots very frequently and ideally want to find a proper solution as opposed to a workaround. </p>
<pre><code>data = {'reports': [4, 24, 31, 2, 3],'coverage': [35050800, 54899767, 57890789, 62890798, 70897871]}
df = pd.DataFrame(data)
df
</code></pre>
<p>Produces this dataframe:</p>
<pre><code> coverage reports
0 35050800 4
1 54899767 24
2 57890789 31
3 62890798 2
4 70897871 3
</code></pre>
<p>And then this Seaborn code:</p>
<pre><code>sns.factorplot(y="coverage", x="reports", kind='bar', data=df, label="Total")
</code></pre>
<p>Produces this plot:</p>
<p><a href="https://i.stack.imgur.com/SaCHg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SaCHg.png" alt="enter image description here"></a></p>
<p>Is there a way to get the y axis to display an appropriate numeric scale based on the <code>coverage</code> values?</p> | 36,781,734 | 2 | 7 | null | 2016-04-21 21:38:18.73 UTC | 6 | 2017-02-02 23:33:38.79 UTC | 2017-05-23 11:53:12.58 UTC | null | -1 | null | 4,061,070 | null | 1 | 31 | python|matplotlib|seaborn | 28,963 | <p>It looks like the following line solves the issue: </p>
<pre><code>plt.ticklabel_format(style='plain', axis='y')
</code></pre>
<p>Here is the <a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.ticklabel_format" rel="noreferrer">documentation link</a>.</p> |
20,813,486 | Exploring Docker container's file system | <p>I've noticed with docker that I need to understand what's happening inside a container or what files exist in there. One example is downloading images from the docker index - you don't have a clue what the image contains so it's impossible to start the application.</p>
<p>What would be ideal is to be able to ssh into them or equivalent. Is there a tool to do this, or is my conceptualisation of docker wrong in thinking I should be able to do this.</p> | 20,816,397 | 32 | 7 | null | 2013-12-28 10:29:02.46 UTC | 356 | 2022-09-06 00:10:42.893 UTC | 2017-06-30 23:03:53.923 UTC | null | 42,223 | null | 2,668,128 | null | 1 | 957 | linux|docker|filesystems | 976,228 | <p>Here are a couple different methods...</p>
<h3>A) Use docker exec <em>(easiest)</em></h3>
<p>Docker version 1.3 or newer supports the command <code>exec</code> that behave similar to <code>nsenter</code>. This command can run new process in already running container (container must have PID 1 process running already). You can run <code>/bin/bash</code> to explore container state:</p>
<pre><code>docker exec -t -i mycontainer /bin/bash
</code></pre>
<p>see <a href="https://docs.docker.com/engine/reference/commandline/exec/" rel="noreferrer">Docker command line documentation</a></p>
<h3>B) Use Snapshotting</h3>
<p>You can evaluate container filesystem this way:</p>
<pre><code># find ID of your running container:
docker ps
# create image (snapshot) from container filesystem
docker commit 12345678904b5 mysnapshot
# explore this filesystem using bash (for example)
docker run -t -i mysnapshot /bin/bash
</code></pre>
<p>This way, you can evaluate filesystem of the running container in the precise time moment. Container is still running, no future changes are included.</p>
<p>You can later delete snapshot using (filesystem of the running container is not affected!):</p>
<pre><code>docker rmi mysnapshot
</code></pre>
<h3>C) Use ssh</h3>
<p>If you need continuous access, you can install sshd to your container and run the sshd daemon:</p>
<pre><code> docker run -d -p 22 mysnapshot /usr/sbin/sshd -D
# you need to find out which port to connect:
docker ps
</code></pre>
<p>This way, you can run your app using ssh (connect and execute what you want).</p>
<h3>D) Use nsenter</h3>
<p>Use <code>nsenter</code>, see <a href="https://web.archive.org/web/20160305150559/http://blog.docker.com/2014/06/why-you-dont-need-to-run-sshd-in-docker/" rel="noreferrer">Why you don't need to run SSHd in your Docker containers</a></p>
<blockquote>
<p><em>The short version is: with nsenter, you can get a shell into an
existing container, even if that container doesn’t run SSH or any kind
of special-purpose daemon</em></p>
</blockquote> |
11,018,747 | Create New EC2 Instance with Custom ISO | <p>I'm using Switchvox, an Asterisk PBX and I'd like to host it on EC2. </p>
<p>Digium Switchvox provides an ISO which contains everything needed to host the pbx server: OS, software, etc. It's basically an image of the server. </p>
<p><strong>How do I instantiate a new EC2 instance using the custom ISO they're providing?</strong></p> | 11,179,324 | 4 | 1 | null | 2012-06-13 15:53:52.173 UTC | 11 | 2021-01-15 10:48:42.627 UTC | null | null | null | null | 361,833 | null | 1 | 27 | amazon-ec2|asterisk|iso|ec2-ami|pbx | 76,964 | <p>From this ISO, you can create either a <a href="http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1002" rel="noreferrer">VMware</a> or <a href="http://www.virtualbox.org/manual/ch01.html#idp12780688" rel="noreferrer">VirtualBox</a> image. Form there, you may convert this image into an <a href="https://forums.aws.amazon.com/message.jspa?messageID=192226" rel="noreferrer">EC2 AMI</a> image and go from there.</p>
<p>Just make sure you are using the same arch (32 v. 64) and proper kernel.</p>
<p>That being said, you might get into more operations then simply fire up an existing vanilla AMI available from the community. There might be one that closely match your OS requirements. </p> |
11,144,370 | Using mousedown event on mobile without jQuery mobile? | <p>I've built a webapp, and for a little bit of polish, I wanted to add mousedown and mouseup handlers to swap out images (in this case, to make a button look like it's being pressed).</p>
<p>my code is something like this:</p>
<pre><code>window.onload = function() {
//preload mouse down image here via Image()
$("#button_img").mousedown(function(){$("#button_img").attr("src","button_on.png");});
$("#button_img").mouseup(function(){$("#button_img").attr("src","button_off.png")});
}
</code></pre>
<p>This works swimmingly on the desktop, but on mobile (testing in iOS Safari), the mousedown and mouseup events happen at the same time, so effectively nothing happens.</p>
<p>I tried to use the vmousedown and vmouseup events in jQueryMobile, however this code:</p>
<pre><code>//include jquerymobile.js and jquerymobile.css
window.onload = function() {
//preload mouse down image here via Image()
$("#button_img").vmousedown(function(){$("#button_img").attr("src","button_on.png");});
$("#button_img").vmouseup(function(){$("#button_img").attr("src","button_off.png")});
}
</code></pre>
<p>Just gave me the errors that vmousedown and vmouseup don't exist. Also, jQueryMobile overrides the CSS I've already written for the page.</p>
<p>So is there a way to get vmousedown and vmouseup to work, and to do so without jQuery Mobile's CSS?</p> | 11,145,262 | 4 | 3 | null | 2012-06-21 18:21:38.293 UTC | 9 | 2021-01-24 21:09:19.143 UTC | 2018-08-28 23:44:38.67 UTC | null | 759,866 | null | 671,890 | null | 1 | 34 | javascript|jquery|jquery-mobile|mouseevent | 74,008 | <p>You're looking for <code>touchstart</code> and <code>touchend</code>. They are the events that <code>vmousedown</code> and <code>vmouseup</code> attempt to mimic.</p>
<p>Here's an example:</p>
<pre><code>window.onload = function() {
//preload mouse down image here via Image()
$("#button_img").bind('touchstart', function(){
$("#button_img").attr("src","button_on.png");
}).bind('touchend', function(){
$("#button_img").attr("src","button_off.png");
});
}
</code></pre>
<p>This will work without any framework on any device that supports touch events. You could use something like <a href="http://www.modernizr.com" rel="noreferrer">Modernizr</a> to do this test and if the device does not support touch events, bind to the regular desktop events.</p>
<p>When you use <code>touchstart</code>/<code>touchend</code>/<code>touchmove</code> you get some interesting information, for instance how many touches are occurring at once, so you can detect if the user is scrolling or attempting to zoom.</p>
<p><strong>UPDATE</strong></p>
<p>Since the <code>event</code> object inside an event handler differs for touch events and mouse events, if you want to know the coordinates of the event either way, you can do something like this (the example below assumes Modernizr has been loaded):</p>
<pre><code>//determine which events to use
var startEventType = 'mousedown',
endEventType = 'mouseup';
if (Modernizr.touch === true) {
startEventType = 'touchstart';
endEventType = 'touchend';
}
//bind to determined event(s)
$("#button_img").bind(startEventType, function(event) {
//determine where to look for pageX by the event type
var pageX = (startEventType === 'mousedown')
? event.pageX
: event.originalEvent.touches[0].pageX;
...
})...
</code></pre>
<p><strong>UPDATE</strong></p>
<p>I was looking this over and it seems like you don't need to detect the event type before binding the event handler:</p>
<pre><code>//bind to determined event(s)
$("#button_img").bind('mousedown touchstart', function(event) {
//determine where to look for pageX by the event type
var pageX = (event.type.toLowerCase() === 'mousedown')
? event.pageX
: event.originalEvent.touches[0].pageX;
...
})...
</code></pre>
<p>If you are worried about receiving both events in quick succession you could use a timeout to throttle the event handler:</p>
<pre><code>//create timer
var timer = null;
//bind to determined event(s)
$("#button_img").bind('mousedown touchstart', function(event) {
//clear timer
clearTimeout(timer);
//set timer
timer = setTimeout(function () {
//determine where to look for pageX by the event type
var pageX = (event.type.toLowerCase() === 'mousedown')
? event.pageX
: event.originalEvent.touches[0].pageX;
...
}, 50);
})...
</code></pre>
<p>Note: You can force <code>mousedown</code> and <code>touchstart</code> events in quick succession with developer tools but I'm not sure about the real world use case here.</p> |
11,085,151 | C++ ifstream failbit and badbit | <p>In case of <code>ifstream</code> in C++, under what conditions are <code>failbit</code> and <code>badbit</code> flags set ?</p> | 11,085,193 | 1 | 2 | null | 2012-06-18 14:38:50.023 UTC | 15 | 2014-11-22 09:00:38.623 UTC | 2014-11-22 09:00:38.623 UTC | null | 1,009,479 | null | 682,869 | null | 1 | 70 | c++|file-io|ifstream | 57,075 | <p>According to <a href="http://www.cplusplus.com">cplusplus.com</a>:</p>
<blockquote>
<p><strong>failbit</strong> is generally set by an input operation when the error was related to the internal logic of the operation itself, so other operations on the stream may be possible. While <strong>badbit</strong> is generally set when the error involves the loss of integrity of the stream, which is likely to persist even if a different operation is performed on the stream. badbit can be checked independently by calling member function bad.</p>
</blockquote>
<p>In <em>simple words</em>, if you get a <strong>number</strong> when expect to retrieve a <strong>letter</strong>, it's <code>failbit</code>. If a <strong>serious</strong> error happens, which disrupts the ability to read from the stream at all - it's a <code>badbit</code>.</p>
<p>Except mentioned flags there is a third quite similar — <code>eofbit</code>. You can check the state using several functions: <a href="http://www.cplusplus.com/reference/iostream/ios/fail/"><code>ios::fail</code></a>, <a href="http://www.cplusplus.com/reference/iostream/ios/good/"><code>ios::good</code></a> and <a href="http://www.cplusplus.com/reference/iostream/ios/bad/"><code>ios::bad</code></a></p>
<p>And you can get familiar with <a href="http://msdn.microsoft.com/en-us/library/aa277347%28v=vs.60%29"><strong>iostream library</strong></a> at MSDN resource too.</p>
<p><strong>Finally</strong>, if you search for the <strong>correct</strong> solution of how to handling all error bits and exceptions while reading from the file (or accessing some file or directory), I highly recommend you read a very comprehensive and well-written article "<a href="http://gehrcke.de/2011/06/reading-files-in-c-using-ifstream-dealing-correctly-with-badbit-failbit-eofbit-and-perror/">Reading files in C++ using ifstream: dealing correctly with badbit, failbit, eofbit, and perror()</a>", at the end of which you will find a few <strong><a href="http://gehrcke.de/2011/06/reading-files-in-c-using-ifstream-dealing-correctly-with-badbit-failbit-eofbit-and-perror/#ideal">Ideal solutions</a></strong>. The article is worth to read indeed.</p> |
11,374,059 | make an html svg object also a clickable link | <p>I have an SVG object in my HTML page and am wrapping it in an anchor so when the svg image is clicked it takes the user to the anchor link.</p>
<pre><code><a href="http://www.google.com/">
<object data="mysvg.svg" type="image/svg+xml">
<span>Your browser doesn't support SVG images</span>
</object>
</a>
</code></pre>
<p>When I use this code block, clicking the svg object doesn't take me to google. In IE8< the span text is clickable.</p>
<p>I do not want to modify my svg image to contain tags.</p>
<p>My question is, how can I make the svg image clickable?</p> | 17,133,804 | 13 | 1 | null | 2012-07-07 10:05:16.187 UTC | 43 | 2021-05-10 17:58:11.58 UTC | null | null | null | null | 1,072,287 | null | 1 | 164 | html|object|svg|anchor | 139,678 | <p>Actually, the best way to solve this is... on the <object> tag, use:</p>
<pre><code>pointer-events: none;
</code></pre>
<p><em>Note: Users which have the Ad Blocker plugin installed get a tab-like [Block] at the upper right corner upon hovering (the same as a flash banner gets). By settings this css, that'll go away as well.</em></p>
<p><a href="http://jsfiddle.net/energee/UL9k9/" rel="noreferrer">http://jsfiddle.net/energee/UL9k9/</a></p> |
12,892,536 | how to choose java nio vs io? | <p>As we had known, If we want to use traditional IO to construct server, it must block somewhere, so we had to use loop or one thread one socket mode, So nio seem it is better choice. So I want know if the nio is better choice forever?</p> | 12,893,057 | 7 | 1 | null | 2012-10-15 09:15:45.39 UTC | 11 | 2020-12-08 08:19:29.27 UTC | null | null | null | null | 1,288,446 | null | 1 | 29 | java|nio | 15,819 | <p>IMHO, Blocking IO is generally the simplest to use, and unless you have a specific requirement which demands more from your system, you should stick with simplest option.</p>
<p>The next simplest option is blocking NIO, which I often prefer if I want something more efficiency or control than IO. It is still relatively simple but allows you to use ByteBuffers. e.g. ByteBuffers support little endian.</p>
<p>A common option is to use non-blocking NIO with Selectors. Much of the complexity this introduces can be handled by frameworks such as Netty or Mina. I suggest you use such a library if you <em>need</em> non-blocking IO e.g. because you have thousands of concurrent connections per server. IMHO You have thousands of connections, you should consider having more servers unless what each connection does is pretty trivial. AFAIK google go for more servers rather thousands of users per server.</p>
<p>The more extreme option is to use NIO2. This is even more complex and lengthy it write than non-blocking NIO. I don't know of any frameworks which support this well. i.e. it is actually faster when you do. AFAIK It appears this is worth using if you have Infiniband (which is what it was designed to support) but perhaps not worth using if you have Ethernet.</p> |
13,018,295 | How to add a Web reference Visual Studio 2012 | <p>Is it possible to add a web reference to my project in Visual Studio 2012? In Visual Studio 2010 it was possible by clicking the "Advanced" button in the "Add Service Reference" dialog, as it is written on this page : <a href="http://www.c-sharpcorner.com/uploadfile/anavijai/add-web-reference-in-visual-studio-2010/" rel="nofollow noreferrer">
Add Web Reference in Visual Studio 2010
</a> <br></p>
<p>But in Visual Studio 2012 there is no section "Compatibility" in the "Service Reference Settings" and no "Add Web Reference" button in this dialog. I want to use SOAP web-service, but it works correctly only when I add it as Web Reference (in .NET Framework 2.0 compatibility mode. If I Add it as usual service reference I have an exception during using this service).<br></p>
<p>How to add old-style web reference to my project? <br>
Or how to use my web service with new style of service references?</p>
<p>Thanks</p> | 13,027,713 | 4 | 0 | null | 2012-10-22 19:21:25.213 UTC | 8 | 2017-06-21 20:21:19.48 UTC | 2017-06-21 20:21:19.48 UTC | null | 6,472,853 | null | 1,029,518 | null | 1 | 33 | soap|visual-studio-2012|web-reference | 73,902 | <p>Solved. CheckBox "Always generate message contracts" Helped. Thanks for all.</p> |
12,906,048 | Ruby convention for chaining calls over multiple lines | <p>What are the conventions for this?</p>
<p>I use the folowing style, but not sure it is the preferred one since if I miss a dot at the end I can run into a lot of issue without realising that.</p>
<pre><code>query = reservations_scope.for_company(current_company).joins{property.development}.
group{property.development.id}.
group{property.development.name}.
group{property.number}.
group{created_at}.
group{price}.
group{reservation_path}.
group{company_id}.
group{user_id}.
group{fee_paid_date}.
group{contract_exchanged_date}.
group{deposit_paid_date}.
group{cancelled_date}.
select_with_reserving_agent_name_for(current_company, [
"developments.id as dev_id",
"developments.name as dev_name",
"properties.number as prop_number",
"reservations.created_at",
"reservations.price",
"reservations.fee_paid_date",
"reservations.contract_exchanged_date",
"reservations.deposit_paid_date",
"reservations.cancelled_date"
]).reorder("developments.name")
query.to_a # ....
</code></pre>
<p>So what are the conventions for <strong>chaining</strong> methods over <strong>multiple lines</strong> and which one should I prefer?</p>
<p><strong>NOTE</strong>: I couldn't find a good example from the <a href="https://github.com/bbatsov/ruby-style-guide/" rel="noreferrer">Ruby coding style guide</a>. </p> | 16,770,307 | 4 | 0 | null | 2012-10-16 00:48:23.06 UTC | 9 | 2018-04-29 04:24:04.51 UTC | null | null | null | null | 148,473 | null | 1 | 46 | ruby-on-rails|ruby|coding-style | 25,018 | <p>There is actually a section on that in the <a href="https://github.com/bbatsov/ruby-style-guide">Ruby style guide</a>:</p>
<blockquote>
<p>Adopt a consistent multi-line method chaining style. There are two
popular styles in the Ruby community, both of which are considered
good - leading <code>.</code> (Option A) and trailing <code>.</code> (Option B).</p>
<ul>
<li><p><strong>(Option A)</strong> When continuing a chained method invocation on
another line keep the <code>.</code> on the second line.</p>
<pre><code># bad - need to consult first line to understand second line
one.two.three.
four
# good - it's immediately clear what's going on the second line
one.two.three
.four
</code></pre></li>
<li><p><strong>(Option B)</strong> When continuing a chained method invocation on another line,
include the <code>.</code> on the first line to indicate that the
expression continues.</p>
<pre><code># bad - need to read ahead to the second line to know that the chain continues
one.two.three
.four
# good - it's immediately clear that the expression continues beyond the first line
one.two.three.
four
</code></pre></li>
</ul>
<p>A discussion on the merits of both alternative styles can be found
<a href="https://github.com/bbatsov/ruby-style-guide/pull/176">here</a>.</p>
</blockquote> |
16,620,509 | How to identify what device was plugged into the USB slot? | <p>I want to detect when the user plugs in or removes a USB sound card. I've managed to actually catch the event when this happens, but I can't tell what just got plugged in.</p>
<p>I tried an approach based on <a href="https://stackoverflow.com/questions/5278860/using-wmi-to-identify-which-device-caused-a-win32-devicechangeevent">this</a> question: </p>
<pre><code>string query =
"SELECT * FROM __InstanceCreationEvent " +
"WITHIN 2 "
+ "WHERE TargetInstance ISA 'Win32_PnPEntity'";
var watcher = new ManagementEventWatcher(query);
watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
watcher.Start();
</code></pre>
<p>While I get the notifications via the EventArrived event, I have no idea how to determine the actual name of the device that just got plugged in. I've gone through every property and couldn't make heads or tails out of it.</p>
<p>I also tried a different query: </p>
<pre><code>var query = new WqlEventQuery("SELECT * FROM Win32_DeviceChangeEvent where EventType = 1 or EventType = 2");
var watcher = new ManagementEventWatcher(query);
watcher.EventArrived += watcher_EventArrived;
watcher.Stopped += watcher_Stopped;
watcher.Query = query;
watcher.Start();
</code></pre>
<p>but also to no avail. Is there a way to find the name of the device that got plugged in or removed.</p>
<p>The bottom line is that I'd like to know when a USB sound card is plugged in or removed from the system. It should work on Windows 7 and Vista (though I will settle for Win7 only).</p>
<p>EDIT: Based on the suggestions by the winning submitter, I've created a <a href="http://pastebin.com/amLAHuEa" rel="nofollow noreferrer">full solution</a> that wraps all the functionality.</p> | 16,793,425 | 3 | 2 | null | 2013-05-18 03:54:52.63 UTC | 9 | 2018-04-27 18:57:01.22 UTC | 2017-05-23 11:48:32.887 UTC | null | -1 | null | 9,382 | null | 1 | 15 | c#|usb|wmi|plug-and-play | 13,774 | <p>If I use your first code, I can define my event like this:</p>
<pre><code> // define USB class guid (from devguid.h)
static readonly Guid GUID_DEVCLASS_USB = new Guid("{36fc9e60-c465-11cf-8056-444553540000}");
static void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
ManagementBaseObject instance = (ManagementBaseObject )e.NewEvent["TargetInstance"];
if (new Guid((string)instance["ClassGuid"]) == GUID_DEVCLASS_USB)
{
// we're only interested by USB devices, dump all props
foreach (var property in instance.Properties)
{
Console.WriteLine(property.Name + " = " + property.Value);
}
}
}
</code></pre>
<p>And this will dump something like this:</p>
<pre><code>Availability =
Caption = USB Mass Storage Device
ClassGuid = {36fc9e60-c465-11cf-8056-444553540000}
CompatibleID = System.String[]
ConfigManagerErrorCode = 0
ConfigManagerUserConfig = False
CreationClassName = Win32_PnPEntity
Description = USB Mass Storage Device
DeviceID = USB\VID_18A5&PID_0243\07072BE66DD78609
ErrorCleared =
ErrorDescription =
HardwareID = System.String[]
InstallDate =
LastErrorCode =
Manufacturer = Compatible USB storage device
Name = USB Mass Storage Device
PNPDeviceID = USB\VID_18A5&PID_0243\07072BE66DD78609
PowerManagementCapabilities =
PowerManagementSupported =
Service = USBSTOR
Status = OK
StatusInfo =
SystemCreationClassName = Win32_ComputerSystem
SystemName = KILROY_WAS_HERE
</code></pre>
<p>This should contain everything you need, including the device ID that you can get with something like <code>instance["DeviceID"]</code>.</p> |
16,921,384 | aggregating gradle multiproject test results using TestReport | <p>I have a project structure that looks like the below. I want to use the <a href="http://www.gradle.org/docs/current/dsl/org.gradle.api.tasks.testing.TestReport.html">TestReport</a> functionality in Gradle to aggregate all the test results to a single directory.
Then I can access all the test results through a single index.html file for ALL subprojects.
How can I accomplish this?</p>
<pre><code>.
|--ProjectA
|--src/test/...
|--build
|--reports
|--tests
|--index.html (testresults)
|--..
|--..
|--ProjectB
|--src/test/...
|--build
|--reports
|--tests
|--index.html (testresults)
|--..
|--..
</code></pre> | 16,921,750 | 6 | 0 | null | 2013-06-04 15:10:51.793 UTC | 13 | 2022-08-23 11:31:58.233 UTC | null | null | null | null | 203,882 | null | 1 | 28 | build|automated-tests|gradle | 16,568 | <p>From <a href="https://docs.gradle.org/current/userguide/java_testing.html#test_reporting" rel="noreferrer">Example 4. Creating a unit test report for subprojects</a> in the <a href="http://gradle.org/docs/current/userguide/userguide_single.html" rel="noreferrer">Gradle User Guide</a>:</p>
<pre><code>subprojects {
apply plugin: 'java'
// Disable the test report for the individual test task
test {
reports.html.enabled = false
}
}
task testReport(type: TestReport) {
destinationDir = file("$buildDir/reports/allTests")
// Include the results from the `test` task in all subprojects
reportOn subprojects*.test
}
</code></pre>
<p>Fully working sample is available from <code>samples/testing/testReport</code> in the full Gradle distribution.</p> |
57,795,263 | "Test events were not received" when run tests using Intellij | <p>I have a Kotlin project and when I run my JUnit tests, I can't see tests execution result in IntelliJ and get this message instead: </p>
<blockquote>
<p>test events were not received</p>
</blockquote>
<p>I'm using this setup:</p>
<pre><code>macOS Mojave
Intellij CE 2019.2
JDK 11.0.3
Kotlin 1.3.50
Gradle 5.2.1
JUnit 4.12
</code></pre>
<p>Can you help me?</p> | 57,795,360 | 22 | 3 | null | 2019-09-04 20:28:44.6 UTC | 12 | 2022-08-11 18:37:45.893 UTC | 2019-09-09 12:12:23.693 UTC | null | 3,026,283 | null | 3,026,283 | null | 1 | 85 | testing|intellij-idea|kotlin|junit | 72,187 | <p>Update to <a href="https://blog.jetbrains.com/idea/2019/09/intellij-idea-2019-2-2-is-here/" rel="noreferrer">2019.2.2</a> or later, which contains the fix for the <a href="https://youtrack.jetbrains.com/issue/IDEA-221159" rel="noreferrer">related issue</a>.</p>
<p>A workaround is to run the tests using IntelliJ IDEA instead of Gradle by changing the <a href="https://i.imgur.com/HpeUaUE.png" rel="noreferrer">delegation option</a>.</p> |
9,935,690 | mySQL dateTime range Query Issue | <p>I have a quick question. I'm have a db an audit Table with a datetime column in it. (i.e 2012-03-27 00:00:00) and I'm building a mySQL query to return a set of rows if the date is in between the two dates I'm giving it.</p>
<p>so far my query looks like this:</p>
<pre><code>SELECT * FROM util_audit WHERE DATED >= DATE(03/15/2012) AND DATED <= DATE(03/31/2012);
</code></pre>
<p>if I just use</p>
<pre><code>SELECT * FROM util_audit WHERE DATED >= DATE(03/15/2012);
</code></pre>
<p>It'll return all my record because they were dated this week.</p>
<p>I also tried this:</p>
<pre><code>SELECT * FROM util_audit WHERE DATED >= '02/15/2012 00:00:00' AND DATED <= '03/31/2012 00:00:00';
</code></pre>
<p>and nothing! It'll return zero rows, when I know I have all of them dated from the 27 of this month to today. Am I missing something here? why does it work on its own, but not when I add the second date?I'm probably overlooking something.</p> | 9,935,709 | 3 | 0 | null | 2012-03-30 00:58:24.367 UTC | 8 | 2016-07-20 16:43:55.123 UTC | null | null | null | null | 929,694 | null | 1 | 34 | mysql|datetime | 101,298 | <p>Try:</p>
<pre><code>SELECT * FROM util_audit WHERE `DATED` BETWEEN "2012-03-15" AND "2012-03-31";
</code></pre> |
9,847,559 | Conditionally change panel background with facet_grid? | <p>I'm using the "tips" data set in <strong>ggplot2</strong>. If I do</p>
<pre><code>sp = ggplot(tips,aes(x=total_bill, y = tip/total_bill)) +
geom_point(shape=1) +
facet_grid(sex ~ day)
</code></pre>
<p>The plot comes out fine. But I now want to change the panel background for just the plots under "Fri". Is there a way to do this? </p>
<p>Even better, can I conditionally change colors by passing parameters? For example if more than 3 points are below 0.1, then change panel background (for just that panel) to a certain color while all others remain the default light grey?</p> | 9,847,994 | 2 | 0 | null | 2012-03-23 23:02:55.197 UTC | 24 | 2017-04-03 16:33:30.067 UTC | 2012-03-23 23:12:39.63 UTC | null | 324,364 | null | 1,210,178 | null | 1 | 39 | r|ggplot2 | 20,228 | <p>The general rule for doing anything in <strong>ggplot2</strong> is to,</p>
<ol>
<li>Create a data frame that encodes the information you want to plot</li>
<li>Pass that data frame to a geom</li>
</ol>
<p>This is made a bit more complicated in this case because of the particular aspect of the plot you want to alter. The Powers That Be designed <strong>ggplot2</strong> in a way that separates data elements of the plot (i.e. geom's) from non-data elements (i.e. theme's), and it so happens that the plot background falls under the "non-data" category.</p>
<p>There is always the option of modifying the underlying grid object <a href="https://stackoverflow.com/questions/6750664/how-to-change-the-format-of-an-individual-ggplot2-facet-plot">manually</a> but this is tedious and the details may change with different versions of <strong>ggplot2</strong>. Instead, we'll employ the "hack" that Hadley refers to in <a href="https://stackoverflow.com/q/3167444/324364">this</a> question.</p>
<pre><code>#Create a data frame with the faceting variables
# and some dummy data (that will be overwritten)
tp <- unique(tips[,c('sex','day')])
tp$total_bill <- tp$tip <- 1
#Just Fri
ggplot(tips,aes(x=total_bill, y = tip/total_bill)) +
geom_rect(data = subset(tp,day == 'Fri'),aes(fill = day),xmin = -Inf,xmax = Inf,
ymin = -Inf,ymax = Inf,alpha = 0.3) +
geom_point(shape=1) +
facet_grid(sex ~ day)
</code></pre>
<p><img src="https://i.stack.imgur.com/Yntjo.png" alt="enter image description here"></p>
<pre><code>#Each panel
ggplot(tips,aes(x=total_bill, y = tip/total_bill)) +
geom_rect(data = tp,aes(fill = day),xmin = -Inf,xmax = Inf,
ymin = -Inf,ymax = Inf,alpha = 0.3) +
geom_point(shape=1) +
facet_grid(sex ~ day)
</code></pre>
<p><img src="https://i.stack.imgur.com/EC4xF.png" alt="enter image description here"></p> |
10,127,818 | ssh_exchange_identification: Connection closed by remote host under Git bash | <p>I work at win7 and set up git server with sshd.
I <code>git --bare init myapp.git</code>, and clone <code>ssh://git@localhost/home/git/myapp.git</code> in <strong>Cywgin</strong> correctly. But I need config git of <strong>Cygwin</strong> again, I want to git clone in <strong>Git Bash</strong>. I run <code>git clone ssh://git@localhost/home/git/myapp.git</code> and get following message</p>
<pre><code>ssh_exchange_identification: Connection closed by remote host
</code></pre>
<p>then I run <code>ssh -vvv git@localhost</code> in <strong>Git Bash</strong> and get message</p>
<pre><code>debug2: ssh_connect: needpriv 0
debug1: Connecting to localhost [127.0.0.1] port 22.
debug1: Connection established.
debug1: identity file /c/Users/MoreFreeze/.ssh/identity type -1
debug3: Not a RSA1 key file /c/Users/MoreFreeze/.ssh/id_rsa.
debug2: key_type_from_name: unknown key type '-----BEGIN'
debug3: key_read: missing keytype
debug3: key_read: missing whitespace
// above it repeats 24 times
debug2: key_type_from_name: unknown key type '-----END'
debug3: key_read: missing keytype
debug1: identity file /c/Users/MoreFreeze/.ssh/id_rsa type 1
debug1: identity file /c/Users/MoreFreeze/.ssh/id_dsa type -1
ssh_exchange_identification: Connection closed by remote host
</code></pre>
<p>it seems my private keys has wrong format? And I find that there are exactly 25 line in private keys without <code>BEGIN</code> and <code>END</code>.
I'm confused why it said NOT RSA1 key, I totally ensure it is RSA 2 key.</p>
<p>Any advises are welcome.
btw, I have read first 3 pages on google about this problem.</p> | 12,503,277 | 28 | 8 | null | 2012-04-12 16:32:53.963 UTC | 23 | 2022-02-05 05:51:34.24 UTC | 2012-10-11 18:22:11.217 UTC | null | 957,997 | null | 878,228 | null | 1 | 62 | git|ssh | 246,253 | <p>I had this problem today and I realize that I was connected to 2 differente networks (LAN and WLAN), I solved it just disconnecting the cable from my Ethernet adapter. I suppose that the problem is caused because the ssh key is tied with the MAC address of my wireless adapter. I hope this helps you.</p> |
9,692,525 | Stop Vim wrapping lines in the middle of a word | <p>After doing <code>:set wrap</code>, Vim wraps lines longer than the window.</p>
<p>But is it possible to have Vim wrap to a new line on blank spaces only, not half-way through a word?</p> | 9,692,577 | 5 | 1 | null | 2012-03-13 21:33:15.697 UTC | 8 | 2020-04-29 16:18:01.47 UTC | 2014-09-01 15:01:25.87 UTC | null | 2,071,807 | null | 302,249 | null | 1 | 64 | vim | 10,648 | <p><code>:help wrap</code></p>
<blockquote>
<p>This option changes how text is displayed. It doesn't change the text
in the buffer, see 'textwidth' for that.
When on, lines longer than the width of the window will wrap and
displaying continues on the next line. When off lines will not wrap
and only part of long lines will be displayed. When the cursor is
moved to a part that is not shown, the screen will scroll
horizontally.
The line will be broken in the middle of a word if necessary. <strong>See
'linebreak' to get the break at a word boundary.</strong></p>
</blockquote>
<p><code>:help linebreak</code></p>
<blockquote>
<p>If on Vim will wrap long lines at a character in 'breakat' rather
than at the last character that fits on the screen.</p>
</blockquote>
<p><code>:help breakat</code></p>
<blockquote>
<p>'breakat' 'brk' <code>string</code> (default <code>" ^I!@*-+;:,./?"</code>)</p>
</blockquote>
<p>So, <code>:set linebreak</code> and it should work out of box. Or you can restrict <code>breakat</code> to just break on spaces, instead of spaces+punctuation.</p> |
9,709,818 | Why is $a + ++$a == 2? | <p>If I try this:</p>
<pre><code>$a = 0;
echo $a + ++$a, PHP_EOL;
echo $a;
</code></pre>
<p>I get this output:</p>
<pre><code>2
1
</code></pre>
<p>Demo: <a href="http://codepad.org/ncVuJtJu">http://codepad.org/ncVuJtJu</a></p>
<h3>Why is that?</h3>
<p>I expect to get this as an output:</p>
<pre><code>1
1
</code></pre>
<h3>My understanding:</h3>
<pre><code>$a = 0; // a === 0
echo $a + ++$a, PHP_EOL; // (0) + (0+1) === 1
echo $a; // a === 1
</code></pre>
<p>But why isn't that the output?</p> | 9,716,695 | 13 | 2 | null | 2012-03-14 20:31:24.713 UTC | 17 | 2013-10-14 12:27:11.613 UTC | 2012-10-28 16:29:26.63 UTC | null | 367,456 | null | 561,731 | null | 1 | 65 | php|math|operator-precedence | 6,491 | <p>All the answers explaining why you get 2 and not 1 are actually wrong. According to the PHP documentation, mixing <code>+</code> and <code>++</code> in this manner is undefined behavior, so you could get either 1 or 2. Switching to a different version of PHP may change the result you get, and it would be just as valid.</p>
<p>See <a href="http://php.net/manual/en/language.operators.precedence.php#example-111">example 1</a>, which says: </p>
<pre><code>// mixing ++ and + produces undefined behavior
$a = 1;
echo ++$a + $a++; // may print 4 or 5
</code></pre>
<p>Notes:</p>
<ol>
<li><p>Operator precedence does <em>not</em> determine the order of evaluation. Operator precedence only determines that the expression <code>$l + ++$l</code> is parsed as <code>$l + (++$l)</code>, but doesn't determine if the left or right operand of the <code>+</code> operator is evaluated first. If the left operand is evaluated first, the result would be 0+1, and if the right operand is evaluated first, the result would be 1+1.</p></li>
<li><p>Operator associativity also does not determine order of evaluation. That the <code>+</code> operator has left associativity only determines that <code>$a+$b+$c</code> is evaluated as <code>($a+$b)+$c</code>. It does not determine in what order a single operator's operands are evaluated.</p></li>
</ol>
<p>Also relevant: On <a href="https://bugs.php.net/bug.php?id=61188">this bug report</a> regarding another expression with undefined results, a PHP developer says: "We make no guarantee about the order of evaluation [...], just as C doesn't. Can you point to any place on the documentation where it's stated that the first operand is evaluated first?"</p> |
7,744,038 | Decision when to create Index on table column in database? | <p>I am not db guy. But I need to create tables and do CRUD operations on them. I get confused should I create the index on all columns by default
or not? Here is my understanding which I consider while creating index.</p>
<p>Index basically contains the memory location range ( starting memory location where first value is stored to end memory location where last value is
stored). So when we insert any value in table index for column needs to be updated as it has got one more value but update of column
value wont have any impact on index value. <strong>Right?</strong> So bottom line is when my column is used in join between two tables we should consider
creating index on column used in join but all other columns can be skipped because if we create index on them it will involve extra cost of
updating index value when new value is inserted in column.<strong>Right?</strong></p>
<p>Consider this scenario where table <code>mytable</code> contains two three columns i.e <code>col1</code>,<code>col2</code>,<code>col3</code>. Now we fire this query</p>
<pre><code>select col1,col2 from mytable
</code></pre>
<p>Now there are two cases here. In first case we create the index on <code>col1</code> and <code>col2</code>. In second case we don't create any index.** As per my understanding
case 1 will be faster than case2 because in case 1 we oracle can quickly find column memory location. So here I have not used any join columns but
still index is helping here. So should I consider creating index here or not?**</p>
<p>What if in the same scenario above if we fire</p>
<pre><code>select * from mytable
</code></pre>
<p>instead of</p>
<pre><code>select col1,col2 from mytable
</code></pre>
<p><strong>Will index help here?</strong></p> | 7,745,117 | 3 | 5 | null | 2011-10-12 17:26:03.337 UTC | 22 | 2016-02-05 01:11:07.003 UTC | 2014-07-03 14:26:02.313 UTC | null | 125,389 | null | 802,050 | null | 1 | 39 | sql|oracle|indexing | 76,072 | <blockquote>
<p>but update of column value wont have any impact on index value. Right?</p>
</blockquote>
<p>No. Updating an indexed column will have an impact. The Oracle 11g <a href="http://download.oracle.com/docs/cd/E11882_01/server.112/e16638/data_acc.htm#i2769" rel="noreferrer">performance manual</a> states that: </p>
<blockquote>
<p>UPDATE statements that modify indexed columns and INSERT and DELETE
statements that modify indexed tables take longer than if there were
no index. Such SQL statements must modify data in indexes and data in
tables. They also create additional undo and redo.</p>
</blockquote>
<hr>
<blockquote>
<p>So bottom line is when my column is used in join between two tables we should consider creating index on column used in join but all other columns can be skipped because if we create index on them it will involve extra cost of updating index value when new value is inserted in column. Right?</p>
</blockquote>
<p>Not just Inserts but any other Data Manipulation Language statement. </p>
<blockquote>
<p>Consider this scenario . . . Will index help here?</p>
</blockquote>
<p>With regards to this last paragraph, why not build some test cases with representative data volumes so that you prove or disprove your assumptions about which columns you should index?</p> |
7,874,822 | Draw solid color triangle using XAML only | <p>Is it possible to draw a filled in triangle using XAML only (not a code behind solution)?</p>
<p>Triangle should be like on the image below to represent sort direction <code>Ascending/Descending</code> along with a sort button on a chart control:</p>
<p><img src="https://i.stack.imgur.com/nsqNv.png" alt="enter image description here"></p>
<p><strong>EDIT:</strong> The solution, thanks to <a href="https://stackoverflow.com/users/444231/spezifish">SpeziFish</a>:</p>
<p>Ascending:</p>
<pre><code><Polygon Points="0,0 8,5, 0,10" Stroke="Black" Fill="Black" />
</code></pre>
<p>Descending:</p>
<pre><code><Polygon Points="8,0 0,5, 8,10" Stroke="Black" Fill="Black" />
</code></pre> | 7,874,915 | 3 | 2 | null | 2011-10-24 11:21:00.467 UTC | 8 | 2013-09-20 14:51:07.317 UTC | 2017-05-23 12:02:14.733 UTC | null | -1 | null | 485,076 | null | 1 | 86 | .net|wpf|xaml|draw | 69,139 | <pre><code><Polygon Points="0,0 80,50, 0,100" Stroke="Black" Fill="Black" />
</code></pre>
<p>See <a href="http://msdn.microsoft.com/en-us/library/system.windows.shapes.polygon.aspx" rel="noreferrer">API</a> or <a href="http://msdn.microsoft.com/en-us/library/ms745818.aspx" rel="noreferrer">Example</a>.</p> |
11,843,658 | update a row using spring jdbctemplate | <p>I am new to spring. I am developing a CRUD application using spring jdbc template. I am done with insert and select. but in update am facing some problem. can anybody provide me a simple example of update and delete using jdbctemplate.
thnks in advance.</p>
<p>MY CONTROLLER-</p>
<pre><code>@RequestMapping(method = RequestMethod.GET)
public String showUserForm(@ModelAttribute(value="userview") User user,ModelMap model)
{
List list=userService.companylist();
model.addAttribute("list",list);
return "viewCompany";
}
@RequestMapping( method = RequestMethod.POST)
public String add(@ModelAttribute(value="userview") @Valid User user, BindingResult result)
{
userValidator.validate(user, result);
if (result.hasErrors()) {
return "viewCompany";
} else {
userService.updateCompany(user);
System.out.println("value updated");
return "updateSuccess";
}
</code></pre>
<p>when i click on update button the edited values should be updated in my DB according to the row ID , my problem is how to map the row id from jsp to controller.</p> | 11,843,702 | 2 | 3 | null | 2012-08-07 10:09:48.483 UTC | 1 | 2022-07-27 14:35:40.09 UTC | 2013-01-11 10:29:45.317 UTC | null | 1,530,822 | null | 1,530,822 | null | 1 | 12 | spring|jdbctemplate | 104,942 | <p>Straight from <a href="http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#jdbc-updates">the documentation</a>:</p>
<blockquote>
<p>The following example shows a column updated for a certain primary
key. In this example, an SQL statement has placeholders for row
parameters. The parameter values can be passed in as varargs or
alternatively as an array of objects. Thus primitives should be
wrapped in the primitive wrapper classes explicitly or using
auto-boxing.</p>
</blockquote>
<pre><code>import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
public class ExecuteAnUpdate {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void setName(int id, String name) {
this.jdbcTemplate.update(
"update mytable set name = ? where id = ?",
name, id);
}
}
</code></pre> |
11,532,144 | How to detect IP address change on OSX programmatically in C or C++ | <p>I have to be able to detect an IP address change for my Mac client. I need to perform an action every time I get a new one, when I go from wifi to wired ...</p>
<p>Anyone has done something similar? I currently poll every minute and I need to change that to be more event driven.</p> | 11,532,488 | 1 | 2 | null | 2012-07-17 23:12:50.677 UTC | 13 | 2012-07-19 20:52:47.403 UTC | null | null | null | null | 496,136 | null | 1 | 17 | c++|c|macos | 8,673 | <p>There are multiple ways to do this, from IOKit notifications on up, but the simplest is probably the SystemConfiguration framework.</p>
<p>The first step is to fire up scutil and play with it to figure out which key(s) you want notification on:</p>
<pre><code>$ scutil
> list
...
> n.add State:/Network/Global/IPv4
> n.watch
... unplug your network cable (or disconnect from WiFi)
notification callback (store address = 0x10e80e3c0).
changed key [0] = State:/Network/Global/IPv4
</code></pre>
<p>Look at that, got it on first try. :) But if you want to watch a particular NIC, or use IPv6 instead of v4, etc., obviously you'll want a different key from the list. Note that you can use regex patterns (POSIX style, as defined by <code>man 3 regex</code>), so if you want to watch, say, any NIC for IPv4, you can use <code>State:/Network/Interface/.*/IPv4</code>, or if you want to say global IPv4 or IPv6, <code>State:/Network/Global/IPv.</code>, etc.</p>
<p>Now you just call SCDynamicStoreSetNotificationKeys with the keys you want.</p>
<p>Note that SCDynamicStoreSetNotificationKeys can take regex patterns (POSIX style, as defined by man 3 regex)</p>
<p>Since it's a bit painful in C, I'll write it in Python:</p>
<pre><code>#!/usr/bin/python
from Foundation import *
from SystemConfiguration import *
def callback(store, keys, info):
for key in keys:
print key, SCDynamicStoreCopyValue(store, key)
store = SCDynamicStoreCreate(None,
"global-network-watcher",
callback,
None)
SCDynamicStoreSetNotificationKeys(store,
None,
['State:/Network/Global/IPv4'])
CFRunLoopAddSource(CFRunLoopGetCurrent(),
SCDynamicStoreCreateRunLoopSource(None, store, 0),
kCFRunLoopCommonModes)
CFRunLoopRun()
</code></pre>
<p>The main reason this is more painful in C is that you need dozens of lines of boilerplate for things like creating an CFArray with a CFString in it, printing CFString values, managing the lifetimes of the objects, etc. From Jeremy Friesner's comment, there's <a href="http://www.lcscanada.com/jaf/osx_ip_change_notify.cpp" rel="noreferrer">C++ sample code</a> available if you'd rather read 113 lines of C++ than 17 lines of Python. But really, there's only one line here that should be unfamiliar to someone who's never used Python:</p>
<pre><code>def callback(store, keys, info):
for key in keys:
print key, SCDynamicStoreCopyValue(store, key)
</code></pre>
<p>… is the equivalent of the C definition:</p>
<pre><code>void callback(SCDynamicStoreRef store, CFArrayRef keys, void *info) {
/* iterate over keys, printing something for each one */
}
</code></pre>
<p>Oddly, I can't find the actual reference or guide documentation on SystemConfiguration anymore; the only thing that comes up for SCDynamicStoreSetNotificationKeys or related functions is in the Navigating Firewalls section of <a href="https://developer.apple.com/library/ios/#documentation/Networking/Conceptual/CFNetwork/CFStreamTasks/CFStreamTasks.html" rel="noreferrer">CFNetwork Programming Guide</a>. But the original technote <a href="https://developer.apple.com/library/mac/#technotes/tn1145/_index.html" rel="noreferrer">TN1145: Living in a Dynamic TCP/IP Environment</a> still exists, and it's got enough background and sample code to figure out how write this yourself (and how to detect the new IP address(es) when you get notified).</p>
<p>Obviously this requires you to know what exactly you're trying to watch for. If you don't know that, nobody can tell you how to watch for it. Your original question was how to "detect an IP address change".</p>
<p>What the code above will do is detect when your default address changes. That's the address that gets used when you connect a socket to an internet address without binding it, or bind a socket to '0.0.0.0' to act as an internet server. If you haven't written the server code you care about, nearly all network clients do the former, and most servers do the latter unless you configure them otherwise, so that's probably all you care about.</p>
<p>Now let's go through the examples in your comments one by one:</p>
<blockquote>
<p>if i am trying to determine a network change, wifi to LAN</p>
</blockquote>
<p>There is no such thing as changing from WiFi to LAN. When you connect to a LAN, the WiFi is still working. Of course you can manually disable it before or after connecting to the LAN, but you don't have to, and it's a separate step, with a separate notification.</p>
<p>Normally, adding a LAN will change your default address to the LAN's address, so <code>/Network/Global</code> will notify you. If the OS can tell the LAN is not actually connected to the internet, or you've changed some hidden settings to make it prefer WiFi to LAN, etc., it won't change the default address, and <code>/Network/Global</code> will not notify you, but you probably don't care.</p>
<p>If you do care about whether a particular interface gets, loses, or changes an address, you can watch that interface. On most Macs, the built-in Ethernet is en0, and the built-in WiFi is en1, but of course you may have a third-party USB WiFi connector, or you may be using a tethered cell phone, or you may be interested not so much in the actual IP address of the LAN as in the VPN address of the VPN the LAN is connected to, etc. If you're writing something special purpose, you probably know which interface you care about, so you can watch, e.g., <code>State:/Network/Interface/en0/IPv4</code>. If you want to be notified on any interface changing no matter what, just watch <code>State:/Network/Interface/.*/IPv4</code>.</p>
<blockquote>
<p>or to hotspot or another wifi</p>
</blockquote>
<p>Changing from one WiFi network to another (hotspot or otherwise) will change en1—or, if you're using a third-party WiFi adapter, some other interface. If your default address at the time comes from WiFi, it will also change <code>Global</code>, which means the code above will work as-is. If your default address is still your LAN, <code>Global</code> won't change, but you probably don't care. If you do care, watch <code>Interface/en1</code> or <code>Interface/.*</code>, etc., as above.</p>
<blockquote>
<p>what all network settings should I be watching for IPV4 and 6</p>
</blockquote>
<p>Just replace IPv4 with IPv6, or use <code>IPv.</code>. But do you really care about IPv6?</p>
<blockquote>
<p>what else</p>
</blockquote>
<p>What else do you care about? If there's something you actually want notification of, you presumably know what that something is. </p>
<p>Beyond that, if the system tells you that the foo address on the bar interface has changed to "ZZ9 Plural Z Alpha", and you've never heard of the foo protocol, what could you usefully do with that information? But if you really want it anyway, again, you can just use a regex pattern to watch for anything under each interface.</p> |
11,809,685 | How do I delete an entity from symfony2 | <p>My first symfony2 project is a list of guests (invited in an event) stored in a database. I have </p>
<ul>
<li>created the entity class Guest with all variables for them (id, name, address, phone number etc.) </li>
<li>created the schema in the mysql db</li>
<li>created a route for "adding a guest" to a twig template</li>
<li>created a formType </li>
</ul>
<p>and finally a "createGuest" method in the Controller and everything works fine. </p>
<p>I can't manage to remove a guest from the database. I have read every tutorial in the web, including the official Symfony2 book; all that it says is :</p>
<p><strong>Deleting an Object</strong></p>
<p><em>Deleting an object is very similar, but requires a call to the remove() method of the entity manager:</em></p>
<pre class="lang-php prettyprint-override"><code>$em->remove($product);
$em->flush();
</code></pre>
<p>It does not say anything more than that (even the "Update an object" section is missing documentation) on how to connect the controller deleteAction($id) with the twig template. What I want to do is to list all guests with a viewGuests action and a viewGuests twig template, having a delete icon next to every row, which you should click to delete an entry. Simple, but I cannot find any documentation and do not know where to start from. </p>
<pre class="lang-php prettyprint-override"><code>public function deleteGuestAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$guest = $em->getRepository('GuestBundle:Guest')->find($id);
if (!$guest) {
throw $this->createNotFoundException('No guest found for id '.$id);
}
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
</code></pre> | 11,810,013 | 3 | 5 | null | 2012-08-04 15:16:25.19 UTC | 7 | 2021-12-04 07:28:28.03 UTC | 2012-08-05 08:09:20.367 UTC | null | 1,047,365 | null | 1,576,116 | null | 1 | 69 | symfony|doctrine | 184,367 | <p>Symfony is smart and knows how to make the <code>find()</code> by itself :</p>
<pre><code>public function deleteGuestAction(Guest $guest)
{
if (!$guest) {
throw $this->createNotFoundException('No guest found');
}
$em = $this->getDoctrine()->getEntityManager();
$em->remove($guest);
$em->flush();
return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
}
</code></pre>
<p>To send the id in your controller, use <code>{{ path('your_route', {'id': guest.id}) }}</code></p> |
3,644,897 | Cannot use RVM-installed Ruby with sudo | <p>I have succefully configured RVM to use Ruby 1.9.2 and everything is fine. However when I'm trying to run Ruby using <code>sudo</code> it says it cannot find RVM or Ruby:</p>
<pre><code>$ ruby -v
ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-linux]
$ sudo ruby -v
[sudo] password for administrator:
sudo: ruby: command not found
</code></pre>
<p>Is that correct behavior or is my RVM misconfigured? Perhaps I should be using the <a href="http://rvm.beginrescueend.com/deployment/system-wide/" rel="noreferrer">system wide install</a>?</p> | 3,695,692 | 4 | 0 | null | 2010-09-05 03:26:59.433 UTC | 12 | 2013-01-27 20:42:14.947 UTC | 2013-01-27 20:42:14.947 UTC | null | 211,563 | null | 161,287 | null | 1 | 53 | ruby|rvm|sudo | 25,432 | <p>Use <code>rvmsudo</code> command instead of <code>sudo</code></p> |
3,906,640 | Why are my div margins overlapping and how can I fix it? | <p>I don't understand why the margins of these divs are overlapping.</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-css lang-css prettyprint-override"><code>.alignright {float: right}
#header .social {margin-top: 50px;}
#header .social a {display: inline-block;}
#header .social .fb {width: 64px; height: 1px; padding-top: 60px; overflow: hidden;}
#header .social .twit {width: 64px; height: 1px; padding-top: 60px; overflow: hidden;}
#header .contact {margin: 20px 70px 20px 0; font-size: 14px; font-weight: bold;}
#header .contact span {color: #FFFFFF;}
#header .search {margin: 10px 0 0;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="alignright">
<div class="social">
<a href="#" class="twit"></a>
<a href="#" class="fb"></a>
</div><!-- social -->
<div class="contact">
Get in Touch: <span>+44 10012 12345</span>
</div><!-- contact -->
<div class="search">
<form method="post" action="">
<input type="text" value="" name="s" gtbfieldid="28">
</form>
</div><!-- search -->
</div></code></pre>
</div>
</div>
</p>
<p><img src="https://i.stack.imgur.com/tOJW5.png" alt="picture"></p> | 3,906,787 | 5 | 2 | null | 2010-10-11 13:27:55.53 UTC | 16 | 2020-01-27 12:56:35.683 UTC | 2019-08-28 17:47:26.14 UTC | null | 2,756,409 | null | 205,024 | null | 1 | 90 | html|css|margins | 89,428 | <p>I think it's a collapsed margin.
Only the largest margin between the bottom of the first element and the top of the second is taken into account.</p>
<p>It is quite normal to don't have too much space between two paragraphs eg.</p>
<p><strike>You cannot avoid that with two adjacent elements so you have to enlarge or reduce the larger margin.</strike></p>
<p>EDIT: cf. <a href="http://www.w3.org/TR/CSS2/box.html#collapsing-margins" rel="noreferrer">W3C</a></p>
<blockquote>
<p>Two margins are adjoining if and only if:</p>
<ul>
<li>both belong to in-flow block-level boxes that participate in the same block formatting context</li>
<li>no line boxes, no clearance, no padding and no border separate them</li>
<li>both belong to vertically-adjacent box edges</li>
</ul>
</blockquote>
<p>So there is no collapsing with <code>float</code> which takes the element out of the flow.</p> |
3,573,475 | How does the Import Library work? Details? | <p>I know this may seem quite basic to geeks. But I want to make it crystal clear.</p>
<p>When I want to use a Win32 DLL, usually I just call the APIs like LoadLibrary() and GetProcAdderss(). But recently, I am developing with DirectX9, and I need to add <em>d3d9.lib</em>, <em>d3dx9.lib</em>, etc files.</p>
<p>I have heard enough that LIB is for static linking and DLL is for dynamic linking.</p>
<p>So my current understanding is that LIB contains the implementation of the methods and is statically linked at link time as part of the final EXE file. While DLL is dynamic loaded at runtime and is not part of the final EXE file.</p>
<p>But sometimes, there're some LIB files <strong>coming with</strong> the DLL files, so:</p>
<ul>
<li>What are these LIB files for?</li>
<li>How do they achieve what they are meant for?</li>
<li>Is there any tools that can let me inspect the internals of these LIB files?</li>
</ul>
<h2>Update 1</h2>
<p>After checking wikipedia, I remember that these LIB files are called <a href="http://en.wikipedia.org/wiki/Dynamic-link_library#Import_libraries" rel="noreferrer">import library</a>.
But I am wondering how it works with my main application and the DLLs to be dynamically loaded.</p>
<h2>Update 2</h2>
<p>Just as RBerteig said, there're some stub code in the LIB files born with the DLLs. So the calling sequence should be like this:</p>
<p>My main application --> stub in the LIB --> real target DLL</p>
<p>So what information should be contained in these LIBs? I could think of the following:</p>
<ul>
<li>The LIB file should contain the fullpath of the corresponding DLL; So the DLL could be loaded by the runtime.</li>
<li>The relative address (or file offset?) of each DLL export method's entry point should be encoded in the stub; So correct jumps/method calls could be made.</li>
</ul>
<p>Am I right on this? Is there something more?</p>
<p><strong>BTW: Is there any tool that can inspect an import library? If I can see it, there'll be no more doubts.</strong></p> | 3,573,527 | 5 | 2 | null | 2010-08-26 08:48:09.543 UTC | 66 | 2022-06-22 22:32:29.323 UTC | 2016-01-22 23:14:37.913 UTC | null | 1,330,381 | null | 264,052 | null | 1 | 103 | c++|c|windows|visual-c++ | 48,930 | <p>Linking to a DLL file can occur <em>implicitly</em> at <strike>compile</strike> link time, or <em>explicitly</em> at run time. Either way, the DLL ends up loaded into the processes memory space, and all of its exported entry points are available to the application.</p>
<p>If used explicitly at run time, you use <code>LoadLibrary()</code> and <code>GetProcAddress()</code> to manually load the DLL and get pointers to the functions you need to call. </p>
<p>If linked implicitly when the program is built, then stubs for each DLL export used by the program get linked in to the program from an import library, and those stubs get updated as the EXE and the DLL are loaded when the process launches. (Yes, I've simplified more than a little here...)</p>
<p>Those stubs need to come from somewhere, and in the Microsoft tool chain they come from a special form of .LIB file called an <em>import library</em>. The required .LIB is usually built at the same time as the DLL, and contains a stub for each function exported from the DLL.</p>
<p>Confusingly, a static version of the same library would also be shipped as a .LIB file. There is no trivial way to tell them apart, except that LIBs that are import libraries for DLLs will usually be smaller (often much smaller) than the matching static LIB would be.</p>
<p>If you use the GCC toolchain, incidentally, you don't actually need import libraries to match your DLLs. The version of the Gnu linker ported to Windows understands DLLs directly, and can synthesize most any required stubs on the fly.</p>
<h3>Update</h3>
<p>If you just can't resist knowing where all the nuts and bolts really are and what is really going on, there is always something at MSDN to help. Matt Pietrek's article <a href="http://msdn.microsoft.com/en-us/magazine/cc301805.aspx" rel="noreferrer"><strong>An In-Depth Look into the Win32 Portable Executable File Format</strong></a> is a very complete overview of the format of the EXE file and how it gets loaded and run. Its even been updated to cover .NET and more since it originally appeared in MSDN Magazine ca. 2002.</p>
<p>Also, it can be helpful to know how to learn exactly what DLLs are used by a program. The tool for that is Dependency Walker, aka depends.exe. A version of it is included with Visual Studio, but the latest version is available from its author at <a href="http://www.dependencywalker.com/" rel="noreferrer">http://www.dependencywalker.com/</a>. It can identify all of the DLLs that were specified at link time (both early load and delay load) and it can also run the program and watch for any additional DLLs it loads at run time.</p>
<h3>Update 2</h3>
<p>I've reworded some of the earlier text to clarify it on re-reading, and to use the terms of art <em>implicit</em> and <em>explicit linking</em> for consistency with MSDN. </p>
<p>So, we have three ways that library functions might be made available to be used by a program. The obvious follow up question is then: "How to I choose which way?"</p>
<p>Static linking is how the bulk of the program itself is linked. All of your object files are listed, and get collected together in to the EXE file by the linker. Along the way, the linker takes care of minor chores like fixing up references to global symbols so that your modules can call each other's functions. Libraries can also be statically linked. The object files that make up the library are collected together by a librarian in a .LIB file which the linker searches for modules containing symbols that are needed. One effect of static linking is that only those modules from the library that are used by the program are linked to it; other modules are ignored. For instance, the traditional C math library includes many trigonometry functions. But if you link against it and use <code>cos()</code>, you don't end up with a copy of the code for <code>sin()</code> or <code>tan()</code> unless you also called those functions. For large libraries with a rich set of features, this selective inclusion of modules is important. On many platforms such as embedded systems, the total size of code available for use in the library can be large compared to the space available to store an executable in the device. Without selective inclusion, it would be harder to manage the details of building programs for those platforms.</p>
<p>However, having a copy of the <em>same</em> library in every program running creates a burden on a system that normally runs lots of processes. With the right kind of virtual memory system, pages of memory that have identical content need only exist once in the system, but can be used by many processes. This creates a benefit for increasing the chances that the pages containing code are likely to be identical to some page in as many other running processes as possible. But, if programs statically link to the runtime library, then each has a different mix of functions each laid out in that processes memory map at different locations, and there aren't many sharable code pages unless it is a program that all by itself is run in more than process. So the idea of a DLL gained another, major, advantage.</p>
<p>A DLL for a library contains all of its functions, ready for use by any client program. If many programs load that DLL, they can all share its code pages. Everybody wins. (Well, until you update a DLL with new version, but that isn't part of this story. Google DLL Hell for that side of the tale.)</p>
<p>So the first big choice to make when planning a new project is between dynamic and static linkage. With static linkage, you have fewer files to install, and you are immune from third parties updating a DLL you use. However, your program is larger, and it isn't quite as good citizen of the Windows ecosystem. With dynamic linkage, you have more files to install, you might have issues with a third party updating a DLL you use, but you are generally being friendlier to other processes on the system.</p>
<p>A big advantage of a DLL is that it can be loaded and used without recompiling or even relinking the main program. This can allow a third party library provider (think Microsoft and the C runtime, for example) to fix a bug in their library and distribute it. Once an end user installs the updated DLL, they immediately get the benefit of that bug fix in all programs that use that DLL. (Unless it breaks things. See DLL Hell.)</p>
<p>The other advantage comes from the distinction between implicit and explicit loading. If you go to the extra effort of explicit loading, then the DLL might not even have existed when the program was written and published. This allows for extension mechanisms that can discover and load plugins, for instance.</p> |
3,298,763 | Maven: Customize web.xml of web-app project | <p>I have a web application Maven project, and I want to customize the web.xml file depending on the Profile that is running. I am using the Maven-War-plugin, which allows me to define a "resources" directory, where the files may be filtered. However, filtering alone is not sufficient for me.</p>
<p>In more detail, I want to <strong>include (or exclude)</strong> the whole section on security, depending on the profile I an running. This is the part:</p>
<pre class="lang-xml prettyprint-override"><code>....
....
<security-constraint>
<web-resource-collection>
<web-resource-name>protected</web-resource-name>
<url-pattern>/pages/*.xhtml</url-pattern>
<url-pattern>/pages/*.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>*</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>${web.modules.auth.type}</auth-method>
<realm-name>MyRealm</realm-name>
</login-config>
<security-constraint>
....
....
</code></pre>
<p>If this is not done easily, is there a way to have two web.xml files and select the appropriate one depending on the profile?</p> | 3,298,876 | 7 | 0 | null | 2010-07-21 11:36:43.81 UTC | 24 | 2019-08-28 20:03:37.89 UTC | 2013-09-05 09:12:29.163 UTC | null | 563,970 | null | 125,713 | null | 1 | 56 | java|web-applications|maven-2|profile|web.xml | 69,450 | <blockquote>
<p>is there a way to have two web.xml files and select the appropriate one depending on the profile?</p>
</blockquote>
<p>Yes, within each profile you can add a configuration of the <a href="http://maven.apache.org/plugins/maven-war-plugin/" rel="noreferrer"><code>maven-war-plugin</code></a> and configure each to point at a different <code>web.xml</code>.</p>
<pre><code><profiles>
<profile>
<id>profile1</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>/path/to/webXml1</webXml>
</configuration>
</plugin>
...
</code></pre>
<p>As an alternative to having to specify the <a href="http://maven.apache.org/plugins/maven-war-plugin/" rel="noreferrer"><code>maven-war-plugin</code></a> configuration in each profile, you can supply a default configuration in the main section of the POM and then just override it for specific profiles.</p>
<p>Or to be even simpler, in the main <code><build><plugins></code> of your POM, use a property to refer to the <code>webXml</code> attribute and then just change it's value in different profiles</p>
<pre><code><properties>
<webXmlPath>path/to/default/webXml</webXmlPath>
</properties>
<profiles>
<profile>
<id>profile1</id>
<properties>
<webXmlPath>path/to/custom/webXml</webXmlPath>
</properties>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>${webXmlPath}</webXml>
</configuration>
</plugin>
...
</code></pre> |
3,323,230 | How can I start ipython running a script? | <p>My use case is I want to initialize some functions in a file and then start up ipython with those functions defined. Is there any way to do something like this?</p>
<pre><code>ipython --run_script=myscript.py
</code></pre> | 3,323,899 | 7 | 0 | null | 2010-07-24 00:14:12.09 UTC | 7 | 2021-08-27 19:27:15.767 UTC | 2021-08-27 19:25:44.157 UTC | null | 4,518,341 | null | 101,126 | null | 1 | 67 | python|ipython | 42,637 | <p>Per <a href="http://ipython.org/ipython-doc/stable/interactive/reference.html" rel="nofollow noreferrer">the docs</a>, it's trivial:</p>
<blockquote>
<p>You start IPython with the command:</p>
<pre><code>$ ipython [options] files
</code></pre>
<p>If invoked with no options, it
executes all the files listed in
sequence and drops you into the
interpreter while still acknowledging
any options you may have set in your
<code>ipythonrc</code> file. This behavior is
different from standard Python, which
when called as <code>python -i</code> will only
execute one file and ignore your
configuration setup.</p>
</blockquote>
<p>So, just use <code>ipython myfile.py</code>... and there you are!-)</p> |
3,344,341 | UIButton inside a view that has a UITapGestureRecognizer | <p>I have view with a <code>UITapGestureRecognizer</code>. So when I tap on the view another view appears above this view. This new view has three buttons. When I now press on one of these buttons I don't get the buttons action, I only get the tap gesture action. So I'm not able to use these buttons anymore. What can I do to get the events through to these buttons? The weird thing is that the buttons still get highlighted.</p>
<p>I can't just remove the UITapGestureRecognizer after I received it's tap. Because with it the new view can also be removed. Means I want a <strong>behavior like the fullscreen vide controls</strong>.</p> | 3,348,532 | 12 | 0 | null | 2010-07-27 13:54:32.117 UTC | 90 | 2020-01-17 06:02:34.69 UTC | 2019-05-15 05:58:10.42 UTC | null | 2,272,431 | null | 186,295 | null | 1 | 195 | ios|objective-c|iphone|cocoa-touch|uitapgesturerecognizer | 78,272 | <p>You can set your controller or view (whichever creates the gesture recognizer) as the delegate of the <code>UITapGestureRecognizer</code>. Then in the delegate you can implement <code>-gestureRecognizer:shouldReceiveTouch:</code>. In your implementation you can test if the touch belongs to your new subview, and if it does, instruct the gesture recognizer to ignore it. Something like the following:</p>
<pre><code>- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
// test if our control subview is on-screen
if (self.controlSubview.superview != nil) {
if ([touch.view isDescendantOfView:self.controlSubview]) {
// we touched our control surface
return NO; // ignore the touch
}
}
return YES; // handle the touch
}
</code></pre> |
3,538,021 | Why do we use Base64? | <p><a href="http://en.wikipedia.org/wiki/Base64" rel="noreferrer">Wikipedia</a> says</p>
<blockquote>
<p>Base64 encoding schemes are commonly used when there is a need to encode binary data that needs be stored and transferred over media that are designed to deal with textual data. This is to ensure that the data remains intact without modification during transport.</p>
</blockquote>
<p>But is it not that data is always stored/transmitted in binary because the memory that our machines have store binary and it just depends how you interpret it? So, whether you encode the bit pattern <code>010011010110000101101110</code> as <code>Man</code> in ASCII or as <code>TWFu</code> in Base64, you are eventually going to store the same bit pattern.</p>
<p><strong>If the ultimate encoding is in terms of zeros and ones and every machine and media can deal with them, how does it matter if the data is represented as ASCII or Base64?</strong></p>
<p>What does it mean "media that are designed to deal with textual data"? They can deal with binary => they can deal with anything.</p>
<hr>
<p>Thanks everyone, I think I understand now.</p>
<p>When we send over data, we cannot be sure that the data would be interpreted in the same format as we intended it to be. So, we send over data coded in some format (like Base64) that both parties understand. That way even if sender and receiver interpret same things differently, but because they agree on the coded format, the data will not get interpreted wrongly.</p>
<p>From <a href="https://stackoverflow.com/questions/3538021/why-do-we-use-base64/3538079#3538079">Mark Byers example</a></p>
<p>If I want to send </p>
<pre><code>Hello
world!
</code></pre>
<p>One way is to send it in ASCII like </p>
<pre><code>72 101 108 108 111 10 119 111 114 108 100 33
</code></pre>
<p>But byte 10 might not be interpreted correctly as a newline at the other end. So, we use a subset of ASCII to encode it like this</p>
<pre><code>83 71 86 115 98 71 56 115 67 110 100 118 99 109 120 107 73 61 61
</code></pre>
<p>which at the cost of more data transferred for the same amount of information ensures that the receiver can decode the data in the intended way, even if the receiver happens to have different interpretations for the rest of the character set.</p> | 3,538,079 | 13 | 8 | null | 2010-08-21 15:21:08.513 UTC | 192 | 2021-12-23 08:57:51.63 UTC | 2017-09-11 10:02:20.123 UTC | null | 6,998,123 | null | 113,124 | null | 1 | 408 | algorithm|character-encoding|binary|ascii|base64 | 135,877 | <p>Your first mistake is thinking that ASCII encoding and Base64 encoding are interchangeable. They are not. They are used for different purposes.</p>
<ul>
<li>When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes.</li>
<li>When you encode data in Base64, you start with a sequence of bytes and convert it to a text string.</li>
</ul>
<p>To understand why Base64 was necessary in the first place we need a little history of computing.</p>
<hr />
<p>Computers communicate in binary - 0s and 1s - but people typically want to communicate with more rich forms data such as text or images. In order to transfer this data between computers it first has to be encoded into 0s and 1s, sent, then decoded again. To take text as an example - there are many different ways to perform this encoding. It would be much simpler if we could all agree on a single encoding, but sadly this is not the case.</p>
<p>Originally a lot of different encodings were created (e.g. <a href="http://en.wikipedia.org/wiki/Baudot_code" rel="noreferrer">Baudot code</a>) which used a different number of bits per character until eventually ASCII became a standard with 7 bits per character. However most computers store binary data in bytes consisting of 8 bits each so <a href="http://en.wikipedia.org/wiki/ASCII" rel="noreferrer">ASCII</a> is unsuitable for tranferring this type of data. Some systems would even wipe the most significant bit. Furthermore the difference in line ending encodings across systems mean that the ASCII character 10 and 13 were also sometimes modified.</p>
<p>To solve these problems <a href="http://en.wikipedia.org/wiki/Base64" rel="noreferrer">Base64</a> encoding was introduced. This allows you to encode arbitrary bytes to bytes which are known to be safe to send without getting corrupted (ASCII alphanumeric characters and a couple of symbols). The disadvantage is that encoding the message using Base64 increases its length - every 3 bytes of data is encoded to 4 ASCII characters.</p>
<p>To send text reliably you can <strong>first</strong> encode to bytes using a text encoding of your choice (for example UTF-8) and then <strong>afterwards</strong> Base64 encode the resulting binary data into a text string that is safe to send encoded as ASCII. The receiver will have to reverse this process to recover the original message. This of course requires that the receiver knows which encodings were used, and this information often needs to be sent separately.</p>
<p>Historically it has been used to encode binary data in email messages where the email server might modify line-endings. A more modern example is the use of Base64 encoding to <a href="http://www.sweeting.org/mark/blog/2005/07/12/base64-encoded-images-embedded-in-html" rel="noreferrer">embed image data directly in HTML source code</a>. Here it is necessary to encode the data to avoid characters like '<' and '>' being interpreted as tags.</p>
<hr />
<p>Here is a working example:</p>
<p>I wish to send a text message with two lines:</p>
<pre>
Hello
world!
</pre>
<p>If I send it as ASCII (or UTF-8) it will look like this:</p>
<pre><code>72 101 108 108 111 10 119 111 114 108 100 33
</code></pre>
<p>The byte 10 is corrupted in some systems so we can base 64 encode these bytes as a Base64 string:</p>
<pre>SGVsbG8Kd29ybGQh</pre>
<p>Which when encoded using ASCII looks like this:</p>
<pre><code>83 71 86 115 98 71 56 75 100 50 57 121 98 71 81 104
</code></pre>
<p>All the bytes here are known safe bytes, so there is very little chance that any system will corrupt this message. I can send this instead of my original message and let the receiver reverse the process to recover the original message.</p> |
3,853,767 | Maximum request length exceeded. | <p>I am getting the error <strong>Maximum request length exceeded</strong> when I am trying to upload a video in my site. </p>
<p>How do I fix this?</p> | 3,853,785 | 15 | 0 | null | 2010-10-04 08:48:28.683 UTC | 296 | 2020-11-23 17:16:36.43 UTC | 2017-11-20 17:29:08.46 UTC | null | 5,291,477 | null | 164,002 | null | 1 | 1,156 | asp.net|iis|file-upload | 904,235 | <p>If you are using IIS for hosting your application, then the default upload file size is 4MB. To increase it, please use this below section in your <code>web.config</code> -</p>
<pre><code><configuration>
<system.web>
<httpRuntime maxRequestLength="1048576" />
</system.web>
</configuration>
</code></pre>
<p>For IIS7 and above, you also need to add the lines below:</p>
<pre><code> <system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
</code></pre>
<p><strong>Note</strong>: </p>
<ul>
<li><strong><code>maxRequestLength</code></strong> is measured in <strong>kilobytes</strong></li>
<li><strong><code>maxAllowedContentLength</code></strong> is measured in <strong>bytes</strong> </li>
</ul>
<p>which is why the values differ in this config example. (Both are equivalent to 1 GB.)</p> |
3,462,784 | check if a string matches an IP address pattern in python? | <p>What is the fastest way to check if a string matches a certain pattern? Is regex the best way?</p>
<p>For example, I have a bunch of strings and want to check each one to see if they are a valid IP address (valid in this case meaning correct format), is the fastest way to do this using regex? Or is there something faster with like string formatting or something. </p>
<p>Something like this is what I have been doing so far:</p>
<pre><code>for st in strs:
if re.match('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', st) != None:
print 'IP!'
</code></pre> | 3,462,840 | 20 | 0 | null | 2010-08-11 20:59:17.42 UTC | 19 | 2022-09-21 09:51:58.417 UTC | 2016-07-30 20:00:33.31 UTC | null | 620,444 | null | 417,722 | null | 1 | 57 | python | 128,277 | <p><strong>update</strong>: The original answer bellow is good for 2011, but since 2012, one is likely better using Python's <a href="https://docs.python.org/3/library/ipaddress.html" rel="noreferrer"><strong>ipaddress</strong> stdlib module</a> - besides checking IP validity for IPv4 and IPv6, it can do a lot of other things as well.<strong><code></update></code></strong></p>
<p>It looks like you are trying to <a href="https://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python">validate IP addresses</a>. A regular expression is probably not the best tool for this.</p>
<p>If you want to accept all valid IP addresses (including some addresses that you probably didn't even know were valid) then you can use <a href="http://pypi.python.org/pypi/IPy/" rel="noreferrer">IPy</a> <a href="https://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python/330107#330107">(Source)</a>:</p>
<pre><code>from IPy import IP
IP('127.0.0.1')
</code></pre>
<p>If the IP address is invalid it will throw an exception.</p>
<p>Or you could use <code>socket</code> <a href="https://stackoverflow.com/questions/319279/how-to-validate-ip-address-in-python/319298#319298">(Source)</a>:</p>
<pre><code>import socket
try:
socket.inet_aton(addr)
# legal
except socket.error:
# Not legal
</code></pre>
<p>If you really want to only match IPv4 with 4 decimal parts then you can split on dot and test that each part is an integer between 0 and 255.</p>
<pre><code>def validate_ip(s):
a = s.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True
</code></pre>
<p>Note that your regular expression doesn't do this extra check. It would accept <code>999.999.999.999</code> as a valid address.</p> |
8,265,693 | How to get ViewFlipper's current child position | <p>I have added a bunch of images to a ViewFlipper and now I am performing an onClick event in the flipper. For this I would like to know the current child position so that I can perform some operations in an array. Is there anyway to find out the position of the current child. </p> | 8,266,102 | 4 | 0 | null | 2011-11-25 06:57:05.667 UTC | 3 | 2013-07-09 10:48:18.52 UTC | null | null | null | null | 603,744 | null | 1 | 31 | android | 19,563 | <p>Use this to get the current Child position:</p>
<pre><code>flipper.getDisplayedChild();
</code></pre>
<p>And this to set child number to view:</p>
<pre><code>flipper.setDisplayedChild(8);
</code></pre> |
8,118,802 | What exactly does ++array[s.charAt(i) - 'A'] do? | <pre><code>for (int i = 0; i < s.length(); ++i)
{
if (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
{
++array[s.charAt(i) - 'A'];
}
}
</code></pre>
<p>I understand the For loop. the s.length() is 26, int[26] to be exact. so this loop will occur 26 times, 0-25. If the Char at i, 0-25 is between or are A-Z it will then proceed to <code>++array[s.charAt(i) - 'A'];</code> From what i see it adds array once per loop, or adds the value of array once per loop, for the String at char i so the first one would be 0 second would be 2, because arrays start at 0. so adding an array at location of <code>i -'A'</code> is where i get confused.</p> | 8,118,814 | 5 | 0 | null | 2011-11-14 08:06:00.327 UTC | 8 | 2020-09-08 23:53:16.95 UTC | 2011-11-14 08:09:02.65 UTC | null | 521,799 | null | 951,563 | null | 1 | 7 | java|arrays|string|char | 24,623 | <p>The statement <code>++array[s.charAt(i) - 'A'];</code> is incrementing the value in the array indexed by <code>s.charAt(i) - 'A'</code>.</p>
<p>What this loop does is that it counts up the number of occurrences of each letter in <code>s</code>.</p>
<p>The reason for <code>- 'A'</code>, is that it "shifts" the ascii/unicode value so that <code>A - Z</code> have values 0 - 25. And are thus more suitable as an array index.</p> |
8,168,578 | Break inner foreach loop and continue outer foreach loop | <p>If I have a nested foreach loop how do I do break the inner loop and tell the outer to continue at that point without doing any other code below the inner loop?</p>
<pre><code>foreach(var item in items)
{
foreach(var otheritem in otheritems)
{
if (!double.TryParse(otheritem))
{
//break inner loop
//continue outer loop so we never get to DoStuff()
}
}
DoStuff();
}
</code></pre> | 8,168,613 | 8 | 1 | null | 2011-11-17 14:17:10.76 UTC | 2 | 2016-12-15 22:36:14.91 UTC | null | null | null | null | 84,539 | null | 1 | 35 | c#|.net|c#-4.0|.net-4.0 | 41,050 | <p>How about using a flag?</p>
<pre><code>foreach(var item in items)
{
bool flag = false;
foreach(var otheritem in otheritems)
{
if (!double.TryParse(otheritem))
{
flag = true;
break;
}
}
if(flag) continue;
DoStuff();
}
</code></pre> |
7,992,034 | SVN upgrade working copy | <p>I cannot do a SVN commit. I get this error:</p>
<pre><code>org.apache.subversion.javahl.ClientException: The working copy needs to be upgraded
svn: Working copy 'C:\.... is too old (format 10, created by Subversion 1.6)
</code></pre>
<p>How can it be fixed?</p> | 7,992,072 | 10 | 0 | null | 2011-11-03 08:37:09.02 UTC | 19 | 2018-03-18 05:03:17.197 UTC | 2018-03-18 05:03:17.197 UTC | null | 322,020 | null | 810,430 | null | 1 | 136 | svn|version|working-copy | 241,053 | <p>You have to upgrade your subversion client to at least 1.7.</p>
<p>With the command line client, you have to manually upgrade your working copy format by issuing the command <code>svn upgrade</code>:</p>
<blockquote>
<p><strong>Upgrading the Working Copy</strong></p>
<p>Subversion 1.7 introduces substantial changes to the working copy
format. In previous releases of Subversion, Subversion would
automatically update the working copy to the new format when a write
operation was performed. Subversion 1.7, however, will make this a
manual step. Before using Subversion 1.7 with their working copies,
users will be required to run a new command, <code>svn upgrade</code> to update the
metadata to the new format. This command may take a while, and for
some users, it may be more practical to simply checkout a new working
copy.<br>
— <a href="http://subversion.apache.org/docs/release-notes/1.7.html#wc-upgrade">Subversion 1.7 Release Notes</a></p>
</blockquote>
<p>TortoiseSVN will perform the working copy upgrade with the next write operation:</p>
<blockquote>
<p><strong>Upgrading the Working Copy</strong></p>
<p>Subversion 1.7 introduces substantial changes to the working copy
format. In previous releases, Subversion would automatically update
the working copy to the new format when a write operation was
performed. Subversion 1.7, however, will make this a manual step.</p>
<p>Before you can use an existing working copy with TortoiseSVN 1.7, you
have to upgrade the format first. If you right-click on an old working
copy, TortoiseSVN only shows you one command in the context menu:
Upgrade working copy.<br>
— <a href="http://tortoisesvn.net/tsvn_1.7_releasenotes.html">TortoiseSVN 1.7 Release notes</a></p>
</blockquote> |
8,297,215 | Spring RestTemplate GET with parameters | <p>I have to make a <code>REST</code> call that includes custom headers and query parameters. I set my <code>HttpEntity</code> with just the headers (no body), and I use the <code>RestTemplate.exchange()</code> method as follows:</p>
<pre><code>HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/json");
Map<String, String> params = new HashMap<String, String>();
params.put("msisdn", msisdn);
params.put("email", email);
params.put("clientVersion", clientVersion);
params.put("clientType", clientType);
params.put("issuerName", issuerName);
params.put("applicationName", applicationName);
HttpEntity entity = new HttpEntity(headers);
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, params);
</code></pre>
<p>This fails at the client end with the <code>dispatcher servlet</code> being unable to resolve the request to a handler. Having debugged it, it looks like the request parameters are not being sent.</p>
<p>When I do a an exchange with a <code>POST</code> using a request body and no query parameters it works just fine.</p>
<p>Does anyone have any ideas?</p> | 8,313,055 | 15 | 0 | null | 2011-11-28 14:21:39.02 UTC | 99 | 2022-07-17 12:01:27.057 UTC | 2018-11-13 15:04:47.167 UTC | null | 6,183,652 | null | 693,815 | null | 1 | 363 | java|spring|rest | 652,454 | <p>OK, so I'm being an idiot and I'm confusing query parameters with url parameters. I was kinda hoping there would be a nicer way to populate my query parameters rather than an ugly concatenated String but there we are. It's simply a case of build the URL with the correct parameters. If you pass it as a String Spring will also take care of the encoding for you.</p> |
4,579,849 | port an iOS (iPhone) app to mac? | <p>Is there a preferred way to go about this?</p>
<p>The app in question is not too large . . . single-player game that I wrote over the course of a couple of months.</p>
<p>EDIT: I should add that I have no experience with mac development . . . outside of what comes naturally with being an iOS developer.</p>
<p>EDIT: Classes heavily used in the game: subclasses of NSObject, UIView, and UIViewController. I don't know much about NSView, but I'm pretty sure all the UIView stuff will work in that class. Also some use of UITableViewController. I do also have Game Center, but I can leave that part out for now. There is no multi-touch.</p>
<p>EDIT: My graphics is all stuff that is in the QuartzCore and CoreGraphics frameworks. I do have a moderate view hierarchy.</p>
<p>EDIT: If you are doing such a port, you may also be interested in the issue of <a href="https://stackoverflow.com/questions/4581556/porting-an-ios-app-to-mac-how-to-handle-memory-management">memory management</a></p> | 4,580,158 | 5 | 2 | null | 2011-01-02 18:40:40.273 UTC | 8 | 2016-11-18 12:43:24.197 UTC | 2017-05-23 11:59:55.387 UTC | null | -1 | null | 246,568 | null | 1 | 37 | iphone|macos|ios|port | 14,116 | <ol>
<li><p><strong><em>There's no easy way.</em></strong> It's that simple. Depressingly, you simply have to become good at programming the Mac.</p></li>
<li><p><em>"I'm pretty sure all the UIView stuff will work in that class"</em> -- unfortunately, no. Everything is different that enough you have to work hard.</p></li>
</ol>
<p>It's not a fun gig. Make sure you really, really think it's worth it financially.</p>
<p>Apart from anything else, be aware of the "sibling views don't work on OSX" problem if you stack up a lot of views in your iOS app. Essentially, you will have to change to using layers (instead of simply views) on the Mac if you rely on nested hierarchies of views here and there on the phone!</p>
<p>Click this link: <a href="https://stackoverflow.com/questions/466297/is-there-a-proper-way-to-handle-overlapping-nsview-siblings/3739007#3739007">Is there a proper way to handle overlapping NSView siblings?</a> for the gory details on that particular problem!</p> |
4,826,404 | Getting first value from map in C++ | <p>I'm using <code>map</code> in C++. Suppose I have 10 values in the <code>map</code> and I want only the first one. How do I get it?</p>
<p>Thanks.</p> | 4,826,416 | 5 | 0 | null | 2011-01-28 08:55:07.867 UTC | 14 | 2011-01-28 09:16:45.383 UTC | 2011-01-28 09:00:47.617 UTC | null | 501,557 | null | 554,250 | null | 1 | 85 | c++|map | 137,787 | <p>A map will not keep insertion order. Use <code>*(myMap.begin())</code> to get the value of the first pair (the one with the smallest key when ordered).</p>
<p>You could also do <code>myMap.begin()->first</code> to get the key and <code>myMap.begin()->second</code> to get the value.</p> |
4,548,684 | How to get the seconds since epoch from the time + date output of gmtime()? | <p>How do you do reverse <code>gmtime()</code>, where you put the time + date and get the number of seconds?</p>
<p>I have strings like <code>'Jul 9, 2009 @ 20:02:58 UTC'</code>, and I want to get back the number of seconds between the epoch and July 9, 2009.</p>
<p>I have tried <code>time.strftime</code> but I don't know how to use it properly, or if it is the correct command to use.</p> | 4,548,711 | 6 | 0 | null | 2010-12-28 19:08:46.39 UTC | 30 | 2022-03-23 20:16:26.13 UTC | 2018-01-14 03:41:42.42 UTC | null | 355,230 | null | 341,683 | null | 1 | 209 | python|datetime|time | 408,144 | <p>If you got here because a search engine told you this is how to get the Unix timestamp, stop reading this answer. Scroll up one.</p>
<p>If you want to reverse <code>time.gmtime()</code>, you want <code>calendar.timegm()</code>.</p>
<pre><code>>>> calendar.timegm(time.gmtime())
1293581619.0
</code></pre>
<p>You can turn your string into a time tuple with <code>time.strptime()</code>, which returns a time tuple that you can pass to <code>calendar.timegm()</code>:</p>
<pre><code>>>> import calendar
>>> import time
>>> calendar.timegm(time.strptime('Jul 9, 2009 @ 20:02:58 UTC', '%b %d, %Y @ %H:%M:%S UTC'))
1247169778
</code></pre>
<p>More information about calendar module <a href="https://docs.python.org/2/library/calendar.html" rel="nofollow noreferrer">here</a></p> |
4,506,019 | Rails 3: guides.rubyonrails.org in PDF? | <p>Where to find Rails 3 guides in PDF to read offline?</p>
<p>Thanks</p> | 4,506,034 | 8 | 1 | null | 2010-12-22 03:49:38.617 UTC | 12 | 2018-05-07 16:12:27.973 UTC | null | null | null | null | 435,951 | null | 1 | 16 | ruby-on-rails|ruby-on-rails-3 | 9,715 | <p>You can't get them in PDF, but you can get them in HTML form by running these commands:</p>
<pre><code>git clone git://github.com/rails/rails.git
cd rails
git checkout origin/3-2-stable -b 3-2-stable
cd railties/guides
ruby rails_guides.rb
cd output
open index.html
</code></pre>
<p>When these commands have finished you should be in the <code>railties/guides/output</code> folder which contains the HTML versions of the guides that were just generated with <code>ruby rails_guides.rb</code>, and if you're on a decent operating system then you'll see the homepage in your default browser.</p> |
4,096,863 | How to get and set the current web page scroll position? | <p>How can I get and set the current web page scroll position?</p>
<p>I have a long form which needs to be refreshed based on user actions/input. When this happens, the page resets to the very top, which is annoying to the users, because they have to scroll back down to the point they were at.</p>
<p>If I could capture the current scroll position (in a hidden input) before the page reloads, I could then set it back after it reloads.</p> | 4,096,891 | 8 | 1 | null | 2010-11-04 12:56:29.09 UTC | 31 | 2022-08-18 10:11:27.053 UTC | 2014-06-11 14:32:22.347 UTC | null | 447,356 | null | 405,921 | null | 1 | 176 | javascript|html | 262,461 | <p>You're looking for the <code>document.documentElement.scrollTop</code> property.</p> |
14,831,255 | How does local initialization with Parallel ForEach work? | <p>I am unsure about the use of the local init function in Parallel.ForEach, as described in the msdn article: <a href="http://msdn.microsoft.com/en-us/library/dd997393.aspx">http://msdn.microsoft.com/en-us/library/dd997393.aspx</a></p>
<pre><code>Parallel.ForEach<int, long>(nums, // source collection
() => 0, // method to initialize the local variable
(j, loop, subtotal) => // method invoked by the loop on each iteration
{
subtotal += nums[j]; //modify local variable
return subtotal; // value to be passed to next iteration
},...
</code></pre>
<p>How does () => 0 initialize anything? What's the name of the variable and how can I use it in the loop logic?</p> | 31,044,246 | 4 | 1 | null | 2013-02-12 11:16:18.717 UTC | 9 | 2018-02-06 10:58:38.01 UTC | null | null | null | null | 1,520,641 | null | 1 | 15 | c#|task-parallel-library | 12,791 | <p>With reference to the <a href="https://msdn.microsoft.com/en-us/library/dd991486(v=vs.110).aspx" rel="noreferrer">following overload</a> of the <code>Parallel.ForEach</code> static extension method:</p>
<pre><code>public static ParallelLoopResult ForEach<TSource, TLocal>(
IEnumerable<TSource> source,
Func<TLocal> localInit,
Func<TSource, ParallelLoopState, TLocal, TLocal> taskBody,
Action<TLocal> localFinally
)
</code></pre>
<p><strong>In your specific example</strong></p>
<p>The line:</p>
<pre><code>() => 0, // method to initialize the local variable
</code></pre>
<p>is simply a lambda (anonymous function) which will return the constant integer zero. This lambda is passed as the <code>localInit</code> parameter to <code>Parallel.ForEach</code> - since the lambda returns an integer, it has type <code>Func<int></code> and type <code>TLocal</code> can be inferred as <code>int</code> by the compiler (similarly, <code>TSource</code> can be inferred from the type of the collection passed as parameter <code>source</code>)</p>
<p>The return value (0) is then passed as the 3rd parameter (named <code>subtotal</code>) to the <code>taskBody</code> <code>Func</code>. This (0) is used the initial seed for the body loop:</p>
<pre><code>(j, loop, subtotal) =>
{
subtotal += nums[j]; //modify local variable (Bad idea, see comment)
return subtotal; // value to be passed to next iteration
}
</code></pre>
<p>This second lambda (passed to <code>taskBody</code>) is called N times, where N is the number of items allocated to this task by the TPL partitioner.</p>
<p>Each subsequent call to the second <code>taskBody</code> lambda will pass the new value of <code>subTotal</code>, effectively calculating a running <strong>partial</strong> total, for this Task. After all the items assigned to this task have been added, the third and last, <code>localFinally</code> function parameter will be called, again, passing the final value of the <code>subtotal</code> returned from <code>taskBody</code>. Because several such tasks will be operating in parallel, there will also need to be a final step to add up all the partial totals into the final 'grand' total. However, because multiple concurrent tasks (on different Threads) could be contending for the <code>grandTotal</code> variable, it is important that changes to it are done in a thread-safe manner.</p>
<p>(I've changed names of the MSDN variables to make it more clear)</p>
<pre><code>long grandTotal = 0;
Parallel.ForEach(nums, // source collection
() => 0, // method to initialize the local variable
(j, loop, subtotal) => // method invoked by the loop on each iteration
subtotal + nums[j], // value to be passed to next iteration subtotal
// The final value of subtotal is passed to the localFinally function parameter
(subtotal) => Interlocked.Add(ref grandTotal, subtotal)
</code></pre>
<p><em>In the MS Example, modification of the parameter subtotal inside the task body is a poor practice, and unnecessary. i.e. The code <code>subtotal += nums[j]; return subtotal;</code> would be better as just <code>return subtotal + nums[j];</code> which could be abbreviated to the lambda shorthand projection <code>(j, loop, subtotal) => subtotal + nums[j]</code></em></p>
<p><strong>In General</strong></p>
<p>The <code>localInit / body / localFinally</code> overloads of <a href="https://msdn.microsoft.com/en-us/library/dd991486(v=vs.110).aspx" rel="noreferrer">Parallel.For / Parallel.ForEach</a> allow <em>once-per task</em> initialization and cleanup code to be run, before, and after (respectively) the <code>taskBody</code> iterations are performed by the Task.</p>
<p>(Noting the For range / Enumerable passed to the parallel <code>For</code> / <code>Foreach</code> will be partitioned into batches of <code>IEnumerable<></code>, each of which will be allocated a Task)</p>
<p>In <strong>each Task</strong>, <code>localInit</code> will be called once, the <code>body</code> code will be repeatedly invoked, once per item in batch (<code>0..N</code> times), and <code>localFinally</code> will be called once upon completion.</p>
<p>In addition, you can pass any state required for the duration of the task (i.e. to the <code>taskBody</code> and <code>localFinally</code> delegates) via a generic <code>TLocal</code> return value from the <code>localInit Func</code> - I've called this variable <code>taskLocals</code> below. </p>
<p><strong>Common uses of "localInit":</strong></p>
<ul>
<li>Creating and initializing expensive resources needed by the loop body, like a database connection or a web service connection.</li>
<li>Keeping Task-Local variables to hold (uncontended) running totals or collections</li>
<li>If you need to return multiple objects from <code>localInit</code> to the <code>taskBody</code> and <code>localFinally</code>, you can make use of a strongly typed class, a <code>Tuple<,,></code> or, if you use only lambdas for the <code>localInit / taskBody / localFinally</code>, you can also pass data via an anonymous class. Note if you use the return from <code>localInit</code> to share a reference type among multiple tasks, that you will need to consider thread safety on this object - immutability is preferable.</li>
</ul>
<p><strong>Common uses of the "localFinally" Action:</strong></p>
<ul>
<li>To release resources such as <code>IDisposables</code> used in the <code>taskLocals</code> (e.g. database connections, file handles, web service clients, etc)</li>
<li>To aggregate / combine / reduce the work done by each task back into shared variable(s). These shared variables will be contended, so thread safety is a concern:
<ul>
<li>e.g. <code>Interlocked.Increment</code> on primitive types like integers</li>
<li><code>lock</code> or similar will be required for write operations</li>
<li>Make use of the <a href="https://msdn.microsoft.com/en-us/library/system.collections.concurrent(v=vs.110).aspx" rel="noreferrer">concurrent collections</a> to save time and effort.</li>
</ul></li>
</ul>
<p>The <code>taskBody</code> is the <code>tight</code> part of the loop operation - you'll want to optimize this for performance.</p>
<p>This is all best summarized with a commented example:</p>
<pre><code>public void MyParallelizedMethod()
{
// Shared variable. Not thread safe
var itemCount = 0;
Parallel.For(myEnumerable,
// localInit - called once per Task.
() =>
{
// Local `task` variables have no contention
// since each Task can never run by multiple threads concurrently
var sqlConnection = new SqlConnection("connstring...");
sqlConnection.Open();
// This is the `task local` state we wish to carry for the duration of the task
return new
{
Conn = sqlConnection,
RunningTotal = 0
}
},
// Task Body. Invoked once per item in the batch assigned to this task
(item, loopState, taskLocals) =>
{
// ... Do some fancy Sql work here on our task's independent connection
using(var command = taskLocals.Conn.CreateCommand())
using(var reader = command.ExecuteReader(...))
{
if (reader.Read())
{
// No contention for `taskLocal`
taskLocals.RunningTotal += Convert.ToInt32(reader["countOfItems"]);
}
}
// The same type of our `taskLocal` param must be returned from the body
return taskLocals;
},
// LocalFinally called once per Task after body completes
// Also takes the taskLocal
(taskLocals) =>
{
// Any cleanup work on our Task Locals (as you would do in a `finally` scope)
if (taskLocals.Conn != null)
taskLocals.Conn.Dispose();
// Do any reduce / aggregate / synchronisation work.
// NB : There is contention here!
Interlocked.Add(ref itemCount, taskLocals.RunningTotal);
}
</code></pre>
<p>And more examples:</p>
<p><a href="https://stackoverflow.com/a/31036093/314291">Example of per-Task uncontended dictionaries</a></p>
<p><a href="https://stackoverflow.com/questions/27774265/c-sharp-multiple-parallel-inserts-in-database">Example of per-Task database connections</a></p> |
14,437,881 | Will Segoe UI work on Mac? | <p>Is Segoe UI font built into the browser? If my visitors are viewing from Mac, will it work properly or do I have to set the CSS url for that? My designer says it will work only when we set the URL, however I removed the </p>
<pre><code>@font-face
{
font-family: "Segoe UI";
src: url("fonts/Segoe UI.ttf") format("truetype");
font-style: normal;
font-weight: normal;
}
</code></pre>
<p>and it still works atleast on Windows 7. I don't have Mac though, to test.</p> | 14,437,958 | 4 | 3 | null | 2013-01-21 11:43:27.97 UTC | 1 | 2021-05-27 12:24:15.1 UTC | 2013-03-07 08:01:27.743 UTC | null | 918,414 | null | 1,323,697 | null | 1 | 16 | html|css|fonts | 41,778 | <p>It will work on any computer with Office 2007, 2010, Vista or 7:</p>
<blockquote>
<p>The Segoe UI font family can be obtained as part of Microsoft Office 2007, Microsoft Office 2010, Windows Vista or Windows 7. </p>
</blockquote>
<p>Will also work on XP if the user has downloaded a Windows Live package:</p>
<blockquote>
<p>Segoe UI is installed into Windows XP if the user installs Windows Live Messenger, or Windows Live Mail</p>
</blockquote>
<p><a href="http://en.wikipedia.org/wiki/Segoe" rel="noreferrer">Source</a></p>
<p>For any computer that doesn't have the above, you will need to declare it with a <code>@font-face</code></p> |
2,749,733 | How to add libraries in C++? | <p>Yea this is a dumb question... However in both of my C++ classes we did not do this at all (except for native libraries: iostream, iomanip, etc.)... My question is can anyone provide a link that gives the general explanation of adding libraries to C++? </p>
<p>I do realize what what #include means; it's just I have no clue on the linker/directories in a C++ IDE.</p>
<p>So long question short; could I get a general explanation of terms used to link libraries in C++?</p>
<p>I'm using c::b w/ MinGW.</p> | 2,749,758 | 2 | 3 | null | 2010-05-01 11:28:08.9 UTC | 9 | 2012-11-01 04:49:41.717 UTC | null | null | null | anon235370 | null | null | 1 | 25 | c++|libraries | 53,465 | <p><a href="http://www.cs.cf.ac.uk/Dave/C/node3.html" rel="noreferrer">This</a> would probably interest you, but here is a short version:</p>
<p>When you assemble the <code>.cpp</code>, <code>.c</code> or whatever files, each translation unit (that is, each file) generates an object file. When creating the final executable, you combine all the object files into a single binary. For static libraries, you compile the static archive (<code>.a</code> or <code>.lib</code>) along with all the object files into the binary itself. For linking to dynamic shared objects (<code>.so</code> or <code>.dll</code>), the binary is created with calls to the global offset table and you inform the linker that you wish to link with the shared object and the operating system loader builds the proper image when you run the program.</p>
<h2>A general explanation of terms used to link libraries in C++</h2>
<p>Starting with...</p>
<p><strong>translation</strong> - This is where the high-level code (in C, Fortran or whatever) is translated into assembly code by translation unit. So, every <code>.cpp</code> file is internally translated to assembly for a specific architecture.</p>
<p><strong>assemble</strong> - Generates object files from the generated assembly. Object files are <em>almost</em> machine code, but they have a lot of "unresolved externals," which you can kind of think of as pointers to actual function definitions.</p>
<p><strong>linking</strong> - This takes all your object files and puts them into a coherent binary, be it a dynamic shared object or an executable. You need to tell the linker where it should find all those unresolved externals from the previous stage or they will show up as errors here.</p>
<p>Now the binary sits on disk, which is waits until...</p>
<p><strong>loader</strong> - The operating system loads a binary off of the disk, which contains all the information needed to build the program image. While the details are extremely platform specific, the loader is generally tasked with finding all the shared library references generated by the linker, loading those (recursively, since each DSO can have its own dependencies) and putting them into the memory space of the program.</p> |
30,176,604 | Nested forEach loop does not work | <p>I have some data that is in JSON object array. I'm trying to use nested forEach loops to extract the data. </p>
<p>The data is modeled like belo. There's multiple dataModels and multiple childNodes inside the dataModels. </p>
<pre><code>//this is what an example data looks like
dataModels[0].childNodes[0].appId
</code></pre>
<p>I am trying to do something like the following:</p>
<pre><code>dataModels.forEach(function(entry){
entry.forEach(function(childrenEntry){
console.log(childrenEntry.appId);
})
})
</code></pre>
<p>The above however does not work and it gives me an error saying that 'entry' is not a function. Is there a better way to achieve what I'm trying to do?</p> | 30,176,680 | 3 | 1 | null | 2015-05-11 20:00:35.963 UTC | 4 | 2016-08-27 10:08:12.127 UTC | 2015-05-11 20:03:02.64 UTC | null | 1,142,130 | null | 1,142,130 | null | 1 | 21 | javascript | 83,241 | <p>You are not targeting the array inside the <code>entry</code> object, you need to loop over the <code>childNodes</code> property in order to get the data you want. See example below.</p>
<pre><code>var dataModels = [];
dataModels[0] = {
childNodes: []
};
dataModels[0].childNodes[0] = {
appId: "foo"
};
dataModels.forEach(function(entry){
entry.childNodes.forEach(function(childrenEntry) { // was missing a )
console.log(childrenEntry.appId);
});
});
</code></pre>
<p><a href="http://jsfiddle.net/e2Lkaqff/" rel="noreferrer">JsFiddle demo</a></p> |
49,899,665 | How to print all elements of String array in Kotlin in a single line? | <p>This is my code</p>
<pre><code> fun main(args : Array<String>){
var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
//How do i print the elements using the print method in a single line?
}
</code></pre>
<p>In java i would do something like this</p>
<p><code>someList.forEach(java.lang.System.out::print);</code></p> | 49,899,833 | 6 | 3 | null | 2018-04-18 12:25:18.277 UTC | 3 | 2021-06-06 00:17:40.09 UTC | null | null | null | null | 6,642,927 | null | 1 | 40 | java|kotlin | 50,254 | <p><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html" rel="noreferrer"><code>Array</code></a> has a <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/for-each.html" rel="noreferrer"><code>forEach</code></a> method as well which can take a lambda:</p>
<pre><code>var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
someList.forEach { System.out.print(it) }
</code></pre>
<p>or a method reference:</p>
<pre><code>var someList : Array<String> = arrayOf("United","Chelsea","Liverpool")
someList.forEach(System.out::print)
</code></pre> |
38,762,368 | Embedded resource in .Net Core libraries | <p>I just have started looking into .Net Core, and I don't see classical resources and anything what looks like resources. In classical .Net class libraries I was able to add, for example, text filtes with some script to my project, than I can add these files to project's resources. After that I could easily use that by the following way:</p>
<pre><code>Connection.Execure(Properties.Resources.MySuperScript);
</code></pre>
<p>I see that there isn't such feature in .Net Core libraries, at least I don't see.
Is there an alternative in .Net Core to store some statical data as an embedded resource in libraries? And how to use that if it exists?</p> | 41,106,851 | 5 | 4 | null | 2016-08-04 08:36:03.603 UTC | 16 | 2022-01-19 20:08:57.107 UTC | 2017-09-01 08:47:40.47 UTC | null | 24,874 | null | 889,562 | null | 1 | 91 | c#|asp.net-core|.net-core | 99,794 | <p><strong>UPDATE:</strong></p>
<p>.NET Core 1.1 and later have dropped <code>project.json</code> and returned to <code>.csproj</code> files.
This changes Step 2, but not all that much. The necessary lines are very similar:</p>
<pre><code><ItemGroup>
<Content Remove="_fonts/OpenSans.ttf" />
<Content Remove="_fonts/OpenSans-Bold.ttf" />
<Content Remove="_fonts/OpenSans-Italic.ttf" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="_fonts/OpenSans.ttf" />
<EmbeddedResource Include="_fonts/OpenSans-Bold.ttf" />
<EmbeddedResource Include="_fonts/OpenSans-Italic.ttf" />
</ItemGroup>
</code></pre>
<p>There may be a similar <code>*.tff</code> form; unconfirmed.</p>
<p>Steps 1 and 3 are unchanged.</p>
<hr>
<p>To use embedded resources in .NET Core 1.0 project do the following:</p>
<ol>
<li><p>Add your embedded file(s) as usual.</p>
<p>Example: some FONT files on a directory named "_fonts"</p>
<p><a href="https://i.stack.imgur.com/AsJhg.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/AsJhg.jpg" alt="enter image description here"></a></p></li>
<li><p>Modify "project.json" to include the related resources.</p>
<p>In my case:</p>
<pre><code> "buildOptions": {
"embed": {
"include": [
"_fonts/*.ttf"
]
}
},
</code></pre></li>
<li><p>Access the embedded resource in code.</p>
<pre><code>var assembly = typeof(MyLibrary.MyClass).GetTypeInfo().Assembly;
Stream resource = assembly.GetManifestResourceStream("MyLibrary._fonts.OpenSans.ttf");
</code></pre>
<p>The key point is to use the right name on <a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.getmanifestresourcestream" rel="noreferrer"><code>GetManifestResourceStream</code></a> call. You have to use <code>[assembly name].[directory].[file name]</code>.</p></li>
</ol> |
44,335,456 | Angular/CLI -- auto reload doesn't happen | <p>I recently started working with Angular/CLI tool, I'm facing a problem while executing the file, that is when I run </p>
<pre><code>ng serve
</code></pre>
<p>then this command helps us in auto reloading the site when any changes are made in the source file but in my system it is not happening (i.e. site is not auto reloading and when I forcely reload the site then also it is not getting updated as per changes made in the source file).</p>
<p>The site is getting updated only when I terminate the "ng serve" command and again run the same command("ng serve") then only my site is getting updated.</p>
<p>So it becomes hard for me to terminate the server and connect the server, when ever the changes are made, so I request you people if any one know solution of this problem please help me out.</p> | 48,042,729 | 14 | 0 | null | 2017-06-02 14:21:35.483 UTC | 12 | 2022-08-12 16:29:09.783 UTC | 2017-06-02 18:38:53.613 UTC | null | 92,837 | Durga Abhist | 8,087,667 | null | 1 | 42 | angular-cli | 61,546 | <p>I also encountered the same problem a few days back in my linuxOS, and when I read about it, I found that this problem is heavily dependent on the system you use and the way you did your setup for angular-cli, both globally and locally.
So, after reading readme.md created by angular-cli for each project, I tried using <code>ng-build --watch</code> but the problem still couldn't be solved because by running this command it should work like <code>ng-serve</code> but it only build the app and doesn't even served it on <code>localhost:4200</code>.
then, after digging into the problem more deeper I found the problem, it was with my OS, I am using ubuntu, the <code>inotify/max_user_watches</code> value 8192, which I crossed, due to which it wasn't showing any changes made further.
So i used these-
<code>echo "fs.inotify.max_user_watches=524288" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p</code>
and it worked fine.</p>
<p>p.s. in the process i also tumbled upon a solution with these commands -
<code>rm -rf nodes_modules/</code> ->
<code>npm update</code> ->
<code>npm install</code>.
try this before doing above stated canges, if this works for you then you are well and good to go.</p> |
26,192,501 | How to use <md-icon> in Angular Material? | <p>I was wondering how to use Material's icons, as this is not working: </p>
<pre><code><material-icon icon = "/img/icons/ic_access_time_24px.svg"> </material-icon>
</code></pre>
<p>I guess there is a problem with the path given as parameter to the the icon attribute. I would like to know where this icon folder actually is?</p> | 26,206,694 | 9 | 0 | null | 2014-10-04 11:48:37.73 UTC | 37 | 2022-06-06 15:58:11.117 UTC | 2017-10-04 20:47:39.46 UTC | null | 1,007,939 | null | 1,531,173 | null | 1 | 102 | angularjs|material-design|angularjs-material | 124,377 | <p>As the other answers didn't address my concern I decided to write my own answer. </p>
<p>The path given in the icon attribute of the <code>md-icon</code> directive is the URL of a .png or .svg file lying somewhere in your static file directory. So you have to put the right path of that file in the icon attribute. p.s put the file in the right directory so that your server could serve it.</p>
<p>Remember <code>md-icon</code> is not like bootstrap icons. Currently they are merely a directive that shows a .svg file. </p>
<p><strong>Update</strong></p>
<p>Angular material design has changed a lot since this question was posted.</p>
<p>Now there are several ways to use <code>md-icon</code></p>
<p><strong><em>The first way is to use SVG icons.</em></strong></p>
<p><code><md-icon md-svg-src = '<url_of_an_image_file>'></md-icon></code></p>
<p>Example:</p>
<p><code><md-icon md-svg-src = '/static/img/android.svg'></md-icon></code></p>
<p>or </p>
<p><code><md-icon md-svg-src = '{{ getMyIcon() }}'></md-icon></code></p>
<p>:where <code>getMyIcon</code> is a method defined in <code>$scope</code>.</p>
<p>or
<code><md-icon md-svg-icon="social:android"></md-icon></code></p>
<p>to use this you have to the <code>$mdIconProvider</code> service to configure your application with svg iconsets.</p>
<pre><code>angular.module('appSvgIconSets', ['ngMaterial'])
.controller('DemoCtrl', function($scope) {})
.config(function($mdIconProvider) {
$mdIconProvider
.iconSet('social', 'img/icons/sets/social-icons.svg', 24)
.defaultIconSet('img/icons/sets/core-icons.svg', 24);
});
</code></pre>
<p><strong><em>The second way is to use font icons.</em></strong></p>
<p><code><md-icon md-font-icon="android" alt="android"></md-icon></code></p>
<p><code><md-icon md-font-icon="fa-magic" class="fa" alt="magic wand"></md-icon></code></p>
<p>prior to doing this you have to load the font library like this..</p>
<p><code><link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"></code></p>
<p>or use font icons with ligatures </p>
<p><code><md-icon md-font-library="material-icons">face</md-icon></code></p>
<p><code><md-icon md-font-library="material-icons">#xE87C;</md-icon></code></p>
<p><code><md-icon md-font-library="material-icons" class="md-light md-48">face</md-icon></code></p>
<p>For further details check our</p>
<p><a href="https://material.angularjs.org/latest/api/directive/mdIcon">Angular Material mdIcon Directive documentation</a></p>
<p><a href="https://material.angularjs.org/latest/api/service/$mdIcon">$mdIcon Service Documentation</a></p>
<p><a href="https://material.angularjs.org/latest/api/service/$mdIconProvider">$mdIconProvider Service Documentation</a> </p> |
38,691,454 | Is it a good idea to store data as keys in HashMap with empty/null values? | <p>I had originally written an <code>ArrayList</code> and stored unique values (usernames, i.e. <code>Strings</code>) in it. I later needed to use the <code>ArrayList</code> to search if a user existed in it. That's <code>O(n)</code> for the search.</p>
<p>My tech lead wanted me to change that to a <code>HashMap</code> and store the usernames as keys in the array and values as empty <code>Strings</code>.</p>
<p>So, in Java - </p>
<pre><code>hashmap.put("johndoe","");
</code></pre>
<p>I can see if this user exists later by running - </p>
<pre><code>hashmap.containsKey("johndoe");
</code></pre>
<p>This is <code>O(1)</code> right?</p>
<p>My lead said this was a more efficient way to do this and it made sense to me, but it just seemed a bit off to put null/empty as values in the hashmap and store elements in it as keys.</p>
<p>My question is, is this a good approach? The efficiency beats <code>ArrayList#contains</code> or an array search in general. It works.
My worry is, I haven't seen anyone else do this after a search. I may be missing an obvious issue somewhere but I can't see it.</p> | 38,691,482 | 2 | 8 | null | 2016-08-01 05:17:48.663 UTC | 2 | 2016-08-01 18:49:11.423 UTC | 2016-08-01 14:58:02.733 UTC | null | 3,745,896 | null | 3,627,023 | null | 1 | 63 | java|arrays|performance|hashmap|asymptotic-complexity | 6,197 | <p>Since you have a set of unique values, a <code>Set</code> is the appropriate data structure. You can put your values inside <code>HashSet</code>, an implementation of the <code>Set</code> interface.</p>
<blockquote>
<p>My lead said this was a more efficient way to do this and it made sense to me, but it just seemed a bit off to put null/empty as values in the hashmap and store elements in it as keys.</p>
</blockquote>
<p>The advice of the lead is flawed. <code>Map</code> is not the right abstraction for this, <code>Set</code> is. A <code>Map</code> is appropriate for key-value pairs. But you don't have values, only keys. </p>
<p>Example usage:</p>
<pre><code>Set<String> users = new HashSet<>(Arrays.asList("Alice", "Bob"));
System.out.println(users.contains("Alice"));
// -> prints true
System.out.println(users.contains("Jack"));
// -> prints false
</code></pre>
<p>Using a <code>Map</code> would be awkward, because what should be the type of the values? That question makes no sense in your use case,
as you have just keys, not key-value pairs.
With a <code>Set</code>, you don't need to ask that, the usage is perfectly natural.</p>
<blockquote>
<p>This is O(1) right? </p>
</blockquote>
<p>Yes, searching in a <code>HashMap</code> or a <code>HashSet</code> is O(1) amortized worst case, while searching in a <code>List</code> or an array is O(n) worst case.</p>
<hr>
<p>Some comments point out that a <code>HashSet</code> is implemented in terms of <code>HashMap</code>.
That's fine, <em>at that level of abstraction</em>.
At the level of abstraction of the task at hand ---
to store a collection of unique usernames,
using a set is a natural choice, more natural than a map.</p> |
7,046,370 | HTTPS request with Boost.Asio and OpenSSL | <p>I'm trying to read the ticker symbol at <a href="https://mtgox.com/api/0/data/ticker.php" rel="nofollow noreferrer">https://mtgox.com/api/0/data/ticker.php</a> from my C++ application.
I use Boost.Asio and OpenSSL because the service requires HTTPS.</p>
<p>Boost version: 1.47.0</p>
<p>OpenSSL: 1.0.0d [8 Feb 2011] Win32</p>
<p>For the application; I took the example from <a href="http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/example/ssl/client.cpp" rel="nofollow noreferrer">http://www.boost.org/doc/libs/1_47_0/doc/html/boost_asio/example/ssl/client.cpp</a>
to get started and modified it as follows:</p>
<p>This is where I want to connect to:</p>
<pre><code>boost::asio::ip::tcp::resolver::query query("mtgox.com", "443");
</code></pre>
<p>I set verification to none because the handshake fails otherwise. I'm not sure if this is a problem with mtgox or that this implementation is really strict because when I print the certificate to the screen it looks legit (and chrome has no problem with it when visiting the ticker page).</p>
<pre><code>socket_.set_verify_mode(boost::asio::ssl::context::verify_none);
</code></pre>
<p>This is the request I send:</p>
<pre><code>std::stringstream request_;
request_ << "GET /api/0/data/ticker.php HTTP/1.1\r\n";
request_ << "Host: mtgox.com\r\n";
request_ << "Accept-Encoding: *\r\n";
request_ << "\r\n";
boost::asio::async_write(socket_, boost::asio::buffer(request_.str()), boost::bind(&client::handle_write, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
</code></pre>
<p>(full code: <a href="http://pastebin.com/zRTTqZVe" rel="nofollow noreferrer">http://pastebin.com/zRTTqZVe</a>)</p>
<p>I run into the following error:</p>
<pre><code>Connection OK!
Verifying:
/C=IL/O=StartCom Ltd./OU=Secure Digital Certificate Signing/CN=StartCom Certification Authority
Sending request:
GET /api/0/data/ticker.php HTTP 1.1
Host: mtgox.com
Accept-Encoding: *
Sending request OK!
Read failed: An existing connection was forcibly closed by the remote host
</code></pre>
<p>Am I going in the right direction with this? The error message isn't really descriptive of the problem and I don't know which step I did wrong.</p>
<p><strong>Update:</strong>
I used cURL to see what went wrong:</p>
<pre><code>curl --trace-ascii out.txt https://mtgox.com/api/0/data/ticker.php
</code></pre>
<p>(full output: <a href="http://pastebin.com/Rzp0RnAK" rel="nofollow noreferrer">http://pastebin.com/Rzp0RnAK</a>)
It fails during verification.
When I connect with the "unsafe" parameter</p>
<pre><code>curl --trace-ascii out.txt -k https://mtgox.com/api/0/data/ticker.php
</code></pre>
<p>(full output: <a href="http://pastebin.com/JR43A7ux" rel="nofollow noreferrer">http://pastebin.com/JR43A7ux</a>)</p>
<p>everything works fine. </p>
<p><strong>Fix:</strong></p>
<ol>
<li>I fixed the typo in the HTTP headers </li>
<li>I added a root certificate and
turned SSL verification back on.</li>
</ol> | 7,050,070 | 1 | 3 | null | 2011-08-12 21:10:56.17 UTC | 12 | 2017-01-25 10:42:22.993 UTC | 2017-01-25 10:42:22.993 UTC | null | 996,815 | null | 624,586 | null | 1 | 14 | c++|boost|https|openssl|boost-asio | 21,168 | <p>In short:</p>
<ol>
<li><p>You send "HTTP 1.1" instead of "HTTP/1.1". That's surely enough to make the server refuse your request. There are other differences between your request and cURL's, you might need to change those params as well - even if they seem valid to me.</p></li>
<li><p>Maybe OpenSSL does not have the root certificate used by the server, unlike Chrome, and that's why verification is failing.</p></li>
</ol>
<p>Details:</p>
<ol>
<li><p>Given a working and non-working tool, you should always compare what's happening. Here you have cURL's output and your request - comparing them showed a number of differences; usually, even with an encrypted connection, you can use a powerful packet sniffer like Wireshark, which decodes as much information from the packets as possible. Here it would allow to see that the server is actually sending less packets (I expect); another possibility would have been that your client was not getting the data sent by the server (say because the client had some bug).</p></li>
<li><p>If I understand correctly, curl showed only why you needed to disable verification, right? The certificate looks valid for me on chrome as well, but the root certification authority is quite unknown; curl mentions the "CA cert", i.e. the certificate of the certification authority. The root certificate is trusted because it is already present in a certificate DB on the client - I think that Chrome might have a more complete DB than OpenSSL (which is used by both cURL and your program).</p></li>
</ol> |
41,828,711 | flask - blueprint - sqlalchemy - cannot import name 'db' into moles file | <p>I'm new in bluprint, and have problem with importing db into mydatabase.py file which is models file.</p>
<p>I've faced with this error:</p>
<blockquote>
<p>ImportError: cannot import name 'db'</p>
</blockquote>
<p>The tree of my project</p>
<pre><code>nikoofar/
run.py
bookshelf/
__init__.py
mydatabase.py
main/
controllers.py
__init__.py
</code></pre>
<p>run.py</p>
<pre><code>from bookshelf import app
if __name__ == '__main__':
app.run(debug=True, port=8000)
</code></pre>
<p>bookshelf / <strong>intit</strong>.py</p>
<pre><code>from flask import Flask
from bookshelf.main.controllers import main
from flask_sqlalchemy import SQLAlchemy
from mydatabase import pmenu
app = Flask(__name__, instance_relative_config=True)
db = SQLAlchemy(app)
db.init_app(app)
application.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://username:password@localhost/databasename'
app.config.from_object('config')
app.register_blueprint(main, url_prefix='/')
</code></pre>
<p>bookshelf / main / controllers.py</p>
<pre><code>from flask import Blueprint
from bookshelf.mydatabase import *
from flask_sqlalchemy import SQLAlchemy
main = Blueprint('main', __name__)
@main.route('/')
def index():
g = pmenu.query.all()
print (g)
return "ok"
</code></pre>
<p>The problem backs to <code>from bookshelf import db</code>, and if I delete that, the error will be changed to:</p>
<blockquote>
<p>ImportError: cannot import name 'db'</p>
</blockquote>
<p>bookshelf / mydatabase.py</p>
<pre><code>from bookshelf import db
class pmenu(db.Model):
__tablename__ = 'p_menu'
id = db.Column(db.Integer, primary_key=True)
txt = db.Column(db.String(80), unique=True)
link = db.Column(db.String(1024))
def __init__(self, txt, link):
self.txt = txt
self.link = link
def __repr__(self):
return "{'txt': " + self.txt + ", 'link':" + self.link + "}"
</code></pre>
<p>Any solution?</p> | 41,839,910 | 1 | 0 | null | 2017-01-24 12:51:44.567 UTC | 8 | 2017-01-24 22:11:54.66 UTC | 2017-01-24 15:26:31.227 UTC | null | 5,968,236 | null | 5,968,236 | null | 1 | 16 | python|flask|import|sqlalchemy|blueprint | 21,149 | <p>This is actually a simple, yet frustrating issue. The problem is you are importing main <code>BEFORE</code> you are creating the instance of <code>db</code> in your <code>__init__.py</code></p>
<p>If move the import to after your <code>db = SQLAlchemy(app)</code>, it will work:</p>
<pre><code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://uername:password@localhost/test'
db = SQLAlchemy(app)
from bookshelf.main.controllers import main #<--move this here
app.register_blueprint(main, url_prefix='/')
</code></pre> |
2,574,266 | Is it possible in git to create a new, empty remote branch without pushing? | <p>Most examples of creating remote branches involve pushing from a local branch</p>
<p>Is there a way of creating an empty remote branch without pushing?</p>
<p>Is it also possible to create a local empty branch,check it out then link it to the new also empty remote branch without pushing? </p> | 2,574,521 | 3 | 2 | null | 2010-04-04 11:39:42.39 UTC | 11 | 2021-01-08 21:59:40.177 UTC | 2012-01-16 09:11:13.73 UTC | null | 172,406 | null | 172,406 | null | 1 | 32 | git|branch | 30,855 | <p>As mentioned in the blog post "<a href="http://www.zorched.net/2008/04/14/start-a-new-branch-on-your-remote-git-repository/" rel="noreferrer">Start a New Branch on your Remote Git Repository</a>":</p>
<blockquote>
<ul>
<li>Creating a Remote Branch </li>
</ul>
</blockquote>
<pre><code>git push origin origin:refs/heads/new_feature_name
</code></pre>
<blockquote>
<ul>
<li>Make sure everything is up-to-date</li>
</ul>
</blockquote>
<pre><code>git fetch origin
</code></pre>
<blockquote>
<ul>
<li>Then you can see that the branch is created.</li>
</ul>
</blockquote>
<pre><code>git branch -r
</code></pre>
<blockquote>
<p>This should show ‘<code>origin/new_feature_name</code>’</p>
<ul>
<li>Start tracking the new branch</li>
</ul>
</blockquote>
<pre><code>git checkout --track -b new_feature_name origin/new_feature_name
</code></pre>
<p>So to declare a remote branch, even one which doesn't yet exist on the <em>local</em> repository, <code>git push</code> is mandatory.</p> |
3,166,123 | How to call shell script from php that requires SUDO? | <p>I have a file that is a bash script that requires SUDO to work.</p>
<p>I can run it from the command line using SUDO but I will be prompted to put in the SUDO password.</p>
<p>I want to run this script from php via <code>shell_exec</code> but I if I call SUDO, its not like a command line where I can be prompted for the password. Is there a way to pass the password for sudo with the sudo call?</p>
<p>How can I do this?</p> | 3,166,174 | 4 | 8 | null | 2010-07-02 13:35:56.517 UTC | 18 | 2019-02-06 10:06:39.7 UTC | null | null | null | null | 46,011 | null | 1 | 46 | php|bash|sudo|shellexecute | 57,557 | <p>Edit the sudoers file (with <code>visudo</code>) and add a rule that allows the web server user to run the command without a password. For example:</p>
<pre><code>www-data ALL=NOPASSWD: /path/to/script
</code></pre> |
31,849,334 | PHP Carbon, get all dates between date range? | <p>How can I get all dates between two dates in PHP? Prefer using Carbon for dates.</p>
<pre><code>$from = Carbon::now();
$to = Carbon::createFromDate(2017, 5, 21);
</code></pre>
<p>I wanna have all dates between those two dates.. But how? Can only found solutions using strtotime function.</p> | 50,854,594 | 10 | 0 | null | 2015-08-06 07:24:48.307 UTC | 29 | 2022-01-17 03:41:30.977 UTC | 2015-08-06 07:29:27.69 UTC | null | 162,671 | null | 1,469,734 | null | 1 | 96 | php|php-carbon | 115,398 | <p>As of Carbon 1.29 it is possible to do:</p>
<pre><code>$period = CarbonPeriod::create('2018-06-14', '2018-06-20');
// Iterate over the period
foreach ($period as $date) {
echo $date->format('Y-m-d');
}
// Convert the period to an array of dates
$dates = $period->toArray();
</code></pre>
<p>See documentation for more details: <a href="https://carbon.nesbot.com/docs/#api-period" rel="noreferrer">https://carbon.nesbot.com/docs/#api-period</a>.</p> |
40,454,030 | Count and Sort with Pandas | <p>I have a dataframe for values form a file by which I have grouped by two columns, which return a count of the aggregation. Now I want to sort by the max count value, however I get the following error:</p>
<blockquote>
<p>KeyError: 'count'</p>
</blockquote>
<p>Looks the group by agg count column is some sort of index so not sure how to do this, I'm a beginner to Python and Panda.
Here's the actual code, please let me know if you need more detail:</p>
<pre><code>def answer_five():
df = census_df#.set_index(['STNAME'])
df = df[df['SUMLEV'] == 50]
df = df[['STNAME','CTYNAME']].groupby(['STNAME']).agg(['count']).sort(['count'])
#df.set_index(['count'])
print(df.index)
# get sorted count max item
return df.head(5)
</code></pre> | 40,454,119 | 5 | 0 | null | 2016-11-06 20:13:18.053 UTC | 14 | 2022-02-07 12:59:46.133 UTC | 2017-11-16 10:24:47.207 UTC | null | 562,769 | null | 244,093 | null | 1 | 43 | python|sorting|pandas|count|group-by | 137,579 | <p>I think you need add <code>reset_index</code>, then parameter <code>ascending=False</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="noreferrer"><code>sort_values</code></a> because <code>sort</code> return:</p>
<blockquote>
<p>FutureWarning: sort(columns=....) is deprecated, use sort_values(by=.....)
.sort_values(['count'], ascending=False)</p>
</blockquote>
<pre><code>df = df[['STNAME','CTYNAME']].groupby(['STNAME'])['CTYNAME'] \
.count() \
.reset_index(name='count') \
.sort_values(['count'], ascending=False) \
.head(5)
</code></pre>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'STNAME':list('abscscbcdbcsscae'),
'CTYNAME':[4,5,6,5,6,2,3,4,5,6,4,5,4,3,6,5]})
print (df)
CTYNAME STNAME
0 4 a
1 5 b
2 6 s
3 5 c
4 6 s
5 2 c
6 3 b
7 4 c
8 5 d
9 6 b
10 4 c
11 5 s
12 4 s
13 3 c
14 6 a
15 5 e
df = df[['STNAME','CTYNAME']].groupby(['STNAME'])['CTYNAME'] \
.count() \
.reset_index(name='count') \
.sort_values(['count'], ascending=False) \
.head(5)
print (df)
STNAME count
2 c 5
5 s 4
1 b 3
0 a 2
3 d 1
</code></pre>
<hr>
<p>But it seems you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nlargest.html" rel="noreferrer"><code>Series.nlargest</code></a>:</p>
<pre><code>df = df[['STNAME','CTYNAME']].groupby(['STNAME'])['CTYNAME'].count().nlargest(5)
</code></pre>
<p>or:</p>
<pre><code>df = df[['STNAME','CTYNAME']].groupby(['STNAME'])['CTYNAME'].size().nlargest(5)
</code></pre>
<blockquote>
<p>The difference between <code>size</code> and <code>count</code> is:</p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.size.html#pandas.core.groupby.GroupBy.size" rel="noreferrer"><code>size</code></a> counts <code>NaN</code> values, <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.count.html#pandas.core.groupby.GroupBy.count" rel="noreferrer"><code>count</code></a> does not.</p>
</blockquote>
<p>Sample:</p>
<pre><code>df = pd.DataFrame({'STNAME':list('abscscbcdbcsscae'),
'CTYNAME':[4,5,6,5,6,2,3,4,5,6,4,5,4,3,6,5]})
print (df)
CTYNAME STNAME
0 4 a
1 5 b
2 6 s
3 5 c
4 6 s
5 2 c
6 3 b
7 4 c
8 5 d
9 6 b
10 4 c
11 5 s
12 4 s
13 3 c
14 6 a
15 5 e
df = df[['STNAME','CTYNAME']].groupby(['STNAME'])['CTYNAME']
.size()
.nlargest(5)
.reset_index(name='top5')
print (df)
STNAME top5
0 c 5
1 s 4
2 b 3
3 a 2
4 d 1
</code></pre> |
33,716,369 | error TRK0005: Failed to locate: "CL.exe" | <p>I'm using Windows 8.1. I installed Visual Studio 2015 community edition. When I run npm install -g generator-keystone, I get the error at the bottom. I tried running the following commands, but I'm still getting the same results.</p>
<pre><code>set GYP_MSVS_VERSION=2015
npm config set msvs_version 2015 --global
C:\Users\user\AppData\Roaming\npm\node_modules\generator-keystone\node_modules\buffertools>if not defined npm_config_no
de_gyp (node "C:\Users\user\AppData\Roaming\npm\node_modules\npm\bin\node-gyp-bin\\..\..\node_modules\node-gyp\bin\node
-gyp.js" rebuild ) else (node rebuild )
Building the projects in this solution one at a time. To enable parallel build, please add the "/m" switch.
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppBuild.targets(366,5): warning MSB8003: Could not fi
nd WindowsSDKDir variable from the registry. TargetFrameworkVersion or PlatformToolset may be set to an invalid versio
n number. [C:\Users\user\AppData\Roaming\npm\node_modules\generator-keystone\node_modules\buffertools\build\buffertool
s.vcxproj]
TRACKER : error TRK0005: Failed to locate: "CL.exe". The system cannot find the file specified. [C:\Users\user\AppData
\Roaming\npm\node_modules\generator-keystone\node_modules\buffertools\build\buffertools.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Program Files (x86)\MSBuild\14.0\bin\msbuild.exe` failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Users\user\AppData\Roaming\npm\node_modules\npm\node_modules\node-gyp\lib
\build.js:270:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:200:12)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Users\\user\\AppData\\Roaming\\npm\\node_modules\\npm
\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\user\AppData\Roaming\npm\node_modules\generator-keystone\node_modules\buffertools
gyp ERR! node -v v4.2.2
gyp ERR! node-gyp -v v3.0.3
gyp ERR! not ok
npm WARN install:[email protected] [email protected] install: `node-gyp rebuild`
npm WARN install:[email protected] Exit status 1
C:\Users\user\AppData\Roaming\npm
├── [email protected]
└── UNMET PEER DEPENDENCY yo@>=1.0.0
</code></pre> | 33,716,573 | 7 | 0 | null | 2015-11-15 04:20:07.49 UTC | 10 | 2022-07-08 12:41:10.317 UTC | null | null | null | null | 994,165 | null | 1 | 27 | node.js|visual-studio|npm | 54,377 | <p>I went into Visual Studio and created a Visual C++ project, which installed several libraries. npm install worked after that.</p> |
34,840,168 | Efiicient way to show 'Cant access network' View with 'Retry' and additional options like 'Wifi Settings', 'Mobile Network' | <p>I need to include this in my app</p>
<p><a href="https://i.stack.imgur.com/Roiro.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Roiro.png" alt="No Connection"></a></p>
<blockquote>
<p>When should it get triggered?</p>
</blockquote>
<ul>
<li>Any action triggered by user from UI requires internet and there's no internet</li>
<li>Any background activities (like asynchronous loading of images) requiring internet has no internet</li>
<li><strong>NOT</strong> when the app is idle or background/user actions <strong>not</strong> requiring internet are being processed</li>
</ul>
<blockquote>
<p>What I tried?</p>
</blockquote>
<ol>
<li>I use <strong>Volley</strong>. Triggered <code>AlertDialog</code> inside <code>Response.ErrorListener</code> of Volley, everytime I wrote a <code>JsonObjectRequest</code></li>
</ol>
<p><em><strong>Problem</strong>: too repetitive, had too many lines of AlertDialog code</em> </p>
<ol start="2">
<li><p>Added a common class called <code>Alerts</code> and called the <code>AlertDialog</code> from it like</p>
<pre><code>DialogInterface.OnClickListener onClickTryAgain = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Swift.getInstance(ProfileActivity.this).addToRequestQueue(jsonObjectRequest);
}
};
if(error instanceof TimeoutError) Alerts.timeoutErrorAlert(ProfileActivity.this, onClickTryAgain);
else if(error instanceof NoConnectionError) Alerts.internetConnectionErrorAlert(ProfileActivity.this, onClickTryAgain);
else Alerts.unknownErrorAlert(ProfileActivity.this);
</code></pre></li>
</ol>
<p>My Alerts.class</p>
<pre><code> public class Alerts {
public static void internetConnectionErrorAlert(final Context context, DialogInterface.OnClickListener onClickTryAgainButton) {
String message = "Sometimes the internet gets a bit sleepy and takes a nap. Make sure its up and running then we'll give it another go";
new AlertDialog.Builder(context)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle("Network Error")
.setMessage(message)
.setPositiveButton("Try Again", onClickTryAgainButton)
.setNegativeButton("Turn Internet On", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Settings.ACTION_SETTINGS);
((Activity) context).startActivityForResult(i, 0);
}
})
.show();
}
public static void timeoutErrorAlert(Context context, DialogInterface.OnClickListener onClickTryAgainButton) {
String message = "Are you connected to internet? We guess you aren't. Turn it on and we'll rock and roll!";
new AlertDialog.Builder(context)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle("Network Error")
.setMessage(message)
.setPositiveButton("Try Again", onClickTryAgainButton)
.show();
}
public static void unknownErrorAlert(Context context) {
new AlertDialog.Builder(context)
.setIconAttribute(android.R.attr.alertDialogIcon)
.setTitle("Server Error")
.setMessage("We all have bad days! We'll fix this soon...")
.setPositiveButton("Hmm, I understand", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
}
</code></pre>
<p><em><strong>Problem</strong>: <code>Try again</code> button doesn't do what I wanted. Well, <strong>assuming someone gives a fix for that</strong>, I can say, it just replaced some 30 lines of code with 5 lines, well, but what about the transitions? I need to say <code>connecting</code>, till response arrives</em> </p>
<ol start="3">
<li><p>This time, I added a layout called <code>ConnectingLayout</code> covering the whole of the screen.</p>
<pre><code><LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:id="@+id/loading_layout"
android:visibility="gone">
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/loading"
android:gravity="center_horizontal"
android:textSize="25sp"
android:fontFamily="sans-serif-light"
android:layout_margin="5dp"
android:singleLine="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/loading_description"
android:gravity="center_horizontal"
android:fontFamily="sans-serif-light"
android:layout_margin="5dp"
android:singleLine="true" />
</LinearLayout>
</code></pre></li>
</ol>
<p>and used it as in</p>
<pre><code> jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, getString(R.string.api_root_path) + "/profile", getJson(), new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
if(response.getBoolean("success")) {
Animations.fadeOut(loadingLayout,500);
Animations.fadeIn(mainLayout,500);
JSONObject dataJson = response.getJSONObject("data");
JSONObject userJson = dataJson.getJSONObject("user");
name.setText(userJson.getString("name"));
dob.setText(userJson.getString("dob").equals("null")?null:userJson.getString("dob"));
email.setText(userJson.getString("email"));
phone.setText(userJson.getString("mobile_no"));
promotionOffers.setChecked(userJson.getBoolean("offers"));
} else {
Alerts.requestUnauthorisedAlert(ProfileActivity.this);
System.out.println(response.getString("error"));
}
} catch (JSONException e) { e.printStackTrace(); }
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
DialogInterface.OnClickListener onClickTryAgain = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
VolleyBaseClass.getInstance(ProfileActivity.this).addToRequestQueue(jsonObjectRequest);
}
};
if(error instanceof TimeoutError) Alerts.timeoutErrorAlert(ProfileActivity.this, onClickTryAgain);
else if(error instanceof NoConnectionError) Alerts.internetConnectionErrorAlert(ProfileActivity.this, onClickTryAgain);
else Alerts.unknownErrorAlert(ProfileActivity.this);
System.out.println("Response Error: " + error);
}
});
Animations.fadeIn(loadingLayout, 500);
Animations.fadeOut(mainLayout, 500);
VolleyBaseClass.getInstance(this).addToRequestQueue(jsonObjectRequest);
</code></pre>
<p>Assume that <code>Animations.fadeIn(View view, int ms);</code> and <code>Animations.fadeOut(View view, int ms);</code> are properly defined and does the job.</p>
<p><em><strong>Problem</strong>: Pain of repeating layouts in all acivities and writing code to fade</em></p>
<ol start="4">
<li>Learnt about <code>ViewStub</code>s. Generated code programmatically to get the same <code>ConnectingLayout</code>. Now I can change text like saving, loading, etc.</li>
</ol>
<p><em><strong>Problem</strong>: Not a big leap, but... .., it's one more stepping stone I just landed on</em></p>
<ol start="5">
<li>I don't need to say its connecting or loading, I just need to say 'Hey, your phone is processing someething'. So I just thought why not use the loading circle in <a href="http://developer.android.com/reference/android/.../SwipeRefreshLayout.html" rel="nofollow noreferrer">SwipeRefreshLayout</a>s ?</li>
</ol>
<p><em><strong>Problem</strong>: Great, it shows little loading circular notch on top, and if loading fails, i can call the alert, <strong>but where is turn wifi on, turn 3G on and other things</strong>, too big for an <code>AlertDialog</code> to accommodate all that, is there any other way to show <code>try again</code>?</em></p>
<ol start="6">
<li>Looked about using <code>same fragment in all activities</code> and <code>redirecting to a callActivityForResult</code> (sorry that I can't add more than two links)</li>
</ol>
<p><em><strong>Problem</strong>: Hmm...! Taking the user to a new activity is what I find eating resources and bringing down performance considerably. And fragments?</em></p>
<blockquote>
<p>I am not giving up! I know I'm learning it the hard way, but with great hopes that the developer community will help me.</p>
</blockquote> | 37,909,236 | 2 | 0 | null | 2016-01-17 15:39:05.567 UTC | 8 | 2016-06-19 16:12:37.95 UTC | null | null | null | null | 3,211,422 | null | 1 | 2 | android-layout|android-fragments|view|loading|android-volley | 828 | <blockquote>
<p>Volley <strong>DETROYS all listeners</strong> as soon as it receives something from the server, regardless of whether the response is a proper response or an error response.</p>
</blockquote>
<p>A request needs to constructed everytime it should be sent or resent.</p>
<p>These steps will help achieve it</p>
<ul>
<li>Create a fragment with <code>Retry</code> and other necessary buttons like <code>Wifi Settings</code>, <code>Mobile Network Settings</code></li>
<li>Create a full sized <code>FrameLayout</code> inside <code>RelativeLayout</code> on necessary views <strong>to accommodate the fragment created</strong> and hide it initially</li>
<li>When request fails, make the <code>FrameLayout</code> visible and the retry button should call the function that <strong>constructs and calls</strong> the request</li>
</ul> |
45,950,646 | What is lexicographical order? | <p>What is the exact meaning of lexicographical order? How it is different from alphabetical order?</p> | 45,950,665 | 6 | 0 | null | 2017-08-30 01:45:57.963 UTC | 26 | 2021-12-19 13:50:50.223 UTC | 2019-02-15 19:17:29.353 UTC | null | 10,607,772 | null | 6,576,225 | null | 1 | 136 | string|sorting|lexicographic | 161,380 | <p>lexicographical order <strong>is</strong> alphabetical order. The other type is numerical ordering. Consider the following values,</p>
<pre><code>1, 10, 2
</code></pre>
<p>Those values are in lexicographical order. 10 comes after 2 in numerical order, but 10 comes before 2 in "alphabetical" order.</p> |
32,125,281 | Removing watermark out of an image using OpenCV | <p>First of all I have this image and I want to make an application that can detect images like it and remove the circle (watermark) from it.</p>
<p><a href="https://i.stack.imgur.com/YZeOg.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/YZeOg.jpg" alt="image has a watermark"></a></p>
<pre><code>int main(){
Mat im1,im2,im3,gray,gray2,result;
im2=imread(" (2).jpg");
namedWindow("x",CV_WINDOW_FREERATIO);
imshow("x",im2);
//converting it to gray
cvtColor(im2,gray,CV_BGR2GRAY);
// creating a new image that will have the cropped ellipse
Mat ElipseImg(im2.rows,im2.cols,CV_8UC1,Scalar(0,0,0));
//detecting the largest circle
GaussianBlur(gray,gray,Size(5,5),0);
vector<Vec3f> circles;
HoughCircles(gray,circles,CV_HOUGH_GRADIENT,1,gray.rows/8,100,100,100,0);
uchar x;
int measure=0;int id=0;
for(int i=0;i<circles.size();i++){
if(cvRound(circles[i][2])>measure && cvRound(circles[i][2])<1000){
measure=cvRound(circles[i][2]);
id=i;
}
}
Point center(cvRound(circles[id][0]),cvRound(circles[id][1]));
int radius=cvRound(circles[id][2]);
circle(im2,center,3,Scalar(0,255,0),-1,8,0);
circle(im2,center,radius,Scalar(0,255,0),2,8,0);
ellipse(ElipseImg,center,Size(radius,radius),0,0,360,Scalar(255,255,255),-1,8);
cout<<"center: "<<center<<" radius: "<<radius<<endl;
Mat res;
bitwise_and(gray,ElipseImg,result);
namedWindow("bitwise and",CV_WINDOW_FREERATIO);
imshow("bitwise and",result);
// trying to estimate the Intensity of the circle for the thresholding
x=result.at<uchar>(cvRound(circles[id][0]+30),cvRound(circles[id][1]));
cout<<(int)x;
//thresholding the output image
threshold(ElipseImg,ElipseImg,(int)x-10,250,CV_THRESH_BINARY);
namedWindow("threshold",CV_WINDOW_FREERATIO);
imshow("threshold",ElipseImg);
// making bitwise_or
bitwise_or(gray,ElipseImg,res);
namedWindow("bitwise or",CV_WINDOW_FREERATIO);
imshow("bitwise or",res);
waitKey(0);
}
</code></pre>
<p>So far what I made is:</p>
<ol>
<li>I convert it to grayscale </li>
<li>I detect the largest circle using Hough circles and then make a circle with same radius in a new image </li>
<li>This new circle with the gray-scaled one using (<code>bitwise_and</code>) gives me an image with only that circle</li>
<li>Threshold that new image</li>
<li><code>bitwise_or</code> the result of the threshold</li>
</ol>
<p>My problem is that any black text on the curved white line inside this circle didn't appear. I tried to remove the color by using the pixel values instead of threshold, but the problem is the same.
So any solutions or suggestions?</p>
<p>These are the results:
<a href="https://i.stack.imgur.com/eaaD4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eaaD4.png" alt="enter image description here"></a></p> | 32,141,019 | 2 | 0 | null | 2015-08-20 18:03:12.947 UTC | 39 | 2020-02-04 08:34:33.697 UTC | 2020-02-04 08:34:33.697 UTC | null | 9,487,693 | null | 5,083,643 | null | 1 | 60 | c++|opencv|image-processing|watermark | 26,373 | <p>I'm not sure if the following solution is acceptable in your case. But I think it performs slightly better, and doesn't care about the shape of the watermark.</p>
<ul>
<li><p>Remove the strokes using morphological filtering. This should give you a background image.
<a href="https://i.stack.imgur.com/txq3A.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/txq3A.jpg" alt="background"></a></p></li>
<li><p>Calculate the difference image: difference = background - initial, and threshold it: binary = threshold(difference)</p></li>
</ul>
<p><a href="https://i.stack.imgur.com/VfB2B.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/VfB2B.jpg" alt="binary1"></a></p>
<ul>
<li>Threshold the background image and extract the dark region covered by the watermark</li>
</ul>
<p><a href="https://i.stack.imgur.com/X2PBU.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/X2PBU.jpg" alt="dark"></a></p>
<ul>
<li>From the initial image, extract pixels within the watermark region and threshold these pixels, then paste them to the earlier binary image</li>
</ul>
<p><a href="https://i.stack.imgur.com/9g7ql.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/9g7ql.jpg" alt="binary2"></a></p>
<p>Above is a rough description. Code below should explain it better.</p>
<pre><code>Mat im = [load the color image here];
Mat gr, bg, bw, dark;
cvtColor(im, gr, CV_BGR2GRAY);
// approximate the background
bg = gr.clone();
for (int r = 1; r < 5; r++)
{
Mat kernel2 = getStructuringElement(MORPH_ELLIPSE, Size(2*r+1, 2*r+1));
morphologyEx(bg, bg, CV_MOP_CLOSE, kernel2);
morphologyEx(bg, bg, CV_MOP_OPEN, kernel2);
}
// difference = background - initial
Mat dif = bg - gr;
// threshold the difference image so we get dark letters
threshold(dif, bw, 0, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU);
// threshold the background image so we get dark region
threshold(bg, dark, 0, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU);
// extract pixels in the dark region
vector<unsigned char> darkpix(countNonZero(dark));
int index = 0;
for (int r = 0; r < dark.rows; r++)
{
for (int c = 0; c < dark.cols; c++)
{
if (dark.at<unsigned char>(r, c))
{
darkpix[index++] = gr.at<unsigned char>(r, c);
}
}
}
// threshold the dark region so we get the darker pixels inside it
threshold(darkpix, darkpix, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);
// paste the extracted darker pixels
index = 0;
for (int r = 0; r < dark.rows; r++)
{
for (int c = 0; c < dark.cols; c++)
{
if (dark.at<unsigned char>(r, c))
{
bw.at<unsigned char>(r, c) = darkpix[index++];
}
}
}
</code></pre> |
32,065,160 | Method FloatMath.sqrt() not found | <p>I'm using the new Android Marshmallow SDK and the method <code>FloatMath.sqrt()</code> is gone. What should I use now?</p> | 32,065,188 | 1 | 0 | null | 2015-08-18 06:34:12.937 UTC | 10 | 2015-08-18 06:35:50.547 UTC | null | null | null | null | 995,926 | null | 1 | 88 | android|android-6.0-marshmallow | 47,645 | <p>The documentations say this:</p>
<blockquote>
<p>Historically these methods were faster than the equivalent double-based
java.lang.Math methods. On versions of Android with a JIT they
became slower and have since been re-implemented to wrap calls to
java.lang.Math. java.lang.Math should be used in preference.</p>
<p>All methods were removed from the public API in version 23.</p>
<p>@deprecated Use java.lang.Math instead.</p>
</blockquote>
<p>This means the solution is to use the Math class:</p>
<pre><code>(float)Math.sqrt(...)
</code></pre> |
56,942,058 | Spark union column order | <p>I've come across something strange recently in Spark. As far as I understand, given the column based storage method of spark dfs, the order of the columns really don't have any meaning, they're like keys in a dictionary. </p>
<p>During a <code>df.union(df2)</code>, does the order of the columns matter? I would've assumed that it shouldn't, but according to the wisdom of sql forums it does. </p>
<p>So we have <code>df1</code></p>
<pre><code>df1
| a| b|
+---+----+
| 1| asd|
| 2|asda|
| 3| f1f|
+---+----+
df2
| b| a|
+----+---+
| asd| 1|
|asda| 2|
| f1f| 3|
+----+---+
result
| a| b|
+----+----+
| 1| asd|
| 2|asda|
| 3| f1f|
| asd| 1|
|asda| 2|
| f1f| 3|
+----+----+
</code></pre>
<p>It looks like the schema from df1 was used, but the data appears to have joined following the order of their original dataframes.
Obviously the solution would be to do <code>df1.union(df2.select(df1.columns))</code></p>
<p>But the main question is, why does it do this? Is it simply because it's part of pyspark.sql, or is there some underlying data architecture in Spark that I've goofed up in understanding?</p>
<p>code to create test set if anyone wants to try</p>
<pre><code>d1={'a':[1,2,3], 'b':['asd','asda','f1f']}
d2={ 'b':['asd','asda','f1f'], 'a':[1,2,3],}
pdf1=pd.DataFrame(d1)
pdf2=pd.DataFrame(d2)
df1=spark.createDataFrame(pdf1)
df2=spark.createDataFrame(pdf2)
test=df1.union(df2)
</code></pre> | 56,942,309 | 2 | 0 | null | 2019-07-08 20:20:24.047 UTC | 5 | 2022-09-15 10:48:42.977 UTC | 2022-09-15 10:48:42.977 UTC | null | 2,753,501 | null | 11,579,554 | null | 1 | 32 | apache-spark|pyspark|apache-spark-sql | 22,529 | <p>in spark Union is not done on metadata of columns and data is not shuffled like you would think it would. rather union is done on the column numbers as in, if you are unioning 2 Df's both must have the same numbers of columns..you will have to take in consideration of positions of your columns previous to doing union. unlike SQL or Oracle or other RDBMS, underlying files in spark are physical files. hope that answers your question </p> |
2,605,133 | how do I get co-ordinates of selected text in an html using javascript document.getSelecttion() | <p>I would like to position element above selected text. But I am not able to figure out the coordinates.</p>
<pre><code>var sel = document.getSelection();
if(sel != null) {
positionDiv();
}
</code></pre>
<p>Example: (image)</p>
<p><a href="https://i.stack.imgur.com/QLOeU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QLOeU.png" alt="alt text"></a>
</p> | 2,605,429 | 1 | 3 | null | 2010-04-09 04:44:43.98 UTC | 9 | 2019-07-22 07:12:37.45 UTC | 2019-07-22 07:12:37.45 UTC | null | 4,751,173 | null | 167,719 | null | 1 | 8 | javascript|getselection | 3,628 | <p>Here is the basic idea. You insert dummy element in the beginning of the selection and get the coordinates of that dummy html element. Then you remove it.</p>
<pre><code>var range = window.getSelection().getRangeAt(0);
var dummy = document.createElement("span");
range.insertNode(dummy);
var box = document.getBoxObjectFor(dummy);
var x = box.x, y = box.y;
dummy.parentNode.removeChild(dummy);
</code></pre> |
3,016,283 | Create a color generator from given colormap in matplotlib | <p>I have a series of lines that each need to be plotted with a separate colour. Each line is actually made up of several data sets (positive, negative regions etc.) and so I'd like to be able to create a generator that will feed one colour at a time across a spectrum, for example the <code>gist_rainbow</code> map <a href="http://www.scipy.org/Cookbook/Matplotlib/Show_colormaps" rel="noreferrer">shown here</a>.</p>
<p>I have found the following works but it seems very complicated and more importantly difficult to remember,</p>
<pre><code>from pylab import *
NUM_COLORS = 22
mp = cm.datad['gist_rainbow']
get_color = matplotlib.colors.LinearSegmentedColormap.from_list(mp, colors=['r', 'b'], N=NUM_COLORS)
...
# Then in a for loop
this_color = get_color(float(i)/NUM_COLORS)
</code></pre>
<p>Moreover, it does not cover the range of colours in the <code>gist_rainbow</code> map, I have to redefine a map.</p>
<p>Maybe a generator is not the best way to do this, if so what is the accepted way? </p> | 3,018,380 | 1 | 0 | null | 2010-06-10 16:18:14.27 UTC | 15 | 2016-11-25 20:39:45.857 UTC | 2013-04-21 02:41:23.287 UTC | null | 202,229 | null | 199 | null | 1 | 21 | python|matplotlib|color-mapping | 26,445 | <p>To index colors from a specific colormap you can use:</p>
<pre><code>import pylab
NUM_COLORS = 22
cm = pylab.get_cmap('gist_rainbow')
for i in range(NUM_COLORS):
color = cm(1.*i/NUM_COLORS) # color will now be an RGBA tuple
# or if you really want a generator:
cgen = (cm(1.*i/NUM_COLORS) for i in range(NUM_COLORS))
</code></pre> |
46,672,523 | helm list : cannot list configmaps in the namespace "kube-system" | <p>I have installed helm 2.6.2 on the kubernetes 8 cluster. <code>helm init</code> worked fine. but when I run <code>helm list</code> it giving this error.</p>
<pre><code> helm list
Error: configmaps is forbidden: User "system:serviceaccount:kube-system:default" cannot list configmaps in the namespace "kube-system"
</code></pre>
<p>How to fix this RABC error message?</p> | 46,688,254 | 8 | 0 | null | 2017-10-10 17:25:20.253 UTC | 49 | 2020-05-12 09:54:50.823 UTC | 2018-08-12 19:26:55.65 UTC | null | 278,183 | null | 344,669 | null | 1 | 115 | kubernetes|kubernetes-helm | 54,143 | <p>Once these commands:</p>
<pre><code>kubectl create serviceaccount --namespace kube-system tiller
kubectl create clusterrolebinding tiller-cluster-rule --clusterrole=cluster-admin --serviceaccount=kube-system:tiller
kubectl patch deploy --namespace kube-system tiller-deploy -p '{"spec":{"template":{"spec":{"serviceAccount":"tiller"}}}}'
helm init --service-account tiller --upgrade
</code></pre>
<p>were run, the issue has been solved.</p> |
32,188,386 | Can't read from file issue in Swagger UI | <p>I have incorporated <code>swagger-ui</code> in my application.</p>
<p>When I try and see the <code>swagger-ui</code> I get the documentation of the API nicely but after some time it shows some error icon at the button.</p>
<p>The Error message is like below:</p>
<blockquote>
<p>[{"level":"error","message":"Can't read from file
http://MYIP/swagger/docs/v1"}]</p>
</blockquote>
<p>I am not sure what is causing it. If I refresh it works and shows error after few seconds.</p> | 32,244,495 | 6 | 0 | null | 2015-08-24 17:40:48.19 UTC | 10 | 2021-06-11 14:06:19.887 UTC | 2021-06-11 14:06:19.887 UTC | null | 11,880,324 | null | 2,792,480 | null | 1 | 76 | swagger-ui|swashbuckle | 47,642 | <p>I am guessing "<a href="http://MYIP/swagger/docs/v1" rel="noreferrer">http://MYIP/swagger/docs/v1</a>" is not publicly accessible.</p>
<p>By default swagger ui uses an online validator: online.swagger.io. If it cannot access your swagger url then you will see that error message.</p>
<p>Possible solutions:</p>
<ol>
<li><p>Disable validation:</p>
<p><code>config.EnableSwagger().EnableSwaggerUi(c => c.DisableValidator());</code></p></li>
<li><p>Make your site publicly accessible</p></li>
<li><p>Host the validator locally:</p></li>
</ol>
<p>You can get the validator from: <a href="https://github.com/swagger-api/validator-badge#running-locally" rel="noreferrer">https://github.com/swagger-api/validator-badge#running-locally</a></p>
<p>You will also need to tell swaggerui the location of the validator</p>
<p><code>config.EnableSwagger().EnableSwaggerUi(c => c.SetValidatorUrl(<validator_url>));</code></p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.