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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5,606,541 | How to capture a list of specific type with mockito | <p>Is there a way to capture a list of specific type using mockitos ArgumentCaptore. This doesn't work:</p>
<pre><code>ArgumentCaptor<ArrayList<SomeType>> argument = ArgumentCaptor.forClass(ArrayList.class);
</code></pre> | 5,655,702 | 8 | 1 | null | 2011-04-09 17:17:25.497 UTC | 43 | 2022-01-03 16:53:35.85 UTC | 2014-12-01 21:40:49.147 UTC | null | 32,453 | null | 184,883 | null | 1 | 357 | java|unit-testing|junit|mockito | 188,900 | <p>The nested generics-problem can be avoided with the <a href="http://site.mockito.org/mockito/docs/current/org/mockito/Captor.html" rel="noreferrer">@Captor annotation</a>:</p>
<pre><code>public class Test{
@Mock
private Service service;
@Captor
private ArgumentCaptor<ArrayList<SomeType>> captor;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test
public void shouldDoStuffWithListValues() {
//...
verify(service).doStuff(captor.capture()));
}
}
</code></pre> |
5,518,826 | How to have a nested inline formset within a form in Django? | <p>I hope this question has not been asked yet, but I want to know if it is possible to have a normal class-based form for an object and to have an inline formset inside it to edit its related objects. </p>
<p>For example, I have a Contact model<br></p>
<pre><code>class Contact(models.Model):
...
</code></pre>
<p><br>
And a Communication model<br></p>
<pre><code>class Communication(models.Model):
contact = models.ForeignKey(Contact)
</code></pre>
<p><br></p>
<p>and I want to have a form for Contact with a inline formset nested in it for managing communications related to it.</p>
<p>Is it possible to do so with existing components or do I have a hopeless dream?</p>
<p>EDIT : I know that the admin panel does it, but how do I make work in a view?</p> | 5,518,841 | 1 | 0 | null | 2011-04-01 21:02:58.06 UTC | 12 | 2021-03-09 22:40:15.97 UTC | 2018-05-28 14:37:12.94 UTC | null | 6,243,838 | null | 688,290 | null | 1 | 17 | python|django|django-templates|django-forms | 14,527 | <p>Of course it's possible - how do you think the admin does it?</p>
<p>Take a look at the <a href="http://docs.djangoproject.com/en/stable/topics/forms/modelforms/#inline-formsets" rel="nofollow noreferrer">inline formsets documentation</a>.</p>
<p><strong>Edited after comment</strong> Of course, you need to instantiate and render both the parent form and the nested formset. Something like:</p>
<pre><code>def edit_contact(request, contact_pk=None):
if contact_pk:
my_contact = Contact.objects.get(pk=contact_pk)
else:
my_contact = Contact()
CommunicationFormSet = inlineformset_factory(Contact, Communication)
if request.POST:
contact_form = ContactForm(request.POST, instance=my_contact)
communication_set = CommunicationFormSet(request.POST,
instance=my_contact)
if contact_form.is_valid() and communication_set.is_valid():
contact_form.save()
communication_set.save()
else:
contact_form = ContactForm(instance=my_contact)
communication_set = CommunicationFormSet(instance=my_contact)
return render_to_response('my_template.html',
{'form': contact_form, 'formset':communication_set})
</code></pre>
<p>and the template can be as simple as:</p>
<pre><code><form action="" method="POST">
{{ form.as_p }}
{{ formset }}
</form>
</code></pre>
<p>although you'll probably want to be a bit more detailed in how you render it.</p> |
4,940,036 | Mysql function returning a value from a query | <p>i want to create a function which calculates a value using a query and I am having a problem returning the value: </p>
<p>Shortened, my query is:</p>
<pre><code>CREATE FUNCTION func01(value1 INT , monto DECIMAL (10,2)) RETURNS DECIMAL(10,2)
BEGIN
SET @var_name = 0;
select @var_name=if(value1 = 1,monto * table.divisa_dolar,table.monto *divisa_euro) from table where data_init = 1;
return @var_nam;
END
</code></pre>
<p>I get a SQL syntax error. </p>
<blockquote>
<p>SQL Error (1064): You have an error in your SQL syntax;</p>
</blockquote> | 4,940,148 | 1 | 0 | null | 2011-02-09 00:10:26.92 UTC | 3 | 2017-10-29 14:21:59.207 UTC | 2017-10-29 14:21:59.207 UTC | null | 479,156 | null | 29,770 | null | 1 | 21 | mysql|function|mysql-error-1064 | 88,544 | <p>Assuming these are all generic names (table will not be a good table name), the problem is you can't use == for comparison. You are also missing some key syntax (DECLARE, SELECT INTO, etc.).</p>
<p>Change to this:</p>
<pre><code>CREATE FUNCTION func01(value1 INT , monto DECIMAL (10,2))
RETURNS DECIMAL(10,2)
DETERMINISTIC
BEGIN
DECLARE var_name DECIMAL(10,2);
SET var_name = 0;
SELECT if(value1 = 1,monto *divisa_dolar,monto *divisa_euro) INTO var_name
FROM table
WHERE data_init = 1;
RETURN var_name;
END
</code></pre>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html" rel="noreferrer">MySQL Comparison Functions and Operators</a></p>
<p>Related Question: <a href="https://stackoverflow.com/questions/1132686/single-equals-in-mysql">Single Equals in MYSQL</a></p>
<p>Function Help: <a href="http://www.databasejournal.com/features/mysql/article.php/3569846/MySQL-Stored-Functions.htm" rel="noreferrer">http://www.databasejournal.com/features/mysql/article.php/3569846/MySQL-Stored-Functions.htm</a></p> |
24,831,580 | Return row of Data Frame based on value in a column - R | <p>My R data.frame <code>df</code> looks like:</p>
<pre><code> Name Amount
1 "A" 150
2 "B" 120
3 "C" "NA"
4 "D" 160
.
.
.
</code></pre>
<p>I want to get the Name and Amount row when I do something like <code>min(df$Amount)</code>.</p>
<p>That gets me the minimum number in the Amount column, but how do I get the Name in that same row? Or the entire row for that matter?</p>
<p>Name should be "B" in this case.</p>
<p>Similar to <code>Select * Where Amount = min(Amount)</code></p>
<p>What is the best way to do this in R?</p> | 24,831,675 | 4 | 1 | null | 2014-07-18 18:30:30.647 UTC | 15 | 2019-01-10 12:22:50.447 UTC | 2014-07-18 18:45:43.367 UTC | null | 1,708,772 | null | 1,708,772 | null | 1 | 34 | r | 143,890 | <p>@Zelazny7's answer works, but if you want to keep ties you could do:</p>
<pre><code>df[which(df$Amount == min(df$Amount)), ]
</code></pre>
<p>For example with the following data frame:</p>
<pre><code>df <- data.frame(Name = c("A", "B", "C", "D", "E"),
Amount = c(150, 120, 175, 160, 120))
df[which.min(df$Amount), ]
# Name Amount
# 2 B 120
df[which(df$Amount == min(df$Amount)), ]
# Name Amount
# 2 B 120
# 5 E 120
</code></pre>
<p><strong>Edit:</strong> If there are NAs in the <code>Amount</code> column you can do:</p>
<pre><code>df[which(df$Amount == min(df$Amount, na.rm = TRUE)), ]
</code></pre> |
24,482,337 | How is aerospike different from other key-value nosql databases? | <p><a href="http://www.aerospike.com/docs/architecture/" rel="noreferrer">Aerospike</a> is a key-value, in-memory, operational NoSQL database with ACID properties which support complex objects and easy to scale. But I have already used something which does absolutely the same. </p>
<p><a href="http://redis.io/" rel="noreferrer">Redis</a> is also a key-value, in-memory (but persistent to disk) NoSQL database. It also support different complex objects. But in comparison to Aerospike, Redis was in use for a lot of time, already have an active community and a lot of projects developed in it.</p>
<p>So what is the difference between aerospike and other no-sql key-value databases like redis. Is there a particular place which is better suited for aerospike.</p>
<p>P.S. I am looking for an answer from people who used at least one of these dbs (preferably both) in real world and havend real life experience (not copy-pastes from official website).</p> | 24,493,715 | 5 | 2 | null | 2014-06-30 02:49:07.733 UTC | 23 | 2018-08-03 17:26:41.3 UTC | null | null | null | null | 1,090,562 | null | 1 | 55 | redis|key-value-store|aerospike | 37,420 | <p>If it has to be answered in one word, its "performance". Aerospike's performance is much better than any clustered-nosql solutions out there. Higher performance per-node means smaller cluster which is lower TCO (Total Cost of Ownership) and maintenance. Aerospike does auto-clustering, auto-sharding, auto-rebalancing (when cluster state changes) most of which needs manual steps in other databases.</p>
<p>I said "clustered" because I dont want to mix redis in that group (though redis clustering is in beta). Pure in-memory performance of Aerospike and redis will be comparable. But Redis expects a lot of things to be handled at the application layer like sharding, request redirection etc. Even though redis has a way to persist (snapshot or AOF), it has its own problems as its designed more like an addon. Aerospike is developed natively with persistence in mind. The clustering of redis also involves setting up master slave etc. You may want to take a look at this <a href="https://hasgeek.tv/miniconf/2014-redis-miniconf/899-alternatives-to-redis-while-not-compromising-on-its-speed" rel="noreferrer">talk</a> comparing and contrasting redis vs aerospike.</p> |
24,603,620 | Redirecting EC2 Elastic Load Balancer from HTTP to HTTPS | <p>I want to redirect all the HTTP request to https request on <a href="https://aws.amazon.com/elasticloadbalancing/" rel="noreferrer">ELB</a>. I have two EC2 instances. I am using nginx for the server. I have tried a rewriting the nginx conf files without any success. I would love some advice on it.</p> | 51,540,255 | 11 | 2 | null | 2014-07-07 05:35:19.097 UTC | 23 | 2022-05-18 13:47:11.14 UTC | 2019-07-22 08:23:29.947 UTC | null | 814,702 | null | 4,058,838 | null | 1 | 122 | redirect|nginx|amazon-ec2|https|amazon-elb | 98,386 | <p>AWS Application Load Balancers now support native HTTP to HTTPS redirect.</p>
<p>To enable this in the console, do the the following:</p>
<ol>
<li>Go to your Load Balancer in EC2 and tab "Listeners"</li>
<li>Select "View/edit rules" on your HTTP listener</li>
<li>Delete all rules except for the default one (bottom)</li>
<li>Edit default rule: choose "Redirect to" as an action, leave everything as default and enter "443" as a port.</li>
</ol>
<p><a href="https://i.stack.imgur.com/Sib40.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Sib40.jpg" alt="Native redirect listener rule"></a></p>
<p>The same can be achieved by using the CLI as described <a href="https://docs.aws.amazon.com/cli/latest/reference/elbv2/modify-listener.html" rel="noreferrer">here</a>.</p>
<p>It is also possible to do this in Cloudformation, where you need to set up a Listener object like this:</p>
<pre><code> HttpListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
LoadBalancerArn: !Ref LoadBalancer
Port: 80
Protocol: HTTP
DefaultActions:
- Type: redirect
RedirectConfig:
Protocol: HTTPS
StatusCode: HTTP_301
Port: 443
</code></pre>
<p>If you still use Classic Load Balancers, go with one of the NGINX configs described by the others.</p> |
49,271,750 | Is it possible to "hack" Python's print function? | <p>Note: This question is for informational purposes only. I am interested to see how deep into Python's internals it is possible to go with this.</p>
<p>Not very long ago, a discussion began inside a certain <a href="https://stackoverflow.com/q/49271187/4909087">question</a> regarding whether the strings passed to print statements could be modified after/during the call to <code>print</code> has been made. For example, consider the function:</p>
<pre><code>def print_something():
print('This cat was scared.')
</code></pre>
<p>Now, when <code>print</code> is run, then the output to the terminal should display:</p>
<pre><code>This dog was scared.
</code></pre>
<p>Notice the word "cat" has been replaced by the word "dog". Something somewhere somehow was able to modify those internal buffers to change what was printed. Assume this is done without the original code author's explicit permission (hence, hacking/hijacking).</p>
<p>This <a href="https://stackoverflow.com/questions/49271187/how-to-change-a-string-in-a-function-when-calling-a-function/49271219?noredirect=1#comment85545706_49271219">comment</a> from the wise @abarnert, in particular, got me thinking:</p>
<blockquote>
<p>There are a couple of ways to do that, but they're all very ugly, and
should never be done. The least ugly way is to probably replace the
<code>code</code> object inside the function with one with a different <code>co_consts</code>
list. Next is probably reaching into the C API to access the str's
internal buffer. [...]</p>
</blockquote>
<p>So, it looks like this is actually possible.</p>
<p>Here's my naive way of approaching this problem:</p>
<pre><code>>>> import inspect
>>> exec(inspect.getsource(print_something).replace('cat', 'dog'))
>>> print_something()
This dog was scared.
</code></pre>
<p>Of course, <code>exec</code> is bad, but that doesn't really answer the question, because it does not actually modify anything <em>during when/after</em> <code>print</code> is called.</p>
<p>How would it be done as @abarnert has explained it?</p> | 49,272,080 | 4 | 1 | null | 2018-03-14 07:18:41.637 UTC | 40 | 2018-12-24 08:36:36.657 UTC | 2018-05-06 09:26:31.627 UTC | null | 63,550 | null | 4,909,087 | null | 1 | 151 | python|python-3.x|printing|python-internals | 15,217 | <p>First, there's actually a much less hacky way. All we want to do is change what <code>print</code> prints, right?</p>
<pre><code>_print = print
def print(*args, **kw):
args = (arg.replace('cat', 'dog') if isinstance(arg, str) else arg
for arg in args)
_print(*args, **kw)
</code></pre>
<p>Or, similarly, you can monkeypatch <code>sys.stdout</code> instead of <code>print</code>.</p>
<hr>
<p>Also, nothing wrong with the <code>exec … getsource …</code> idea. Well, of course there's <em>plenty</em> wrong with it, but less than what follows here…</p>
<hr>
<p>But if you do want to modify the function object's code constants, we can do that.</p>
<p>If you really want to play around with code objects for real, you should use a library like <a href="https://github.com/vstinner/bytecode" rel="noreferrer"><code>bytecode</code></a> (when it's finished) or <a href="https://github.com/serprex/byteplay" rel="noreferrer"><code>byteplay</code></a> (until then, or for older Python versions) instead of doing it manually. Even for something this trivial, the <code>CodeType</code> initializer is a pain; if you actually need to do stuff like fixing up <code>lnotab</code>, only a lunatic would do that manually. </p>
<p>Also, it goes without saying that not all Python implementations use CPython-style code objects. This code will work in CPython 3.7, and probably all versions back to at least 2.2 with a few minor changes (and not the code-hacking stuff, but things like generator expressions), but it won't work with any version of IronPython.</p>
<pre><code>import types
def print_function():
print ("This cat was scared.")
def main():
# A function object is a wrapper around a code object, with
# a bit of extra stuff like default values and closure cells.
# See inspect module docs for more details.
co = print_function.__code__
# A code object is a wrapper around a string of bytecode, with a
# whole bunch of extra stuff, including a list of constants used
# by that bytecode. Again see inspect module docs. Anyway, inside
# the bytecode for string (which you can read by typing
# dis.dis(string) in your REPL), there's going to be an
# instruction like LOAD_CONST 1 to load the string literal onto
# the stack to pass to the print function, and that works by just
# reading co.co_consts[1]. So, that's what we want to change.
consts = tuple(c.replace("cat", "dog") if isinstance(c, str) else c
for c in co.co_consts)
# Unfortunately, code objects are immutable, so we have to create
# a new one, copying over everything except for co_consts, which
# we'll replace. And the initializer has a zillion parameters.
# Try help(types.CodeType) at the REPL to see the whole list.
co = types.CodeType(
co.co_argcount, co.co_kwonlyargcount, co.co_nlocals,
co.co_stacksize, co.co_flags, co.co_code,
consts, co.co_names, co.co_varnames, co.co_filename,
co.co_name, co.co_firstlineno, co.co_lnotab,
co.co_freevars, co.co_cellvars)
print_function.__code__ = co
print_function()
main()
</code></pre>
<p>What could go wrong with hacking up code objects? Mostly just segfaults, <code>RuntimeError</code>s that eat up the whole stack, more normal <code>RuntimeError</code>s that can be handled, or garbage values that will probably just raise a <code>TypeError</code> or <code>AttributeError</code> when you try to use them. For examples, try creating a code object with just a <code>RETURN_VALUE</code> with nothing on the stack (bytecode <code>b'S\0'</code> for 3.6+, <code>b'S'</code> before), or with an empty tuple for <code>co_consts</code> when there's a <code>LOAD_CONST 0</code> in the bytecode, or with <code>varnames</code> decremented by 1 so the highest <code>LOAD_FAST</code> actually loads a freevar/cellvar cell. For some real fun, if you get the <code>lnotab</code> wrong enough, your code will only segfault when run in the debugger.</p>
<p>Using <code>bytecode</code> or <code>byteplay</code> won't protect you from all of those problems, but they do have some basic sanity checks, and nice helpers that let you do things like insert a chunk of code and let it worry about updating all offsets and labels so you can't get it wrong, and so on. (Plus, they keep you from having to type in that ridiculous 6-line constructor, and having to debug the silly typos that come from doing so.)</p>
<hr>
<p>Now on to #2.</p>
<p>I mentioned that code objects are immutable. And of course the consts are a tuple, so we can't change that directly. And the thing in the const tuple is a string, which we also can't change directly. That's why I had to build a new string to build a new tuple to build a new code object.</p>
<p>But what if you could change a string directly?</p>
<p>Well, deep enough under the covers, everything is just a pointer to some C data, right? If you're using CPython, there's <a href="https://docs.python.org/3/c-api/unicode.html#creating-and-accessing-unicode-strings" rel="noreferrer">a C API to access the objects</a>, and <a href="https://docs.python.org/3/library/ctypes.html#accessing-values-exported-from-dlls" rel="noreferrer">you can use <code>ctypes</code> to access that API from within Python itself, which is such a terrible idea that they put a <code>pythonapi</code> right there in the stdlib's <code>ctypes</code> module</a>. :) The most important trick you need to know is that <code>id(x)</code> is the actual pointer to <code>x</code> in memory (as an <code>int</code>).</p>
<p>Unfortunately, the C API for strings won't let us safely get at the internal storage of an already-frozen string. So screw safely, let's just <a href="https://github.com/python/cpython/blob/master/Include/unicodeobject.h" rel="noreferrer">read the header files</a> and find that storage ourselves.</p>
<p>If you're using CPython 3.4 - 3.7 (it's different for older versions, and who knows for the future), a string literal from a module that's made of pure ASCII is going to be stored using the compact ASCII format, which means the struct ends early and the buffer of ASCII bytes follows immediately in memory. This will break (as in probably segfault) if you put a non-ASCII character in the string, or certain kinds of non-literal strings, but you can read up on the other 4 ways to access the buffer for different kinds of strings.</p>
<p>To make things slightly easier, I'm using the <a href="https://github.com/abarnert/superhackyinternals" rel="noreferrer"><code>superhackyinternals</code></a> project off my GitHub. (It's intentionally not pip-installable because you really shouldn't be using this except to experiment with your local build of the interpreter and the like.)</p>
<pre><code>import ctypes
import internals # https://github.com/abarnert/superhackyinternals/blob/master/internals.py
def print_function():
print ("This cat was scared.")
def main():
for c in print_function.__code__.co_consts:
if isinstance(c, str):
idx = c.find('cat')
if idx != -1:
# Too much to explain here; just guess and learn to
# love the segfaults...
p = internals.PyUnicodeObject.from_address(id(c))
assert p.compact and p.ascii
addr = id(c) + internals.PyUnicodeObject.utf8_length.offset
buf = (ctypes.c_int8 * 3).from_address(addr + idx)
buf[:3] = b'dog'
print_function()
main()
</code></pre>
<p>If you want to play with this stuff, <code>int</code> is a whole lot simpler under the covers than <code>str</code>. And it's a lot easier to guess what you can break by changing the value of <code>2</code> to <code>1</code>, right? Actually, forget imagining, let's just do it (using the types from <code>superhackyinternals</code> again):</p>
<pre><code>>>> n = 2
>>> pn = PyLongObject.from_address(id(n))
>>> pn.ob_digit[0]
2
>>> pn.ob_digit[0] = 1
>>> 2
1
>>> n * 3
3
>>> i = 10
>>> while i < 40:
... i *= 2
... print(i)
10
10
10
</code></pre>
<p>… pretend that code box has an infinite-length scrollbar.</p>
<p>I tried the same thing in IPython, and the first time I tried to evaluate <code>2</code> at the prompt, it went into some kind of uninterruptable infinite loop. Presumably it's using the number <code>2</code> for something in its REPL loop, while the stock interpreter isn't?</p> |
21,888,910 | How to specify names of columns for x and y when joining in dplyr? | <p>I have two data frames that I want to join using dplyr. One is a data frame containing first names.</p>
<pre><code>test_data <- data.frame(first_name = c("john", "bill", "madison", "abby", "zzz"),
stringsAsFactors = FALSE)
</code></pre>
<p>The other data frame contains a cleaned up version of the Kantrowitz names corpus, identifying gender. Here is a minimal example:</p>
<pre><code>kantrowitz <- structure(list(name = c("john", "bill", "madison", "abby", "thomas"), gender = c("M", "either", "M", "either", "M")), .Names = c("name", "gender"), row.names = c(NA, 5L), class = c("tbl_df", "tbl", "data.frame"))
</code></pre>
<p>I essentially want to look up the gender of the name from the <code>test_data</code> table using the <code>kantrowitz</code> table. Because I'm going to abstract this into a function <code>encode_gender</code>, I won't know the name of the column in the data set that's going to be used, and so I can't guarantee that it will be <code>name</code>, as in <code>kantrowitz$name</code>.</p>
<p>In base R I would perform the merge this way:</p>
<pre><code>merge(test_data, kantrowitz, by.x = "first_names", by.y = "name", all.x = TRUE)
</code></pre>
<p>That returns the correct output:</p>
<pre><code> first_name gender
1 abby either
2 bill either
3 john M
4 madison M
5 zzz <NA>
</code></pre>
<p>But I want to do this in dplyr because I'm using that package for all my other data manipulation. The dplyr <code>by</code> option to the various <code>*_join</code> functions only lets me specify one column name, but I need to specify two. I'm looking for something like this:</p>
<pre><code>library(dplyr)
# either
left_join(test_data, kantrowitz, by.x = "first_name", by.y = "name")
# or
left_join(test_data, kantrowitz, by = c("first_name", "name"))
</code></pre>
<p>What is the way to perform this kind of join using dplyr?</p>
<p>(Never mind that the Kantrowitz corpus is a bad way to identify gender. I'm working on a better implementation, but I want to get this working first.)</p> | 26,432,382 | 2 | 1 | null | 2014-02-19 18:14:04.9 UTC | 29 | 2014-10-17 19:44:37.507 UTC | 2014-07-15 17:57:32.393 UTC | null | 559,784 | null | 1,293,073 | null | 1 | 114 | r|join|left-join|dplyr | 173,618 | <p>This feature has been added in dplyr v0.3. You can now pass a named character vector to the <code>by</code> argument in <code>left_join</code> (and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:</p>
<pre><code>left_join(test_data, kantrowitz, by = c("first_name" = "name"))
</code></pre> |
21,446,804 | Find if video file has audio present in it | <p>I'm trying to figure out if a video has audio present in it so as to extract the mp3 using ffmpeg. When the video contains no audio channels, ffmpeg creates an empty mp3 file which I'm using to figure out if audio was present in the video in the first place. I'm sure there is a better way to identify if audio is present in a video. Will avprobe help with this? Can anyone point me to a resource or probably a solution?</p>
<p>Edit: Surprisingly, the same command on my server running the latest build of ffprobe doesn't run. It throws an error saying </p>
<p>Unrecognized option 'select_stream'</p>
<p>Failed to set value 'a' for option 'select_stream'</p>
<p>Any ideas how to rectify this out?</p> | 21,447,100 | 5 | 1 | null | 2014-01-30 02:39:38.54 UTC | 7 | 2018-07-30 13:29:40.193 UTC | 2014-02-04 08:18:51.24 UTC | null | 728,825 | null | 728,825 | null | 1 | 29 | audio|video|ffmpeg|ffprobe|avprobe | 26,187 | <p>I would use FFprobe (it comes along with FFMPEG):</p>
<pre><code>ffprobe -i INPUT -show_streams -select_streams a -loglevel error
</code></pre>
<p>In case there's no audio it ouputs nothing. If there is an audio stream then you get something like:</p>
<blockquote>
<p>[STREAM]</p>
<p>index=0</p>
<p>codec_name=mp3</p>
<p>codec_long_name=MP3 (MPEG audio layer 3)</p>
<p>profile=unknown</p>
<p>codec_type=audio</p>
<p>codec_time_base=1/44100</p>
<p>etc</p>
<p>etc...</p>
<p>[/STREAM]</p>
</blockquote>
<p>That should be easy enough to parse regardless of the language you're using to make this process automated.</p> |
33,007,878 | NodeJs : TypeError: require(...) is not a function | <p>I am trying to require a file and afterwards pass it to a var. I am following <a href="https://scotch.io/tutorials/easy-node-authentication-setup-and-local" rel="noreferrer">this</a> tutorial to create an authentication system. After writing the server.js file and trying to compile I got a BSON error therefore I changed the line that required the release version of it in mongoose.</p>
<p>Here are my code and error:</p>
<p><em><strong>server.js</strong></em></p>
<pre><code>require('./app/routes')(app, passport);
</code></pre>
<p><em><strong>Error</strong></em></p>
<pre><code>require('./app/routes')(app, passport);
^
TypeError: require(...) is not a function
at Object.<anonymous> (d:\Node JS learning\WorkWarV2\server.js:38:24)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:475:10)
at startup (node.js:117:18)
at node.js:951:3
Process finished with exit code 1
</code></pre>
<p>I have read that this usually means that <code>requireJS</code> is not getting loaded properly yet I am not aware why or how to fix it.</p>
<p><em><strong>Edit due to comment:</strong></em></p>
<p>As asked, <a href="http://paste.isomorphis.me/vj3" rel="noreferrer">here</a> is the result of <code>console.log(require);</code></p> | 33,008,076 | 8 | 1 | null | 2015-10-08 06:11:09.55 UTC | 23 | 2021-11-12 04:43:20.087 UTC | 2021-10-11 22:48:57.373 UTC | null | 10,158,227 | null | 1,640,736 | null | 1 | 128 | javascript|node.js|require | 206,696 | <p>I think this means that <code>module.exports</code> in your <code>./app/routes</code> module is not assigned to be a function so therefore <code>require('./app/routes')</code> does not resolve to a function so therefore, you cannot call it as a function like this <code>require('./app/routes')(app, passport)</code>. </p>
<p>Show us <code>./app/routes</code> if you want us to comment further on that.</p>
<p>It should look something like this;</p>
<pre><code>module.exports = function(app, passport) {
// code here
}
</code></pre>
<p>You are exporting a function that can then be called like <code>require('./app/routes')(app, passport)</code>.</p>
<hr>
<p>One other reason a similar error could occur is if you have a circular module dependency where module A is trying to <code>require(B)</code> and module B is trying to <code>require(A)</code>. When this happens, it will be detected by the <code>require()</code> sub-system and one of them will come back as <code>null</code> and thus trying to call that as a function will not work. The fix in that case is to remove the circular dependency, usually by breaking common code into a third module that both can separately load though the specifics of fixing a circular dependency are unique for each situation.</p> |
33,383,854 | how to fix Angular not using explicit annotation and cannot be invoked in strict mode | <p>I am using strict mode and <code>Angular 1.4.7</code> , I get the following error:</p>
<pre><code>Error: [$injector:strictdi] function($scope, $element, $attrs, mouseCapture) is not using explicit annotation and cannot be invoked in strict mode
</code></pre>
<p>The angular generated url for the error is:</p>
<p><a href="https://docs.angularjs.org/error/">https://docs.angularjs.org/error/</a>$injector/strictdi?p0=function($scope,%20$element,%20$attrs,%20mouseCapture</p>
<p>And the following is the service</p>
<pre><code>angular.module('mouseCapture', [])
//
// Service used to acquire 'mouse capture' then receive dragging events while the mouse is captured.
//
.factory('mouseCapture', function ($rootScope) {
//
// Element that the mouse capture applies to, defaults to 'document'
// unless the 'mouse-capture' directive is used.
//
var $element = document;
//
// Set when mouse capture is acquired to an object that contains
// handlers for 'mousemove' and 'mouseup' events.
//
var mouseCaptureConfig = null;
//
// Handler for mousemove events while the mouse is 'captured'.
//
var mouseMove = function (evt) {
if (mouseCaptureConfig && mouseCaptureConfig.mouseMove) {
mouseCaptureConfig.mouseMove(evt);
$rootScope.$digest();
}
};
//
// Handler for mouseup event while the mouse is 'captured'.
//
var mouseUp = function (evt) {
if (mouseCaptureConfig && mouseCaptureConfig.mouseUp) {
mouseCaptureConfig.mouseUp(evt);
$rootScope.$digest();
}
};
return {
//
// Register an element to use as the mouse capture element instead of
// the default which is the document.
//
registerElement: function(element) {
$element = element;
},
//
// Acquire the 'mouse capture'.
// After acquiring the mouse capture mousemove and mouseup events will be
// forwarded to callbacks in 'config'.
//
acquire: function (evt, config) {
//
// Release any prior mouse capture.
//
this.release();
mouseCaptureConfig = config;
//
// In response to the mousedown event register handlers for mousemove and mouseup
// during 'mouse capture'.
//
$element.mousemove(mouseMove);
$element.mouseup(mouseUp);
},
//
// Release the 'mouse capture'.
//
release: function () {
if (mouseCaptureConfig) {
if (mouseCaptureConfig.released) {
//
// Let the client know that their 'mouse capture' has been released.
//
mouseCaptureConfig.released();
}
mouseCaptureConfig = null;
}
$element.unbind("mousemove", mouseMove);
$element.unbind("mouseup", mouseUp);
},
};
})
//
// Directive that marks the mouse capture element.
//
.directive('mouseCapture', function () {
return {
restrict: 'A',
controller: function($scope, $element, $attrs, mouseCapture) {
//
// Register the directives element as the mouse capture element.
//
mouseCapture.registerElement($element);
},
};
})
;
</code></pre>
<p>How do i fix this error</p> | 33,383,997 | 4 | 1 | null | 2015-10-28 05:55:05.55 UTC | 7 | 2019-10-11 22:39:49.603 UTC | null | null | null | null | 5,034,995 | null | 1 | 39 | javascript|angularjs|angularjs-directive | 53,672 | <p>From the <a href="https://docs.angularjs.org/error/$injector/strictdi">documentation</a> it looks like you need to declare all dependency injections in string array.</p>
<p>There are other ways but normally I would do it like this:</p>
<pre><code>controller: ['$scope', '$element', '$attrs', 'mouseCapture',
function($scope, $element, $attrs, mouseCapture) {
...
}
]
</code></pre>
<p>One of the reason we do this is because when we try to minify this js file, variable names would be reduced to one or 2 characters, and DI needs the exact name to find the services. By declaring DI in a string array, angular can match services with their minified variable name. For this reason, the string array and the function arguments need EXACT MATCHING in number and order.</p>
<hr>
<p><em>Update:</em></p>
<p>If you are following <a href="https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#manual-annotating-for-dependency-injection">John Papa's Angular style guide</a>, you should do it like this:</p>
<pre><code>controller: MouseCaptureController,
...
MouseCaptureController.$inject = ['$scope', '$element', '$attrs', 'mouseCapture'];
function MouseCaptureController($scope, $element, $attrs, mouseCapture) {
...
}
</code></pre> |
9,565,912 | Convert the output of os.cpus() in Node.js to percentage | <p>Is there a way to convert the os.cpus() info to percentage? Just like the output of iostat (on the CPU section).</p>
<p>My code:</p>
<pre><code>var os = require('os');
console.log(os.cpus());
</code></pre>
<p>The output:</p>
<pre><code>[ { model: 'MacBookAir4,2',
speed: 1800,
times:
{ user: 5264280,
nice: 0,
sys: 4001110,
idle: 58703910,
irq: 0 } },
{ model: 'MacBookAir4,2',
speed: 1800,
times:
{ user: 2215030,
nice: 0,
sys: 1072600,
idle: 64657440,
irq: 0 } },
{ model: 'MacBookAir4,2',
speed: 1800,
times:
{ user: 5973360,
nice: 0,
sys: 3197990,
idle: 58773760,
irq: 0 } },
{ model: 'MacBookAir4,2',
speed: 1800,
times:
{ user: 2187650,
nice: 0,
sys: 1042550,
idle: 64714820,
irq: 0 } } ]
</code></pre>
<p>I would like to have the "times" metric converted to percentage, just like is show on the <code>iostat</code> command:</p>
<pre><code> cpu
us sy id
6 3 91
</code></pre>
<p>I understand that the values in the nodejs function are in CPU ticks, but I have no idea what formula should I use to convert them to percentage :)</p>
<p>Thanks.</p> | 9,567,357 | 9 | 0 | null | 2012-03-05 11:33:08.447 UTC | 11 | 2021-01-29 09:52:22.043 UTC | null | null | null | null | 28,388 | null | 1 | 20 | node.js|operating-system|cpu | 38,861 | <p>According to <a href="http://nodejs.org/docs/latest/api/os.html#os_os_cpus" rel="noreferrer">the docs</a>, <code>times</code> is</p>
<blockquote>
<p>an object containing the number of CPU ticks spent in: user, nice, sys, idle, and irq</p>
</blockquote>
<p>So you should just be able to sum the times and calculate the percentage, like below:</p>
<pre><code>var cpus = os.cpus();
for(var i = 0, len = cpus.length; i < len; i++) {
console.log("CPU %s:", i);
var cpu = cpus[i], total = 0;
for(var type in cpu.times) {
total += cpu.times[type];
}
for(type in cpu.times) {
console.log("\t", type, Math.round(100 * cpu.times[type] / total));
}
}
</code></pre>
<p><strong>EDIT:</strong> As Tom Frost says in the comments, this is the average usage since system boot. This is consistent with the question, since the same is true of <code>iostat</code>. However, <code>iostat</code> has the option of doing regular updates, showing the average usage since the last update. Tom's method would work well for implementing that.</p> |
9,622,061 | Thread-safe class in Java by means of synchronized blocks | <p>Let's say we have very simple Java class <code>MyClass</code>.</p>
<pre><code>public class MyClass {
private int number;
public MyClass(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
</code></pre>
<p>There are three ways to construct thread-safe Java class which has some state:<br /></p>
<ol>
<li><p>Make it truly immutable<br/></p>
<pre><code>public class MyClass {
private final int number;
public MyClass(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
</code></pre></li>
<li><p>Make field <code>number</code> <code>volatile</code>.</p>
<pre><code>public class MyClass {
private volatile int number;
public MyClass(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
</code></pre></li>
<li><p>Use a <code>synchronized</code> block. Classic version of this approach described in Chapter 4.3.5 of Java Concurrency in practice. And the funny thing about that it has an error in the example which is mentioned in a errata for this book. </p>
<pre><code>public class MyClass {
private int number;
public MyClass(int number) {
setNumber(number);
}
public synchronized int getNumber() {
return number;
}
public synchronized void setNumber(int number) {
this.number = number;
}
}
</code></pre></li>
</ol>
<p>There is one more fact that should be added to the context of discussion. In a multhithreaded environment JVM is free to reorder instructions outside of <code>synchronized</code> block preserving a logical sequence and <em>happens-before</em> relationships specified by JVM. It may cause publishing object which is not properly constructed yet to another thread.</p>
<p>I've got a couple of questions regarding the third case. </p>
<ol>
<li><p>Will it be equivalent to a following piece of code:</p>
<pre><code>public class MyClass {
private int number;
public MyClass(int number) {
synchronized (this){
this.number = number;
}
}
public synchronized int getNumber() {
return number;
}
public synchronized void setNumber(int number) {
this.number = number;
}
}
</code></pre></li>
<li><p>Will a reordering be prevented in the third case or it possible for JVM to reorder intstructions and therefore publish object with default value in field <code>number</code>?</p></li>
<li><p>If an answer for the second question is yes than I have one more question.</p>
<pre><code> public class MyClass {
private int number;
public MyClass(int number) {
synchronized (new Object()){
this.number = number;
}
}
public synchronized int getNumber() {
return number;
}
public synchronized void setNumber(int number) {
this.number = number;
}
}
</code></pre></li>
</ol>
<p>This strange-looking <code>synchronized (new Object())</code> is supposed to prevent reordering effect. Will it work?</p>
<p>Just to be clear, all these examples don't have any practical applications. I'm just curious about nuances of multithreading.</p> | 9,622,236 | 2 | 0 | null | 2012-03-08 17:30:33.03 UTC | 11 | 2012-03-08 20:35:02.91 UTC | null | null | null | null | 136,971 | null | 1 | 20 | java|multithreading|concurrency|thread-safety | 35,205 | <p><code>synchronized(new Object())</code> will do nothing, since synchronization is only on the object you synchronize on. So if thread A synchronizes on <code>oneObject</code>, and thread B synchronizes on <code>anotherObject</code>, there is no happens-before between them. Since we can know for a fact that no other thread will ever synchronize on the <code>new Object()</code> you create there, this won't establish a happens-before between any other thread.</p>
<p>Regarding your <code>synchronzied</code> in the constructor, if your object is safely published to another thread, you don't need it; and if it's not, you're probably in a mess of trouble as it is. I asked this question on the concurrency-interest list a bit ago, and <a href="http://concurrency.markmail.org/message/mav53xzo4bqu7udw?q=synchronized%20constructor&page=3" rel="noreferrer">an interesting thread resulted</a>. See in particular <a href="http://concurrency.markmail.org/message/3jk6cejxvl6eqb6t?q=synchronized%20constructor&page=3" rel="noreferrer">this email</a>, which points out that even with your constructor synchronized, in the absence of safe publication another thread could see default values in your fields, and <a href="http://concurrency.markmail.org/message/4kzczarfrtfu4cv4?q=synchronized%20constructor&page=3" rel="noreferrer">this email</a> which (imho) ties the whole thing together.</p> |
9,422,069 | jquery's live() is deprecated. What do I use now? | <p>I saw on the jquery documentation that live() is deprecated. Is there a direct replacement function?</p> | 9,422,088 | 4 | 0 | null | 2012-02-23 22:02:26.593 UTC | 11 | 2013-10-21 11:49:12.75 UTC | null | null | null | null | 387,405 | null | 1 | 43 | javascript|jquery | 38,894 | <p>Of course:</p>
<p><a href="http://api.jquery.com/on/" rel="noreferrer">http://api.jquery.com/on/</a></p>
<p><a href="http://api.jquery.com/off/" rel="noreferrer">http://api.jquery.com/off/</a></p>
<p>The page for <code>live()</code> shows how to convert to <code>on()</code>:</p>
<p><a href="http://api.jquery.com/live/" rel="noreferrer">http://api.jquery.com/live/</a></p> |
9,509,002 | CSS transition when class removed | <p>I have a form that functions as a settings page. When form elements are modified, they are marked as <code>unsaved</code> and have a different border color. When the form is saved, they are marked as saved by having another border color.</p>
<p>What I want is that when the form is saved, the border will gradually fade out.</p>
<p>The order will go:</p>
<pre><code><input type='text' class='unsaved' /> Not saved yet, border is yellow
<input type='text' class='saved' /> Saved, so the border is green
<input type='text' class='' /> Fade out if coming from class saved
</code></pre>
<p>If I can get a CSS3 transition to fire when the class <code>saved</code> is removed, then it could fade out and everything would be hunky-dory. Currently, I have to manually animate it (using a plug-in, of course), but it looks choppy, and I would like to move the code to CSS3 so it will be smoother.</p>
<p>I only need this to work in Chrome and Firefox 4+, though others would be nice.</p>
<p><strong>CSS:</strong></p>
<p>Here's the associated CSS:</p>
<pre><code>.unsaved {
border: 3px solid #FFA500;
padding: 0;
}
.saved {
border: 3px solid #0F0;
padding: 0;
}
</code></pre>
<p>I would like to work in the following transition (or something like it):</p>
<pre><code>border-color: rgba(0,0,0,0);
-webkit-transition: border-color .25s ease-in;
-moz-transition: border-color .25s ease-in;
-o-transition: border-color .25s ease-in;
transition: border-color .25s ease-in;
</code></pre>
<p><strong>Note:</strong></p>
<p>Personally, I don't agree with this scheme of user interaction, but that's how our software lead wants it. Please don't suggest that I change the way it functions currently. Thanks!</p> | 9,509,072 | 4 | 0 | null | 2012-03-01 00:36:44.743 UTC | 15 | 2018-07-26 08:39:40.24 UTC | 2013-10-01 20:06:03.543 UTC | null | 538,551 | null | 538,551 | null | 1 | 99 | css|css-transitions | 140,051 | <p>CSS transitions work by defining two states for the object using CSS. In your case, you define how the object looks when it has the class <code>"saved"</code> and you define how it looks when it doesn't have the class <code>"saved"</code> (it's normal look). When you remove the class <code>"saved"</code>, it will transition to the other state according to the transition settings in place for the object without the <code>"saved"</code> class.</p>
<p>If the CSS transition settings apply to the object (without the <code>"saved"</code> class), then they will apply to both transitions.</p>
<p>We could help more specifically if you included all relevant CSS you're using to with the HTML you've provided.</p>
<p>My guess from looking at your HTML is that your transition CSS settings only apply to <code>.saved</code> and thus when you remove it, there are no controls to specify a CSS setting. You may want to add another class <code>".fade"</code> that you leave on the object all the time and you can specify your CSS transition settings on that class so they are always in effect.</p> |
47,239,251 | INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device | <p><a href="https://i.stack.imgur.com/TsZ3Z.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/TsZ3Z.jpg" alt="Android Studio with Failed Error" /></a></p>
<p>Got this freaky error</p>
<pre><code>Installation failed with message Failed to finalize session : INSTALL_FAILED_USER_RESTRICTED: Install canceled by user.
It is possible that this issue is resolved by uninstalling an existing version of the `apk` if it is present, and then re-installing.
WARNING: Uninstalling will remove the application data!
Do you want to uninstall the existing application?
</code></pre>
<p>When trying to run the <code>apk</code> in my redmi 4 <code>MIUI 8.5.4.0</code></p>
<p>OEM unlocking enabled</p>
<p>Solution Tried</p>
<ul>
<li>MIUI optimization turned off</li>
<li>USB debugging turned on</li>
<li>Verify apps over USB turned on</li>
</ul>
<p>NOTE: while turning on <strong>install via USB</strong> a pop up saying <strong>The device is temporarily restricted</strong></p> | 48,524,656 | 28 | 2 | null | 2017-11-11 14:57:22.067 UTC | 51 | 2022-09-24 10:11:05.747 UTC | 2021-08-17 14:18:54.317 UTC | null | 8,031,784 | null | 5,972,289 | null | 1 | 323 | android|android-studio|adb | 328,745 | <p><strong>Steps for MIUI 9 and Above:</strong></p>
<p><em>Settings -> Additional Settings -> Developer options -></em></p>
<ol>
<li><p><strong>Turn off "MIUI optimization" and Restart</strong></p>
</li>
<li><p><strong>Turn On "USB Debugging"</strong></p>
</li>
<li><p><strong>Turn On "Install via USB"</strong></p>
<p><em>MTP(Media Transfer Protocol) is the default mode</em>.<br />
Works even in MTP in some cases</p>
</li>
<li><p><strong>Set USB Configuration to Charging</strong></p>
</li>
</ol> |
10,300,656 | Capture incoming traffic in tcpdump | <p>In tcpdump, how can I capture all incoming IP traffic destined to my machine? I don't care about my local traffic. </p>
<p>Should I just say:</p>
<pre><code>tcpdump ip dst $MyIpAddress and not src net $myIpAddress/$myNetworkBytes
</code></pre>
<p>... or am I missing something?</p> | 10,301,098 | 3 | 1 | null | 2012-04-24 15:04:25.543 UTC | 4 | 2017-02-18 06:11:45.73 UTC | 2017-02-18 06:11:45.73 UTC | null | 6,862,601 | null | 497,180 | null | 1 | 37 | capture|packet|traffic|packet-capture|tcpdump | 85,545 | <p>In Bash shell try this:</p>
<pre><code>tcpdump -i eth0 tcp and dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes
</code></pre>
<p>or this equivalent formulation:</p>
<pre><code>tcpdump -i eth0 ip proto \\tcp and dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes
</code></pre>
<p>On my system this resolves to something like:</p>
<pre><code>tcpdump -i eth0 tcp and dst host 10.0.0.35 and not src net 10.0.0.0/24
</code></pre>
<p>If you want to see all of the traffic to your destination host, not just TCP protocol traffic you could do:</p>
<pre><code>tcpdump -i eth0 dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes
</code></pre>
<p>Some notes:</p>
<ol>
<li><p>I changed <code>$myIpAddress/$myNetworkBytes</code> to <code>$MyNetworkAddress/$myNetworkBytes</code>. This is because the apparent intent of your rule is to exclude traffic from your local network, and the <a href="http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing" rel="noreferrer">correct way</a> to specify a network address is to specify the network's lowest IP address (which is called the network address) / netmask. If you specify any address other than the lowest address in the range for a network with a netmask of $myNetworkBytes, then you will get the error message:</p>
<pre><code>tcpdump: non-network bits set in "10.0.0.3/24"
</code></pre></li>
<li><p>In the first example 'tcp' is a <em>keyword</em> in the libpcap expression language (man pcap-filter) , whereas in the second example, 'tcp' is used as a <em>value</em> of <code>ip proto</code>. In order to indicate that the 'tcp' in the second instance is a value and not another 'tcp' keyword, I need to escape the 'tcp' with a double backslash. It has to be a double backslash so that the Bash interpreter will pass a single backslash on to the libpcap interpreter (Bash eats the first backslash, libpcap gets the second.) To reduce the double escape confusion, it might be good to get into the habit of double quoting the entire expression part of the command:</p>
<pre><code>tcpdump -i eth0 "ip proto \tcp and dst host $MyIpAddress and not src net $MyNetworkAddress/$myNetworkBytes"
</code></pre></li>
<li><p>To avoid warnings and surprises, it is better to use the interface specifier <code>-i eth0</code> or whatever interface you wish. Not all interfaces necessarily have an IP address assigned and without being specific, you might see traffic that you hadn't intended to see. This is especially true on systems that have the network-manager running, which seems to have its own mind about what interfaces to add and when.</p></li>
</ol> |
10,653,367 | How to check 'undefined' value in jQuery | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/27509/detecting-an-undefined-object-property-in-javascript">Detecting an undefined object property in JavaScript</a><br>
<a href="https://stackoverflow.com/questions/2778901/javascript-undefined-compare">javascript undefined compare</a> </p>
</blockquote>
<p>How we can add a check for an undefined variable, like:</p>
<pre><code>function A(val) {
if (val == undefined)
// do this
else
// do this
}
</code></pre> | 10,653,381 | 10 | 1 | null | 2012-05-18 13:16:30.723 UTC | 31 | 2022-04-29 05:21:49.393 UTC | 2017-05-23 12:10:06.433 UTC | null | -1 | null | 1,163,736 | null | 1 | 190 | javascript|jquery|undefined | 593,582 | <p>JQuery library was developed specifically to simplify and to unify certain JavaScript functionality.</p>
<p>However if you need to check a variable against <code>undefined</code> value, there is no need to invent any special method, since JavaScript has a <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof"><code>typeof</code></a> operator, which is simple, fast and cross-platform:</p>
<pre><code>if (typeof value === "undefined") {
// ...
}
</code></pre>
<p>It returns a string indicating the type of the variable or other unevaluated operand. The main advantage of this method, compared to <code>if (value === undefined) { ... }</code>, is that <code>typeof</code> will never raise an exception in case if variable <code>value</code> does not exist.</p> |
7,560,979 | CGContextDrawImage is EXTREMELY slow after large UIImage drawn into it | <p>It seems that CGContextDrawImage(CGContextRef, CGRect, CGImageRef) performs MUCH WORSE when drawing a CGImage that was created by CoreGraphics (i.e. with CGBitmapContextCreateImage) than it does when drawing the CGImage which backs a UIImage. See this testing method:</p>
<pre><code>-(void)showStrangePerformanceOfCGContextDrawImage
{
///Setup : Load an image and start a context:
UIImage *theImage = [UIImage imageNamed:@"reallyBigImage.png"];
UIGraphicsBeginImageContext(theImage.size);
CGContextRef ctxt = UIGraphicsGetCurrentContext();
CGRect imgRec = CGRectMake(0, 0, theImage.size.width, theImage.size.height);
///Why is this SO MUCH faster...
NSDate * startingTimeForUIImageDrawing = [NSDate date];
CGContextDrawImage(ctxt, imgRec, theImage.CGImage); //Draw existing image into context Using the UIImage backing
NSLog(@"Time was %f", [[NSDate date] timeIntervalSinceDate:startingTimeForUIImageDrawing]);
/// Create a new image from the context to use this time in CGContextDrawImage:
CGImageRef theImageConverted = CGBitmapContextCreateImage(ctxt);
///This is WAY slower but why?? Using a pure CGImageRef (ass opposed to one behind a UIImage) seems like it should be faster but AT LEAST it should be the same speed!?
NSDate * startingTimeForNakedGImageDrawing = [NSDate date];
CGContextDrawImage(ctxt, imgRec, theImageConverted);
NSLog(@"Time was %f", [[NSDate date] timeIntervalSinceDate:startingTimeForNakedGImageDrawing]);
}
</code></pre>
<p>So I guess the question is, #1 what may be causing this and #2 is there a way around it, i.e. other ways to create a CGImageRef which may be faster? I realize I could convert everything to UIImages first but that is such an ugly solution. I already have the CGContextRef sitting there.</p>
<p>UPDATE : This seems to not necessarily be true when drawing small images? That may be a clue- that this problem is amplified when large images (i.e. fullsize camera pics) are used. 640x480 seems to be pretty similar in terms of execution time with either method</p>
<p>UPDATE 2 : Ok, so I've discovered something new.. Its actually NOT the backing of the CGImage that is changing the performance. I can flip-flop the order of the 2 steps and make the UIImage method behave slowly, whereas the "naked" CGImage will be super fast. It seems whichever you perform second will suffer from terrible performance. This seems to be the case UNLESS I free memory by calling CGImageRelease on the image I created with CGBitmapContextCreateImage. Then the UIImage backed method will be fast subsequently. The inverse it not true. What gives? "Crowded" memory shouldn't affect performance like this, should it?</p>
<p>UPDATE 3 : Spoke too soon. The previous update holds true for images at size 2048x2048 but stepping up to 1936x2592 (camera size) the naked CGImage method is still way slower, regardless of order of operations or memory situation. Maybe there are some CG internal limits that make a 16MB image efficient whereas the 21MB image can't be handled efficiently. Its literally 20 times slower to draw the camera size than a 2048x2048. Somehow UIImage provides its CGImage data much faster than a pure CGImage object does. o.O</p>
<p>UPDATE 4 : I thought this might have to do with some memory caching thing, but the results are the same whether the UIImage is loaded with the non-caching [UIImage imageWithContentsOfFile] as if [UIImage imageNamed] is used.</p>
<p>UPDATE 5 (Day 2) : After creating mroe questions than were answered yesterday I have <em>something</em> solid today. What I can say for sure is the following:</p>
<ul>
<li>The CGImages behind a UIImage don't use alpha. (kCGImageAlphaNoneSkipLast). I thought that maybe they were faster to be drawn because my context WAS using alpha. So I changed the context to use kCGImageAlphaNoneSkipLast. This makes the drawing MUCH faster, UNLESS:</li>
<li>Drawing into a CGContextRef with a UIImage FIRST, makes ALL subsequent image drawing slow</li>
</ul>
<p>I proved this by 1)first creating a non-alpha context (1936x2592). 2) Filled it with randomly colored 2x2 squares. 3) Full frame drawing a CGImage into that context was FAST (.17 seconds) 4) Repeated experiment but filled context with a drawn CGImage backing a UIImage. Subsequent full frame image drawing was 6+ seconds. SLOWWWWW. </p>
<p>Somehow drawing into a context with a (Large) UIImage drastically slows all subsequent drawing into that context. </p> | 7,599,794 | 2 | 2 | null | 2011-09-26 20:32:27.117 UTC | 34 | 2013-04-22 09:11:26.743 UTC | 2011-09-27 20:01:16.833 UTC | null | 346,381 | null | 346,381 | null | 1 | 33 | ios|performance|core-graphics|cgcontextdrawimage | 15,260 | <p>Well after a TON of experimentation I think I have found the fastest way to handle situations like this. The drawing operation above which was taking 6+ seconds now .1 seconds. YES. Here's what I discovered:</p>
<ul>
<li><p>Homogenize your contexts & images with a pixel format! The root of the question I asked boiled down to the fact that the CGImages inside a UIImage were using THE SAME PIXEL FORMAT as my context. Therefore fast. The CGImages were a different format and therefore slow. Inspect your images with CGImageGetAlphaInfo to see which pixel format they use. I'm using kCGImageAlphaNoneSkipLast EVERYWHERE now as I don't need to work with alpha. If you don't use the same pixel format everywhere, when drawing an image into a context Quartz will be forced to perform expensive pixel-conversions for EACH pixel. = SLOW </p></li>
<li><p>USE CGLayers! These make offscreen-drawing performance much better. How this works is basically as follows. 1) create a CGLayer from the context using CGLayerCreateWithContext. 2) do any drawing/setting of drawing properties on THIS LAYER's CONTEXT which is gotten with CGLayerGetContext. READ any pixels or information from the ORIGINAL context. 3) When done, "stamp" this CGLayer back onto the original context using CGContextDrawLayerAtPoint.This is FAST as long as you keep in mind: </p></li>
<li><p>1) Release any CGImages created from a context (i.e. those created with CGBitmapContextCreateImage) BEFORE "stamping" your layer back into the CGContextRef using CGContextDrawLayerAtPoint. This creates a 3-4x speed increase when drawing that layer. 2) Keep your pixel format the same everywhere!! 3) Clean up CG objects AS SOON as you can. Things hanging around in memory seem to create strange situations of slowdown, probably because there are callbacks or checks associated with these strong references. Just a guess, but I can say that CLEANING UP MEMORY ASAP helps performance immensely.</p></li>
</ul> |
31,878,901 | Should I add the Visual Studio 2015 .vs folder to source control? | <p>Visual Studio 2015 creates a new folder called ".vs". What is the purpose of it and should I add it to source control?</p> | 31,879,242 | 3 | 2 | null | 2015-08-07 13:26:26.71 UTC | 24 | 2018-11-26 11:46:27.143 UTC | null | null | null | null | 1,442,776 | null | 1 | 350 | git|svn|version-control|visual-studio-2015|ignore | 106,533 | <p>No, you should not add it to source control. The purpose of this folder is to move machine- and user-specific files to a central location. The explanation on the <a href="https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/6079923-store-project-related-information-in-vs-folder-to">Visual Studio User Voice issue</a> explains it well:</p>
<blockquote>
<p>So far, we have moved the .SUO file and the VB/C# compiler IntelliSense database files to the new location. All new project specific, machine local files will be added to the new location too. We plan on taking this even further in future releases and are investigating how to improve the directory structure of build output and other existing files that can clutter the source tree.</p>
</blockquote>
<p>These are all files that you would never check in, since they are generated from a build or contain machine-specific information.</p> |
18,909,579 | How to add event for Checkbox click in Asp.net Gridview Column | <p>I have a gridview in asp where i have added first column as checkbox column.Now i want to select this column and get the id values of the row ..But I am not getting how to do it..</p>
<p>This is my Aspx code..</p>
<pre><code><asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound"
AutoGenerateColumns="False" BackColor="LightGoldenrodYellow"
BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black"
GridLines="None">
<AlternatingRowStyle BackColor="PaleGoldenrod" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkhdr" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkChild" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("col0") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role(Admin)">
<ItemTemplate>
<asp:CheckBox ID="chkAdmin" runat="server" Checked='<%# Eval("col1") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role(User)">
<ItemTemplate>
<asp:CheckBox ID="chkUser" runat="server" Checked='<%# Eval("col2") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Role(GeneralUser)">
<ItemTemplate>
<asp:CheckBox ID="chkgen" runat="server" Checked='<%# Eval("col3") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</code></pre>
<p>And here is my code behind file...</p>
<pre><code>protected void BindGridviewData()
{
var role = from MembershipUser u in Membership.GetAllUsers()
select new
{
User = u.UserName,
Role = string.Join(",", Roles.GetRolesForUser(u.UserName))
};
DataTable dTable = new DataTable();
dTable.Columns.Add("col0", typeof(string));
dTable.Columns.Add("col1", typeof(bool));
dTable.Columns.Add("col2", typeof(bool));
dTable.Columns.Add("col3", typeof(bool));
foreach (MembershipUser u in Membership.GetAllUsers())
{
DataRow dRow = dTable.NewRow();
dRow[0] = u.UserName;
string[] roles = Roles.GetRolesForUser(u.UserName);
dRow[1] = roles.Contains("Admin") ? true : false;
dRow[2] = roles.Contains("DPAO User") ? true : false;
dRow[3] = roles.Contains("GeneralUser") ? true : false;
dTable.Rows.Add(dRow);
}
GridView1.DataSource = dTable;
GridView1.DataBind();
}
</code></pre>
<p>Please Guys help me as i have no idea how to accomplish this ...Thanks in advance...</p> | 18,910,220 | 5 | 1 | null | 2013-09-20 05:40:25.18 UTC | 1 | 2016-02-25 10:08:32.263 UTC | null | null | null | null | 2,767,385 | null | 1 | 6 | c#|asp.net|gridview | 69,471 | <p>If you want <strong>Delete</strong> record by <strong>Button</strong> try this:</p>
<p>Add a Button outside of gridview for Delete:</p>
<pre><code><asp:Button ID="cmdDelete" runat="server" onclick="cmdDelete_Click" Text="Delete" />
</code></pre>
<p>Code behind:</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
protected void BindGridviewData()
{
DataTable dTable = new DataTable();
dTable.Columns.Add("col0", typeof(string));
dTable.Columns.Add("col1", typeof(bool));
dTable.Columns.Add("col2", typeof(bool));
dTable.Columns.Add("col3", typeof(bool));
foreach (MembershipUser u in Membership.GetAllUsers())
{
DataRow dRow = dTable.NewRow();
dRow[0] = u.UserName;
string[] roles = Roles.GetRolesForUser(u.UserName);
dRow[1] = roles.Contains("Admin") ? true : false;
dRow[2] = roles.Contains("DPAO User") ? true : false;
dRow[3] = roles.Contains("GeneralUser") ? true : false;
dTable.Rows.Add(dRow);
}
GridView1.DataSource = dTable;
GridView1.DataBind();
}
protected void cmdDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chkChild");
if (chk.Checked)
{
Label username = (Label)row.FindControl("Label1");
Membership.DeleteUser(username.Text);
BindGridviewData();
}
}
}
</code></pre> |
3,615,518 | CSS selector to select first element of a given class | <p>I'm trying to select a first element of class 'A' in an element with id or class 'B'. I've tried a combination of > + and first-child selectors, since it's not a first element inside class element 'B'. It worked, but ... i'm trying to override some default css and i have no control over the server side and it seems that the class 'A' element is sometimes generated in a different position. Here's an illustration:</p>
<pre class="lang-html prettyprint-override"><code><class-C>
<class-B> might have a different name
<some-other-classes> structure and element count might differ
<class-A></class-A> our target
<class-A></class-A> this shouldn't be affected
<class-A></class-A> this shouldn't be affected
</class-B>
</class-C>
</code></pre>
<p>Sometimes the name of the class 'B' differs and the elements before 'A' differ as well. So is there any way to select the first occurrence of 'A' in an element 'C'? Because class 'C' is always there. I can't use + > and first-child selectors since the path to first 'A' element differs, but element 'C' is always there and it would be a nice starting point.</p> | 3,615,559 | 1 | 3 | null | 2010-09-01 06:29:31.157 UTC | 12 | 2018-03-19 19:09:00.707 UTC | 2018-03-19 19:09:00.707 UTC | null | 2,756,409 | null | 422,778 | null | 1 | 19 | css|css-selectors | 29,998 | <p>CSS3 provides the <code>:first-of-type</code> pseudo-class for selecting the first element of its type in relation to its siblings. However it doesn't have a <code>:first-of-class</code> pseudo-class.</p>
<p>As a workaround, if you know the default styles for your other <code>.A</code> elements, you can use an overriding rule with the general sibling combinator <code>~</code> to apply styles to them. This way, you sort of "undo" the first rule.</p>
<p>The bad news is that <code>~</code> is a CSS3 selector.<br>
The good news is that IE recognizes it starting from IE7, like CSS2's <code>></code>, so if you're worried about browser compatibility, the only "major browser" this fails on is IE6.</p>
<p>So you have these two rules:</p>
<pre><code>.C > * > .A {
/*
* Style every .A that's a grandchild of .C.
* This is the element you're looking for.
*/
}
.C > * > .A ~ .A {
/*
* Style only the .A elements following the first .A child
* of each element that's a child of .C.
* You need to manually revert/undo the styles in the above rule here.
*/
}
</code></pre>
<p>How styles are applied to elements is illustrated below:</p>
<pre class="lang-html prettyprint-override"><code><div class="C">
<!--
As in the question, this element may have a class other than B.
Hence the intermediate '*' selector above (I don't know what tag it is).
-->
<div class="B">
<div class="E">Content</div> <!-- [1] -->
<div class="F">Content</div> <!-- [1] -->
<div class="A">Content</div> <!-- [2] -->
<div class="A">Content</div> <!-- [3] -->
</div>
<div class="D">
<div class="A">Content</div> <!-- [2] -->
<div class="E">Content</div> <!-- [1] -->
<div class="F">Content</div> <!-- [1] -->
<div class="A">Content</div> <!-- [3] -->
</div>
</div>
</code></pre>
<ol>
<li><p>This element does not have class <code>A</code>. No rules are applied.</p></li>
<li><p>This element has class <code>A</code>, so the first rule is applied. However it doesn't have any other such elements occurring before it, which the <code>~</code> selector requires, so the second rule is <strong>not</strong> applied.</p></li>
<li><p>This element has class <code>A</code>, so the first rule is applied. It also comes after other elements with the same class under the same parent, as required by <code>~</code>, so the second rule is also applied. The first rule is overridden.</p></li>
</ol> |
3,483,604 | Which shortcut in Zsh does the same as Ctrl-U in Bash? | <p>In Bash, when I am typing a command, I press <kbd>Ctrl</kbd>+<kbd>U</kbd>, all characters from the beginning of the line to the cursor are going to be removed. However, in zsh, if I pressed <kbd>Ctrl</kbd>+<kbd>U</kbd>, the whole line is gone.</p>
<p>How to do the same in Zsh as in Bash?</p> | 3,483,679 | 1 | 1 | null | 2010-08-14 13:55:24.04 UTC | 18 | 2014-02-17 01:38:48.787 UTC | 2014-02-17 01:38:48.787 UTC | null | 50,939 | null | 164,835 | null | 1 | 74 | bash|zsh | 8,105 | <p>It sounds like you'd like for <kbd>Ctrl</kbd>+<kbd>U</kbd> to be bound to <code>backward-kill-line</code> rather than <code>kill-whole-line</code>, so add this to your <code>.zshrc</code>:</p>
<pre><code>bindkey \^U backward-kill-line
</code></pre>
<p>The <code>bindkey</code> builtin and the available editing commands (“widgets”) are documented in the <code>zshzle</code> man page.</p> |
28,211,806 | How to count number of rows using JPA? | <p>I try to count number of rows using JPA.I want to use where clause
however I can't. </p>
<pre><code>CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
cq.where(); //how to write where clause
return entityManager.createQuery(cq).getSingleResult();
</code></pre>
<p>How can I set where clause forexample where age="45".
Thanks in advance.</p> | 28,211,896 | 5 | 2 | null | 2015-01-29 10:02:18.567 UTC | 2 | 2022-05-12 20:55:50.137 UTC | null | null | null | null | 4,104,008 | null | 1 | 12 | java|hibernate|jpa | 47,104 | <p>Use <a href="http://docs.oracle.com/javaee/7/api/javax/persistence/criteria/ParameterExpression.html" rel="noreferrer"><code>ParameterExpression</code></a>. Note: <em>Untested</em>.</p>
<pre><code>CriteriaBuilder qb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = qb.createQuery(Long.class);
cq.select(qb.count(cq.from(MyEntity.class)));
ParameterExpression<Integer> p = qb.parameter(Integer.class);
q.where(qb.eq(c.get("age"), 45));
return entityManager.createQuery(cq).getSingleResult();
</code></pre>
<p><a href="http://www.objectdb.com/java/jpa/query/jpql/where" rel="noreferrer">Reference</a>.</p> |
2,077,054 | How to compute a radius around a point in an Android MapView? | <p>I have a <a href="http://code.google.com/android/add-ons/google-apis/reference/index.html?com/google/android/maps/MapView.html" rel="noreferrer">MapView</a> that I'm displaying a "useful radius" (think accuracy of coordinate) in. Using <code>MapView</code>'s <a href="http://code.google.com/android/add-ons/google-apis/reference/com/google/android/maps/Projection.html" rel="noreferrer">Projection</a>'s <a href="http://code.google.com/android/add-ons/google-apis/reference/com/google/android/maps/Projection.html#metersToEquatorPixels%28float%29" rel="noreferrer">metersToEquatorPixels</a>, which is admittedly just for equatorial distance) isn't giving me an accurate enough distance (in pixels). How would you compute this if you wanted to display a circle around your coordinate, given radius?</p> | 2,083,156 | 3 | 4 | null | 2010-01-16 10:50:33.83 UTC | 10 | 2017-02-07 14:23:10.88 UTC | null | null | null | null | 76,835 | null | 1 | 12 | android|gps|android-mapview | 12,122 | <p>So, Google Maps uses a <a href="http://en.wikipedia.org/wiki/Mercator_projection" rel="noreferrer">Mercator projection</a>. This means that the further you get from the equator the more distorted the distances become. According to <a href="http://www.anddev.org/viewtopic.php?p=16075" rel="noreferrer">this discussion</a>, the proper way to convert for distances is something like:</p>
<pre><code>public static int metersToRadius(float meters, MapView map, double latitude) {
return (int) (map.getProjection().metersToEquatorPixels(meters) * (1/ Math.cos(Math.toRadians(latitude))));
}
</code></pre> |
8,776,788 | Best practice on PHP singleton classes | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/4595964/who-needs-singletons">Who needs singletons?</a> </p>
</blockquote>
<p>I always write with respect to <em>best practice</em>, but I also want to understand why a given thing is a <em>best practice</em>.</p>
<p>I've read on in an article (I unfortunately don't remember) that singleton classes are prefered to be instantiated, rather than being made with static functions and accessed with the scope resolution operator (::). So if I have a class that contains all my tools to validate, in short:</p>
<pre><code>class validate {
private function __construct(){}
public static function email($input){
return true;
}
}
</code></pre>
<p>I've been told this is considered <em>bad practice</em> (or at least warned against), because of such things as the garbage collector and maintenance. So what the critiques of the "singleton class as static methods" wants, is that I instantiate a class I'm 100% certain I will only ever instantiate once. To me it seems like doing "double work", because it's all ready there. What am I missing?</p>
<p>What's the view on the matter? Of course it's not a life and death issue, but one might as well do a thing the right way, if the option is there :)</p> | 8,776,814 | 3 | 1 | null | 2012-01-08 10:28:47.61 UTC | 48 | 2012-07-29 20:07:49.903 UTC | 2017-05-23 10:30:55.627 UTC | null | -1 | null | 1,064,776 | null | 1 | 24 | php|oop|class|design-patterns|singleton | 71,498 | <p>An example singleton classes in php:<br/>
<a href="https://stackoverflow.com/a/203359/858515">Creating the Singleton design pattern in PHP5 : Ans 1 :</a><br/>
<a href="https://stackoverflow.com/a/1939269/858515">Creating the Singleton design pattern in PHP5 : Ans 2 :</a></p>
<p><code>Singleton is considered "bad practice".</code></p>
<p>Mainly because of this: <a href="https://stackoverflow.com/questions/5283102/how-is-testing-registry-pattern-or-singleton-hard-in-php/5283151#5283151">How is testing the registry pattern or singleton hard in PHP?</a></p>
<blockquote>
<ul>
<li><p><a href="http://www.slideshare.net/go_oh/singletons-in-php-why-they-are-bad-and-how-you-can-eliminate-them-from-your-applications" rel="noreferrer">why are singleton bad?</a></p>
</li>
<li><p><a href="http://blogs.msdn.com/b/scottdensmore/archive/2004/05/25/140827.aspx" rel="noreferrer">why singletons are evil?</a></p>
</li>
<li><p><a href="http://fabien.potencier.org/article/11/what-is-dependency-injection" rel="noreferrer">A good approach: Dependency Injection</a></p>
</li>
<li><p><a href="http://fabien.potencier.org/talk/19/decouple-your-code-for-reusability-ipc-2008" rel="noreferrer">Presentation on reusability: Decouple your PHP code for reusability</a></p>
</li>
<li><p><a href="http://fabien.potencier.org/article/12/do-you-need-a-dependency-injection-container" rel="noreferrer">Do you need a dependency injection container</a></p>
</li>
<li><p><a href="http://www.phparch.com/2010/03/static-methods-vs-singletons-choose-neither/" rel="noreferrer">Static methods vs singletons choose neither</a></p>
</li>
<li><p><a href="http://www.youtube.com/watch?v=-FRm3VPhseI" rel="noreferrer">The Clean Code Talks - "Global State and Singletons"</a></p>
</li>
<li><p><a href="http://martinfowler.com/articles/injection.html" rel="noreferrer">Inversion of Control Containers and the Dependency Injection pattern</a></p>
</li>
</ul>
</blockquote>
<p>Wanna read more? :</p>
<blockquote>
<ul>
<li><p><a href="https://stackoverflow.com/questions/3124412/what-are-the-disadvantages-of-using-a-php-database-class-as-singleton/3124428#3124428">What are the disadvantages of using a PHP database class as a singleton?</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/3272090/php-pdo-database-abstraction-class-design-question/3274863#3274863">Database abstraction class design using PHP PDO</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/3870635/would-singleton-be-a-good-design-pattern-for-a-microblogging-site/3870710#3870710">Would singleton be a good design pattern for a microblogging site?</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/4244437/modifying-a-class-to-encapsulate-instead-of-inherit/4244824#4244824">Modifying a class to encapsulate instead of inherit</a></p>
</li>
<li><p><a href="https://stackoverflow.com/questions/3820103/how-to-access-an-object-from-another-class/3820286#3820286">How to access an object from another class?</a></p>
</li>
<li><p><a href="http://sebastian-bergmann.de/archives/882-Testing-Code-That-Uses-Singletons.html" rel="noreferrer">Testing Code That Uses Singletons</a></p>
</li>
</ul>
</blockquote>
<p><em><strong>A Singleton decision diagram (<a href="https://stackoverflow.com/a/4596323/208809">source</a>):</strong></em></p>
<p><img src="https://i.stack.imgur.com/Dzdio.png" alt="Singleton Decision Diagram" /></p> |
27,210,646 | Swift equivalent to __attribute((objc_requires_super))? | <p>Is there a Swift equivalent to</p>
<pre><code>__attribute((objc_requires_super))
</code></pre>
<p>which gives a warning if a method doesn't call it's super method?</p>
<p>Basically, I want to warn (or even better, throw a compiler error) if an overridden method doesn't call its super method.</p> | 27,328,607 | 1 | 2 | null | 2014-11-30 06:21:20.117 UTC | 6 | 2016-04-29 20:12:53.77 UTC | 2016-04-29 20:12:53.77 UTC | null | 2,792,531 | null | 1,648,724 | null | 1 | 28 | swift | 3,256 | <p>No, there is no Swift equivalent to <code>__attribute((objc_requires_super))</code>.</p>
<p>The equivalent feature, <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Attributes.html" rel="noreferrer">Swift Attributes</a>, contains no such attribute.</p>
<p>The section of the <a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Inheritance.html#//apple_ref/doc/uid/TP40014097-CH17-XID_296" rel="noreferrer">Swift inheritance documentation</a> where such a feature <em>would</em> be mentioned says only:</p>
<blockquote>
<p>When you provide a method, property, or subscript override for a subclass, it is sometimes useful to use the existing superclass implementation as part of your override.</p>
</blockquote>
<hr>
<p>Note that you <strong>can</strong> prevent overriding functions using <code>final</code>, so you could <em>effectively</em> accomplish what you want by providing empty overridable methods that are called by non-overridable methods:</p>
<pre><code>class AbstractStarship {
var tractorBeamOn = false
final func enableTractorBeam() {
tractorBeamOn = true
println("tractor beam successfully enabled")
tractorBeamDidEnable()
}
func tractorBeamDidEnable() {
// Empty default implementation
}
}
class FancyStarship : AbstractStarship {
var enableDiscoBall = false
override func tractorBeamDidEnable() {
super.tractorBeamDidEnable() // this line is irrelevant
enableDiscoBall = true
}
}
</code></pre>
<p>Subclasses would then override the overridable methods, and it wouldn't matter whether they called <code>super</code> or not since the superclass's implementation is empty.</p>
<p>As <a href="https://stackoverflow.com/users/642626/bryan-chen">Bryan Chen</a> notes in the comments, this breaks down if the subclass is subclassed.</p>
<p>I make no claims to whether this approach is <em>stylistically good</em>, but it is certainly possible.</p> |
623,903 | Defining a class within a namespace | <p>Is there a more succinct way to define a class in a namespace than this:</p>
<pre><code>namespace ns { class A {}; }
</code></pre>
<p>I was hoping something like <code>class ns::A {};</code> would work, but alas not.</p> | 623,932 | 4 | 0 | null | 2009-03-08 17:03:18.06 UTC | 13 | 2009-03-08 22:00:19.797 UTC | null | null | null | Iraimbilanja | null | null | 1 | 26 | c++|class|syntax|namespaces|definition | 53,407 | <p>You're close, you can forward declare the class in the namespace and then define it outside if you want:</p>
<pre><code>namespace ns {
class A; // just tell the compiler to expect a class def
}
class ns::A {
// define here
};
</code></pre>
<p>What you cannot do is define the class in the namespace without members and then define the class again outside of the namespace. That violates the One Definition Rule (or somesuch nonsense).</p> |
934,233 | cscope or ctags why choose one over the other? | <p>I primarily use vim / gvim as an editor and am looking at using a combination of <a href="http://lxr.linux.no/" rel="noreferrer">lxr (the Linux Cross Reference)</a> and either <a href="http://cscope.sourceforge.net/" rel="noreferrer">cscope</a> or <a href="http://ctags.sourceforge.net/" rel="noreferrer">ctags</a> for exploring the kernel source. However, I haven't ever used either <a href="http://cscope.sourceforge.net/" rel="noreferrer">cscope</a> or <a href="http://ctags.sourceforge.net/" rel="noreferrer">ctags</a> and would like to hear why one might choose one over the other taking into consideration my use of vim as a primary editor.</p> | 934,523 | 4 | 0 | null | 2009-06-01 10:14:34.167 UTC | 109 | 2018-11-30 08:50:23.807 UTC | 2013-03-05 14:42:14.333 UTC | null | 95,592 | null | 71,074 | null | 1 | 144 | vim|kernel|ctags|cscope | 75,311 | <p>ctags enables two features: allowing you to jump from function calls to their definitions, and omni completion. The first means that when you are over a call to a method, hitting <code>g]</code> or <code>CTRL-]</code> will jump to the place where that method is defined or implemented. The second feature means that when you type <code>foo.</code> or <code>foo-></code>, and if foo is a structure, then a pop-up menu with field completion will be shown.</p>
<p>cscope also has the first feature - using <code>set cscopetag</code> - but not the last. However cscope additionally adds the ability to jump to any of the places where a function is called as well.</p>
<p>So as far as jumping around a code base is concerned, ctags will only ever lead you towards the place where the function is implemented, whereas cscope can show you where a function is called too.</p>
<p>Why would you choose one over the other? Well, I use both. ctags is easier to set up, faster to run and if you only care about jumping one way it will show you less lines. You can just run <code>:!ctags -R .</code> and <code>g]</code> just works. It also enables that omni complete thing.</p>
<p>Cscope is great for bigger, unknown code bases. The set up is a pain because cscope needs a file containing a list of names of files to parse. Also in vim, by default there are no key bindings set up - you need to run <code>:cscope blah blah</code> manually.</p>
<p>To solve the fist problem I've got a bash script <code>cscope_gen.sh</code> that looks like this:</p>
<pre><code>#!/bin/sh
find . -name '*.py' \
-o -name '*.java' \
-o -iname '*.[CH]' \
-o -name '*.cpp' \
-o -name '*.cc' \
-o -name '*.hpp' \
> cscope.files
# -b: just build
# -q: create inverted index
cscope -b -q
</code></pre>
<p>This searches for code that I'm interested in, creates the cscope.files list and creates the database. That way I can run ":!cscope_gen.sh" instead of having to remember all the set up steps.</p>
<p>I map cscope search to ctrl-space x 2 with this snippet, which mitigates the other downer of cscope:</p>
<pre><code>nmap <C-@><C-@> :cs find s <C-R>=expand("<cword>")<CR><CR>
</code></pre>
<p>There's <a href="http://cscope.sourceforge.net/cscope_maps.vim" rel="noreferrer">this cscope_maps.vim plugin</a> that sets up a bunch of similar bindings. I can never remember what all the options mean, so tend to stick to ctrl-space.</p>
<p>So to conclude: ctags is easier to set up and mostly works without doing much else, it's vital for omni-complete too. cscope provides more features if you have to maintain a large and mostly unknown code base, but requires more leg work.</p> |
22,080,382 | mysql: why comparing a 'string' to 0 gives true? | <p>I was doing some MySQL test queries, and realized that comparing a string column with <code>0</code> (as a number) gives <code>TRUE</code>!</p>
<pre><code>select 'string' = 0 as res; -- res = 1 (true), UNexpected! why!??!?!
</code></pre>
<p>however, comparing it to any other number, positive or negative, integer or decimal, gives <code>false</code> as expected
(of course unless the string is the representation of the number as string)</p>
<pre><code>select 'string' = -12 as res; -- res = 0 (false), expected
select 'string' = 3131.7 as res; -- res = 0 (false), expected
select '-12' = -12 as res; -- res = 1 (true), expected
</code></pre>
<p>Of course comparing the string with <code>'0'</code> as string, gives false, as expected.</p>
<pre><code>select 'string' = '0' as res; -- res = 0 (false), expected
</code></pre>
<p>but why does it give true for <code>'string' = 0</code> ?</p>
<p>why is that?</p> | 22,080,540 | 3 | 1 | null | 2014-02-27 21:06:43.933 UTC | 10 | 2016-08-20 15:59:24.003 UTC | null | null | null | null | 1,385,198 | null | 1 | 19 | mysql|string|comparison | 8,284 | <p>MySQL automatically casts a string to a number:</p>
<pre><code>SELECT '1string' = 0 AS res; -- res = 0 (false)
SELECT '1string' = 1 AS res; -- res = 1 (true)
SELECT '0string' = 0 AS res; -- res = 1 (true)
</code></pre>
<p>and a string that does not begin with a number is evaluated as 0:</p>
<pre><code>SELECT 'string' = 0 AS res; -- res = 1 (true)
</code></pre>
<p>Of course, when we try to compare a string with another string there's no conversion:</p>
<pre><code>SELECT '0string' = 'string' AS res; -- res = 0 (false)
</code></pre>
<p>but we can force a conversion using, for example, a + operator:</p>
<pre><code>SELECT '0string' + 0 = 'string' AS res; -- res = 1 (true)
</code></pre>
<p>last query returns TRUE because we ar summing a string '0string' with a number 0, so the string has to be converted to a number, it becomes <code>SELECT 0 + 0 = 'string'</code> and then again the string 'string' is converted to a number before being compared to 0, and it then becomes <code>SELECT 0 = 0</code> which is TRUE.</p>
<p>This will also work:</p>
<pre><code>SELECT '1abc' + '2ef' AS total; -- total = 1+2 = 3
</code></pre>
<p>and will return the sum of the strings converted to numbers (1 + 2 in this case).</p> |
52,941,346 | CSS `height: calc(100vh);` Vs `height: 100vh;` | <p>I'm working on a project where the former developer used:</p>
<pre><code>.main-sidebar {
height: calc(100vh);
}
</code></pre>
<p>I have no way to contact him/her anymore, and I would like to understand what is the difference (if any) between the two methods.</p>
<p>(Is this the right place to ask this question?)</p> | 52,941,381 | 6 | 2 | null | 2018-10-23 04:46:17.56 UTC | 6 | 2022-01-19 10:40:21.3 UTC | null | null | null | null | 4,603,295 | null | 1 | 25 | html|css|user-interface|cross-browser | 129,743 | <p>There's no difference, since any time the expression <code>calc(100vh)</code> is calculated, it always ends up being <code>100vh</code>.</p> |
34,301,881 | Should I 'use strict' for every single javascript function I write? | <p>Should I 'use strict' for every single javascript function I write?</p>
<p>What is a good practice to use strict in a large AngularJS project? Using it globally can break a third party library that doesn't support it, but doing 'use strict' every single time is just a lot of repetition.</p> | 34,302,448 | 4 | 0 | null | 2015-12-16 00:16:24.15 UTC | 3 | 2018-03-02 14:20:42.677 UTC | 2015-12-16 01:13:03.72 UTC | null | 1,048,572 | null | 46,869 | null | 1 | 32 | javascript|strict-mode | 17,039 | <p>On this question, do beware a general tendency to oversimplify.</p>
<p>First, all of your code absolutely should <em>be run</em> in strict mode. Core modern javascript functionality is changed (see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call" rel="noreferrer">.call() and apply()</a>) or disfigured (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode" rel="noreferrer">silent Errors</a>) by executing code outside of strict mode. (More on this <a href="http://www.yuiblog.com/blog/2010/12/14/strict-mode-is-coming-to-town/" rel="noreferrer">here</a>, from Crockford.)</p>
<p>However, that doesn't address <em>how</em> you should ensure that your code runs in strict mode. There are at least two contexts to consider:</p>
<p><strong>In the browser</strong>, your code should be delivered after being minified. If you include <code>'use strict'</code> in every function body, your minifier won't strip it out, and you'll waste bytes repeating it everywhere. You only need it in your outermost function scope(s)—at the top of your module definitions. One approach is to wrap your minified code in a single IIFE closure as part of the build process:</p>
<pre><code>;(function (){
'use strict'
// All code here.
}())
</code></pre>
<p>This, I think, is close to the ideal way of doing it, but it more or less dictates that you adopt a continuous integration workflow (since, to observe your code running in strict mode, you must have it all wrapped up one closure). If you don't work that way, you'll have to include the <code>use strict</code> directive at the top of every function that isn't being declared within another function's scope.</p>
<p><strong>On the server</strong>, it's much simpler, of course. Code isn't minified, and bytes don't matter, so you can just include the <code>use strict</code> directive at the top of every file.</p>
<p><em>A word of warning on <code>--use_strict</code></em>: In cases where you control how scripts are run, you may find yourself tempted to use the <code>--use_strict</code> runtime flag. It's easy, but it means <em>all dependencies</em> must be strict mode compliant. Since you can't control every third-party's compliance, this is usually unwise.</p> |
36,401,375 | How to use angular component with ui.bootstrap.modal in angular 1.5? | <p>I'd like to use angular component with ui.bootstrap.modal. angular version is 1.5.<br>
I tried to use like below.</p>
<p><strong>component</strong> </p>
<pre><code>function MyComponentController($uibModalInstance){
var ctrl = this;
ctrl.doSomething = function() {
//doSomething
}
}
app.component('myComponent', {
contoller: MyComponentController,
templateUrl: '/path/to/myComponent.html'
}
</code></pre>
<p><strong>parent controller</strong></p>
<pre><code>function parentController($uibModal){
var ctrl = this;
ctrl.openModal = function(){
var modalInstance = $uibModal.open({
template: '<my-component></my-component>'
}
}
</code></pre>
<p>And when I execute <code>parentController.openModal()</code> , I got the error of <a href="https://docs.angularjs.org/error/$injector/unpr?p0=$uibModalInstanceProvider%20%3C-%20$uibModalInstance">$injector:unpr Unknown Provider</a> although modal window is open.<br>
Is there a way to use angular component with ui.bootstrap.modal?
If you need more information, please let me know that.<br>
Thank you.</p>
<p><strong>EDIT</strong><br>
I've got a way to use component with ui.bootstrap.modal from Renato Machado, Thanks Renato.<br>
But I feel It's a little bit complicated and not convenient. So finally I think that it's better to use component inside the modal.<br>
Modal is opened with regular way(just set controller and template in <code>$uibModal.open({})</code> ) and the modal contains the component which has logics you want to use commonly.<br>
Modal should have only simple logics that are related with modal like close modal window.<br>
Another logics mainly related with business/Application should be in component.<br>
It makes easy to commonalize.</p> | 37,381,735 | 4 | 5 | null | 2016-04-04 11:28:38.183 UTC | 15 | 2018-05-18 20:46:24.78 UTC | 2016-04-22 02:46:54.627 UTC | null | 6,005,861 | null | 6,005,861 | null | 1 | 43 | javascript|angularjs|angular-ui-bootstrap | 43,139 | <p>EDIT: As of UI Bootstrap 2.1.0 there is native support for component in bootstrap modals. It looks like there have been several quick releases after 2.1.0 to fix some issues with the modals, so I'd be sure to grab the latest. </p>
<p>See this Plunk for a version using UI Bootstrap 2.1.0+</p>
<p><a href="http://plnkr.co/edit/jy8WHfJLnMMldMQRj1tf?p=preview" rel="noreferrer">http://plnkr.co/edit/jy8WHfJLnMMldMQRj1tf?p=preview</a></p>
<pre><code>angular.module('app', ['ngAnimate', 'ui.bootstrap']);
angular.module('app')
.component('myContent', {
template: 'I am content! <button type="button" class="btn btn-default" ng-click="$ctrl.open()">Open Modal</button>',
controller: function($uibModal) {
$ctrl = this;
$ctrl.dataForModal = {
name: 'NameToEdit',
value: 'ValueToEdit'
}
$ctrl.open = function() {
$uibModal.open({
component: "myModal",
resolve: {
modalData: function() {
return $ctrl.dataForModal;
}
}
}).result.then(function(result) {
console.info("I was closed, so do what I need to do myContent's controller now. Result was->");
console.info(result);
}, function(reason) {
console.info("I was dimissed, so do what I need to do myContent's controller now. Reason was->" + reason);
});
};
}
});
angular.module('app')
.component('myModal', {
template: `<div class="modal-body"><div>{{$ctrl.greeting}}</div>
<label>Name To Edit</label> <input ng-model="$ctrl.modalData.name"><br>
<label>Value To Edit</label> <input ng-model="$ctrl.modalData.value"><br>
<button class="btn btn-warning" type="button" ng-click="$ctrl.handleClose()">Close Modal</button>
<button class="btn btn-warning" type="button" ng-click="$ctrl.handleDismiss()">Dimiss Modal</button>
</div>`,
bindings: {
modalInstance: "<",
resolve: "<"
},
controller: [function() {
var $ctrl = this;
$ctrl.$onInit = function() {
$ctrl.modalData = $ctrl.resolve.modalData;
}
$ctrl.handleClose = function() {
console.info("in handle close");
$ctrl.modalInstance.close($ctrl.modalData);
};
$ctrl.handleDismiss = function() {
console.info("in handle dismiss");
$ctrl.modalInstance.dismiss("cancel");
};
}]
});
</code></pre>
<p>Original answer is below:</p>
<p>I was trying to figure this out the other day too. I took the information I found in this post along with this link to try and come up with an alternate way to accomplish this. These are some reference links I found that helped me:</p>
<p><a href="https://github.com/angular-ui/bootstrap/issues/5683" rel="noreferrer">https://github.com/angular-ui/bootstrap/issues/5683</a></p>
<p><a href="http://www.codelord.net/" rel="noreferrer">http://www.codelord.net/</a> (this one helped in understanding passing arguments to callbacks in components)</p>
<p>Also here is a Plunk: <a href="http://plnkr.co/edit/PjQdBUq0akXP2fn5sYZs?p=preview" rel="noreferrer">http://plnkr.co/edit/PjQdBUq0akXP2fn5sYZs?p=preview</a></p>
<p>I tried to demonstrate a common real world scenario of using a modal to edit some data.</p>
<pre><code>angular.module('app', ['ngAnimate', 'ui.bootstrap']);
angular.module('app')
.component('myContent', {
template: 'I am content! <button type="button" class="btn btn-default" ng-click="$ctrl.open()">Open Modal</button>',
controller: function($uibModal) {
$ctrl = this;
$ctrl.dataForModal = {
name: 'NameToEdit',
value: 'ValueToEdit'
}
$ctrl.open = function() {
$uibModal.open({
template: '<my-modal greeting="$ctrl.greeting" modal-data="$ctrl.modalData" $close="$close(result)" $dismiss="$dismiss(reason)"></my-modal>',
controller: ['modalData', function(modalData) {
var $ctrl = this;
$ctrl.greeting = 'I am a modal!'
$ctrl.modalData = modalData;
}],
controllerAs: '$ctrl',
resolve: {
modalData: $ctrl.dataForModal
}
}).result.then(function(result) {
console.info("I was closed, so do what I need to do myContent's controller now and result was->");
console.info(result);
}, function(reason) {
console.info("I was dimissed, so do what I need to do myContent's controller now and reason was->" + reason);
});
};
}
});
angular.module('app')
.component('myModal', {
template: `<div class="modal-body"><div>{{$ctrl.greeting}}</div>
<label>Name To Edit</label> <input ng-model="$ctrl.modalData.name"><br>
<label>Value To Edit</label> <input ng-model="$ctrl.modalData.value"><br>
<button class="btn btn-warning" type="button" ng-click="$ctrl.handleClose()">Close Modal</button>
<button class="btn btn-warning" type="button" ng-click="$ctrl.handleDismiss()">Dimiss Modal</button>
</div>`,
bindings: {
$close: '&',
$dismiss: '&',
greeting: '<',
modalData: '<'
},
controller: [function() {
var $ctrl = this;
$ctrl.handleClose = function() {
console.info("in handle close");
$ctrl.$close({
result: $ctrl.modalData
});
};
$ctrl.handleDismiss = function() {
console.info("in handle dismiss");
$ctrl.$dismiss({
reason: 'cancel'
});
};
}],
});
</code></pre> |
7,683,434 | PermGen space error - Glassfish Server | <p>I am running java web application using Hibernate and glassfish Server. I am getting </p>
<p><code>java.lang.OutOfMemoryError: PermGen space</code> exception when after I deploying it several times.</p>
<p>I tried <code>-XX:MaxPermSize=128M</code> in my Environment variables, but it doesn't work.</p> | 7,685,644 | 4 | 1 | null | 2011-10-07 05:40:01.067 UTC | 15 | 2013-07-09 14:49:24.457 UTC | 2011-10-07 10:25:24.127 UTC | null | 936,832 | null | 596,770 | null | 1 | 31 | java|exception|memory-leaks|glassfish | 50,225 | <p>This is class loader memory leak. Each time you redeploy the application, a new classloader is created for it and all classes of your application are loaded again. This consumes memory in the perm gen space.</p>
<p>The old classloader and all its loaded classes have to be garbage collected, otherwise you will eventually run into a PermGen space OOME after deploying multiple times. This does not work if an object loaded by an outside classloader holds a reference to any object loaded by the old classloader. <a href="http://blogs.oracle.com/fkieviet/entry/classloader_leaks_the_dreaded_java" rel="noreferrer">This article</a> gives a good explanation of the problem.</p>
<p>Generally, classloader leaks are difficult to analyze and sometimes difficult to fix.
To find out why the old classloaders are not garbage collected, you have to use a profiler. In <a href="http://www.ej-technologies.com/products/jprofiler/overview.html" rel="noreferrer">JProfiler</a>, use the heap walker, select the glassfish classloader objects and use the incoming references view to check for paths to garbage collector roots.</p>
<p>The class loader class is called <code>org.apache.servlet.jasper.JasperLoader</code>. Here's a screenshot of a regular situation, where the class loader is only held by live instances of loaded objects.</p>
<p><img src="https://i.stack.imgur.com/B6u2Q.png" alt="enter image description here"></p>
<p>In your situation, you should see references from outside objects. Another common cause of a classloader leak in web containers is a background thread that is not stopped. Google Guice for example has such a bug in 3.0.</p>
<p>(Disclaimer: my company develops JProfiler)</p> |
21,727,873 | Queue<Integer> q = new LinkedList<Integer>() | <p>Here is <a href="https://stackoverflow.com/questions/4626812/how-do-i-instantiate-a-queue-object-in-java/4626858#4626858">an answer to "How do I instantiate a Queue object in java?"</a>,</p>
<blockquote>
<p><a href="http://download.oracle.com/javase/6/docs/api/java/util/Queue.html" rel="noreferrer"><code>Queue</code></a> is an interface. You can't instantiate an interface directly except via an anonymous inner class. Typically this <em>isn't</em> what you want to do for a collection. Instead, choose an existing implementation. For example:</p>
<p>Queue q = new LinkedList();</p>
<p>or</p>
<p>Queue q = new ArrayDeque();</p>
<p>Typically you pick a collection implementation by the performance and concurrency characteristics you're interested in.</p>
</blockquote>
<p>How does this work? What does it mean for Queue, an interface, to take on the implementation of LinkedList?</p>
<p>Does that mean objects can be dequeued in a FIFO (first-in-first-out order), and calling linked list methods on <code>q</code> would work?</p> | 21,728,088 | 5 | 3 | null | 2014-02-12 12:23:49.243 UTC | 8 | 2019-05-22 09:22:19.35 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 3,301,555 | null | 1 | 9 | java|data-structures|queue | 24,290 | <p>To explain with a (perhaps somewhat flawed) metaphor - think of a <code>LinkedList</code> as a piece of paper. Think of the assignment to a <code>Queue</code> as covering all but a little part of this piece of paper which reveals that it's a <code>Queue</code>.</p>
<p>If you call a <code>Queue</code> method on it, it will still do things like a <code>LinkedList</code> normally would, since that that's what the piece of paper is.</p>
<p>Given that most of it is covered, you can't see it's a <code>LinkedList</code>, all you can see is that it's a <code>Queue</code>, so you can only call the <code>Queue</code> methods on it.</p>
<p>The whole piece of paper is still there - you could simply remove the covering, which would be synonymous to casting it back to a <code>LinkedList</code>, which would then allow you to call any <code>LinkedList</code> method on it again.</p>
<hr>
<p>Now for a bit more technical details:</p>
<p>By the way a <code>LinkedList</code> "normally would" do things I mentioned above, I mean a <code>LinkedList</code> is always a linked-list, even if you assign it to a <code>Queue</code> - it doesn't suddenly start using an array as the underlying implementation, as an <a href="http://docs.oracle.com/javase/6/docs/api/java/util/ArrayDeque.html" rel="noreferrer"><code>ArrayDeque</code></a> would (which also implements <code>Queue</code>), or something else.</p>
<p><code>Queue</code> doesn't actually need to be FIFO (see <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Queue.html" rel="noreferrer">the docs</a>) (if it needed to be, a <code>LinkedList</code> would also need to be), so <code>LinkedList</code> would have quite a bit of freedom in this regard, so let's continue this explanation using <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Deque.html" rel="noreferrer"><code>Deque</code></a> - it has methods to support addition and removal from either the front or the back.</p>
<p>Because <code>LinkedList</code> implements <code>Deque</code>, it needs to implement the <code>addFirst</code> function. Based on the docs, the <code>addFirst</code> function needs to add to the front of the <code>Deque</code>, and indeed, with a <code>LinkedList</code>, it will add to the front of the <code>LinkedList</code> (while the front of the <code>LinkedList</code> doesn't need to be the front of the <code>Deque</code>, by looking at the <code>Deque</code> methods implemented in <code>LinkedList</code>, we see that the front of the <code>Deque</code> is the front of the <code>LinkedList</code>, and all the methods add to / remove from one of the sides, do so from the correct side).</p>
<p>Now for an important albeit somewhat confusing note - <code>LinkedList</code> can, for example, implement <code>Deque</code> and have an <code>addFirst</code> that doesn't do what it's supposed to - it can just, for example, print some random text. There's nothing in the language itself that prevents this - since, as far as the compiler is concerned, implementing <code>Deque</code> just requires that you define a bunch of methods - there's no enforcement of what these methods are supposed to do. In terms of the Java API, and any decent library, it should be safe to assume that every class implementing an interface will conform to what that interface claims to do, but just keep in mind that there isn't something stopping it from not conforming when it comes to more shady libraries or less experienced programmers.</p> |
1,743,131 | "Must Know" IIS features for .NET Architect/Lead | <p>What all IIS features in regards to maintain application/optimization should an .NET (ASP.NET) architect or team lead should be aware of?</p>
<p>LIST of features</p>
<ol>
<li><strong><a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/502ef631-3695-4616-b268-cbe7cf1351ce.mspx?mfr=true" rel="nofollow noreferrer">HTTP Compression</a></strong>. This option significantly improves bandwidth utilization and application performs much faster.</li>
<li><strong>Load Balancing</strong> (<a href="https://stackoverflow.com/users/2424/chris-lively">chris-lively</a>)</li>
<li><strong>Sessions</strong> (<a href="https://stackoverflow.com/users/2424/chris-lively">chris-lively</a>) Different options for Session and reasons for / against its usage </li>
<li><strong>Application Pools</strong> (<a href="https://stackoverflow.com/users/2424/chris-lively">chris-lively</a>)</li>
<li><strong>Security</strong> (<a href="https://stackoverflow.com/users/2424/chris-lively">chris-lively</a>) How to break in and how to defend against it.</li>
</ol>
<p>EDIT: Changed question to wiki. It would be better to put together all these at one place.</p> | 1,743,166 | 4 | 3 | 2009-11-16 16:23:06.43 UTC | 2009-11-16 16:02:00.593 UTC | 11 | 2009-11-16 18:53:02.073 UTC | 2017-05-23 11:45:36.47 UTC | null | -1 | null | 189,311 | null | 1 | 9 | .net|asp.net|performance|iis | 776 | <p>They should understand (in no particular order) </p>
<ul>
<li>web gardens</li>
<li>application pools</li>
<li>Different options for Session and reasons for / against its usage.</li>
<li>Browser inconsistencies with form request size (particularly safari)</li>
<li>Load balancing</li>
<li>Use of secondary servers for static content (images, css, etc)</li>
<li>Browser inconsistencies around cookie handling</li>
<li>Performance monitoring deployed applications</li>
</ul>
<p>If you need proper google/search engine support</p>
<ul>
<li>URL Rewriting</li>
<li>The types of Redirects</li>
</ul>
<p>And the Number 1 thing EVERY web architect should understand</p>
<ul>
<li>Security. How to break in and how to defend against it.</li>
</ul>
<p>If they don't know security then I wouldn't hire them. It is too serious a subject to learn on the job; everything else can be acquired pretty quickly.</p> |
2,042,342 | How to copy a file from a network share to local disk with variables? | <p>If I use the following line:</p>
<pre><code>shutil.copyfile(r"\\mynetworkshare\myfile.txt","C:\TEMP\myfile.txt")
</code></pre>
<p>everything works fine. However, what I can't seem to figure out is how to use a variable with the network share path, because I need the 'r' (relative?) flag. The end result I would imagine would be something like:</p>
<pre><code>source_path = "\\mynetworkshare"
dest_path = "C:\TEMP"
file_name = "\\myfile.txt"
shutil.copyfile(r source_path + file_name,dest_path + file_name)
</code></pre>
<p>But I have had no luck with different variations of this approach.</p> | 2,042,376 | 4 | 0 | null | 2010-01-11 14:16:58.737 UTC | 7 | 2016-08-07 07:51:45.497 UTC | 2016-08-07 07:51:45.497 UTC | null | 3,555,000 | null | 82,541 | null | 1 | 16 | python|network-programming|share | 53,948 | <p>The <code>r</code> used in your first code example is making the string a "raw" string. In this example, that means the string will see the backslashes and not try to use them to escape <code>\\</code> to just <code>\</code>.</p>
<p>To get your second code sample working, you'd use the <code>r</code> on the strings, and not in the <code>copyfile</code> command:</p>
<pre><code>source_path = r"\\mynetworkshare"
dest_path = r"C:\TEMP"
file_name = "\\myfile.txt"
shutil.copyfile(source_path + file_name, dest_path + file_name)
</code></pre> |
1,383,535 | .NET 4.0 code contracts - How will they affect unit testing? | <p>For example this <a href="http://odetocode.com/Blogs/scott/archive/2009/02/24/12574.aspx" rel="nofollow noreferrer">article</a> introduces them. </p>
<p>What is the benefit?</p>
<p>Static analysis seems cool but at the same time it would prevent the ability to pass null as a parameter in unit test. (if you followed the example in the article that is)</p>
<p>While on the topic of unit testing - given how things are now surely there is no point for code contracts if you already practice automated testing? </p>
<p><strong>Update</strong></p>
<p>Having played with Code Contracts I'm a little disappointed. For example, based on the code in the accepted answer:</p>
<pre><code>public double CalculateTotal(Order order)
{
Contract.Requires(order != null);
Contract.Ensures(Contract.Result<double>() >= 0);
return 2.0;
}
</code></pre>
<p>For unit testing, you <strong>still</strong> have to write tests to ensure that null cannot be passed, and the result is greater than or equal to zero if the contracts are <em>business logic</em>. In other words, if I was to remove the first contract, no tests would break, unless I had specifically had a test for this feature. This is based on not using the static analysis built into the better (ultimate etc...) editions of Visual Studio however. </p>
<p>Essentially they all boil down to an alternate way of writing traditional if statements. My experience actually using <a href="https://stackoverflow.com/questions/2639960/how-come-you-cannot-catch-code-contract-exceptions">TDD, with Code Contracts</a> shows why, and how I went about it.</p> | 1,383,611 | 4 | 2 | null | 2009-09-05 15:02:56.587 UTC | 4 | 2014-02-28 00:35:24.73 UTC | 2017-05-23 11:46:21.557 UTC | null | -1 | null | 102,482 | null | 1 | 38 | unit-testing|.net-4.0|code-contracts|microsoft-contracts | 4,047 | <p>I don't think unit testing and contracts interfere with each other that much, and if anything contracts should help unit testing since it removes the need to add tedious repetitive tests for invalid arguments. Contracts specify the minimum you can expect from the function, whereas unit tests attempt to validate the actual behaviour for a particular set of inputs. Consider this contrived example:</p>
<pre><code>
public class Order
{
public IEnumerable Items { get; }
}
public class OrderCalculator
{
public double CalculateTotal(Order order)
{
Contract.Requires(order != null);
Contract.Ensures(Contract.Result<double>() >= 0);
return 2.0;
}
}
</code></pre>
<p>Clearly the code satisfies the contract, but you'd still need unit testing to validate it actually behaves as you'd expect.</p> |
1,526,471 | git: difference between "branchname" and "refs/heads/branchname" | <p>Best to be explained at an example: I am on branch 0.58 of repository and this his how I pull:</p>
<pre><code>git pull origin 0.58
</code></pre>
<p>When I just call "git pull", I get:</p>
<pre><code>ip238:openlierox az$ git pull
You asked me to pull without telling me which branch you
want to merge with, and 'branch.0.58.merge' in
your configuration file does not tell me either. Please
name which branch you want to merge on the command line and
try again (e.g. 'git pull <repository> <refspec>').
See git-pull(1) for details on the refspec.
If you often merge with the same branch, you may want to
configure the following variables in your configuration
file:
branch.0.58.remote = <nickname>
branch.0.58.merge = <remote-ref>
remote.<nickname>.url = <url>
remote.<nickname>.fetch = <refspec>
See git-config(1) for details.
</code></pre>
<p>Seems I probably forgot some option (--track ?) when I checked that branch out. Anyway, I have set this now:</p>
<pre><code>git config branch.0.58.merge 0.58
git config branch.0.58.remote origin
</code></pre>
<p>And this seems to work. Then, just because of interest, I took a look at some other branch about these setting:</p>
<pre><code>ip238:openlierox az$ git config branch.0.57.merge
refs/heads/0.57
ip238:openlierox az$ git config branch.0.57.remote
origin
</code></pre>
<p>I was wondering now, is there a difference between "0.58" or should I specify "refs/heads/0.58"?</p>
<p>What is the difference exactly?</p> | 1,526,526 | 4 | 1 | null | 2009-10-06 15:47:49.34 UTC | 29 | 2021-11-01 14:16:13.257 UTC | 2020-03-19 12:02:06.31 UTC | null | 78,973 | null | 133,374 | null | 1 | 128 | git | 89,773 | <p>A <code>ref</code> is anything pointing to a commit, for example, branches (heads), tags, and remote branches. You should see heads, remotes, and tags in your <code>.git/refs</code> directory, assuming you have all three types of refs in your repository.</p>
<p><code>refs/heads/0.58</code> specifies a <em>branch</em> named 0.58. If you don't specify what namespace the ref is in, git will look in the default ones. This makes using only 0.58 conceivably ambiguous - you could have both a branch and a tag named 0.58.</p> |
52,627,739 | How to Merge Numerical and Embedding Sequential Models to treat categories in RNN | <p>I would like to build a one layer LSTM model with embeddings for my categorical features. I currently have numerical features and a few categorical features, such as Location, which can't be one-hot encoded e.g. using <code>pd.get_dummies()</code> due to computational complexity, which is what I originally intended to do. </p>
<p>Let's visualise an example:</p>
<h3>Sample Data</h3>
<pre><code>data = {
'user_id': [1,1,1,1,2,2,3],
'time_on_page': [10,20,30,20,15,10,40],
'location': ['London','New York', 'London', 'New York', 'Hong Kong', 'Tokyo', 'Madrid'],
'page_id': [5,4,2,1,6,8,2]
}
d = pd.DataFrame(data=data)
print(d)
user_id time_on_page location page_id
0 1 10 London 5
1 1 20 New York 4
2 1 30 London 2
3 1 20 New York 1
4 2 15 Hong Kong 6
5 2 10 Tokyo 8
6 3 40 Madrid 2
</code></pre>
<p>Let's look at the person visiting a website. I'm tracking numerical data such as time on page and others. Categorical data includes: Location (over 1000 uniques), Page_id (> 1000 uniques), Author_id (100+ uniques). The simplest solution would be to one-hot encoding everything and put this into LSTM with variable sequence lengths, each timestep corresponding to a different page view.</p>
<p>The above DataFrame will generate 7 training samples, with variable sequence lengths. For example, for <code>user_id=2</code> I will have 2 training samples:</p>
<pre><code>[ ROW_INDEX_4 ] and [ ROW_INDEX_4, ROW_INDEX_5 ]
</code></pre>
<p>Let <code>X</code> be the training data, and let's look at the first training sample <code>X[0]</code>.</p>
<p><a href="https://i.stack.imgur.com/uAATZ.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/uAATZ.jpg" alt="enter image description here"></a></p>
<p>From the picture above, my categorical features are <code>X[0][:, n:]</code>.</p>
<p>Before creating sequences, I factorized the categorical variables into <code>[0,1... number_of_cats-1]</code>, using <code>pd.factorize()</code> so the data in <code>X[0][:, n:]</code> is numbers corresponding to their index. </p>
<p>Do I need to create an <code>Embedding</code> for each of the Categorical Features separately? E.g. an embedding for each of <code>x_*n, x_*n+1, ..., x_*m</code>?</p>
<p>If so, how do I put this into Keras code?</p>
<pre><code>model = Sequential()
model.add(Embedding(?, ?, input_length=variable)) # How do I feed the data into this embedding? Only the categorical inputs.
model.add(LSTM())
model.add(Dense())
model.add.Activation('sigmoid')
model.compile()
model.fit_generator() # fits the `X[i]` one by one of variable length sequences.
</code></pre>
<p><strong>My solution idea:</strong></p>
<p>Something that looks like:</p>
<p><a href="https://i.stack.imgur.com/FVNWi.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/FVNWi.jpg" alt="enter image description here"></a></p>
<p>I can train a Word2Vec model on every single categorical feature (m-n) to vectorise any given value. E.g. London will be vectorised in 3 dimensions. Let's suppose I use 3 dimensional embeddings. Then I will put everything back into the X matrix, which will now have n + 3(n-m), and use the LSTM model to train it? </p>
<p>I just think there should be an easier/smarter way.</p> | 52,629,902 | 2 | 3 | null | 2018-10-03 13:07:04.693 UTC | 11 | 2020-04-24 08:40:46.86 UTC | 2018-10-03 17:22:40.557 UTC | null | 2,099,607 | null | 4,729,764 | null | 1 | 16 | python|tensorflow|machine-learning|keras|lstm | 5,430 | <p>One solution, as you mentioned, is to one-hot encode the categorical data (or even use them as they are, in index-based format) and feed them along the numerical data to an LSTM layer. Of course, you can also have two LSTM layers here, one for processing the numerical data and another for processing categorical data (in one-hot encoded format or index-based format) and then merge their outputs.</p>
<p>Another solution is to have one separate embedding layer for each of those categorical data. Each embedding layer may have its own embedding dimension (and as suggested above, you may have more than one LSTM layer for processing numerical and categorical features separately):</p>
<pre><code>num_cats = 3 # number of categorical features
n_steps = 100 # number of timesteps in each sample
n_numerical_feats = 10 # number of numerical features in each sample
cat_size = [1000, 500, 100] # number of categories in each categorical feature
cat_embd_dim = [50, 10, 100] # embedding dimension for each categorical feature
numerical_input = Input(shape=(n_steps, n_numerical_feats), name='numeric_input')
cat_inputs = []
for i in range(num_cats):
cat_inputs.append(Input(shape=(n_steps,1), name='cat' + str(i+1) + '_input'))
cat_embedded = []
for i in range(num_cats):
embed = TimeDistributed(Embedding(cat_size[i], cat_embd_dim[i]))(cat_inputs[i])
cat_embedded.append(embed)
cat_merged = concatenate(cat_embedded)
cat_merged = Reshape((n_steps, -1))(cat_merged)
merged = concatenate([numerical_input, cat_merged])
lstm_out = LSTM(64)(merged)
model = Model([numerical_input] + cat_inputs, lstm_out)
model.summary()
</code></pre>
<p>Here is the model summary:</p>
<pre><code>Layer (type) Output Shape Param # Connected to
==================================================================================================
cat1_input (InputLayer) (None, 100, 1) 0
__________________________________________________________________________________________________
cat2_input (InputLayer) (None, 100, 1) 0
__________________________________________________________________________________________________
cat3_input (InputLayer) (None, 100, 1) 0
__________________________________________________________________________________________________
time_distributed_1 (TimeDistrib (None, 100, 1, 50) 50000 cat1_input[0][0]
__________________________________________________________________________________________________
time_distributed_2 (TimeDistrib (None, 100, 1, 10) 5000 cat2_input[0][0]
__________________________________________________________________________________________________
time_distributed_3 (TimeDistrib (None, 100, 1, 100) 10000 cat3_input[0][0]
__________________________________________________________________________________________________
concatenate_1 (Concatenate) (None, 100, 1, 160) 0 time_distributed_1[0][0]
time_distributed_2[0][0]
time_distributed_3[0][0]
__________________________________________________________________________________________________
numeric_input (InputLayer) (None, 100, 10) 0
__________________________________________________________________________________________________
reshape_1 (Reshape) (None, 100, 160) 0 concatenate_1[0][0]
__________________________________________________________________________________________________
concatenate_2 (Concatenate) (None, 100, 170) 0 numeric_input[0][0]
reshape_1[0][0]
__________________________________________________________________________________________________
lstm_1 (LSTM) (None, 64) 60160 concatenate_2[0][0]
==================================================================================================
Total params: 125,160
Trainable params: 125,160
Non-trainable params: 0
__________________________________________________________________________________________________
</code></pre>
<p>Yet there is another solution which you can try: just have one embedding layer for all the categorical features. It involves some preprocessing though: you need to re-index all the categories to make them distinct from each other. For example, the categories in first categorical feature would be numbered from 1 to <code>size_first_cat</code> and then the categories in the second categorical feature would be numbered from <code>size_first_cat + 1</code> to <code>size_first_cat + size_second_cat</code> and so on. However, in this solution all the categorical features would have the same embedding dimension since we are using only one embedding layer. </p>
<hr>
<p><strong>Update:</strong> Now that I think about it, you can also reshape the categorical features in data preprocessing stage or even in the model to get rid of <code>TimeDistributed</code> layers and the <code>Reshape</code> layer (and this may increase the training speed as well):</p>
<pre><code>numerical_input = Input(shape=(n_steps, n_numerical_feats), name='numeric_input')
cat_inputs = []
for i in range(num_cats):
cat_inputs.append(Input(shape=(n_steps,), name='cat' + str(i+1) + '_input'))
cat_embedded = []
for i in range(num_cats):
embed = Embedding(cat_size[i], cat_embd_dim[i])(cat_inputs[i])
cat_embedded.append(embed)
cat_merged = concatenate(cat_embedded)
merged = concatenate([numerical_input, cat_merged])
lstm_out = LSTM(64)(merged)
model = Model([numerical_input] + cat_inputs, lstm_out)
</code></pre>
<p>As for fitting the model, you need to feed each input layer separately with its own corresponding numpy array, for example:</p>
<pre><code>X_tr_numerical = X_train[:,:,:n_numerical_feats]
# extract categorical features: you can use a for loop to this as well.
# note that we reshape categorical features to make them consistent with the updated solution
X_tr_cat1 = X_train[:,:,cat1_idx].reshape(-1, n_steps)
X_tr_cat2 = X_train[:,:,cat2_idx].reshape(-1, n_steps)
X_tr_cat3 = X_train[:,:,cat3_idx].reshape(-1, n_steps)
# don't forget to compile the model ...
# fit the model
model.fit([X_tr_numerical, X_tr_cat1, X_tr_cat2, X_tr_cat3], y_train, ...)
# or you can use input layer names instead
model.fit({'numeric_input': X_tr_numerical,
'cat1_input': X_tr_cat1,
'cat2_input': X_tr_cat2,
'cat3_input': X_tr_cat3}, y_train, ...)
</code></pre>
<p>If you would like to use <code>fit_generator()</code> there is no difference:</p>
<pre><code># if you are using a generator
def my_generator(...):
# prep the data ...
yield [batch_tr_numerical, batch_tr_cat1, batch_tr_cat2, batch_tr_cat3], batch_tr_y
# or use the names
yield {'numeric_input': batch_tr_numerical,
'cat1_input': batch_tr_cat1,
'cat2_input': batch_tr_cat2,
'cat3_input': batch_tr_cat3}, batch_tr_y
model.fit_generator(my_generator(...), ...)
# or if you are subclassing Sequence class
class MySequnece(Sequence):
def __init__(self, x_set, y_set, batch_size):
# initialize the data
def __getitem__(self, idx):
# fetch data for the given batch index (i.e. idx)
# same as the generator above but use `return` instead of `yield`
model.fit_generator(MySequence(...), ...)
</code></pre> |
10,738,866 | Will md5(file_contents_as_string) equal md5_file(/path/to/file)? | <p>If I do:</p>
<p><code><?php echo md5(file_get_contents("/path/to/file")) ?></code></p>
<p>...will this always produce the same hash as:</p>
<p><code><?php echo md5_file("/path/to/file") ?></code></p> | 10,739,027 | 4 | 2 | null | 2012-05-24 13:53:28 UTC | 2 | 2017-07-12 13:57:43.263 UTC | 2013-11-28 12:16:07.253 UTC | null | 1,347,953 | null | 375,968 | null | 1 | 33 | php|md5|md5-file | 14,234 | <p>Yes they return the same:</p>
<pre><code>var_dump(md5(file_get_contents(__FILE__)));
var_dump(md5_file(__FILE__));
</code></pre>
<p>which returns this in my case:</p>
<pre><code>string(32) "4d2aec3ae83694513cb9bde0617deeea"
string(32) "4d2aec3ae83694513cb9bde0617deeea"
</code></pre>
<p>Edit:
Take a look at the source code of both functions: <a href="https://github.com/php/php-src/blob/master/ext/standard/md5.c" rel="noreferrer">https://github.com/php/php-src/blob/master/ext/standard/md5.c</a> (Line 47 & 76). They both use the same functions to generate the hash except that the <code>md5_file()</code> function opens the file first.</p>
<p>2nd Edit:
Basically the <code>md5_file()</code> function generates the hash based on the file contents, not on the file meta data like the filename. This is the same way <code>md5sum</code> on Linux systems work.
See this example:</p>
<pre><code>pr@testumgebung:~# echo foobar > foo.txt
pr@testumgebung:~# md5sum foo.txt
14758f1afd44c09b7992073ccf00b43d foo.txt
pr@testumgebung:~# mv foo.txt bar.txt
pr@testumgebung:~# md5sum bar.txt
14758f1afd44c09b7992073ccf00b43d bar.txt
</code></pre> |
26,295,062 | Get organization Job title in AD using powershell | <p>I have been searching everywhere, and have tried many different combinations, but I can't seem to figure out how to get the "Job title" from the organization part of AD.</p>
<p>Here are a few things that I have tried</p>
<pre><code>get-aduser -Filter * -SearchBase "Bob.Barker" -Properties sAMAccountName,Title
Get-ADUser -identity "Bob.Barker" -Filter * -Properties title | group title -NoElement
</code></pre>
<p>Also, as a bonus question how would you set the job title.</p>
<p>Thank you all for your assistance.</p> | 26,298,865 | 3 | 2 | null | 2014-10-10 08:30:02.203 UTC | 1 | 2020-12-05 06:30:07.227 UTC | null | null | null | null | 1,342,015 | null | 1 | 4 | powershell|active-directory | 52,029 | <p>In your example, if the user's username is Bob.Barker then use this:</p>
<pre><code>get-aduser -Filter {samAccountName -eq "Bob.Barker"} -Properties sAMAccountName,Title
</code></pre>
<p>or if surname is <em>Barker</em></p>
<pre><code>get-aduser -Filter {sn -eq "Barker"} -Properties sAMAccountName,Title
</code></pre> |
7,400,220 | How to give space in javascript? | <p>I have a response where I have an Image in that response and after every response I need to give a space.How can I do that?</p>
<p>Any help will be appreciated!</p>
<p>Here is my script:</p>
<pre><code><script type="text/javascript>
$("#thumbnail").append(response)
</script>
</code></pre> | 7,400,242 | 5 | 0 | null | 2011-09-13 10:18:09.32 UTC | 2 | 2019-10-11 16:40:04.473 UTC | null | null | null | user676589 | null | null | 1 | 4 | javascript | 52,761 | <pre><code><script type="text/javascript>
$("#thumbnail").append(response +'&nbsp;')
</script>
</code></pre> |
7,396,978 | Left and Right Folding over an Infinite list | <p>I have issues with the following passage from <a href="http://learnyouahaskell.com/higher-order-functions#folds">Learn You A Haskell</a> (Great book imo, not dissing it):</p>
<blockquote>
<p>One big difference is that right
folds work on infinite lists, whereas left ones don't! To put it
plainly, if you take an infinite list at some point and you fold it up
from the right, you'll eventually reach the beginning of the list.
However, if you take an infinite list at a point and you try to fold
it up from the left, you'll never reach an end!</p>
</blockquote>
<p>I just don't get this. If you take an infinite list and try to fold it up from the right then you'll have to start at the point at infinity, which just isn't happening (If anyone knows of a language where you can do this do tell :p). At least, you'd have to start there according to Haskell's implementation because in Haskell foldr and foldl don't take an argument that determines where in the list they should start folding.</p>
<p>I would agree with the quote iff foldr and foldl took arguments that determined where in the list they should start folding, because it makes sense that if you take an infinite list and start folding right from a defined index it <em>will</em> eventually terminate, whereas it doesn't matter where you start with a left fold; you'll be folding towards infinity. However foldr and foldl <em>do not</em> take this argument, and hence the quote makes no sense. In Haskell, both a left fold and a right fold over an infinite list <strong>will not terminate</strong>.</p>
<p>Is my understanding correct or am I missing something?</p> | 7,397,148 | 5 | 2 | null | 2011-09-13 04:54:01.607 UTC | 21 | 2017-11-20 21:12:33.737 UTC | 2011-12-25 22:00:41.46 UTC | null | 283,240 | null | 877,603 | null | 1 | 73 | list|haskell|functional-programming|infinite|fold | 8,059 | <p>The key here is laziness. If the function you're using for folding the list is strict, then neither a left fold nor a right fold will terminate, given an infinite list.</p>
<pre><code>Prelude> foldr (+) 0 [1..]
^CInterrupted.
</code></pre>
<p>However, if you try folding a less strict function, you can get a terminating result.</p>
<pre><code>Prelude> foldr (\x y -> x) 0 [1..]
1
</code></pre>
<p>You can even get a result that is an infinite data structure, so while it does in a sense not terminate, it's still able to produce a result that can be consumed lazily.</p>
<pre><code>Prelude> take 10 $ foldr (:) [] [1..]
[1,2,3,4,5,6,7,8,9,10]
</code></pre>
<p>However, this will not work with <code>foldl</code>, as you will never be able to evaluate the outermost function call, lazy or not.</p>
<pre><code>Prelude> foldl (flip (:)) [] [1..]
^CInterrupted.
Prelude> foldl (\x y -> y) 0 [1..]
^CInterrupted.
</code></pre>
<p>Note that the key difference between a left and a right fold is not the order in which the list is traversed, which is always from left to right, but rather how the resulting function applications are nested.</p>
<ul>
<li><p>With <code>foldr</code>, they are nested on "the inside"</p>
<pre><code>foldr f y (x:xs) = f x (foldr f y xs)
</code></pre>
<p>Here, the first iteration will result in the outermost application of <code>f</code>. Thus, <code>f</code> has the opportunity to be lazy so that the second argument is either not always evaluated, or it can produce some part of a data structure without forcing its second argument.</p></li>
<li><p>With <code>foldl</code>, they are nested on "the outside"</p>
<pre><code>foldl f y (x:xs) = foldl f (f y x) xs
</code></pre>
<p>Here, we can't evaluate anything until we have reached the outermost application of <code>f</code>, which we will never reach in the case of an infinite list, regardless of whether <code>f</code> is strict or not.</p></li>
</ul> |
7,601,823 | How do chained assignments work? | <p>A quote from something:</p>
<pre><code>>>> x = y = somefunction()
</code></pre>
<p>is the same as</p>
<pre><code>>>> y = somefunction()
>>> x = y
</code></pre>
<p>Question: Is </p>
<pre><code>x = y = somefunction()
</code></pre>
<p>the same as </p>
<pre><code>x = somefunction()
y = somefunction()
</code></pre>
<p>?</p>
<p>Based on my understanding, they should be same because <code>somefunction</code> can only return exactly one value.</p> | 7,601,890 | 6 | 1 | null | 2011-09-29 18:34:45.163 UTC | 25 | 2022-03-28 17:23:31.917 UTC | 2011-09-29 18:37:25.143 UTC | null | 500,584 | null | 391,104 | null | 1 | 54 | python|python-3.x | 19,119 | <p>They will not necessarily work the same if <code>somefunction</code> returns a mutable value. Consider:</p>
<pre><code>>>> def somefunction():
... return []
...
>>> x = y = somefunction()
>>> x.append(4)
>>> x
[4]
>>> y
[4]
>>> x = somefunction(); y = somefunction()
>>> x.append(3)
>>> x
[3]
>>> y
[]
</code></pre> |
7,225,630 | How to echo "2" (no quotes) to a file, from a batch script? | <p>How do I echo the number <em>2</em> into a file, from a batch script?</p>
<p>This doesn't work:</p>
<pre><code>Echo 2>> file.txt
</code></pre>
<p>because <code>2>></code> is a special command. :(</p> | 7,225,659 | 11 | 0 | null | 2011-08-29 02:53:39.687 UTC | 8 | 2020-03-24 23:51:52.097 UTC | 2020-03-24 23:35:41.68 UTC | null | 5,047,996 | null | 541,686 | null | 1 | 73 | windows|batch-file|cmd|echo|io-redirection | 34,032 | <p>Use <code>(ECHO 2)>>file.txt</code>. This will output <code>2</code> without any spaces.</p> |
14,275,821 | How to run celery as a daemon in production? | <p>i created a celeryd file in /etc/defaults/ from the code here:</p>
<p><a href="https://github.com/celery/celery/blob/3.0/extra/generic-init.d/celeryd" rel="noreferrer">https://github.com/celery/celery/blob/3.0/extra/generic-init.d/celeryd</a></p>
<p>Now when I want to run celeryd as a daemon and do this: sudo /etc/init.d/celerdy it says command not found. Where am I going wrong?</p> | 14,276,580 | 5 | 0 | null | 2013-01-11 10:09:37.053 UTC | 14 | 2017-02-09 19:39:18.833 UTC | 2014-12-08 21:33:54.523 UTC | null | 908,703 | null | 105,167 | null | 1 | 19 | python|django|celery | 31,237 | <p>I am not sure what you are doing here but these are the steps to run celery as a daemon.</p>
<ol>
<li>The file that you have referred in the link
<a href="https://github.com/celery/celery/blob/3.1/extra/generic-init.d/celeryd" rel="noreferrer">https://github.com/celery/celery/blob/3.0/extra/generic-init.d/celeryd</a>
needs to be copied in your <code>/etc/init.d</code> folder with the name
<code>celeryd</code></li>
<li>Then you need to create a configuration file in the folder
<code>/etc/default</code> with the name <code>celeryd</code> that is used by the above
script. This configuration file basically defines certain variables
and paths that are used by the above script. Here's <a href="http://docs.celeryproject.org/en/latest/userguide/daemonizing.html#example-configuration" rel="noreferrer">an example configuration.</a></li>
<li>This link <a href="http://docs.celeryproject.org/en/latest/userguide/daemonizing.html#generic-init-scripts" rel="noreferrer">Generic init scripts</a> explains the process and can be used for reference</li>
</ol> |
13,834,034 | How does Audiobus for iOS work? | <p>What SDK's does <a href="http://audiob.us" rel="noreferrer">Audiobus</a> use to provide inter-app audio routing? I am not aware of any Apple SDK that could facilitate inter-app communication for iOS and was under the impression that apps were sandboxed from each other so I'm really intrigued to hear how they pulled this off.</p> | 15,645,852 | 3 | 0 | null | 2012-12-12 06:26:46.377 UTC | 12 | 2013-03-26 19:33:35.483 UTC | 2013-03-04 15:14:34.62 UTC | null | 399,772 | null | 399,772 | null | 1 | 21 | ios|objective-c|cocoa-touch | 1,984 | <p>iOS allows inter-app communication via MIDI Sysex messages. AudioBus works by sending audio as MIDI Sysex message. You can read details from the developer himself:</p>
<p><a href="http://atastypixel.com/blog/thirteen-months-of-audiobus/" rel="noreferrer">http://atastypixel.com/blog/thirteen-months-of-audiobus/</a></p> |
13,899,530 | GAE SDK 1.7.4 and InvalidCertificateException | <p>Recently, I upgraded my GAE SDK to ver. 1.7.4 and it started to throw 'InvalidCertificateException' when I try to run development server. I searched about this error and some people said it goes away with time, but mine didn't. What should I look into to fix this problem? I am using python framework Django for my app if that has to matter somehow.</p>
<pre><code>$ dev_appserver.py ./
INFO 2012-12-16 07:44:31,412 appcfg.py:586] Checking for updates to the SDK.
Traceback (most recent call last):
File "/usr/local/bin/dev_appserver.py", line 171, in <module>
run_file(__file__, globals())
File "/usr/local/bin/dev_appserver.py", line 167, in run_file
execfile(script_path, globals_)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_main.py", line 747, in <module>
sys.exit(main(sys.argv))
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/dev_appserver_main.py", line 680, in main
update_check.CheckForUpdates()
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/appcfg.py", line 597, in CheckForUpdates
runtime=self.config.runtime)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/tools/appengine_rpc.py", line 391, in Send
f = self.opener.open(req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 394, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 412, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 372, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1207, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/fancy_urllib/fancy_urllib/__init__.py", line 379, in do_open
url_error.reason.args[1])
fancy_urllib.InvalidCertificateException: Host appengine.google.com returned an invalid certificate (_ssl.c:503: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed):
To learn more, see http://code.google.com/appengine/kb/general.html#rpcssl
</code></pre> | 14,565,784 | 4 | 7 | null | 2012-12-16 07:51:24.777 UTC | 12 | 2020-10-07 09:19:28.17 UTC | null | null | null | null | 1,120,326 | null | 1 | 22 | python|django|google-app-engine | 7,112 | <p>Quick workaround that I found: delete the file <code>google_appengine/lib/cacerts/cacerts.txt</code> from your installed SDK.</p>
<p>Starting from the GoogleAppEngineLauncher:</p>
<blockquote>
<p>GoogleAppEngineLauncher/Contents/Resources/GoogleAppEngineDefault.bundle/Contents/Resources/google_appengine/lib/cacerts/cacerts.txt</p>
</blockquote>
<p>EDIT #</p>
<blockquote>
<p>as of google app engine SDK 1.8.1 this file as been renamed to
urlfetch_cacerts.txt. Still in the same directory and removing it
still fixes the problem.</p>
</blockquote>
<p>– @Harrison</p> |
14,299,945 | How to sort by a field of the pivot table of a many-to-many relationship in Eloquent ORM | <p>I have been using Eloquent ORM for some time now and I know it quite well, but I can't do the following, while <strong>it's very easy to do in Fluent</strong>.</p>
<p>I have users with a many-to-many songs, intermediate table being song_user (like it should be). I'd like to get the top songs of a user, judging by the play count. Of course, play count is stored in the intermediate table.</p>
<p>I can do it in Fluent:</p>
<pre><code>$songs = DB::table('songs')
->join('song_user', 'songs.id', '=', 'song_user.song_id')
->where('song_user.user_id', '=', $user->id)
->orderBy("song_user.play_count", "desc")
->get();
</code></pre>
<p>Easy. But I want to do it in Eloquent, which of course <strong>doesn't work:</strong></p>
<pre><code>$songs = Song::
with(array("song_user" => function($query) use ($user) {
$query->where("user_id", "=", $user->id)->orderBy("play_count", "desc");
}))
</code></pre> | 17,065,671 | 5 | 5 | null | 2013-01-13 02:04:08.97 UTC | 6 | 2017-09-26 14:34:36.46 UTC | 2013-01-14 07:42:53.993 UTC | null | 1,244,588 | null | 291,557 | null | 1 | 33 | laravel|eloquent | 25,754 | <p>Not sure if you plan to move to Laravel 4, but here's an Eloquent example for sorting by a pivot tables fields:</p>
<pre><code>public function songs() {
return $this
->belongsToMany('Song')
->withPivot('play_count')
->orderBy('pivot_play_count', 'desc');
}
</code></pre>
<p><code>withPivot</code> is like the eloquent <code>with</code> and will add the <code>play_count</code> field from the pivot table to the other keys it already includes. All the pivot table fields are prefixed with <code>pivot</code> in the results, so you can reference them directly in the <code>orderBy</code>.</p>
<p>I've no idea what it would look like in Laravel 3, but perhaps this will help point you in the right direction.</p>
<p>Cheers!</p> |
13,861,318 | Why is it considered good practice to describe git commits in the present tense? | <p>I've read all kinds of Git tutorials, including the official one, and they all seem to tell me it's good convention and practice to write Git commit notes in the present tense.</p>
<p>Why is that? What is the reasoning behind it?</p> | 13,861,351 | 2 | 1 | null | 2012-12-13 13:54:12.907 UTC | 12 | 2020-07-29 14:19:01.613 UTC | null | null | null | null | 871,050 | null | 1 | 37 | git|commit|commit-message | 10,360 | <p>Git is a distributed VCS (version control system). Multiple people can work on the same projects. It'll get changes from many sources.<br />Rather than writing messages that say what a committer has done. It's better to <strong>consider these messages as the instructions for what is going to be done after the commit is applied</strong> on the repo. </p>
<p>So write a message like this</p>
<blockquote>
<p>Fix bug#1234</p>
</blockquote>
<p>Instead of </p>
<blockquote>
<p>Fixed bug #1234</p>
</blockquote>
<p>Treat the git log not a history of your actions, but a sequence descriptions of what all the commits do. </p>
<p>There is a big thread on <a href="http://news.ycombinator.com/item?id=2079612" rel="noreferrer">hacker news</a> about it. There you'll get many more reasons behind this convention. </p> |
14,150,508 | How to get null instead of the KeyNotFoundException accessing Dictionary value by key? | <p>In some certain scenario it appeared to be useful for me to have a short-spoken, readable way to get <code>null</code> instead of the <code>KeyNotFoundException</code> while accessing dictionary value by key, when there is no such key in the dictionary.</p>
<p>The first thing that came into my mind was an extension method:</p>
<pre><code>public static U GetValueByKeyOrNull<T, U>(this Dictionary<T, U> dict, T key)
where U : class //it's acceptable for me to have this constraint
{
if (dict.ContainsKey(key))
return dict[key];
else
//it could be default(U) to use without U class constraint
//however, I didn't need this.
return null;
}
</code></pre>
<p>But it's not very short-spoken actually, when you write something like this:</p>
<pre><code>string.Format("{0}:{1};{2}:{3}",
dict.GetValueByKeyOrNull("key1"),
dict.GetValueByKeyOrNull("key2"),
dict.GetValueByKeyOrNull("key3"),
dict.GetValueByKeyOrNull("key4"));
</code></pre>
<p>I'd say, it would be much better to havesomething close to base syntax: <code>dict["key4"]</code>.</p>
<p>Then I came up with an idea to have a class with a <code>private</code> dictionary field, which exposed the functionality I need:</p>
<pre><code>public class MyDictionary<T, U> //here I may add any of interfaces, implemented
//by dictionary itself to get an opportunity to,
//say, use foreach, etc. and implement them
// using the dictionary field.
where U : class
{
private Dictionary<T, U> dict;
public MyDictionary()
{
dict = new Dictionary<T, U>();
}
public U this[T key]
{
get
{
if (dict.ContainsKey(key))
return dict[key];
else
return null;
}
set
{
dict[key] = value;
}
}
}
</code></pre>
<p>But it seems a little overhead to get the slight change in the basic behaviour.</p>
<p>One more workaround could be to define a <code>Func</code> in the current context like this:</p>
<pre><code>Func<string, string> GetDictValueByKeyOrNull = (key) =>
{
if (dict.ContainsKey(key))
return dict[key];
else
return null;
};
</code></pre>
<p>so it could be utilized like <code>GetDictValueByKeyOrNull("key1")</code>.</p>
<p>Could you, please, give me any more suggestions or help to choose a better one?</p> | 14,151,273 | 7 | 9 | null | 2013-01-04 03:02:15.95 UTC | 9 | 2021-02-18 01:29:24.04 UTC | 2013-01-04 04:38:10.337 UTC | null | 1,467,858 | null | 1,467,858 | null | 1 | 103 | c#|dictionary | 87,085 | <p>In the end I came up with a variant using a deriving from dictionary class with explicit interface implementation:</p>
<pre><code>public interface INullValueDictionary<T, U>
where U : class
{
U this[T key] { get; }
}
public class NullValueDictionary<T, U> : Dictionary<T, U>, INullValueDictionary<T, U>
where U : class
{
U INullValueDictionary<T, U>.this[T key]
{
get
{
U val;
this.TryGetValue(key, out val);
return val;
}
}
}
</code></pre>
<p>So it exposes the functionality I need the following way:</p>
<pre><code>//create some dictionary
NullValueDictionary<int, string> dict = new NullValueDictionary<int, string>
{
{1,"one"}
};
//have a reference to the interface
INullValueDictionary<int, string> idict = dict;
try
{
//this throws an exception, as the base class implementation is utilized
Console.WriteLine(dict[2] ?? "null");
}
catch { }
//this prints null, as the explicit interface implementation
//in the derived class is used
Console.WriteLine(idict[2] ?? "null");
</code></pre> |
28,991,319 | Ubuntu Python "No module named paramiko" | <p>So I'm trying to use Paramiko on Ubuntu with Python 2.7, but import paramiko causes this error:</p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named paramiko
</code></pre>
<p>The other questions on this site don't help me since I'm new to Ubuntu.</p>
<p>Here are some important commands that I ran to check stuff:</p>
<pre><code>sudo pip install paramiko
pip install paramiko
sudo apt-get install python-paramiko
</code></pre>
<p>Paramiko did "install". These are the only commands I used to "install" paramiko. I'm new to Ubuntu, so if I need to run more commands, lay them on me.</p>
<pre><code>which python
/usr/local/bin/python
python -c "from pprint import pprint; import sys; pprint(sys.path);"
['',
'/usr/local/lib/python27.zip',
'/usr/local/lib/python2.7',
'/usr/local/lib/python2.7/plat-linux2',
'/usr/local/lib/python2.7/lib-tk',
'/usr/local/lib/python2.7/lib-old',
'/usr/local/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/site-packages']
</code></pre>
<p>In the python interpreter, I ran <code>help("modules")</code> and Paramiko is not in the list.</p>
<p>two paramiko folders are located in <code>usr/local/lib/python2.7/dist-packages</code>.</p> | 28,991,846 | 7 | 4 | null | 2015-03-11 15:51:45.95 UTC | 1 | 2019-08-08 08:48:24.863 UTC | 2015-03-11 15:57:32.357 UTC | null | 2,259,175 | null | 2,259,175 | null | 1 | 5 | python|ubuntu|import|paramiko | 58,154 | <p>Short version: You're mixing Ubuntu's packaged version of Python (<code>/usr/bin/python</code>) and a locally built and installed version (<code>/usr/local/bin/python</code>).</p>
<p>Long version:</p>
<ul>
<li>You used <code>apt-get install python-paramiko</code> to install Ubuntu's official Paramiko package to <code>/usr/lib/python2.7/dist-packages</code>.</li>
<li>You used (I assume) Ubuntu's version of <code>pip</code>, which installs to <code>/usr/local/lib/python2.7/dist-packages</code>. (See <a href="https://stackoverflow.com/q/9387928/25507">here</a>.)</li>
<li>You used a locally built version of Python, and because it's locally built, it uses <code>/usr/local/lib/python2.7</code> instead of <code>/usr/lib/python2.7</code>, and because it doesn't have Debian/Ubuntu customizations, it doesn't check use <code>dist-packages</code>.</li>
</ul>
<p>Solution: You should be able to add <code>/usr/local/lib/python2.7/dist-packages</code> to your <code>/usr/local/bin/python</code>'s <code>sys.path</code>, but since you're using Ubuntu, it's easiest to let Ubuntu do the work for you:</p>
<ul>
<li>Use /usr/bin/python instead of a local version.</li>
<li>Use Ubuntu's packages wherever possible (i.e., use <code>apt-get</code> instead of <code>pip</code>).</li>
<li>Use virtualenv for the rest (to keep a clean separation between Ubuntu-packaged and personally installed modules).</li>
</ul>
<p>I'd go so far as to uninstall the local version of Python and delete <code>/usr/local/lib/python2.7</code>, to ensure that no further mismatches occur. If you don't want to be that drastic, then you can edit your $PATH to put <code>/usr/bin</code> before <code>/usr/local/bin</code> to run the system version of Python by default.</p> |
30,039,512 | How to view an HTML file in the browser with Visual Studio Code | <p>How can I view my HTML code in a browser with the new Microsoft Visual Studio Code?</p>
<p>With Notepad++ you have the option to Run in a browser. How can I do the same thing with Visual Studio Code?</p> | 30,043,507 | 28 | 5 | null | 2015-05-04 20:36:53.317 UTC | 110 | 2022-09-21 20:22:32.59 UTC | 2020-04-29 15:23:49.49 UTC | null | 604,687 | user4863890 | null | null | 1 | 366 | html|visual-studio-code|preview | 723,845 | <p>For Windows - Open your Default Browser - Tested on VS Code v 1.1.0</p>
<p>Answer to both opening a specific file (name is hard-coded) OR opening ANY other file.</p>
<p><strong>Steps:</strong></p>
<ol>
<li><p>Use <kbd>ctrl</kbd> + <kbd>shift</kbd> + <kbd>p</kbd> (or <kbd>F1</kbd>) to open the Command Palette.</p></li>
<li><p>Type in <code>Tasks: Configure Task</code> or on older versions <code>Configure Task Runner</code>. Selecting it will open the <strong>tasks.json</strong> file. Delete the script displayed and replace it by the following:</p>
<pre><code>{
"version": "0.1.0",
"command": "explorer",
"windows": {
"command": "explorer.exe"
},
"args": ["test.html"]
}
</code></pre>
<p>Remember to change the "args" section of the tasks.json file to the name of your file. This will always open that specific file when you hit F5.</p>
<p>You may also set the this to open whichever file you have open at the time by using <code>["${file}"]</code> as the value for "args". Note that the <code>$</code> goes outside the <code>{...}</code>, so <code>["{$file}"]</code> is incorrect.</p></li>
<li><p>Save the file.</p></li>
<li><p>Switch back to your html file (in this example it's "text.html"), and press <kbd>ctrl</kbd> + <kbd>shift</kbd> + <kbd>b</kbd> to view your page in your Web Browser.</p></li>
</ol>
<p><img src="https://i.stack.imgur.com/ahjua.png" alt="enter image description here"></p> |
29,934,252 | How to edit a FabricJS IText and apply new styles (e.g. highlighting, etc...) | <p>I want to edit the highlighted characters in a text in canvas using fabric.js, like change its color, font, style etc.</p>
<p>just like this <a href="http://fabricjs.com/test/misc/itext.html" rel="noreferrer">http://fabricjs.com/test/misc/itext.html</a></p>
<p>to @user43250937
hey uhm. I tried it and it works! :D thanks.
I tried Underline, Bold, Italic, but I have a problem changing the color of the text, I tried :</p>
<pre><code>// "cinput" is the id of the color picker.
addHandler('cinput', function(obj) {
var color = $("#cinput").val();
var isColor = (getStyle(obj, 'fill') || '').indexOf(color) > -1;
setStyle(obj, 'fill', isColor ? '' : color);
});
</code></pre> | 29,935,020 | 1 | 9 | null | 2015-04-29 04:13:24.16 UTC | 13 | 2018-07-20 08:42:21.243 UTC | 2015-05-12 14:29:22.113 UTC | null | 4,788,412 | null | 4,788,412 | null | 1 | 7 | javascript|canvas|fabricjs | 18,257 | <p>Usually answers without a description of what you tried and what didn't work are completely ignored here, i'm answering this time because the fabricjs library is quite complex and the documentation is a bit lacking sometimes...</p>
<p>That page has samples for the <a href="http://fabricjs.com/docs/fabric.IText.html">IText object</a>, text that can be edited in place (the content of the basic fabricjs text object can be modified only from outside via javascript).</p>
<p>Building a static IText object with different styles applied it's simple:</p>
<p><em>HTML:</em></p>
<pre><code><canvas id="canv" width="250" height="300" style="border: 1px solid rgb(204, 204, 204); width: 400px; height: 400px; -webkit-user-select: none;"></canvas>
</code></pre>
<p><em>Javascript:</em></p>
<pre><code>var canvas=new fabric.Canvas('canv');
var iTextSample = new fabric.IText('hello\nworld', {
left: 50,
top: 50,
fontFamily: 'Helvetica',
fill: '#333',
lineHeight: 1.1,
styles: {
0: {
0: { textDecoration: 'underline', fontSize: 80 },
1: { textBackgroundColor: 'red' }
},
1: {
0: { textBackgroundColor: 'rgba(0,255,0,0.5)' },
4: { fontSize: 20 }
}
}
});
canvas.add(iTextSample);
</code></pre>
<p>Link to <a href="https://jsfiddle.net/tLy9eqj6/">JSFiddle</a></p>
<p>As you can see you just specify the style for every character of each for each line (first for the <code>hello</code> line, then for the <code>world</code> line).</p>
<p>If you want something dynamic with the ability to select some text and change the appearance/style <strong>there is some work to do</strong>, you'll need to:</p>
<ol>
<li>Add a button or a clickable element for each style (bold,italic,change color, change background,etc...) that you want to apply dynamically;</li>
<li>Add a click listener to each button with some code that changes the style of the selected text inside the IText.</li>
</ol>
<p>You'll need a basic function that add handlers that you will reuse for every style button:</p>
<pre><code>function addHandler(id, fn, eventName) {
document.getElementById(id)[eventName || 'onclick'] = function() {
var el = this;
if (obj = canvas.getActiveObject()) {
fn.call(el, obj);
canvas.renderAll();
}
};
}
</code></pre>
<p>And some helper functions to change the styles:</p>
<pre><code>function setStyle(object, styleName, value) {
if (object.setSelectionStyles && object.isEditing) {
var style = { };
style[styleName] = value;
object.setSelectionStyles(style);
}
else {
object[styleName] = value;
}
}
function getStyle(object, styleName) {
return (object.getSelectionStyles && object.isEditing)
? object.getSelectionStyles()[styleName]
: object[styleName];
}
addHandler('underline', function(obj) {
var isUnderline = (getStyle(obj, 'textDecoration') || '').indexOf('underline') > -1;
setStyle(obj, 'textDecoration', isUnderline ? '' : 'underline');
});
</code></pre>
<p><a href="https://jsfiddle.net/4nzygs8a/">Link to working JSFiddle</a> with a working underline button.</p>
<p>A bit of coding is involved as you can see, but it's not that complex, for the full list of available style options you can check the fabricjs documentation.</p> |
9,126,831 | How to count lines of code (LOC) using IntelliJ IDEA? | <p>title says everything plus:
- development language Lua
- code revision control system - Perforce (integrated with IntelliJ IDE)</p> | 9,126,874 | 2 | 1 | null | 2012-02-03 10:05:03.98 UTC | 4 | 2021-12-29 13:06:02.25 UTC | 2018-04-05 15:15:47.537 UTC | null | 1,187,217 | null | 1,187,217 | null | 1 | 26 | lua|intellij-idea | 43,025 | <p>You can either turn on the display of lines of code for a single file by right clicking in the left gutter and highlighting "display lines of code". Or you can do it for your entire project by downloading the <a href="http://plugins.intellij.net/plugin/?idea&id=4509">Statistic plug-in</a>. It's very nice indeed, because it shows LOC and other metrics for your entire project.</p> |
9,268,378 | How do I clone a large Git repository on an unreliable connection? | <p>I want to clone LibreOffice. From the official website, this is what's written:</p>
<blockquote>
<p>All our source code is hosted in git:</p>
<p>Clone: <code>$ git clone git://anongit.freedesktop.org/libreoffice/core</code> # (browse)</p>
<p>Clone (http): <code>$ git clone http://anongit.freedesktop.org/git/libreoffice/core.git</code> # slower</p>
<p>Tarballs: <code>http://download.documentfoundation.org/libreoffice/src/</code></p>
<p>please find the latest versions (usually near the bottom)</p>
</blockquote>
<p>now, when I write this command in git bash to clone, it starts fetching. But the repository is so big that after hours I lose connectivity for a few seconds, it rolls back the download, and I get nothing.</p>
<p>Is there any way I can download the repository smoothly even if interruptions occur?</p>
<p>P.S. I am a new user of Git and I use a 1 MB DSL internet connection. The repository must be over 1 GB.</p> | 9,268,487 | 6 | 1 | null | 2012-02-13 21:33:27.667 UTC | 5 | 2022-08-30 08:23:20.167 UTC | 2022-08-30 08:23:20.167 UTC | null | 894,319 | null | 1,207,785 | null | 1 | 34 | git|git-clone | 10,657 | <p>The repository is accessible via the <code>http</code> protocol (aka dumb protocol) here: <a href="http://anongit.freedesktop.org/git/libreoffice/core.git" rel="noreferrer">http://anongit.freedesktop.org/git/libreoffice/core.git</a>.</p>
<p>You can download everything here with <code>wget</code> or another download manager, and you'll have a clone of the repository. After that, you rename the directory from <code>core.git</code> to <code>.git</code>, and use the following command to tell git about the remote url:</p>
<pre><code>$ git remote add remote http://anongit.freedesktop.org/git/libreoffice/core.git
$ git reset --hard HEAD
</code></pre> |
44,398,075 | Can DPI scaling be enabled/disabled programmatically on a per-session basis? | <p>My application happens to be written in Python using pygame, which wraps SDL, but I'm imagining that this is <em>probably</em> a more-general question to do with the Windows API.</p>
<p>In some of my Python applications, I want pixel-for-pixel control under Windows 10 even at high resolutions. I want to be able to ensure, for example, that if my Surface Pro 3 has a native resolution of 2160x1440, then I can enter full-screen mode with those dimensions and present a full-screen image of exactly those dimensions.</p>
<p>The barrier to this is "DPI scaling". By default, under Windows' Settings -> Display, the value of "Change the size of text, apps, and other items" is "150% (Recommended)" and the result is that I only see 2/3 of my image. I have discovered how to fix this behaviour...</p>
<ol>
<li>systemwide, by moving that slider down to 100% (but that's <a href="https://i.imgur.com/HFO5Rz8.png" rel="noreferrer">undesirable</a> for most other applications)</li>
<li>just for <code>python.exe</code> and <code>pythonw.exe</code>, by going to those executables' "Properties" dialogs, Compatibility tab, and clicking "Disable display scaling on high DPI settings". I can do this for me alone, or for all users. I can also automate this process by setting the appropriate keys in the registry programmatically. Or via <code>.exe.manifest</code> files (which also seems to require a global setting change, to prefer external manifests, with possible side-effects on other applications).</li>
</ol>
<p>My question is: can I do this from <em>inside</em> my program on a per-launch basis, before I open my graphics window? I, or anyone using my software, won't necessarily want this setting enabled for <em>all</em> Python applications ever—we might want it just when running particular Python programs. I'm imagining there might be a <code>winapi</code> call (or failing that something inside SDL, wrapped by pygame) that could achieve this, but so far my research is drawing a blank.</p> | 44,422,362 | 1 | 5 | null | 2017-06-06 19:14:01.627 UTC | 10 | 2019-01-11 21:22:16.017 UTC | 2017-09-13 20:46:45.073 UTC | null | 3,019,689 | null | 3,019,689 | null | 1 | 11 | winapi|graphics|windows-10 | 8,663 | <p>Here's the answer I was looking for, based on comments by IInspectable and andlabs (many thanks):</p>
<pre class="lang-python prettyprint-override"><code> import ctypes
# Query DPI Awareness (Windows 10 and 8)
awareness = ctypes.c_int()
errorCode = ctypes.windll.shcore.GetProcessDpiAwareness(0, ctypes.byref(awareness))
print(awareness.value)
# Set DPI Awareness (Windows 10 and 8)
errorCode = ctypes.windll.shcore.SetProcessDpiAwareness(2)
# the argument is the awareness level, which can be 0, 1 or 2:
# for 1-to-1 pixel control I seem to need it to be non-zero (I'm using level 2)
# Set DPI Awareness (Windows 7 and Vista)
success = ctypes.windll.user32.SetProcessDPIAware()
# behaviour on later OSes is undefined, although when I run it on my Windows 10 machine, it seems to work with effects identical to SetProcessDpiAwareness(1)
</code></pre>
<p>The awareness levels <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/dn280512.aspx" rel="noreferrer">are defined</a> as follows:</p>
<pre class="lang-c prettyprint-override"><code>typedef enum _PROCESS_DPI_AWARENESS {
PROCESS_DPI_UNAWARE = 0,
/* DPI unaware. This app does not scale for DPI changes and is
always assumed to have a scale factor of 100% (96 DPI). It
will be automatically scaled by the system on any other DPI
setting. */
PROCESS_SYSTEM_DPI_AWARE = 1,
/* System DPI aware. This app does not scale for DPI changes.
It will query for the DPI once and use that value for the
lifetime of the app. If the DPI changes, the app will not
adjust to the new DPI value. It will be automatically scaled
up or down by the system when the DPI changes from the system
value. */
PROCESS_PER_MONITOR_DPI_AWARE = 2
/* Per monitor DPI aware. This app checks for the DPI when it is
created and adjusts the scale factor whenever the DPI changes.
These applications are not automatically scaled by the system. */
} PROCESS_DPI_AWARENESS;
</code></pre>
<p>Level 2 sounds most appropriate for my goal although 1 will also work provided there's no change in system resolution / DPI scaling.</p>
<p><code>SetProcessDpiAwareness</code> will fail with <code>errorCode = -2147024891 = 0x80070005 = E_ACCESSDENIED</code> if it has previously been called for the current process (and that includes being called by the system when the process is launched, due to a registry key or <code>.manifest</code> file)</p> |
32,615,713 | toBe(true) vs toBeTruthy() vs toBeTrue() | <p>What is the difference between <code>expect(something).toBe(true)</code>, <code>expect(something).toBeTruthy()</code> and <code>expect(something).toBeTrue()</code>?</p>
<p>Note that <code>toBeTrue()</code> is a <em>custom matcher</em> introduced in <a href="https://github.com/JamieMason/Jasmine-Matchers"><code>jasmine-matchers</code></a> among other useful and handy matchers like <code>toHaveMethod()</code> or <code>toBeArrayOfStrings()</code>.</p>
<hr>
<p>The question is meant to be generic, but, as a real-world example, I'm testing that an element is displayed in <code>protractor</code>. Which matcher should I use in this case?</p>
<pre><code>expect(elm.isDisplayed()).toBe(true);
expect(elm.isDisplayed()).toBeTruthy();
expect(elm.isDisplayed()).toBeTrue();
</code></pre> | 32,767,435 | 5 | 3 | null | 2015-09-16 18:10:01.29 UTC | 51 | 2021-02-08 22:41:14.507 UTC | null | null | null | null | 771,848 | null | 1 | 240 | javascript|testing|jasmine|protractor|jasmine-matchers | 170,595 | <p>What I do when I wonder something like the question asked here is go to the source.</p>
<h3>toBe()</h3>
<p><a href="https://github.com/jasmine/jasmine/blob/4097718b6682f643833f5435b63e4f590f22919f/lib/jasmine-core/jasmine.js#L2779" rel="noreferrer"><code>expect().toBe()</code></a> is defined as:</p>
<pre><code>function toBe() {
return {
compare: function(actual, expected) {
return {
pass: actual === expected
};
}
};
}
</code></pre>
<p>It performs its test with <code>===</code> which means that when used as <code>expect(foo).toBe(true)</code>, it will pass only if <code>foo</code> actually has the value <code>true</code>. Truthy values won't make the test pass.</p>
<h3>toBeTruthy()</h3>
<p><a href="https://github.com/jasmine/jasmine/blob/4097718b6682f643833f5435b63e4f590f22919f/lib/jasmine-core/jasmine.js#L2908" rel="noreferrer"><code>expect().toBeTruthy()</code></a> is defined as:</p>
<pre><code>function toBeTruthy() {
return {
compare: function(actual) {
return {
pass: !!actual
};
}
};
}
</code></pre>
<h3>Type coercion</h3>
<p>A value is truthy if the coercion of this value to a boolean yields the value <code>true</code>. The operation <code>!!</code> tests for truthiness by coercing the value passed to <code>expect</code> to a boolean. Note that contrarily to what the currently accepted answer <a href="https://stackoverflow.com/revisions/32615803/2">implies</a>, <code>== true</code> is <strong>not</strong> a correct test for truthiness. You'll get funny things like </p>
<pre><code>> "hello" == true
false
> "" == true
false
> [] == true
false
> [1, 2, 3] == true
false
</code></pre>
<p>Whereas using <code>!!</code> yields:</p>
<pre><code>> !!"hello"
true
> !!""
false
> !![1, 2, 3]
true
> !![]
true
</code></pre>
<p>(Yes, empty or not, an array is truthy.)</p>
<h3>toBeTrue()</h3>
<p><code>expect().toBeTrue()</code> is part of <a href="https://github.com/JamieMason/Jasmine-Matchers" rel="noreferrer">Jasmine-Matchers</a> (which is registered on npm as <code>jasmine-expect</code> after a later project registered <code>jasmine-matchers</code> first). </p>
<p><a href="https://github.com/JamieMason/Jasmine-Matchers/blob/e02982ea40d85761f9d0a9eae8358512a6fad133/src/toBeTrue.js#L7-L11" rel="noreferrer"><code>expect().toBeTrue()</code></a> is defined as:</p>
<pre><code>function toBeTrue(actual) {
return actual === true ||
is(actual, 'Boolean') &&
actual.valueOf();
}
</code></pre>
<p>The difference with <code>expect().toBeTrue()</code> and <code>expect().toBe(true)</code> is that <code>expect().toBeTrue()</code> tests whether it is dealing with a <code>Boolean</code> object. <code>expect(new Boolean(true)).toBe(true)</code> would fail whereas <code>expect(new Boolean(true)).toBeTrue()</code> would pass. This is because of this funny thing:</p>
<pre><code>> new Boolean(true) === true
false
> new Boolean(true) === false
false
</code></pre>
<p>At least it is truthy:</p>
<pre><code>> !!new Boolean(true)
true
</code></pre>
<h3>Which is best suited for use with <code>elem.isDisplayed()</code>?</h3>
<p>Ultimately Protractor hands off this request to Selenium. The <a href="https://selenium.googlecode.com/git/docs/api/javascript/module_selenium-webdriver_class_WebElement.html" rel="noreferrer">documentation</a> states that the value produced by <code>.isDisplayed()</code> is a promise that resolves to a <code>boolean</code>. I would take it at face value and use <code>.toBeTrue()</code> or <code>.toBe(true)</code>. If I found a case where the implementation returns truthy/falsy values, I would file a bug report.</p> |
19,829,507 | Android - java.lang.SecurityException: Permission Denial: starting Intent | <p>I have a library (jar) on build path of my project. The project accesses the MainActivity in the jar, using the following intent:</p>
<pre><code>final Intent it = new Intent();
it.setClassName("com.example.lib", "com.example.lib.MainActivity");
startActivity(it);
</code></pre>
<p>It used to work for sometime, but suddenly started getting 'ActivityNotFoundException: No Activity found to handle Intent' which I was able to resolve. But now I am stuck with a 'java.lang.SecurityException: Permission Denial: starting Intent'.</p>
<p>I have tried all suggestions made on stackoverflow (check for duplicates in manifest file; add android:exported="true" to lib manifest; Eclipse> Project> Clean; adding/ modifying 'intent-filter' tags; etc.). I even tried re-writing the manifest of the project but not going anywhere with it.</p>
<p>Here's the logcat output:</p>
<pre><code>11-07 06:20:52.176: E/AndroidRuntime(4626): FATAL EXCEPTION: main
11-07 06:20:52.176: E/AndroidRuntime(4626): java.lang.SecurityException: Permission Denial: starting Intent { cmp=com.example.lib/.MainActivity } from ProcessRecord{40dd3778 4626:com.example.project/u0a10046} (pid=4626, uid=10046) not exported from uid 10047
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.os.Parcel.readException(Parcel.java:1425)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.os.Parcel.readException(Parcel.java:1379)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1885)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1412)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.app.Activity.startActivityForResult(Activity.java:3370)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.app.Activity.startActivityForResult(Activity.java:3331)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:824)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.app.Activity.startActivity(Activity.java:3566)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.app.Activity.startActivity(Activity.java:3534)
11-07 06:20:52.176: E/AndroidRuntime(4626): at com.example.project.MainActivity.onOptionsItemSelected(MainActivity.java:93)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.app.Activity.onMenuItemSelected(Activity.java:2548)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:366)
11-07 06:20:52.176: E/AndroidRuntime(4626): at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:980)
11-07 06:20:52.176: E/AndroidRuntime(4626): at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
11-07 06:20:52.176: E/AndroidRuntime(4626): at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
11-07 06:20:52.176: E/AndroidRuntime(4626): at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
11-07 06:20:52.176: E/AndroidRuntime(4626): at com.android.internal.view.menu.ActionMenuView.invokeItem(ActionMenuView.java:547)
11-07 06:20:52.176: E/AndroidRuntime(4626): at com.android.internal.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:115)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.view.View.performClick(View.java:4204)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.view.View$PerformClick.run(View.java:17355)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.os.Handler.handleCallback(Handler.java:725)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.os.Handler.dispatchMessage(Handler.java:92)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.os.Looper.loop(Looper.java:137)
11-07 06:20:52.176: E/AndroidRuntime(4626): at android.app.ActivityThread.main(ActivityThread.java:5041)
11-07 06:20:52.176: E/AndroidRuntime(4626): at java.lang.reflect.Method.invokeNative(Native Method)
11-07 06:20:52.176: E/AndroidRuntime(4626): at java.lang.reflect.Method.invoke(Method.java:511)
11-07 06:20:52.176: E/AndroidRuntime(4626): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-07 06:20:52.176: E/AndroidRuntime(4626): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-07 06:20:52.176: E/AndroidRuntime(4626): at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Manifest XML of Project:</p>
<pre><code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.project"
android:versionCode="4"
android:versionName="4.0" >
<!-- Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<supports-screens android:anyDensity="true" />
<!-- SDK Settings -->
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="18" />
<!-- APP Start -->
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<!-- App Activity -->
<activity
android:name="com.example.project.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Library Activity -->
<activity android:name="com.example.lib.MainActivity" android:label="LibMain">
<intent-filter>
<action android:name="android.intent.action.MAIN"></action>
</intent-filter>
</activity>
</application>
<!-- END - APP -->
</manifest>
</code></pre>
<p>What am I overlooking? Any suggestions?</p>
<p><strong>EDIT</strong></p>
<p>I updated the manifest.xml with all other activities & somehow, that resolved the problem. The intent activity starts up without any errors. <em>BUT</em>, this is only on AVD. On actual device, it is still throwing same error. I have uninstalled the app from device completely and reinstalled, yet the same error.</p> | 19,829,733 | 11 | 2 | null | 2013-11-07 06:38:40.333 UTC | 13 | 2022-04-07 05:23:43.143 UTC | 2013-11-07 08:46:50.2 UTC | null | 1,057,263 | null | 1,057,263 | null | 1 | 96 | android|android-intent|android-library | 170,107 | <p>You need to set <code>android:exported="true"</code> in your <code>AndroidManifest.xml</code> file where you declare this <code>Activity</code>:</p>
<pre><code><activity
android:name="com.example.lib.MainActivity"
android:label="LibMain"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" >
</action>
</intent-filter>
</activity>
</code></pre> |
34,225,779 | How to set the app icon as the notification icon in the notification drawer | <p>As shown in the figure...<br>
I am getting my notification icon(on left to the red colour).<br>
But I need to display the app icon as shown by the black arrow</p>
<p><a href="https://i.stack.imgur.com/65RaI.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/65RaI.jpg" alt="enter image description here"></a></p>
<pre><code> public void notify(View view){
notification.setSmallIcon(R.drawable.ic_stat_name);
notification.setTicker("Welcome to ****");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("abcd");
notification.setContentText("abcd");
Intent intent = new Intent(this, home.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(uniqueID, notification.build());
}
</code></pre> | 34,225,836 | 3 | 3 | null | 2015-12-11 14:26:25.97 UTC | 11 | 2020-08-06 11:22:57.707 UTC | 2015-12-11 15:38:21.457 UTC | null | 2,649,012 | null | 5,664,716 | null | 1 | 41 | android|android-studio|notifications|android-notifications|android-notification-bar | 99,277 | <p>Try this code at your notification builder :</p>
<pre><code>NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
R.mipmap.ic_launcher))
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
android.app.NotificationManager notificationManager =
(android.app.NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
</code></pre>
<p>Set Large icon does the trick.Comment below if you have any further info</p> |
172,175 | How do you bind a DropDownList in a GridView in the EditItemTemplate Field? | <p>Here's my code in a gridview that is bound at runtime:</p>
<pre><code>...
<asp:templatefield>
<edititemtemplate>
<asp:dropdownlist runat="server" id="ddgvOpp" />
</edititemtemplate>
<itemtemplate>
<%# Eval("opponent.name") %>
</itemtemplate>
</asp:templatefield>
...
</code></pre>
<p>I want to bind the dropdownlist "ddgvOpp" but i don't know how. I should, but I don't. Here's what I have, but I keep getting an "Object reference" error, which makes sense:</p>
<pre><code>protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //skip header row
{
DropDownList ddOpp = (DropDownList)e.Row.Cells[5].FindControl("ddgvOpp");
BindOpponentDD(ddOpp);
}
}
</code></pre>
<p>Where <code>BindOpponentDD()</code> is just where the DropDownList gets populated. Am I not doing this in the right event? If not, which do I need to put it in?</p>
<p>Thanks so much in advance...</p> | 172,220 | 5 | 0 | null | 2008-10-05 15:53:35.703 UTC | 2 | 2014-02-04 07:35:20.007 UTC | 2008-10-05 15:56:36.757 UTC | Adhip Gupta | 384 | null | 7,173 | null | 1 | 7 | asp.net|data-binding|gridview | 42,434 | <p>Ok, I guess I'm just dumb. I figured it out.</p>
<p>In the RowDataBound event, simply add the following conditional:</p>
<pre><code>if (myGridView.EditIndex == e.Row.RowIndex)
{
//do work
}
</code></pre> |
1,020,061 | How to use dates in X-axis with Google chart API? | <p>Is there a way to plot a chart with Google chart API so that the X-axis values are days in a month?</p>
<p>I have data points that are not provided with the same frequency. For example:</p>
<pre><code>Date - Value
1/1/2009 - 100
1/5/2009 - 150
1/6/2009 - 165
1/13/2009 - 200
1/20/2009 - 350
1/30/2009 - 500
</code></pre>
<p>I want to make a chart that will separate each data point with the relative distance based on time during a month. This can be done with Excel, but how can I calculate and display it with Google chart?</p>
<p>Other free solutions similar to Google chart or a free library that can be used with ASP.NET are also welcome.</p> | 1,020,161 | 5 | 0 | null | 2009-06-19 21:19:03.037 UTC | 12 | 2018-04-25 22:40:56.007 UTC | 2012-06-06 07:28:28.243 UTC | null | 1,128,737 | null | 103,166 | null | 1 | 42 | javascript|asp.net|vb.net|google-visualization | 60,248 | <blockquote>
<p><strong>UPDATE</strong> This is now supported directly in the Chart API using the advanced graphs "annotated chart" feature - <a href="https://developers.google.com/chart/interactive/docs/gallery/annotationchart" rel="nofollow noreferrer">https://developers.google.com/chart/interactive/docs/gallery/annotationchart</a></p>
</blockquote>
<p>I have done this on my <s><a href="http://rehash.dustinfineout.com/db_stats.php" rel="nofollow noreferrer" title="ReHash Database Statistics">ReHash Database Statistics</a></s> chart (even though the dates turned out to be evenly spaced, so it doesn't exactly demonstrate that it's doing this).</p>
<p>First, you want to get your <strong>overall time period</strong>, which will be analogous to the overall width of your chart. To do this we subtract the earliest date from the latest. I prefer to use Unix-epoch timestamps as they are integers and easy to compare in this way, but you could easily calculate the number of seconds, etc.</p>
<p>Now, loop through your data. For each date we want the <em>percentile</em> in the overall period that the date is from the beginning (i.e. the earliest date is 0, the latest is 100). For each date, you first want to calculate the <strong>distance of the present date</strong> from the earliest date in the data set. Essentially, "how far are we from the start". So, subtract the earliest date from the present date. Then, to find the percentile, we divide the <strong>distance of the present date</strong> by the <strong>overall time period</strong>, and then multiply by 100 and truncate or round any decimal to give our integral <strong>x-coordinate</strong>.</p>
<p>And it is as simple as that! Your x-values will range from 0 (the left-side of the chart) to 100 (the right side) and each data point will lie at a distance from the start respective of its true temporal distance.</p>
<p>If you have any questions, feel free to ask! I can post pesudocode or PHP if desired.</p> |
973,721 | C# - Detecting if the SHIFT key is held when opening a context menu | <p>In my C# application I want to display a context menu, but I want to add special options to the menu if the SHIFT key is being held down when the context menu is opened.</p>
<p>I'm currently using the <code>GetKeyState</code> API to check for the SHIFT key. It works fine on my computer but users with non-English Windows say it doesn't work at all for them.</p>
<p>I also read that in the Win32 API when a context menu is opened there's a flag that indicates in the menu should show <code>EXTENDEDVERBS</code>. In C# the <code>EventArgs</code> for the <code>Opening</code> event doesn't contain (from what I can tell) a property indicating <code>EXTENDEDVERBS</code> or if any modifier keys are pressed.</p>
<p>Here's the code I'm using now inside the "<code>Opening</code>" event:</p>
<pre><code>// SHIFT KEY is being held down
if (Convert.ToBoolean(GetKeyState(0x10) & 0x1000))
{
_menuStrip.Items.Add(new ToolStripSeparator());
ToolStripMenuItem log = new ToolStripMenuItem("Enable Debug Logging");
log.Click += new EventHandler(log_Click);
log.Checked = Settings.Setting.EnableDebugLogging;
_menuStrip.Items.Add(log);
}
</code></pre>
<p>If GetKeyState is the right way of doing it, is my code properly detecting the SHIFT key being pressed?</p> | 973,733 | 5 | 0 | null | 2009-06-10 04:51:16.657 UTC | 6 | 2018-11-21 11:31:44.06 UTC | 2009-06-10 05:12:05.197 UTC | null | 5,982 | null | 5,982 | null | 1 | 51 | c#|keyboard|contextmenu | 69,877 | <p>You can use the <a href="https://msdn.microsoft.com/en-us/library/9byw5s2d(v=vs.110).aspx" rel="noreferrer">ModifierKeys static property</a> on control to determine if the shift key is being held. </p>
<pre><code>if (Control.ModifierKeys == Keys.Shift ) {
...
}
</code></pre>
<p>This is a flag style enum though so depending on your situation you may want to do more rigorous testing.</p>
<p>Also note that this will check to see if the Shift key is held at the moment you check the value. Not the moment when the menu open was initiated. That may not be a significant difference for your application but it's worth noting. </p> |
986,627 | Detect if app was downloaded from Android Market | <p>I have an Android library that uploads data to a test server and production server. I'd like developers using this library to use the test server when developing, and production server when the app is downloaded from Android Market.</p>
<p>Is this possible for an app to tell where it came from (Market or non-Market?) I would imagine one could detect the presence of the signed JAR file.</p> | 991,120 | 5 | 3 | null | 2009-06-12 13:25:09.707 UTC | 39 | 2011-12-22 00:13:59.32 UTC | null | null | null | null | 104,181 | null | 1 | 53 | android | 9,914 | <p>Yes, you could use the signature for that. If you use a debug key to sign your app during development and a release key when uploading your app to the market you can check for the signature that the app was signed with and based on that use test or production server.
Here is a small code piece to read the signature of your app:</p>
<pre><code> try {
PackageManager manager = context.getPackageManager();
PackageInfo appInfo = manager.getPackageInfo(
YOUR_PACKAGE_NAME, PackageManager.GET_SIGNATURES);
// Now test if the first signature equals your debug key.
boolean shouldUseTestServer =
appInfo.signatures[0].toCharsString().equals(YOUR_DEBUG_KEY);
} catch (NameNotFoundException e) {
// Expected exception that occurs if the package is not present.
}
</code></pre>
<p>YOUR_PACKAGE_NAME must be something like 'com.wsl.CardioTrainer'. It must be the package name you used in your AndroidManifest.xml.
Good Luck</p>
<p>mark</p> |
30,865,233 | print without newline in swift | <p>In swift 2.0, <code>print()</code> automatically adds a newline character. In swift 1.2, <code>println()</code> and <code>print()</code> used to be separate functions. So how do I print some text and not add a newline to it since swift no longer has a print function that does not append newlines. </p> | 32,266,079 | 5 | 3 | null | 2015-06-16 10:39:03.447 UTC | 39 | 2022-06-10 18:31:23.843 UTC | 2017-06-17 17:58:06.063 UTC | null | 1,920,977 | null | 1,920,977 | null | 1 | 135 | swift|swift3|swift2 | 83,708 | <p>Starting in Swift 2.0, the recommended method of printing without newline is:</p>
<pre><code>print("Hello", terminator: "")
</code></pre> |
16,594,148 | while loop nested in a while loop | <p>I was using a nested while loop, and ran into a problem, as the inner loop is only run once.
To demonstrate I've made a bit of test code.</p>
<pre><code>#include <stdio.h>
int main(){
int i = 0;
int j = 0;
while(i < 10){
printf("i:%d\n", i);
while(j < 10){
printf("j:%d\n", j);
j++;
}
i++;
}
}
</code></pre>
<p>This returns:</p>
<pre><code>i:0
j:0
j:1
j:2
j:3
j:4
j:5
j:6
j:7
j:8
j:9
i:1
i:2
i:3
i:4
i:5
i:6
i:7
i:8
i:9
</code></pre>
<p>Can anyone explain why the nested loop doesn't execute 10 times? And what can I do to fix it?</p> | 16,594,184 | 7 | 2 | null | 2013-05-16 17:48:54.7 UTC | 1 | 2018-09-14 11:37:43.95 UTC | null | null | null | null | 2,232,340 | null | 1 | 2 | c|while-loop | 49,779 | <p>You never reset the value of <code>j</code> to <code>0</code>, and as such, your inner loop condition is never true after the first run. Assigning <code>j = 0;</code> in the outer loop afterward should fix it.</p> |
1,791,234 | lua call function from a string with function name | <p>Is it possible in lua to execute a function from a string representing its name?<br>
i.e: I have the <code>string x = "foo"</code>, is it possible to do <code>x()</code> ? </p>
<p>If yes what is the syntax ?</p> | 1,791,506 | 5 | 0 | null | 2009-11-24 16:31:01.36 UTC | 13 | 2011-01-29 13:55:27.237 UTC | null | null | null | null | 155,166 | null | 1 | 26 | dynamic|lua | 44,476 | <p>To call a function in the global namespace (as mentioned by @THC4k) is easily done, and does not require <code>loadstring()</code>.</p>
<pre><code>x='foo'
_G[x]() -- calls foo from the global namespace
</code></pre>
<p>You would need to use <code>loadstring()</code> (or walk each table) if the function in another table, such as if <code>x='math.sqrt'</code>.</p>
<p>If <code>loadstring()</code> is used you would want to not only append parenthesis with ellipse <code>(...)</code> to allow for parameters, but also add <code>return</code> to the front.</p>
<pre><code>x='math.sqrt'
print(assert(loadstring('return '..x..'(...)'))(25)) --> 5
</code></pre>
<p>or walk the tables:</p>
<pre><code>function findfunction(x)
assert(type(x) == "string")
local f=_G
for v in x:gmatch("[^%.]+") do
if type(f) ~= "table" then
return nil, "looking for '"..v.."' expected table, not "..type(f)
end
f=f[v]
end
if type(f) == "function" then
return f
else
return nil, "expected function, not "..type(f)
end
end
x='math.sqrt'
print(assert(findfunction(x))(121)) -->11
</code></pre> |
2,317,728 | Ext JS: what is xtype good for? | <p>I see there are lot's of examples in Ext JS where instead of actually creating Ext JS objects, an object literal with an <code>xtype</code> property is passed in.</p>
<p>What is this good for? Where is the performance gain (if that's the reason) if the object is going to be created anyway?</p> | 2,318,285 | 5 | 0 | null | 2010-02-23 11:37:37.333 UTC | 11 | 2018-04-20 14:46:14.48 UTC | 2018-04-20 14:38:59.117 UTC | null | 3,728,901 | null | 63,051 | null | 1 | 29 | extjs | 37,416 | <p><code>xtype</code> is a shorthand way to identify particular components: <code>panel</code> = <code>Ext.Panel</code>, <code>textfield</code> = <code>Ext.form.TextField</code>, etc. When you create a page or a form, you may use these <code>xtypes</code> rather than instantiate objects. For example,</p>
<pre><code>items: [{
xtype: 'textfield',
autoWidth: true,
fieldLabel: 'something'
}]
</code></pre>
<p><strong>Moreover</strong>, creating pages in this manner allows Ext JS <a href="http://extjs.com/forum/showthread.php?p=138612" rel="nofollow noreferrer">to render lazily the page</a>. This is where you see a "performance gain." Instead of creating a large number of components when the app loads, Ext JS renders components when the user needs to see them. Not a big deal if you have one page, but if you exploit tabs or an accordion, many pages are initially hidden and therefore the app will load more quickly.</p>
<p>Furthermore, you may create <strong>and register</strong> new components creating xtypes of your choosing. Ext JS will similarly render your components lazily.</p>
<p>You may also retrieve components by ID. Since your component (as well as the Ext JS components) may provide a bunch of nice behavior, it is sometimes convenient to search for and retrieve a component rather than a simple DOM element or node.</p>
<p>In short, xtypes identify components and components are a key aspect of Ext JS.</p> |
1,408,171 | Thread local storage in Python | <p>How do I use thread local storage in Python?</p>
<h3>Related</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/104983/what-is-thread-local-storage-in-python-and-why-do-i-need-it">What is “thread local storage” in Python, and why do I need it?</a> - This thread appears to be focused more on when variables are shared.</li>
<li><a href="https://stackoverflow.com/questions/1403471/efficient-way-to-determine-whether-a-particular-function-is-on-the-stack-in-pytho/1403485#1403485">Efficient way to determine whether a particular function is on the stack in Python</a> - Alex Martelli gives a nice solution</li>
</ul> | 13,240,093 | 5 | 3 | null | 2009-09-10 23:03:33.213 UTC | 38 | 2019-04-15 08:07:50.34 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 165,495 | null | 1 | 85 | python|multithreading|thread-local-storage | 73,045 | <p>Thread local storage is useful for instance if you have a thread worker pool and each thread needs access to its own resource, like a network or database connection. Note that the <code>threading</code> module uses the regular concept of threads (which have access to the process global data), but these are not too useful due to the global interpreter lock. The different <code>multiprocessing</code> module creates a new sub-process for each, so any global will be thread local.</p>
<h1>threading module</h1>
<p>Here is a simple example:</p>
<pre><code>import threading
from threading import current_thread
threadLocal = threading.local()
def hi():
initialized = getattr(threadLocal, 'initialized', None)
if initialized is None:
print("Nice to meet you", current_thread().name)
threadLocal.initialized = True
else:
print("Welcome back", current_thread().name)
hi(); hi()
</code></pre>
<p>This will print out:</p>
<pre><code>Nice to meet you MainThread
Welcome back MainThread
</code></pre>
<p>One important thing that is easily overlooked: a <code>threading.local()</code> object only needs to be created once, not once per thread nor once per function call. The <code>global</code> or <code>class</code> level are ideal locations.</p>
<p>Here is why: <code>threading.local()</code> actually creates a new instance each time it is called (just like any factory or class call would), so calling <code>threading.local()</code> multiple times constantly overwrites the original object, which in all likelihood is not what one wants. When any thread accesses an existing <code>threadLocal</code> variable (or whatever it is called), it gets its own private view of that variable.</p>
<p>This won't work as intended:</p>
<pre><code>import threading
from threading import current_thread
def wont_work():
threadLocal = threading.local() #oops, this creates a new dict each time!
initialized = getattr(threadLocal, 'initialized', None)
if initialized is None:
print("First time for", current_thread().name)
threadLocal.initialized = True
else:
print("Welcome back", current_thread().name)
wont_work(); wont_work()
</code></pre>
<p>Will result in this output:</p>
<pre><code>First time for MainThread
First time for MainThread
</code></pre>
<h1>multiprocessing module</h1>
<p>All global variables are thread local, since the <code>multiprocessing</code> module creates a new process for each thread.</p>
<p>Consider this example, where the <code>processed</code> counter is an example of thread local storage:</p>
<pre><code>from multiprocessing import Pool
from random import random
from time import sleep
import os
processed=0
def f(x):
sleep(random())
global processed
processed += 1
print("Processed by %s: %s" % (os.getpid(), processed))
return x*x
if __name__ == '__main__':
pool = Pool(processes=4)
print(pool.map(f, range(10)))
</code></pre>
<p>It will output something like this:</p>
<pre><code>Processed by 7636: 1
Processed by 9144: 1
Processed by 5252: 1
Processed by 7636: 2
Processed by 6248: 1
Processed by 5252: 2
Processed by 6248: 2
Processed by 9144: 2
Processed by 7636: 3
Processed by 5252: 3
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
</code></pre>
<p>... of course, the thread IDs and the counts for each and order will vary from run to run.</p> |
1,348,191 | Default Transaction Timeout | <p>I used to set Transaction timeouts by using <strong>TransactionOptions.Timeout</strong>, but have decided for ease of maintenance to use the config approach:</p>
<pre><code> <system.transactions>
<defaultSettings timeout="00:01:00" />
</system.transactions>
</code></pre>
<p>Of course, after putting this in, I wanted to test it was working, so reduced the timeout to 5 seconds, then ran a test that lasted longer than this - but the transaction does not appear to abort! If I adjust the test to set TransactionOptions.Timeout to 5 seconds, the test works as expected</p>
<p>After Investigating I think the problem appears to relate to TransactionOptions.Timeout, even though I'm no longer using it.</p>
<p>I still need to use TransactionOptions so I can set IsolationLevel, but I no longer set the Timeout value, if I look at this object after I create it, the timeout value is 00:00:00, which equates to infinity. Does this mean my value set in the config file is being ignored?</p>
<p>To summarise:</p>
<ul>
<li>Is it impossible to mix the config
setting, and use of
TransactionOptions </li>
<li>If not, is there
any way to extract the config setting
at runtime, and use this to set the
Timeout property</li>
<li><strong>[Edit] OR</strong> Set the default isolation-level without using TransactionOptions</li>
</ul> | 1,367,630 | 6 | 2 | null | 2009-08-28 16:45:18.017 UTC | 14 | 2013-07-26 10:50:59.953 UTC | 2009-09-01 09:56:16.203 UTC | null | 71,813 | null | 71,813 | null | 1 | 41 | .net|configuration|transactions|timeout | 66,112 | <p>You can mix system.transaction configuration settings and the use of the <code>TransactionOption</code> class, but there are some things you need to be aware of.</p>
<blockquote>
<p>If you use the <code>TransactionOption</code> and
specify a <code>Timeout</code> value, that value
will be used over the
system.transactions/defaultTimeout
value.</p>
</blockquote>
<p>The above is the crux of the problem in your case I think. You are using the <code>TransactionOption</code> to specify the <em>isolation</em> level, and as a side effect you are getting an <em>infinite</em> Timeout value because infinite is the default Timeout value for <code>TransactionOption</code> if its not specified. Though, I'm not quite sure why that is...it would make sense to default to the default Transaction Timeout.</p>
<p>You can implement your own TransactionOptions helper class that includes defaults that are read from app.config (if found) or default to reasonable values for a TransactionOption class that can be used.</p>
<p>In any case, you can still limit this by using the <strong>system.transaction/machineSettings/maxTimeout</strong> value. This is an administrative setting and can only be configured through the machine.config. You'll get a ConfigurationException if you try it from app/web.config.</p>
<pre><code><system.transactions>
<machineSettings maxTimeout="00:00:30" />
</system.transactions>
</code></pre>
<p>With the <strong>maxTimeout</strong> set, no matter what timeout value you specify, the maximum value will be limited to the maxTimeout value. The default maxTimeout is 00:10:00, or 10 minutes, so you wouldn't actually ever have an infinite timeout on a transaction.</p>
<p>You can also set the transaction IsolationLevel <strong>explicitly</strong> on the database connection you are using within the transaction. Something like this?</p>
<pre><code> var connectionString = "Server=.;Database=master;Trusted_Connection=True;";
using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
using (var conn = new SqlConnection(connectionString))
{
conn.Open();
var sqlTransaction = conn.BeginTransaction(System.Data.IsolationLevel.Serializable);
// do database work
//
sqlTransaction.Commit();
}
// do other work..
//
scope.Complete();
}
</code></pre>
<p>In your testing, you may need to make sure you rebuild so that the app.config is regenerated . In my testing, it appeared that I needed to terminate the *.vshost.exe process in order for it to pick up the system.transaction configuration setting change - though I feel that may have been a fluke. Just fyi..</p> |
2,239,249 | Team Foundation Build or TeamCity? | <p>We are a mostly MS shop at work doing .NET LOB development. We also use MS Dynamics for our CRM app... all the devs are currently using VS/SQL Server 2008. We also use VSS, but everyone hates it at work and that is quickly on its way out. </p>
<p>We are begining our initiative for TDD implementation across the team (~dozen ppl). I've gotten TeamCity setup and have my first automated builds running succesfully using the 2008 sln builder and also using SVN that a co-worker had setup who is doing the source control analysis. When demoing to managament, I think they started to buy into my snake oil and threw out the suggestions of looking into TFS. </p>
<p>This threw a wrench in what I had planned for our TDD architecture; In a good way though, because I had always assumed that TFS was just too expensive and not worth it for our team (and i've seen the same in other shops i've worked at / know of). I do feel like MS is years behind in the TDD/CI area and that the third party products were probably much better and more mature... I still need to do a lot of research, but I figured I'd come here to see if anyone has actually used both systems.</p>
<p>I realize the TFS encompasses a lot more then just a build server... but I didn't want to make this too broad of a question at least on purpose. <strong><em>What are the practical pros/cons of using TFS/TFB instead of TeamCity - e.g. which benefits would we lose/gain? Has anyone here actually used both systems (TFS for TDD/CI and TeamCity/SVN) and can speak from practical standpoint?</em></strong></p>
<p>I've done some searching on this topic, and one post I found here on SO mentioned that the cons of TFB was it only supported MSBuild. I was planning on using FinalBuilder with TeamCity; and it appears it also supports TFS as well...</p>
<p>Thanks for any advice</p>
<p><strong><em>EDIT: Has anyone used TFS as their Build/CI server and can tell of success/failure stories?</em></strong></p> | 2,290,679 | 7 | 5 | null | 2010-02-10 18:12:17.713 UTC | 26 | 2016-09-17 05:39:06.097 UTC | 2011-04-11 09:30:37.54 UTC | null | 11,635 | null | 191,206 | null | 1 | 60 | tfs|tdd|continuous-integration|teamcity|tfsbuild | 31,142 | <p>We are a small development shop, and decided that Team Foundation Server carries too much overhead for us. We used to write custom MSBuild scripts to run from the command line, but after we discovered TeamCity, we moved our entire build process over to it.</p>
<p>We've found TeamCity to be easy to use and configure, and JetBrains provides excellent support and documentation. They are also on a much faster release and update cycle than Microsoft.</p>
<p>Their support for SVN source control is excellent, and we like the fact that they support both MSTest and NUnit for unit testing.</p>
<p>We also liked the fact that the TeamCity Professional edition was free, so we could evaluate it to see if it worked for us. We haven't hit the number of project configurations (20) that would require us to upgrade to the Enterprise edition.</p> |
2,237,537 | Which maven dependencies to include for spring 3.0? | <p>I am trying to do my first project with Spring 3.0 (and maven). I have been using Spring 2.5 (and primer versions) in quite some projects. Nevertheless I am kinda confused, what modules I have to define as dependencies in my pom.xml. I just want to use the core container functions (beans, core, context, el).</p>
<p>I was used to do this:</p>
<pre><code><dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
</code></pre>
<p>But now I am kinda confused, as there is no full packed spring module for version 3.0 anymore. I tried the following but it didnt work (some classes are missing).</p>
<pre><code> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
</code></pre>
<p>Any help would be appreciated!</p> | 2,237,805 | 8 | 1 | null | 2010-02-10 14:40:26.467 UTC | 105 | 2019-05-10 21:30:59.713 UTC | 2010-02-10 14:55:48.89 UTC | null | 21,234 | null | 255,036 | null | 1 | 114 | java|spring|maven-2|dependencies | 138,680 | <p>There was a really nice post on the <a href="http://blog.springsource.com/" rel="noreferrer">Spring Blog</a> from Keith Donald detailing howto <a href="http://blog.springsource.com/2009/12/02/obtaining-spring-3-artifacts-with-maven/" rel="noreferrer">Obtain Spring 3 Aritfacts with Maven</a>, with comments detailing when you'd need each of the dependencies...</p>
<pre class="lang-xml prettyprint-override"><code><!-- Shared version number properties -->
<properties>
<org.springframework.version>3.0.0.RELEASE</org.springframework.version>
</properties>
<!-- Core utilities used by other modules.
Define this if you use Spring Utility APIs
(org.springframework.core.*/org.springframework.util.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Expression Language (depends on spring-core)
Define this if you use Spring Expression APIs
(org.springframework.expression.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Bean Factory and JavaBeans utilities (depends on spring-core)
Define this if you use Spring Bean APIs
(org.springframework.beans.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Aspect Oriented Programming (AOP) Framework
(depends on spring-core, spring-beans)
Define this if you use Spring AOP APIs
(org.springframework.aop.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Application Context
(depends on spring-core, spring-expression, spring-aop, spring-beans)
This is the central artifact for Spring's Dependency Injection Container
and is generally always defined-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Various Application Context utilities, including EhCache, JavaMail, Quartz,
and Freemarker integration
Define this if you need any of these integrations-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Transaction Management Abstraction
(depends on spring-core, spring-beans, spring-aop, spring-context)
Define this if you use Spring Transactions or DAO Exception Hierarchy
(org.springframework.transaction.*/org.springframework.dao.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- JDBC Data Access Library
(depends on spring-core, spring-beans, spring-context, spring-tx)
Define this if you use Spring's JdbcTemplate API
(org.springframework.jdbc.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Object-to-Relation-Mapping (ORM) integration with Hibernate, JPA and iBatis.
(depends on spring-core, spring-beans, spring-context, spring-tx)
Define this if you need ORM (org.springframework.orm.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Object-to-XML Mapping (OXM) abstraction and integration with JAXB, JiBX,
Castor, XStream, and XML Beans.
(depends on spring-core, spring-beans, spring-context)
Define this if you need OXM (org.springframework.oxm.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Web application development utilities applicable to both Servlet and
Portlet Environments
(depends on spring-core, spring-beans, spring-context)
Define this if you use Spring MVC, or wish to use Struts, JSF, or another
web framework with Spring (org.springframework.web.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Servlet Environments
(depends on spring-core, spring-beans, spring-context, spring-web)
Define this if you use Spring MVC with a Servlet Container such as
Apache Tomcat (org.springframework.web.servlet.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Spring MVC for Portlet Environments
(depends on spring-core, spring-beans, spring-context, spring-web)
Define this if you use Spring MVC with a Portlet Container
(org.springframework.web.portlet.*)-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc-portlet</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Support for testing Spring applications with tools such as JUnit and TestNG
This artifact is generally always defined with a 'test' scope for the
integration testing framework and unit testing stubs-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
<scope>test</scope>
</dependency>
</code></pre> |
1,696,877 | How to set a value to a file input in HTML? | <p>How can I set the value of this?</p>
<pre><code><input type="file" />
</code></pre> | 1,696,884 | 9 | 2 | null | 2009-11-08 15:32:27.337 UTC | 80 | 2022-08-08 03:12:26.213 UTC | 2020-06-18 04:21:21.727 UTC | null | 2,430,549 | null | 140,937 | null | 1 | 425 | javascript|html|file-upload|preset | 842,508 | <p>You cannot set it to a client side disk file system path, due to security reasons.</p>
<p>Imagine:</p>
<pre class="lang-html prettyprint-override"><code><form name="foo" method="post" enctype="multipart/form-data">
<input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>
</code></pre>
<p>You don't want the websites you visit to be able to do this, do you? =)</p>
<p>You can only set it to a publicly accessible web resource as seen in <a href="https://stackoverflow.com/a/70485949">this answer</a>, but this is clearly not the same as a client side disk file system path and it's therefore useless in that context.</p> |
1,960,939 | Disabling browser print options (headers, footers, margins) from page? | <p>I have seen this question asked in a couple of different ways on SO and several other websites, but most of them are either too specific or out-of-date. I'm hoping someone can provide a definitive answer here without pandering to speculation.</p>
<p>Is there a way, either with CSS or javascript, to change the default printer settings when someone prints within their browser? And of course by "prints from their browser" I mean some form of HTML, not PDF or some other plug-in reliant mime-type.</p>
<p>Please note:</p>
<p>If some browsers offer this and others don't (or if you only know how to do it for some browsers) I welcome browser-specific solutions.</p>
<p>Similarly, if you know of a mainstream browser that has specific restrictions against EVER doing this, that is also helpful, but some fairly up-to-date documentation would be appreciated. (simply saying "that goes against XYZ's security policy" isn't very convincing when XYZ has made significant changes in said policy in the last three years).</p>
<p>Finally, when I say "change default print settings" I don't mean forever, just for my page, and I am referring specifically to print margins, headers, and footers.</p>
<p>I am very aware that CSS offers the option of changing the page orientation as well as the page margins. One of the many struggles is with Firefox. If I set the page margins to 1 inch, it ADDS this to the half inch it already puts into place.</p>
<p>I very much want to reduce the usage of PDFs on my client's site, but the infringement on presentation (as well as the lack of reliability) are their main concern.</p> | 2,780,518 | 9 | 5 | null | 2009-12-25 10:33:32.847 UTC | 85 | 2020-09-27 14:00:46.753 UTC | null | null | null | null | 49,478 | null | 1 | 193 | javascript|html|css|browser|printing | 276,221 | <p>The CSS standard enables some advanced formatting. There is a <code>@page</code> directive in CSS that enables some formatting that applies only to paged media (like paper). See <a href="http://www.w3.org/TR/1998/REC-CSS2-19980512/page.html" rel="noreferrer" title="Paged media">http://www.w3.org/TR/1998/REC-CSS2-19980512/page.html</a>.</p>
<p>Downside is that behavior in different browsers is not consistent. Safari still does not support setting printer page margin at all, but all the other major browsers now support it.</p>
<p>With the <code>@page</code> directive, you can specify printer margin of the page (which is not the same as normal CSS margin of an HTML element):</p>
<pre><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Print Test</title>
<style type="text/css" media="print">
@page
{
size: auto; /* auto is the initial value */
margin: 0mm; /* this affects the margin in the printer settings */
}
html
{
background-color: #FFFFFF;
margin: 0px; /* this affects the margin on the html before sending to printer */
}
body
{
border: solid 1px blue ;
margin: 10mm 15mm 10mm 15mm; /* margin you want for the content */
}
</style>
</head>
<body>
<div>Top line</div>
<div>Line 2</div>
</body>
</html>
</code></pre>
<blockquote>
<p>Note that we basically disables the page-specific margins here to achieve the effect of removing the header and footer, so the margin we set on the body will not be used in page breaks (as <a href="https://stackoverflow.com/questions/1960939/disabling-browser-print-options-headers-footers-margins-from-page/2780518?noredirect=1#comment74527214_2780518">commented by Konrad</a>) This means that it will only work properly if the printed content is only one page.</p>
</blockquote>
<p>This does not work in <strong>Firefox 3.6</strong>, <strong>IE 7</strong>, <strong>Safari 5.1.7</strong> or <strong>Google Chrome 4.1</strong>.</p>
<p>Setting the @page margin does have effect in <strong>IE 8</strong>, <strong>Opera 10</strong>, <strong>Google Chrome 21</strong> and <strong>Firefox 19</strong>.<br />
Although the page margins are set correctly for your content in these browsers, the behavior is not ideal in trying to solve the hiding of the header/footer.</p>
<h2>This is how it behaves in different browsers:</h2>
<ul>
<li><p>In <strong>Internet Explorer</strong>, the margin is actually set to 0mm in the settings for this printing, and if you do Preview you will get 0mm as default, but the user can change it in the preview.<br />
You will see that the page content actually are <em>positioned</em> correctly, but the browser print header and footer is shown with non-transparent background, and so effectively hiding the page content at that position.</p>
</li>
<li><p>In <strong>Firefox</strong> newer versions, it is <em>positioned</em> correctly, but both the header/footer text and content text is displayed, so it looks like a bad mix of browser header text and your page content.</p>
</li>
<li><p>In <strong>Opera</strong>, the page content hides the header when using a non-transparent background in the standard css and the header/footer position conflicts with content. Quite good, but looks strange if margin is set to a small value that causes the header to be partially visible. Also the page margin is not set properly.</p>
</li>
<li><p>In <strong>Chrome</strong> newer versions, the browser header and footer is hidden if the @page margin is set so small that the header/footer position conflicts with content. In my opinion, this is exactly how this should behave.</p>
</li>
</ul>
<p>So the conclusion is that <strong>Chrome</strong> has the best implementation of this in respect to hiding the header/footer.</p> |
2,245,201 | How can I make my .NET application erase itself? | <p>How can I make my C# app erase itself (self-destruct)? Here's two ways that I think might work:</p>
<ul>
<li>Supply another program that deletes the main program. How is this deleter program deleted then, though?</li>
<li>Create a process to CMD that waits a few seconds then deletes your file. During those few seconds, you close your application.</li>
</ul>
<p>Both of those methods seem inefficient. I have a feeling that there's some built-in flag or something in Windows that allows for such stuff. How should I do it? Also, can you provide some sample code? </p>
<p><strong>UPDATE:</strong> Thanks for all your answers! I'm going to try them, and see where that gets me.</p>
<p>First of all, some people have asked why I'd want my app to do this. Here's the answer: a few days ago, I read the Project Aardvark spec that Joel Spolsky posted on his blog, and it mentioned that the client app would delete itself after the remote session. I'm wondering how this works, and how, if I ever need to do this, I can accomplish such a feat. </p>
<p>Here's a little overview of what's been suggested:</p>
<ul>
<li><strong>Create a registry entry that tells Windows to delete the file on reboot</strong></li>
<li><strong>Launch CMD with a ping command to wait a few seconds and then delete the file</strong></li>
</ul>
<p>Both of those, of course, have their disadvantages, as outlined in the comments.</p>
<p>However, would such a method as outlined below work?</p>
<p>There are two executables: Program.exe and Cleaner.exe. The former is the program itself, the latter is the app that deletes Program.exe and itself (if it's loaded into memory, as I'm about to explain). Is it possible for Program.exe (which has dependencies) to <strong>load</strong> all of Cleaner.exe, which doesn't have any dependencies, <strong>into memory</strong> and run it?</p>
<p>If this is possible, could Cleaner.exe be packaged inside Program.exe, loaded into memory, and run?</p> | 2,245,219 | 11 | 8 | null | 2010-02-11 14:49:39.823 UTC | 9 | 2021-02-16 17:09:15.523 UTC | 2015-07-06 11:40:00.967 UTC | null | 4,370,109 | null | 130,164 | null | 1 | 24 | c#|.net|windows|delete-file|self-destruction | 14,966 | <p>There's a <a href="http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx" rel="noreferrer">MoveFileEx</a> API, which, when given a <code>MOVEFILE_DELAY_UNTIL_REBOOT</code> flag, will delete specified file on next system startup.</p> |
1,828,613 | Check if a key is down? | <p>Is there a way to detect if a key is currently down in JavaScript?</p>
<p>I know about the "keydown" event, but that's not what I need. Some time AFTER the key is pressed, I want to be able to detect if it is still pressed down.</p>
<p>P. S. The biggest issue seems to be that after some period of time the key begins to repeat, firing off keydown and keyup events like a fiend. Hopefully there is just a simple isKeyDown(key) function, but if not then this issue will need to be overcome / worked around.</p> | 1,828,802 | 14 | 2 | null | 2009-12-01 20:17:23.133 UTC | 11 | 2022-06-15 11:34:40.017 UTC | null | null | null | null | 68,210 | null | 1 | 116 | javascript|input|keyboard | 159,097 | <blockquote>
<p>Is there a way to detect if a key is currently down in JavaScript?</p>
</blockquote>
<p>Nope. The only possibility is monitoring each <code>keyup</code> and <code>keydown</code> and remembering.</p>
<blockquote>
<p>after some period of time the key begins to repeat, firing off keydown and keyup events like a fiend.</p>
</blockquote>
<p>It shouldn't. You'll definitely get <code>keypress</code> repeating, and in many browsers you'll also get repeated <code>keydown</code>, but if <code>keyup</code> repeats, it's a bug.</p>
<p>Unfortunately it is not a completely unheard-of bug: on Linux, Chromium, and Firefox (when it is being run under GTK+, which it is in popular distros such as Ubuntu) both generate repeating keyup-keypress-keydown sequences for held keys, which are impossible to distinguish from someone hammering the key really fast.</p> |
8,755,876 | Excel 2003 VBA - kernel32 functions - and other libs | <p>I've been programming in VBA for Excel 2003 for some years now, and only recently I've been introduced to:</p>
<pre><code>Declare Sub AAAA Lib "kernel32" Alias "AAAA"
</code></pre>
<p>by an <a href="https://stackoverflow.com/questions/4876300/timed-alarm-in-excel-vba/8510092#8510092">answer here on Stack Overflow</a>.</p>
<p>What I've been unable to find is (no googlefu could help me):</p>
<ul>
<li><p>What are all the functions available in "<strong>kernel32</strong>"?</p>
</li>
<li><p>What are the other available (free) <strong>LIBS</strong>?</p>
</li>
<li><p>Can I make my own?</p>
</li>
</ul>
<p>I just need some pointers, ideas and/or tutorial links to point me in the right direction.</p> | 8,793,761 | 2 | 2 | null | 2012-01-06 09:37:59.54 UTC | 9 | 2020-06-27 10:30:05.633 UTC | 2020-06-27 10:30:05.633 UTC | user590715 | 8,422,953 | user590715 | null | null | 1 | 7 | excel|vba|windows-xp|excel-2003 | 14,728 | <p>What you are looking at are <strong>Windows API declarations</strong>.</p>
<p>Several popular examples include:</p>
<ul>
<li><a href="http://www.jkp-ads.com/articles/apideclarations.asp" rel="noreferrer">Declaring API functions in 64 bit Office</a> </li>
<li><a href="http://allapi.mentalis.org/apilist/apilist.php" rel="noreferrer">API List</a> </li>
<li><a href="http://www.bettersolutions.com/vba/VFD153/LA416011411.htm" rel="noreferrer">Windows APIs</a></li>
</ul>
<p>As far your specific questions:</p>
<blockquote>
<p>What are all the functions available in "kernel32"</p>
</blockquote>
<p>A DLL viewer such as <a href="http://www.nirsoft.net/utils/dll_export_viewer.html" rel="noreferrer">DLL Export Viewer</a> or <a href="http://www.activevb.de/rubriken/apiviewer/index-apiviewereng.html" rel="noreferrer">ApiViewer</a> may be useful here.</p>
<blockquote>
<p>What are the other available (free) LIBS</p>
</blockquote>
<p>See the links I posted, although I imagine there are dozens or hundreds more proprietary DLLs that we'll never find.</p>
<blockquote>
<p>Can I make my own?</p>
</blockquote>
<p>Yes, but I only have experience creating ActiveX DLLs so I can't speak to that. I did find one example, however: <a href="http://support.microsoft.com/kb/815065" rel="noreferrer">What is a DLL?</a></p> |
17,681,234 | How do I get total physical memory size using PowerShell without WMI? | <p>I'm trying to get the physical memory size using PowerShell, but without using get-wmiobject.</p>
<p>I have been using the following PS cmdlet to get the physical memory size, but the value changes with each new poll.</p>
<pre><code>(get-counter -counter "\Memory\Available Bytes").CounterSamples[0].CookedValue +
(get-counter -counter "\Memory\Committed Bytes").CounterSamples[0].CookedValue
</code></pre>
<p>In general, this gives me a value around: 8605425664 bytes</p>
<p>I'm also testing the value I get from adding these counters with the returned value from </p>
<pre><code>(get-wmiobject -class "win32_physicalmemory" -namespace "root\CIMV2").Capacity
</code></pre>
<p>This gives me the value: 8589934592 bytes</p>
<p>So, not only is the total physical memory calculated from counters changing, but it's value differs from the WMI value by a couple megabytes. Anyone have any ideas as to how to get the physical memory size without using WMI?</p> | 17,681,706 | 12 | 4 | null | 2013-07-16 15:50:19.393 UTC | 5 | 2022-09-14 05:58:19.117 UTC | 2015-10-29 02:16:00.96 UTC | null | 1,505,120 | null | 2,052,523 | null | 1 | 23 | powershell|memory|byte|wmi | 150,314 | <p>If you don't want to use WMI, I can suggest systeminfo.exe. But, there may be a better way to do that.</p>
<pre><code>(systeminfo | Select-String 'Total Physical Memory:').ToString().Split(':')[1].Trim()
</code></pre> |
18,075,343 | Java project in Eclipse: The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files | <p>I am getting the following error after importing a project in Eclipse:</p>
<blockquote>
<p>The type java.lang.Object cannot be resolved. It is indirectly referenced from required .class files</p>
</blockquote>
<p>However, I have set the path as <strong>C:\Program Files\Java\jdk1.6.0_41</strong> in Eclipse Kepler, through <strong>Window » Preferences » Java » Installed JREs</strong>.</p> | 18,075,742 | 27 | 3 | null | 2013-08-06 08:36:36.563 UTC | 48 | 2022-07-07 17:05:54.073 UTC | 2019-06-22 18:02:25.05 UTC | null | -1 | null | 2,571,430 | null | 1 | 244 | java|eclipse | 522,580 | <p>This is an annoying Eclipse Bug which seems to bite now and then. See <a href="http://dev-answers.blogspot.de/2009/06/eclipse-build-errors-javalangobject.html" rel="noreferrer">http://dev-answers.blogspot.de/2009/06/eclipse-build-errors-javalangobject.html</a> for a possible solution, otherwise try the following;</p>
<ul>
<li><p>Close the project and reopen it.</p>
</li>
<li><p>Clean the project (It will rebuild the buildpath hence reconfiguring with the JDK libraries)</p>
<p>OR</p>
</li>
<li><p>Delete and Re-import the project and if necessary do the above steps again.</p>
</li>
</ul>
<p>The better cure is to try NetBeans instead of Eclipse :-)</p> |
44,779,000 | Powershell Connection to Oracle Database | <p>I'm having trouble connecting to an Oracle database from Powershell using the <code>Oracle.ManagedDataAccess.dll</code>.</p>
<p>I followed <a href="https://blogs.technet.microsoft.com/heyscriptingguy/2012/12/04/use-oracle-odp-net-and-powershell-to-simplify-data-access/" rel="noreferrer">this</a> tutorial on Technet and ended up with this code:</p>
<pre><code>add-type -path "C:\oracle\product\12.1.0\client_1\ODP.NET\managed\common\Oracle.ManagedDataAccess.dll"
$username = "XXXX"
$password = "XXXX"
$data_source = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=XXXX)(PORT=XXXX))(CONNECT_DATA = (SERVER=dedicated)(SERVICE_NAME=XXXX)))"
$connection_string = "User Id=$username;Password=$password;Data Source=$data_source"
try{
$con = New-Object Oracle.ManagedDataAccess.Client.OracleConnection($connection_string)
$con.Open()
} catch {
Write-Error (“Can’t open connection: {0}`n{1}” -f `
$con.ConnectionString, $_.Exception.ToString())
} finally{
if ($con.State -eq ‘Open’) { $con.close() }
}
</code></pre>
<p>Unfortunately I'm getting this error:</p>
<pre><code>C:\Users\XXXX\Desktop\oracle_test.ps1 : Can’t open connection: User Id=XXXX;Password=XXXX;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=XXXX)(PORT=XXXX))(CONNECT_DATA =
(SERVER=dedicated)(SERVICE_NAME=XXXX)))
System.Management.Automation.MethodInvocationException: Exception calling "Open" with "0" argument(s): "The type initializer for 'Oracle.ManagedDataAccess.Types.TimeStamp' threw an exception." --->
System.TypeInitializationException: The type initializer for 'Oracle.ManagedDataAccess.Types.TimeStamp' threw an exception. ---> System.Runtime.Serialization.SerializationException: Unable to find assembly
'Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=XXXX'.
at OracleInternal.Common.OracleTimeZone.GetInstance()
at Oracle.ManagedDataAccess.Types.TimeStamp..cctor()
--- End of inner exception stack trace ---
at OracleInternal.ConnectionPool.PoolManager`3.CreateNewPR(Int32 reqCount, Boolean bForPoolPopulation, ConnectionString csWithDiffOrNewPwd, String instanceName)
at OracleInternal.ConnectionPool.PoolManager`3.Get(ConnectionString csWithDiffOrNewPwd, Boolean bGetForApp, String affinityInstanceName, Boolean bForceMatch)
at OracleInternal.ConnectionPool.OraclePoolManager.Get(ConnectionString csWithNewPassword, Boolean bGetForApp, String affinityInstanceName, Boolean bForceMatch)
at OracleInternal.ConnectionPool.OracleConnectionDispenser`3.Get(ConnectionString cs, PM conPM, ConnectionString pmCS, SecureString securedPassword, SecureString securedProxyPassword)
at Oracle.ManagedDataAccess.Client.OracleConnection.Open()
at CallSite.Target(Closure , CallSite , Object )
--- End of inner exception stack trace ---
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,oracle_test.ps1
</code></pre>
<ul>
<li>I have checked, that the connection string is correct (it works for <code>tnsping</code>)</li>
<li>The Username and password are correct as well</li>
<li>I replaced anything that shouldn't be disclosed with <strong>XXXX</strong></li>
<li>The database version is: <strong>Oracle Database 12c Release 12.1.0.1.0</strong></li>
<li>The error is the same for the 32-Bit and 64-Bit Powershell instances</li>
<li>Before the first run the <code>Oracle.ManagedDataAccess.dll</code> isn't loaded, after the run it stays loaded until I close that shell</li>
</ul>
<p>Unfortunately I'm neither an Oracle nor a Powershell Expert (I prefer MySQL and Python), therefore I would really appreciate any ideas and/or insights you might have.</p> | 44,804,696 | 5 | 7 | null | 2017-06-27 11:20:46.78 UTC | 5 | 2021-01-22 16:02:37.127 UTC | 2019-02-07 07:48:05.683 UTC | null | 285,795 | null | 6,485,881 | null | 1 | 9 | oracle|powershell | 54,713 | <p><em>Im not sure if this is technically a solution - I'd classify it more as a workaround, but it worked for me.</em></p>
<hr>
<p>After doing some more research I found a suitable alternative to the <code>Oracle.ManagedDataAccess.dll</code>. I found the <a href="https://msdn.microsoft.com/en-US/library/system.data.oracleclient(v=vs.110).aspx" rel="noreferrer">System.Data.OracleClient</a> class of the .Net Framework. (It requires an installed Oracle Client, which the machine fortunately has)</p>
<p>Here's an outline of the solution that worked for me:</p>
<pre><code>add-type -AssemblyName System.Data.OracleClient
$username = "XXXX"
$password = "XXXX"
$data_source = "XXXX"
$connection_string = "User Id=$username;Password=$password;Data Source=$data_source"
$statement = "select level, level + 1 as Test from dual CONNECT BY LEVEL <= 10"
try{
$con = New-Object System.Data.OracleClient.OracleConnection($connection_string)
$con.Open()
$cmd = $con.CreateCommand()
$cmd.CommandText = $statement
$result = $cmd.ExecuteReader()
# Do something with the results...
} catch {
Write-Error (“Database Exception: {0}`n{1}” -f `
$con.ConnectionString, $_.Exception.ToString())
} finally{
if ($con.State -eq ‘Open’) { $con.close() }
}
</code></pre> |
6,710,957 | Xcode 4: Keyboard shortcut for switching Assistant Editor to Tracking (Automatic) mode? | <p>I like using the Assistant Editor in Xcode 4. I frequently Option-Click files to open them in the Assistant Editor, or use Open Quickly (Command-Shift-O), and hold the option key when selecting a file to open it in the Assistant Editor.</p>
<p>Both of these actions switch the Assistant Editor to Manual mode. Is there a keyboard shortcut to switch the Assistant Editor back to Tracking mode (also called Automatic)? In tracking mode it automatically shows the counterpart, e.g. the corresponding header/implementation file for the file in your main editor. know I can select Automatic mode it with the mouse on the Assistant Editor Jump bar, but I really want a keyboard shortcut to do this. </p> | 7,028,668 | 3 | 0 | null | 2011-07-15 17:31:57.7 UTC | 21 | 2013-04-22 23:58:57.7 UTC | null | null | null | null | 155,186 | null | 1 | 27 | xcode|xcode4 | 13,696 | <p>In the View -> Assistant Editor menu, there's an item called "Reset Editor". The default keyboard shortcut is Cmd-Opt-Shift-Z. It resets the Assistant View to show Counterparts.</p>
<p>I don't know if it's new in Xcode 4.1, but it should be a little easier than AppleScripting.</p>
<p>Alternatively, you could create a behavior to reset the editor how you'd like and bind it to a keyboard shortcut.</p> |
6,911,427 | Is it possible to invoke private attributes or methods via reflection | <p>I was trying to fetch the value of an static private attribute via reflection, but it fails with an error.</p>
<pre><code>Class class = home.Student.class;
Field field = studentClass.getDeclaredField("nstance");
Object obj = field.get(null);
</code></pre>
<p>The exception I get is:</p>
<pre><code>java.lang.IllegalAccessException: Class com.test.ReflectionTest can not access a member of class home.Student with modifiers "private static".
</code></pre>
<p>Moreover, there is a private I need to invoke, with the following code.</p>
<pre><code>Method method = studentClass.getMethod("addMarks");
method.invoke(studentClass.newInstance(), 1);
</code></pre>
<p>but the problem is the Student class is a singleton class, and constructor in private, and cannot be accessed.</p> | 6,911,478 | 3 | 0 | null | 2011-08-02 11:38:37.277 UTC | 9 | 2016-05-10 17:40:01.023 UTC | 2016-05-10 17:40:01.023 UTC | user719662 | null | null | 197,831 | null | 1 | 57 | java|reflection | 42,892 | <p>You can set the field accessible:</p>
<pre><code>field.setAccessible(true);
</code></pre> |
23,515,754 | How to remove the caret from an input element | <p>How can I remove the caret from a <code><input type="text"></code> element only using CSS and not JavaScript?</p> | 23,515,887 | 2 | 3 | null | 2014-05-07 10:50:27.363 UTC | 6 | 2018-02-08 00:09:20.487 UTC | 2018-02-08 00:09:20.487 UTC | null | 8,154,765 | user3596335 | null | null | 1 | 38 | html|css|input | 71,765 | <p>Of course you can do it just with <code>CSS</code>.</p>
<p>Add this code to your CSS file:</p>
<pre><code>border: none;
color: transparent;
text-shadow: 0 0 0 gray;
text-align: center;
&:focus {
outline: none;
}
</code></pre>
<p>Here you have the <a href="https://coderwall.com/p/tsbmfw">SOURCE</a> and a <a href="http://jsfiddle.net/KvdkV/">DEMO</a></p> |
15,973,434 | Foreach in a Foreach in MVC View | <p>BIG EDIT : I have edited my full post with the answer that I came up with the help of Von V and Johannes, A BIG THANK YOU GUYS !!!!</p>
<p>I've been trying to do a foreach loop inside a foreach loop in my index view to display my products in an accordion. Let me show you how I'm trying to do this.</p>
<p>Here are my models :</p>
<pre class="lang-cs prettyprint-override"><code>public class Product
{
[Key]
public int ID { get; set; }
public int CategoryID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Path { get; set; }
public virtual Category Category { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
</code></pre>
<p>It's a <strike>one-one</strike> one-many relationship, One product has only one category but a category had many products.</p>
<p>Here is what I'm trying to do in my view :</p>
<pre class="lang-cs prettyprint-override"><code>@model IEnumerable<MyPersonalProject.Models.Product>
<div id="accordion1" style="text-align:justify">
@foreach (var category in ViewBag.Categories)
{
<h3><u>@category.Name</u></h3>
<div>
@foreach (var product in Model)
{
if (product.CategoryID == category.CategoryID)
{
<table cellpadding="5" cellspacing"5" style="border:1px solid black; width:100%;background-color:White;">
<thead>
<tr>
<th style="background-color:black; color:white;">
@product.Title
@if (System.Web.Security.UrlAuthorizationModule.CheckUrlAccessForPrincipal("/admin", User, "GET"))
{
@Html.Raw(" - ")
@Html.ActionLink("Edit", "Edit", new { id = product.ID }, new { style = "background-color:black; color:white !important;" })
}
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="background-color:White;">
@product.Description
</td>
</tr>
</tbody>
</table>
}
}
</div>
}
</div>
</code></pre>
<p>I'm not quite sure this is the right way of doing it but this is pretty much what I'm trying to do. Foreach categories, put all products of that categories inside an accordion tab.</p>
<ul>
<li>category 1</li>
<ul><li>product 1</li><li>product 3</li></ul>
<li>category 2</li>
<ul><li>product 2</li><li>product 4</li></ul>
<li>category 3</li>
<ul><li>product 5</li></ul>
</ul>
<p>Here I will add my mapping for <strike>my one-one</strike> one-many (Thanks Brian P) relationship :</p>
<pre class="lang-cs prettyprint-override"><code>public class MyPersonalProjectContext : DbContext
{
public DbSet<Product> Product { get; set; }
public DbSet<Category> Category { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Product>();
modelBuilder.Entity<Category>();
}
}
</code></pre>
<p>I will also add my controller so you can see how I did it :</p>
<pre class="lang-cs prettyprint-override"><code>public ActionResult Index()
{
ViewBag.Categories = db.Category.OrderBy(c => c.Name).ToList();
return View(db.Product.Include(c => c.Category).ToList());
}
</code></pre>
<p>BIG EDIT : I have edited my full post with the answer that I came up with the help of Von V and Johannes, A BIG THANK YOU GUYS !!!!</p> | 15,973,853 | 4 | 4 | null | 2013-04-12 14:05:19.803 UTC | 2 | 2016-11-16 13:43:05.737 UTC | 2013-04-12 19:28:30.713 UTC | null | 2,157,220 | null | 2,157,220 | null | 1 | 10 | c#|asp.net|asp.net-mvc|entity-framework|asp.net-mvc-4 | 149,754 | <p>Assuming your controller's action method is something like this:</p>
<pre><code>public ActionResult AllCategories(int id = 0)
{
return View(db.Categories.Include(p => p.Products).ToList());
}
</code></pre>
<p>Modify your models to be something like this:</p>
<pre><code>public class Product
{
[Key]
public int ID { get; set; }
public int CategoryID { get; set; }
//new code
public virtual Category Category { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Path { get; set; }
//remove code below
//public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
[Key]
public int CategoryID { get; set; }
public string Name { get; set; }
//new code
public virtual ICollection<Product> Products{ get; set; }
}
</code></pre>
<p>Then your since now the controller takes in a Category as Model (instead of a Product):</p>
<pre><code>foreach (var category in Model)
{
<h3><u>@category.Name</u></h3>
<div>
<ul>
@foreach (var product in Model.Products)
{
// cut for brevity, need to add back more code from original
<li>@product.Title</li>
}
</ul>
</div>
}
</code></pre>
<p>UPDATED: Add ToList() to the controller return statement.</p> |
19,114,328 | Managing a user password for linux in puppet | <p>I need to create a test user with a password using puppet.</p>
<p>I've read that puppet cannot manage user passwords in a generic cross-platform way, which is a pity.
I am doing this for Red Hat Enterprise Linux Server release 6.3.</p>
<p>I do as follows:</p>
<pre><code>user { 'test_user':
ensure => present,
password => sha1('hello'),
}
</code></pre>
<p>puppet updates the password of the user,
but Linux says login/pwd incorrect when I try to log in.</p>
<p>It works (I can login) if I set the password manually in Linux with <code>sudo passwd test_user</code>, and then look at <code>/etc/shadow</code> and hardcode that value in puppet. something like:</p>
<pre><code>user { 'test_user':
ensure => present,
password => '$1$zi13KdCr$zJvdWm5h552P8b34AjxO11',
}
</code></pre>
<p>I've tried also by adding <code>$1$</code> in front of the <code>sha1('hello')</code>,
but it does not work either (note, <code>$1$</code> stands for sha1).</p>
<p>How to modify the first example to make it work (using the plaintext password in the puppet file)?</p>
<p>P.S.: I am aware that I should use LDAP, or sshkeys, or something else, instead of hardcoding the user passwords in the puppet file. however, I am doing this only for running a puppet vagrant test, so it is ok to hardcode the user password.</p> | 24,883,231 | 8 | 2 | null | 2013-10-01 10:52:47.473 UTC | 19 | 2019-10-08 13:09:11.277 UTC | 2019-10-08 13:09:11.277 UTC | null | 6,370,924 | null | 280,393 | null | 1 | 38 | linux|puppet | 54,340 | <p><a href="https://gist.github.com/pschyska/26002d5f8ee0da2a9ea0">I had success (gist)</a> with ruby's String#crypt method from within a Puppet parser function.</p>
<p>AFAICS it's using the crypt libc functions (see: <code>info crypt</code>), and takes the same arguments <code>$n$[rounds=<m>$]salt</code>, where n is the hashing function ($6 for SHA-512) and m is the number of key strengthening rounds (5000 by default).</p> |
18,969,083 | assignment operator vs. copy constructor C++ | <p>I have the following code to test out my understanding of basic pointers in C++:</p>
<pre><code>// Integer.cpp
#include "Integer.h"
Integer::Integer()
{
value = new int;
*value = 0;
}
Integer::Integer( int intVal )
{
value = new int;
*value = intVal;
}
Integer::~Integer()
{
delete value;
}
Integer::Integer(const Integer &rhInt)
{
value = new int;
*value = *rhInt.value;
}
int Integer::getInteger() const
{
return *value;
}
void Integer::setInteger( int newInteger )
{
*value = newInteger;
}
Integer& Integer::operator=( const Integer& rhInt )
{
*value = *rhInt.value;
return *this;
}
// IntegerTest.cpp
#include <iostream>
#include <cstdlib>
#include "Integer.h"
using namespace std;
void displayInteger( char* str, Integer intObj )
{
cout << str << " is " << intObj.getInteger() << endl;
}
int main( int argc, char* argv[] )
{
Integer intVal1;
Integer intVal2(10);
displayInteger( "intVal1", intVal1 );
displayInteger( "intVal2", intVal2 );
intVal1 = intVal2;
displayInteger( "intVal1", intVal1 );
return EXIT_SUCCESS;
}
</code></pre>
<p>This code works exactly as expected as is, it prints out:</p>
<pre><code>intVal1 is 0
intVal2 is 10
intVal1 is 10
</code></pre>
<p>However if I remove the copy constructor it prints out something like:</p>
<pre><code>intVal1 is 0
intVal2 is 10
intVal1 is 6705152
</code></pre>
<p>I don't understand why this is the case. My understanding is that the copy constructor is used when the assignment is to an object that doesn't exist. Here <code>intVal1</code> does exist, so why isn't the assignment operator called?</p> | 18,969,190 | 3 | 2 | null | 2013-09-23 21:19:10.613 UTC | 9 | 2014-09-16 10:05:41.46 UTC | 2013-09-23 21:52:37.547 UTC | null | 1,168,156 | null | 1,818,443 | null | 1 | 20 | c++|pointers|memory-management|copy-constructor | 21,479 | <p>The copy constructor is not used during assignment. Copy constructor in your case is used when passing arguments to <code>displayInteger</code> function. The second parameter is passed by value, meaning that it is initailized by copy contructor.</p>
<p>Your version of copy constructor performs <em>deep</em> copying of data owned by the class (just like your assignment operator does). So, everything works correctly with your version of copy constructor.</p>
<p>If you remove your own copy constructor, the compiler will generate one for you implicitly. The compiler-generated copy constructor will perform <em>shallow</em> copying of the object. This will violate the <a href="https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three">"Rule of Three"</a> and destroy the functionality of your class, which is exactly what you observe in your experiment. Basically, the first call to <code>displayInteger</code> damages your <code>intVal1</code> object and the second call to <code>displayInteger</code> damages your <code>intVal2</code> object. After that both of your objects are broken, which is why the third <code>displayInteger</code> call displays garbage.</p>
<p>If you change the declaration of <code>displayInteger</code> to</p>
<pre><code>void displayInteger( char* str, const Integer &intObj )
</code></pre>
<p>your code will "work" even without an explicit copy constructor. But it is not a good idea to ignore the <a href="https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three">"Rule of Three"</a> in any case. A class implemented in this way either has to obey the "Rule of Three" or has to be made non-copyable.</p> |
19,267,979 | ng-click not working from dynamically generated HTML | <p><strong>HTML</strong></p>
<pre><code><table data-ng-table="tableParams" class="table table-bordered table-hover " style="border-collapse:collapse" data-ng-init="host.editSave = false" >
<tr id="newTransaction">
</tr>
<tr data-ng-repeat="host in hosts|filter:search:strict" >
<td class="hostTableCols" data-ng-hide="host.editSave">{{host.hostCd}}</td>
<td class="hostTableCols" data-ng-hide="host.editSave">{{host.hostName}}</td>
</tr>
</table>
</code></pre>
<p><strong>Jquery</strong></p>
<pre><code>$('#newTransaction').append(
'<td contenteditable><input type="text" class="editBox" value=""/></td>'+
'<td contenteditable><input type="text" class="editBox" value=""/></td>'+
'<td>'+
'<span>'+
'<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>'+
'</span>'+
'</td>'
);
</code></pre>
<p><strong>Angular Script</strong></p>
<pre><code>$scope.create = function() {
alert("Hi");
};
</code></pre>
<p>Here the function called in the controller part of the AngularJS is not getting trigger from the ng-click event. The Html is getting appended successfully, but the ng-click is not working. Tell me solutions to make it work</p> | 19,268,415 | 5 | 3 | null | 2013-10-09 09:25:18.99 UTC | 9 | 2017-04-12 06:54:40.847 UTC | null | null | null | null | 2,365,712 | null | 1 | 49 | jquery|html|angularjs | 72,207 | <p>Not a perfect fix, still!!! - just to show how dynamic compilation can be done</p>
<pre><code>app.controller('AppController', function ($scope, $compile) {
var $el = $('<td contenteditable><input type="text" class="editBox" value=""/></td>' +
'<td contenteditable><input type="text" class="editBox" value=""/></td>' +
'<td>' +
'<span>' +
'<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>' +
'</span>' +
'</td>').appendTo('#newTransaction');
$compile($el)($scope);
$scope.create = function(){
console.log('clicked')
}
})
</code></pre>
<p>Demo: <a href="http://jsfiddle.net/arunpjohny/udmcv/" rel="noreferrer">Fiddle</a></p>
<p><strong>Don't use controller for dom manipulation - it has to be done with the help of directives</strong></p> |
27,761,543 | How do I display large numbers with commas? HTML | <p>I am wanting to display large numbers more nicely with commas. So if the number was say 123456789, it would display 123,456,789. I have looked around but I only found code that just wouldn't work the way I wanted so I was hoping I could find some help here. Also, I hope it is also dynamic, so the commas will change as the number changes.</p>
<p>The number that I want to affect has the id="value".</p>
<p>That should be all, I don't think I am missing anything. So again I want the number with an id="value" to have commas introduced when it's needed. If you need any more information please let me know!</p> | 27,761,572 | 3 | 2 | null | 2015-01-04 01:46:25.85 UTC | 9 | 2018-04-03 12:31:23.67 UTC | null | null | null | null | 4,024,353 | null | 1 | 27 | html | 86,186 | <p>This was answered here:</p>
<p><a href="https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript">How to print a number with commas as thousands separators in JavaScript</a></p>
<p>In case you're not interested in reading the answer above, the code given was this:</p>
<pre><code>function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
</code></pre>
<p>If you're using jquery use something like:</p>
<pre><code>var val = parseInt($('#value').text());
//Use the code in the answer above to replace the commas.
val = numberWithCommas(val);
$('#value').text(val);
</code></pre> |
5,429,947 | Supporting resumable HTTP-downloads through an ASHX handler? | <p>We are providing downloads of our application setups through an ASHX handler in ASP.NET.</p>
<p>A customer told us he uses some third party download manager application and that our way of providing the files currently does not support the "resume" feature of his download manager application.</p>
<p><strong>My questions are:</strong></p>
<p>What are the basic ideas behind resuming a download? Is there a certain HTTP GET request that tells me the offset to start at?</p> | 5,430,113 | 2 | 0 | null | 2011-03-25 08:07:10.363 UTC | 9 | 2016-07-14 09:14:59.933 UTC | null | null | null | null | 107,625 | null | 1 | 10 | asp.net|download|ashx|download-manager | 9,226 | <p>Resuming a download usually works through the HTTP <code>Range</code> header. For example, if a client wants only the second kilobyte of a file, it might send the header <code>Range: bytes=1024-2048</code>.</p>
<p>You can see page 139 of <a href="http://www.ietf.org/rfc/rfc2616.txt" rel="nofollow">the RFC for HTTP/1.1</a> for more information.</p> |
16,207,758 | how to check out from svn using Eclipse | <p>I am using Eclipse for PHP Developers Version: 3.0.2. How could I check out from a remote svn(TortoiseSVN). I googled online, but it did help, I tried to import, but there is no such option as 'from svn'.</p> | 16,207,797 | 3 | 0 | null | 2013-04-25 06:21:41.837 UTC | null | 2019-01-26 19:18:24.543 UTC | 2013-04-25 06:25:13.893 UTC | null | 1,233,836 | null | 2,294,256 | null | 1 | 3 | eclipse|svn|tortoisesvn | 47,702 | <ol>
<li>Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Insturctions <a href="http://subclipse.tigris.org/install.html" rel="noreferrer">here</a> </li>
<li>Go to <code>File->New->Other->Under the SVN category</code>, select Checkout Projects from SVN.</li>
<li>Select your project's root folder and select checkout as a project in the workspace.</li>
</ol>
<p>For more details take a look for <a href="http://www.ibm.com/developerworks/opensource/library/os-ecl-subversion/" rel="noreferrer">How to use Subversion with Eclipse</a></p> |
221,455 | Ghostscript PDF -> TIFF conversion is awful for me, people rave about it, I alone look sullen | <p>My stomach churns when I see this kind of output.</p>
<p><a href="http://www.freeimagehosting.net/uploads/e1097a5a10.jpg" rel="nofollow noreferrer">http://www.freeimagehosting.net/uploads/e1097a5a10.jpg</a></p>
<p>and this was my command
as suggested by <a href="https://stackoverflow.com/questions/75500/best-way-to-convert-pdf-files-to-tiff-files#221341">Best way to convert pdf files to tiff files</a></p>
<pre><code>gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif a.pdf -c quit
</code></pre>
<p>What am I doing wrong?</p>
<p>(commercial products will not be considered)</p> | 221,504 | 7 | 2 | null | 2008-10-21 10:56:14.05 UTC | 11 | 2020-12-07 08:04:34.033 UTC | 2017-05-23 10:31:24.007 UTC | Ates Goral | -1 | Setori | 21,537 | null | 1 | 11 | pdf|image-manipulation|tiff|ghostscript | 50,450 | <p>tiffg4 is a black&white output device.
You should use tiff24nc or tiff12nc as the output device colour PDFs - see <a href="http://pages.cs.wisc.edu/~ghost/doc/AFPL/8.00/Devices.htm#TIFF" rel="noreferrer">ghostscript output devices</a>.
These will be uncompressed but you could put the resulting TIFFs through imagemagick or similar to resave as compressed TIFF.</p> |
919,136 | Subtracting one row of data from another in SQL | <p>I've been stumped with some SQL where I've got several rows of data, and I want to subtract a row from the previous row and have it repeat all the way down.</p>
<p>So here is the table:</p>
<pre>CREATE TABLE foo (
id,
length
)</pre>
<pre>INSERT INTO foo (id,length) VALUES(1,1090)
INSERT INTO foo (id,length) VALUES(2,888)
INSERT INTO foo (id,length) VALUES(3,545)
INSERT INTO foo (id,length) VALUES(4,434)
INSERT INTO foo (id,length) VALUES(5,45)</pre>
<p>I want the results to show a third column called difference which is one row subtracting from the one below with the final row subtracting from zero.</p>
<pre>
+------+------------------------+
| id |length | difference |
+------+------------------------+
| 1 | 1090 | 202 |
| 2 | 888 | 343 |
| 3 | 545 | 111 |
| 4 | 434 | 389 |
| 5 | 45 | 45 |</pre>
<p>I've tried a self join but I'm not exactly sure how to limit the results instead of having it cycle through itself. I can't depend that the id value will be sequential for a given result set so I'm not using that value. I could extend the schema to include some kind of sequential value.</p>
<p>This is what I've tried:</p>
<pre>SELECT id, f.length, f2.length, (f.length - f2.length) AS difference
FROM foo f, foo f2</pre>
<p>Thank you for the assist.</p> | 919,151 | 7 | 1 | null | 2009-05-28 04:09:12.723 UTC | 4 | 2017-09-27 18:41:25.037 UTC | 2009-05-28 04:36:20.15 UTC | null | 18,255 | null | 113,521 | null | 1 | 12 | sql|mysql|join|subtraction | 62,779 | <p>This might help you (somewhat).</p>
<pre>
<code>
select a.id, a.length,
coalesce(a.length -
(select b.length from foo b where b.id = a.id + 1), a.length) as diff
from foo a
</code>
</pre> |
1,192,004 | Specific down-sides to many-'small'-assemblies? | <p>I am planning out some work to introduce Dependency Injection into what is currently a large monolithic library in an attempt to make the library easier to unit-test, easier to understand, and possibly more flexible as a bonus.</p>
<p>I have decided to use <a href="http://ninject.org/" rel="noreferrer">NInject</a>, and I really like Nate's motto of 'do one thing, do it well' (paraphrased), and it seems to go particularly well within the context of DI.</p>
<p>What I have been wondering now, is whether I should split what is currently a single large assembly into multiple smaller assemblies with disjoint feature sets. Some of these smaller assemblies will have inter-dependencies, but far from all of them, because the architecture of the code is pretty loosely coupled already.</p>
<p>Note that these feature sets are not trivial and small unto themselves either... it encompasses things like client/server communications, serialisation, custom collection types, file-IO abstractions, common routine libraries, threading libraries, standard logging, etc.</p>
<p>I see that a previous question: <a href="https://stackoverflow.com/questions/568780/what-is-better-many-small-assemblies-or-one-big-assembly">What is better, many small assemblies, or one big assembly?</a> kind-of addresses this issue, but with what seems to be even finer granularity that this, which makes me wonder if the answers there still apply in this case?</p>
<p>Also, in the various questions that skirt close to this topic a common answer is that having 'too many' assemblies has caused unspecified 'pain' and 'problems'. I would really like to know concretely what the possible down-sides of this approach could be.</p>
<p>I agree that adding 8 assemblies when before only 1 was needed is 'a bit of a pain', but having to include a big monolithic library for every application is also not exactly ideal... plus adding the 8 assemblies is something you do only once, so I have very little sympathy for that argument (even tho I would probably complain along with everyone else at first).</p>
<p><strong>Addendum:</strong><br>
So far I have seen no convinging reasons against smaller assemblies, so I think I will proceed for now as if this is a non-issue. If anyone can think of good solid reasons with verifiable facts to back them up I would still be very interested to hear about them. (I'll add a bounty as soon as I can to increase visibility)</p>
<p><strong>EDIT:</strong> Moved the performance analysis and results into a separate answer (see below).</p> | 1,215,043 | 7 | 0 | null | 2009-07-28 05:00:58.107 UTC | 12 | 2009-08-02 05:23:58.957 UTC | 2017-05-23 12:26:24.367 UTC | null | -1 | null | 111,781 | null | 1 | 23 | .net|dependency-injection|ninject | 3,682 | <p>I will give you a real-world example where the use of many (very) small assemblies has produced .Net DLL Hell. </p>
<p>At work we have a large homegrown framework that is long in the tooth (.Net 1.1). Aside from usual framework type plumbing code (including logging, workflow, queuing, etc), there were also various encapsulated database access entities, typed datasets and some other business logic code. I wasn't around for the initial development and subsequent maintenance of this framework, but did inherit it's use. As I mentioned, this entire framework resulted in numerous small DLLs. And, when I say numerous, we're talking upwards of 100 -- not the managable 8 or so you've mentioned. Further complicating matters were that the assemblies were all stronly-signed, versioned and to appear in the GAC. </p>
<p>So, fast-forward a few years and a number of maintenance cycles later, and what's happened is that the inter dependencies on the DLLs and the applications they support has wreaked havoc. On every production machine is a huge assembly redirect section in the machine.config file that ensures that "correct" assembly get's loaded by Fusion no matter what assembly is requested. This grew out of the difficulty that was encountered to rebuild every dependent framework and application assembly that took a dependency on one that was modified or upgraded. Great pains (usually) were taken to ensure that no breaking changes were made to assemblies when they were modified. The assemblies were rebuilt and a new or updated entry was made in the machine.config. </p>
<p>Here's were I will pause to listen to the sound of a huge collective groan and gasp!</p>
<p>This particular scenario is the poster-child for what not to do. Indeed in this situation, you get into a completely unmaintainable situation. I recall it took me 2 days to get my machine setup for development against this framework when I first started working with it -- resolving differences between my GAC and a runtime environment's GAC, machine.config assembly redirects, version conflicts at compile time due to incorrect references or, more likely, version conflict due to direct referencing component A and component B, but component B referenced component A, but a different version than my application's direct reference. You get the idea.</p>
<p>The real problem with this specific scenario is that the assembly contents were far too granular. And, this is ultimately what caused the tangled web of inter dependencies. My thoughts are that the initial architects thought this would create a system of highly maintainable code -- only having to rebuild very small changes to components of the system. In fact, the opposite was true. Further, to some of the other answers posted here already, when you get to this number of assemblies, loading a ton of assemblies does incur a performance hit -- definitely during resolution, and I would guess, though I have no empirical evidence, that runtime might suffer in some edge case situations, particularly where reflection might come into play -- could be wrong on that point.</p>
<p>You'd think I'd be scorned, but I believe there are logic physical separations for assemblies -- and when I say "assemblies" here, I am assuming one assembly per DLL. What it all boils down to are the inter dependencies. If I have an assembly A that depends on assembly B, I always ask myself if I'll ever have the need to reference assembly B with out assembly A. Or, is there a benefit to that separation. Looking at how assemblies are referenced is usually a good indicator as well. If you were to divide your large library in assemblies A, B, C, D and E. If you referenced assembly A 90% of the time and because of that, you always had to reference assembly B and C because A was dependent on them, then it's likely a better idea that assemblies A, B and C be combined, unless there's a really compelling argument to allow them to remain separated. Enterprise Library is classic example of this where you've nearly always got to reference 3 assemblies in order to use a single facet of the library -- in the case of Enterprise Library, however, the ability to build on top of core functionality and code reuse are the reason for it's architecture. </p>
<p>Looking at architecture is another good guideline. If you have a nice cleanly stacked architecture, where your assembly dependencies are int the form of a stack, say "vertical", as opposed to a "web", which starts to form when you have dependencies in every direction, then separation of assemblies on functional boundaries makes sense. Otherwise, look to roll things into one or look to re-architect.</p>
<p>Either way, good luck!</p> |
50,371 | Better Merge Tool for Subversion | <p>Is there a good external merge tool for tortoisesvn (I don't particularly like the built in Merge tool). I use WinMerge for diffs, but it doesn't work with the three way merge (maybe a better question would be is there a way to force tortoisesvn to merge like tortoisecvs?)</p>
<p>[Edit]</p>
<p>After trying all of them, for me, the SourceGear is the one I prefer. The way to specify the DiffMerge from sourcegear is:</p>
<blockquote>
<p>C:\Program Files\SourceGear\DiffMerge\DiffMerge.exe /t1="My Working Version" /t2="Repository Version" /t3="Base" /r=%merged %mine %theirs %base</p>
</blockquote> | 50,407 | 7 | 2 | null | 2008-09-08 18:32:13.503 UTC | 18 | 2017-05-18 12:05:38.967 UTC | 2013-05-22 10:34:34.05 UTC | Kris Erickson | 107,625 | Kris Erickson | 3,798 | null | 1 | 58 | svn|tortoisesvn | 34,776 | <p>Take a look at <a href="http://www.sourcegear.com/diffmerge/" rel="nofollow noreferrer">Sourcegear DiffMerge</a>. DiffMerge is the compare and merge tool from their Vault and Fortress products, but they make it available for free as a standalone tool. One noteworthy feature is that it allows diffing of entire directory trees.</p>
<p><strong>Edit:</strong> While DiffMerge remains a free tool, it nags for registration with a popup at least once a day (since at least version 4.2). It also states in the popup:</p>
<blockquote>
<p>Select new features in future releases will also require registration,
but core features and fixes will be available to everyone.</p>
</blockquote> |
441,631 | How to detect right mouse click + paste using JavaScript? | <p>Is there a way to detect a right click followed by paste with JavaScript on IE and Firefox ?</p>
<p>Update:</p>
<p>I decided to use Jquery to do it:</p>
<pre><code>$('#controlId').bind('paste', null, function() {
// code
});
</code></pre>
<p>It's not exactly what I was looking (because it gets fired on 'ctrl + v' as well as in 'right click + paste' but I can work around it.</p>
<p>Tested it on Chrome, Firefox 3, IE 7 and IE 6 and it's working</p> | 441,647 | 8 | 4 | null | 2009-01-14 01:51:51.887 UTC | 18 | 2019-12-18 21:59:41.197 UTC | 2009-01-15 01:06:31.933 UTC | Rismo | 1,560 | Rismo | 1,560 | null | 1 | 47 | javascript|jquery | 49,366 | <p>With IE you have onpaste</p>
<p>With Mozilla you can look into
oninput
and</p>
<pre><code>elementReference.addEventListener("DOMCharacterDataModified", function(e){ foo(e);}, false);
</code></pre>
<p>There is no easy as pie solution.</p>
<p>Eric</p> |
1,255,099 | What's the proper use of printf to display pointers padded with 0s | <p>In C, I'd like to use printf to display pointers, and so that they line up properly, I'd like to pad them with 0s.</p>
<p>My guess was that the proper way to do this was:</p>
<pre>printf("%016p", ptr);</pre>
<p>This works, but this gcc complains with the following message:</p>
<pre>warning: '0' flag used with ‘%p’ gnu_printf format</pre>
<p>I've googled a bit for it, and the following thread is on the same topic, but doesn't really give a solution.</p>
<p><a href="http://gcc.gnu.org/ml/gcc-bugs/2003-05/msg00484.html" rel="noreferrer">http://gcc.gnu.org/ml/gcc-bugs/2003-05/msg00484.html</a></p>
<p>Reading it, it seems that the reason why gcc complains is that the syntax I suggested is not defined in C99. But I can't seem to find any other way to do the same thing in a standard approved way.</p>
<p>So here is the double question:</p>
<ul>
<li>Is my understanding correct that this behavior is not defined by the C99 standard?
<li>If so, is there a standard approved, portable way of doing this?
</ul> | 1,255,185 | 9 | 1 | null | 2009-08-10 14:08:53.21 UTC | 10 | 2018-01-17 19:14:46.093 UTC | null | null | null | Florian | null | null | 1 | 46 | c|pointers|printf|c99 | 38,713 | <p><code>#include <inttypes.h></code></p>
<p><code>#include <stdint.h></code></p>
<p><code>printf("%016" PRIxPTR "\n", (uintptr_t)ptr);</code></p>
<p>but it won't print the pointer in the implementation defined way (says <code>DEAD:BEEF</code> for 8086 segmented mode).</p> |
212,999 | Continuous Integration for Xcode projects? | <p>After using Hudson for continuous integration with a prior project, I want to set up a continuous integration server for the iPhone projects I'm working on now. After doing some research it looks like there aren't any CI engines designed specifically for Xcode, but one guy has had success <a href="http://www.pragmaticautomation.com/cgi-bin/pragauto.cgi/Build/XcodeOnCC.rdoc" rel="noreferrer">using Cruise Control combined with the xcodebuild CLI tool</a>. Has anyone here tried this? Are there any CI engines that work well with Xcode projects?</p>
<p>I'm probably going to give Cruise Control a try. I'll post an answer with my findings.</p> | 1,182,726 | 9 | 2 | null | 2008-10-17 17:10:44.25 UTC | 53 | 2016-05-05 13:36:17.73 UTC | null | null | null | Mike Akers | 17,188 | null | 1 | 56 | iphone|xcode|continuous-integration|cruisecontrol|xcodebuild | 21,652 | <p>I'm successfully using Hudson on the mac with xcodebuild. With the release of the 3.0 iPhone sdk you have compete control over the target, configuration and sdk that the project is to be built against. </p>
<p>It's as simple as creating a build step in hudson and telling xcodebuild to build the project:</p>
<pre><code>xcodebuild -target "myAppAppStore" -configuration "DistributionAppStore" -sdk iphoneos2.1
</code></pre>
<p>The upfront work has paid off for me as my builds just work without any additional thought. I've written a detailed description on my blog if anyone is interested.</p>
<p><a href="http://silent-code.blogspot.com/2009/07/iphone-app-distribution-made-easy-part.html" rel="nofollow noreferrer">iPhone app distribution made easy</a></p> |
720,856 | Database design for point in time "snapshot" of data? | <p>How to design a database that supports a feature that would allow the application user to create a snapshot of their data at a point in time, a bit like version control.</p>
<p>It would give the user the ability to go back and see what their data looked like in the past.</p>
<p>Assume that the data being "snapshotted" is complex and includes joins of multiple tables.</p>
<p>I'm looking for a way to give each application user the ability to snapshot their data and go back to it. Whole database snapshots is not what I'm looking for.</p>
<p>EDIT: Thanks for your answers. The 6NF answer is compelling as is the suggestion to de-normalise the snapshot data due to its simplicity.</p>
<p>Clarification: this is not a data warehousing question, nor is it a question about DB backup and restore; its about how to build a schema that allows us to capture the state of a specific set of related data at a point in time. The snapshots are generated by the application users when they see fit. Users do not snapshot the entire DB, just the data object they are interested in.</p> | 720,968 | 10 | 2 | null | 2009-04-06 09:57:50.91 UTC | 13 | 2019-03-07 04:31:40.837 UTC | 2009-04-07 01:35:44.993 UTC | null | 30,246 | null | 30,246 | null | 1 | 24 | database-design | 17,714 | <p>We did this once by creating separate database tables that contained the data we wanted to snapshot, but denormalized, i.e. every record contained all data required to make sense, not references to id's that may or may no longer exist. It also added a date to each row.</p>
<p>Then we produced triggers for specific inserts or updates that did a join on all affected tables, and inserted it into the snapshot tables.</p>
<p>This way it would be trivial to write something that restored the users' data to a point in time.</p>
<p>If you have a table:</p>
<p>user:</p>
<pre><code>id, firstname, lastname, department_id
</code></pre>
<p>department:</p>
<pre><code>id, name, departmenthead_id
</code></pre>
<p>your snapshot of the user table could look like this:</p>
<pre><code>user_id, user_firstname, user_lastname, department_id, department_name, deparmenthead_id, deparmenthead_firstname, departmenthead_lastname, snapshot_date
</code></pre>
<p>and a query something like</p>
<pre><code>INSERT INTO usersnapshot
SELECT user.id AS user_id, user.firstname AS user_firstname, user.lastname AS user_lastname,
department.id AS department_id, department.name AS department_name
departmenthead.id AS departmenthead_id, departmenthead.firstname AS departmenthead_firstname, departmenthead.lastname AS departmenthead_lastname,
GETDATE() AS snapshot_date
FROM user
INNER JOIN department ON user.department_id = department.id
INNER JOIN user departmenthead ON department.departmenthead_id = departmenthead.id
</code></pre>
<p>This ensures each row in the snapshot is true for that moment in time, even if department or department head has changed in the meantime.</p> |
421,046 | What are all of the allowable characters for people's names? | <p>There are the standard A-Z, a-z characters, but also there are hyphens, em dashes, quotes, etc.</p>
<p>Plus, there are all of the international characters, like umlauts, etc.</p>
<p>So, for an English-based system, what's the complete set? What about sets for other languages? What about UTF8, UTF16, etc?</p>
<p>Bonus question: How many name fields are needed, and what are their maximum lengths?</p>
<p><strong>EDIT:</strong> There are definitely two different types of characters involved in people's names, those that are there as part of the context, and those that are there for structural reasons. I don't want to limit or interfere with the context characters, but I do need to deal with the structural ones. </p>
<p>For example, I had a name come in that was separated by an em dash, but it was hard to distinguish that from the minus character. To make the system easier for searching, I want to take all five different types of dashes, and map them onto one unique character (minus), that way the searcher doesn't need to know specifically which symbol was initially entered. </p>
<p>The problem exists for dashes, probably quotes as well, but also how many other symbols?</p> | 421,073 | 10 | 7 | null | 2009-01-07 16:42:41.663 UTC | 18 | 2018-08-06 15:27:52.343 UTC | 2012-05-04 19:51:15.05 UTC | yogman | 285,587 | Paul W Homer | 43,371 | null | 1 | 58 | character-encoding|character|names | 100,451 | <p>There's good article by the W3C called <a href="http://www.w3.org/International/questions/qa-personal-names" rel="noreferrer">Personal names around the world</a> that explains the problems (and possible solutions) pretty well (it was originally a two-part blog post by Richard Ishida: <a href="https://r12a.github.io/blog/200610#20070709" rel="noreferrer">part 1</a> and <a href="https://r12a.github.io/blog/200707#20070716" rel="noreferrer">part 2</a>)</p>
<p>Personally I'd say: support every printable Unicode-Character and to be safe provide just a single field "name" that contains the full, formatted name. This way you can store pretty much every form of name. You might need a more structured storage, but then don't expect to be able to store every single combination in a structured form, as there are simply too many different ones.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.