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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
31,156,101 | Dynamo DB + In put Item Request how to pass null value? | <p>I have one field which i have declared as string in the model as show below:</p>
<pre><code>App.Student= DS.Model.extend({
name: DS.attr('string'),
address1: DS.attr('string'),
address2: DS.attr('string'),
city: DS.attr('string'),
state: DS.attr('string'),
postal: DS.attr('string'),
country: DS.attr('string'),
});
</code></pre>
<p>Here in the Edit mode when i update Adderess 2 field as null then below error comes: </p>
<p><code>"Failed to edit property: One or more parameter values were invalid: An AttributeValue may not contain an empty string"</code> </p>
<p>I know this Error is generated because i am updating address 2 field as null and that what i want <strong>Address 2 field is not mandatory(One can pass data or can also left that column as blank")</strong></p> | 31,265,563 | 7 | 0 | null | 2015-07-01 08:21:04.237 UTC | 1 | 2020-07-03 22:58:37.917 UTC | null | null | null | null | 3,454,221 | null | 1 | 11 | amazon-dynamodb | 38,108 | <p>Finally i got this right, The way might be some what different but it work for me !!!</p>
<p>Here is the code for the same.</p>
<pre><code>AttributeUpdates: {
Address2:
{
Action: "DELETE"
},
}
</code></pre>
<p>And then i am adding the value on the condition.</p>
<pre><code>if (propertyObj.address2) {
params.AttributeUpdates.address2 = {
Value: {
S: propertyObj.address2
},
Action: "PUT"
}
}
</code></pre>
<p>Thank you to all from bottom of my heart :)who tried to help me, Cheers !!!</p> |
58,236,175 | What is a GitLab instance URL, and how can I get it? | <p>I have tried searching for it everywhere, but I can’t find anything.</p>
<p>It would be really awesome if someone could define it straight out of the box.</p>
<p>I don’t know what an instance of GitLab URL is. I’m asking if someone could clarify what it is, and where can I get it. I am currently trying to add it in <a href="https://en.wikipedia.org/wiki/Visual_Studio_Code" rel="noreferrer">Visual Studio Code</a> extension <em><a href="https://marketplace.visualstudio.com/items?itemName=gitlab.gitlab-workflow" rel="noreferrer">GitLab Workflow</a></em>. The extension is asking for my GitLab instance URL, and I don’t know where to get it.</p> | 58,259,627 | 2 | 1 | null | 2019-10-04 12:10:34.317 UTC | 3 | 2022-03-18 17:05:20.563 UTC | 2021-08-17 09:49:28.72 UTC | null | 11,435,798 | null | 11,435,798 | null | 1 | 34 | gitlab | 40,448 | <p>The instance URL of any GitLab install is basically the link to the GitLab you're trying to connect to.</p>
<p>For example, if your project is hosted on <code>gitlab.example.com/yourname/yourproject</code> then for the instance URL enter <code>https://gitlab.example.com</code>.</p>
<p>Another example, if your project is hosted on <code>gitlab.com/username/project</code> then the instance URL is <code>https://gitlab.com</code>. Though note that in the VS Code extension specifically, <a href="https://marketplace.visualstudio.com/items?itemName=GitLab.gitlab-workflow#extension-settings" rel="noreferrer">gitlab.com is the default</a> so you can leave it blank in this case.</p> |
47,336,704 | Repeat rows in a pandas DataFrame based on column value | <p>I have the following df:</p>
<pre><code>code . role . persons
123 . Janitor . 3
123 . Analyst . 2
321 . Vallet . 2
321 . Auditor . 5
</code></pre>
<p>The first line means that I have 3 persons with the role Janitors.
My problem is that I would need to have one line for each person. My df should look like this:</p>
<pre><code>df:
code . role . persons
123 . Janitor . 3
123 . Janitor . 3
123 . Janitor . 3
123 . Analyst . 2
123 . Analyst . 2
321 . Vallet . 2
321 . Vallet . 2
321 . Auditor . 5
321 . Auditor . 5
321 . Auditor . 5
321 . Auditor . 5
321 . Auditor . 5
</code></pre>
<p>How could I do that using pandas?</p> | 47,336,762 | 3 | 0 | null | 2017-11-16 18:25:27.047 UTC | 9 | 2022-07-23 10:41:06.18 UTC | 2019-02-06 22:22:19.703 UTC | null | 4,909,087 | null | 5,606,352 | null | 1 | 30 | python|pandas|dataframe|repeat | 20,359 | <p><code>reindex</code>+ <code>repeat</code></p>
<pre><code>df.reindex(df.index.repeat(df.persons))
Out[951]:
code . role ..1 persons
0 123 . Janitor . 3
0 123 . Janitor . 3
0 123 . Janitor . 3
1 123 . Analyst . 2
1 123 . Analyst . 2
2 321 . Vallet . 2
2 321 . Vallet . 2
3 321 . Auditor . 5
3 321 . Auditor . 5
3 321 . Auditor . 5
3 321 . Auditor . 5
3 321 . Auditor . 5
</code></pre>
<p>PS: you can add<code>.reset_index(drop=True)</code> to get the new index</p> |
20,997,062 | Specify encoding XmlSerializer | <p>I've a class correctly defined and after serialize it to XML I'm getting no encoding.</p>
<p>How can I define encoding "ISO-8859-1"?</p>
<p>Here's a sample code</p>
<pre><code>var xml = new XmlSerializer(typeof(Transacao));
var file = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "transacao.xml"),FileMode.OpenOrCreate);
xml.Serialize(file, transacao);
file.Close();
</code></pre>
<p>Here are the beginning of xml generated</p>
<pre><code><?xml version="1.0"?>
<requisicao-transacao xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<dados-ec>
<numero>1048664497</numero>
</code></pre> | 21,003,031 | 2 | 1 | null | 2014-01-08 13:27:57.99 UTC | 2 | 2014-01-08 17:55:49.023 UTC | null | null | null | null | 833,531 | null | 1 | 11 | c#|xml|c#-4.0|export-to-xml | 41,259 | <p>The following should work:</p>
<pre><code>var xml = new XmlSerializer(typeof(Transacao));
var fname = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "transacao.xml");
var appendMode = false;
var encoding = Encoding.GetEncoding("ISO-8859-1");
using(StreamWriter sw = new StreamWriter(fname, appendMode, encoding))
{
xml.Serialize(sw, transacao);
}
</code></pre>
<p>If you don't mind me asking, why do you need <code>ISO-8859-1</code> encoding in particular? You could probably use <code>UTF-8</code> or <code>UTF-16</code> (they're more commonly recognizable) and get away with it.</p> |
36,764,791 | In Tensorflow, how to use tf.gather() for the last dimension? | <p>I am trying to gather slices of a tensor in terms of the last dimension for partial connection between layers. Because the output tensor's shape is <code>[batch_size, h, w, depth]</code>, I want to select slices based on the last dimension, such as</p>
<pre><code># L is intermediate tensor
partL = L[:, :, :, [0,2,3,8]]
</code></pre>
<p>However, <code>tf.gather(L, [0, 2,3,8])</code> seems to only work for the first dimension (right?) Can anyone tell me how to do it? </p> | 36,777,781 | 8 | 0 | null | 2016-04-21 09:04:06.123 UTC | 3 | 2017-11-20 16:58:06.967 UTC | 2017-11-20 16:58:06.967 UTC | null | 3,924,118 | null | 3,251,207 | null | 1 | 19 | python|tensorflow|deep-learning | 42,946 | <p>There's a tracking bug to support this use-case here: <a href="https://github.com/tensorflow/tensorflow/issues/206" rel="noreferrer">https://github.com/tensorflow/tensorflow/issues/206</a></p>
<p>For now you can:</p>
<ol>
<li><p>transpose your matrix so that dimension to gather is first (transpose is expensive)</p></li>
<li><p>reshape your tensor into 1d (reshape is cheap) and turn your gather column indices into a list of individual element indices at linear indexing, then reshape back</p></li>
<li>use <code>gather_nd</code>. Will still need to turn your column indices into list of individual element indices.</li>
</ol> |
28,128,400 | Keep footer at the bottom of the page (with scrolling if needed) | <p>I'm trying to show a footer at the bottom of my pages. And if the page is longer then 1 screen I like the footer to only show after scrolling to the bottom. So I can't use 'position: fixed', because then it will always show.</p>
<p>I'm trying to copy the following example: <a href="http://peterned.home.xs4all.nl/examples/csslayout1.html" rel="noreferrer">http://peterned.home.xs4all.nl/examples/csslayout1.html</a></p>
<p>However when I use the following, the footer is showing halfway my long page for some reason.</p>
<pre><code>position: absolute; bottom:0
</code></pre>
<p>I have both short pages and long pages and I would like it to be at the bottom of both of them.</p>
<p>How can I keep the footer at the bottom on a long page as well?</p>
<p><strong>Fiddle</strong></p>
<p>I've created these Fiddles to show the problem and test the code.
Please post a working example with your solution.</p>
<ul>
<li><p><a href="http://jsfiddle.net/Dyna18/243x9s2o/" rel="noreferrer">Short page</a></p></li>
<li><p><a href="http://jsfiddle.net/Dyna18/ozzuvrow/" rel="noreferrer">Long page</a></p></li>
</ul>
<p><strong>My footer css:</strong></p>
<pre><code>html,body {
margin:0;
padding:0;
height:100%; /* needed for container min-height */
}
.content {
position:relative; /* needed for footer positioning*/
margin:0 auto; /* center, not in IE5 */
height:auto !important; /* real browsers */
height:100%; /* IE6: treaded as min-height*/
min-height:100%; /* real browsers */
}
/* --- Footer --- */
.footerbar { position: absolute;
width: 100%;
bottom: 0;
color: white;
background-color: #202020;
font-size: 12px; }
a.nav-footer:link,
a.nav-footer:visited { color: white !important; }
a.nav-footer:hover,
a.nav-footer:focus { color: black !important;
background-color: #E7E7E7 !important; }
</code></pre> | 28,128,430 | 9 | 0 | null | 2015-01-24 17:49:18.067 UTC | 2 | 2022-05-30 18:26:02.957 UTC | 2015-01-24 19:22:45.63 UTC | null | 3,881,236 | null | 3,881,236 | null | 1 | 20 | html|css|footer | 84,098 | <p>I would suggest the "sticky footer" approach. See the following link:</p>
<p><a href="http://css-tricks.com/snippets/css/sticky-footer/" rel="noreferrer">http://css-tricks.com/snippets/css/sticky-footer/</a></p> |
8,794,886 | Create a link with an anchor with Twig path function in Symfony 2 | <p>I'm trying to create a link with an anchor like "www.example.com/services#anchor1" in my Twig template. So far I've been using the <strong>path</strong> function to create links <code>path('services')</code>. I have tried with <code>path('services#anchor1')</code> but obviously it doesn't work.</p>
<p>It doesn't seem to be a lot of information about this function or it's just that I can't find it. Any idea about how could I do it?</p>
<p>Thanks!</p> | 8,794,949 | 3 | 0 | null | 2012-01-09 20:38:41.68 UTC | 1 | 2017-06-14 08:02:20.743 UTC | null | null | null | null | 701,243 | null | 1 | 34 | symfony|twig | 35,978 | <p>Try <code><a href="{{ path('_welcome') }}#home">Home</a></code></p> |
27,087,483 | How to resolve "git pull,fatal: unable to access 'https://github.com...\': Empty reply from server" | <p>It's failed when I used Git command "git pull" to update my repository, messages as below:
fatal: unable to access '...': Empty reply from server. </p>
<p>And the I tried to use the GitHub App, but alert this: </p>
<pre><code>Cloning into 'renren_mobile'...
warning: templates not found /Applications/GitHub.app/Contents/Resources/git/templates
2014-11-23 13:58:57.975 GitHub for Mac Login[659:11891] AskPass with arguments: (
"/Applications/GitHub.app/Contents/MacOS/GitHub for Mac Login",
"Username for 'https://github.com': "
)
2014-11-23 13:58:58.032 GitHub for Mac Login[660:11915] AskPass with arguments: (
"/Applications/GitHub.app/Contents/MacOS/GitHub for Mac Login",
"Password for '': "
)
fatal: unable to access '...': Empty reply from server
(128)
</code></pre> | 27,352,176 | 18 | 1 | null | 2014-11-23 09:33:06.453 UTC | 21 | 2021-05-25 04:43:44.93 UTC | 2021-05-25 04:43:44.93 UTC | null | 13,046,806 | null | 4,283,912 | null | 1 | 84 | git|github|ssh-keys | 374,530 | <p>I resolved this problem. I think it happened maybe because of https but I am not very sure.
You can Switch remote URLs from HTTPS to SSH.</p>
<p>1.Pls refer to this link for details:<a href="https://help.github.com/articles/changing-a-remote-s-url/" rel="noreferrer">https://help.github.com/articles/changing-a-remote-s-url/</a></p>
<p>Also I had to config the ssh key.</p>
<p>2.Follow this:<a href="https://help.github.com/articles/generating-ssh-keys/" rel="noreferrer">https://help.github.com/articles/generating-ssh-keys/</a></p>
<p>I came across this problem because I replaced my mac, but I do the transfer of data,I think it is probably because the key reasons.</p> |
27,416,164 | What is CoNLL data format? | <p>I am new to text mining. I am using a open source jar (Mate Parser) which gives me output in a CoNLL 2009 format after dependency parsing. I want to use the dependency parsing results for Information Extraction. But i am able to understand some of the output but not able to comprehend the CoNLL data format. Can any one help me in making me understand the CoNLL data format?? Any kind of pointers would be appreciated.</p> | 27,425,613 | 2 | 1 | null | 2014-12-11 05:45:51.443 UTC | 22 | 2022-02-23 16:49:57.69 UTC | null | null | null | null | 3,505,968 | null | 1 | 64 | nlp|text-parsing|text-mining|information-extraction | 46,228 | <p>There are many different <a href="http://ifarm.nl/signll/conll/" rel="nofollow noreferrer">CoNLL</a> formats since CoNLL is a different shared task each year. The format for CoNLL 2009 is described <a href="http://ufal.mff.cuni.cz/conll2009-st/task-description.html" rel="nofollow noreferrer">here</a>. Each line represents a single word with a series of tab-separated fields. <code>_</code>s indicate empty values. <a href="https://mate-tools.googlecode.com/files/shortmanual.pdf" rel="nofollow noreferrer">Mate-Parser's manual</a> says that it uses the first 12 columns of CoNLL 2009:</p>
<pre><code>ID FORM LEMMA PLEMMA POS PPOS FEAT PFEAT HEAD PHEAD DEPREL PDEPREL
</code></pre>
<p>The definition of some of these columns come from earlier shared tasks (the <a href="https://web.archive.org/web/20160814191537/http://ilk.uvt.nl/conll/#dataformat" rel="nofollow noreferrer">CoNLL-X format</a> used in 2006 and 2007):</p>
<ul>
<li><code>ID</code> (index in sentence, starting at 1)</li>
<li><code>FORM</code> (word form itself)</li>
<li><code>LEMMA</code> (word's lemma or stem)</li>
<li><code>POS</code> (part of speech)</li>
<li><code>FEAT</code> (list of morphological features separated by |)</li>
<li><code>HEAD</code> (index of syntactic parent, 0 for <code>ROOT</code>)</li>
<li><code>DEPREL</code> (syntactic relationship between <code>HEAD</code> and this word)</li>
</ul>
<p>There are variants of those columns (e.g., <code>PPOS</code> but not <code>POS</code>) that start with <code>P</code> indicate that the value was automatically predicted rather a gold standard value.</p>
<p><strong>Update:</strong> There is now a <a href="http://universaldependencies.github.io/docs/format.html" rel="nofollow noreferrer">CoNLL-U</a> data format as well which extends the CoNLL-X format.</p> |
438,610 | How do I write a query that outputs the row number as a column? | <p>How do I write a query that outputs the row number as a column? This is DB2 SQL on an iSeries.</p>
<p>eg if I have</p>
<p>table Beatles:</p>
<pre><code>John
Paul
George
Ringo
</code></pre>
<p>and I want to write a statement, without writing a procedure or view if possible, that gives me</p>
<pre><code>1 John
2 Paul
3 George
4 Ringo
</code></pre> | 438,640 | 3 | 0 | null | 2009-01-13 10:53:56.74 UTC | 2 | 2013-10-28 05:59:44.653 UTC | 2009-01-13 11:05:32.49 UTC | nearly_lunchtime | 23,447 | nearly_lunchtime | 23,447 | null | 1 | 14 | sql|db2 | 62,271 | <pre><code>SELECT ROW_NUMBER() OVER (ORDER BY beatle_name ASC) AS ROWID, * FROM beatles
</code></pre> |
1,182,315 | Python: Multicore processing? | <p>I've been reading about Python's <a href="http://docs.python.org/library/multiprocessing.html" rel="noreferrer">multiprocessing module</a>. I still don't think I have a very good understanding of what it can do.</p>
<p>Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply do:</p>
<pre><code>list_sum = sum(my_list)
</code></pre>
<p>But this only sends it to one core.</p>
<p>Is it possible, using the multiprocessing module, to divide the array up and have each core get the sum of it's part and return the value so the total sum may be computed?</p>
<p>Something like:</p>
<pre><code>core1_sum = sum(my_list[0:500000]) #goes to core 1
core2_sum = sum(my_list[500001:1000000]) #goes to core 2
all_core_sum = core1_sum + core2_sum #core 3 does final computation
</code></pre>
<p>Any help would be appreciated.</p> | 1,182,350 | 3 | 0 | null | 2009-07-25 15:31:35.79 UTC | 19 | 2009-07-25 18:32:32.057 UTC | 2009-07-25 15:41:57.753 UTC | null | 33,006 | null | 41,718 | null | 1 | 29 | python|multicore|multiprocessing | 43,540 | <p>Yes, it's possible to do this summation over several processes, very much like doing it with multiple threads:</p>
<pre><code>from multiprocessing import Process, Queue
def do_sum(q,l):
q.put(sum(l))
def main():
my_list = range(1000000)
q = Queue()
p1 = Process(target=do_sum, args=(q,my_list[:500000]))
p2 = Process(target=do_sum, args=(q,my_list[500000:]))
p1.start()
p2.start()
r1 = q.get()
r2 = q.get()
print r1+r2
if __name__=='__main__':
main()
</code></pre>
<p>However, it is likely that doing it with multiple processes is likely slower than doing it in a single process, as copying the data forth and back is more expensive than summing them right away.</p> |
672,501 | Is there an easy way to use InternalsVisibleToAttribute? | <p>I have a C# project and a test project with unit tests for the main project. I want to have testable <code>internal</code> methods and I want to test them without a magical Accessor object that you can have with Visual Studio test projects. I want to use <strong><code>InternalsVisibleToAttribute</code></strong> but every time I've done it I've had to go back and look up how to do it, which I remember involves creating key files for signing the assemblies and then using <code>sn.exe</code> to get the public key and so on. </p>
<ul>
<li><p><strong>Is there a utility that automates the process of creating a SNK file, setting projects to sign the assemblies, extracting the public key, and applying the <em>InternalsVisibleTo</em> attribute?</strong></p></li>
<li><p><strong>Is there a way to use the attribute <em>without</em> signed assemblies?</strong></p></li>
</ul> | 672,510 | 3 | 0 | null | 2009-03-23 07:48:55.287 UTC | 6 | 2017-07-21 12:15:11.993 UTC | 2009-03-23 20:58:33.297 UTC | marxidad | 1,659 | marxidad | 1,659 | null | 1 | 33 | c#|.net|visual-studio | 14,730 | <p>You don't have to use signed assemblies to use <code>InternalsVisibleTo</code>. If you don't use signed assemblies, you can just enter the full name of the assembly. </p>
<p>So if you want to have access to <code>MyAssembly</code> in you test assembly (<code>MyAssembly.Test</code>) all you need in <code>AssemblyInfo.cs</code> for <code>MyAssembly</code> is the name of the test assembly like this:</p>
<pre><code>[assembly: InternalsVisibleTo("CompanyName.Project.MyAssembly.Test")]
</code></pre> |
680,022 | Is there a decent Vim regexp OR command? What is the best way to find mismatched if else's? | <p>I have some mismatching if and fi statements in a script. I would like to strip out everything but the if's else's and fi's. Just so I can see the structure. Why am working so HARD with such a powerful editor? I need a <strong>BIGFATOR</strong> operator for regexp or some epiphany that has eluded me... I don't care for pontification on regular expressions just something practical working in VIM7.2. </p>
<blockquote>
<p>:g/[ ^\t]if [/print</p>
</blockquote>
<p>will print out the ifs </p>
<blockquote>
<p>:g/[ ^\t]fi/print</p>
</blockquote>
<p>will printout the fi</p>
<p>What I want to do is or the conditions</p>
<p>:g/[ ^\t]fi <strong>BIGFATOROPERATOR</strong> [ ^\t]fi/print</p>
<p>I have had success doing the following... but I feel I am working TOO HARD!</p>
<blockquote>
<p>:call TripMatch('[ ^\t]*if [', 'else', 'fi[ \t$]')</p>
<p>function! TripMatch(str1, str2, str3)</p>
<p>let var1 = a:str1</p>
<p>let var2 = a:str2</p>
<p>let var3 = a:str3</p>
<p>let max = line("$")</p>
<p>let n = 1</p>
<p>for n in range (1, max)</p>
<p>let currentline = getline(n)</p>
<pre><code>if currentline =~? var1
echo n "1:" currentline
else
if currentline =~? var2
echo n "2:" currentline
else
if currentline =~? var3
echo n "3:" currentline
else
let foo = "do nothing"
endif
endif
endif
</code></pre>
<p>endfor</p>
<p>endfunction</p>
</blockquote> | 680,031 | 3 | 0 | null | 2009-03-25 02:30:31.727 UTC | 16 | 2009-09-10 21:41:29.94 UTC | 2009-04-03 22:03:59.973 UTC | Chad Birch | 41,665 | ojblass | 66,519 | null | 1 | 45 | regex|vim | 25,006 | <pre><code>:g/[ ^\t]if\|[ ^\t]fi/print
</code></pre>
<p><strong>BIGFATOROPERATOR</strong> is <code>\|</code>. It's called the <a href="http://devmanual.gentoo.org/tools-reference/sed/index.html" rel="noreferrer">alternation operator</a>. In PCRE, it's plain <code>|</code>. It's escaped in Vim/ex because <code>|</code> is used elsewhere for general commands (or something -- FIXME).</p> |
6,899,392 | Generic Hash function for all STL-containers | <p>I'm using an <code>std::unordered_map<key,value></code> in my implementation. i will be using any of the STL containers as the key. I was wondering if it is possible to create a generic hash function for any container being used. </p>
<p><a href="https://stackoverflow.com/questions/4850473/pretty-print-c-stl-containers">This</a> question in SO offers generic print function for all STL containers. While you can have that, why cant you have something like a Hash function that defines everything ? And yeah, a big concern is also that it needs to fast and efficient. </p>
<p>I was considering doing a simple hash function that converts the values of the key to a <code>size_t</code> and do a simple function like <a href="https://stackoverflow.com/questions/628790/have-a-good-hash-function-for-a-c-hash-table">this</a>.</p>
<p>Can this be done ?</p>
<p>PS : Please don't use <code>boost</code> libraries. Thanks.</p> | 6,899,457 | 1 | 3 | null | 2011-08-01 13:52:03.733 UTC | 10 | 2014-07-24 09:51:31.31 UTC | 2017-05-23 12:16:40.643 UTC | null | -1 | null | 419,074 | null | 1 | 14 | c++|stl|hash|map|c++11 | 4,609 | <p>We can get an answer by mimicking Boost and combining hashes.</p>
<p><strong>Warning:</strong> Combining hashes, i.e. computing a hash of many things from many hashes of the things, is not a good idea generally, since the resulting hash function is not "good" in the statistical sense. A proper hash of many things should be build from the entire raw data of all the constituents, not from intermediate hashes. But there currently isn't a good standard way of doing this.</p>
<p>Anyway:</p>
<p>First off, we need the <code>hash_combine</code> function. For reasons beyond my understanding it's not been included in the standard library, but it's the centrepiece for everything else:</p>
<pre><code>template <class T>
inline void hash_combine(std::size_t & seed, const T & v)
{
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
</code></pre>
<p>Using this, we can hash everything that's made up from hashable elements, in particular pairs and tuples (exercise for the reader).</p>
<p>However, we can also use this to hash containers by hashing their elements. This is precisely what Boost's "range hash" does, but it's straight-forward to make that yourself by using the combine function.</p>
<p>Once you're done writing your range hasher, just specialize <code>std::hash</code> and you're good to go:</p>
<pre><code>namespace std
{
template <typename T, class Comp, class Alloc>
struct hash<std::set<T, Comp, Alloc>>
{
inline std::size_t operator()(const std::set<T, Comp, Alloc> & s) const
{
return my_range_hash(s.begin(), s.end());
}
};
/* ... ditto for other containers */
}
</code></pre>
<p>If you want to mimic the pretty printer, you could even do something more extreme and specialize <code>std::hash</code> for all containers, but I'd probably be more careful with that and make an explicit hash object for containers:</p>
<pre><code>template <typename C> struct ContainerHasher
{
typedef typename C::value_type value_type;
inline size_t operator()(const C & c) const
{
size_t seed = 0;
for (typename C::const_iterator it = c.begin(), end = c.end(); it != end; ++it)
{
hash_combine<value_type>(seed, *it);
}
return seed;
}
};
</code></pre>
<p>Usage:</p>
<pre><code>std::unordered_map<std::set<int>, std::string, ContainerHasher<std::set<int>>> x;
</code></pre> |
36,648,375 | What are the differences between IMPORTED target and INTERFACE libraries? | <p>As I understand it <a href="https://cmake.org/cmake/help/v3.5/command/add_library.html?highlight=interface#interface-libraries" rel="noreferrer">INTERFACE</a> libraries are like <a href="https://msdn.microsoft.com/en-us/library/669zx6zc.aspx" rel="noreferrer">Visual Studio property sheets</a>, so very useful. We can use it to link with static libs and propagate properties.</p>
<p>But <a href="https://cmake.org/cmake/help/v3.5/command/add_library.html?highlight=interface#imported-libraries" rel="noreferrer">IMPORTED</a> targets bother me : I can't see a problem which can be solved with IMPORTED target only.</p> | 36,649,194 | 2 | 2 | null | 2016-04-15 13:22:01.253 UTC | 15 | 2018-10-22 07:10:49.423 UTC | 2016-04-15 15:03:07.973 UTC | null | 282,815 | null | 282,815 | null | 1 | 23 | cmake | 14,359 | <p>When you create an imported target, you're telling CMake: I have this { static library | shared library | module library | executable } already built in this location on disk. I want to be able to treat it just like a target built by my own buildsystem, so take note that when I say <code>ImportedTargetName</code>, it should refer to that binary on disk (with the associated import lib if applicable, and so on).</p>
<p>When you create an interface library, you're telling CMake: I have this set of properties (include directories etc.) which clients can use, so if they "link" to my interface library, please propagate these properties to them.</p>
<p>The fundamental difference is that interface libraries are not backed by anything on disk, they're just a set of requirements/properties. You <em>can</em> set the <code>INTERFACE_LINK_LIBRARIES</code> property on an interface library if you really want to, but that's not really what they were designed for. They're to encapsulate client-consumable properties, and make sense primarily for things like header-only libraries in C++.</p>
<p>Also notice that an interface library is a <em>library</em>—there's no such thing as an interface executable, but you can indeed have imported executables. E.g. a package config file for Bison could define an imported target for the Bison executable, and your project could then use it for custom commands:</p>
<pre><code># In Bison package config file:
add_executable(Bison IMPORTED)
set_property(TARGET Bison PROPERTY IMPORTED_LOCATION ...)
# In your project:
find_package(Bison)
add_custom_command(
OUTPUT parser.c
COMMAND Bison tab.y -o parser.c
DEPENDS tab.y
...
)
</code></pre>
<p>(Bison is used just as an example of something you might want to use in custom commands, and the command line is probably not right for it).</p> |
34,913,590 | Fillna in multiple columns in place in Python Pandas | <p>I have a pandas dataFrame of mixed types, some are strings and some are numbers. I would like to replace the NAN values in string columns by '.', and the NAN values in float columns by 0.</p>
<p>Consider this small fictitious example:</p>
<pre><code>df = pd.DataFrame({'Name':['Jack','Sue',pd.np.nan,'Bob','Alice','John'],
'A': [1, 2.1, pd.np.nan, 4.7, 5.6, 6.8],
'B': [.25, pd.np.nan, pd.np.nan, 4, 12.2, 14.4],
'City':['Seattle','SF','LA','OC',pd.np.nan,pd.np.nan]})
</code></pre>
<p>Now, I can do it in 3 lines:</p>
<pre><code>df['Name'].fillna('.',inplace=True)
df['City'].fillna('.',inplace=True)
df.fillna(0,inplace=True)
</code></pre>
<p>Since this is a small dataframe, 3 lines is probably ok. In my real example (which I cannot share here due to data confidentiality reasons), I have many more string columns and numeric columns. SO I end up writing many lines just for fillna. Is there a concise way of doing this? </p> | 34,916,691 | 9 | 2 | null | 2016-01-21 01:00:25.927 UTC | 22 | 2022-05-17 20:33:06.98 UTC | 2016-01-21 01:38:24.95 UTC | null | 2,838,606 | null | 5,818,752 | null | 1 | 54 | python|pandas|dataframe | 85,107 | <p>You could use <a href="https://www.google.ru/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjEkvbtobrKAhXJkSwKHVRRAxgQFggcMAA&url=http%3A%2F%2Fpandas.pydata.org%2Fpandas-docs%2Fversion%2F0.17.1%2Fgenerated%2Fpandas.DataFrame.apply.html&usg=AFQjCNEV-3rhym9xF5j7u78SpzSm6Ra4PA" rel="noreferrer"><code>apply</code></a> for your columns with checking <code>dtype</code> whether it's <code>numeric</code> or not by checking <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.dtype.kind.html" rel="noreferrer"><code>dtype.kind</code></a>:</p>
<pre><code>res = df.apply(lambda x: x.fillna(0) if x.dtype.kind in 'biufc' else x.fillna('.'))
print(res)
A B City Name
0 1.0 0.25 Seattle Jack
1 2.1 0.00 SF Sue
2 0.0 0.00 LA .
3 4.7 4.00 OC Bob
4 5.6 12.20 . Alice
5 6.8 14.40 . John
</code></pre> |
20,520,614 | tableau aggregate data based on dimension | <p>I am having a problem in Tableau, hopefully someone can help me and
is very much appreciated!!</p>
<p>A simplifiend example of a problem I can't fix in Tableau:</p>
<pre><code>Payment Customer Amount
1 BMW 20000
2 VW 30000
3 BMW 1000
4 VW 5000
5 VW 6000
</code></pre>
<p>This has to be aggregated on the Customer level and has to look like this:</p>
<pre><code>Customer Amount
BMW 21000
VW 41000
</code></pre>
<p>This is for 10.000 customers.. </p>
<p>Thanks in advance!</p>
<p>Tim</p>
<hr>
<p><img src="https://i.stack.imgur.com/ZIzhE.png" alt="my data"></p>
<p>I want to take the average/mean/max for each year (pool cut-off date) in order to compare the years.</p>
<p>In R I always saved the new dataframe, but here this seems to be different.</p>
<p>Thanks,</p>
<p>Tim</p> | 20,549,727 | 2 | 0 | null | 2013-12-11 13:36:09.283 UTC | 1 | 2014-03-06 17:24:04.173 UTC | 2014-03-06 17:24:04.173 UTC | null | 19,679 | null | 2,944,773 | null | 1 | 2 | aggregate-functions|aggregate|tableau-api | 40,130 | <p>Sum() is one of Tableau's built-in aggregation functions, so there is no need to write a calculated field if that's all you're doing. Just drag the [Amount] field on to (say) the text shelf and select Sum() as the aggregation. Then put [Customer] on the row shelf.</p>
<p>Sum() is efficient, and performed on the database server only sending back the results to the client. So if you are summing a million rows, only the answer needs to be sent over the wire. Of course, if you are grouping by a dimension so that half your dimension members have only one row, you'll still be sending back lots of data.</p>
<p>If your calculation is more complicated, emh is correct about where to start making calculated fields.</p> |
24,196,820 | NSData from Byte array in Swift | <p>I'm trying to create an <code>NSData</code> <code>var</code> from an array of bytes.</p>
<p>In Obj-C I might have done this: </p>
<p><code>NSData *endMarker = [[NSData alloc] initWithBytes:{ 0xFF, 0xD9 }, length: 2]</code></p>
<p>I can't figure out a working equivalent in Swift.</p> | 24,196,962 | 6 | 0 | null | 2014-06-13 02:32:04.157 UTC | 9 | 2022-05-26 22:22:49.083 UTC | null | null | null | null | 8,597 | null | 1 | 38 | ios|swift | 61,682 | <p><code>NSData</code> has an initializer that takes a <code>bytes</code> pointer: <code>init(bytes: UnsafeMutablePointer <Void>, length: Int)</code>. An <code>UnsafePointer</code> parameter can accept a variety of different things, including a simple Swift array, so you can use pretty much the same syntax as in Objective-C. When you pass the array, you need to make sure you identify it as a <code>UInt8</code> array or Swift's type inference will assume you mean to create an <code>Int</code> array.</p>
<pre><code>var endMarker = NSData(bytes: [0xFF, 0xD9] as [UInt8], length: 2)
</code></pre>
<p>You can read more about unsafe pointer parameters in Apple's <a href="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/buildingcocoaapps/InteractingWithCAPIs.html">Interacting with C APIs</a> documentation.</p> |
19,936,025 | java JPanel How to fixed sizes | <p>I want to have a resizable panel, that always has the top green panel of a fixed depth. i.e. all changes in height should effect the yellow panel only.</p>
<p>My code below is almost OK, except the green panel varies in size a little.</p>
<p>How do I do this?</p>
<pre><code> Panel.setLayout(new BoxLayout(Panel, BoxLayout.Y_AXIS));
Panel.setAlignmentX(Component.LEFT_ALIGNMENT);
JPanel TopPanel = new JPanel();
TopPanel.setPreferredSize(new Dimension(80,150));
TopPanel.setVisible(true);
TopPanel.setBackground(Color.GREEN);
JPanel MainPanel = new JPanel();
MainPanel.setPreferredSize(new Dimension(80,750));
MainPanel.setVisible(true);
MainPanel.setOpaque(true);
MainPanel.setBackground(Color.YELLOW);
Panel.add(TopPanel);
Panel.add(MainPanel);
</code></pre>
<p><img src="https://i.stack.imgur.com/geXv2.jpg" alt="enter image description here"></p> | 19,936,269 | 2 | 0 | null | 2013-11-12 17:34:15.993 UTC | null | 2013-11-12 18:57:38.937 UTC | 2013-11-12 17:43:25.413 UTC | null | 418,556 | null | 439,497 | null | 1 | 12 | java|swing|jpanel|layout-manager | 46,468 | <p>Your question didn't restrict the solution to a <code>BoxLayout</code>, so I am going to suggest a different layout manager.</p>
<p>I would attack this with a <code>BorderLayout</code> and put the green panel in the PAGE_START location. Then put the yellow panel in the CENTER location without a <code>preferredSize</code> call.</p>
<p><a href="http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html</a></p>
<p>Here is an SSCCE example of the solution:</p>
<pre><code>import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestPad extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
JPanel green = new JPanel();
green.setPreferredSize(new Dimension(80, 150));
green.setBackground(Color.GREEN);
JPanel yellow = new JPanel();
yellow.setBackground(Color.YELLOW);
frame.getContentPane().add(green, BorderLayout.PAGE_START);
frame.getContentPane().add(yellow, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
</code></pre> |
5,753,256 | popTOViewController | <p>I have a button named 'HOME'. In that button action I have the following code:</p>
<pre><code>[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
</code></pre>
<p>When I click this button my app crashes.</p>
<p>Changing the index from 1 to 2, then it pops the view perfectly.</p>
<pre><code>[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
</code></pre>
<p>My view sequence is Page1 --> Page2 --> Page3 </p>
<p>I want to go from Page3 to Page1 but the app crashes. From Page3 to Page2 it works fine.</p> | 5,753,313 | 4 | 0 | null | 2011-04-22 07:32:05.95 UTC | 15 | 2018-07-19 10:18:42.48 UTC | 2016-01-29 19:31:00.837 UTC | null | 4,486,699 | null | 699,655 | null | 1 | 30 | ios|objective-c | 30,747 | <p>Try this.</p>
<p>Where I have written SeeMyScoresViewController you should write your View Controller class on which you have to go.(eg. Class of Home)</p>
<pre><code>NSArray *viewControllers = [[self navigationController] viewControllers];
for( int i=0;i<[viewControllers count];i++){
id obj=[viewControllers objectAtIndex:i];
if([obj isKindOfClass:[SeeMyScoresViewController class]]){
[[self navigationController] popToViewController:obj animated:YES];
return;
}
}
</code></pre> |
34,873,209 | Implementation of strcmp | <p>I tried to implement <a href="http://pubs.opengroup.org/onlinepubs/009695399/functions/strcmp.html" rel="nofollow noreferrer"><code>strcmp</code></a>:</p>
<pre><code>int strCmp(char string1[], char string2[])
{
int i = 0, flag = 0;
while (flag == 0) {
if (string1[i] > string2[i]) {
flag = 1;
} else
if (string1[i] < string2[i]) {
flag = -1;
} else {
i++;
}
}
return flag;
}
</code></pre>
<p>but I'm stuck with the case that the user will input the same strings, because the function works with <code>1</code> and <code>-1</code>, but it's doesn't return <code>0</code>. Can anyone help? And please without pointers!</p> | 34,874,063 | 8 | 1 | null | 2016-01-19 09:38:27.463 UTC | 8 | 2021-11-14 06:00:30.21 UTC | 2020-12-01 14:09:13.867 UTC | null | 4,593,267 | null | 5,655,007 | null | 1 | 9 | c|c-strings|strcmp | 40,093 | <p>You seem to want to avoid pointer arithmetics which is a pity since that makes the solution shorter, but your problem is just that you scan beyond the end of the strings. Adding an explicit break will work. Your program slightly modified:</p>
<pre><code>int strCmp(char string1[], char string2[] )
{
int i = 0;
int flag = 0;
while (flag == 0)
{
if (string1[i] > string2[i])
{
flag = 1;
}
else if (string1[i] < string2[i])
{
flag = -1;
}
if (string1[i] == '\0')
{
break;
}
i++;
}
return flag;
}
</code></pre>
<p>A shorter version:</p>
<pre><code>int strCmp(char string1[], char string2[] )
{
for (int i = 0; ; i++)
{
if (string1[i] != string2[i])
{
return string1[i] < string2[i] ? -1 : 1;
}
if (string1[i] == '\0')
{
return 0;
}
}
}
</code></pre> |
34,458,985 | Eloquent model returns 0 as primary key | <p>I have this migration:</p>
<pre><code>Schema::create('provincias', function (Blueprint $table) {
$table->string('codigo', 2);
$table->string('nombre', 50);
$table->timestamp('creado');
$table->primary('codigo');
});
</code></pre>
<p>This is my model:</p>
<pre><code>class Provincia extends Model
{
protected $primaryKey = 'codigo';
public $timestamps = false;
}
</code></pre>
<p>I run the migration and save data like this:</p>
<pre><code>$provincia = new Provincia;
$provincia->codigo = "BA";
$provincia->nombre = "Buenos Aires";
$provincia->save();
</code></pre>
<p>The problem is that when I get all and dump:</p>
<pre><code>$provincias = Provincia::all();
return $provincias;
</code></pre>
<p>The primary key "codigo" is always 0 even when I check the database table and it has the proper value:</p>
<pre><code>{
codigo: 0,
nombre: "Buenos Aires",
creado: "2015-12-24 21:00:24"
}
</code></pre> | 34,459,024 | 2 | 1 | null | 2015-12-25 00:07:29.113 UTC | 3 | 2019-05-20 10:51:33.52 UTC | null | null | null | null | 1,922,561 | null | 1 | 30 | laravel|eloquent | 10,927 | <p>You can try setting <code>public $incrementing = false;</code> on your model so eloquent doesn't expect your primary key to be an autoincrement primary key.</p> |
2,017,865 | SQL Server 2008 Open Master Key error upon physical server change over | <p>I copied a SQL Server database from one system to the next, identical setup, but completely different physical machine. I used Norton Ghost and recoverd files manually, for example, the entire SQL Server 2008 folder found in c:\Program Files after re-installing SQL Server 2008 Express. </p>
<p>One of my databases has AES_256 encryption enabled on a number of one of its tables, columns. I resetup my IIS7 and tried to run the app that access the database, upon retrieving the data, I get this error:</p>
<blockquote>
<p>Server Error in '/' Application.
Please create a master key in the
database or open the master key in the
session before performing this
operation. Description: An unhandled
exception occurred during the
execution of the current web request.
Please review the stack trace for more
information about the error and where
it originated in the code.</p>
<p>Exception Details:
System.Data.SqlClient.SqlException:
Please create a master key in the
database or open the master key in the
session before performing this
operation.</p>
<p>Source Error:</p>
<p>An unhandled exception was generated
during the execution of the current
web request. Information regarding the
origin and location of the exception
can be identified using the exception
stack trace below.</p>
</blockquote>
<p>I've done some reading and found some links about how the AES encryption is linked with the machine key, but am at a loss as to how to copy it over to the new system. Or perhaps this even isn't the case. </p>
<p>NOTE: I've tried dropping the symmetric key, certificate and the master key and re-creating them. This gets rid of the error, but than the data that in encrypted via AES_256 does not show up. The columns that are NOT encrypted do, however.</p>
<p>Any help would be much appreciated. Thanks in advance! </p> | 2,018,063 | 2 | 0 | null | 2010-01-07 02:37:39.513 UTC | 13 | 2018-06-19 02:34:16.71 UTC | 2010-01-07 06:08:24.003 UTC | null | 13,302 | null | 113,329 | null | 1 | 25 | sql|sql-server-2008|encryption|aes | 29,749 | <p>The database master key is encrypted using the server master key, which is specific to the machine where SQL Server is installed. When you move the database to another server, you lose the ability to automatically decrypt and open the database master key because the local server key will most likely be different. If you can't decrypt the database master key, you can't decrypt anything else that depends on it (certificates, symmetric keys, etc).</p>
<p>Basically, you want to re-encrypt the database master key against the new server key, which can be done with this script (using admin privileges):</p>
<pre><code>-- Reset database master key for server (if database was restored from backups on another server)
OPEN MASTER KEY DECRYPTION BY PASSWORD = '---your database master key password---'
ALTER MASTER KEY ADD ENCRYPTION BY SERVICE MASTER KEY
GO
</code></pre>
<p>Note that when you create a database master key, you should always provide a password as well so that you can open the key using the password in the scenario where the service master key cannot be used - hopefully you've got that password stored somewhere!</p>
<p>Alternatively, you can restore a backup of the database master key - but you need one that was created for the target server, not the source server.</p>
<p>If you haven't got either a backup or a password, then I'm not sure you will be able to recover the encrypted data on the new server, as you will have to drop and recreate the database master key with a new password, which will kill any dependent keys and data.</p> |
1,374,098 | With.Parameters.ConstructorArgument with ninject 2.0 | <p>How to use this functionality in ninject 2.0?</p>
<pre><code>MyType obj = kernel.Get<MyType>(With.Parameters.ConstructorArgument("foo","bar"));
</code></pre>
<p>The "With" isn't there :(</p> | 1,375,734 | 2 | 0 | null | 2009-09-03 15:22:46.12 UTC | 11 | 2011-10-30 19:04:21.567 UTC | 2011-10-30 19:04:21.567 UTC | null | 11,635 | null | 22,693 | null | 1 | 35 | c#|ninject | 13,159 | <pre><code> [Fact]
public void CtorArgTestResolveAtGet()
{
IKernel kernel = new StandardKernel();
kernel.Bind<IWarrior>().To<Samurai>();
var warrior = kernel
.Get<IWarrior>( new ConstructorArgument( "weapon", new Sword() ) );
Assert.IsType<Sword>( warrior.Weapon );
}
[Fact]
public void CtorArgTestResolveAtBind()
{
IKernel kernel = new StandardKernel();
kernel.Bind<IWarrior>().To<Samurai>()
.WithConstructorArgument("weapon", new Sword() );
var warrior = kernel.Get<IWarrior>();
Assert.IsType<Sword>( warrior.Weapon );
}
</code></pre> |
5,841,370 | Can't get my EC2 Windows Server 2008 (Web stack) instance to receive publishings of my website | <p>I installed a fresh AMI for EC2 (<a href="http://aws.amazon.com/amis/Microsoft/5147732567196848" rel="nofollow noreferrer">http://aws.amazon.com/amis/Microsoft/5147732567196848</a>) and have installed Web deploy 2.1 on it.</p>
<p>The web deploy 2.1 service is running for real as</p>
<pre><code>netstat -an
</code></pre>
<p>Shows 8172 is being listened on by the Web Deployment Agent Service.</p>
<p>But, when I try to deploy to this site using Project->right-click->Publish (via web deploy) I receive the following error message</p>
<pre><code>------ Build started: Project: Cir.Web, Configuration: Debug Any CPU ------
Cir.Web -> C:\Projects\CrazyInsaneRobot\Source\Cir.Web\bin\Cir.Web.dll
------ Publish started: Project: Cir.Web, Configuration: Debug Any CPU ------
Transformed Web.config using Web.Debug.config into obj\Debug\TransformWebConfig\transformed\Web.config.
Auto ConnectionString Transformed Views\Web.config into obj\Debug\CSAutoParameterize\transformed\Views\Web.config.
Auto ConnectionString Transformed obj\Debug\TransformWebConfig\transformed\Web.config into obj\Debug\CSAutoParameterize\transformed\Web.config.
Copying all files to temporary location below for package/publish:
obj\Debug\Package\PackageTmp.
Start Web Deploy Publish the Application/package to https://ec2-175-41-170-198.ap-southeast-1.compute.amazonaws.com:8172/msdeploy.axd?site=Default%20Web%20Site ...
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets(3847,5): Warning : Retrying the sync because a socket error (10054) occurred.
Retrying operation 'Serialization' on object sitemanifest (sourcePath). Attempt 1 of 10.
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets(3847,5): Warning : Retrying the sync because a socket error (10054) occurred.
Retrying operation 'Serialization' on object sitemanifest (sourcePath). Attempt 2 of
...
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets(3847,5): Warning : Retrying the sync because a socket error (10054) occurred.
Retrying operation 'Serialization' on object sitemanifest (sourcePath). Attempt 10 of 10.
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets(3847,5): Error : Web deployment task failed.(Could not complete the request to remote agent URL 'https://ec2-175-41-170-198.ap-southeast-1.compute.amazonaws.com:8172/msdeploy.axd?site=Default Web Site'.)
This error indicates that you cannot connect to the server. Make sure the service URL is correct, firewall and network settings on this computer and on the server computer are configured properly, and the appropriate services have been started on the server.
Error details:
Could not complete the request to remote agent URL 'https://ec2-175-41-170-198.ap-southeast-1.compute.amazonaws.com:8172/msdeploy.axd?site=Default Web Site'.
The underlying connection was closed: An unexpected error occurred on a send.
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
An existing connection was forcibly closed by the remote host
Publish failed to deploy.
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
========== Publish: 0 succeeded, 1 failed, 0 skipped ==========
</code></pre>
<p>My firewall on the EC2 instance has been turned off. And my AWS firewall settings are</p>
<p><img src="https://i.stack.imgur.com/RJdi7.png" alt="http://dl.dropbox.com/u/7881451/ec2-firewall-settings.PNG"></p>
<p>which are the recommended settings.</p>
<p>Other notes/thoughts:</p>
<ul>
<li>My Web Deploy Error log in the windows error log is completely empty</li>
<li>I've used web deploy before using a different AMI in the past and succeeded without problems.</li>
</ul>
<p>If anyone has any suggestions about how to debug this, I would be so ever grateful!</p> | 6,242,793 | 5 | 3 | null | 2011-04-30 11:11:06.34 UTC | 10 | 2017-11-20 23:59:03.603 UTC | 2014-09-21 10:05:52.69 UTC | null | 1,505,120 | null | 209 | null | 1 | 18 | asp.net|iis|amazon-ec2|webdeploy | 12,228 | <p>I contact Microsoft directly about this problem and they had an immediate answer for me.</p>
<p><strong>From MS guy:</strong></p>
<p>It looks like your Web Management Service not contactable. I have seen this before when the certificate for the service is invalid. Can you run the attached script on your server?</p>
<ol>
<li>Start a PowerShell prompt elevated</li>
<li>Run set-executionpolicy unrestricted –force</li>
<li>Run .\00_Certificate.ps1</li>
<li>Net stop wmsvc</li>
<li>Net start wmsvc</li>
</ol>
<p>Does this fix the problem?</p>
<hr>
<p>The script he is referring to is <a href="https://www.dropbox.com/s/9de96l9dyyrfvdg/00_Certificate.zip?dl=0" rel="nofollow noreferrer">available here</a> </p> |
5,731,042 | Split array into two parts without for loop in java | <p>I have an array of size 300000 and i want it to split it into 2 equal parts. Is there any method that can be used here to achieve this goal?</p>
<p>Will it be faster than the for-loop operation or it will cause no effect on performance?</p> | 5,731,124 | 5 | 0 | null | 2011-04-20 13:24:56.347 UTC | 8 | 2017-10-06 13:14:20.793 UTC | null | null | null | null | 461,537 | null | 1 | 42 | java|arrays | 143,321 | <p>You can use <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#arraycopy-java.lang.Object-int-java.lang.Object-int-int-" rel="noreferrer"><code>System.arraycopy()</code></a>.</p>
<pre><code>int[] source = new int[1000];
int[] part1 = new int[500];
int[] part2 = new int[500];
// (src , src-offset , dest , offset, count)
System.arraycopy(source, 0 , part1, 0 , part1.length);
System.arraycopy(source, part1.length, part2, 0 , part2.length);
</code></pre> |
6,163,611 | Compare two files | <p>I'm trying to write a function which compares the content of two files.</p>
<p>I want it to return 1 if files are the same, and 0 if different.</p>
<p><code>ch1</code> and <code>ch2</code> works as a buffer, and I used <code>fgets</code> to get the content of my files.</p>
<p>I think there is something wrong with the <code>eof</code> pointer, but I'm not sure. <code>FILE</code> variables are given within the command line.</p>
<p>P.S. It works with small files with size under 64KB, but doesn't work with larger files (700MB movies for example, or 5MB of .mp3 files).</p>
<p>Any ideas, how to work it out?</p>
<pre><code>int compareFile(FILE* file_compared, FILE* file_checked)
{
bool diff = 0;
int N = 65536;
char* b1 = (char*) calloc (1, N+1);
char* b2 = (char*) calloc (1, N+1);
size_t s1, s2;
do {
s1 = fread(b1, 1, N, file_compared);
s2 = fread(b2, 1, N, file_checked);
if (s1 != s2 || memcmp(b1, b2, s1)) {
diff = 1;
break;
}
} while (!feof(file_compared) || !feof(file_checked));
free(b1);
free(b2);
if (diff) return 0;
else return 1;
}
</code></pre>
<p>EDIT: I've improved this function with the inclusion of your answers. But it's only comparing first buffer only -> but with an exception -> I figured out that it stops reading the file until it reaches 1A character (attached file). How can we make it work?</p>
<p>EDIT2: Task solved (working code attached). Thanks to everyone for the help!</p> | 6,163,633 | 6 | 7 | null | 2011-05-28 18:28:36.093 UTC | 8 | 2018-03-16 11:05:49.793 UTC | 2018-03-16 11:05:49.793 UTC | null | 4,393,935 | null | 595,535 | null | 1 | 14 | c++ | 48,355 | <p>Since you've allocated your arrays on the stack, they are filled with random values ... they aren't zeroed out.</p>
<p>Secondly, <code>strcmp</code> will only compare to the first NULL value, which, if it's a binary file, won't necessarily be at the end of the file. Therefore you should really be using <code>memcmp</code> on your buffers. But again, this will give unpredictable results because of the fact that your buffers were allocated on the stack, so even if you compare to files that are the same, the end of the buffers past the EOF may not be the same, so <code>memcmp</code> will still report false results (i.e., it will most likely report that the files are not the same when they are because of the random values at the end of the buffers past each respective file's EOF).</p>
<p>To get around this issue, you should really first measure the length of the file by first iterating through the file and seeing how long the file is in bytes, and then using <code>malloc</code> or <code>calloc</code> to allocate the buffers you're going to compare, and re-fill those buffers with the actual file's contents. Then you should be able to make a valid comparison of the binary contents of each file. You'll also be able to work with files larger than 64K at that point since you're dynamically allocating the buffers at run-time.</p> |
6,310,787 | How to set value inside div in JS | <p>I have some code that looks like this:</p>
<pre><code>document.getElementById("error").style.display = 'block';
</code></pre>
<p>and when this happens I also want to display the error that is supposed to be shown which is stored in another JS variable. How can I add the value of that variable to the div which has id="error"</p>
<p>Thanks!</p> | 6,310,813 | 6 | 1 | null | 2011-06-10 18:50:54.69 UTC | 2 | 2011-06-10 18:54:22.657 UTC | null | null | null | null | 731,255 | null | 1 | 19 | javascript | 65,019 | <pre><code>var errorMsg = "<p>Example error message</p>"
document.getElementById("error").innerHTML = errorMsg
</code></pre> |
5,997,960 | How to remove class from all elements jquery | <p>I am changing the class of an element with the following</p>
<pre><code> $("#"+data.id).addClass("highlight")
</code></pre>
<p>Given the list below. </p>
<pre><code> <div id="menuItems">
<ul id="contentLeft" class="edgetoedge">
<li class="sep" ">Shakes and Floats</li>
<li id="297"><a href="#" onClick="cart('297','add')"><small>$5.00</small><b>Vanilla</b> </a></li>
<li id="298"><a href="#" onClick="cart('298','add')"><small>$5.00</small><b>Peanut Butter</b></a></li>
<li id="299"><a href="#" onClick="cart('299','add')"><small>$5.00</small><b>Combo</b></a></li>
<li id="300"><a href="#" onClick="cart('300','add')"><small>$5.00</small><b>Chocolate</b></a></li>
<li id="301"><a href="#" onClick="cart('301','add')"><small>$5.00</small><b>Strawberry</b></a></li>
<li id="303"><a href="#" onClick="cart('303','add')"><small>$5.00</small><b>Banana</b></a></li>
<li id="304"><a href="#" onClick="cart('304','add')"><small>$5.00</small><b>Root Beer Float</b></a></li>
<li id="305"><a href="#" onClick="cart('305','add')"><small>$5.00</small><b>Espresso</b></a></li>
</ul>
</div>
</code></pre>
<p>I assumed I could remove the class with this...</p>
<pre><code> $(".edgetoedge").removeClass("highlight");
</code></pre>
<p>But this doesn't work. How can I remove the class?</p> | 5,997,989 | 6 | 0 | null | 2011-05-13 21:28:15.543 UTC | 9 | 2020-04-19 08:56:06.38 UTC | null | null | null | null | 505,055 | null | 1 | 98 | jquery | 204,691 | <p>You need to select the <code>li</code> tags contained within the <code>.edgetoedge</code> class. <code>.edgetoedge</code> only matches the one <code>ul</code> tag:</p>
<pre><code>$(".edgetoedge li").removeClass("highlight");
</code></pre> |
6,073,221 | PHP remove special character from string | <p>I have problems with removing special characters. I want to remove all special characters except "( ) / . % - &", because I'm setting that string as a title.</p>
<p>I edited code from the original (look below):</p>
<pre><code>preg_replace('/[^a-zA-Z0-9_ -%][().][\/]/s', '', $String);
</code></pre>
<p>But this is not working to remove special characters like: "’s, "“", "â€", among others.</p>
<p>original code: (this works but it removes these characters: "( ) / . % - &")</p>
<pre><code>preg_replace('/[^a-zA-Z0-9_ -]/s', '', $String);
</code></pre> | 6,073,257 | 8 | 2 | null | 2011-05-20 14:15:10.61 UTC | 5 | 2019-07-24 10:50:19.703 UTC | 2013-05-02 18:38:07.297 UTC | null | 1,845,301 | null | 453,089 | null | 1 | 31 | php|regex|string|preg-replace | 175,168 | <p>Your dot is matching all characters. Escape it (and the other special characters), like this:</p>
<pre><code>preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);
</code></pre> |
6,057,781 | wkhtmltopdf with full page background | <p>I am using wkhtmltopdf to generate a PDF file that is going to a printer and have some troubles with making the content fill up an entire page in the resulting PDF.</p>
<p>In the CSS I've set the width and height to 2480 X 3508 pixels (a4 300 dpi) and when creating the PDF I use 0 for margins but still end up with a small white border to the right and bottom. Also tried to use mm and percentage but with the same result.</p>
<p>I'd need someone to please provide an example on how to style the HTML and what options to use at command line so that the resulting PDF pages fill out the entire background. One way might be to include bleeding (this might be necessary anyway) but any tips are welcome. At the moment I am creating one big HTML page (without CSS page breaks - might help?) but if needed it would be fine to generate each page separately and then feed them all to wkhtmltopdf.</p> | 21,052,719 | 8 | 1 | null | 2011-05-19 11:16:45.7 UTC | 19 | 2022-05-11 13:19:19.47 UTC | 2013-08-30 17:11:34.087 UTC | null | 127,880 | null | 760,937 | null | 1 | 38 | wkhtmltopdf | 61,544 | <p>wkhtmltopdf v 0.11.0 rc2</p>
<p><strong>What ended up working:</strong></p>
<pre><code>wkhtmltopdf --margin-top 0 --margin-bottom 0 --margin-left 0 --margin-right 0 <url> <output>
</code></pre>
<p><strong>shortens to</strong> </p>
<pre><code>wkhtmltopdf -T 0 -B 0 -L 0 -R 0 <url> <output>
</code></pre>
<p><strong>Using html from stdin (Note dash)</strong></p>
<pre><code>echo "<h1>Testing Some Html</h2>" | wkhtmltopdf -T 0 -B 0 -L 0 -R 0 - <output>
</code></pre>
<p><strong>Using html from stdin to stdout</strong></p>
<p>echo "Testing Some Html" | wkhtmltopdf -T 0 -B 0 -L 0 -R 0 - test.pdf</p>
<p>echo "Testing Some Html" | wkhtmltopdf -T 0 -B 0 -L 0 -R 0 - - > test.pdf</p>
<p><strong>What <em>did not</em> work:</strong></p>
<ul>
<li>Using <code>--dpi</code></li>
<li>Using <code>--page-width and --page-height</code></li>
<li>Using <code>--zoom</code></li>
</ul> |
5,994,026 | Failed to install HelloAndroid.apk on device 'emulator-5554! | <p>Ive seen the questions posted about this issue. I understand it takes several minutes for the emulator to configure itself and launch. But if Im getting the specific error:</p>
<pre><code>[2011-05-13 08:41:36 - HelloAndroid] ------------------------------
[2011-05-13 08:41:36 - HelloAndroid] Android Launch!
[2011-05-13 08:41:36 - HelloAndroid] adb is running normally.
[2011-05-13 08:41:36 - HelloAndroid] Performing com.santiapps.helloandroid.HelloAndroid activity launch
[2011-05-13 08:41:36 - HelloAndroid] Automatic Target Mode: launching new emulator with compatible AVD 'my_avd'
[2011-05-13 08:41:36 - HelloAndroid] Launching a new emulator with Virtual Device 'my_avd'
[2011-05-13 08:41:49 - Emulator] 2011-05-13 08:41:49.650 emulator[411:903] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
[2011-05-13 08:41:50 - Emulator] emulator: emulator window was out of view and was recentred
[2011-05-13 08:41:50 - Emulator]
[2011-05-13 08:41:50 - HelloAndroid] New emulator found: emulator-5554
[2011-05-13 08:41:50 - HelloAndroid] Waiting for HOME ('android.process.acore') to be launched...
[2011-05-13 08:44:33 - HelloAndroid] WARNING: Application does not specify an API level requirement!
[2011-05-13 08:44:33 - HelloAndroid] Device API version is 12 (Android 3.1)
[2011-05-13 08:44:33 - HelloAndroid] HOME is up on device 'emulator-5554'
[2011-05-13 08:44:33 - HelloAndroid] Uploading HelloAndroid.apk onto device 'emulator-5554'
[2011-05-13 08:44:34 - HelloAndroid] Installing HelloAndroid.apk...
[2011-05-13 08:47:20 - HelloAndroid] Failed to install HelloAndroid.apk on device 'emulator-5554!
[2011-05-13 08:47:20 - HelloAndroid] (null)
[2011-05-13 08:47:22 - HelloAndroid] Launch canceled!
[2011-05-13 08:53:55 - HelloAndroid] ------------------------------
[2011-05-13 08:53:55 - HelloAndroid] Android Launch!
[2011-05-13 08:53:55 - HelloAndroid] adb is running normally.
[2011-05-13 08:53:55 - HelloAndroid] Performing com.santiapps.helloandroid.HelloAndroid activity launch
[2011-05-13 08:53:55 - HelloAndroid] Automatic Target Mode: launching new emulator with compatible AVD 'my_avd'
[2011-05-13 08:53:55 - HelloAndroid] Launching a new emulator with Virtual Device 'my_avd'
[2011-05-13 08:54:06 - Emulator] 2011-05-13 08:54:06.327 emulator[460:903] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
[2011-05-13 08:54:06 - Emulator] emulator: emulator window was out of view and was recentred
[2011-05-13 08:54:06 - Emulator]
[2011-05-13 08:54:06 - HelloAndroid] New emulator found: emulator-5554
[2011-05-13 08:54:06 - HelloAndroid] Waiting for HOME ('android.process.acore') to be launched...
[2011-05-13 09:08:07 - Emulator] emulator: ERROR: unexpected qemud char. channel close
</code></pre>
<p>couldnt it be I have a bad configuration...?</p> | 6,005,712 | 9 | 1 | null | 2011-05-13 15:14:44.463 UTC | 3 | 2015-12-30 10:10:00.483 UTC | 2011-05-13 15:25:34.797 UTC | null | 571,433 | null | 452,889 | null | 1 | 16 | android | 96,753 | <p>wait for the emulator to setup completely and then test your app. Also, I would leave you AVD open so you dont have to wait so long everytime you run your application.</p>
<p>When it shows the red writing, don't close anything - leave it there and then press the run button again. Worked like a charm.</p> |
6,102,125 | Family Tree Algorithm | <p>I'm working on putting together a problem set for an intro-level CS course and came up with a question that, on the surface, seems very simple:</p>
<blockquote>
<p>You are given a list of people with the names of their parents, their birth dates, and their death dates. You are interested in finding out who, at some point in their lifetime, was a parent, a grandparent, a great-grandparent, etc. Devise an algorithm to label each person with this information as an integer (0 means the person never had a child, 1 means that the person was a parent, 2 means that the person was a grandparent, etc.)</p>
</blockquote>
<p>For simplicity, you can assume that the family graph is a DAG whose undirected version is a tree.</p>
<p>The interesting challenge here is that you can't just look at the shape of the tree to determine this information. For example, I have 8 great-great-grandparents, but since none of them were alive when I was born, in their lifetimes none of them were great-great-grandparents.</p>
<p>The best algorithm I can come up with for this problem runs in time O(n<sup>2</sup>), where n is the number of people. The idea is simple - start a DFS from each person, finding the furthest descendant down in the family tree that was born before that person's death date. However, I'm pretty sure that this is not the optimal solution to the problem. For example, if the graph is just two parents and their n children, then the problem can be solved trivially in O(n). What I'm hoping for is some algorithm that is either beats O(n<sup>2</sup>) or whose runtime is parameterized over the shape of the graph that makes it fast for wide graphs with a graceful degradation to O(n<sup>2</sup>) in the worst-case.</p> | 6,142,209 | 9 | 15 | null | 2011-05-23 19:43:30.203 UTC | 27 | 2015-08-07 14:59:36.96 UTC | 2015-08-07 14:59:36.96 UTC | null | 5,640 | null | 501,557 | null | 1 | 46 | algorithm|graph|tree|family-tree | 15,771 | <p>I thought of this this morning, then found that @Alexey Kukanov had similar thoughts. But mine is more fleshed out and has some more optimization, so I'll post it anyways.</p>
<p>This algorithm is <code>O(n * (1 + generations))</code>, and will work for any dataset. For realistic data this is <code>O(n)</code>.</p>
<ol>
<li>Run through all records and generate objects representing people which include date of birth, links to parents, and links to children, and several more uninitialized fields. (Time of last death between self and ancestors, and an array of dates that they had 0, 1, 2, ... surviving generations.)</li>
<li>Go through all people and recursively find and store the time of last death. If you call the person again, return the memoized record. For each person you can encounter the person (needing to calculate it), and can generate 2 more calls to each parent the first time you calculate it. This gives a total of <code>O(n)</code> work to initialize this data.</li>
<li>Go through all people and recursively generate a record of when they first added a generation. These records only need go to the maximum of when the person or their last ancestor died. It is <code>O(1)</code> to calculate when you had 0 generations. Then for each recursive call to a child you need to do <code>O(generations)</code> work to merge that child's data in to yours. Each person gets called when you encounter them in the data structure, and can be called once from each parent for <code>O(n)</code> calls and total expense <code>O(n * (generations + 1))</code>.</li>
<li>Go through all people and figure out how many generations were alive at their death. This is again <code>O(n * (generations + 1))</code> if implemented with a linear scan.</li>
</ol>
<p>The sum total of all of these operations is <code>O(n * (generations + 1))</code>.</p>
<p>For realistic data sets, this will be <code>O(n)</code> with a fairly small constant.</p> |
5,601,647 | HTML5 Email input pattern attribute | <p>I’m trying to make a html5 form that contains one email input, one check box input, and one submit input.
I'm trying to use the pattern attribute for the email input but I don't know what to place in this attribute. I do know that I'm supposed to use a regular expression that must match the JavaScript Pattern production but I don't know how to do this.</p>
<p>What I'm trying to get this attribute to do is to check to make sure that the email contains one @ and at least one or more dot and if possible check to see if the address after the @ is a real address. If I can't do this through this attribute then I'll consider using JavaScript but for checking for one @ and one or more dot I do want to use the pattern attribute for sure.</p>
<p>The pattern attribute needs to check for:</p>
<ol>
<li>Only one @</li>
<li>One or more dot</li>
<li>And if possible check to see if the address after the @ is a valid address</li>
</ol>
<p>An alternative to this one is to use a JavaScript but for all the other conditions I do not want to use a JavaScript.</p> | 8,897,615 | 20 | 4 | null | 2011-04-08 23:07:03.533 UTC | 37 | 2022-01-30 02:18:34.45 UTC | 2020-12-24 20:42:16.927 UTC | null | 4,442,606 | null | 633,498 | null | 1 | 78 | html|html-email|email-validation|html-input | 368,440 | <p>This is a dual problem (as many in the world wide web world).</p>
<p>You need to evaluate if the browser supports html5 (I use Modernizr to do it). In this case if you have a normal form the browser will do the job for you, but if you need ajax/json (as many of everyday case) you need to perform manual verification anyway.</p>
<p>.. so, my suggestion is to use a regular expression to evaluate anytime before submit. The expression I use is the following:</p>
<pre><code>var email = /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;
</code></pre>
<p>This one is taken from <a href="http://www.regular-expressions.info/" rel="noreferrer">http://www.regular-expressions.info/</a> . This is a hard world to understand and master, so I suggest you to read this page carefully.</p> |
17,769,245 | Terminating with uncaught exception of type NSException? | <p>My application crashes when clicking a button to go to segue into a new view. This comes up: </p>
<pre><code>int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
</code></pre>
<p>"return UIApplicationMain..." is highlighted in green with "Thread 1: Signal SIGABRT" at the end.
The error also includes this in the output:</p>
<pre><code>**Terminating app due to uncaught exception *** 'NSUnknownKeyException reason:'[<SlopeViewController 0x8b68c70> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key m.' *** First throw call stack: (0x16b19b8 0x14328b6 0x17407c1 0x10f00ee 0x105c7db 0x105bd33 0x10be069 0x4b579b 0x14447d2 0x16acf5a 0x4b42f4 0x336e79 0x337491 0x337792 0x337c98 0x345912 0x345c5a 0x5aca79 0x34279a 0x3429a0 0x3429e0 0x73dd2b 0x72e181 0x72e1fc 0x1444874 0x2343b7 0x234343 0x32027e 0x320641 0x31f8fd 0x26fa0d 0x270266 0x245076 0x232efb 0x2ee332b 0x162d48d 0x162d3e5 0x162d11b 0x1657b30 0x165710d 0x1656f3b 0x35f5ff2 0x35f5e19 0x2304eb 0x6fd3 0x1d1370d 0x1)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb
</code></pre>
<p>I have no idea what to do. Please help!</p> | 17,770,531 | 1 | 3 | null | 2013-07-21 05:05:31.32 UTC | 5 | 2014-01-12 19:48:37.957 UTC | 2013-07-21 06:13:23.377 UTC | user529758 | null | null | 2,603,513 | null | 1 | 20 | objective-c|nsexception | 83,666 | <p>To prevent the NSException crashes, you should click the cross (X) to remove the yellow triangles:</p>
<p><img src="https://i.stack.imgur.com/ZgiB4.png" alt="enter image description here"> </p> |
25,047,463 | Group By and Sum using Underscore/Lodash | <p>I have JSON like this: </p>
<pre><code>[
{
platformId: 1,
payout: 15,
numOfPeople: 4
},
{
platformId: 1,
payout: 12,
numOfPeople: 3
},
{
platformId: 2,
payout: 6,
numOfPeople: 5
},
{
platformId: 2,
payout: 10,
numOfPeople: 1
},
]
</code></pre>
<p>And I want to Group it by <code>platformId</code> with sum of <code>payout</code> and <code>numOfPeople</code>.</p>
<p>I.e. in result I want JSON like this:</p>
<pre><code>[
"1": {
payout: 27,
numOfPeople: 7
},
"2": {
payout: 16,
numOfPeople: 6
}
]
</code></pre>
<p>I tried to use <code>underscore.js</code>'s <code>_.groupBy</code> method, and it groups fine, but how I can get the SUM of objects properties values like I demonstrated above? </p> | 25,047,658 | 6 | 2 | null | 2014-07-30 21:39:44.777 UTC | 9 | 2022-03-17 18:39:57.237 UTC | 2016-01-07 15:34:07.76 UTC | null | 1,903,116 | null | 921,193 | null | 1 | 22 | javascript|arrays|object|underscore.js|lodash | 36,874 | <p>You can do this without Underscore:</p>
<pre><code>var result = data.reduce(function(acc, x) {
var id = acc[x.platformId]
if (id) {
id.payout += x.payout
id.numOfPeople += x.numOfPeople
} else {
acc[x.platformId] = x
delete x.platformId
}
return acc
},{})
</code></pre>
<p>But why would you want an object with numeric keys? You could convert it back to a collection:</p>
<pre><code>var toCollection = function(obj) {
return Object.keys(obj)
.sort(function(x, y){return +x - +y})
.map(function(k){return obj[k]})
}
toCollection(result)
</code></pre>
<p>Note that objects are mutated, so you may to clone them first if you want to maintain the original data.</p> |
979,555 | iPhone drag/drop | <p>Trying to get some basic drag/drop functionality happening for an iPhone application.</p>
<p>My current code for trying to do this is as follows:</p>
<pre><code>- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event
{
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self];
self.center = location;
}
</code></pre>
<p>This code has the result of a the touched UIView flickering while it follows the touch around. After playing around with it a bit, I also noticed that the UIView seemed to flicker from the 0,0 position on the screen to the currently touched location.</p>
<p>Any ideas what I'm doing wrong?</p> | 980,124 | 1 | 2 | null | 2009-06-11 05:58:06.107 UTC | 10 | 2015-08-15 01:24:25.417 UTC | null | null | null | null | 116,994 | null | 1 | 16 | iphone|objective-c|drag-and-drop | 20,005 | <p>The center property needs to be specified in the coordinate system of the superview, but you've asked the touch event for the location in terms of your subview. Instead ask for them based on the superview's coordinates, like this:</p>
<pre><code>- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:self.superview]; // <--- note self.superview
self.center = location;
}
</code></pre> |
19,399,477 | Setting up a custom domain with Heroku and namecheap | <p>I've followed all the instructions on <a href="https://devcenter.heroku.com/articles/custom-domains" rel="nofollow noreferrer">https://devcenter.heroku.com/articles/custom-domains</a> to get my custom domain set up, and it still isn't working.</p>
<p>On Heroku, I have the following domains:</p>
<p><code>myapp.herokuapp.com</code></p>
<p><code>example.com</code></p>
<p><code>www.example.com</code></p>
<p>And on Namecheap, I have the following settings:</p>
<p><strong>HOST NAME | IP ADDRESS/URL | RECORD TYPE</strong></p>
<p>@ <code>http://example.com</code> URL Redirect</p>
<p>www <code>myapp.herokuapp.com</code>. CNAME(Alias)</p>
<hr />
<p>When I run: "host <code>www.example.com</code>" in my terminal, I expect to get "<code>www.example.com</code> is an alias for <code>myapp.herokuapp.com</code>". Instead, I get:</p>
<p>"<code>www.example.com</code> is an alias for <code>myapp.heroku.com</code>"</p>
<p>I can't figure out why it is pointing to <code>myapp.heroku.com</code>, because I have only specified <code>myapp.herokuapps.com</code>.</p>
<p>Does anybody know why this is happening?</p> | 25,925,332 | 9 | 0 | null | 2013-10-16 09:16:36.7 UTC | 20 | 2022-07-05 07:19:03.417 UTC | 2022-07-02 23:29:06.08 UTC | null | 1,145,388 | null | 1,975,151 | null | 1 | 46 | ruby-on-rails|heroku | 20,016 | <p>1) Go To Namecheap, and go to the domain you want to manage.</p>
<p>2) On the left sidebar, click "All Record Hosts", NOT any of the other jazz other tutorials tell you. No DNS pointing changes are necessary. It's easier to use alias.</p>
<p><img src="https://i.stack.imgur.com/pHKL1.png" alt="namecheap sidebar all host records"></p>
<p>3) Once you do, you'll see a line starting with "www" as a CNAME (Alias) option. Fill this in as your heroku app's domain name <code>example.herokuapp.com</code></p>
<p><img src="https://i.stack.imgur.com/tCUSi.png" alt="namecheap CNAME alias location"></p>
<p>That's it for namecheap.</p>
<p>4) Then at heroku settings, under "domains", enter your purchased domain name you wish to be displayed.</p>
<p><img src="https://i.stack.imgur.com/lkjOf.png" alt="heroku settings domains"></p>
<p>That's it!
It's as easy as letting heroku and namecheap know about both domain aliases.</p>
<p>Credits to this blog:
<a href="http://blog.romansanchez.me/2013/06/08/point-namecheap-domain-to-heroku/" rel="noreferrer">http://blog.romansanchez.me/2013/06/08/point-namecheap-domain-to-heroku/</a></p>
<p>Update:</p>
<p>Apparently, heroku will only allow sites with <code>www.</code> prepended. To have a true root domain without <code>www.</code> will take some extra ninja hacking.</p> |
32,617,811 | Imputation of missing values for categories in pandas | <p>The question is how to fill NaNs with most frequent levels for category column in pandas dataframe?</p>
<p>In R randomForest package there is
<a href="http://lojze.lugos.si/~darja/software/r/library/randomForest/html/na.roughfix.html" rel="noreferrer">na.roughfix</a> option : <code>A completed data matrix or data frame. For numeric variables, NAs are replaced with column medians. For factor variables, NAs are replaced with the most frequent levels (breaking ties at random). If object contains no NAs, it is returned unaltered.</code></p>
<p>in Pandas for numeric variables I can fill NaN values with :</p>
<pre><code>df = df.fillna(df.median())
</code></pre> | 32,619,781 | 4 | 0 | null | 2015-09-16 20:11:17.957 UTC | 17 | 2021-03-30 06:33:08.223 UTC | 2021-03-30 06:33:08.223 UTC | null | 2,884,859 | null | 1,268,964 | null | 1 | 43 | python|pandas | 81,240 | <p>You can use <code>df = df.fillna(df['Label'].value_counts().index[0])</code> to fill NaNs with the most frequent value from one column. </p>
<p>If you want to fill every column with its own most frequent value you can use </p>
<p><code>df = df.apply(lambda x:x.fillna(x.value_counts().index[0]))</code></p>
<p><strong>UPDATE 2018-25-10</strong> ⬇</p>
<p>Starting from <code>0.13.1</code> pandas includes <code>mode</code> method for <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mode.html?highlight=mode#pandas.Series.mode" rel="noreferrer">Series</a> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.mode.html" rel="noreferrer">Dataframes</a>.
You can use it to fill missing values for each column (using its own most frequent value) like this</p>
<pre><code>df = df.fillna(df.mode().iloc[0])
</code></pre> |
29,980,832 | Request permissions again after user denies location services? | <p>I track the user's location and ask for permission when my load first loads using this:</p>
<pre><code>locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
</code></pre>
<p>If the user denies, but later changes their mind by enabling the configuration option in my app, how do I ask again? For example, I have a switch for auto detecting the user's location so when they enable it, I am trying to do this:</p>
<pre><code>@IBAction func gpsChanged(sender: UISwitch) {
// Request permission for auto geolocation if applicable
if sender.on {
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
</code></pre>
<p>But this code doesn't seem to do anything. I was hoping it would ask the user again if they want to allow the app to track the user's location. Is this possible?</p> | 29,980,902 | 6 | 0 | null | 2015-05-01 02:29:53.993 UTC | 12 | 2021-07-22 10:26:52.017 UTC | null | null | null | null | 235,334 | null | 1 | 43 | ios|iphone|swift|ios8|core-location | 39,377 | <p>The OS will only ever prompt the user once. If they deny permission, that's it. What you <em>can</em> do is direct the user to the Settings for your app by passing <code>UIApplicationOpenSettingsURLString</code> to <code>UIApplication</code>'s <code>openURL:</code> method. From there, they can re-enable location services if they wish. That said, you probably shouldn't be too aggressive about bugging them for the permission.</p> |
49,798,549 | Declarative pipeline when condition in post | <p>As far as declarative pipelines go in Jenkins, I'm having trouble with the <em>when</em> keyword.</p>
<p>I keep getting the error <code>No such DSL method 'when' found among steps</code>. I'm sort of new to Jenkins 2 declarative pipelines and don't think I am mixing up scripted pipelines with declarative ones.</p>
<p>The goal of this pipeline is to run <code>mvn deploy</code> after a successful Sonar run and send out mail notifications of a failure or success. I only want the artifacts to be deployed when on master or a release branch.</p>
<p>The part I'm having difficulties with is in the <em>post</em> section. The <strong>Notifications</strong> stage is working great. Note that I got this to work without the <em>when</em> clause, but really need it or an equivalent.</p>
<pre><code>pipeline {
agent any
tools {
maven 'M3'
jdk 'JDK8'
}
stages {
stage('Notifications') {
steps {
sh 'mkdir tmpPom'
sh 'mv pom.xml tmpPom/pom.xml'
checkout([$class: 'GitSCM', branches: [[name: 'origin/master']], doGenerateSubmoduleConfigurations: false, submoduleCfg: [], userRemoteConfigs: [[url: 'https://repository.git']]])
sh 'mvn clean test'
sh 'rm pom.xml'
sh 'mv tmpPom/pom.xml ../pom.xml'
}
}
}
post {
success {
script {
currentBuild.result = 'SUCCESS'
}
when {
branch 'master|release/*'
}
steps {
sh 'mvn deploy'
}
sendNotification(recipients,
null,
'https://link.to.sonar',
currentBuild.result,
)
}
failure {
script {
currentBuild.result = 'FAILURE'
}
sendNotification(recipients,
null,
'https://link.to.sonar',
currentBuild.result
)
}
}
}
</code></pre> | 49,812,779 | 3 | 1 | null | 2018-04-12 13:58:15.063 UTC | 7 | 2022-05-13 11:39:50.773 UTC | null | null | null | null | 9,230,302 | null | 1 | 41 | jenkins | 43,760 | <p>In the <a href="https://jenkins.io/doc/book/pipeline/syntax/#when" rel="nofollow noreferrer">documentation</a> of declarative pipelines, it's mentioned that you can't use <code>when</code> in the <code>post</code> block. <code>when</code> is allowed only inside a stage directive.
So what you can do is test the conditions using an <code>if</code> in a <code>script</code>:</p>
<pre><code>post {
success {
script {
if (env.BRANCH_NAME == 'master')
currentBuild.result = 'SUCCESS'
}
}
// failure block
}
</code></pre> |
49,555,189 | How to create table in partition data in hive? | <pre><code>drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/_impala_insert_staging
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI
[mgupta@sjc-dev-binn01 ~]$ hadoop fs -ls /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI
Found 27 items
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201602
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201603
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201604
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201605
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201606
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201607
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201608
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201609
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201610
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201611
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201612
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201701
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201702
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201703
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201704
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201705
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201706
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:17 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201707
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201708
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201709
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201710
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201711
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201712
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201801
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201802
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:18 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201803
[mgupta@sjc-dev-binn01 ~]$ hadoop fs -ls /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601
Found 3 items
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601/company_sid=0
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601/company_sid=38527
drwxr-xr-x - mgupta supergroup 0 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601/company_sid=__HIVE_DEFAULT_PARTITION__
[mgupta@sjc-dev-binn01 ~]$ hadoop fs -ls /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601/company_sid=0
Found 1 items
-rw-r--r-- 3 mgupta supergroup 2069014 2018-03-26 22:16 /kylin/retailer/qi_basket_brand_bucket_fact/product_hierarchy_type=CI/month_id=201601/company_sid=0/f9466a0068b906cf-6ace7f8500000049_294515768_data.0.parq
[mgupta@sjc-dev-binn01 ~]$
</code></pre> | 49,557,506 | 2 | 0 | null | 2018-03-29 11:44:13.787 UTC | 1 | 2022-01-18 19:30:09.007 UTC | 2019-09-03 07:26:09.353 UTC | null | 1,000,551 | null | 6,363,023 | null | 1 | 1 | hive|create-table|hive-partitions | 39,570 | <p>You may try the steps given below.</p>
<p><strong>Approach 1</strong></p>
<ol>
<li><p>Identify the schema (column names and types, including the partitioned column)</p>
</li>
<li><p>Create a hive partitioned table (Make sure to add partition column & delimiter information)</p>
</li>
<li><p>Load data into the partitioned table.(In this case, the loading file will not have partition column as you will hard-code it via the <code>load</code> command)</p>
<pre><code> create table <table_name> (col1 data_type1, col2 data_type2..)
partitioned by(part_col data_type3)
row format delimited
fields terminated by '<field_delimiter_in_your_data>'
load data inpath '/hdfs/loc/file1' into table <table_name>
partition (<part_col>='201601');
load data inpath '/hdfs/loc/file2' into table <table_name>
partition (<part_col>='201602')
load data inpath '/hdfs/loc/file3' into table <table_name>
partition (<part_col>='201603')
</code></pre>
</li>
</ol>
<p>and so on.</p>
<hr />
<p><strong>Approach 2</strong></p>
<ol>
<li><p>Create a staging table (temporary table) with same schema as of main table but without any partitions</p>
</li>
<li><p>Load your entire data into this table (Make sure you have the '<strong>partition column</strong>' as one of the fields in these files)</p>
</li>
<li><p>Load data to your main table from staging table using <em><strong>dynamic partition insert</strong></em>.</p>
<pre><code> create table <staging_table> (col1 data_type1, col2 data_type2..)
row format delimited
fields terminated by '<field_delimiter_in_your_data>'
create table <main_table> (col1 data_type1, col2 data_type2..)
partitioned by(part_col data_type3);
load data inpath '/hdfs/loc/directory/' into table <staging_table>;
SET hive.exec.dynamic.partition=true;
SET hive.exec.dynamic.partition.mode=nonstrict;
insert into table <main_table>
partition(part_col)
select col1,col2,....part_col from <staging_table>;
</code></pre>
</li>
</ol>
<p>Key aspects in approach 2 are:</p>
<ul>
<li>Making the '<strong>part_col</strong>' available as a field in the loading file</li>
<li>In the final insert statement, get '<strong>part_col</strong>' as the last field from select clause.</li>
</ul> |
49,603,498 | Convolution2D + LSTM versus ConvLSTM2D | <p>Are <code>1</code> and <code>2</code> the same?</p>
<ol>
<li>Use <code>Convolution2D</code> layers and <code>LSTM</code> layers </li>
<li>Use <code>ConvLSTM2D</code></li>
</ol>
<p>If there is any difference, could you explain it for me?</p> | 49,770,553 | 2 | 0 | null | 2018-04-01 23:14:53.4 UTC | 9 | 2018-04-13 16:40:43.003 UTC | 2018-04-13 16:40:43.003 UTC | null | 7,224,320 | null | 4,088,201 | null | 1 | 25 | python|tensorflow|keras | 12,197 | <p>They are not exactly the same, here is why:</p>
<h3>1. Use <code>Convolution2D</code> layers and <code>LSTM</code> layers</h3>
<p>As it is known, <code>Convolution2D</code> serves well for capturing image or spatial features, whilst <code>LSTM</code> are used to detect correlations over time. However, by stacking these kind of layers, the correlation between space and time features may not be captured properly.</p>
<h3>2. Use <code>ConvLSTM2D</code></h3>
<p>To solve this, <a href="https://arxiv.org/abs/1506.04214v1" rel="noreferrer">Xingjian Shi et al.</a> proposed a network structure able to capture spatiotemporal correlations, namely <code>ConvLSTM</code>. In Keras, this is reflected in the <a href="https://keras.io/layers/recurrent/#convlstm2d" rel="noreferrer"><code>ConvLSTM2D</code></a> class, which computes convolutional operations in both the input and the recurrent transformations.</p>
<h3>Keras code</h3>
<p>Too illustrate this, you can see <a href="https://github.com/keras-team/keras/blob/master/keras/layers/recurrent.py" rel="noreferrer">here</a> the <code>LSTM</code> code, if you go to the <code>call</code> method from <code>LSTMCell</code>, you'd only see:</p>
<pre class="lang-python prettyprint-override"><code> x_i = K.dot(inputs_i, self.kernel_i)
x_f = K.dot(inputs_f, self.kernel_f)
x_c = K.dot(inputs_c, self.kernel_c)
x_o = K.dot(inputs_o, self.kernel_o)
</code></pre>
<p>Instead, the <a href="https://github.com/keras-team/keras/blob/master/keras/layers/convolutional_recurrent.py" rel="noreferrer"><code>ConvLSTM2DCell</code></a> class calls:</p>
<pre class="lang-python prettyprint-override"><code> x_i = self.input_conv(inputs_i, self.kernel_i, self.bias_i, padding=self.padding)
x_f = self.input_conv(inputs_f, self.kernel_f, self.bias_f, padding=self.padding)
x_c = self.input_conv(inputs_c, self.kernel_c, self.bias_c, padding=self.padding)
x_o = self.input_conv(inputs_o, self.kernel_o, self.bias_o, padding=self.padding)
h_i = self.recurrent_conv(h_tm1_i, self.recurrent_kernel_i)
h_f = self.recurrent_conv(h_tm1_f, self.recurrent_kernel_f)
h_c = self.recurrent_conv(h_tm1_c, self.recurrent_kernel_c)
h_o = self.recurrent_conv(h_tm1_o, self.recurrent_kernel_o)
</code></pre>
<p>Where:</p>
<pre class="lang-python prettyprint-override"><code>def input_conv(self, x, w, b=None, padding='valid'):
conv_out = K.conv2d(x, w, strides=self.strides,
padding=padding,
data_format=self.data_format,
dilation_rate=self.dilation_rate)
if b is not None:
conv_out = K.bias_add(conv_out, b,
data_format=self.data_format)
return conv_out
def recurrent_conv(self, x, w):
conv_out = K.conv2d(x, w, strides=(1, 1),
padding='same',
data_format=self.data_format)
return conv_out
</code></pre>
<p>In <code>LSTM</code>, the equivalent for <code>h_x</code> (recurrent transformations) would be:</p>
<pre class="lang-python prettyprint-override"><code>K.dot(h_tm1_x, self.recurrent_kernel_x)
</code></pre>
<p>Instead of <code>ConvLSTM2D</code>'s:</p>
<pre class="lang-python prettyprint-override"><code>self.recurrent_conv(h_tm1_x, self.recurrent_kernel_x)
</code></pre>
<p>These kind of transformations could not be computed with stacked <code>Conv2D</code> and <code>LSTM</code> layers.</p> |
22,252,956 | Android Studio Gradle issue upgrading to version 0.5.0 - Gradle Migrating From 0.8 to 0.9 - Also Android Studio upgrade to 0.8.1 | <p>After upgrade message states: </p>
<pre><code>Failed to refresh Gradle project 'XXX'
The project is using an unsupported version of the Android Gradle plug-in (0.8.3).
Version 0.9.0 introduced incompatible changes in the build language.
Please read the migration guide to learn how to update your project.
</code></pre>
<p>Same kind of issue after upgrade to Android Studio to version >= 0.8.0</p> | 22,252,957 | 8 | 0 | null | 2014-03-07 14:35:24.397 UTC | 17 | 2016-04-09 06:31:53.647 UTC | 2014-07-08 13:11:11.68 UTC | null | 1,590,950 | null | 2,838,910 | null | 1 | 28 | android|gradle|android-studio|android-gradle-plugin|build.gradle | 30,725 | <p>To fix it, open file called <code>build.gradle</code> in the project root, and change gradle version there to 0.9.+.</p>
<pre><code>buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.9.+'
}
}
</code></pre>
<p>To be repeated for each project ;(</p>
<p>If you then get a message like "<em>Unable to load class '<code>org.gradle.api.artifacts.result.ResolvedComponentResult</code></em>".</p>
<p>Go to you <code>project_folder/gradle/wrapper</code> directory and edit <code>Unable to load class 'org.gradle.api.artifacts.result.ResolvedComponentResult'.</code> file changing the <code>distributionUrl</code> to</p>
<pre><code>distributionUrl=http\://services.gradle.org/distributions/gradle-1.10-all.zip
</code></pre>
<p>After upgrade to version 0.8.1 (full download and copy SDK folder over), had to have new version of gradle installed by IDE (using the "Fix it" link a couple of time :S ), and modifing the "android" section of the gradle file in project folder from 19.0 to 19.1, as below:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.12.+'
}
}
apply plugin: 'android'</p>
<pre><code>repositories {
mavenCentral()
}
android {
compileSdkVersion 19
buildToolsVersion '19.1.0'
defaultConfig {
minSdkVersion 7
targetSdkVersion 19
}
}
dependencies {
compile 'com.android.support:appcompat-v7:19.1.+'
compile 'com.android.support:support-v4:19.1.0'
}
</code></pre> |
22,181,944 | Using utf-8 characters in a Jinja2 template | <p>I'm trying to use utf-8 characters when rendering a template with Jinja2. Here is how my template looks like:</p>
<pre><code><!DOCTYPE HTML>
<html manifest="" lang="en-US">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
...
</code></pre>
<p>The title variable is set something like this:</p>
<pre><code>index_variables = {'title':''}
index_variables['title'] = myvar.encode("utf8")
template = env.get_template('index.html')
index_file = open(preview_root + "/" + "index.html", "w")
index_file.write(
template.render(index_variables)
)
index_file.close()
</code></pre>
<p>Now, the problem is that <strong>myvar</strong> is a message read from a message queue and can contain those special utf8 characters (ex. "Séptimo Cine"). </p>
<p>The rendered template looks something like:</p>
<pre><code>...
<title>S\u00e9ptimo Cine</title>
...
</code></pre>
<p>and I want it to be:</p>
<pre><code>...
<title>Séptimo Cine</title>
...
</code></pre>
<p>I have made several tests but I can't get this to work.</p>
<ul>
<li><p>I have tried to set the title variable without <strong>.encode("utf8")</strong>, but it throws an exception (<em>ValueError: Expected a bytes object, not a unicode object</em>), so my guess is that the initial message is unicode</p></li>
<li><p>I have used <strong>chardet.detect</strong> to get the encoding of the message (it's "ascii"), then did the following: myvar.decode("ascii").encode("cp852"), but the title is still not rendered correctly.</p></li>
<li><p>I also made sure that my template is a UTF-8 file, but it didn't make a difference.</p></li>
</ul>
<p>Any ideas on how to do this?</p> | 22,182,709 | 3 | 0 | null | 2014-03-04 20:10:17.737 UTC | 7 | 2021-07-22 09:10:01.207 UTC | null | null | null | null | 1,646,670 | null | 1 | 33 | python|python-2.7|utf-8|character-encoding|jinja2 | 45,323 | <p>TL;DR:</p>
<ul>
<li><a href="http://jinja.pocoo.org/docs/api/#unicode" rel="nofollow noreferrer">Pass Unicode</a> to <code>template.render()</code></li>
<li>Encode the rendered unicode result to a bytestring before writing it to a file</li>
</ul>
<p>This had me puzzled for a while. Because you do</p>
<pre><code>index_file.write(
template.render(index_variables)
)
</code></pre>
<p>in one statement, that's basically just one line where Python is concerned, so the traceback you get is misleading: The exception I got when recreating your test case didn't happen in <code>template.render(index_variables)</code>, but in <code>index_file.write()</code> instead. So splitting the code up like this</p>
<pre><code>output = template.render(index_variables)
index_file.write(output)
</code></pre>
<p>was the first step to diagnose where exactly the <code>UnicodeEncodeError</code> happens.</p>
<p>Jinja returns unicode whet you let it render the template. Therefore you need to encode the result to a bytestring before you can write it to a file:</p>
<pre><code>index_file.write(output.encode('utf-8'))
</code></pre>
<p>The second error is that you pass in an <code>utf-8</code> encoded bytestring to <code>template.render()</code> - <a href="http://jinja.pocoo.org/docs/api/#unicode" rel="nofollow noreferrer">Jinja wants unicode</a>. So assuming your <code>myvar</code> contains UTF-8, you need to decode it to unicode first:</p>
<pre><code>index_variables['title'] = myvar.decode('utf-8')
</code></pre>
<p>So, to put it all together, this works for me:</p>
<pre><code># -*- coding: utf-8 -*-
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myproject', 'templates'))
# Make sure we start with an utf-8 encoded bytestring
myvar = 'Séptimo Cine'
index_variables = {'title':''}
# Decode the UTF-8 string to get unicode
index_variables['title'] = myvar.decode('utf-8')
template = env.get_template('index.html')
with open("index_file.html", "wb") as index_file:
output = template.render(index_variables)
# jinja returns unicode - so `output` needs to be encoded to a bytestring
# before writing it to a file
index_file.write(output.encode('utf-8'))
</code></pre> |
28,900,207 | How do I add classes to items in Owl Carousel 2? | <p>My goal is to make a carousel that looks like this:</p>
<p><img src="https://i.imgur.com/c4xTgH5.jpg" alt="Carousel"></p>
<p>In case you don't know what you're looking at, there are 5 images/items but only the center one is displayed in its full size. The images next to the center one are smaller, and the outer ones smaller still.</p>
<p>I've achieved this in the first version of Owl Carousel but it doesn't support looping, which makes this design ridiculous (can't reach the side images...).</p>
<p>Here's how I did it:</p>
<pre><code>var owl = $("#owl-demo");
owl.owlCarousel({
pagination: false,
lazyLoad: true,
itemsCustom: [
[0, 3],
[900, 5],
[1400, 7],
],
afterAction: function(el){
.$owlItems
.removeClass('active') //what I call the center class
.removeClass('passive') //what I call the next-to-center class
this
.$owlItems
.eq(this.currentItem + 2) //+ 2 is the center with 5 items
.addClass('active')
this
.$owlItems
.eq(this.currentItem + 1)
.addClass('passive')
this
.$owlItems
.eq(this.currentItem + 3)
.addClass('passive')
}
</code></pre>
<p>Just showing you the code for 5 items, but I used some if-clauses to get it working for 3 and 7 as well. The <code>active</code> class is just composed of <code>width: 100%</code> and the <code>passive</code> one <code>width: 80%</code>.</p>
<p>Does anyone know how to get the same result in Owl Carousel 2? I'm using <code>_items</code> instead of <code>$owlItems</code> but I don't know if that's correct. There is no <code>afterAction</code> and the events/callbacks don't seem to work as they should in v2.</p> | 28,903,704 | 2 | 0 | null | 2015-03-06 13:50:31.367 UTC | 10 | 2019-03-17 18:55:47.84 UTC | null | null | null | user4325086 | null | null | 1 | 10 | jquery|carousel|owl-carousel|owl-carousel-2 | 32,634 | <p>You can do it this way:</p>
<pre><code>$(function(){
$('.loop').owlCarousel({
center: true,
items:5,
loop:true,
margin:10
});
$('.loop').on('translate.owl.carousel', function(e){
idx = e.item.index;
$('.owl-item.big').removeClass('big');
$('.owl-item.medium').removeClass('medium');
$('.owl-item').eq(idx).addClass('big');
$('.owl-item').eq(idx-1).addClass('medium');
$('.owl-item').eq(idx+1).addClass('medium');
});
});
</code></pre>
<p>Listening to the event of your choice </p>
<p><a href="https://owlcarousel2.github.io/OwlCarousel2/docs/api-events.html" rel="noreferrer"><strong>List of available events here</strong></a></p>
<p>In the demo, I just add the class <strong>big</strong> to the main item, and the class <strong>medium</strong> to the previous and next one. From that you can play with whichever css property you want.</p>
<p><a href="http://jsfiddle.net/knc6h0vu/" rel="noreferrer"><strong>LIVE DEMO</strong></a></p>
<hr>
<p>NOTE:</p>
<p>You could also just play with plugin classes, <code>.active</code> and <code>.center</code> (or you can also define your own, as you can see here: <a href="https://owlcarousel2.github.io/OwlCarousel2/docs/api-classes.html" rel="noreferrer"><strong>custom classes</strong></a></p> |
29,319,361 | How to see diff between working directory and staging index? | <p>We can see difference between <strong>repository and working directory</strong> with:</p>
<pre><code>git diff
</code></pre>
<p>We can see difference between <strong>repository and staging index</strong> with:</p>
<pre><code>git diff --staged
</code></pre>
<p>But how do we see difference between <strong>working directory and staging index</strong>?</p> | 29,319,403 | 3 | 0 | null | 2015-03-28 16:09:23.153 UTC | 15 | 2021-04-30 15:05:06.68 UTC | null | null | null | null | 1,075,423 | null | 1 | 27 | git|git-diff | 15,485 | <p>Actually, <code>git diff</code> is between index and working tree. It just so happens that until you have staged changes to the index (with <code>git add</code>) that its contents will be identical to the <code>HEAD</code> commit.</p>
<p><code>git diff HEAD</code> is between repo and working tree.</p>
<p>See <a href="http://365git.tumblr.com/post/3464927214/getting-a-diff-between-the-working-tree-and-other" rel="noreferrer">365git.tumblr.com post</a>:</p>
<p><a href="https://i.stack.imgur.com/DU1sH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DU1sH.png" alt="git diffs" /></a></p> |
29,080,026 | How to reference header files in Bridging-Header.h after updating CocoaPods to 0.36.x and above? | <p>After updating to CocoaPods 0.36.x, I am unable to add imports into my Bridging-Header.h file. I get the "DBSphereView.h file not found".</p>
<p>The file is indeed present in:</p>
<pre><code>"Pods/DBSphereTagCloud/DBSphereView.h"
"Headers/public/DBSphereTagCloud/DBSphereView.h"
"Headers/private/DBSphereTagCloud/DBSphereView.h"
</code></pre>
<p>My bridge file:</p>
<pre><code>#ifndef Loan_Bridging_Header_h
#define Loan_Bridging_Header_h
#import "DBSphereView.h"
#endif
</code></pre>
<p>I am able to use Frameworks. I have a reference to a well known Framework (Alamofire), and it works great!</p>
<p>My podfile:</p>
<pre><code>source 'https://github.com/CocoaPods/Specs.git'
use_frameworks!
pod 'DBSphereTagCloud', '~> 1.0'
pod 'Alamofire', '~> 1.1'
</code></pre>
<p>Before updating, I had no problems with importing header files.</p>
<p>How do I reference header files in Bridging-Header.h after updating CocoaPods to 0.36.x?</p>
<p>Thank you!</p>
<p>EDIT:</p>
<p>I also tried to create a separate project based on the example "Get Started" from cocoapods.org, without success. After using Frameworks, I can't seem to reference header files in my bridging header file. I must be missing some detail?</p> | 29,094,237 | 5 | 0 | null | 2015-03-16 14:58:27.91 UTC | 11 | 2015-09-30 13:55:08.83 UTC | 2015-07-07 07:30:33 UTC | null | 4,145,420 | null | 1,544,047 | null | 1 | 47 | ios|swift|cocoapods|ios-frameworks | 28,031 | <p>In your <code>Podfile</code>, you specified <code>use_frameworks!</code>. </p>
<p>As a result, the Objective-C code you're including as a dependency (<code>DBSphereTagCloud</code>) is packaged as a framework, instead of a static library. Please see <a href="http://blog.cocoapods.org/CocoaPods-0.36/" rel="noreferrer">CocoaPods 0.36 - Framework and Swift Support</a> for more details. </p>
<p>As a consequence, you don't need a bridging header file. It's enough for you to add:</p>
<pre><code>import DBSphereTagCloud
</code></pre>
<p>in all the Swift files that need that module.</p> |
21,606,987 | How can I strip the whitespace from Pandas DataFrame headers? | <p>I am parsing data from an Excel file that has extra white space in some of the column headings.</p>
<p>When I check the columns of the resulting dataframe, with <code>df.columns</code>, I see:</p>
<pre><code>Index(['Year', 'Month ', 'Value'])
^
# Note the unwanted trailing space on 'Month '
</code></pre>
<p>Consequently, I can't do: </p>
<p><code>df["Month"]</code></p>
<p>Because it will tell me the column is not found, as I asked for "Month", not "Month ".</p>
<p>My question, then, is how can I strip out the unwanted white space from the column headings?</p> | 21,607,530 | 5 | 1 | null | 2014-02-06 15:26:25.683 UTC | 30 | 2021-11-27 00:16:25.803 UTC | 2020-02-11 00:29:31.293 UTC | null | 202,229 | null | 73,371 | null | 1 | 123 | python|pandas|whitespace | 98,587 | <p>You can give functions to the <code>rename</code> method. The <code>str.strip()</code> method should do what you want:</p>
<pre><code>In [5]: df
Out[5]:
Year Month Value
0 1 2 3
[1 rows x 3 columns]
In [6]: df.rename(columns=lambda x: x.strip())
Out[6]:
Year Month Value
0 1 2 3
[1 rows x 3 columns]
</code></pre>
<p><strong>Note</strong>: that this returns a <code>DataFrame</code> object and it's shown as output on screen, but the changes are not actually set on your columns. To make the changes, either use this in a method chain or re-assign the <code>df</code> variabe:</p>
<pre><code>df = df.rename(columns=lambda x: x.strip())
</code></pre> |
21,887,315 | cURL SSL connect error 35 with NSS error -5961 | <p>I have a remote Windows 7 server that is accessible only via HTTPS on port 768. The server is using a signed certificate from a CA listed in the local CentOS server.</p>
<p>Whenever I try to access the remote server via cURL using the following command, it errors out as follows:</p>
<pre><code>[usr@serv certs]# curl -3 -v https://1.1.1.1:768/user/login
* About to connect() to 1.1.1.1 port 768 (#0)
* Trying 1.1.1.1... connected
* Connected to 1.1.1.1 (1.1.1.1) port 768 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
CApath: none
* NSS error -5961
* Closing connection #0
* SSL connect error
curl: (35) SSL connect error
</code></pre>
<p>(Note that the IP address has been hidden for security reasons).</p>
<p>I am running the following version of cURL:</p>
<pre><code>curl 7.19.7 (x86_64-redhat-linux-gnu) libcurl/7.19.7 NSS/3.14.0.0 zlib/1.2.3 libidn/1.18 libssh2/1.4.2
</code></pre>
<p>It's worth noting that this is working on two other remote servers which are both running Windows XP rather than windows 7.</p>
<p>I have tried forcing cURL to use SSLv3 (using the -3 flag and the -SSLv3 flag) with no success.</p>
<hr>
<p>I have just tested the same CURL command on a Raspberry Pi running Raspbian and have been able to connect successfully. I therefore believe it may be an issue with the version of cURL in use on the CentOS server. The raspberry pi is running the following version:</p>
<pre><code>curl 7.26.0 (arm-unknown-linux-gnueabihf) libcurl/7.26.0 OpenSSL/1.0.1e zlib/1.2.7 libidn/1.25 libssh2/1.4.2 librtmp/2.3
Protocols: dict file ftp ftps gopher http https imap imaps ldap pop3 pop3s rtmp rtsp scp sftp smtp smtps telnet tftp
Features: Debug GSS-Negotiate IDN IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP
</code></pre> | 22,145,195 | 5 | 1 | null | 2014-02-19 17:03:03.553 UTC | 10 | 2020-01-29 22:07:06.873 UTC | 2014-03-03 10:09:28.777 UTC | null | 951,577 | null | 951,577 | null | 1 | 22 | curl|ssl|windows-7|centos | 100,388 | <p><code>curl</code> with NSS read the Root CA certificates by default from <code>"/etc/pki/tls/certs/ca-bundle.crt"</code> in the PEM format.</p>
<pre><code>* Initializing NSS with certpath: sql:/etc/pki/nssdb
* CAfile: /etc/pki/tls/certs/ca-bundle.crt
</code></pre>
<p>You can specify another (your) CA certificate (or bundle on the <a href="https://wiki.mozilla.org/NSS_Shared_DB_And_LINUX">NSS Shared DB</a>) by curl's option <code>--cacert</code> with the PEM file containing the CA certificate(s).</p>
<p>If you don't specify the certificate manually with <code>--cacert</code> option, NSS tries to select the right one from the NSS database (located at <code>/etc/pki/nssdb</code>) automatically. You can specify it's nickname by curl's option <code>--cert</code>, this should be sufficient if the key is embedded in the cert, if not you can specify the PEM file with the certificate key using the <code>--key</code>. If the key is protected by a pass-phrase, you can give it by curl's option <code>--pass</code> so you can import your certificate to the NSS shared DB using the <a href="https://developer.mozilla.org/en/docs/NSS/Tools">nss-tools</a> (<code>yum install nss-tools</code>)</p>
<p><strong>Adding a certificate (common command line)</strong></p>
<pre><code>certutil -d sql:/etc/pki/nssdb -A -t <TRUSTARGS> -n <certificate nickname> -i <certificate filename>
</code></pre>
<p>About TRUSTARGS</p>
<p>Specify the trust attributes to modify in an existing certificate or to apply to a certificate when creating it or adding it to a database.</p>
<blockquote>
<p>There are three available trust categories for each certificate,
expressed in this order: " SSL , email , object signing ". In each
category position use zero or more of the following attribute codes:</p>
<ul>
<li>p prohibited (explicitly distrusted)</li>
<li>P Trusted peer</li>
<li>c Valid CA</li>
<li>T Trusted CA to issue client certificates (implies c)</li>
<li>C Trusted CA to issue server certificates (SSL only) (implies c)</li>
<li>u Certificate can be used for authentication or signing</li>
<li>w Send warning (use with other attributes to include a warning when the certificate is used in that context)</li>
</ul>
<p>The attribute codes for the categories are separated by commas, and
the entire set of attributes enclosed by quotation marks. For example:</p>
<p>-t "TCu,Cu,Tuw"</p>
</blockquote>
<p><strong>Trusting a root CA certificate for issuing SSL server certificates</strong></p>
<pre><code>certutil -d sql:/etc/pki/nssdb -A -t "C,," -n <certificate nickname> -i <certificate filename>
</code></pre>
<p><strong>Importing an intermediate CA certificate</strong></p>
<pre><code>certutil -d sql:/etc/pki/nssdb -A -t ",," -n <certificate nickname> -i <certificate filename>
</code></pre>
<p><strong>Trusting a self-signed server certificate</strong></p>
<pre><code>certutil -d sql:/etc/pki/nssdb -A -t "P,," -n <certificate nickname> -i <certificate filename>
</code></pre>
<p><strong>Adding a personal certificate and private key for SSL client authentication</strong></p>
<pre><code>pk12util -d sql:/etc/pki/nssdb -i PKCS12_file_with_your_cert.p12
</code></pre>
<p><strong>Listing all the certificates stored into NSS DB</strong></p>
<pre><code>certutil -d sql:/etc/pki/nssdb -L
</code></pre>
<p><strong>Listing details of a certificate</strong></p>
<pre><code>certutil -d sql:/etc/pki/nssdb -L -n <certificate nickname>
</code></pre>
<p><strong>Deleting a certificate</strong></p>
<pre><code>certutil -d sql:/etc/pki/nssdb -D -n <certificate nickname>
</code></pre>
<p>Hope this helps.</p> |
33,376,486 | Is there a way other than traits to add methods to a type I don't own? | <p>I'm trying to extend the <a href="http://docs.piston.rs/graphics/graphics/grid/struct.Grid.html" rel="noreferrer"><code>Grid</code></a> struct from the piston-2dgraphics library. There's no method for getting the location on the window of a particular cell, so I implemented a trait to calculate that for me. Then, I wanted a method to calculate the neighbours of a particular cell on the grid, so I implemented another trait.</p>
<p>Something about this is ugly and feels unnecessary seeing as how I'll likely never use these traits for anything other than this specific grid structure. Is there another way in Rust to extend a type without having to implement traits each time?</p> | 33,378,549 | 2 | 1 | null | 2015-10-27 19:04:50.543 UTC | 5 | 2018-07-14 13:47:53.823 UTC | 2018-07-14 13:45:50.097 UTC | null | 155,423 | null | 4,622,121 | null | 1 | 41 | rust | 8,782 | <p>As of Rust 1.27, no, there is no other way. It's not possible to define inherent methods on a type defined in another crate. </p>
<p>You can define your own trait with the methods you need, then implement that trait for an external type. This pattern is known as <em>extension traits</em>. The name of extension traits, by convention, ends with <code>Ext</code>, to indicate that this trait is not meant to be used as a generic bound or as a trait object. <a href="http://doc.rust-lang.org/stable/std/?search=trait%3AExt" rel="noreferrer">There are a few examples in the standard library.</a></p>
<pre><code>trait DoubleExt {
fn double(&self) -> Self;
}
impl DoubleExt for i32 {
fn double(&self) -> Self {
*self * 2
}
}
fn main() {
let a = 42;
println!("{}", 42.double());
}
</code></pre>
<p>Other libraries can also export extension traits (example: <a href="http://burntsushi.net/rustdoc/byteorder/?search=trait%3AExt" rel="noreferrer">byteorder</a>). However, as for any other trait, you need to bring the trait's methods in scope with <code>use SomethingExt;</code>.</p> |
9,305,036 | How do I obfuscate the ids of my records in rails? | <p>I'm trying to figure out how to obfuscate the ids of my records in rails.</p>
<p>For example: a typical path might look like <a href="http://domain/records/1" rel="noreferrer">http://domain/records/1</a>, so it's pretty easy for people to deduce how much traffic the site is getting if they just create a new record. </p>
<p>One solution that I've used is to hash the id with a salt, but since I'm not sure whether that function is bijective, I end up storing it in another column in my database and double check for uniqueness. </p>
<p>Another option I was thinking about was generating a random hash and storing that as another column. If it isn't unique ... just generate another one. </p>
<p>What's the best way of doing this?</p> | 9,305,230 | 6 | 0 | null | 2012-02-16 03:15:22.923 UTC | 13 | 2020-08-18 08:00:28.417 UTC | null | null | null | null | 686,567 | null | 1 | 16 | ruby-on-rails|database|ruby-on-rails-3|data-binding|obfuscation | 7,167 | <p>You could use the built-in OpenSSL library to encrypt and decrypt your identifiers, that way you would only need to overwrite <code>to_param</code> on your models. You'll also need to use Base64 to convert the encrypted data into plain text. I would stick this in a module so it can be reused:</p>
<pre><code>require 'openssl'
require 'base64'
module Obfuscate
def self.included(base)
base.extend self
end
def cipher
OpenSSL::Cipher::Cipher.new('aes-256-cbc')
end
def cipher_key
'blah!'
end
def decrypt(value)
c = cipher.decrypt
c.key = Digest::SHA256.digest(cipher_key)
c.update(Base64.decode64(value.to_s)) + c.final
end
def encrypt(value)
c = cipher.encrypt
c.key = Digest::SHA256.digest(cipher_key)
Base64.encode64(c.update(value.to_s) + c.final)
end
end
</code></pre>
<p>So now your models would need to look something like this:</p>
<pre><code>class MyModel < ActiveRecord::Base
include Obfuscate
def to_param
encrypt id
end
end
</code></pre>
<p>Then in your controller when you need to find a record by the encrypted id, you would use something like this:</p>
<pre><code>MyModel.find MyModel.decrypt(params[:id])
</code></pre>
<p>If you're looking to encrypt/decrypt ids <strong><em>without</em></strong> storing them in the database, this is probably the easiest way to go.</p> |
30,765,157 | Is it possible to opt your iPad app out of multitasking on iOS 9 | <p>I have a large app that I will need some time to optimize for iOS9. </p>
<p>Edit: What I am worried about is all the UI getting squeezed together when the app window size is reduced. So my question is, is there any way to force full screen for the app?</p> | 30,768,183 | 4 | 1 | null | 2015-06-10 19:06:22.78 UTC | 12 | 2019-10-22 16:22:46.61 UTC | 2017-03-16 14:06:09.713 UTC | null | 1,586,924 | null | 2,891,327 | null | 1 | 76 | ios|xcode|ipad|ios9|multitasking | 36,406 | <p>You have to modify your project to support multitasking. According to <a href="https://developer.apple.com/videos/wwdc/2015/?id=205">WWDC 2015 video</a>, to adopt your app for multitasking, satisfy these requirements:</p>
<ol>
<li>Build your app with iOS 9 SDK</li>
<li>Support all orientations</li>
<li>Use Launch Storyboards</li>
</ol>
<p>So, if any of this is not done yet, your app will not be able to support multitasking.</p>
<p>Of course, if you don't use size classes, put it at the top of the list.</p>
<p>Edit: according to you question edit. There is a UIRequiresFullScreen key in Info.plist. See more at <a href="https://developer.apple.com/library/prerelease/ios/documentation/WindowsViews/Conceptual/AdoptingMultitaskingOniPad/index.html#//apple_ref/doc/uid/TP40015145-CH3-SW1">Apple docs</a></p> |
34,368,385 | Does an array object explicitly contain the indexes? | <p>Since day one of learning Java I've been told by various websites and many teachers that arrays are consecutive memory locations which can store the specified number of data all of the same type.</p>
<p>Since an array is an object and object references are stored on the stack, and actual objects live in the heap, object references point to actual objects.</p>
<p>But when I came across examples of how arrays are created in memory, they always show something like this:</p>
<p>(In which a reference to an array object is stored on the stack and that reference points to the actual object in the heap, where there are also explicit indexes pointing to specific memory locations)</p>
<p><a href="https://i.stack.imgur.com/DDMui.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/DDMui.jpg" alt="Internal working of objects taught by various websites and teachers"></a></p>
<p>But recently I came across <a href="http://chortle.ccsu.edu/java5/Notes/chap49C/ch49C_4.html#array,_row_and_column_numbers" rel="noreferrer">online notes</a> of Java in which they stated that arrays' explicit indexes are not specified in the memory. The compiler just knows where to go by looking at the provided array index number during runtime.</p>
<p>Just like this:</p>
<p><a href="https://i.stack.imgur.com/K71DK.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/K71DK.jpg" alt="Enter image description here"></a></p>
<p>After reading the notes, I also searched on Google regarding this matter, but the contents on this issue were either quite ambiguous or non-existent.</p>
<p>I need more clarification on this matter. Are array object indexes explicitly shown in memory or not? If not, then how does Java manage the commands to go to a particular location in an array during runtime?</p> | 34,373,672 | 9 | 1 | null | 2015-12-19 07:21:44.267 UTC | 8 | 2016-06-30 14:29:36.513 UTC | 2015-12-19 18:01:56.953 UTC | null | 964,243 | null | 2,015,669 | null | 1 | 29 | java|arrays | 3,921 | <blockquote>
<p>Does an array object explicitly contain the indexes?</p>
</blockquote>
<p><strong>Short answer:</strong> No.</p>
<p><strong>Longer answer:</strong> Typically not, but it theoretically could do.</p>
<p><strong>Full answer:</strong></p>
<p>Neither the Java Language Specification nor the Java Virtual Machine Specification makes <em>any</em> guarantees about how arrays are implemented internally. All it requires is that array elements are accessed by an <code>int</code> index number having a value from <code>0</code> to <code>length-1</code>. How an implementation actually fetches or stores the values of those indexed elements is a detail private to the implementation.</p>
<p>A perfectly conformant JVM could use a <a href="https://en.wikipedia.org/wiki/Hash_table" rel="nofollow">hash table</a> to implement arrays. In that case, the elements would be non-consecutive, scattered around memory, and it <em>would</em> need to record the indexes of elements, to know what they are. Or it could send messages to a man on the moon who writes the array values down on labeled pieces of paper and stores them in lots of little filing cabinets. I can't see why a JVM would want to do these things, but it could.</p>
<p>What will happen in practice? A typical JVM will allocate the storage for array elements as a flat, contiguous chunk of memory. Locating a particular element is trivial: multiply the fixed memory size of each element by the index of the wanted element and add that to the memory address of the start of the array: <code>(index * elementSize) + startOfArray</code>. This means that the array storage consists of nothing but raw element values, consecutively, ordered by index. There is no purpose to also storing the index value with each element, because the element's address in memory implies its index, and vice-versa. However, I don't think the diagram you show was trying to say that it explicitly stored the indexes. The diagram is simply labeling the elements on the diagram so you know what they are.</p>
<p>The technique of using contiguous storage and calculating the address of an element by formula is simple and extremely quick. It also has very little memory overhead, assuming programs allocate their arrays only as big as they really need. Programs depend on and expect the particular performance characteristics of arrays, so a JVM that did something weird with array storage would probably perform poorly and be unpopular. So <em>practical</em> JVMs will be constrained to implement contiguous storage, or something that performs similarly.</p>
<p>I can think of only a couple of variations on that scheme that would ever be useful:</p>
<ol>
<li><p>Stack-allocated or register-allocated arrays: During optimization, a JVM might determine through <a href="https://en.wikipedia.org/wiki/Escape_analysis" rel="nofollow">escape analysis</a> that an array is only used within one method, and if the array is also a smallish fixed size, it would then be an ideal candidate object for being allocated directly on the stack, calculating the address of elements relative to the stack pointer. If the array is extremely small (fixed size of maybe up to 4 elements), a JVM could go even further and store the elements directly in CPU registers, with all element accesses unrolled & hardcoded.</p></li>
<li><p>Packed boolean arrays: The smallest directly addressable unit of memory on a computer is typically an 8-bit byte. That means if a JVM uses a byte for each boolean element, then boolean arrays waste 7 out of every 8 bits. It would use only 1 bit per element if booleans were packed together in memory. This packing isn't done typically because extracting individual bits of bytes is slower, and it needs special consideration to be safe with multithreading. However, packed boolean arrays might make perfect sense in some memory-constrained embedded devices.</p></li>
</ol>
<p>Still, neither of those variations requires every element to store its own index.</p>
<p>I want to address a few other details you mentioned:</p>
<blockquote>
<p>arrays store the specified number of data all of the same type</p>
</blockquote>
<p>Correct.</p>
<p>The fact that all an array's elements are the same <strong>type</strong> is important because it means all the elements are the same <strong>size</strong> in memory. That's what allows for elements to be located by simply multiplying by their common size.</p>
<p>This is still technically true if the array element type is a reference type. Although in that case, the value of each element is not the object itself (which could be of varying size) but only an address which refers to an object. Also, in that case, the actual runtime type of objects referred to by each element of the array could be any subclass of the element type. E.g.,</p>
<pre><code>Object[] a = new Object[4]; // array whose element type is Object
// element 0 is a reference to a String (which is a subclass of Object)
a[0] = "foo";
// element 1 is a reference to a Double (which is a subclass of Object)
a[1] = 123.45;
// element 2 is the value null (no object! although null is still assignable to Object type)
a[2] = null;
// element 3 is a reference to another array (all arrays classes are subclasses of Object)
a[3] = new int[] { 2, 3, 5, 7, 11 };
</code></pre>
<blockquote>
<p>arrays are consecutive memory locations</p>
</blockquote>
<p>As discussed above, this doesn't have to be true, although it is almost surely true in practice.</p>
<p>To go further, note that although the JVM might allocate a contiguous chunk of memory from the operating system, that doesn't mean it ends up being contiguous in <em>physical RAM</em>. The OS can give programs a <a href="https://en.wikipedia.org/wiki/Virtual_memory" rel="nofollow">virtual address space</a> that behaves as if contiguous, but with individual pages of memory scattered in various places, including physical RAM, swap files on disk, or regenerated as needed if their contents are known to be currently blank. Even to the extent that pages of the virtual memory space are resident in physical RAM, they could be arranged in physical RAM in an arbitrary order, with complex <em>page tables</em> that define the mapping from virtual to physical addresses. And even if the OS thinks it is dealing with "physical RAM", it still could be running in an emulator. There can be layers upon layers upon layers, is my point, and getting to the bottom of them <a href="https://en.wikipedia.org/wiki/Simulism" rel="nofollow">all</a> to find out what's really going on takes a while!</p>
<p>Part of the purpose of programming language specifications is to separate the <em>apparent behavior</em> from the <em>implementation details</em>. When programming you can often program to the specification alone, free from worrying about how it happens internally. The implementation details become relevant however, when you need to deal with the the real-world constraints of limited speed and memory.</p>
<blockquote>
<p>Since an array is an object and object references are stored on the stack, and actual objects live in the heap, object references point to actual objects</p>
</blockquote>
<p>This is correct, except what you said about the stack. Object references <em>can</em> be stored on the stack (as local variables), but they can <em>also</em> be stored as static fields or instance fields, or as array elements as seen in the example above.</p>
<p>Also, as I mentioned earlier, clever implementations can sometimes allocate objects directly on the stack or in CPU registers as an optimization, although this has zero effect on your program's apparent behavior, only its performance.</p>
<blockquote>
<p>The compiler just knows where to go by looking at the provided array index number during runtime.</p>
</blockquote>
<p>In Java, it's not the compiler that does this, but the virtual machine. Arrays are <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-3.html#jvms-3.9" rel="nofollow">a feature of the JVM itself</a>, so the compiler can translate your source code that uses arrays simply to bytecode that uses arrays. Then it's the JVM's job to decide how to implement arrays, and the compiler neither knows nor cares how they work.</p> |
34,303,371 | Can we load Parquet file into Hive directly? | <p>I know we can load parquet file using Spark SQL and using Impala but wondering if we can do the same using Hive. I have been reading many articles but I am still confused. </p>
<p>Simply put, I have a parquet file - say users.parquet. Now I am struck here on how to load/insert/import data from the users.parquet into hive (obviously into a table).</p>
<p>Please advise or point me in right direction if I am missing something obvious.</p>
<p><a href="https://stackoverflow.com/questions/33625617/creating-hive-table-using-parquet-file-metadata">Creating hive table using parquet file metadata</a></p>
<p><a href="https://phdata.io/examples-using-textfile-and-parquet-with-hive-and-impala/" rel="noreferrer">https://phdata.io/examples-using-textfile-and-parquet-with-hive-and-impala/</a></p> | 34,344,654 | 4 | 1 | null | 2015-12-16 03:16:26.09 UTC | 8 | 2017-11-10 12:33:09.263 UTC | 2017-05-23 12:02:34.313 UTC | null | -1 | null | 2,305,003 | null | 1 | 25 | hadoop|hive|apache-spark-sql|hiveql|parquet | 66,764 | <p>Get schema of the parquet file using parquet tools, for details check link <a href="http://kitesdk.org/docs/0.17.1/labs/4-using-parquet-tools-solution.html" rel="noreferrer">http://kitesdk.org/docs/0.17.1/labs/4-using-parquet-tools-solution.html</a></p>
<p>and build table using the schema on the top of the file, for details check <a href="https://stackoverflow.com/questions/34202743/create-hive-table-to-read-parquet-files-from-parquet-avro-schema/34207923#34207923">Create Hive table to read parquet files from parquet/avro schema</a></p> |
10,263,956 | Use datetime.strftime() on years before 1900? ("require year >= 1900") | <p>I used :
<code>utctime = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds = tup[5])
last_visit_time = "Last visit time:"+ utctime.strftime('%Y-%m-%d %H:%M:%S')</code></p>
<p>But I have the time of 1601, so the error show:
<code>ValueError: year=1601 is before 1900; the datetime strftime() methods require year >= 1900</code></p>
<p>I used python2.7, how can I make it? Thanks a lot!</p> | 10,264,070 | 4 | 1 | null | 2012-04-21 23:32:13.81 UTC | 8 | 2016-02-24 16:43:05.77 UTC | 2012-04-21 23:38:26.57 UTC | user166390 | null | null | 1,277,161 | null | 1 | 36 | python|datetime|strftime | 21,024 | <p>You can do the following:</p>
<pre><code>>>> utctime.isoformat()
'1601-01-01T00:00:00.000050'
</code></pre>
<p>Now if you want to have exactly the same format as above:</p>
<pre><code>iso = utctime.isoformat()
tokens = iso.strip().split("T")
last_visit_time = "Last visit time: %s %s" % (tokens[0], tokens[1].strip().split(".")[0])
</code></pre>
<p>Not that there seems to be a patch for <code>strftime</code> to fix this behavior <a href="http://bugs.python.org/file10253/strftime-pre-1900.patch">here</a> (not tested)</p> |
22,489,703 | Trying to remove fragment from view gives me NullPointerException on mNextAnim | <p>I've got 3 fragments, one NavigationDrawer, one MapFragment, and one user-defined "MapInfoFragment". I want the "MapInfoFragment" to appear semi-transparent over top of the MapFragment on certain events and disappear on others. I don't really care if I completely remove the fragment and create a new one each time, or I just change the visibility and information displayed. Currently I'm just trying to use FragmentManager's .hide() function, but I've also tried .remove and .detach with similar results. </p>
<p>Error:</p>
<pre><code>03-18 14:28:10.965 24711-24711/com.[packageName].asTest D/AndroidRuntime﹕ Shutting down VM
03-18 14:28:10.965 24711-24711/com.[packageName].asTest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.[packageName].asTest, PID: 24711
java.lang.NullPointerException: Attempt to write to field 'int android.app.Fragment.mNextAnim' on a null object reference
at android.app.BackStackRecord.run(BackStackRecord.java:658)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
</code></pre>
<p>Activity_main.xml:</p>
<pre><code><android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.[packageName].asTest.MainActivity">
<!-- As the main content view, the view below consumes the entire
space available using match_parent in both dimensions. -->
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
map:cameraZoom="8"
map:mapType="satellite"
map:uiRotateGestures="false"
android:layout_gravity="center_horizontal|top"
/>
</FrameLayout>
<fragment android:id="@+id/navigation_drawer"
android:layout_width="@dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
android:name="com.[packageName].asTest.NavigationDrawerFragment"
tools:layout="@layout/simple_list_item_1" />
<fragment android:id="@+id/map_info"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.[packageName].asTest.MapInfoFragment" />
</android.support.v4.widget.DrawerLayout>
</code></pre>
<p>Offending Code:</p>
<pre><code>FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.hide(getFragmentManager().findFragmentById(R.id.map_info));
ft.commit();
</code></pre>
<h2>Update 1</h2>
<p>I changed <code>map_info_layout</code> to <code>map_info</code> and there's no change in the error I'm getting. I'd previously had <code>map_info_layout</code> defined as the id for the root FrameLayout of the MapInfoFragment's layout xml, so I think <code>map_info_layout</code> and <code>map_info</code> were pointing to the same thing.</p>
<h2>Update 2: My solution</h2>
<p>Turned out that I had <code>MapInfoFragment</code> extending <code>android.support.v4.app.Fragment</code> instead of <code>android.app.Fragment</code> and I was using the <code>android.app.FragmentTransaction</code> instead of <code>android.support.v4.app.FragmentTransaction</code>. Switched everything to <code>android.app.</code> since I'm not interested in older device compatibility. Thanks Fllo.</p>
<h2>Update 3: General solution</h2>
<p>Stop trying to hide null objects</p> | 23,770,928 | 7 | 1 | null | 2014-03-18 19:57:24.313 UTC | 13 | 2021-03-29 11:55:42.48 UTC | 2016-03-01 02:49:32.43 UTC | null | 1,321,236 | null | 1,321,236 | null | 1 | 46 | android|android-fragments|android-studio | 43,910 | <p>I know you've solved this yourself, but I want to explain how this error happens, since it just happened to me.</p>
<p>Basically you're calling <code>hide()</code>, <code>remove()</code>, etc., with a null value.</p>
<p>The error isn't obvious, and the stack trace doesn't originate from your own sources when this happens, so it's not trivial to realise what it is.</p> |
7,202,647 | What are the best practices for implementing form in iOS | <p>I need to create several screens-forms that would be used for entering data and posting to the server. I have not done that kind of stuff yet, so I'm just wondering are there any best practices for doing that. Currently, I would just drop several text fields, radios and etc, do some manual input validation, do an assembly of input data into URL and then do submission to the server. </p>
<p>I'm thinking about usability, so I think I should implement "move to next text field" after a user dismisses keyboard (resigns first responder). But if all the inputs are filled already and a user changes the value of one field then just navigate to submit button. So, IMHO that might be an example of practice for implementing a form. What practices do you apply?</p> | 7,203,003 | 2 | 0 | null | 2011-08-26 09:26:00.827 UTC | 13 | 2012-10-17 07:29:44.643 UTC | null | null | null | null | 597,292 | null | 1 | 22 | iphone|objective-c|ios|forms | 12,490 | <p>A few of my experiences from implementing forms:</p>
<ul>
<li><p>Place inputs and labels in the rows of a <code>UITableView</code> (grouped). It's the way Apple does it and the way most users are used to. But be wary with the reuse of cells, as this may cause your inputs to move around otherwise. In other words, keep references to your inputs in a separate <code>NSArray</code> (or <code>NSDictionary</code>) to make sure they're not lost when the UITableViewCells are reused.</p></li>
<li><p>Using the keyboard return key to move to the next input is a good idea. It's easy to do if you just keep track of which table cell you're editing, so you can move on to the next one using its NSIndexPath.</p></li>
<li><p>Check your form validity when the user's made modifications, i.e. by listening to <code>UITextFieldTextDidChangeNotification</code> and in <code>textFieldShouldEndEditing:</code>. If the form's valid, allow the user to submit it on return or using a Done button (or similar).</p></li>
<li><p>If the user's editing the last row in the form, change the keyboard return button type to Done or similar.</p></li>
<li><p><strong>UPDATE</strong>: Since posting this, it's also become quite common to show input accessory views (the toolbar with Prev/Next/Done) on top of the keyboard. In particular when you've got a more extensive form where users might want to go back and forth between inputs. And it's quite <a href="https://stackoverflow.com/questions/5953439/adding-input-accessory-view-to-uitextfield-while-keyboard-is-visible">easy to implement</a>.</p></li>
</ul>
<p>Hope that helps!</p> |
7,117,200 | Devise for Twitter, Cookie Overflow error? | <p>I am trying to integrate twitter into devise using this <a href="https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview" rel="noreferrer">guide</a>. I basically take all occurence of facebook and substitue it with twitter. However, when I sign in with twitter, I am getting the following error:</p>
<pre><code>ActionDispatch::Cookies::CookieOverflow (ActionDispatch::Cookies::CookieOverflow):
</code></pre>
<p>at the following url:</p>
<pre><code>http://localhost:3000/users/auth/twitter/callback?oauth_token=something&oauth_verifier=blah
</code></pre>
<p>Is there any nice way to get around fixing this problem? </p>
<p>Thanks!</p> | 7,117,278 | 2 | 0 | null | 2011-08-19 05:11:21.013 UTC | 11 | 2011-08-19 08:54:38.643 UTC | null | null | null | null | 140,330 | null | 1 | 27 | ruby-on-rails|twitter|devise | 9,437 | <p>The problem is with <code>session["devise.facebook_data"] = env["omniauth.auth"]</code>. Twitter's response contains an <code>extra</code> section that is very large and does not fit in the session. One option is to store <code>env["omniauth.auth"].except("extra")</code> in the session instead.</p> |
35,602,541 | Create .pyi files automatically? | <p>How can I automatically create the boilerplate code of <a href="https://www.python.org/dev/peps/pep-0484/#stub-files" rel="noreferrer">pyi</a> files?</p>
<p>I want to create a <a href="https://www.python.org/dev/peps/pep-0484/#stub-files" rel="noreferrer">pyi</a> file for type hinting as described in <a href="https://www.python.org/dev/peps/pep-0484/" rel="noreferrer">pep484</a> which contains all method names.</p>
<p>I don't want magic. I want to add the type information after auto creating the file. </p>
<p>I want to avoid the copy+paste work.</p>
<p>Goal: Type hinting in PyCharm for Python2.</p> | 35,706,456 | 2 | 2 | null | 2016-02-24 12:42:46.71 UTC | 16 | 2020-01-11 13:40:15.957 UTC | 2016-02-29 19:17:19.747 UTC | null | 633,961 | null | 633,961 | null | 1 | 31 | python|pycharm|type-hinting | 19,589 | <p>As far as I am concerned, there is no such direct tool in PyCharm. There are, however, 3rd party tools for this.</p>
<hr>
<h1><code>.pyi</code> generators</h1>
<h2><a href="http://www.mypy-lang.org/" rel="noreferrer" title="MyPy-lang official website">MyPy</a></h2>
<p>Yes, I guess anyone who wants to use compile-time type checking in Python, probably ends up using MyPy. MyPy contains <a href="https://github.com/python/mypy/blob/master/mypy/stubgen.py" rel="noreferrer" title="stubgen.py on Github">stubgen.py</a> tool which generates <code>.pyi</code> files.</p>
<h3>Usage</h3>
<pre><code>mkdir out
stubgen urllib.parse
</code></pre>
<p>generates <code>out/urllib/parse.pyi</code>.</p>
<p>You can use it wit Python2 too:</p>
<pre><code>stubgen --py2 textwrap
</code></pre>
<p>And for C modules:</p>
<pre><code>scripts/stubgen --docpath <DIR>/Python-3.4.2/Doc/library curses
</code></pre>
<p>If you want to specify the path to your custom package, you can use <code>--search-path</code> option:</p>
<pre><code>stubgen my-pkg --search-path=folder/path/to/the/package
</code></pre>
<h2><a href="https://github.com/edreamleo/make-stub-files" rel="noreferrer" title="make-stub-files on Github">make-stub-files</a></h2>
<p>This project is dedicated to exactly this goal.</p>
<h3>Usage</h3>
<p>A very basic one (but it has a handful of options, just consult <code>README.md</code> or <code>make_stub_files -h</code></p>
<pre><code>make_stub_files foo.py
</code></pre>
<hr>
<h1>pre-written <code>.pyi</code> files</h1>
<p>So you don't have to write your own.</p>
<h2><a href="https://github.com/python/typeshed" rel="noreferrer" title="Typeshed on Github">Typeshed</a></h2>
<p>Yes, if you're using <code>.pyi</code> files in your own project, you probably want to use this also when using external code. Typeshed contains <code>.pyi</code> files for Python2 and Python3 stdlib and a bunch of Python2 libraries (like <a href="https://github.com/python/typeshed/tree/master/third_party/2/redis" rel="noreferrer">redis</a>, <a href="https://github.com/python/typeshed/tree/master/third_party/2and3/Crypto" rel="noreferrer">crypto</a>, ...) and some Python3 libraries (like <a href="https://github.com/python/typeshed/tree/master/third_party/3/werkzeug" rel="noreferrer">werkzeug</a> or <a href="https://github.com/python/typeshed/tree/master/third_party/2and3/requests" rel="noreferrer">requests</a>), all nicely versioned.</p>
<hr>
<h1>PyCharm alternatives to <code>.pyi</code> files</h1>
<p>In case you're lazy, or simply just working on a project which doesn't require <code>.pyi</code> files and you don't want to be bothered by using 3rd party tools, PyCharm allows you to use:</p>
<ul>
<li><a href="https://www.jetbrains.com/pycharm/help/type-hinting-in-pycharm.html#legacy" rel="noreferrer">Type docstrings</a> (legacy)</li>
<li><a href="https://www.python.org/dev/peps/pep-3107/" rel="noreferrer">Python 3 function annotations</a></li>
</ul> |
18,227,540 | Error: MapFragment cannot be cast to android.support.v4.app.Fragment | <p>First, I watched out here: <a href="https://stackoverflow.com/questions/13757730/start-fragmentactivity-from-activity">Start FragmentActivity from Activity</a> and now I have the following problem:</p>
<p><strong>MapsActivity:</strong></p>
<pre><code>public class MapsActivity extends FragmentActivity {
private GoogleMap mMap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
setUpMapIfNeeded();
}
...
</code></pre>
<p>and want to start it out of the <strong>MainActivity</strong> with:</p>
<pre><code>startActivity(new Intent(this, MapsActivity.class));
</code></pre>
<p>The activity is registered in Android Manifest:</p>
<pre><code><activity android:name="de.xbjoernx.gapp.MapsActivity"></activity>
</code></pre>
<h1>Error</h1>
<pre><code>FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{de.xbjoernx.gapp/de.xbjoernx.gapp.MapsActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
at android.app.ActivityThread.access$600(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.inflate(LayoutInflater.java:466)
at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:323)
at android.app.Activity.setContentView(Activity.java:1881)
at de.xbjoernx.gapp.MapsActivity.onCreate(MapsActivity.java:19)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2262)
... 11 more
Caused by: java.lang.ClassCastException: com.google.android.gms.maps.MapFragment cannot be cast to android.support.v4.app.Fragment
at android.support.v4.app.Fragment.instantiate(Fragment.java:394)
at android.support.v4.app.Fragment.instantiate(Fragment.java:369)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:272)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:676)
... 20 more
</code></pre>
<p>Any suggestions how to fix it?</p>
<p>Thanks so far :)</p> | 18,227,605 | 1 | 2 | null | 2013-08-14 09:11:13.883 UTC | 6 | 2019-06-25 14:50:12.967 UTC | 2017-05-23 11:54:50.48 UTC | null | -1 | null | 2,542,147 | null | 1 | 47 | android|google-maps-android-api-2 | 35,300 | <p>as you are extending <code>FragmentActivity</code> which indicates you are using Support library v4 compatible with lower version of android. Replace <code>MapFragment</code> with <code>SupportMapFragment</code> inside your xml file. <code>SupportMapFragment</code> is the one to use with the Android Support package. <code>MapFragment</code> is for the native API Level 11 version of fragments.</p> |
2,206,397 | Android: Intent.ACTION_SEND with EXTRA_STREAM doesn't attach any image when choosing Gmail app on htc Hero | <p>On the Emulator with a default mail-app all works fine. But I have no attach when I'am receiving a mail which I've sent from my Hero using a Gmail app. The default Mail app on the hero works fine. </p>
<p>How can I make this code works with Gmail app on Hero?<br/>
You can see the code below.</p>
<pre><code> private void startSendIntent() {
Bitmap bitmap = Bitmap.createBitmap(editableImageView.getWidth(), editableImageView.getHeight(), Bitmap.Config.RGB_565);
editableImageView.draw(new Canvas(bitmap));
File png = getFileStreamPath(getString(R.string.file_name));
FileOutputStream out = null;
try {
out = openFileOutput(getString(R.string.file_name), MODE_WORLD_READABLE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) out.close();
}
catch (IOException ignore) {}
}
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(png));
emailIntent.setType("image/png");
startActivity(Intent.createChooser(emailIntent, getString(R.string.send_intent_name)));
}
</code></pre>
<p>in Logs I see the following:</p>
<pre><code>02-05 17:03:37.526: DEBUG/Gmail(11511): URI FOUND:file:///sdcard/DCIM/100MEDIA/IMAG0001.jpg
02-05 17:03:37.535: DEBUG/Gmail(11511): ComposeActivity added to message:0 attachment:|IMAG0001.jpg|image/jpeg|0|image/jpeg|LOCAL_FILE|file:///sdcard/DCIM/100MEDIA/IMAG0001.jpg size:0
02-05 17:03:37.585: INFO/Gmail(11511): >>>>> Attachment uri: file:///sdcard/DCIM/100MEDIA/IMAG0001.jpg
02-05 17:03:37.585: INFO/Gmail(11511): >>>>> type: image/jpeg
02-05 17:03:37.585: INFO/Gmail(11511): >>>>> name: IMAG0001.jpg
02-05 17:03:37.585: INFO/Gmail(11511): >>>>> size: 0
</code></pre>
<p>Thank you for the answer.</p> | 3,268,557 | 3 | 2 | null | 2010-02-05 10:04:47.563 UTC | 7 | 2013-05-20 05:54:19.59 UTC | 2010-02-05 14:06:57.34 UTC | null | 227,016 | null | 227,016 | null | 1 | 12 | android|email|attachment|android-intent|htc-hero | 38,877 | <p>For me the problem was solved with the following lines of code:</p>
<pre><code>Bitmap screenshot = Bitmap.createBitmap(_rootView.getWidth(), _rootView.getHeight(), Bitmap.Config.RGB_565);
_rootView.draw(new Canvas(screenshot));
String path = Images.Media.insertImage(getContentResolver(), screenshot, "title", null);
Uri screenshotUri = Uri.parse(path);
final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
emailIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
emailIntent.setType("image/png");
startActivity(Intent.createChooser(emailIntent, "Send email using"));
</code></pre>
<p>The key thing is that I'm saving the screen-shot to the media library and then it can successfully send a file from there.</p> |
8,974,328 | MySQL Multiple Joins in one query? | <p>I have the following query:</p>
<pre><code>SELECT
dashboard_data.headline,
dashboard_data.message,
dashboard_messages.image_id
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
</code></pre>
<p>So I am using an <code>INNER JOIN</code> and grabbing the <code>image_id</code>. So now, I want to take that image_id and turn it into <code>images.filename</code> from the images table. </p>
<p>How can I add that in to my query?</p> | 8,974,371 | 4 | 1 | null | 2012-01-23 15:46:12.81 UTC | 37 | 2019-03-15 15:19:01.537 UTC | 2012-01-23 15:52:37.193 UTC | null | 68,998 | null | 799,653 | null | 1 | 141 | mysql|sql|join | 441,571 | <p>You can simply add another join like this:</p>
<pre><code>SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
INNER JOIN images
ON dashboard_messages.image_id = images.image_id
</code></pre>
<p>However be aware that, because it is an <code>INNER JOIN</code>, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a <code>LEFT OUTER JOIN</code> which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a null)</p>
<pre><code>SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data
INNER JOIN dashboard_messages
ON dashboard_message_id = dashboard_messages.id
LEFT OUTER JOIN images
ON dashboard_messages.image_id = images.image_id
</code></pre> |
769,995 | Debugging a release version of a DLL (with PDB file) | <p>If I have a DLL (that was built in release-mode) and the corresponding PDB file, is it possible to debug (step-into) classes/methods contained in that DLL?</p>
<p>If so, what are the required steps/configuration (e.g. where to put the PDB file)?</p>
<p><strong>Edit:</strong></p>
<p>If have the PDB file in the same place as the DLL (in the bin/debug directory of a simple console test application). I can see that the symbols for the DLL are loaded (in the Output window and also in the Modules window), but still I cannot step into the methods of that DLL.</p>
<p>Could this be the result of compiler optimizations (as described by Michael in his answer)?</p> | 777,033 | 4 | 0 | null | 2009-04-20 20:40:45.243 UTC | 11 | 2010-04-14 00:34:37.57 UTC | 2010-04-14 00:34:37.57 UTC | null | 294,313 | null | 19,635 | null | 1 | 23 | c#|visual-studio-2008|debugging|pdb-files | 29,463 | <p>I finally found what cause the problems debugging a DLL that was built in release configuration:</p>
<p>First of all, it basically works as expected. Which means, if I have a DLL built in release-configuration plus the corresponding PDB file, then I can debug the classes/methods contained in that DLL.</p>
<p>When I first tried this, I unfortunately tried to step into methods of a class which has the <strong>DebuggerStepThroughAttribute</strong>, e.g:</p>
<pre><code>[System.Diagnostics.DebuggerStepThrough]
public class MyClass {
public void Test() { ... }
}
</code></pre>
<p>In that case, it is of course not possible to step into the method from the debugger (as expected/intended).</p>
<p>So everything works as intended. Thanks a lot for your answers.</p> |
42,605,093 | AWS Lambda RDS connection timeout | <p>I'm trying to write a Lambda function using Node.js which connects to my RDS database. The database is working and accessible from my Elastic Beanstalk environment. When I run the function, it returns a timeout error.</p>
<p>Tried to increase the timeout up to 5 minutes with the exact same result.</p>
<p>The conclusion I came to after some research is that it's probably a security issue but couldn't find the solution in Amazon's documentation or in <a href="https://stackoverflow.com/questions/35880022/error-connect-etimedout-rds-lambda">this</a> answer (which is the only one I could find on the topic).</p>
<p>Here are the security details:</p>
<ul>
<li>Both the RDS and the Lambda are in the same security group.</li>
<li>The RDS has All traffic inbound and outbound rules.</li>
<li>The Lambda has AmazonVPCFullAccess policy in it's role.</li>
</ul>
<p>My code is:</p>
<pre><code>'use strict';
console.log("Loading getContacts function");
var AWS = require('aws-sdk');
var mysql = require('mysql');
exports.handler = (event, context, callback) => {
var connection = mysql.createConnection({
host : '...',
user : '...',
password : '...',
port : 3306,
database: 'ebdb',
debug : false
});
connection.connect(function(err) {
if (err) callback(null, 'error ' +err);
else callback(null, 'Success');
});
};
</code></pre>
<p>The result I'm getting is:</p>
<pre><code>"errorMessage": "2017-03-05T05:57:46.851Z 9ae64c49-0168-11e7-b49a-a1e77ae6f56c Task timed out after 10.00 seconds"
</code></pre> | 42,619,071 | 10 | 3 | null | 2017-03-05 06:07:36.473 UTC | 9 | 2022-07-08 10:40:05.477 UTC | 2017-07-01 09:01:55.263 UTC | null | 6,382,901 | null | 2,318,632 | null | 1 | 37 | node.js|amazon-web-services|aws-lambda|rds | 36,146 | <p>I want to thank everyone who helped, the problem turned out to be different than I thought. The <code>callback</code> in the code doesn't work for some reason even though it's in AMAZON'S OWN DEFAULT SAMPLE.</p>
<p>The working code looks like this:</p>
<pre><code>'use strict';
console.log("Loading getContacts function");
var AWS = require('aws-sdk');
var mysql = require('mysql');
exports.handler = (event, context) => {
var connection = mysql.createConnection({
host : '...',
user : '...',
password : '...',
port : 3306,
database: 'ebdb',
debug : false
});
connection.connect(function(err) {
if (err) context.fail();
else context.succeed('Success');
});
};
</code></pre> |
29,803,093 | Check which columns in DataFrame are Categorical | <p>I am new to Pandas... I want to a simple and generic way to find which columns are <code>categorical</code> in my <code>DataFrame</code>, when I don't manually specify each column type, unlike in <a href="https://stackoverflow.com/questions/26924904/check-if-dataframe-column-is-categorical">this SO question</a>. The <code>df</code> is created with:</p>
<pre><code>import pandas as pd
df = pd.read_csv("test.csv", header=None)
</code></pre>
<p>e.g.</p>
<pre><code> 0 1 2 3 4
0 1.539240 0.423437 -0.687014 Chicago Safari
1 0.815336 0.913623 1.800160 Boston Safari
2 0.821214 -0.824839 0.483724 New York Safari
</code></pre>
<p>.</p>
<p><strong>UPDATE (2018/02/04) The question assumes numerical columns are NOT categorical, @Zero's <a href="https://stackoverflow.com/a/29803290/1910555">accepted answer solves this</a>.</strong></p>
<p><strong>BE CAREFUL - As @Sagarkar's comment points out that's not always true.</strong> The difficulty is that Data Types and Categorical/Ordinal/Nominal types are orthogonal concepts, thus mapping between them isn't straightforward. @Jeff's <a href="https://stackoverflow.com/a/29821799/1910555">answer</a> below specifies the precise manner to achieve the manual mapping.</p> | 29,803,290 | 22 | 1 | null | 2015-04-22 16:03:36.407 UTC | 19 | 2022-07-27 15:45:09.15 UTC | 2018-10-28 07:50:48.167 UTC | null | 1,910,555 | null | 1,910,555 | null | 1 | 58 | python|pandas | 131,538 | <p>You could use <code>df._get_numeric_data()</code> to get numeric columns and then find out categorical columns</p>
<pre><code>In [66]: cols = df.columns
In [67]: num_cols = df._get_numeric_data().columns
In [68]: num_cols
Out[68]: Index([u'0', u'1', u'2'], dtype='object')
In [69]: list(set(cols) - set(num_cols))
Out[69]: ['3', '4']
</code></pre> |
4,589,333 | Git ignore locally deleted folder | <p>I have a Ruby on Rails application which crashes when <code>vendor/rails</code> is present but works fine if it is not. I need to keep this folder deleted in my local copy so that I can work, but I don't want this deletion to ever be committed. Someone put it there for a reason.</p>
<p>So how do I delete this folder without it coming up in <code>git status</code> as a thousand deleted files? Obviously <code>.gitignore</code> won't work since you can't ignore files which are already tracked. Neither do any of the solutions listed <a href="https://stackoverflow.com/questions/2718372/git-ignore-deleted-files">here</a> (<code>git update-index --assume-unchanged</code>) work.</p> | 4,590,664 | 1 | 0 | null | 2011-01-03 23:23:13.977 UTC | 24 | 2018-03-21 12:13:17.343 UTC | 2017-05-23 10:30:09.167 UTC | null | -1 | null | 76,900 | null | 1 | 32 | git|ignore | 14,392 | <pre><code> git ls-files <strong>--deleted</strong> -z | <a href="http://www.kernel.org/pub/software/scm/git/docs/git-update-index.html" rel="noreferrer">git update-index</a> <strong>--assume-unchanged</strong> -z --stdin</code></pre>
<p>Note that because this is an index-based operation, you cannot set directories to be ignored – only individual files. If upstream ever adds a file inside those directories, you will have to repeat the fix-up.</p> |
39,469,264 | Fatal error: Uncaught Error: Call to undefined function ereg_replace() PHP 7 | <p>below code is giving me the fatal error in php 7</p>
<pre><code> $jquery_click_hook = ereg_replace("[^A-Za-z0-9]", "", strtolower($value['name']));
</code></pre>
<p>is there any way to make it compatible with php 7?</p> | 39,469,320 | 2 | 1 | null | 2016-09-13 11:46:45.847 UTC | 1 | 2016-09-13 11:58:41.68 UTC | 2016-09-13 11:58:41.68 UTC | null | 487,813 | user5247236 | null | null | 1 | 10 | php|php-7|ereg-replace | 60,521 | <p>Switch to <a href="http://php.net/preg_replace"><code>preg_replace</code><sup><em>Docs</em></sup></a> and update the expression to use preg syntax (PCRE) instead of ereg syntax (POSIX) <a href="http://php.net/reference.pcre.pattern.posix">where there are differences<sup><em>Docs</em></sup></a> (just as it says to do in the manual for <a href="http://php.net/ereg_replace"><code>ereg_replace</code><sup><em>Docs</em></sup></a>).</p>
<p>Your above code should be this way:</p>
<pre><code>$jquery_click_hook = preg_replace("[^A-Za-z0-9]", "", strtolower($value['name']));
</code></pre> |
26,657,319 | How do you set up encrypted mosquitto broker like a webpage which has https? | <p>I'm trying to setup a mosquitto broker which is encrypted using ssl/tls. I don't want to generate client certificates. I just want an encrypted connection. </p>
<p>The man page only described the settings which are available, not which are needed and how they are used.</p>
<p>Which settings are needed and how do you set them?</p>
<p>I use mosquitto 1.3.5</p> | 26,657,320 | 2 | 0 | null | 2014-10-30 15:39:11.223 UTC | 11 | 2016-08-15 04:31:04.42 UTC | null | null | null | null | 3,199,565 | null | 1 | 11 | ssl|encryption|certificate|mqtt|mosquitto | 28,913 | <p>There is a small guide here, but it does not say much: <a href="http://mosquitto.org/man/mosquitto-tls-7.html" rel="noreferrer">http://mosquitto.org/man/mosquitto-tls-7.html</a></p>
<p>You need to set these:
certfile
keyfile
cafile</p>
<p>They can be generated with the commands in the link above. But easier is to use this script: <a href="https://github.com/owntracks/tools/blob/master/TLS/generate-CA.sh" rel="noreferrer">https://github.com/owntracks/tools/blob/master/TLS/generate-CA.sh</a></p>
<p>After running the script and changing the config it could look something like this:</p>
<pre><code>listener 8883
cafile /etc/mosquitto/certs/ca.crt
certfile /etc/mosquitto/certs/hostname.localdomain.crt
keyfile /etc/mosquitto/certs/hostname.localdomain.key
</code></pre>
<p>If mosquitto says <code>Unable to load server key file</code> it means that the user which is running mosquitto does not have permission to read the file. Even if you start it as root the broker might start as another user, mosquitto for example. To solve this do e.g. <code>chown mosquitto:root keyfile</code></p>
<p>To connect to the broker the client will need the ca.crt-file. If you do not supply this the broker will say something like:</p>
<blockquote>
<p>OpenSSL Error: error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number</p>
</blockquote>
<p>To supply it to the mosquitto_sub command you use <code>--cafile pathToCaCrt</code>. The ca.crt can be distributed with the clients and it will make sure that the server it is connected to actually is the correct server.</p>
<p>The <code>--insecure</code> flag of mosquitto_sub does not make the client accept all certificates (like with wget or similar), it just allows that the certificate not to have the host you are connecting to in common name. So you should make sure your certificate has your broker host as common name.</p> |
6,702,856 | Close a running application from DOS command line | <p>The start command can launch an application like notepad in a batch file like this:</p>
<pre><code>start notepad
start "my love.mp3"
</code></pre>
<p>But how do I close the running application from the command line? I found <code>taskkill</code> in my searches but I don't think that is the right command because it's not working—it says no such file.</p>
<p>How do I close an application launched with <code>start</code>?</p> | 6,702,868 | 2 | 1 | null | 2011-07-15 04:59:33.21 UTC | 0 | 2015-07-17 16:09:34.697 UTC | 2011-07-15 18:43:13.943 UTC | null | 57,611 | null | 834,032 | null | 1 | 11 | command-line|batch-file|dos|kill-process|taskkill | 96,436 | <p>Taskkill is correct. But you must kill the process playing the file, not the file itself. Figuring out the registered handler for mp3 files from a command prompt will be a bit tricky.</p>
<p>If you know it then you can kill that process.</p>
<p>Here's a script that figures out the registered application for mp3 files and kills the task:</p>
<pre><code>@echo off
if not .%1==. goto show
:createtemp
set tempfile="%temp%\temp-%random%-%time:~6,5%.bat"
if exist %tempfile% goto :createtemp
reg query HKEY_CLASSES_ROOT\mp3file\shell\play\command\ > %tempfile%
for /F "skip=4 delims=> tokens=2 usebackq" %%e in (`type %tempfile%`) do call %0 %%e
del %tempfile% > nul
set tempfile=
set handler=
set teststring=
set offset=
set cmd=
goto end
:show
set handler=%2
set handler=%handler:~1,-1%
set /A offset=-1
:loop
set cmd=set teststring=%%handler:~%offset%%%
echo %cmd% > %tempfile%
call %tempfile%
if %teststring:~0,1%==\ goto complete
set /A offset=offset-1
goto loop
:complete
set /A offset=offset+1
set cmd=set handler=%%handler:~%offset%%%
echo %cmd% > %tempfile%
call %tempfile%
taskkill /IM %handler% > nul
:end
</code></pre>
<p>If you save this as <code>killmp3.bat</code> or something, you can call it when you want. Of course be aware that if the program was already running, doing something else, that it will be closed anyway.</p>
<p>Note that this depends heavily on the entry in the registry to have the executable path inside double quotes. If you don't have that and there are spaces in the executable name, it will fail.</p>
<p>You could generalize my technique to be able to pass in the file extension (such as <code>.mp3</code>, which you could look up in the registry to find the class name <code>mp3file</code> and then find the handler from there.</p>
<p>A more generic solution that takes the name of the file you started and figures out the extension from it is theoretically possible but a lot more difficult. In the case of <code>notepad</code> you have to figure out what that is by searching the path for all executable files, etc.</p>
<p>This might be simpler if you created an extremely short mp3 file that you could start. Depending on the program, it might stop playing the current file and switch to the new one, which would end almost instantly and effectively stop playback.</p> |
7,095,845 | When run bundle get invalid byte sequence in US-ASCII | <p>I'm trying to deploy my Rails 3.0 app. I use rvm and ruby 1.9.2 (p 180 or p 290 - no difference) on the FreeBSD production server. When I run bundle command, I get this exception on every :git gem (it seems that exception is raised only when I use edge versions with :git option in Gemfile):</p>
<pre><code>...
Installing has_scope (0.5.1)
Installing responders (0.6.4)
Using inherited_resources (1.2.2) from https://github.com/josevalim/inherited_resources.git (at master) /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:1915:in `gsub': invalid byte sequence in US-ASCII (ArgumentError)
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/specification.rb:1915:in `to_yaml'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/builder.rb:79:in `block (2 levels) in write_package'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/package/tar_output.rb:73:in `block (3 levels) in add_gem_contents'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/package/tar_writer.rb:83:in `new'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/package/tar_output.rb:67:in `block (2 levels) in add_gem_contents'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/package/tar_output.rb:65:in `wrap'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/package/tar_output.rb:65:in `block in add_gem_contents'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/package/tar_writer.rb:113:in `add_file'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/package/tar_output.rb:63:in `add_gem_contents'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/package/tar_output.rb:31:in `open'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/package.rb:44:in `open'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/builder.rb:78:in `block in write_package'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/open-uri.rb:35:in `open'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/open-uri.rb:35:in `open'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/builder.rb:77:in `write_package'
from /home/tmr/data/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/site_ruby/1.9.1/rubygems/builder.rb:39:in `build'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/source.rb:456:in `block in generate_bin'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/source.rb:456:in `chdir'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/source.rb:456:in `generate_bin'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/source.rb:565:in `install'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/installer.rb:58:in `block (2 levels) in run'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/rubygems_integration.rb:93:in `with_build_args'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/installer.rb:57:in `block in run'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/installer.rb:49:in `run'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/installer.rb:8:in `install'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/cli.rb:220:in `install'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/vendor/thor/task.rb:22:in `run'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/vendor/thor/invocation.rb:118:in `invoke_task'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/vendor/thor.rb:263:in `dispatch'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/lib/bundler/vendor/thor/base.rb:386:in `start'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/gems/bundler-1.0.18/bin/bundle:13:in `<top (required)>'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/bin/bundle:19:in `load'
from /home/tmr/data/.rvm/gems/ruby-1.9.2-p180/bin/bundle:19:in `<main>'
</code></pre>
<p>My gemfile:</p>
<pre><code>source 'http://rubygems.org'
group :production do
gem "unicorn"
end
gem 'rails', '3.0.10'
gem 'devise' #, :git=>'https://github.com/plataformatec/devise.git'
gem 'russian', :git => 'https://github.com/yaroslav/russian.git'
gem 'i18n'
gem 'cancan', :git=>'https://github.com/ryanb/cancan.git'
gem 'riddle', :git => 'git://github.com/freelancing-god/riddle.git'
gem 'thinking-sphinx', :git => 'https://github.com/freelancing-god/thinking-sphinx.git', :branch=>'rails3'
gem 'inherited_resources', :git=> 'https://github.com/josevalim/inherited_resources.git'
gem 'has_scope'
gem 'simple_form'
gem 'dynamic_form'
#gem "crummy", ">= 1.0.1"
gem "haml"
gem 'jquery-rails', '>= 0.2.6'
gem 'kaminari'
gem 'mysql2', '< 0.3'
gem "paperclip", "~> 2.3"
gem "whenever"
group :development do
gem 'haml-rails' #, :git=>"https://github.com/indirect/haml-rails.git"
gem "capistrano"
end
</code></pre>
<p>1.9 is horrible with it's encoding problems... could you help once again?</p> | 7,126,196 | 3 | 1 | null | 2011-08-17 15:56:31.523 UTC | 13 | 2021-07-05 10:05:26.37 UTC | 2011-08-17 16:28:40.44 UTC | null | 590,345 | null | 590,345 | null | 1 | 23 | ruby-on-rails-3|deployment|encoding|bundler | 11,274 | <pre><code>export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
</code></pre> |
7,187,302 | What is serialVersionUID in java, normally in exception class? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/285793/why-should-i-bother-about-serialversionuid">Why should I bother about serialVersionUID?</a> </p>
</blockquote>
<p>I am going through some exception handling code and i saw something named as serialVersionUID. What this uid is for?? Is it only limited to exception or can be used in all classes??? what is the advantage of this id???</p> | 7,187,455 | 3 | 6 | null | 2011-08-25 08:33:27.093 UTC | 5 | 2019-02-19 04:09:14.087 UTC | 2017-05-23 11:47:07.663 UTC | null | -1 | null | 789,214 | null | 1 | 41 | java|serialization|serialversionuid | 39,069 | <p><code>serialVersionUID</code> is a field to define the version of a particular class while <code>seriializing</code> & <code>deseriializing</code>.. consider a scenario where you have a class <code>Employee</code> which has 3 fields which has been in production for some time (meaning there may exist many serialized versions of employee objects), when you update the class to include (say a 4th field) then all the previous class (which are serialized) cannot be casted or de-serialized to the new one & you'll get an exception.</p>
<p>to avoid this issue, you can use the <code>serialVersionUID</code> field to tell <code>JVM</code> that the new class is in fact of a different version (by changing the <code>serialVersionUID</code>).</p>
<p><code>@Farmor</code> & <code>@Tom Jefferys</code> said pretty much the same thing, but with an example things look a lot simpler.</p> |
7,407,242 | How to cancel handler.postDelayed? | <p>What if I have <code>handler.postDelayed</code> thread already under execution and I need to cancel it?</p> | 7,407,417 | 3 | 3 | null | 2011-09-13 19:19:38.073 UTC | 10 | 2016-01-10 01:35:38.243 UTC | null | null | null | null | 397,991 | null | 1 | 78 | android | 44,553 | <p>I do this to cancel postDelays, per the Android: <a href="http://developer.android.com/reference/android/os/Handler.html#removeCallbacks%28java.lang.Runnable%29" rel="noreferrer">removeCallbacks</a> removes any pending posts of Runnable r that are in the message queue.</p>
<pre><code>handler.removeCallbacks(runnableRunner);
</code></pre>
<p>or use to remove all messages and callbacks</p>
<pre><code>handler.removeCallbacksAndMessages(null);
</code></pre> |
7,646,657 | Writing response body with BaseHTTPRequestHandler | <p>I'm playing a little with Python 3.2.2 and want to write a simple web server to access some data remotely. This data will be generated by Python so I don't want to use the SimpleHTTPRequestHandler as it's a file server, but a handler of my own.</p>
<p>I copied some example from the internet but I'm stuck because <strong>the response outputstream refuses to write the body content</strong>.</p>
<p>This is my code:</p>
<pre><code>import http.server
import socketserver
PORT = 8000
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_HEAD(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
print(self.wfile)
self.wfile.write("<html><head><title>Title goes here.</title></head>")
self.wfile.write("<body><p>This is a test.</p>")
# If someone went to "http://something.somewhere.net/foo/bar/",
# then s.path equals "/foo/bar/".
self.wfile.write("<p>You accessed path: %s</p>" % self.path)
self.wfile.write("</body></html>")
self.wfile.close()
try:
server = http.server.HTTPServer(('localhost', PORT), MyHandler)
print('Started http server')
server.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server')
server.socket.close()
</code></pre>
<p>What should be a correct code for writing the response body?</p>
<p>Thanks a lot.</p>
<p><strong>Edit:</strong></p>
<p>The error is:</p>
<pre><code>...
File "server.py", line 16, in do_GET
self.wfile.write("<html><head><title>Title goes here.</title></head>")
File "C:\Python32\lib\socket.py", line 297, in write
return self._sock.send(b)
TypeError: 'str' does not support the buffer interface
</code></pre> | 7,647,695 | 4 | 3 | null | 2011-10-04 10:43:04.957 UTC | 6 | 2020-04-14 00:45:28.93 UTC | 2011-10-04 11:43:14.647 UTC | null | 9,686 | null | 9,686 | null | 1 | 39 | python|basehttprequesthandler | 72,701 | <p>In Python3 string is a different type than that in Python 2.x. Cast it into bytes using either </p>
<pre><code>self.wfile.write(bytes("<html><head><title>Title goes here.</title></head>/html>","utf-8"))
</code></pre>
<p>or </p>
<pre><code>self.wfile.write("<html><head><title>Title goes here.</title></head></html>".encode("utf-8"))
</code></pre> |
23,969,619 | Plotting with seaborn using the matplotlib object-oriented interface | <p>I strongly prefer using <code>matplotlib</code> in OOP style:</p>
<pre><code>f, axarr = plt.subplots(2, sharex=True)
axarr[0].plot(...)
axarr[1].plot(...)
</code></pre>
<p>This makes it easier to keep track of multiple figures and subplots.</p>
<p>Question: How to use seaborn this way? Or, how to change <a href="http://www.stanford.edu/~mwaskom/software/seaborn/examples/anscombes_quartet.html">this example</a> to OOP style? How to tell <code>seaborn</code> plotting functions like <code>lmplot</code> which <code>Figure</code> or <code>Axes</code> it plots to?</p> | 23,973,562 | 1 | 1 | null | 2014-05-31 11:39:01.68 UTC | 64 | 2021-02-16 16:47:42.72 UTC | 2014-06-01 16:40:54.273 UTC | null | 1,533,576 | null | 2,925,169 | null | 1 | 123 | python|oop|matplotlib|seaborn | 99,713 | <p>It depends a bit on which seaborn function you are using.</p>
<p>The plotting functions in seaborn are broadly divided into two classes</p>
<ul>
<li>"Axes-level" functions, including <code>regplot</code>, <code>boxplot</code>, <code>kdeplot</code>, and many others</li>
<li>"Figure-level" functions, including <code>relplot</code>, <code>catplot</code>, <code>displot</code>, <code>pairplot</code>, <code>jointplot</code> and one or two others</li>
</ul>
<p>The first group is identified by taking an explicit <code>ax</code> argument and returning an <code>Axes</code> object. As this suggests, you can use them in an "object oriented" style by passing your <code>Axes</code> to them:</p>
<pre><code>f, (ax1, ax2) = plt.subplots(2)
sns.regplot(x, y, ax=ax1)
sns.kdeplot(x, ax=ax2)
</code></pre>
<p>Axes-level functions will only draw onto an <code>Axes</code> and won't otherwise mess with the figure, so they can coexist perfectly happily in an object-oriented matplotlib script.</p>
<p>The second group of functions (Figure-level) are distinguished by the fact that the resulting plot can potentially include several Axes which are always organized in a "meaningful" way. That means that the functions need to have total control over the figure, so it isn't possible to plot, say, an <code>lmplot</code> onto one that already exists. Calling the function always initializes a figure and sets it up for the specific plot it's drawing.</p>
<p>However, once you've called <code>lmplot</code>, it will return an object of the type <a href="http://stanford.edu/%7Emwaskom/software/seaborn/tutorial/axis_grids.html" rel="noreferrer"><code>FacetGrid</code></a>. This object has some methods for operating on the resulting plot that know a bit about the structure of the plot. It also exposes the underlying figure and array of axes at the <code>FacetGrid.fig</code> and <code>FacetGrid.axes</code> arguments. The <code>jointplot</code> function is very similar, but it uses a <a href="http://stanford.edu/%7Emwaskom/software/seaborn/tutorial/axis_grids.html#plotting-bivariate-data-with-jointgrid" rel="noreferrer"><code>JointGrid</code></a> object. So you can still use these functions in an object-oriented context, but all of your customization has to come after you've called the function.</p> |
24,005,974 | Cannot use mkdir in home directory: permission denied (Linux Lubuntu) | <p>I am trying to create a directory in my home directory on Linux using the mkdir command, but am getting a 'permission denied' error. I have recently installed Lubuntu on my laptop, and have the only user profile on the computer.</p>
<p>Here's what happened on my command line:</p>
<pre><code>jdub@Snowball:~$ cd /home
jdub@Snowball:/home$ mkdir bin
mkdir: cannot create directory ‘bin’: Permission denied
jdub@Snowball:/home$
</code></pre>
<p>How do I gain access to this folder? I am trying to write a script and following a tutorial here: <a href="http://linuxcommand.org/wss0010.php" rel="noreferrer">http://linuxcommand.org/wss0010.php</a></p>
<p>Thanks for your help!</p> | 24,006,189 | 3 | 1 | null | 2014-06-03 01:57:51.617 UTC | 8 | 2020-07-13 23:25:20.433 UTC | null | null | null | null | 3,701,355 | null | 1 | 25 | linux|bash | 230,883 | <p>As @kirbyfan64sos notes in a comment, <strong><code>/home</code> is NOT your home directory</strong> (a.k.a. home folder):</p>
<p>The fact that <code>/home</code> is an <em>absolute, literal</em> path that <em>has no user-specific component</em> provides a clue.</p>
<p>While <code>/home</code> happens to be the <em>parent</em> directory of <em>all</em> user-specific home directories on Linux-based systems, you shouldn't even rely on that, given that this differs across platforms: for instance, the equivalent directory on macOS is <code>/Users</code>.</p>
<p>What <strong>all Unix platforms DO have in common</strong> are the following ways to navigate to / refer to your home directory:</p>
<ul>
<li><strong>Using <code>cd</code> with NO argument</strong> <em>changes to</em> your home dir., i.e., makes your home dir. the <em>working directory</em>.
<ul>
<li>e.g.: <code>cd # changes to home dir; e.g., '/home/jdoe'</code></li>
</ul>
</li>
</ul>
<ul>
<li><strong><em>Unquoted</em> <code>~</code> by itself / <em>unquoted</em> <code>~/</code> at the start of a path string</strong> represents your home dir. / a path starting at your home dir.; this is referred to as <em>tilde expansion</em> (see <code>man bash</code>)
<ul>
<li>e.g.: <code>echo ~ # outputs, e.g., '/home/jdoe'</code></li>
</ul>
</li>
</ul>
<ul>
<li><strong><code>$HOME</code> - as part of either unquoted or preferably a <em>double-quoted</em> string - refers to your home dir.</strong> <code>HOME</code> is a predefined, user-specific <em>environment variable</em>:
<ul>
<li>e.g.: <code>cd "$HOME/tmp" # changes to your personal folder for temp. files</code></li>
</ul>
</li>
</ul>
<hr />
<p>Thus, to create the desired folder, you could use:</p>
<pre><code>mkdir "$HOME/bin" # same as: mkdir ~/bin
</code></pre>
<p>Note that most locations <em>outside</em> your home dir. require <em>superuser</em> (root user) privileges in order to create files or directories - that's why you ran into the <code>Permission denied</code> error.</p> |
21,635,870 | How to zoom out a div using animations? | <p>I have a DIV that is covering the whole page (height and width are 100%). I am trying to use CSS (and possibly JavaScript) to create a zoom out animation effect so the DIV is smaller (making everything inside the div - its children - smaller as well) to a specific point on the page (middle of the page) and to a specific <code>width</code> and <code>height</code> (let's say 100 * 100px for example).</p>
<p>I am starting with the following code:</p>
<pre><code><div id="toBeZoomedOut">
<div>something</div>
<div><img src="background.jpg"></div>
</div>
#toBeZoomedOut {
background-color: black;
border: 1px solid #AAAAAA;
color: white;
width: 300px;
height: 300px;
margin-left: auto;
margin-right: auto;
-webkit-transition: 1s ease-in-out;
-moz-transition: 1s ease-in-out;
transition: 1s ease-in-out;
}
#toBeZoomedOut img {
height: 250px;
width: 250px;
}
#toBeZoomedOut:hover {
zoom: 0.5;
}
</code></pre>
<p>The issue with this code is that it zooms out on component down (the parent div) and immediately zooms out what's inside it then goes back to zoom in the components. </p>
<p>Basically it is a little buggy. Any helpful fixes to make it zoom out everything together? It would be great if I can zoom out everything together to a specific location on the page and to a specific width/height (for example, zoom everything out to left: 100px, top: 100px and the parent div should be: 100px * 100px and everything else is relative in size).</p>
<p>I understand this might be easier with JavaScript? Any help?</p>
<p>One final note, if you notice the animation is not really reflecting a zoom animation. Although this would be an additional plus, the actual zoom animation would be great.</p>
<p>JSFiddle link to make it easier: <a href="http://jsfiddle.net/HU46s/" rel="nofollow noreferrer">http://jsfiddle.net/HU46s/</a></p> | 21,636,147 | 2 | 3 | null | 2014-02-07 19:08:40.79 UTC | 1 | 2018-09-05 18:51:45.78 UTC | 2018-09-05 18:51:45.78 UTC | null | 2,756,409 | null | 220,755 | null | 1 | 8 | javascript|jquery|html|css | 44,086 | <p>I am using the universal selector to target everything inside of the parent container to have the css transitions applied to it.</p>
<p>The next thing I did was changed the inside contents width to a <code>%</code> for ease of scaling.</p>
<p>Here is the css:</p>
<pre><code>#toBeZoomedOut * {
-webkit-transition: all 1s ease;
-moz-transition: 1s ease;
transition: 1s ease;
}
</code></pre>
<p>Finally, a fiddle: <a href="http://jsfiddle.net/HU46s/2/" rel="noreferrer">Demo</a></p> |
2,015,451 | Domain queries in CQRS | <p>We are trying out <a href="http://codebetter.com/blogs/gregyoung/archive/2009/08/13/command-query-separation.aspx" rel="noreferrer">CQRS</a>. We have a validation situation where a CustomerService (domain service) needs to know whether or not a Customer exists. Customers are unique by their email address. Our Customer repository (a generic repository) only has Get(id) and Add(customer). How should the CustomerService find out if the Customer exists?</p> | 2,017,029 | 4 | 0 | null | 2010-01-06 19:06:34.25 UTC | 25 | 2017-11-08 10:20:51.023 UTC | null | null | null | null | 32,855 | null | 1 | 26 | domain-driven-design|cqrs | 9,902 | <p>Take a look at this blog post: <a href="http://web.archive.org/web/20120111165641/http://bjarte.com/post/224749430/set-based-validation-in-the-cqrs-architecture" rel="noreferrer">Set based validation in the CQRS Architecture</a>.</p>
<p>It addresses this very issue. It's a complex issue to deal with in CQRS. What Bjarte is suggesting is to query the reporting database for existing Customer e-mail addresses and issue a Compensating Command (such as <code>CustomerEmailAddressIsNotUniqueCompensatingCommand</code>) back to the Domain Model if an e-mail address was found. You can then fire off appropriate events, which may include an <code>UndoCustomerCreationEvent</code>.</p>
<p>Read through the comments on the above blog post for alternative ideas.</p>
<p><a href="http://www.dymitruk.com/" rel="noreferrer">Adam D.</a> suggests in a comment that validation is a domain concern. As a result, you can store ReservedEmailAddresses in a service that facilitates customer creation and is hydrated by events in your event store.</p>
<p>I'm not sure there's an easy solution to this problem that feels completely clean. Let me know what you come up with!</p>
<p>Good luck!</p> |
10,411,650 | How to shutdown an Android mobile programmatically? | <p>Is it possible to shutdown the mobile programmatically.
that is with out using su commands..</p> | 10,411,681 | 7 | 2 | null | 2012-05-02 10:09:19.99 UTC | 5 | 2022-08-25 14:22:52.207 UTC | 2019-01-22 08:02:38.813 UTC | null | 1,033,581 | null | 1,271,445 | null | 1 | 7 | android | 40,903 | <p>You could possibly use the PowerManager to make it reboot (this does not guarantee that it'll reboot - OS may cancel it):</p>
<p><a href="http://developer.android.com/reference/android/os/PowerManager.html#reboot(java.lang.String" rel="nofollow">http://developer.android.com/reference/android/os/PowerManager.html#reboot(java.lang.String</a>)</p>
<p>It requires the REBOOT permission:</p>
<p><a href="http://developer.android.com/reference/android/Manifest.permission.html#REBOOT" rel="nofollow">http://developer.android.com/reference/android/Manifest.permission.html#REBOOT</a></p>
<p>Can you also check your logcat when trying to enable/disable keyguard, and post what's there?</p>
<p>You cannot do this from an ordinary SDK application. Only applications signed with the system firmware signing key can do this</p> |
10,660,260 | What are my options to check for viruses on a PHP upload? | <p>I am looking to see how I can go about checking if an uploaded file has a virus or not via PHP. What options exist, pros and cons of each, etc.</p> | 10,660,335 | 2 | 2 | null | 2012-05-18 22:02:15.933 UTC | 10 | 2022-04-06 15:15:29.073 UTC | 2015-07-03 21:53:20.433 UTC | null | 472,495 | null | 1,361,948 | null | 1 | 20 | php|file-upload|antivirus|virus | 33,146 | <p><a href="http://clamav.net" rel="noreferrer">ClamAV</a> is a free anti virus commonly used on server applications.</p>
<p><a href="http://sourceforge.net/projects/php-clamav/" rel="noreferrer">php-clamav</a> is an extension for binding ClamAV to PHP. You can check their <a href="http://php-clamav.sourceforge.net/" rel="noreferrer">documentation</a>.</p>
<p>I've found a <a href="http://phpmaster.com/zf-clamav/" rel="noreferrer">tutorial on how to use clamav as a Zend Framework Validator</a> which already includes instructions on how to verify upload files. The tutorial should also help you on using it on another frameworks or architectures.</p>
<p>You can also call clamav by its command line interface with <code>clamscan</code>. This requires clamav to be installed but not the PHP extension. In the PHP side, you can <code>shell_exec('clamscan myuploadedfile.zip');</code> then parse the output. Lines ending with <code>OK</code> are safe files, lines ending with <code>FOUND</code> are malicious files.</p> |
10,860,745 | php - working with dates like "every other week on tuesday" | <p>I have a web scheduling app that I'm currently rewriting and have some questions about how to work with recurring appointments (I know there is no shortage of "what's the best way to do this" when it comes to recurring appts).</p>
<p>So I want to offer recurring appointments where the user can schedule an appointment for a date like <strong><em>Sat, June 2nd</em></strong>, and it should repeat every other week on Saturday for some pre-determined time period (like 1 year).</p>
<p>What php functions can help me determine which date "every other saturday" falls on? I'm attaching a picture of my UI for clarification.</p>
<p><img src="https://i.stack.imgur.com/oejYj.png" alt="enter image description here"></p> | 10,861,039 | 3 | 3 | null | 2012-06-02 07:57:24.667 UTC | 9 | 2012-06-02 09:32:43.283 UTC | 2012-06-02 08:06:02.963 UTC | null | 472,700 | null | 472,700 | null | 1 | 6 | php|date|recurring-events | 8,950 | <p>Personally I'd look to work with <a href="http://www.php.net/manual/en/class.datetime.php" rel="noreferrer">DateTime</a> objects and use the <a href="http://www.php.net/manual/en/class.dateinterval.php" rel="noreferrer">DateInterval</a> class.</p>
<p>In your above case, you need to work out the date of the first/next saturday, then just work with a P2W date interval</p>
<p><strong>Basic example</strong></p>
<pre><code>$dow = 'saturday';
$step = 2;
$unit = 'W';
$start = new DateTime('2012-06-02');
$end = clone $start;
$start->modify($dow); // Move to first occurence
$end->add(new DateInterval('P1Y')); // Move to 1 year from start
$interval = new DateInterval("P{$step}{$unit}");
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
echo $date->format('D, d M Y'), PHP_EOL;
}
/*
Sat, 02 Jun 2012
Sat, 16 Jun 2012
Sat, 30 Jun 2012
Sat, 14 Jul 2012
…
Sat, 20 Apr 2013
Sat, 04 May 2013
Sat, 18 May 2013
Sat, 01 Jun 2013
*/
</code></pre> |
26,057,995 | Changing default welcome-page for spring-boot application deployed as a war | <p>I was trying to find a way to change the default welcome-page for a spring-boot application that is being deployed as a war in production but I can't find a way to do it without a web.xml file.</p>
<p>According to the documentation we can do it using the EmbeddedServletContainerFactory with this code:</p>
<pre><code>@Bean
public EmbeddedServletContainerFactory servletContainer() {
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
TomcatContextCustomizer contextCustomizer = new TomcatContextCustomizer() {
@Override
public void customize(Context context) {
context.addWelcomeFile("/<new welcome file>");
}
};
factory.addContextCustomizers(contextCustomizer);
return factory;
}
</code></pre>
<p>Although, as we're creating a war file and deploying it to tomcat and not using the Embedded Tomcat, this isn't doing anything.</p>
<p>Any idea? If we really need to add a web.xml file, how can we do it and still using spring boot? Should we specify the Application bean(with the main method) as the application context for DispatcherServlet? The documentation isn't very clear about that.</p>
<blockquote>
<p>Older Servlet containers don’t have support for the ServletContextInitializer bootstrap process used in Servlet 3.0. You can still use Spring and Spring Boot in these containers but you are going to need to add a web.xml to your application and configure it to load an ApplicationContext via a DispatcherServlet.</p>
</blockquote>
<p>Thanks in advance!</p>
<p>Pedro</p> | 29,054,676 | 4 | 1 | null | 2014-09-26 10:59:26.237 UTC | 8 | 2019-02-14 19:30:32.37 UTC | null | null | null | null | 2,785,655 | null | 1 | 22 | spring|tomcat7|spring-boot | 44,365 | <p>It's not too hard to do... you just need to forward the default mapping... </p>
<pre><code>@Configuration
public class DefaultView extends WebMvcConfigurerAdapter{
@Override
public void addViewControllers( ViewControllerRegistry registry ) {
registry.addViewController( "/" ).setViewName( "forward:/yourpage.html" );
registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
super.addViewControllers( registry );
}
}
</code></pre> |
7,059,299 | How to properly convert an unsigned char array into an uint32_t | <p>So, I'm trying to convert an array of <code>unsigned char</code>s into an <code>uint32_t</code>, but keep getting different results each time:</p>
<pre><code>unsigned char buffer[] = {0x80, 0x00, 0x00, 0x00};;
uint32_t num = (uint32_t*)&buffer;
</code></pre>
<p>Now, I keep getting this warning: </p>
<blockquote>
<p>warning: initialization makes integer from pointer without a cast</p>
</blockquote>
<p>When I change <code>num</code> to <code>*num</code> i don't get that warning, but that's not actually the real problem (<strong>UPDATE:</strong> well, those might be related now that I think of it.), because <em>every time I run the code there is different results</em>. Secondly the <code>num</code>, once it's cast properly, should be <code>128</code>, but If I need to change the endianness of the buffer I could manage to do that myself, <em>I think</em>.</p>
<p>Thanks!</p> | 7,059,314 | 6 | 1 | null | 2011-08-14 19:51:41.503 UTC | 0 | 2020-07-29 17:26:46.577 UTC | null | null | null | null | 2,133,758 | null | 1 | 13 | c|casting | 43,024 | <p>Did you try this ?</p>
<pre><code>num = (uint32_t)buffer[0] << 24 |
(uint32_t)buffer[1] << 16 |
(uint32_t)buffer[2] << 8 |
(uint32_t)buffer[3];
</code></pre>
<p>This way you control endianness and whatnot.</p>
<p>It's really not safe to cast a <code>char</code> pointer and interpret it as anything bigger. Some machines expect pointers to integers to be aligned.</p> |
7,461,080 | Fastest way to check if string contains only digits in C# | <p>I know a few ways of how to check if a string contains only digits:<br />
RegEx, <code>int.parse</code>, <code>tryparse</code>, looping, etc.</p>
<p>Can anyone tell me what the <em>fastest</em> way to check is?</p>
<p>I need only to <strong>CHECK</strong> the value, no need to actually parse it.</p>
<p>By "digit" I mean specifically ASCII digits: <code>0 1 2 3 4 5 6 7 8 9</code>.</p>
<p>This is not the same question as <a href="https://stackoverflow.com/questions/894263/how-do-i-identify-if-a-string-is-a-number">Identify if a string is a number</a>, since this question is not only about how to identify, but also about what the <strong>fastest</strong> method for doing so is.</p> | 7,461,095 | 20 | 7 | null | 2011-09-18 11:10:50.24 UTC | 29 | 2022-07-06 08:31:28.053 UTC | 2021-12-21 15:09:51.367 UTC | null | 11,047,824 | null | 846,351 | null | 1 | 224 | c#|string|performance | 286,653 | <pre><code>bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
</code></pre>
<p>Will probably be the fastest way to do it.</p> |
14,116,569 | Force Div below another and prevent overlap | <p>I have two Div elements. The first should be 100% height and width of the screen. I would like the second Div to be 100% width but variable height depending on the contents and to start inline (below the first). So the full screen is Div 1 and you have to scroll down to see Div 2. But everything I have tried they overlap.</p>
<pre><code><div style="background-color:red;height:100%;width:100%;left:0px;top:0px"></div>
<br/>
<div style="width:100%;position:relative;background-color:yellow">
<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>test<br/>..
</div>
</code></pre>
<p>
<a href="http://jsfiddle.net/FBJ8h/" rel="noreferrer">http://jsfiddle.net/FBJ8h/</a></p> | 14,116,617 | 3 | 0 | null | 2013-01-02 03:31:38.377 UTC | 1 | 2017-12-31 05:07:00.573 UTC | null | null | null | user759885 | null | null | 1 | 10 | css|layout|html | 50,639 | <p>Becasue</p>
<pre class="lang-css prettyprint-override"><code>position:absolute
</code></pre>
<p>makes the div non-occupy, which means other elements don't "see" them when aligning and positioning.</p>
<p>Use this:</p>
<pre class="lang-css prettyprint-override"><code>html,body {
height:100%;
}
div.div2 {
top:100%;
}
</code></pre>
<p><a href="http://jsfiddle.net/FBJ8h/1/">JSFiddle</a></p> |
13,892,638 | Extracting the relationship between entities in Stanford CoreNLP | <p>I want to extract the complete relationship between two entities using Stanford CoreNLP (or maybe other tools).</p>
<p>For example:</p>
<blockquote>
<p>Windows is <em>more popular than</em> Linux.</p>
<p>This tool <em>requires</em> Java.</p>
<p>Football is <em>the most popular game in</em> the World.</p>
</blockquote>
<p>What is the fastest way? And what is the best practice for that?</p>
<p>Thanks in advance</p> | 13,924,721 | 4 | 1 | null | 2012-12-15 13:30:52.62 UTC | 9 | 2016-11-25 10:11:22.82 UTC | 2012-12-15 13:36:21.337 UTC | null | 905,902 | null | 1,240,492 | null | 1 | 13 | nlp|stanford-nlp | 8,047 | <p>You are probably looking for dependency relations between nouns. Stanford Parser provides such output. Have a look <a href="http://nlp.stanford.edu/software/stanford-dependencies.shtml" rel="noreferrer">here</a>. You can combine what Pete said (i.e. the POS graph) with the dependency graph to identify what relationship (for example, direct object or nominal subject, etc.) a pair of nouns (or noun phrases) share.</p> |
13,805,188 | Switch button - disable swipe function | <p>I have a <code>switch</code> button (actually is a custom one) and I want to disable the swipe functionality for some reason; I want the user to be able to click it only. Is there a way to achieve this?
Thanks.</p> | 17,199,262 | 8 | 2 | null | 2012-12-10 16:39:30.08 UTC | 4 | 2022-07-28 08:10:31.35 UTC | null | null | null | null | 500,096 | null | 1 | 29 | android | 51,542 | <p>You can setClickable(false) to your Switch, then listen for the onClick() event within the Switch's parent and toggle it programmatically. The switch will still appear to be enabled but the swipe animation won't happen.</p>
<p>...</p>
<p>[In onCreate()]</p>
<pre><code>Switch switchInternet = (Switch) findViewById(R.id.switch_internet);
switchInternet.setClickable(false);
</code></pre>
<p>...</p>
<p>[click listener]</p>
<pre><code>public void ParentLayoutClicked(View v){
Switch switchInternet = (Switch) findViewById(R.id.switch_internet);
if (switchInternet.isChecked()) {
switchInternet.setChecked(false);
} else {
switchInternet.setChecked(true);
}
}
</code></pre>
<p>...</p>
<p>[layout.xml]</p>
<pre><code> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="ParentLayoutClicked"
android:focusable="false"
android:orientation="horizontal" >
<Switch
android:layout_marginTop="5dip"
android:layout_marginBottom="5dip"
android:id="@+id/switch_internet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="NOT CONNECTED"
android:textOn="CONNECTED"
android:focusable="false"
android:layout_alignParentRight="true"
android:text="@string/s_internet_status" />
</RelativeLayout>
</code></pre> |
9,338,122 | Action items from Viewpager initial fragment not being displayed | <p>In the application I am developing I am using a ViewPager with fragments and each fragment constructs its own menu independently of all of the other fragments in the ViewPager.</p>
<p>The issue is that sometimes the fragments that are initialised by the ViewPager by default (i.e in it's initial state) are not having their items populated into the action items menu. What's worse is that this issue only occurs intermittently. If I swipe through the ViewPager enough so that the fragments are forced to re-initialise them selves, when I swipe back, the menu populates correctly.</p>
<p>Activity code:</p>
<pre><code>package net.solarnz.apps.fragmentsample;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.v13.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
public class FragmentSampleActivity extends Activity {
private ViewPagerAdapter mViewPagerAdapter;
private ViewPager mViewPager;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (mViewPagerAdapter == null) {
mViewPagerAdapter = new ViewPagerAdapter(getFragmentManager());
}
mViewPager = (ViewPager) findViewById(R.id.log_pager);
mViewPager.setAdapter(mViewPagerAdapter);
mViewPager.setCurrentItem(0);
}
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return 8;
}
@Override
public Fragment getItem(int position) {
Fragment f = Fragment1.newInstance(position);
// f.setRetainInstance(true);
f.setHasOptionsMenu(true);
return f;
}
}
}
</code></pre>
<p>Fragment code:</p>
<pre><code>package net.solarnz.apps.fragmentsample;
import android.app.Fragment;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
public class Fragment1 extends Fragment {
int mNum;
static Fragment newInstance(int num) {
Fragment1 f = new Fragment1();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mNum = getArguments() != null ? getArguments().getInt("num") : 0;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_list, menu);
}
}
</code></pre>
<p>Layout:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<android.support.v4.view.ViewPager
android:id="@+id/log_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</code></pre>
<p>Menu:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_refresh"
android:title="Refresh"
android:icon="@android:drawable/ic_delete"
android:showAsAction="ifRoom|withText" />
</menu>
</code></pre>
<p>Action menu being populated:
<a href="https://i.stack.imgur.com/QFMDd.png" rel="noreferrer">http://i.stack.imgur.com/QFMDd.png</a></p>
<p>Action menu not being populated:
<a href="https://i.stack.imgur.com/sH5Pp.png" rel="noreferrer">http://i.stack.imgur.com/sH5Pp.png</a></p> | 12,048,173 | 8 | 1 | null | 2012-02-18 03:01:23.88 UTC | 16 | 2020-12-29 23:50:50.22 UTC | null | null | null | null | 181,358 | null | 1 | 32 | android|android-fragments|android-actionbar|android-viewpager | 14,268 | <p><strong>You should read this (by xcolw...)</strong></p>
<p>Through experimentation it seems like the root cause is invalidateOptionsMenu getting called more than one without a break on the main thread to process queued up jobs. A guess - this would matter if some critical part of menu creation was deferred via a post, leaving the action bar in a bad state until it runs. </p>
<p>There are a few spots this can happen that aren't obvious:</p>
<ol>
<li><p>calling viewPager.setCurrentItem multiple times for the same item</p></li>
<li><p>calling viewPager.setCurrentItem in onCreate of the activity. setCurrentItem causes an option menu invalidate, which is immediately followed by the activity's option menu invalidate</p></li>
</ol>
<p>Workarounds I've found for each</p>
<ol>
<li><p>Guard the call to viewPager.setCurrentItem</p>
<pre><code>if (viewPager.getCurrentItem() != position)
viewPager.setCurrentItem(position);
</code></pre></li>
<li><p>Defer the call to viewPager.setCurrentItem in onCreate</p>
<pre><code>public void onCreate(...) {
...
view.post(new Runnable() {
public void run() {
// guarded viewPager.setCurrentItem
}
}
}
</code></pre></li>
</ol>
<p>After these changes options menu inside the view pager seems to work as expected. I hope someone can shed more light into this.</p>
<p><em>source</em> <a href="http://code.google.com/p/android/issues/detail?id=29472" rel="noreferrer">http://code.google.com/p/android/issues/detail?id=29472</a></p> |
32,689,686 | Overlapping CSS flexbox items in Safari | <p>What's the correct CSS to force Safari to not overlap flex items within a default flex container?</p>
<p>Safari seems to give too much width to flex items with lots of content.</p>
<p><strong>Safari:</strong> (v8.0.8 on Mac OS X 10.10.5 Yosemite)<br>
<a href="https://i.stack.imgur.com/6oBeN.png"><img src="https://i.stack.imgur.com/6oBeN.png" alt="flex-items-safari.png"></a></p>
<p>The flex items display fine in Chrome and Firefox.</p>
<p><strong>Chrome:</strong><br>
<a href="https://i.stack.imgur.com/TiDCv.png"><img src="https://i.stack.imgur.com/TiDCv.png" alt="enter image description here"></a></p>
<p><br>
<strong>CSS:</strong></p>
<pre><code>main {
display: flex;
border: 3px solid silver;
}
main >div {
background-color: plum;
margin: 10px;
}
</code></pre>
<p><br>
<strong>HTML:</strong></p>
<pre><code><main>
<div>
Doh!!!!!!!!!!!
</div>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam.
</div>
</main>
</code></pre>
<p>Fiddle with the code:<br>
<a href="http://jsfiddle.net/LL05grus/6">http://jsfiddle.net/LL05grus/6</a></p> | 32,695,233 | 3 | 3 | null | 2015-09-21 07:34:10.28 UTC | 10 | 2021-01-14 10:55:01.387 UTC | 2016-05-26 21:56:05.19 UTC | null | 1,553,812 | null | 1,553,812 | null | 1 | 47 | html|css|safari|flexbox | 18,841 | <p>The element is shrinking. You need to set the <code>flex-shrink</code> property to <code>0</code> on the shrinking element.</p>
<pre><code>main >div:first-child {
-webkit-flex: 0;
flex-shrink: 0;
}
</code></pre> |
19,682,818 | Collections.sort() using comparator? | <pre><code>import java.util.*;
public class C_2 {
public static void main(String args[]) {
String theStrings[] = { "x", "a", "b", "c", "d" };
List l = Arrays.asList(theStrings);
Collections.sort(l); // line a
Collections.sort(l, new ThisIsMyThing()); // line b
System.out.println(l);
}
}
class ThisIsMyThing implements Comparator {
public int compare(Object o1, Object o2) {
String s1 = (String)o1;
String s2 = (String)o2;
return -1 * s1.compareTo(s2);
}
}
</code></pre>
<p>I understand that class <code>C_2</code> does sorting based on two different techniques.
One is the standard <code>Collections.sort(l);</code>
And the other is <code>Collections.sort(l,Comparator<>());</code> I am not able to understand this sort method. Can someone please explain it to me?</p> | 19,683,102 | 3 | 3 | null | 2013-10-30 12:54:49.46 UTC | 1 | 2014-12-16 14:08:09.33 UTC | 2013-10-30 12:58:32.443 UTC | null | 684,368 | null | 2,909,299 | null | 1 | 5 | java|collections|comparator | 44,122 | <p><code>Collection.sort(l)</code> assumes that the contents of <code>l</code> are <code>Comparable</code>. <code>Collection.sort(1, Comparator)</code> uses a custom comparator to compare the contents of <code>l</code>, this is what you did. The very idea of sorting (including the <code>sort()</code> method) implies the objects MUST be comparable - in this case, with either <code>Comparable</code> or <code>Comparator</code>.</p>
<p>Note that many Java objects are comparable already, including <code>String</code>, <code>Date</code> and <code>Number</code>. For those, you can just use <code>Collection.sort(someList);</code></p>
<p><b>Example</b></p>
<p>Say you have a <code>Circle</code> class</p>
<pre><code>public class Circle {
double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea(){
return radius * radius * Math.PI;
}
}
</code></pre>
<p>If you created 100 <code>Circle</code> objects:</p>
<pre><code>ArrayList<Circle> circleList = new ArrayList<>();
for (int i = 0; i < 100; i++) {
// adds a circle with random radius
circleList.add(new Circle((int)(Math.random() * 100)));
}
// try to sort the list
Collections.sort(circleList); //compilation error: must be Comparable
</code></pre>
<p>You can't sort them because Java has no idea how to compare them. You have to tell this to Java:</p>
<pre><code>public class Circle implements Comparable<Circle> {
double radius;
public Circle(double radius) {
this.radius = radius;
}
// you MUST override the compareTo method from the Comparable interface
@Override
public int compareTo(Circle cirlce){
if (this.getArea() > circle.getArea())
return 1;
else if (this.getArea() == circle.getArea())
return 0;
else
return -1;
}
public double getArea(){
return radius * radius * Math.PI;
}
}
</code></pre>
<p>With the <code>compareTo()</code> method in the Circle class, Java now knows how to compare them and can sort them.</p>
<p>Now you can do this:</p>
<pre><code>Collections.sort(circleList);
// Yayyy I'm being sorted by the size of my areas!!!!!
</code></pre> |
34,007,632 | How to remove a column in a numpy array? | <p>Imagine we have a 5x4 matrix.
We need to remove only the first dimension.
How can we do it with <strong>numpy</strong>? </p>
<pre><code>array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.],
[ 12., 13., 14., 15.],
[ 16., 17., 18., 19.]], dtype=float32)
</code></pre>
<p>I tried:</p>
<pre><code>arr = np.arange(20, dtype=np.float32)
matrix = arr.reshape(5, 4)
new_arr = numpy.delete(matrix, matrix[:,0])
trimmed_matrix = new_arr.reshape(5, 3)
</code></pre>
<p>It looks a bit clunky.
Am I doing it correctly?
If yes, is there a cleaner way to remove the dimension without reshaping? </p> | 34,008,274 | 3 | 3 | null | 2015-11-30 20:42:46.503 UTC | 5 | 2015-12-01 18:54:00.547 UTC | 2015-11-30 20:52:28.44 UTC | null | 2,588,210 | null | 1,984,680 | null | 1 | 18 | python|arrays|numpy | 76,163 | <p>If you want to remove a column from a 2D Numpy array you can specify the columns like this </p>
<p>to keep all rows and to get rid of column 0 (or start at column 1 through the end)</p>
<pre><code>a[:,1:]
</code></pre>
<p>another way you can specify the columns you want to keep ( and change the order if you wish)
This keeps all rows and only uses columns 0,2,3</p>
<pre><code>a[:,[0,2,3]]
</code></pre>
<p>The documentation on this can be found <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html" rel="noreferrer">here</a></p>
<p>And if you want something which specifically removes columns you can do something like this:</p>
<pre><code>idxs = list.range(4)
idxs.pop(2) #this removes elements from the list
a[:, idxs]
</code></pre>
<p>and @hpaulj brought up numpy.delete()</p>
<p>This would be how to return a view of 'a' with 2 columns removed (0 and 2) along axis=1.</p>
<pre><code>np.delete(a,[0,2],1)
</code></pre>
<p>This doesn't actually remove the items from 'a', it's return value is a new numpy array.</p> |
24,797,857 | Java - Filtering List Entries by Regex | <p>My code looks like this:</p>
<pre><code>List<String> filterList(List<String> list, String regex) {
List<String> result = new ArrayList<String>();
for (String entry : list) {
if (entry.matches(regex)) {
result.add(entry);
}
}
return result;
}
</code></pre>
<p>It returns a list that contains only those entries that match the <code>regex</code>.
I was wondering if there was a built in function for this along the lines of:</p>
<pre><code>List<String> filterList(List<String> list, String regex) {
List<String> result = new ArrayList<String>();
result.addAll(list, regex);
return result;
}
</code></pre> | 31,888,916 | 3 | 2 | null | 2014-07-17 07:55:00.72 UTC | 7 | 2019-01-14 10:58:58.137 UTC | null | null | null | null | 919,578 | null | 1 | 19 | java|regex|collections | 44,266 | <p>In addition to the answer from Konstantin: Java 8 added <code>Predicate</code> support to the <code>Pattern</code> class via <code>asPredicate</code>, which calls <code>Matcher.find()</code> internally:</p>
<pre><code>Pattern pattern = Pattern.compile("...");
List<String> matching = list.stream()
.filter(pattern.asPredicate())
.collect(Collectors.toList());
</code></pre>
<p>Pretty awesome!</p> |
44,911,251 | How to create an RXjs RetryWhen with delay and limit on tries | <p>I am trying to make an API call (using angular4), which retries when it fails, using retryWhen.
I want it to delay for 500 ms and retry again. This can be achieved with this code:</p>
<pre><code>loadSomething(): Observable<SomeInterface> {
return this.http.get(this.someEndpoint, commonHttpHeaders())
.retryWhen(errors => errors.delay(500));
}
</code></pre>
<p>But this will keep trying forever. How do I limit it to, let's say 10 times?</p>
<p>Thank you!</p> | 44,911,567 | 2 | 1 | null | 2017-07-04 17:12:28.483 UTC | 13 | 2020-10-20 18:11:29.233 UTC | 2018-06-10 10:01:55.963 UTC | null | 3,100,587 | null | 2,044,706 | null | 1 | 31 | angular|rxjs|observable | 21,358 | <p>You need to apply the limit to the retry signal, for instance if you only wanted 10 retries:</p>
<pre class="lang-js prettyprint-override"><code>loadSomething(): Observable<SomeInterface> {
return this.http.get(this.someEndpoint, commonHttpHeaders())
.retryWhen(errors =>
// Time shift the retry
errors.delay(500)
// Only take 10 items
.take(10)
// Throw an exception to signal that the error needs to be propagated
.concat(Rx.Observable.throw(new Error('Retry limit exceeded!'))
);
</code></pre>
<p><strong>EDIT</strong></p>
<p>Some of the commenters asked how to make sure that the last error is the one that gets thrown. The answer is a bit less clean but no less powerful, just use one of the flattening map operators (concatMap, mergeMap, switchMap) to check which index you are at.</p>
<p>Note: Using the new RxJS 6 <code>pipe</code> syntax for future proofing (this is also available in later versions of RxJS 5).</p>
<pre class="lang-js prettyprint-override"><code>loadSomething(): Observable<SomeInterface> {
const retryPipeline =
// Still using retryWhen to handle errors
retryWhen(errors => errors.pipe(
// Use concat map to keep the errors in order and make sure they
// aren't executed in parallel
concatMap((e, i) =>
// Executes a conditional Observable depending on the result
// of the first argument
iif(
() => i > 10,
// If the condition is true we throw the error (the last error)
throwError(e),
// Otherwise we pipe this back into our stream and delay the retry
of(e).pipe(delay(500))
)
)
));
return this.http.get(this.someEndpoint, commonHttpHeaders())
// With the new syntax you can now share this pipeline between uses
.pipe(retryPipeline)
}
</code></pre> |
910,850 | jquery assign onclick for li from a link | <p>I have a list of items</p>
<pre><code><ul class="list">
<li>
<a href="#Course1" class="launch" onclick="alert('event 1')">event 1</a>
</li>
<li class="alt">
<a href="#Course2" class="launch" onclick="alert('event 2')">event 2</a>
</li>
<li>
<a href="#Course3" class="launch" onclick="alert('event 3')">event 3</a>
</li>
<li class="alt">
<a href="#Course4" class="launch" onclick="alert('event 4')">event 4</a>
</li>
</ul>
</code></pre>
<p>I want to be able to assign the onclick of the link to the onclick of the li aswell</p>
<p>My attempt so far is one click behind (as I am assigning the script to the onclick rather than executing the script)</p>
<pre><code>$('.list li').click(function() {
var launch = $('a.launch', this);
if (launch.size() > 0) { this.onclick = launch.attr('onclick'); }
});
</code></pre>
<p>Thanks in advance
Tim</p> | 913,875 | 5 | 0 | null | 2009-05-26 14:01:29.87 UTC | 7 | 2009-05-27 04:56:44.06 UTC | null | null | null | null | 53,365 | null | 1 | 5 | jquery | 40,702 | <p>building on <a href="https://stackoverflow.com/users/72859/thomas-stock">@Thomas Stock's</a> <a href="https://stackoverflow.com/questions/910850/jquery-assign-onclick-for-li-from-a-link/910877#910877">answer</a> the following code prevents double execution on clicking on link instead of li. (got it from <a href="http://docs.jquery.com/Events/jQuery.Event" rel="nofollow noreferrer">here</a> jQuery site)</p>
<pre><code>$(document).ready(function() {
$('ul.list li').click(function(e) {
var $target = $(e.target);
if(!$target.is("li")) //magic happens here!!
{
return;
}
var launch = $('a.launch', this);
if (launch.size() > 0)
{
eval(launch[0].onclick());
}
});
});
</code></pre> |
99,876 | Selenium Critique | <p>I just wanted some opinions from people that have run Selenium (<a href="http://selenium.openqa.org" rel="nofollow noreferrer">http://selenium.openqa.org</a>) I have had a lot of experience with WaTiN and even wrote a recording suite for it. I had it producing some well-structured code but being only maintained by me it seems my company all but abandoned it. </p>
<p>If you have run selenium have you had a lot of success? </p>
<p>I will be using .NET 3.5, does Selenium work well with it? </p>
<p>Is the code produced clean or simply a list of all the interaction? (<a href="http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx" rel="nofollow noreferrer">http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx</a>) </p>
<p>How well does the distributed testing suite fair?</p>
<p>Any other gripes or compliments on the system would be greatly appreciated!</p> | 99,965 | 5 | 0 | null | 2008-09-19 05:29:11.03 UTC | 16 | 2019-09-03 07:12:25.723 UTC | 2019-09-03 07:12:25.723 UTC | moocha | 8,791,568 | Adam Driscoll | 13,688 | null | 1 | 16 | unit-testing|selenium|automated-tests|ui-testing | 3,675 | <p>If you are using <a href="http://selenium-ide.openqa.org/" rel="nofollow noreferrer">Selenium IDE</a> to generate code, then you just get a list of every action that selenium will execute. To me, Selenium IDE is a good way to start or do a fast "try and see" test. But, when you think about maintainability and more readable code, you must write your own code.</p>
<p>A good way to achieve good selenium code is to use the <a href="http://code.google.com/p/webdriver/wiki/PageObjects" rel="nofollow noreferrer">Page Object Pattern</a> in a way that the code represents your navigation flow. Here is a good example that I see in <a href="http://dojofloripa.wordpress.com/2008/04/20/como-usar-tdd-e-page-objects-para-construir-interfaces-web/" rel="nofollow noreferrer">Coding Dojo Floripa</a> (from Brazil):</p>
<pre><code>public class GoogleTest {
private Selenium selenium;
@Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*firefox",
"http://www.google.com/webhp?hl=en");
selenium.start();
}
@Test
public void codingDojoShouldBeInFirstPageOfResults() {
GoogleHomePage home = new GoogleHomePage(selenium);
GoogleSearchResults searchResults = home.searchFor("coding dojo");
String firstEntry = searchResults.getResult(0);
assertEquals("Coding Dojo Wiki: FrontPage", firstEntry);
}
@After
public void tearDown() throws Exception {
selenium.stop();
}
}
public class GoogleHomePage {
private final Selenium selenium;
public GoogleHomePage(Selenium selenium) {
this.selenium = selenium;
this.selenium.open("http://www.google.com/webhp?hl=en");
if (!"Google".equals(selenium.getTitle())) {
throw new IllegalStateException("Not the Google Home Page");
}
}
public GoogleSearchResults searchFor(String string) {
selenium.type("q", string);
selenium.click("btnG");
selenium.waitForPageToLoad("5000");
return new GoogleSearchResults(string, selenium);
}
}
public class GoogleSearchResults {
private final Selenium selenium;
public GoogleSearchResults(String string, Selenium selenium) {
this.selenium = selenium;
if (!(string + " - Google Search").equals(selenium.getTitle())) {
throw new IllegalStateException(
"This is not the Google Results Page");
}
}
public String getResult(int i) {
String nameXPath = "xpath=id('res')/div[1]/div[" + (i + 1) + "]/h2/a";
return selenium.getText(nameXPath);
}
}
</code></pre>
<p>Hope that Helps</p> |
880,981 | In a join table, what's the best workaround for Rails' absence of a composite key? | <pre><code>create_table :categories_posts, :id => false do |t|
t.column :category_id, :integer, :null => false
t.column :post_id, :integer, :null => false
end
</code></pre>
<p>I have a join table (as above) with columns that refer to a corresponding <em>categories</em> table and a <em>posts</em> table. I wanted to enforce a unique constraint on <strong>the composite key category_id, post_id</strong> in the <strong>categories_posts</strong> join table. But Rails does not support this (I believe). </p>
<p>To avoid the potential for duplicate rows in my data having the same combination of category_id and post_id, <strong>what's the best workaround for the absence of a composite key in Rails</strong>? </p>
<p>My assumptions here are:</p>
<ol>
<li>The default auto-number column
(id:integer) would do nothing to
protect my data in this situation.</li>
<li>ActiveScaffold may provide a
solution but I'm not sure if
it's overkill to include it in my
project simply for this single
feature, especially if there is a
more elegant answer.</li>
</ol> | 881,024 | 5 | 0 | null | 2009-05-19 04:30:25.203 UTC | 18 | 2016-01-06 21:58:43.083 UTC | 2009-05-19 04:36:25.67 UTC | null | 101,050 | null | 101,050 | null | 1 | 32 | ruby-on-rails|database|composite-key|junction-table | 10,209 | <p>Add a unique index that includes both columns. That will prevent you from inserting a record that contains a duplicate category_id/post_id pair.</p>
<pre><code>add_index :categories_posts, [ :category_id, :post_id ], :unique => true, :name => 'by_category_and_post'
</code></pre> |
1,142,562 | Loading a webpage through UIWebView with POST parameters | <p>Is it possible to load a page through UIWebView with POST parameters?
I can probably just load an embedded form with the parameters and fill them in with javascript and force a submit, but is there a cleaner and faster way?</p>
<p>Thanks!</p> | 1,143,020 | 5 | 0 | null | 2009-07-17 10:47:26.66 UTC | 23 | 2022-06-17 10:28:08.853 UTC | null | null | null | jurek epimetheus | null | null | 1 | 57 | iphone|http|uiwebview | 42,030 | <p>Create POST URLRequest and use it to fill webView</p>
<pre><code>NSURL *url = [NSURL URLWithString: @"http://your_url.com"];
NSString *body = [NSString stringWithFormat: @"arg1=%@&arg2=%@", @"val1",@"val2"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
[webView loadRequest: request];
</code></pre> |
220,250 | In C# why can't a conditional operator implicitly cast to a nullable type | <p>I am curious as to why an implicit cast fails in...</p>
<pre><code>int? someValue = SomeCondition ? ResultOfSomeCalc() : null;
</code></pre>
<p>and why I have to perform an explicit cast instead</p>
<pre><code>int? someValue = SomeCondition ? ResultofSomeCalc() : (int?)null;
</code></pre>
<p>It seems to me that the compiler has all the information it need to make an implicit casting decision, no?</p> | 220,268 | 6 | 4 | null | 2008-10-20 23:04:11.337 UTC | 8 | 2015-04-14 10:13:17.14 UTC | 2010-04-07 10:11:00.04 UTC | Marc Gravell | 19,750 | Tim J | 10,387 | null | 1 | 32 | c#|conditional-operator|nullable | 14,020 | <p>The relevant section of the C# 3.0 spec is 7.13, the conditional operator:</p>
<p>The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,</p>
<p>If X and Y are the same type, then this is the type of the conditional
Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
Otherwise, no expression type can be determined, and a compile-time error occurs.</p> |
628,416 | JAAS for human beings | <p>I am having a hard time understanding JAAS. It all seems more complicated than it should be (especially the Sun tutorials). I need a simple tutorial or example on how to implement security (authentication + authorization) in java application based on Struts + Spring + Hibernate with custom user repository. Can be implemented using ACEGI.</p> | 628,451 | 6 | 3 | null | 2009-03-09 23:27:00.08 UTC | 50 | 2017-04-01 23:43:33.78 UTC | 2009-03-09 23:59:46.18 UTC | matt b | 4,249 | Dan | 68,473 | null | 1 | 86 | java|security|spring|spring-security|jaas | 32,427 | <p>Here are some of the links I used to help understand JAAS:</p>
<p><a href="http://www.owasp.org/index.php/JAAS_Tomcat_Login_Module" rel="nofollow noreferrer">http://www.owasp.org/index.php/JAAS_Tomcat_Login_Module</a></p>
<p><a href="http://www.javaworld.com/jw-09-2002/jw-0913-jaas.html" rel="nofollow noreferrer">http://www.javaworld.com/jw-09-2002/jw-0913-jaas.html</a></p>
<p><a href="http://jaasbook.wordpress.com/" rel="nofollow noreferrer">http://jaasbook.wordpress.com/</a></p>
<p><a href="http://roneiv.wordpress.com/2008/02/18/jaas-authentication-mechanism-is-it-possible-to-force-j_security_check-to-go-to-a-specific-page/" rel="nofollow noreferrer">http://roneiv.wordpress.com/2008/02/18/jaas-authentication-mechanism-is-it-possible-to-force-j_security_check-to-go-to-a-specific-page/</a></p>
<p>Also have a look at the Apache tomcat realms configuration how-to:</p>
<p><a href="http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html" rel="nofollow noreferrer">http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html</a></p> |
299,703 | delegate keyword vs. lambda notation | <p>Once it is compiled, is there a difference between:</p>
<pre><code>delegate { x = 0; }
</code></pre>
<p>and</p>
<pre><code>() => { x = 0 }
</code></pre>
<p>?</p> | 299,712 | 6 | 0 | null | 2008-11-18 18:38:08.537 UTC | 87 | 2019-11-06 18:28:55.45 UTC | 2011-10-07 12:18:45.357 UTC | Joel Coehoorn | 41,956 | MojoFilter | 93 | null | 1 | 190 | c#|.net|delegates|lambda|anonymous-methods | 73,423 | <p>Short answer : no.</p>
<p>Longer answer that may not be relevant: </p>
<ul>
<li>If you assign the lambda to a delegate type (such as <code>Func</code> or <code>Action</code>) you'll get an anonymous delegate.</li>
<li>If you assign the lambda to an Expression type, you'll get an expression tree instead of a anonymous delegate. The expression tree can then be compiled to an anonymous delegate.</li>
</ul>
<p>Edit:
Here's some links for Expressions.</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/bb335710.aspx" rel="noreferrer">System.Linq.Expression.Expression(TDelegate)</a> (start here).</li>
<li>Linq in-memory with delegates (such as System.Func) uses <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable_methods.aspx" rel="noreferrer">System.Linq.Enumerable</a>. Linq to SQL (and anything else) with expressions uses <a href="http://msdn.microsoft.com/en-us/library/system.linq.queryable_members.aspx" rel="noreferrer">System.Linq.Queryable</a>. Check out the parameters on those methods.</li>
<li>An <a href="http://weblogs.asp.net/scottgu/archive/2007/04/08/new-orcas-language-feature-lambda-expressions.aspx" rel="noreferrer">Explanation from ScottGu</a>. In a nutshell, Linq in-memory will produce some anonymous methods to resolve your query. Linq to SQL will produce an expression tree that represents the query and then translate that tree into T-SQL. Linq to Entities will produce an expression tree that represents the query and then translate that tree into platform appropriate SQL.</li>
</ul> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.