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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
59,744,589 | How can I convert the string '2020-01-06T00:00:00.000Z' into a datetime object? | <p>As the question says, I have a series of strings like <code>'2020-01-06T00:00:00.000Z'</code>. How can I convert this series to <code>datetime</code> using Python? I prefer the method on pandas. If not is there any method to solve this task? Thank all.</p>
<pre><code>string '2020-01-06T00:00:00.000Z'
convert to 2020-01-06 00:00:00 under datetime object
</code></pre> | 59,744,630 | 4 | 2 | null | 2020-01-15 02:58:02.003 UTC | 3 | 2022-09-20 21:36:18.277 UTC | 2021-12-02 12:08:12.32 UTC | null | 6,789,321 | null | 11,198,558 | null | 1 | 11 | python|pandas|datetime | 52,539 | <p>With Python 3.7+, that can be achieved with <a href="https://docs.python.org/3/library/datetime.html#datetime.date.fromisoformat" rel="noreferrer"><code>datetime.fromisoformat()</code></a> and some <em>tweaking</em> of the source string:</p>
<pre class="lang-py prettyprint-override"><code>>>> from datetime import datetime
>>> datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1] + '+00:00')
datetime.datetime(2020, 1, 6, 0, 0, tzinfo=datetime.timezone.utc)
>>>
</code></pre>
<p>And here is a more <em>Pythonic</em> way to achieve the same result:</p>
<pre class="lang-py prettyprint-override"><code>>>> from datetime import datetime
>>> from datetime import timezone
>>> datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1]).astimezone(timezone.utc)
datetime.datetime(2020, 1, 6, 3, 0, tzinfo=datetime.timezone.utc)
>>>
</code></pre>
<p>Finally, to format it as <code>%Y-%m-%d %H:%M:%S</code>, you can do:</p>
<pre class="lang-py prettyprint-override"><code>>>> d = datetime.fromisoformat('2020-01-06T00:00:00.000Z'[:-1]).astimezone(timezone.utc)
>>> d.strftime('%Y-%m-%d %H:%M:%S')
'2020-01-06 00:00:00'
>>>
</code></pre> |
18,022,534 | Moment.js and Unix Epoch Conversion | <p>I have a web service that is returning a date as the following string:</p>
<p><code>/Date(1377907200000)/</code></p>
<p>I use MomentJS to parse this to a <code>moment</code> object.</p>
<p><code>moment("/Date(1377907200000)/")</code> => <code>Fri Aug 30 2013 20:00:00 GMT-0400</code></p>
<p>All of that is fine. But when I call <code>unix()</code> on the object I am given the value <code>1377907200</code>. This, however, corresponds to <code>Fri Jan 16 1970 17:45:07 GMT-0500</code>. I could just multiply the value returned by <code>unix()</code> but that seems sloppy to me. I suspect that what I am doing by calling <code>unix()</code> is not exactly what I think it is. Do I need to specify some sort of format when calling <code>unix()</code>? What am I missing here?</p>
<p><a href="http://jsfiddle.net/RobertKaucher/CqrLA/" rel="noreferrer">JSFidle showing the conversion to moment and then back.</a></p> | 18,023,203 | 3 | 2 | null | 2013-08-02 17:10:51.167 UTC | 3 | 2021-03-04 12:55:38.883 UTC | null | null | null | null | 330,430 | null | 1 | 17 | javascript|date|epoch|momentjs | 39,202 | <p>The answer provided by meagar is correct, from strictly a JavaScript / Unix time perspective. However, if you just multiply by 1000, you will loose any sub-second precision that might have existed in your data.</p>
<p>Moment.js offers two different methods, as described <a href="http://momentjs.com/docs/#/displaying/unix-offset/" rel="noreferrer">in the docs</a>. <code>.unix()</code> returns the value in seconds. It is effectively dividing by 1000 and truncating any decimals. You want to use the <code>.valueOf()</code> method, which just returns the milliseconds without modification.</p> |
17,916,101 | How many lines of code differs between two commits or two branches? | <p>I want to know how many lines of code I changed between two different commits. My purpose is to understand how many lines of code I've written today but my abstract idea is to understand how many lines of code I've write from a moment to another one. Can someone help me for this stuff?</p> | 17,916,132 | 3 | 0 | null | 2013-07-29 04:33:47.817 UTC | 7 | 2017-10-09 20:31:31.513 UTC | 2017-10-09 20:31:31.513 UTC | null | 1,420,625 | null | 1,420,625 | null | 1 | 33 | git | 11,347 | <p><code>--shortstat</code> is what you want:</p>
<pre><code>git diff --shortstat commit1 commit2
</code></pre>
<p>You could also use it like:</p>
<pre><code>git diff --shortstat "@{1 day ago}"
</code></pre> |
17,864,742 | How to apply font anti-alias effects in CSS? | <p>How can we apply Photoshop-like font anti-aliasing such as crisp, sharp, strong, smooth in CSS?</p>
<p>Are these supported by all browsers?</p> | 17,886,204 | 3 | 2 | null | 2013-07-25 17:24:30.207 UTC | 17 | 2018-11-13 16:32:58.237 UTC | 2013-07-25 17:29:39.963 UTC | null | 2,539,720 | null | 2,416,577 | null | 1 | 63 | html|css|antialiasing | 231,602 | <p>here you go Sir :-)</p>
<p>1</p>
<pre><code>.myElement{
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
</code></pre>
<p>2</p>
<pre><code>.myElement{
text-shadow: rgba(0,0,0,.01) 0 0 1px;
}
</code></pre> |
2,313,949 | Learning ARM assembly | <p>During this year there will be coming couple sub-600€ multi-touch portable computers that contain Tegra2. They bring me to a good excuse to learning ARM assembly language. But I have no clue where to start from aside the arm.com.</p>
<p>For first throw I could just pick up an emulator with a linux distribution in it. But which emulator and distro would work best on this one? Having access to the host system's files would be okay so I could compile and execute ARM binaries straight from my home-directory.</p>
<p>I wouldn't want to waste much money to books so I'd need some assembly source code examples and a good free introduction to the instruction set. gcc compiler flags for compiling ARM programs on x86 would be also nice but I might find them out myself as well.</p> | 2,314,009 | 5 | 2 | null | 2010-02-22 20:32:39.793 UTC | 13 | 2019-06-05 01:35:30.193 UTC | null | null | null | null | 21,711 | null | 1 | 23 | assembly|arm | 15,139 | <p>Obtain an evaluation version of of <a href="http://www.keil.com/arm/rvcomparison.asp" rel="noreferrer">one of the arm software toolkits</a> which will include a debugger/software emulator. If you're willing to spend a few hundred dollars, obtain an arm eval board (<a href="http://www.keil.com" rel="noreferrer">Keil</a> sells a few). You can test your code on the board via a JTAG interface and see what happens on real hardware.</p>
<p>These should get your going in the right direction</p>
<p><em>Disclosure: I work for ARM.</em></p> |
2,253,185 | How do I drop a column with object dependencies in SQL Server 2008? | <p>The error message I'm obtaining when trying to drop a column:</p>
<blockquote>
<p>The object 'defEmptyString' is dependent on column 'fkKeywordRolleKontakt'.</p>
<p>Msg 5074, Level 16, State 1, Line 43</p>
<p>ALTER TABLE DROP COLUMN fkKeywordRolleKontakt failed because one or more objects access this column.</p>
</blockquote>
<p>I have already tried to find the default constraints, as described here:
<a href="https://stackoverflow.com/questions/314998/sql-server-2005-drop-column-with-constraints">SQL Server 2005 drop column with constraints</a></p>
<p>Unfortunately without any success :( The line returned is:</p>
<pre><code>fkKeywordRolleKontakt 2 814625945 0 defEmptyString
</code></pre>
<p>And I cannot remove either of <code>fkKeywordRolleKontakt</code> and <code>defEmptyString</code>.</p>
<p>What is the correct way to get rid of this dependency?</p>
<p>EDIT: Perhaps this is of importance too. The column fkKeywordRolleKontakt is of type udKeyword (nvarchar(50)) with default <code>dbo.defEmptyString</code>.</p>
<p><br /><b>Edit 2: Solved</b></p>
<p>I could solve the problem now. I'm sorry, I did not copy the full error message, which was:</p>
<p><code>Msg 5074, Level 16, State 1, Line 1<br />
The object 'defEmptyString' is dependent on column 'fkKeywordRolleKontakt'.<br />
Msg 5074, Level 16, State 1, Line 1<br />
The object 'FK_tlkpRolleKontakt_tlkpKeyword' is dependent on column 'fkKeywordRolleKontakt'.<br />
Msg 4922, Level 16, State 9, Line 1<br />
ALTER TABLE DROP COLUMN fkKeywordRolleKontakt failed because one or more objects access this column.</code></p>
<p>I could generate a script to drop the column by right-clicking on the column entry (dbo.tlkpRolleKontakt > Columns > fkKeywordRolleKontakt) (in MSSQL Server Manager), selecting Modify and deleting the column. Then Table Designer > Generate Change Script generated the necessary commands:</p>
<pre><code>ALTER TABLE dbo.tlkpRolleKontakt
DROP CONSTRAINT FK_tlkpRolleKontakt_tlkpKeyword
EXECUTE sp_unbindefault N'dbo.tlkpRolleKontakt.fkKeywordRolleKontakt'
ALTER TABLE dbo.tlkpRolleKontakt
DROP COLUMN fkKeywordRolleKontakt
</code></pre>
<p>That's it :)</p> | 37,723,536 | 5 | 2 | null | 2010-02-12 16:12:10.4 UTC | 2 | 2016-09-15 16:22:48.717 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 271,961 | null | 1 | 30 | sql|sql-server|sql-server-2008|dependencies|sql-drop | 102,910 | <p>I could solve the problem now. I'm sorry, I did not copy the full error message, which was:</p>
<p>Msg 5074, Level 16, State 1, Line 1<br />
The object 'defEmptyString' is dependent on column 'fkKeywordRolleKontakt'.<br /></p>
<blockquote>
<p>Msg 5074, Level 16, State 1, Line 1<br /> The object
'FK_tlkpRolleKontakt_tlkpKeyword' is dependent on column
'fkKeywordRolleKontakt'.<br /> Msg 4922, Level 16, State 9, Line 1 ALTER TABLE DROP COLUMN fkKeywordRolleKontakt failed because one or
more objects access this column.</p>
</blockquote>
<p>I could generate a script to drop the column by right-clicking on the column entry (dbo.tlkpRolleKontakt > Columns > fkKeywordRolleKontakt) (in MSSQL Server Manager), selecting Modify and deleting the column. Then Table Designer > Generate Change Script generated the necessary commands:</p>
<pre><code>ALTER TABLE dbo.tlkpRolleKontakt
DROP CONSTRAINT FK_tlkpRolleKontakt_tlkpKeyword
EXECUTE sp_unbindefault N'dbo.tlkpRolleKontakt.fkKeywordRolleKontakt'
ALTER TABLE dbo.tlkpRolleKontakt
DROP COLUMN fkKeywordRolleKontakt
</code></pre> |
2,063,199 | jQuery: How can I show an image popup onclick of the thumbnail? | <p>In my aspx page I have a thumbnail image <code><img></code>. When the user clicks on that image I would like a popup to show that blocks out the rest of the UI with the larger (full) version of the image.</p>
<p>Are there any plugins that can do this?</p> | 2,063,211 | 5 | 1 | null | 2010-01-14 09:28:24.527 UTC | 34 | 2020-09-06 22:51:37.473 UTC | 2010-04-25 00:35:12.447 UTC | null | 45,433 | null | 219,152 | null | 1 | 54 | jquery|jquery-plugins|popup | 259,074 | <p>There are a lot of jQuery plugins available for this</p>
<p><strong><a href="http://codylindley.com/thickbox/" rel="noreferrer">Thickbox</a></strong></p>
<p><strong><a href="http://www.lokeshdhakar.com/projects/lightbox2/?u=9" rel="noreferrer">LightBox</a></strong></p>
<p><strong><a href="http://fancybox.net/" rel="noreferrer">FancyBox</a></strong></p>
<p><strong><a href="https://github.com/defunkt/facebox" rel="noreferrer">FaceBox</a></strong></p>
<p><strong><a href="http://nyromodal.nyrodev.com/" rel="noreferrer">NyroModal</a></strong></p>
<p><strong><a href="http://www.pirolab.it/pirobox/" rel="noreferrer">PiroBox</a></strong></p>
<p><strong><em>Thickbox Examples</em></strong></p>
<p>For a single image</p>
<blockquote>
<ol>
<li>Create a link element ()</li>
<li>Give the link a class attribute with a value of thickbox
(class="thickbox")</li>
<li>Provide a path in the href attribute to an image file (.jpg .jpeg
.png .gif .bmp)</li>
</ol>
</blockquote> |
2,186,848 | How to find locked rows in Oracle | <p>We have an Oracle database, and the customer account table has about a million rows. Over the years, we've built four different UIs (two in Oracle Forms, two in .Net), all of which remain in use. We have a number of background tasks (both persistent and scheduled) as well. </p>
<p>Something is occasionally holding a long lock (say, more than 30 seconds) on a row in the account table, which causes one of the persistent background tasks to fail. The background task in question restarts itself once the update times out. We find out about it a few minutes after it happens, but by then the lock has been released.</p>
<p>We have reason to believe that it might be a misbehaving UI, but haven't been able to find a "smoking gun".</p>
<p>I've found some queries that list blocks, but that's for when you've got two jobs contending for a row. I want to know which rows have locks when there's not necessarily a second job trying to get a lock.</p>
<p>We're on 11g, but have been experiencing the problem since 8i.</p> | 2,187,582 | 6 | 0 | null | 2010-02-02 19:09:40.04 UTC | 7 | 2022-06-07 07:46:31.99 UTC | null | null | null | null | 12,304 | null | 1 | 18 | oracle|locking | 111,531 | <p><code>Oracle</code>'s locking concept is quite different from that of the other systems.</p>
<p>When a row in <code>Oracle</code> gets locked, the record itself is updated with the new value (if any) and, in addition, a lock (which is essentially a pointer to transaction lock that resides in the rollback segment) is placed right into the record.</p>
<p>This means that locking a record in <code>Oracle</code> means updating the record's metadata and issuing a logical page write. For instance, you cannot do <code>SELECT FOR UPDATE</code> on a read only tablespace.</p>
<p>More than that, the records themselves are not updated after commit: instead, the rollback segment is updated.</p>
<p>This means that each record holds some information about the transaction that last updated it, even if the transaction itself has long since died. To find out if the transaction is alive or not (and, hence, if the record is alive or not), it is required to visit the rollback segment.</p>
<p>Oracle does not have a traditional lock manager, and this means that obtaining a list of all locks requires scanning all records in all objects. This would take too long.</p>
<p>You can obtain some special locks, like locked metadata objects (using <code>v$locked_object</code>), lock waits (using <code>v$session</code>) etc, but not the list of all locks on all objects in the database.</p> |
1,756,862 | URL Decoding in PHP | <p>I am trying to decode this URL string using PHP's urldecode function:</p>
<pre><code>urldecode("Ant%C3%B4nio+Carlos+Jobim");
</code></pre>
<p>This is supposed to output...</p>
<pre><code>'Antônio Carlos Jobim'
</code></pre>
<p>...but instead is ouptutting this</p>
<pre><code>'Antônio Carlos Jobim'
</code></pre>
<p>I've tested the string in a <a href="http://meyerweb.com/eric/tools/dencoder/" rel="noreferrer">JS-based online decoder</a> with great success, but can't seem to do this operation server side. Any ideas?</p> | 1,756,925 | 6 | 1 | null | 2009-11-18 15:39:33.563 UTC | 6 | 2019-01-03 09:33:11.503 UTC | 2012-09-01 18:40:13.087 UTC | null | 220,060 | null | 189,569 | null | 1 | 36 | php|url|utf-8|urldecode | 94,225 | <p>Your string is <em>also</em> UTF-8 encoded. This will work:</p>
<pre><code>echo utf8_decode(urldecode("Ant%C3%B4nio+Carlos+Jobim"));
</code></pre>
<p>Output: "Antônio Carlos Jobim".</p> |
1,986,418 | 'typeid' versus 'typeof' in C++ | <p>I am wondering what the difference is between <code>typeid</code> and <code>typeof</code> in C++. Here's what I know:</p>
<ul>
<li><p><code>typeid</code> is mentioned in the documentation for <a href="http://www.cplusplus.com/reference/typeinfo/type_info/" rel="noreferrer">type_info</a> which is defined in the C++ header file <a href="http://www.cplusplus.com/reference/typeinfo/?kw=typeinfo" rel="noreferrer">typeinfo</a>.</p></li>
<li><p><code>typeof</code> is defined in the GCC extension for C and in the C++ <a href="http://en.wikipedia.org/wiki/Boost_C%2B%2B_Libraries" rel="noreferrer">Boost</a> library.</p></li>
</ul>
<p>Also, here is test code test that I've created where I've discovered that <code>typeid</code> does not return what I expected. Why?</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include <typeinfo> //for 'typeid' to work
class Person {
public:
// ... Person members ...
virtual ~Person() {}
};
class Employee : public Person {
// ... Employee members ...
};
int main () {
Person person;
Employee employee;
Person *ptr = &employee;
int t = 3;
std::cout << typeid(t).name() << std::endl;
std::cout << typeid(person).name() << std::endl; // Person (statically known at compile-time)
std::cout << typeid(employee).name() << std::endl; // Employee (statically known at compile-time)
std::cout << typeid(ptr).name() << std::endl; // Person * (statically known at compile-time)
std::cout << typeid(*ptr).name() << std::endl; // Employee (looked up dynamically at run-time
// because it is the dereference of a pointer
// to a polymorphic class)
}
</code></pre>
<p><strong>output:</strong></p>
<pre class="lang-none prettyprint-override"><code>bash-3.2$ g++ -Wall main.cpp -o main
bash-3.2$ ./main
i
6Person
8Employee
P6Person
8Employee
</code></pre> | 1,986,485 | 6 | 3 | null | 2009-12-31 17:55:32.32 UTC | 61 | 2018-06-28 22:43:05.147 UTC | 2016-05-30 22:37:34.233 UTC | null | 5,183,619 | null | 156,458 | null | 1 | 192 | c++|typeof|typeid | 452,484 | <p>C++ language has no such thing as <code>typeof</code>. You must be looking at some compiler-specific extension. If you are talking about GCC's <code>typeof</code>, then a similar feature is present in C++11 through the keyword <code>decltype</code>. Again, C++ has no such <code>typeof</code> keyword.</p>
<p><code>typeid</code> is a C++ language operator which returns type identification information at run time. It basically returns a <code>type_info</code> object, which is equality-comparable with other <code>type_info</code> objects.</p>
<p>Note, that the only defined property of the returned <code>type_info</code> object has is its being equality- and non-equality-comparable, i.e. <code>type_info</code> objects describing different types shall compare non-equal, while <code>type_info</code> objects describing the same type have to compare equal. Everything else is implementation-defined. Methods that return various "names" are not guaranteed to return anything human-readable, and even not guaranteed to return anything at all.</p>
<p>Note also, that the above probably implies (although the standard doesn't seem to mention it explicitly) that consecutive applications of <code>typeid</code> to the same type might return different <code>type_info</code> objects (which, of course, still have to compare equal).</p> |
1,411,172 | Javadoc Inserting UML Diagrams | <p>Is there a way to embed images into my JavaDoc? Basically i want to include some UML diagrams explaining the hierarchy of my classes in some of the documentation.</p>
<p>Thanks!</p> | 1,411,201 | 7 | 1 | null | 2009-09-11 14:20:33.073 UTC | 13 | 2021-01-16 02:29:04.283 UTC | 2017-02-08 08:55:19.82 UTC | null | 1,429,387 | null | 139,203 | null | 1 | 24 | java|javadoc|class-diagram | 13,797 | <p>Check out <a href="http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#images" rel="nofollow noreferrer">this section</a> of the Javadoc documentation, which explains how to embed images in your Javadoc.</p>
<p>Also, here is an <a href="https://dzone.com/articles/reverse-engineer-source-code-u" rel="nofollow noreferrer">article</a> describing how to reverse engineer UML diagrams and embed them in your Javadoc using <a href="https://www.spinellis.gr/umlgraph/" rel="nofollow noreferrer">UMLGraph</a>.</p> |
1,900,956 | Write variable to file, including name | <p>Let's say I have the following dictionary in a small application. </p>
<pre><code>dict = {'one': 1, 'two': 2}
</code></pre>
<p>What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, but maybe there is an easier way.</p>
<p>I do not need a way to convert it to a string, that I can do. But if there is a built in function that does this for me, I would like to know.</p>
<p>To make it clear, what I would like to write to the file is:</p>
<pre><code>write_to_file("dict = {'one': 1, 'two': 2}")
</code></pre> | 1,901,016 | 8 | 5 | null | 2009-12-14 13:34:33.723 UTC | 11 | 2021-08-15 19:54:39.61 UTC | 2009-12-14 13:41:27.513 UTC | null | 28,169 | null | 55,366 | null | 1 | 42 | python | 293,526 | <p>the <code>repr</code> function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.</p>
<pre><code>>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'one': 1}"
</code></pre>
<p>writing to a file is pretty standard stuff, like any other file write:</p>
<pre><code>f = open( 'file.py', 'w' )
f.write( 'dict = ' + repr(dict) + '\n' )
f.close()
</code></pre> |
1,714,461 | ANSI SQL Manual | <p>Can anyone recommend a good ANSI SQL reference manual? </p>
<p>I don't necessary mean a tutorial but a proper reference document to lookup when you need either a basic or more in-depth explanation or example.</p>
<p>Currently I am using <a href="http://www.w3schools.com/SQl/default.asp" rel="noreferrer">W3Schools SQL Tutorial</a> and <a href="http://www.sql-tutorial.net/SQL-IN.asp" rel="noreferrer">SQL Tutorial</a> which are ok, but I don't find them "deep" enough.</p>
<p>Of course, each major RDBMS producer will have some sort of reference manuals targeting their own product, but they tend to be biased and sometime will use proprietary extensions.</p>
<p>EDITED: The aim of the question was to focus on the things database engines have in common i.e. the SQL roots. But understanding the differences can also be a positive thing - <a href="http://troels.arvin.dk/db/rdbms/" rel="noreferrer">this</a> is quite interesting.</p> | 1,714,789 | 10 | 7 | null | 2009-11-11 10:58:55.053 UTC | 26 | 2013-08-16 17:14:04.023 UTC | 2013-08-16 17:14:04.023 UTC | user1228 | null | null | 181,406 | null | 1 | 52 | sql|reference|manual|ansi-sql | 43,954 | <p>Here's the ‘Second Informal Review Draft’ of <a href="http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt" rel="noreferrer">SQL:1992</a>, which seems to have been accurate enough for everything I've looked up. 1992 covers most of the stuff routinely used across DBMSs.</p> |
2,289,381 | How to time an operation in milliseconds in Ruby? | <p>I'm wishing to figure out how many milliseconds a particular function uses. So I looked high and low, but could not find a way to get the time in Ruby with millisecond precision. </p>
<p>How do you do this? In most programming languages its just something like</p>
<pre><code>start = now.milliseconds
myfunction()
end = now.milliseconds
time = end - start
</code></pre> | 2,289,563 | 10 | 0 | null | 2010-02-18 14:42:06.707 UTC | 11 | 2019-12-18 11:31:04 UTC | 2012-10-24 09:52:46.303 UTC | null | 125,816 | null | 69,742 | null | 1 | 83 | ruby|timer | 65,831 | <p>You can use ruby's <code>Time</code> class. For example:</p>
<pre><code>t1 = Time.now
# processing...
t2 = Time.now
delta = t2 - t1 # in seconds
</code></pre>
<p>Now, <code>delta</code> is a <code>float</code> object and you can get as fine grain a result as the class will provide.</p> |
1,606,679 | Remove duplicates in the list using linq | <p>I have a class <code>Items</code> with <code>properties (Id, Name, Code, Price)</code>.</p>
<p>The List of <code>Items</code> is populated with duplicated items. </p>
<p>For ex.: </p>
<pre><code>1 Item1 IT00001 $100
2 Item2 IT00002 $200
3 Item3 IT00003 $150
1 Item1 IT00001 $100
3 Item3 IT00003 $150
</code></pre>
<p>How to remove the duplicates in the list using linq?</p> | 1,606,686 | 11 | 2 | null | 2009-10-22 11:48:26.677 UTC | 75 | 2020-05-14 10:17:54.683 UTC | 2009-10-22 12:26:18.453 UTC | null | 52,502 | null | 111,435 | null | 1 | 365 | c#|linq|linq-to-objects|generic-list | 368,322 | <pre><code>var distinctItems = items.Distinct();
</code></pre>
<p>To match on only some of the properties, create a custom equality comparer, e.g.:</p>
<pre><code>class DistinctItemComparer : IEqualityComparer<Item> {
public bool Equals(Item x, Item y) {
return x.Id == y.Id &&
x.Name == y.Name &&
x.Code == y.Code &&
x.Price == y.Price;
}
public int GetHashCode(Item obj) {
return obj.Id.GetHashCode() ^
obj.Name.GetHashCode() ^
obj.Code.GetHashCode() ^
obj.Price.GetHashCode();
}
}
</code></pre>
<p>Then use it like this:</p>
<pre><code>var distinctItems = items.Distinct(new DistinctItemComparer());
</code></pre> |
1,950,038 | Firing events on CSS class changes in jQuery | <p>How can I fire an event if a CSS class is added or changed using jQuery?
Does changing of a CSS class fire the jQuery <code>change()</code> event?</p> | 1,950,052 | 13 | 3 | null | 2009-12-23 00:21:25.447 UTC | 82 | 2020-04-17 21:18:27 UTC | 2020-04-17 21:18:27 UTC | null | 4,370,109 | null | 237,060 | null | 1 | 245 | jquery|css|jquery-events | 346,497 | <p>Whenever you change a class in your script, you could use a <code>trigger</code> to raise your own event.</p>
<pre><code>$(this).addClass('someClass');
$(mySelector).trigger('cssClassChanged')
....
$(otherSelector).bind('cssClassChanged', data, function(){ do stuff });
</code></pre>
<p>but otherwise, no, there's no baked-in way to fire an event when a class changes. <code>change()</code> only fires after focus leaves an input whose input has been altered.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
var button = $('.clickme')
, box = $('.box')
;
button.on('click', function() {
box.removeClass('box');
$(document).trigger('buttonClick');
});
$(document).on('buttonClick', function() {
box.text('Clicked!');
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.box { background-color: red; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">Hi</div>
<button class="clickme">Click me</button></code></pre>
</div>
</div>
</p>
<p><a href="http://docs.jquery.com/Events/trigger#eventdata" rel="noreferrer">More info on jQuery Triggers</a></p> |
1,482,586 | Comparison between Corona, Phonegap, Titanium | <p>I am a web developer and I want to move my web products to iPhone. One of the products is like Google Maps: show map on the phone screen, you can drag or resize the map and view some information that we add to the map.</p>
<p>I know there are some technologies that enables you to use HTML, CSS and Javascript to develop native iPhone apps. I've identified a few:</p>
<ul>
<li><a href="http://www.anscamobile.com/" rel="nofollow noreferrer">Ansca Mobile</a></li>
<li><a href="http://phonegap.com/" rel="nofollow noreferrer">PhoneGap</a></li>
<li><a href="http://www.appcelerator.com/" rel="nofollow noreferrer">Appcelerator</a></li>
</ul>
<p>Are there other, similar products? What are the differences between them? Which should I choose?</p> | 1,806,940 | 14 | 2 | null | 2009-09-27 01:46:50.02 UTC | 457 | 2012-10-28 01:12:52.91 UTC | 2011-02-18 10:17:17.677 UTC | Roger Pate | -1 | null | 115,781 | null | 1 | 310 | iphone|android|html|mobile-website | 212,258 | <p>I registered with stackoverflow just for the purpose of commenting on the mostly voted answer on top. The bad thing is stackoverflow does not allow new members to post comments. So I have to make this comment more look like an answer.</p>
<p>Rory Blyth's answer contains some valid points about the two javascript mobile frameworks. However, his key points are incorrect. The truth is that Titanium and PhoneGap are more similar than different. They both expose mobile phone functions through a set of javascript APIs, and the application's logic (html, css, javascript) runs inside a native WebView control.</p>
<ol>
<li><p>PhoneGap is not just a native wrapper of a web app. Through the PhoneGap javascript APIs, the "web app" has access to the mobile phone functions such as Geolocation, Accelerometer Camera, Contacts, Database, File system, etc. Basically any function that the mobile phone SDK provides can be "bridged" to the javascript world. On the other hand, a normal web app that runs on the mobile web browser does not have access to most of these functions (security being the primary reason). Therefore, a PhoneGap app is more of a mobile app than a web app. You can certainly use PhoneGap to wrap a web app that does not use any PhoneGap APIs at all, but that is not what PhoneGap was created for.</p></li>
<li><p>Titanium does NOT compile your html, css or javascript code into "native bits". They are packaged as resources to the executable bundle, much like an embedded image file. When the application runs, these resources are loaded into a UIWebView control and run there (as javascript, not native bits, of course). There is no such thing as a javascript-to-native-code (or to-objective-c) compiler. This is done the same way in PhoneGap as well. From architectural standpoint, these two frameworks are very similar.</p></li>
</ol>
<p>Now, are they any different? Yes. First, Titanium appears to be more feature rich than PhoneGap by bridging more mobile phone functions to javascript. Most noticeably, PhoneGap does not expose many (if any) native UI components to javascript. Titanium, on the other hand, has a comprehensive UI APIs that can be called in javascript to create and control all kinds of native UI controls. Utilizaing these UI APIs, a Titanium app can look more "native" than a PhoneGap app. Second, PhoneGap supports more mobile phone platforms than Titanium does. PhoneGap APIs are more generic and can be used on different platforms such as iPhone, Android, Blackberry, Symbian, etc. Titanium is primarily targeting iPhone and Android at least for now. Some of its APIs are platform specific (like the iPhone UI APIs). The use of these APIs will reduce the cross-platform capability of your application.</p>
<p>So, if your concern for your app is to make it more "native" looking, Titanium is a better choice. If you want to be able to "port" your app to another platform more easily, PhoneGap will be better. </p>
<p><strong>Updated 8/13/2010:</strong>
<a href="https://appcelerator.tenderapp.com/discussions/titanium-mobile-discussion/553-what-are-the-differences-between-titanium-and-phonegap" rel="noreferrer">Link to a Titanium employee's answer to Mickey's question.</a> </p>
<p><strong>Updated 12/04/2010:</strong>
I decided to give this post an annual review to keep its information current. Many things have changes in a year that made some of the information in the initial post outdated.</p>
<p>The biggest change came from Titanium. Earlier this year, Appcelerator released Titanium 1.0, which departed drastically from its previous versions from the architectural standpoint. In 1.0, the UIWebView control is no longer in use. Instead, you call Titanium APIs for any UI functions. This change means a couple things:</p>
<ol>
<li><p>Your app UI becomes completely native. There is no more web UI in your app since the native Titanium APIs take over control of all your UI needs. Titanium deserves a lot of credit by pioneering on the "Cross-Platform Native UI" frontier. It gives programmers who prefer the look and feel of native UI but dislike the official programming language an alternative. </p></li>
<li><p>You won't be able to use HTML or CSS in your app, as the web view is gone. (Note: you can still create web view in Titanium. But there are few Titanium features that you can take advantage of in the web view.)<a href="http://developer.appcelerator.com/question/71/what-happened-to-html--css" rel="noreferrer">Titanium Q&A: What happened to HTML & CSS?</a></p></li>
<li><p>You won't be able to use popular JS libraries such as JQuery that assume the existence of an DOM object. You continue to use JavaScript as your coding language. But that is pretty much the only web technology you can utilize if you come to Titanium 1.0 as a web programmer.</p></li>
</ol>
<p><a href="http://www.vimeo.com/9953236" rel="noreferrer">Titanium video: What is new in Titanium 1.0.</a></p>
<p>Now, does Titanium 1.0 compile your JavaScript into "native bits"? No. Appcelerator finally came clean on this issue with this developer blog:<a href="http://developer.appcelerator.com/blog/2010/12/titanium-guides-project-js-environment.html" rel="noreferrer">Titanium Guides Project: JS Environment.</a> We programmers are more genuine people than those in the Marketing department, aren't we? :-) </p>
<p>Move on to PhoneGap. There are not many new things to say about PhoneGap. My perception is that PhoneGap development was not very active until IBM jumped on board later this year. Some people even argued that IBM is contributing more code to PhoneGap than Nitobi is. That being true or not, it is good to know that PhoneGap is being active developed. </p>
<p>PhoneGap continues to base itself on web technologies, namely HTML, CSS and JavaScript. It does not look like PhoneGap has any plan to bridge native UI features to JavaScript as Titanium is doing. While Web UI still lags behind native UI on performance and native look and feel, such gap is being rapidly closed. There are two trends in web technologies that ensure bright feature to mobile web UI in terms of performance:</p>
<ol>
<li><p>JavaScript engine moving from an interpreter to a virtual machine. JavaScript is JIT compiled into native code for faster execution. <a href="http://webkit.org/blog/214/introducing-squirrelfish-extreme/" rel="noreferrer">Safari JS engine: SquirrelFish Extreme</a></p></li>
<li><p>Web page rendering moving from relying on CPU to using GPU acceleration. Graphic intensive tasks such as page transition and 3D animation become a lot smoother with the help of hardware acceleration. <a href="https://sites.google.com/a/chromium.org/dev/developers/design-documents/gpu-accelerated-compositing-in-chrome" rel="noreferrer">GPU Accelerated Compositing in Chrome</a></p></li>
</ol>
<p>Such improvements that are originated from desktop browsers are being delivered to mobile browsers quickly. In fact, since iOS 3.2 and Android 2.0, the mobile web view control has become much more performing and HTML5 friendly. The future of mobile web is so promising that it has attracted a big kid to town: <a href="http://jquerymobile.com/" rel="noreferrer">JQuery has recently announced its mobile web framework.</a> With JQuery Mobile providing UI gadgets, and PhoneGap providing phone features, they two combined creates a perfect mobile web platform in my opinion.</p>
<p>I should also mention <a href="http://www.sencha.com/products/touch/" rel="noreferrer">Sencha Touch</a> as another mobile web UI gadget framework. Sencha Touch version 1.0 was recently released under a dual licensing model that includes GPLv3. Sencha Touch works well with PhoneGap just as JQuery Mobile does.</p>
<p>If you are a <a href="http://code.google.com/webtoolkit/overview.html" rel="noreferrer">GWT</a> programmer(like me), you may want to check out <a href="http://www.gwtmobile.com" rel="noreferrer">GWT Mobile</a>, an open source project for creating mobile web apps with GWT. It includes a PhoneGap GWT wrapper that enables the use of PhoneGap in GWT. </p> |
1,665,744 | Xcode + remove all breakpoints | <p>Is there any way to remove all the breakpoints in Xcode?</p> | 1,665,772 | 14 | 0 | null | 2009-11-03 07:22:19.683 UTC | 41 | 2021-03-19 06:50:31.967 UTC | 2012-04-27 19:32:11.86 UTC | null | 18,821 | null | 178,369 | null | 1 | 209 | xcode|breakpoints | 101,980 | <p>Well there's a 3 step way:</p>
<ol>
<li>Press CMD(⌘)+7 to show all breakpoints.
In Xcode4 press CMD(⌘)+6, in Xcode3 press CMD(⌘)+ALT+B.</li>
<li>Select all breakpoints with CMD(⌘)+A and delete them, like deleting text, with backspace.</li>
<li>There's no step 3 :)</li>
</ol> |
1,607,271 | How do you find the current user in a Windows environment? | <p>When running a command-line script, is it possible to get the name of the current user?</p> | 1,607,287 | 15 | 2 | null | 2009-10-22 13:38:15.603 UTC | 15 | 2021-08-19 07:10:06.813 UTC | 2019-11-26 19:06:29.497 UTC | null | 252,518 | null | 31,610 | null | 1 | 182 | windows|batch-file | 405,807 | <p>You can use the username variable: <code>%USERNAME%</code></p> |
33,629,416 | How to tell if hex value is negative? | <p>I have just learned how to read hexadecimal values. Until now, I was only reading them as positive numbers. I heard you could also write negative hex values.</p>
<p>My issue is that <strong>I can't tell if a value is negative or positive</strong>.
I found a few explanations here and there but if I try to verify them by using online hex to decimal converters, they always give me different results.</p>
<p>Sources I found: <br>
<a href="https://stackoverflow.com/a/5827491/5016201">https://stackoverflow.com/a/5827491/5016201</a> <br>
<a href="https://coderanch.com/t/246080/java-programmer-OCPJP/certification/Negative-Hexadecimal-number" rel="noreferrer">https://coderanch.com/t/246080/java-programmer-OCPJP/certification/Negative-Hexadecimal-number</a> <br><br>
If I understand correctly it means that: <br> <strong>If a hex value written with all its bits having something > 7 as its first hex digit, it is negative.</strong><br>
<strong>All 'F' at the beginning or the first digit means is that the value is negative, it is not calculated.</strong> <br><br>
For exemple if the hex value is written in 32 bits:<br>
FFFFF63C => negative ( -2500 ?)<br>
844fc0bb => negative ( -196099909 ?)<br>
F44fc0bb => negative ( -196099909 ?)<br>
FFFFFFFF => negative ( -1 ?)<br>
7FFFFFFF => positive <br></p>
<p>Am I correct? If not, could you tell me what I am not getting right?</p> | 33,629,511 | 4 | 4 | null | 2015-11-10 11:55:36.65 UTC | 6 | 2020-10-05 21:18:32.397 UTC | 2020-01-16 10:15:46.657 UTC | null | 12,229,372 | null | 5,016,201 | null | 1 | 19 | hex | 128,549 | <p>Read up on Two's complement representation: <a href="https://en.wikipedia.org/wiki/Two%27s_complement" rel="noreferrer">https://en.wikipedia.org/wiki/Two%27s_complement</a></p>
<p>I think that the easiest way to understand how negative numbers (usually) are treated is to write down a small binary number and then figure out how to do subtraction by one. When you reach 0 and apply that method once again - you'll see that you suddenly get all 1's. And that is how "-1" is (usually) represented: all ones in binary or all f's in hexadecimal. Commonly, if you work with signed numbers, they are represented by the first (most significant) bit being one. That is to say that if you work with a number of bits that is a multiple of four, then a number is negative if the first hexadecimal digit is 8,9,A,B,C,D,E or F.</p>
<p>The method to do negation is:</p>
<ol>
<li>invert all the bits</li>
<li>add 1</li>
</ol>
<p>Another benefit from this representation (two's complement) is that you only get one representation for zero, which would not be the case if you marked signed numbers by setting the MSB or just inverting them.</p> |
18,099,514 | WHERE CASE WHEN statement with Exists | <p>I am creating a SQL query having <code>WHERE CASE WHEN</code> statement. I am doing something wrong and getting error. </p>
<p>My SQL statement is like</p>
<pre><code>DECLARE @AreaId INT = 2
DECLARE @Areas Table(AreaId int)
INSERT INTO @Areas SELECT AreaId
FROM AreaMaster
WHERE CityZoneId IN (SELECT CityZoneId FROM AreaMaster WHERE AreaId = @AreaID)
SELECT *
FROM dbo.CompanyMaster
WHERE AreaId IN
(CASE WHEN EXISTS (SELECT BusinessId
FROM dbo.AreaSubscription
WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId)
THEN @AreaId
ELSE (SELECT [@Areas].AreaId FROM @Areas)
END)
</code></pre>
<p>I am getting error as </p>
<blockquote>
<p>Msg 512, Level 16, State 1, Line 11<br>
Subquery returned more than 1 value. This is not permitted when the subquery
follows =, !=, <, <= , >, >= or when the subquery is used as an
expression.</p>
</blockquote>
<p>Please help to successfully run query. My logic is to checking for conditional <code>AreaId</code> in (statement) for each row.</p>
<p>I want to select the row only when </p>
<ol>
<li>company has subscription entry into <code>AreaSubscription</code> for specific area passed by <code>@AreaId</code> </li>
<li>table <code>AreaSubscription</code> does not have subscription entry then evaluate <code>AreaId</code> in <code>(SELECT [@Areas].AreaId FROM @Areas)</code></li>
</ol> | 18,099,853 | 4 | 6 | null | 2013-08-07 09:21:30.61 UTC | 4 | 2022-08-13 06:49:17.307 UTC | 2013-08-07 11:58:25.317 UTC | null | 13,302 | null | 1,777,213 | null | 1 | 22 | sql|sql-server|sql-server-2008 | 119,632 | <p>This may help you.</p>
<pre><code>SELECT * FROM dbo.CompanyMaster
WHERE AreaId=
(CASE WHEN EXISTS (SELECT BusinessId
FROM dbo.AreaSubscription
WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId)
THEN @AreaId ELSE AreaId END)
AND AreaId IN (SELECT [@Areas].AreaId FROM @Areas)
</code></pre>
<p>One more solution is</p>
<pre><code>SELECT * FROM dbo.CompanyMaster A
LEFT JOIN @Areas B ON A.AreaId=B.AreaID
WHERE A.AreaId=
(CASE WHEN EXISTS (SELECT BusinessId
FROM dbo.AreaSubscription
WHERE AreaSubscription.BusinessId = CompanyMaster.BusinessId)
THEN @AreaId ELSE B.AreaId END)
)
</code></pre> |
18,214,233 | Simple ticket reservation java | <pre><code>import java.io.*;
import java.util.*;
public class Ticket_reserve {
private static int counter=100;
List<String> BookingList=new ArrayList<String>();
ArrayList<Integer> AgeList=new ArrayList<Integer>();
public void reservation(){
System.out.println("Enter the tickets needed:");
Scanner tkts=new Scanner(System.in);
int tickets=tkts.nextInt();
if(tickets<=counter){
System.out.println("Name and age please");
System.out.println("age:");
Scanner age=new Scanner(System.in);
int Age=age.nextInt();
if(Age<18){
System.out.println("You're under 18.Booking cancelled");
}else{
for(int i=0;i<tickets;i++){
System.out.println("Name:");
Scanner nom=new Scanner(System.in);
String name=nom.nextLine();
BookingList.add(name);
AgeList.add(Age);
counter--;
}
}
}else{
System.out.println(tickets+"tickets unavailable");
}
System.out.println("Names: "+BookingList+","+"Age:"+AgeList);
}
public static void main(String[] args) {
Ticket_reserve t1=new Ticket_reserve();
t1.reservation();
}
}
</code></pre>
<p>This is my code and it works perfectly. The only problem I have is I need to check the age of each person and then book the ticket for that person (if they are above 18); else cancel it. I couldn't get a better idea, so I put it inside <code>if</code> checking for ticket availability and now I can only get the age of one person. I need to iterate through each person and print their age. Should I use a <code>while</code> loop instead?</p>
<p>Thank you.</p> | 18,214,488 | 4 | 2 | null | 2013-08-13 16:20:30.807 UTC | 0 | 2015-07-15 09:47:37.757 UTC | 2013-08-13 16:33:07.597 UTC | null | 2,192,903 | null | 2,624,674 | null | 1 | -5 | java | 41,114 | <p>But you are taking just 1 person?You should use a loop for taking more than 1 person.Second, you should have a person class for OOP.
Let us come to your question:
After taking the properties of people, you should create a Person with these information.And add it to Person list(no need to have age list).Once you take people into a list, you can iterate on the list:</p>
<pre><code>List<Person> people=new ArrayList<Person>();
//take people info from console and add it to the list:
Person person=new Person(age,name,etc);
people.add(person);
for(Person p:people){
if(p.getAge<18){//say something
}
else{//say something
}
}
</code></pre> |
17,912,432 | Adding an image and text both in asp.net button | <p>I am looking for a solution where I will be able to add an image and text both in asp.net button.</p>
<pre><code> <asp:Button ID="Button1" runat="server" Text="Button"/>
</code></pre>
<p>I am only able to specify text to the button, but how can I add an image as well to it?</p> | 17,912,632 | 4 | 6 | null | 2013-07-28 20:14:27.763 UTC | 2 | 2021-05-04 18:54:55.32 UTC | null | null | null | null | 992,124 | null | 1 | 9 | asp.net|.net|button | 55,030 | <p>By default, ASP .Net doesn't have a button which can <strong>render both image and text at the same time</strong>. However, you can achieve in two ways. </p>
<h2>Using CSS</h2>
<p>I prefer CSS because it is light weight, and you can style it whatever you want.</p>
<p><img src="https://i.stack.imgur.com/BUXgg.png" alt="enter image description here"></p>
<pre><code><style type="text/css">
.submit {
border: 1px solid #563d7c;
border-radius: 5px;
color: white;
padding: 5px 10px 5px 25px;
background: url(https://i.stack.imgur.com/jDCI4.png)
left 3px top 5px no-repeat #563d7c;
}
</style>
<asp:Button runat="server" ID="Button1" Text="Submit" CssClass="submit" />
</code></pre>
<h2>Third Party Control</h2>
<p>It works right out of the box. However, you cannot change their style easily.</p>
<p><img src="https://i.stack.imgur.com/OoLdu.png" alt="enter image description here"></p>
<p>Use third party control like <a href="http://demos.telerik.com/aspnet-ajax/button/examples/embeddedicons/defaultcs.aspx" rel="noreferrer">Telerik RadButton</a>.</p>
<p><em>Last but not least if you want, you can implement a custom server control by yourself.</em></p> |
17,903,705 | Is it possible to start a shell session in a running container (without ssh) | <p>I was naively expecting this command to run a bash shell in a running container : </p>
<pre><code>docker run "id of running container" /bin/bash
</code></pre>
<p>it looks like it's not possible, I get the error : </p>
<pre><code>2013/07/27 20:00:24 Internal server error: 404 trying to fetch remote history for 27d757283842
</code></pre>
<p>So, if I want to run bash shell in a running container (ex. for diagnosis purposes)</p>
<p>do I have to run an SSH server in it and loggin via ssh ?</p> | 17,931,950 | 15 | 5 | null | 2013-07-28 00:05:06.317 UTC | 92 | 2020-11-08 18:44:26.993 UTC | 2013-07-28 00:09:07.857 UTC | null | 1,371,070 | null | 535,782 | null | 1 | 349 | docker | 251,207 | <p>EDIT: Now you can use <code>docker exec -it "id of running container" bash</code> (<a href="https://docs.docker.com/engine/reference/commandline/exec/" rel="noreferrer">doc</a>)</p>
<p>Previously, the answer to this question was:</p>
<p>If you really must and you are in a debug environment, you can do this: <code>sudo lxc-attach -n <ID></code>
Note that the id needs to be the full one (<code>docker ps -notrunc</code>).</p>
<p>However, I strongly recommend against this.</p>
<p>notice: <code>-notrunc</code> is deprecated, it will be replaced by <code>--no-trunc</code> soon.</p> |
6,919,405 | Mystical restriction on std::binary_search | <p><strong>Problem description:</strong><br/>
Consider some structure having an <code>std::string name</code> member. For clearness let's suppose that it's a <code>struct Human</code>, representing information about people. Besides the <code>name</code> it can also have many other data members.<br/>
Let there be a container <code>std::vector<Human> vec</code>, where the objects are already sorted by <code>name</code>. Also for clearness suppose that all the names are unique.<br/>
<em>The problem is</em>: having some string <code>nameToFind</code> find out if there exists an element in the array having such name.</p>
<p><strong>Solution and my progress:</strong><br/>
The obvious and natural solution seems to perform a binary search using the <code>std::binary_search</code> function. But there is a problem: the type of the element being searched (<code>std::string</code>) is different from the type of the elements in the container (<code>Human</code>), and std::binary_search needs a rule to compare these elements. I tried to solve this in three ways, described below. First two are provided just to illustrate the evolution of my solution and the problems which I came across. My main question refers to the third one.</p>
<p><strong>Attempt 1: convert <code>std::string</code> to <code>Human</code>.</strong></p>
<p>Write a comparing function:</p>
<pre><code>bool compareHumansByNames( const Human& lhs, const Human& rhs )
{
return lhs.name < rhs.name;
}
</code></pre>
<p>Then add a constructor which constructs a <code>Human</code> object from <code>std::string</code>:</p>
<pre><code>struct Human
{
Human( const std::string& s );
//... other methods
std::string name;
//... other members
};
</code></pre>
<p>and use the binary_search in following form:</p>
<pre><code>std::binary_search( vec.begin(), vec.end(), nameToFind, compareHumansByNames );
</code></pre>
<p>Seems working, but turns up two big problems:<br/>
First, how to initialize other data members but <code>Human::name</code>, especially in the case when they don't have a default constructor ? setting magic values may lead to creation of an object which is semantically illegal.<br/>
Second, we have to declare this constructor as non <code>explicit</code> to allow implicit conversions during the algorithm. The bad consequences of this are well known.<br/>
Also, such a temporary <code>Human</code> object will be constructed at each iteration, which can turn out to be quite expensive.</p>
<p><strong>Attempt 2: convert <code>Human</code> to <code>std::string</code>.</strong></p>
<p>We can try to add an <code>operator string ()</code> to the <code>Human</code> class which returns it's <code>name</code>, and then use the comparsion for two <code>std::string</code>s. However, this approach is also inconvenient by the following reasons:</p>
<p>First, the code will not compile at once because of the problem discussed <a href="https://stackoverflow.com/questions/6788169/why-does-not-the-compiler-perform-a-type-conversion">here</a>. We will have to work a bit more to make the compiler use the appropriate <code>operator <</code>.<br/>
Second, what does mean "convert a Human to string" ? Existence of such conversion can lead to semantically wrong usage of class <code>Human</code>, which is undesirable.</p>
<p><strong>Attempt 3: compare without conversions.</strong></p>
<p>The best solution I got so far is to create a</p>
<pre><code>struct Comparator
{
bool operator() ( const Human& lhs, const std::string& rhs )
{
return lhs.name < rhs;
}
bool operator() ( const std::string& lhs, const Human& rhs )
{
return lhs < rhs.name;
}
};
</code></pre>
<p>and use binary search as</p>
<pre><code>binary_search( vec.begin(), vec.end(), nameToFind, Comparator() );
</code></pre>
<p>This compiles and executes correctly, everything seems to be ok, but here is where the interesting part begins:<br/> </p>
<p>Have a look at <a href="http://www.sgi.com/tech/stl/binary_search.html" rel="nofollow noreferrer">http://www.sgi.com/tech/stl/binary_search.html</a>. It's said here that "<strong><em>ForwardIterator</strong>'s value type is <strong>the same type as T</strong>.</em>". Quite confusing restriction, and my last solution breaks it. Let's see what does the C++ standard say about it:</p>
<hr>
<p><strong>25.3.3.4</strong> binary_search</p>
<pre><code>template<class ForwardIterator, class T>
bool binary_search(ForwardIterator first, ForwardIterator last,
const T& value);
template<class ForwardIterator, class T, class Compare>
bool binary_search(ForwardIterator first, ForwardIterator last,
const T& value, Compare comp);
</code></pre>
<p><strong>Requires:</strong> Type T is LessThanComparable (20.1.2).<br/></p>
<hr>
<p>Nothing is explicitly said about <code>ForwardIterator</code>'s type. But, in definition of <em>LessThanComparable</em> given in <em>20.1.2</em> it is said about comparsion of two elements of <strong>the same type</strong>. And here is what I do not understand. Does it indeed mean that the <em>type of the object being searched</em> and the <em>type of the container's objects</em> <strong>must</strong> be the same, and my solution breaks this restriction ? Or it does not refer to the case when the <code>comp</code> comparator is used, and only is about the case when the default <code>operator <</code> is used for comparsion ? In first case, I'm confused about how to use <code>std::binary_search</code> to solve this without coming across the problems mentioned above. </p>
<p>Thanks in advance for help and finding time to read my question.</p>
<p><em>Note:</em> I understand that writing a binary search by hand takes no time and will solve the problem instantly, but to avoid re-inventing a wheel I want to use the std::binary_search. Also it's very interesting to me to find out about existence of such restriction according to standard.</p> | 6,919,649 | 4 | 13 | 2011-08-04 08:22:14.973 UTC | 2011-08-02 22:20:32.087 UTC | 4 | 2016-01-27 17:48:26.877 UTC | 2017-05-23 11:44:54.523 UTC | null | -1 | null | 810,312 | null | 1 | 29 | c++|algorithm|search|stl|standards | 2,280 | <p>If your goal is to find if there is a <code>Human</code> with a given name, then the following should work for sure:</p>
<pre><code>const std::string& get_name(const Human& h)
{
return h.name;
}
...
bool result = std::binary_search(
boost::make_transform_iterator(v.begin(), &get_name),
boost::make_transform_iterator(v.end(), &get_name),
name_to_check_against);
</code></pre> |
6,884,616 | Intercept all ajax calls? | <p>I'm trying to intercept all AJAX calls in order to check if that AJAX response contains specific error code that I send as JSON from my PHP script (codes: ACCESS_DENIED, SYSTEM_ERROR, NOT_FOUND).</p>
<p>I know one can do something like this:</p>
<pre><code>$('.log').ajaxSuccess(function(e, xhr, settings) {
});
</code></pre>
<p>But - does this work only if "ajaxSuccess" event bubble up to .log div? Am I correct? Can I achieve what I want by binding "ajaxSuccess" event to document?</p>
<pre><code>$(document).ajaxSuccess(function(e, xhr, settings) {
});
</code></pre>
<p>I can do this in either jQuery or raw JavaScript.</p> | 6,884,707 | 4 | 2 | null | 2011-07-30 16:57:18.32 UTC | 21 | 2021-06-30 22:04:34.723 UTC | 2019-08-26 22:00:47.243 UTC | null | 4,370,109 | null | 471,891 | null | 1 | 34 | javascript|jquery|ajax|dom-events | 42,961 | <p>From <a href="http://api.jquery.com/ajaxSuccess/" rel="noreferrer">http://api.jquery.com/ajaxSuccess/</a> :</p>
<blockquote>
<p>Whenever an Ajax request completes successfully, jQuery triggers the ajaxSuccess event. Any and all handlers that have been registered with the .ajaxSuccess() method are executed at this time.</p>
</blockquote>
<p>So the selector doesn't define the position where you are "catching" the event (because, honestly, ajax event by its nature doesn't start from a DOM element), but rather defines a scope to which the handling will be defaulted (i.e. <code>this</code> will poitn to that/those element(s)).</p>
<p>In summary - it should be exactly what you wish for</p> |
35,817,565 | How to filter array when object key value is in array | <p>I have an array model as below:</p>
<pre><code>records:[{
"empid":1,
"fname": "X",
"lname": "Y"
},
{
"empid":2,
"fname": "A",
"lname": "Y"
},
{
"empid":3,
"fname": "B",
"lname": "Y"
},
{
"empid":4,
"fname": "C",
"lname": "Y"
},
{
"empid":5,
"fname": "C",
"lname": "Y"
}
]
</code></pre>
<p>Now I have an array of empid's <code>[1,4,5]</code>.</p>
<p>So now I need to filter the first array which contains all the keys in my second.</p>
<p><strong>Output:</strong></p>
<pre><code>records:[{
"empid":1,
"fname": "X",
"lname": "Y"
},
{
"empid":4,
"fname": "C",
"lname": "Y"
},
{
"empid":5,
"fname": "C",
"lname": "Y"
}
]
</code></pre>
<p>I can do this using a <code>forEach</code> loop in <code>angular</code> but as I have more than 100 records in my model object. I need a suggestion on how to handle this in much better way.</p>
<p>I am thinking of creating a custom filter, but what is your take on it.(If yes please provide sample code to achieve this).</p> | 35,817,622 | 8 | 4 | null | 2016-03-05 17:48:41.81 UTC | 20 | 2021-09-11 04:43:49.867 UTC | 2021-02-16 10:09:50.49 UTC | null | 5,267,751 | null | 1,533,883 | null | 1 | 64 | javascript|angularjs|angular-filters | 220,664 | <p>You can do it with <code>Array.prototype.filter()</code>,</p>
<pre><code>var data = { records : [{ "empid": 1, "fname": "X", "lname": "Y" }, { "empid": 2, "fname": "A", "lname": "Y" }, { "empid": 3, "fname": "B", "lname": "Y" }, { "empid": 4, "fname": "C", "lname": "Y" }, { "empid": 5, "fname": "C", "lname": "Y" }] }
var empIds = [1,4,5]
var filteredArray = data.records.filter(function(itm){
return empIds.indexOf(itm.empid) > -1;
});
filteredArray = { records : filteredArray };
</code></pre>
<p>If the <code>callBack</code> returns a <code>true</code> value, then the <code>itm</code> passed to that particular <code>callBack</code> will be filtered out. You can read more about it <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="noreferrer">here</a>.</p> |
46,011,754 | How to add a custom payment gateway to Social Engine | <p>I need to integrate a new payment gateway to our corporate website, which is based on Social Engine. There is an extension for this <code>CMS</code> called Advanced Payment Gateways which allows integration of new gateways. In fact, it gets your gateway name and generates a skeleton structure zipped as a file so you can unzip and upload to your server and thus merge with the application directory. </p>
<p>I'm going to explain how I implement my gateway without Social Engine, and I hope someone can tell me how I can incorporate that into Social Engine. </p>
<ol>
<li><p>First I connect to my <code>PSP</code> service: </p>
<pre><code>$client = new nusoap_client('https://example.com/pgwchannel/services/pgw?wsdl');
</code></pre></li>
<li><p>I prepare the following parameters in an array to send to <code>bpPayRequest</code>: </p>
<pre><code>$parameters = array(
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $orderId,
'amount' => $amount,
'localDate' => $localDate,
'localTime' => $localTime,
'additionalData' => $additionalData,
'callBackUrl' => $callBackUrl,
'payerId' => $payerId);
// Call the SOAP method
$result = $client->call('bpPayRequest', $parameters, $namespace);
</code></pre></li>
<li><p>If payment request is accepted, the result is a comma separated string, with the first element being <strong>0</strong>.<br>
Then we can send the second element (reference id) to payment
gateway as follows via <code>POST</code> method:</p>
<pre><code>echo "<script language='javascript' type='text/javascript'>postRefId('" . $res[1] . "');</script>";
<script language="javascript" type="text/javascript">
function postRefId (refIdValue) {
var form = document.createElement("form");
form.setAttribute("method", "POST");
form.setAttribute("action", "https://example.com/pgwchannel/startpay");
form.setAttribute("target", "_self");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "RefId");
hiddenField.setAttribute("value", refIdValue);
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
</script>
</code></pre></li>
<li><p>The gateway will return the following parameters via <code>POST</code> method to the call back <code>URL</code> that we provided in payment request:<br>
<code>RefId</code> (reference id as produced in previous steps)<br>
<code>ResCode</code> (Result of payment: 0 denotes success)<br>
<code>saleOrderId</code> (order id as passed during payment request)<br>
<code>SaleReferenceId</code> (sale reference code is given by PSP to the merchant) </p></li>
<li><p>If <code>ResCode</code> in the previous step was <strong>0</strong>, then we'd need to pass the call <code>bpVerifyRequest</code> with the following parameters to verify payment, otherwise the payment will be canceled. </p>
<pre><code> $parameters = array(
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $orderId,
'saleOrderId' => $verifySaleOrderId,
'saleReferenceId' => $verifySaleReferenceId);
// Call the SOAP method
$result = $client->call('bpVerifyRequest', $parameters, $namespace);
</code></pre></li>
<li><p>In case the result of <code>bpVerifyRequest</code> is zero, payment is certain and the merchant has to provide goods or services purchased. However, there is an optional method <code>bpSettleRequest</code>, which is used to request a settlement. It is called as follows: </p></li>
</ol>
<pre><code> $parameters = array(
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $orderId,
'saleOrderId' => $settleSaleOrderId,
'saleReferenceId' => $settleSaleReferenceId);
// Call the SOAP method
$result = $client->call('bpSettleRequest', $parameters, $namespace);
</code></pre>
<p>I get confused by looking at default gateways in the Payment Gateways plugin e.g. PayPal, Stripe, 2Checkout, etc. How am I incorporate this code logic into the newly created gateway skeleton? (the structure is shown below):<br>
<a href="https://i.stack.imgur.com/PZyCe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PZyCe.png" alt="enter image description here"></a></p>
<p>You can check out the complete source code here:<br>
<a href="https://gist.github.com/anonymous/02dcf681b3cd0852a18fb7723e34447f" rel="nofollow noreferrer">default.php</a><br>
<a href="https://gist.github.com/anonymous/19a5b759f767cef6cd40158b9a3f0577" rel="nofollow noreferrer">callback.php</a></p> | 57,259,513 | 1 | 27 | null | 2017-09-02 08:03:38.6 UTC | 2 | 2019-07-29 18:25:28.347 UTC | 2019-07-29 17:56:06.48 UTC | null | 2,009,178 | null | 2,009,178 | null | 1 | 58 | php|customization|payment-gateway|socialengine | 2,135 | <p>I solved this by adding the payment code inside the <code>Engine_Payment_Gateway_MyGateway</code> class: </p>
<p>Once the user confirms on the SocialEngine page that they want to pay, the method <code>processTransaction()</code> inside the mentioned class is called and the user is redirected to the PSP's payment secure page. Once they are done with the payment, i.e. paid successfully or failed or canceled the transaction, they PSP's page redirects them to the page we had sent to it earlier as a parameter called callBackUrl. There, you will receive PSP-specific parameters which helps you decide whether the payment was successful and to ask the PSP with another SOAP call to confirm the payment and then optionally ask it to settle (deposit money ASAP into the seller's account): </p>
<p><strong>Add to processTransaction()</strong>:</p>
<pre><code> $data = array();
$rawData = $transaction->getRawData();
//Save order ID for later
$this->_orderId = $rawData['vendor_order_id'];
$this->_grandTotal = $rawData['AMT'];
$client = new nusoap_client('https://example.com/pgwchannel/services/pgw?wsdl');
$namespace = 'http://interfaces.core.sw.example.com/';
// Check for an error
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
die();
}
/* Set variables */
//Get price from SEAO
//$order_ids = Engine_Api::_()->getDbTable('orders','sitestoreproduct')->getOrderIds($this->parent_id);
//$price = Engine_Api::_()->getDbTable('orders','sitestoreproduct')->getGrandTotal($this->parent_id);
$terminalId = '1111111';
$userName = 'username';
$userPassword = '1111111';
$orderId = $rawData['vendor_order_id'];
$amount = $rawData['AMT'];
$localDate = date("Y") . date("m") . date("d");
$localTime = date("h") . date("i") . date("s");
$additionalData = $rawData['return_url'];
$callBackUrl = 'https://example.com/pgateway/pay/callback';
$payerId = '0';
/* Define parameters array */
$parameters = array(
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $orderId,
'amount' => $amount,
'localDate' => $localDate,
'localTime' => $localTime,
'additionalData' => $additionalData,
'callBackUrl' => $callBackUrl,
'payerId' => $payerId
);
$result = $client->call('bpPayRequest', $parameters, $namespace);
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
die();
} else { //Check for errors
$error = $client->getError();
if ($error) {
echo "An error occurred: ";
print_r($error);
die();
} else {
//break the code
$resultSegmts = explode(',', $result);
$ResCode = $resultSegmts [0];
if ($ResCode == "0") {
//Notify admin of the order
echo '<h3>Redirecting you to the payment page. Please wait...</h3><br/>';
echo '<script language="javascript" type="text/javascript">
postRefId("' . $resultSegmts[1] . '");
</script>';
} elseif ($ResCode == "25") {
echo "<h3>Purchase successful</h3>";
} else {
echo "<h3>PSP response is: $ResCode</h3>";
}
}
}
</code></pre>
<p><strong>Add to your callBack action</strong>:</p>
<pre><code> $this->view->message = 'This is callback action for PayController';
$RefId = $_POST['RefId'];
$ResCode = $_POST['ResCode'];
$saleOrderId = $_POST['SaleOrderId'];
$saleReferenceId = $_POST['SaleReferenceId'];
$this->_orderId = $saleOrderId;
$this->view->RefId = $RefId;
$this->view->saleOlderId = $saleOrderId;
$this->view->saleReferenceId = $saleReferenceId;
}
if ($ResCode == "0") {
try {
$client = new nusoap_client('https://example.com/pgwchannel/services/pgw?wsdl');
} catch (Exception $e) {
die($e->getMessage());
}
$namespace = 'http://interfaces.core.sw.example.com/';
$terminalId = "111111";
$userName = "username";
$userPassword = "11111111";
$parameters = array(
'terminalId' => $terminalId,
'userName' => $userName,
'userPassword' => $userPassword,
'orderId' => $saleOrderId,
'saleOrderId' => $saleOrderId,
'saleReferenceId' => $saleReferenceId
);
$resVerify = $client->call('bpVerifyRequest', $parameters, $namespace);
if ($resVerify->fault) { //Check for fault
echo "<h1>Fault: </h1>";
print_r($result);
die();
} else { //No fault: check for errors now
$err = $client->getError();
if ($err) {
echo "<h1>Error: " . $err . " </h1>";
} else {
if ($resVerify == "0") {//Check verification response: if 0, then purchase was successful.
echo "<div class='center content green'>Payment successful. Thank you for your order.</div>";
$this->view->message = $this->_translate('Thanks for your purchase.');
$this->dbSave(); //update database table
} else
echo "<script language='javascript' type='text/javascript'>alert( 'Verification Response: " . $resVerify . "');</script>";
}
}
//Note that we need to send bpSettleRequest to PSP service to request settlement once we have verified the payment
if ($resVerify == "0") {
// Update table, Save RefId
//Create parameters array for settle
$this->sendEmail();
$this->sendSms();
$resSettle = $client->call('bpSettleRequest', $parameters, $namespace);
//Check for fault
if ($resSettle->fault) {
echo "<h1>Fault: </h1><br/><pre>";
print_r($resSettle);
echo "</pre>";
die();
} else { //No fault in bpSettleRequest result
$err = $client->getError();
if ($err) {
echo "<h1>Error: </h1><pre>" . $err . "</pre>";
die();
} else {
if ($resSettle == "0" || $resSettle == "45") {//Settle request successful
// echo "<script language='javascript' type='text/javascript'>alert('Payment successful');</script>";
}
}
}
}
} else {
echo "<div class='center content error'>Payment failed. Please try again later.</div> ";
// log error in app
// Update table, log the error
// Show proper message to user
}
$returnUrl = 'https://example.com/stores/products'; //Go to store home for now. Later I'll set this to the last page
echo "<div class='center'>";
echo "<form action=$returnUrl method='POST'>";
echo "<input class='center' id='returnstore' type='submit' value='Return to store'/>";
echo "</form>";
echo "</div>";
</code></pre> |
15,556,725 | Start Service on boot but not entire Android app | <p>I am working with Android.</p>
<p>I have an app I am working on uses an Activity to setup specific user input values that are then used by a service to provide alerts based on those values. Doing the research I determined how I could get the app to start up when the phone boots, however, what I really want is to have the service start but not have the app load to the screen. Currently the entire app loads to the screen when I turn on the device and then I have to exit out of it. </p>
<p>I have downloaded similar programs that have interfaces for settings but otherwise run in the background. How is that done?</p> | 15,560,264 | 1 | 4 | null | 2013-03-21 19:50:04.167 UTC | 8 | 2013-03-21 23:49:23.603 UTC | 2013-03-21 20:08:00.603 UTC | null | 2,196,720 | null | 2,196,720 | null | 1 | 6 | android|service|background|startup | 7,666 | <p>First you have to create a receiver:</p>
<pre><code>public class BootCompletedReceiver extends BroadcastReceiver {
final static String TAG = "BootCompletedReceiver";
@Override
public void onReceive(Context context, Intent arg1) {
Log.w(TAG, "starting service...");
context.startService(new Intent(context, YourService.class));
}
}
</code></pre>
<p>Then add permission to your AndroidManifest.xml:</p>
<pre><code><uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</code></pre>
<p>and register intent receiver:</p>
<pre><code><receiver android:name=".BootCompletedReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</code></pre>
<p>After this is done, your application (<code>Application</code> class) will run along with services, but no Activities.</p>
<p>Ah, and don't put your application on SD card (APP2SD or something like that), because it has to reside in the main memory to be available right after the boot is completed.</p> |
15,540,806 | Getting sql connection string from web.config file | <p>I am learning to write into a database from a textbox with the click of a button. I have specified the connection string to my NorthWind database in my <code>web.config</code> file. However I am not able to access the connection string in my code behind. </p>
<p>This is what I have tried.</p>
<pre><code>protected void buttontb_click(object sender, EventArgs e)
{
System.Configuration.Configuration rootwebconfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Mohtisham");
System.Configuration.ConnectionStringSettings constring;
constring = rootwebconfig.ConnectionStrings.ConnectionStrings["northwindconnect"];
SqlConnection sql = new SqlConnection(constring);
sql.Open();
SqlCommand comm = new SqlCommand("Insert into categories (categoryName) values ('" + tb_database.Text + "')", sql);
comm.ExecuteNonQuery();
sql.Close();
}
</code></pre>
<p>I get a tooltip error for </p>
<pre><code>SqlConnection sql = new SqlConnection(constring);
</code></pre>
<p>as</p>
<blockquote>
<p><em>System.data.SqlClient.Sqlconnection.Sqlconnection(string) has some invalid arguments.</em></p>
</blockquote>
<p>I want to load the connection string from the <code>web.config</code> in <code>constring</code></p> | 15,540,847 | 4 | 4 | null | 2013-03-21 06:25:06.067 UTC | 2 | 2013-03-21 06:39:20.283 UTC | 2013-03-21 06:27:38.237 UTC | null | 13,302 | null | 1,851,048 | null | 1 | 12 | c#|asp.net|sql-server|web-config|connection-string | 42,770 | <p>That's because the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.connectionstringsettingscollection.aspx" rel="noreferrer"><code>ConnectionStrings</code></a> collection is a collection of <a href="http://msdn.microsoft.com/en-us/library/system.configuration.connectionstringsettings.aspx" rel="noreferrer"><code>ConnectionStringSettings</code></a> objects, but the <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.aspx" rel="noreferrer"><code>SqlConnection</code></a> constructor expects a <code>string</code> parameter. So you can't just pass in <code>constring</code> by itself.</p>
<p>Try this instead.</p>
<pre><code>SqlConnection sql = new SqlConnection(constring.ConnectionString);
</code></pre> |
40,177,250 | In Firebase after uploading Image how can I get Url? | <p>Right now, I'm fetching image from storage of Firebase by using below code:</p>
<pre><code>mStoreRef.child("photos/" + model.getBase64Image())
.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
// Got the download URL for 'photos/profile.png'
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
Toast.makeTextthis, "image not dowloaded", Toast.LENGTH_SHORT).show();
}
});
</code></pre>
<p><a href="https://i.stack.imgur.com/QVqET.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QVqET.png" alt="How to get this URL ?" /></a></p>
<p>Is it possible to get this URL which is shown in image?</p> | 42,444,292 | 12 | 6 | null | 2016-10-21 12:55:20.653 UTC | 14 | 2021-07-31 08:06:42.753 UTC | 2021-07-31 08:06:42.753 UTC | null | 466,862 | null | 5,155,422 | null | 1 | 30 | java|android|firebase|firebase-storage | 127,800 | <p>Follow this link -<a href="https://firebase.google.com/docs/storage/android/download-files#download_data_via_url" rel="noreferrer">https://firebase.google.com/docs/storage/android/download-files#download_data_via_url</a> </p>
<pre><code> storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png'
Uri downloadUri = taskSnapshot.getMetadata().getDownloadUrl();
generatedFilePath = downloadUri.toString(); /// The string(file link) that you need
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});
</code></pre> |
27,886,024 | Lazy Var vs Let | <p>I want to use Lazy initialization for some of my properties in Swift.
My current code looks like this:</p>
<pre><code>lazy var fontSize : CGFloat = {
if (someCase) {
return CGFloat(30)
} else {
return CGFloat(17)
}
}()
</code></pre>
<p>The thing is that once the fontSize is set it will NEVER change.
So I wanted to do something like this:</p>
<pre><code>lazy let fontSize : CGFloat = {
if (someCase) {
return CGFloat(30)
} else {
return CGFloat(17)
}
}()
</code></pre>
<p>Which is impossible.</p>
<p>Only this works:</p>
<pre><code>let fontSize : CGFloat = {
if (someCase) {
return CGFloat(30)
} else {
return CGFloat(17)
}
}()
</code></pre>
<p>So - I want a property that will be lazy loaded but will never change.
What is the correct way to do that? using <code>let</code> and forget about the lazy init? Or should I use <code>lazy var</code> and forget about the constant nature of the property?</p> | 28,444,671 | 4 | 2 | null | 2015-01-11 10:24:51.397 UTC | 6 | 2019-10-15 16:38:29.813 UTC | 2015-08-07 12:27:55.647 UTC | null | 126,855 | null | 915,824 | null | 1 | 51 | swift|var|lazy-initialization|let | 26,622 | <p>This is the latest scripture from the <a href="http://adcdownload.apple.com//Developer_Tools/Xcode_6.3_beta/Xcode_6.3_beta_Release_Notes.pdf">Xcode 6.3 Beta / Swift 1.2 release notes</a>: </p>
<blockquote>
<p>let constants have been generalized to no longer require immediate
initialization. The new rule is that a let constant must be
initialized before use (like a var), and that it may only be
initialized: not reassigned or mutated after initialization. </p>
<p>This enables patterns like:</p>
</blockquote>
<pre><code>let x: SomeThing
if condition {
x = foo()
} else {
x = bar()
}
use(x)
</code></pre>
<blockquote>
<p>which formerly required the use of a var, even though there is no
mutation taking place. (16181314)</p>
</blockquote>
<p>Evidently you were not the only person frustrated by this.</p> |
5,228,238 | Rails - How to send an image from a controller | <p>in my rails app, I need to pass back a image.</p>
<p>I have a 1x1.gif tracking pixel in my route as follows:</p>
<pre><code> match "/_ctrack.gif" => "email_tracking_pixels#my_method"
</code></pre>
<p>In the controller:</p>
<pre><code>def my_method
send_data open('https://www.xxxxxx.com/images/1x1_transparent.gif') {|f| f.read }, :filename => '1x1_transparent.gif', :type => 'image/gif'
end
</code></pre>
<p>The problem is that for some reason sometimes this times outs. with the following error:</p>
<pre><code>2011-03-07T20:08:36-08:00 heroku[router]: Error H12 (Request timeout) -> GET www.xxxxxxx.com/images/1x1_transparent.gif dyno=web.1 queue=0 wait=0ms service=0ms bytes=0
2011-03-07T20:08:36-08:00 app[web.1]:
2011-03-07T20:08:36-08:00 app[web.1]: OpenURI::HTTPError (503 Service Unavailable):
2011-03-07T20:08:36-08:00 app[web.1]: app/controllers/email_tracking_pixels_controller.rb:19:in `my_method'
2011-03-07T20:08:36-08:00 app[web.1]: lib/rack/www.rb:7:in `call'
</code></pre>
<p>Any ideas on how I can pass this image that's stored locally, versus having to use open and make a web call back to my own server?</p>
<p>Thanks</p> | 5,228,259 | 2 | 0 | null | 2011-03-08 04:10:45.523 UTC | 10 | 2012-02-21 19:23:42.627 UTC | null | null | null | null | 149,080 | null | 1 | 20 | ruby-on-rails|ruby-on-rails-3|open-uri | 18,132 | <p>Is there a reason that you cannot save the file to <code>public/_ctrack.gif</code>, remove the route, and let the underlying web server serve the image?</p>
<p>If you need to process the image from disk, just use <a href="http://www.ruby-doc.org/core/classes/Kernel.html#M001399"><code>open</code></a> on the local filename:</p>
<pre><code>send_data open("#{Rails.root}/path/to/file.gif", "rb") { |f| f.read } .......
</code></pre>
<p>The <code>rb</code> sets the file to <code>open</code> and <code>binary</code> modes.</p> |
4,933,143 | JSESSIONID Cookie with Expiration Date in Tomcat | <p>What's the best way to set an expiration date for the JSESSIONID cookie sent by Tomcat for a servlet session? </p>
<p>By default, the expiration date of the cookie seems to be 'session', which means that the session disappears in the client as soon as the browser restarts. But I would like to keep it open for 12h, even after a browser restart (and would then configure the session timeout in the server accordingly). </p>
<p>Is there any way to set an expiration date within Tomcat, e.g. using some configuration option or extension module? Or is there a reliable way to set an expiration date for JSESSIONID using a Servlet filter?</p> | 9,892,025 | 2 | 0 | null | 2011-02-08 12:42:47.133 UTC | 9 | 2018-12-12 14:04:42.983 UTC | 2011-02-08 13:14:07.273 UTC | null | 49,553 | null | 49,553 | null | 1 | 28 | session|tomcat|servlets|cookies|jsessionid | 39,102 | <p>As of Servlet 3.0, this can simply be specified in the web.xml:</p>
<pre><code><session-config>
<session-timeout>720</session-timeout> <!-- 720 minutes = 12 hours -->
<cookie-config>
<max-age>43200</max-age> <!-- 43200 seconds = 12 hours -->
</cookie-config>
</session-config>
</code></pre>
<p>Note that <code>session-timeout</code> is measured in minutes but <code>max-age</code> is measured in seconds.</p> |
506,705 | How can I get the classname from a static call in an extended PHP class? | <p>I have two classes: <code>Action</code> and <code>MyAction</code>. The latter is declared as:</p>
<pre><code>class MyAction extends Action {/* some methods here */}
</code></pre>
<p>All I need is method in the <code>Action</code> class (only in it, because there will be a lot of inherited classes, and I don’t want to implement this method in all of them), which will return classname from a static call. Here is what I’m talking about:</p>
<pre><code>Class Action {
function n(){/* something */}
}
</code></pre>
<p>And when I call it:</p>
<pre><code>MyAction::n(); // it should return "MyAction"
</code></pre>
<p>But each declaration in the parent class has access only to the parent class <code>__CLASS__</code> variable, which has the value “Action”.</p>
<p>Is there any possible way to do this?</p> | 506,737 | 7 | 0 | null | 2009-02-03 11:04:21.033 UTC | 10 | 2020-08-22 14:15:00.623 UTC | 2014-07-22 17:03:28.207 UTC | null | 209,139 | Anton | 61,876 | null | 1 | 97 | php|oop|inheritance | 69,668 | <p><code>__CLASS__</code> always returns the name of the class in which it was used, so it's not much help with a static method. If the method wasn't static you could simply use <a href="http://php.net/get_class" rel="noreferrer">get_class</a>($this). e.g.</p>
<pre><code>class Action {
public function n(){
echo get_class($this);
}
}
class MyAction extends Action {
}
$foo=new MyAction;
$foo->n(); //displays 'MyAction'
</code></pre>
<h2>Late static bindings, available in PHP 5.3+</h2>
<p>Now that PHP 5.3 is released, you can use <a href="http://php.net/oop5.late-static-bindings" rel="noreferrer">late static bindings</a>, which let you resolve the target class for a static method call at runtime rather than when it is defined.</p>
<p>While the feature does not introduce a new magic constant to tell you the classname you were called through, it does provide a new function, <a href="http://php.net/get_called_class" rel="noreferrer">get_called_class()</a> which can tell you the name of the class a static method was called in. Here's an example:</p>
<pre><code>Class Action {
public static function n() {
return get_called_class();
}
}
class MyAction extends Action {
}
echo MyAction::n(); //displays MyAction
</code></pre> |
744,256 | Reading Huge File in Python | <p>I have a 384MB text file with 50 million lines. Each line contains 2 space-separated integers: a key and a value. The file is sorted by key. I need an efficient way of looking up the values of a list of about 200 keys in Python.</p>
<p>My current approach is included below. It takes 30 seconds. There must be more efficient Python foo to get this down to a reasonable efficiency of a couple of seconds at most.</p>
<pre><code># list contains a sorted list of the keys we need to lookup
# there is a sentinel at the end of list to simplify the code
# we use pointer to iterate through the list of keys
for line in fin:
line = map(int, line.split())
while line[0] == list[pointer].key:
list[pointer].value = line[1]
pointer += 1
while line[0] > list[pointer].key:
pointer += 1
if pointer >= len(list) - 1:
break # end of list; -1 is due to sentinel
</code></pre>
<p>Coded binary search + seek solution (thanks kigurai!):</p>
<pre><code>entries = 24935502 # number of entries
width = 18 # fixed width of an entry in the file padded with spaces
# at the end of each line
for i, search in enumerate(list): # list contains the list of search keys
left, right = 0, entries-1
key = None
while key != search and left <= right:
mid = (left + right) / 2
fin.seek(mid * width)
key, value = map(int, fin.readline().split())
if search > key:
left = mid + 1
else:
right = mid - 1
if key != search:
value = None # for when search key is not found
search.result = value # store the result of the search
</code></pre> | 744,284 | 8 | 1 | null | 2009-04-13 15:28:04.29 UTC | 9 | 2010-03-14 20:25:29.373 UTC | 2010-03-14 20:25:29.373 UTC | null | 164,901 | null | 89,806 | null | 1 | 13 | python|performance|file-io|large-files | 10,334 | <p>If you only need 200 of 50 million lines, then reading all of it into memory is a waste. I would sort the list of search keys and then apply binary search to the file using seek() or something similar. This way you would not read the entire file to memory which I think should speed things up.</p> |
563,035 | Can I pass custom data in the HTTP header? | <p>I have a whole bunch of web services each with several web methods. The consumers of these services are varied and many. I want to augment each of these web methods with an extra optional parameter (Int64 or Int32) but adding new methods with this extra (optional parameter) is a lot of work and getting the clients to use the new methods will be even more time consuming.</p>
<p>So I was wondering if I could allow the clients that wanted to take advantage of the new feature that this param provides could pass this Int in the HTTP header or some other way.</p>
<p>So the first question is can I pass an int in the HTTP header? If so, how would one do that in C#/ASP.NET?</p>
<p>Otherwise, what other suggestions do you have for tackling this problem?</p> | 563,087 | 8 | 0 | null | 2009-02-18 22:01:13.717 UTC | 3 | 2021-06-17 16:43:17.78 UTC | null | null | null | Guy | 1,463 | null | 1 | 22 | http-headers | 40,174 | <p>Its a bit unorthodox and I'm sure some purists would be upset at the idea (the headers should only be used for the transport of the message, and should not contain the semantics of the message).</p>
<p>Practically its doable, but you want to be sure all your clients can add these headers. If your clients are using tools to call the web methods rather than generating the HTTP requests themselves (which I'd hope is the case) then there's a real chance this is a problem.</p>
<p>Why is it so hard to add these additional overloads of the methods?</p> |
23,689 | Natural language date/time parser for .NET? | <p>Does anyone know of a .NET date/time parser similar to <a href="http://chronic.rubyforge.org/" rel="noreferrer">Chronic for Ruby</a> (handles stuff like "tomorrow" or "3pm next thursday")?</p>
<p>Note: I do write Ruby (which is how I know about Chronic) but this project must use .NET.</p> | 631,134 | 9 | 2 | null | 2008-08-22 22:45:10.79 UTC | 10 | 2015-08-01 09:41:49.043 UTC | null | null | null | palmsey | 521 | null | 1 | 27 | .net|datetime|nlp | 5,918 | <p>We developed exactly what you are looking for on an internal project. We are thinking of making this public if there is sufficient need for it. Take a look at this blog for more details: <a href="http://precisionsoftwaredesign.com/blog.php" rel="noreferrer">http://precisionsoftwaredesign.com/blog.php</a>.</p>
<p>Feel free to contact me if you are interested: [email protected]</p>
<p>This library is now a SourceForge project. The page is at:</p>
<p><a href="http://www.SourceForge.net/p/naturaldate" rel="noreferrer">http://www.SourceForge.net/p/naturaldate</a></p>
<p>The assembly is in the downloads section, and the source is available with Mercurial. </p> |
615,738 | Adding MS-Word-like comments in LaTeX | <p>I need a way to add text comments in "Word style" to a Latex document. I don't mean to comment the source code of the document. What I want is a way to add corrections, suggestions, etc. to the document, so that they don't interrupt the text flow, but that would still make it easy for everyone to know, which part of the sentence they are related to. They should also "disappear" when compiling the document for printing.</p>
<p>At first, I thought about writing a new command, that would just forward the input to <code>\marginpar{}</code>, and when compiling for printing would just make the definition empty. The problem is you have no guarantee where the comments will appear and you will not be able to distinguish them from the other <code>marginpars</code>.</p>
<p>Any idea?</p> | 616,900 | 9 | 3 | null | 2009-03-05 17:22:19.833 UTC | 16 | 2019-10-23 08:08:36.227 UTC | 2018-11-15 14:59:49.17 UTC | dmckee | 5,457,466 | Mouk | 60,795 | null | 1 | 36 | latex|ms-word|comments | 24,755 | <p><a href="http://ctan.org/pkg/todonotes" rel="noreferrer"><code>todonotes</code></a> is another package that makes nice looking callouts. You can see a number of examples in the <a href="http://tug.ctan.org/tex-archive/macros/latex/contrib/todonotes/todonotes.pdf" rel="noreferrer">documentation</a>.</p> |
757,649 | Is there an iPhone SDK API for twitter? | <p>mobclix.com has an API for integrating with facebook.com. Is there something similar for twitter.com and other social services? Meaning, these will look like native parts of your app?</p> | 757,694 | 10 | 1 | null | 2009-04-16 19:20:44.64 UTC | 14 | 2012-11-27 01:18:42.067 UTC | null | null | null | null | 40,106 | null | 1 | 15 | objective-c|iphone | 36,663 | <p>Try <a href="http://mattgemmell.com/2008/02/22/mgtwitterengine-twitter-from-cocoa" rel="noreferrer">MGTwitterEngine</a></p> |
497,241 | How do I perform a GROUP BY on an aliased column in SQL Server? | <p>I'm trying to perform a <em>group by</em> action on an aliased column (example below) but can't determine the proper syntax.</p>
<pre><code>SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY 'FullName'
</code></pre>
<p>What is the correct syntax?</p>
<p>Extending the question further (I had not expected the answers I had received) would the solution still apply for a CASEed aliased column?</p>
<pre><code>SELECT
CASE
WHEN LastName IS NULL THEN FirstName
WHEN LastName IS NOT NULL THEN LastName + ', ' + FirstName
END AS 'FullName'
FROM customers
GROUP BY
LastName, FirstName
</code></pre>
<p>And the answer is yes it does still apply.</p> | 497,251 | 12 | 0 | null | 2009-01-30 21:05:35.38 UTC | 19 | 2022-01-18 21:45:35.957 UTC | 2022-01-18 21:45:35.957 UTC | LFSR Consulting | 1,127,428 | LFSR Consulting | 33,226 | null | 1 | 81 | sql|sql-server|tsql|syntax | 150,697 | <p>You pass the expression you want to group by rather than the alias </p>
<pre><code>SELECT LastName + ', ' + FirstName AS 'FullName'
FROM customers
GROUP BY LastName + ', ' + FirstName
</code></pre> |
154,314 | When should one use final for method parameters and local variables? | <p>I've found a couple of references (<a href="http://www.javapractices.com/topic/TopicAction.do?Id=23" rel="noreferrer">for example</a>) that suggest using <code>final</code> as much as possible and I'm wondering how important that is. This is mainly in the the context of method parameters and local variables, not final methods or classes. For constants, it makes obvious sense.</p>
<p>On one hand, the compiler can make some optimizations and it makes the programmer's intent clearer. On the other hand, it adds verbosity and the optimizations may be trivial.</p>
<p>Is it something I should make an effort to remember?</p> | 154,510 | 15 | 4 | null | 2008-09-30 18:25:04.33 UTC | 67 | 2020-01-15 00:14:01.307 UTC | 2019-03-21 00:10:33.513 UTC | Alex Miller | 2,361,308 | null | 23,669 | null | 1 | 191 | java|final | 61,325 | <p>Obsess over:</p>
<ul>
<li>Final fields - Marking fields as final forces them to be set by end of construction, making that field reference immutable. This allows safe publication of fields and can avoid the need for synchronization on later reads. (Note that for an object reference, only the field reference is immutable - things that object reference refers to can still change and that affects the immutability.)</li>
<li>Final static fields - Although I use enums now for many of the cases where I used to use static final fields.</li>
</ul>
<p>Consider but use judiciously:</p>
<ul>
<li>Final classes - Framework/API design is the only case where I consider it.</li>
<li>Final methods - Basically same as final classes. If you're using template method patterns like crazy and marking stuff final, you're probably relying too much on inheritance and not enough on delegation. </li>
</ul>
<p>Ignore unless feeling anal:</p>
<ul>
<li><p>Method parameters and local variables - I RARELY do this largely because I'm lazy and I find it clutters the code. I will fully admit that marking parameters and local variables that I'm not going to modify is "righter". I wish it was the default. But it isn't and I find the code more difficult to understand with finals all over. If I'm in someone else's code, I'm not going to pull them out but if I'm writing new code I won't put them in. One exception is the case where you have to mark something final so you can access it from within an anonymous inner class. </p></li>
<li><p>Edit: note that one use case where final local variables are actually very useful as mentioned by <a href="https://stackoverflow.com/a/18856192/2750743">@adam-gent</a> is when value gets assigned to the var in the <code>if</code>/<code>else</code> branches.</p></li>
</ul> |
1,323,704 | Which Computer Science Concept Do you Value the Most? | <p>For some reason, I notice that I end up using a lot of finite state machines at work. In particular, when I'm implementing a custom TCP/serial protocol, they are very helpful and produce a very robust output (in my opinion).</p>
<p>My days in CS classes are long behind me. As such my recollection of the stuff I learned there is fuzzy. I was curious if there are other concepts people are leveraging that I've forgotten about.</p>
<p>There is no "right" answer. Vote up the answers containing the concept you use this most. We'll simply end up with the most used concepts on top. For me, it'll be a list of stuff to study up on.</p>
<p>-Robert</p> | 1,324,126 | 44 | 9 | 2009-08-24 19:46:50.48 UTC | 2009-08-24 17:31:12.717 UTC | 25 | 2010-08-23 00:05:03.46 UTC | 2009-08-25 19:08:00.94 UTC | null | 20,471 | null | 108,958 | null | 1 | 22 | computer-science | 3,690 | <p>Strive for <strong><a href="http://www.codeodor.com/index.cfm/2009/6/17/Strive-for-low-coupling-and-high-cohesion-What-does-that-even-mean/2902">low coupling, high cohesion</a></strong>.</p>
<p><a href="http://www.codeodor.com/images/from_spaghetti_code_to_better_code.jpg">low coupling, high cohesion http://www.codeodor.com/images/from_spaghetti_code_to_better_code.jpg</a></p>
<p>(I stole this image from the website linked above)</p> |
6,534,535 | Best way to store small UI user preferences in web app? | <p>I have a web app I'm developing and quite like the idea that if the user makes changes to the view of the UI (eg. Lists open or closed, certain viewing preferences) those changes remain after they close the browser and visit the web app at a later date.</p>
<p><strong>Possible options I can think of:</strong></p>
<ol>
<li>Store UI preferences JSON object in cookie.</li>
<li>Use HTML5 local storage (no experience of this)</li>
<li>Store in mySQL database (not keen on storing such trivial data in the DB)</li>
</ol>
<p>Once stored I will retrieve these preferences when the user returns and set the UI as it was when they last left it.</p>
<p><strong>Does anyone have any experience of this type of feature and can suggest the best method for UI state save and retrieval?</strong></p> | 6,534,582 | 4 | 0 | null | 2011-06-30 12:13:56.957 UTC | 13 | 2017-05-10 10:07:28.483 UTC | null | null | null | null | 516,629 | null | 1 | 45 | javascript|jquery|web-applications|cookies|local-storage | 23,579 | <p>If it's so small you should probably store the UI settings json object in your own database. </p>
<p>That will leave users with less problems at their end, like cache clearance and local storage unsupported browsers.</p>
<p>It will also make it possible for users to use the UI settings across different computers or browsers.</p> |
6,601,536 | iOS Voip Socket will not run in background | <p>I am getting a VOIP socket to run in the background in an iOS application.</p>
<p>My connection works fine, but it won't wake up when my app goes into the background. If I open the app back up, though, it responds to any messages it got while it was asleep.</p>
<p>I set up my stream like this:</p>
<pre><code>CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
(CFStringRef) @"test.iusealocaltestserver.com",
5060,
&myReadStream,
&myWriteStream);
CFReadStreamSetProperty ( myReadStream,
kCFStreamNetworkServiceType,
kCFStreamNetworkServiceTypeVoIP
);
CFSocketNativeHandle native;
CFDataRef nativeProp = CFReadStreamCopyProperty(myReadStream, kCFStreamPropertySocketNativeHandle);
CFDataGetBytes(nativeProp, CFRangeMake(0, CFDataGetLength(nativeProp)), (UInt8 *)&native);
CFRelease(nativeProp);
CFSocketRef theSocket = CFSocketCreateWithNative(kCFAllocatorDefault, native, 0, NULL, NULL);
CFSocketGetContext(theSocket,&theContext);
CFOptionFlags readStreamEvents = kCFStreamEventHasBytesAvailable |
kCFStreamEventErrorOccurred |
kCFStreamEventEndEncountered |
kCFStreamEventOpenCompleted;
CFReadStreamSetClient(myReadStream,
readStreamEvents,
(CFReadStreamClientCallBack)&MyCFReadStreamCallback,
(CFStreamClientContext *)(&theContext));
CFReadStreamScheduleWithRunLoop(myReadStream, CFRunLoopGetCurrent(),
kCFRunLoopCommonModes);
</code></pre>
<p>Then my callback is set up like this:</p>
<pre><code>static void MyCFReadStreamCallback(CFReadStreamRef stream, CFStreamEventType type, void *pInfo);
static void MyCFReadStreamCallback (CFReadStreamRef stream, CFStreamEventType type, void *pInfo)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSLog(@"Callback Happened");
[pool release];
}
</code></pre>
<p>"Callback Happened" is getting called when I receive data and the app is open, but it doesn't if the app is minimized. When the app comes back up, though, it processes any data it received while minimized. </p>
<p>I added the voip tag to the info.plist. My CFReadStreamSetProperty returns true. I am running on a device not a simulator. It still doesn't work though, so I dont know what my problem could be. I probably just did something silly, but there's almost nothing online to check my code against.</p>
<p>EDIT: I can't test any of the answers because I am no longer working on this project and don't have access to a mac/iOs sdk. If someone with a similar problem found one of the below answers useful, let me know and I will vote it best answer.</p> | 7,393,083 | 5 | 5 | null | 2011-07-06 18:59:02.51 UTC | 31 | 2012-08-31 10:51:51.593 UTC | 2011-08-15 16:09:11.457 UTC | null | 774,808 | null | 774,808 | null | 1 | 21 | objective-c|ios4|voip|background-process|cfreadstream | 26,758 | <p>If you want to let your VOIP application run in background , except those base settings in plist file, you need a TCP socket who's property is set to VOIP, than the iOS system will take care this socket for you, when your application enter background , every thing was 'sleep' except that tcp socket. and if VOIP server send some data thought that TCP socket, your application will be awake up for 10 secs. during this time, you can post a local notification.</p>
<p>Only Tcp socket can be set as VOIP Socket. But from i know , mostly VOIP application are based on UDP socket. if you do not want to separate the control socket from the data socket. you should create another tcp socket which is focus on 'awake' your application , and from my personal experience , it's very hard to keep this 'awake' signal and the real sip control signal synchronize, the application always miss the sip invite request. </p>
<p>So,the best way is separating the sip control single from the UDP data socket , make it as a tcp socket , this is the best solution , but never use tcp socket to transfer voice data. </p>
<p>Another dirty way: keep the application awake all the time.
As i said , each TCP single the application received thought that 'VOIP' tcp socket , will keep application awake for 10 seconds, so at the end of this duration(after 9 secs) , you can send a response to the server to ask for another signal , when the next signal arrived, the application will be awake again,after 9 secs , send response again. keep doing this, your application will awake forever.</p> |
6,331,504 | Omitting the double quote to do query on PostgreSQL | <p>Simple question, is there any way to omit the double quote in PostgreSQL?</p>
<p>Here is an example, giving <code>select * from A;</code>, I will retrieve <code>ERROR: relation "a" does not exist</code>, and I would have to give <code>select * from "A";</code> to get the real result.</p>
<p>Is there any way not to do the second and instead do the first on PostgreSQL?</p> | 6,331,658 | 5 | 0 | null | 2011-06-13 14:05:30.463 UTC | 6 | 2019-03-12 19:58:21.153 UTC | null | null | null | null | 491,748 | null | 1 | 66 | postgresql|double-quotes | 59,835 | <p>Your problem with this query started when you created your table. When you create your table, don't use quotes.</p>
<p>Use this:</p>
<pre><code>CREATE TABLE a ( ... );
</code></pre>
<p>Not this:</p>
<pre><code>CREATE TABLE "A" ( ... );
</code></pre>
<p>The latter will make it so that you always have to quote it later. The former makes it a normal name and you can use <code>SELECT * FROM a;</code> or <code>SELECT * FROM A;</code></p>
<p>If you can't just recreate your table, use the <code>ALTER TABLE</code> syntax:</p>
<pre><code>ALTER TABLE "A" RENAME TO a;
</code></pre> |
6,966,772 | Using the __call__ method of a metaclass instead of __new__? | <p>When discussing metaclasses, <a href="http://docs.python.org/reference/datamodel.html" rel="noreferrer">the docs</a> state:</p>
<blockquote>
<p>You can of course also override other class methods (or add new
methods); for example defining a custom <code>__call__()</code> method in the
metaclass allows custom behavior when the class is called, e.g. not
always creating a new instance.</p>
</blockquote>
<p><em>[Editor's note: This was removed from the docs in 3.3. It's here in 3.2: <a href="https://docs.python.org/3.2/reference/datamodel.html#customizing-class-creation" rel="noreferrer">Customizing class creation</a>]</em></p>
<p>My questions is: suppose I want to have custom behavior when the class is called, for example caching instead of creating fresh objects. I can do this by overriding the <code>__new__</code> method of the class. When would I want to define a metaclass with <code>__call__</code> instead? What does this approach give that isn't achievable with <code>__new__</code>?</p> | 6,966,942 | 6 | 2 | null | 2011-08-06 12:28:37.333 UTC | 32 | 2022-05-12 21:21:10.71 UTC | 2022-01-17 21:14:29.647 UTC | null | 4,518,341 | null | 8,206 | null | 1 | 69 | python|oop|metaclass | 29,493 | <p>The direct answer to your question is: when you want to do <strong>more</strong> than just customize instance creation, or when you want to separate what the class <strong>does</strong> from how it's created.</p>
<p>See my answer to <a href="https://stackoverflow.com/questions/6760685/creating-a-singleton-in-python">Creating a singleton in Python</a> and the associated discussion.</p>
<p>There are several advantages.</p>
<ol>
<li><p>It allows you to separate what the class <em>does</em> from the details of how it's created. The metaclass and class are each responsible for one thing.</p></li>
<li><p>You can write the code once in a metaclass, and use it for customizing several classes' call behavior without worrying about multiple inheritance.</p></li>
<li><p>Subclasses can override behavior in their <code>__new__</code> method, but <code>__call__</code> on a metaclass doesn't have to even call <code>__new__</code> at all.</p></li>
<li><p>If there is setup work, you can do it in the <code>__new__</code> method of the metaclass, and it only happens once, instead of every time the class is called. </p></li>
</ol>
<p>There are certainly lots of cases where customizing <code>__new__</code> works just as well if you're not worried about the single responsibility principle.</p>
<p>But there are other use cases that have to happen earlier, when the class is created, rather than when the instance is created. It's when these come in to play that a metaclass is necessary. See <a href="https://stackoverflow.com/questions/392160/what-are-your-concrete-use-cases-for-metaclasses-in-python">What are your (concrete) use-cases for metaclasses in Python?</a> for lots of great examples.</p> |
6,621,683 | How to check if an array contains empty elements? | <p>Let's make some examples:</p>
<pre><code>array("Paul", "", "Daniel") // false
array("Paul", "Daniel") // true
array("","") // false
</code></pre>
<p>What's a neat way to work around this function?</p> | 6,621,714 | 7 | 0 | null | 2011-07-08 08:08:49.8 UTC | 5 | 2021-07-08 21:48:37.213 UTC | null | null | null | null | 241,654 | null | 1 | 22 | php | 39,952 | <p>Try using <a href="http://php.net/manual/en/function.in-array.php"><code>in_array</code></a>:</p>
<pre><code>return !in_array("", array("Paul", "", "Daniel")); //returns false
</code></pre> |
6,499,268 | MongoDb connection refused | <p>This is my first attempt to consume MongoDB. I've got Mongo running:</p>
<pre><code>ps -ef | grep [m]ongo
mongodb 11023 1 0 Jun24 ? 00:00:03 /usr/lib/mongodb/mongod --config /etc/mongodb.conf
</code></pre>
<p>And the error comes as the result of doing</p>
<pre><code>Datastore.save( stuff ); // (pseudo code)
</code></pre>
<p>The error:</p>
<blockquote>
<pre><code>Jun 27, 2011 3:20:29 PM com.mongodb.DBTCPConnector fetchMaxBsonObjectSize
WARNING: Exception determining maxBSON size using0
java.io.IOException: couldn't connect to [russ-elite-book/127.0.1.1:27017] bc:java.net.ConnectException: Connection refused
at com.mongodb.DBPort._open(DBPort.java:206)
at com.mongodb.DBPort.go(DBPort.java:94)
at com.mongodb.DBPort.go(DBPort.java:75)
at com.mongodb.DBPort.findOne(DBPort.java:129)
at com.mongodb.DBPort.runCommand(DBPort.java:138)
...
</code></pre>
</blockquote>
<p>Note that I'm using <em>127.0.0.1:27017</em> for my connection, which works to the Mongo shell. Also, I get the admin page in the browser using <em><code>http://localhost:28017</code></em>.</p>
<p>Profuse thanks for any and all ideas!</p> | 6,511,920 | 9 | 0 | null | 2011-06-27 21:41:45.21 UTC | 4 | 2017-11-14 15:21:30.837 UTC | 2015-08-25 03:59:32.787 UTC | null | 4,519,059 | null | 339,736 | null | 1 | 21 | mongodb|mongodb-java | 73,792 | <p>(I think it slightly bad form to answer one's own question, but in fact, the answer turns out to be none of those suggested. Nevertheless, my profuse thanks to all of them. When answering a question, one needs to be able to assume it's based on correctly installed and working software. I did not have that.)</p>
<p>I installed MongoDB using the Ubuntu Software Center. It worked from the shell and from the browser as noted elsewhere in this question. However, it did not work from Java (nor from Django either).</p>
<p>The problem, despite what it said in the Java stack trace, was simply "connection refused."</p>
<p><strong>The solution is to install it from proper Mongo sources and not to trust the Ubuntu repository.</strong></p>
<p>(Yes, this also frequently happens to other products obtain from there too, like Eclipse, but you know it's such a nice service that you want to trust it.)</p>
<p>If you want to read how I installed what then worked, check out <a href="http://www.javahotchocolate.com/tutorials/mongodb.html">http://www.javahotchocolate.com/tutorials/mongodb.html</a>.</p> |
42,245,288 | Add new element to existing JSON array with jq | <p>I want to append an element to an array in a JSON file using the <code>jq``add</code> command, but it's not working. </p>
<p><code>report-2017-01-07.json</code> file:</p>
<pre><code>{
"report": "1.0",
"data": {
"date": "2010-01-07",
"messages": [
{
"date": "2010-01-07T19:58:42.949Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "OK",
"message": "metadata loaded into iRODS successfully"
},
{
"date": "2010-01-07T20:22:46.949Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "NOK",
"message": "metadata duplicated into iRODS"
},
{
"date": "2010-01-07T22:11:55.949Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "NOK",
"message": "metadata was not validated by XSD schema"
}
]
}
}
</code></pre>
<p>I am using this command:</p>
<pre><code>$ cat report-2017-01-07.json
| jq -s '.data.messages {"date": "2010-01-07T19:55:99.999Z", "xml": "xml_samplesheet_2017_01_07_run_09.xml", "status": "OKKK", "message": "metadata loaded into iRODS successfullyyyyy"}'
jq: error: syntax error, unexpected '{', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.data.messages {"date": "2010-01-07T19:55:99.999Z", "xml": "xml_samplesheet_2017_01_07_run_09.xml", "status": "OKKK", "message": "metadata loaded into iRODS successfullyyyyy"}
jq: 1 compile error
</code></pre>
<p>Here's how I want the output to look:</p>
<pre><code>{
"report": "1.0",
"data": {
"date": "2010-01-07",
"messages": [{
"date": "2010-01-07T19:58:42.949Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "OK",
"message": "metadata loaded into iRODS successfully"
}, {
"date": "2010-01-07T20:22:46.949Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "NOK",
"message": "metadata duplicated into iRODS"
}, {
"date": "2010-01-07T22:11:55.949Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "NOK",
"message": "metadata was not validated by XSD schema"
}, {
"date": "2010-01-07T19:55:99.999Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "OKKKKKKK",
"message": "metadata loaded into iRODS successfullyyyyy"
}]
}
}
</code></pre> | 42,248,841 | 3 | 5 | null | 2017-02-15 09:24:32.743 UTC | 19 | 2022-02-17 12:50:58.097 UTC | 2021-02-19 04:33:07.58 UTC | null | 997,358 | null | 2,096,986 | null | 1 | 94 | arrays|json|bash|jq | 144,120 | <p>The <code>|= .+</code> part in the filter adds a new element to the existing array. You can use <code>jq</code> with filter like:</p>
<pre><code>jq '.data.messages[3] |= . + {"date": "2010-01-07T19:55:99.999Z", "xml": "xml_samplesheet_2017_01_07_run_09.xml", "status": "OKKK", "message": "metadata loaded into iRODS successfullyyyyy"}' inputJson
</code></pre>
<p>To avoid using the hardcoded length value <code>3</code> and dynamically add a new element, use <code>. | length</code> which returns the length, which can be used as the next array index, i.e.,</p>
<pre><code>jq '.data.messages[.data.messages| length] |= . + {"date": "2010-01-07T19:55:99.999Z", "xml": "xml_samplesheet_2017_01_07_run_09.xml", "status": "OKKK", "message": "metadata loaded into iRODS successfullyyyyy"}' inputJson
</code></pre>
<p>(or) as per peak's suggestion in the comments, using the <code>+=</code> operator alone</p>
<pre><code>jq '.data.messages += [{"date": "2010-01-07T19:55:99.999Z", "xml": "xml_samplesheet_2017_01_07_run_09.xml", "status": "OKKK", "message": "metadata loaded into iRODS successfullyyyyy"}]'
</code></pre>
<p>which produces the output you need:</p>
<pre><code>{
"report": "1.0",
"data": {
"date": "2010-01-07",
"messages": [
{
"date": "2010-01-07T19:58:42.949Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "OK",
"message": "metadata loaded into iRODS successfully"
},
{
"date": "2010-01-07T20:22:46.949Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "NOK",
"message": "metadata duplicated into iRODS"
},
{
"date": "2010-01-07T22:11:55.949Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "NOK",
"message": "metadata was not validated by XSD schema"
},
{
"date": "2010-01-07T19:55:99.999Z",
"xml": "xml_samplesheet_2017_01_07_run_09.xml",
"status": "OKKK",
"message": "metadata loaded into iRODS successfullyyyyy"
}
]
}
}
</code></pre>
<p>Use <a href="https://jqplay.org/" rel="noreferrer">jq-play</a> to dry-run your <code>jq-filter</code> and optimize any way you want.</p> |
42,223,587 | Plt.Scatter: How to add title and xlabel and ylabel | <p>Is there a way to add title (and xlabel and ylabel) to plt.scatter(x,y,...) or plt.plot(x,y,...) directly without writing additional lines? </p>
<p>It is easy to add it when we use Series_name.plot in which we simply write Series_name.plot(...,title='name') but it does not work for me if I write: plt.scatter(...,title='name') or plt.plot(...,title='name')</p>
<p>[plt<< import matplotlib.pyplot as plt]</p>
<p>I am using Python 3.</p> | 42,223,679 | 3 | 9 | null | 2017-02-14 10:23:46.763 UTC | 7 | 2020-04-13 14:08:24.347 UTC | 2017-02-14 11:42:25.65 UTC | null | 7,467,432 | null | 7,467,432 | null | 1 | 36 | python|matplotlib|plot | 129,020 | <p>From the documentation of <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter" rel="noreferrer"><code>plt.scatter()</code></a> there is no such arguments to set the title or labels. </p>
<p>But neither does the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot" rel="noreferrer"><code>plt.plot()</code></a> command have such arguments. <code>plt.plot(x,y, title="title")</code> throws an error <code>AttributeError: Unknown property title</code>. So I wonder why this should work in either case.</p>
<p>In any case, the usual way to set the title is <code>plt.title</code>. The usual way to set the labels is <code>plt.xlabel</code>and <code>plt.ylabel</code>.</p>
<pre><code>import matplotlib.pyplot as plt
x= [8,3,5]; y = [3,4,5]
plt.scatter(x,y)
plt.title("title")
plt.xlabel("x-label")
plt.ylabel("y-label")
plt.show()
</code></pre> |
38,141,951 | Why does scipy.norm.pdf sometimes give PDF > 1? How to correct it? | <p>Given mean and variance of a Gaussian (normal) random variable, I would like to compute its probability density function (PDF). </p>
<p><a href="https://i.stack.imgur.com/XwgLg.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/XwgLg.gif" alt="enter image description here"></a></p>
<p>I referred this post: <a href="https://stackoverflow.com/questions/12412895/calculate-probability-in-normal-distribution-given-mean-std-in-python">Calculate probability in normal distribution given mean, std in Python</a>,</p>
<p>Also the scipy docs: <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html#scipy.stats.norm" rel="noreferrer">scipy.stats.norm</a></p>
<p>But when I plot a PDF of a curve, the probability exceeds 1! Refer to this minimum working example:</p>
<pre class="lang-python prettyprint-override"><code>import numpy as np
import scipy.stats as stats
x = np.linspace(0.3, 1.75, 1000)
plt.plot(x, stats.norm.pdf(x, 1.075, 0.2))
plt.show()
</code></pre>
<p>This is what I get:</p>
<p><a href="https://i.stack.imgur.com/8H2Oi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8H2Oi.png" alt="Gaussian PDF Curve"></a></p>
<p>How is it even possible to have 200% probability to get the mean, 1.075? Am I misinterpreting anything here? Is there any way to correct this?</p> | 38,142,058 | 2 | 1 | null | 2016-07-01 09:34:02.233 UTC | 11 | 2020-04-26 05:32:28.327 UTC | 2017-05-23 12:01:45.9 UTC | null | -1 | null | 4,565,943 | null | 1 | 14 | python|scipy|distribution|normal-distribution | 26,733 | <p>It's not a bug. It's not an incorrect result either. Probability density function's value at some specific point does not give you probability; it is a measure of how <em>dense</em> the distribution is around that value. For continuous random variables, the probability at a given point is equal to zero. Instead of <code>p(X = x)</code>, we calculate probabilities between 2 points <code>p(x1 < X < x2)</code> and it is equal to the area below that probability density function. Probability density function's value can very well be above 1. It can even approach to infinity.</p> |
45,519,176 | How do I "use" or import a local Rust file? | <p>How do I include a file with the full path <code>my_project/src/include_me.rs</code> in <code>main.rs</code>?</p>
<p>I've checked the <a href="http://doc.crates.io/specifying-dependencies.html" rel="noreferrer">dependencies guide</a>, and all of them appear to be including a binary. I've also checked <a href="https://doc.rust-lang.org/book/second-edition/ch07-03-importing-names-with-use.html" rel="noreferrer">"The Book"</a>, but none of the examples there end in ".rs" either.</p>
<p>How do I make <code>include_me.rs</code> compile with the rest of the project?</p> | 45,520,092 | 1 | 3 | null | 2017-08-05 06:54:14.853 UTC | 21 | 2022-06-27 07:29:28.337 UTC | 2022-05-05 21:24:15.103 UTC | null | 63,550 | null | 4,808,079 | null | 1 | 65 | import|rust | 54,174 | <p>There are basically two (main) ways in Rust to include code from somewhere else:</p>
<h3>1. "Including" <em>internal</em> code</h3>
<p>If your <code>include_me.rs</code> belongs to your project, you should move it to the same folder <code>main.rs</code> lies in:</p>
<pre class="lang-none prettyprint-override"><code>└── src
├── include_me.rs
└── main.rs
</code></pre>
<p>Then you can write this in your <code>main.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>mod include_me;
fn main() {
// Call a function defined in the other file (module)
include_me::some_function();
}
</code></pre>
<p>A <code>mod</code> declaration makes the Rust compiler look for the corresponding <code>.rs</code> files automatically!</p>
<p>So everything that belongs to your project, belongs in the same folder (or a subfolder thereof) as the folder where <code>main.rs</code> (or <code>lib.rs</code>) is lying. The files are then "included" via the module system. To read a good introduction into modules, please read <a href="https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html" rel="noreferrer">the chapter on modules in the Rust book</a>. You could also check out <a href="https://doc.rust-lang.org/rust-by-example/mod.html" rel="noreferrer">Rust by Example</a> on that topic. The module system is pretty central and thus important to learning Rust.</p>
<h3>2. "Including" <em>external</em> code</h3>
<p>If your <code>include_me.rs</code> is something that doesn't belong to your actual project, but is rather a collection of useful things you are using in multiple projects, it should be seen as a <em>library</em>. To include code of such external libraries, you have to include it as an extern crate. And to make your life easier, you really want to use Cargo!</p>
<p>So let's prepare your <code>include_me.rs</code> as Cargo library project. You need the following file structure (which is automatically generated by <code>cargo new my_library --lib</code>):</p>
<pre class="lang-none prettyprint-override"><code>. my_library
├── Cargo.toml
└── src
└── lib.rs
</code></pre>
<p>Now copy all the contents from <code>include_me.rs</code> into <code>lib.rs</code> (it is just convention to call the root file of a library project <code>lib.rs</code>). Let's say that the <code>my_library</code> folder's full path is <code>~/code/my_library</code>.</p>
<p>Now let's prepare your main project's Cargo project. It has a similar file
structure (but a <code>main.rs</code> instead of <code>lib.rs</code>, because it's a executable-project, not a library-project):</p>
<pre class="lang-none prettyprint-override"><code>. my_project
├── Cargo.toml
└── src
└── main.rs
</code></pre>
<p>To declare your dependency on <code>my_library</code>, you have to put this into your <code>Cargo.toml</code>:</p>
<pre class="lang-ini prettyprint-override"><code>[package]
name = "my_project"
version = "0.1.0"
authors = ["you"]
edition = "2018"
[dependencies]
my_library = { path = "~/code/my_library" }
</code></pre>
<p>You can also use relative paths (<code>"../my_library"</code>), but it only makes sense if you know that the two projects always stay where they are, relative to one another (like if they are both managed in the same repository).</p>
<p>Now you can, in your <code>main.rs</code>, write:</p>
<pre class="lang-rust prettyprint-override"><code>use my_library::some_function;
fn main() {
// Call a function defined in the other file (extern crate)
some_function();
}
</code></pre>
<p>If you want to upload any of those two projects, you have to interact with <code>crates.io</code> (or another crates registry, if your company has one), but this is another topic.</p>
<p>(<em>Note</em>: some time ago, it was necessary to write <code>extern crate my_library;</code> inside <code>main.rs</code>. This is not necessary anymore, but you might find old code with <code>extern crate</code> declarations.)</p>
<h3>Any other ways?</h3>
<p>Yes, but you shouldn't use those. There is <a href="https://doc.rust-lang.org/stable/std/macro.include.html" rel="noreferrer">the <code>include!()</code> macro</a> which allows you to verbatim include other files, just like the <code>#include</code> from C-land. <strong>However</strong>, it is strongly discouraged to use this in situations where the module system would be able to solve your problem. <code>include!()</code> is only useful in very special situations, often linked to a more complex build system which generates code.</p> |
16,033,448 | SQL Server - GROUP BY on one column | <p>I'm trying to get orders from an orderview. In my view I do have some rows with exactly the same values, but I want to group these values on orderid and take the sum of the quantity of that order.</p>
<p>My view results something like:</p>
<pre><code> Order_id Customer_id Article_id Delivery_date Quantity
---------------------------------------------------------------------------
PR10.001 11 20.001a 17-04-2013 1
PR10.001 11 20.001a 17-04-2013 1
PR10.001 11 20.001a 17-04-2013 1
PR13.001 15 41.022b 19-04-2013 1
PR13.001 15 41.022b 19-04-2013 1
</code></pre>
<p>I want to do something like:</p>
<pre><code>SELECT Order_id, Customer_id Article_id, Delivery_date, sum(Quantity)
FROM Orders
GROUP BY Order_id
</code></pre>
<p>To get something like:</p>
<pre><code> Order_id Customer_id Article_id Delivery_date Quantity
---------------------------------------------------------------------------
PR10.001 11 20.001a 17-04-2013 3
PR13.001 15 41.022b 19-04-2013 2
</code></pre>
<p>But I know grouping by one single column is not possible, otherwise you'll get the message:</p>
<blockquote>
<p>[...] is invalid in the select list because it is not contained in
either an aggregate function or the GROUP BY clause.</p>
</blockquote>
<p>Is there another possibility or workaround to group by one specific column in SQL Server?</p> | 16,033,595 | 4 | 1 | null | 2013-04-16 09:32:17.137 UTC | 4 | 2020-07-29 13:15:18.15 UTC | 2013-04-16 09:44:55.757 UTC | null | 1,635,767 | null | 1,635,767 | null | 1 | 20 | sql-server|group-by | 86,188 | <p>You could use a <a href="http://msdn.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx"><code>CTE</code></a> with <a href="http://msdn.microsoft.com/en-us/library/ms189461.aspx"><code>SUM(Quantity)OVER(PARTITION BY Order_id)</code></a> + <a href="http://msdn.microsoft.com/en-us/library/ms186734.aspx"><code>ROW_NUMBER</code></a> to pick out the desired row from the order-group:</p>
<pre><code>WITH cte
AS (SELECT order_id,
customer_id,
article_id,
delivery_date,
quantity=Sum(quantity)
OVER(
partition BY order_id),
rn = Row_number()
OVER(
partition BY order_id
ORDER BY delivery_date ASC)
FROM orders)
SELECT order_id,
customer_id,
article_id,
delivery_date,
quantity
FROM cte
WHERE rn = 1
</code></pre>
<p><a href="http://sqlfiddle.com/#!3/c0c82/2/0"><strong>DEMO</strong></a></p>
<p><strike>However, your desired result seems to be incorrect</strike> (question edited)</p>
<p>This is my result:</p>
<pre><code>ORDER_ID CUSTOMER_ID ARTICLE_ID DELIVERY_DATE QUANTITY
PR10.001 11 20.001a 17-04-2013 3
PR13.001 15 41.022b 19-04-2013 2
</code></pre> |
15,969,948 | Use Composer without ssh access to server | <p>Is it possible to run <a href="http://getcomposer.org/" rel="noreferrer">composer</a> on a cheap webspace that can't be accessed using ssh, only ftp?</p>
<p>Running <code>system('php composer.phar install');</code> should work in theory - is that the recommended method?</p> | 17,629,907 | 2 | 2 | null | 2013-04-12 11:16:00.22 UTC | 10 | 2019-11-11 21:11:09.833 UTC | null | null | null | null | 781,662 | null | 1 | 21 | php|composer-php | 21,314 | <p>I think the best way, as suggested in the comments before, is to execute the composer step on a local system that is able to do it, and then upload the result via FTP.</p>
<p>Composer has some (probably optional) software dependencies that most likely will not be available on your webspace. For example it needs the Git and SVN client software in case the project you are about to install references such dependencies.</p>
<p>Another thing is that downloading from Github (or anywhere else) can fail. Or trigger the API limit and ask for a login.</p>
<p>You'd really want to collect all the software and know that it worked instead of hoping it will execute well remotely.</p> |
15,563,155 | Gson to json conversion with two DateFormat | <p>My server JSON is returning with two different type of DateFormat.
"MMM dd, yyyy" and "MMM dd, yyyy HH:mm:ss"</p>
<p>When I convert the JSON with the following it is fine:</p>
<pre><code>Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy").create();
</code></pre>
<p>But when I want the detailed date format and changed it to this, it throws exception com.google.gson.JsonSyntaxException: Mar 21, 2013 </p>
<pre><code>Gson gson = new GsonBuilder().setDateFormat("MMM dd, yyyy HH:mm:ss").create();
</code></pre>
<p>Is there a way for gson to handle two different DateFormat for its Json conversion?</p> | 18,337,283 | 3 | 0 | null | 2013-03-22 05:09:52.047 UTC | 11 | 2017-04-05 13:01:53.617 UTC | null | null | null | null | 1,543,498 | null | 1 | 32 | java|gson | 22,389 | <p>I was facing the same issue. Here is my solution via custom deserialization:</p>
<pre><code>new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer());
private static final String[] DATE_FORMATS = new String[] {
"MMM dd, yyyy HH:mm:ss",
"MMM dd, yyyy"
};
private class DateDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF,
JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
} catch (ParseException e) {
}
}
throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
+ "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}
}
</code></pre> |
36,229,911 | Using BottomSheetBehavior with a inner CoordinatorLayout | <p>The design support library <code>v. 23.2</code> introduced <code>BottomSheetBehavior</code>, which allows childs of a coordinator to act as bottom sheets (views draggable from the bottom of the screen).</p>
<p>What I’d like to do is to have, <strong>as a bottom sheet view</strong>, the following view (the typical coordinator + collapsing stuff):</p>
<pre><code><CoordinatorLayout
app:layout_behavior=“@string/bottom_sheet_behavior”>
<AppBarLayout>
<CollapsingToolbarLayout>
<ImageView />
</CollapsingToolbarLayout>
</AppBarLayout>
<NestedScrollView>
<LinearLayout>
< Content ... />
</LinearLayout>
</NestedScrollView>
</CoordinatorLayout>
</code></pre>
<p>Unfortunately, bottom sheet views should implement nested scrolling, or they won’t get scroll events. If you try with a main activity and then load this view as a bottom sheet, you’ll see that scroll events only act on the “sheet” of paper, with some strange behavior, as you can see if you keep reading.</p>
<p>I am pretty sure that this can be handled by subclassing <code>CoordinatorLayout</code>, or even better by subclassing <code>BottomSheetBehavior</code>. Do you have any hint?</p>
<h2>Some thoughts</h2>
<ul>
<li><p><code>requestDisallowInterceptTouchEvent()</code> should be used, to steal events from the parent in some conditions:</p>
<ul>
<li>when the <code>AppBarLayout</code> offset is > 0</li>
<li>when the <code>AppBarLayout</code> offset is == 0, but we are scrolling up (think about it for a second and you’ll see)</li>
</ul></li>
<li><p>the first condition can be obtained by setting an <code>OnOffsetChanged</code> to the inner app bar;</p></li>
<li><p>the second requires some event handling, for example:</p>
<pre><code>switch (MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN:
startY = event.getY();
lastY = startY;
userIsScrollingUp = false;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
userIsScrollingUp = false;
break;
case MotionEvent.ACTION_MOVE:
lastY = event.getY();
float yDeltaTotal = startY - lastY;
if (yDeltaTotal > touchSlop) { // Moving the finger up.
userIsScrollingUp = true;
}
break;
}
</code></pre></li>
</ul>
<h2>Issues</h2>
<p>Needless to say, I can’t make this work right now. I am not able to catch the events when the conditions are met, and not catch them in other cases. In the image below you can see what happens with a standard CoordinatorLayout:</p>
<ul>
<li><p>The sheet is dismissed if you scroll down on the appbar, but not if you scroll down on the nested content. It seems that nested scroll events are not propagated to the Coordinator behavior;</p></li>
<li><p>There is also a problem with the inner appbar: the nested scroll content does not follow the appbar when it is being collapsed..</p></li>
</ul>
<p><a href="https://i.stack.imgur.com/nZBle.gif"><img src="https://i.stack.imgur.com/nZBle.gif" alt="enter image description here"></a></p>
<p>I have setup a <a href="https://github.com/miav/BottomSheetCoordinatorLayout">sample project on github</a> that shows these issues.</p>
<h2>Just to be clear, desired behavior is:</h2>
<ul>
<li><p>Correct behavior of appbars/scroll views inside the sheet;</p></li>
<li><p>When sheet is expanded, it can collapse on scroll down, but <strong>only if the inner appbar is fully expanded too</strong>. Right now it does collapse with no regards to the appbar state, and only if you drag the appbar;</p></li>
<li><p>When sheet is collapsed, scroll up gestures will expand it (with no effect on the inner appbar).</p></li>
</ul>
<p>An example from the contacts app (which probably does not use BottomSheetBehavior, but this is what I want):</p>
<p><a href="https://i.stack.imgur.com/WWLcN.gif"><img src="https://i.stack.imgur.com/WWLcN.gif" alt="enter image description here"></a></p> | 43,528,372 | 6 | 18 | null | 2016-03-25 23:50:33.267 UTC | 23 | 2017-04-20 19:34:54.067 UTC | 2016-03-28 12:36:41.413 UTC | null | 4,288,782 | null | 4,288,782 | null | 1 | 58 | android|android-support-library|ontouchlistener|touch-event|android-support-design | 12,994 | <p>I have finally released my implementation. Find it <a href="https://github.com/natario1/BottomSheetCoordinatorLayout" rel="noreferrer">on Github</a> or directly from jcenter:</p>
<pre><code>compile 'com.otaliastudios:bottomsheetcoordinatorlayout:1.0.0’
</code></pre>
<p>All you have to do is using <code>BottomSheetCoordinatorLayout</code> as the root view for your bottom sheet. It will automatically inflate a working behavior for itself, so don’t worry about it.</p>
<p>I have been using this for a long time and it shouldn’t have scroll issues, supports dragging on the ABL etc.</p> |
50,259,025 | Using .env files for unit testing with jest | <p>Is it possible to load environment variables from an env file for unit testing purposes in Jest? I'm looking to run a series of tests on it like so:</p>
<pre><code>// unit tests for env file
describe('env', () => {
it('should have a client id', () => {
expect(process.env.CLIENT_ID).toBeDefined();
});
it('should have a client secret', () => {
expect(process.env.CLIENT_SECRET).toBeDefined();
});
it('should have a host', () => {
expect(process.env.HOST).toBeDefined();
});
it('should have a scope', () => {
expect(process.env.SCOPE).toBeDefined();
});
it('should have a response type', () => {
expect(process.env.RESPONSE_TYPE).toBeDefined();
});
it('should have a redirect uri', () => {
expect(process.env.REDIRECT_URI).toBeDefined();
});
});
</code></pre>
<p>Currently, all the above tests will fail, stating that the variables are undefined. Initially I was using a mocha/chai setup, which allowed me to just load all of my env variables via the use of dotenv. This involved running all unit tests through webpack and worked fine. </p>
<p>However, from reading the <a href="https://facebook.github.io/jest/docs/en/webpack.html" rel="noreferrer">documentation</a> Jest doesn't run tests through webpack; instead modules are mocked out via moduleNameMapper. This works fine for everything else, but I can't get the env file variables to load. So far I've tried using the setupFiles option to a js file that calls dotenv.config with the path of the env file given to it like so:</p>
<pre><code>// setup file for jest
const dotenv = require('dotenv');
dotenv.config({ path: './env' });
</code></pre>
<p>This didn't work, so I've now resorted to using just a .env.js file for unit tests and passing this file into the setupFiles option instead. However, for maintainability, and to keep it working with webpack for production, I'd like to just keep it all in one file. Here's an extract of how the .env.js file looks for reference </p>
<pre><code>// .env.js extract example
process.env.PORT = 3000;
process.env.HOST = 'localhost';
process.env.CLIENT_ID = 'your client id';
process.env.REDIRECT_URI = 'your callback endpoint';
</code></pre> | 50,270,823 | 9 | 3 | null | 2018-05-09 17:31:25.537 UTC | 12 | 2022-05-18 23:07:19.073 UTC | 2018-05-09 19:24:35.557 UTC | null | 9,450,709 | null | 9,450,709 | null | 1 | 75 | javascript|unit-testing|environment-variables|jestjs | 69,275 | <p>Your top config path using <code>./</code> is relative from the point of injection, it's likely your test suite might be inside a folder named <code>test</code> which causes it to not be found when running your unit tests. <code>dotenv.config();</code> Uses global injection strategy which is similar to absolute pathing.</p> |
50,664,648 | Why even use *DB.exec() or prepared statements in Golang? | <p>I'm using golang with Postgresql.</p>
<p>It says <a href="http://go-database-sql.org/retrieving.html" rel="noreferrer">here</a> that for operations that do not return rows (insert, delete, update) we should use <code>exec()</code></p>
<blockquote>
<p>If a function name includes Query, it is designed to ask a question of the database, and will return a set of rows, even if it’s empty. Statements that don’t return rows should not use Query functions; they should use Exec().</p>
</blockquote>
<p>Then it says <a href="http://go-database-sql.org/prepared.html" rel="noreferrer">here</a>:</p>
<blockquote>
<p>Go creates prepared statements for you under the covers. A simple db.Query(sql, param1, param2), for example, works by preparing the sql, then executing it with the parameters and finally closing the statement.</p>
</blockquote>
<p>If <strong><code>query()</code> uses under the covers prepared statements</strong> why should I even bother using prepared statements?</p> | 50,666,083 | 1 | 3 | null | 2018-06-03 08:38:27.617 UTC | 11 | 2018-10-29 09:59:25.337 UTC | 2018-10-29 09:59:25.337 UTC | null | 4,031,815 | null | 4,031,815 | null | 1 | 21 | sql|database|postgresql|go|prepared-statement | 27,077 | <h3>"Why even use db.Exec()":</h3>
<p>It's true that you can use <code>db.Exec</code> and <code>db.Query</code> interchangeably to execute the same sql statements however the two methods return different types of results. If implemented by the driver the result returned from <code>db.Exec</code> can tell you how many rows were affected by the query, while <code>db.Query</code> will return the rows object instead.</p>
<p>For example let's say you want to execute a <code>DELETE</code> statement and you want to know how many rows were deleted by it. You can do it either the proper way:</p>
<pre><code>res, err := db.Exec(`DELETE FROM my_table WHERE expires_at = $1`, time.Now())
if err != nil {
panic(err)
}
numDeleted, err := res.RowsAffected()
if err != nil {
panic(err)
}
print(numDeleted)
</code></pre>
<p>or the more verbose and objectively costlier way:</p>
<pre><code>rows, err := db.Query(`DELETE FROM my_table WHERE expires_at = $1 RETURNING *`, time.Now())
if err != nil {
panic(err)
}
defer rows.Close()
var numDelete int
for rows.Next() {
numDeleted += 1
}
if err := rows.Err(); err != nil {
panic(err)
}
print(numDeleted)
</code></pre>
<p>There's a 3rd way you could do this with a combination of postgres CTEs, <code>SELECT COUNT</code>, <code>db.QueryRow</code> and <code>row.Scan</code> but I don't think an example is necessary to show how unreasonable an approach that would be when compared to <code>db.Exec</code>.</p>
<p>Another reason to use <code>db.Exec</code> over <code>db.Query</code> is when you don't care about the returned result, when all you need is to execute the query and check if there was an error or not. In such a case you can do this:</p>
<pre><code>if _, err := db.Exec(`<my_sql_query>`); err != nil {
panic(err)
}
</code></pre>
<p>On the other hand, you cannot (you can but you shouldn't) do this:</p>
<pre><code>if _, err := db.Query(`<my_sql_query>`); err != nil {
panic(err)
}
</code></pre>
<p>Doing this, after a short while, your program will panic with an error that says something akin to <code>too many connections open</code>. This is because you're discarding the returned <code>db.Rows</code> value without first making the mandatory <code>Close</code> call on it, and so you end up with the number of open connections going up and eventually hitting the server's limit.</p>
<hr />
<h3>"or prepared statements in Golang?":</h3>
<p>I don't think the book you've cited is correct. At least to me it looks like whether or not a <code>db.Query</code> call creates a new prepared statement every time is dependent upon the driver you are using.</p>
<p>See for example these two sections of <code>queryDC</code> (an unexported method called by <code>db.Query</code>): <a href="https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1541-L1555" rel="noreferrer">without prepared statement</a> and <a href="https://github.com/golang/go/blob/master/src/database/sql/sql.go#L1558-L1585" rel="noreferrer">with prepared statement</a>.</p>
<p>Regardless of whether the book is correct or not a <code>db.Stmt</code> created by <code>db.Query</code> would be, unless there is some internal caching going on, thrown away after you close the returned <code>Rows</code> object. If you instead manually call <code>db.Prepare</code> and then cache and reuse the returned <code>db.Stmt</code> you can potentially improve the performance of the queries that need to be executed often.</p>
<p>To understand how a prepared statement can be used to optimize performance you can take a look at the official documentation: <a href="https://www.postgresql.org/docs/current/static/sql-prepare.html" rel="noreferrer">https://www.postgresql.org/docs/current/static/sql-prepare.html</a></p> |
51,007,636 | how javascript single threaded and asynchronous | <p>I went through the link below and understood single threaded javascript and its asynchronous nature a little</p>
<p><a href="https://www.sohamkamani.com/blog/2016/03/14/wrapping-your-head-around-async-programming/" rel="noreferrer">https://www.sohamkamani.com/blog/2016/03/14/wrapping-your-head-around-async-programming/</a></p>
<p>But I still have questions that javascript is single threaded and it always moves in forward direction in sequential manner until it finishes its execution.</p>
<p>Whenever we made call to function which has a callback, that callback will be executed after function receives response. Execution of javascript code continues during the wait time for the response. In this way where execution happening in sequence how callback execution will be resumed once after response received. It's like thread is moving backwards for callback execution. </p>
<p>Thread of execution should always move in forward direction righy?.</p>
<p>please clarify on this.</p> | 51,007,688 | 2 | 1 | null | 2018-06-24 06:55:00.46 UTC | 9 | 2022-09-24 10:14:24.377 UTC | 2018-06-24 06:56:58.67 UTC | null | 295,783 | null | 8,201,193 | null | 1 | 13 | javascript | 8,410 | <p>It's true that JavaScript is (now) specified to have only a single active thread <em>per <a href="https://tc39.es/ecma262/multipage/executable-code-and-execution-contexts.html#realm" rel="nofollow noreferrer">realm</a></em> (roughly: a global environment and its contents).¹ But I wouldn't call it "single-threaded;" you can have multiple threads via workers. They do not share a common global environment, which makes it dramatically easier to reason about code and not worry about the values of variables changing out from under you unexpectedly, but they can communicate via messaging and even access <a href="https://tc39.es/ecma262/multipage/memory-model.html#sec-memory-model" rel="nofollow noreferrer">shared memory</a> (with all the complications that brings, including the values of shared memory slots changing out from under you unexpectedly).</p>
<p>But running on a single thread and having asynchronous callbacks are not at all in conflict. A JavaScript thread works on the basis of a <a href="https://tc39.es/ecma262/multipage/executable-code-and-execution-contexts.html#sec-jobs" rel="nofollow noreferrer"><em>job queue</em></a> that jobs get added to. A job is a unit of code that runs to completion (no other code in the realm can run until it does). When that unit of code is done running to completion, the thread picks up the next job from the queue and runs that. One job cannot interrupt another job. Jobs running on the main thread (the UI thread in browsers) cannot be suspended in the middle (mostly²), though jobs on worker threads can be (via <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics/wait" rel="nofollow noreferrer"><code>Atomics.wait</code></a>). If a job is suspended, no other job in the realm will run until that job is resumed and completed.</p>
<p>So for instance, consider:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log("one");
setTimeout(function() {
console.log("three");
}, 10);
console.log("two");</code></pre>
</div>
</div>
</p>
<p>When you run that, you see</p>
<pre>
one
two
three
</pre>
<p>in the console. Here's what happened:</p>
<ol>
<li>A job for the main script execution was added to the job queue</li>
<li>The main JavaScript thread for the browser picked up that job</li>
<li>It ran the first <code>console.log</code>, <code>setTimeout</code>, and last <code>console.log</code></li>
<li>The job terminated</li>
<li>The main JavaScript thread idled for a bit</li>
<li>The browser's timer mechanism determined that it was time for that <code>setTimeout</code> callback to run and added a job to the job queue to run it</li>
<li>The main JavaScript thread picked up that job and ran that final <code>console.log</code></li>
</ol>
<p>If the main JavaScript thread were tied up (for instance, <code>while (true);</code>), jobs would just pile up in the queue and never get processed, because that job never completes.</p>
<hr />
<p>¹ The JavaScript specification was silent on the topic of threading until fairly recently. Browsers and Node.js used a single-active-thread-per-realm model (mostly), but some much less common environments didn't. I vaguely recall an early fork of V8 (the JavaScript engine in Chromium-based browsers and Node.js) that added multiple threading, but it never went anywhere. The Java virtual machine can run JavaScript code via its scripting support, and that code is multi-threaded (or at least it was with the Rhino engine; I have no ideal whether Narwhal changes that), but again that's quite niche.</p>
<p>² <em>"A job is a unit of code that runs to completion."</em> and <em>"Jobs running on th emain thread...cannot be suspended in the middle..."</em> Two caveats here:</p>
<ol>
<li><p><code>alert</code>, <code>confirm</code>, and <code>prompt</code> — those 90's synchronous user interactions — suspend a job on the main UI thread while waiting on the user. This is antiquated behavior that's grandfathered in (and is being at least partially <a href="https://developers.google.com/web/updates/2017/03/dialogs-policy" rel="nofollow noreferrer">phased out</a>).</p>
</li>
<li><p>Naturally, the host process — browser, etc. — can terminate the entire environment a job is running in while the job is running. For instance, when a web page becomes "unresponsive," the browser can kill it. But that's not just the job, it's the entire environment the job was running in.</p>
</li>
</ol> |
10,366,045 | Django: How to save data to ManyToManyField? | <p>I have a question concerning the following model. I want to populate the <code>ManyToManyField</code> from views.py instead of doing it from the Admin.</p>
<p>But how do I add data to the <code>genres</code> field which is the <code>ManyToManyField</code>?</p>
<p><strong>views.py</strong></p>
<pre><code>content = Movie_Info(id = m_id,
title = data[0].get('title'),
overview = data[0].get('overview'),
release_date = data[0].get('release_date'),
)
content.save()
</code></pre>
<p><strong>models.py</strong></p>
<pre><code>class Movie_Info_genre(models.Model):
genre = models.CharField(max_length=100)
class Movie_Info(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=100, blank=True, null=True)
overview = models.TextField(blank=True, null=True)
release_date = models.CharField(max_length=10, blank=True, null=True)
genres = models.ManyToManyField(Movie_Info_genre)
</code></pre> | 10,366,094 | 1 | 3 | null | 2012-04-28 17:51:34.777 UTC | 9 | 2018-03-03 18:27:43.407 UTC | 2018-03-03 18:27:43.407 UTC | null | 438,157 | null | 445,600 | null | 1 | 40 | django|django-models | 36,458 | <p>Use the <a href="https://docs.djangoproject.com/en/dev/ref/models/relations/#django.db.models.fields.related.RelatedManager.add">add method for related fields</a>:</p>
<pre><code># using Model.object.create is a shortcut to instantiating, then calling save()
myMoveInfo = Movie_Info.objects.create(title='foo', overview='bar')
myMovieGenre = Movie_Info_genre.objects.create(genre='horror')
myMovieInfo.genres.add(myMoveGenre)
</code></pre>
<p>Unlike modifying other fields, both models must exist in the database prior to doing this, so you must call <code>save</code> before adding the many-to-many relationship. Since add immediately affects the database, you do not need to save afterwards.</p> |
10,675,070 | Multiple TypeFace in single TextView | <p>I want to set the first character on <code>TextView</code> with a <code>TypeFace</code> and the second character with a different Type face and so on.<br>
I read this example: </p>
<pre><code>Spannable str = (Spannable) textView.getText();
str.setSpan(new StyleSpan(android.graphics.Typeface.ITALIC), 0, 7
,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</code></pre>
<p>but it didn't help me, because I want to set multiple <code>TypeFace (external TTFs)</code><br>
Any idea??</p> | 10,740,758 | 2 | 3 | null | 2012-05-20 16:15:48.76 UTC | 26 | 2020-09-01 08:24:46.503 UTC | 2012-08-24 04:59:32.127 UTC | null | 1,155,805 | null | 1,030,937 | null | 1 | 42 | java|android | 22,774 | <h2>Use the following code:(I'm using Bangla and Tamil font)</h2>
<pre><code> TextView txt = (TextView) findViewById(R.id.custom_fonts);
txt.setTextSize(30);
Typeface font = Typeface.createFromAsset(getAssets(), "Akshar.ttf");
Typeface font2 = Typeface.createFromAsset(getAssets(), "bangla.ttf");
SpannableStringBuilder SS = new SpannableStringBuilder("আমারநல்வரவு");
SS.setSpan (new CustomTypefaceSpan("", font2), 0, 4,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
SS.setSpan (new CustomTypefaceSpan("", font), 4, 11,Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
txt.setText(SS);
</code></pre>
<hr>
<p>The outcome is:</p>
<p><img src="https://i.stack.imgur.com/eJ55j.png" alt="enter image description here"></p>
<hr>
<p>This uses the <code>CustomTypefaceSpan</code> class, taken from <a href="https://stackoverflow.com/questions/4819049/how-can-i-use-typefacespan-or-stylespan-with-custom-typeface">How can I use TypefaceSpan or StyleSpan with a custom Typeface?</a>:</p>
<hr>
<pre><code>package my.app;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.text.style.TypefaceSpan;
public class CustomTypefaceSpan extends TypefaceSpan {
private final Typeface newType;
public CustomTypefaceSpan(String family, Typeface type) {
super(family);
newType = type;
}
@Override
public void updateDrawState(TextPaint ds) {
applyCustomTypeFace(ds, newType);
}
@Override
public void updateMeasureState(TextPaint paint) {
applyCustomTypeFace(paint, newType);
}
private static void applyCustomTypeFace(Paint paint, Typeface tf) {
int oldStyle;
Typeface old = paint.getTypeface();
if (old == null) {
oldStyle = 0;
} else {
oldStyle = old.getStyle();
}
int fake = oldStyle & ~tf.getStyle();
if ((fake & Typeface.BOLD) != 0) {
paint.setFakeBoldText(true);
}
if ((fake & Typeface.ITALIC) != 0) {
paint.setTextSkewX(-0.25f);
}
paint.setTypeface(tf);
}
}
</code></pre>
<hr> |
10,542,451 | Button color change on hover | <p>I'm just a beginner with Android. I want the button to change its color on mouseover.<br>
I don't know how to do that in android. Can it be done? </p>
<p>View for a button:</p>
<pre><code><Button
android:id="@+id/b8"
android:text="click me"
style="?android:attr/buttonStyleSmall"
android:textSize="20dp" />
</code></pre> | 10,542,534 | 4 | 4 | null | 2012-05-10 21:31:51.86 UTC | 3 | 2017-02-17 11:18:51.217 UTC | 2012-05-11 00:39:26.46 UTC | null | 1,328,610 | null | 1,383,687 | null | 1 | 9 | android|button|colors | 58,589 | <p>You need to use what's called a <code>selector</code>.</p>
<p>You can read about them and get a tutorial from <a href="http://www.mkyong.com/android/android-imagebutton-selector-example/" rel="nofollow">this site.</a></p>
<p>Keep in mind that there really isn't a concept in Android as "hover" since you can't hover your finger over the display. But you can create selectors for, say, when a button has focus. Normally a button can have three states: Normal, Focused and Pressed.</p> |
10,669,181 | C# Threading - How to start and stop a thread | <p>Can anyone give me a headstart on the topic of threading? I think I know how to do a few things but I need to know how to do the following:</p>
<p>Setup a main thread that will stay active until I signal it to stop(in case you wonder, it will terminate when data is received). Then i want a second thread to start which will capture data from a textbox and should quit when I signal it to that of which occurs when the user presses the enter key.</p>
<p>Cheers!</p> | 10,669,337 | 3 | 4 | null | 2012-05-19 22:05:08.613 UTC | 9 | 2015-06-25 19:44:17.73 UTC | 2015-06-25 19:44:17.73 UTC | null | 4,987,287 | null | 1,128,380 | null | 1 | 27 | c#|multithreading | 173,024 | <p>This is how I do it...</p>
<pre><code>public class ThreadA {
public ThreadA(object[] args) {
...
}
public void Run() {
while (true) {
Thread.sleep(1000); // wait 1 second for something to happen.
doStuff();
if(conditionToExitReceived) // what im waiting for...
break;
}
//perform cleanup if there is any...
}
}
</code></pre>
<p>Then to run this in its own thread... ( I do it this way because I also want to send args to the thread)</p>
<pre><code>private void FireThread(){
Thread thread = new Thread(new ThreadStart(this.startThread));
thread.start();
}
private void (startThread){
new ThreadA(args).Run();
}
</code></pre>
<p>The thread is created by calling "FireThread()"</p>
<p>The newly created thread will run until its condition to stop is met, then it dies...</p>
<p>You can signal the "main" with delegates, to tell it when the thread has died.. so you can then start the second one...</p>
<p>Best to read through : <a href="http://msdn.microsoft.com/en-us/library/ms173178%28v=vs.10%29.aspx" rel="noreferrer">This MSDN Article</a></p> |
25,270,885 | installing cx_Freeze to python at windows | <p>I am using python 3.4 at win-8. I want to obtain .exe program from python code. I learned that it can be done by cx_Freeze.</p>
<p>In MS-DOS command line, I wrote pip install cx_Freeze to set up cx_Freeze. It is installed but it is not working. </p>
<p>(When I wrote cxfreeze to command line, I get this warning:C:\Users\USER>cxfreeze
'cxfreeze' is not recognized as an internal or external command,operable program or batch file.)</p>
<p>(I also added location of cxfreeze to "PATH" by environment variables)</p>
<p>Any help would be appriciated thanks.</p> | 25,936,813 | 3 | 8 | null | 2014-08-12 17:48:23.16 UTC | 11 | 2015-10-20 18:54:29.64 UTC | 2014-09-19 15:37:58.613 UTC | null | 1,504,026 | null | 3,934,552 | null | 1 | 26 | python|batch-file|python-3.x|cx-freeze | 27,698 | <p>I faced a similar problem (Python 3.4 32-bit, on Windows 7 64-bit). After installation of cx_freeze, three files appeared in <code>c:\Python34\Scripts\</code>:</p>
<ul>
<li><code>cxfreeze</code></li>
<li><code>cxfreeze-postinstall</code></li>
<li><code>cxfreeze-quickstart</code></li>
</ul>
<p>These files have no file extensions, but appear to be Python scripts. When you run <code>python.exe cxfreeze-postinstall</code> from the command prompt, two batch files are being created in the Python scripts directory:</p>
<ul>
<li><code>cxfreeze.bat</code></li>
<li><code>cxfreeze-quickstart.bat</code></li>
</ul>
<p>From that moment on, you should be able to run cx_freeze.</p>
<p>cx_freeze was installed using the provided win32 installer (<code>cx_Freeze-4.3.3.win32-py3.4.exe</code>). Installing it using pip gave exactly the same result.</p> |
33,313,858 | ImportError: No module named 'email.mime'; email is not a package | <p>When running the below code, I keep getting the error:</p>
<pre><code>ImportError: No module named 'email.mime'; email is not a package
</code></pre>
<p>So I run: </p>
<pre><code>pip install email
</code></pre>
<p>And get the following error: </p>
<pre><code>ImportError: No module named 'cStringIO'...
Command "python setup.py egg_info" failed with error code 1
</code></pre>
<p>The internet has told me to run:</p>
<pre><code>pip install --upgrade pip
</code></pre>
<p>To solve this problem, which I've done many times now. I don't know what else I can do. </p>
<p>Python version: Python 3.3.5 | Anaconda 2.3.0 (x86_64)</p>
<pre><code>import smtplib,email,email.encoders,email.mime.text,email.mime.base
smtpserver = '[email protected]'
to = ['[email protected]']
fromAddr = '[email protected]'
subject = "testing email attachments"
# create html email
html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" '
html +='"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml">'
html +='<body style="font-size:12px;font-family:Verdana"><p>...</p>'
html += "</body></html>"
emailMsg = email.MIMEMultipart.MIMEMultipart('text/csv')
emailMsg['Subject'] = subject
emailMsg['From'] = fromAddr
emailMsg['To'] = ', '.join(to)
emailMsg['Cc'] = ", ".join(cc)
emailMsg.attach(email.mime.text.MIMEText(html,'html'))
# now attach the file
fileMsg = email.mime.base.MIMEBase('text/csv')
fileMsg.set_payload(file('rsvps.csv').read())
email.encoders.encode_base64(fileMsg)
fileMsg.add_header('Content-Disposition','attachment;filename=rsvps.csv')
emailMsg.attach(fileMsg)
# send email
server = smtplib.SMTP(smtpserver)
server.sendmail(fromAddr,to,emailMsg.as_string())
server.quit()
</code></pre> | 44,410,573 | 4 | 9 | null | 2015-10-24 02:18:49.04 UTC | 8 | 2019-06-02 17:37:38.823 UTC | 2015-10-24 02:52:23.917 UTC | null | 5,299,236 | null | 2,716,298 | null | 1 | 43 | python|pip | 82,707 | <p>I encountered the same problem just now. Finally, I found it's because I name the python file as 'email.py'. It works after changing its name.</p> |
13,719,579 | Equivalent code of CreateObject in C# | <p>I have a code in VB6. Can anyone tell me how to write it in <code>C#</code>. This code is below:</p>
<pre><code>Set Amibroker = CreateObject("Broker.Application")
Set STOCK = Amibroker.Stocks.Add(ticker)
Set quote = STOCK.Quotations.Add(stInDate)
quote.Open = stInOpen
quote.High = stInHigh
quote.Low = stInlow
quote.Close = stInYcp
quote.Volume = stInVolume
Set STOCK = Nothing
Set quote = Nothing
</code></pre>
<p>What is the equivalent of <code>CreateObject</code> in C#?. I try to add references to com object but i can't find any com object as Broker.Application or amibroker</p> | 13,719,933 | 4 | 0 | null | 2012-12-05 09:06:59.63 UTC | 11 | 2021-07-04 03:24:53.13 UTC | 2012-12-05 09:18:03.94 UTC | null | 522,374 | null | 1,687,944 | null | 1 | 20 | c#|com | 54,618 | <p>If you are using .net 4 or later, and therefore can make use of <code>dynamic</code>, you can do this quite simply. Here's an example that uses the Excel automation interface.</p>
<pre><code>Type ExcelType = Type.GetTypeFromProgID("Excel.Application");
dynamic ExcelInst = Activator.CreateInstance(ExcelType);
ExcelInst.Visible = true;
</code></pre>
<p>If you can't use dynamic then it's much more messy.</p>
<pre><code>Type ExcelType = Type.GetTypeFromProgID("Excel.Application");
object ExcelInst = Activator.CreateInstance(ExcelType);
ExcelType.InvokeMember("Visible", BindingFlags.SetProperty, null,
ExcelInst, new object[1] {true});
</code></pre>
<p>Trying to do very much of that will sap the lifeblood from you.</p>
<p>COM is so much easier if you can use early bound dispatch rather than late bound as shown above. Are you sure you can't find the right reference for the COM object?</p> |
13,354,158 | How to query for a List<String> in JdbcTemplate? | <p>I'm using Spring's <code>JdbcTemplate</code> and running a query like this:</p>
<pre><code>SELECT COLNAME FROM TABLEA GROUP BY COLNAME
</code></pre>
<p>There are no named parameters being passed, however, column name, <code>COLNAME</code>, will be passed by the user.</p>
<p><strong>Questions</strong></p>
<ol>
<li><p>Is there a way to have placeholders, like <code>?</code> for column names? For example <code>SELECT ? FROM TABLEA GROUP BY ?</code></p>
</li>
<li><p>If I want to simply run the above query and get a <code>List<String></code> what is the best way?</p>
</li>
</ol>
<p>Currently I'm doing:</p>
<pre><code>List<Map<String, Object>> data = getJdbcTemplate().queryForList(query);
for (Map m : data) {
System.out.println(m.get("COLNAME"));
}
</code></pre> | 13,354,273 | 4 | 0 | null | 2012-11-13 00:59:40.747 UTC | 7 | 2021-05-25 07:36:09.767 UTC | 2021-05-25 07:36:09.767 UTC | null | 452,775 | null | 131,194 | null | 1 | 43 | java|jdbc|jdbctemplate|spring-jdbc | 133,480 | <blockquote>
<p>Is there a way to have placeholders, like ? for column names? For example SELECT ? FROM TABLEA GROUP BY ?</p>
</blockquote>
<p>Use dynamic query as below:</p>
<pre><code>String queryString = "SELECT "+ colName+ " FROM TABLEA GROUP BY "+ colName;
</code></pre>
<blockquote>
<p>If I want to simply run the above query and get a List what is the best way?</p>
</blockquote>
<pre><code>List<String> data = getJdbcTemplate().query(query, new RowMapper<String>(){
public String mapRow(ResultSet rs, int rowNum)
throws SQLException {
return rs.getString(1);
}
});
</code></pre>
<p>EDIT: To Stop SQL Injection, check for non word characters in the colName as :</p>
<pre><code> Pattern pattern = Pattern.compile("\\W");
if(pattern.matcher(str).find()){
//throw exception as invalid column name
}
</code></pre> |
13,364,112 | Spring profiles and testing | <p>I've got a web application where I have the typical problem that it requires different configuration files for different environments. Some configuration is placed in the application server as JNDI datasources, however some configuration stays in property files.</p>
<p>Therefore I want to use the Spring profiles feature.</p>
<p>My problem is that I don't get the test case running.</p>
<p>context.xml:</p>
<pre><code><context:property-placeholder
location="classpath:META-INF/spring/config_${spring.profiles.active}.properties"/>
</code></pre>
<p>Test:</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration(locations = {
"classpath:context.xml" })
public class TestContext {
@Test
public void testContext(){
}
}
</code></pre>
<p>The problem seems to be that the variable for loading the profile isn't resolved:</p>
<pre><code>Caused by: java.io.FileNotFoundException: class path resource [META-INF/spring/config_${spring.profiles.active}.properties] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157)
at org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:181)
at org.springframework.core.io.support.PropertiesLoaderSupport.mergeProperties(PropertiesLoaderSupport.java:161)
at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.postProcessBeanFactory(PropertySourcesPlaceholderConfigurer.java:138)
... 31 more
</code></pre>
<p>The current profile should be set with the <code>@ActiveProfile</code> annotation. As it's a test case I won't be able to use the <code>web.xml</code>. If possible I'd like to avoid runtime options as well. The test should run as is (if possible).</p>
<p>How can I properly activate the profile? Is it possible to set the profile with a context.xml? Could I declare the variable in a test-context.xml that is actually calling the normal context?</p> | 13,364,550 | 5 | 1 | null | 2012-11-13 15:59:05.017 UTC | 12 | 2020-07-09 04:28:24.743 UTC | 2019-05-24 09:03:40.757 UTC | null | 1,240,557 | null | 1,022,141 | null | 1 | 70 | java|spring|junit|profile | 152,490 | <p>Can I recommend doing it this way, define your test like this:</p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
</code></pre>
<p>with the following content in myprops.properties file:</p>
<pre><code>spring.profiles.active=localtest
</code></pre>
<p>With this your second properties file should get resolved:</p>
<pre><code>META-INF/spring/config_${spring.profiles.active}.properties
</code></pre> |
9,621,131 | Error while reading Excel sheet using Java | <p>I'm working with Spring/Hibernet using NetBeans 6.9.1. I'm trying to read an Excel file (.xlsx- Office 2007). The code for reading an Excel file is as follows using a <code>Vactor</code> to store data from the Excel sheet.</p>
<pre><code>import java.io.FileInputStream;
import java.util.Iterator;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.NewHibernateUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.hibernate.Session;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
private Vector importExcelSheet(ModelAndView mv)
{
Vector cellVectorHolder = new Vector();
try
{
HSSFWorkbook myWorkBook = new HSSFWorkbook(new POIFSFileSystem(new FileInputStream("E:/Project/SpringHibernet/MultiplexTicketBookingNew/web/excelSheets/Country.xlsx")));
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
System.out.println(mySheet.getRow(1).getCell(0));
while(rowIter.hasNext())
{
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector=new Vector();
while(cellIter.hasNext())
{
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreVector.addElement(myCell);
}
cellVectorHolder.addElement(cellStoreVector);
}
}
catch (Exception e)
{
mv.addObject("msg", e.getMessage());
}
return cellVectorHolder;
}
</code></pre>
<p>The following is a method in my <code>Controller</code> that calls the above method to read the specified Excel file</p>
<hr>
<pre><code>@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception
{
ModelAndView mv=new ModelAndView();
try
{
if(request.getParameter("import")!=null)
{
session=NewHibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Vector dataHolder=importExcelSheet(mv);
for (int i=0;i<dataHolder.size(); i++)
{
Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
for (int j=0; j < cellStoreVector.size();j++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
String st = myCell.toString();
System.out.println(st.substring(0,1)+"\t");
}
System.out.println();
}
session.flush();
session.getTransaction().commit();
}
}
catch (Exception e)
{
mv.addObject("msg", e.getMessage());
}
return mv;
}
</code></pre>
<p>On executing this code, the following exception is thrown.</p>
<blockquote>
<p>The supplied data appears to be in the Office 2007+ XML. You are
calling the part of POI that deals with OLE2 Office Documents. You
need to call a different part of POI to process this data (eg XSSF
instead of HSSF)</p>
</blockquote>
<p>Am I using a wrong source or something else is wrong with the above code? What is the solution?</p>
<p>The code is taken from <a href="http://www.roseindia.net/tutorial/java/poi/readExcelFile.html" rel="noreferrer">here</a>.</p> | 9,632,869 | 2 | 2 | null | 2012-03-08 16:27:12.18 UTC | 8 | 2017-06-27 06:30:08.1 UTC | 2014-09-21 14:49:39.73 UTC | null | 1,391,249 | null | 1,013,649 | null | 1 | 10 | java|excel|apache-poi | 47,796 | <p>Your code as it stands explicitly requests HSSF, so will only work with the older .xls (binary) files.</p>
<p>If you want, you can ask POI to auto-detect which file type you have, and pick the appropriate one of HSSF or XSSF for your case. However, to do that you need to change your code slightly, and use interfaces rather than concrete classes (so your code works whether you get a HSSF or XSSF object)</p>
<p>The POI website has a <a href="http://poi.apache.org/spreadsheet/converting.html" rel="noreferrer">guide to making these changes</a> which should guide you through. </p>
<p>As an example, when you follow this, your first few lines which were:</p>
<pre><code> HSSFWorkbook myWorkBook = new HSSFWorkbook(new POIFSFileSystem(new FileInputStream("E:/Project/SpringHibernet/MultiplexTicketBookingNew/web/excelSheets/Country.xlsx")));
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator rowIter = mySheet.rowIterator();
System.out.println(mySheet.getRow(1).getCell(0));
</code></pre>
<p>Will become in the new system:</p>
<pre><code> Workbook wb = WorkbookFactory.create(new File("/path/to/your/excel/file"));
Sheet mySheet = wb.getSheetAt(0);
Iterator<Row> rowIter = mySheet.rowIterator();
System.out.println(mySheet.getRow(1).getCell(0));
</code></pre>
<p>This will then work for both .xls and .xlsx files</p> |
9,556,474 | How do I automatically update a timestamp in PostgreSQL | <p>I want the code to be able to automatically update the time stamp when a new row is inserted as I can do in MySQL using CURRENT_TIMESTAMP.</p>
<p>How will I be able to achieve this in PostgreSQL?</p>
<pre><code>CREATE TABLE users (
id serial not null,
firstname varchar(100),
middlename varchar(100),
lastname varchar(100),
email varchar(200),
timestamp timestamp
)
</code></pre> | 9,556,581 | 6 | 2 | null | 2012-03-04 16:08:15.403 UTC | 55 | 2021-10-28 13:45:38.743 UTC | 2020-01-28 20:20:04.087 UTC | null | 1,828,296 | null | 604,864 | null | 1 | 208 | database|postgresql|timestamp | 220,146 | <p>To populate the column during insert, use a <a href="http://www.postgresql.org/docs/current/static/ddl-default.html" rel="noreferrer"><code>DEFAULT</code></a> value:</p>
<pre><code>CREATE TABLE users (
id serial not null,
firstname varchar(100),
middlename varchar(100),
lastname varchar(100),
email varchar(200),
timestamp timestamp default current_timestamp
)
</code></pre>
<p>Note that the value for that column can explicitly be overwritten by supplying a value in the <a href="http://www.postgresql.org/docs/current/static/dml-insert.html" rel="noreferrer"><code>INSERT</code></a> statement. If you want to prevent that you do need a <a href="http://www.postgresql.org/docs/current/static/plpgsql-trigger.html" rel="noreferrer">trigger</a>. </p>
<p>You also need a trigger if you need to update that column whenever the row is updated (as <a href="https://stackoverflow.com/a/9556527/642706">mentioned by E.J. Brennan</a>)</p>
<p>Note that using reserved words for column names is usually not a good idea. You should find a different name than <code>timestamp</code></p> |
16,163,176 | Module not found error in node.js | <p>I am new to node.js, this is my first node application so, please excuse me if I'm asking obvious question. I have a file called <code>utils.js</code> and I need to have functions defined in that file to be available in <code>main.js</code>. So I tried giving</p>
<p><code>require(utils.js)</code></p>
<p>But it is throwing me this error:</p>
<pre><code>Error: Cannot find module 'utils.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
</code></pre>
<p>My <code>main.js</code> is under <code>c:\demo\proj\src\main\main.js</code> and <code>utils.js</code> is under <code>c:\demo\proj\src\utils\utils.js</code>.</p>
<p>I tried below require combinations, but still I am getting cannot find module error:</p>
<ul>
<li><p><code>require(/proj/src/utils/utils.js</code>);</p></li>
<li><p><code>require(/utils.js</code>);</p></li>
<li><code>require(c:/demo/proj/src/utils/utils.js</code>);</li>
</ul>
<p>Even I tried to put it under <code>node_modules</code> folder, but still same error. Can you kindly guide me what I am doing mistake here?</p>
<p><strong>Edit:</strong></p>
<p>I tried putting changing my folder structure as pointed out by @mithunsatheesh as below:</p>
<ul>
<li>project
<ul>
<li>src
<ul>
<li>utils - utils.js</li>
</ul></li>
</ul></li>
<li>main.js</li>
</ul>
<p>My <code>require</code> is as follows: <code>require('./src/utils/utils.js')</code></p>
<p>But when I execute <code>node main.js</code> still I am getting below error:</p>
<pre><code>Error: Cannot find module './src/utils/utils.js'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
</code></pre> | 16,163,386 | 3 | 2 | null | 2013-04-23 07:14:14.133 UTC | 3 | 2021-06-05 01:59:46.343 UTC | 2013-04-23 08:43:20.877 UTC | null | 1,506,071 | null | 1,506,071 | null | 1 | 18 | javascript|node.js | 115,700 | <p>according to the folder structure you mentioned in the question, you have to try </p>
<pre><code>require('../utils/utils.js')
</code></pre>
<p>This is the case if you have your project folder structured like</p>
<ul>
<li>proj
<ul>
<li>src
<ul>
<li>utils
<ul>
<li>utils.js</li>
</ul></li>
<li>main
<ul>
<li>main.js</li>
</ul></li>
</ul></li>
</ul></li>
</ul>
<p>and you are doing <code>node main.js</code></p>
<p>To comment on the details provided in your question.</p>
<ol>
<li><p>please dont use <code>require(c:/demo/proj/src/utils/utils.js);</code> as you are tried out. imagine like you are exporting the <code>proj</code> folder with your project files then the mentioned require will be an error.</p></li>
<li><p>Also the folder structure could be made to something like</p>
<ul>
<li>proj
<ul>
<li>src
<ul>
<li>utils
- utils.js</li>
</ul></li>
<li>main.js</li>
<li>package.json</li>
</ul></li>
</ul></li>
</ol>
<p>so that you keep the main file in root of project folder. and require the utils.js like</p>
<pre><code> require('./src/utils/utils.js')
</code></pre>
<h3>UPDATE</h3>
<p>As far as ican see from the updated error message. Its still the issue with the path of 'utils.js' in require. From your updated folder structre It seems that <code>main.js</code> is in same level as <code>proj</code> folder, see that the proposed folder structure had <code>main.js</code> and <code>src</code> folder in same level inside <code>proj</code> folder. </p>
<p>Even that was a suggestion that I made as you were following a folder structure that dint make any sense. Simply <code>require('../utils/utils.js')</code> would have solved your issue without even altering the folder structure you mentioned in the beginning. </p> |
16,373,906 | Address family not supported by protocol family - SocketException on a specific computer | <p>In an app which I have programmed, I have a <strong>java.net.SocketException</strong> on a specific computer:</p>
<blockquote>
<p>java.net.SocketException: Address family not supported by protocol family: connect</p>
</blockquote>
<p>This specific computer runs Windows 7 32 Bit and is connected to the internet through Local Area Connection (Ethernet).
The app runs correctly on other computers, with Windows 7 and Windows 8, connected through Local Area Connection or through Wi-Fi, so I am actually not sure that the problem is programmatic.
I have tried to check the protocols of the Local Area Connection, but I didn't see any problems.
Can someone please help me understand what is the problem? Why is this exception thrown?</p> | 21,383,865 | 6 | 11 | null | 2013-05-04 11:44:06.52 UTC | 7 | 2018-10-11 18:30:26.06 UTC | null | null | null | null | 2,338,522 | null | 1 | 20 | java|sockets|socketexception | 81,636 | <p>Try to check whether the spy program called "RelevantKnowledge" is installed. Its uninstallation helped me to solve the problem.</p> |
16,469,410 | Data Compression Algorithms | <p>I was wondering if anyone has a list of data compression algorithms. I know basically nothing about data compression and I was hoping to learn more about different algorithms and see which ones are the newest and have yet to be developed on a lot of ASICs. </p>
<p>I'm hoping to implement a data compression ASIC which is independent of the type of data coming in (audio,video,images,etc.)</p>
<p>If my question is too open ended, please let me know and I'll revise. Thank you</p> | 16,469,857 | 5 | 3 | null | 2013-05-09 19:16:24.673 UTC | 22 | 2018-06-05 17:47:57.367 UTC | null | null | null | null | 688,463 | null | 1 | 43 | c++|c|algorithm|compression|signal-processing | 91,503 | <p>There are a ton of compression algorithms out there. What you need here is a lossless compression algorithm. A lossless compression algorithm compresses data such that it can be decompressed to achieve exactly what was given before compression. The opposite would be a lossy compression algorithm. Lossy compression can remove data from a file. PNG images use lossless compression while JPEG images can and often do use lossy compression.</p>
<p>Some of the most widely known compression algorithms include:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Run-length_encoding">RLE</a></li>
<li><a href="http://en.wikipedia.org/wiki/Huffman_coding">Huffman</a></li>
<li><a href="https://en.wikipedia.org/wiki/LZ77_and_LZ78">LZ77</a></li>
</ul>
<p>ZIP archives use a combination of Huffman coding and LZ77 to give fast compression and decompression times <strong>and</strong> reasonably good compression ratios.</p>
<p>LZ77 is pretty much a generalized form of RLE and it will often yield much better results.</p>
<p>Huffman allows the most repeating bytes to represent the least number of bits.
Imagine a text file that looked like this:</p>
<pre><code>aaaaaaaabbbbbcccdd
</code></pre>
<p>A typical implementation of Huffman would result in the following map:</p>
<pre><code>Bits Character
0 a
10 b
110 c
1110 d
</code></pre>
<p>So the file would be compressed to this:</p>
<pre><code>00000000 10101010 10110110 11011101 11000000
^^^^^
Padding bits required
</code></pre>
<p>18 bytes go down to 5. Of course, the table must be included in the file. This algorithm works better with more data :P</p>
<p>Alex Allain has <a href="http://www.cprogramming.com/tutorial/computersciencetheory/huffman.html">a nice article</a> on the Huffman Compression Algorithm in case the Wiki doesn't suffice.</p>
<p>Feel free to ask for more information. This topic is pretty darn wide.</p> |
16,046,146 | Checking if values in List is part of String | <p>I have a string like this:</p>
<pre><code>val a = "some random test message"
</code></pre>
<p>I have a list like this:</p>
<pre><code>val keys = List("hi","random","test")
</code></pre>
<p>Now, I want to check whether the string <code>a</code> contains any values from <code>keys</code>. How can we do this using the in built library functions of Scala ?</p>
<p>( I know the way of splitting <code>a</code> to List and then do a check with <code>keys</code> list and then find the solution. But I'm looking a way of solving it more simply using standard library functions.)</p> | 16,046,198 | 2 | 0 | null | 2013-04-16 20:10:27.993 UTC | 9 | 2018-07-18 02:09:40.177 UTC | 2018-07-18 02:09:40.177 UTC | null | 2,370,483 | null | 1,651,941 | null | 1 | 49 | string|scala|list | 33,042 | <p>Something like this?</p>
<pre><code>keys.exists(a.contains(_))
</code></pre>
<p>Or even more idiomatically</p>
<pre><code>keys.exists(a.contains)
</code></pre> |
11,207,223 | How to add background image for options in a select box? | <p>Can anyone give me a cross-browser supported solution for this problem?</p> | 11,207,300 | 2 | 1 | null | 2012-06-26 12:20:35.367 UTC | null | 2012-06-26 12:28:27.22 UTC | 2012-06-26 12:20:57.413 UTC | null | 759,019 | null | 1,479,606 | null | 1 | 3 | javascript|jquery|html|css|cross-browser | 41,664 | <p>You can use a custom jquery plugin like in this reference: </p>
<p><a href="http://www.marghoobsuleman.com/jquery-image-dropdown" rel="nofollow">http://www.marghoobsuleman.com/jquery-image-dropdown</a></p> |
28,954,884 | Mongorestore don't know what to do with file "db/collection.bson", skipping | <p>I want to migrate my mongodb from 2.0 to 3.0. So I followed the official doc to use mongodump to backup my dbs and use mongorestore to restore the dbs to mongodb 3.0.</p>
<p>But when I use mongorestore, it tells me "don't know what to do with file "db/collection.bson", skipping...".</p>
<p>Nothing to do. How could I migrate my dbs?</p>
<p>Thanks.</p>
<p>EDIT: Here is my steps.</p>
<p>Use mongodump in mongodb 2.0</p>
<pre><code>mongodump
tree dump
db
├── collection-1.bson
├── collection-2.bson
├── collection-3.bson
├── ...
</code></pre>
<p>Copy db directory to mongodb 3.0 server.</p>
<p>On the mongodb 3.0 server calls <code>mongorestore db</code></p>
<p>But I get this error:</p>
<pre><code>mongorestore db
2015-03-10T09:36:26.237+0800 building a list of dbs and collections to restore from db dir
2015-03-10T09:36:26.237+0800 don't know what to do with file "db/collection-1.bson", skipping...
2015-03-10T09:36:26.237+0800 don't know what to do with file "db/collection-2.bson", skipping...
2015-03-10T09:36:26.237+0800 don't know what to do with file "db/collection-3.bson", skipping...
...
2015-03-10T09:36:26.237+0800 done
</code></pre> | 29,010,509 | 10 | 5 | null | 2015-03-10 01:51:58.4 UTC | 12 | 2022-08-30 10:14:27 UTC | 2015-03-10 02:12:55.543 UTC | null | 2,701,866 | null | 2,701,866 | null | 1 | 57 | mongodb | 54,911 | <p>It seems one must also specify -d in 3.0 like this:</p>
<pre><code>mongorestore -d db db
</code></pre> |
24,880,835 | How to melt and cast dataframes using dplyr? | <p>Recently I am doing all my data manipulations using dplyr and it is an excellent tool for that. However I am unable to melt or cast a data frame using dplyr. Is there any way to do that? Right now I am using reshape2 for this purpose.</p>
<p>I want 'dplyr' solution for:</p>
<pre><code>require(reshape2)
data(iris)
dat <- melt(iris,id.vars="Species")
</code></pre> | 24,884,418 | 3 | 5 | null | 2014-07-22 07:01:33.943 UTC | 15 | 2017-03-09 00:54:43.29 UTC | 2017-03-09 00:54:43.29 UTC | null | 4,606,130 | null | 2,743,244 | null | 1 | 44 | r|reshape|dplyr|melt | 62,790 | <p>The successor to <code>reshape2</code> is <code>tidyr</code>. The equivalent of <code>melt()</code> and <code>dcast()</code> are <code>gather()</code> and <code>spread()</code> respectively. The equivalent to your code would then be</p>
<pre><code>library(tidyr)
data(iris)
dat <- gather(iris, variable, value, -Species)
</code></pre>
<p>If you have <code>magrittr</code> imported you can use the pipe operator like in <code>dplyr</code>, i.e. write </p>
<pre><code>dat <- iris %>% gather(variable, value, -Species)
</code></pre>
<p>Note that you need to specify the variable and value names explicitly, unlike in <code>melt()</code>. I find the syntax of <code>gather()</code> quite convenient, because you can just specify the columns you want to be converted to long format, or specify the ones you want to remain in the new data frame by prefixing them with '-' (just like for Species above), which is a bit faster to type than in <code>melt()</code>. However, I've noticed that on my machine at least, <code>tidyr</code> can be noticeably slower than <code>reshape2</code>. </p>
<p><em>Edit</em> In reply to @hadley 's comment below, I'm posting some timing info comparing the two functions on my PC. </p>
<pre><code>library(microbenchmark)
microbenchmark(
melt = melt(iris,id.vars="Species"),
gather = gather(iris, variable, value, -Species)
)
# Unit: microseconds
# expr min lq median uq max neval
# melt 278.829 290.7420 295.797 320.5730 389.626 100
# gather 536.974 552.2515 567.395 683.2515 1488.229 100
set.seed(1)
iris1 <- iris[sample(1:nrow(iris), 1e6, replace = T), ]
system.time(melt(iris1,id.vars="Species"))
# user system elapsed
# 0.012 0.024 0.036
system.time(gather(iris1, variable, value, -Species))
# user system elapsed
# 0.364 0.024 0.387
sessionInfo()
# R version 3.1.1 (2014-07-10)
# Platform: x86_64-pc-linux-gnu (64-bit)
#
# locale:
# [1] LC_CTYPE=en_GB.UTF-8 LC_NUMERIC=C
# [3] LC_TIME=en_GB.UTF-8 LC_COLLATE=en_GB.UTF-8
# [5] LC_MONETARY=en_GB.UTF-8 LC_MESSAGES=en_GB.UTF-8
# [7] LC_PAPER=en_GB.UTF-8 LC_NAME=C
# [9] LC_ADDRESS=C LC_TELEPHONE=C
# [11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C
# attached base packages:
# [1] stats graphics grDevices utils datasets methods base
#
# other attached packages:
# [1] reshape2_1.4 microbenchmark_1.3-0 magrittr_1.0.1
# [4] tidyr_0.1
#
# loaded via a namespace (and not attached):
# [1] assertthat_0.1 dplyr_0.2 parallel_3.1.1 plyr_1.8.1 Rcpp_0.11.2
# [6] stringr_0.6.2 tools_3.1.1
</code></pre> |
24,896,193 | What's the difference between python's multiprocessing and concurrent.futures? | <p>A simple way of implementing multiprocessing in python is</p>
<pre><code>from multiprocessing import Pool
def calculate(number):
return number
if __name__ == '__main__':
pool = Pool()
result = pool.map(calculate, range(4))
</code></pre>
<p>An alternative implementation based on futures is</p>
<pre><code>from concurrent.futures import ProcessPoolExecutor
def calculate(number):
return number
with ProcessPoolExecutor() as executor:
result = executor.map(calculate, range(4))
</code></pre>
<p>Both alternatives do essentially the same thing, but one striking difference is that we don't have to guard the code with the usual <code>if __name__ == '__main__'</code> clause. Is this because the implementation of futures takes care of this or us there a different reason?</p>
<p>More broadly, what are the differences between <code>multiprocessing</code> and <code>concurrent.futures</code>? When is one preferred over the other?</p>
<p>EDIT:
My initial assumption that the guard <code>if __name__ == '__main__'</code> is only necessary for multiprocessing was wrong. Apparently, one needs this guard for both implementations on windows, while it is not necessary on unix systems.</p> | 24,896,362 | 2 | 5 | null | 2014-07-22 19:32:10.713 UTC | 8 | 2020-05-29 13:45:05.693 UTC | 2014-07-22 19:56:55.357 UTC | null | 932,593 | null | 932,593 | null | 1 | 23 | python|multiprocessing|concurrent.futures | 8,957 | <p>You actually should use the <code>if __name__ == "__main__"</code> guard with <code>ProcessPoolExecutor</code>, too: It's using <code>multiprocessing.Process</code> to populate its <code>Pool</code> under the covers, just like <code>multiprocessing.Pool</code> does, so all the same caveats regarding picklability (especially on Windows), etc. apply.</p>
<p>I believe that <code>ProcessPoolExecutor</code> is meant to eventually replace <code>multiprocessing.Pool</code>, according to <a href="http://bugs.python.org/issue9205#msg132661" rel="nofollow noreferrer">this statement made by Jesse Noller</a> (a Python core contributor), when asked why Python has both APIs:</p>
<blockquote>
<p>Brian and I need to work on the consolidation we intend(ed) to occur
as people got comfortable with the APIs. My eventual goal is to remove
anything but the basic multiprocessing.Process/Queue stuff out of MP
and into concurrent.* and support threading backends for it.</p>
</blockquote>
<p>For now, <code>ProcessPoolExecutor</code> is mostly doing the exact same thing as <code>multiprocessing.Pool</code> with a simpler (and more limited) API. If you can get away with using <code>ProcessPoolExecutor</code>, use that, because I think it's more likely to get enhancements in the long-term. Note that you can use all the helpers from <code>multiprocessing</code> with <code>ProcessPoolExecutor</code>, like <code>Lock</code>, <code>Queue</code>, <code>Manager</code>, etc., so needing those isn't a reason to use <code>multiprocessing.Pool</code>.</p>
<p>There are some notable differences in their APIs and behavior though:</p>
<ol>
<li><p>If a Process in a <code>ProcessPoolExecutor</code> terminates abruptly, <a href="https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ProcessPoolExecutor" rel="nofollow noreferrer">a <code>BrokenProcessPool</code> exception is raised</a>, aborting any calls waiting for the pool to do work, and preventing new work from being submitted. If the same thing happens to a <code>multiprocessing.Pool</code> it will silently replace the process that terminated, but the work that was being done in that process will never be completed, which will likely cause the calling code to hang forever waiting for the work to finish.</p></li>
<li><p>If you are running Python 3.6 or lower, support for <code>initializer</code>/<code>initargs</code> is missing from <code>ProcessPoolExecutor</code>. <a href="https://bugs.python.org/issue21423" rel="nofollow noreferrer">Support for this was only added in 3.7</a>).</p></li>
<li><p>There is no support in <code>ProcessPoolExecutor</code> for <code>maxtasksperchild</code>. </p></li>
<li><p><code>concurrent.futures</code> doesn't exist in Python 2.7, unless you manually install the backport.</p></li>
<li><p>If you're running below Python 3.5, according to <a href="https://stackoverflow.com/q/18671528/2073595">this question</a>, <code>multiprocessing.Pool.map</code> outperforms <code>ProcessPoolExecutor.map</code>. Note that the performance difference is very small <em>per work item</em>, so you'll probably only notice a large performance difference if you're using <code>map</code> on a very large iterable. The reason for the performance difference is that <code>multiprocessing.Pool</code> will batch the iterable passed to map into chunks, and then pass the chunks to the worker processes, which reduces the overhead of IPC between the parent and children. <code>ProcessPoolExecutor</code> always (or by default, starting in 3.5) passes one item from the iterable at a time to the children, which can lead to much slower performance with large iterables, due to the increased IPC overhead. The good news is this issue is fixed in Python 3.5, as the <code>chunksize</code> keyword argument has been added to <code>ProcessPoolExecutor.map</code>, which can be used to specify a larger chunk size when you know you're dealing with large iterables. See this <a href="http://bugs.python.org/issue11271" rel="nofollow noreferrer">bug</a> for more info. </p></li>
</ol> |
11,504,350 | codeigniter resize image and create thumbnail | <p>hi according to the ci document you can resize images with image_lib and there are options that suggest we can create additional thumbnail from that image </p>
<pre><code>create_thumb FALSE TRUE/FALSE (boolean) Tells the image processing function to create a thumb. R
thumb_marker _thumb None Specifies the thumbnail indicator. It will be inserted just before the file extension, so mypic.jpg would become mypic_thumb.jpg R
</code></pre>
<p>so here is my code</p>
<pre><code> $config_manip = array(
'image_library' => 'gd2',
'source_image' => "./uploads/avatar/tmp/{$this->input->post('new_val')}",
'new_image' => "./uploads/avatar/{$this->input->post('new_val')}",
'maintain_ratio'=> TRUE ,
'create_thumb' => TRUE ,
'thumb_marker' => '_thumb' ,
'width' => 150,
'height' => 150
);
$this->load->library('image_lib', $config_manip);
$this->image_lib->resize();
</code></pre>
<p>i would assume this code resizes my image and also creates a thumbnail , but i only get one image with specified dimensions and _tump postfix </p>
<p>i've also tried to add this code to create second image manually but still it doesn't work and i get only one image</p>
<pre><code> $this->image_lib->clear();
$config_manip['new_image'] =
"./uploads/avatar/thumbnail_{$this->input->post('new_val')}";
$config_manip['width'] = 30 ;
$config_manip['height'] = 30 ;
$this->load->library('image_lib', $config_manip);
$this->image_lib->resize();
</code></pre> | 11,505,260 | 4 | 5 | null | 2012-07-16 12:29:31.847 UTC | 1 | 2018-01-25 22:52:55.717 UTC | 2012-07-16 13:37:31.18 UTC | null | 782,535 | null | 590,589 | null | 1 | 4 | php|codeigniter|resize|gd | 40,616 | <p>It seems path is the issue in your code. I modified and tested myself it works.</p>
<pre><code>public function do_resize()
{
$filename = $this->input->post('new_val');
$source_path = $_SERVER['DOCUMENT_ROOT'] . '/uploads/avatar/tmp/' . $filename;
$target_path = $_SERVER['DOCUMENT_ROOT'] . '/uploads/avatar/';
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => TRUE,
'create_thumb' => TRUE,
'thumb_marker' => '_thumb',
'width' => 150,
'height' => 150
);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
}
// clear //
$this->image_lib->clear();
}
</code></pre>
<p>Hope this helps you. Thanks!!</p> |
17,502,082 | iOS : How to add drop shadow and stroke shadow on UIView? | <p>I want to add <strong>drop shadow</strong> and <strong>stroke shadow</strong> on <code>UIView</code>
This is what my designer given me to apply shadow,</p>
<ul>
<li><p>For drop shadow, he told me to use RGB(176,199,226) with 90% opacity, distance-3 and size-5</p></li>
<li><p>For stroke shadow, he told to apply, RGB(209,217,226) of size-1 and 100% opacity.</p></li>
</ul>
<p>This is photoshop applied effects screen,</p>
<p><img src="https://i.stack.imgur.com/OHILX.png" alt="enter image description here"><img src="https://i.stack.imgur.com/nLjsP.png" alt="enter image description here"></p>
<p><strong>The view with the required shadow (expected output)</strong></p>
<p><img src="https://i.stack.imgur.com/E9KfR.png" alt="enter image description here"></p>
<p><strong>I tried the following to get the drop shadow</strong></p>
<pre><code>viewCheck.layer.masksToBounds = NO;
viewCheck.layer.cornerRadius = 5.f;
viewCheck.layer.shadowOffset = CGSizeMake(.0f,2.5f);
viewCheck.layer.shadowRadius = 1.5f;
viewCheck.layer.shadowOpacity = .9f;
viewCheck.layer.shadowColor = [UIColor colorWithRed:176.f/255.f green:199.f/255.f blue:226.f/255.f alpha:1.f].CGColor;
viewCheck.layer.shadowPath = [UIBezierPath bezierPathWithRect:viewCheck.bounds].CGPath;
</code></pre>
<p>And this is the result of it,</p>
<p><img src="https://i.stack.imgur.com/RMnVd.png" alt="enter image description here"></p>
<p>I'm having problem in understanding how I can apply stroke and drop shadow as showing into photoshop screenshots (I've added above). How to apply Distance, Spread, Size, Position?</p>
<p>Can someone point me to a guide to applying these kind of shadows? There's lots of shadow effects coming out and I want to learn how it can be possible instead asking each of the questions here! </p>
<p>Thanks :)</p> | 31,829,309 | 4 | 0 | null | 2013-07-06 10:37:42.487 UTC | 11 | 2015-08-05 10:20:51.047 UTC | null | null | null | null | 1,603,234 | null | 1 | 23 | ios|objective-c|uiview|dropshadow|strokeshadow | 32,317 | <p>I believe most of configuration you look for can be achieved by employing the <code>shadowPath</code> property.</p>
<pre><code>viewCheck.layer.shadowRadius = 1.5f;
viewCheck.layer.shadowColor = [UIColor colorWithRed:176.f/255.f green:199.f/255.f blue:226.f/255.f alpha:1.f].CGColor;
viewCheck.layer.shadowOffset = CGSizeMake(0.0f, 0.0f);
viewCheck.layer.shadowOpacity = 0.9f;
viewCheck.layer.masksToBounds = NO;
UIEdgeInsets shadowInsets = UIEdgeInsetsMake(0, 0, -1.5f, 0);
UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:UIEdgeInsetsInsetRect(viewCheck.bounds, shadowInsets)];
viewCheck.layer.shadowPath = shadowPath.CGPath;
</code></pre>
<p>e.g, by setting <code>shadowInsets</code> this way</p>
<pre><code>UIEdgeInsets shadowInsets = UIEdgeInsetsMake(0, 0, -1.5f, 0);
</code></pre>
<p>you will get a nice desirable shadow:</p>
<p><a href="https://i.stack.imgur.com/NXGcf.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NXGcf.png" alt="enter image description here"></a></p>
<p>You can decide now how you want the shadow rectangle to be constructed by controlling the shadow path rectangle insets.</p> |
17,558,547 | HBase (Easy): How to Perform Range Prefix Scan in hbase shell | <p>I am designing an app to run on hbase and want to interactively explore the contents of my cluster. I am in the hbase shell and I want to perform a scan of all keys starting with the chars "abc". Such keys might inlcude "abc4", "abc92", "abc20014" etc... I tried a scan</p>
<pre><code>hbase(main):003:0> scan 'mytable', {STARTROW => 'abc', ENDROW => 'abc'}
</code></pre>
<p>But this does not seem to return anything since there is technically no rowkey "abc" only rowkeys starting with "abc"</p>
<p>What I want is something like</p>
<pre><code>hbase(main):003:0> scan 'mytable', {STARTSROWPREFIX => 'abc', ENDROWPREFIX => 'abc'}
</code></pre>
<p>I hear HBase can do this quickly and is one of its main selling points. How do I do this in the hbase shell?</p> | 17,558,843 | 4 | 0 | null | 2013-07-09 21:26:21.64 UTC | 17 | 2020-01-29 04:24:00.163 UTC | 2020-01-29 04:24:00.163 UTC | null | 1,746,118 | null | 1,698,695 | null | 1 | 35 | hbase|database-scan|hbase-shell | 86,971 | <p>So it turns out to be very easy. The scan ranges are not inclusive, the logic is start <= key < end. So the answer is</p>
<pre><code>scan 'mytable', {STARTROW => 'abc', ENDROW => 'abd'}
</code></pre> |
17,568,469 | Jersey 2.0 equivalent to POJOMappingFeature | <p>I have some experience using Jersey < 2.0. Now I am trying to build a war application to provide a JSON Webservice API.</p>
<p>I am now struggling for a considerable amount of time trying to configure Moxy and it seams to be way more complicated than what was adding</p>
<pre><code> <init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
</code></pre>
<p>to your web.xml back in Jersey < 2.0. </p>
<p>Is there some possibility to just say "please add json support"?</p>
<p>Currently I just get a lot of Internal Server Error errors without any log entries on the server and just think "I have to do something totally wrong, this can't be so hard"</p>
<p>Can anyone give me a hint? </p> | 17,603,217 | 6 | 1 | null | 2013-07-10 10:38:08.16 UTC | 8 | 2018-06-01 08:59:55.363 UTC | 2013-07-10 15:09:29.953 UTC | null | 1,465,785 | null | 1,465,785 | null | 1 | 36 | java|json|web-services|moxy|jersey-2.0 | 47,801 | <p>You can configure <a href="http://www.eclipse.org/eclipselink/moxy.php"><strong>EclipseLink MOXy</strong></a> as the JSON-binding provider by configuring the <code>MOXyJsonProvider</code> class through a JAX-RS <code>Application</code> class.</p>
<p><strong>Example #1</strong></p>
<pre><code>package org.example;
import java.util.*;
import javax.ws.rs.core.Application;
import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
public class CustomerApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>(2);
set.add(MOXyJsonProvider.class);
set.add(CustomerService.class);
return set;
}
}
</code></pre>
<p><strong>Example #2</strong></p>
<pre><code>package org.example;
import java.util.*;
import javax.ws.rs.core.Application;
import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
public class CustomerApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
HashSet<Class<?>> set = new HashSet<Class<?>>(1);
set.add(ExampleService.class);
return set;
}
@Override
public Set<Object> getSingletons() {
MOXyJsonProvider moxyJsonProvider = new MOXyJsonProvider();
moxyJsonProvider.setAttributePrefix("@");
moxyJsonProvider.setFormattedOutput(true);
moxyJsonProvider.setIncludeRoot(true);
moxyJsonProvider.setMarshalEmptyCollections(false);
moxyJsonProvider.setValueWrapper("$");
Map<String, String> namespacePrefixMapper = new HashMap<String, String>(1);
namespacePrefixMapper.put("http://www.example.org/customer", "cust");
moxyJsonProvider.setNamespacePrefixMapper(namespacePrefixMapper);
moxyJsonProvider.setNamespaceSeparator(':');
HashSet<Object> set = new HashSet<Object>(1);
set.add(moxyJsonProvider);
return set;
}
}
</code></pre>
<p><strong>For More Information</strong></p>
<ul>
<li><a href="http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html">http://blog.bdoughan.com/2012/05/moxy-as-your-jax-rs-json-provider.html</a></li>
<li><a href="http://blog.bdoughan.com/2013/06/moxy-is-new-default-json-binding.html">http://blog.bdoughan.com/2013/06/moxy-is-new-default-json-binding.html</a></li>
</ul> |
17,169,541 | Copy file in Java and replace existing target | <p>I'm trying to copy a file with java.nio.file.Files like this:</p>
<pre><code>Files.copy(cfgFilePath, strTarget, StandardCopyOption.REPLACE_EXISTING);
</code></pre>
<p>The problem is that Eclipse says "The method copy(Path, Path, CopyOption...) in the type Files is not applicable for the arguments (File, String, StandardCopyOption)"</p>
<p>I'm using Eclipse and Java 7 on Win7 x64. My project is set up to use Java 1.6 compatibility.</p>
<p>Is there a solution to this or do I have to create something like this as a workaround:</p>
<pre><code>File temp = new File(target);
if(temp.exists())
temp.delete();
</code></pre>
<p>Thanks.</p> | 17,169,700 | 4 | 0 | null | 2013-06-18 13:00:54.59 UTC | 9 | 2019-02-19 13:46:51.567 UTC | null | null | null | null | 765,075 | null | 1 | 50 | java|file|replace|copy | 92,706 | <p>As a complement to @assylias' answer:</p>
<p>If you use Java 7, drop <code>File</code> entirely. What you want is <code>Path</code> instead.</p>
<p>And to get a <code>Path</code> object matching a path on your filesystem, you do:</p>
<pre><code>Paths.get("path/to/file"); // argument may also be absolute
</code></pre>
<p>Get used to it real fast. Note that if you still use APIs which require <code>File</code>, <code>Path</code> has a <code>.toFile()</code> method.</p>
<p>Note that if you are in the unfortunate case where you use an API which returns <code>File</code> objects, you can always do:</p>
<pre><code>theFileObject.toPath()
</code></pre>
<p>But in code of yours, use <code>Path</code>. Systematically. Without a second thought.</p>
<p><strong>EDIT</strong> Copying a file to another using 1.6 using NIO can be done as such; note that the <code>Closer</code> class is inspited by <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Closer.html" rel="noreferrer">Guava</a>:</p>
<pre><code>public final class Closer
implements Closeable
{
private final List<Closeable> closeables = new ArrayList<Closeable>();
// @Nullable is a JSR 305 annotation
public <T extends Closeable> T add(@Nullable final T closeable)
{
closeables.add(closeable);
return closeable;
}
public void closeQuietly()
{
try {
close();
} catch (IOException ignored) {
}
}
@Override
public void close()
throws IOException
{
IOException toThrow = null;
final List<Closeable> l = new ArrayList<Closeable>(closeables);
Collections.reverse(l);
for (final Closeable closeable: l) {
if (closeable == null)
continue;
try {
closeable.close();
} catch (IOException e) {
if (toThrow == null)
toThrow = e;
}
}
if (toThrow != null)
throw toThrow;
}
}
// Copy one file to another using NIO
public static void doCopy(final File source, final File destination)
throws IOException
{
final Closer closer = new Closer();
final RandomAccessFile src, dst;
final FileChannel in, out;
try {
src = closer.add(new RandomAccessFile(source.getCanonicalFile(), "r");
dst = closer.add(new RandomAccessFile(destination.getCanonicalFile(), "rw");
in = closer.add(src.getChannel());
out = closer.add(dst.getChannel());
in.transferTo(0L, in.size(), out);
out.force(false);
} finally {
closer.close();
}
}
</code></pre> |
17,596,246 | Access scope variables from a filter in AngularJS | <p>I am passing <code>date</code> value to my custom filter this way:</p>
<pre><code>angular.module('myapp').
filter('filterReceiptsForDate', function () {
return function (input, date) {
var out = _.filter(input, function (item) {
return moment(item.value.created).format('YYYY-MM-DD') == date;
});
return out;
}
});
</code></pre>
<p>I would like to inject a couple of scope variables there too, like what I can do in directives. Is that possible to do this without having to passing these vars explicitly as function arguments?</p> | 17,597,023 | 2 | 0 | null | 2013-07-11 14:34:55.57 UTC | 11 | 2017-03-22 04:45:03.917 UTC | null | null | null | null | 135,829 | null | 1 | 75 | javascript|angularjs|scope | 69,291 | <p>Apparently you can.</p>
<p>Usually you would pass scope variables to the filter as function parameter:</p>
<pre class="lang-js prettyprint-override"><code>function MyCtrl($scope){
$scope.currentDate = new Date();
$scope.dateFormat = 'short';
}
</code></pre>
<pre class="lang-html prettyprint-override"><code><span ng-controller="MyCtrl">{{currentDate | date:dateFormat}}</span> // --> 7/11/13 4:57 PM
</code></pre>
<p>But, to pass the current scope in, you'd have to pass <code>this</code>:</p>
<pre class="lang-html prettyprint-override"><code><span ng-controller="MyCtrl">{{currentDate | date:this}}</span>
</code></pre>
<p>and <code>this</code> will be a reference to current scope:</p>
<p>Simplified:</p>
<pre class="lang-js prettyprint-override"><code>app.controller('AppController',
function($scope) {
$scope.var1 = 'This is some text.';
$scope.var2 = 'And this is appended with custom filter.';
}
);
app.filter('filterReceiptsForDate', function () {
return function (input, scope) {
return input + ' <strong>' + scope.var2 + '</strong>';
};
});
</code></pre>
<pre class="lang-html prettyprint-override"><code><div ng-bind-html-unsafe="var1 | filterReceiptsForDate:this"></div>
<!-- Results in: "This is some text. <strong>And this is appended with custom filter.</strong>" -->
</code></pre>
<p><kbd><a href="http://plnkr.co/edit/8bHvoKVpACjFkgkP5iCn?p=preview" rel="noreferrer">PLUNKER</a></kbd></p>
<h2>Warning:</h2>
<ol>
<li>Be careful with this and use scope only to read the values inside the filter, because otherwise you will easily find your self in $digest loop.</li>
<li>Filters that require such a "heavy" dependency (the whole scope) tend to be very difficult to test.</li>
</ol> |
37,139,019 | Excel VBA - Convert Date String to Date | <p>I have a number of strings in cells which are dates but they need to be converted to date format.</p>
<p>They are in the following format: </p>
<pre><code>mmm dd, yyyy
</code></pre>
<p>For Example: </p>
<pre><code>Feb 10, 2016
</code></pre>
<p>So they can be 11 or 12 in length: </p>
<pre><code>Feb 1, 2016
</code></pre>
<p>I have started writing a function to parse each part of the string individually (day as integer, month as integer and year as integer) to then convert into date format.</p>
<p>Firstly, is there an easier/slicker way to do this than the above?</p>
<p>If there isn't an easier way, what's the best was to convert the 3 letter month (e.g. Feb or Mar or Apr) into a month number (e.g. 2 or 3 or 4)? As that is the only bit I'm really stuck with.</p> | 37,139,272 | 4 | 3 | null | 2016-05-10 12:47:24.927 UTC | 2 | 2020-04-23 19:55:10.247 UTC | 2020-04-23 19:55:10.247 UTC | null | 11,636,588 | null | 5,873,603 | null | 1 | 1 | excel|vba | 44,919 | <p>In VBA you could use: <code>cdate("Feb 10, 2016")</code>.<br>
As a function this would be: </p>
<pre><code>Public Function ConvertToDate(rng As Range) As Date
ConvertToDate = CDate(rng)
End Function
</code></pre> |
5,079,797 | What's wrong with Groovy multi-line String? | <p>Groovy scripts raises an error:</p>
<pre><code>def a = "test"
+ "test"
+ "test"
</code></pre>
<p>Error:</p>
<pre><code>No signature of method: java.lang.String.positive() is
applicable for argument types: () values: []
</code></pre>
<p>While this script works fine:</p>
<pre><code>def a = new String(
"test"
+ "test"
+ "test"
)
</code></pre>
<p>Why?</p> | 5,079,914 | 3 | 1 | null | 2011-02-22 15:01:02.793 UTC | 16 | 2019-09-03 14:04:09.08 UTC | 2019-09-03 14:04:09.08 UTC | null | 1,828,296 | null | 187,141 | null | 1 | 146 | string|groovy|multiline | 130,610 | <p>As groovy doesn't have EOL marker (such as <code>;</code>) it gets confused if you put the operator on the following line</p>
<p>This would work instead:</p>
<pre><code>def a = "test" +
"test" +
"test"
</code></pre>
<p>as the Groovy parser knows to expect something on the following line</p>
<p>Groovy sees your original <code>def</code> as three separate statements. The first assigns <code>test</code> to <code>a</code>, the second two try to make <code>"test"</code> positive (and this is where it fails)</p>
<p>With the <code>new String</code> constructor method, the Groovy parser is still in the constructor (as the brace hasn't yet closed), so it can logically join the three lines together into a single statement</p>
<p>For true multi-line Strings, you can also use the triple quote:</p>
<pre><code>def a = """test
test
test"""
</code></pre>
<p>Will create a String with test on three lines</p>
<p>Also, you can make it neater by:</p>
<pre><code>def a = """test
|test
|test""".stripMargin()
</code></pre>
<p>the <a href="http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/CharSequence.html#stripMargin%28%29" rel="noreferrer"><code>stripMargin</code> method</a> will trim the left (up to and including the <code>|</code> char) from each line</p> |
9,407,892 | How to generate random SHA1 hash to use as ID in node.js? | <p>I am using this line to generate a sha1 id for node.js:</p>
<pre><code>crypto.createHash('sha1').digest('hex');
</code></pre>
<p>The problem is that it's returning the same id every time.</p>
<p>Is it possible to have it generate a random id each time so I can use it as a database document id?</p> | 9,408,217 | 5 | 4 | null | 2012-02-23 05:51:54.11 UTC | 98 | 2022-07-06 09:07:56.5 UTC | 2014-02-05 23:48:11.553 UTC | null | 633,183 | null | 206,446 | null | 1 | 151 | javascript|node.js|random|sha1|entropy | 111,546 | <p>Have a look here: <a href="https://stackoverflow.com/questions/7480158/how-do-i-use-node-js-crypto-to-create-a-hmac-sha1-hash">How do I use node.js Crypto to create a HMAC-SHA1 hash?</a>
I'd create a hash of the current timestamp + a random number to ensure hash uniqueness:</p>
<pre><code>var current_date = (new Date()).valueOf().toString();
var random = Math.random().toString();
crypto.createHash('sha1').update(current_date + random).digest('hex');
</code></pre> |
27,867,328 | Creating Professional Looking Powerpoints in R | <p>Is there a good way to use data from R and a package like ReporteRs to generate complete Powerpoints?
I have about 900 slides to create. Our analysts currently follow this path:</p>
<p>DB --> SAS --> CSV --> PPTX (embedded graphics) (x900 times)</p>
<p>This is manual, open to lots of errors and slow.</p>
<p>Ideally, I would prefer:</p>
<p>DB --> R + ReporteRs --> PPTX (x1 time)</p>
<p>The issue is 2-fold. First, our clients (unreasonably) prefer PPTX over a web or even PDF format. Second, R graphics cannot be edited in PPTX, and are sometimes not ideally sized/formatted, especially in terms of axis text sizes. <strong>So is there a way to use R to create editable Powerpoint graphics, hyperlinked tables of contents, etc?</strong> If not that, is there at least <strong>a good set of ggplot2 templates to use with decent PPTX presentation formatting</strong>?</p> | 53,136,776 | 2 | 9 | null | 2015-01-09 18:56:41.617 UTC | 12 | 2018-11-04 00:36:28.627 UTC | 2015-01-31 19:03:15.95 UTC | null | 1,898,580 | null | 3,652,621 | null | 1 | 15 | r|package|powerpoint|reporters | 3,667 | <p>You can use my new <code>export</code> package that just came out on CRAN to easily export to Office (Word/Powerpoint) in native Office vector format, resulting in fully editable graphs, see
<a href="https://cran.r-project.org/web/packages/export/index.html" rel="nofollow noreferrer">https://cran.r-project.org/web/packages/export/index.html</a> and
<a href="https://github.com/tomwenseleers/export" rel="nofollow noreferrer">https://github.com/tomwenseleers/export</a></p>
<p>For example:</p>
<pre><code>install.packages("export")
library(export)
?graph2ppt
?graph2doc
library(ggplot2)
qplot(Sepal.Length, Petal.Length, data = iris, color = Species,
size = Petal.Width, alpha = I(0.7))
graph2ppt(file="ggplot2_plot.pptx", width=7, height=5)
graph2doc(file="ggplot2_plot.docx", width=7, height=5)
</code></pre> |
15,455,048 | Releasing memory in Python | <p>I have a few related questions regarding memory usage in the following example.</p>
<ol>
<li><p>If I run in the interpreter,</p>
<pre><code>foo = ['bar' for _ in xrange(10000000)]
</code></pre>
<p>the real memory used on my machine goes up to <code>80.9mb</code>. I then,</p>
<pre><code>del foo
</code></pre>
<p>real memory goes down, but only to <code>30.4mb</code>. The interpreter uses <code>4.4mb</code> baseline so what is the advantage in not releasing <code>26mb</code> of memory to the OS? Is it because Python is "planning ahead", thinking that you may use that much memory again?</p></li>
<li><p>Why does it release <code>50.5mb</code> in particular - what is the amount that is released based on?</p></li>
<li><p>Is there a way to force Python to release all the memory that was used (if you know you won't be using that much memory again)?</p></li>
</ol>
<p><strong>NOTE</strong>
This question is different from <a href="https://stackoverflow.com/questions/1316767/how-can-i-explicitly-free-memory-in-python">How can I explicitly free memory in Python?</a>
because this question primarily deals with the increase of memory usage from baseline even after the interpreter has freed objects via garbage collection (with use of <code>gc.collect</code> or not).</p> | 15,457,947 | 4 | 5 | null | 2013-03-16 21:44:59.94 UTC | 72 | 2021-04-11 01:00:03.813 UTC | 2019-01-20 16:52:39.947 UTC | null | 2,147,024 | null | 2,147,024 | null | 1 | 160 | python|memory-management | 178,851 | <p>Memory allocated on the heap can be subject to high-water marks. This is complicated by Python's internal optimizations for allocating small objects (<code>PyObject_Malloc</code>) in 4 KiB pools, classed for allocation sizes at multiples of 8 bytes -- up to 256 bytes (512 bytes in 3.3). The pools themselves are in 256 KiB arenas, so if just one block in one pool is used, the entire 256 KiB arena will not be released. In Python 3.3 the small object allocator was switched to using anonymous memory maps instead of the heap, so it should perform better at releasing memory.</p>
<p>Additionally, the built-in types maintain freelists of previously allocated objects that may or may not use the small object allocator. The <code>int</code> type maintains a freelist with its own allocated memory, and clearing it requires calling <code>PyInt_ClearFreeList()</code>. This can be called indirectly by doing a full <code>gc.collect</code>.</p>
<p>Try it like this, and tell me what you get. Here's the link for <a href="https://psutil.readthedocs.io/en/latest/index.html#psutil.Process.memory_info" rel="noreferrer">psutil.Process.memory_info</a>.</p>
<pre><code>import os
import gc
import psutil
proc = psutil.Process(os.getpid())
gc.collect()
mem0 = proc.memory_info().rss
# create approx. 10**7 int objects and pointers
foo = ['abc' for x in range(10**7)]
mem1 = proc.memory_info().rss
# unreference, including x == 9999999
del foo, x
mem2 = proc.memory_info().rss
# collect() calls PyInt_ClearFreeList()
# or use ctypes: pythonapi.PyInt_ClearFreeList()
gc.collect()
mem3 = proc.memory_info().rss
pd = lambda x2, x1: 100.0 * (x2 - x1) / mem0
print "Allocation: %0.2f%%" % pd(mem1, mem0)
print "Unreference: %0.2f%%" % pd(mem2, mem1)
print "Collect: %0.2f%%" % pd(mem3, mem2)
print "Overall: %0.2f%%" % pd(mem3, mem0)
</code></pre>
<p>Output:</p>
<pre><code>Allocation: 3034.36%
Unreference: -752.39%
Collect: -2279.74%
Overall: 2.23%
</code></pre>
<p>Edit:</p>
<p>I switched to measuring relative to the process VM size to eliminate the effects of other processes in the system.</p>
<p>The C runtime (e.g. glibc, msvcrt) shrinks the heap when contiguous free space at the top reaches a constant, dynamic, or configurable threshold. With glibc you can tune this with <a href="http://man7.org/linux/man-pages/man3/mallopt.3.html" rel="noreferrer"><code>mallopt</code></a> (M_TRIM_THRESHOLD). Given this, it isn't surprising if the heap shrinks by more -- even a lot more -- than the block that you <code>free</code>.</p>
<p>In 3.x <code>range</code> doesn't create a list, so the test above won't create 10 million <code>int</code> objects. Even if it did, the <code>int</code> type in 3.x is basically a 2.x <code>long</code>, which doesn't implement a freelist.</p> |
15,373,823 | Template default arguments | <p>If I am allowed to do the following:</p>
<pre><code>template <typename T = int>
class Foo{
};
</code></pre>
<p>Why am I not allowed to do the following in main?</p>
<pre><code>Foo me;
</code></pre>
<p>But I must specify the following:</p>
<pre><code>Foo<int> me;
</code></pre>
<p>C++11 introduced default template arguments and right now they are being elusive to my complete understanding.</p> | 15,373,833 | 6 | 0 | null | 2013-03-12 22:52:49.763 UTC | 36 | 2022-04-14 14:29:56.837 UTC | 2015-06-23 22:53:14.497 UTC | null | 63,550 | null | 633,658 | null | 1 | 202 | c++|templates | 108,685 | <p><em><strong>Note:</strong></em></p>
<p><code>Foo me;</code> without template arguments is legal as of C++17. See this answer: <a href="https://stackoverflow.com/a/50970942/539997">https://stackoverflow.com/a/50970942/539997</a>.</p>
<p><em><strong>Original answer applicable before C++17:</strong></em></p>
<p>You have to do:</p>
<pre><code>Foo<> me;
</code></pre>
<p>The template arguments must be present but you can leave them empty.</p>
<p>Think of it like a function <code>foo</code> with a single default argument. The expression <code>foo</code> won't call it, but <code>foo()</code> will. The argument syntax must still be there. This is consistent with that.</p> |
8,334,049 | How to get all the account details using Get-MailBox | <p>I know this is silly question but I am new with Powershell cmdlet.</p>
<p>I want all details of user of a mailbox. I am using <code>Get-MailBox</code> but I just get Alias name and name there, but I want all the details. I can't find any parameter for that even. Is there any way??Thank You</p> | 8,334,481 | 2 | 2 | null | 2011-11-30 22:41:55.98 UTC | 1 | 2014-10-08 21:33:34.657 UTC | 2011-11-30 22:58:28.21 UTC | null | 2,975 | null | 1,073,975 | null | 1 | 4 | c#|.net|powershell|asp.net-3.5|exchange-server | 88,363 | <p>If you're new to <a href="http://technet.microsoft.com/en-us/scriptcenter/dd742419" rel="noreferrer">PowerShell</a> I suggest you look at some of the resources <a href="http://social.technet.microsoft.com/wiki/contents/articles/windows-powershell-survival-guide.aspx" rel="noreferrer">here</a>. Apart from that you probably want to use <code>Get-Member</code>, <code>Select-Object</code> and/or <code>Format-List</code>. Perhaps doing something like:</p>
<pre><code>PS> Get-MailBox | Get-Member
</code></pre>
<p>a load of properties and methods will be scrolling by you can select the properties you wish to see using something like</p>
<pre><code>PS> Get-MailBox | Select-Object Alias
</code></pre>
<p>To get all available information you could use <code>Format-List</code> with the <code>*</code> glob like so:</p>
<pre><code>PS> Get-MailBox | Format-List *
</code></pre>
<p>I don't have acces to an Exchange environment so I can't provide any specific examples I'm afraid.</p> |
8,191,105 | How to extract url data from Reddit API using JSON | <p>I'm trying to extract the image post URLs from a subreddit feed, and render <code><img></code> elements on my page.</p>
<p>Been trying to hack together the <code>.getJSON()</code> <a href="http://api.jquery.com/jQuery.getJSON/#example-0" rel="nofollow noreferrer">Flickr example</a> from the jQuery Docs for a while now and I'm not getting anywhere. </p>
<p>Code in question:</p>
<pre><code>$.getJSON('http://www.reddit.com/r/pics.json', function (data) {
$.each(data.children, function (i, item) {
$('<img/>').attr("src", url).appendTo("#images");
});
});
</code></pre>
<p>In the body, I have the element: <code>div#images</code></p>
<p>I understand that I need to use JSONP, but not sure how. Can somebody point me in the right direction?</p> | 8,191,296 | 2 | 0 | null | 2011-11-19 01:16:44.433 UTC | 8 | 2021-03-23 05:29:46.477 UTC | 2016-08-25 21:50:57.533 UTC | null | 362,136 | null | 362,136 | null | 1 | 14 | javascript|json|api|reddit | 26,485 | <p>You are using the wrong url. Use this: </p>
<pre><code>$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) {
// Do whatever you want with it..
});
</code></pre>
<p><strong>EDIT :</strong> Working example based on your <a href="http://jsfiddle.net/DHKtW/" rel="noreferrer">fiddle</a> in the comments.</p>
<pre><code>$.getJSON("http://www.reddit.com/r/pics/.json?jsonp=?", function(data) {
$.each(data.data.children, function(i,item){
$("<img/>").attr("src", item.data.url).appendTo("#images");
});
});
</code></pre>
<p>You should use <code>data.data.children</code> and not <code>data.children</code></p> |
19,623,100 | Java Access DB Connection | <p>I try to make project with connection to db (MS Access 2010)
I use this tutorial <a href="http://www.codeproject.com/Articles/35018/Access-MS-Access-Databases-from-Java" rel="nofollow noreferrer">on CodeProject</a>.</p>
<pre><code>import java.sql.*;
public class DbAccess
{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database =
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=myDB.mdb;";
Connection conn = DriverManager.getConnection(database, "", "");
Statement s = conn.createStatement();
// create a table
String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0));
String createTable = "CREATE TABLE " + tableName +
" (id Integer, name Text(32))";
s.execute(createTable);
// enter value into table
for(int i=0; i<25; i++)
{
String addRow = "INSERT INTO " + tableName + " VALUES ( " +
String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " +
String.valueOf(Math.random()) + "')";
s.execute(addRow);
}
// Fetch table
String selTable = "SELECT * FROM " + tableName;
s.execute(selTable);
ResultSet rs = s.getResultSet();
while((rs!=null) && (rs.next()))
{
System.out.println(rs.getString(1) + " : " + rs.getString(2));
}
// drop the table
String dropTable = "DROP TABLE " + tableName;
s.execute(dropTable);
// close and cleanup
s.close();
conn.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
</code></pre>
<p>But i get strange Exception : java.sql.SQLException: [Microsoft][????????? ????????? ODBC] ???????? ?????? ?? ?????? ? ?? ?????? ???????, ???????????? ?? ?????????</p>
<blockquote>
<p>java.sql.SQLException: [Microsoft][????????? ????????? ODBC] ????????
?????? ?? ?????? ? ?? ?????? ???????, ???????????? ?? ????????? at
sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956) at
sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113) at
sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(JdbcOdbc.java:3072) at
sun.jdbc.odbc.JdbcOdbcConnection.initialize(JdbcOdbcConnection.java:323)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(JdbcOdbcDriver.java:174) at
java.sql.DriverManager.getConnection(DriverManager.java:579) at
java.sql.DriverManager.getConnection(DriverManager.java:221) at
dbaccess.DbAccess.main(DbAccess.java:28)</p>
</blockquote>
<p>I google it and find other questions on Stack like this : <a href="https://stackoverflow.com/questions/15893262/java-sql-sqlexception-microsoftodbc-microsoft-access-driver">Stack Post</a></p>
<p>So i add all ODBC drivers that can help me connect *.mdb file. But nothing good hepend.(</p>
<p>What is it and how connect to Access DB?</p> | 19,741,625 | 2 | 9 | null | 2013-10-27 20:24:13.713 UTC | 1 | 2017-08-17 09:36:15.377 UTC | 2017-05-23 12:03:02.517 UTC | null | -1 | null | 2,167,382 | null | 1 | 5 | java|database-connection|jdbc-odbc | 58,410 | <p>There is nothing fundamentally wrong with your code because I pasted it into Eclipse and it ran fine. The only change I made was to specify the path to the database file, i.e., instead of using</p>
<pre><code>DBQ=myDB.mdb
</code></pre>
<p>I used</p>
<pre><code>DBQ=C:\\__tmp\\myDB.mdb
</code></pre>
<p>I was also running it under a 32-bit JVM (on a 32-bit computer). So, my suggestions would be</p>
<ol>
<li><p>Try specifying the complete path to the <code>.mdb</code> file like I did.</p></li>
<li><p>If you still get an error, check your Java environment to see if your application is running in a 64-bit JVM. If it is, then <code>Driver={Microsoft Access Driver (*.mdb)}</code> will not work: there is no 64-bit version of the older Jet ODBC driver. In that case you have two options:</p>
<p>i. Configure your application to run in a 32-bit JVM, or</p>
<p>ii. Download and install the 64-bit version of the Access Database Engine from <a href="http://www.microsoft.com/en-US/download/details.aspx?id=13255" rel="nofollow">here</a>, and then use <code>Driver={Microsoft Access Driver (*.mdb, *.accdb)}</code>.</p></li>
</ol> |
8,426,773 | How to refresh a parent page after closing sharepoint dialog? | <p>How to refresh a parent page after closing sharepoint dialog?
Here is my coding to open a pop-up.</p>
<pre><code><input type="button" value="Add" class="button submit" style="width: 80px" onclick="javascript:OpenAttachmentUpload()" />
<script type="text/javascript">
//User Defined Function to Open Dialog Framework
function OpenAttachmentUpload() {
var strPageURL = '<%= ResolveClientUrl("~/Dialogs/AttachUpload.aspx") %>';
//OpenFixCustomDialog(strPageURL, "Attachment");
OpenCustomDialog(strPageURL, 350, 200, "Attachment");
return false;
}
</script>
</code></pre>
<p>here is the script.</p>
<pre><code>function OpenCustomDialog(dialogUrl, dialogWidth, dialogHeight, dialogTitle, dialogAllowMaximize, dialogShowClose) {
var options = {
url: dialogUrl,
allowMaximize: dialogAllowMaximize,
showClose: dialogShowClose,
width: dialogWidth,
height: dialogHeight,
title: dialogTitle,
dialogReturnValueCallback: Function.createDelegate(null, CloseCallback3)
};
SP.UI.ModalDialog.showModalDialog(options);
}
</code></pre>
<p>After opening it, when I close the pop-up <strong>(~/Dialogs/AttachUpload.aspx)</strong> , I wanna refresh the parent page.
How can I do it?
I google and see <strong>SP.UI.ModalDialog.RefreshPage</strong> but still can't find an answer for me.
Thanks.</p>
<p>P.s
I don't know much about SharePoint.</p> | 8,428,532 | 5 | 4 | null | 2011-12-08 05:51:26.023 UTC | 8 | 2016-01-20 13:19:27.52 UTC | null | null | null | null | 631,733 | null | 1 | 16 | c#|sharepoint|dialog|modal-dialog | 46,628 | <p>You're almost there.</p>
<p>In the option <code>dialogReturnValueCallback</code> you can define a function that will be executed after the dialog was closed. By now you create a delegate pointing to <code>CloseCallback3</code> but this is not defined in your code.</p>
<p>If you call <code>SP.UI.ModalDialog.RefreshPage</code> in this callback method the page gets refreshed after the dialog was closed with <em>OK</em>.</p>
<pre><code> var options =
{
url: dialogUrl,
allowMaximize: dialogAllowMaximize,
showClose: dialogShowClose,
width: dialogWidth,
height: dialogHeight,
title: dialogTitle,
dialogReturnValueCallback: function(dialogResult)
{
SP.UI.ModalDialog.RefreshPage(dialogResult)
}
}
</code></pre>
<p><strong>Btw:</strong>
You use <code>javascript:</code> in the <code>onclick</code> of the button. This is not necessary. this is only required in the <code>href</code> of an <code>a</code> tag</p> |
5,452,555 | Converting timezone-aware datetime to local time in Python | <p>How do you convert a timezone-aware datetime object to the equivalent non-timezone-aware datetime for the local timezone?</p>
<p>My particular application uses Django (although, this is in reality a generic Python question):</p>
<pre><code>import iso8601
</code></pre>
<p>....</p>
<pre><code>date_str="2010-10-30T17:21:12Z"
</code></pre>
<p>....</p>
<pre><code>d = iso8601.parse_date(date_str)
foo = app.models.FooModel(the_date=d)
foo.save()
</code></pre>
<p>This causes Django to throw an error: </p>
<pre><code>raise ValueError("MySQL backend does not support timezone-aware datetimes.")
</code></pre>
<p>What I need is:</p>
<pre><code>d = iso8601.parse_date(date_str)
local_d = SOME_FUNCTION(d)
foo = app.models.FooModel(the_date=local_d)
</code></pre>
<p>What would <strong>SOME_FUNCTION</strong> be?</p> | 5,452,709 | 5 | 1 | null | 2011-03-27 21:24:13.78 UTC | 19 | 2022-09-15 08:28:01.26 UTC | null | null | null | null | 13,271 | null | 1 | 53 | python|django|datetime|iso8601 | 71,527 | <p>In general, to convert an arbitrary timezone-aware datetime to a naive (local) datetime, I'd use the <code>pytz</code> module and <code>astimezone</code> to convert to local time, and <code>replace</code> to make the datetime naive:</p>
<pre><code>In [76]: import pytz
In [77]: est=pytz.timezone('US/Eastern')
In [78]: d.astimezone(est)
Out[78]: datetime.datetime(2010, 10, 30, 13, 21, 12, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
In [79]: d.astimezone(est).replace(tzinfo=None)
Out[79]: datetime.datetime(2010, 10, 30, 13, 21, 12)
</code></pre>
<p>But since your particular datetime seems to be in the UTC timezone, you could do this instead:</p>
<pre><code>In [65]: d
Out[65]: datetime.datetime(2010, 10, 30, 17, 21, 12, tzinfo=tzutc())
In [66]: import datetime
In [67]: import calendar
In [68]: datetime.datetime.fromtimestamp(calendar.timegm(d.timetuple()))
Out[68]: datetime.datetime(2010, 10, 30, 13, 21, 12)
</code></pre>
<hr>
<p>By the way, you might be better off storing the datetimes as naive UTC datetimes instead of naive local datetimes. That way, your data is local-time agnostic, and you only convert to local-time or any other timezone when necessary. Sort of analogous to working in unicode as much as possible, and encoding only when necessary.</p>
<p>So if you agree that storing the datetimes in naive UTC is the best way, then all you'd need to do is define:</p>
<pre><code>local_d = d.replace(tzinfo=None)
</code></pre> |
4,919,191 | Simulating touch events on a PC browser | <p>I am developing an HTML application for the iPad. As such it utilizes touch events and webkit-CSS animations.</p>
<p>Up until now I have used chrome as my debugging environment because of it's awesome developer mode.</p>
<p>What I would like is to be able to debug my Html/JavaScript using Google-Chrome's debugger on my PC while simulating touch events with my mouse.</p>
<p>My site does not have any multi-touch events and no mouse events (no mouse on iPad).</p>
<p>I am not actually interested in seeing the applications layout, but more in debugging its behavior.</p>
<p>Is there some plugin to get mouse events translated into touch events on a desktop browser?</p> | 10,150,177 | 5 | 2 | null | 2011-02-07 08:15:06.663 UTC | 22 | 2016-10-31 14:32:50.59 UTC | 2016-03-08 04:28:02.993 UTC | null | 5,530,155 | null | 508,459 | null | 1 | 72 | javascript|ipad|html|google-chrome|touch | 53,031 | <p><strong>As of April 13th 2012</strong></p>
<p>In Google Chrome developer and canary builds there is now a checkbox for "Emulate touch events"</p>
<p>You can find it by opening the F12 developer tools and clicking on the gear at the bottom right of the screen.</p>
<p><img src="https://i.stack.imgur.com/VqZOJ.png" alt="on Chrome v22 Mac OS X"></p>
<p>For now (Chrome ver.36.0.1985.125) you can find it here: F12 => Esc => Emulation.
<img src="https://i.stack.imgur.com/mNZQN.png" alt="console"></p> |
5,408,276 | Sampling uniformly distributed random points inside a spherical volume | <p>I am looking to be able to generate a random uniform sample of particle locations that fall within a spherical volume.</p>
<p>The image below (courtesy of <a href="http://nojhan.free.fr/metah/" rel="noreferrer">http://nojhan.free.fr/metah/</a>) shows what I am looking for. This is a slice through the sphere, showing a uniform distribution of points:</p>
<p><img src="https://i.stack.imgur.com/udd8T.png" alt="Uniformly distributed circle"></p>
<p>This is what I am currently getting:</p>
<p><img src="https://i.stack.imgur.com/eu7Jc.png" alt="Uniformly Distributed but Cluster Of Points"></p>
<p>You can see that there is a cluster of points at the center due to the conversion between spherical and Cartesian coordinates. </p>
<p>The code I am using is:</p>
<pre><code>def new_positions_spherical_coordinates(self):
radius = numpy.random.uniform(0.0,1.0, (self.number_of_particles,1))
theta = numpy.random.uniform(0.,1.,(self.number_of_particles,1))*pi
phi = numpy.arccos(1-2*numpy.random.uniform(0.0,1.,(self.number_of_particles,1)))
x = radius * numpy.sin( theta ) * numpy.cos( phi )
y = radius * numpy.sin( theta ) * numpy.sin( phi )
z = radius * numpy.cos( theta )
return (x,y,z)
</code></pre>
<p>Below is some MATLAB code that supposedly creates a uniform spherical sample, which is similar to the equation given by <a href="http://nojhan.free.fr/metah" rel="noreferrer">http://nojhan.free.fr/metah</a>. I just can't seem to decipher it or understand what they did. </p>
<pre><code>function X = randsphere(m,n,r)
% This function returns an m by n array, X, in which
% each of the m rows has the n Cartesian coordinates
% of a random point uniformly-distributed over the
% interior of an n-dimensional hypersphere with
% radius r and center at the origin. The function
% 'randn' is initially used to generate m sets of n
% random variables with independent multivariate
% normal distribution, with mean 0 and variance 1.
% Then the incomplete gamma function, 'gammainc',
% is used to map these points radially to fit in the
% hypersphere of finite radius r with a uniform % spatial distribution.
% Roger Stafford - 12/23/05
X = randn(m,n);
s2 = sum(X.^2,2);
X = X.*repmat(r*(gammainc(s2/2,n/2).^(1/n))./sqrt(s2),1,n);
</code></pre>
<p>I would greatly appreciate any suggestions on generating a truly uniform sample from a spherical volume in Python.</p>
<p>There seem to be plenty of examples showing how to sample from a uniform spherical shell, but that seems to be easier an easier problem. The issue has to do with the scaling - there should be fewer particles at a radius of 0.1 than at a radius of 1.0 to generate a uniform sample from the volume of the sphere.</p>
<p><strong><em>Edit:</em></strong> Fixed and removed the fact I asked for normally and I meant uniform.</p> | 5,408,843 | 10 | 1 | null | 2011-03-23 16:11:51.73 UTC | 24 | 2022-03-18 21:54:11.42 UTC | 2018-12-23 08:38:12.807 UTC | null | 815,724 | null | 329,344 | null | 1 | 40 | python|matlab|random|geometry|uniform-distribution | 58,275 | <p>While I prefer the discarding method for spheres, for completeness <a href="https://stackoverflow.com/questions/918736/random-number-generator-that-produces-a-power-law-distribution/918782#918782">I offer the exact solution</a>.</p>
<p>In spherical coordinates, taking advantage of the <a href="https://stackoverflow.com/questions/2106503/pseudorandom-number-generator-exponential-distribution/2106568#2106568">sampling rule</a>:</p>
<pre><code>phi = random(0,2pi)
costheta = random(-1,1)
u = random(0,1)
theta = arccos( costheta )
r = R * cuberoot( u )
</code></pre>
<p>now you have a <code>(r, theta, phi)</code> group which can be transformed to <code>(x, y, z)</code> in the usual way</p>
<pre><code>x = r * sin( theta) * cos( phi )
y = r * sin( theta) * sin( phi )
z = r * cos( theta )
</code></pre> |
5,180,365 | Add commas into number string | <p>I have a value running through my program that puts out a number rounded to 2 decimal places at the end, like this:</p>
<pre><code>print ("Total cost is: ${:0.2f}".format(TotalAmount))
</code></pre>
<p>Is there a way to insert a comma value every 3 digits left of the decimal point?</p>
<p>e.g. <code>10000.00</code> becomes <code>10,000.00</code> or <code>1000000.00</code> becomes <code>1,000,000.00</code>.</p> | 5,180,405 | 11 | 0 | null | 2011-03-03 11:52:58.627 UTC | 16 | 2022-05-14 16:01:44.137 UTC | 2022-05-14 16:01:44.137 UTC | null | 68,587 | null | 192,944 | null | 1 | 83 | python|string | 118,716 | <p>In Python 2.7 and 3.x, you can use the format syntax <code>:,</code></p>
<pre class="lang-py prettyprint-override"><code>>>> total_amount = 10000
>>> print("{:,}".format(total_amount))
10,000
</code></pre>
<pre class="lang-py prettyprint-override"><code>>>> print("Total cost is: ${:,.2f}".format(total_amount))
Total cost is: $10,000.00
</code></pre>
<p>This is documented in <a href="http://www.python.org/dev/peps/pep-0378/" rel="noreferrer">PEP 378 -- Format Specifier for Thousands Separator</a> and has an example in the <a href="https://docs.python.org/3/library/string.html#format-examples" rel="noreferrer">Official Docs "Using the comma as a thousands separator"</a></p> |
5,385,714 | Deploying website: 500 - Internal server error | <p>I am trying to deploy an ASP.NET application. I have deployed the site to IIS, but when visiting it with the browser, it shows me this:</p>
<blockquote>
<p>Server Error</p>
<p>500 - Internal server error.</p>
<p>There is a problem with the resource you are looking for, and it cannot be displayed.</p>
</blockquote>
<p>After fiddling around with the web.config, I got:</p>
<blockquote>
<p>The page cannot be displayed because an internal server error has occurred.</p>
</blockquote>
<p>How can I see the actual issue behind this server error?</p> | 5,385,884 | 22 | 1 | null | 2011-03-22 01:22:43.83 UTC | 64 | 2022-06-21 14:50:13.567 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 559,884 | null | 1 | 216 | asp.net|iis|error-handling | 590,564 | <p>First, <strong>you need to enable and see detailed errors</strong> of your web messages, because this is a general message without giving information on what's really happening for security reasons.</p>
<p>With the detailed error, you can locate the real issue here.</p>
<p>Also, if you can <strong>run the browser on the server</strong>, you get details on the error, because the server recognizes that you are local and shows it to you. <strong>Or if you can read the log</strong> of the server using the Event Viewer, you also see the details of your error.</p>
<p>###On <a href="https://en.wikipedia.org/wiki/Internet_Information_Services" rel="nofollow noreferrer">IIS</a> 6</p>
<pre class="lang-xml prettyprint-override"><code><configuration>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true"/>
</system.web>
</configuration>
</code></pre>
<p>###On IIS 7</p>
<pre class="lang-xml prettyprint-override"><code><configuration>
<system.webServer>
<httpErrors errorMode="Detailed" />
<asp scriptErrorSentToBrowser="true"/>
</system.webServer>
<system.web>
<customErrors mode="Off"/>
<compilation debug="true"/>
</system.web>
</configuration>
</code></pre>
<p>Note: <strong>You can avoid the Debug=true</strong>. You only need to close the custom errors for a while and get the detailed error page.</p>
<p>This can help: <em><a href="https://docs.microsoft.com/archive/blogs/rakkimk/iis7-how-to-enable-the-detailed-error-messages-for-the-website-while-browsed-from-for-the-client-browsers" rel="nofollow noreferrer">How to enable the detailed error messages</a></em> (from IIS).</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.