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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
30,574,322 | MemberData tests show up as one test instead of many | <p>When you use <code>[Theory]</code> together with <code>[InlineData]</code> it will create a test for each item of inline data that is provided. However, if you use <code>[MemberData]</code> it will just show up as one test.</p>
<p>Is there a way to make <code>[MemberData]</code> tests show up as multiple tests?</p> | 32,218,948 | 5 | 4 | null | 2015-06-01 13:05:53.267 UTC | 9 | 2020-09-16 21:20:25.407 UTC | 2017-09-14 15:26:02.007 UTC | null | 247,702 | null | 2,838,509 | null | 1 | 49 | c#|xunit.net|data-driven-tests|xunit2 | 19,286 | <p>I spent a lot of time trying to figure this one out in my project. <a href="https://github.com/xunit/xunit/issues/429" rel="noreferrer">This related Github discussion</a> from @NPadrutt himself helped a lot, but it was still confusing.</p>
<p>The tl;dr is this: <code>[MemberInfo]</code> will report a single group test unless the provided objects for each test can be completely <strong>serialized and deserialized</strong> by implementing <code>IXunitSerializable</code>.</p>
<hr>
<p><strong>Background</strong></p>
<p>My own test setup was something like:</p>
<pre><code>public static IEnumerable<object[]> GetClients()
{
yield return new object[] { new Impl.Client("clientType1") };
yield return new object[] { new Impl.Client("clientType2") };
}
[Theory]
[MemberData(nameof(GetClients))]
public void ClientTheory(Impl.Client testClient)
{
// ... test here
}
</code></pre>
<p>The test ran twice, once for each object from <code>[MemberData]</code>, as expected. As @NPadrutt experienced, only one item showed up in the Test Explorer, instead of two. This is because the provided object <code>Impl.Client</code> was not serializable by either interface xUnit supports (more on this later).</p>
<p>In my case, I didn't want to bleed test concerns into my main code. I thought I could write a thin proxy around my real class that would fool the xUnit runner into thinking it could serialize it, but after fighting with it for longer than I'd care to admit, I realized the part I wasn't understanding was:</p>
<blockquote>
<p>The objects aren't just serialized during discovery to count permutations; each object is also <strong>deserialized at test run time</strong> as the test starts.</p>
</blockquote>
<p>So any object you provide with <code>[MemberData]</code> must support a full round-trip (de-)serialization. This seems obvious to me now, but I couldn't find any documentation on it while I was trying to figure it out.</p>
<hr>
<p><strong>Solution</strong></p>
<ul>
<li><p>Make sure every object (and any non-primitive it may contain) can be fully serialized and deserialized. Implementing xUnit's <code>IXunitSerializable</code> tells xUnit that it's a serializable object.</p></li>
<li><p>If, as in my case, you don't want to add attributes to the main code, one solution is to make a thin serializable builder class for testing that can represent everything needed to recreate the actual class. Here's the above code, after I got it to work:</p></li>
</ul>
<p><strong>TestClientBuilder</strong></p>
<pre><code>public class TestClientBuilder : IXunitSerializable
{
private string type;
// required for deserializer
public TestClientBuilder()
{
}
public TestClientBuilder(string type)
{
this.type = type;
}
public Impl.Client Build()
{
return new Impl.Client(type);
}
public void Deserialize(IXunitSerializationInfo info)
{
type = info.GetValue<string>("type");
}
public void Serialize(IXunitSerializationInfo info)
{
info.AddValue("type", type, typeof(string));
}
public override string ToString()
{
return $"Type = {type}";
}
}
</code></pre>
<p><strong>Test</strong></p>
<pre><code>public static IEnumerable<object[]> GetClients()
{
yield return new object[] { new TestClientBuilder("clientType1") };
yield return new object[] { new TestClientBuilder("clientType2") };
}
[Theory]
[MemberData(nameof(GetClients))]
private void ClientTheory(TestClientBuilder clientBuilder)
{
var client = clientBuilder.Build();
// ... test here
}
</code></pre>
<p>It's mildly annoying that I don't get the target object injected anymore, but it's just one extra line of code to invoke my builder. And, my tests pass (and show up twice!), so I'm not complaining.</p> |
18,616,414 | Read line-by-line file and split values | <p>I need to read a txt file composed as follow:</p>
<pre><code> AA=1000,AA=320009#999999
AA=1011,AA=320303#111111
</code></pre>
<p>for each readed line I need to split it by "#" to get at the first turn </p>
<pre><code> $test[0] = AA=1000,AA=320009 and $test[1]=999999
</code></pre>
<p>and at the second turn</p>
<pre><code> $test[0] = AA=1000,AA=320003 $test[1]= 1111111
</code></pre>
<p>I have some problems to understand how to use get-content or to get it.</p> | 18,616,767 | 3 | 0 | null | 2013-09-04 14:20:58.463 UTC | null | 2021-10-28 08:20:48.147 UTC | null | null | null | null | 1,157,530 | null | 1 | 5 | powershell|powershell-2.0 | 56,368 | <pre><code># Basically, Get-Content will return you an array of strings such as below:
# $tests = Get-Content "c:\myfile\path\mytests.txt"
$tests = @(
"AA=1000,AA=320009#999999",
"AA=1011,AA=320303#111111"
)
$tests | %{ $test = $_ -split '#'; Write-Host $test[0]; Write-Host $test[1] }
</code></pre>
<p>The line above is equivalent to:</p>
<pre><code>$tests | foreach {
$test = $_ -split '#'
Write-Host $test[0]
Write-Host $test[1]
}
</code></pre>
<p>Meaning that for each line of $tests (each line being materialized by $_, one does a split on '#' (which produces an array used in the Write-Host statements)</p> |
5,063,878 | How to cleanly deal with global variables? | <p>I have a number of aspx pages (50+).
I need to declare a number(5-7) of global variables in each of these pages.
Variables in one page independent of the other pages even though some might be same.</p>
<p>Currently I am declaring at the page top and outside of any function.</p>
<p>Should I approach this differently and is there any side effects of this approach?</p>
<p>If exact duplicate, please let me know.
Thanks</p> | 5,064,235 | 3 | 3 | null | 2011-02-21 08:47:50.787 UTC | 13 | 2020-05-28 04:00:46.793 UTC | 2014-09-03 23:36:40.247 UTC | null | 2,864,740 | null | 182,305 | null | 1 | 40 | javascript|global-variables | 23,993 | <p>It is best practice to not clutter the global scope. Especially since other frameworks or drop-in scripts can pollute or overwrite your vars.</p>
<p>Create a namespace for yourself</p>
<p><a href="https://www.geeksforgeeks.org/javascript-namespace/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/javascript-namespace/</a></p>
<p>More here: <a href="https://stackoverflow.com/search?q=namespace+javascript+global">https://stackoverflow.com/search?q=namespace+javascript+global</a></p>
<p>Some examples using different methods of setting the vars</p>
<pre><code>myOwnNS = {}; // or window.myOwnNS
myOwnNS.counter = 0;
myOwnNS["page1"] = { "specificForPage1":"This is page 1"}
myOwnNS.page2 = { "specificForPage2":"This is page 2", "pagenumber":2}
myOwnNS.whatPageAmIOn = function { return location.href.substring(location.href.lastIndexOf('page')+4)}
</code></pre> |
5,276,915 | Do common JavaScript implementations use string interning? | <p>Do common JavaScript engines, such as V8 and WebKit's JavaScriptCore, use <a href="http://en.wikipedia.org/wiki/String_interning" rel="noreferrer">string interning</a> for JavaScript strings? Or do they actually keep multiple instances of identical strings in memory?</p> | 5,276,975 | 3 | 0 | null | 2011-03-11 18:34:15.77 UTC | 7 | 2021-05-21 00:55:58.853 UTC | null | null | null | null | 100,335 | null | 1 | 46 | javascript|programming-languages|webkit|v8|string-interning | 9,147 | <p>Yes. In general any literal string, identifier, or other constant string in JS source is interned. However implementation details (exactly what is interned for instance) varies, as well as when the interning occurs.</p>
<p>Note that a string value is not the same as a String Object though, String Objects are not interned because that would be fundamentally incorrect behaviour.</p> |
5,461,796 | How to Convert a Float String to Number? | <p>A1 is formatted as text and contains a decimal number I would like to programmatically convert to a number.</p>
<p>The "convert to number" function N() only works with whole numbers apparently.</p>
<p>Trying a trick like =A1+0 seems to similarly only work with whole numbers.</p> | 5,461,887 | 4 | 1 | null | 2011-03-28 16:04:50.517 UTC | 1 | 2019-04-03 14:19:51.61 UTC | null | null | null | null | 304,410 | null | 1 | 5 | excel | 41,650 | <p>Use the function</p>
<pre><code>value(A1)
</code></pre>
<p>to convert a string to a number.</p> |
9,252,712 | Twitter Bootstrap: What is the correct way to use the `.btn` class within a navbar? | <p>I'm using a navbar for the standard nav stuff and i'd like to include a button for Sign in and Sign up.</p>
<p>The I'm using an <code>a</code> tag with the <code>btn btn-large btn-success</code> classes and by default it appears the navbar does not accommodate the use of nested <code>btn</code>s.</p>
<p>The result is something like this: </p>
<p><img src="https://i.stack.imgur.com/RTnxy.png" alt="default without hover"></p>
<p>And when hovered over, it comes out as: </p>
<p><img src="https://i.stack.imgur.com/9kuSi.png" alt="hovered"></p>
<p>My question is basically: Am i doing this wrong? Is there something I'm missing?</p>
<p>Thought i'd ask before I redefine CSS classes for .btn. within a navbar.</p>
<p>Thanks. </p> | 9,253,556 | 6 | 4 | null | 2012-02-12 21:12:38.543 UTC | 21 | 2013-07-13 22:46:35.627 UTC | 2012-02-13 04:23:06.62 UTC | null | 365,858 | null | 365,858 | null | 1 | 61 | css|navigation|twitter-bootstrap|css-frameworks | 48,180 | <p>The navbar accommodates buttons without a problem - I have buttons in the navbar without any problems, and I was able to add them to the <a href="http://twitter.github.com/bootstrap/components.html#navbar" rel="noreferrer">static navbar example on the Bootstrap page</a>:</p>
<p><img src="https://i.stack.imgur.com/5GVtR.png" alt="Buttons added to the navbar."></p>
<p>The html should be laid out like this:</p>
<pre><code><div class="navbar navbar-fixed-top active">
<div class="navbar-inner">
<div class="container" style="width: auto;">
<a class="brand" href="#">Project name</a>
<div class="nav-collapse">
<ul class="nav">
... nav links ...
</ul>
<form class="navbar-search pull-left" action="">
... search box stuff
</form>
<a class="btn btn-success">Sign in</a>
<a class="btn btn-primary">Sign up</a>
</div>
</div>
</div>
</div>
</code></pre>
<p>If you're not using the responsive layout to collapse the navbar on smaller screens, just put your button links one level up, in <code><div class="container"></code>.</p>
<p>If you're still not finding the problem, try using <a href="http://code.google.com/chrome/devtools/docs/overview.html" rel="noreferrer">Chrome's Dev Tools</a> to see what CSS is being applied to the buttons that shouldn't be.</p> |
18,292,578 | What does Git (master|REBASE 1/1) mean? How do I get rid of it? | <p>I'm kind of a <a href="/questions/tagged/git" class="post-tag" title="show questions tagged 'git'" rel="tag">git</a> beginner and I was attempting to roll back to a previous commit. But I accidentally just rolled back the commit (I was using the Windows GUI). Anyway, after some weird pushing, merging, and other confusing stuff I didn't quite understand, I finally got my files the way I wanted them. The only weird thing is in the shell now it says:</p>
<blockquote>
<p>(master|REBASE 1/1)</p>
</blockquote>
<p>It used to just say <code>master</code>, so what happened? What does this mean? And how do I get it back to how it was?</p> | 18,292,656 | 5 | 0 | null | 2013-08-17 19:31:37.15 UTC | 7 | 2020-11-18 07:36:53.723 UTC | 2020-11-18 07:36:53.723 UTC | null | 2,265,151 | null | 1,542,306 | null | 1 | 34 | git|version-control|git-branch|rebase | 39,357 | <p>You are stuck in the middle of a rebase. </p>
<p>If you have merged/solved conflicts for all the paths:<br>
use <code>git add .</code> to commit resolved items.<br>
use <code>git rebase --continue</code> to complete the process. </p>
<p>Or use <code>git rebase --abort</code> to exit the rebase process without any risk. </p> |
18,445,825 | how to know status of currently running jobs | <p>I need to know if a given Job is currently running on Ms SQL 2008 server. So as to not to invoke same job again that may lead to concurrency issues.</p> | 18,446,365 | 9 | 1 | null | 2013-08-26 13:52:31.723 UTC | 11 | 2019-02-14 07:01:29.15 UTC | 2018-02-09 05:53:53.717 UTC | null | 2,067,941 | null | 225,394 | null | 1 | 73 | sql-server|sql-server-2008|tsql|sql-agent | 284,341 | <p>It looks like you can use <code>msdb.dbo.sysjobactivity</code>, checking for a record with a non-null start_execution_date and a null stop_execution_date, meaning the job was started, but has not yet completed.</p>
<p>This would give you currently running jobs:</p>
<pre><code>SELECT sj.name
, sja.*
FROM msdb.dbo.sysjobactivity AS sja
INNER JOIN msdb.dbo.sysjobs AS sj ON sja.job_id = sj.job_id
WHERE sja.start_execution_date IS NOT NULL
AND sja.stop_execution_date IS NULL
</code></pre> |
19,986,089 | __init__() got an unexpected keyword argument 'user' | <p>i am using Django to create a user and an object when the user is created. But there is an error</p>
<p><code>__init__() got an unexpected keyword argument 'user'</code></p>
<p>when calling the <code>register()</code> function in view.py.
The function is:</p>
<pre><code>def register(request):
'''signup view'''
if request.method=="POST":
form=RegisterForm(request.POST)
if form.is_valid():
username=form.cleaned_data["username"]
email=form.cleaned_data["email"]
password=form.cleaned_data["password"]
user=User.objects.create_user(username, email, password)
user.save()
return HttpResponseRedirect('/keenhome/accounts/login/')
else:
form = RegisterForm()
return render_to_response("polls/register.html", {'form':form}, context_instance=RequestContext(request))
#This is used for reinputting if failed to register
else:
form = RegisterForm()
return render_to_response("polls/register.html", {'form':form}, context_instance=RequestContext(request))
</code></pre>
<p>and the object class is:</p>
<pre><code>class LivingRoom(models.Model):
'''Living Room object'''
user = models.OneToOneField(User)
def __init__(self, temp=65):
self.temp=temp
TURN_ON_OFF = (
('ON', 'On'),
('OFF', 'Off'),
)
TEMP = (
('HIGH', 'High'),
('MEDIUM', 'Medium'),
('LOW', 'Low'),
)
on_off = models.CharField(max_length=2, choices=TURN_ON_OFF)
temp = models.CharField(max_length=2, choices=TEMP)
#signal function: if a user is created, add control livingroom to the user
def create_control_livingroom(sender, instance, created, **kwargs):
if created:
LivingRoom.objects.create(user=instance)
post_save.connect(create_control_livingroom, sender=User)
</code></pre>
<p>The Django error page notifies the error information:
<code>user=User.objects.create_user(username, email, password)</code>
and
<code>LivingRoom.objects.create(user=instance)</code></p>
<p>I tried to search this problem, finding some cases, but still cannot figure out how to solve it.</p> | 19,986,188 | 4 | 2 | null | 2013-11-14 18:59:59.197 UTC | 8 | 2020-11-23 20:21:42.117 UTC | 2013-11-14 19:12:06.99 UTC | null | 1,572,562 | null | 2,284,861 | null | 1 | 40 | python|django|django-models|django-forms|django-views | 154,428 | <p>You can't do</p>
<pre><code>LivingRoom.objects.create(user=instance)
</code></pre>
<p>because you have an <code>__init__</code> method that does NOT take <code>user</code> as argument.</p>
<p>You need something like</p>
<pre><code>#signal function: if a user is created, add control livingroom to the user
def create_control_livingroom(sender, instance, created, **kwargs):
if created:
my_room = LivingRoom()
my_room.user = instance
</code></pre>
<p><strong>Update</strong></p>
<p>But, as <a href="https://stackoverflow.com/users/41316/bruno-desthuilliers">bruno</a> has <a href="https://stackoverflow.com/a/19987873/2689986">already said it</a>, Django's <code>models.Model</code> subclass's initializer is best left alone, or should accept <code>*args</code> and <code>**kwargs</code> matching the model's meta fields.</p>
<p>So, following better principles, you should probably have something like</p>
<pre><code>class LivingRoom(models.Model):
'''Living Room object'''
user = models.OneToOneField(User)
def __init__(self, *args, temp=65, **kwargs):
self.temp = temp
return super().__init__(*args, **kwargs)
</code></pre>
<p>Note - If you weren't using <code>temp</code> as a keyword argument, e.g. <code>LivingRoom(65)</code>, then you'll have to start doing that. <code>LivingRoom(user=instance, temp=66)</code> or if you want the default (65), simply <code>LivingRoom(user=instance)</code> would do.</p> |
15,186,520 | scala - Any vs underscore in generics | <p>What is the different between the following Generics definitions in Scala:</p>
<pre><code>class Foo[T <: List[_]]
</code></pre>
<p>and </p>
<pre><code>class Bar[T <: List[Any]]
</code></pre>
<p>My gut tells me they are about the same but that the latter is more explicit. I am finding cases where the former compiles but the latter doesn't, but can't put my finger on the exact difference.</p>
<p>Thanks!</p>
<p><strong>Edit:</strong></p>
<p>Can I throw another into the mix?</p>
<pre><code>class Baz[T <: List[_ <: Any]]
</code></pre> | 15,204,140 | 2 | 1 | null | 2013-03-03 14:07:32.683 UTC | 42 | 2019-02-22 20:27:52.493 UTC | 2019-02-22 20:27:52.493 UTC | null | 2,707,792 | null | 1,906,491 | null | 1 | 81 | scala|generics|covariance|any|existential-type | 17,002 | <p>OK, I figured I should have my take on it, instead of just posting comments. Sorry, this is going to be long, if you want the TL;DR skip to the end.</p>
<p>As Randall Schulz said, here <code>_</code> is a shorthand for an existential type. Namely,</p>
<pre><code>class Foo[T <: List[_]]
</code></pre>
<p>is a shorthand for</p>
<pre><code>class Foo[T <: List[Z] forSome { type Z }]
</code></pre>
<p>Note that contrary to what Randall Shulz's answer mentions (full disclosure: I got it wrong too in an earlier version of this post, thanks to Jesper Nordenberg for pointing it out) this not the same as:</p>
<pre><code>class Foo[T <: List[Z]] forSome { type Z }
</code></pre>
<p>nor is it the same as:</p>
<pre><code>class Foo[T <: List[Z forSome { type Z }]]
</code></pre>
<p>Beware, it is easy to get it wrong (as my earlier goof shows): the author of the article referenced by Randall Shulz's answer got it wrong himself (see comments), and fixed it later. My main problem with this article is that in the example shown, the use of existentials is supposed to save us from a typing problem, but it does not. Go check the code, and try to compile <code>compileAndRun(helloWorldVM("Test"))</code> or <code>compileAndRun(intVM(42))</code>. Yep, does not compile. Simply making <code>compileAndRun</code> generic in <code>A</code> would make the code compile, and it would be much simpler.
In short, that's probably not the best article to learn about existentials and what they are good for (the author himself acknowledge in a comment that the article "needs tidying up").</p>
<p>So I would rather recommend reading this article: <a href="http://www.artima.com/scalazine/articles/scalas_type_system.html" rel="noreferrer">http://www.artima.com/scalazine/articles/scalas_type_system.html</a>, in particular the sections named "Existential types" and "Variance in Java and Scala".</p>
<p>The important point that you hould get from this article is that existentials are useful (apart from being able to deal with generic java classes) when dealing with non-covariant types.
Here is an example.</p>
<pre><code>case class Greets[T]( private val name: T ) {
def hello() { println("Hello " + name) }
def getName: T = name
}
</code></pre>
<p>This class is generic (note also that is is invariant), but we can see that <code>hello</code> really doesn't make any use of the type parameter (unlike <code>getName</code>), so if I get an instance of <code>Greets</code> I should always be able to call it, whatever <code>T</code> is. If I want to define a method that takes a <code>Greets</code> instance and just calls its <code>hello</code> method, I could try this:</p>
<pre><code>def sayHi1( g: Greets[T] ) { g.hello() } // Does not compile
</code></pre>
<p>Sure enough, this does not compile, as <code>T</code> comes out of nowhere here.</p>
<p>OK then, let's make the method generic:</p>
<pre><code>def sayHi2[T]( g: Greets[T] ) { g.hello() }
sayHi2( Greets("John"))
sayHi2( Greets('Jack))
</code></pre>
<p>Great, this works. We could also use existentials here:</p>
<pre><code>def sayHi3( g: Greets[_] ) { g.hello() }
sayHi3( Greets("John"))
sayHi3( Greets('Jack))
</code></pre>
<p>Works too. So all in all, there is no real benefit here from using an existential (as in <code>sayHi3</code>) over type parameter (as in <code>sayHi2</code>).</p>
<p>However, this changes if <code>Greets</code> appears itself as a type parameter to another generic class. Say by example that we want to store several instances of <code>Greets</code> (with different <code>T</code>) in a list. Let's try it:</p>
<pre><code>val greets1: Greets[String] = Greets("John")
val greets2: Greets[Symbol] = Greets('Jack)
val greetsList1: List[Greets[Any]] = List( greets1, greets2 ) // Does not compile
</code></pre>
<p>The last line does not compile because <code>Greets</code> is invariant, so a <code>Greets[String]</code> and <code>Greets[Symbol]</code> cannot be treated as a <code>Greets[Any]</code> even though <code>String</code> and <code>Symbol</code> both extends <code>Any</code>.</p>
<p>OK, let's try with an existential, using the shorthand notation <code>_</code>:</p>
<pre><code>val greetsList2: List[Greets[_]] = List( greets1, greets2 ) // Compiles fine, yeah
</code></pre>
<p>This compiles fine, and you can do, as expected:</p>
<pre><code>greetsSet foreach (_.hello)
</code></pre>
<p>Now, remember that the reason we had a type checking problem in the first place was because <code>Greets</code> is invariant. If it was turned into a covariant class (<code>class Greets[+T]</code>) then everything would have worked out of the box and we would never have needed existentials.</p>
<hr>
<p>So to sum up, existentials are useful to deal with generic invariant classes, but if the generic class does not need to appear itself as a type parameter to another generic class, chances are that you don't need existentials and simply adding a type parameter to your method will work</p>
<p>Now come back(at last, I know!) to your specific question, regarding</p>
<pre><code>class Foo[T <: List[_]]
</code></pre>
<p>Because <code>List</code> is covariant, this is for all intents and purpose the same as just saying:</p>
<pre><code>class Foo[T <: List[Any]]
</code></pre>
<p>So in this case, using either notation is really just a matter of style.</p>
<p>However, if you replace <code>List</code> with <code>Set</code>, things change:</p>
<pre><code>class Foo[T <: Set[_]]
</code></pre>
<p><code>Set</code> is invariant and thus we are in the same situation as with the <code>Greets</code> class from my example. Thus the above really is very different from</p>
<pre><code>class Foo[T <: Set[Any]]
</code></pre> |
15,405,916 | Correct way to load a Nib for a UIView subclass | <p>I am aware this question has been asked before but the answers are contradicting and I am confused, so please don't flame me.</p>
<p>I want to have a reusable <code>UIView</code> subclass throughout my app. I want to describe the interface using a nib file.</p>
<p>Now let's say it's a loading indicator view with an activity indicator in it. I would like on some event to instantiate this view and animate in to a view controller's view. I could describe the view's interface no problem programmatically, creating the elements programmatically and setting their frame inside an init method etc.</p>
<p>How can I do this using a nib though? Maintaining the size given in interface builder without having to set a frame.</p>
<p>I've managed to do it like this, but I'm sure it is wrong (it's just a view with a picker in it):</p>
<pre><code> - (id)initWithDataSource:(NSDictionary *)dataSource {
self = [super init];
if (self){
self = [[[NSBundle mainBundle] loadNibNamed:[NSString stringWithFormat:@"%@", [self class]] owner:self options:nil] objectAtIndex:0];
self.pickerViewData = dataSource;
[self configurePickerView];
}
return self;
}
</code></pre>
<p>But I'm overwriting self, and when I instantiate it:</p>
<pre><code>FSASelectView *selectView = [[FSASelectView alloc] initWithDataSource:selectViewDictionary];
selectView.delegate = self;
selectView.frame = CGRectMake(0, self.view.bottom + 50, [FSASelectView width], [FSASelectView height]);
</code></pre>
<p>I have to manually set the frame rather than have it picked up from IB.</p>
<p>EDIT: I want to create this custom view in a view controller, and have access to control the view's elements. I don't want a new view controller.</p>
<p>Thanks</p>
<p><strong>EDIT: I Don't know if this is best practice, I'm sure it's not, but this is how I did it:</strong></p>
<pre><code>FSASelectView *selectView = [[[NSBundle mainBundle] loadNibNamed:[NSString stringWithFormat:@"%@",[FSASelectView class]] owner:self options:nil] objectAtIndex:0];
selectView.delegate = self;
[selectView configurePickerViewWithData:ds];
selectView.frame = CGRectMake(0, self.view.bottom + 50, selectView.width, selectView.height);
selectView.alpha = 0.9;
[self.view addSubview:selectView];
[UIView animateWithDuration: 0.25 delay: 0 options:UIViewAnimationOptionAllowUserInteraction |UIViewAnimationOptionCurveEaseInOut animations:^{
selectView.frame = CGRectMake(0, self.view.bottom - selectView.height, selectView.width, selectView.height);
selectView.alpha = 1;
} completion:^(BOOL finished) {
}];
</code></pre>
<p><strong>Correct practice still wanted</strong></p>
<p>Should this have been done using a view controller and init with nib name? Should I have set the nib in some UIView initialisation method in the code? Or is what I have done ok?</p> | 15,406,012 | 6 | 3 | null | 2013-03-14 09:51:23.14 UTC | 24 | 2017-04-10 07:57:46.45 UTC | 2017-03-16 16:49:28.847 UTC | null | 1,032,372 | null | 1,050,447 | null | 1 | 100 | iphone|ios|objective-c|uiview|xib | 104,528 | <pre><code>MyViewClass *myViewObject = [[[NSBundle mainBundle] loadNibNamed:@"MyViewClassNib" owner:self options:nil] objectAtIndex:0]
</code></pre>
<p>I'm using this to initialise the reusable custom views I have.</p>
<hr>
<p>Note that you can use <strong>"firstObject"</strong> at the end there, it's a little cleaner. "firstObject" is a handy method for NSArray and NSMutableArray.</p>
<p>Here's a typical example, of loading a xib to use as a table header. In your file YourClass.m</p>
<pre><code>- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
return [[NSBundle mainBundle] loadNibNamed:@"TopArea" owner:self options:nil].firstObject;
}
</code></pre>
<p>Normally, in the <code>TopArea.xib</code>, you would click on File Owner and <strong>set the file owner to YourClass</strong>. Then actually <strong>in YourClass.h</strong> you would have IBOutlet properties. In <code>TopArea.xib</code>, you can drag controls to those outlets.</p>
<p>Don't forget that in <code>TopArea.xib</code>, you may have to <strong>click on the View itself</strong> and drag that to some outlet, so you have control of it, if necessary. (A very worthwhile tip is that when you are doing this for table cell rows, you absolutely have to do that - you have to connect the view itself to the relevant property in your code.)</p> |
15,208,711 | Mongoose subdocuments vs nested schema | <p>I'm curious as to the pros and cons of using subdocuments vs a deeper layer in my main schema:</p>
<pre><code>var subDoc = new Schema({
name: String
});
var mainDoc = new Schema({
names: [subDoc]
});
</code></pre>
<p>or </p>
<pre><code>var mainDoc = new Schema({
names: [{
name: String
}]
});
</code></pre>
<p>I'm currently using subdocs everywhere but I am wondering primarily about performance or querying issues I might encounter.</p> | 16,493,881 | 6 | 4 | null | 2013-03-04 18:43:00.807 UTC | 32 | 2019-11-06 15:28:21.58 UTC | 2016-01-28 22:29:39.013 UTC | null | 23,501 | null | 856,498 | null | 1 | 147 | javascript|node.js|mongodb|mongoose | 118,903 | <p>According to <a href="http://mongoosejs.com/docs/subdocs.html#altsyntax" rel="noreferrer">the docs</a>, it's exactly the same.
However, using a Schema would add an <code>_id</code> field as well (as long as you don't have that disabled), and presumably uses some more resources for tracking subdocs.</p>
<blockquote>
<p><strong>Alternate declaration syntax</strong></p>
<p><em>New in v3</em> If you don't need access to the sub-document schema instance, you may also declare sub-docs by simply passing an object literal [...]</p>
</blockquote> |
28,114,352 | java.lang.IllegalArgumentException: Illegal character in scheme at index 0: localhost | <p>I'am developping an android app that receive an data from server (localhost - mssql and nodejs), save data and then display it</p>
<p>after receiving the server response I get this error</p>
<p>I follow the instructions below <a href="http://spring.io/guides/gs/consuming-rest-android/" rel="noreferrer">enter link description here</a> instead of the web server I use localhost. Thank you</p>
<pre class="lang-none prettyprint-override"><code> Illegal character in scheme at index 0: 192.168.2.7:3000
java.net.URISyntaxException: Illegal character in scheme at index 0: 192.168.2.7:3000
at java.net.URI.validateScheme(URI.java:419)
at java.net.URI.parseURI(URI.java:363)
at java.net.URI.<init>(URI.java:204)
at cz.uhk.fim.jedlima3.searchrooms.asyncTask.DownloadDatabaseAsync.doInBackground(DownloadDatabaseAsync.java:30)
at cz.uhk.fim.jedlima3.searchrooms.asyncTask.DownloadDatabaseAsync.doInBackground(DownloadDatabaseAsync.java:15)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
</code></pre> | 33,211,847 | 6 | 2 | null | 2015-01-23 16:29:19.233 UTC | 2 | 2022-08-18 01:36:45.097 UTC | 2015-01-23 16:33:18.073 UTC | null | 2,711,488 | null | 3,468,921 | null | 1 | 16 | java|localhost|spring-android | 48,121 | <p>you should remove space from url and define scheme <code>http</code> or <code>https</code></p> |
45,142,080 | Why can't constructors be explicitly called while destructors can? | <p>In the following C++ code, I am allowed to explicitly call the destructor but not the constructor. Why is that? Wouldn't be explicit ctor call more <strong>expressive</strong> and <strong>unified</strong> with the dtor case?</p>
<pre><code>class X { };
int main() {
X* x = (X*)::operator new(sizeof(X));
new (x) X; // option #1: OK
x->X(); // option #2: ERROR
x->~X();
::operator delete(x);
}
</code></pre> | 45,142,200 | 3 | 12 | null | 2017-07-17 10:40:51.417 UTC | 4 | 2017-09-14 21:17:27.073 UTC | 2017-09-14 21:17:27.073 UTC | null | 963,864 | null | 580,083 | null | 1 | 28 | c++|constructor|destructor|placement-new|explicit-destructor-call | 4,151 | <p>Because before the constructor is started, there is no object of type <code>X</code> at that address. As such, dereferencing <code>x</code> as an <code>X</code> type or accessing members/methods of it would be Undefined Behavior.</p>
<p>So the major difference between <code>x->X();</code> (hypothetical syntax) and <code>x->~X()</code> is that in the 2nd case you have an object on which you can call a (special) member such as the destructor, while in the first case, <strong>there is no object yet</strong> on which you can call methods (even the special method - constructor).</p>
<p>You could argue that there could be an exception to this rule, but then it ultimately would be a matter of syntax preference, where you have inconsistencies in both cases. With the current syntax the call to constructor doesn't look like a call to constructor, in your proposed syntax there would be symmetry with the destructor call, but inconsistencies in the rules which govern when you can dereference/access methods of an object. Actually there would have to be an exception allowing calling a method on something that is not a object yet. Then you would have to strictly define in the letter of the standard <em>something that is not an object yet</em>.</p> |
7,882,074 | How do you set one array's values to another array's values in Java? | <p>Lets say you had two arrays:</p>
<pre><code> int[] a = {2, 3, 4};
int[] b = {4, 5, 6};
</code></pre>
<p>How would you set array a to array b and keep them different different objects? Like I thought of doing this:</p>
<pre><code> a = b;
</code></pre>
<p>But that doesn't work since it just makes "a" reference array b. So, is the only way to set two arrays equal, while keeping them separate objects, to loop through every element of one array and set it to the other?</p>
<p>And what about ArrayList? How would you set one ArrayList equal to another when you have objects in them?</p> | 7,882,095 | 2 | 1 | null | 2011-10-24 21:15:08.847 UTC | 7 | 2017-10-26 12:57:38.833 UTC | 2015-11-03 04:56:31.32 UTC | null | 597,657 | null | 906,497 | null | 1 | 8 | java|arrays | 91,429 | <p>You may want to use <code>clone</code>:</p>
<pre><code>a = b.clone();
</code></pre>
<p>or use <code>arraycopy(Object source, int sourcePosition, Object destination, int destinationPosition, int numberOfElements)</code></p>
<pre><code>System.arraycopy(b, 0, a, 0, b.length());
</code></pre> |
7,842,393 | Create a div with bottom half one color and top half another color | <p>I have a which I am going to make into a button. The top half should be #ffd41a and the bottom half should be #fac915. Here is a link to the button at present. <a href="http://jsfiddle.net/WnwNW/">http://jsfiddle.net/WnwNW/</a></p>
<p>The problem that I'm facing is how should I deal with two background colors. Is there a way to do what I'm trying to do without the need for addition divs or spans? Can I have two background attributes within the same CSS class? </p> | 7,842,446 | 2 | 0 | null | 2011-10-20 21:19:34.503 UTC | 2 | 2022-03-05 23:37:46.793 UTC | null | null | null | null | 155,726 | null | 1 | 16 | html|css | 44,426 | <p>CSS3 provides a way to do this</p>
<pre><code>background-image: linear-gradient(to bottom, #FFD51A 50%, #FAC815 50%);
background-image: -o-linear-gradient(bottom, #FFD51A 50%, #FAC815 50%);
background-image: -moz-linear-gradient(bottom, #FFD51A 50%, #FAC815 50%);
background-image: -webkit-linear-gradient(bottom, #FFD51A 50%, #FAC815 50%);
background-image: -ms-linear-gradient(bottom, #FFD51A 50%, #FAC815 50%);
</code></pre>
<p><a href="http://jsfiddle.net/WnwNW/1/" rel="nofollow noreferrer">http://jsfiddle.net/WnwNW/1/</a></p> |
8,352,708 | How to check if file already exists in the folder | <p>I am trying to copy some files to folder. I am using the following statement to check if the source fie exists</p>
<pre> If My.Computer.FileSystem.FileExists(fileToCopy) Then</pre>
<p>But I donot know how to check if file exists in the folder before copying.
Please advise.</p>
<p>Thanks and best regards,
Furqan</p> | 8,353,425 | 2 | 2 | null | 2011-12-02 06:48:16.487 UTC | 3 | 2019-12-27 08:41:58.677 UTC | null | null | null | null | 415,037 | null | 1 | 18 | vb.net | 160,420 | <pre><code>Dim SourcePath As String = "c:\SomeFolder\SomeFileYouWantToCopy.txt" 'This is just an example string and could be anything, it maps to fileToCopy in your code.
Dim SaveDirectory As string = "c:\DestinationFolder"
Dim Filename As String = System.IO.Path.GetFileName(SourcePath) 'get the filename of the original file without the directory on it
Dim SavePath As String = System.IO.Path.Combine(SaveDirectory, Filename) 'combines the saveDirectory and the filename to get a fully qualified path.
If System.IO.File.Exists(SavePath) Then
'The file exists
Else
'the file doesn't exist
End If
</code></pre> |
8,314,827 | How can I specialize a template member function for std::vector<T> | <p>I need to define a get method in two different ways. One for simple types T. And once for std::vector.</p>
<pre><code>template<typename T>
const T& Parameters::get(const std::string& key)
{
Map::iterator i = params_.find(key);
...
return boost::lexical_cast<T>(boost::get<std::string>(i->second));
...
}
</code></pre>
<p>How can I specialize this method for std::vector. As there the code should look something like this:</p>
<pre><code>template<typename T>
const T& Parameters::get(const std::string& key)
{
Map::iterator i = params_.find(key);
std::vector<std::string> temp = boost::get<std::vector<std::string> >(i->second)
std::vector<T> ret(temp.size());
for(int i=0; i<temp.size(); i++){
ret[i]=boost::lexical_cast<T>(temp[i]);
}
return ret;
}
</code></pre>
<p>But I do not know how to specialize the function for this. Thanks a lot.</p> | 8,315,197 | 2 | 1 | null | 2011-11-29 17:12:17.34 UTC | 5 | 2014-02-02 15:20:40.807 UTC | 2011-11-29 17:15:52.413 UTC | null | 248,123 | null | 992,460 | null | 1 | 28 | c++|templates | 9,113 | <p><strong>Don't specialize function template.</strong> </p>
<ul>
<li><a href="http://www.gotw.ca/publications/mill17.htm">Why Not Specialize Function Templates?</a></li>
<li><a href="http://www.gotw.ca/gotw/049.htm">Template Specialization and Overloading</a></li>
</ul>
<p><strong>Instead, use overload.</strong> </p>
<p>Write a function template <code>get_impl</code> to handle the general case, and <em>overload</em> (not <em>specialize</em>) this to handle the specific case, then call <code>get_impl</code> from <code>get</code> as:</p>
<pre><code>template<typename T>
const T& Parameters::get(const std::string& key)
{
//read the explanation at the bottom for the second argument!
return get_impl(key, static_cast<T*>(0) );
}
</code></pre>
<p>And here goes the actual implementations.</p>
<pre><code>//general case
template<typename T>
const T& Parameters::get_impl(const std::string& key, T*)
{
Map::iterator i = params_.find(key);
return boost::lexical_cast<T>(boost::get<std::string>(i->second));
}
//this is overload - not specialization
template<typename T>
const std::vector<T>& Parameters::get_impl(const std::string& key, std::vector<T> *)
{
//vector specific code
}
</code></pre>
<p>The <code>static_cast<T*>(0)</code> in <code>get</code> is just a tricky way to disambiguate the call. The type of <code>static_cast<T*>(0)</code> is <code>T*</code>, and passing it as second argument to <code>get_impl</code> will help compiler to choose the correct version of <code>get_impl</code>. If <code>T</code> is not <code>std::vector</code>, the first version will be chosen, otherwise the second version will be chosen.</p> |
8,120,466 | Missalignment with inline-block (other elements pushed down) | <p>I'm trying to align small boxes in a row. These boxes have something like 2 elements in each. In some cases, the first element is so "much" text, that it splits into 2 lines. If this happens, all other blocks in this special line are shown below.</p>
<p>Long story short, here is the example:
<a href="http://jsfiddle.net/PMRQ5/" rel="noreferrer">http://jsfiddle.net/PMRQ5/</a></p>
<p>If you resize the HTML field, you can see what I mean. Can somebody help?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.songlist .even {
background: #c2e4fa;
background: -moz-linear-gradient(top, #d9eefc, #c2e4fa);
margin-right: 5px;
}
.songlist .odd {
background: #faf4c2;
background: -moz-linear-gradient(top, #fcf8d9, #faf4c2);
margin-right: 5px;
}
.songlist .itemBox {
font-size: 11px;
width: 220px;
min-height: 100px;
clear: both;
padding: 5px;
margin: 5px 10px 5px 10px;
display: inline-block;
position: relative;
border-radius: 4px;
}
.songlist .itemBox .title {
font-weight: bold;
font-size: 16px;
}
.songlist .itemBox .artist {
clear: left;
font-size: 11px;
}
.songlist .itemBox .titlerating {
bottom: 10px;
left: 10px;
position: absolute;
}
.songlist .itemBox .dance {
bottom: 5px;
right: 10px;
position: absolute;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='songlist'>
<div class='itemBox even'>
<div class='cover'></div>
<div class='title'>You and you</div>
<div class='artist'>101 Strings Orchestra</div>
<div class='clear'></div>
</div>
<div class='itemBox odd'>
<div class='title'>The Queen's lace hankerchief waltz</div>
<div class='artist'>101 Strings Orchestra</div>
<div class='clear'></div>
</div>
<div class='itemBox even'>
<div class='cover'></div>
<div class='title'>Voices of spring</div>
<div class='artist'>101 Strings Orchestra</div>
<div class='clear'></div>
</div>
<div class='itemBox odd'>
<div class='cover'></div>
<div class='title'>Roses from the south</div>
<div class='artist'>101 Strings Orchestra</div>
<div class='clear'></div>
</div>
</div></code></pre>
</div>
</div>
</p> | 8,120,546 | 2 | 1 | null | 2011-11-14 10:48:38.287 UTC | 9 | 2016-12-24 07:20:50.81 UTC | 2016-12-24 07:17:26.477 UTC | null | 2,142,994 | null | 490,647 | null | 1 | 41 | html|css|row|offset | 32,592 | <p><a href="http://jsfiddle.net/PMRQ5/1/" rel="noreferrer">http://jsfiddle.net/PMRQ5/1/</a></p>
<p>Add <code>vertical-align: top</code> or <code>vertical-align: bottom</code> to the box, depends on what you want.</p> |
5,079,525 | MVC ViewModels and Entity Framework queries | <p>I am new to both MVC and Entity Framework and I have a question about the right/preferred way to do this.</p>
<p>I have sort of been following the Nerd Dinner MVC application for how I am writing this application. I have a page that has data from a few different places. It shows details that come from a few different tables and also has a dropdown list from a lookup table.</p>
<p>I created a ViewModel class that contains all of this information:</p>
<pre><code>class DetailsViewModel {
public List<Foo> DropdownListData { get; set; }
// comes from table 1
public string Property1 { get; set; }
public string Property2 { get; set; }
public Bar SomeBarObject { get; set; } // comes from table 2
}
</code></pre>
<p>In the Nerd Dinner code, their examples is a little too simplistic. The DinnerFormViewModel takes in a single entity: Dinner. Based on the Dinner it creates a SelectList for the countries based on the dinners location.</p>
<p>Because of the simplicity, their data access code is also pretty simple. He has a simple DinnerRepository with a method called GetDinner(). In his action methods he can do simple things like:</p>
<pre><code>Dinner dinner = new Dinner();
// return the view model
return View(new DinnerFormViewModel(dinner));
</code></pre>
<p>OR</p>
<pre><code>Dinner dinner = repository.GetDinner(id);
return View(new DinnerFormViewModel(dinner));
</code></pre>
<p>My query is a lot more complex than this, pulling from multiple tables...creating an anonymous type:</p>
<pre><code>var query = from a in ctx.Table1
where a.Id == id
select new { a.Property1, a.Property2, a.Foo, a.Bar };
</code></pre>
<p>My question is as follows:</p>
<p><strong>What should my repository class look like?</strong> Should the repository class return the ViewModel itself? That doesn't seem like the right way to do things, since the ViewModel sort of implies it is being used in a view. Since my query is returning an anonymous object, how do I return that from my repository so I can construct the ViewModel in my controller actions?</p> | 5,079,784 | 5 | 1 | null | 2011-02-22 14:41:36.263 UTC | 13 | 2013-06-07 14:00:07.997 UTC | 2012-06-29 05:40:38.263 UTC | null | 503,969 | null | 143,919 | null | 1 | 19 | c#|asp.net-mvc|entity-framework|repository-pattern|viewmodel | 10,967 | <p>You are correct a repository should not return a view model. As changes to your view will cause you to change your data layer.</p>
<p>Your repository should be an <a href="https://stackoverflow.com/questions/1958621/whats-an-aggregate-root">aggregate root</a>. If your property1, property2, Foo, Bar are related in some way I would extract a new class to handle this.</p>
<pre><code>public class FooBarDetails
{
public string Property1 {get;set;}
public string Property2 {get;set;}
public Foo Foo {get;set;}
public Bar Bar {get;set;}
}
var details = _repo.GetDetails(detailId);
</code></pre>
<p>If Foo and Bar are not related at all it might be an option to introduce a service to compose your FooBarDetails.</p>
<pre><code>FooBarDetails details = _service.GetFooBar(id);
</code></pre>
<p>where <code>GetFooBar(int)</code> would look something like this:</p>
<pre><code>_fooRepo.Get(id);
_barRepo.Get(id);
return new FooBarDetails{Foo = foo, Bar = bar, Property1 = "something", Property2 = "something else"};
</code></pre>
<p>This all is conjecture since the design of the repository really depends on your domain. Using generic terms makes it hard to develop potential relationships between your objects.</p>
<p><strong>Updated</strong>
From the comment if we are dealing with an aggregate root of an Order. An order would have the OrderItem and also the customer that placed the order.</p>
<pre><code>public class Order
{
public List<OrderItem> Items{get; private set;}
public Customer OrderedBy {get; private set;}
//Other stuff
}
public class Customer
{
public List<Orders> Orders{get;set;}
}
</code></pre>
<p>Your repo should return a fully hydrated order object.</p>
<pre><code>var order = _rep.Get(orderId);
</code></pre>
<p>Since your order has all the information needed I would pass the order directly to the view model.</p>
<pre><code>public class OrderDetailsViewModel
{
public Order Order {get;set;}
public OrderDetailsViewModel(Order order)
{
Order = order;
}
}
</code></pre>
<p>Now having a viewmodel with only one item might seem overkill (and it most likely will be at first). If you need to display more items on your view it starts to help.</p>
<pre><code>public class OrderDetailsViewModel
{
public Order Order {get;set;}
public List<Order> SimilarOrders {get;set;}
public OrderDetailsViewModel(Order order, List<Order> similarOrders)
{
Order = order;
SimilarOrders = similarOrders;
}
}
</code></pre> |
5,218,927 | z-index not working with fixed positioning | <p>I have a <code>div</code> with default positioning (i.e. <code>position:static</code>) and a <code>div</code> with a <code>fixed</code> position.</p>
<p>If I set the z-indexes of the elements, it seems impossible to make the fixed element go behind the static element.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code> #over {
width: 600px;
z-index: 10;
}
#under {
position: fixed;
top: 5px;
width: 420px;
left: 20px;
border: 1px solid;
height: 10%;
background: #fff;
z-index: 1;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!DOCTYPE html>
<html>
<body>
<div id="over">
Hello Hello HelloHelloHelloHelloHello Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello
</div>
<div id="under">
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>Or on jsfiddle here: <a href="http://jsfiddle.net/mhFxf/" rel="noreferrer">http://jsfiddle.net/mhFxf/</a></p>
<p>I can work around this by using
<code>position:absolute</code>
on the static element, but can anyone tell me <em>why</em> this is happening?</p>
<p>(There seems to be a similar question to this one, (<a href="https://stackoverflow.com/questions/5182030/fixed-positioning-breaking-z-index">Fixed Positioning breaking z-index</a>) but it doesn't have a satisfactory answer, hence I am asking this here with my example code)</p> | 42,076,701 | 9 | 0 | null | 2011-03-07 11:09:36.48 UTC | 82 | 2022-05-20 04:17:39.22 UTC | 2020-07-29 23:54:49.413 UTC | null | 214,143 | null | 43,965 | null | 1 | 486 | css|z-index | 592,495 | <p>This question can be solved in a number of ways, but really, knowing the stacking rules allows you to find the best answer that works for you.</p>
<h1>Solutions</h1>
<p>The <code><html></code> element is your only stacking context, so just follow the stacking rules inside a stacking context and you will see that elements are stacked in this order</p>
<blockquote>
<ol>
<li>The stacking context’s root element (the <code><html></code> element in this case)</li>
<li>Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)</li>
<li>Non-positioned elements (ordered by appearance in the HTML)</li>
<li>Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)</li>
<li>Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)</li>
</ol>
</blockquote>
<p>So you can</p>
<ol>
<li>set a z-index of -1, for <code>#under</code> positioned -ve z-index appear behind non-positioned <code>#over</code> element</li>
<li>set the position of <code>#over</code> to <code>relative</code> so that rule 5 applies to it </li>
</ol>
<h1>The Real Problem</h1>
<p><strong>Developers should know the following before trying to change the stacking order of elements.</strong></p>
<ol>
<li>When a stacking context is formed
<ul>
<li>By default, the <code><html></code> element is the root element and is the first stacking context</li>
</ul></li>
<li>Stacking order within a stacking context</li>
</ol>
<hr>
<p><a href="https://philipwalton.com/articles/what-no-one-told-you-about-z-index/" rel="noreferrer">The Stacking order and stacking context rules below are from this link</a></p>
<h1>When a stacking context is formed</h1>
<ul>
<li>When an element is the root element of a document (the <code><html></code> element)</li>
<li>When an element has a position value other than static and a z-index value other than auto</li>
<li>When an element has an opacity value less than 1</li>
<li>Several newer CSS properties also create stacking contexts. These include: transforms, filters, css-regions, paged media, and possibly others. <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context</a></li>
<li>As a general rule, it seems that if a CSS property requires rendering in an offscreen context, it must create a new stacking context.</li>
</ul>
<h1>Stacking Order within a Stacking Context</h1>
<p>The order of elements:</p>
<ol>
<li>The stacking context’s root element (the <code><html></code> element is the only stacking context by default, but any element can be a root element for a stacking context, see rules above)
<ul>
<li><strong>You cannot put a child element behind a root stacking context element</strong></li>
</ul></li>
<li>Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)</li>
<li>Non-positioned elements (ordered by appearance in the HTML)</li>
<li>Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)</li>
<li>Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML) </li>
</ol> |
5,387,371 | How to convert minutes to Hours and minutes (hh:mm) in java | <p>I need to convert minutes to hours and minutes in java. For example 260 minutes should be 4:20. can anyone help me how to do convert it.</p> | 5,387,398 | 14 | 2 | null | 2011-03-22 05:51:37.517 UTC | 23 | 2021-07-19 17:19:34.967 UTC | 2021-07-19 17:19:34.967 UTC | null | 642,706 | null | 2,405,181 | null | 1 | 86 | java | 186,648 | <p>If your time is in a variable called <code>t</code></p>
<pre><code>int hours = t / 60; //since both are ints, you get an int
int minutes = t % 60;
System.out.printf("%d:%02d", hours, minutes);
</code></pre>
<p>It couldn't get easier</p>
<p><strong>Addendum from 2021:</strong></p>
<p>Please notice that this answer is about the literal meaning of the question: how to convert an amount of minute to hours + minutes. It has nothing to do with time, time zones, AM/PM...</p>
<p>If you need better control about this kind of stuff, i.e. you're dealing with moments in time and not just an amount of minutes and hours, see <a href="https://stackoverflow.com/a/41800301/133203">Basil Bourque's answer</a> below.</p> |
16,987,692 | can I write a loop for css | <p>I have a scenario where I am getting ID generated like this </p>
<pre><code><div class="containerLength">
<div id="new-1"></div>
<div id="new-2"></div>
<div id="new-3"></div>
<div id="new-4"></div>
</div>
</code></pre>
<p>and so on</p>
<p>is there a way I could write some css to target them through a loop?
maybe something like </p>
<pre><code>#new[i; for(i=0; i<="containerLength.length"; i++)]{
float:left;
}
</code></pre>
<p>Probably I am day dreaming correct? </p> | 16,987,767 | 5 | 9 | null | 2013-06-07 15:25:05.807 UTC | 4 | 2013-06-07 15:42:02.793 UTC | null | null | null | null | 1,315,393 | null | 1 | 12 | css | 46,701 | <p>You can't do loops with pure CSS, however, if you're using something like SASS or LESS then you can do both like:</p>
<p><strong>SASS</strong>:</p>
<pre><code>@for $i from 1 through 4
.#{$class-slug}-#{$i}
width: 60px + $i
</code></pre>
<p><strong>LESS</strong>:</p>
<p><a href="https://stackoverflow.com/questions/7226347/can-you-do-a-javascript-for-loop-inside-of-less-css">Can you do a javascript for loop inside of LESS css?</a></p>
<p>However, assuming you just want to apply the same style to each nested <code>div</code>, you can just do</p>
<pre><code>.containerLength > div{
float: left;
}
</code></pre>
<p>or perhaps create a class named <code>.float-left</code> and apply it to each element you want floated right.</p> |
41,660,150 | How to print the value of variable in java | <pre><code>System.out.printf("The Sum is %d%n" , sum);
</code></pre>
<p>and the error is
The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, int)</p>
<pre><code>System.out.printf("The sum is " + sum);
</code></pre>
<p>Works but What if i need to print</p>
<blockquote>
<p>"The Sum of 5 and 6 is 11"</p>
</blockquote>
<pre><code>System.out.printf("The sum of %d and %d is %d . " ,a,b,sum);
</code></pre>
<p>But got the above error on Eclipse Platform Version: 3.8.1 (Ubuntu)</p> | 41,660,305 | 3 | 3 | null | 2017-01-15 10:34:38.467 UTC | 2 | 2018-09-20 08:56:56.993 UTC | 2017-01-15 10:36:45.727 UTC | null | 335,858 | null | 6,932,421 | null | 1 | 4 | java | 124,533 | <p>If <code>System.out.printf</code> is giving you this error:</p>
<pre><code> The method printf(String, Object[]) in the type PrintStream is not applicable for the arguments (String, int)
</code></pre>
<p>Then you must configure your project for the proper Java version.</p>
<p>Methods with variable arguments were introduced with Java 5.</p>
<p>Alternatively, you could do:</p>
<pre><code>System.out.printf("The Sum of %d and %d is %d\n", new Object[] {a, b, sum});
</code></pre> |
41,627,631 | Exclude/overwrite npm-provided typings | <p>I've got an npm package with badly written, out of date typings. I've written my own typings and now I'm wondering if I can somehow exclude the original typings from the npm package. It's not a simple extension of interfaces, the originals are basically garbage at this point.</p>
<p>Using the exclude list in tsconfig.json does not work for this purpose of course, since it still loads files from node_modules even if you exclude that folder.</p> | 41,641,001 | 2 | 3 | null | 2017-01-13 04:56:28.867 UTC | 10 | 2018-06-18 10:04:14.167 UTC | null | null | null | null | 727,944 | null | 1 | 35 | typescript|typescript-typings | 10,946 | <p>You can get the desired behavior with the paths option in the tsConfig
It could look something like this:</p>
<pre><code>{
"compilerOptions": {
...
"paths": {
"*": [
"src/*",
"declarations/*"
]
}
},
...
}
</code></pre>
<p>With this config typescript looks for modules in src (there should be all the app source) and also in declarations, in the declarations folder I usually place my extra needed declarations.</p>
<p>To override the typings of a node module there are two options:</p>
<ol>
<li><p>place a folder named like the module inside the declarations folder, containing a file called index.d.ts for the typings</p></li>
<li><p>place a declaration file, named like the module, inside the declarations folder</p></li>
</ol>
<p>As a working example you can take a look at this repo <a href="https://github.com/kaoDev/react-ts-sample" rel="noreferrer">https://github.com/kaoDev/react-ts-sample</a></p>
<p>An important hint by <a href="https://stackoverflow.com/users/1217387/bernhard-koenig">Bernhard Koenig</a>:</p>
<blockquote>
<p>The order of the paths matters. I had to put the path with my overrides before the path with the original type definitions so my overrides get picked up first. – Bernhard Koenig</p>
</blockquote> |
12,463,091 | iOS background Location not sending http request | <p>My app needs to track the users location in the background but it is failing to send a 'get' request. The http request gets sent immediately when the app comes to the foreground. I am using RestKit for all my network requests and I followed <a href="http://www.mindsizzlers.com/2011/07/ios-background-location/" rel="nofollow noreferrer">this tutorial</a> to setup my background locations service.
In my applicationDidEnterBackground </p>
<pre><code>-(void)applicationDidEnterBackground:(UIApplication *)application
{
self.bgLocationManager = [[CLLocationManager alloc] init];
self.bgLocationManager.delegate = self;
[self.bgLocationManager startMonitoringSignificantLocationChanges];
NSLog(@"Entered Background");
}
</code></pre>
<p>and I stopMonitoringSignificantLocationChange in my applicationDidBecomeActive delegate</p>
<p>This is my locationManager delegate where I accept the new updated location and send to my server</p>
<pre><code>-(void) locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
NSLog(@"I am in the background");
bgTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:
^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
// ANY CODE WE PUT HERE IS OUR BACKGROUND TASK
NSString *currentLatitude = [[NSString alloc]
initWithFormat:@"%g",
newLocation.coordinate.latitude];
NSString *currentLongitude = [[NSString alloc]
initWithFormat:@"%g",
newLocation.coordinate.longitude];
NSString *webToken = [[NSUserDefaults standardUserDefaults] stringForKey:@"userWebToken"];
NSLog(@"I am in the bgTask, my lat %@", currentLatitude);
NSDictionary *queryParams;
queryParams = [NSDictionary dictionaryWithObjectsAndKeys:webToken, @"auth_token", currentLongitude, @"lng", currentLatitude, @"lat", nil];
RKRequest* request = [[RKClient sharedClient] post:@"/api/locations/background_update" params:queryParams delegate:self];
//default is RKRequestBackgroundPolicyNone
request.backgroundPolicy = RKRequestBackgroundPolicyContinue;
// AFTER ALL THE UPDATES, close the task
if (bgTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}
</code></pre>
<p>The network requests works as planned but it will not get called in the background. Is there any additional steps I need? In my info.plist I have the Required Background modes key and location-services as the value.</p>
<p>EDIT</p>
<p>I also referred to <a href="https://stackoverflow.com/questions/5394880/can-iphone-app-woken-in-background-for-significant-location-change-do-network-ac">this past SO answer</a>. I ran some tests with putting logs throughout the didUpdateToLocation call and they were all called but the 'get' request was not sent. Instead when I finally launch the app to the foreground it sent all the built of network requests (over 10).</p>
<p>EDIT (2)
I added RKRequestBackgroundPolicyContinue to my request but it did not change my results. (As you can see <a href="https://bitbucket.org/deger/restkit/src/91482ebbbe9a/Docs/MobileTuts%20Advanced%20RestKit/Advanced_RestKit_Tutorial.md" rel="nofollow noreferrer">here</a> in the background upload/download for restkit). I see Restkit initialize the host but fails to send the request until the app becomes active.</p>
<p>ANSWER</p>
<p>RestKit must be doing something that is prohibited in the background. Using an NSURLRequest works perfectly.</p>
<pre><code>NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.example.com/api/locations/background_update"]];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:jsonData];
NSHTTPURLResponse *response = nil;
[NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
</code></pre>
<p>It is fine to use a synchronous request since there is no UI to disrupt with background tasks </p> | 12,558,104 | 3 | 3 | null | 2012-09-17 16:05:43.67 UTC | 12 | 2012-09-25 17:04:06.417 UTC | 2017-05-23 12:32:42.543 UTC | null | -1 | null | 976,975 | null | 1 | 12 | iphone|ios|ios5|nsurlconnection|restkit | 5,405 | <p>Re-creating original suggestion as an answer</p>
<blockquote>
<p>Have your try replacing your restKit calls with a stock synchronous NSURLConnection? – dklt Sep 20 </p>
</blockquote> |
12,072,500 | Apache CXF - None of the policy alternatives can be satisfied | <p>I'm trying to create client of 3rd party WS. My app is running on JBoss AS 6 (with its Apache CXF 2.3.1 stack). I generated client code by wsconsume (wsdl2java). When I tried to connect to WS a got exception:</p>
<pre><code>No assertion builder for type http://schemas.microsoft.com/ws/06/2004/policy/http}BasicAuthentication registered.
Exception in thread "main" org.apache.cxf.ws.policy.PolicyException: None of the policy alternatives can be satisfied.
</code></pre>
<p>Auth part of WSDL looks like:</p>
<pre><code><wsp:Policy wsu:Id="abc_ssl_policy">
<wsp:ExactlyOne>
<wsp:All>
<http:BasicAuthentication
xmlns:http="http://schemas.microsoft.com/ws/06/2004/policy/http" />
<sp:TransportBinding
xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
<wsp:Policy>
<sp:TransportToken>
<wsp:Policy>
<sp:HttpsToken RequireClientCertificate="false" />
</wsp:Policy>
</sp:TransportToken>
<sp:AlgorithmSuite>
<wsp:Policy>
<sp:Basic256 />
</wsp:Policy>
</sp:AlgorithmSuite>
<sp:Layout>
<wsp:Policy>
<sp:Strict />
</wsp:Policy>
</sp:Layout>
</wsp:Policy>
</sp:TransportBinding>
</wsp:All>
</wsp:ExactlyOne>
</wsp:Policy>
</code></pre>
<p>Client code:</p>
<pre><code>@WebServiceClient(name = "Abc",
wsdlLocation = "https://hiddendomain.com/abc/abc.svc?wsdl",
targetNamespace = "http://tempuri.org/")
public class Abc extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://tempuri.org/", "Abc");
public final static QName AbcSsl = new QName("http://tempuri.org/", "abc_ssl");
static {
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user", "pas".toCharArray());
}
});
URL url = null;
try {
url = new URL("https://hiddendomain.com/abc/abc.svc?wsdl");
} catch (MalformedURLException e) {
java.util.logging.Logger.getLogger(DistrInfo.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "...");
}
WSDL_LOCATION = url;
}
</code></pre>
<p>Exception is thrown whe I try get Conduit:</p>
<pre><code> Client client = ClientProxy.getClient(port);
HTTPConduit con = (HTTPConduit) client.getConduit(); <- exception
</code></pre>
<p>I suspect that is because of non-standard MS policy and I need proper Intercerptor to handle this policy, but can somebody show me a way how to do it?</p>
<p>I dont even no, where I should put my HTTPS credentials to auth (I can't get conduit)</p> | 12,090,592 | 3 | 0 | null | 2012-08-22 11:52:40.857 UTC | 9 | 2016-09-29 09:54:05.127 UTC | null | null | null | null | 1,616,779 | null | 1 | 14 | java|cxf | 33,884 | <p>The problem gone when I used this code:</p>
<pre><code>import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
...
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
//factory.getInInterceptors().add(new LoggingInInterceptor());
//factory.getOutInterceptors().add(new LoggingOutInterceptor());
factory.setServiceClass(IAbc.class);
factory.setAddress("https://hiddendomain.com/abc/abc.svc/soap"); <- must be /soap there, otherwise 404
IAbc info = (IAbc) factory.create();
Client client = ClientProxy.getClient(info);
HTTPConduit http = (HTTPConduit) client.getConduit();
http.getAuthorization().setUserName("user");
http.getAuthorization().setPassword("pass");
String abc = info.abc();
</code></pre> |
12,131,789 | How to disable subtitles decoding in ffmpeg | <p>I'm trying to convert some video file containing <em>video</em>, <em>audio</em> and <em>subtitles</em> streams into another format using <strong>FFMpeg</strong>. However, ffmpeg complains about the <em>subtitles</em> format - it cannot decode the stream. Since I don't need this subtitles stream, I'd like to know how can I disable subtitles stream decoding during conversion?</p> | 12,175,153 | 3 | 1 | null | 2012-08-26 16:27:01.89 UTC | 10 | 2020-06-16 21:18:35.89 UTC | null | null | null | null | 1,091,054 | null | 1 | 35 | video|stream|ffmpeg|video-encoding|subtitle | 50,464 | <p>I've finally found an answer.</p>
<p>There is such option as <code>-sn</code> which disables subtitles decoding from input stream. Also there are analogous options for audio and video decoding: <code>-an</code> and <code>-vn</code> respectively.</p>
<p>It also turned out that there is another way to achieve this. One may use the <code>-map</code> option to select which streams are to be decoded. So omitting the subtitles stream among the <code>-map</code> options does the job.</p>
<p>For example, if one has a movie file with 3 streams:</p>
<ul>
<li>Stream 0: video</li>
<li>Stream 1: audio</li>
<li>Stream 2: subtitles</li>
</ul>
<p>the converting command for FFmpeg may look as follows:</p>
<pre><code>ffmpeg -i <input file> -sn -vcodec <video codec> -acodec <audio codec> <output file>
</code></pre>
<p>or</p>
<pre><code>ffmpeg -i <input file> -vcodec <video codec> -acodec <audio codec> -map 0:0 -map 0:1 <output file>
</code></pre>
<p>The former command line <em>deselects</em> the subtitles stream (probably all of them, if there are several) while the latter one <em>selects</em> only the necessary streams to decode.</p> |
12,422,473 | @Nullable input in Google Guava Function interface triggers FindBugs warning | <p>The <code>com.google.common.base.Function</code> interface (from <a href="http://code.google.com/p/guava-libraries/wiki/Release13">Google Guava</a>) defines <code>apply</code> as:</p>
<p><code>@Nullable T apply(@Nullable F input);</code> </p>
<p>The method has the following javadoc note:</p>
<p><code>@throws NullPointerException if {@code input} is null and this function does not accept null arguments</code>.</p>
<p>FindBugs complains about my implementation of Function:</p>
<pre><code>private static final class Example implements Function<MyBean, String> {
@Override
@Nullable
public String apply(@Nullable MyBean input) {
if (null == input) {
throw new NullPointerException();
}
return input.field;
}
}
</code></pre>
<p>with a <strong>high-priority</strong> warning:</p>
<blockquote>
<p>NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE, Priority: High</p>
<p>input must be nonnull but is marked as nullable</p>
<p>This parameter is always used in a way that requires it to be nonnull, but the parameter is explicitly annotated as being Nullable. Either the use of the parameter or the annotation is wrong.</p>
</blockquote>
<p>My function does not support <code>null</code> inputs and an exception is thrown if that is the case. If I understand correctly, FindBugs treats this as a requirement for non-null.</p>
<p>To me it looks like a contradiction: input is @Nullable but method @throws NullPointerException when it is null. Am I missing something? </p>
<p>The only way to get rid of the warning that I can see is manual suppression. (Guava code is out of my control, obviously).</p>
<p>Who is wrong about the usage of @Nullable annotation, FindBugs, Guava or myself?</p> | 12,422,809 | 3 | 2 | null | 2012-09-14 10:13:14.293 UTC | 9 | 2017-07-28 09:39:54.843 UTC | 2012-09-14 10:31:39.12 UTC | null | 954,570 | null | 954,570 | null | 1 | 35 | java|guava|findbugs | 15,498 | <p>Your implementation is wrong ;)</p>
<p>Basically docs says (I'll paraphrase and emphasise):</p>
<blockquote>
<p><code>@throws NullPointerException</code> if <code>input</code> is null and <strong>the concrete
function implementation</strong> does not accept null arguments</p>
</blockquote>
<p>By implementing your function you must decide if it accepts nulls or not. In first case:</p>
<pre><code>private static final class Example implements Function<MyBean, String> {
@Override
@Nullable
public String apply(@Nullable MyBean input) {
return input == null ? null : input.field;
}
}
</code></pre>
<p>In second case:</p>
<pre><code>private static final class Example implements Function<MyBean, String> {
@Override
@Nullable
public String apply(MyBean input) {
if (null == input) {
throw new NullPointerException();
}
return input.field;
}
}
</code></pre>
<p>In both examples returning null is allowed.</p>
<p><strong>EDIT:</strong></p>
<p>Note that Guava uses <code>@javax.annotation.ParametersAreNonnullByDefault</code> on all packages, hence if <code>@Nullable</code> is present it means "suspend global <code>@Nonnull</code> and allow nulls here" and if not it means "nulls forbidden here". </p>
<p>That said, you may want use <code>@Nonnull</code> annotation on your argument or <code>@ParametersAreNonnullByDefault</code> in package to tell FindBugs Function's argument can't be null.</p>
<p><strong>EDIT 2:</strong></p>
<p>Turns out <a href="http://code.google.com/p/guava-libraries/issues/detail?id=920" rel="noreferrer">this case is known issue</a>, see comment #3 (from Guava's lead dev Kevin Bourrillion, about his conversation with Bill Pugh, Findbugs' lead):</p>
<blockquote>
<p>My reference was a series of in-person conversations with Bill Pugh.
He asserted unambiguously that <code>@Nullable</code> means only that some subtypes
<em>might</em> accept null. And this seems to be borne out by findbugs for us -- our code passes the nullability checks pretty cleanly (though we
should check again since this particular Function change was made).</p>
</blockquote> |
12,334,316 | Give the Python Terminal a Persistent History | <p>Is there a way to tell the interactive Python shell to preserve its history of executed commands between sessions?</p>
<p>While a session is running, after commands have been executed, I can arrow up and access said commands, I'm just wondering if there is some way for a certain number of these commands to be saved until the next time I use the Python shell.</p>
<p>This would be very useful since I find myself reusing commands in a session, that I used at the end of the last session.</p> | 12,334,344 | 3 | 1 | null | 2012-09-08 20:43:36.357 UTC | 7 | 2018-07-17 08:22:42.173 UTC | 2012-09-08 20:44:26.337 UTC | null | 707,111 | null | 1,378,292 | null | 1 | 37 | python|linux|python-2.7 | 11,399 | <p>Sure you can, with a small startup script. From <a href="http://docs.python.org/tutorial/interactive.html" rel="noreferrer">Interactive Input Editing and History Substitution</a> in the python tutorial:</p>
<pre><code># Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it: "export PYTHONSTARTUP=~/.pystartup" in bash.
import atexit
import os
import readline
import rlcompleter
historyPath = os.path.expanduser("~/.pyhistory")
def save_history(historyPath=historyPath):
import readline
readline.write_history_file(historyPath)
if os.path.exists(historyPath):
readline.read_history_file(historyPath)
atexit.register(save_history)
del os, atexit, readline, rlcompleter, save_history, historyPath
</code></pre>
<p>From Python 3.4 onwards, <a href="https://docs.python.org/3/whatsnew/3.4.html#other-improvements" rel="noreferrer">the interactive interpreter supports autocompletion and history out of the box</a>:</p>
<blockquote>
<p>Tab-completion is now enabled by default in the interactive interpreter on systems that support <code>readline</code>. History is also enabled by default, and is written to (and read from) the file <code>~/.python-history</code>.</p>
</blockquote> |
12,378,271 | What does an object look like in memory? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/422830/structure-of-a-c-object-in-memory-vs-a-struct">Structure of a C++ Object in Memory Vs a Struct</a><br>
<a href="https://stackoverflow.com/questions/1632600/memory-layout-c-objects">memory layout c++ objects</a> </p>
</blockquote>
<p>This is probably a really dumb question, but I will ask anyway. I am curious what an object looks like in memory. Obviously it would have to have all of its member data in it. I assume that functions for an object would not be duplicated in memory (or maybe I am wrong?). It would seem wasteful to have 999 objects in memory all with the same function defined over and over. If there is only 1 function in memory for all 999 objects, then how does each function know who's member data to modify (I specifically want to know at the low level). Is there an object pointer that gets sent to the function behind the scenes? Perhaps it is different for every compiler?</p>
<p>Also, how does the static keyword affect this? With static member data, I would think that all 999 objects would use the exact same memory location for their static member data. Where does this get stored? Static functions I guess would also just be one place in memory, and would not have to interact with instantiated objects, which I think I understand.</p> | 12,378,370 | 5 | 5 | null | 2012-09-11 21:36:22.637 UTC | 38 | 2021-06-07 13:17:32.2 UTC | 2017-05-23 12:10:15.51 UTC | null | -1 | null | 308,843 | null | 1 | 49 | c++ | 42,934 | <p>Static class members are treated almost exactly like global variables / functions. Because they are not tied to an instance, there is nothing to discuss regarding memory layout.</p>
<p>Class member <em>variables</em> are duplicated for each instance as you can imagine, as each instance can have its own unique values for every member variable.</p>
<p>Class member <em>functions</em> only exist once in a code segment in memory. At a low level, they are just like normal global functions but they receive a pointer to <code>this</code>. With Visual Studio on x86, it's via <code>ecx</code> register using <a href="http://en.wikipedia.org/wiki/X86_calling_conventions#thiscall"><code>thiscall</code></a> calling convention.</p>
<p>When talking about virtual functions, polymorphism, then the memory layout gets more complicated, introducing a "<a href="http://en.wikipedia.org/wiki/Virtual_method_table">vtable</a>" which is basically a bunch of function pointers that define the topography of the class instance.</p> |
12,539,006 | Tooltips for mobile browsers | <p>I currently set the <code>title</code> attribute of some HTML if I want to provide more information:</p>
<pre><code><p>An <span class="more_info" title="also called an underscore">underline</span> character is used here</p>
</code></pre>
<p>Then in CSS:</p>
<pre><code>.more_info {
border-bottom: 1px dotted;
}
</code></pre>
<p>Works very nice, visual indicator to move the mouse over and then a little popup with more information. But on mobile browsers, I don't get that tooltip. <code>title</code> attributes don't seem to have an effect. What's the proper way to give more information on a piece of text in a mobile browser? Same as above but use Javascript to listen for a click and then display a tooltip-looking dialog? Is there any native mechanism?</p> | 12,538,532 | 11 | 8 | null | 2012-09-21 19:52:02.833 UTC | 27 | 2021-07-02 09:28:46.037 UTC | null | null | null | at. | 326,389 | null | 1 | 77 | mobile|mobile-website|tooltip|html | 102,524 | <p>You can fake the title tooltip behavior with Javascript. When you click/tab on an element with a <code>title</code> attribute, a child element with the title text will be appended. Click again and it gets removed.</p>
<p>Javascript (done with jQuery):</p>
<pre><code>$("span[title]").click(function () {
var $title = $(this).find(".title");
if (!$title.length) {
$(this).append('<span class="title">' + $(this).attr("title") + '</span>');
} else {
$title.remove();
}
});
</code></pre>
<p>CSS:</p>
<pre><code>.more_info {
border-bottom: 1px dotted;
position: relative;
}
.more_info .title {
position: absolute;
top: 20px;
background: silver;
padding: 4px;
left: 0;
white-space: nowrap;
}
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/xaAN3/" rel="noreferrer">http://jsfiddle.net/xaAN3/</a></p> |
3,676,004 | Java API for encrypting / decrypting pdf files | <p>I need to encrypt and decrypt pdf files. Is there a free or low cost Java API that does that ? Basically I need to hide files from normal users. Any other suggestion on achieving that programatically ?</p>
<p>Thanks,
Deep</p> | 3,676,337 | 3 | 1 | null | 2010-09-09 11:17:44.96 UTC | 9 | 2017-12-13 06:00:07.997 UTC | null | null | null | null | 306,631 | null | 1 | 9 | java|pdf|encryption | 23,100 | <p>Using <a href="http://itextpdf.com/" rel="noreferrer">iText</a>:</p>
<pre><code> // Assuming you provide the following yourself:
File inputFile;
File outputFile;
String userPassword;
String ownerPassword;
// A bit-field containing file permissions.
int permissions = PDFWriter.ALLOW_PRINTING | PDFWriter.ALLOW_COPY;
PdfReader reader = new PdfReader(inputFile);
PdfEncryptor.encrypt(reader, new FileOutputStream(outputFile),
ENCRYPTION_AES128, userPassword, ownerPassword,
permissions);
</code></pre>
<p>Here's the API for <a href="http://api.itextpdf.com/com/itextpdf/text/pdf/PdfEncryptor.html" rel="noreferrer">PDFEncryptor</a> and <a href="http://api.itextpdf.com/com/itextpdf/text/pdf/PdfWriter.html" rel="noreferrer">PDFWriter</a> (for the permissions).</p> |
3,363,767 | How do you virus scan a file being uploaded to your java webapp as it streams? | <p>Basically, I want to virus scan files as they are uploaded (before writing them to disk) to a web app. </p>
<p>In particular, I'd like to integrate with "McAfee VirusScan Enterprise" (latest version).</p>
<p>From a design and maintenance perspective, would it perhaps be better to scan certain paths at the firewall using a third party product? That way the web app would not have to concern itself with virus scanning. So as to minimize overhead, do typical virus scanning firewalls let you specify URL patterns as well as a particular POST data pattern. This of course would not work if it's an HTTPS site (unless there's some way around that).</p>
<p><a href="https://stackoverflow.com/questions/908356/calling-the-mcafee-virus-scan-engine">This post from stackoverflow</a> seems to suggest that an SDK from McAfee is no longer available, but are there open source alternatives?</p> | 3,363,900 | 3 | 3 | null | 2010-07-29 14:50:03.023 UTC | 19 | 2013-03-14 19:22:12.297 UTC | 2017-05-23 11:33:13.693 UTC | null | -1 | null | 39,489 | null | 1 | 29 | java|web-applications|antivirus|mcafee|antivirus-integration | 43,179 | <p>Check out Clamv ( <a href="http://www.clamav.net/" rel="noreferrer">http://www.clamav.net/</a> )
It is a open source anti-virus, and you can scan a stream.
So you do not need to save the file for scanning it.</p>
<p><a href="http://linux.die.net/man/1/clamscan" rel="noreferrer">http://linux.die.net/man/1/clamscan</a></p>
<p>Scan a data stream:
cat testfile | clamscan - </p>
<p>So it is quite easy, start the clamscan process with the - arg. write the file content to the stdin, and wait for the result code.</p>
<p>During your testing, you can use the EICAR file, which is a file dedicated for checking if an anti-virus is working. <a href="http://en.wikipedia.org/wiki/EICAR_test_file" rel="noreferrer">http://en.wikipedia.org/wiki/EICAR_test_file</a></p> |
3,638,953 | Do TCP connections get moved to another port after they are opened? | <p>If a TCP socket server listens on port 28081 for incoming connections and then accepts a connection and start receiving data. Is the port that data is coming into still 28081 or does the port get changed.</p>
<p>for example what port does the incoming data come to in the pseudo code below? Is it still 28081 or does the OS assign a new port?:</p>
<pre><code>bind
listen (on port 28081)
while 1
fd = accept
fork
if child process incoming data
</code></pre> | 3,639,017 | 3 | 1 | null | 2010-09-03 19:28:56.587 UTC | 18 | 2012-09-19 16:26:27.497 UTC | 2010-09-04 03:30:54.21 UTC | null | 134,633 | null | 234,789 | null | 1 | 32 | c|sockets|networking|tcp | 19,896 | <p>A TCP connection is uniquely identified by two <code>(IP address, TCP port)</code> tuples (one for each endpoint). So by definition, one can't <em>move</em> a port or IP address of a connection but just open a different one. </p>
<p>If the server binds to port 28081 all accepted connections will have this port on the server side (although they most likely will have varying port numbers on the client side).</p>
<p>For example, if two processes from the same client machine will connect to the same server, the <code>IP address</code> and <code>TCP port</code> on the server side will be the same for both connections. On the client side however, they will have two different port numbers allowing the operating system on both sides to uniquely identify which process and file descriptor the received TCP packets should be assigned to. </p> |
19,239,743 | Create multiple tables using single .sql script file | <p>I have created multiple table in oracle xe 11g database and i have saved the script for each table in different .sql file. But i need to create all tables at once using single .sql file.
I tried to run below script but it is creating only once table at once.</p>
<pre><code>CREATE TABLE ACCOUNT_DETAILS_TB
(
CUSTOMER_ID VARCHAR2(20) NOT NULL
, ACCOUNT_ID VARCHAR2(20) NOT NULL
);
CREATE TABLE ADDRESS_DETAILS_TB
(
ACCOUNT_ID VARCHAR2(20) NOT NULL
, ADDRESS_ID VARCHAR2(20) NOT NULL
);
</code></pre> | 19,239,848 | 2 | 8 | null | 2013-10-08 05:27:02.077 UTC | null | 2013-10-08 09:23:39.587 UTC | 2013-10-08 09:23:39.587 UTC | null | 1,568,755 | null | 1,568,755 | null | 1 | 11 | sql|database|oracle|oracle11g|oracle-sqldeveloper | 93,642 | <p>You need to separate the create table scripts with <code>/</code> or end the command with <code>;</code>, Try like this,</p>
<pre><code>CREATE TABLE ACCOUNT_DETAILS_TB ( CUSTOMER_ID VARCHAR2(20) NOT NULL , ACCOUNT_ID VARCHAR2(20) NOT NULL )
/
CREATE TABLE ADDRESS_DETAILS_TB ( ACCOUNT_ID VARCHAR2(20) NOT NULL , ADDRESS_ID VARCHAR2(20) NOT NULL )
/
</code></pre>
<p>OR</p>
<pre><code>CREATE TABLE ACCOUNT_DETAILS_TB ( CUSTOMER_ID VARCHAR2(20) NOT NULL , ACCOUNT_ID VARCHAR2(20) NOT NULL );
CREATE TABLE ADDRESS_DETAILS_TB ( ACCOUNT_ID VARCHAR2(20) NOT NULL , ADDRESS_ID VARCHAR2(20) NOT NULL );
</code></pre> |
8,425,195 | Vertically aligning my div within the body | <p>Is there a CSS way to vertically align my div within the body element?</p>
<p>The thing is my div will have a different height each time, so its not constant.</p>
<p>These are the things I've tried but they dont work:</p>
<pre><code>body { vertical-align: middle; }
#mainContent {
vertical-align: middle;
}
// Also this
body { margin-top: 20%; margin-bottom: 20%; }
</code></pre> | 8,440,862 | 5 | 7 | null | 2011-12-08 01:54:29.2 UTC | 11 | 2018-04-29 21:51:49.647 UTC | null | null | null | null | 972,202 | null | 1 | 4 | javascript|html|css | 23,242 | <p>Honestly, my opinion is often that if you're doing vertical alignment you should still be using a table. I know it's often frowned upon, but it is still the simplest and cleanest way to vertically center something. </p>
<p>HTML</p>
<pre><code><table>
<tbody>
<tr>
<td>
<div>Your DIV here.</div>
</td>
</tr>
</tbody>
</table>
</code></pre>
<p>CSS</p>
<pre><code>td {vertical-align: middle;}
</code></pre> |
22,056,153 | Designing UICollectionView cells in nib with Interface Builder (without storyboard) | <p>I am trying to design a custom <code>UICollectionViewCell</code> prototype (in Xcode 5.0.2), however Interface Builder doesn't let me add a cell to my <code>UICollectionView</code> while designing a nib. I can set the number of items (cells) and Interface Builder creates and displays cells perfectly if I'm using storyboard, but I can't add a cell to my collection view in a nib. I've tried:</p>
<ul>
<li>Drag and dropping collection view cell into collection view manually from the object library. (fails: doesn't let me drop the cell anywhere in my view)</li>
<li>Creating my collection view with cells in storyboard and copy-pasting the whole view into nib. (fails: collection view is copied but the cell is gone)</li>
<li>Creating my collection view with cells in storyboard, opening the storyboard as source code, finding my collection view cells, copying the relevant XML, opening my nib as source code, pasting it inside my collection view in XML. (fails: unable to open the nib in Interface Builder, it gives errors. When I remove the cell from source code, it opens again. Do <em>not</em> try this if you don't know what you are doing.)</li>
</ul>
<p>I've also seen several questions about the same issue:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/8100247/is-it-possible-to-create-prototype-cells-in-interface-builder-without-story-boar">Is it possible to create prototype cells in Interface Builder without story boards?</a></li>
<li><a href="https://stackoverflow.com/questions/19002793/custom-header-in-uicollectionview-with-interface-builder-without-storyboard">Custom Header in UICollectionView with Interface Builder without Storyboard</a></li>
<li><a href="https://stackoverflow.com/questions/8574188/prototype-cells-in-a-nib-instead-of-a-storyboard">Prototype Cells in a nib instead of a storyboard</a></li>
</ul>
<p>They all point out to doing them programatically and/or using another nib for the cell. I know how to do them, but is there any way to design the collection view cell, inside a collection view <em>inside the same view</em> in a nib, just as in storyboard? Why doesn't Interface Builder let me do that in nib where it allows (and even encourages) perfectly using storyboard?</p> | 25,143,037 | 1 | 5 | null | 2014-02-26 23:53:32.583 UTC | 3 | 2014-08-05 20:58:40.017 UTC | 2017-05-23 12:17:26.303 UTC | null | -1 | null | 811,405 | null | 1 | 29 | xcode|interface-builder|uicollectionview|nib|uicollectionviewcell | 14,373 | <p>The simple answer is no, this cannot be done. Think of a storyboard as a collection of XIBs. A XIB simply defines the facets of a particular view so that it can be constructed at runtime.</p>
<p>Regarding collection views and their storyboard implementations, it's important to understand that a storyboard allows for nesting of viewcontrollers and defining collection views with their XIBs because that keeps the fundamental paradigm of storyboards coherent. Since a storyboard is the means of defining the "story" or scene of an application it is only natural that it allows for the declaration of the reusable views for use inside a collection view.</p>
<p>The same cannot be said for XIBs because the fundamental idea behind XIBs is in reusability. This will allow a collection view defined in a XIB to have any cells used with it as long as the controller registers these classes with the collection view. This way you get the benefit of reusability as another controller can use the same XIB and register different cells etc.</p>
<p>So I think it would be far more confusing to allow for the declaration of the supported cells of a collection view inside a XIB since that breaks the single responsibility principle(if it can be called that) that XIBs aspire to. </p>
<p>Your best solution would be to define a custom collection view subclass that registers the relevant cells on instantiation, and then use this class in your XIB.</p> |
11,117,511 | There was an exception running the extensions specified in the config file. Maximum request length exceeded | <p>I have a report part which deployed perfectly every time I made any changes until today.</p>
<p>The report has around 20 links, and an image on it.</p>
<p>I have added a table to it today, clicked deploy and it gave me the following error:</p>
<pre><code>Error 1 There was an exception running the extensions specified in the config file. ---> Maximum request length exceeded. 0 0
</code></pre>
<p>As I say, all I have done is added a table to it and that has caused mayhem. WHY?</p> | 11,117,735 | 3 | 0 | null | 2012-06-20 10:22:11.323 UTC | 1 | 2021-11-24 14:50:11.547 UTC | null | null | null | null | 1,025,915 | null | 1 | 13 | sql-server|sql-server-2008|reporting-services|bids | 41,618 | <p>I faced this problem recently. There is a property called <code>maxRequestLength</code> which needs to be increased in the machine and <code>web.config</code> file which is in the following location.</p>
<pre><code>C:\Program Files\Microsoft SQL Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer
</code></pre>
<p>For further reference, please refer to <a href="http://www.bidn.com/blogs/MikeMollenhour/ssis/248/reporting-services-2008-error-maximum-request-length-exceeded" rel="noreferrer">this article</a>.</p> |
11,168,916 | weak or strong for IBOutlet and other | <p>I have switched my project to ARC, and I don't understand if I have to use <code>strong</code> or <code>weak</code> for IBOutlets. Xcode do this: in interface builder, if a create a <code>UILabel</code> for example and I connect it with assistant editor to my <code>ViewController</code>, it create this:</p>
<pre><code>@property (nonatomic, strong) UILabel *aLabel;
</code></pre>
<p>It uses the <code>strong</code>, instead I read a tutorial on RayWenderlich website that say this:</p>
<blockquote>
<p>But for these two particular properties I have other plans. Instead of
<code>strong</code>, we will declare them as <code>weak</code>.</p>
</blockquote>
<pre><code>@property (nonatomic, weak) IBOutlet UITableView *tableView;
@property (nonatomic, weak) IBOutlet UISearchBar *searchBar;
</code></pre>
<blockquote>
<p><code>Weak</code> is the recommended relationship for all <em>outlet</em> properties.
These view objects are already part of the view controller’s view
hierarchy and don’t need to be retained elsewhere. The big advantage
of declaring your outlets <code>weak</code> is that it saves you time writing the
viewDidUnload method.</p>
<p>Currently our <code>viewDidUnload</code> looks like this:</p>
</blockquote>
<pre><code>- (void)viewDidUnload
{
[super viewDidUnload];
self.tableView = nil;
self.searchBar = nil;
soundEffect = nil;
}
</code></pre>
<blockquote>
<p>You can now simplify it to the following:</p>
</blockquote>
<pre><code>- (void)viewDidUnload
{
[super viewDidUnload];
soundEffect = nil;
}
</code></pre>
<p>So use <code>weak</code>, instead of the <code>strong</code>, and remove the set to nil in the <code>videDidUnload</code>, instead Xcode use the <code>strong</code>, and use the <code>self... = nil</code> in the <code>viewDidUnload</code>.</p>
<p>My question is: when do I have to use <code>strong</code>, and when <code>weak</code>?
I want also use for deployment target iOS 4, so when do I have to use the <code>unsafe_unretain</code>? Anyone can help to explain me well with a small tutorial, when use <code>strong</code>, <code>weak</code> and <code>unsafe_unretain</code> with ARC?</p> | 11,170,327 | 2 | 0 | null | 2012-06-23 10:55:01.87 UTC | 33 | 2015-01-22 05:22:04.987 UTC | 2015-01-22 05:22:04.987 UTC | null | 1,400,768 | null | 678,833 | null | 1 | 31 | ios|ios5|automatic-ref-counting|weak-references|strong-references | 22,899 | <p><strong>A rule of thumb</strong></p>
<p><em>When a parent has a reference to a child object, you should use a <code>strong</code> reference. When a child has a reference to its parent object, you should use a <code>weak</code> reference or a <code>unsafe_unretained</code> one (if the former is not available). A typical scenario is when you deal with delegates. For example, a <code>UITableViewDelegate</code> doesn't retain a controller class that contains a table view.</em></p>
<p><img src="https://i.stack.imgur.com/Qheyl.jpg" alt="enter image description here"></p>
<p>Here a simple schema to present the main concepts.</p>
<p>Suppose first A,B and C are <code>strong</code> references. In particular, C has a <code>strong</code> ref to its parent. When obj1 is released (somewhere), the A reference doesn't exist anymore but you have a leak since there is a cycle between obj1 and obj2. Speaking in terms of retain counts (<strong>only for explain purposes</strong>), obj1 has a retain count of 2 (obj2 has a <code>strong</code> reference to it), while obj2 has a retain count of 1. If obj1 is released, its retain count is now 1 and its <code>dealloc</code> method is not called. obj1 and obj2 still remain in memory but no one has a reference to them: <strong>Leak</strong>.</p>
<p>On the contary, if only A and B are <code>strong</code> refs and C is qualified as <code>weak</code> all is ok. You have no leaks. In fact, when obj1 is released, it also releases obj2. Speaking in terms of retain counts, obj1 has a retain count of 1, obj2 has a retain count of 1. If obj1 is released, its retain count is now 0 and its <code>dealloc</code> method is called. obj1 and obj2 are removed from memory.</p>
<p><strong>A simple suggestion: Start to think in terms of object graph when you deal with ARC.</strong></p>
<p>About your first question, both solutions are valid when you deal with XIBs. In general <code>weak</code> references are used when you deal with memory cycles.
Concerning XIBs files, if you use <code>strong</code> you need to set <code>nil</code> in <code>viewDidUnload</code> since if you don't do it, in memory low conditions, you could cause unexpected leaks. You don't release them in <code>dealloc</code> because ARC will do it for you.
<code>weak</code> instead doesn't need that treatment since, when the target object is destroyed, those values are set as <code>nil</code> automatically. No dangling pointers anymore.</p>
<p>If you are interested in, I really suggest you to read <a href="http://www.mikeash.com/pyblog/friday-qa-2012-04-13-nib-memory-management.html" rel="nofollow noreferrer">friday-qa-2012-04-13-nib-memory-management</a> by <strong>Mike Ash</strong>.</p>
<p>About your second question, if you need to support iOS 4, instead of <code>weak</code> you have to use <code>unsafe_unretained</code>.</p>
<p>Within SO there are a lot of questions/answers. Here the main ones:</p>
<p><a href="https://stackoverflow.com/questions/6893038/how-do-i-replace-weak-references-when-using-arc-and-targeting-ios-4-0">How do I replace weak references when using ARC and targeting iOS 4.0?</a></p>
<p><a href="https://stackoverflow.com/questions/6260256/what-kind-of-leaks-does-automatic-reference-counting-in-objective-c-not-prevent/">What kind of leaks does automatic reference counting in Objective-C not prevent or minimize?</a></p>
<p><a href="https://stackoverflow.com/questions/8397511/using-arc-lifetime-qualifier-assign-and-unsafe-unretained">using ARC, lifetime qualifier assign and unsafe_unretained</a></p>
<p><a href="https://stackoverflow.com/questions/9784762/strong-weak-retain-unsafe-unretained-assign">strong / weak / retain / unsafe_unretained / assign</a></p>
<p>Hope that helps.</p>
<p><strong>Update</strong></p>
<p>As per shaunlim's comment, starting from iOS 6 <code>viewDidUnload</code> method is deprecated. Here I really suggest to see Rob's answer: <a href="https://stackoverflow.com/questions/12674268/ios-6-viewdidunload-migrate-to-didreceivememorywarning">iOS 6 - viewDidUnload migrate to didReceiveMemoryWarning?</a>. </p> |
10,953,070 | How to debug "Vagrant cannot forward the specified ports on this VM" message | <p>I'm trying to start a Vagrant instance and getting the following message:</p>
<pre><code>Vagrant cannot forward the specified ports on this VM, since they
would collide with another VirtualBox virtual machine's forwarded
ports! The forwarded port to 4567 is already in use on the host
machine.
To fix this, modify your current projects Vagrantfile to use another
port. Example, where '1234' would be replaced by a unique host port:
config.vm.forward_port 80, 1234
</code></pre>
<p>I opened VirtualBox, but I don't have any running boxes at the moment, so I'm stumped. How can I figure out which process is listening on 4567? Is there a way to list all Vagrant boxes running on my machine? </p>
<p>Thanks,
Kevin</p> | 11,037,995 | 15 | 2 | null | 2012-06-08 17:01:56.977 UTC | 8 | 2021-10-19 15:24:44.067 UTC | null | null | null | null | 329,700 | null | 1 | 50 | vagrant | 58,588 | <p>As message says, the port collides with the host box. I would simply change the port to some other value on the host machine. So if I am getting error for</p>
<pre><code>config.vm.forward_port 80, 1234
</code></pre>
<p>then I would change it to </p>
<pre><code>config.vm.forward_port 80, 5656
</code></pre>
<p>As 1234 might be used on my host machine. </p>
<p>For actually inspecting ports on any machine, I use the <code>tcpview</code> utility for that OS and get to know which port is used where.</p> |
11,029,294 | Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8) | <p>How do I programmatically access the value shown in the image below ?</p>
<p><img src="https://i.stack.imgur.com/J7vWU.png" alt="enter image description here"></p> | 11,029,386 | 6 | 1 | null | 2012-06-14 08:25:29.523 UTC | 17 | 2022-06-03 10:11:21.617 UTC | 2013-10-22 19:22:03.14 UTC | null | 58,074 | null | 604,383 | null | 1 | 61 | android|serial-number | 131,925 | <p>This is the hardware serial number. To access it on</p>
<ul>
<li><p><strong>Android Q</strong> (>= SDK 29)
<code>android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE</code> is required. Only system apps can require this permission. If the calling package is the device or profile owner then the <code>READ_PHONE_STATE</code> permission suffices.</p></li>
<li><p><strong>Android 8 and later</strong> (>= SDK 26) use <code>android.os.Build.getSerial()</code> which requires the dangerous permission <a href="https://developer.android.com/reference/android/Manifest.permission.html#READ_PHONE_STATE" rel="noreferrer">READ_PHONE_STATE</a>. Using <code>android.os.Build.SERIAL</code> returns <a href="https://developer.android.com/reference/android/os/Build.html#UNKNOWN" rel="noreferrer">android.os.Build.UNKNOWN</a>.</p></li>
<li><p><strong>Android 7.1 and earlier</strong> (<= SDK 25) and earlier <a href="http://developer.android.com/reference/android/os/Build.html" rel="noreferrer"><code>android.os.Build.SERIAL</code></a> does return a valid serial.</p></li>
</ul>
<p>It's unique for any device. If you are looking for possibilities on how to get/use a unique device id you should read <a href="https://stackoverflow.com/questions/2785485/is-there-a-unique-android-device-id">here</a>.</p>
<p>For a solution involving reflection without requiring a permission see <a href="https://stackoverflow.com/a/52606366/821894">this answer</a>.</p> |
10,936,059 | How to convert items in array to a comma separated string in PHP? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/2435216/how-to-create-comma-separated-list-from-array-in-php">How to create comma separated list from array in PHP?</a> </p>
</blockquote>
<p>Given this array:</p>
<pre><code>$tags = array('tag1','tag2','tag3','tag4','...');
</code></pre>
<p>How do I generate this string (using PHP):</p>
<pre><code>$tags = 'tag1, tag2, tag3, tag4, ...';
</code></pre> | 10,936,075 | 4 | 2 | null | 2012-06-07 16:37:16.747 UTC | 3 | 2012-06-07 16:57:44.197 UTC | 2017-05-23 11:55:07.183 UTC | null | -1 | null | 1,385,112 | null | 1 | 67 | php|arrays | 113,549 | <p>Use <a href="http://php.net/implode" rel="noreferrer">implode</a>:</p>
<pre><code> $tags = implode(', ', array('tag1','tag2','tag3','tag4'));
</code></pre> |
11,270,753 | Underscores or camelCase in PostgreSQL identifiers, when the programming language uses camelCase? | <p>This has been bothering me for a while, and I can't arrive at a solution that feels <i>right</i>...</p>
<p>Given an OO language in which the usual naming convention for object properties is camelCased, and an example object like this:</p>
<pre><code>{
id: 667,
firstName: "Vladimir",
lastName: "Horowitz",
canPlayPiano: true
}
</code></pre>
<p>How should I model this structure in a PostgreSQL table?</p>
<p>There are three main options:</p>
<ol>
<li>unquoted camelCase column names</li>
<li>quoted camelCase column names</li>
<li>unquoted (lowercase) names with underscores</li>
</ol>
<p>They each have their drawbacks:</p>
<ol>
<li><p>Unquoted identifiers automatically fold to lowercase. This means that you can create a table with a <code>canPlayPiano</code> column, but the mixed case never reaches the database. When you inspect the table, the column will always show up as <code>canplaypiano</code> - in psql, pgadmin, explain results, error messages, everything.</p></li>
<li><p>Quoted identifiers keep their case, but once you create them like that, you will <em>always</em> have to quote them. IOW, if you create a table with a <code>"canPlayPiano"</code> column, a <code>SELECT canPlayPiano ...</code> will fail. This adds a lot of unnecessary noise to all SQL statements.</p></li>
<li><p>Lowercase names with underscores are unambiguous, but they don't map well to the names that the application language is using. You will have to remember to use different names for storage (<code>can_play_piano</code>) and for code (<code>canPlayPiano</code>). It also prevents certain types of code automation, where properties and DB columns need to be named the same.</p></li>
</ol>
<p>So I'm caught between a rock and a hard place (and a large stone; there are three options). Whatever I do, some part is going to feel awkward. For the last 10 years or so, I've been using option 3, but I keep hoping there would be a better solution.</p>
<p>I'm grateful for any advice you might have.</p>
<p>PS: I do realize where the case folding and the need for quotes is coming from - the SQL standard, or rather PostgreSQL's adaptation of the standard. I know how it works; I'm more interested in advice about best practices than explanations about how PG handles identifiers.</p> | 11,271,763 | 3 | 2 | null | 2012-06-30 01:27:29.913 UTC | 10 | 2020-04-17 18:04:57.867 UTC | 2012-06-30 02:06:08.85 UTC | null | 169,603 | null | 169,603 | null | 1 | 73 | oop|postgresql|database-design|naming-conventions|camelcasing | 39,671 | <p>Given that PostgreSQL uses case-insensitive identifiers with underscores, should you change all your identifiers in your application to do the same? Clearly not. So why do you think the reverse is a reasonable choice?</p>
<p>The convention in PostgreSQL has come about through a mix of standards compliance and long-term experience of its users. Stick with it.</p>
<p>If translating between column-names and identifiers gets tedious, have the computer do it - they're good at things like that. I'm guessing almost all of the 9-million database abstraction libraries out there can do that. If you have a dynamic language it'll take you all of two lines of code to swap column-names to identifiers in CamelCase.</p> |
11,278,387 | Is it possible to download an old APK for my app from Google Play? | <p>Over the last few months, I've published several revisions to my app. Unfortunately, I didn't keep copies of all the old APKs, and now I'd like to test upgrade from the old versions to my new version. Is there any way to download Google's copy of my old versions? The Google Play developer console shows my old APKs, but without a download link. I tried "Real APK Leecher", but that doesn't let you choose the APK version you want to download. And I'm not able to even temporarily reactivate the old version in the Developer Console since it complains that it's of an earlier version.</p> | 11,278,480 | 9 | 1 | null | 2012-06-30 23:17:10.48 UTC | 13 | 2022-02-20 17:47:51.757 UTC | null | null | null | null | 342,647 | null | 1 | 117 | android|google-play | 83,801 | <p><strong>THE ANSWER IS OUTDATED. NOW THIS IS POSSIBLE, CHECK <a href="https://stackoverflow.com/a/40037886/944070">@tesla's</a> AND <a href="https://stackoverflow.com/a/40759979/944070">@olleh's</a> ANSWERS.</strong></p>
<p><strong>FOR THE NEW 2020 GOOGLE PLAY CONSOLE, SEE ANSWER FROM <a href="https://stackoverflow.com/questions/11278387/is-it-possible-to-download-an-old-apk-for-my-app-from-google-play/63599659#63599659">@IonicBurger</a></strong></p>
<p>No, unfortunately.</p>
<p>The Android Developer Console is a real disaster, everywhere you look there is something that needs to be fixed or improved, being this issue you mention one of them. Unfortunately for the time being you're out of luck. Unless Google enables this, you cannot download old APKS's. I suppose you could recompile the old code, but I guess you don't have that either and that's why you are here :-)</p> |
10,944,621 | Dynamically updating plot in matplotlib | <p>I am making an application in Python which collects data from a serial port and plots a graph of the collected data against arrival time. The time of arrival for the data is uncertain. I want the plot to be updated when data is received. I searched on how to do this and found two methods:</p>
<ol>
<li>Clear the plot and re-draw the plot with all the points again.</li>
<li>Animate the plot by changing it after a particular interval.</li>
</ol>
<p>I do not prefer the first one as the program runs and collects data for a long time (a day for example), and redrawing the plot will be pretty slow.
The second one is also not preferable as time of arrival of data is uncertain and I want the plot to update only when the data is received.</p>
<p>Is there a way in which I can update the plot just by adding more points to it only when the data is received?</p> | 10,944,967 | 4 | 1 | null | 2012-06-08 07:22:07.973 UTC | 72 | 2020-02-03 08:41:43.287 UTC | 2012-06-08 09:05:34.117 UTC | null | 885,443 | null | 1,418,822 | null | 1 | 140 | python|matplotlib|tkinter | 278,280 | <blockquote>
<p><em>Is there a way in which I can update the plot just by adding more point[s] to it...</em></p>
</blockquote>
<p>There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the <a href="http://www.scipy.org/Cookbook/Matplotlib/Animations">matplotlib cookbook</a> examples? Also, check out the more modern <a href="http://matplotlib.sourceforge.net/examples/animation/index.html">animation examples</a> in the matplotlib documentation. Finally, the <a href="http://matplotlib.sourceforge.net/api/animation_api.html">animation API</a> defines a function <a href="http://matplotlib.sourceforge.net/api/animation_api.html#matplotlib.animation.FuncAnimation">FuncAnimation</a> which animates a function in time. This function could just be the function you use to acquire your data.</p>
<p>Each method basically sets the <code>data</code> property of the object being drawn, so doesn't require clearing the screen or figure. The <code>data</code> property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).</p>
<p>Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy
hl, = plt.plot([], [])
def update_line(hl, new_data):
hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
plt.draw()
</code></pre>
<p>Then when you receive data from the serial port just call <code>update_line</code>.</p> |
12,929,848 | how make float to integer in awk | <p>I have a variable in my awk code . after some arithmatic operation on this variable and printing (<code>print $1,$2,variable</code>) the result is made like below:</p>
<p><strong>my result</strong></p>
<pre><code>Bama 2 5
Bama 2 5.001
Bama 2 5.002
Bama 2 5.003
Bama 2 5.004
Bama 2 6
Bama 2 6.003
Bama 2 6.004
Bama 2 4.005
</code></pre>
<p>But i want only integer section of my variable print </p>
<p><strong>desired result</strong></p>
<pre><code>Bama 2 5
Bama 2 5
Bama 2 5
Bama 2 5
Bama 2 5
Bama 2 6
Bama 2 6
Bama 2 6
Bama 2 4
</code></pre>
<p>How can I do this?</p> | 12,929,974 | 2 | 1 | null | 2012-10-17 08:10:09.347 UTC | 3 | 2020-08-16 16:35:57.457 UTC | 2012-10-17 08:21:31.327 UTC | user647772 | null | null | 1,728,917 | null | 1 | 25 | awk | 45,258 | <p>Truncate it using the <code>int</code> function:</p>
<pre><code>print $1, $2, int( variable );
</code></pre> |
37,382,889 | Can't get AWS Lambda function to log (text output) to CloudWatch | <p>I'm trying to set up a Lambda function that will process a file when it's uploaded to an S3 bucket. I need a way to see the output of <code>console.log</code> when I upload a file, but I can't figure out how to link my Lambda function to CloudWatch.</p>
<p>I figured about by looking at the <code>context</code> object that my log group is <code>/aws/lambda/wavToMp3</code> and the log stream is <code>2016/05/23/[$LATEST]hex_code_redacted</code>. So I created that group and stream in CloudWatch, yet nothing is being logged to it.</p> | 37,383,297 | 16 | 7 | null | 2016-05-23 04:56:09.243 UTC | 14 | 2021-12-03 12:42:32.79 UTC | null | null | null | null | 5,228,806 | null | 1 | 99 | amazon-web-services|aws-lambda|amazon-cloudwatch | 77,937 | <p>For the lambda function to create log stream and publish logs to cloudwatch, the lambda execution role needs to have the following permissions.</p>
<pre class="lang-html prettyprint-override"><code>{
"Statement": [
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Effect": "Allow",
"Resource": "arn:aws:logs:*:*:*"
}
]
}
</code></pre>
<p>Please refer to the following AWS documentation for more details
<a href="http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role" rel="noreferrer">http://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html#lambda-intro-execution-role</a></p> |
16,649,943 | CSS to set A4 paper size | <p>I need simulate an A4 paper in web and allow to print this page as it is show on browser (Chrome, specifically). I set the element size to 21cm x 29.7cm, but when I send to print (or print preview) it clip my page.</p>
<p>See this <a href="https://jsfiddle.net/2wk6Q/1/" rel="noreferrer"><strong>Live example</strong></a>!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
margin: 0;
padding: 0;
background-color: #FAFAFA;
font: 12pt "Tahoma";
}
* {
box-sizing: border-box;
-moz-box-sizing: border-box;
}
.page {
width: 21cm;
min-height: 29.7cm;
padding: 2cm;
margin: 1cm auto;
border: 1px #D3D3D3 solid;
border-radius: 5px;
background: white;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}
.subpage {
padding: 1cm;
border: 5px red solid;
height: 256mm;
outline: 2cm #FFEAEA solid;
}
@page {
size: A4;
margin: 0;
}
@media print {
.page {
margin: 0;
border: initial;
border-radius: initial;
width: initial;
min-height: initial;
box-shadow: initial;
background: initial;
page-break-after: always;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="book">
<div class="page">
<div class="subpage">Page 1/2</div>
</div>
<div class="page">
<div class="subpage">Page 2/2</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>I think I'm forgetting something. But what would it be?</p>
<ul>
<li><strong>Chrome</strong>: clipping page, double page (<em>it's just what I need it to work</em>)</li>
<li><strong>Firefox</strong>: it works perfectly.</li>
<li><strong>IE10</strong>: believe it or not, it's perfect!</li>
<li><strong>Opera</strong>: very buggy on print preview</li>
</ul> | 16,650,459 | 3 | 3 | null | 2013-05-20 12:51:20.603 UTC | 163 | 2021-04-14 15:19:43.88 UTC | 2021-04-03 09:21:38.61 UTC | null | 9,193,372 | null | 755,393 | null | 1 | 283 | css|printing|print-preview | 632,344 | <p>I looked into this a bit more and the actual problem seems to be with assigning <code>initial</code> to page <code>width</code> under the <code>print</code> media rule. It seems like in Chrome <code>width: initial</code> on the <code>.page</code> element results in <em><strong>scaling</strong></em> of the page content if no specific length value is defined for <code>width</code> on any of the parent elements (<code>width: initial</code> in this case resolves to <code>width: auto</code> ... but actually any value smaller than the size defined under the <code>@page</code> rule causes the same issue).</p>
<p>So not only the content is now <em><strong>too long</strong></em> for the page (by about <em><code>2cm</code></em>), but also the page padding will be slightly more than the initial <em><code>2cm</code></em> and so on (it seems to render the contents under <code>width: auto</code> to the width of <em><code>~196mm</code></em> and then scale the whole content up to the width of <em><code>210mm</code></em> ~ but strangely exactly the same scaling factor is applied to contents with any width smaller than <em><code>210mm</code></em>).</p>
<p>To fix this problem you can simply in the <code>print</code> media rule assign the A4 paper width and hight to <code>html, body</code> or directly to <code>.page</code> and in this case avoid the <code>initial</code> keyword.</p>
<h3><a href="http://jsfiddle.net/mturjak/2wk6Q/1949/" rel="noreferrer"><strong>DEMO</strong></a></h3>
<pre><code>@page {
size: A4;
margin: 0;
}
@media print {
html, body {
width: 210mm;
height: 297mm;
}
/* ... the rest of the rules ... */
}
</code></pre>
<p><sup><strong>This seems to keep everything else the way it is in your original CSS and fix the problem in Chrome (tested in different versions of Chrome under Windows, OS X and Ubuntu).</strong></sup></p> |
16,936,250 | SharePoint 2013 add javascript after whole page load | <p>Disclaimer: I have no experience with SharePoint2013.</p>
<p>I have problem - I must include/fire some javascript functions after the whole page has been loaded. I tried listening to DOMDocumentReady and window.load events, but sharepoint render the rest of page after those events.</p>
<p>My question is: what I should do to be able to run script after whole page with ajax is rendered.
Also I noticed that page navigation is based on hash (#) part. Obviously I must detect that moment also.</p>
<p>Any help or even link to right page in documentation would be great!</p> | 17,326,405 | 5 | 6 | null | 2013-06-05 09:27:25.95 UTC | 18 | 2017-03-02 07:37:39.537 UTC | null | null | null | null | 1,812,679 | null | 1 | 29 | javascript|sharepoint-2013 | 100,438 | <p>You are right, MANY things happen on page after $(document).ready(). 2013 does provide a few options. </p>
<p>1) Script on Demand: (load a js file then execute my code.)</p>
<pre><code>function stuffThatRequiresSP_JS(){
//your code
}
</code></pre>
<p><code>SP.SOD.executeFunc("sp.js")</code></p>
<p>2) Delay until loaded (wait for a js file, then run)</p>
<pre><code>function stuffToRunAfterSP_JS(){
//your code
}
ExecuteOrDelayUntilScriptLoaded(stuffToRunAfterSP_JS, "sp.js")
</code></pre>
<p>3) load after other stuff finishes</p>
<pre><code>function runAfterEverythingElse(){
// your code
}
_spBodyOnLoadFunctionNames.push("runAfterEverythingElse");
</code></pre>
<p>Sources:</p>
<p>executeFunc: <a href="http://msdn.microsoft.com/en-us/library/ff409592(v=office.14).aspx">http://msdn.microsoft.com/en-us/library/ff409592(v=office.14).aspx</a></p>
<p>ExecuteOrDelayUntilScriptLoaded: <a href="http://msdn.microsoft.com/en-us/library/ff411788(v=office.14).aspx">http://msdn.microsoft.com/en-us/library/ff411788(v=office.14).aspx</a></p>
<p>Cant find a source on _spBodyOnLoadFunctionNames but I am using it in a few places. </p>
<p>good luck. </p> |
17,080,494 | Using grunt server, how can I redirect all requests to root url? | <p>I am building my first <a href="http://angularjs.org/" rel="noreferrer">Angular.js</a> application and I'm using <a href="http://yeoman.io/" rel="noreferrer">Yeoman</a>. </p>
<p>Yeoman uses Grunt to allow you to run a node.js connect server with the command 'grunt server'.</p>
<p>I'm running my angular application in html5 mode. According to the angular docs, this requires a modification of the server to redirect all requests to the root of the application (index.html), since angular apps are single page ajax applications. </p>
<blockquote>
<p>"Using [html5] mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)"</p>
</blockquote>
<p>The problem that I'm trying to solve is detailed in <a href="https://stackoverflow.com/questions/16569841/angularjs-html5-mode-reloading-the-page-gives-wrong-get-request">this</a> question.</p>
<p>How can I modify my grunt server to redirect all page requests to the index.html page?</p> | 20,553,608 | 5 | 0 | null | 2013-06-13 06:22:42.993 UTC | 22 | 2016-01-05 19:46:16.747 UTC | 2017-05-23 11:54:17.563 UTC | null | -1 | null | 1,826,354 | null | 1 | 46 | node.js|angularjs|gruntjs|yeoman|angularjs-routing | 30,294 | <p>First, using your command line, navigate to your directory with your gruntfile.</p>
<p>Type this in the CLI: </p>
<pre><code>npm install --save-dev connect-modrewrite
</code></pre>
<p>At the top of your grunt file put this:</p>
<pre><code>var modRewrite = require('connect-modrewrite');
</code></pre>
<p>Now the next part, you only want to add <a href="https://www.npmjs.com/package/connect-modrewrite">modRewrite</a> into your connect:</p>
<pre><code>modRewrite(['!\\.html|\\.js|\\.svg|\\.css|\\.png$ /index.html [L]']),
</code></pre>
<p>Here is a example of what my "connect" looks like inside my Gruntfile.js. You don't need to worry about my lrSnippet and my ssIncludes. The main thing you need is to just get the modRewrite in.</p>
<pre><code> connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: '0.0.0.0',
},
livereload: {
options: {
middleware: function (connect) {
return [
modRewrite(['!\\.html|\\.js|\\.svg|\\.css|\\.png$ /index.html [L]']),
lrSnippet,
ssInclude(yeomanConfig.app),
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app)
];
}
}
},
test: {
options: {
middleware: function (connect) {
return [
mountFolder(connect, '.tmp'),
mountFolder(connect, 'test')
];
}
}
},
dist: {
options: {
middleware: function (connect) {
return [
mountFolder(connect, yeomanConfig.dist)
];
}
}
}
},
</code></pre> |
17,073,688 | How to use argparse subparsers correctly? | <p>I've been searching through a lot of the subparser examples on here and in general but can't seem to figure this seemingly simple thing out.</p>
<p>I have two var types of which one has constraints so thought subparser was the way to go. e.g. -t allows for either "A" or "B". If the user passes "A" then they are further required to also specify if it is either "a1" or "a2". If they pass just "B" then nothing.</p>
<p>Can I do this and have argparse return me what type of "A" was passed or if it was just "B"?</p>
<p>The below seems to work but for some reason breaks when passing anything after the subparse.</p>
<p>e.g. from a linux terminal</p>
<pre><code>>> python test01.py -t A a1 -v 61
</code></pre>
<p>errors with...</p>
<pre><code>usage: test01.py a1 [-h]
test01.py a1: error: unrecognized arguments: -v
</code></pre>
<p>Hopefully that makes sense.</p>
<p>The code:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='types of A')
parser.add_argument("-t",
choices = ["A", "B"],
dest = "type",
required=True,
action='store',
help="Some help blah blah")
cam_parser = subparsers.add_parser('a1', help='Default')
cam_parser.set_defaults(which='a1')
cam_parser = subparsers.add_parser('a2', help='parse this instead of default')
cam_parser.set_defaults(which='a2')
parser.add_argument("-v",
nargs = '+',
required=True,
dest = "version",
type=int,
action='store',
help="some version help blah blah")
argument = parser.parse_args()
print argument.type
print argument.version
</code></pre> | 17,074,215 | 1 | 0 | null | 2013-06-12 19:28:27.06 UTC | 12 | 2021-03-15 03:36:16.71 UTC | 2021-03-15 03:36:16.71 UTC | null | 1,214,800 | null | 1,571,144 | null | 1 | 72 | python|argparse | 95,054 | <p>Subparsers are invoked based on the value of the first <em>positional</em> argument, so your call would look like</p>
<pre><code>python test01.py A a1 -v 61
</code></pre>
<p>The "A" triggers the appropriate subparser, which would be defined to allow a positional argument and the <code>-v</code> option.</p>
<p>Because <code>argparse</code> does not otherwise impose any restrictions on the order in which arguments and options may appear, and there is no simple way to modify what arguments/options <em>may</em> appear once parsing has begun (something involving custom actions that modify the parser instance might work), you should consider replacing <code>-t</code> itself:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='types of A')
parser.add_argument("-v", ...)
a_parser = subparsers.add_parser("A")
b_parser = subparsers.add_parser("B")
a_parser.add_argument("something", choices=['a1', 'a2'])
</code></pre>
<p>Since <code>-v</code> is defined for the main parser, it must be specified <em>before</em> the argument that specifies which subparser is used for the remaining arguments.</p> |
25,677,035 | How to create a range of dates in R | <p>From two integers <code>(1, 5)</code> one can create a range in the following way</p>
<pre><code>1:5
</code></pre>
<blockquote>
<p>[1] 1 2 3 4 5</p>
</blockquote>
<p>How can you make a range of dates if you are give two dates <code>("2014-09-04 JST", "2014-09-11 JST")</code></p>
<p>The output must be </p>
<blockquote>
<p>[1] ("2014-09-04 JST", "2014-09-05 JST", "2014-09-06 JST", "2014-09-07 JST", "2014-09-08 JST")</p>
</blockquote> | 25,677,051 | 5 | 5 | null | 2014-09-05 00:40:52.87 UTC | 8 | 2022-04-21 09:41:17.89 UTC | null | null | null | null | 835,724 | null | 1 | 24 | r|date | 35,483 | <p>Does this help?</p>
<pre><code>seq(as.Date("2014/09/04"), by = "day", length.out = 5)
# [1] "2014-09-04" "2014-09-05" "2014-09-06" "2014-09-07" "2014-09-08"
</code></pre>
<p><strong>edit: adding in something about timezones</strong></p>
<p>this works for my current timezone</p>
<pre><code>seq(c(ISOdate(2014,4,9)), by = "DSTday", length.out = 5)
#[1] "2014-04-09 08:00:00 EDT" "2014-04-10 08:00:00 EDT" "2014-04-11 08:00:00 EDT" "2014-04-12 08:00:00 EDT"
#[5] "2014-04-13 08:00:00 EDT"
</code></pre>
<p><strong>edit2:</strong></p>
<pre><code>OlsonNames() # I used this to find out what to write for the JST tz - it's "Japan"
x <- as.POSIXct("2014-09-04 23:59:59", tz="Japan")
format(seq(x, by="day", length.out=5), "%Y-%m-%d %Z")
# [1] "2014-09-04 JST" "2014-09-05 JST" "2014-09-06 JST" "2014-09-07 JST" "2014-09-08 JST"
</code></pre> |
60,902,001 | Why have i++; i--; right after each other? | <p>I was looking at the source code for <a href="https://en.wikipedia.org/wiki/Nmap" rel="noreferrer">nmap</a> that was released in 1997 and I noticed this section of code that looks a little odd to me:</p>
<pre><code>int i=0, j=0,start,end;
char *expr = strdup(origexpr);
ports = safe_malloc(65536 * sizeof(short));
i++; /* <<<<<< */
i--; /* <<<<<< */
for(;j < exlen; j++)
if (expr[j] != ' ') expr[i++] = expr[j];
expr[i] = '\0';
</code></pre>
<p>Why would you have <code>i++;</code> and then <code>i--;</code> right after each other? <code>i</code> is <code>0</code>, then <code>i++</code> turns <code>i</code> to <code>1</code>. After that, <code>i--</code> turns <code>i</code> to <code>0</code>.</p>
<p><a href="https://nmap.org/p51-11.html" rel="noreferrer">Link to original source code.</a> Search for:</p>
<pre><code>i++;
i--;
</code></pre>
<p>Can anyone explain what this is for?</p> | 60,902,078 | 4 | 13 | null | 2020-03-28 13:51:55.027 UTC | 8 | 2020-07-13 10:19:32.337 UTC | 2020-04-03 12:58:48.64 UTC | null | 2,102,457 | null | 12,134,095 | null | 1 | 166 | c|nmap | 11,301 | <p>This was a bug. These lines together result in <code>i</code> being unchanged, so they shouldn't have been there.</p>
<p>The linked article that introduced nmap was published on September 1 1997. If you look at the SVN repository for nmap at <a href="https://svn.nmap.org/nmap" rel="noreferrer">https://svn.nmap.org/nmap</a>, the initial revision checked in on February 10 1998 does not have those lines:</p>
<pre><code>int i=0, j=0,start,end;
char *expr = strdup(origexpr);
char *mem = expr;
ports = safe_malloc(65536 * sizeof(short));
for(;j < exlen; j++)
if (expr[j] != ' ') expr[i++] = expr[j];
expr[i] = '\0';
</code></pre>
<p>So this is something the author found and fixed between publishing the initial nmap source code and the initial checkin to SVN.</p> |
4,812,891 | fork() and pipes() in c | <p>What is <code>fork</code> and what is <code>pipe</code>?
Any scenarios explaining why their use is necessary will be appreciated.
What are the differences between <code>fork</code> and <code>pipe</code> in C?
Can we use them in C++?</p>
<p>I need to know this is because I want to implement a program in C++ which can access live video input, convert its format and write it to a file.
What would be the best approach for this?
I have used x264 for this. So far I have implemented the part of conversion on a file format.
Now I have to implement it on a live stream.
Is it a good idea to use pipes? Capture video in another process and feed it to the other?</p> | 4,812,963 | 2 | 2 | null | 2011-01-27 04:57:59.227 UTC | 18 | 2017-04-26 00:05:04.113 UTC | 2017-04-26 00:05:04.113 UTC | null | 556,595 | null | 590,198 | null | 1 | 35 | c++|c | 96,087 | <p>A pipe is a mechanism for interprocess communication. Data written to the pipe by one process can be read by another process. The primitive for creating a pipe is the <code>pipe</code> function. This creates both the reading and writing ends of the pipe. It is not very useful for a single process to use a pipe to talk to itself. In typical use, a process creates a pipe just before it <code>forks</code> one or more child processes. The pipe is then used for communication either between the parent or child processes, or between two sibling processes. A familiar example of this kind of communication can be seen in all operating system shells. When you type a command at the shell, it will spawn the executable represented by that command with a call to <code>fork</code>. A pipe is opened to the new child process and its output is read and printed by the shell. <a href="http://www.gnu.org/s/libc/manual/html_node/Creating-a-Pipe.html#Creating-a-Pipe" rel="noreferrer">This page</a> has a full example of the <code>fork</code> and <code>pipe</code> functions. For your convenience, the code is reproduced below:</p>
<pre><code> #include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
/* Read characters from the pipe and echo them to stdout. */
void
read_from_pipe (int file)
{
FILE *stream;
int c;
stream = fdopen (file, "r");
while ((c = fgetc (stream)) != EOF)
putchar (c);
fclose (stream);
}
/* Write some random text to the pipe. */
void
write_to_pipe (int file)
{
FILE *stream;
stream = fdopen (file, "w");
fprintf (stream, "hello, world!\n");
fprintf (stream, "goodbye, world!\n");
fclose (stream);
}
int
main (void)
{
pid_t pid;
int mypipe[2];
/* Create the pipe. */
if (pipe (mypipe))
{
fprintf (stderr, "Pipe failed.\n");
return EXIT_FAILURE;
}
/* Create the child process. */
pid = fork ();
if (pid == (pid_t) 0)
{
/* This is the child process.
Close other end first. */
close (mypipe[1]);
read_from_pipe (mypipe[0]);
return EXIT_SUCCESS;
}
else if (pid < (pid_t) 0)
{
/* The fork failed. */
fprintf (stderr, "Fork failed.\n");
return EXIT_FAILURE;
}
else
{
/* This is the parent process.
Close other end first. */
close (mypipe[0]);
write_to_pipe (mypipe[1]);
return EXIT_SUCCESS;
}
}
</code></pre>
<p>Just like other C functions you can use both <code>fork</code> and <code>pipe</code> in C++.</p> |
4,054,511 | What exactly does the T-SQL "LineNo" reserved word do? | <p>I was writing a query against a table today on a SQL Server 2000 box, and while writing the query in Query Analyzer, to my surprise I noticed the word <code>LineNo</code> was converted to blue text. </p>
<p>It appears to be a <a href="http://msdn.microsoft.com/en-us/library/aa238507(SQL.80).aspx" rel="noreferrer">reserved word</a> according to MSDN documentation, but I can find no information on it, just speculation that it might be a legacy reserved word that doesn't <em>do</em> anything.</p>
<p>I have no problem escaping the field name, but I'm curious -- does anyone know what "LineNo" in T-SQL is actually used for?</p> | 4,054,590 | 2 | 0 | null | 2010-10-29 17:50:20.957 UTC | 4 | 2018-07-17 15:37:05.583 UTC | 2012-06-19 11:58:29.407 UTC | null | 92,837 | null | 334,849 | null | 1 | 39 | sql-server|tsql|sql-server-2000|reserved-words | 7,813 | <p>OK, this is completely undocumented, and I had to figure it out via trial and error, but it sets the line number for error reporting. For example:</p>
<pre><code>LINENO 25
SELECT * FROM NON_EXISTENT_TABLE
</code></pre>
<p>The above will give you an error message, indicating an error at line 27 (instead of 3, if you convert the LINENO line to a single line comment (e.g., by prefixing it with two hyphens) ):</p>
<pre><code>Msg 208, Level 16, State 1, Line 27
Invalid object name 'NON_EXISTENT_TABLE'.
</code></pre>
<p>This is related to similar mechanisms in programming languages, such as the #line preprocessor directives in Visual C++ and Visual C# (which are documented, by the way). </p>
<p>How is this useful, you may ask? Well, one use of this it to help SQL code generators that generate code from some higher level (than SQL) language and/or perform macro expansion, tie generated code lines to user code lines.</p>
<p>P.S., It is not a good idea to rely on undocumented features, especially when dealing with a database.</p>
<p>Update: This explanation is still correct up to and including the current version of SQL Server, which at the time of this writing is SQL Server 2008 R2 Cumulative Update 5 (10.50.1753.0) .</p> |
4,412,848 | XML Node to String in Java | <p>I came across this piece of Java function to convert an XML node to a Java String representation:</p>
<pre><code>private String nodeToString(Node node) {
StringWriter sw = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(new DOMSource(node), new StreamResult(sw));
} catch (TransformerException te) {
System.out.println("nodeToString Transformer Exception");
}
return sw.toString();
}
</code></pre>
<p>It looks straightforward in that it wants the output string doesn't have any XML declaration and it must contain indentation.</p>
<p>But I wonder how the actual output should be, suppose I have an XML node:</p>
<pre><code><p><media type="audio" id="au008093" rights="wbowned">
<title>Bee buzz</title>
</media>Most other kinds of bees live alone instead of in a colony. These bees make
tunnels in wood or in the ground. The queen makes her own nest.</p>
</code></pre>
<p>Could I assume the resulting String after applying the above transformation is:</p>
<pre><code>"media type="audio" id="au008093" rights="wbowned" title Bee buzz title /media"
</code></pre>
<p>I want to test it myself, but I have no idea on how to represent this XML node in the way this function actually wants.</p>
<p>I am bit confused, and thanks in advance for the generous help.</p> | 4,413,325 | 2 | 0 | null | 2010-12-10 20:07:54.393 UTC | 6 | 2021-07-09 12:34:58.857 UTC | 2021-07-09 12:34:58.857 UTC | null | 8,764,150 | null | 203,175 | null | 1 | 41 | java|xml | 87,897 | <p>You have an XML respesentation in a DOM tree.<br>
For example you have opened an XML file and you have passed it in the DOM parser.<br>
As a result a DOM tree in memory with your XML is created.<br>
Now you can only access the XML info via traversal of the DOM tree.<br>
If you need though, a String representation of the XML info of the DOM tree you use a transformation.<br>
This happens since it is not possible to get the String representation directly from a DOM tree.<br>
So if for example as <code>Node node</code> you pass in <code>nodeToString</code> is the root element of the XML doc then the result is a String containing the original XML data.<br>
The tags will still be there. I.e. you will have a valid XML representation. Only this time will be in a String variable. </p>
<p>For example:</p>
<pre><code> DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document xmlDoc = parser.parse(file);//file has the xml
String xml = nodeToString(xmlDoc.getDocumentElement());//pass in the root
//xml has the xml info. E.g no xml declaration. Add it
xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?> + xml;//bad to append this way...
System.out.println("XML is:"+xml);
</code></pre>
<p><strong>DISCLAIMER:</strong> Did not even attempt to compile code. Hopefully you understand what you have to do</p> |
4,212,877 | When and how to use Tornado? When is it useless? | <p>Ok, Tornado is non-blocking and quite fast and it can handle a lot of standing requests easily.</p>
<p>But I guess it's not a silver bullet and if we just blindly run Django-based or any other site with Tornado it won't give any performance boost.</p>
<p>I couldn't find comprehensive explanation of this, so I'm asking it here:</p>
<ul>
<li>When should Tornado be used?</li>
<li>When is it useless?</li>
<li>When using it, what should be taken into account?</li>
<li>How can we make <em>inefficient</em> site using Tornado?</li>
<li>There is a server and a webframework.
When should we use framework and when can we replace it with other one?</li>
</ul> | 4,213,777 | 2 | 0 | null | 2010-11-18 08:29:04.31 UTC | 35 | 2020-04-12 08:12:04.143 UTC | 2010-11-18 08:47:57.583 UTC | null | 240,424 | null | 411,934 | null | 1 | 87 | python|asynchronous|nonblocking|tornado | 29,460 | <blockquote>
<p>There is a server and a webframework. When should we use framework and when can we replace it with other one?</p>
</blockquote>
<p>This distinction is a bit blurry. If you are only serving static pages, you would use one of the fast servers like lighthttpd. Otherwise, most servers provide a varying complexity of framework to develop web applications. Tornado is a good web framework. Twisted is even more capable and is considered a good networking framework. It has support for lot of protocols. </p>
<p>Tornado and Twisted are frameworks that provide support non-blocking, asynchronous web / networking application development. </p>
<blockquote>
<p>When should Tornado be used?
When is it useless?
When using it, what should be taken into account?</p>
</blockquote>
<p>By its very nature, Async / Non-Blocking I/O works great when it is I/O intensive and not computation intensive. Most web / networking applications suits well for this model. If your application demands certain computational intensive task to be done then it has to be delegated to some other service that can handle it better. While Tornado / Twisted can do the job of web server, responding to web requests.</p>
<blockquote>
<p>How can we make inefficient site using Tornado?</p>
</blockquote>
<ol>
<li>Do any thing computational intensive task </li>
<li>Introduce blocking operations</li>
</ol>
<blockquote>
<p>But I guess it's not a silver bullet and if we just blindly run Django-based or any other site with Tornado it won't give any performance boost.</p>
</blockquote>
<p>Performance is usually a characteristic of complete web application architecture. You can bring down the performance with most web frameworks, if the application is not designed properly. Think about caching, load balancing etc. </p>
<p>Tornado and Twisted provide reasonable performance and they are good for building performant web applications. You can check out the testimonials for both twisted and tornado to see what they are capable of. </p> |
4,105,956 | Regex - Does not contain certain Characters | <p>I need a regex to match if anywhere in a sentence there is NOT either < or >.</p>
<p>If either < or > are in the string then it must return false.</p>
<p>I had a partial success with this but only if my < > are at the beginning or end:</p>
<pre><code>(?!<|>).*$
</code></pre>
<p>I am using .Net if that makes a difference.</p>
<p>Thanks for the help.</p> | 4,105,987 | 2 | 0 | null | 2010-11-05 12:50:04.383 UTC | 42 | 2019-06-20 20:16:05.15 UTC | 2019-06-20 20:16:05.15 UTC | null | 16,287 | null | 105,254 | null | 1 | 376 | regex|regex-negation | 598,587 | <pre><code>^[^<>]+$
</code></pre>
<p>The caret in the character class (<code>[^</code>) means match anything but, so this means, beginning of string, then one or more of anything except <code><</code> and <code>></code>, then the end of the string.</p> |
10,011,508 | TextBox maximum amount of characters (it's not MaxLength) | <p>I'm using a <code>System.Windows.Forms.TextBox</code>. According to the docs, the <code>MaxLength</code> property controls the amount of characters enter a user can type or paste into the TextBox (i.e. more than that can be added programmatically by using e.g. the <code>AppendText</code> function or the <code>Text</code> property). The current amount of characters can be got from the <code>TextLength</code> property.</p>
<ol>
<li>Is there any way to set the maximum amount of characters without making a custom limiter which calls <code>Clear()</code> when the custom limit is reached?</li>
<li>Regardless, what is the absolute maximum it can hold? Is it only limited by memory?</li>
<li>What happens when the maximum is reached / memory is full? Crash? Top x lines is cleared?</li>
<li>What would be the best way to manually clear only the top x lines? Substring operation?</li>
</ol>
<p>edit: I have tested it to hold more than 600k characters, regardless of <code>MaxLength</code>, at which point I manually stopped the program and asked this question.</p> | 10,013,009 | 3 | 3 | null | 2012-04-04 12:52:23.783 UTC | 4 | 2017-08-19 09:54:19.773 UTC | 2012-04-04 13:07:27.41 UTC | null | 1,094,268 | null | 1,094,268 | null | 1 | 8 | c#|.net|winforms | 57,277 | <ol>
<li>Sure. Override / shadow <code>AppendText</code> and <code>Text</code> in a derived class. See code below.</li>
<li>The backing field for the <code>Text</code> property is a plain old string (private field <code>System.Windows.Forms.Control::text</code>). So the maximum length is the max length of a string, which is "2 GB, or about 1 billion characters" (see <a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">System.String</a>).</li>
<li>Why don't you try it and see?</li>
<li>It depends on your performance requirements. You could use the <code>Lines</code> property, but beware that every time you call it your entire <code>text</code> will be internally parsed into lines. If you're pushing the limits of content length this would be a bad idea. So that faster way (in terms of execution, not coding) would be to zip through the characters and count the cr / lfs. You of course need to decide what you are considering a line ending. </li>
</ol>
<p><strong>Code: Enforce <code>MaxLength</code> property even when setting text programmatically:</strong></p>
<pre><code>using System;
using System.Windows.Forms;
namespace WindowsFormsApplication5 {
class TextBoxExt : TextBox {
new public void AppendText(string text) {
if (this.Text.Length == this.MaxLength) {
return;
} else if (this.Text.Length + text.Length > this.MaxLength) {
base.AppendText(text.Substring(0, (this.MaxLength - this.Text.Length)));
} else {
base.AppendText(text);
}
}
public override string Text {
get {
return base.Text;
}
set {
if (!string.IsNullOrEmpty(value) && value.Length > this.MaxLength) {
base.Text = value.Substring(0, this.MaxLength);
} else {
base.Text = value;
}
}
}
// Also: Clearing top X lines with high performance
public void ClearTopLines(int count) {
if (count <= 0) {
return;
} else if (!this.Multiline) {
this.Clear();
return;
}
string txt = this.Text;
int cursor = 0, ixOf = 0, brkLength = 0, brkCount = 0;
while (brkCount < count) {
ixOf = txt.IndexOfBreak(cursor, out brkLength);
if (ixOf < 0) {
this.Clear();
return;
}
cursor = ixOf + brkLength;
brkCount++;
}
this.Text = txt.Substring(cursor);
}
}
public static class StringExt {
public static int IndexOfBreak(this string str, out int length) {
return IndexOfBreak(str, 0, out length);
}
public static int IndexOfBreak(this string str, int startIndex, out int length) {
if (string.IsNullOrEmpty(str)) {
length = 0;
return -1;
}
int ub = str.Length - 1;
int intchr;
if (startIndex > ub) {
throw new ArgumentOutOfRangeException();
}
for (int i = startIndex; i <= ub; i++) {
intchr = str[i];
if (intchr == 0x0D) {
if (i < ub && str[i + 1] == 0x0A) {
length = 2;
} else {
length = 1;
}
return i;
} else if (intchr == 0x0A) {
length = 1;
return i;
}
}
length = 0;
return -1;
}
}
}
</code></pre> |
9,880,841 | Using list preference in Android | <p>I have a text to speech application where the user can select a language and also select a male or female voice. The problem is that for each language there are different strings used to called the male and female voice but in my preference I only have two options (male and female).</p>
<pre><code><string-array name="Language">
<item>English (US)</item>
<item>English (UK)</item>
<item>French (France)</item>
<item>Spanish (Spain)</item>
<item>Italian</item>
</string-array>
<string-array name="languageAlias">
<item>"en-US"</item>
<item>"en-GB"</item>
<item>"fr-FR"</item>
<item>"es-ES"</item>
<item>"it-IT"</item>
</string-array>
<string-array name="Voice">
<item>Male</item>
<item>Female</item>
</string-array>
<string-array name="VoiceAlias">
<item>"usenglishmale"</item>
<item>"usenglishfemale"</item>
<item>"ukenglishmale"</item>
<item>"ukenglishfemale"</item>
<item>"eurfrenchmale"</item>
<item>"eurfrenchfemale"</item>
<item>"eurspanishmale"</item>
<item>"eurspanishfemale"</item>
<item>"euritalianmale"</item>
<item>"euritalianfemale"</item>
</string-array>
</code></pre>
<p>I'm trying to find a way to only reference the relevant male and female voiceAlias depending on the language selected. Is it possible to do this here or do I have to write some code which changes the values of the voiceAlias array depending on the language selected? </p>
<p>Thanks in Advance</p> | 9,881,253 | 3 | 0 | null | 2012-03-26 22:31:41.427 UTC | 9 | 2016-04-16 10:35:49.307 UTC | 2012-03-26 22:48:17.61 UTC | null | 645,270 | null | 647,423 | null | 1 | 31 | android|preferences|text-to-speech|listpreference | 78,184 | <p>Ok, you can accomplish this with two <code>ListPreference</code>s and an <code>OnPreferenceChangeListener</code> for each. First the XML:</p>
<pre><code><ListPreference
android:key="language_preference"
android:title="Language"
android:entries="@array/Language"
android:entryValues="@array/languageAlias"/>
<ListPreference
android:key="gender_preference"
android:title="Gender"
android:entries="@array/Voice"
android:entryValues="@array/VoiceData"/>
</code></pre>
<p>Let's make a new entry in res/values/array.xml:</p>
<pre><code><string-array name="VoiceData">
<item>0</item>
<item>1</item>
</string-array>
</code></pre>
<p>And now in your extention of <code>PreferenceActivity</code>, we're going to take the string values which persist in your <code>SharedPreferences</code> and from them create a completely new entry in the <code>SharedPreferences</code> which gets its value from "VoiceAlias".</p>
<pre><code>SharedPreferences shareprefs = getPreferenceManager().getSharedPreferences();
Resources resources = YourContext.getResources();
private void makeVoiceData() {
String languageData = shareprefs.getString("language_preference", "en-US");
int genderData = Integer.parseInt(shareprefs.getString("gender_preference", "0"));
String[] voiceAlias = resources.getStringArray(R.array.VoiceAlias);
int a = 0
String[] languageAlias = resources.getStringArray(R.array.languageAlias);
for (a ; a < languageAlias.length ; a++) {
if (languageAlias[a].equals(languageData)) {
break;
}
}
shareprefs.putString("VoiceAlias", voiceAlias[(2 * a) + genderData]);
}
ListPreference language_preference = getPreference("language_preference");
ListPreference gender_preference = getPreference("gender_preference");
language_preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChanged(Preference preference, Object newValue) {
shareprefs.putString("language_preference", (String) newValue);
makeVoiceData();
}
});
gender_preference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
public boolean onPreferenceChanged(Preference preference, Object newValue) {
shareprefs.putString("gender_preference", (String) newValue);
makeVoiceData();
}
});
</code></pre> |
28,357,754 | TypeError: range() integer end argument expected, got float? | <p>I know this has been asked before, but the answers did not help me :/</p>
<p>I created a function that runs a for loop over the squared max of the inputs, and by all accounts my code is correct...and yet it still asks for float inputs.</p>
<pre><code>def spiral(X, Y):
x = y = 0
dx = 0
dy = 0
count = 0
for i in range(max(X, Y)**2):
if (-X/2.0 < x <= X/20) and (-Y/2.0 < y <= Y/2.0):
print (x, y)
if x == y or (x < 0 and x == -y) or (x > 0 and x == 1-y):
dx, dy = -dy, dx
x, y = x+dx, y+dy
</code></pre>
<p>print spiral(3.0,3.0)</p>
<p>And I get this error: <code>TypeError: range() integer end argument expected, got float.</code></p>
<p>But I put 3.0 when I try and print the function...so what am I missing?</p>
<p>Thanks :)</p> | 28,357,822 | 1 | 7 | null | 2015-02-06 02:47:35.453 UTC | 1 | 2019-09-19 11:21:06.76 UTC | null | null | null | null | 3,470,746 | null | 1 | 9 | python|floating-point | 45,697 | <p>Like others said in the comment, the problem is mainly because of the float value in range function. Because range function won't accept float type as an argument.</p>
<pre><code>for i in range(max(int(X), int(Y))**2):
</code></pre> |
9,719,570 | Generate random password string with requirements in javascript | <p>I want to generate a random string that has to have 5 letters from a-z and 3 numbers. </p>
<p>How can I do this with JavaScript?</p>
<p>I've got the following script, but it doesn't meet my requirements.</p>
<pre><code> var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
var string_length = 8;
var randomstring = '';
for (var i=0; i<string_length; i++) {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
</code></pre> | 9,719,815 | 26 | 5 | null | 2012-03-15 12:21:02.213 UTC | 52 | 2022-07-09 18:19:17.893 UTC | 2021-02-15 15:24:38.78 UTC | null | 12,340,179 | null | 1,193,449 | null | 1 | 133 | javascript|random | 195,414 | <p>Forcing a fixed number of characters is a <strong>bad</strong> idea. It doesn't improve the quality of the password. Worse, it reduces the number of possible passwords, so that hacking by bruteforcing becomes easier.</p>
<p>To generate a random word consisting of alphanumeric characters, use:</p>
<pre><code>var randomstring = Math.random().toString(36).slice(-8);
</code></pre>
<h3>How does it work?</h3>
<pre><code>Math.random() // Generate random number, eg: 0.123456
.toString(36) // Convert to base-36 : "0.4fzyo82mvyr"
.slice(-8);// Cut off last 8 characters : "yo82mvyr"
</code></pre>
<p>Documentation for the <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toString" rel="noreferrer"><code>Number.prototype.toString</code></a> and <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/slice" rel="noreferrer"><code>string.prototype.slice</code></a> methods.</p> |
9,985,559 | Organizing a multiple-file Go project | <p>Note: this question is related to <a href="https://stackoverflow.com/questions/2182469/to-use-package-properly-how-to-arrange-directory-file-name-unit-test-file">this one</a>, but two years is a very long time in Go history.</p>
<p>What is the standard way to organize a Go project during development ?</p>
<p>My project is a single package <code>mypack</code>, so I guess I put all the .go files in a <code>mypack</code> directory.</p>
<p>But then, I would like to test it during development so I need at least a file declaring the <code>main</code> package, so that I can do <code>go run trypack.go</code></p>
<p>How should I organize this ? Do I need to do <code>go install mypack</code> each time I want to try it ?</p> | 9,985,600 | 7 | 3 | null | 2012-04-03 00:20:13.693 UTC | 72 | 2019-04-28 03:03:15.587 UTC | 2017-11-10 08:48:49.503 UTC | null | 3,218,674 | null | 820,664 | null | 1 | 252 | go | 152,871 | <p>I would recommend reviewing this page on <a href="http://golang.org/doc/code.html" rel="noreferrer">How to Write Go Code</a></p>
<p>It documents both how to structure your project in a <code>go build</code> friendly way, and also how to write tests. Tests do not need to be a cmd using the <code>main</code> package. They can simply be TestX named functions as part of each package, and then <code>go test</code> will discover them.</p>
<p>The structure suggested in that link in your question is a bit outdated, now with the release of Go 1. You no longer would need to place a <code>pkg</code> directory under <code>src</code>. The only 3 spec-related directories are the 3 in the root of your GOPATH: bin, pkg, src . Underneath src, you can simply place your project <code>mypack</code>, and underneath that is all of your .go files including the mypack_test.go</p>
<p><code>go build</code> will then build into the root level pkg and bin.</p>
<p>So your GOPATH might look like this:</p>
<pre><code>~/projects/
bin/
pkg/
src/
mypack/
foo.go
bar.go
mypack_test.go
</code></pre>
<p><code>export GOPATH=$HOME/projects</code></p>
<pre><code>$ go build mypack
$ go test mypack
</code></pre>
<p>Update: as of >= Go 1.11, the <a href="https://github.com/golang/go/wiki/Modules" rel="noreferrer">Module</a> system is now a standard part of the tooling and the GOPATH concept is close to becoming obsolete. </p> |
7,908,954 | Google books API searching by ISBN | <p>I am trying to figure out how to search for a book by ISBN using the Google Books API. I need to write a program that searches for an ISBN then prints out the title, author, and edition. I tried using <code>List volumesList = books.volumes.list("");</code> but that did not allow me to search by ISBN and I did not see a way to get the information I needed(when an ISBN was placed in it had no results) . What I have right now is:</p>
<pre><code> JsonFactory jsonFactory = new JacksonFactory();
final Books books = new Books(new NetHttpTransport(), jsonFactory);
List volumesList = books.volumes.list("9780262140874");
volumesList.setMaxResults((long) 2);
volumesList.setFilter("ebooks");
try
{
Volumes volumes = volumesList.execute();
for (Volume volume : volumes.getItems())
{
VolumeVolumeInfo volumeInfomation = volume.getVolumeInfo();
System.out.println("Title: " + volumeInfomation.getTitle());
System.out.println("Id: " + volume.getId());
System.out.println("Authors: " + volumeInfomation.getAuthors());
System.out.println("date published: " + volumeInfomation.getPublishedDate());
System.out.println();
}
} catch (Exception ex) {
// TODO Auto-generated catch block
System.out.println("didnt wrork "+ex.toString());
}
</code></pre>
<p>If anyone has any suggestions about how to make this more efficient let me know.
New Code:</p>
<pre><code> String titleBook="";
////////////////////////////////////////////////
try
{
BooksService booksService = new BooksService("UAH");
String isbn = "9780262140874";
URL url = new URL("http://www.google.com/books/feeds/volumes/?q=ISBN%3C" + isbn + "%3E");
VolumeQuery volumeQuery = new VolumeQuery(url);
VolumeFeed volumeFeed = booksService.query(volumeQuery, VolumeFeed.class);
VolumeEntry bookInfo=volumeFeed.getEntries().get(0);
System.out.println("Title: " + bookInfo.getTitles().get(0));
System.out.println("Id: " + bookInfo.getId());
System.out.println("Authors: " + bookInfo.getAuthors());
System.out.println("Version: " + bookInfo.getVersionId());
System.out.println("Description: "+bookInfo.getDescriptions()+"\n");
titleBook= bookInfo.getTitles().get(0).toString();
titleBook=(String) titleBook.subSequence(titleBook.indexOf("="), titleBook.length()-1);
}catch(Exception ex){System.out.println(ex.getMessage());}
/////////////////////////////////////////////////
JsonFactory jsonFactory = new JacksonFactory();
final Books books = new Books(new NetHttpTransport(), jsonFactory);
List volumesList = books.volumes.list(titleBook);
try
{
Volumes volumes = volumesList.execute();
Volume bookInfomation= volumes.getItems().get(0);
VolumeVolumeInfo volumeInfomation = bookInfomation.getVolumeInfo();
System.out.println("Title: " + volumeInfomation.getTitle());
System.out.println("Id: " + bookInfomation.getId());
System.out.println("Authors: " + volumeInfomation.getAuthors());
System.out.println("date published: " + volumeInfomation.getPublishedDate());
System.out.println();
} catch (Exception ex) {
System.out.println("didnt wrork "+ex.toString());
}
</code></pre> | 7,909,402 | 3 | 0 | null | 2011-10-26 21:09:31.95 UTC | 16 | 2020-07-03 00:43:19.703 UTC | 2020-07-03 00:43:19.703 UTC | null | 11,407,695 | null | 968,117 | null | 1 | 32 | java|isbn|google-books-api | 54,970 | <p>Are you using the <a href="http://code.google.com/apis/books/docs/gdata/developers_guide_java.html">deprecated data API</a>?</p>
<p>With <a href="http://code.google.com/apis/books/docs/v1/using.html">Books API v1</a> (from Labs) you could use the query</p>
<pre><code>https://www.googleapis.com/books/v1/volumes?q=isbn:<your_isbn_here>
</code></pre>
<p>for example</p>
<p><a href="https://www.googleapis.com/books/v1/volumes?q=isbn:0735619670">https://www.googleapis.com/books/v1/volumes?q=isbn:0735619670</a></p>
<p>to query a book by its ISBN.</p>
<p>You may want to look at Googles example code: <a href="http://code.google.com/p/google-api-java-client/source/browse/books-cmdline-sample/src/main/java/com/google/api/services/samples/books/cmdline/BooksSample.java?repo=samples">BooksSample.java</a></p> |
11,894,194 | How to install ruby-oci8? | <p>I'm trying to install ruby-oci8 on OS X.</p>
<p>I've tried installing both with and without <code>sudo</code>.</p>
<p>Error Message without <code>sudo</code>:</p>
<pre><code>gem install ruby-oci8
ERROR: While executing gem ... (Gem::FilePermissionError)
You don't have write permissions into the /Library/Ruby/Gems/1.8 directory.
</code></pre>
<p>Error Message with <code>sudo</code>:</p>
<pre><code>sudo gem install ruby-oci8
Password:
Building native extensions. This could take a while...
ERROR: Error installing ruby-oci8:
ERROR: Failed to build gem native extension.
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby extconf.rb
checking for load library path...
DYLD_LIBRARY_PATH is not set.
checking for cc... ok
checking for gcc... yes
checking for LP64... yes
checking for sys/types.h... yes
checking for ruby header... ok
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby
--with-instant-client
--without-instant-client
./oraconf.rb:887:in `get_home': RuntimeError (RuntimeError)
from ./oraconf.rb:703:in `initialize'
from ./oraconf.rb:319:in `new'
from ./oraconf.rb:319:in `get'
from extconf.rb:18
</code></pre>
<p>Error Message:</p>
<pre><code>Set the environment variable ORACLE_HOME if Oracle Full Client.
Append the path of Oracle client libraries to DYLD_LIBRARY_PATH if Oracle Instant Client.
The 'sudo' command unset some environment variables for security reasons.
Pass required varialbes as follows
sudo env DYLD_LIBRARY_PATH=$DYLD_LIBRARY_PATH /usr/bin/gem install ruby-oci8
or
sudo env ORACLE_HOME=$ORACLE_HOME /usr/bin/gem install ruby-oci8
Backtrace:
./oraconf.rb:887:in `get_home'
./oraconf.rb:703:in `initialize'
./oraconf.rb:319:in `new'
./oraconf.rb:319:in `get'
extconf.rb:18
See:
* http://ruby-oci8.rubyforge.org/en/HowToInstall.html
* http://ruby-oci8.rubyforge.org/en/ReportInstallProblem.html
</code></pre> | 21,443,313 | 12 | 2 | null | 2012-08-10 01:17:08.747 UTC | 10 | 2021-06-30 05:22:00.167 UTC | 2016-05-22 15:56:22.143 UTC | null | 4,717,992 | null | 849,019 | null | 1 | 23 | ruby|macos|oracle | 22,368 | <p>Slightly updated version of install of ruby-oci8 for 10.9/10.10/10.11OSX Mavericks/Yosemite/El Capitan - step-by-step:</p>
<ol>
<li>Go here: <a href="http://www.oracle.com/technetwork/topics/intel-macsoft-096467.html">http://www.oracle.com/technetwork/topics/intel-macsoft-096467.html</a></li>
<li><strong>Download the 64bit versions of instantclient-sqlplus, instantclient-sdk, instantclient-basic</strong> - the 32bit versions do not work with OSX 10.9</li>
<li>Create directories at /opt/oracle</li>
<li>Unzip instantclient-basic first, move to /opt/oracle (should add a folder - something like /opt/oracle/instantclient_11_2/)</li>
<li>Unzip instantclient-sdk and move its contents to /opt/oracle/instantclient_11_2/</li>
<li>Unzip instantclient-sqlplus and move its contents /opt/oracle/instantclient_11_2/</li>
<li>Open Terminal (if you haven't already) and type...</li>
<li><code>DYLD_LIBRARY_PATH=/opt/oracle/instantclient_11_2 export DYLD_LIBRARY_PATH</code></li>
<li><code>ORACLE_HOME=/opt/oracle/instantclient_11_2 export ORACLE_HOME</code></li>
<li><code>cd /opt/oracle/instantclient_11_2</code></li>
<li><code>ln -s libclntsh.dylib.11.1 libclntsh.dylib</code> (creates a symbolic link)</li>
<li><code>env</code></li>
<li>verify that DYLD_LIBRARY_PATH=/opt/oracle/instantclient_11_2 (be sure there's no trailing / after instantclient_11_2)</li>
<li>verify ORACLE_HOME=/opt/oracle/instantclient_11_2</li>
<li>gem install ruby-oci8</li>
</ol>
<p>Should work after that. The file structure should look similar to this:</p>
<p><img src="https://i.stack.imgur.com/pTsjy.png" alt="enter image description here"></p> |
12,001,502 | How to easily reorder TabControl? | <p>I have a <code>TabControl</code> which I have designed in the VS2005 designer that has about 7 tabs.</p>
<p>How can I easily switch the order of the tabs around?</p>
<p>I put one tab at the end in a rush, but now I want it somewhere in the middle.</p> | 12,001,571 | 3 | 0 | null | 2012-08-17 07:22:57.8 UTC | 2 | 2021-04-03 09:36:28.323 UTC | 2012-08-17 07:29:04.82 UTC | null | 327,528 | null | 327,528 | null | 1 | 34 | c#|winforms|visual-studio-2005|tabcontrol | 36,847 | <p>In the properties of the tab control there's a TabPages collection. You should be able to shuffle them around in there. Just click the ellipses next to TabPages and a dialog will appear allowing you to move each one up or down in the order.</p> |
11,469,122 | Run unit tests in IntelliJ IDEA from multiple modules together | <p>How can I run all tests from two or more IDEA modules at once? </p>
<p>I'm using many modules and it is important to run all of the unit tests often and when I choose more than one folder to run, there's no 'run' option on the context menu any more.</p> | 17,678,240 | 7 | 0 | null | 2012-07-13 10:57:12.013 UTC | 27 | 2021-12-15 05:22:52.01 UTC | null | null | null | null | 990,074 | null | 1 | 104 | testing|intellij-idea | 49,947 | <p><strong>Best way way:</strong> (edit after 3 years)</p>
<p>There is even a better way to achieve this. From the <a href="https://www.jetbrains.com/help/idea/run-debug-configuration-junit.html#configTab" rel="noreferrer">JetBrains JUnit Run Configuration docs</a>:</p>
<ol>
<li><p>Select menu "Run" → "Edit Configurations...". Click green plus in left top corner and select JUnit.</p>
</li>
<li><p>Select "Test kind" to "Pattern" and enter this regexp exactly as you see it: <code>^(?!.*IT$).*$</code> (it starts with caret <code>^</code> and ends with dollar <code>$</code>). This regexp says: <em>all tests that do not finish with IT in their name</em>.</p>
<p><strong>Note:</strong> The regexp will match against the qualified file names, making it easy to exclude by module/packages as well. If your integration tests are grouped in a package <code>com.me.integrationtests</code>, the regex to match everything not in this package would be <code>^(?!.*com\.me\.integrationtests.*).*$</code>.</p>
</li>
<li><p>Select "Search for tests" to "In whole project". Working directory should be set to top module working directory (it should be set by default).</p>
</li>
<li><p>Enter a Name for your test like "All Unit tests". I also prefer to mark "Share" option so this configuration won't disappear later. Click Apply and OK.</p>
</li>
</ol>
<p>You can experiment with this regexp to fit your needs.</p>
<p><strong>Original answer:</strong></p>
<p>It is doable, although it's not comfortable.</p>
<ol>
<li>Select first module, right-click on <code>test/java</code> directory and "Run All Tests". It creates test configuration.</li>
<li>Select "Edit configurations" and check "Share" on newly created configuration so it will be saved.</li>
<li>Select second module, "Run All Tests" on it, and check "Share" on this configuration as well.</li>
<li>In "Before launch" section, click "+" and select "Run Another Configuration" and then select first module's configuration.</li>
</ol>
<p>This way you run configurations in a sequence and every configuration gets a new tab. Still, better than nothing.</p> |
11,939,166 | How to override trait function and call it from the overridden function? | <p>Scenario:</p>
<pre><code>trait A {
function calc($v) {
return $v+1;
}
}
class MyClass {
use A;
function calc($v) {
$v++;
return A::calc($v);
}
}
print (new MyClass())->calc(2); // should print 4
</code></pre>
<p>This code doesn't work, and I cannot find a way to call a trait function like it was inherited. I tried calling <code>self::calc($v)</code>, <code>static::calc($v)</code>, <code>parent::calc($v)</code>, <code>A::calc($v)</code> and the following:</p>
<pre><code>trait A {
function calc($v) {
return $v+1;
}
}
class MyClass {
use A {
calc as traitcalc;
}
function calc($v) {
$v++;
return traitcalc($v);
}
}
</code></pre>
<p>Nothing works. </p>
<p>Is there a way to make it work or must I override completely the trait function which is much more complex than this :)</p> | 11,939,306 | 6 | 0 | null | 2012-08-13 17:19:28.17 UTC | 65 | 2022-08-20 14:40:57.107 UTC | 2022-08-10 17:59:24.907 UTC | null | 7,319,250 | null | 635,786 | null | 1 | 444 | php|traits | 133,013 | <p>Your last one was almost there:</p>
<pre><code>trait A {
function calc($v) {
return $v+1;
}
}
class MyClass {
use A {
calc as protected traitcalc;
}
function calc($v) {
$v++;
return $this->traitcalc($v);
}
}
</code></pre>
<p>The trait is not a class. You can't access its members directly. It's basically just automated copy and paste...</p> |
20,107,593 | ASP.Net - It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level | <p>Getting this error on an intranet application we have running in our development environment, and I'm not sure where to go/look for a solution. The application used to work fine, however it is run on a shared server with another team of developers and we're having trouble tracking down the error (no updates were made to the application by my team, it suddenly stopped working). </p>
<p>We're running Windows Server 2003 and IIS 6.0. If I open the solution on my machine, however, I receive an error in Visual Studio solution points to this line in the web.config, however I believe this is a relatively standard setting and we actually have this running in another environment (same server/IIS set up)</p>
<pre><code><authentication mode="Windows" />
</code></pre>
<p>The error reads</p>
<pre><code>It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.
</code></pre>
<p>I've also changed the <code><system.web></code> section of the web.config on the server to include <code><customErrors mode="Off"/></code>, however oddly enough when I navigate to the site I am still getting the custom error page...</p>
<p>I'm relatively new to IIS and never worked with Windows Server 2003. Can someone help point me in the right direction either to get the actual error so display in the browser or how to fix the error given to me by Visual Studio? </p> | 20,107,906 | 7 | 6 | null | 2013-11-20 21:39:43.777 UTC | null | 2020-12-16 15:18:28.08 UTC | null | null | null | null | 1,489,378 | null | 1 | 5 | asp.net|iis|iis-6|windows-server-2003 | 51,559 | <p>Bring up project properties page in Visual Studio. Right-click on project node in Solution Explorer and click properties. Look for the Web tab and click the button to create a virtual directory.</p> |
3,613,074 | MySQLi count(*) always returns 1 | <p>I'm trying to count the number of rows in a table and thought that this was the correct way to do that:</p>
<pre><code>$result = $db->query("SELECT COUNT(*) FROM `table`;");
$count = $result->num_rows;
</code></pre>
<p>But counts always returns <code>(int)1</code>. If I use the same query in phpMyAdmin I get the right result. It sits in a table so I tried testing <code>$count[0]</code> as well, but that returns <code>NULL</code>.</p>
<p>What is the right way to do this?</p> | 3,613,087 | 4 | 0 | null | 2010-08-31 20:43:20.7 UTC | 14 | 2021-02-01 18:18:24.847 UTC | null | null | null | null | 230,422 | null | 1 | 45 | php|mysql|mysqli | 114,848 | <p>You have to fetch that one record, it will contain the result of Count()</p>
<pre><code>$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
</code></pre> |
3,793,818 | What is a good IDE for working with shell-scripting in a Windows environment? | <p>I have already learned shell-scripting in Linux environment.</p>
<p>However, now I am unable to install Linux on my PC, but I need to practice shell-scripting.</p>
<p>Currently, I have Windows XP installed on my PC. Is there any known IDE which can help me practice shell-scripting programs in windows environment?</p> | 3,805,108 | 5 | 6 | null | 2010-09-25 12:34:51.687 UTC | 14 | 2016-01-05 13:57:05.827 UTC | 2016-01-05 13:57:05.827 UTC | null | 5,299,236 | null | 459,638 | null | 1 | 25 | linux|bash|ide|windows-xp | 59,447 | <p>I found a cool <strong>Online</strong> IDE, which will perhaps help me to write simple bash scripts.</p>
<p>Here it is: <a href="http://ideone.com" rel="noreferrer">Ideone.com</a></p> |
3,737,077 | WPF TextBox won't fill in StackPanel | <p>I have a <code>TextBox</code> control within a <code>StackPanel</code> whose <code>Orientation</code> is set to <code>Horizontal</code>, but can't get the TextBox to fill the remaining StackPanel space.</p>
<p>XAML:</p>
<pre><code><Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="180" Width="324">
<StackPanel Background="Orange" Orientation="Horizontal" >
<TextBlock Text="a label" Margin="5" VerticalAlignment="Center"/>
<TextBox Height="25" HorizontalAlignment="Stretch" Width="Auto"/>
</StackPanel>
</Window>
</code></pre>
<p>And this is what it looks like:</p>
<p><img src="https://i.stack.imgur.com/kSeqt.png" alt="alt text"></p>
<p>Why is that TextBox not filling the StackPanel?</p>
<p>I know I can have more control by using a <code>Grid</code> control, I'm just confused about the layout.</p> | 3,737,120 | 6 | 0 | null | 2010-09-17 16:16:07.06 UTC | 11 | 2022-07-11 10:28:30.637 UTC | null | null | null | null | 172,387 | null | 1 | 105 | .net|wpf | 81,337 | <p>I've had the same problem with <code>StackPanel</code>, and the behavior is "by design". <code>StackPanel</code> is meant for "stacking" things even outside the visible region, so it won't allow you to fill remaining space in the stacking dimension.</p>
<p>You can use a <code>DockPanel</code> with <code>LastChildFill</code> set to <code>true</code> and dock all the non-filling controls to the <code>Left</code> to simulate the effect you want.</p>
<pre><code><DockPanel Background="Orange" LastChildFill="True">
<TextBlock Text="a label" Margin="5"
DockPanel.Dock="Left" VerticalAlignment="Center"/>
<TextBox Height="25" Width="Auto"/>
</DockPanel>
</code></pre> |
3,780,543 | How to pass an array into a PHP SoapClient call | <p>Using PHP and SoapClient.</p>
<p>I need to pass the following XML into a soap request - i.e. multiple <code><stay></code>'s within <code><stays></code>.</p>
<pre><code><reservation>
<stays>
<stay>
<start_date>2011-01-01</start_date>
<end_date>2011-01-15</end_date>
</stay>
<stay>
<start_date>2011-01-16</start_date>
<end_date>2011-01-30</end_date>
</stay>
</stays>
</reservation>
</code></pre>
<p>The problem is that I'm passing the data in as an array:</p>
<pre><code>$xml = array('reservation' => array(
'stays' => array(
array(
'start_date' => '2011-01-01',
'end_date' => 2011-01-15
),
array(
'start_date' => '2011-01-16',
'end_date' => 2011-01-30
)
)
);
</code></pre>
<p>The above doesn't work, as <code><stay></code> is not defined. So the alternative is:</p>
<pre><code>$xml = array('reservation' => array(
'stays' => array(
'stay' => array(
'start_date' => '2011-01-01',
'end_date' => 2011-01-15
),
'stay' => array(
'start_date' => '2011-01-01',
'end_date' => 2011-01-15
)
)
);
</code></pre>
<p>But that results in duplicate keys, so only one of the <code><stay></code>'s is sent.</p>
<p>I'm running this as:</p>
<pre><code>$soapClient->saveReservation($xml);
</code></pre>
<p>Any ideas on how I can structure the array so that the above XML is generated?</p>
<hr>
<p>Some further information. The above examples were super-simplified, so here's a real use example of what I'm doing, with benjy's suggestion implemented.</p>
<pre><code>$options = $this->api->getDefaultOptions();
$options['baseProductCode'] = '123'.$basket->accommodation['feed_primary_identifier'];
# ^^^^^ just to ensure it fails and doesn't process
$reservation = new stdClass();
$reservation->external_id = $order->pb_ref;
$reservation->etab_id = $basket->accommodation['feed_primary_identifier'];
$reservation->reservation_type = 'gin';
$reservation->firstname = $order->forename;
$reservation->lastname = $order->surname;
$reservation->birthdate = date('Y-m-d', strtotime('- 21 YEAR'));
$reservation->stays = array();
$details = $basket->getDetailedBasketContents();
foreach ($details['room_types'] as $roomTypeId => $roomType) {
foreach($roomType['instances'] as $instance) {
$stay = new stdClass();
$stay->nb_rooms = 1;
$stay->room_type_code = $roomTypeId;
$stay->start_date = date('Y-m-d', strtotime($order['checkin']));
$stay->end_date = date('Y-m-d', strtotime($order['checkout']));
$stay->occupants = array();
foreach($instance['occupancy']['occupants'] as $key => $occupantData) {
if ($occupantData['forename'] and $occupantData['surname']) {
$occupant = new stdClass();
$occupant->firstname = $occupantData['forename'];
$occupant->lastname = $occupantData['surname'];
$occupant->pos = 100;
$occupant->birthdate = date('Y-m-d', strtotime('- 21 YEAR'));
$stay->occupants[] = $occupant;
}
}
$reservation->stays[] = $stay;
}
}
$options['reservation'] = new stdClass();
$options['reservation']->reservation = $reservation;
//echo XmlUtil::formatXmlString($this->api->);
try {
$this->parsePlaceOrderResponse($this->api->__soapCall('saveDistribReservation2', $options));
} catch (Exception $e) {
echo $e->getMessage();
echo XmlUtil::formatXmlString($this->api->__getLastRequest());
echo XmlUtil::formatXmlString($this->api->__getLastResponse());
}
exit;
</code></pre>
<p>This fails, with the message <code>object hasn't 'stay' property</code> which is due to the same issue, that the <code><stays></code> tag should contain 1 or more <code><stay></code> tags. If I set <code>$reservation->stays['stay'] = $stay;</code> then it is accepted, but that again only allows me to have a single <code><stay></code> within <code><stays></code></p>
<p>Additionally, the SOAP request looks like this:</p>
<pre><code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:hom="homingwns" xmlns:v1="...">
<soapenv:Header/>
<soapenv:Body>
<hom:saveDistribReservation2>
<base_id>?</base_id>
<username>?</username>
<password>?</password>
<partnerCode>?</partnerCode>
<baseProductCode>?</baseProductCode>
<reservation>
<v1:reservation>
<v1:external_id>?</v1:external_id>
<v1:etab_id>?</v1:etab_id>
<v1:reservation_type>?</v1:reservation_type>
<!--Optional:-->
<v1:option_date>?</v1:option_date>
<!--Optional:-->
<v1:gender>?</v1:gender>
<!--Optional:-->
<v1:firstname>?</v1:firstname>
<v1:lastname>?</v1:lastname>
<!--Optional:-->
<v1:birthdate>?</v1:birthdate>
<!--Optional:-->
<v1:stays>
<v1:stay>
<v1:nb_rooms>?</v1:nb_rooms>
<v1:room_type_code>?</v1:room_type_code>
<v1:start_date>?</v1:start_date>
<v1:end_date>?</v1:end_date>
<!--Optional:-->
<v1:occupants>
<!--Optional:-->
<v1:occupant>
<!--Optional:-->
<v1:gender>?</v1:gender>
<!--Optional:-->
<v1:firstname>?</v1:firstname>
<v1:lastname>?</v1:lastname>
<!--Optional:-->
<v1:birthdate>?</v1:birthdate>
<v1:pos>?</v1:pos>
</v1:occupant>
</v1:occupants>
</v1:stay>
</v1:stays>
</v1:reservation>
</reservation>
</hom:saveDistribReservation2>
</soapenv:Body>
</soapenv:Envelope>
</code></pre> | 15,981,533 | 7 | 6 | null | 2010-09-23 16:33:36.34 UTC | 5 | 2021-12-02 10:37:27.807 UTC | 2017-07-14 11:12:01.077 UTC | null | 378,955 | null | 378,955 | null | 1 | 17 | php|soap-client | 39,463 | <p>'stay' has to be defined just once. This should be the right answer:</p>
<pre><code>$xml = array('reservation' => array(
'stays' => array(
'stay' => array(
array(
'start_date' => '2011-01-01',
'end_date' => 2011-01-15
),
array(
'start_date' => '2011-01-01',
'end_date' => 2011-01-15
)
)
)
));
</code></pre> |
3,888,517 | Get iPhone Status Bar Height | <p>I need to resize some elements in relation to the height of the iPhone's Status Bar. I know that the status bar is usually 20 points high but this isn't the case when it's in tethering mode. It gets doubled to 40. What is the proper way to determine it's height? I've tried </p>
<pre><code>[[UIApplication sharedApplication] statusBarFrame]
</code></pre>
<p>but it gives me 20 x 480 in landscape which is correct but then it gives me 320 x 40 in portrait. Why isn't it giving me the opposite of that (40 x 320)?</p> | 7,038,870 | 7 | 3 | null | 2010-10-08 07:33:33.677 UTC | 17 | 2019-07-08 08:26:09.457 UTC | 2019-07-08 08:26:09.457 UTC | null | 1,306,012 | null | 435,471 | null | 1 | 62 | iphone|statusbar | 63,668 | <p>The statusBarFrame returns the frame in screen coordinates. I believe the correct way to get what this corresponds to in view coordinates is to do the following:</p>
<pre><code>- (CGRect)statusBarFrameViewRect:(UIView*)view
{
CGRect statusBarFrame = [[UIApplication sharedApplication] statusBarFrame];
CGRect statusBarWindowRect = [view.window convertRect:statusBarFrame fromWindow: nil];
CGRect statusBarViewRect = [view convertRect:statusBarWindowRect fromView: nil];
return statusBarViewRect;
}
</code></pre>
<p>Now in most cases the window uses the same coordinates as the screen, so <code>[UIWindow convertRect:fromWindow:]</code> doesn't change anything, but in the case that they might be different this method should do the right thing.</p> |
3,419,847 | What is a lookup table? | <p>I just gave a database diagram for a DB I created to our head database person, and she put a bunch of notes on it suggesting that I rename certain tables so it is clear they are lookup tables (add "lu" to the beginning of the table name).</p>
<p>My problem is that these don't fit the definition of what I consider a lookup table to be. I have always considered a lookup table to basically be a set of options that don't define any relationships. Example:</p>
<pre><code>luCarMake
-----------
id Make
-- ---------
1 Audi
2 Chevy
3 Ford
</code></pre>
<p>The database person at my work is suggesting that I rename several tables that are just IDs mapping one table to another as lookup tables. Example (Location_QuadMap below):</p>
<pre><code>Location
----------
LocationId
name
description
Location_QuadMap <-- suggesting I rename this to luLocationQuad
----------------
QuadMapId
LocationId
luQuadMap
---------
QuadMapId
QuadMapName
</code></pre>
<p>Is it safe to assume that she misread the diagram, or is there another definition that I am not aware of?</p> | 3,419,868 | 8 | 0 | null | 2010-08-05 23:01:55.597 UTC | 12 | 2021-07-28 07:13:54.777 UTC | 2021-02-13 01:54:29.953 UTC | null | 12,344,822 | null | 226,897 | null | 1 | 49 | database|database-design|terminology | 101,099 | <p>What you have there is called a <a href="http://en.wikipedia.org/wiki/Junction_table" rel="noreferrer">junction table</a>. It is also known as:</p>
<ul>
<li>cross-reference table</li>
<li>bridge table</li>
<li>join table</li>
<li>map table</li>
<li>intersection table</li>
<li>linking table</li>
<li>link table</li>
</ul>
<p>But I've never seen the term "lookup table" used for this purpose.</p> |
3,963,100 | How do you do a ‘Pause’ with PowerShell 2.0? | <p>OK, I'm losing it. PowerShell is annoying me. I'd like a pause dialog to appear, and it won't.</p>
<pre><code>PS W:\>>> $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
Exception calling "ReadKey" with "1" argument(s): "The method or operation is not implemented."
At line:1 char:23
+ $host.UI.RawUI.ReadKey <<<< ("NoEcho")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
</code></pre> | 7,167,691 | 9 | 3 | null | 2010-10-18 20:27:37.467 UTC | 33 | 2022-01-13 06:15:17.687 UTC | 2014-12-27 14:53:33.653 UTC | null | 63,550 | null | 455,822 | null | 1 | 129 | powershell | 241,180 | <pre><code>cmd /c pause | out-null
</code></pre>
<p>(It is not the PowerShell way, but it's so much more elegant.)</p>
<p>Save trees. Use one-liners.</p> |
3,229,459 | Algorithm to cover maximal number of points with one circle of given radius | <p>Let's imagine we have a plane with some points on it.
We also have a circle of given radius.</p>
<p>I need an algorithm that determines such position of the circle that it covers maximal possible number of points. Of course, there are many such positions, so the algorithm should return one of them.<br>
Precision is not important and the algorithm may do small mistakes.</p>
<p>Here is an example picture:<br>
<img src="https://i.stack.imgur.com/XGdiJ.png" alt="Example"></p>
<p>Input:<br>
<code>int n</code> (n<=50) – number of points;<br>
<code>float x[n]</code> and <code>float y[n]</code> – arrays with points' X and Y coordinates;<br>
<code>float r</code> – radius of the circle.</p>
<p>Output:<br>
<code>float cx</code> and <code>float cy</code> – coordinates of the circle's center</p>
<p>Lightning speed of the algorithm is not required, but it shouldn't be too slow (because I know a few slow solutions for this situation).</p>
<p>C++ code is preferred, but not obligatory.</p> | 3,229,582 | 10 | 3 | null | 2010-07-12 14:44:12.86 UTC | 14 | 2019-10-25 11:12:36.11 UTC | 2012-02-12 17:11:01.327 UTC | null | 241,039 | null | 241,039 | null | 1 | 44 | c++|algorithm|geometry|points | 12,258 | <p>Edited to better wording, as suggested :</p>
<p>Basic observations :</p>
<ul>
<li>I assume the radius is one, since it doesn't change anything.</li>
<li>given any two points, there exists at most two unit circles on which they lie.</li>
<li>given a solution circle to your problem, you can move it until it contains two points of your set while keeping the same number of points of your set inside it.</li>
</ul>
<p>The algorithm is then:</p>
<ul>
<li>For each pair of points, if their distance is < 2, compute the two unit circles C1 and C2 that pass through them.</li>
<li>Compute the number of points of your set inside C1 and C2</li>
<li>Take the max.</li>
</ul> |
3,953,645 | Ternary operator (?:) in Bash | <p>Is there a way to do something like this</p>
<pre><code>int a = (b == 5) ? c : d;
</code></pre>
<p>using Bash?</p> | 3,953,666 | 23 | 3 | null | 2010-10-17 14:38:52.12 UTC | 114 | 2022-09-15 12:11:07.307 UTC | 2018-09-01 19:10:19.75 UTC | user166390 | 6,862,601 | null | 201,065 | null | 1 | 660 | bash|syntax|conditional-operator | 361,758 | <p>ternary operator <code>? :</code> is just short form of <code>if/else</code></p>
<pre><code>case "$b" in
5) a=$c ;;
*) a=$d ;;
esac
</code></pre>
<p>Or</p>
<pre><code> [[ $b = 5 ]] && a="$c" || a="$d"
</code></pre> |
3,302,476 | Mysql 1050 Error "Table already exists" when in fact, it does not | <p>I'm adding this table:</p>
<pre><code>CREATE TABLE contenttype (
contenttypeid INT UNSIGNED NOT NULL AUTO_INCREMENT,
class VARBINARY(50) NOT NULL,
packageid INT UNSIGNED NOT NULL,
canplace ENUM('0','1') NOT NULL DEFAULT '0',
cansearch ENUM('0','1') NOT NULL DEFAULT '0',
cantag ENUM('0','1') DEFAULT '0',
canattach ENUM('0','1') DEFAULT '0',
isaggregator ENUM('0', '1') NOT NULL DEFAULT '0',
PRIMARY KEY (contenttypeid),
UNIQUE KEY packageclass (packageid, class)
);
</code></pre>
<p>And I get a 1050 "table already exists"</p>
<p>But the table does NOT exist. Any ideas?</p>
<p>EDIT: more details because everyone seems to not believe me :)</p>
<pre><code>DESCRIBE contenttype
</code></pre>
<p>yields:</p>
<blockquote>
<p>1146 - Table 'gunzfact_vbforumdb.contenttype' doesn't exist</p>
</blockquote>
<p>and</p>
<pre><code>CREATE TABLE gunzfact_vbforumdb.contenttype(
contenttypeid INT UNSIGNED NOT NULL AUTO_INCREMENT ,
class VARBINARY( 50 ) NOT NULL ,
packageid INT UNSIGNED NOT NULL ,
canplace ENUM( '0', '1' ) NOT NULL DEFAULT '0',
cansearch ENUM( '0', '1' ) NOT NULL DEFAULT '0',
cantag ENUM( '0', '1' ) DEFAULT '0',
canattach ENUM( '0', '1' ) DEFAULT '0',
isaggregator ENUM( '0', '1' ) NOT NULL DEFAULT '0',
PRIMARY KEY ( contenttypeid ) ,
</code></pre>
<p>Yields:</p>
<blockquote>
<p>1050 - Table 'contenttype' already exists</p>
</blockquote> | 3,302,837 | 26 | 7 | null | 2010-07-21 18:22:21.58 UTC | 35 | 2022-01-18 23:33:10.973 UTC | 2011-03-28 01:59:28.753 UTC | null | 135,152 | null | 175,250 | null | 1 | 86 | mysql|sql|mysql-error-1146|mysql-error-1050 | 325,144 | <p>Sounds like you have <a href="http://en.wikipedia.org/wiki/Schr%C3%B6dinger's_cat" rel="noreferrer">Schroedinger's table</a>... </p>
<p>Seriously now, you probably have a broken table. Try:</p>
<ul>
<li><code>DROP TABLE IF EXISTS contenttype</code></li>
<li><code>REPAIR TABLE contenttype</code></li>
<li>If you have sufficient permissions, delete the data files (in /mysql/data/db_name)</li>
</ul> |
3,601,515 | How to check if a variable is set in Bash | <p>How do I know if a variable is set in Bash?</p>
<p>For example, how do I check if the user gave the first parameter to a function?</p>
<pre><code>function a {
# if $1 is set ?
}
</code></pre> | 13,864,829 | 37 | 12 | null | 2010-08-30 14:54:38.197 UTC | 705 | 2022-09-04 21:17:16.753 UTC | 2022-03-01 17:18:19.13 UTC | null | 63,550 | null | 260,127 | null | 1 | 2,184 | bash|shell|variables | 1,956,415 | <h2>(Usually) The right way</h2>
<pre><code>if [ -z ${var+x} ]; then echo "var is unset"; else echo "var is set to '$var'"; fi
</code></pre>
<p>where <code>${var+x}</code> is a <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02" rel="noreferrer">parameter expansion</a> which evaluates to nothing if <code>var</code> is unset, and substitutes the string <code>x</code> otherwise.</p>
<h3>Quotes Digression</h3>
<p>Quotes can be omitted (so we can say <code>${var+x}</code> instead of <code>"${var+x}"</code>) because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands to <code>x</code> (which contains no word breaks so it needs no quotes), or to nothing (which results in <code>[ -z ]</code>, which conveniently evaluates to the same value (true) that <code>[ -z "" ]</code> does as well)).</p>
<p>However, while quotes can be safely omitted, and it was not immediately obvious to all (it wasn't even apparent to <a href="https://stackoverflow.com/users/2255628/destiny-architect">the first author of this quotes explanation</a> who is also a major Bash coder), it would sometimes be better to write the solution with quotes as <code>[ -z "${var+x}" ]</code>, at the very small possible cost of an O(1) speed penalty. The first author also added this as a comment next to the code using this solution giving the URL to this answer, which now also includes the explanation for why the quotes can be safely omitted.</p>
<h2>(Often) The wrong way</h2>
<pre><code>if [ -z "$var" ]; then echo "var is blank"; else echo "var is set to '$var'"; fi
</code></pre>
<p>This is often wrong because it doesn't distinguish between a variable that is unset and a variable that is set to the empty string. That is to say, if <code>var=''</code>, then the above solution will output "var is blank".</p>
<p>The distinction between unset and "set to the empty string" is essential in situations where the user has to specify an extension, or additional list of properties, and that not specifying them defaults to a non-empty value, whereas specifying the empty string should make the script use an empty extension or list of additional properties.</p>
<p>The distinction may not be essential in every scenario though. In those cases <code>[ -z "$var" ]</code> will be just fine.</p> |
8,349,817 | Ruby gem for finding timezone of location | <p>I have a location (city, state), date, and time and I want to convert it to utc, but need to first find the timezone of the location. I've done a little research and everything seems to point to either earthtools or geonames but both webservices appear to be latitude and longitude only. Is there a service or gem or any other way to find the timezone based on this format of location? or how can the location be converted to latitude and longitude?</p> | 8,350,225 | 5 | 1 | null | 2011-12-01 23:24:49.423 UTC | 11 | 2019-10-22 11:44:17.213 UTC | null | null | null | null | 1,076,471 | null | 1 | 28 | ruby|web-services|timezone|gem|location | 13,299 | <p>You can easily get a latitude and longitude using the <a href="http://code.google.com/apis/maps/documentation/geocoding" rel="noreferrer">google maps geocoding API</a>. There are ruby implementations for the API like <a href="http://geokit.rubyforge.org" rel="noreferrer">GeoKit</a>. Once you have that you can use the <a href="https://rubygems.org/gems/timezone" rel="noreferrer">timezone gem</a> to easily get the timezone of a latitude and longitude. The gem makes it easy to do time conversions in your timezone as well.</p>
<p>Here is an example using <a href="https://github.com/andre/geokit-gem" rel="noreferrer">GeoKit</a> and <a href="https://github.com/panthomakos/timezone" rel="noreferrer">TimeZone</a>.</p>
<pre><code>require 'geokit'
require 'timezone'
res = Geokit::Geocoders::GoogleGeocoder.geocode('140 Market St, San Francisco, CA')
timezone = Timezone::Zone.new(:latlon => res.ll)
timezone.zone
=> "America/Los_Angeles"
timezone.time Time.now
=> 2011-12-01 14:02:13 UTC
</code></pre> |
7,734,202 | Boolean.parseBoolean("1") = false...? | <p>sorry to be a pain... I have: <code>HashMap<String, String> o</code></p>
<pre><code>o.get('uses_votes'); // "1"
</code></pre>
<p>Yet...</p>
<pre><code>Boolean.parseBoolean(o.get('uses_votes')); // "false"
</code></pre>
<p>I'm guessing that <code>....parseBoolean</code> doesn't accept the standard <code>0 = false</code> <code>1 = true</code>?</p>
<p>Am I doing something wrong or will I have to wrap my code in:</p>
<pre><code>boolean uses_votes = false;
if(o.get('uses_votes').equals("1")) {
uses_votes = true;
}
</code></pre>
<p>Thanks</p> | 7,734,219 | 11 | 0 | null | 2011-10-12 01:02:55.07 UTC | 7 | 2019-07-12 16:39:19.86 UTC | null | null | null | null | 414,972 | null | 1 | 85 | java | 135,089 | <p>It accepts only a string value of <code>"true"</code> to represent boolean <code>true</code>. Best what you can do is</p>
<pre><code>boolean uses_votes = "1".equals(o.get("uses_votes"));
</code></pre>
<p>Or if the <code>Map</code> actually represents an "entitiy", I think a <a href="https://stackoverflow.com/tags/javabeans/info">Javabean</a> is way much better. Or if it represents configuration settings, you may want to take a look into <a href="http://commons.apache.org/configuration/" rel="noreferrer">Apache Commons Configuration</a>.</p> |
8,050,854 | How to find maximum avg | <p>I am trying to display the maximum average salary; however, I can't seem to get it to work.</p>
<p>I can get a list of the average salaries to display with:</p>
<pre><code>select worker_id, avg(salary)
from workers
group by worker_id;
</code></pre>
<p>However, when I try to display a list of the maximum average salary with:</p>
<pre><code>select max (avg(salary))
from (select worker_id, avg(salary)
from workers
group by worker_id);
</code></pre>
<p>it doesn't run. I get an "invalid identifier" error. How do I use the average salary for each worker to find the maximum average for each worker?</p>
<p>Thanks.</p> | 8,050,885 | 15 | 2 | null | 2011-11-08 13:07:17.87 UTC | 4 | 2020-10-12 13:55:19.707 UTC | null | null | null | null | 1,035,270 | null | 1 | 19 | sql|oracle | 108,616 | <p>Columns resulting from aggregate functions (e.g. avg) usually get arbitrary names. Just use an alias for it, and select on that:</p>
<pre><code>select max(avg_salary)
from (select worker_id, avg(salary) AS avg_salary
from workers
group by worker_id) As maxSalary;
</code></pre> |
8,204,680 | Java regex email | <p>First of all, I know that using regex for email is not recommended but I gotta test this out.</p>
<p>I have this regex:</p>
<pre><code>\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
</code></pre>
<p>In Java, I did this:</p>
<pre><code>Pattern p = Pattern.compile("\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b");
Matcher m = p.matcher("[email protected]");
if (m.find())
System.out.println("Correct!");
</code></pre>
<p>However, the regex fails regardless of whether the email is wel-formed or not. A "find and replace" inside Eclipse works fine with the same regex.</p>
<p>Any idea?</p>
<p>Thanks,</p> | 8,204,716 | 22 | 3 | null | 2011-11-20 20:58:21.13 UTC | 52 | 2021-12-01 12:55:20.957 UTC | 2014-03-28 21:56:53.863 UTC | null | 801,807 | null | 801,807 | null | 1 | 149 | java|regex|email | 366,414 | <p>FWIW, here is the Java code we use to validate email addresses. The Regexp's are very similar:</p>
<pre><code>public static final Pattern VALID_EMAIL_ADDRESS_REGEX =
Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", Pattern.CASE_INSENSITIVE);
public static boolean validate(String emailStr) {
Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(emailStr);
return matcher.find();
}
</code></pre>
<p>Works fairly reliably.</p> |
4,780,586 | How to get friends likes via Facebook API | <p>Is this possible to get all my friends likes?? Now, I'm getting this by 2 steps:</p>
<ol>
<li>Getting all my friends list</li>
<li>By iterating those list I'm getting all individuals Likes,</li>
</ol>
<p>but it seems very big process, anybody have idea to improve the performance for this task?</p> | 5,323,807 | 3 | 0 | null | 2011-01-24 09:48:42.463 UTC | 12 | 2015-06-04 23:43:12.64 UTC | null | null | null | null | 444,521 | null | 1 | 13 | facebook|facebook-graph-api|facebook-fql | 19,447 | <p>At last I found it after 2 weeks looking at Facebook API documentation</p>
<pre class="lang-js prettyprint-override"><code>FB.api("/likes?ids=533856945,841978743")
FB.api("me/friends",{
fields:'id',
limit:10
},function(res){
var l=''
$.each(res.data,function(idx,val){
l=l+val.id+(idx<res.data.length-1?',':'')
})
FB.api("likes?ids="+l,function(res){
console.log(res);
})
})
</code></pre> |
4,584,882 | How to change focus color of EditText in Android | <p>How can I change the focus color (orange) on an <code>EditText</code> box?</p>
<p>The focus color is a small rim around the entire control and is bright
orange when the control has focus. How can I change the color of that
focus to a different color?</p> | 4,585,750 | 3 | 0 | null | 2011-01-03 13:36:26.447 UTC | 20 | 2019-09-12 11:58:01.79 UTC | 2019-09-12 11:58:01.79 UTC | null | 452,775 | null | 429,501 | null | 1 | 40 | android|android-edittext|android-styles | 76,640 | <p>You'll have to create/modify your own NinePatch image to replace the default one, and use that as the background of your EditText. If you look in your SDK folder, under your platform, then res/drawable, you should find the NinePatch image for the EditText focus state. If that's all you want to change, you can just pull it into Photoshop, or whatever image editing software you have, and change the orange color to a color of your choosing. Then save that into your drawable folder, and build a new StateListDrawable, for example something like the below:</p>
<p><strong>edittext_modified_states.xml</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android"
>
<item
android:state_pressed="true"
android:drawable="@android:drawable/edittext_pressed"
/> <!-- pressed -->
<item
android:state_focused="true"
android:drawable="@drawable/edittext_focused_blue"
/> <!-- focused -->
<item
android:drawable="@android:drawable/edittext_normal"
/> <!-- default -->
</selector>
</code></pre>
<p>I don't know offhand the actual names for the default NinePatches for the EditText, so replace those as necessary, but the key here is to just use the <code>@android:drawable</code> images for the ones you haven't modified (or you can copy them over to your project's drawable folder), and then use your modified drawable for your focused state.</p>
<p>You can then set this StateListDrawable as the background for your TextView, like so:</p>
<pre><code><TextView
android:background="@drawable/edittext_modified_states"
</code></pre> |
4,701,928 | Disable Lock Screen | <p>I am looking for a way to replace the stock lock screen (with an app, not a rom).
What is the best way to do it, for a start to disable the lock screen on as much devices as possible?
Thanks!</p> | 6,095,866 | 4 | 1 | null | 2011-01-15 20:21:11.943 UTC | 12 | 2016-02-03 13:11:51.783 UTC | null | null | null | null | 246,206 | null | 1 | 23 | android | 36,825 | <pre><code>KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
</code></pre>
<p>in androidmanifest:</p>
<pre><code><uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
</code></pre> |
4,398,136 | Use PowerShell for Visual Studio Command Prompt | <p>In a serious intiative to migrate all my command line operations to PowerShell, I would like to avoid using the old fashioned command console for anything. However, the Visual Studio Command prompt has various environment variables and path settings not found in the default command prompt. How could I create a 'Visual Studio PowerShell' with those same settings?</p> | 4,398,325 | 6 | 1 | null | 2010-12-09 12:22:43.677 UTC | 13 | 2021-10-04 12:39:41.56 UTC | null | null | null | null | 8,741 | null | 1 | 21 | windows|visual-studio|windows-7|powershell | 9,750 | <p>You can use for example <a href="https://stackoverflow.com/questions/4384814/how-to-call-batch-script-from-powershell/4385011#4385011">this script</a> to import Visual Studio command prompt environment, see the examples in the script documentation comments, e.g. for Visual Studio 2010:</p>
<pre><code>Invoke-Environment '"%VS100COMNTOOLS%\vsvars32.bat"'
</code></pre>
<p>Having done that in the beginning of a PowerShell session (from your profile or manually), you get what you ask for in this PowerShell session.</p>
<p>Or you can use the solution provided by Keith Hill in <a href="https://stackoverflow.com/questions/4384814/how-to-call-batch-script-from-powershell/4388217#4388217">this answer</a>.</p> |
4,240,050 | Python: sort function breaks in the presence of nan | <p><code>sorted([2, float('nan'), 1])</code> returns <code>[2, nan, 1]</code></p>
<p>(At least on Activestate Python 3.1 implementation.)</p>
<p>I understand <code>nan</code> is a weird object, so I wouldn't be surprised if it shows up in random places in the sort result. But it also messes up the sort for the non-nan numbers in the container, which is really unexpected.</p>
<p>I asked a <a href="https://stackoverflow.com/questions/4237914/python-max-min-builtin-functions-depend-on-parameter-order">related question</a> about <code>max</code>, and based on that I understand why <code>sort</code> works like this. But should this be considered a bug?</p>
<p>Documentation just says "Return a new sorted list [...]" without specifying any details.</p>
<p>EDIT:
I now agree that this isn't in violation of the IEEE standard. However, it's a bug from any common sense viewpoint, I think. Even Microsoft, which isn't known to admit their mistakes often, has recognized this one as a bug, and fixed it in the latest version: <a href="http://connect.microsoft.com/VisualStudio/feedback/details/363379/bug-in-list-double-sort-in-list-which-contains-double-nan" rel="noreferrer">http://connect.microsoft.com/VisualStudio/feedback/details/363379/bug-in-list-double-sort-in-list-which-contains-double-nan</a>.</p>
<p>Anyway, I ended up following @khachik's answer:</p>
<pre><code>sorted(list_, key = lambda x : float('-inf') if math.isnan(x) else x)
</code></pre>
<p>I suspect it results in a performance hit compared to the language doing that by default, but at least it works (barring any bugs that I introduced).</p> | 7,165,183 | 8 | 5 | null | 2010-11-21 20:05:54.62 UTC | 7 | 2021-11-18 08:09:06.917 UTC | 2017-05-23 12:09:56.23 UTC | null | -1 | null | 336,527 | null | 1 | 47 | python|math|sorting|nan | 12,382 | <p>The previous answers are useful, but perhaps not clear regarding the root of the problem.</p>
<p>In any language, sort applies a given ordering, defined by a comparison function or in some other way, over the domain of the input values. For example, less-than, a.k.a. <code>operator <,</code> could be used throughout if and only if less than defines a suitable ordering over the input values.</p>
<p>But this is specifically NOT true for floating point values and less-than:
"NaN is unordered: it is not equal to, greater than, or less than anything, including itself." (<strong>Clear prose from GNU C manual,</strong> but applies to all modern <code>IEEE754</code> based <strong>floating point</strong>)</p>
<p>So the possible solutions are:</p>
<blockquote>
<ol>
<li>remove the NaNs first, making the input domain well defined via <
(or the other sorting function being used)</li>
<li>define a custom comparison function (a.k.a. predicate) that does
define an ordering for NaN, such as less than any number, or greater
than any number.</li>
</ol>
</blockquote>
<p>Either approach can be used, in any language.</p>
<p>Practically, considering python, I would prefer to remove the NaNs if you either don't care much about fastest performance or if removing NaNs is a desired behavior in context. </p>
<p>Otherwise you could use a suitable predicate function via "cmp" in older python versions, or via this and <code>functools.cmp_to_key()</code>. The latter is a bit more awkward, naturally, than removing the NaNs first. And care will be required to avoid <em>worse</em> performance, when defining this predicate function.</p> |
4,053,918 | How to portably write std::wstring to file? | <p>I have a <code>wstring</code> declared as such:</p>
<pre><code>// random wstring
std::wstring str = L"abcàdëefŸg€hhhhhhhµa";
</code></pre>
<p><strike>The literal would be UTF-8 encoded, because my source file is.</strike></p>
<p>[EDIT: According to Mark Ransom this is not necessarily the case, the compiler will decide what encoding to use - let us instead assume that I read this string from a file encoded in e.g. UTF-8]</p>
<p>I would very much like to get this into a file reading (when text editor is set to the correct encoding)</p>
<pre><code>abcàdëefŸg€hhhhhhhµa
</code></pre>
<p>but <code>ofstream</code> is not very cooperative (refuses to take <code>wstring</code> parameters), and <code>wofstream</code> supposedly needs to know locale and encoding settings. I just want to output this set of bytes. How does one normally do this?</p>
<p>EDIT: It must be cross platform, and <strong>should not rely on the encoding being UTF-8</strong>. I just happen to have a set of bytes stored in a <code>wstring</code>, and want to output them. It could very well be UTF-16, or plain ASCII.</p> | 4,054,138 | 9 | 5 | null | 2010-10-29 16:31:49.427 UTC | 6 | 2019-02-08 18:19:15.917 UTC | 2013-08-25 14:44:51.58 UTC | null | 1,237,747 | user1481860 | null | null | 1 | 23 | c++|file|unicode|wstring|wofstream | 39,639 | <p>Why not write the file as a binary. Just use ofstream with the std::ios::binary setting. The editor should be able to interpret it then. Don't forget the Unicode flag 0xFEFF at the beginning.
You might be better of writing with a library, try one of these:</p>
<p><a href="http://www.codeproject.com/KB/files/EZUTF.aspx" rel="noreferrer">http://www.codeproject.com/KB/files/EZUTF.aspx</a></p>
<p><a href="http://www.gnu.org/software/libiconv/" rel="noreferrer">http://www.gnu.org/software/libiconv/</a></p>
<p><a href="http://utfcpp.sourceforge.net/" rel="noreferrer">http://utfcpp.sourceforge.net/</a></p> |
4,337,942 | Using enum vs Boolean? | <p>This may initially seem generic, but in fact, I am actually making the decision on which I need to use.</p>
<p>What I am currently working on involves Employment Applications, those in which will need to be marked at some point <b>Active</b> or <b>Inactive</b>. When an application is submitted, it will default to <b>Active</b>. For certain reasons, it might later be set to <b>Inactive</b>. It can only be one of these and never <b>null</b>(In case this changes anything).</p>
<p>I am using this with <b>Java + Hibernate + PostgresSQL</b>, in case this also makes any difference. My first instinct is to use <b>Boolean</b> as my solution so that it truly acts as a flag, but I have coworkers who have suggested using <b>enums</b> or <b>ints</b> as more of a status rather then a flag. </p>
<p>I have solved problems such as this using all of the above solutions, and they all seem somewhat transparent to eachother. </p>
<p><b>Is there one way that is better for this situation?</b></p> | 4,338,016 | 11 | 1 | null | 2010-12-02 17:31:59.797 UTC | 2 | 2022-09-22 23:23:30.283 UTC | null | null | null | null | 180,253 | null | 1 | 27 | java|hibernate|postgresql | 39,841 | <p>It totally depends on your requirement/specification. If you only want to record the status as active or inactive, the best way is to use <code>boolean</code>.</p>
<p>But if in the future, you will have a status such as, </p>
<ul>
<li>ACTIVE</li>
<li>INACTIVE</li>
<li>SUSPENDED</li>
<li>BLOCKED</li>
</ul>
<p>Enums is perfect for you. In your case, for now, a boolean is sufficient. Don't try overcomplicate things too early, you'll lose focus in your design & development of your system.</p> |
14,863,536 | Iterate through Python dictionary by Keys in sorted order | <p>I have a dictionary in Python that looks like this:</p>
<pre><code>D = {1:'a', 5:'b', 2:'a', 7:'a'}
</code></pre>
<p>The values of the keys are mostly irrelevant. Is there are way to iterate through the dictionary by keys in numerical order? The keys are all integers.</p>
<p>Instead of saying</p>
<pre><code>for key in D:
# some code...
</code></pre>
<p>Can I go through the dictionary keys in the order <code>1, 2, 5, 7</code>?</p>
<p>Additionally, I cannot use the sort/sorted functions.</p> | 14,863,575 | 4 | 0 | null | 2013-02-13 21:31:53.61 UTC | 4 | 2019-01-31 16:52:02.2 UTC | 2019-01-31 16:52:02.2 UTC | null | 10,607,772 | null | 1,760,431 | null | 1 | 35 | python|loops|sorting|dictionary | 47,119 | <p>You can use this:</p>
<pre><code>for key in sorted(D.iterkeys()):
.. code ..
</code></pre>
<p>In Python 3.x, use <code>D.keys()</code> (which is the same as <code>D.iterkeys()</code> in Python 2.x).</p> |
14,897,608 | Cancel a AngularJS $timeout on routeChange | <p>On a specific page in my application I think of doing a server-call to update information on a set interval.
I stumbled upon a problem though. I want to cancel my $timeout when a user navigates away from the page in question so that the application doesn't try to work with stuff that isn't there anymore.</p>
<p>Any ideas on how to work around this?</p> | 18,059,591 | 1 | 0 | null | 2013-02-15 15:11:32.867 UTC | 3 | 2015-07-28 19:55:08.157 UTC | null | null | null | null | 384,868 | null | 1 | 37 | javascript|timeout|angularjs | 32,305 | <p>Use <code>$timeout.cancel</code> like this:</p>
<pre><code>yourTimer = $timeout(function() { /* ... */ }, 5000);
$timeout.cancel(yourTimer);
</code></pre>
<p><a href="http://docs.angularjs.org/api/ng.%24timeout">Reference</a></p> |
9,748,524 | jQuery: Get each checked radio button and append its datasrc value | <p>I am having a problem when trying to use each() twice.</p>
<p>I have a list of radio checked buttons of which each has a datasrc of a website.</p>
<p>Example:</p>
<pre><code><input type="radio" checked datasrc="www.john.com" id="John">John<br/>
<input type="radio" checked datasrc="www.maria.com" id="Maria">Maria<br/>
<input type="radio" datasrc="www.joe.com" id="Joe">Joe<br/>
</code></pre>
<p>I want to retrieve each checked radio button so I do this:</p>
<pre><code>$("input:radio").each(function(){
var name = $(this).attr("id");
if($("[id="+name+"]:checked").length == 1)
{
var src = $('#' + name).attr("datasrc")
console.log(name);
console.log(src);
}
});
</code></pre>
<p>Now when I retrieve every checked radio button, I want to append it with id its id and for value, its datasrc. For example:</p>
<pre><code><div id="John">www.john.com</div>
<div id="Maria">www.maria.com</div>
</code></pre>
<p>When I tried using each again I get manage to get it printed but several times. For example john will print 4 times and maria will print 5 times (the amount of the id).</p>
<p>For example:</p>
<pre><code>$("input:radio").each(function () {
var name = $(this).attr("id");
if ($("[id=" + name + "]:checked").length == 1) {
var src = $('#' + name).attr("datasrc")
var html = "";
for (i = 0; i < name.length; i++) {
html += "<div id='" + name + "'>" + src + "</div>"
}
$("body").append(html);
}
});
</code></pre>
<p>Will print:</p>
<pre><code>www.john.com
www.john.com
www.john.com
www.john.com
www.maria.com
www.maria.com
www.maria.com
www.maria.com
www.maria.com
</code></pre>
<p>What I'm I doing wrong?</p> | 9,748,594 | 4 | 0 | null | 2012-03-17 08:40:39.233 UTC | 2 | 2012-03-17 21:45:18.843 UTC | null | null | null | null | 701,363 | null | 1 | 1 | jquery|append|each | 42,100 | <p>It's because you're nesting a for loop inside each so the results of the for loop run as many times as the each loop...You don't need the for loop though, a simple array and and <code>each()</code> will work:</p>
<p><strong>Edit:</strong> Made it a function so you can use it at any time.</p>
<pre><code>var getUrls = function () {
var urls = [];
$('input:radio').each(function () {
var $this = $(this),
id = $this.attr('id'),
url = $this.attr('datasrc');
if ($(this).prop('checked')) {
urls.push('<div class="' + id + '">' + url + '</div>');
}
});
return urls;
};
$('body').append(getUrls().join(''));
</code></pre> |
2,591,897 | Which font and size does apple use for the navigation bar title? | <p>I made an totally custom navigation bar and would like to use the exact same font and size like apple does for the title of their navigation bar. It looks like some kind of fat printed arial, but not sure if that's right. Does anyone know?</p> | 2,592,022 | 4 | 0 | null | 2010-04-07 11:16:20.263 UTC | 5 | 2021-11-24 13:17:11.523 UTC | 2010-04-07 11:36:55.263 UTC | null | 74,118 | null | 268,733 | null | 1 | 28 | iphone|cocoa-touch|user-interface | 23,272 | <p>Definitely not Arial. It's Helvetica. You can probably get the same font using </p>
<pre><code>UIFont *navFont = [UIFont boldSystemFontOfSize:18];
</code></pre>
<p>Change the size to find out what Apple is using (and write it below in a comment if you find the best one).</p>
<p>All the navigation bar text has a white shadow underneath it to give it the embossed effect. It's a white shadow 1 pixel underneath the text. Use <code>shadowColor</code> and <code>shadowOffset</code> in a <code>UILabel</code> to get the same effect.</p> |
3,130,541 | Access Query string parameters with no values in ASP.NET | <p>I am trying to set up a page that has two behaviors. I'm separating them by URL: One behavior is accessed via <code>/some-controller/some-action</code>, the other is via <code>/some-controller/some-action?customize</code>. </p>
<p>It doesn't look like the Request.QueryString object contains anything, though, when I visit the second URL...I mean, the keys collection has one element in it, but it's <code>null</code>, not <code>'customize'</code>. Anyone have any ideas about this or how to enable this. I'd like to avoid manually parsing the query string at all costs :).</p> | 3,130,553 | 4 | 0 | null | 2010-06-28 06:47:49.16 UTC | 7 | 2016-10-26 00:01:14.733 UTC | 2016-10-26 00:01:14.733 UTC | null | 2,864,740 | null | 176,645 | null | 1 | 30 | c#|asp.net|query-string | 27,814 | <p>ASP.NET does not support determining the presence of query string parameters without values since <code>Request.QueryString["customize"]</code> and <code>Request.QueryString["foo"]</code> are both <code>null</code>. You'll either have to parse it yourself or specify a value e.g. <code>?customize=1</code></p> |
27,616,778 | Case insensitive argparse choices | <p>Is it possible to check <a href="https://docs.python.org/3/library/argparse.html#choices">argparse choices</a> in case-insensitive manner?</p>
<pre><code>import argparse
choices = ["win64", "win32"]
parser = argparse.ArgumentParser()
parser.add_argument("-p", choices=choices)
print(parser.parse_args(["-p", "Win32"]))
</code></pre>
<p>results in:</p>
<pre><code>usage: choices.py [-h] [-p {win64,win32}]
choices.py: error: argument -p: invalid choice: 'Win32' (choose from 'win64','win32')
</code></pre> | 27,616,814 | 4 | 0 | null | 2014-12-23 08:39:09.773 UTC | 5 | 2022-03-29 19:17:48.433 UTC | null | null | null | null | 2,838,364 | null | 1 | 87 | python|argparse|case-insensitive | 27,917 | <p>Transform the argument into lowercase by using</p>
<pre><code>type = str.lower
</code></pre>
<p>for the <code>-p</code> switch. </p>
<p>This solution was pointed out by <a href="https://stackoverflow.com/users/1126841/chepner">chepner</a> in a <a href="https://stackoverflow.com/questions/27616778/case-insensitive-argparse-choices#comment43678050_27616814">comment</a>. The solution I proposed earlier was</p>
<pre><code>type = lambda s : s.lower()
</code></pre>
<p>which is also valid, but it's simpler to just use <code>str.lower</code>. </p> |
29,876,904 | How do I take code from Codepen, and use it locally? | <p>How do I take the code from codepen, and use it locally in my text-editor?</p>
<p><a href="http://codepen.io/mfields/pen/BhILt">http://codepen.io/mfields/pen/BhILt</a></p>
<p>I am trying to have a play with this creation locally, but when I open it in chrome, I get a blank white page with nothing going on.</p>
<pre><code><!DOCTYPE HTML>
<html>
<head>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="celtic.js"></script>
<link rel="stylesheet" type="text/css" src="celtic.css"></link>
</head>
<body>
<canvas id="animation" width="400" height="400"></canvas>
</body>
</html>
</code></pre>
<p>I have copy, pasted and saved the css and js into different files and saved them, then tried to link them into the html file as I have shown above.</p>
<p>I have also included the jquery library as I understand a lot of the codepen creations use it.</p>
<p>The only console error I'm getting is </p>
<pre><code>Uncaught TypeError: Cannot read property 'getContext' of null
</code></pre>
<p>which is linking to my js file, line 4</p>
<pre><code>(function(){
var canvas = document.getElementById( 'animation' ),
c = canvas.getContext( '2d' ),
</code></pre>
<p>Sorry if this is dumb, but I'm new to all this.
I'm sure this is basic as hell. Any help would be awesome!</p> | 29,877,026 | 5 | 0 | null | 2015-04-26 11:14:51.133 UTC | 9 | 2016-09-28 11:33:08.76 UTC | null | null | null | null | 4,141,578 | null | 1 | 20 | javascript|css|html|html5-canvas | 41,557 | <p>Joe Fitter is right, but I think is better to <a href="https://blog.codepen.io/documentation/features/exporting-pens/" rel="noreferrer">export your pen</a> (use the export to export.zip option for using your pen locally). This will give you a working version of your pen without having to copy and paste the CSS, JavaScript and HTML code and without having to make changes on it for making it work.</p> |
35,132,687 | How to access externally to consul UI | <p>How can I access to consul UI externally?</p>
<p>I want to access consul UI writing </p>
<p><code><ANY_MASTER_OR_SLAVE_NODE_IP>:8500</code></p>
<p>I have try doing a ssh tunnel to acces:
ssh -N -f -L 8500:localhost:8500 [email protected]</p>
<p>Then if I access <a href="http://localhost:8500">http://localhost:8500</a>
It works, but it is not what I want. I need to access externally, without ssh tunnel.</p>
<p>My config.json file is the next:</p>
<pre><code>{
"bind_addr":"172.16.8.216",
"server": false,
"datacenter": "nyc2",
"data_dir": "/var/consul",
"ui_dir": "/home/ikerlan/dist",
"log_level": "INFO",
"enable_syslog": true,
"start_join": ["172.16.8.211","172.16.8.212","172.16.8.213"]
}
</code></pre>
<p>Any help?
Thanks</p> | 35,276,638 | 6 | 0 | null | 2016-02-01 14:11:29.043 UTC | 12 | 2019-07-14 14:53:11.757 UTC | 2016-02-16 17:06:16.84 UTC | null | 5,621,509 | null | 5,621,509 | null | 1 | 32 | consul | 25,158 | <p>Add</p>
<pre><code>{
"client_addr": "0.0.0.0"
}
</code></pre>
<p>to your configuration or add the option <code>-client 0.0.0.0</code> to the command line of consul to make your Web UI accessible from the outside (<a href="https://www.consul.io/docs/agent/options.html">see the docs for more information</a>).</p>
<p>Please note that this will also make your Consul REST API accessible from the outside. Depending on your environment you might want to activate Consul's ACLs to restrict access.</p> |
Subsets and Splits