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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3,957,252 | Is there any way to compute the width of an integer type at compile-time? | <p>The size of an integer type (or any type) in units of <code>char</code>/bytes is easily computed as <code>sizeof(type)</code>. A common idiom is to multiply by <code>CHAR_BIT</code> to find the number of bits occupied by the type, but on implementations with padding bits, this will not be equal to the <em>width</em> in value bits. Worse yet, code like:</p>
<pre><code>x>>CHAR_BIT*sizeof(type)-1
</code></pre>
<p>may actually have undefined behavior if <code>CHAR_BIT*sizeof(type)</code> is greater than the actual width of <code>type</code>.</p>
<p>For simplicity, let's assume our types are unsigned. Then the width of <code>type</code> is <code>ceil(log2((type)-1)</code>. Is there any way to compute this value as a constant expression?</p> | 4,589,384 | 7 | 8 | null | 2010-10-18 07:30:34.38 UTC | 12 | 2022-01-17 05:11:37.39 UTC | null | null | null | null | 379,897 | null | 1 | 17 | c|integer|width|padding | 4,670 | <p>There is a function-like macro that can determine the <strong><strong>value bits</strong></strong> of an integer type, but only if you already know that type's maximum value. Whether or not you'll get a compile-time constant depends on your compiler but I would guess in most cases the answer is yes.</p>
<p>Credit to Hallvard B. Furuseth for his IMAX_BITS() function-like macro that he posted in reply to a <a href="https://groups.google.com/g/comp.lang.c/c/NfedEFBFJ0k" rel="nofollow noreferrer">question on comp.lang.c</a></p>
<pre><code>/* Number of bits in inttype_MAX, or in any (1<<b)-1 where 0 <= b < 3E+10 */
#define IMAX_BITS(m) ((m) /((m)%0x3fffffffL+1) /0x3fffffffL %0x3fffffffL *30 \
+ (m)%0x3fffffffL /((m)%31+1)/31%31*5 + 4-12/((m)%31+3))
</code></pre>
<blockquote>
<p>IMAX_BITS(INT_MAX) computes the number of bits in an int, and IMAX_BITS((unsigned_type)-1) computes the number of bits in an unsigned_type. Until someone implements 4-gigabyte integers, anyway:-)</p>
</blockquote>
<br>
And <strike>credit to Eric Sosman</strike> for this [alternate version](http://groups.google.com/group/comp.lang.c/msg/e998153ef07ff04b?dmode=source) that should work with less than 2040 bits:
**(EDIT 1/3/2011 11:30PM EST: It turns out this version was also written by Hallvard B. Furuseth)**
<pre><code>/* Number of bits in inttype_MAX, or in any (1<<k)-1 where 0 <= k < 2040 */
#define IMAX_BITS(m) ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12))
</code></pre>
<br>
**Remember that although the width of an unsigned integer type is equal to the number of value bits, the width of a signed integer type is one greater (§6.2.6.2/6).** This is of special importance as in my original comment to your question I had incorrectly stated that the IMAX_BITS() macro calculates the width when it actually calculates the number of value bits. Sorry about that!
<p>So for example <code>IMAX_BITS(INT64_MAX)</code> will create a compile-time constant of 63. However, in this example, we are dealing with a signed type so you must add 1 to account for the sign bit if you want the actual width of an int64_t, which is of course 64.</p>
<p>In a separate comp.lang.c discussion a user named blargg gives a breakdown of how the macro works:<br />
<a href="https://web.archive.org/web/20150403064546/http://coding.derkeiler.com/Archive/C_CPP/comp.lang.c/2009-01/msg02242.html" rel="nofollow noreferrer">Re: using pre-processor to count bits in integer types...</a></p>
<p>Note that the macro only works with 2^n-1 values (ie all 1s in binary), as would be expected with any MAX value. Also note that while it is easy to get a compile-time constant for the maximum value of an unsigned integer type (<code>IMAX_BITS((unsigned type)-1)</code>), at the time of this writing I don't know any way to do the same thing for a signed integer type without invoking implementation-defined behavior. If I ever find out I'll answer my own related SO question, here:<br />
<a href="https://stackoverflow.com/questions/4514572/c-question-off-t-and-other-signed-integer-types-minimum-and-maximum-values">C question: off_t (and other signed integer types) minimum and maximum values - Stack Overflow</a></p> |
3,805,584 | Please explain about insertable=false and updatable=false in reference to the JPA @Column annotation | <p>If a field is annotated <code>insertable=false, updatable=false</code>, doesn't it mean that you cannot insert value nor change the existing value? Why would you want to do that?</p>
<pre><code>@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany(mappedBy="person", cascade=CascadeType.ALL)
private List<Address> addresses;
}
@Entity
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name="ADDRESS_FK")
@Column(insertable=false, updatable=false)
private Person person;
}
</code></pre> | 3,805,682 | 8 | 0 | null | 2010-09-27 15:59:16.273 UTC | 54 | 2021-06-25 09:45:34.013 UTC | 2019-07-18 16:04:41.457 UTC | null | 431,941 | null | 240,337 | null | 1 | 187 | java|jpa|jakarta-ee|eclipselink | 189,250 | <p>You would do that when the <strong>responsibility</strong> of creating/updating the referenced column isn't in the <em>current</em> entity, but in <em>another</em> entity.</p> |
3,770,187 | difference between int* i and int *i | <p>I'm converting a header file for a DLL written in C to Delphi so I can use the DLL. </p>
<p>My question is what is the difference between</p>
<pre><code>int* i
</code></pre>
<p>and</p>
<pre><code>int *i
</code></pre>
<p>I convert the first to</p>
<pre><code>i: PInteger;
</code></pre>
<p>But i'm not sure what the correct conversion is for the second one in Delphi.</p>
<p>from my understanding the first is a simple typed pointer.
The second is a pointer variable. but i'm not sure what the difference is.</p> | 3,770,204 | 9 | 1 | null | 2010-09-22 14:21:01.34 UTC | 13 | 2022-07-05 06:55:09.857 UTC | null | null | null | null | 407,361 | null | 1 | 40 | c|delphi | 25,254 | <p><code>int* i</code> and <code>int *i</code> are completely equivalent</p> |
3,653,298 | Concatenating two lists - difference between '+=' and extend() | <p>I've seen there are actually two (maybe more) ways to concatenate lists in Python:</p>
<p>One way is to use the <code>extend()</code> method:</p>
<pre><code>a = [1, 2]
b = [2, 3]
b.extend(a)
</code></pre>
<p>the other to use the plus (+) operator:</p>
<pre><code>b += a
</code></pre>
<p>Now I wonder: which of those two options is the 'pythonic' way to do list concatenation and is there a difference between the two? (I've looked up the official Python tutorial but couldn't find anything anything about this topic).</p> | 3,653,339 | 11 | 1 | null | 2010-09-06 17:35:50.797 UTC | 51 | 2022-07-07 08:46:57.5 UTC | 2022-03-23 16:59:02.297 UTC | null | 5,446,749 | null | 1,178,669 | null | 1 | 314 | list|python | 93,174 | <p>The only difference on a bytecode level is that the <a href="https://docs.python.org/2/library/array.html?#array.array.extend" rel="noreferrer"><code>.extend</code></a> way involves a function call, which is slightly more expensive in Python than the <a href="https://docs.python.org/2/library/dis.html?highlight=inplace_add#opcode-INPLACE_ADD" rel="noreferrer"><code>INPLACE_ADD</code></a>.</p>
<p>It's really nothing you should be worrying about, unless you're performing this operation billions of times. It is likely, however, that the bottleneck would lie some place else.</p> |
3,710,483 | Select where count of one field is greater than one | <p>I want to do something like this:</p>
<pre><code>SELECT *
FROM db.table
WHERE COUNT(someField) > 1
</code></pre>
<p>How can I achieve this in MySql?</p> | 3,710,501 | 11 | 0 | null | 2010-09-14 15:43:16.937 UTC | 14 | 2022-09-21 11:17:14.233 UTC | 2016-08-29 18:43:20.903 UTC | null | 4,823,977 | null | 301,816 | null | 1 | 116 | sql|mysql | 370,174 | <p>Use the <code>HAVING</code>, not <code>WHERE</code> clause, for aggregate result comparison.</p>
<p>Taking the query at face value:</p>
<pre><code>SELECT *
FROM db.table
HAVING COUNT(someField) > 1
</code></pre>
<p>Ideally, there should be a <code>GROUP BY</code> defined for proper valuation in the <code>HAVING</code> clause, but <a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html" rel="noreferrer">MySQL does allow hidden columns from the GROUP BY</a>...</p>
<p>Is this in preparation for a unique constraint on <code>someField</code>? Looks like it should be...</p> |
3,847,736 | How can I compare two dates in PHP? | <p>How can I compare two dates in PHP?</p>
<p>The date is stored in the database in the following format </p>
<blockquote>
<p>2011-10-2</p>
</blockquote>
<p>If I wanted to compare today's date against the date in the database to see which one is greater, how would I do it?</p>
<p>I tried this,</p>
<pre><code>$today = date("Y-m-d");
$expire = $row->expireDate //from db
if($today < $expireDate) { //do something; }
</code></pre>
<p>but it doesn't really work that way. What's another way of doing it?</p> | 3,847,782 | 13 | 1 | null | 2010-10-02 22:19:54.903 UTC | 25 | 2020-06-13 15:19:00.913 UTC | 2020-06-12 19:22:26.583 UTC | null | 1,839,439 | null | 451,725 | null | 1 | 147 | php|date|compare | 303,146 | <blockquote>
<p>in the database the date looks like this 2011-10-2</p>
</blockquote>
<p>Store it in YYYY-MM-DD and then string comparison will work because '1' > '0', etc.</p> |
3,396,754 | onKeyPress Vs. onKeyUp and onKeyDown | <p>What is the difference between these three events? Upon googling I found that:</p>
<blockquote>
<ul>
<li>The <code>onKeyDown</code> event is triggered when the user presses a key.</li>
<li>The <code>onKeyUp</code> event is triggered when the user releases a key.</li>
<li>The <code>onKeyPress</code> event is triggered when the user presses & releases a key
(<code>onKeyDown</code> followed by <code>onKeyUp</code>).</li>
</ul>
</blockquote>
<p>I understand the first two, but isn't <code>onKeyPress</code> the same as <code>onKeyUp</code>? Is it possible to release a key (<code>onKeyUp</code>) without pressing it (<code>onKeyDown</code>)?</p>
<p>This is a bit confusing, can someone clear this up for me?</p> | 3,396,790 | 14 | 3 | null | 2010-08-03 13:10:42.283 UTC | 112 | 2022-04-24 12:36:47.637 UTC | 2020-03-14 10:55:15.71 UTC | null | 462,347 | null | 391,441 | null | 1 | 452 | javascript|dom|dom-events | 372,137 | <p>Check here for the archived <a href="http://web.archive.org/web/20161212021242/http://www.bloggingdeveloper.com/post/KeyPress-KeyDown-KeyUp-The-Difference-Between-Javascript-Key-Events.aspx" rel="noreferrer">link</a> originally used in this answer.</p>
<p>From that link:</p>
<blockquote>
<p>In theory, the <code>onKeyDown</code> and <code>onKeyUp</code> events represent keys being pressed or released, while the <code>onKeyPress</code> event represents a character being typed. The implementation of the theory is not same in all browsers.</p>
</blockquote> |
7,793,009 | How to retrieve images from MySQL database and display in an html tag | <p>I created a MySQL database with a table using phpmyadmin. I created this table with a BLOB column to hold a jpeg file.</p>
<p>I have issues with regards to the php variable <code>$result</code> here.</p>
<p>My code so far: (catalog.php):</p>
<pre><code><body>
<?php
$link = mysql_connect("localhost", "root", "");
mysql_select_db("dvddb");
$sql = "SELECT dvdimage FROM dvd WHERE id=1";
$result = mysql_query("$sql");
mysql_close($link);
?>
<img src="" width="175" height="200" />
</body>
</code></pre>
<p>How can I get the variable $result from PHP into the HTML so I can display it in the <code><img></code> tag?</p> | 7,793,098 | 4 | 6 | null | 2011-10-17 11:20:40.403 UTC | 21 | 2022-08-30 18:58:33.88 UTC | 2013-04-17 16:05:45.207 UTC | null | 445,131 | null | 911,372 | null | 1 | 32 | php|mysql|html | 322,247 | <p>You can't. You need to create another php script to return the image data, e.g. getImage.php. Change catalog.php to:</p>
<pre><code><body>
<img src="getImage.php?id=1" width="175" height="200" />
</body>
</code></pre>
<p>Then getImage.php is</p>
<pre><code><?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "");
mysql_select_db("dvddb");
$sql = "SELECT dvdimage FROM dvd WHERE id=$id";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['dvdimage'];
?>
</code></pre> |
8,040,105 | Execute sp_executeSql for select...into #table but Can't Select out Temp Table Data | <p>Was trying to select...into a temp Table #TempTable in sp_Executedsql.
Not its successfully inserted or not but there Messages there written
(359 row(s) affected) that mean successful inserted?
Script below</p>
<pre><code>DECLARE @Sql NVARCHAR(MAX);
SET @Sql = 'select distinct Coloum1,Coloum2 into #TempTable
from SPCTable with(nolock)
where Convert(varchar(10), Date_Tm, 120) Between @Date_From And @Date_To';
SET @Sql = 'DECLARE @Date_From VARCHAR(10);
DECLARE @Date_To VARCHAR(10);
SET @Date_From = '''+CONVERT(VARCHAR(10),DATEADD(d,DATEDIFF(d,0,GETDATE()),0)-1,120)+''';
SET @Date_To = '''+CONVERT(VARCHAR(10),DATEADD(d,DATEDIFF(d,0,GETDATE()),0)-1,120)+''';
'+ @Sql;
EXECUTE sp_executesql @Sql;
</code></pre>
<p>After executed,its return me on messages (359 row(s) affected).
Next when trying to select out the data from #TempTable.</p>
<pre><code>Select * From #TempTable;
</code></pre>
<p>Its return me:</p>
<pre><code>Msg 208, Level 16, State 0, Line 2
Invalid object name '#TempTable'.
</code></pre>
<p>Suspected its working only the 'select' section only. The insert is not working.
how fix it?</p> | 8,040,185 | 9 | 0 | null | 2011-11-07 17:22:56.773 UTC | 3 | 2021-02-28 10:42:09.22 UTC | 2017-04-16 04:19:36.567 UTC | null | 1,033,581 | null | 883,398 | null | 1 | 47 | sql|sql-server-2008|tsql|sp-executesql|temp-tables | 89,170 | <p>Local temporary table <code>#table_name</code> is visible in current session only, global temporary <code>##table_name</code> tables are visible in all sessions. Both lives until their session is closed.
<code>sp_executesql</code> - creates its own session (maybe word "scope" would be better) so that's why it happens.</p> |
7,798,908 | Disable warning in IntelliJ for one line | <p>I have a Java code line where IntelliJ displays a warning. How do I silence the warning in that particular line, without affecting warnings displayed in other lines?</p>
<p>In this question it's irrelevant what the actual warning is: now I'm not seeking advice on how to improve the quality of a specific piece of Java code, but I want to know in general how to prevent IntelliJ from displaying a warning on a specific Java source line.</p> | 7,799,271 | 10 | 4 | null | 2011-10-17 20:02:45.6 UTC | 7 | 2021-08-08 23:40:57.733 UTC | 2011-10-17 20:41:45.83 UTC | null | 207,815 | null | 207,815 | null | 1 | 101 | java|intellij-idea|warnings|line | 54,318 | <p>Mostly in IntelliJ, you can click on the line and <code>Alt+Enter</code>, and it will have options for suppressing the warning, among other things.</p> |
7,959,499 | Force re-download of release dependency using Maven | <p>I'm working on a project with dependency X. X, in turn, depends on Y.</p>
<p>I used to explicitly include Y in my project's pom. However, it was not used and to make things cleaner, I instead added it to X's pom as a dependency. X is marked as a release dependency.</p>
<p>The problem is that after removing Y from my project's pom and adding it to X's pom, my project isn't picking it up on <code>mvn -U clean package</code>. I know -U update snapshots but not releases.</p>
<p>So, <em>without deleting the ~/.m2/repository directory</em> how can I force a re-download of X's pom? Also, I tried running <code>dependency:purge-local-repository</code> and it didn't work either.</p> | 8,624,906 | 13 | 6 | null | 2011-10-31 20:44:25.973 UTC | 42 | 2021-04-21 17:56:58.687 UTC | 2011-12-24 15:08:20.587 UTC | null | 313,758 | null | 174,674 | null | 1 | 175 | maven-2|maven|dependency-management|maven-dependency-plugin | 290,434 | <p>You cannot make Maven re-download dependencies, but what you can do instead is to purge dependencies that were incorrectly downloaded using <code>mvn dependency:purge-local-repository</code></p>
<p>See: <a href="http://maven.apache.org/plugins/maven-dependency-plugin/purge-local-repository-mojo.html" rel="noreferrer">http://maven.apache.org/plugins/maven-dependency-plugin/purge-local-repository-mojo.html</a></p>
<p>This looks up the list of all transitive dependencies of the current project, deletes them, then redownloads them. You can even add it as a plugin into your pom if you want to run it with every build.</p> |
7,959,247 | Test if number is odd or even | <p>What is the simplest most basic way to find out if a number/variable is odd or even in PHP?
Is it something to do with mod?</p>
<p>I've tried a few scripts but.. google isn't delivering at the moment.</p> | 7,959,256 | 19 | 2 | null | 2011-10-31 20:17:57.1 UTC | 49 | 2022-09-07 12:40:14.14 UTC | 2018-03-27 15:24:18.857 UTC | null | 142,162 | null | 1,022,585 | null | 1 | 296 | php|variables|numbers | 480,542 | <p>You were right in thinking mod was a good place to start. Here is an expression which will return true if <code>$number</code> is even, false if odd:</p>
<pre><code>$number % 2 == 0
</code></pre>
<p>Works for every <a href="http://php.net/manual/en/language.types.integer.php">integer<sup><em>PHP</em></sup></a> value, see as well <a href="http://php.net/manual/en/language.operators.arithmetic.php">Arithmetic Operators<sup><em>PHP</em></sup></a>.</p>
<p><strong>Example:</strong></p>
<pre><code>$number = 20;
if ($number % 2 == 0) {
print "It's even";
}
</code></pre>
<p>Output:</p>
<blockquote>
<p>It's even</p>
</blockquote> |
4,797,802 | Deploying WCF Service with both http and https bindings/endpoints | <p>I've written a WCF web service for consumption by a Silverlight app. Initially, the service only required a basic http binding. We now need to be able to deploy the service for use under both http and https. I've found some settings for web.config that allow me to do this as follows:</p>
<pre><code><system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="SilverlightFaultBehavior">
<silverlightFaults />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="CxtMappingWebService.CxtMappingWebServiceBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="True" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="SecureHttpBinding">
<security mode="Transport" />
</binding>
<binding name="BasicHttpBinding">
<security mode="None" />
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="CxtMappingWebService.CxtMappingWebService" behaviorConfiguration="CxtMappingWebService.CxtMappingWebServiceBehavior">
<endpoint address="" bindingConfiguration="SecureHttpBinding" binding="basicHttpBinding" contract="CxtMappingWebService.ICxtMappingWebService" behaviorConfiguration="SilverlightFaultBehavior" />
<endpoint address="" bindingConfiguration="BasicHttpBinding" binding="basicHttpBinding" contract="CxtMappingWebService.ICxtMappingWebService" behaviorConfiguration="SilverlightFaultBehavior" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
</code></pre>
<p>Unfortunately, however, there's a problem with this. </p>
<p>This web service needs to be deployed to hundreds of our customers' servers, and not all of them will be using https. Deploying it to a server that doesn't have an https binding set up in IIS causes it to fail. Is there a way to have both of these bindings in the web.config by default without it dying if there's not an https binding set up in IIS? </p>
<p>We've got a possible solution for this problem, but it doesn't really fit well with our deployment requirements. </p>
<p>Has anybody else encountered anything like this before, and how did you resolve it?</p> | 38,525,425 | 4 | 1 | null | 2011-01-25 19:14:29.933 UTC | 7 | 2016-07-22 11:33:59.16 UTC | 2016-04-29 10:55:20.707 UTC | null | 206,730 | null | 160,161 | null | 1 | 29 | wcf|iis|ssl|https|wcf-binding | 26,718 | <p>The accepted answer on this page is not of much use if you don't use an installer.
The correct answer lies in a later edit by the OP himself, all one needs to do is bind both http and https ports in IIS and then use the configuration below.</p>
<pre><code> <service name="CxtMappingWebService.CxtMappingWebService" behaviorConfiguration="CxtMappingWebService.CxtMappingWebServiceBehavior">
<endpoint address="" bindingConfiguration="SecureHttpBinding" binding="basicHttpBinding" contract="CxtMappingWebService.ICxtMappingWebService" behaviorConfiguration="SilverlightFaultBehavior" />
<endpoint address="" bindingConfiguration="BasicHttpBinding" binding="basicHttpBinding" contract="CxtMappingWebService.ICxtMappingWebService" behaviorConfiguration="SilverlightFaultBehavior" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</code></pre>
<p>That worked just fine for me!</p> |
4,560,720 | Why does the stack address grow towards decreasing memory addresses? | <p>I read in text books that the stack grows by decreasing memory address; that is, from higher address to lower address. It may be a bad question, but I didn't get the concept right. Can you explain?</p> | 4,560,763 | 4 | 0 | null | 2010-12-30 07:06:49.807 UTC | 29 | 2019-07-01 07:46:52.95 UTC | 2019-07-01 07:46:52.95 UTC | null | 224,132 | null | 414,844 | null | 1 | 53 | memory-management|stack|virtual-memory|callstack | 40,824 | <p>First, it's platform dependent. In some architectures, stack is allocated from the bottom of the address space and grows upwards.</p>
<p>Assuming an architecture like x86 that stack grown downwards from the top of address space, the idea is pretty simple:</p>
<pre><code>=============== Highest Address (e.g. 0xFFFF)
| |
| STACK |
| |
|-------------| <- Stack Pointer (e.g. 0xEEEE)
| |
. ... .
| |
|-------------| <- Heap Pointer (e.g. 0x2222)
| |
| HEAP |
| |
=============== Lowest Address (e.g. 0x0000)
</code></pre>
<p>To grow stack, you'd decrease the stack pointer:</p>
<pre><code>=============== Highest Address (e.g. 0xFFFF)
| |
| STACK |
| |
|.............| <- Old Stack Pointer (e.g. 0xEEEE)
| |
| Newly |
| allocated |
|-------------| <- New Stack Pointer (e.g. 0xAAAA)
. ... .
| |
|-------------| <- Heap Pointer (e.g. 0x2222)
| |
| HEAP |
| |
=============== Lowest Address (e.g. 0x0000)
</code></pre>
<p>As you can see, to grow stack, we have <em>decreased</em> the stack pointer from 0xEEEE to 0xAAAA, whereas to grow heap, you have to increase the heap pointer. </p>
<p><em>Obviously, this is a simplification of memory layout. The actual executable, data section, ... is also loaded in memory. Besides, threads have their own stack space.</em></p>
<p>You may ask, why should stack grow downwards. Well, as I said before, some architectures do the reverse, making heap grow downwards and stack grow upwards. It makes sense to put stack and heap on opposite sides as it prevents overlap and allows both areas to grow freely as long as you have enough address space available.</p>
<p>Another valid question could be: Isn't the program supposed to decrease/increase the stack pointer itself? How can an architecture impose one over the other to the programmer? Why it's not so program dependent as it's architecture dependent?
While you can pretty much fight the architecture and somehow get away your stack in the opposite direction, some instructions, notably <code>call</code> and <code>ret</code> that modify the stack pointer directly are going to assume another direction, making a mess.</p> |
4,196,385 | Find element that has either class 1 or class 2 | <p>I'm trying to find text inside an element whose class is either myClass1 OR myClass2.</p>
<pre><code>var myText = $(this).find('.myClass1:first').text();
</code></pre>
<p>This works fine but I am unsure if/how I can check for one of 2 classes (my element will only have one class out of these 2 I mentioned).</p>
<p>Thanks for your help!</p> | 4,196,424 | 4 | 1 | null | 2010-11-16 16:24:55.183 UTC | 4 | 2017-09-06 12:20:54.78 UTC | 2014-12-31 12:54:34.74 UTC | null | 128,165 | null | 491,230 | null | 1 | 65 | jquery|jquery-selectors | 59,518 | <p>If you want the first one found (<em>but only one</em>) use</p>
<pre><code>var myText = $(this).find('.myClass1,.myClass2').eq(0).text();
</code></pre>
<p>If you want the first of each kind (<em>two results</em>) then look at the answer provided by <a href="https://stackoverflow.com/questions/4196385/find-element-that-has-either-class-1-or-class-2/4196410#4196410">@jelbourn</a>.</p> |
4,708,549 | What is the difference between $(command) and `command` in shell programming? | <p>To store the output of a command as a variable in sh/ksh/bash, you can do either</p>
<pre><code>var=$(command)
</code></pre>
<p>or</p>
<pre><code>var=`command`
</code></pre>
<p>What's the difference if any between the two methods?</p> | 4,708,569 | 6 | 3 | null | 2011-01-16 22:34:37.407 UTC | 94 | 2018-12-02 21:01:05.253 UTC | 2018-05-25 18:17:27.19 UTC | null | 6,862,601 | null | 42,303 | null | 1 | 310 | bash|shell|ksh|sh | 59,351 | <p>The backticks/gravemarks have been deprecated in favor of <code>$()</code> for command substitution because <code>$()</code> can easily nest within itself as in <code>$(echo foo$(echo bar))</code>. There are other differences such as how backslashes are parsed in the backtick/gravemark version, etc. </p>
<p>See <a href="http://mywiki.wooledge.org/BashFAQ/082" rel="noreferrer"><strong>BashFAQ/082</strong></a> for several reasons to always prefer the $(...) syntax.</p>
<p>Also see the <a href="http://pubs.opengroup.org/onlinepubs/9699919799/xrat/V4_xcu_chap02.html#tag_23_02_06_03" rel="noreferrer"><strong>POSIX</strong></a> spec for detailed information on the various differences.</p> |
4,113,365 | What does -> mean in C++? | <blockquote>
<p><strong>Possible Duplicates:</strong><br>
<a href="https://stackoverflow.com/questions/1238613/what-is-the-difference-between-the-dot-operator-and-in-c">What is the difference between the dot (.) operator and -> in C++?</a><br>
<a href="https://stackoverflow.com/questions/221346/what-is-the-arrow-operator-synonym-for-in-c">What is the arrow operator (->) synonym for in C++?</a> </p>
</blockquote>
<p>The header says it all.</p>
<p>What does <strong>-></strong> mean in C++?</p> | 4,113,373 | 7 | 2 | null | 2010-11-06 13:56:32.957 UTC | 30 | 2017-12-06 16:21:18.027 UTC | 2017-12-06 16:21:18.027 UTC | null | 4,284,627 | null | 385,559 | null | 1 | 44 | c++ | 168,476 | <p>It's to access a member function or member variable of an object through a <em>pointer</em>, as opposed to a regular variable or reference.</p>
<p>For example: with a regular variable or reference, you use the <code>.</code> operator to access member functions or member variables.</p>
<pre><code>std::string s = "abc";
std::cout << s.length() << std::endl;
</code></pre>
<p>But if you're working with a pointer, you need to use the <code>-></code> operator:</p>
<pre><code>std::string* s = new std::string("abc");
std::cout << s->length() << std::endl;
</code></pre>
<p>It can also be overloaded to perform a specific function for a certain object type. Smart pointers like <code>shared_ptr</code> and <code>unique_ptr</code>, as well as STL container iterators, overload this operator to mimic native pointer semantics.</p>
<p>For example:</p>
<pre><code>std::map<int, int>::iterator it = mymap.begin(), end = mymap.end();
for (; it != end; ++it)
std::cout << it->first << std::endl;
</code></pre> |
4,617,220 | CSS rotate property in IE | <p>I want to rotate the DIV to a certain degree. In FF it functions but in IE I am facing a problem.</p>
<p>For example in the following style I can set rotation=1 to 4</p>
<pre><code> filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1);
</code></pre>
<p>This means that the DIV will be rotated to 90 or 180 or 270 or 360 degree. But if I need to rotate the DIV only 20 degrees, then it doesn't work anymore.</p>
<p>How may I solve this problem in IE?</p> | 4,617,511 | 7 | 1 | null | 2011-01-06 16:36:12.07 UTC | 44 | 2016-06-20 22:32:58.793 UTC | 2015-03-16 15:42:07.083 UTC | null | 279,764 | null | 160,820 | null | 1 | 73 | css|internet-explorer|rotation | 140,233 | <p>To rotate by 45 degrees in IE, you need the following code in your stylesheet:</p>
<pre><code>filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476); /* IE6,IE7 */
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476)"; /* IE8 */
</code></pre>
<p>You’ll note from the above that IE8 has different syntax to IE6/7. You need to supply both lines of code if you want to support all versions of IE.</p>
<p>The horrible numbers there are in Radians; you’ll need to work out the figures for yourself if you want to use an angle other than 45 degrees (there are <a href="http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/filters/matrix.htm" rel="noreferrer">tutorials</a> on the internet if you look for them).</p>
<p>Also note that the IE6/7 syntax causes problems for other browsers due to the unescaped colon symbol in the filter string, meaning that it is invalid CSS. In my tests, this causes Firefox to ignore all CSS code after the filter. This is something you need to be aware of as it can cause hours of confusion if you get caught out by it. I solved this by having the IE-specific stuff in a separate stylesheet which other browsers didn’t load.</p>
<p>All other current browsers (including IE9 and IE10 — yay!) support the CSS3 <code>transform</code> style (albeit often with vendor prefixes), so you can use the following code to achieve the same effect in all other browsers:</p>
<pre><code>-moz-transform: rotate(45deg); /* FF3.5/3.6 */
-o-transform: rotate(45deg); /* Opera 10.5 */
-webkit-transform: rotate(45deg); /* Saf3.1+ */
transform: rotate(45deg); /* Newer browsers (incl IE9) */
</code></pre>
<p>Hope that helps.</p>
<h3>Edit</h3>
<p>Since this answer is still getting up-votes, I feel I should update it with information about a JavaScript library called <a href="http://www.useragentman.com/blog/2010/03/09/cross-browser-css-transforms-even-in-ie/#more-896" rel="noreferrer">CSS Sandpaper</a> that allows you to use (near) standard CSS code for rotations even in older IE versions.</p>
<p>Once you’ve added CSS Sandpaper to your site, you should then be able to write the following CSS code for IE6–8:</p>
<pre><code>-sand-transform: rotate(40deg);
</code></pre>
<p>Much easier than the traditional <code>filter</code> style you'd normally need to use in IE.</p>
<h3>Edit</h3>
<p>Also note an additional quirk specifically with IE9 (and only IE9), which supports both the standard <code>transform</code> and the old style IE <code>-ms-filter</code>. If you have both of them specified, this can result in IE9 getting completely confused and rendering just a solid black box where the element would have been. The best solution to this is to avoid the <code>filter</code> style by using the Sandpaper polyfill mentioned above.</p> |
4,749,783 | How to obtain a list of directories within a directory, like list.files(), but instead "list.dirs()" | <p>This may be a very easy question for someone - I am able to use <code>list.files()</code> to obtain a list of files in a given directory, but if I want to get a list of directories, how would I do this? Is it somehow right in front of me as an option within <code>list.files()</code>?</p>
<p>Also, I'm using Windows, so if the answer is to shell out to some Linux/unix command, that won't work for me.</p>
<p>.NET for example has a <code>Directory.GetFiles()</code> method, and a separate <code>Directory.GetDirectories()</code>
method, so I figured R would have an analogous pair. Thanks in advance.</p> | 4,749,909 | 7 | 0 | null | 2011-01-20 16:32:21.453 UTC | 17 | 2016-04-18 14:42:52.22 UTC | 2014-12-08 17:56:44.863 UTC | null | 489,704 | null | 297,400 | null | 1 | 91 | r|directory | 81,118 | <p>Update: A <code>list.dirs</code> function was added to the base package in revision 54353, which was included in the R-2.13.0 release in April, 2011.</p>
<pre><code>list.dirs(path = ".", full.names = TRUE, recursive = TRUE)
</code></pre>
<p>So my function below was only useful for a few months. :)</p>
<hr>
<p>I couldn't find a base R function to do this, but it would be pretty easy to write your own using:</p>
<pre><code>dir()[file.info(dir())$isdir]
</code></pre>
<p>Update: here's a function (now corrected for Timothy Jones' comment):</p>
<pre><code>list.dirs <- function(path=".", pattern=NULL, all.dirs=FALSE,
full.names=FALSE, ignore.case=FALSE) {
# use full.names=TRUE to pass to file.info
all <- list.files(path, pattern, all.dirs,
full.names=TRUE, recursive=FALSE, ignore.case)
dirs <- all[file.info(all)$isdir]
# determine whether to return full names or just dir names
if(isTRUE(full.names))
return(dirs)
else
return(basename(dirs))
}
</code></pre> |
4,570,980 | generating a random code in php? | <p>i know this might seem silly, but i want to generate a random code of 8 characetrs, only numbers or letters using php. i needs this to generate a password for each user that signs up, thanks</p> | 4,571,013 | 8 | 1 | null | 2010-12-31 15:51:52.837 UTC | 3 | 2022-04-22 09:02:27.67 UTC | null | null | null | null | 428,137 | null | 1 | 6 | php|random | 54,582 | <p>I would rather use <a href="http://php.net/manual/en/function.md5.php" rel="noreferrer">md5</a> to generate passwords</p>
<p><strong>But you can use something like this if you want a custom:</strong></p>
<pre><code>function createRandomPassword() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
</code></pre> |
4,336,068 | Trouble with NUnit when determining the assembly's directory | <p>I've just started to work with NUnit in order to provide some test coverage for my projects.</p>
<p>Within my main library.dll I need to load up configuration data from an external file that goes with the library, library.xml.</p>
<p>This works fine when I'm using the library, because I use the following to get the directory in which to look for the config file:</p>
<pre><code>string settingspath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
</code></pre>
<p>The problem I've noticed is that when I'm unit testing with NUnit, it copies my assemblies to a Shadow Copy, but doesn't take any of the other files with it, so of course my init fails due to missing config files.</p>
<p>Should I be doing something different to locate config files from within my library? (it's a server app, and I don't want to use the standard app settings, or user's local settings, etc)</p> | 4,336,153 | 8 | 1 | null | 2010-12-02 14:31:13.887 UTC | 5 | 2020-01-27 13:38:37.34 UTC | null | null | null | null | 138,033 | null | 1 | 30 | .net|nunit | 13,194 | <p>When unit testing it is generally recommended to avoid external dependencies such as the file system and databases, by mocking/stubbing out the routines that call them - that way your tests are more localised, less fragile and faster. See if you can remove the dependencies by providing fake configuration information.</p> |
14,584,175 | how to find control in edit item template? | <p>i have a gridview on the form and have some template field, one of them is:</p>
<pre><code><asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left">
<EditItemTemplate>
<asp:DropDownList ID="DdlCountry" runat="server" DataTextField="Country" DataValueField="Sno">
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
</code></pre>
<p>now on the RowEditing event i need to get the selected value of dropdownlist of country and then i will set that value as Ddlcountry.selectedvalue=value; so that when dropdownlist of edit item template appears it will show the selected value not the 0 index of dropdownlist. but i am unable to get the value of dropdown list.
i have tried this already:</p>
<pre><code>int index = e.NewEditIndex;
DropDownList DdlCountry = GridView1.Rows[index].FindControl("DdlCountry") as DropDownList;
</code></pre>
<p>need help please.
thanx.</p> | 14,584,319 | 2 | 0 | null | 2013-01-29 13:32:49.347 UTC | 3 | 2016-02-08 08:15:29.847 UTC | null | null | null | null | 1,699,581 | null | 1 | 11 | c#|asp.net|gridview | 41,033 | <p>You need to databind the <code>GridView</code> again to be able to access the control in the <code>EditItemTemplate</code>. So try this:</p>
<pre><code>int index = e.NewEditIndex;
DataBindGridView(); // this is a method which assigns the DataSource and calls GridView1.DataBind()
DropDownList DdlCountry = GridView1.Rows[index].FindControl("DdlCountry") as DropDownList;
</code></pre>
<p>But instead i would use <code>RowDataBound</code> for this, otherwise you're duplicating code:</p>
<pre><code>protected void gridView1_RowDataBound(object sender, GridViewEditEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList DdlCountry = (DropDownList)e.Row.FindControl("DdlCountry");
// bind DropDown manually
DdlCountry.DataSource = GetCountryDataSource();
DdlCountry.DataTextField = "country_name";
DdlCountry.DataValueField = "country_id";
DdlCountry.DataBind();
DataRowView dr = e.Row.DataItem as DataRowView;
Ddlcountry.SelectedValue = value; // you can use e.Row.DataItem to get the value
}
}
}
</code></pre> |
14,596,599 | Run command prompt as Administrator | <p>I am developing a small shutdown scheduler project in which i have to put the computer in <code>"Stand By"</code> mode. The command that i am using is</p>
<pre><code>Runtime.getRuntime().exec("cmd /c Powrprof.dll,SetSuspendState ");
</code></pre>
<p>This command requires Admin rights which i don't know how to get. Also while searching for previous answers i found i can use <code>elevate.exe</code> as</p>
<pre><code>Runtime.getRuntime().exec("c:/elevate Rundll32.exe Powrprof.dll,SetSuspendState ");
</code></pre>
<p><code>Elevate.exe</code> is doing the task but is consuming too much of time i.e. making the software slow. Is there any other speedy way? I am using Netbeans IDE.</p> | 14,596,920 | 4 | 3 | null | 2013-01-30 04:15:57.987 UTC | 8 | 2019-10-16 18:28:18.727 UTC | null | null | null | null | 1,979,347 | null | 1 | 13 | java|command-line|command-prompt | 56,830 | <p>You have a few options</p>
<p>A. Create a shortcut with admin priv.</p>
<p>The shortcut will run <code>cmd /c Rundll32.exe Powrprof.dll,SetSuspendState</code></p>
<p>Your Java code will run the shortcut:</p>
<pre><code>Runtime rt = Runtime.getRuntime();
rt.exec("cmd /c start \"\" \"myshortcut.lnk\"")
</code></pre>
<p>Right click the shortcut icon > properties > advanced > run as administrator</p>
<p>B. Run the java process as administrator</p>
<p>Again, create a shortcut and set to run as administrator. Any processes spawned will also have admin privileges. Your java code will run:</p>
<pre><code>rt.exec("cmd /c Powrprof.dll,SetSuspendState")
</code></pre>
<p>C. Use JNA to directly call SetSuspendState routine. The Java process will require admin priv (like B), but you won't have to spawn a process. If you like this, I can provide source code.</p>
<p>D. <strong>Use <a href="http://www.grc.com/wizmo/wizmo.htm" rel="noreferrer">wizmo</a> utility</strong>: <code>wizmo quiet standby</code></p> |
14,571,714 | Angular JS - Make service globally accessible from controllers and view | <p>Let's say we have the following service: </p>
<pre><code>myApp.factory('FooService', function () { ...
</code></pre>
<p>Then, from a controller, I would say:</p>
<pre><code>myApp.controller('FooCtrl', ['$scope', 'FooService', function ($scope, FooService) { ...
</code></pre>
<p>The two-part question is:</p>
<ol>
<li><strong>Global Accessibility</strong>: If I have 100 controllers and all need access to the service, I don't want to explicitly inject it 100 times. <strong>How can I make the service globally available?</strong> Only thing I can think of at the moment is wrapping it from within the root scope, which defeats the purpose.</li>
<li><strong>Accessibility from view</strong>: How can I access the service from within the view? <a href="https://groups.google.com/forum/?fromgroups=#!topic/angular/H6xROj3t1H0" rel="noreferrer">This post</a> suggests wrapping the service from within the controller. If I am going to that length, seems I ought to just implement the functionality right on the root scope?</li>
</ol> | 14,571,879 | 3 | 0 | null | 2013-01-28 21:38:46.343 UTC | 17 | 2018-01-11 03:18:37.74 UTC | null | null | null | null | 433,344 | null | 1 | 30 | javascript|angularjs | 26,095 | <p>Found a reasonable solution. Inject it into the bootstrap method (run), and add it to the root scope. From there it will be available to all controllers and views.</p>
<pre><code>myApp.run(function ($rootScope, $location, $http, $timeout, FooService) {
$rootScope.foo = FooService;
....
</code></pre>
<p>Re-reading the post I mentioned above, it didn't say "wrap" exactly... just "abstract", so I presume the poster was referring to this same solution.</p>
<p>For thoroughness, the answer to (1) is then:</p>
<pre><code>myApp.controller('FooCtrl', ['$scope', function ($scope) {
// scope inherits from root scope
$scope.foo.doSomething();
...
</code></pre>
<p>and the answer to (2) is simply:</p>
<pre><code>{{doSomething()}}
</code></pre>
<p>Adding Christopher's comment to make sure it's seen:</p>
<blockquote>
<p>@rob - According to best practices, the factory should be injected in
to the controllers that need to use it, rather than on the root scope.
As asked, question number one actually is the antipattern. If you need
the factory 100 times, you inject it 100 times. It's barely any extra
code when minified, and makes it very clear where the factory is used,
and it makes it easier (and more obvious) to test those controllers
with mocks, by having the required factories all listed in the
function signature. – Christopher WJ Rueber Nov 25 '13 at 20:06</p>
</blockquote> |
14,368,596 | How can I check that two objects have the same set of property names? | <p>I am using node, mocha, and chai for my application. I want to test that my returned results data property is the same "type of object" as one of my model objects (Very similar to chai's instance). I just want to confirm that the two objects have the same sets of property names. <strong>I am specifically not interested in the actual values of the properties.</strong></p>
<p>Let's say I have the model Person like below. I want to check that my results.data has all the same properties as the expected model does. So in this case, Person which has a firstName and lastName.</p>
<p>So if <code>results.data.lastName</code> and <code>results.data.firstName</code> both exist, then it should return true. If either one doesn't exist, it should return false. A bonus would be if results.data has any additional properties like results.data.surname, then it would return false because surname doesn't exist in Person.</p>
<p><strong>This model</strong></p>
<pre><code>function Person(data) {
var self = this;
self.firstName = "unknown";
self.lastName = "unknown";
if (typeof data != "undefined") {
self.firstName = data.firstName;
self.lastName = data.lastName;
}
}
</code></pre> | 14,368,628 | 7 | 0 | null | 2013-01-16 21:56:05.687 UTC | 20 | 2021-11-25 02:51:20.387 UTC | 2019-09-19 14:48:48.413 UTC | null | 11,741,753 | null | 1,540,904 | null | 1 | 70 | javascript|node.js|mocha.js|chai | 144,815 | <p>You can serialize simple data to check for equality:</p>
<pre><code>data1 = {firstName: 'John', lastName: 'Smith'};
data2 = {firstName: 'Jane', lastName: 'Smith'};
JSON.stringify(data1) === JSON.stringify(data2)
</code></pre>
<p>This will give you something like</p>
<pre><code>'{firstName:"John",lastName:"Smith"}' === '{firstName:"Jane",lastName:"Smith"}'
</code></pre>
<p>As a function...</p>
<pre><code>function compare(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
compare(data1, data2);
</code></pre>
<h1>EDIT</h1>
<p>If you're using chai like you say, check out <a href="http://chaijs.com/api/bdd/#equal-section">http://chaijs.com/api/bdd/#equal-section</a></p>
<h1>EDIT 2</h1>
<p>If you just want to check keys...</p>
<pre><code>function compareKeys(a, b) {
var aKeys = Object.keys(a).sort();
var bKeys = Object.keys(b).sort();
return JSON.stringify(aKeys) === JSON.stringify(bKeys);
}
</code></pre>
<p>should do it.</p> |
3,010,363 | NSArray writeToFile fails | <p>I am trying to save an array, which has some dictionaries inside, to a plist file but it fails. I don't get any errors. I do exactly the same few lines above in the code just with another array and that works.. I can't figure out why it does not save the file.</p>
<p>This is where I save the file: (see some debugger output below)</p>
<pre><code>// When built parse through dictionary and save to file
for ( NSString *keys in [dicByCountry allKeys] )
{
NSArray *arrr = [[NSArray alloc] initWithArray:[dicByCountry objectForKey:keys]];
NSString *fname = [self filePath:[NSString stringWithFormat:@"regions.cid%@.plist",keys]];
if (![arrr writeToFile:fname atomically:YES])
NSLog(@"Could not write file regions.cid%@.plist",keys);
}
</code></pre>
<p>Here some GDB Output</p>
<pre><code>(gdb) po fname
/Users/chris/Library/Application Support/iPhone Simulator/4.0/Applications/44A9FF9E-5715-4BF0-9BE2-525883281420/Documents/regions.cid0.plist
(gdb) po arrr
<__NSArrayI 0x8022b30>(
{
countryID = "<null>";
region = "?\U00e2vora";
regionID = 16;
},
{
countryID = "<null>";
region = Vicenza;
regionID = 14;
},
{
countryID = "<null>";
region = Wales;
regionID = 23;
}
)
</code></pre> | 3,011,037 | 2 | 0 | null | 2010-06-09 22:11:34.397 UTC | 9 | 2014-01-07 10:01:03.603 UTC | null | null | null | null | 335,427 | null | 1 | 21 | iphone|file|nsarray | 17,585 | <p>If you read <a href="http://developer.apple.com/iphone/library/documentation/cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/writeToFile:atomically:" rel="noreferrer">the documentation</a> closely, <code>writeToFile:atomically:</code> expects the array to contain only objects which can be written into a plist file. </p>
<p>Only objects of type: </p>
<ul>
<li><code>NSString</code></li>
<li><code>NSData</code></li>
<li><code>NSDate</code></li>
<li><code>NSNumber</code></li>
<li><code>NSArray</code></li>
<li><code>NSDictionary</code> </li>
</ul>
<p>are permitted. If you have arrays or dictionaries within the array you're saving, their values will be examined by the same criteria.</p>
<p>This is somewhat more restrictive than what's usually allowed in <code>NSArray</code>s. In particular, the value <code>[NSNull null]</code> is not acceptable. </p> |
2,370,388 | SocketException: address incompatible with requested protocol | <p>I was trying to run a .Net socket server code on Win7-64bit machine .<br>
I keep getting the following error: </p>
<blockquote>
<p>System.Net.Sockets.SocketException: An address incompatible with the requested protocol
was used.<br>
Error Code: 10047</p>
</blockquote>
<p>The code snippet is : </p>
<pre><code>IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
IPEndPoint ip = new IPEndPoint(ipAddress, 9989);
Socket serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
try
{
serverSocket.Bind(ip);
serverSocket.Listen(10);
serverSocket.BeginAccept(new AsyncCallback(AcceptConn), serverSocket);
}
catch (SocketException excep)
{
Log("Native code:"+excep.NativeErrorCode);
// throw;
}
</code></pre>
<p>The above code works fine in Win-XP sp3 .</p>
<p>I have checked <a href="http://msdn.microsoft.com/en-us/library/ms740668%28VS.85%29.aspx" rel="noreferrer">Error code details on MSDN</a> but it doesn't make much sense to me.</p>
<p>Anyone has encountered similar problems? Any help?</p> | 2,370,440 | 2 | 1 | null | 2010-03-03 10:29:26.1 UTC | 4 | 2013-09-09 14:25:58.483 UTC | 2013-09-09 14:25:58.483 UTC | null | 158,297 | null | 158,297 | null | 1 | 44 | c#|.net|sockets | 59,282 | <p>On Windows Vista (and Windows 7), Dns.GetHostEntry also returns IPv6 addresses. In your case, the IPv6 address (::1) is first in the list.</p>
<p>You cannot connect to an IPv6 (InterNetworkV6) address with an IPv4 (InterNetwork) socket.</p>
<p>Change your code to create the socket to use the address family of the specified IP address:</p>
<pre><code>Socket serverSocket =
new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
↑
</code></pre>
<p><strong>Note</strong>: There's a shortcut to obtain the IP address of <em>localhost</em>: You can simply use <a href="http://msdn.microsoft.com/en-us/library/system.net.ipaddress.loopback.aspx" rel="noreferrer">IPAddress.Loopback</a> (127.0.0.1) or <a href="http://msdn.microsoft.com/en-us/library/system.net.ipaddress.ipv6loopback.aspx" rel="noreferrer">IPAddress.IPv6Loopback</a> (::1).</p> |
38,568,129 | Incrementing counter in Stream foreach Java 8 | <p>I'd like to increment a <code>counter</code> which is an <code>AtomicInteger</code> as I loop through using <code>foreach</code> </p>
<pre><code>public class ConstructorTest {
public static void main(String[] args) {
AtomicInteger counter = new AtomicInteger(0);
List<Foo> fooList = Collections.synchronizedList(new ArrayList<Foo>());
List<String> userList = Collections.synchronizedList(new ArrayList<String>());
userList.add("username1_id1");
userList.add("username2_id2");
userList.stream().map(user -> new Foo(getName(user), getId(user))).forEach(fooList::add);
//how do I increment the counter in the above loop
fooList.forEach(user -> System.out.println(user.getName() + " " + user.getId()));
}
private static String getName(String user) {
return user.split("_")[0];
}
private static String getId(String user) {
return user.split("_")[1];
}
}
</code></pre> | 38,568,349 | 6 | 0 | null | 2016-07-25 12:42:58.923 UTC | 6 | 2022-02-24 19:35:36.657 UTC | null | null | null | null | 1,629,109 | null | 1 | 52 | java | 110,955 | <p>Depends on where you want to increment.</p>
<p>Either </p>
<pre><code>userList.stream()
.map(user -> {
counter.getAndIncrement();
return new Foo(getName(user), getId(user));
})
.forEach(fooList::add);
</code></pre>
<p>or</p>
<pre><code>userList.stream()
.map(user -> new Foo(getName(user), getId(user)))
.forEach(foo -> {
fooList.add(foo);
counter.getAndIncrement();
});
</code></pre> |
48,861,029 | What is the benefit of using RWMutex instead of Mutex? | <p>I am not sure when to use RWMutex and when to use Mutex.</p>
<p>Do you save resources if you use RWMutex instead of Mutex if you do more reads then writes?</p>
<p>I see some people use Mutex all the time no matter what they do, and some use RWMutex and run these methods:</p>
<pre><code>func (rw *RWMutex) Lock()
func (rw *RWMutex) Unlock()
func (rw *RWMutex) RLock()
func (rw *RWMutex) RUnlock()
</code></pre>
<p>instead of just:</p>
<pre><code>func (m *Mutex) Lock()
func (m *Mutex) Unlock()
</code></pre>
<p>If you save resources, is it that much of a difference that you should use RWMutex if you do more reads then writes?</p> | 48,861,083 | 2 | 0 | null | 2018-02-19 07:04:19.717 UTC | 9 | 2022-08-29 07:29:44.647 UTC | null | null | null | null | 3,759,007 | null | 1 | 49 | go | 18,180 | <p>From <a href="https://golang.org/pkg/sync/#RWMutex" rel="noreferrer">the docs</a> (emphasize mine):</p>
<blockquote>
<p>A RWMutex is a reader/writer mutual exclusion lock. <em>The lock can be held by an arbitrary number of readers or a single writer.</em> The zero value for a RWMutex is an unlocked mutex.</p>
</blockquote>
<p>In other words, readers don't have to wait for each other. They only have to wait for writers holding the lock.</p>
<p>A sync.RWMutex is thus preferable for data that is mostly read, and the resource that is saved compared to a sync.Mutex is time.</p> |
27,480,967 | Why does the asyncio's event loop suppress the KeyboardInterrupt on Windows? | <p>I have this really small test program which does nothing apart from a executing an <code>asyncio</code> event loop:</p>
<pre><code>import asyncio
asyncio.get_event_loop().run_forever()
</code></pre>
<p>When I run this program on Linux and press <kbd>Ctrl</kbd>+<kbd>C</kbd>, the program will terminate correctly with a <code>KeyboardInterrupt</code> exception. On Windows pressing <kbd>Ctrl</kbd>+<kbd>C</kbd> does nothing (tested with Python 3.4.2). A simple inifinite loop with <code>time.sleep()</code> raises the <code>KeyboardInterrupt</code> correctly even on Windows:</p>
<pre><code>import time
while True:
time.sleep(3600)
</code></pre>
<p>Why does the asyncio's event loop suppress the KeyboardInterrupt on Windows?</p> | 27,492,344 | 3 | 0 | null | 2014-12-15 09:32:42.027 UTC | 6 | 2018-06-30 06:29:03.76 UTC | 2014-12-16 16:25:37.57 UTC | null | 2,073,595 | null | 376,203 | null | 1 | 31 | python|windows|python-3.4|python-asyncio|keyboardinterrupt | 9,240 | <p>This is a bug, sure.</p>
<p>See <a href="http://bugs.python.org/issue23057">issue on python bug-tracker</a> for the problem solving progress.</p> |
36,193,553 | Get the value of some weights in a model trained by TensorFlow | <p>I have trained a ConvNet model with TensorFlow, and I want to get a particular weight in layer. For example in torch7 I would simply access <code>model.modules[2].weights</code>. to get the weights of layer 2. How would I do the same thing in TensorFlow?</p> | 36,193,677 | 5 | 0 | null | 2016-03-24 04:58:58.457 UTC | 26 | 2021-12-18 22:35:23.96 UTC | 2016-03-24 06:08:22.703 UTC | null | 3,574,081 | null | 3,106,889 | null | 1 | 74 | tensorflow | 100,687 | <p>In TensorFlow, trained weights are represented by <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/state_ops.html#Variable"><code>tf.Variable</code></a> objects. If you created a <code>tf.Variable</code>—e.g. called <code>v</code>—yourself, you can get its value as a NumPy array by calling <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/client.html#Session.run"><code>sess.run(v)</code></a> (where <code>sess</code> is a <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/client.html#Session"><code>tf.Session</code></a>).</p>
<p>If you do not currently have a pointer to the <code>tf.Variable</code>, you can get a list of the trainable variables in the current graph by calling <a href="https://www.tensorflow.org/versions/r0.7/api_docs/python/state_ops.html#trainable_variables"><code>tf.trainable_variables()</code></a>. This function returns a list of all trainable <code>tf.Variable</code> objects in the current graph, and you can select the one that you want by matching the <code>v.name</code> property. For example:</p>
<pre><code># Desired variable is called "tower_2/filter:0".
var = [v for v in tf.trainable_variables() if v.name == "tower_2/filter:0"][0]
</code></pre> |
29,748,013 | What is the correct implementation of the Open Graph "article" type? | <p>I need to add Open Graph tags to a blog page. It seems from reading the spec (<a href="http://ogp.me/" rel="noreferrer">http://ogp.me/</a>) using an <code>og:type</code> of <code>article</code> is the way to go. However, I find the spec unclear and I'm unsure how to implement the syntax correctly.</p>
<p>Two example websites implement this differently for example:</p>
<ol>
<li><p>Example from GitHub: (<a href="https://github.com/niallkennedy/open-graph-protocol-examples/blob/master/article-utc.html" rel="noreferrer">https://github.com/niallkennedy/open-graph-protocol-examples/blob/master/article-utc.html</a>)</p>
<pre class="lang-html prettyprint-override"><code><head prefix="og: http://ogp.me/ns# article: http://ogp.me/ns/article#">
<meta property="og:title" content="...">
<meta property="og:type" content="article">
<meta property="article:published_time" content="...">
</code></pre>
<p><em>Note the <code>og</code> and <code>article</code> namespaces are registered and that <code>og</code> and <code>article</code> are used as properties.</em></p></li>
<li><p>BBC News article</p>
<pre class="lang-html prettyprint-override"><code><head>
<meta property="og:title" content="...">
<meta property="og:type" content="article">
<meta property="og:article:author" content="...">
</code></pre>
<p><em>Note no namespace registration and <code>og</code> and <code>og:article</code> are used as properties.</em></p></li>
<li><p>A variation I've seen in the wild of the above, registering only the <code>og</code> namespace and still referencing <code>og:article</code> as a property.</p>
<pre class="lang-html prettyprint-override"><code><head prefix="og: http://ogp.me/ns#">
<meta property="og:title" content="...">
<meta property="og:type" content="article">
<meta property="og:article:published_time" content="..">
</code></pre></li>
</ol>
<p>Option 3 is what I used the first time I tried to implement this. When I ran it through the Facebook validation tool I was told:</p>
<blockquote>
<p>Objects of this type do not allow properties named 'og:article:published_time'.</p>
</blockquote>
<p>For the moment, I have gone with option 1 and although this validates, I would like to know what the definitive correct syntax is?</p> | 29,831,974 | 4 | 0 | null | 2015-04-20 12:33:10.08 UTC | 6 | 2019-12-10 09:24:24.76 UTC | 2015-04-20 12:47:14.92 UTC | null | 4,810,214 | null | 4,810,214 | null | 1 | 44 | facebook-opengraph|article | 36,193 | <p>Have a look at the Facebook developers page: <a href="https://developers.facebook.com/docs/reference/opengraph/object-type/article" rel="noreferrer">https://developers.facebook.com/docs/reference/opengraph/object-type/article</a></p>
<p>It looks like your examples 2 and 3 have incorrect formatting. None of the "article" properties should begin with "og:"</p>
<p>Here's what I have on one of my sites, and I get no errors from the FB debugger:</p>
<pre><code><meta property='og:type' content='article' />
<meta property='article:author' content='https://www.facebook.com/YOUR-NAME' />
<meta property='article:publisher' content='https://www.facebook.com/YOUR-PAGE' />
<meta property='og:site_name' content='YOUR-SITE-NAME' />
</code></pre> |
36,262,748 | save plotly plot to local file and insert into html | <p>I am using python and plotly to product interactive html report. <a href="http://moderndata.plot.ly/generate-html-reports-with-python-pandas-and-plotly/" rel="noreferrer">This post</a> gives a nice framework.</p>
<p>If I produce the plot(via plotly) online, and insert the url into the html file, it works but refreshing the charts takes a long time. I wonder if I could produce the chart offline and have it embedded in the html report, so that loading speed is not a problem.</p>
<p>I find plot offline would generate a html for the chart, but I don't know how to embed it in another html. Anyone could help?</p> | 36,376,371 | 14 | 0 | null | 2016-03-28 12:52:29.25 UTC | 59 | 2022-09-01 19:46:28.333 UTC | 2022-09-01 19:46:28.333 UTC | null | 7,758,804 | null | 5,873,055 | null | 1 | 66 | python|plotly | 101,888 | <p><strong>Option 1</strong>: Use plotly's offline functionality in your Jupyter Notebook (I suppose you are using a Jupyter Notebook from the link you are providing). You can simply save the whole notebook as a HTML file. When I do this, the only external reference is to JQuery; plotly.js will be inlined in the HTML source.</p>
<p><strong>Option 2</strong>: The best way is probably to code directly against plotly's JavaScript library. Documentation for this can be found here: <a href="https://plot.ly/javascript/" rel="noreferrer">https://plot.ly/javascript/</a></p>
<p><strong>Update</strong>: Calling an internal function has never been a good idea. I recommend to use the approach given by @Fermin Silva. In newer versions, there now is also a dedicated function for this: <code>plotly.io.to_html</code> (see <a href="https://plotly.com/python-api-reference/generated/plotly.io.to_html.html" rel="noreferrer">https://plotly.com/python-api-reference/generated/plotly.io.to_html.html</a>)</p>
<p><strong>Hacky Option 3</strong> (original version for reference only): If you really want to continue using Python, you can use some hack to extract the HTML it generates. You need some recent version of plotly (I tested it with <code>plotly.__version__ == '1.9.6'</code>). Now, you can use an internal function to get the generated HTML:</p>
<pre><code>from plotly.offline.offline import _plot_html
data_or_figure = [{"x": [1, 2, 3], "y": [3, 1, 6]}]
plot_html, plotdivid, width, height = _plot_html(
data_or_figure, False, "", True, '100%', 525)
print(plot_html)
</code></pre>
<p>You can simply paste the output somewhere in the body of your HTML document. Just make sure that you include a reference to plotly in the head:</p>
<pre><code><script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</code></pre>
<p>Alternatively, you can also reference the exact plotly version you used to generate the HTML or inline the JavaScript source (which removes any external dependencies; be aware of the legal aspects however).</p>
<p>You end up with some HTML code like this:</p>
<pre><code><html>
<head>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<!-- Output from the Python script above: -->
<div id="7979e646-13e6-4f44-8d32-d8effc3816df" style="height: 525; width: 100%;" class="plotly-graph-div"></div><script type="text/javascript">window.PLOTLYENV=window.PLOTLYENV || {};window.PLOTLYENV.BASE_URL="https://plot.ly";Plotly.newPlot("7979e646-13e6-4f44-8d32-d8effc3816df", [{"x": [1, 2, 3], "y": [3, 1, 6]}], {}, {"showLink": false, "linkText": ""})</script>
</body>
</html>
</code></pre>
<p><strong>Note</strong>: The underscore at the beginning of the function's name suggests that <code>_plot_html</code> is not meant to be called from external code. So it is likely that this code will break with future versions of plotly.</p> |
40,416,357 | Difference between df.repartition and DataFrameWriter partitionBy? | <p>What is the difference between DataFrame <code>repartition()</code> and DataFrameWriter <code>partitionBy()</code> methods?</p>
<p>I hope both are used to "partition data based on dataframe column"? Or is there any difference?</p> | 40,417,992 | 3 | 1 | null | 2016-11-04 06:10:15.22 UTC | 59 | 2021-03-04 19:29:34.12 UTC | 2021-03-04 18:41:44.76 UTC | null | 792,066 | null | 1,907,755 | null | 1 | 66 | apache-spark-sql|data-partitioning | 61,165 | <p>If you run <code>repartition(COL)</code> you change the partitioning during calculations - you will get <code>spark.sql.shuffle.partitions</code> (default: 200) partitions. If you then call <code>.write</code> you will get one directory with many files.</p>
<p>If you run <code>.write.partitionBy(COL)</code> then as the result you will get as many directories as unique values in COL. This speeds up futher data reading (if you filter by partitioning column) and saves some space on storage (partitioning column is removed from data files).</p>
<p><strong>UPDATE</strong>: See @conradlee's answer. He explains in details not only how the directories structure will look like after applying different methods but also what will be resulting number of files in both scenarios.</p> |
2,579,453 | NSData-AES Class Encryption/Decryption in Cocoa | <p>I am attempting to encrypt/decrypt a plain text file in my text editor. encrypting seems to work fine, but the decrypting does not work, the text comes up encrypted. I am certain i've decrypted the text using the word i encrypted it with - could someone look through the snippet below and help me out?</p>
<p>Thanks :)</p>
<p>Encrypting:</p>
<pre><code>NSAlert *alert = [NSAlert alertWithMessageText:@"Encryption"
defaultButton:@"Set"
alternateButton:@"Cancel"
otherButton:nil
informativeTextWithFormat:@"Please enter a password to encrypt your file with:"];
[alert setIcon:[NSImage imageNamed:@"License.png"]];
NSSecureTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 24)];
[alert setAccessoryView:input];
NSInteger button = [alert runModal];
if (button == NSAlertDefaultReturn) {
[[NSUserDefaults standardUserDefaults] setObject:[input stringValue] forKey:@"password"];
NSData *data;
[self setString:[textView textStorage]];
NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSPlainTextDocumentType
forKey:NSDocumentTypeDocumentAttribute];
[textView breakUndoCoalescing];
data = [[self string] dataFromRange:NSMakeRange(0, [[self string] length])
documentAttributes:dict error:outError];
NSData*encrypt = [data AESEncryptWithPassphrase:[input stringValue]];
[encrypt writeToFile:[absoluteURL path] atomically:YES];
</code></pre>
<p>Decrypting:</p>
<pre><code> NSAlert *alert = [NSAlert alertWithMessageText:@"Decryption"
defaultButton:@"Open"
alternateButton:@"Cancel"
otherButton:nil
informativeTextWithFormat:@"This file has been protected with a password.To view its contents,enter the password below:"];
[alert setIcon:[NSImage imageNamed:@"License.png"]];
NSSecureTextField *input = [[NSSecureTextField alloc] initWithFrame:NSMakeRect(0, 0, 300, 24)];
[alert setAccessoryView:input];
NSInteger button = [alert runModal];
if (button == NSAlertDefaultReturn) {
NSLog(@"Entered Password - attempting to decrypt.");
NSMutableDictionary *dict = [NSDictionary dictionaryWithObject:NSPlainTextDocumentType
forKey:NSDocumentTypeDocumentOption];
NSData*decrypted = [[NSData dataWithContentsOfFile:[self fileName]] AESDecryptWithPassphrase:[input stringValue]];
mString = [[NSAttributedString alloc]
initWithData:decrypted options:dict documentAttributes:NULL
error:outError];
</code></pre> | 4,275,156 | 1 | 5 | null | 2010-04-05 16:11:33.21 UTC | 15 | 2012-02-15 05:30:12.603 UTC | null | null | null | null | 237,882 | null | 1 | 10 | cocoa|nsdata|encryption | 18,528 | <p>Why not use the built-in encryption algorithms? Here's an <a href="https://github.com/nicerobot/objc/tree/master/NSData/NSData%2BAES/" rel="noreferrer">NSData+AES</a> i wrote which uses <a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/CCCrypt.3cc.html" rel="noreferrer">CCCrypt</a> with a 256it key for AES256 encryption.</p>
<p>You can use it like:</p>
<pre><code>NSData *data = [[NSData dataWithContentsOfFile:@"/etc/passwd"]
encryptWithString:@"mykey"];
</code></pre>
<p>and decrypt it with:</p>
<pre><code>NSData *file = [data decryptWithString:@"mykey"];
</code></pre>
<p>DISCLAIMER: There no guarantee my <a href="https://github.com/nicerobot/objc/tree/master/NSData/NSData%2BAES/" rel="noreferrer">NSData+AES</a> is bug-free :) It's fairly new. I welcome code reviews.</p> |
34,060,394 | CloudFront + S3 Website: "The specified key does not exist" when an implicit index document should be displayed | <p>I've just deployed a static website to Amazon S3, which can currently be viewed here: <a href="http://www.rdegges.com.s3-website-us-east-1.amazonaws.com/" rel="noreferrer">http://www.rdegges.com.s3-website-us-east-1.amazonaws.com/</a></p>
<p>If you click any of the article links, you'll notice the following error:</p>
<p><a href="https://i.stack.imgur.com/c715j.png" rel="noreferrer"><img src="https://i.stack.imgur.com/c715j.png" alt="S3 Error"></a></p>
<p>S3 is complaining the file doesn't exist. Now, here's what's weird about this -- I'm using CloudFront on my domain. So when you click that article link, it's sending the request to CloudFront which then tries to fetch the file back from the S3 bucket.</p>
<p>However, if you visit that same URL from S3 directly, eg: <a href="http://www.rdegges.com.s3-website-us-east-1.amazonaws.com/2015/building-a-heroku-addon-planning/" rel="noreferrer">http://www.rdegges.com.s3-website-us-east-1.amazonaws.com/2015/building-a-heroku-addon-planning/</a> the page will load just fine.</p>
<p>It appears that something is getting lost in translation here.</p>
<p>Anyone got a suggestion of what I can do to fix my settings?</p> | 34,065,543 | 10 | 0 | null | 2015-12-03 07:46:57.997 UTC | 17 | 2022-07-05 14:16:02.907 UTC | 2016-07-12 12:03:59.387 UTC | null | 1,695,906 | null | 194,175 | null | 1 | 74 | amazon-web-services|amazon-s3|amazon-cloudfront | 51,508 | <p>I'll go out on a limb and say that the specified key doesn't <em>technically</em> exist, so the error message is technically accurate but doesn't tell the whole story. This should be an easy fix.</p>
<p>S3 buckets have two¹ endpoints, "REST" and "website." They have two different feature sets. The web site endpoint provides magical resolution of index documents (e.g. index.html, which appears to be what is actually supposed to be returned to the browser in the example you provided) while the REST endpoints don't.</p>
<p>When you configure CloudFront in front of a bucket used for web site hosting, you usually don't want to configure the origin as an "S3" origin by selecting the bucket name from the drop-down list; instead, you want to configure it as a "Custom" origin, and use the web site endpoint hostname as provided in the S3 console (e.g. <code>example-bucket.s3-website-us-east-1...</code>) because otherwise, CloudFront assumes you want it to use the REST endpoint for the bucket (which allows authentication and private content, which the web site endpoint doesn't).</p>
<blockquote>
<p><strike><strong>Important</strong></strike></p>
</blockquote>
<blockquote>
<p><strike>Do not select the name of your bucket from the list, for example, example.com.s3.amazonaws.com.</strike></p>
</blockquote>
<blockquote>
<p><strike>http://docs.aws.amazon.com/gettingstarted/latest/swh/getting-started-create-cfdist.html</strike></p>
</blockquote>
<p>The documentation was refactored since this question was originally answered, so the message shown above now appears one page later, and has been reworded, but the gist is the same. The "name of the bucket" seems to refer to the choices shown in the drop-down, which is not what you want.</p>
<blockquote>
<p><strong>Note</strong></p>
</blockquote>
<blockquote>
<p>Be sure to specify the static website hosting endpoint, not the name of the bucket.</p>
</blockquote>
<blockquote>
<p>http://docs.aws.amazon.com/AmazonS3/latest/dev/website-hosting-cloudfront-walkthrough.html</p>
</blockquote>
<p>The hint that you're using the REST endpoint for the bucket is that the error message is returned in XML. If you were using the web site endpoint, then the web site endpoint would return error messages in HTML.</p>
<p>Create a new origin for the CloudFront distribution, as described, then change the behavior to send requests to the new origin, then send a CloudFront cache invalidation request for <code>/*</code> and you should be set.</p>
<p>See also:</p>
<p><a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff" rel="noreferrer">http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff</a></p>
<hr />
<p>¹ two endpoints. Technically, there are more than two, since all buckets have at least two possible REST endpoint hostnames... but there are two <em>types</em> of endpoints. Buckets also have an optional transfer acceleration endpoint that uses the AWS edge network (the same infrastructure that powers CloudFront) for faster/optimized transfers, particularly from geographic locations more distant from the region where the bucket is provisioned, but without using the CloudFront cache. This endpoint looks like <code>https://example-bucket.s3-accelerate.amazonaws.com</code> if you activate it, and carries an additional usage charge for most requests since you are using more of the AWS network and less of the public Internet... but, that is a difference in the behind-the-scenes deployment of the endpoint, not the behavior of the endpoint. The transfer acceleration endpoint is still a REST endpoint, so just like the other REST endpoints, it does not have the web site hosting features. CloudFront won't let you use an acceleration endpoint for an origin domain name, because that wouldn't make sense -- if such a configuration were allowed, requests and responses would loop through the AWS Edge Network twice and increase both latency and costs without providing any benefit.</p> |
37,601,346 | Create Options Menu for RecyclerView-Item | <p>How do I create an Options Menu like in the following Screenshot:</p>
<p><a href="https://i.stack.imgur.com/wxPNk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/wxPNk.png" alt="enter image description here"></a></p>
<p>The Options Menu should be opened afther clicking on the "More"-Icon of a RecyclerView Item!</p>
<p>My try was this:</p>
<pre><code>@Override
public void onBindViewHolder(Holder holder, int position) {
holder.txvSongTitle.setText(sSongs[position].getTitle());
holder.txvSongInfo.setText(sSongs[position].getAlbum() + " - " + sSongs[position].getArtist());
holder.btnMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(mContext, "More...", Toast.LENGTH_SHORT).show();
}
});
}
</code></pre>
<p>But this causes problems because the full item is clicked if I touch on the RecyclerView Item More-Button...</p>
<p>Here's my RecyclerViewOnTouchListener:</p>
<pre><code>public class RecyclerViewOnTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector mGestureDetector;
private OnTouchCallback mOnTouchCallback;
public RecyclerViewOnTouchListener(Context context, final RecyclerView recyclerView, final OnTouchCallback onTouchCallback) {
mOnTouchCallback = onTouchCallback;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && onTouchCallback != null) {
onTouchCallback.onLongClick(child, recyclerView.getChildLayoutPosition(child));
}
super.onLongPress(e);
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && mOnTouchCallback != null && mGestureDetector.onTouchEvent(e)) {
mOnTouchCallback.onClick(child, rv.getChildLayoutPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
public interface OnTouchCallback {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
</code></pre>
<p>I wasn't able to find any similar problem so I hope you can help me!</p> | 37,643,613 | 8 | 0 | null | 2016-06-02 20:17:45.347 UTC | 28 | 2022-06-03 08:05:45.583 UTC | null | null | null | null | 5,994,190 | null | 1 | 65 | android|android-recyclerview | 70,517 | <p>I found out that the only Menu, that looks like the Menu above is the <code>PopupMenu</code>.</p>
<p>So in <code>onClick</code>:</p>
<pre><code>@Override
public void onClick(View view, int position, MotionEvent e) {
ImageButton btnMore = (ImageButton) view.findViewById(R.id.item_song_btnMore);
if (RecyclerViewOnTouchListener.isViewClicked(btnMore, e)) {
PopupMenu popupMenu = new PopupMenu(view.getContext(), btnMore);
getActivity().getMenuInflater().inflate(R.menu.menu_song, popupMenu.getMenu());
popupMenu.show();
//The following is only needed if you want to force a horizontal offset like margin_right to the PopupMenu
try {
Field fMenuHelper = PopupMenu.class.getDeclaredField("mPopup");
fMenuHelper.setAccessible(true);
Object oMenuHelper = fMenuHelper.get(popupMenu);
Class[] argTypes = new Class[] {int.class};
Field fListPopup = oMenuHelper.getClass().getDeclaredField("mPopup");
fListPopup.setAccessible(true);
Object oListPopup = fListPopup.get(oMenuHelper);
Class clListPopup = oListPopup.getClass();
int iWidth = (int) clListPopup.getDeclaredMethod("getWidth").invoke(oListPopup);
clListPopup.getDeclaredMethod("setHorizontalOffset", argTypes).invoke(oListPopup, -iWidth);
clListPopup.getDeclaredMethod("show").invoke(oListPopup);
}
catch (NoSuchFieldException nsfe) {
nsfe.printStackTrace();
}
catch (NoSuchMethodException nsme) {
nsme.printStackTrace();
}
catch (InvocationTargetException ite) {
ite.printStackTrace();
}
catch (IllegalAccessException iae) {
iae.printStackTrace();
}
}
else {
MusicPlayer.playSong(position);
}
}
</code></pre>
<p>You have to make your onClick-Method pass the MotionEvent and finally implement the Method <code>isViewClicked</code> in your RecyclerViewOnTouchListener:</p>
<pre><code>public static boolean isViewClicked(View view, MotionEvent e) {
Rect rect = new Rect();
view.getGlobalVisibleRect(rect);
return rect.contains((int) e.getRawX(), (int) e.getRawY());
}
</code></pre> |
38,570,188 | React Native - How to see what's stored in AsyncStorage? | <p>I save some items to <code>AsyncStorage</code> in React Native and I am using chrome debugger and iOS simulator.</p>
<p>Without react native, using regular web development <code>localStorage</code>, I was able to see the stored <code>localStorage</code> items under <code>Chrome Debugger > Resources > Local Storage</code></p>
<p>Any idea how can I view the React Native <code>AsyncStorage</code> stored items?</p> | 43,603,394 | 11 | 3 | null | 2016-07-25 14:16:25.573 UTC | 9 | 2022-09-13 14:38:51.84 UTC | null | null | null | null | 485,961 | null | 1 | 52 | react-native|asyncstorage | 48,188 | <p>You can use reactotron i think it has Async Storage explorer ;)
<a href="https://github.com/infinitered/reactotron" rel="noreferrer">https://github.com/infinitered/reactotron</a></p>
<p><a href="https://i.stack.imgur.com/lqTCa.png" rel="noreferrer"><img src="https://i.stack.imgur.com/lqTCa.png" alt="enter image description here"></a></p> |
32,274,684 | How do I remove a bridge header without getting errors? | <p>I added a bridge header to my app the other day because I was trying to add Objective-C files to my Swift project. I was having trouble getting the connection to work(and I also did not know how to implement the Objective-C files), so I decided I wanted to start over again. I deleted the Objective-C files and the Bridge-Header file and now I am getting an error saying:<br>
<code><unknown>:0: error: bridging header '/Users/CalebKleveter/Documents/Development/iOS/personal/swift/Projects/Dicey/Dicey/Dicey-Bridging-Header.h' does not exist</code></p>
<p><a href="https://i.stack.imgur.com/d8tkM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/d8tkM.png" alt="Xcode Bridge-Header error"></a>
<a href="https://i.stack.imgur.com/DRKx1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DRKx1.png" alt="File tree for an Xcode project"></a></p> | 32,274,718 | 4 | 0 | null | 2015-08-28 15:31:29.44 UTC | 3 | 2021-04-11 06:20:46.67 UTC | null | null | null | null | 5,236,226 | null | 1 | 38 | ios|objective-c|xcode|swift|objective-c-swift-bridge | 17,208 | <p>Go to <strong>Build Settings</strong> of your project, find <strong>Objective-C Bridging Header</strong> row and remove its contents.</p>
<p><a href="https://i.stack.imgur.com/liPVV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/liPVV.png" alt="enter image description here"></a></p> |
41,910,583 | Errno 13 Permission denied Python | <p>In python, I am currently experimenting with what I can do with <code>open</code> command. I tried to open a file, and got an error message. Here's my code:</p>
<pre><code>open(r'C:\Users\****\Desktop\File1')
</code></pre>
<p>My error message was:</p>
<pre><code>PermissionError: [Errno 13] Permission denied: 'C:\\Users\\****\\Desktop\\File1'
</code></pre>
<p>I looked on the website to try and find some answers and I saw a post where somebody mentioned <code>chmod</code>. 1. I'm not sure what this is and 2. I don't know how to use it, and thats why I've come here.</p> | 41,910,734 | 6 | 0 | null | 2017-01-28 13:54:50.007 UTC | 8 | 2022-08-10 18:58:33.38 UTC | 2019-02-08 22:01:32.133 UTC | null | 513,951 | null | 7,416,656 | null | 1 | 29 | python | 218,688 | <p>Your user don't have the right permissions to <code>read</code> the file, since you used <a href="https://docs.python.org/3/library/functions.html#open" rel="noreferrer"><code>open()</code></a> without specifying a mode.</p>
<p>Since you're using Windows, you should read a little more about <a href="https://technet.microsoft.com/en-us/library/cc754344(v=ws.11).aspx" rel="noreferrer">File and Folder Permissions</a>.</p>
<p>Also, if you want to play with your file permissions, you should <code>right-click</code> it, choose <code>Properties</code> and select <code>Security</code> tab.</p>
<p>Or if you want to be a little more hardcore, you can run your script as admin.</p>
<p><strong>SO Related Questions:</strong></p>
<ul>
<li><a href="https://stackoverflow.com/questions/13215716/ioerror-errno-13-permission-denied-when-trying-to-open-hidden-file-in-w-mod">Example1</a></li>
</ul> |
5,690,637 | Android HTTP login questions | <p>I am implementing a login feature in Android.</p>
<ol>
<li><p>Does android have anything like sessions or cookies? How should I 'remember' that the user is loged in? Obviously I don't want to ask for the password every time my application is used!</p>
</li>
<li><p>Should I hash the password before sending it to the server? I have a table in my database with a user and password column. When I want to check the login, should I send the password hashed to the server like <code>login.php?u=sled&p=34819d7beeabb9260a5c854bc85b3e44</code>, or just plain text like <code>login.php?u=sled&p=mypassword</code> and hash it on the server before I perform the authentication?</p>
</li>
</ol> | 5,692,496 | 1 | 0 | null | 2011-04-17 00:36:23.77 UTC | 9 | 2020-08-03 10:08:42.267 UTC | 2020-08-03 10:08:42.267 UTC | null | 1,783,163 | user393964 | null | null | 1 | 9 | android|http|authentication | 3,660 | <blockquote>
<p>Does android have anything like sessions or cookies?</p>
</blockquote>
<p>Yes. There are two alternatives. </p>
<p>Option #1:</p>
<p>You can use <a href="http://developer.android.com/reference/android/webkit/CookieManager.html" rel="nofollow"><code>CookieManager</code></a> to set your cookie.</p>
<p>Option #2:</p>
<p>The other alternative (I'm using this alternative in one of my applications) is to grab your cookie after you've sent your username and password to the server (e.g. via <code>HttpPost</code> or <code>HttpGet</code>). In your question you're using <code>$_GET</code> style of your login authentication, so my sample code will be using <code>HttpGet</code>.</p>
<p>Sample code using <code>HttpGet</code>:</p>
<pre><code>HttpParams httpParams = new BasicHttpParams();
// It's always good to set how long they should try to connect. In this
// this example, five seconds.
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
DefaultHttpClient postClient = new DefaultHttpClient(httpParams);
// Your url using $_GET style.
final String url = "www.yourwebsite.com/login.php?u=myusername&p=mypassword";
HttpGet httpGet = new HttpGet(url);
HttpResponse response;
try {
// Execute your HttpGet against the server and catch the response to our
// HttpResponse.
response = postClient.execute(httpGet);
// Check if everything went well.
if(response.getStatusLine().getStatusCode() == 200) {
// If so, grab the entity.
HttpEntity entity = response.getEntity();
// If entity isn't null, grab the CookieStore from the response.
if (entity != null) {
CookieStore cookies = postClient.getCookieStore();
// Do some more stuff, this should probably be a method where you're
// returning the CookieStore.
}
}
} catch (Exception e) {
}
</code></pre>
<p>Now when you have your <code>CookieStore</code>; grab a list of cookies from it and after that you can use <a href="http://developer.android.com/reference/org/apache/http/cookie/Cookie.html" rel="nofollow"><code>Cookie</code></a> to determine the name, domain, value etc...</p>
<p>Next time you're trying to access "locked" content of your website; set a cookie to your <code>HttpURLConnection</code> from your <code>Cookie</code> information:</p>
<pre><code>URL url = new URL("www.yourwebsite.com/lockedcontent.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setInstanceFollowRedirects(false);
// "Host" and "Cookie" are fields in the HTTP response. Use WireShark
// via your computer to determine correct header names.
httpURLConnection.setRequestProperty("Host", domainOfYourCookie);
httpURLConnection.setRequestProperty("Cookie", valueOfYourCookie);
final int responseCode = httpURLConnection.getResponseCode();
// And get the content...
</code></pre>
<blockquote>
<p>Should I hash the password before sending it to the server?</p>
</blockquote>
<p>Depends on how your system is designed. You must have correct information when sending it to your server. This also depends on how you're hashing your information in your .php file. </p>
<blockquote>
<p>How should I 'remember' that the user is loged in?</p>
</blockquote>
<p>Store the information in a <code>SharedPreferences</code> or something. Like I said earlier, you can hash it if your login system is correctly designed - this depends on how you're hashing it in your .php file. </p> |
5,760,662 | When using Backbone.View a "parent.apply is not a function" error is returned | <p>Consider this markup</p>
<pre><code><div id="controls" class="controls">
<a href="#">Home</a> -
<a href="#/get">get</a> -
<a href="#/new">new</a>
<input type="text" val="" id="input">
</div>
</code></pre>
<p>And this piece of javascript:</p>
<pre><code>$(document).ready(function() {
"use strict";
// this is used on my code as root.App,
// but the code was omitted here for clarity purposes
var root = this,
undefined;
var controller = Backbone.Controller.extend({
routes : {
// static
},
});
var view = new Backbone.View.extend({
el : $('#controls'),
events : {
'click a' : 'updateOnEnter'
},
updateOnEnter : function(el) {
alert('sss');
return this;
},
initialize : function() {
_.bindAll(this, 'render', 'updateOnEnter');
},
render : function() {
return this;
}
});
new view;
new controller;
Backbone.history.start();
)};
</code></pre>
<p>When <code>view</code> is called (with <code>new view</code>), Firebug fires this error:</p>
<pre><code>parent.apply is not a function
error backbone.js (line 1043): child = function(){ return parent.apply(this, arguments); };
</code></pre>
<p>Any ideas to why this is happening? Thanks.</p> | 5,764,066 | 1 | 0 | null | 2011-04-22 22:26:06.1 UTC | 7 | 2011-04-24 02:32:07.087 UTC | 2011-04-23 12:07:39.25 UTC | null | 104,419 | null | 104,419 | null | 1 | 30 | backbone.js | 8,479 | <p>Never mind.</p>
<p>The problem is on line 16 of the above js code:</p>
<pre><code>var view = new Backbone.View.extend({
</code></pre>
<p>it <strong>should</strong> instead be:</p>
<pre><code>var view = Backbone.View.extend({
</code></pre>
<p><em>I'm not deleting this question since somebody may find it useful.</em> The pitfalls of not coming from a CS background, I guess.</p> |
28,553,307 | Ansible Using Custom ssh config File | <p>I have a custom SSH config file that I typically use as follows</p>
<pre><code>ssh -F ~/.ssh/client_1_config amazon-server-01
</code></pre>
<p>Is it possible to assign Ansible to use this config for certain groups? It already has the keys and ports and users all set up. I have this sort of config for multiple clients, and would like to keep the config separate if possible.</p> | 28,553,408 | 4 | 0 | null | 2015-02-17 01:35:11.063 UTC | 4 | 2020-02-25 00:41:21.387 UTC | 2015-07-13 07:40:37.247 UTC | null | 2,753,241 | null | 3,152,127 | null | 1 | 30 | ansible | 44,866 | <p>Not fully possible. You can set ssh arguments in the <a href="http://docs.ansible.com/intro_configuration.html#ssh-args"><code>ansible.cfg</code></a>: </p>
<pre><code>[ssh_connection]
ssh_args = -F ~/.ssh/client_1_config amazon-server-01
</code></pre>
<p>Unfortunately it is not possible to define this per group, inventory or anything else specific.</p> |
2,974,442 | How to convert PDF files to images using RMagick and Ruby | <p>I'd like to take a PDF file and convert it to images, each PDF page becoming a separate image.</p>
<p>"<a href="https://stackoverflow.com/questions/65250/convert-a-doc-or-pdf-to-an-image-and-display-a-thumbnail-in-ruby">Convert a .doc or .pdf to an image and display a thumbnail in Ruby?</a>" is a similar post, but it doesn't cover how to make separate images for each page.</p> | 2,974,506 | 3 | 0 | null | 2010-06-04 13:12:53.457 UTC | 10 | 2020-02-29 04:57:42.813 UTC | 2020-02-29 04:54:58.92 UTC | null | 128,421 | null | 202,875 | null | 1 | 8 | ruby-on-rails|ruby|pdf|imagemagick|rmagick | 20,904 | <p><a href="http://www.imagemagick.org/" rel="nofollow noreferrer">ImageMagick</a> can do that with PDFs. Presumably <a href="http://rmagick.rubyforge.org/" rel="nofollow noreferrer">RMagick</a> can do it too, but I'm not familiar with it.</p>
<p>The code from the post you linked to:</p>
<pre><code>require 'RMagick'
pdf = Magick::ImageList.new("doc.pdf")
</code></pre>
<p><code>pdf</code> is an <code>ImageList</code> object, which according to the <a href="http://www.imagemagick.org/RMagick/doc/ilist.html#array_methods" rel="nofollow noreferrer">documentation</a> delegates many of its methods to <code>Array</code>. You should be able to iterate over <code>pdf</code> and call <code>write</code> to write the individual images to files.</p> |
7,481,869 | spring-security how ACL grants permissions | <p>I'm currently integrating springs-security into our new web application stack. We will need to be able to grant permissions for a user or role to access a specific object or all objects of a certain type. However that's one thing I didn't really get when working through documentations and examples:</p>
<p>Does an ACL only grant permissions to a user/role for a single object or does it do that for the entire type? As I understand it, <code>domain object</code> means the type but the examples and tutorials seem like they assign permissions to specific objects. Am I just confused or can I do both? If not, how do I do the other? </p>
<p>Thanks!</p> | 7,482,188 | 1 | 0 | null | 2011-09-20 07:58:23.497 UTC | 11 | 2011-10-04 12:01:29.337 UTC | 2011-09-20 08:27:42.46 UTC | null | 872,975 | null | 872,975 | null | 1 | 11 | permissions|spring-security|acl | 13,515 | <p>With spring-security you can do both. It's possible because spring-security supports the so called permission rules - within the spring-security terminology they call it <strong>permission evaluators</strong>. Permission rules encompass ACL, but also you can secure instances of objects when they're in a certain state...etc. </p>
<p>This is how it works:</p>
<ol>
<li><p>You need to extend the PermissionEvaluator - this allows you to have super custom logic for determining access rights - you can check the type of the object or check for a particular id, or check if the user invoking the method is the user that created the object, etc.:</p>
<pre class="lang-java prettyprint-override"><code>public class SomePermissionsEvaluator implements PermissionEvaluator {
@Override
public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
if (permission.equals("do_something") &&
/*authentication authorities has the role A*/) {
return true
} else if (permission.equals("do_something_else") &&
/*authentication authorities has the role B*/) {
return /*true if targetDomainObject satisfies certain condition*/;
}
return false;
}
@Override
public boolean hasPermission(Authentication authentication,
Serializable targetId, String targetType, Object permission) {
throw new UnsupportedOperationException();
}
}
</code></pre></li>
<li><p>Now that you have a security rule, you need to apply it through annotations:</p>
<pre class="lang-java prettyprint-override"><code>@PreAuthorize("hasRole('SOME_ROLE_OR_RIGHT') and" +
" hasPermission(#someDomainObject, 'do_something')")
public void updateSomeDomainObject(SomeDomainObject someDomainObject) {
// before updating the object spring-security will check the security rules
}
</code></pre></li>
<li><p>In order for this to work the security annotations should be enabled in the <strong>applicationContext.xml</strong>:</p>
<pre class="lang-xml prettyprint-override"><code><global-method-security secured-annotations="enabled" pre-post-annotations="enabled">
<expression-handler ref="expressionHandler"/>
</global-method-security>
<beans:bean id="expressionHandler" class="org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler">
<beans:property name="permissionEvaluator">
<beans:bean id="permissionEvaluator" class="com.npacemo.permissions.SomePermissionsEvaluator"/>
</beans:property>
</beans:bean>
</code></pre></li>
</ol> |
24,658,011 | Can you remove a folder structure when copying files in gulp? | <p>If I use : </p>
<pre><code> gulp.src(['app/client/**/*.html'])
.pipe(gulp.dest('dist'));
</code></pre>
<p>The folder structure in which my <code>.html</code> files were in, is maintained in the <code>dist</code> folder, but I would like to remove the folder structure completely and just a flat hierarchy in my <code>dist</code> folder.</p> | 24,741,585 | 2 | 0 | null | 2014-07-09 15:38:30.993 UTC | 15 | 2016-03-17 13:33:26.4 UTC | 2016-03-17 13:33:26.4 UTC | null | 2,568,670 | null | 3,759,372 | null | 1 | 65 | gulp | 19,386 | <p>You could use <code>gulp-rename</code> to accomplish this:</p>
<pre><code>var rename = require('gulp-rename');
gulp.src('app/client/**/*.html')
.pipe(rename({dirname: ''}))
.pipe(gulp.dest('dist'));
</code></pre> |
22,149,989 | AWS: "Unable to parse certificate. Please ensure the certificate is in PEM format." | <p>I am trying to update a wildcard certificate for EC2 instances on AWS. The service these servers belong to consists of a single server and a set of servers behind AWS ELB. </p>
<p>The certificate has been successfully updated and verified on the single server.</p>
<p>The same is true for an instance pulled up from the image the ELB uses for AutoScaling.</p>
<p>However, when trying to add a new certificate to the load-balancer, I get the above error. I'm sure the certificate is correct and is in PEM format. I first tried via the web console, then using the aws aim command line tools with the same result.</p>
<p>Anyone came across similar issue recently?</p> | 22,165,198 | 5 | 0 | null | 2014-03-03 14:57:53.383 UTC | 11 | 2022-07-21 11:30:47.69 UTC | 2015-05-13 17:19:25.87 UTC | null | 1,207,049 | null | 1,207,049 | null | 1 | 45 | amazon-web-services|ssl-certificate|amazon-elb | 22,350 | <p>Just ran into the same exact issue: web console and AWS CLI reporting the same error in not being able to parse the certificate.</p>
<p>The error's root cause turned out to be in the private key -- converting my private key to a "RSA PRIVATE KEY" fixed the issue:</p>
<pre><code>openssl rsa -in server.key -out server.key.rsa
</code></pre>
<p>Then, use the <code>server.key.rsa</code> in the private key field and leave the public cert as is.</p> |
2,550,628 | How to use external makefile in Eclipse | <p>I have a source code of an OpenSource project which I get from SVN. I was able to run autogen --> configure --> and make successfully (through the terminal). But I want to build the same project with Eclipse, and I can't port manually those source files to eclipse though. So, How can I set Eclipse to use external make files ? can anyone please help me ? Thanks.</p> | 2,654,178 | 3 | 2 | null | 2010-03-31 05:12:50.873 UTC | 4 | 2021-03-13 10:19:21.523 UTC | 2010-04-04 21:03:45.137 UTC | null | 39,590 | null | 134,804 | null | 1 | 20 | c++|eclipse|makefile|ubuntu-9.04 | 56,092 | <p>Ok, I got it, It was straightforward. Just go to project properties --> C/C++ Build --> Make file generation --> and untick "Generate Make files automatically". In additionally you may have to set the Build location also. </p> |
2,573,805 | using objc_msgSend to call a Objective C function with named arguments | <p>I want to add scripting support for an Objective-C project using the objc runtime. Now I face the problem, that I don't have a clue, how I should call an Objective-C method which takes several named arguments.</p>
<p>So for example the following objective-c call</p>
<pre><code>[object foo:bar];
</code></pre>
<p>could be called from C with:</p>
<pre><code>objc_msgSend(object, sel_getUid("foo:"), bar);
</code></pre>
<p>But how would I do something similar for the method call:</p>
<pre><code>[object foo:var bar:var2 err:errVar];
</code></pre>
<p>??</p>
<p>Best Markus</p> | 2,573,816 | 3 | 2 | null | 2010-04-04 07:08:20.99 UTC | 20 | 2012-04-19 12:37:16.163 UTC | null | null | null | null | 153,815 | null | 1 | 26 | objective-c|cocoa|reflection | 20,757 | <pre><code>objc_msgSend(object, sel_getUid("foo:bar:err:"), var, var2, errVar);
</code></pre>
<p>If one of the variables is a <code>float</code>, you need to use <a href="https://stackoverflow.com/questions/2573805/using-objc-msgsend-to-call-a-objective-c-function-with-named-arguments/2573949#2573949">@Ken</a>'s method, or <em>cheat</em> by a reinterpret-cast:</p>
<pre><code>objc_msgSend(..., *(int*)&var, ...)
</code></pre>
<p>Also, if the selector returns a float, you <em>may</em> need to use <code>objc_msgSend_fpret</code>, and if it returns a struct you must use <code>objc_msgSend_stret</code>. If that is a call to superclass you need to use <code>objc_msgSendSuper2</code>.</p> |
2,503,555 | Using LaTeX, how can I have a list of references at the end of each section? | <p>I want to generate the bibliography for each section, and have it at the end of the section. When I do this at the moment it generates the full bibliography and places it after each section.</p>
<p>Is there a way that this can be done? </p>
<p>The advice <a href="http://merkel.zoneo.net/Latex/natbib.php" rel="noreferrer">here</a> says </p>
<blockquote>
<p>"The chapterbib package provides an
option sectionbib that puts the
bibliography in a \section* instead of
\chapter*, something that makes sense
if there is a bibliography in each
chapter. This option will not work
when natbib is also loaded; instead,
add the option to natbib. "</p>
</blockquote>
<p>I don't understand what this means, and I've tried experimenting with what I thought the options are. Specifically, what does "add the option to natbib" mean?</p>
<p>My subsequent question (which evolved after my first one was solved) is to not have pagebreaks between the references, and the next section.</p>
<p>Thank you for your help.</p> | 2,665,057 | 4 | 0 | null | 2010-03-23 20:55:25.733 UTC | 10 | 2010-04-19 03:30:17.167 UTC | 2010-03-24 15:02:44.957 UTC | null | 258,755 | null | 258,755 | null | 1 | 15 | latex|bibtex|bibliography | 28,641 | <p>If you are using <a href="http://www.ctan.org/tex-archive/help/Catalogue/entries/biblatex.html" rel="nofollow noreferrer">Biblatex</a>, as for <a href="https://stackoverflow.com/questions/2496599/how-do-i-cite-the-title-of-an-article-in-latex">citing article titles</a>, you can use it to produce bibliographies at the end of sections or chapters, or even have a combined bibliography where they are separated by chapter/section. As a package, it is intended to replace "babelbib, bibtopic, bibunits, chapterbib, cite, inlinebib, mlbib, multibib, splitbib."</p>
<p>You can put a bibliography after each section, in one of three ways. First, wrap the text of your section in a <code>\begin{refsection}</code>/<code>\end{refsection}</code> pair, as such</p>
<pre><code>\section{SomeSectionName}
\begin{refsection}
% your text goes here
\printbibliography
\end{refsection}
\section{NextSection}
</code></pre>
<p>Second, after each <code>\section</code> statement you put a <code>\newrefsection</code> statement which ends the previous section and begins the new one. And, you precede the next <code>\section</code> with a <code>\printbibliography</code> statement, again. Finally, there is a <code>refsection</code> package option that takes either <code>none</code>, <code>part</code>, <code>chapter</code>, <code>section</code>, or <code>subsection</code> as an argument. To group your bibliographic entries per section in a global bibliography you use <code>refsegment</code> instead, using <code>\bibbysegment</code> to print all the segments in order. (<code>\bibbysection</code> can be used in the same manner for ref-sections, too.)</p>
<p>I don't know how much you'll have to split up your text, as per @Norman's answer, but with a little experimentation you can figure it out.</p> |
2,804,688 | how to change the color of the tabs indicator text in android? | <p>how to change the color of the text indicator of tab? i can change the icon using selector tag refered the <a href="http://developer.android.com/resources/tutorials/views/hello-tabwidget.html" rel="noreferrer">example</a>. but cant to the text color. how? </p> | 2,805,256 | 4 | 0 | null | 2010-05-10 17:01:54.087 UTC | 17 | 2013-03-28 11:04:18.597 UTC | 2010-08-21 13:03:01.343 UTC | null | 267,269 | null | 267,269 | null | 1 | 25 | android|tabs|tabwidget | 66,763 | <p>Style it
in your custom theme change </p>
<pre><code><item name="android:tabWidgetStyle">@android:style/Widget.TabWidget</item>
</code></pre>
<p>and</p>
<pre><code><style name="Widget.TabWidget">
<item name="android:textAppearance">@style/TextAppearance.Widget.TabWidget</item>
<item name="android:ellipsize">marquee</item>
<item name="android:singleLine">true</item>
</style>
<style name="TextAppearance.Widget.TabWidget">
<item name="android:textSize">14sp</item>
<item name="android:textStyle">normal</item>
<item name="android:textColor">@android:color/tab_indicator_text</item>
</style>
</code></pre> |
31,743,534 | Angular Grid ag-grid columnDefs Dynamically change | <p>I have a problem about <code>columnDefs</code> change dynamically. Here is my gridOptions:</p>
<pre><code>$scope.gridOptions = {
columnDefs: [],
enableFilter: true,
rowData: null,
rowSelection: 'multiple',
rowDeselection: true
};
</code></pre>
<p>And when I retrieve data from server:</p>
<pre><code>$scope.customColumns = [];
$http.post('/Home/GetProducts', { tableName: 'TABLE_PRODUCT' }).success(function (data) {
angular.forEach(data.Columns, function (c) {
$scope.customColumns.push(
{
headerName: c.Name,
field: c.Value,
width: c.Width
}
);
});
$scope.gridOptions.columnDefs = $scope.customColumns;
$scope.gridOptions.rowData = data.Products;
$scope.gridOptions.api.onNewRows();
}).error(function () {
});
</code></pre>
<p><strong>Note: here c is column object which comes from server.</strong></p>
<p>When dynamically generating columns and assigning it to $scope.gridOptions.columnDefs there is blank grid but <code>$scope.customColumns</code> array is filled with right generated column objects. Please help me is this bug or I am doing something wrong?</p> | 31,816,050 | 3 | 1 | null | 2015-07-31 10:05:02.043 UTC | 3 | 2020-10-29 11:07:56.387 UTC | 2020-10-29 07:44:43.22 UTC | null | 5,377,805 | null | 3,256,552 | null | 1 | 26 | angularjs|dynamic|ag-grid | 77,318 | <p>In ag-grid the columns in gridOptions are used once at grid initialisation. If you change the columns after initialisation, you must tell the grid. This is done by calling <code>gridOptions.api.setColumnDefs()</code></p>
<p>Details of this api method are provided in the <a href="http://www.ag-grid.com/angular-grid-api/index.php" rel="noreferrer">ag-grid documentation here</a>.</p> |
31,922,349 | How to add TextField to UIAlertController in Swift | <p>I am trying to show a <code>UIAlertController</code> with a <code>UITextView</code>. When I add the line:</p>
<pre><code> //Add text field
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
}
</code></pre>
<p>I get a <code>Runtime</code> error: </p>
<blockquote>
<p>fatal error: unexpectedly found nil while unwrapping an Optional value</p>
</blockquote>
<pre><code> let alertController: UIAlertController = UIAlertController(title: "Find image", message: "Search for image", preferredStyle: .Alert)
//cancel button
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//cancel code
}
alertController.addAction(cancelAction)
//Create an optional action
let nextAction: UIAlertAction = UIAlertAction(title: "Search", style: .Default) { action -> Void in
let text = (alertController.textFields?.first as! UITextField).text
println("You entered \(text)")
}
alertController.addAction(nextAction)
//Add text field
alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
textField.textColor = UIColor.greenColor()
}
//Present the AlertController
presentViewController(alertController, animated: true, completion: nil)
</code></pre>
<p>This is presented inside my <code>ViewController</code> via an <code>IBAction</code>.</p>
<p>I have downloaded the code from <a href="http://sourcefreeze.com/uialertcontroller-ios-8-using-swift/" rel="noreferrer">here</a> and it works fine. I copied and pasted that method into my code and it breaks. The presence of <strong>self</strong> on the last line has no impact.</p> | 33,000,328 | 13 | 1 | null | 2015-08-10 14:33:22.223 UTC | 16 | 2021-11-08 08:24:31.843 UTC | 2021-11-08 08:24:31.843 UTC | null | 8,090,893 | null | 932,052 | null | 1 | 103 | ios|swift|xcode|uitextfield|uialertcontroller | 108,080 | <h3>Swift 5.1</h3>
<pre><code>alert.addTextField { (textField) in
textField.placeholder = "Enter First Name"
}
</code></pre>
<hr />
<p>Use this code, I am running this code in my app successfully.</p>
<pre><code>@IBAction func addButtonClicked(sender : AnyObject){
let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
textField.placeholder = "Enter Second Name"
}
let saveAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: { alert -> Void in
let firstTextField = alertController.textFields![0] as UITextField
let secondTextField = alertController.textFields![1] as UITextField
})
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: {
(action : UIAlertAction!) -> Void in })
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
textField.placeholder = "Enter First Name"
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
</code></pre>
<p>Edited: Swift 3.0 version</p>
<pre><code>@IBAction func addButtonClicked(_ sender: UIButton){
let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = "Enter Second Name"
}
let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
let firstTextField = alertController.textFields![0] as UITextField
let secondTextField = alertController.textFields![1] as UITextField
print("firstName \(firstTextField.text), secondName \(secondTextField.text)")
})
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: { (action : UIAlertAction!) -> Void in })
alertController.addTextField { (textField : UITextField!) -> Void in
textField.placeholder = "Enter First Name"
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
</code></pre> |
48,989,238 | post equivalent in scripted pipeline? | <p>What is the syntax of 'post' in scripted pipeline comparing to declarative pipeline?
<a href="https://jenkins.io/doc/book/pipeline/syntax/#post" rel="noreferrer">https://jenkins.io/doc/book/pipeline/syntax/#post</a> </p> | 48,991,594 | 2 | 0 | null | 2018-02-26 13:05:26.78 UTC | 11 | 2022-04-12 10:25:42.457 UTC | null | null | null | null | 7,726,272 | null | 1 | 51 | jenkins-pipeline | 28,148 | <p>For scripted pipeline, everything must be written programmatically and most of the work is done in the <code>finally</code> block:</p>
<p><code>Jenkinsfile</code> (Scripted Pipeline):</p>
<pre class="lang-groovy prettyprint-override"><code>node {
try {
stage('Test') {
sh 'echo "Fail!"; exit 1'
}
echo 'This will run only if successful'
} catch (e) {
echo 'This will run only if failed'
// Since we're catching the exception in order to report on it,
// we need to re-throw it, to ensure that the build is marked as failed
throw e
} finally {
def currentResult = currentBuild.result ?: 'SUCCESS'
if (currentResult == 'UNSTABLE') {
echo 'This will run only if the run was marked as unstable'
}
def previousResult = currentBuild.getPreviousBuild()?.result
if (previousResult != null && previousResult != currentResult) {
echo 'This will run only if the state of the Pipeline has changed'
echo 'For example, if the Pipeline was previously failing but is now successful'
}
echo 'This will always run'
}
}
</code></pre>
<p><a href="https://jenkins.io/doc/pipeline/tour/running-multiple-steps/#finishing-up" rel="noreferrer">https://jenkins.io/doc/pipeline/tour/running-multiple-steps/#finishing-up</a></p> |
3,094,730 | iPhone NSDateFormatter Timezone Conversion | <p>I am trying to create a formatter that will convert the date format shown to an NSDate object:</p>
<pre><code>NSString *dateStr = @"2010-06-21T19:00:00-05:00";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate *date = [dateFormat dateFromString:dateStr];
</code></pre>
<p>The issue is the timezone -05:00, which is not parsed properly with the format above. Any suggestions?</p> | 3,096,463 | 6 | 5 | null | 2010-06-22 15:42:48.397 UTC | 8 | 2015-05-19 23:18:57.587 UTC | 2010-06-22 16:07:13.777 UTC | null | 73,043 | null | 73,043 | null | 1 | 34 | iphone|nsdateformatter | 34,401 | <p>Honestly, you'll just have to change the source data (removing the colon) before running it through the formatter. Your original date string is non-standard and none of the time zone format strings will work properly on it.</p>
<p>You can see the valid inputs <a href="http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns" rel="noreferrer">on unicode.org</a>.</p>
<p>ZZZ e.g. "-0500"</p>
<p>ZZZZ e.g. "GMT-05:00"</p>
<p>Nothing for "-05:00"</p> |
3,205,730 | javascript parseFloat '500,000' returns 500 when I need 500000 | <p>How would it be a nice way of handling this?</p>
<p>I already thought on removing the comma and then parsing to float. </p>
<p>Do you know a better/cleaner way?</p>
<p>Thanks</p> | 3,205,735 | 7 | 1 | null | 2010-07-08 16:15:05.817 UTC | 8 | 2016-10-05 09:03:46.95 UTC | null | null | null | null | 102,957 | null | 1 | 39 | javascript|parsefloat | 35,913 | <p>Nope. Remove the comma.</p> |
2,633,483 | Best approach for GPGPU/CUDA/OpenCL in Java? | <p>General-purpose computing on graphics processing units (<a href="http://en.wikipedia.org/wiki/GPGPU" rel="noreferrer">GPGPU</a>) is a very attractive concept to harness the power of the GPU for any kind of computing. </p>
<p>I'd love to use GPGPU for image processing, particles, and fast geometric operations.</p>
<p>Right now, it seems the two contenders in this space are CUDA and OpenCL. I'd like to know:</p>
<ul>
<li>Is OpenCL usable yet from Java on Windows/Mac?</li>
<li>What are the libraries ways to interface to OpenCL/CUDA?</li>
<li>Is using JNA directly an option?</li>
<li>Am I forgetting something?</li>
</ul>
<p>Any real-world experience/examples/war stories are appreciated.</p> | 3,307,145 | 8 | 10 | null | 2010-04-13 21:53:54.96 UTC | 39 | 2019-10-22 08:23:50.85 UTC | null | null | null | null | 231,298 | null | 1 | 96 | java|cuda|gpgpu|opencl | 48,861 | <p>AFAIK, <a href="https://github.com/nativelibs4java/JavaCL" rel="noreferrer" title="JavaCL / OpenCL4Java">JavaCL / OpenCL4Java</a> is the only OpenCL binding that is available on all platforms right now (including MacOS X, FreeBSD, Linux, Windows, Solaris, all in Intel 32, 64 bits and ppc variants, thanks to its use of <a href="https://github.com/twall/jna/" rel="noreferrer" title="JNA">JNA</a>).</p>
<p>It has demos that actually run fine from Java Web Start at least on Mac and Windows (to avoid random crashes on Linux, please see <a href="http://code.google.com/p/javacl/wiki/TroubleShootingJavaCLOnLinux" rel="noreferrer" title="this wiki page">this wiki page</a>, such as this <a href="http://nativelibs4java.sourceforge.net/webstart/OpenCL/ParticlesDemo.jnlp" rel="noreferrer" title="Particles Demo">Particles Demo</a>.</p>
<p>It also comes with a few utilities (GPGPU random number generation, basic parallel reduction, linear algebra) and a <a href="http://ochafik.free.fr/blog/?p=207" rel="noreferrer" title="Scala DSL">Scala DSL</a>.</p>
<p>Finally, it's the oldest bindings available (since june 2009) and <a href="http://groups.google.com/group/nativelibs4java" rel="noreferrer" title="NativeLibs4Java's user group">it has an active user community</a>.</p>
<p>(Disclaimer: I'm <a href="http://code.google.co" rel="noreferrer">JavaCL</a>'s author :-))</p> |
2,432,452 | How to capitalize the first word of the sentence in Objective-C? | <p>I've already found how to capitalize all words of the sentence, but not the first word only.</p>
<pre><code>NSString *txt =@"hi my friends!"
[txt capitalizedString];
</code></pre>
<p>I don't want to change to lower case and capitalize the first char. I'd like to capitalize the first word only without change the others.</p> | 2,435,502 | 9 | 0 | null | 2010-03-12 11:53:08.833 UTC | 17 | 2015-09-08 14:57:50.7 UTC | 2011-08-13 17:01:59.123 UTC | null | 60,488 | null | 276,615 | null | 1 | 35 | objective-c|string|cocoa|nsstring|capitalization | 24,712 | <p>Here is another go at it:</p>
<pre><code>NSString *txt = @"hi my friends!";
txt = [txt stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[txt substringToIndex:1] uppercaseString]];
</code></pre>
<p>For Swift language:</p>
<pre><code>txt.replaceRange(txt.startIndex...txt.startIndex, with: String(txt[txt.startIndex]).capitalizedString)
</code></pre> |
2,521,901 | Get a list/tuple/dict of the arguments passed to a function? | <p>Given the following function:</p>
<pre><code>def foo(a, b, c):
pass
</code></pre>
<p>How would one obtain a list/tuple/dict/etc of the arguments passed in, <strong>without having to build the structure myself</strong>?</p>
<p>Specifically, I'm looking for Python's version of JavaScript's <code>arguments</code> keyword or PHP's <code>func_get_args()</code> method.</p>
<p>What I'm <strong>not</strong> looking for is a solution using <code>*args</code> or <code>**kwargs</code>; I need to specify the argument names in the function definition (to ensure they're being passed in) but within the function I want to work with them in a list- or dict-style structure.</p> | 2,521,937 | 9 | 4 | null | 2010-03-26 08:30:54.55 UTC | 9 | 2021-01-27 21:11:05.983 UTC | 2010-03-26 08:39:12.833 UTC | null | 30,478 | null | 30,478 | null | 1 | 102 | python|function|arguments | 51,064 | <p>You can use <code>locals()</code> to get a dict of the local variables in your function, like this:</p>
<pre><code>def foo(a, b, c):
print locals()
>>> foo(1, 2, 3)
{'a': 1, 'c': 3, 'b': 2}
</code></pre>
<p>This is a bit hackish, however, as <code>locals()</code> returns all variables in the local scope, not only the arguments passed to the function, so if you don't call it at the very top of the function the result might contain more information than you want:</p>
<pre><code>def foo(a, b, c):
x = 4
y = 5
print locals()
>>> foo(1, 2, 3)
{'y': 5, 'x': 4, 'c': 3, 'b': 2, 'a': 1}
</code></pre>
<p>I would rather construct a dict or list of the variables you need at the top of your function, as suggested in the other answers. It's more explicit and communicates the intent of your code in a more clear way, IMHO.</p> |
2,404,577 | .Net System.Mail.Message adding multiple "To" addresses | <p>This question is pointless, except as an exercise in red herrings. The issue turned out to be a combination of my idiocy (NO ONE was being emailed as the host was not being specified and was incorrect in <code>web.config</code>) and the users telling me that they sometimes got the emails and sometimes didn't, when in reality they were NEVER getting the emails.**</p>
<p><strong>So, instead of taking proper steps to reproduce the problem in a controlled setting, I relied on user information and the "it works on my machine" mentality.
Good reminder to myself and anyone else out there who is sometimes an idiot.</strong></p>
<hr />
<p>I just hit something I think is inconsistent, and wanted to see if I'm doing something wrong, if I'm an idiot, or...</p>
<pre><code>MailMessage msg = new MailMessage();
msg.To.Add("[email protected]");
msg.To.Add("[email protected]");
msg.To.Add("[email protected]");
msg.To.Add("[email protected]");
</code></pre>
<p>Really only sends this email to 1 person, the last one.</p>
<p>To add multiples I have to do this:</p>
<pre><code>msg.To.Add("[email protected],[email protected],[email protected],[email protected]");
</code></pre>
<p>I don't get it. I thought I was adding multiple people to the <code>To</code> address collection, but what I was doing was replacing it.</p>
<p>I think I just realized my error -- to add one item to the collection, use
.To.Add(new MailAddress("[email protected]"))</p>
<p>If you use just a <code>string</code>, it replaces everything it had in its list.
Other people have tested and are not seeing this behavior. This is either a bug in my particular version of the framework, or more likely, an idiot maneuver by me.**</p>
<p>Ugh. I'd consider this a rather large gotcha! Since I answered my own question, but I think this is of value to have in the Stack Overflow archive, I'll still ask it. Maybe someone even has an idea of other traps that you can fall into.</p> | 2,404,666 | 10 | 3 | null | 2010-03-08 20:42:17.863 UTC | 4 | 2022-07-09 23:42:49.92 UTC | 2022-07-09 23:40:33.477 UTC | null | 1,145,388 | null | 232 | null | 1 | 43 | asp.net|system.net.mail | 112,591 | <p>I wasn't able to replicate your bug:</p>
<pre><code>var message = new MailMessage();
message.To.Add("[email protected]");
message.To.Add("[email protected]");
message.From = new MailAddress("[email protected]");
message.Subject = "Test";
message.Body = "Test";
var client = new SmtpClient("localhost", 25);
client.Send(message);
</code></pre>
<p>Dumping the contents of the To: <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.mailaddresscollection.aspx" rel="noreferrer">MailAddressCollection</a>:</p>
<blockquote>
<p>MailAddressCollection (2 items)<br>
DisplayName User Host Address </p>
<p>user example.com [email protected]<br>
user2 example.com [email protected]</p>
</blockquote>
<p>And the resulting e-mail as caught by <a href="http://smtp4dev.codeplex.com/" rel="noreferrer">smtp4dev</a>:</p>
<pre><code>Received: from mycomputername (mycomputername [127.0.0.1])
by localhost (Eric Daugherty's C# Email Server)
3/8/2010 12:50:28 PM
MIME-Version: 1.0
From: [email protected]
To: [email protected], [email protected]
Date: 8 Mar 2010 12:50:28 -0800
Subject: Test
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: quoted-printable
Test
</code></pre>
<p><strong>Are you sure there's not some other issue going on with your code or SMTP server?</strong></p> |
2,614,767 | Using R to Analyze Balance Sheets and Income Statements | <p>I am interested in analyzing balance sheets and income statements using R. I have seen that there are R packages that pull information from Yahoo and Google Finance, but all the examples I have seen concern historical stock price information. Is there a way I can pull historical information from balance sheets and income statements using R?</p> | 2,614,785 | 11 | 2 | null | 2010-04-10 20:02:10.287 UTC | 14 | 2020-10-15 18:33:54.563 UTC | null | null | null | null | 235,349 | null | 1 | 11 | r|finance | 29,199 | <p>You are making the common mistake of confusing 'access to Yahoo or Google data' with 'everything I see on Yahoo or Google Finance can be downloaded'.</p>
<p>When R functions download historical stock price data, they almost always access an interface explicitly designed for this purpose as e.g. a cgi handler providing csv files given a stock symbol and start and end date. So this <em>easy</em> as all we need to do is form the appropriate query, hit the webserver, fetch the csv file an dparse it.</p>
<p>Now balance sheet information is (as far as I know) not available in such an interface. So you will need to 'screen scrape' and parse the html directly. </p>
<p>It is not clear that R is the best tool for this. I am aware of some Perl modules for the purpose of getting non-time-series data off Yahoo Finance but have not used them.</p> |
3,086,467 | Confused, are languages like python, ruby single threaded? unlike say java? (for web apps) | <p>I was reading how Clojure is 'cool' because of its syntax + it runs on the JVM so it is multithreaded etc. etc.</p>
<p>Are languages like ruby and python single threaded in nature then? (when running as a web app).</p>
<p>What are the underlying differences between python/ruby and say java running on tomcat?</p>
<p>Doesn't the web server have a pool of threads to work with in all cases?</p> | 3,086,582 | 13 | 4 | null | 2010-06-21 16:29:18.27 UTC | 26 | 2020-02-12 05:21:16.377 UTC | 2010-06-21 18:14:33.85 UTC | null | 84,018 | null | 39,677 | null | 1 | 63 | java|python|ruby|multithreading | 38,252 | <p>Both Python and Ruby have full support for multi-threading. There are some implementations (e.g. CPython, MRI, YARV) which cannot actually run threads in parallel, but that's a limitation of those specific implementations, not the language. This is similar to Java, where there are also some implementations which cannot run threads in parallel, but that doesn't mean that Java is single-threaded.</p>
<p>Note that in both cases there are lots of implementations which <em>can</em> run threads in parallel: PyPy, IronPython, Jython, IronRuby and JRuby are only few of the examples.</p>
<p>The main difference between Clojure on the one side and Python, Ruby, Java, C#, C++, C, PHP and pretty much every other mainstream and not-so-mainstream language on the other side is that Clojure has a <em>sane</em> concurrency model. All the other languages use threads, which we have known to be a bad concurrency model for at least 40 years. Clojure OTOH has a sane update model which allows it to not only present one but actually multiple sane concurrency models to the programmer: atomic updates, software transactional memory, asynchronous agents, concurrency-aware thread-local global variables, futures, promises, dataflow concurrency and in the future possibly even more.</p> |
2,611,764 | Can I use a binary literal in C or C++? | <p>I need to work with a binary number.</p>
<p>I tried writing:</p>
<pre><code>const char x = 00010000;
</code></pre>
<p>But it didn't work.</p>
<p>I know that I can use a hexadecimal number that has the same value as <code>00010000</code>, but I want to know if there is a type in C++ for binary numbers, and if there isn't, is there another solution for my problem?</p> | 2,611,883 | 23 | 9 | null | 2010-04-10 00:35:10.7 UTC | 59 | 2022-09-19 13:27:14.773 UTC | 2022-09-19 13:27:14.773 UTC | null | 18,413,363 | null | 1,815,939 | null | 1 | 225 | c++|c|binary | 436,632 | <p>You can <a href="http://www.boost.org/doc/libs/1_42_0/libs/utility/utility.htm#BOOST_BINARY" rel="nofollow noreferrer">use <strong><code>BOOST_BINARY</code></strong></a> while waiting for C++0x. :) <code>BOOST_BINARY</code> arguably has an advantage over template implementation insofar as it <strong>can be used in C programs as well</strong> (it is 100% preprocessor-driven.)</p>
<p>To do the converse (i.e. print out a number in binary form), you can use the non-portable <a href="http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/" rel="nofollow noreferrer"><code>itoa</code> function</a>, or <a href="http://www.jb.man.ac.uk/~slowe/cpp/itoa.html" rel="nofollow noreferrer">implement your own</a>.</p>
<p>Unfortunately you cannot do base 2 formatting with STL streams (since <a href="http://en.cppreference.com/w/cpp/io/manip/setbase" rel="nofollow noreferrer"><code>setbase</code></a> will only honour bases 8, 10 and 16), but you <em>can</em> use either a <code>std::string</code> version of <code>itoa</code>, or (the more concise, yet marginally less efficient) <code>std::bitset</code>.</p>
<pre><code>#include <boost/utility/binary.hpp>
#include <stdio.h>
#include <stdlib.h>
#include <bitset>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
unsigned short b = BOOST_BINARY( 10010 );
char buf[sizeof(b)*8+1];
printf("hex: %04x, dec: %u, oct: %06o, bin: %16s\n", b, b, b, itoa(b, buf, 2));
cout << setfill('0') <<
"hex: " << hex << setw(4) << b << ", " <<
"dec: " << dec << b << ", " <<
"oct: " << oct << setw(6) << b << ", " <<
"bin: " << bitset< 16 >(b) << endl;
return 0;
}
</code></pre>
<p>produces:</p>
<pre><code>hex: 0012, dec: 18, oct: 000022, bin: 10010
hex: 0012, dec: 18, oct: 000022, bin: 0000000000010010
</code></pre>
<p>Also read Herb Sutter's <em><a href="http://www.gotw.ca/publications/mill19.htm" rel="nofollow noreferrer">The String Formatters of Manor Farm</a></em> for an interesting discussion.</p> |
40,697,845 | What is a good practice to check if an environmental variable exists or not? | <p>I want to check my environment for the existence of a variable, say <code>"FOO"</code>, in Python. For this purpose, I am using the <code>os</code> standard library. After reading the library's documentation, I have figured out 2 ways to achieve my goal:</p>
<p>Method 1: </p>
<pre><code>if "FOO" in os.environ:
pass
</code></pre>
<p>Method 2:</p>
<pre><code>if os.getenv("FOO") is not None:
pass
</code></pre>
<p>I would like to know which method, if either, is a good/preferred conditional and why.</p> | 40,698,307 | 6 | 10 | null | 2016-11-19 20:59:57.637 UTC | 25 | 2021-10-02 21:13:19.733 UTC | 2016-11-19 22:35:28.993 UTC | null | 4,952,130 | null | 4,927,751 | null | 1 | 231 | python|python-2.7|python-3.x|if-statement|environment-variables | 211,289 | <p>Use the first; it directly tries to check if something is defined in <code>environ</code>. Though the second form works equally well, it's lacking semantically since you get a value back if it exists and <em>only</em> use it for a comparison. </p>
<p>You're trying to see if something is present <em>in</em> <code>environ</code>, why would you <em>get</em> just to compare it and then <em>toss it away</em>? </p>
<p>That's exactly what <code>getenv</code> does:</p>
<blockquote>
<p><em>Get an environment variable</em>, return <code>None</code> if it doesn't exist. The
optional second argument can specify an alternate default.</p>
</blockquote>
<p>(this also means your check could just be <code>if getenv("FOO")</code>)</p>
<p>you don't want to <em>get it</em>, you want to check for it's existence. </p>
<p>Either way, <code>getenv</code> is just a wrapper around <code>environ.get</code> but you don't see people checking for membership in mappings with:</p>
<pre><code>from os import environ
if environ.get('Foo') is not None:
</code></pre>
<p>To summarize, use: </p>
<pre><code>if "FOO" in os.environ:
pass
</code></pre>
<p>if you <em>just</em> want to check for existence, while, use <code>getenv("FOO")</code> if you actually want to do something with the value you might get.</p> |
25,243,586 | Javascript: add value to array while looping that will then also be included in the loop | <p>Sorry if this is a dupplicate, can't seem to find it.</p>
<pre><code>var a = [1,2,3,4];
a.forEach(function(value){
if(value == 1) a.push(5);
console.log(value);
});
</code></pre>
<p>I wonder if there is a way (any sort of loop or datatype) so that this will ouput 1 2 3 4 5 during the loop (or in any order, as long as all the 5 numbers are in there)</p> | 25,243,688 | 9 | 0 | null | 2014-08-11 12:42:59.097 UTC | 3 | 2022-09-19 16:43:01.437 UTC | 2014-08-11 19:07:27.303 UTC | null | 977,206 | null | 977,206 | null | 1 | 21 | javascript|arrays|loops | 81,298 | <p>Using <code>Array.prototype.forEach()</code> will <em>not</em> apply the callback to elements that are appended to, or removed from, the array during execution. From the <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18">specification</a>:</p>
<blockquote>
<p>The range of elements processed by <strong>forEach</strong> is set before the first
call to <em>callbackfn</em>. Elements which are appended to the array after the
call to <strong>forEach</strong> begins will not be visited by <em>callbackfn</em>.</p>
</blockquote>
<p>You can, however, use a standard <code>for</code> loop with the conditional checking the current length of the array during each iteration:</p>
<pre><code>for (var i = 0; i < a.length; i++) {
if (a[i] == 1) a.push(5);
console.log(a[i]);
}
</code></pre> |
45,466,090 | How to get the API Token for Jenkins | <p>I am trying to use the jenkins rest api. In the instructions it says I need to have the api key. I have looked all over the configuration pages to find it. How do i get the API key for jenkins?</p> | 45,466,184 | 4 | 1 | null | 2017-08-02 16:19:52.65 UTC | 21 | 2022-07-08 02:45:40.413 UTC | null | null | null | null | 184,773 | null | 1 | 102 | jenkins | 126,798 | <p>Since Jenkins 2.129 the API token configuration <a href="https://jenkins.io/blog/2018/07/02/new-api-token-system/" rel="noreferrer">has changed</a>:</p>
<p>You can now have multiple tokens and name them. They can be revoked individually.</p>
<ol>
<li>Log in to Jenkins.</li>
<li>Click you name (upper-right corner).</li>
<li>Click <strong>Configure</strong> (left-side menu).</li>
<li>Use "Add new Token" button to generate a new one then name it.</li>
<li>You must copy the token when you generate it as you cannot view the token afterwards.</li>
<li>Revoke old tokens when no longer needed.</li>
</ol>
<p>Before Jenkins 2.129: Show the API token as follows:</p>
<ol>
<li>Log in to Jenkins.</li>
<li>Click your name (upper-right corner).</li>
<li>Click <strong>Configure</strong> (left-side menu).</li>
<li>Click <strong>Show API Token</strong>.</li>
</ol>
<p>The API token is revealed.</p>
<p>You can change the token by clicking the <strong>Change API Token</strong> button.</p> |
10,507,100 | What is ".el" in relationship to JavaScript/HTML/jQuery? | <p>I couldn't find much from Googling, but I'm probably Googling the wrong terms.</p>
<p>I'm trying to understand what the "el" in "$.el" is from here:
<a href="http://joestelmach.github.com/laconic/" rel="noreferrer">http://joestelmach.github.com/laconic/</a></p>
<pre><code>$.el.table(
$.el.tr(
$.el.th('first name'),
$.el.th('last name')),
$.el.tr(
$.el.td('Joe'),
$.el.td('Stelmach'))
).appendTo(document.body);
</code></pre>
<p>Thanks in advance!</p> | 10,507,133 | 4 | 0 | null | 2012-05-08 21:51:52.587 UTC | 3 | 2014-09-04 18:55:36.267 UTC | null | null | null | null | 1,207,596 | null | 1 | 18 | javascript|jquery|html | 59,600 | <p><code>el</code> is just an identifier and it refers to an element, a DOM element, which is a convention in that library.</p> |
10,418,929 | How to add a view programmatically to RelativeLayout? | <p>Can you give me a very simple example of adding child view programmatically to <code>RelativeLayout</code> at a given position?</p>
<p>For example, to reflect the following XML:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="107dp"
android:layout_marginTop="103dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</code></pre>
<p></p>
<p>I don't understand how to create an appropriate <code>RelativeLayout.LayoutParams</code> instance.</p> | 10,419,021 | 2 | 0 | null | 2012-05-02 17:41:10.963 UTC | 12 | 2019-01-22 08:39:53.647 UTC | 2019-01-22 08:39:53.647 UTC | null | 1,033,581 | null | 1,171,620 | null | 1 | 64 | android|android-layout|android-relativelayout | 89,222 | <p>Heres an example to get you started, fill in the rest as applicable:</p>
<pre><code>TextView tv = new TextView(mContext);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
params.leftMargin = 107
...
mRelativeLayout.addView(tv, params);
</code></pre>
<p>The docs for RelativeLayout.LayoutParams and the constructors are <a href="http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html#RelativeLayout.LayoutParams%28int,%20int%29">here</a></p> |
5,918,534 | Why can't I add a subfolder in a F# project? | <p>In most .NET project I can use folder to organise the code files. In C++, I can't, but filters end up playing the same role. However, in F# with Visual Studio 2010, I can't. Every code file is shown directly in the project dir. Why is this feature not available?</p>
<p>And what is the optimal strategy for organizing a project with a lot of files?</p> | 5,918,602 | 2 | 1 | null | 2011-05-07 01:20:57.833 UTC | 2 | 2013-01-30 15:37:06.177 UTC | null | null | null | null | 142,222 | null | 1 | 32 | visual-studio-2010|f# | 4,503 | <p>Actually, you can add folders to F# projects but it's not supported directly through Visual Studio (you have to edit the project file yourself): <a href="http://fsprojectextender.codeplex.com/" rel="nofollow noreferrer">http://fsprojectextender.codeplex.com/</a> (edit: old link was broken, updated to F# Project Extender home page which has links to the original blog posts which were moved) (which I found in <a href="https://stackoverflow.com/questions/5396465/how-to-organize-f-source-of-large-project-300-classes-in-visual-studio/5396636#5396636">this</a> answer).</p>
<p>I do this myself, but it is cumbersome and you end up avoiding it until keeping sanity really demands it. I think the feature simply slipped, or perhaps there wasn't as much a culture for folder organization with the F# designers in the first place. You can see in the F# source code that they favor huge source files with no directories, with separate projects as an organization boundary.</p>
<p>I imagine the F# project template could be modified to support this, and it is certainly something I'd like to see happen. At the same time the linear compilation order F# enforces causes your code to be somewhat self-organized, and so folder grouping plays a less significant role.</p> |
31,133,963 | Multiple models generic ListView to template | <p>What is the SIMPLEST method for getting 2 models to be listed in a generic IndexView? My two models are <code>CharacterSeries</code> and <code>CharacterUniverse</code>.</p>
<p>My views.py</p>
<pre><code> from .models import CharacterSeries, CharacterUniverse
class IndexView(generic.ListView):
template_name = 'character/index.html'
context_object_name = 'character_series_list'
def get_queryset(self):
return CharacterSeries.objects.order_by('name')
class IndexView(generic.ListView):
template_name = 'character/index.html'
context_object_name = 'character_universe_list'
def get_queryset(self):
return CharacterUniverse.objects.order_by('name')
</code></pre>
<p>I need to know the shortest and most elegant code. Looked a lot but don't want to use mixins. I am perhaps not being pointed in the right direction.</p>
<p>Thanks all.</p> | 31,134,299 | 2 | 0 | null | 2015-06-30 09:05:32.427 UTC | 9 | 2015-06-30 09:35:00.527 UTC | null | null | null | null | 1,064,843 | null | 1 | 12 | django|django-views | 20,097 | <p>You can pass the one queryset in as context on the ListView like this, </p>
<pre><code>class IndexView(generic.ListView):
template_name = 'character/index.html'
context_object_name = 'character_series_list'
model = CharacterSeries
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context.update({
'character_universe_list': CharacterUniverse.objects.order_by('name'),
'more_context': Model.objects.all(),
})
return context
def get_queryset(self):
return CharacterSeries.objects.order_by('name')
</code></pre> |
31,571,830 | pandas - histogram from two columns? | <p>I have this data:</p>
<pre><code>data = pd.DataFrame().from_dict([r for r in response])
print data
_id total
0 213 1
1 194 3
2 205 156
...
</code></pre>
<p>Now, if I call:</p>
<pre><code>data.hist()
</code></pre>
<p>I will get two separate histograms, one for each column. This is not what I want. What I want is a single histogram made using those two columns, where one column is interpreted as a value and another one as a number of occurrences of this value. What should I do to generate such a histogram?</p>
<p>I tried:</p>
<pre><code>data.hist(column="_id", by="total")
</code></pre>
<p>But this generates even more (empty) histograms with error message.</p> | 31,571,972 | 2 | 1 | null | 2015-07-22 19:02:29.983 UTC | null | 2015-07-22 19:19:53.33 UTC | null | null | null | null | 940,208 | null | 1 | 6 | python|pandas|plot|histogram | 48,608 | <p>You can always drop to the lower-level <a href="http://matplotlib.org/examples/pylab_examples/histogram_demo_extended.html" rel="noreferrer"><code>matplotlib.hist</code></a>:</p>
<pre><code>from matplotlib.pyplot import hist
df = pd.DataFrame({
'_id': np.random.randn(100),
'total': 100 * np.random.rand()
})
hist(df._id, weights=df.total)
</code></pre>
<p><a href="https://i.stack.imgur.com/jouSi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jouSi.png" alt="enter image description here"></a></p> |
32,767,044 | ng-class one time binding | <p>I'm wondering if it's possible to have a ng-class with class one time binded and class which are evaluated each digest cycle.</p>
<pre><code><div ng-class="{'one_time_binded_class': isMonkey(), 'not_one_time_binded_class': isUnicorn()}"></div>
</code></pre>
<p>I know I can one time bind the complete ng-class with <code>ng-class="::{...}"</code>
but my need is to one time bind a particular expression</p>
<p>Of course, this thing doesn't work :</p>
<pre><code><div ng-class="{'my_static_class': ::isMonkey(), 'my_dynamic_class': isUnicorn()}"></div>
</code></pre>
<p>Is there a way to do it ?</p> | 35,506,447 | 3 | 0 | null | 2015-09-24 17:01:26.48 UTC | 3 | 2018-02-16 11:49:00.96 UTC | 2018-02-16 11:49:00.96 UTC | null | 4,906,701 | null | 4,906,701 | null | 1 | 38 | angularjs|class | 8,891 | <p><strong>Method 1:</strong></p>
<pre><code>class="some-class {{::expression ? 'my-class' : ''}}"
</code></pre>
<p><strong>Method 2:</strong></p>
<pre><code>ng-class="::{'my-class': expression}"
</code></pre> |
20,922,835 | Appending an existing XML file with XmlWriter | <p>I've used the following code to create an XML file:</p>
<pre><code>XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.NewLineOnAttributes = true;
using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("School");
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Close();
}
</code></pre>
<p>I need to insert nodes dynamically creating the following structure:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<School />
<Student>
<FirstName>David</FirstName>
<LastName>Smith</LastName>
</Student>
...
<Teacher>
<FirstName>David</FirstName>
<LastName>Smith</LastName>
</Teacher>
...
</School>
</code></pre>
<p>How can I do it? The values of "FirstName" and "LastName" should be read from the keyboard and the values can be entered at any time, of course under existing.</p> | 20,924,835 | 5 | 1 | null | 2014-01-04 15:29:15.587 UTC | 3 | 2019-09-11 23:22:02.57 UTC | 2014-01-04 16:58:48.417 UTC | null | 3,105,160 | null | 3,105,160 | null | 1 | 9 | c#|xml|xmlreader|xmlwriter | 73,274 | <p>finally I succeeded :)</p>
<pre><code>if (!File.Exists("Test.xml"))
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
xmlWriterSettings.NewLineOnAttributes = true;
using (XmlWriter xmlWriter = XmlWriter.Create("Test.xml", xmlWriterSettings))
{
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("School");
xmlWriter.WriteStartElement("Student");
xmlWriter.WriteElementString("FirstName", firstName);
xmlWriter.WriteElementString("LastName", lastName);
xmlWriter.WriteEndElement();
xmlWriter.WriteEndElement();
xmlWriter.WriteEndDocument();
xmlWriter.Flush();
xmlWriter.Close();
}
}
else
{
XDocument xDocument = XDocument.Load("Test.xml");
XElement root= xDocument.Element("School");
IEnumerable<XElement> rows = root.Descendants("Student");
XElement firstRow= rows.First();
firstRow.AddBeforeSelf(
new XElement("Student",
new XElement("FirstName", firstName),
new XElement("LastName", lastName)));
xDocument.Save("Test.xml");
}
</code></pre> |
21,131,015 | How to send a String array as basic name value pair as HTTPPOST? | <p>I want to send a array as name value pair as httppost.My server accepts only array values.The following is my code snippet..</p>
<pre><code>public String SearchWithType(String category_name, String[] type,int page_no) {
String url = "http://myURL";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String auth_token = Login.authentication_token;
String key = Login.key;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("authentication_token",
auth_token));
nameValuePairs.add(new BasicNameValuePair("key", key));
nameValuePairs.add(new BasicNameValuePair("category_name",
category_name));
int i = 0;
nameValuePairs.add(new BasicNameValuePair("type", type[i]));
nameValuePairs.add(new BasicNameValuePair("page", String.valueOf(page_no)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
eu = EntityUtils.toString(entity).toString();
} catch (IOException ioe) {
String ex = ioe.toString();
return ex;
}
return eu;
}
</code></pre> | 21,154,349 | 4 | 1 | null | 2014-01-15 07:02:41.13 UTC | 5 | 2017-05-11 11:10:41.643 UTC | 2014-04-16 19:05:46.63 UTC | null | 2,753,340 | null | 2,753,340 | null | 1 | 14 | java|android|json|http | 41,338 | <p>I got the issue. Here's how:</p>
<pre><code>try {
int i = 0;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("authentication_token", auth_token));
nameValuePairs.add(new BasicNameValuePair("key", key));
nameValuePairs.add(new BasicNameValuePair("category_name", category_name));
nameValuePairs.add(new BasicNameValuePair("type", type[i]));
nameValuePairs.add(new BasicNameValuePair("page", String.valueOf(page_no)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
eu = EntityUtils.toString(entity).toString();
} catch (Exception e) {
Log.e(TAG, e.toString());
}
</code></pre>
<p>All I had to do was initialize a loop:</p>
<pre><code>for (int i = 0; i < type.length; i++) {
nameValuePairs.add(new BasicNameValuePair("type[]",type[i]));
}
</code></pre> |
19,274,295 | How to select from SQL table WHERE a TIMESTAMP is a specific Date | <p>Im trying to do a query where a TIMESTAMP field is = to a specific date but my query is not working:</p>
<p>The field is type TIMESTAMP(6) which I have only ever worked with DATE / DATETIME fields before. Here is example of a value stored here: <strong>04-OCT-13 12.29.53.000000000 PM</strong></p>
<p>Here is my SELECT statement: </p>
<pre><code>SELECT * FROM SomeTable WHERE timestampField = TO_DATE('2013-10-04','yyyy-mm-dd')
</code></pre>
<p>I am retrieving no results and I am assuming it has to do with the fact that its not matching the TIME portion of the timestamp</p> | 19,274,543 | 1 | 0 | null | 2013-10-09 14:02:49.19 UTC | 3 | 2015-09-10 00:52:10.157 UTC | null | null | null | null | 1,342,249 | null | 1 | 4 | sql|oracle|select|timestamp|where-clause | 44,685 | <p>If you want every record that occurs on a given day then this should work:</p>
<pre><code>SELECT * FROM SomeTable
WHERE timestampField >= TO_TIMESTAMP( '2013-03-04', 'yyyy-mm-dd' )
AND timestampField < TO_TIMESTAMP( '2013-03-05', 'yyyy-mm-dd')
</code></pre>
<p>That will be likely to take advantage of an index on <code>timestampField</code> if it exists. Another way would be:</p>
<pre><code>SELECT * FROM SomeTable
WHERE TRUNC(timestampField) = TO_DATE( '2013-03-04', 'yyyy-mm-dd' )
</code></pre>
<p>in which case you may want a function-based index on <code>TRUNC(timestampField)</code>.</p>
<p>(Note that TRUNC applied to a TIMESTAMP returns a DATE.)</p> |
19,068,308 | Access Django models with scrapy: defining path to Django project | <p>I'm very new to Python and Django. I'm currently exploring using Scrapy to scrape sites and save data to the Django database. My goal is to run a spider based on domain given by a user. </p>
<p>I've written a spider that extracts the data I need and store it correctly in a json file when calling </p>
<pre><code>scrapy crawl spider -o items.json -t json
</code></pre>
<p>As described in the <a href="http://doc.scrapy.org/en/latest/intro/tutorial.html" rel="noreferrer">scrapy tutorial</a>.</p>
<p>My goal is now to get the spider to succesfully to save data to the Django database, and then work on getting the spider to run based on user input. </p>
<p>I'm aware that various posts exists on this subject, such as these:
<a href="https://stackoverflow.com/questions/4271975/access-django-models-inside-of-scrapy">link 1</a>
<a href="https://stackoverflow.com/questions/7883196/saving-django-model-from-scrapy-project">link 2</a>
<a href="https://stackoverflow.com/questions/4271975/access-django-models-inside-of-scrapy">link 3</a></p>
<p>But having spend more than 8 hours on trying to get this to work, I'm assuming i'm not the only one still facing issues with this. I'll therefor try and gather all the knowledge i've gotten so far in this post, as well a hopefully posting a working solution at a later point. Because of this, this post is rather long. </p>
<p>It appears to me that there is two different solutions to saving data to the Django database from Scrapy. One is to use <a href="https://scrapy.readthedocs.org/en/latest/topics/djangoitem.html" rel="noreferrer">DjangoItem</a>, another is to to import the models directly(as done <a href="https://stackoverflow.com/questions/7883196/saving-django-model-from-scrapy-project">here</a>).</p>
<p>I'm not completely aware of the advantages and disadvantages of these two, but it seems like the difference is simply the using DjangoItem is just more convenient and shorter.</p>
<p><strong>What i've done:</strong> </p>
<p>I've added:</p>
<pre><code>def setup_django_env(path):
import imp, os
from django.core.management import setup_environ
f, filename, desc = imp.find_module('settings', [path])
project = imp.load_module('settings', f, filename, desc)
setup_environ(project)
setup_django_env('/Users/Anders/DjangoTraining/wsgi/')
</code></pre>
<p><strong>Error i'm getting is:</strong></p>
<pre><code>ImportError: No module named settings
</code></pre>
<p>I'm thinking i'm defining the path to my Django project in a wrong way?</p>
<p>I've also tried the following:</p>
<pre><code>setup_django_env('../../')
</code></pre>
<p>How do I define the path to my Django project correctly? (if that is the issue)</p> | 19,073,347 | 2 | 0 | null | 2013-09-28 15:02:34.353 UTC | 24 | 2016-12-21 20:09:37.307 UTC | 2017-05-23 10:31:30.497 UTC | null | -1 | null | 1,474,170 | null | 1 | 35 | python|django|django-models|scrapy | 11,223 | <p>I think the main misconception is the package path vs the settings module path. In order to use django's models from an external script you need to set the <code>DJANGO_SETTINGS_MODULE</code>. Then, this module has to be <em>importable</em> (i.e. if the settings path is <code>myproject.settings</code>, then the statement <code>from myproject import settings</code> should work in a python shell).</p>
<p>As most projects in django are created in a path outside the default <code>PYTHONPATH</code>, you must add the project's path to the <code>PYTHONPATH</code> environment variable.</p>
<p>Here is a step-by-step guide to create a fully working (and minimal) Django models integration into a Scrapy project:</p>
<p><strong>Note:</strong> This instructions work at the date of the last edit. If it doesn't work for you, please add a comment and describe your issue and scrapy/django versions.</p>
<ol>
<li><p>The projects will be created within <code>/home/rolando/projects</code> directory.</p></li>
<li><p>Start the <strong>django project</strong>.</p>
<pre><code>$ cd ~/projects
$ django-admin startproject myweb
$ cd myweb
$ ./manage.py startapp myapp
</code></pre></li>
<li><p>Create a model in <code>myapp/models.py</code>.</p>
<pre><code>from django.db import models
class Person(models.Model):
name = models.CharField(max_length=32)
</code></pre></li>
<li><p>Add <code>myapp</code> to <code>INSTALLED_APPS</code> in <code>myweb/settings.py</code>.</p>
<pre><code># at the end of settings.py
INSTALLED_APPS += ('myapp',)
</code></pre></li>
<li><p>Set my db settings in <code>myweb/settings.py</code>.</p>
<pre><code># at the end of settings.py
DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
DATABASES['default']['NAME'] = '/tmp/myweb.db'
</code></pre></li>
<li><p>Create the database.</p>
<pre><code>$ ./manage.py syncdb --noinput
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
</code></pre></li>
<li><p>Create the <strong>scrapy project</strong>.</p>
<pre><code>$ cd ~/projects
$ scrapy startproject mybot
$ cd mybot
</code></pre></li>
<li><p>Create an item in <code>mybot/items.py</code>.</p></li>
</ol>
<p><strong>Note:</strong> In newer versions of Scrapy, you need to install <code>scrapy_djangoitem</code> and use <code>from scrapy_djangoitem import DjangoItem</code>.</p>
<pre><code> from scrapy.contrib.djangoitem import DjangoItem
from scrapy.item import Field
from myapp.models import Person
class PersonItem(DjangoItem):
# fields for this item are automatically created from the django model
django_model = Person
</code></pre>
<p>The final directory structure is this:</p>
<pre><code>/home/rolando/projects
├── mybot
│ ├── mybot
│ │ ├── __init__.py
│ │ ├── items.py
│ │ ├── pipelines.py
│ │ ├── settings.py
│ │ └── spiders
│ │ └── __init__.py
│ └── scrapy.cfg
└── myweb
├── manage.py
├── myapp
│ ├── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── myweb
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
</code></pre>
<p>From here, basically we are done with the code required to use the django models in a scrapy project. We can test it right away using <code>scrapy shell</code> command but be aware of the required environment variables:</p>
<pre><code>$ cd ~/projects/mybot
$ PYTHONPATH=~/projects/myweb DJANGO_SETTINGS_MODULE=myweb.settings scrapy shell
# ... scrapy banner, debug messages, python banner, etc.
In [1]: from mybot.items import PersonItem
In [2]: i = PersonItem(name='rolando')
In [3]: i.save()
Out[3]: <Person: Person object>
In [4]: PersonItem.django_model.objects.get(name='rolando')
Out[4]: <Person: Person object>
</code></pre>
<p>So, it is working as intended.</p>
<p>Finally, you might not want to have to set the environment variables each time you run your bot. There are many alternatives to address this issue, although the best it is that the projects' packages are actually installed in a path set in <code>PYTHONPATH</code>.</p>
<p>This is one of the simplest solutions: add this lines to your <code>mybot/settings.py</code> file to set up the environment variables.</p>
<pre><code># Setting up django's project full path.
import sys
sys.path.insert(0, '/home/rolando/projects/myweb')
# Setting up django's settings module name.
# This module is located at /home/rolando/projects/myweb/myweb/settings.py.
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'myweb.settings'
# Since Django 1.7, setup() call is required to populate the apps registry.
import django; django.setup()
</code></pre>
<p><strong>Note:</strong> A better approach to the path hacking is to have <code>setuptools</code>-based <code>setup.py</code> files in both projects and run <code>python setup.py develop</code> which will link your project path into the python's path (I'm assuming you use <code>virtualenv</code>).</p>
<p>That is enough. For completeness, here is a basic spider and pipeline for a fully working project:</p>
<ol>
<li><p>Create the spider.</p>
<pre><code>$ cd ~/projects/mybot
$ scrapy genspider -t basic example example.com
</code></pre>
<p>The spider code:</p>
<pre><code># file: mybot/spiders/example.py
from scrapy.spider import BaseSpider
from mybot.items import PersonItem
class ExampleSpider(BaseSpider):
name = "example"
allowed_domains = ["example.com"]
start_urls = ['http://www.example.com/']
def parse(self, response):
# do stuff
return PersonItem(name='rolando')
</code></pre></li>
<li><p>Create a pipeline in <code>mybot/pipelines.py</code> to save the item.</p>
<pre><code>class MybotPipeline(object):
def process_item(self, item, spider):
item.save()
return item
</code></pre>
<p>Here you can either use <code>item.save()</code> if you are using the <code>DjangoItem</code> class or import the django model directly and create the object manually. In both ways the main issue is to define the environment variables so you can use the django models.</p></li>
<li><p>Add the pipeline setting to your <code>mybot/settings.py</code> file.</p>
<pre><code>ITEM_PIPELINES = {
'mybot.pipelines.MybotPipeline': 1000,
}
</code></pre></li>
<li><p>Run the spider.</p>
<pre><code>$ scrapy crawl example
</code></pre></li>
</ol> |
25,759,046 | iPhone 6 and 6 Plus Media Queries | <p>Does anyone know specific screen sizes to target media queries for iPhone 6 and 6 Plus?</p>
<p>Also, the icon sizes and splash screens?</p> | 25,759,240 | 7 | 0 | null | 2014-09-10 06:52:44.037 UTC | 69 | 2018-02-26 06:47:07.997 UTC | 2017-09-13 13:24:31.163 UTC | null | 1,000,551 | null | 3,262,475 | null | 1 | 73 | ios|css|media-queries|iphone-6|iphone-6-plus | 204,459 | <h1>iPhone 6</h1>
<ul>
<li><p>Landscape</p>
<pre><code>@media only screen
and (min-device-width : 375px) // or 213.4375em or 3in or 9cm
and (max-device-width : 667px) // or 41.6875em
and (width : 667px) // or 41.6875em
and (height : 375px) // or 23.4375em
and (orientation : landscape)
and (color : 8)
and (device-aspect-ratio : 375/667)
and (aspect-ratio : 667/375)
and (device-pixel-ratio : 2)
and (-webkit-min-device-pixel-ratio : 2)
{ }
</code></pre></li>
<li><p>Portrait</p>
<pre><code>@media only screen
and (min-device-width : 375px) // or 213.4375em
and (max-device-width : 667px) // or 41.6875em
and (width : 375px) // or 23.4375em
and (height : 559px) // or 34.9375em
and (orientation : portrait)
and (color : 8)
and (device-aspect-ratio : 375/667)
and (aspect-ratio : 375/559)
and (device-pixel-ratio : 2)
and (-webkit-min-device-pixel-ratio : 2)
{ }
</code></pre>
<p><em>if you prefer you can use <code>(device-width : 375px)</code> and <code>(device-height: 559px)</code> in place of the <code>min-</code> and <code>max-</code> settings.</em></p>
<p><em>It is not necessary to use all of these settings, and these are not all the possible settings. These are just the majority of possible options so you can pick and choose whichever ones meet your needs.</em></p></li>
<li><p>User Agent</p>
<p><em>tested with my iPhone 6 (model MG6G2LL/A) with iOS 9.0 (13A4305g)</em></p>
<pre><code># Safari
Mozilla/5.0 (iPhone; CPU iPhone OS 9_0 like Mac OS X) AppleWebKit/601.1.39 (KHTML, like Gecko) Version/9.0 Mobile/13A4305g Safari 601.1
# Google Chrome
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.53.11 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10 (000102)
# Mercury
Mozilla/5.0 (iPhone; CPU iPhone OS 7_0_4 like Mac OS X) AppleWebKit/537.51.1 (KHTML, like Gecko) Version/7.0 Mobile/11B554a Safari/9537.53
</code></pre></li>
<li><p>Launch images</p>
<ul>
<li>750 x 1334 (@2x) for portrait</li>
<li>1334 x 750 (@2x) for landscape</li>
</ul></li>
<li><p>App icon</p>
<ul>
<li>120 x 120</li>
</ul></li>
</ul>
<hr>
<h3>iPhone 6+</h3>
<ul>
<li><p>Landscape</p>
<pre><code>@media only screen
and (min-device-width : 414px)
and (max-device-width : 736px)
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio : 3)
{ }
</code></pre></li>
<li><p>Portrait</p>
<pre><code>@media only screen
and (min-device-width : 414px)
and (max-device-width : 736px)
and (device-width : 414px)
and (device-height : 736px)
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio : 3)
and (-webkit-device-pixel-ratio : 3)
{ }
</code></pre></li>
<li><p>Launch images</p>
<ul>
<li>1242 x 2208 (@3x) for portrait</li>
<li>2208 x 1242 (@3x) for landscape</li>
</ul></li>
<li><p>App icon</p>
<ul>
<li>180 x 180</li>
</ul></li>
</ul>
<hr>
<h3>iPhone 6 and 6+</h3>
<pre><code>@media only screen
and (max-device-width: 640px),
only screen and (max-device-width: 667px),
only screen and (max-width: 480px)
{ }
</code></pre>
<hr>
<h2>Predicted</h2>
<p>According to <a href="http://www.apple.com/iphone-6/display/">the Apple website</a> the iPhone 6 Plus will have 401 pixels-per-inch and be 1920 x 1080. The smaller version of the iPhone 6 will be 1334 x 750 with 326 PPI.</p>
<p>So, assuming that information is correct, we can write a media query for the iPhone 6:</p>
<pre class="lang-css prettyprint-override"><code>@media screen
and (min-device-width : 1080px)
and (max-device-width : 1920px)
and (min-resolution: 401dpi)
and (device-aspect-ratio:16/9)
{ }
@media screen
and (min-device-width : 750px)
and (max-device-width : 1334px)
and (min-resolution: 326dpi)
{ }
</code></pre>
<p>Note that <a href="/questions/tagged/device-aspect-ratio" class="post-tag" title="show questions tagged 'device-aspect-ratio'" rel="tag">device-aspect-ratio</a> will be deprecated in <a href="http://dev.w3.org/csswg/mediaqueries-4/">http://dev.w3.org/csswg/mediaqueries-4/</a> and replaced with <a href="/questions/tagged/aspect-ratio" class="post-tag" title="show questions tagged 'aspect-ratio'" rel="tag">aspect-ratio</a></p>
<p>Min-width and max-width may be something like 1704 x 960.</p>
<hr>
<h2>Apple Watch (speculative)</h2>
<p>Specs on the Watch are still a bit speculative since (as far as I'm aware) there has been no official spec sheet yet. But Apple did mention in <a href="http://www.apple.com/pr/library/2014/09/09Apple-Unveils-Apple-Watch-Apples-Most-Personal-Device-Ever.html">this press release</a> that the Watch will be available in two sizes.. 38mm and 42mm.</p>
<p>Further assuming.. that those sizes refer to the screen size rather than the overall size of the Watch face these media queries should work.. And I'm sure you could give or take a few millimeters to cover either scenario without sacrificing any unwanted targeting because.. </p>
<pre><code>@media (!small) and (damn-small), (omfg) { }
</code></pre>
<p>or</p>
<pre><code>@media
(max-device-width:42mm)
and (min-device-width:38mm)
{ }
</code></pre>
<p>It's worth noting that <a href="http://www.w3.org/TR/mediaqueries-4/">Media Queries Level 4</a> from W3C currently only available as a first public draft, once available for use will bring with it a lot of new features designed with smaller wearable devices like this in mind.</p> |
8,817,130 | Java : The import collides with another import statement | <p>I have imported an Existing Java Application into my Workspace .
I see that , a class with same name is present in different packages with in the Application.</p>
<p>For example a class named "Status.java" is present with in </p>
<pre><code>com.tata.model.common.Status;
com.bayer.frontlayer.dao.Status;
</code></pre>
<p>When I tried to use both of them within a class, for example as shown below </p>
<pre><code>import com.tata.model.common.Status;
import com.bayer.frontlayer.dao.Status;
public class Adapter
{
}
</code></pre>
<p>It started giving an error in Eclipse stating </p>
<blockquote>
<p>The <strong>import com.bayer.frontlayer.dao.Status</strong> collides with another import statement</p>
</blockquote>
<p>Is there anyway to solve this without changing the name of the classes??</p>
<p>Thank you.</p> | 8,817,158 | 3 | 0 | null | 2012-01-11 09:44:46.853 UTC | 8 | 2016-12-29 08:56:34.823 UTC | 2016-09-01 19:37:20.44 UTC | null | 4,325,010 | user663724 | null | null | 1 | 28 | java|import|importerror | 46,395 | <p>You can use them explicitly without importing them, so the included package name differentiates between the two:</p>
<pre><code> //No imports required!
public class Adapter
{
private com.tata.model.common.Status x;
private com.bayer.frontlayer.dao.Status y;
}
</code></pre> |
43,724,011 | Gist Vs. Repository for Tutorial | <p>I'm publishing a tutorial that includes a lot of code interspersed with documentation. I'm considering two ways of hosting the code:</p>
<ol>
<li>Separate git repository with code files and markdown files explaining the code </li>
<li>Github gist containing both of these</li>
</ol>
<p>Are there advantages of hosting in a gist v/s a repository? When would one prefer one of these over the other?</p> | 43,724,121 | 2 | 0 | null | 2017-05-01 18:05:17.323 UTC | 8 | 2022-02-06 18:37:05.477 UTC | 2017-05-01 18:23:19.993 UTC | null | 759,019 | null | 4,227,408 | null | 1 | 36 | github|gist | 10,903 | <p>Gist is a simple way to share snippets and pastes with others.
Whereas Repo is simply a place where the history of your work is stored.</p>
<p>There is no good answer, it's personal preference. I make mine a conceptual distinction. If it's code designed to demonstrate a technique, teach a principle, or show off a solution it goes in a gist. Doesn't matter if it's one file or 30 files. If it's actual code intended to be run, used as is, or forked as boilerplate I put it in a proper repository.</p> |
462,458 | ASP.NET MVC Areas: Are they important to a large application? | <p>I am in the process of developing a large ASP.NET MVC application. I am currently working through the mechanisms I'll use to structure my controllers/views. I have see some mention of monorail and it's use of "areas". I have reviewed <a href="http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx" rel="noreferrer">Haacked's</a> article and it looks like an intresting option. What I would like to know is whether or not anyone has implemented areas in a produciton ASP.NET MVC application and if they have are there any online resources that might help implement the areas and justify their existence.</p> | 463,315 | 3 | 1 | null | 2009-01-20 18:23:38.283 UTC | 10 | 2009-01-22 23:10:16.317 UTC | null | null | null | JPrescottSanders | 19,444 | null | 1 | 30 | asp.net-mvc | 16,705 | <p>Me and my team are currently developing a very large application using the ASP.NET MVC framework as the underlying technology. We are using <a href="http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx" rel="noreferrer">Areas</a>, <a href="http://oddiandeveloper.blogspot.com/2008/11/strongly-typed-view-names.html" rel="noreferrer">Strongly Typed View Names</a> and our own version of <a href="http://oddiandeveloper.blogspot.com/2008/11/localization-with-aspnet-mvc.html" rel="noreferrer">Localisation</a>. So far it is working together very well.</p>
<p>The deal breaker with ASP.NET MVC for me was going to be that the controller names had to be unique. It was perfectly foreseeable to require a controller for managing stock within inventory and dispatching areas of my application and sorting these was going to be too hard. With areas this is no longer a problem. I would highly recommend using them as Phil Haack has outlined.</p>
<p>Alternatively you could look at <a href="http://blog.codeville.net/2008/11/05/app-areas-in-aspnet-mvc-take-2/" rel="noreferrer">Steven Sanderson's implementation</a> where he has taken it a little further, though for us it was not something we needed.</p>
<p>I wouldn't be surprised to see Areas implemented into ASP.NET MVC very soon.</p>
<p>Good luck with your application, I don't think you'll regret choosing ASP.NET MVC.</p> |
1,240,034 | how can I create a file with file_put_contents that has group write permissions? | <p>I am using <code>file_put_contents</code> to create a file. My php process is running in a group with permissions to write to the directory. When <code>file_put_contents</code> is called, however, the resulting file does not have group write permissions (it creates just fine the first time). This means that if I try to overwrite the file it fails because of a lack of permissions.</p>
<p>Is there a way to create the file with group write permissions? </p> | 1,240,063 | 3 | 0 | null | 2009-08-06 16:26:19.117 UTC | 2 | 2009-08-06 18:59:04.113 UTC | null | null | null | null | 105,678 | null | 1 | 31 | php|linux|nginx | 50,660 | <p>You might what to try setting the <a href="http://php.net/umask" rel="noreferrer"><code>umask</code></a> before calling <code>file_put_contents</code> : it will change the default permissions that will be given to the file when it's created.</p>
<p>The other way (better, according to the documentation) is to use <a href="http://php.net/chmod" rel="noreferrer"><code>chmod</code></a> to change the permissions, just after the file has been created.</p>
<p><br>
<em>Well, after re-reading the question, I hope I understood it well...</em></p> |
6,668,271 | Get Cell Tower Locations - Android | <p>Does anyone know if it is possible to get information about all of the cell towers in range of a device? Just be able to get the location of them or maybe any other information about them and how I would go about doing it? </p> | 6,668,444 | 1 | 4 | null | 2011-07-12 17:17:38.953 UTC | 13 | 2011-07-12 17:39:10.737 UTC | null | null | null | null | 573,595 | null | 1 | 13 | java|android|location | 23,830 | <p>This is how you get the cell tower id (CID) and the lac (Location Area Code) from your current network state: </p>
<pre><code>mPhoneStateReceiver = new PhoneStateIntentReceiver(this, new ServiceStateHandler());
mPhoneStateReceiver.notifyServiceState(MY_NOTIFICATION_ID);
mPhoneStateReceiver.notifyPhoneCallState(MY_NOTIFICATION_ID);
mPhoneStateReceiver.notifySignalStrength(MY_NOTIFICATION_ID);
mPhoneStateReceiver.registerIntent();
private class ServiceStateHandler extends Handler {
public void handleMessage(Message msg) {
switch (msg.what) {
case MY_NOTIFICATION_ID:
ServiceState state = mPhoneStateReceiver.getServiceState();
System.out.println(state.getCid());
System.out.println(state.getLac());
System.out.println(mPhoneStateReceiver.getSignalStrength());
break;
}
}
}
</code></pre>
<p>Getting Lat,Lng location information after that is a little trickier. Here's a link to a post that's about Symbian but talks about Cell Tower -> Lat,Lng conversion: <a href="http://discussion.forum.nokia.com/forum/showthread.php?s=&threadid=19693" rel="noreferrer">http://discussion.forum.nokia.com/forum/showthread.php?s=&threadid=19693</a></p> |
28,802,243 | How can I redirect to another view-model in Aurelia JS? | <p>I'm writing an application using <a href="http://aurelia.io/">Aurelia JS</a>. How can I redirect to another URL? Is there a way to do it without creating a whole new <a href="http://aurelia.io/docs.html#customizing-the-navigation-pipeline">navigation pipeline step</a>?</p>
<p>Thanks</p> | 28,802,383 | 4 | 2 | null | 2015-03-02 03:26:44.167 UTC | 2 | 2018-04-16 16:04:34.58 UTC | null | null | null | null | 551,904 | null | 1 | 38 | aurelia | 18,222 | <p>to do that inject the router in the ViewModel and use the method <a href="https://github.com/aurelia/router/blob/master/src/router.js#L69" rel="noreferrer">navigate(route) </a></p>
<p>here is an example:</p>
<pre><code>import {Router} from 'aurelia-router';
export class MyVM {
static inject() { return [Router]; }
constructor(router){
this.router = router;
}
someMethod(){
this.router.navigate("myroute");
}
}
</code></pre> |
20,707,921 | How to get twitter bootstrap toggle switch values using jquery | <p>I am using <a href="http://bootstrapswitch.site/" rel="nofollow noreferrer">http://bootstrapswitch.site/</a> for toggle switch buttons. How can I get the toggle switch like 'on' or 'off' using jQuery?</p>
<p>My Code is :</p>
<pre><code><div class="make-switch switch-small"><input type="radio" class="nsfw"></div>
</code></pre>
<p>Please tell me how to solve this issue.</p> | 20,707,969 | 4 | 0 | null | 2013-12-20 16:28:06.737 UTC | 11 | 2020-10-21 03:52:53.513 UTC | 2018-09-07 01:23:52.97 UTC | null | 684,617 | null | 1,774,312 | null | 1 | 25 | jquery|twitter-bootstrap | 54,178 | <pre><code>$('#switcher').bootstrapSwitch('state'); // true || false
$('#switcher').bootstrapSwitch('toggleState');
</code></pre>
<p>Refer <a href="http://bootstrapswitch.site/documentation-2.html" rel="noreferrer">this link</a> for more functions</p> |
6,085,568 | Fluent nhibernate one to one mapping | <p>How do I make a one to one mapping.</p>
<pre class="lang-cs prettyprint-override"><code>public class Setting
{
public virtual Guid StudentId { get; set; }
public virtual DateFilters TaskFilterOption { get; set; }
public virtual string TimeZoneId { get; set; }
public virtual string TimeZoneName { get; set; }
public virtual DateTime EndOfTerm { get; set; }
public virtual Student Student { get; set; }
}
</code></pre>
<p>Setting Class map:</p>
<pre class="lang-cs prettyprint-override"><code>public SettingMap()
{
// Id(Reveal.Member<Setting>("StudentId")).GeneratedBy.Foreign("StudentId");
//Id(x => x.StudentId);
Map(x => x.TaskFilterOption)
.Default(DateFilters.All.ToString())
.NvarcharWithMaxSize()
.Not.Nullable();
Map(x => x.TimeZoneId)
.NvarcharWithMaxSize()
.Not.Nullable();
Map(x => x.TimeZoneName)
.NvarcharWithMaxSize()
.Not.Nullable();
Map(x => x.EndOfTerm)
.Default("5/21/2011")
.Not.Nullable();
HasOne(x => x.Student);
}
</code></pre>
<hr />
<p>Student Class map</p>
<pre class="lang-cs prettyprint-override"><code>public class StudentMap: ClassMap<Student>
{
public StudentMap()
{
Id(x => x.StudentId);
HasOne(x => x.Setting)
.Cascade.All();
}
}
public class Student
{
public virtual Guid StudentId { get; private set; }
public virtual Setting Setting { get; set; }
}
</code></pre>
<hr />
<p>Now every time I try to create a settings object and save it to the database it crashes.</p>
<pre class="lang-cs prettyprint-override"><code>Setting setting = new Setting
{
TimeZoneId = viewModel.SelectedTimeZone,
TimeZoneName = info.DisplayName,
EndOfTerm = DateTime.UtcNow.AddDays(-1),
Student = student
};
</code></pre>
<blockquote>
<p>The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Settings_Students". The conflict occurred in database "Database", table "dbo.Students", column 'StudentId'.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p>
</blockquote>
<blockquote>
<p>Exception Details: System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Settings_Students". The conflict occurred in database "Database", table "dbo.Students", column 'StudentId'.
The statement has been terminated.</p>
</blockquote>
<p>What am I missing?</p>
<p><strong>Edit</strong></p>
<pre class="lang-cs prettyprint-override"><code>public class StudentMap: ClassMap<Student>
{
public StudentMap()
{
Id(x => x.StudentId)
.GeneratedBy.Guid();
HasOne(x => x.Setting)
.PropertyRef("Student")
.Cascade.All();
}
}
public class SettingMap: ClassMap<Setting>
{
public SettingMap()
{
Id(x => x.StudentId)
.GeneratedBy.Guid();
Map(x => x.TaskFilterOption)
.Default(DateFilters.All.ToString())
.NvarcharWithMaxSize().Not.Nullable();
Map(x => x.TimeZoneId)
.NvarcharWithMaxSize().Not.Nullable();
Map(x => x.TimeZoneName)
.NvarcharWithMaxSize().Not.Nullable();
Map(x => x.EndOfTerm)
.Default("5/21/2011").Not.Nullable();
References(x => x.Student).Unique();
}
}
</code></pre>
<hr />
<pre class="lang-cs prettyprint-override"><code>Setting setting = new Setting
{
TimeZoneId = viewModel.SelectedTimeZone,
TimeZoneName = info.DisplayName,
EndOfTerm = DateTime.UtcNow.AddDays(-1),
Student = student
};
studentRepo.SaveSettings(setting);
studentRepo.Commit();
</code></pre>
<p>I get these error for both ways</p>
<blockquote>
<p>Invalid index 5 for this SqlParameterCollection with Count=5. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p>
</blockquote>
<blockquote>
<p>Exception Details: System.IndexOutOfRangeException: Invalid index 5 for this SqlParameterCollection with Count=5. Source Error: Line 76: using (ITransaction transaction = session.BeginTransaction()) Line 77: { Line 78: transaction.Commit(); Line 79: } Line 80: }</p>
</blockquote> | 6,087,236 | 4 | 0 | null | 2011-05-22 01:57:05.847 UTC | 13 | 2022-03-21 17:26:48.257 UTC | 2022-03-21 17:26:48.257 UTC | null | 1,663,001 | null | 130,015 | null | 1 | 28 | c#|nhibernate|fluent-nhibernate | 27,799 | <p>There are two basic ways how to map bidirectional one-to-one association in NH. Let's say the classes look like this:</p>
<pre><code>public class Setting
{
public virtual Guid Id { get; set; }
public virtual Student Student { get; set; }
}
public class Student
{
public virtual Guid Id { get; set; }
public virtual Setting Setting { get; set; }
}
</code></pre>
<p>Setting class is a master in the association ("aggregate root"). It is quite unusual but it depends on problem domain...</p>
<p><strong>Primary key association</strong></p>
<pre><code>public SettingMap()
{
Id(x => x.Id).GeneratedBy.Guid();
HasOne(x => x.Student).Cascade.All();
}
public StudentMap()
{
Id(x => x.Id).GeneratedBy.Foreign("Setting");
HasOne(x => x.Setting).Constrained();
}
</code></pre>
<p>and a new setting instance should be stored:</p>
<pre><code> var setting = new Setting();
setting.Student = new Student();
setting.Student.Name = "student1";
setting.Student.Setting = setting;
setting.Name = "setting1";
session.Save(setting);
</code></pre>
<p><strong>Foreign key association</strong></p>
<pre><code>public SettingMap()
{
Id(x => x.Id).GeneratedBy.Guid();
References(x => x.Student).Unique().Cascade.All();
}
public StudentMap()
{
Id(x => x.Id).GeneratedBy.Guid();
HasOne(x => x.Setting).Cascade.All().PropertyRef("Student");
}
</code></pre>
<p>Primary key association is close to your solution. Primary key association should be used only when you are absolutely sure that the association will be always one-to-one. Note that AllDeleteOrphan cascade is not supported for one-to-one in NH.</p>
<p>EDIT: For more details see:</p>
<p><a href="http://fabiomaulo.blogspot.com/2010/03/conform-mapping-one-to-one.html" rel="noreferrer">http://fabiomaulo.blogspot.com/2010/03/conform-mapping-one-to-one.html</a></p>
<p><a href="http://ayende.com/blog/3960/nhibernate-mapping-one-to-one" rel="noreferrer">http://ayende.com/blog/3960/nhibernate-mapping-one-to-one</a></p> |
5,674,518 | Does BroadcastReceiver.onReceive always run in the UI thread? | <p>In my App, I create a custom <code>BroadcastReceiver</code> and register it to my Context manually via <code>Context.registerReceiver</code>. I also have an <code>AsyncTask</code> that dispatches notifier-Intents via <code>Context.sendBroadcast</code>. The intents are sent from a non-UI worker thread, but it seems that <code>BroadcastReceiver.onReceive</code> (which receives said Intents) always runs in the UI thread (which is good for me). Is this guaranteed or should I not rely on that?</p> | 5,676,888 | 4 | 0 | null | 2011-04-15 09:00:27.827 UTC | 34 | 2020-01-16 14:20:24.24 UTC | 2020-01-16 14:20:24.24 UTC | null | 1,000,551 | null | 379,767 | null | 1 | 124 | android|broadcastreceiver | 55,747 | <blockquote>
<p>Does BroadcastReceiver.onReceive always run in the UI thread?</p>
</blockquote>
<p>Yes.</p> |
2,122,167 | What's the default size for the UIImage in a UITableViewCell? | <p>I want to put a UIImage in the left side of each row in a UITableView. This is pretty standard, and is supported directly by UIKit. But putting in a (large) image causes all kinds of wonkiness, so presumably I'm supposed to scale the thing correctly myself. But none of the docs give a default size for this image using the standard out of the box views-- I'm surprised.</p>
<p>Others on SO indicate that 44 is the default height of a row (<a href="https://stackoverflow.com/questions/594852/what-is-the-default-height-of-uitableviewcell">What is the default height of UITableViewCell?</a>) Is 44x44 the "default" image size?</p>
<p>Thanks!</p> | 2,122,183 | 2 | 0 | null | 2010-01-23 04:47:48.257 UTC | 8 | 2016-10-06 06:28:19.57 UTC | 2017-05-23 12:26:29.837 UTC | null | -1 | null | 73,297 | null | 1 | 45 | iphone|uitableview|uiimage | 34,571 | <p>40x40</p>
<p><a href="https://stackoverflow.com/questions/1055495/uitableviewcells-imageview-fit-to-40x40">UITableViewCell's imageView fit to 40x40</a></p>
<blockquote>
<p>Need to make imageView filled in 40x40... I am using SDK 3.0 with build in "Cell Objects in Predefined Styles"...</p>
</blockquote> |
28,947,571 | How to Count Number of Instances of a Class | <p>Can anyone tell me how to count the number of instances of a class?</p>
<p>Here's my code </p>
<pre><code>public class Bicycle {
//instance variables
public int gear, speed, seatHeight;
public String color;
//constructor
public Bicycle(int gear, int speed, int seatHeight, String color) {
gear = 0;
speed = 0;
seatHeight = 0;
color ="Unknown";
}
//getters and setters
public int getGear() {
return gear;
}
public void setGear(int Gear) {
this.gear = Gear;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int Speed){
this.speed = Speed;
}
public int getSeatHeight() {
return seatHeight;
}
public void setSeatHeight(int SeatHeight) {
this.seatHeight = SeatHeight;
}
public String getColor() {
return color;
}
public void setColor(String Color) {
this.color = Color;
}
}//end class
public class Variable extends Bicycle {
public Variable(int gear, int speed, int seatHeight, String color) {
super(gear, speed, seatHeight, color);
}
}//end class
public class Tester {
public static void main(String args[]){
Bicycle bicycle1 = new Bicycle(0, 0, 0, null);
bicycle1.setColor("red");
System.out.println("Color: "+bicycle1.getColor());
bicycle1.setSeatHeight(4);
System.out.println("Seat Height: "+bicycle1.getSeatHeight());
bicycle1.setSpeed(10);
System.out.println("Speed: "+bicycle1.getSpeed());
bicycle1.setGear(6);
System.out.println("Gear: "+bicycle1.getGear());
System.out.println("");//space
Bicycle bicycle2 = new Bicycle(0, 0, 0, null);
bicycle2.setColor("black");
System.out.println("Color: "+bicycle2.getColor());
bicycle2.setSeatHeight(6);
System.out.println("Seat Height: "+bicycle2.getSeatHeight());
bicycle2.setSpeed(12);
System.out.println("Speed: "+bicycle2.getSpeed());
bicycle2.setGear(6);
System.out.println("Gear: "+bicycle2.getGear());
System.out.println("");//space
}//end method
}//end class
</code></pre>
<p>The class variable is to be used to keep count of the number of instances of the Bicycle class created and the tester class creates a number of instances of the Bicycle class and demonstrates the workings of the Bicycle class and the class variable. I've looked all over the internet and I can't seem to find anything, could someone show me how to do it please, thanks in advance :)</p> | 28,947,625 | 9 | 2 | null | 2015-03-09 16:53:46.267 UTC | 6 | 2021-10-18 17:37:01.35 UTC | null | null | null | null | 4,181,145 | null | 1 | 11 | java|variables|instances | 68,470 | <p>Since <code>static</code> variables are initialized only once, and they're shared between all instances, you can:</p>
<pre><code>class MyClass {
private static int counter;
public MyClass() {
//...
counter++;
}
public static int getNumOfInstances() {
return counter;
}
}
</code></pre>
<p>and to access the static field <code>counter</code> you can use <code>MyClass.getNumOfInstances()</code></p>
<p>Read more about <code>static</code> fields in the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.1" rel="nofollow noreferrer">JLS - 8.3.1.1. <strong>static Fields</strong></a>:</p>
<blockquote>
<p>If a field is declared <code>static</code>, <strong>there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created</strong>. A <code>static</code> field, sometimes called a class variable, is incarnated when the class is initialized (§12.4).</p>
</blockquote>
<p><sup> Note that <code>counter</code> is implicitly set to zero</sup></p> |
50,383,003 | How to re-render a component manually Angular 5 | <p>Is there a way I can re render a component manually, say when a user clicks a button??</p>
<p>I've seen similar posts but none of these worked for me for example <a href="https://stackoverflow.com/questions/35105374/how-to-force-a-components-re-rendering-in-angular-2">here</a></p>
<p>For example,</p>
<pre><code>renderComponent() {
// force component re-render
}
</code></pre> | 50,385,240 | 8 | 1 | null | 2018-05-17 03:42:30.243 UTC | 5 | 2022-05-21 20:18:22.997 UTC | 2018-05-17 03:51:01.123 UTC | null | 8,724,160 | null | 8,724,160 | null | 1 | 27 | angular|typescript | 93,077 | <p>If you meant to manipulate the view (add, remove or reattach) then here is an example: </p>
<pre><code>import { Component, ViewContainerRef, AfterViewInit, ViewChild, ViewRef,TemplateRef} from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'host-comp',
template: `
<h1>I am a host component</h1>
<ng-container #vc><ng-container>
<br>
<button (click)="insertChildView()">Insert Child View</button>
<button (click)="removeChildView()">Remove Child View</button>
<button (click)="reloadChildView()">Reload Child View</button>
<ng-template #tpl>
<child-comp><child-comp>
<ng-template>
`
})
export class HostComponent implements AfterViewInit{
@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
@ViewChild('tpl', {read: TemplateRef}) tpl: TemplateRef<any>;
childViewRef: ViewRef;
constructor(){}
ngAfterViewInit(){
this.childViewRef = this.tpl.createEmbeddedView(null);
}
insertChildView(){
this.vc.insert(this.childViewRef);
}
removeChildView(){
this.vc.detach();
}
reloadChildView(){
this.removeChildView();
setTimeout(() =>{
this.insertChildView();
}, 3000);
}
}
</code></pre>
<p><a href="https://stackblitz.com/edit/ng-embedded-view" rel="noreferrer">live example here</a></p> |
6,053,602 | What arguments are passed into AsyncTask<arg1, arg2, arg3>? | <p>I don't understand what I am supposed to put in here and where these arguments end up? What exactly should I put, and where exactly will it go? Do I need to include all 3 or can I include 1,2,20? </p> | 6,053,673 | 5 | 0 | null | 2011-05-19 04:00:33.67 UTC | 112 | 2021-04-01 21:11:25.76 UTC | 2011-05-19 04:25:40.813 UTC | null | 510,491 | null | 629,599 | null | 1 | 163 | android|arguments|android-asynctask | 114,587 | <p>Google's Android Documentation Says that :</p>
<p>An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.</p>
<p>AsyncTask's generic types : </p>
<p>The three types used by an asynchronous task are the following:</p>
<pre><code>Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
</code></pre>
<p>Not all types are always used by an asynchronous task. To mark a type as unused, simply use the type Void:</p>
<pre><code> private class MyTask extends AsyncTask<Void, Void, Void> { ... }
</code></pre>
<p>You Can further refer : <a href="http://developer.android.com/reference/android/os/AsyncTask.html" rel="noreferrer">http://developer.android.com/reference/android/os/AsyncTask.html</a></p>
<p>Or You Can clear whats the role of AsyncTask by refering <a href="http://sankarganesh-info-exchange.blogspot.com/p/need-and-vital-role-of-asynctas-in.html" rel="noreferrer">Sankar-Ganesh's Blog</a></p>
<h2>Well The structure of a typical AsyncTask class goes like :</h2>
<pre><code>private class MyTask extends AsyncTask<X, Y, Z>
protected void onPreExecute(){
}
</code></pre>
<p>This method is executed before starting the new Thread. There is no input/output values, so just initialize variables or whatever you think you need to do.</p>
<pre><code> protected Z doInBackground(X...x){
}
</code></pre>
<p>The most important method in the AsyncTask class. You have to place here all the stuff you want to do in the background, in a different thread from the main one. Here we have as an input value an array of objects from the type “X” (Do you see in the header? We have “...extends AsyncTask” These are the TYPES of the input parameters) and returns an object from the type “Z”.</p>
<pre><code> protected void onProgressUpdate(Y y){
}
</code></pre>
<p>This method is called using the method publishProgress(y) and it is usually used when you want to show any progress or information in the main screen, like a progress bar showing the progress of the operation you are doing in the background.</p>
<pre><code> protected void onPostExecute(Z z){
}
</code></pre>
<p>This method is called after the operation in the background is done. As an input parameter you will receive the output parameter of the doInBackground method.</p>
<p><strong>What about the X, Y and Z types?</strong></p>
<p>As you can deduce from the above structure:</p>
<pre><code> X – The type of the input variables value you want to set to the background process. This can be an array of objects.
Y – The type of the objects you are going to enter in the onProgressUpdate method.
Z – The type of the result from the operations you have done in the background process.
</code></pre>
<p>How do we call this task from an outside class? Just with the following two lines:</p>
<pre><code>MyTask myTask = new MyTask();
myTask.execute(x);
</code></pre>
<p>Where x is the input parameter of the type X.</p>
<p>Once we have our task running, we can find out its status from “outside”. Using the “getStatus()” method.</p>
<pre><code> myTask.getStatus();
</code></pre>
<p>and we can receive the following status:</p>
<p><strong>RUNNING</strong> - Indicates that the task is running.</p>
<p><strong>PENDING</strong> - Indicates that the task has not been executed yet.</p>
<p><strong>FINISHED</strong> - Indicates that onPostExecute(Z) has finished.</p>
<p><strong><em>Hints about using AsyncTask</em></strong></p>
<ol>
<li><p>Do not call the methods onPreExecute, doInBackground and onPostExecute manually. This is automatically done by the system.</p></li>
<li><p>You cannot call an AsyncTask inside another AsyncTask or Thread. The call of the method execute must be done in the UI Thread.</p></li>
<li><p>The method onPostExecute is executed in the UI Thread (here you can call another AsyncTask!).</p></li>
<li><p>The input parameters of the task can be an Object array, this way you can put whatever objects and types you want.</p></li>
</ol> |
5,641,103 | How to use Toast when I cant use "this" as context | <p>I have a location listener activity and I want to make toast notifications. But it will not let me pass <code>this</code> as the context. How should I make toast work?</p> | 5,641,226 | 7 | 3 | null | 2011-04-12 20:16:30.67 UTC | 4 | 2019-11-10 12:36:20.823 UTC | null | null | null | null | 679,413 | null | 1 | 18 | java|android|toast | 44,323 | <p>If the toast is located inside your activity class, you could use <code>YourActiviy.this</code> where <code>YourActivity</code> is the class name. If it's outside your class, you'll need to get your activity context (pass it in the constructor etc).</p> |
5,632,662 | Saving timestamp in mysql table using php | <p>I have a field in a MySQL table which has a <code>timestamp</code> data type. I am saving data into that table. But when I pass the timestamp (<code>1299762201428</code>) to the record, it automatically saves the value <code>0000-00-00 00:00:00</code> into that table.</p>
<p>How can I store the timestamp in a MySQL table?</p>
<p>Here is my <code>INSERT</code> statement:</p>
<pre><code>INSERT INTO table_name (id,d_id,l_id,connection,s_time,upload_items_count,download_items_count,t_time,status)
VALUES (1,5,9,'2',1299762201428,5,10,20,'1'),
(2,5,9,'2',1299762201428,5,10,20,'1')
</code></pre> | 5,632,691 | 15 | 2 | null | 2011-04-12 08:53:29.98 UTC | 25 | 2018-11-06 00:14:28.82 UTC | 2017-05-03 18:31:49.85 UTC | null | 3,478,852 | null | 417,143 | null | 1 | 105 | php|mysql|database|sql-insert | 215,219 | <p>pass like this</p>
<pre><code>date('Y-m-d H:i:s','1299762201428')
</code></pre> |
44,110,876 | Kubernetes service external ip pending | <p>I am trying to deploy nginx on kubernetes, kubernetes version is v1.5.2,
I have deployed nginx with 3 replica, YAML file is below,</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: deployment-example
spec:
replicas: 3
revisionHistoryLimit: 2
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.10
ports:
- containerPort: 80
</code></pre>
<p>and now I want to expose its port 80 on port 30062 of node, for that I created a service below,</p>
<pre><code>kind: Service
apiVersion: v1
metadata:
name: nginx-ils-service
spec:
ports:
- name: http
port: 80
nodePort: 30062
selector:
app: nginx
type: LoadBalancer
</code></pre>
<p>this service is working good as it should be, but it is showing as pending not only on kubernetes dashboard also on terminal.
<a href="https://i.stack.imgur.com/ix5v1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ix5v1.png" alt="Terminal output" /></a><a href="https://i.stack.imgur.com/TUMOB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/TUMOB.png" alt="Dash board status" /></a></p> | 44,112,285 | 30 | 0 | null | 2017-05-22 10:44:12.13 UTC | 63 | 2022-07-29 05:54:22.323 UTC | 2020-09-21 14:27:08.79 UTC | null | 1,788,806 | null | 5,433,567 | null | 1 | 277 | nginx|kubernetes|load-balancing | 262,616 | <p>It looks like you are using a custom Kubernetes Cluster (using <code>minikube</code>, <code>kubeadm</code> or the like). In this case, there is no LoadBalancer integrated (unlike AWS or Google Cloud). With this default setup, you can only use <a href="https://kubernetes.io/docs/concepts/services-networking/service/#nodeport" rel="noreferrer"><code>NodePort</code></a> or an Ingress Controller.</p>
<p>With the <a href="https://kubernetes.io/docs/concepts/services-networking/ingress/#ingress-class" rel="noreferrer">Ingress Controller</a> you can setup a domain name which maps to your pod; you don't need to give your Service the <code>LoadBalancer</code> type if you use an Ingress Controller.</p> |
44,805,303 | Django Model Method or Calculation as Field in Database | <p><em>Using Django ~=1.11 and Python 3.6</em></p>
<p>I need to store 'calculated' variables as fields in the Django model database.</p>
<p>Here's a model:</p>
<pre><code>from django.db import models
from datetime import date
class Person(model.Model)
"Last Name"
last_name = models.CharField(max_length=25)
"Birthday"
birth_date = models.DateField()
"City of birth"
city_of_birth = models.CharField(max_length=25)
</code></pre>
<p>I am creating a Unique ID using these fields. Specifically, I'm conjoining parts of each field into one string variable (details below). I was able to get this to work as a Property but I don't know how to store a calculated field in the database.</p>
<pre><code>"Unique ID"
def get_id(self):
a = self.last_name[:2].upper() #First 2 letters of last name
b = self.birth_date.strftime('%d') #Day of the month as string
c = self.city_of_birth[:2].upper() #First 2 letters of city
return a + b + c
unique_id = property(get_id)
</code></pre>
<p>I want to do a similar thing with Age. Here's what I have as a calculation:</p>
<pre><code>"Age calculated from Birth Date"
def get_age(self):
return int((datetime.date.now() - self.birth_date.days) / 365.25)
age = property(get_age)
</code></pre>
<p>So I'd like to store the UniqueID and Age variables in the database, as fields in the Person model. What is the best practice when doing these? Do I need to initialize the fields first, then do some sort of update query to these?</p>
<p><em>Note: It is my understanding that the current code using 'property' works for rendering in the view, but it is not stored in the database.</em></p>
<p>Thanks in advance! Please help me improve what I already have.</p>
<p><strong>UPDATE:</strong>
Here is code that worked for me. The problem was that I needed to drop the parentheses in the save() section, after <em>self.unique_id=self.get_unique_id</em> . It has been suggested to drop age from the database, and leave it as a property.</p>
<pre><code>class Person(models.Model):
unique_id = models.CharField(max_length=6, blank=True)
last_name = models.CharField(max_length=25)
birth_date = models.DateField()
city_of_birth = models.CharField(max_length=25)
@property
def get_unique_id(self):
a = self.last_name[:2].upper() #First 2 letters of last name
b = self.birth_date.strftime('%d') #Day of the month as string
c = self.city_of_birth[:2].upper() #First 2 letters of city
return a + b + c
@property
def age(self):
return relativedelta(self.birth_date.days, datetime.date.now()).years
def save(self, *args, **kwarg):
self.unique_id = self.get_unique_id
super(Person, self).save(*args, **kwarg)
def __str__(self):
return self.unique_id
</code></pre> | 44,805,659 | 2 | 2 | null | 2017-06-28 14:24:21.627 UTC | 9 | 2020-12-02 01:22:10.873 UTC | 2019-03-26 08:15:51.103 UTC | null | 2,837,262 | null | 1,794,543 | null | 1 | 12 | python|django|methods|django-models|calculated-field | 14,607 | <p>You have to override the <code>save</code> method of yout Model <code>Person</code> and create <code>unique_id</code> and <code>age</code> field in the Model.</p>
<pre><code>from dateutil.relativedelta import relativedelta
from datetime import datetime
class Person(model.Model)
unique_id = models.CharField(max_length=25)
age = models.IntegerField()
last_name = models.CharField(max_length=25)
birth_date = models.DateField()
city_of_birth = models.CharField(max_length=25)
@property
def get_unique_id(self):
a = self.last_name[:2].upper() #First 2 letters of last name
b = self.birth_date.strftime('%d') #Day of the month as string
c = self.city_of_birth[:2].upper() #First 2 letters of city
return a + b + c
@property
def get_age(self):
return relativedelta(self.birth_date.days, datetime.date.now()).years
def save(self, *args, **kwargs):
self.unique_id = self.get_unique_id
self.age = self.get_age
super(Person, self).save(*args, **kwargs)
</code></pre>
<p>UPDATE: Previously the <code>self.get_unique_id</code> and <code>self.get_age</code> were being called with '()' which is not required for class properties.</p> |
33,198,849 | What is the temporal dead zone? | <p>I've heard that accessing <code>let</code> and <code>const</code> values before they are initialized can cause a <code>ReferenceError</code> because of something called the <strong>temporal dead zone</strong>.</p>
<p>What is the temporal dead zone, how does it relate to scope and hoisting, and in what situations is it encountered?</p> | 33,198,850 | 3 | 1 | null | 2015-10-18 14:06:32.78 UTC | 85 | 2021-09-02 11:18:50.307 UTC | 2018-12-27 18:57:14.357 UTC | null | 1,709,587 | null | 2,806,996 | null | 1 | 189 | javascript|ecmascript-6|constants|let | 43,601 | <p><code>let</code> and <code>const</code> have two broad differences from <code>var</code>:</p>
<ol>
<li>They are <a href="https://hacks.mozilla.org/2015/07/es6-in-depth-let-and-const/" rel="noreferrer">block scoped</a>.</li>
<li>Accessing a <code>var</code> before it is declared has the result <code>undefined</code>; accessing a <code>let</code> or <code>const</code> before it is declared throws <code>ReferenceError</code>:</li>
</ol>
<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(aVar); // undefined
console.log(aLet); // Causes ReferenceError: Cannot access 'aLet' before initialization
var aVar = 1;
let aLet = 2;</code></pre>
</div>
</div>
</p>
<p>It appears from these examples that <code>let</code> declarations (and <code>const</code>, which works the same way) may not be <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting" rel="noreferrer">hoisted</a>, since <code>aLet</code> does not appear to exist before it is assigned a value.</p>
<p>That is not the case, however—<code>let</code> and <code>const</code> <em>are</em> hoisted (like <code>var</code>, <code>class</code> and <code>function</code>), but there is a period between entering scope and being declared where they cannot be accessed. <strong>This period is the temporal dead zone (TDZ)</strong>.</p>
<p>The TDZ ends when <code>aLet</code> is <em>declared</em>, rather than <em>assigned</em>:</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(aLet) // Would throw ReferenceError
let aLet;
console.log(aLet); // undefined
aLet = 10;
console.log(aLet); // 10</code></pre>
</div>
</div>
</p>
<p>This example shows that <code>let</code> is hoisted:</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>let x = "outer value";
(function() {
// Start TDZ for x.
console.log(x);
let x = "inner value"; // Declaration ends TDZ for x.
}());</code></pre>
</div>
</div>
</p>
<p>Credit: <a href="http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified" rel="noreferrer">Temporal Dead Zone (TDZ) demystified</a>.</p>
<p>Accessing <code>x</code> in the inner scope still causes a <code>ReferenceError</code>. If <code>let</code> were not hoisted, it would log <code>outer value</code>.</p>
<p>The TDZ is a good thing because it helps to highlight bugs—accessing a value before it has been declared is rarely intentional.</p>
<p>The TDZ also applies to default function arguments. Arguments are evaluated left to right, and each argument is in the TDZ until it is assigned:</p>
<pre><code>// b is in TDZ until its value is assigned.
function testDefaults(a = b, b) { }
testDefaults(undefined, 1); // Throws ReferenceError because the evaluation of a reads b before it has been evaluated.
</code></pre>
<p>The TDZ is not enabled by default in the <a href="https://babeljs.io" rel="noreferrer">babel.js</a> transpiler. Turn on "high compliance" mode to use it in the <a href="https://babeljs.io/repl" rel="noreferrer">REPL</a>. Supply the <code>es6.spec.blockScoping</code> flag to use it with the CLI or as a library.</p>
<p>Recommended further reading: <a href="http://jsrocks.org/2015/01/temporal-dead-zone-tdz-demystified" rel="noreferrer">TDZ demystified</a> and <a href="https://ponyfoo.com/articles/es6-let-const-and-temporal-dead-zone-in-depth" rel="noreferrer">ES6 Let, Const and the “Temporal Dead Zone” (TDZ) in Depth</a>.</p> |
9,624,803 | php get all url variables | <p>I'm trying to make links to include the current _GET variables.</p>
<p>Example link: <code><a href="?page=2">Page 2</a></code></p>
<p>The current url is: <a href="http://example.com/test.php?id=2&a=1" rel="nofollow">http://example.com/test.php?id=2&a=1</a></p>
<p>So if someone clicks on the link of page 2 it will take them to:
<a href="http://example.com/test.php?id=2&a=1&page=2" rel="nofollow">http://example.com/test.php?id=2&a=1&page=2</a></p>
<p>Currently if they click on the link it takes them to:
<a href="http://example.com/test.php?page=2" rel="nofollow">http://example.com/test.php?page=2</a></p>
<p>As you can see, I need a way to get the current _GET variables in the url and add them to the link. Advice?</p> | 9,624,892 | 5 | 0 | null | 2012-03-08 20:56:02.823 UTC | null | 2016-01-14 23:40:08.56 UTC | null | null | null | null | 962,449 | null | 1 | 4 | php|get | 47,270 | <p>The superglobal entry <code>$_SERVER['QUERY_STRING']</code> has the query string in it. You could just append that to any further links. </p>
<p><strong>update:</strong> The alternate response on this page using http_build_query is better because it lets you add new variables to the query string without worrying about extraneous ?s and such. But I'll leave this here because I wanted to mention that you can access the literal query string that's in the current address.</p> |
9,104,207 | Comparing record to previous record in postgresql | <p>I have a table in PostgreSQL DB like this:</p>
<pre><code> Client | Rate | StartDate|EndDate
A | 1000 | 2005-1-1 |2005-12-31
A | 2000 | 2006-1-1 |2006-12-31
A | 3000 | 2007-1-1 |2007-12-31
B | 5000 | 2006-1-1 |2006-12-31
B | 8000 | 2008-1-1 |2008-12-31
C | 2000 | 2006-1-1 |2006-12-31
</code></pre>
<p>How to get this result?</p>
<pre><code> Client | Rate | StartDate|EndDate |Pre Rate | Pre StartDate |Pre EndDate
A | 1000 | 2005-1-1 |2005-12-31 | | |
A | 2000 | 2006-1-1 |2006-12-31 | 1000 | 2005-1-1 |2005-12-31
A | 3000 | 2007-1-1 |2007-12-31 | 2000 | 2006-1-1 |2006-12-31
B | 5000 | 2006-1-1 |2006-12-31 | | |
B | 8000 | 2008-1-1 |2008-12-31 | 5000 | 2006-1-1 |2006-12-31
C | 2000 | 2006-1-1 |2006-12-31
</code></pre>
<p>Thanks a lot!!!</p> | 9,104,437 | 1 | 0 | null | 2012-02-01 22:18:42.457 UTC | 10 | 2018-10-07 14:21:08.323 UTC | 2018-10-07 14:21:08.323 UTC | null | 3,984,221 | null | 957,106 | null | 1 | 15 | postgresql|comparison|max|next|seconds | 10,616 | <pre><code>SELECT client,
rate,
startdate,
enddate,
lag(rate) over client_window as pre_rate,
lag(startdate) over client_window as pre_startdate,
lag(enddate) over client_window as pre_enddate
FROM the_table
WINDOW client_window as (partition by client order by startdate)
ORDER BY client, stardate;
</code></pre>
<p>This assumes that enddate is always greater than startdate from the same row and that no enddate is greater than the following startdate</p> |
9,527,988 | Cannot Inject Dependencies into ASP.NET Web API Controller using Unity | <p>Has anyone had any success running using an IoC container to inject dependencies into ASP.NET WebAPI controllers? I cannot seem to get it to work.</p>
<p>This is what I'm doing now. </p>
<p>In my <code>global.ascx.cs</code>:</p>
<p></p>
<pre><code> public static void RegisterRoutes(RouteCollection routes)
{
// code intentionally omitted
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
IUnityContainer container = BuildUnityContainer();
System.Web.Http.GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
t =>
{
try
{
return container.Resolve(t);
}
catch (ResolutionFailedException)
{
return null;
}
},
t =>
{
try
{
return container.ResolveAll(t);
}
catch (ResolutionFailedException)
{
return new System.Collections.Generic.List<object>();
}
});
System.Web.Mvc.ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container));
BundleTable.Bundles.RegisterTemplateBundles();
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer().LoadConfiguration();
return container;
}
</code></pre>
<p>My controller factory:</p>
<p></p>
<pre><code>public class UnityControllerFactory : DefaultControllerFactory
{
private IUnityContainer _container;
public UnityControllerFactory(IUnityContainer container)
{
_container = container;
}
public override IController CreateController(System.Web.Routing.RequestContext requestContext,
string controllerName)
{
Type controllerType = base.GetControllerType(requestContext, controllerName);
return (IController)_container.Resolve(controllerType);
}
}
</code></pre>
<p>It never seems to look in my unity file to resolve dependencies, and I get an error like:</p>
<blockquote>
<p>An error occurred when trying to create a controller of type
'PersonalShopper.Services.WebApi.Controllers.ShoppingListController'.
Make sure that the controller has a parameterless public constructor.</p>
<p>at
System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpControllerContext
controllerContext, Type controllerType)
at System.Web.Http.Dispatcher.DefaultHttpControllerFactory.CreateInstance(HttpControllerContext
controllerContext, HttpControllerDescriptor controllerDescriptor)
at System.Web.Http.Dispatcher.DefaultHttpControllerFactory.CreateController(HttpControllerContext
controllerContext, String controllerName)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage
request, CancellationToken cancellationToken)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage
request, CancellationToken cancellationToken)</p>
</blockquote>
<p>Controller looks like:</p>
<p></p>
<pre><code>public class ShoppingListController : System.Web.Http.ApiController
{
private Repositories.IProductListRepository _ProductListRepository;
public ShoppingListController(Repositories.IUserRepository userRepository,
Repositories.IProductListRepository productListRepository)
{
_ProductListRepository = productListRepository;
}
}
</code></pre>
<p>My unity file looks like:</p>
<pre><code><unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="PersonalShopper.Repositories.IProductListRepository, PersonalShopper.Repositories" mapTo="PersonalShopper.Implementations.MongoRepositories.ProductListRepository, PersonalShopper.Implementations" />
</container>
</unity>
</code></pre>
<p>Note that I don't have a registration for the controller itself because in previous versions of mvc the controller factory would figure out that the dependencies needed to be resolved.</p>
<p>It seems like my controller factory is never being called.</p> | 9,544,114 | 11 | 0 | null | 2012-03-02 04:29:46.483 UTC | 31 | 2017-06-20 13:15:34.853 UTC | 2015-09-11 13:20:43.52 UTC | null | 2,874,896 | null | 773,210 | null | 1 | 83 | c#|.net|asp.net-web-api|unity-container | 98,217 | <p>Figured it out.</p>
<p>For <strong>ApiControllers</strong>, MVC 4 uses a <strong>System.Web.Http.Dispatcher.IHttpControllerFactory</strong> and <strong>System.Web.Http.Dispatcher.IHttpControllerActivator</strong> to create the controllers. If there is no static method to register what the implementation of these they are; when they are resolved, the mvc framework looks for the implementations in the dependency resolver, and if they are not found, uses the default implementations.</p>
<p>I got unity resolution of controller dependencies working by doing the following:</p>
<p>Created a UnityHttpControllerActivator:</p>
<pre><code>public class UnityHttpControllerActivator : IHttpControllerActivator
{
private IUnityContainer _container;
public UnityHttpControllerActivator(IUnityContainer container)
{
_container = container;
}
public IHttpController Create(HttpControllerContext controllerContext, Type controllerType)
{
return (IHttpController)_container.Resolve(controllerType);
}
}
</code></pre>
<p>Registered that controller activator as the implementation in the unity container itself:</p>
<pre><code>protected void Application_Start()
{
// code intentionally omitted
IUnityContainer container = BuildUnityContainer();
container.RegisterInstance<IHttpControllerActivator>(new UnityHttpControllerActivator(container));
ServiceResolver.SetResolver(t =>
{
// rest of code is the same as in question above, and is omitted.
});
}
</code></pre> |
30,051,725 | Cannot implicitly convert type 'System.Collections.IList' to 'System.Collections.Generic.List | <p>This is the error I encounter</p>
<blockquote>
<p>Error 1 Cannot implicitly convert type <code>System.Collections.Generic.IList<Model.DTO.RoleDTO></code> to <code>System.Collections.Generic.List<Model.DTO.RoleDTO></code>. An explicit conversion exists (are you missing a cast?) </p>
</blockquote>
<p>My code:</p>
<pre><code>IList<RoleDTO> rl = new List<RoleDTO>();
rl.Add(new RoleDTO{ roleId = new Guid("D3DCBCDA-AD61-4764-B5A1-057D654F1C26"),
role = "admin" });
UserDTO user = new UserDTO
{
username = "administrator",
email = "[email protected]",
role = rl
};
</code></pre>
<p>And the model:</p>
<pre><code>namespace Model.DTO
{
public class UserDTO
{
public string username { get; set; }
public string email { get; set; }
public IList<RoleDTO> role { get; set; }
}
public class RoleDTO
{
public Guid roleId { get; set; }
public string role { get; set; }
}
}
</code></pre>
<p>How do I do this correctly? </p> | 30,051,976 | 3 | 4 | null | 2015-05-05 11:27:27.033 UTC | null | 2021-07-02 04:53:03.873 UTC | 2015-05-05 11:55:05.72 UTC | null | 266,143 | null | 3,264,998 | null | 1 | 15 | c#|.net|generics | 61,333 | <p>Just change <code>r1</code> to be <code>IList<RoleDTO></code>.</p>
<pre><code>IList<RoleDTO> rl = new List<RoleDTO>();
</code></pre>
<p>You cannot mix generic and non generic lists because <code>IList<T></code> does not inherit from <code>IList</code> and <code>List<T></code> does not inherit from <code>List</code> and does not implement <code>IList</code>.</p>
<p><strong>EDIT</strong></p>
<p>Based on the new error you have it means that somewhere you are trying to convert a <code>IList<RoleDTO></code> to a <code>List<RoleDTO></code> which can not be done implicitly because anyone could write a class that implements <code>IList<RoleDTO></code>. So you either need to do an explicit cast, or change the types to match. The problem is that your current code does not show anywhere that a <code>IList<RoleDTO></code> is being implicitly converted to a <code>List<RoleDTO></code>. But here's some guesses on my part. If <code>UserDTO.roles</code> is actually defined as a <code>List<RoleDTO></code> instead of <code>IList<RoleDTO></code> then just change <code>r1</code> to be defined as a <code>List<RoleDTO></code> or change <code>UserDTO.roles</code> to be a <code>IList<RoleDTO></code>. The latter would be my preference. If you are assigning <code>UserDTO.roles</code> to a variable of type <code>List<RoleDTO></code> you should change the type of that variable to <code>IList<RoleDTO></code> instead.</p> |
29,912,489 | How to remove all navigationbar back button title | <p>When I push a <code>UIViewController</code>, it has some title in back button at new <code>UIViewController</code>, if the title has a lot of text, It does not look good in iPhone 4s So I want to remove it.</p>
<p>If I add some code in <code>prepareForSegue</code> function, it is going to be a trouble.</p>
<p>Any better way to achieve this?</p> | 29,912,585 | 34 | 4 | null | 2015-04-28 07:03:11.53 UTC | 23 | 2022-02-05 13:30:58.897 UTC | 2015-04-28 07:27:58.903 UTC | null | 463,857 | null | 4,663,420 | null | 1 | 90 | ios|swift|uibarbuttonitem | 109,241 | <p>If you want back arrow so following code put into <code>AppDelegate</code> file into <code>didFinishLaunchingWithOptions</code> method.</p>
<p><code>For Objective-C</code></p>
<pre><code> [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];
</code></pre>
<p><code>For Swift</code></p>
<pre><code>let BarButtonItemAppearance = UIBarButtonItem.appearance()
BarButtonItemAppearance.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal)
</code></pre>
<p>Another option give below.</p>
<p>In <code>Objective C</code></p>
<pre><code>self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
</code></pre>
<p>In <code>Swift</code></p>
<pre><code>self.navigationItem.backBarButtonItem = UIBarButtonItem(title:"", style:.plain, target:nil, action:nil)
</code></pre>
<p><strong>UPDATE :</strong></p>
<pre><code> let BarButtonItemAppearance = UIBarButtonItem.appearance()
let attributes: [NSAttributedStringKey: Any] = [
BarButtonItemAppearance.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.clear], for: .normal)
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 0.1),
NSAttributedStringKey.foregroundColor: UIColor.clear]
BarButtonItemAppearance.setTitleTextAttributes(attributes, for: .normal)
BarButtonItemAppearance.setTitleTextAttributes(attributes, for: .highlighted)
</code></pre>
<p><strong>UPDATE SWIFT 4.1 :</strong></p>
<pre><code> let attributes = [NSAttributedStringKey.font: UIFont(name: "Helvetica-Bold", size: 0.1)!, NSAttributedStringKey.foregroundColor: UIColor.clear]
BarButtonItemAppearance.setTitleTextAttributes(attributes, for: .normal)
BarButtonItemAppearance.setTitleTextAttributes(attributes, for: .highlighted)
</code></pre>
<p><strong>Using Offset</strong></p>
<pre><code>UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(-1000, 0), for:UIBarMetrics.default)
</code></pre> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.