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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
40,259,178 | How to retry image pull in a kubernetes Pods? | <p>I am new to kubernetes. I have an issue in the pods. When I run the command</p>
<pre><code> kubectl get pods
</code></pre>
<p>Result:</p>
<pre><code>NAME READY STATUS RESTARTS AGE
mysql-apim-db-1viwg 1/1 Running 1 20h
mysql-govdb-qioee 1/1 Running 1 20h
mysql-userdb-l8q8c 1/1 Running 0 20h
wso2am-default-813fy 0/1 ImagePullBackOff 0 20h
</code></pre>
<p>Due to an issue of "wso2am-default-813fy" node, I need to restart it. Any suggestion? </p> | 40,259,759 | 8 | 0 | null | 2016-10-26 09:58:46.143 UTC | 27 | 2021-04-26 09:56:29.033 UTC | 2018-08-16 08:43:02.377 UTC | null | 169,545 | null | 5,996,099 | null | 1 | 104 | docker|kubernetes|coreos | 109,979 | <p>Usually in case of "ImagePullBackOff" it's retried after few seconds/minutes. In case you want to try again manually you can delete the old pod and recreate the pod. The one line command to delete and recreate the pod would be:</p>
<pre><code>kubectl replace --force -f <yml_file_describing_pod>
</code></pre> |
10,777,271 | Python using enumerate inside list comprehension | <p>Lets suppose I have a list like this:</p>
<pre><code>mylist = ["a","b","c","d"]
</code></pre>
<p>To get the values printed along with their index I can use Python's <code>enumerate</code> function like this</p>
<pre><code>>>> for i,j in enumerate(mylist):
... print i,j
...
0 a
1 b
2 c
3 d
>>>
</code></pre>
<p>Now, when I try to use it inside a <code>list comprehension</code> it gives me this error</p>
<pre><code>>>> [i,j for i,j in enumerate(mylist)]
File "<stdin>", line 1
[i,j for i,j in enumerate(mylist)]
^
SyntaxError: invalid syntax
</code></pre>
<p>So, my question is: what is the correct way of using enumerate inside list comprehension?</p> | 10,777,287 | 7 | 0 | null | 2012-05-27 21:03:37.023 UTC | 47 | 2019-07-29 13:21:35.28 UTC | 2012-08-21 22:45:50.177 UTC | null | 1,267,329 | null | 776,084 | null | 1 | 140 | python|list|iteration|list-comprehension | 275,340 | <p>Try this:</p>
<pre><code>[(i, j) for i, j in enumerate(mylist)]
</code></pre>
<p>You need to put <code>i,j</code> inside a tuple for the list comprehension to work. Alternatively, given that <code>enumerate()</code> <em>already</em> returns a tuple, you can return it directly without unpacking it first:</p>
<pre><code>[pair for pair in enumerate(mylist)]
</code></pre>
<p>Either way, the result that gets returned is as expected:</p>
<pre><code>> [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
</code></pre> |
33,328,739 | System.Environment.OSVersion returns wrong version | <p>Using windows 10, upgraded from windows 8 => 8.1 => 10 When I use this code.</p>
<pre><code>OperatingSystem os = System.Environment.OSVersion;
</code></pre>
<p>The os.Version = {6.2.9200.0} System.Version</p>
<p>I read this was because of the version it was <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx" rel="noreferrer" title="manifested for">manifested for</a> but I do not understand what that means.</p>
<p>I want the correct OS version because I am logging a user agent string on a web service, and want to correctly identify the windows version for support. what is the easiest way to get that to correctly report the correct version?</p> | 33,328,814 | 4 | 0 | null | 2015-10-25 10:41:57.303 UTC | 5 | 2021-04-22 13:26:44.59 UTC | 2017-11-14 04:58:11.727 UTC | null | 2,130,976 | null | 1,490,306 | null | 1 | 36 | c# | 13,230 | <p>Windows 10 returns that string unless you declare that your application is compatible using a manifest. To do so add an <code>app.manifest</code> (right click your project -> Add -> New Item -> Application Manifest File) then uncomment the following line:</p>
<pre><code><supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</code></pre>
<p>You can do the same thing for Windows Vista to Windows 10. All are in the same section:</p>
<pre><code><application>
<!-- A list of the Windows versions that this application has been tested on and is
is designed to work with. Uncomment the appropriate elements and Windows will
automatically selected the most compatible environment. -->
<!-- Windows Vista -->
<!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
<!-- Windows 7 -->
<!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->
<!-- Windows 8 -->
<!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
<!-- Windows 8.1 -->
<!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</code></pre>
<p>And now when you run your application it'll report the correct 10.0.*.0 version</p> |
31,452,451 | Importing an svg file into a matplotlib figure | <p>I like to produce high quality plots and therefore avoid rasterized graphics as much as possible. </p>
<p>I am trying to import an svg file on to a matplotlib figure:</p>
<pre><code>import matplotlib.pyplot as plt
earth = plt.imread('./gfx/earth.svg')
fig, ax = plt.subplots()
im = ax.imshow(earth)
plt.show()
</code></pre>
<p>This works with png perfectly. Can somebody tell me how to do it with svg or at least point my to proper documentation. </p>
<p>I know that a similar question has been asked (but not answered): <a href="https://stackoverflow.com/questions/12161559/plot-svg-within-matplotlib-figure-embedded-in-wxpython">here</a>. Has anything changed since?</p>
<p>P.S. I know that I could just export a high resolution png and achieve a similar effect. This is not the solution I am looking for.</p>
<p>Here is the image I would like to import: </p>
<p><a href="https://upload.wikimedia.org/wikipedia/commons/a/a0/Worldmap_northern.svg" rel="noreferrer"><img src="https://upload.wikimedia.org/wikipedia/commons/a/a0/Worldmap_northern.svg" alt="Earth_from_above"></a> .</p> | 41,924,687 | 3 | 1 | null | 2015-07-16 11:06:58.5 UTC | 13 | 2022-07-30 21:10:48.573 UTC | 2020-01-15 03:54:15.787 UTC | null | 10,659,910 | null | 959,888 | null | 1 | 27 | python|matplotlib|svg|python-imaging-library | 23,283 | <p>Maybe what you are looking for is <a href="https://pypi.python.org/pypi/svgutils" rel="noreferrer">svgutils</a> </p>
<pre><code>import svgutils.compose as sc
from IPython.display import SVG # /!\ note the 'SVG' function also in svgutils.compose
import numpy as np
# drawing a random figure on top of your SVG
fig, ax = plt.subplots(1, figsize=(4,4))
ax.plot(np.sin(np.linspace(0,2.*np.pi)), np.cos(np.linspace(0,2.*np.pi)), 'k--', lw=2.)
ax.plot(np.random.randn(20)*.3, np.random.randn(20)*.3, 'ro', label='random sampling')
ax.legend()
ax2 = plt.axes([.2, .2, .2, .2])
ax2.bar([0,1], [70,30])
plt.xticks([0.5,1.5], ['water ', ' ground'])
plt.yticks([0,50])
plt.title('ratio (%)')
fig.savefig('cover.svg', transparent=True)
# here starts the assembling using svgutils
sc.Figure("8cm", "8cm",
sc.Panel(sc.SVG("./Worldmap_northern.svg").scale(0.405).move(36,29)),
sc.Panel(sc.SVG("cover.svg"))
).save("compose.svg")
SVG('compose.svg')
</code></pre>
<p>Output:</p>
<p><a href="https://i.stack.imgur.com/ckXg5.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ckXg5.png" alt="enter image description here"></a></p> |
41,177,965 | AWS Lambda:The provided execution role does not have permissions to call DescribeNetworkInterfaces on EC2 | <p>Today I have a new AWS Lambda question, and can't find anywhere in Google.</p>
<p>I new a Lambda function, there is no question.
But when I input any code in this function[eg. console.log();] and click "Save", error is occured:
"The provided execution role does not have permissions to call DescribeNetworkInterfaces on EC2" </p>
<pre><code>exports.handler = (event, context, callback) => {
callback(null, 'Hello from Lambda');
console.log(); // here is my code
};
</code></pre>
<p>I bound the function with Role: lambda_excute_execution(Policy:AmazonElasticTranscoderFullAccess)
And this function is not bound with any triggers now.</p>
<p>And then, I give the role "AdministratorAccess" Policy, I can save my source code correctly.</p>
<p>This role can run Functions successfully before today.</p>
<p>Is anyone know this error?</p>
<p>Thanks Very much!</p> | 54,668,725 | 10 | 0 | null | 2016-12-16 05:45:18.63 UTC | 15 | 2022-07-26 19:58:04.67 UTC | 2016-12-16 14:25:13.76 UTC | null | 13,070 | null | 6,070,417 | null | 1 | 139 | amazon-web-services|aws-lambda|amazon-iam|policy|role | 115,888 | <p>This error is common if you try to deploy a Lambda in a VPC without giving it the required network interface related permissions <code>ec2:DescribeNetworkInterfaces</code>, <code>ec2:CreateNetworkInterface</code>, and <code>ec2:DeleteNetworkInterface</code> (see <a href="https://forums.aws.amazon.com/message.jspa?messageID=756727" rel="noreferrer">AWS Forum</a>).</p>
<p>For example, this a policy that allows to deploy a Lambda into a VPC:</p>
<pre><code>{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeNetworkInterfaces",
"ec2:CreateNetworkInterface",
"ec2:DeleteNetworkInterface",
"ec2:DescribeInstances",
"ec2:AttachNetworkInterface"
],
"Resource": "*"
}
]
}
</code></pre> |
52,068,066 | How do you use "NextToken" in AWS API calls | <p>I've run into a little issue that I am really struggling to understand how it works. I have a tool I am writing that basically does a describe-organization to collect all the accounts in our AWS organization. Per the documentation <a href="https://boto3.readthedocs.io/en/latest/reference/services/organizations.html#Organizations.Client.list_accounts" rel="noreferrer">here</a> it says it responds with a json of the accounts which in my case will be hundreds and hundreds of accounts. So I wrote some very simple code to switch roles into our master account and make the call:</p>
<pre><code>import boto3
import uuid
import pprint
iam_client = boto3.client('iam')
sts_client = boto3.client('sts')
org_client = boto3.client('organizations')
print("Starting in account: %s" % sts_client.get_caller_identity().get('Account'))
assumedRoleObject = sts_client.assume_role(
RoleArn="arn:aws:iam::123456xxx:role/MsCrossAccountAccessRole",
RoleSessionName="MasterPayer"
)
credentials = assumedRoleObject['Credentials']
org_client = boto3.client(
'organizations',
aws_access_key_id = credentials['AccessKeyId'],
aws_secret_access_key = credentials['SecretAccessKey'],
aws_session_token = credentials['SessionToken'],
)
getListAccounts = org_client.list_accounts(
NextToken='string'
)
</code></pre>
<p>But when I execute the code, I get the following error:</p>
<p>"botocore.errorfactory.InvalidInputException: An error occurred (InvalidInputException) when calling the ListAccounts operation: You specified an invalid value for nextToken. You must get the value from the response to a previous call to the API."</p>
<p>I'm really stumped on what that means. I see the NextToken, and I can find many references to it in the AWS documentation but I can't figure out how to actually USE it. Like, what do I need to do with it? </p> | 52,068,477 | 7 | 1 | null | 2018-08-29 00:57:14.65 UTC | 4 | 2022-08-09 01:15:05.72 UTC | null | null | null | null | 6,373,504 | null | 1 | 28 | python|amazon-web-services|boto3|aws-organizations | 30,010 | <p>Don't take the boto3 examples literally (they are not actual examples). Here is how this works:</p>
<p>1) The first time you make a call to <code>list_accounts</code> you'll do it without the <code>NextToken</code>, so simply </p>
<pre><code>getListAccounts = org_client.list_accounts()
</code></pre>
<p>2) This will return a JSON response which looks roughly like this (this is what is saved in your <code>getListAccounts</code> variable): </p>
<pre><code>{
"Accounts": [<lots of accounts information>],
"NextToken": <some token>
}
</code></pre>
<p>Note that the <code>NextToken</code> is only returned in case you have more accounts than one <code>list_accounts</code> call can return, usually this is <code>100</code> (the boto3 documentation does not state how many by default). If all accounts were returned in one call there is no <code>NextToken</code> in the response!</p>
<p>3) So if and only if not all accounts were returned in the first call you now want to return more accounts and you will have to use the <code>NextToken</code> in order to do this: </p>
<pre><code>getListAccountsMore = org_client.list_accounts(NextToken=getListAccounts['NextToken'])
</code></pre>
<p>4) Repeat until no <code>NextToken</code> is returned in the response anymore (then you retrieved all accounts).</p>
<p>This is how the AWS SDK handles pagination in many cases. You will see the usage of the <code>NextToken</code> in other service clients as well.</p> |
21,258,250 | SQL How to Update only first Row | <p>I'm working with PostgreSQL.
I have table with some elements. In last column there is 'Y' or 'N' letter. I need command which Select only first that match (I mean where last column is 'N') and change it on 'Y'.</p>
<p>My idea:</p>
<pre><code>UPDATE Table SET Checked='Y'
WHERE (SELECT Checked FROM Table WHERE Checked='N' ORDER BY ID LIMIT 1) = 'N'
</code></pre>
<p>But it changes 'N' to 'Y' in every row.</p> | 21,258,303 | 4 | 0 | null | 2014-01-21 12:32:06.14 UTC | 2 | 2019-06-04 10:18:53.89 UTC | 2015-08-31 10:14:25.777 UTC | null | 336,648 | null | 2,965,257 | null | 1 | 15 | sql|postgresql | 60,401 | <p>Here is query</p>
<pre><code>UPDATE Table SET Checked='Y'
WHERE ID =(SELECT ID FROM Table WHERE Checked='N' ORDER BY ID LIMIT 1)
</code></pre> |
21,280,803 | Using VBA to apply conditional formatting to a range of cells | <p>I would like to know how to access the column in conditional formatting titled 'Applies To' and input my own conditions.
I have included a screenshot for better reference.</p>
<p><img src="https://i.stack.imgur.com/mSZaR.png" alt="Applies To column"></p>
<p>My code for adding the syntax in conditional formatting is,</p>
<pre><code>With Selection
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, Formula1:="=" & c.Address & "=TRUE"
.
.
.
End With
</code></pre>
<p>I believe the code should be added in there but i just cannot find the correct syntax.</p>
<p><strong>Update :</strong></p>
<p>I updated my code to look like this,</p>
<pre><code>With Range(Cells(c.Row, "B"), Cells(c.Row, "N"))
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, Formula1:="=" & c.Address
.FormatConditions(1).Interior.ColorIndex = 15 'change for other color when ticked
End With
</code></pre>
<p>This would essentially make rows of a specific range relevant to where i placed the checkbox, have their background colour changed.
The checkbox position is represented by c.Address where 'c' contains the location of the cell that i selected to place my checkbox.</p> | 21,281,162 | 2 | 1 | null | 2014-01-22 10:49:29.563 UTC | 1 | 2016-10-19 17:37:21.837 UTC | 2016-10-19 17:37:21.837 UTC | null | 4,949,483 | null | 1,796,386 | null | 1 | 11 | vba|excel|conditional-formatting | 80,685 | <p>You need to do something like this (<code>Range("A25")</code> is exactly what you are going to find):</p>
<pre><code>With Range("A25")
.FormatConditions.Delete
.FormatConditions.Add Type:=xlExpression, _
Formula1:="=" & c.Address
'.
'.
'.
End With
</code></pre>
<p>and there is no need to write <code>"=" & c.Address & "=TRUE"</code>, you can use just <code>"=" & c.Address</code>.</p> |
21,571,709 | Difference between machine language, binary code and a binary file | <p>I'm studying programming and in many sources I see the concepts: "machine language", "binary code" and "binary file". The distinction between these three is unclear to me, because according to my understanding machine language means the raw language that a computer can understand i.e. sequences of 0s and 1s. </p>
<p>Now if machine language is a sequence of 0s and 1s and binary code is also a sequence of 0s and 1s then does <strong>machine language = binary code</strong>?</p>
<p>What about binary file? What really is a binary file? To me the word "binary file" means a file, which consists of binary code. So for example, if my file was:</p>
<pre><code>010010101010010
010010100110100
010101100111010
010101010101011
010101010100101
010101010010111
</code></pre>
<p>Would this be a binary file? If I google binary file and see <a href="http://en.wikipedia.org/wiki/Binary_file" rel="noreferrer">Wikipedia</a> I see this example picture of binary file which confuses me (it's not in binary?....)</p>
<p><img src="https://i.stack.imgur.com/686wZ.png" alt="Hex image"></p>
<p>Where is my confusion happening? Am I mixing file encoding here or what? If I were to ask one to SHOW me what is machine language, binary code and binary file, what would they be? =) I guess the distinction is too abstract to me.</p>
<p>Thnx for any help! =)</p>
<p><strong>UPDATE</strong>: </p>
<p>In Python for example, there is one phrase in a file I/O <a href="http://www.tutorialspoint.com/python/python_files_io.htm" rel="noreferrer">tutorial</a>, which I don't understand: <strong>Opens a file for reading only in binary format.</strong> What does reading a file in binary format mean?</p> | 21,578,250 | 4 | 0 | null | 2014-02-05 08:05:40.7 UTC | 18 | 2018-09-13 17:07:24.24 UTC | 2014-02-05 08:17:48.547 UTC | null | 1,565,754 | null | 1,565,754 | null | 1 | 29 | encoding|binary | 39,823 | <p>Machine code and binary are the same - a number system with base 2 - either a 1 or 0. <strong>But machine code can also be expressed in hex-format <em>(hexadecimal)</em> - a number system with base 16</strong>. The binary system and hex are very interrelated with each other, its easy to convert from binary to hex and convert back from hex to binary. And because hex is much more readable and useful than binary - it's often used and shown. For instance in the picture above in your question -uses hex-numbers!</p>
<p>Let say you have the binary sequence 1001111000001010 - it can easily be converted to hex by grouping in blocks - each block consisting of four bits. </p>
<pre><code> 1001 1110 0000 1010 => 9 14 0 10 which in hex becomes: 9E0A.
</code></pre>
<p>One can agree that 9E0A is much more readable than the binary - and hex is what you see in the image.</p> |
30,142,107 | Python: "Print" and "Input" in one line | <p>If I'd like to put some input in between a text in python, how can I do it without, after the user has input something and pressed enter, switching to a new line?</p>
<p>E.g.:</p>
<pre><code>print "I have"
h = input()
print "apples and"
h1 = input()
print "pears."
</code></pre>
<p>Should be modified as to output to the console in one line saying:</p>
<pre><code>I have h apples and h1 pears.
</code></pre>
<p>The fact that it should be on one line has no deeper purpose, it is hypothetical and I'd like it to look that way.</p> | 37,653,832 | 3 | 1 | null | 2015-05-09 16:01:17.013 UTC | 3 | 2016-06-06 09:25:36.36 UTC | 2015-05-09 17:35:57.74 UTC | null | 1,884,961 | null | 4,856,605 | null | 1 | 4 | python|input|printing|line | 43,415 | <p>If I understand correctly, what you are trying to do is get input without echoing the newline. If you are using Windows, you could use the msvcrt module's getwch method to get individual characters for input without printing anything (including newlines), then print the character if it isn't a newline character. Otherwise, you would need to define a getch function:</p>
<pre><code>import sys
try:
from msvcrt import getwch as getch
except ImportError:
def getch():
"""Stolen from http://code.activestate.com/recipes/134892/"""
import tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
def input_():
"""Print and return input without echoing newline."""
response = ""
while True:
c = getch()
if c == "\b" and len(response) > 0:
# Backspaces don't delete already printed text with getch()
# "\b" is returned by getch() when Backspace key is pressed
response = response[:-1]
sys.stdout.write("\b \b")
elif c not in ["\r", "\b"]:
# Likewise "\r" is returned by the Enter key
response += c
sys.stdout.write(c)
elif c == "\r":
break
sys.stdout.flush()
return response
def print_(*args, sep=" ", end="\n"):
"""Print stuff on the same line."""
for arg in args:
if arg == inp:
input_()
else:
sys.stdout.write(arg)
sys.stdout.write(sep)
sys.stdout.flush()
sys.stdout.write(end)
sys.stdout.flush()
inp = None # Sentinel to check for whether arg is a string or a request for input
print_("I have", inp, "apples and", inp, "pears.")
</code></pre> |
48,700,453 | Docker image build with PHP zip extension shows "bundled libzip is deprecated" warning | <p>I have a <code>Dockerfile</code> with a build command like this:</p>
<pre><code>#install some base extensions
RUN apt-get install -y \
zlib1g-dev \
zip \
&& docker-php-ext-install zip
</code></pre>
<p>I get this warning from build output:</p>
<blockquote>
<p>WARNING: Use of bundled libzip is deprecated and will be removed.<br>
configure: WARNING: Some features such as encryption and bzip2 are not available.<br>
configure: WARNING: Use system library and --with-libzip is
recommended.</p>
</blockquote>
<p>What is the correct way to install the zip extension without these warnings?</p>
<p>My complete Dockerfile looks like:</p>
<pre><code>FROM php:7.2-apache
RUN apt-get clean
RUN apt-get update
#install some basic tools
RUN apt-get install -y \
git \
tree \
vim \
wget \
subversion
#install some base extensions
RUN apt-get install -y \
zlib1g-dev \
zip \
&& docker-php-ext-install zip
#setup composer
RUN curl -sS https://getcomposer.org/installer | php \
&& mv composer.phar /usr/local/bin/ \
&& ln -s /usr/local/bin/composer.phar /usr/local/bin/composer
WORKDIR /var/www/
</code></pre> | 48,700,777 | 7 | 2 | null | 2018-02-09 07:09:12.813 UTC | 9 | 2022-04-26 11:28:51.1 UTC | 2018-02-09 07:44:33.023 UTC | null | 962,603 | null | 416,100 | null | 1 | 70 | php|docker|php-extension|libzip | 85,809 | <p>It <a href="https://externals.io/message/98731" rel="noreferrer">looks like</a> PHP no longer bundles <a href="https://libzip.org/" rel="noreferrer">libzip</a>. You need to <a href="https://github.com/docker-library/php/issues/61" rel="noreferrer">install it</a>. You install <code>zlib1g-dev</code>, but instead install <code>libzip-dev</code>. This installs <code>zlib1g-dev</code> as a dependency and allows the <code>configure</code> script to detect that <code>libzip</code> is installed.</p>
<p>For PHP < 7.3, you then need to</p>
<pre class="lang-none prettyprint-override"><code>docker-php-ext-configure zip --with-libzip
</code></pre>
<p>before performing the installation with </p>
<pre class="lang-none prettyprint-override"><code>docker-php-ext-install zip
</code></pre>
<p>as the last warning indicates.</p>
<p>In short: change the relevant part of your Dockerfile to</p>
<p><strong>For PHP < 7.3</strong></p>
<pre class="lang-none prettyprint-override"><code>#install some base extensions
RUN apt-get install -y \
libzip-dev \
zip \
&& docker-php-ext-configure zip --with-libzip \
&& docker-php-ext-install zip
</code></pre>
<p><strong>For PHP >= 7.3</strong></p>
<pre class="lang-none prettyprint-override"><code>#install some base extensions
RUN apt-get install -y \
libzip-dev \
zip \
&& docker-php-ext-install zip
</code></pre>
<p>I have verified that this builds as expected.</p>
<p> </p>
<hr>
<p> </p>
<p>In case you are not using the Docker <a href="https://hub.docker.com/_/php" rel="noreferrer">PHP base image</a>, things may be much easier. For example, for Alpine the following Dockerfile will get you PHP 7 with the zip extension installed.</p>
<pre class="lang-none prettyprint-override"><code>FROM alpine:latest
RUN apk update && apk upgrade
RUN apk add php7 php7-zip composer
</code></pre> |
8,467,700 | How do I merge results from target page to current page in scrapy? | <p>Need example in scrapy on how to get a link from one page, then follow this link, get more info from the linked page, and merge back with some data from first page.</p> | 8,468,824 | 4 | 0 | null | 2011-12-11 21:38:08.333 UTC | 14 | 2019-06-26 19:17:02.62 UTC | 2019-06-26 19:17:02.62 UTC | null | 2,099,607 | null | 345,859 | null | 1 | 21 | python|web-scraping|scrapy | 10,120 | <p>Partially fill your item on the first page, and the put it in your request's meta. When the callback for the next page is called, it can take the partially filled request, put more data into it, and then return it.</p> |
8,978,080 | htaccess exclude one url from Basic Auth | <p>I need to exclude one Url (or even better one prefix) from normal htaccess Basic Auth protection. Something like <code>/callbacks/myBank</code> or <code>/callbacks/.*</code>
Do you have any hints how to do it?</p>
<p>What I'm not looking for is how to exclude a file.
This has to be url (as this is solution based on PHP framework, and all urls are redirected with <code>mod_rewrite</code> to <code>index.php</code>). So there is no file under this URL. Nothing.</p>
<p>Some of those urls are just callbacks from other services (No IP is not known so I cannot exclude based on IP) and they cannot prompt for User / Password.</p>
<p>Current definition is as simple as:</p>
<pre class="lang-sh prettyprint-override"><code>AuthName "Please login."
AuthGroupFile /dev/null
AuthType Basic
AuthUserFile /xxx/.htpasswd
require valid-user
</code></pre> | 33,655,232 | 8 | 0 | null | 2012-01-23 20:26:26.967 UTC | 25 | 2019-04-05 13:04:02.453 UTC | 2019-04-05 13:04:02.453 UTC | null | 1,163,470 | null | 1,163,470 | null | 1 | 83 | apache|.htaccess|authorization | 95,479 | <p>If you are using Apache 2.4, <code>SetEnvIf</code> and mod_rewrite workarounds are no longer necessary since the <code>Require</code> directive is able to interpret expressions directly:</p>
<pre class="lang-sh prettyprint-override"><code>AuthType Basic
AuthName "Please login."
AuthUserFile "/xxx/.htpasswd"
Require expr %{REQUEST_URI} =~ m#^/callbacks/.*#
Require valid-user
</code></pre>
<p>Apache 2.4 treats <code>Require</code> directives that are <em>not</em> grouped by <code><RequireAll></code> as if they were in a <code><RequireAny></code>, which behaves as an "or" statement. Here's a more complicated example that demonstrates matching both the request URI and the query string together, and falling back on requiring a valid user:</p>
<pre class="lang-sh prettyprint-override"><code>AuthType Basic
AuthName "Please login."
AuthUserFile "/xxx/.htpasswd"
<RequireAny>
<RequireAll>
# I'm using the alternate matching form here so I don't have
# to escape the /'s in the URL.
Require expr %{REQUEST_URI} =~ m#^/callbacks/.*#
# You can also match on the query string, which is more
# convenient than SetEnvIf.
#Require expr %{QUERY_STRING} = 'secret_var=42'
</RequireAll>
Require valid-user
</RequireAny>
</code></pre>
<p>This example would allow access to <code>/callbacks/foo?secret_var=42</code> but require a username and password for <code>/callbacks/foo</code>.</p>
<p>Remember that unless you use <code><RequireAll></code>, Apache will attempt to match each <code>Require</code> <strong>in order</strong> so think about which conditions you want to allow first.</p>
<p>The reference for the <code>Require</code> directive is here: <a href="https://httpd.apache.org/docs/2.4/mod/mod_authz_core.html#require" rel="noreferrer">https://httpd.apache.org/docs/2.4/mod/mod_authz_core.html#require</a></p>
<p>And the <code>expr</code>ession reference is here: <a href="https://httpd.apache.org/docs/2.4/expr.html" rel="noreferrer">https://httpd.apache.org/docs/2.4/expr.html</a></p> |
57,335,980 | ChangeNotifierProvider vs ChangeNotifierProvider.value | <p>I am quite new to this framework and working on state management using provider package where I come across <code>ChangeNotifierProvider</code> and <code>ChangeNotifierProvider.value</code>, but I am unable to distinguish their use case.</p>
<p>I had used <code>ChangeNotifierProvider</code> in place of <code>ChangeNotifierProvider.value</code>, but it doesn't work as intended. </p> | 61,861,315 | 5 | 0 | null | 2019-08-03 06:24:56.027 UTC | 7 | 2020-12-31 00:54:26.533 UTC | 2020-05-18 02:05:36.617 UTC | null | 3,681,880 | null | 8,354,049 | null | 1 | 41 | flutter|frameworks|provider|state-management | 22,968 | <p>Let's take this in steps.</p>
<h2>What is ChangeNotifier?</h2>
<p>A class that extends <code>ChangeNotifier</code> can call <code>notifyListeners()</code> any time data in that class has been updated and you want to let a listener know about that update. This is often done in a view model to notify the UI to rebuild the layout based on the new data.</p>
<p>Here is an example:</p>
<pre><code>class MyChangeNotifier extends ChangeNotifier {
int _counter = 0;
int get counter => _counter;
void increment() {
_counter++;
notifyListeners();
}
}
</code></pre>
<p>I wrote more about this in <a href="https://medium.com/flutter-community/a-beginners-guide-to-architecting-a-flutter-app-1e9053211a74" rel="noreferrer">A beginner’s guide to architecting a Flutter app</a>.</p>
<h2>What is ChangeNotifierProvider?</h2>
<p><code>ChangeNotifierProvider</code> is one of <a href="https://medium.com/flutter-community/making-sense-all-of-those-flutter-providers-e842e18f45dd" rel="noreferrer">many types of providers</a> in the <a href="https://pub.dev/packages/provider" rel="noreferrer">Provider package</a>. If you already have a ChangeNotifier class (like the one above), then you can use <code>ChangeNotifierProvider</code> to provide it to the place you need it in the UI layout.</p>
<pre><code>class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<MyChangeNotifier>( // define it
create: (context) => MyChangeNotifier(), // create it
child: MaterialApp(
...
child: Consumer<MyChangeNotifier>( // get it
builder: (context, myChangeNotifier, child) {
...
myChangeNotifier.increment(); // use it
</code></pre>
<p>Note in particular that a new instance of the MyChangeNotifier class was created in this line:</p>
<pre><code>create: (context) => MyChangeNotifier(),
</code></pre>
<p>This is done one time when the widget is first built, and not on subsequent rebuilds.</p>
<h2>What is ChangeNotifierProvider.value for then?</h2>
<p>Use <code>ChangeNotifierProvider.value</code> if you have already created an instance of the <code>ChangeNotifier</code> class. This type of situation might happen if you had initialized your <code>ChangeNotifier</code> class in the <code>initState()</code> method of your <code>StatefulWidget</code>'s <code>State</code> class.</p>
<p>In that case, you wouldn't want to create a whole new instance of your <code>ChangeNotifier</code> because you would be wasting any initialization work that you had already done. Using the <code>ChangeNotifierProvider.value</code> constructor allows you to provide your pre-created <code>ChangeNotifier</code> value.</p>
<pre><code>class _MyWidgeState extends State<MyWidge> {
MyChangeNotifier myChangeNotifier;
@override
void initState() {
myChangeNotifier = MyChangeNotifier();
myChangeNotifier.doSomeInitializationWork();
super.initState();
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider<MyChangeNotifier>.value(
value: myChangeNotifier, // <-- important part
child: ...
</code></pre>
<p>Take special note that there isn't a <code>create</code> parameter here, but a <code>value</code> parameter. That's where you pass in your <code>ChangeNotifier</code> class instance. Again, don't try to create a new instance there.</p>
<p>You can also find the usage of <code>ChangeNotifierProvider</code> and <code>ChangeNotifierProvider.value</code> described in the official docs: <a href="https://pub.dev/packages/provider#exposing-a-value" rel="noreferrer">https://pub.dev/packages/provider#exposing-a-value</a></p> |
47,777,783 | Selenium missing or invalid 'entry.level' Error | <p>I'm trying to run a selenium test which should work just fine (hasn't changed and used to work) but I'm getting this strange error.</p>
<pre><code>System.InvalidOperationException : unknown error: cannot determine loading status
from unknown error: missing or invalid 'entry.level'
(Session info: chrome=63.0.3239.84)
(Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9eed),platform=Windows NT 10.0.15063 x86_64)
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse) in c:\Projects\WebDriver\trunk\dotnet\src\WebDriver\Remote\RemoteWebDriver.cs:line 1015
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters) in c:\Projects\WebDriver\trunk\dotnet\src\WebDriver\Remote\RemoteWebDriver.cs:line 849
at OpenQA.Selenium.Remote.RemoteWebElement.Click() in c:\Projects\WebDriver\trunk\dotnet\src\WebDriver\Remote\RemoteWebElement.cs:line 337
...
</code></pre>
<p>What is this "missing or invalid 'entry.level'" error and how do I fix it?</p> | 47,777,823 | 4 | 1 | null | 2017-12-12 16:55:20.18 UTC | 2 | 2018-03-13 07:25:20.553 UTC | 2018-01-09 21:22:50.403 UTC | null | 7,432 | null | 2,668,545 | null | 1 | 33 | selenium|selenium-chromedriver | 31,411 | <p>I resolved this by updating my chrome driver to the latest version (v2.34 at the time of writing).</p>
<p>You can get the chromedriver here: <a href="https://sites.google.com/a/chromium.org/chromedriver/downloads" rel="noreferrer">https://sites.google.com/a/chromium.org/chromedriver/downloads</a></p>
<p>just download the .exe file then replace the chromedriver file in your project's selenium/bin folder.</p> |
27,300,001 | Is out there any REST API for TFS 2013 On-Premises installation? | <p>We use company Team Foundation Server 2013 for source code and task management. Is there a way how can I manipulate work items within backlog over REST API?</p>
<p>Our project is accessible via web url: <a href="https://tfs.company.com/tfs/ProjectCollection/Project" rel="nofollow noreferrer">https://tfs.company.com/tfs/ProjectCollection/Project</a></p>
<p>I have found this: <a href="https://tfsodata.visualstudio.com/" rel="nofollow noreferrer">https://tfsodata.visualstudio.com/</a> but this seems to work only for projects within <a href="https://visualstudio.com" rel="nofollow noreferrer">https://visualstudio.com</a>.</p>
<p>I would appreciate also some examples.</p>
<p>Thanks!</p> | 27,307,352 | 2 | 1 | null | 2014-12-04 17:16:42.353 UTC | 8 | 2021-05-03 15:22:07.067 UTC | 2018-09-11 21:41:34.77 UTC | null | -1 | null | 1,212,547 | null | 1 | 14 | tfs-sdk|azure-devops-rest-api | 11,937 | <p>Not in any officially supported manner.</p>
<p>That said, it doesn't take too much exploring to see that some of the APIs are already present in TFS 2013 already.</p>
<p>For example, if you're using TFS2013.4, try sending a GET to https://{yourserver}/defaultcollection/_apis/git/repositories?api-version=1.0 and see what the result is.</p>
<p>Examples of using the REST API for on-premise, when they do turn up, will be all but identical to the <a href="http://www.visualstudio.com/integrate/get-started/get-started-rest-basics-vsi" rel="nofollow noreferrer">Visual Studio Team Services REST API documentation</a>.</p>
<p>P.S. I'm not sure if the work item APIs are there yet. I get 404's when calling the work item specific API URLs.</p>
<p><strong>UPDATE:</strong> TFS2015 has now been released and it includes the full REST APIs from Visual Studio Team Services.</p> |
64,874,221 | Property has no initializer and is not definitely assigned in the constructor | <p>I am getting an error when I give</p>
<pre class="lang-ts prettyprint-override"><code>export class UserComponent implements OnInit {
user: User;
constructor() { }
ngOnInit() {
this.user = {
firstName : "test",
lastName : "test",
age : 40,
address: {
street : "Test",
city : "test",
state: "test"
}
}
}
}
</code></pre>
<p>I am getting this error (see <a href="https://i.stack.imgur.com/ngZS4.png" rel="nofollow noreferrer">image 1</a>):</p>
<pre class="lang-none prettyprint-override"><code>Property 'user' has no initializer and is not definitely assigned in the constructor.
</code></pre>
<p><code>user</code> is instantiated from <code>User</code> which is declared in User.ts by this code:</p>
<pre class="lang-ts prettyprint-override"><code>export interface User {
firstName: string,
lastName: string,
age?: number,
address?: {
street?: string,
city?: string,
state?: string
}
}
</code></pre>
<p>If I add a question mark (<code>?</code>) to <code>user</code>, another error appears in some other file (see <a href="https://i.stack.imgur.com/pBRwY.png" rel="nofollow noreferrer">image 2</a>):</p>
<pre class="lang-none prettyprint-override"><code>Error occurs in the template of component UserComponent.
src/app/components/users/users.component.html:2:44 -
error TS2532: Object is possibly 'undefined'.
2 <ul class="list-unstyled" *ngIf="loaded && users?.length > 0">
~~~~~~~~~~~~~~~~~
</code></pre> | 64,993,163 | 4 | 8 | null | 2020-11-17 11:17:46.033 UTC | 13 | 2022-07-15 14:27:32.163 UTC | 2022-07-15 14:27:32.163 UTC | null | 1,951,524 | user14653534 | null | null | 1 | 33 | angular|typescript | 59,916 | <p>This is caused by TypeScript's Strict Class Initialization.</p>
<p><a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#strict-class-initialization" rel="noreferrer">https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#strict-class-initialization</a></p>
<p>To resolve this issue you must either declare that the type can be both Foo|undefined, or utilize the '!' symbol to indicate definite assignment as per the above documentation:</p>
<p>Case 1:</p>
<pre class="lang-js prettyprint-override"><code>@Component({...})
export class Component {
@Input() myInput: string|undefined;
}
</code></pre>
<p>We indicate that the type may be either a string or undefined.</p>
<p>Case 2:</p>
<pre class="lang-js prettyprint-override"><code>@Component({...})
export class Component {
@Input() myInput!: string;
}
</code></pre>
<p>In this case we utilize the ! symbol to indicate that we are aware that <code>myInput</code> is not initialized in the constructor and we will handle it elsewhere.</p>
<h2>Alternate Solution</h2>
<p>If you do not care about strict class initialization, you can disable the feature completely in your <code>tsconfig.json</code> by adding a flag to your compiler options</p>
<pre class="lang-json prettyprint-override"><code>{
"compilerOptions": {
"strictPropertyInitialization": false
}
}
</code></pre>
<p><strong>Note:</strong> You will have to restart the TypeScript server for the compilerOptions to be reapplied. The easiest way to achieve this is to simply restart your IDE.</p> |
884,928 | Two-legged OAuth - looking for information | <p>I want to implement a new REST-based <a href="http://en.wikipedia.org/wiki/Application_programming_interface" rel="noreferrer">API</a> on our infrastructure, and <a href="http://en.wikipedia.org/wiki/OAuth" rel="noreferrer">OAuth</a> seems to be the way to go.</p>
<p>For our implementation, there will first just be server-to-server access, which will be completely unrestricted. I believe this is called two-legged authorization.</p>
<p>Later on, we'd like to allow the API to be consumed by the browser, which will turn our authorization into three-legged.</p>
<p>Is there a good starting point for implementing this? How can we fully authorize a server and down the road add restricted authorization per-user?</p>
<p>The OAuth specification is not really helpful in these scenarios, but I believe this implies we need to create a never-expiring session for the server-to-server access, and later on add normal sessions with limited access for user-only APIs.</p>
<p>I'm hoping to find starting points for more information, let me know!</p>
<p>Is OAuth for me? I'm only looking for a authenticated request system, and only the consumer and service provider exist in this scenario. The end-user does not come in to play!</p> | 978,072 | 3 | 0 | null | 2009-05-19 20:46:56.513 UTC | 12 | 2012-08-22 19:46:35.03 UTC | 2012-08-22 19:37:09.19 UTC | null | 63,550 | null | 80,911 | null | 1 | 26 | web-services|rest|oauth | 12,540 | <p>OAuth will end up being too difficult for our needs. I've decided to adopt Amazon S3's authentication scheme, simply because it fits our model better.</p>
<p>Thanks for helping out finding an answer though.. </p> |
1,085,524 | How to count the number of lines in an Objective-C string (NSString)? | <p>I want to count the lines in an NSString in Objective-C.</p>
<pre><code> NSInteger lineNum = 0;
NSString *string = @"abcde\nfghijk\nlmnopq\nrstu";
NSInteger length = [string length];
NSRange range = NSMakeRange(0, length);
while (range.location < length) {
range = [string lineRangeForRange:NSMakeRange(range.location, 0)];
range.location = NSMaxRange(range);
lineNum += 1;
}
</code></pre>
<p>Is there an easier way?</p> | 1,085,560 | 3 | 0 | null | 2009-07-06 05:14:14.38 UTC | 6 | 2018-06-14 10:13:12.857 UTC | 2011-11-21 11:14:31.54 UTC | user557219 | null | null | 76,509 | null | 1 | 28 | objective-c|cocoa|newline|enumeration | 17,342 | <p>well, a not very efficient, but nice(ish) looking way is</p>
<pre><code>NSString *string = @"abcde\nfghijk\nlmnopq\nrstu";
NSInteger length = [[string componentsSeparatedByCharactersInSet:
[NSCharacterSet newlineCharacterSet]] count];
</code></pre>
<p><strong>Swift 4:</strong></p>
<pre><code>myString.components(separatedBy: .newlines)
</code></pre> |
39,724,161 | Angular 2, set default value to select option | <p>I try to add a default value to an option. It will be like a kind of placeholder and I use <a href="https://stackoverflow.com/questions/5805059/how-do-i-make-a-placeholder-for-a-select-box">this method</a> to do it.
In pure HTML it work, but if I try to use <code>*ngFor</code> of angular 2 attribute, it doesn't select anything.</p>
<p>Here my code that I use in pure HTML:</p>
<pre><code> <select name="select-html" id="select-html">
<option value="0" selected disabled>Select Language</option>
<option value="1">HTML</option>
<option value="2">PHP</option>
<option value="3">Javascript</option>
</select>
</code></pre>
<p>And using Angular template:</p>
<pre><code> <select name="select" id="select" [(ngModel)]="selectLanguage">
<option *ngFor="let item of selectOption"
[selected]="item.value==0"
[disabled]="item.value==0">{{item.label}}</option>
</select>
</code></pre>
<p>The class is</p>
<pre><code>import {Component} from '@angular/core';
@Component({
moduleId: module.id,
selector: 'app-form-select',
templateUrl: 'default.component.html'
})
export class DefaultComponent {
private selectOption: any;
constructor() {
this.selectOption = [
{
id: 1,
label: "Select Language",
value: 0
}, {
id: 2,
label: "HTML 5",
value: 1
}, {
id: 3,
label: "PHP",
value: 2
}, {
id: 4,
label: "Javascript",
value: 3
}
]
}
}
</code></pre>
<p>I want <code>Select Language</code>to be selected as a default value. It's disabled but not selected.</p>
<p>How can I select it as a default value?</p>
<p><strong><a href="http://plnkr.co/edit/fuMlp7XE8tDlDYLoOfni?p=preview" rel="noreferrer">Live example</a></strong></p> | 39,724,223 | 4 | 0 | null | 2016-09-27 12:03:18.623 UTC | null | 2019-11-29 06:42:12.67 UTC | 2017-05-23 12:26:22.437 UTC | null | -1 | null | 3,034,932 | null | 1 | 20 | javascript|angular|angular2-forms | 62,198 | <p><strong>update</strong></p>
<p><a href="https://github.com/angular/angular/compare/4.0.0-beta.5...4.0.0-beta.6" rel="noreferrer">4.0.0-beta.6</a> added <code>compareWith</code></p>
<pre><code><select [compareWith]="compareFn" [(ngModel)]="selectedCountries">
<option *ngFor="let country of countries" [ngValue]="country">
{{country.name}}
</option>
</select>
compareFn(c1: Country, c2: Country): boolean {
return c1 && c2 ? c1.id === c2.id : c1 === c2;
}
</code></pre>
<p>this way the instance assigned to <code>selectedCountries</code> doesn't need to be the identical object, but a custom comparison function can be passed, for example to be able to match an different object instance with identical property values. </p>
<p><strong>original</strong></p>
<p>If you want to use an object as value you need to use <code>[ngValue]</code> on the option element.</p>
<pre><code> <select name="select" id="select" [(ngModel)]="selectLanguage">
<option *ngFor="let item of selectOption" [ngValue]="item"
[disabled]="item.value==0">{{item.label}}</option>
</select>
</code></pre>
<p>When <code>selectLanguage</code> has an options value assigned <code>[(ngModel)]="..."</code> will this one make the one selected by default:</p>
<pre><code>import {Component} from '@angular/core';
@Component({
moduleId: module.id,
selector: 'app-form-select',
templateUrl: 'default.component.html'
})
export class DefaultComponent {
private selectOption: any;
constructor() {
this.selectOption = [
{
id: 1,
label: "Select Language",
value: 0
}, {
id: 2,
label: "HTML 5",
value: 1
}, {
id: 3,
label: "PHP",
value: 2
}, {
id: 4,
label: "Javascript",
value: 3
}
];
this.selectLanguage = this.selectOption[0];
}
}
</code></pre> |
22,006,887 | cassandra - Saved cluster name Test Cluster != configured name | <p>How am I supposed to bot a new Cassandra node when I get this error?</p>
<pre><code>INFO [SSTableBatchOpen:1] 2014-02-25 01:51:17,132 SSTableReader.java (line 223) Opening /var/lib/cassandra/data/system/local/system-local-jb-5 (5725 bytes)
ERROR [main] 2014-02-25 01:51:17,377 CassandraDaemon.java (line 237) Fatal exception during initialization
org.apache.cassandra.exceptions.ConfigurationException: Saved cluster name Test Cluster != configured name thisisstupid
at org.apache.cassandra.db.SystemKeyspace.checkHealth(SystemKeyspace.java:542)
at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:233)
at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:462)
at org.apache.cassandra.service.CassandraDaemon.main(CassandraDaemon.java:552)
</code></pre>
<p>Name of cluster in the cassandra.yaml file is:</p>
<pre><code>cluster_name: 'thisisstupid'
</code></pre>
<p>How do I resolve?</p> | 22,007,669 | 7 | 0 | null | 2014-02-25 06:59:28.397 UTC | 16 | 2019-11-26 05:44:07.05 UTC | null | null | null | null | 1,203,556 | null | 1 | 56 | cassandra | 41,329 | <p>You can rename the cluster without deleting data by updating it's name in the system.local table (but you have to do this <strong>for each node</strong>...)</p>
<pre><code>cqlsh> UPDATE system.local SET cluster_name = 'test' where key='local';
# flush the sstables to persist the update.
bash $ ./nodetool flush
</code></pre>
<p>Finally you need to rename the cluster to the new name in cassandra.yaml (again <strong>on each node</strong>)</p> |
6,875,128 | How to compare two vectors using SIMD and get a single boolean result? | <p>I have two vectors of 4 integers each and I'd like to use a SIMD command to compare them (say generate a result vector where each entry is 0 or 1 according to the result of the comparison).</p>
<p>Then, I'd like to compare the result vector to a vector of 4 zeros and only if they're equal do something.</p>
<p>Do you know what SIMD commands I can use to do it?</p> | 6,875,336 | 1 | 2 | null | 2011-07-29 15:04:20.153 UTC | 9 | 2022-09-04 18:47:18.403 UTC | 2015-04-27 16:01:08.42 UTC | null | 895,245 | null | 787,044 | null | 1 | 17 | assembly|x86|sse|simd | 10,930 | <p>To compare two SIMD vectors:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <stdint.h>
#include <xmmintrin.h>
int32_t __attribute__ ((aligned(16))) vector1[4] = { 1, 2, 3, 4 };
int32_t __attribute__ ((aligned(16))) vector2[4] = { 1, 2, 2, 2 };
int32_t __attribute__ ((aligned(16))) result[4];
__m128i v1 = _mm_load_si128((__m128i *)vector1);
__m128i v2 = _mm_load_si128((__m128i *)vector2);
__m128i vcmp = _mm_cmpeq_epi32(v1, v2);
_mm_store_si128((__m128i *)result, vcmp);
</code></pre>
<p>Notes:</p>
<ul>
<li>data is assumed to be 32 bit integers</li>
<li><code>vector1</code>, <code>vector2</code>, <code>result</code> all need to be 16 byte aligned</li>
<li>result will be -1 for equal, 0 for not equal (<code>{ -1, -1, 0, 0 }</code> for above code example)</li>
</ul>
<hr>
<p><strong>UPDATE</strong></p>
<p>If you just want a single Boolean result for the case where all 4 elements match then you can do it like this:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <stdint.h>
#include <xmmintrin.h>
int32_t __attribute__ ((aligned(16))) vector1[4] = { 1, 2, 3, 4 };
int32_t __attribute__ ((aligned(16))) vector2[4] = { 1, 2, 2, 2 };
__m128i v1 = _mm_load_si128((__m128i *)vector1);
__m128i v2 = _mm_load_si128((__m128i *)vector2);
__m128i vcmp = _mm_cmpeq_epi32(v1, v2);
uint16_t mask = _mm_movemask_epi8(vcmp);
int result = (mask == 0xffff);
</code></pre> |
36,271,702 | C# Read (not write!) string from System.Net.Http.StringContent | <p>I have what seems like it should be a simple question, but I can't find an answer to it anywhere. Given the following code:</p>
<pre><code> using System.Net.Http;
...
StringContent sc = New StringContent("Hello!");
string myContent = ???;
</code></pre>
<p>What do I need to replace the <code>???</code> with in order to read the string value from <code>sc</code>, so that <code>myContent = "Hello!"</code>?</p>
<p><code>.ToString</code> just returns System.String, as does <code>.ReadAsStringAsync</code>. How do I read out what I've written in?</p> | 36,271,771 | 1 | 2 | null | 2016-03-28 21:40:50.14 UTC | null | 2016-03-28 21:46:17.72 UTC | null | null | null | null | 1,985,829 | null | 1 | 33 | c#|asp.net-web-api|system.net | 28,711 | <p>You can use <code>ReadAsStringAsync()</code> method, then get the result using <code>await</code> statement or <code>Result</code> property:</p>
<pre><code>StringContent sc = new StringContent("Hello!");
string myContent = await sc.ReadAsStringAsync();
//or
string myContent = sc.ReadAsStringAsync().Result;
</code></pre> |
20,641,953 | How to select parent element of current element in d3.js | <p>I want to access the parent element of current element</p>
<p>Here is the structure of HTML</p>
<pre><code>svg
g id=invisibleG
g
circle
g
circle
g
circle
</code></pre>
<p>Basically I want to add text inside the circles when I hover over them.</p>
<p>So I want something like this on hover of any particular circle</p>
<pre><code>svg
g id=invisibleG
g
circle --> radius is increased and text presented inside that
text
g
circle
g
circle
</code></pre>
<p>On hover I can select current element through d3.select(this),How can I get root element(g in my case)?</p> | 20,642,072 | 2 | 0 | null | 2013-12-17 18:29:35.227 UTC | 12 | 2017-05-03 20:41:15.08 UTC | null | null | null | null | 3,074,097 | null | 1 | 68 | javascript|d3.js | 73,423 | <p>You can use <code>d3.select(this.parentNode)</code> to select parent element of current element. And for selecting root element you can use <code>d3.select("#invisibleG")</code>.</p> |
24,109,114 | Set contentMode of UIImageView | <p>In Obj-C</p>
<p><code>imageView.contentMode = UIViewContentModeScaleAspectFill;</code></p>
<p>would set the contentMode.</p>
<p>Why does </p>
<p><code>imageView.contentMode = UIViewContentModeScaleAspectFill</code></p>
<p>not work in Swift?</p> | 24,109,162 | 5 | 0 | null | 2014-06-08 17:57:23.397 UTC | 4 | 2018-12-15 17:01:25.167 UTC | null | null | null | null | 1,433,774 | null | 1 | 34 | ios|swift | 50,562 | <p>Somewhat confusingly, Swift drops the prefix for ObjC enum values:</p>
<pre><code>imageView.contentMode = .scaleAspectFill
</code></pre>
<p>This is because Swift already knows what enum type is being used. Alternatively, you can specify the enum too:</p>
<pre><code>imageView.contentMode = UIViewContentMode.scaleAspectFill
</code></pre>
<p>Note: In versions of Swift before version 3, "scaleAspectFill" will need to be capitalized.</p> |
20,064,271 | How to use basic authorization in PHP curl | <p>I am having problem with PHP curl request with basic authorization.</p>
<p>Here is the command line curl:</p>
<pre><code>curl -H "Accept: application/product+xml" "https://{id}:{api_key}@api.domain.com/products?limit=1&offset=0"
</code></pre>
<p>I have tried by setting curl header in following ways but it's not working</p>
<pre><code>Authorization: Basic id:api_key
or
Authorization: Basic {id}:{api_key}
</code></pre>
<p>I get the response "authentication parameter in the request are missing or invalid" but I have used proper id and api_key which is working in command line curl (I tested)</p>
<p>Please help me.</p> | 20,064,360 | 4 | 0 | null | 2013-11-19 05:58:35.467 UTC | 15 | 2020-05-12 15:30:52.21 UTC | 2017-01-23 18:22:03.347 UTC | null | 20,043 | null | 2,199,932 | null | 1 | 57 | php|curl|authorization | 176,047 | <p>Try the following code :</p>
<pre><code>$username='ABC';
$password='XYZ';
$URL='<URL>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_close ($ch);
</code></pre> |
6,199,458 | How to create a modular JSF 2.0 application? | <p>I have an application with a well defined interface. It uses CDI for resolution of the modules, (Specifically it uses Instance<> injection points on API interfaces to resolve modules) and passes various data back and fourth via the interfaces without issue. I've intentionally kept the API and implementation separate, and the modules only inherit from the API to avoid tight coupling, and the application only knows of the modules through runtime dependancies, and data passing accomplished via the APIs. The application runs fine without the modules, which can be added simply by dropping the jar into the WEB-INF/lib folder and restarting the app server.</p>
<p>Where I'm running into issues is that I want the modules to create a portion of the view, and I therefor want to invoke, in a portable way, either a JSF component, or do an include from the module in order to have it render its view. I already have resolved what module I want to invoke, and have references to the module's interface ready. The way I initially thought to do this was to do a ui:include that asks the module to supply where it's view template is, but I have no idea how to answer that query in a meaningful way, as view resolution is done from the application root, not the library root.</p>
<p>The executive summary is that I have no idea how to jump the gap from Application to Library using JSF for .xhtml (template/component) files.</p>
<p>Using a CC would be nice, but how do I specify that I want a particular CC instance at runtime, instead of having that hard coded into the page?</p>
<p>I can of course invoke the application code directly and ask it for markup, but this seems really brute force, and once I have the markup, I'm not sure exactly how to tell JSF to evaluate it. That said, I can imagine a component that would take the resource path, grab the markup and evaluate it, returning the completed markup, I just don't know how to implement that.</p>
<p>I'd rather avoid forcing module developers to go the heavy duty UIComponent approach if possible, which means either a dynamic way of doing ui:include (or some equivalent) or a dynamic way of invoking CCs. (I don't mind coding the UIComponent approach ONCE in the application if that's what it takes to make module developers' lives easier)</p>
<p>Any suggestions on where I should look to figure this out? (I'll post the answer here if I find it first)</p> | 6,201,044 | 3 | 3 | null | 2011-06-01 10:05:30.54 UTC | 42 | 2014-09-01 08:43:57.07 UTC | 2011-06-20 13:23:59.407 UTC | null | 21,234 | null | 151,645 | null | 1 | 26 | java|jsf-2|cdi|jboss-weld|modular | 14,053 | <p>I understand that your question basically boils down to <em>How can I include Facelets views in a JAR?</em></p>
<p>You can do this by placing a custom <a href="http://download.oracle.com/javaee/6/api/javax/faces/view/facelets/ResourceResolver.html" rel="noreferrer"><code>ResourceResolver</code></a> in the JAR.</p>
<pre class="lang-java prettyprint-override"><code>public class FaceletsResourceResolver extends ResourceResolver {
private ResourceResolver parent;
private String basePath;
public FaceletsResourceResolver(ResourceResolver parent) {
this.parent = parent;
this.basePath = "/META-INF/resources"; // TODO: Make configureable?
}
@Override
public URL resolveUrl(String path) {
URL url = parent.resolveUrl(path); // Resolves from WAR.
if (url == null) {
url = getClass().getResource(basePath + path); // Resolves from JAR.
}
return url;
}
}
</code></pre>
<p>Configure this in webapp's <code>web.xml</code> as follows:</p>
<pre class="lang-xml prettyprint-override"><code><context-param>
<param-name>javax.faces.FACELETS_RESOURCE_RESOLVER</param-name>
<param-value>com.example.FaceletsResourceResolver</param-value>
</context-param>
</code></pre>
<p>Imagine that you've a <code>/META-INF/resources/foo/bar.xhtml</code> in <code>random.jar</code>, then you can just include it the usual way</p>
<pre class="lang-xml prettyprint-override"><code><ui:include src="/foo/bar.xhtml" />
</code></pre>
<p>or even dynamically</p>
<pre class="lang-xml prettyprint-override"><code><ui:include src="#{bean.path}" />
</code></pre>
<p>Note: since Servlet 3.0 and newer JBoss/JSF 2.0 versions, the whole <code>ResourceResolver</code> approach is not necessary if you keep the files in <code>/META-INF/resources</code> folder. The above <code>ResourceResolver</code> is only mandatory in Servlet 2.5 or older JBoss/JSF versions because they've bugs in <code>META-INF</code> resource resolving.</p>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/3531432/packaging-facelets-pages-in-a-jar">Packaging Facelets files (templates, includes, composites) in a JAR</a></li>
<li><a href="https://stackoverflow.com/questions/9290482/jsf-facelets-template-packaging">JSF facelets template packaging</a></li>
</ul> |
5,977,326 | call printf using va_list | <pre><code>void TestPrint(char* format, ...)
{
va_list argList;
va_start(argList, format);
printf(format, argList);
va_end(argList);
}
int main()
{
TestPrint("Test print %s %d\n", "string", 55);
return 0;
}
</code></pre>
<p>I need to get:</p>
<pre><code>Test print string 55
</code></pre>
<p>Actually, I get garbage output. What is wrong in this code?</p> | 5,977,344 | 4 | 0 | null | 2011-05-12 11:34:49.01 UTC | 13 | 2021-02-25 15:24:26.113 UTC | 2018-10-03 10:04:47.91 UTC | null | 279,313 | null | 279,313 | null | 1 | 66 | c|printf|variadic-functions | 68,167 | <p>Use <a href="http://www.cplusplus.com/reference/clibrary/cstdio/vprintf/"><code>vprintf()</code></a> instead.</p> |
1,743,454 | How to use jquery next() to select next div by class | <p>I'm fairly new to jquery and struggling with something that should be fairly simple. I want to select the previous and next div with class "MenuItem" from the div with class "MenuItemSelected".</p>
<p>HTML</p>
<pre><code><div id="MenuContainer" class="MenuContainer">
<div id="MainMenu" class="MainMenu">
<div class="MenuItem">
<div class="MenuItemText">Menu Item #1</div>
<div class="MenuItemImage">images/test1.jpg</div>
</div>
<div class="MenuDividerContainer">
<div class="MenuDivider"></div>
</div>
<div class="MenuItem MenuItemSelected">
<div class="MenuItemText">Menu Item #2</div>
<div class="MenuItemImage">images/test2.jpg</div>
</div>
<div class="MenuDividerContainer">
<div class="MenuDivider"></div>
</div>
<div class="MenuItem">
<div class="MenuItemText">Menu Item #3</div>
<div class="MenuItemImage">images/test3.jpg</div>
</div>
</div><!--/ .MainMenu -->
</div><!--/ .MenuContainer -->
</code></pre>
<p>Here is the jquery for next that I thought should have worked.</p>
<pre><code>$('div.MenuItemSelected').next('.MenuItem');
</code></pre>
<p>I also tried</p>
<pre><code>$('div.MenuItemSelected').nextAll('.MenuItem');
</code></pre>
<p>The only thing i could get to work is </p>
<pre><code>$('div.MenuItemSelected').next().next();
</code></pre>
<p>That seems hokey, any ideas?</p> | 1,743,472 | 2 | 0 | null | 2009-11-16 16:59:55.593 UTC | 2 | 2017-12-22 14:02:51.893 UTC | 2017-12-22 14:02:51.893 UTC | null | 4,810,485 | null | 1,375 | null | 1 | 21 | jquery | 68,188 | <p>Have you tried:</p>
<pre><code>$('div.MenuItemSelected').nextAll('.MenuItem:first');
</code></pre>
<p>I think the problem you are facing is that <code>next</code> returns the very next sibling, whereas <code>nextAll</code> returns a collection of all the subsequent siblings matching your selector. Applying the <a href="http://docs.jquery.com/Selectors/first" rel="noreferrer"><code>:first</code></a> selector to your <code>nextAll</code> filter should make things right.</p>
<p>I would like to point out, that if the structure of your markup is consistent (so it's always guaranteed to work), then your current solution <em>might</em> (benchmark, benchmark, benchmark) well be the faster way:</p>
<pre><code>$('div.MenuItemSelected').next().next();
</code></pre> |
5,773,057 | A cool python script to get teen learning python excited about programming? | <p>So I'm teaching a friends son some python programming, just going through control of flow, basic data types/structures.</p>
<p>I want to go through a tutorial with him, and hopefully build something simple yet cool to get him excited about the power of python.</p>
<p>Any ideas?</p> | 5,773,117 | 7 | 2 | null | 2011-04-24 20:31:41.24 UTC | 3 | 2012-07-27 20:23:43.053 UTC | null | null | null | null | 39,677 | null | 1 | 9 | python | 43,705 | <p>Have a look at <a href="http://inventwithpython.com/chapters/" rel="noreferrer">Invent Your Own Computer Games with Python</a> from Albert Sweigart.<br>
It has been written for beginners. It is available in the website of the link, but you can also buy the book if you prefer.<br>
There is a <a href="http://inventwithpython.com/blog/" rel="noreferrer">blog</a> with extra material with nice games as the classic gorillas or tetris. </p> |
6,092,400 | Is there a way to check if geolocation has been DECLINED with Javascript? | <p>I need JavaScript to display a manual entry if geolocation is declined.</p>
<p>What I have tried:</p>
<pre><code>Modernizr.geolocation
navigator.geolocation
</code></pre>
<p>Neither describes if user has previously declined access to geolocation.</p> | 37,750,156 | 7 | 1 | null | 2011-05-23 02:55:01.52 UTC | 21 | 2022-05-17 17:08:32.6 UTC | 2015-02-17 09:56:08.02 UTC | null | 368,691 | null | 12,252 | null | 1 | 81 | javascript|html|w3c-geolocation | 103,223 | <p>Without prompting the user, you can use the new permission api this is available as such:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>navigator.permissions.query({ name: 'geolocation' })
.then(console.log)</code></pre>
</div>
</div>
</p>
<p>(only works for Blink & Firefox)</p>
<p><a href="http://caniuse.com/#feat=permissions-api" rel="noreferrer">http://caniuse.com/#feat=permissions-api</a></p> |
6,036,462 | Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'" | <p>After years of working OK, I'm suddenly getting this message when trying to start the JVM:</p>
<pre><code>Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'
</code></pre>
<p>I tried uninstalling, and got a message saying a DLL was missing (unspecified)
Tried re-installing, all to no avail.</p>
<p>At the same time, when trying to start Scala I get:</p>
<pre><code>\Java\jdk1.6.0_25\bin\java.exe was unexpected at this time.
</code></pre>
<p>Checked <code>%JAVA_HOME%</code> and <code>%path%</code> - both OK</p>
<p>Can anyone help?</p> | 6,215,741 | 22 | 6 | null | 2011-05-17 20:07:39.24 UTC | 9 | 2022-07-29 17:16:32.37 UTC | 2014-06-23 14:02:11.897 UTC | null | 705,773 | null | 559,426 | null | 1 | 45 | java|scala | 228,050 | <p>Might be a slightly different cause, but that second issue occurs for me in scala 2.9.0.1 on Win7 (x64), though scala-2.9.1.final has already resolved this issue mentioned here:</p>
<pre><code>\Java\jdk1.6.0_25\bin\java.exe was unexpected at this time.
</code></pre>
<p>My <code>%JAVA_HOME%</code> set to a path like this: <code>c:\program files</code><strong>(x86)</strong><code>\Java\jdk...</code></p>
<p>Note the space and the parentheses.</p>
<p>If you change line 24 in <code>%SCALA_HOME%\bin\scala.bat</code> from:</p>
<pre><code>if exist "%JAVA_HOME%\bin\java.exe" set _JAVACMD=%JAVA_HOME%\bin\java.exe
</code></pre>
<p>to</p>
<pre><code>if exist "%JAVA_HOME%\bin\java.exe" set "_JAVACMD=%JAVA_HOME%\bin\java.exe"
</code></pre>
<p>It works fine. Note the quotes around the set command parameters, this will properly enclose any spaces and 'special' characters (eg: spaces and parentheses) in the variable's value.</p>
<p>Hope this helps someone else searching for an answer.</p> |
43,999,732 | How to make a fixed column in CSS using CSS Grid Layout? | <p>I've made a simple site with a <code>#container</code> div that is parent to two divs: <code>#left</code> and <code>#right</code>, by using <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout" rel="noreferrer">Grid Layout</a>:</p>
<p>Is there any way to make the left column fixed? I'd like the left text to persist on its position, and the right text to be scrollable as it is now. Adding <code>position: fixed</code> to <code>#left</code> breaks the layout.</p>
<p>I'm aware that this question has been already solved, but I'd appreciate a way to make it work with the grid layout.</p>
<p>Thanks.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
margin: 0 0 0 0;
}
#container {
display: grid;
grid-template-columns: 50% 50%;
}
.section {
padding: 5% 5% 5% 5%;
}
#left {
background-color: aquamarine;
}
#right {
background-color: beige;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
<div id="left" class="section">
<p>This should not scroll</p>
</div>
<div id="right" class="section">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla aliquet consectetur purus nec volutpat. Donec vel libero nec est commodo facilisis vel et nisl. Praesent porta sed eros eu porta. Cras dolor nulla, ullamcorper et tincidunt quis, porta ut
tellus. Maecenas cursus libero sed accumsan luctus. Integer sed consequat ante. Morbi sit amet lectus tempor elit tempor cursus ut sed enim. Donec placerat bibendum volutpat.
</p>
<p>
Nunc sit amet eleifend sapien, sed tincidunt neque. Donec id sapien et nunc scelerisque iaculis dignissim nec mauris. Fusce at pretium nulla. Maecenas vel rutrum tellus, a viverra nunc. Aenean at arcu vitae dui faucibus dapibus. Vivamus hendrerit blandit
mollis. Aenean sit amet lectus a metus faucibus condimentum. Proin vel eros ut elit pharetra lacinia vitae eu orci. Etiam massa massa, aliquam at pulvinar ut, porttitor eu mauris. Ut in iaculis sapien.
</p>
<p>
In vitae rhoncus arcu. Maecenas elementum nunc quis magna finibus, vitae imperdiet diam pulvinar. Phasellus sit amet nibh eu massa facilisis luctus. Nulla ullamcorper sodales ante id vestibulum. Fusce felis nisi, lacinia sit amet mauris vel, euismod suscipit
neque. Mauris quis libero eget enim facilisis pharetra. Fusce non ligula auctor nunc pretium dignissim eget eget turpis. Nam ultricies dolor ac libero maximus vestibulum. Mauris et tortor vitae nisi ultrices vestibulum ac id mauris. Proin interdum
dapibus sollicitudin. Phasellus ultricies vulputate sem id hendrerit. Cras eget posuere nunc, in placerat velit. Pellentesque sed ante at elit ornare efficitur. Donec sed condimentum nisl. Curabitur dapibus leo id ligula dignissim pharetra.
</p>
</div>
</div></code></pre>
</div>
</div>
</p> | 44,005,710 | 8 | 0 | null | 2017-05-16 11:05:52.03 UTC | 20 | 2020-09-30 17:29:01.28 UTC | 2017-05-16 15:05:34.08 UTC | null | 3,597,276 | null | 1,932,096 | null | 1 | 30 | html|css|grid-layout|css-grid | 54,652 | <p><em>You wrote:</em></p>
<blockquote>
<p>Is there any way to make the left column fixed?</p>
<p>I'd appreciate a way to make it work with the grid layout.</p>
</blockquote>
<p>If you want the element to remain a grid item, then the answer is "no".</p>
<p>Once an element has <code>position: absolute</code> or <code>position: fixed</code> (<a href="https://www.w3.org/TR/CSS22/visuren.html#choose-position" rel="noreferrer">which is a form of absolute positioning, with reference to the viewport</a>), it takes on new characteristics:</p>
<ul>
<li>the element is removed from the document flow</li>
<li>the element is removed from the <a href="https://www.w3.org/TR/css3-grid-layout/#grid-model" rel="noreferrer"><strong>grid formatting context</strong></a></li>
<li>the element is no longer a grid item</li>
</ul>
<p><em>From the spec:</em></p>
<blockquote>
<p><a href="https://www.w3.org/TR/css3-grid-layout/#static-position" rel="noreferrer"><strong>10. Absolute
Positioning</strong></a></p>
<p>An absolutely-positioned child of a grid container is out-of-flow and
not a grid item, and so does not affect the placement of other items
or the sizing of the grid.</p>
</blockquote>
<p>So a <em>grid item</em> doesn't work well with absolute positioning.</p>
<p>However, you won't have a problem applying <code>position: fixed</code> to a <em>grid container</em>.</p>
<p>Consider managing your <code>#left</code> and <code>#right</code> elements separately. <code>#left</code> can be a fixed-position grid container. <code>#right</code> can be another grid container and remain in-flow.</p>
<hr>
<p>Also, as an aside, you've given your grid items percentage-based padding:</p>
<pre><code>.section {
padding: 5% 5% 5% 5%;
}
</code></pre>
<p>When applying <code>margin</code> and <code>padding</code> to grid items (and flex items), it's best to stay away from percentage units. Browsers may compute the values differently.</p>
<ul>
<li><a href="https://stackoverflow.com/q/42708323/3597276">Percentage padding on grid item being ignored in Firefox</a></li>
<li><a href="https://stackoverflow.com/q/36783190/3597276">Why doesn't percentage padding work on flex items in Firefox?</a></li>
</ul> |
5,133,998 | IFrame background transparent in IE | <p>So i have this iFrame with the class .transparentbg:</p>
<pre><code>.transparantbg{
background-color: transparent;
}
</code></pre>
<p>This works fine in Chrome, but not in IE...</p>
<p>Help please?</p>
<p>Greetings</p> | 5,135,587 | 1 | 1 | null | 2011-02-27 15:19:56.263 UTC | 18 | 2015-05-26 21:20:54.273 UTC | 2011-03-12 07:45:41.11 UTC | null | 560,735 | null | 528,370 | null | 1 | 45 | html|css|internet-explorer|iframe|transparent | 56,811 | <p>Add allowTransparency="true" to your iframe</p>
<pre><code><IFRAME ID="Frame1" SRC="whatever.htm" allowTransparency="true">
</code></pre>
<p>For whatever.htm add <code>background:transparent</code> to its <code>body</code> tag.</p>
<pre><code><body style="background:transparent">
</code></pre> |
25,065,535 | Intellij IDEA: Hotkey for "scroll from source" | <p>I can't find a hotkey for the feature "Scroll from Source". </p>
<p>What is the difference between Scroll from Source and Scroll to Source as well? </p> | 42,025,214 | 11 | 1 | null | 2014-07-31 17:40:26.083 UTC | 19 | 2021-03-12 19:26:58.79 UTC | 2017-08-15 01:06:01.213 UTC | null | 5,953,643 | null | 961,018 | null | 1 | 165 | intellij-idea|jetbrains-ide | 37,985 | <p>In the latest IntelliJ IDEA, there is a keymap entry called "Select in Project View" with no default shortcut. Just add a shortcut key to it. No need for a plugin.</p>
<p><img src="https://i.stack.imgur.com/8bqd6.png" alt="Keymap|Select in Project View" /></p> |
21,583,758 | How to check if a float value is a whole number | <p>I am trying to find the largest cube root that is a whole number, that is less than 12,000. </p>
<pre><code>processing = True
n = 12000
while processing:
n -= 1
if n ** (1/3) == #checks to see if this has decimals or not
</code></pre>
<p>I am not sure how to check if it is a whole number or not though! I could convert it to a string then use indexing to check the end values and see whether they are zero or not, that seems rather cumbersome though. Is there a simpler way?</p> | 21,583,817 | 15 | 1 | null | 2014-02-05 17:06:10.917 UTC | 43 | 2022-08-06 17:36:10.25 UTC | 2014-02-05 17:21:16.28 UTC | null | 100,297 | null | 3,268,003 | null | 1 | 271 | python|floating-point | 338,458 | <p>To check if a float value is a whole number, use the <a href="http://docs.python.org/library/stdtypes.html#float.is_integer" rel="noreferrer"><code>float.is_integer()</code> method</a>:</p>
<pre><code>>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
</code></pre>
<p>The method was added to the <code>float</code> type in Python 2.6.</p>
<p>Take into account that in Python 2, <code>1/3</code> is <code>0</code> (floor division for integer operands!), and that floating point arithmetic can be imprecise (a <code>float</code> is an approximation using binary fractions, <em>not</em> a precise real number). But adjusting your loop a little this gives:</p>
<pre><code>>>> for n in range(12000, -1, -1):
... if (n ** (1.0/3)).is_integer():
... print n
...
27
8
1
0
</code></pre>
<p>which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:</p>
<pre><code>>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996
</code></pre>
<p>You'd have to check for numbers <strong>close</strong> to the whole number instead, or not use <code>float()</code> to find your number. Like rounding down the cube root of <code>12000</code>:</p>
<pre><code>>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648
</code></pre>
<p>If you are using Python 3.5 or newer, you can use the <a href="https://docs.python.org/library/math.html#math.isclose" rel="noreferrer"><code>math.isclose()</code> function</a> to see if a floating point value is within a configurable margin:</p>
<pre><code>>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
</code></pre>
<p>For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as <a href="https://www.python.org/dev/peps/pep-0485/#proposed-implementation" rel="noreferrer">mentioned in PEP485</a>:</p>
<pre><code>def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
</code></pre> |
9,569,976 | Working with special characters in a Mongo collection | <p>I have a collection I'm unable to drop, I'm assuming that the "-" in its name is a special character. In MongoDB, what is the best way to escape special characters?</p>
<pre><code>> db.tweets.drop();
true
</code></pre>
<p>BUT</p>
<pre><code>> db.tweets-old.drop();
ReferenceError: old is not defined (shell):1
</code></pre>
<p>I've tried to escape with quotes (both single and double) and a slash, but nothing works.</p> | 9,570,126 | 2 | 0 | null | 2012-03-05 16:11:52.233 UTC | 5 | 2015-07-09 13:31:37.177 UTC | 2013-04-08 14:27:24.877 UTC | null | 217,101 | null | 217,101 | null | 1 | 42 | mongodb | 25,543 | <p>The following works:</p>
<pre><code>db["tweets-old"].drop();
</code></pre>
<p>It's called the <a href="https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets">square bracket notation</a>, which allows you to use special characters in property names.</p> |
9,510,932 | Java Package Vs Folder-Structure? what is the difference | <p>I would like to know What are the difference between folder-structure and package used in Eclipse IDE for Java EE development. </p>
<p>When do we use which one and why?.</p>
<p>Whats should be the practice </p>
<ul>
<li>create a folder structure like src/com/utils and then create a class inside it </li>
<li>create a package like src.com.util and then create a class inside it</li>
</ul>
<p>which option would be better and easy to deploy if i have to write a ant script later for deployment ?</p>
<p>if i go for the folder-structure will the deployment is as easy as copying files from development to deployment target ?</p> | 9,511,005 | 6 | 0 | null | 2012-03-01 05:08:14.73 UTC | 20 | 2021-01-07 19:08:27.48 UTC | 2012-03-03 09:40:25.497 UTC | null | 472,792 | null | 798,404 | null | 1 | 79 | java|package|directory | 60,025 | <p>If you configured stuffs correctly. Adding a folder inside <code>src</code>, is same as adding a package from <code>File > New Package</code>.</p>
<p>So, it's up to you, whatever feels comfortable to you -- add a folder or create a package. Also, when you put stuffs under <code>src</code> the package name starts from subfolder. So, <code>src/com/naishe/test</code> will be package <code>com.naishe.test</code>.</p> |
30,887,788 | JSON Web Token (JWT) with Spring based SockJS / STOMP Web Socket | <h1>Background</h1>
<p>I am in the process of setting up a RESTful web application using Spring Boot (1.3.0.BUILD-SNAPSHOT) that includes a STOMP/SockJS WebSocket, which I intend to consume from an iOS app as well as web browsers. I want to use <a href="http://jwt.io">JSON Web Tokens</a> (JWT) to secure the REST requests and the WebSocket interface but I’m having difficulty with the latter.</p>
<p>The app is secured with Spring Security:-</p>
<pre><code>@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
public WebSecurityConfiguration() {
super(true);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("steve").password("steve").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling().and()
.anonymous().and()
.servletApi().and()
.headers().cacheControl().and().and()
// Relax CSRF on the WebSocket due to needing direct access from apps
.csrf().ignoringAntMatchers("/ws/**").and()
.authorizeRequests()
//allow anonymous resource requests
.antMatchers("/", "/index.html").permitAll()
.antMatchers("/resources/**").permitAll()
//allow anonymous POSTs to JWT
.antMatchers(HttpMethod.POST, "/rest/jwt/token").permitAll()
// Allow anonymous access to websocket
.antMatchers("/ws/**").permitAll()
//all other request need to be authenticated
.anyRequest().hasRole("USER").and()
// Custom authentication on requests to /rest/jwt/token
.addFilterBefore(new JWTLoginFilter("/rest/jwt/token", authenticationManagerBean()), UsernamePasswordAuthenticationFilter.class)
// Custom JWT based authentication
.addFilterBefore(new JWTTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
</code></pre>
<p>The WebSocket configuration is standard:-</p>
<pre><code>@Configuration
@EnableScheduling
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
}
</code></pre>
<p>I also have a subclass of <code>AbstractSecurityWebSocketMessageBrokerConfigurer</code> to secure the WebSocket:-</p>
<pre><code>@Configuration
public class WebSocketSecurityConfiguration extends AbstractSecurityWebSocketMessageBrokerConfigurer {
@Override
protected void configureInbound(MessageSecurityMetadataSourceRegistry messages) {
messages.anyMessage().hasRole("USER");
}
@Override
protected boolean sameOriginDisabled() {
// We need to access this directly from apps, so can't do cross-site checks
return true;
}
}
</code></pre>
<p>There is also a couple of <code>@RestController</code> annotated classes to handle various bits of functionality and these are secured successfully via the <code>JWTTokenFilter</code> registered in my <code>WebSecurityConfiguration</code> class.</p>
<h1>Problem</h1>
<p>However I can't seem to get the WebSocket to be secured with JWT. I am using <a href="https://github.com/sockjs/sockjs-client/releases/tag/v1.0.0">SockJS 1.1.0</a> and <a href="https://raw.githubusercontent.com/jmesnil/stomp-websocket/master/lib/stomp.js">STOMP 1.7.1</a> in the browser and can't figure out how to pass the token. It <a href="https://github.com/sockjs/sockjs-client/issues/196">would appear that</a> SockJS does not allow parameters to be sent with the initial <code>/info</code> and/or handshake requests.</p>
<p>The <a href="http://docs.spring.io/autorepo/docs/spring-security/4.0.x/reference/html/websocket.html">Spring Security for WebSockets documentation states</a> that the <code>AbstractSecurityWebSocketMessageBrokerConfigurer</code> ensures that:</p>
<blockquote>
<p>Any inbound CONNECT message requires a valid CSRF token to enforce Same Origin Policy</p>
</blockquote>
<p>Which seems to imply that the initial handshake should be unsecured and authentication invoked at the point of receiving a STOMP CONNECT message. Unfortunately I can't seem to find any information with regards to implementing this. Additionally this approach would require additional logic to disconnect a rogue client that opens a WebSocket connection and never sends a STOMP CONNECT.</p>
<p>Being (very) new to Spring I'm also not sure if or how Spring Sessions fits into this. While the documentation is very detailed there doesn't appear to a nice and simple (aka idiots) guide to how the various components fit together / interact with each other.</p>
<h1>Question</h1>
<p>How do I go about securing the SockJS WebSocket by providing a JSON Web Token, preferably at the point of handshake (is it even possible)?</p> | 31,124,813 | 5 | 1 | null | 2015-06-17 09:37:41.003 UTC | 41 | 2021-11-29 22:16:18.343 UTC | 2015-06-19 06:44:17.54 UTC | null | 2,613,662 | null | 2,613,662 | null | 1 | 71 | spring|spring-security|websocket|jwt|sockjs | 57,496 | <p>Seems like support for a query string was added to the SockJS client, see <a href="https://github.com/sockjs/sockjs-client/issues/72" rel="noreferrer">https://github.com/sockjs/sockjs-client/issues/72</a>.</p> |
23,159,257 | Python Mock Multiple Calls with Different Results | <p>I want to be able to have multiple calls to a particular attribute function return a different result for each successive call.</p>
<p>In the below example, I would like increment to return 5 on its first call and then 10 on its second call.</p>
<p>Ex:</p>
<pre><code>import mock
class A:
def __init__(self):
self.size = 0
def increment(self, amount):
self.size += amount
return amount
@mock.patch("A.increment")
def test_method(self, mock_increment):
def diff_inc(*args):
def next_inc(*args):
#I don't know what belongs in __some_obj__
some_obj.side_effect = next_inc
return 10
return 5
mock_increment.side_effect = diff_inc
</code></pre>
<p>The below page has almost everything that I need except that it assumes that the caller would be an object named "mock", but this can't be assumed.</p>
<p><a href="http://mock.readthedocs.org/en/latest/examples.html#multiple-calls-with-different-effects" rel="noreferrer">http://mock.readthedocs.org/en/latest/examples.html#multiple-calls-with-different-effects</a></p> | 23,207,767 | 3 | 1 | null | 2014-04-18 17:40:51.42 UTC | 7 | 2020-10-23 12:25:04.57 UTC | null | null | null | null | 2,482,605 | null | 1 | 63 | python|mocking | 57,682 | <p>You can just pass an iterable to side effect and have it iterate through the list of values for each call you make.</p>
<pre><code>@mock.patch("A.increment")
def test_method(self, mock_increment):
mock_increment.side_effect = [5,10]
self.assertEqual(mock_increment(), 5)
self.assertEqual(mock_increment(), 10)
</code></pre> |
19,170,781 | Show hide divs on click in HTML and CSS without jQuery | <p>I want something very similar to Theming collapsible headers located here:</p>
<p><a href="http://jquerymobile.com/demos/1.2.0-alpha.1/docs/content/content-collapsible.html" rel="noreferrer">http://jquerymobile.com/demos/1.2.0-alpha.1/docs/content/content-collapsible.html</a></p>
<p>Without using JQuery, is this possible?</p>
<p>It's for a mobile site but the page is always going to be offline so I dont really want to use jquery. Also giving custom styling to jquery mobile is alot harder than using pure css and styling it yourself.</p> | 19,170,853 | 4 | 2 | null | 2013-10-03 23:27:03.15 UTC | 29 | 2021-01-07 21:45:22.37 UTC | 2013-10-03 23:29:21.01 UTC | null | 420,001 | null | 1,305,749 | null | 1 | 27 | javascript|html|css | 120,068 | <h2>Using <code>label</code> and <code>checkbox</code> input</h2>
<p>Keeps the selected item opened and togglable.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.collapse{
cursor: pointer;
display: block;
background: #cdf;
}
.collapse + input{
display: none; /* hide the checkboxes */
}
.collapse + input + div{
display:none;
}
.collapse + input:checked + div{
display:block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="collapse" for="_1">Collapse 1</label>
<input id="_1" type="checkbox">
<div>Content 1</div>
<label class="collapse" for="_2">Collapse 2</label>
<input id="_2" type="checkbox">
<div>Content 2</div></code></pre>
</div>
</div>
</p>
<h2>Using <code>label</code> and named <code>radio</code> input</h2>
<p>Similar to checkboxes, it just closes the already opened one.<br>
Use <code>name="c1" type="radio"</code> on both inputs.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.collapse{
cursor: pointer;
display: block;
background: #cdf;
}
.collapse + input{
display: none; /* hide the checkboxes */
}
.collapse + input + div{
display:none;
}
.collapse + input:checked + div{
display:block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><label class="collapse" for="_1">Collapse 1</label>
<input id="_1" type="radio" name="c1">
<div>Content 1</div>
<label class="collapse" for="_2">Collapse 2</label>
<input id="_2" type="radio" name="c1">
<div>Content 2</div></code></pre>
</div>
</div>
</p>
<h2>Using <code>tabindex</code> and <code>:focus</code></h2>
<p>Similar to <code>radio</code> inputs, additionally you can trigger the states using the <kbd>Tab</kbd> key.<br>
Clicking outside of the accordion will close all opened items.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.collapse > a{
background: #cdf;
cursor: pointer;
display: block;
}
.collapse:focus{
outline: none;
}
.collapse > div{
display: none;
}
.collapse:focus div{
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="collapse" tabindex="1">
<a>Collapse 1</a>
<div>Content 1....</div>
</div>
<div class="collapse" tabindex="1">
<a>Collapse 2</a>
<div>Content 2....</div>
</div></code></pre>
</div>
</div>
</p>
<h2>Using <code>:target</code></h2>
<p>Similar to using <code>radio</code> input, you can additionally use <kbd>Tab</kbd> and <kbd>⏎</kbd> keys to operate</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.collapse a{
display: block;
background: #cdf;
}
.collapse > div{
display:none;
}
.collapse > div:target{
display:block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="collapse">
<a href="#targ_1">Collapse 1</a>
<div id="targ_1">Content 1....</div>
</div>
<div class="collapse">
<a href="#targ_2">Collapse 2</a>
<div id="targ_2">Content 2....</div>
</div></code></pre>
</div>
</div>
</p>
<h2>Using <code><detail></code> and <code><summary></code> tags (pure HTML)</h2>
<p>You can use HTML5's detail and summary tags to solve this problem without any CSS styling or Javascript. Please note that these tags are not supported by Internet Explorer. </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><details>
<summary>Collapse 1</summary>
<p>Content 1...</p>
</details>
<details>
<summary>Collapse 2</summary>
<p>Content 2...</p>
</details></code></pre>
</div>
</div>
</p> |
35,706,835 | React router redirect after action redux | <p>I'm using <code>react-redux</code> and <code>react-router</code>. I need to redirect after an action is dispatched.</p>
<p>For example: I have registration a few steps. And after action:</p>
<pre><code>function registerStep1Success(object) {
return {
type: REGISTER_STEP1_SUCCESS,
status: object.status
};
}
</code></pre>
<p>I want to redirect to page with registrationStep2. How can I do this?</p>
<p>p.s. In history browser '/registrationStep2' has not been visited. This page appears only after successful result registrationStep1 page.</p> | 35,723,458 | 10 | 1 | null | 2016-02-29 18:28:09.607 UTC | 16 | 2021-12-08 12:06:21.083 UTC | 2021-01-28 23:28:20.287 UTC | null | 734,289 | null | 3,038,345 | null | 1 | 79 | reactjs|react-router|redux|redux-framework | 120,240 | <p>With React Router 2+, wherever you dispatch the action, you can call <code>browserHistory.push()</code> (or <code>hashHistory.push()</code> if that’s what you use):</p>
<pre><code>import { browserHistory } from 'react-router'
// ...
this.props.dispatch(registerStep1Success())
browserHistory.push('/registrationStep2')
</code></pre>
<p>You can do this from async action creators too if that is what you use.</p> |
3,435,458 | What is the best Python IDE for Mac OS X? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/893162/whats-a-good-ide-for-python-on-the-mac">What’s a good IDE for Python on the Mac?</a> </p>
</blockquote>
<p>Hi,</p>
<p>I'm going to start a quite big python project development under Mac OS X. What is the best python IDE for Mac OS X -recommended freeware-.</p> | 3,435,501 | 1 | 4 | null | 2010-08-08 18:11:02.95 UTC | 3 | 2010-08-08 18:22:58.847 UTC | 2017-05-23 12:01:57.267 UTC | null | -1 | null | 292,942 | null | 1 | 9 | python|macos|ide | 39,958 | <p><a href="http://pydev.org" rel="nofollow noreferrer">Pydev</a> with Eclipse.</p> |
3,655,708 | Error: The used SELECT statements have a different number of columns | <p>Why am I getting <code>ERROR 1222 (21000): The used SELECT statements have a different number of columns</code> from the following?</p>
<pre><code>SELECT * FROM friends
LEFT JOIN users AS u1 ON users.uid = friends.fid1
LEFT JOIN users AS u2 ON users.uid = friends.fid2
WHERE (friends.fid1 = 1) AND (friends.fid2 > 1)
UNION SELECT fid2 FROM friends
WHERE (friends.fid2 = 1) AND (friends.fid1 < 1)
ORDER BY RAND()
LIMIT 6;
</code></pre>
<p><code>users</code>:</p>
<pre><code>+------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------+------+-----+---------+----------------+
| uid | int(11) | NO | PRI | NULL | auto_increment |
| first_name | varchar(50) | NO | | NULL | |
| last_name | varchar(50) | NO | | NULL | |
| email | varchar(128) | NO | UNI | NULL | |
| mid | varchar(40) | NO | | NULL | |
| active | enum('N','Y') | NO | | NULL | |
| password | varchar(64) | NO | | NULL | |
| sex | enum('M','F') | YES | | NULL | |
| created | datetime | YES | | NULL | |
| last_login | datetime | YES | | NULL | |
| pro | enum('N','Y') | NO | | NULL | |
+------------+---------------+------+-----+---------+----------------+
</code></pre>
<p><code>friends</code>:</p>
<pre><code>+---------------+--------------------------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+--------------------------------------+------+-----+---------+----------------+
| friendship_id | int(11) | NO | MUL | NULL | auto_increment |
| fid1 | int(11) | NO | PRI | NULL | |
| fid2 | int(11) | NO | PRI | NULL | |
| status | enum('pending','accepted','ignored') | NO | | NULL | |
+---------------+--------------------------------------+------+-----+---------+----------------+
</code></pre> | 3,655,718 | 1 | 0 | null | 2010-09-07 04:10:24.983 UTC | 6 | 2022-08-17 14:01:48.49 UTC | 2022-08-17 14:01:48.49 UTC | null | 3,404,097 | null | 373,496 | null | 1 | 15 | sql|mysql|mysql-error-1222 | 70,773 | <p>UNIONs (<code>UNION</code> and <code>UNION ALL</code>) require that all the queries being UNION'd have:</p>
<ol>
<li>The same number of columns in the SELECT clause</li>
<li>The column data type has to match at each position</li>
</ol>
<p>Your query has:</p>
<pre><code>SELECT f.*, u1.*, u2.* ...
UNION
SELECT fid2 FROM friends
</code></pre>
<p>The easiest re-write I have is:</p>
<pre><code> SELECT f.*, u.*
FROM FRIENDS AS f
JOIN USERS AS u ON u.uid = f.fid2
WHERE f.fid1 = 1
AND f.fid2 > 1
UNION
SELECT f.*, u.*
FROM FRIENDS AS f
JOIN USERS AS u ON u.uid = f.fid1
WHERE f.fid2 = 1
AND f.fid1 < 1
ORDER BY RAND()
LIMIT 6;
</code></pre>
<p>You've LEFT JOIN'd to the <code>USERS</code> table twice, but don't appear to be using the information.</p> |
3,814,302 | How to pass in parameters to a SQL Server script called with sqlcmd? | <p>Is it possible to pass parameters to a SQL Server script? I have a script that creates a database. It is called from a batch file using sqlcmd. Part of that SQL script is as follows:</p>
<pre><code>CREATE DATABASE [SAMPLE] ON PRIMARY
( NAME = N'SAMPLE', FILENAME = N'c:\dev\SAMPLE.mdf' , SIZE = 23552KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'SAMPLE_log', FILENAME = N'c:\dev\SAMPLE_log.ldf' , SIZE = 29504KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
</code></pre>
<p>I want to be able to pass in the filenames for the database and the log so that I don't have to hardcode 'C:\dev\SAMPLE.mdf' and 'C:\dev\SAMPLE_log.ldf'. </p>
<p>Is there a way to do this? I am running Microsoft SQL Server 2008 Express. Let me know if you need any more information.</p> | 3,814,366 | 1 | 0 | null | 2010-09-28 15:21:29.053 UTC | 4 | 2017-06-14 22:04:10.843 UTC | 2010-09-28 15:23:58.983 UTC | null | 13,302 | null | 369,689 | null | 1 | 37 | sql|sql-server|scripting|parameters|sqlcmd | 48,597 | <p>Use the -v switch to pass in variables.</p>
<pre><code>sqlcmd -v varMDF="C:\dev\SAMPLE.mdf" varLDF="C:\dev\SAMPLE_log.ldf"
</code></pre>
<p>Then in your script file</p>
<pre><code>CREATE DATABASE [SAMPLE] ON PRIMARY
( NAME = N'SAMPLE', FILENAME = N'$(varMDF)' , SIZE = 23552KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
( NAME = N'SAMPLE_log', FILENAME = N'$(varLDF)' , SIZE = 29504KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)
</code></pre> |
21,253,869 | python: extended ASCII codes | <p>Hi I want to know how I can append and then print extended ASCII codes in python.
I have the following.</p>
<pre><code>code = chr(247)
li = []
li.append(code)
print li
</code></pre>
<p>The result python print out is ['\xf7'] when it should be a division symbol. If I simple print code directly "print code" then I get the division symbol but not if I append it to a list. What am I doing wrong?</p>
<p>Thanks. </p> | 21,254,132 | 4 | 3 | null | 2014-01-21 09:22:01.693 UTC | 1 | 2021-11-23 13:03:19.267 UTC | 2020-03-25 12:53:43.943 UTC | null | 108,205 | null | 1,831,677 | null | 1 | 11 | python|ascii|python-2.x | 40,848 | <p>When you print a list, it outputs the default representation of all its elements - ie by calling <code>repr()</code> on each of them. The <code>repr()</code> of a string is its escaped code, by design. If you want to output all the elements of the list properly you should convert it to a string, eg via <code>', '.join(li)</code>.</p>
<p>Note that as those in the comments have stated, there isn't really any such thing as "extended ASCII", there are just various different encodings. </p> |
18,684,397 | How to create datetime object from "16SEP2012" in python | <p>I can create datetime objects in python this way:</p>
<pre><code>import datetime
new_date= datetime.datetime(2012,09,16)
</code></pre>
<p>How can I create same <code>datetime</code> object from a string in this format: <code>"16SEP2012"</code> ?</p> | 18,684,426 | 2 | 1 | null | 2013-09-08 13:46:11.333 UTC | 6 | 2020-12-12 17:40:32.257 UTC | null | null | null | null | 718,762 | null | 1 | 36 | python|string|datetime | 56,074 | <p>Use <a href="http://docs.python.org/2/library/datetime.html#datetime.datetime.strptime"><code>datetime.datetime.strptime</code></a>:</p>
<pre><code>>>> datetime.datetime.strptime('16Sep2012', '%d%b%Y')
datetime.datetime(2012, 9, 16, 0, 0)
</code></pre> |
2,301,846 | What new features and improvements does Lithium provide over CakePHP? | <p>I've used CakePHP on several projects in the past, and have more recently started using Ruby on Rails, but there's a new project I'm about to start that will require PHP. While refreshing myself on CakePHP I learned that there is a new framework called <a href="http://lithify.me/" rel="noreferrer">Lithium</a> that is essentially what CakePHP 3 was going to be. It's being developed by a group of former core CakePHP devs.</p>
<p>I haven't found a whole lot of information about it since it's still under development status, but I was wondering if anyone knows (or has a link to) some information on what benefits it provides over CakePHP. Hopefully something a bit beyond the quick overview shown on the official site. I'm trying to decide whether to use CakePHP for my upcoming PHP project or to wait a bit for Lithium to release a non-development version and try that out.</p> | 3,097,977 | 3 | 1 | null | 2010-02-20 10:29:54.927 UTC | 15 | 2013-05-07 13:39:48.69 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 242,493 | null | 1 | 28 | cakephp|lithium | 3,258 | <p>Hope this answer doesn't come too late, (and as the lead developer of Lithium, I'm a little biased :-)), but I will say that this is a hard thing to sum up. Lithium is the culmination of over 4 years' experience building and working with CakePHP, and while it retains many of the same designs and conventions, it was built to correct CakePHP's many architectural flaws.</p>
<p>In brief:</p>
<ul>
<li>Framework features are grouped into loosely-coupled "packages" that are easy to use independently.</li>
<li>Tangentially, everything in Lithium is a "library", including your application, and Lithium itself. Support for integrating 3rd-party libraries is vastly improved, and all classes are namespaced, so you can finally have a model called File.</li>
<li>It is very easy to swap out core classes with your own custom implementations.</li>
<li>Lithium has a unique "filter" system that allows you to hook into many methods in the framework, which allows you to design your applications in an aspect-oriented fashion. These features work together to make Lithium the most flexible PHP framework, bar none.</li>
<li>Everything is lazy-loaded, and the architecture has been designed for maximum performance.</li>
<li>Lithium supports the latest tech, especially new databases like CouchDB and MongoDB.</li>
</ul>
<p>I could go on for a while, but that's the gist of it. If you have any more questions, feel free to drop by #li3 on Freenode, and someone will happily give you a tour.</p> |
27,043,922 | Why is the max recursion depth I can reach non-deterministic? | <p>I decided to try a few experiments to see what I could discover about the size of stack frames, and how far through the stack the currently executing code was. There are two interesting questions we might investigate here:</p>
<ol>
<li>How many levels deep into the stack is the current code?</li>
<li>How many levels of recursion can the current method reach before it hits a <code>StackOverflowError</code>?</li>
</ol>
<h1>Stack depth of currently executing code</h1>
<p>Here's the best I could come up with for this:</p>
<pre><code>public static int levelsDeep() {
try {
throw new SomeKindOfException();
} catch (SomeKindOfException e) {
return e.getStackTrace().length;
}
}
</code></pre>
<p>This seems a bit hacky. It generates and catches an exception, and then looks to see what the length of the stack trace is.</p>
<p>Unfortunately it also seems to have a fatal limitation, which is that the maximum length of the stack trace returned is 1024. Anything beyond that gets axed, so the maximum that this method can return is 1024.</p>
<blockquote>
<p><h2>Question:</h2> Is there a better way of doing this that isn't so hacky and doesn't have this limitation?</p>
</blockquote>
<p>For what it's worth, my guess is that there isn't: <code>Throwable.getStackTraceDepth()</code> is a native call, which suggests (but doesn't prove) that it can't be done in pure Java.</p>
<h1>Determining how much more recursion depth we have left</h1>
<p>The number of levels we can reach will be determined by (a) size of stack frame, and (b) amount of stack left. Let's not worry about size of stack frame, and just see how many levels we can reach before we hit a <code>StackOverflowError</code>.</p>
<p>Here's my code for doing this:</p>
<pre><code>public static int stackLeft() {
try {
return 1+stackLeft();
} catch (StackOverflowError e) {
return 0;
}
}
</code></pre>
<p>It does its job admirably, even if it's linear in the amount of stack remaining. But here is the very, very weird part. On 64-bit Java 7 (OpenJDK 1.7.0_65), the results are perfectly consistent: 9,923, on my machine (Ubuntu 14.04 64-bit). But Oracle's Java 8 (1.8.0_25) gives me <strong>non-deterministic results</strong>: I get a recorded depth of anywhere between about 18,500 and 20,700.</p>
<p>Now why on earth would it be non-deterministic? There's supposed to be a fixed stack size, isn't there? And all of the code looks deterministic to me.</p>
<p>I wondered whether it was something weird with the error trapping, so I tried this instead:</p>
<pre><code>public static long badSum(int n) {
if (n==0)
return 0;
else
return 1+badSum(n-1);
}
</code></pre>
<p>Clearly this will either return the input it was given, or overflow.</p>
<p>Again, the results I get are non-deterministic on Java 8. If I call <code>badSum(14500)</code>, it will give me a <code>StackOverflowError</code> about half the time, and return 14500 the other half. but on Java 7 OpenJDK, it's consistent: <code>badSum(9160)</code> completes fine, and <code>badSum(9161)</code> overflows.</p>
<blockquote>
<p><h2>Question:</h2> Why is the maximum recursion depth non-deterministic on Oracle's Java 8? And why is it deterministic on OpenJDK 7?</p>
</blockquote> | 27,047,776 | 4 | 3 | null | 2014-11-20 15:56:39.813 UTC | 4 | 2017-08-09 14:37:39.217 UTC | 2017-08-09 14:37:39.217 UTC | null | 3,933,089 | null | 3,933,089 | null | 1 | 31 | java|recursion|java-8|stack-overflow|stack-size | 4,396 | <p>The observed behavior is affected by the HotSpot optimizer, however it is not the only cause. When I run the following code</p>
<pre><code>public static void main(String[] argv) {
System.out.println(System.getProperty("java.version"));
System.out.println(countDepth());
System.out.println(countDepth());
System.out.println(countDepth());
System.out.println(countDepth());
System.out.println(countDepth());
System.out.println(countDepth());
System.out.println(countDepth());
}
static int countDepth() {
try { return 1+countDepth(); }
catch(StackOverflowError err) { return 0; }
}
</code></pre>
<p>with JIT enabled, I get results like:</p>
<pre class="lang-none prettyprint-override"><code>> f:\Software\jdk1.8.0_40beta02\bin\java -Xss68k -server -cp build\classes X
1.8.0_40-ea
2097
4195
4195
4195
12587
12587
12587
> f:\Software\jdk1.8.0_40beta02\bin\java -Xss68k -server -cp build\classes X
1.8.0_40-ea
2095
4193
4193
4193
12579
12579
12579
> f:\Software\jdk1.8.0_40beta02\bin\java -Xss68k -server -cp build\classes X
1.8.0_40-ea
2087
4177
4177
12529
12529
12529
12529
</code></pre>
<p>Here, the effect of the JIT is clearly visible, obviously the optimized code needs less stack space, and it’s shown that tiered compilation is enabled (indeed, using <code>-XX:-TieredCompilation</code> shows a single jump if the program runs long enough).</p>
<p>In contrast, with disabled JIT I get the following results:</p>
<pre class="lang-none prettyprint-override"><code>> f:\Software\jdk1.8.0_40beta02\bin\java -Xss68k -server -Xint -cp build\classes X
1.8.0_40-ea
2104
2104
2104
2104
2104
2104
2104
> f:\Software\jdk1.8.0_40beta02\bin\java -Xss68k -server -Xint -cp build\classes X
1.8.0_40-ea
2076
2076
2076
2076
2076
2076
2076
> f:\Software\jdk1.8.0_40beta02\bin\java -Xss68k -server -Xint -cp build\classes X
1.8.0_40-ea
2105
2105
2105
2105
2105
2105
2105
</code></pre>
<p>The values still vary, but not within the single runtime thread and with a lesser magnitude.</p>
<p>So, there is a (rather small) difference that becomes much larger if the optimizer can reduce the stack space required per method invocation, e.g. due to inlining.</p>
<p>What can cause such a difference? I don’t know how this JVM does it but one scenario could be that the way a stack limit is enforced requires a certain alignment of the stack <em>end</em> address (e.g. matching memory page sizes) while the memory <em>allocation</em> returns memory with a start address that has a weaker alignment guaranty. Combine such a scenario with <a href="http://en.wikipedia.org/wiki/Address_space_layout_randomization" rel="noreferrer">ASLR</a> and there might be always a difference, within the size of the alignment requirement.</p> |
453,329 | Advice regarding IPython + MacVim Workflow | <p>I've just found <a href="http://ipython.scipy.org/" rel="nofollow noreferrer">IPython</a> and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like <a href="https://stackoverflow.com/questions/431521/run-a-command-in-a-shell-and-keep-running-the-command-when-you-close-the-session#431570">the one I have with screen</a>. Ipython and screen happen to be the best of friends too so it's a triangular drama. Purely platonic, mind you.</p>
<p>The reason IPython hits the soft spots with me are very much because I generally like command prompts, and especially *nix-inspired prompts with inspiration from ksh, csh (yes, chs is a monster, but as a prompt it sport lots of really good features), bash and zsh. And IPython does sure feel like home for a *nix prompt rider. Mixing the system shell and python is also a really good idea. Plus, of course, IPython helps a lot when solving <a href="http://www.pythonchallenge.com/" rel="nofollow noreferrer">the Python Challenge</a> riddles. Invaluable even.</p>
<p>Now, I love Vim too. Since I learnt vi back in the days there's no turning back. And I'm on Mac when I have a choice. Now I'd like to glue together my IPython + MacVim workflow. What I've done so far is that I start Ipython using:</p>
<pre><code>ipython -e "open -a MacVim"
</code></pre>
<p>Thus when I edit from IPython it starts MacVim with the file/module loaded. Could look a bit like so:</p>
<pre><code>In [4]: %run foo #This also "imports" foo anew
hello world
In [5]: edit foo
Editing... done. Executing edited code... #This happens immediately
hello world
In [6]: %run foo
hello SO World
</code></pre>
<p>OK. I think this can be improved. Maybe there's a way to tie IPython into MacVim too? Please share your experiences. Of course if you use TextMate or some other fav editor I'm interested too. Maybe some of the lessons are general.</p> | 453,837 | 4 | 1 | null | 2009-01-17 13:46:27.32 UTC | 9 | 2011-11-10 09:35:52.05 UTC | 2017-05-23 11:45:36.47 UTC | PEZ | -1 | PEZ | 44,639 | null | 1 | 19 | python|vim|ipython | 4,476 | <p>I use Linux, but I believe this tip can be used in OS X too. I use <a href="http://www.gnu.org/software/screen/" rel="noreferrer">GNU Screen</a> to send IPython commands from Vim as recommended by <a href="http://vim.wikia.com/wiki/IPython_integration" rel="noreferrer">this tip</a>. This is how I do it:</p>
<p>First, you should open a terminal and start a screen session called 'ipython' or whatever you want, and then start IPython:</p>
<pre><code>$ screen -S ipython
$ ipython
</code></pre>
<p>Then you should put this in your .vimrc:</p>
<pre><code>autocmd FileType python map F5 :w<CR>:!screen -x ipython -X stuff $'\%run %:p:h\n'<CR><CR>
</code></pre>
<p>Then when you hit F5, it will tell Screen to execute the command '%run file' inside the 'ipython' created previously, where file is your current buffer in Vim.</p>
<p>You can tweak this to execute the command you want inside IPython from Vim. For example I use this: </p>
<pre><code>autocmd FileType python map <F5> :w<CR>:!screen -x ipython -X stuff $'\%reset\ny\n\%cd %:p:h\n\%run %:t\n'<CR><CR>
</code></pre>
<p>This executes %reset (answering yes to the prompt), then change to the directory where the current buffer in vim is located and then %run the file. This is specially useful if you have the %pdb active in IPython.</p>
<p>Don't forget that you need an active Screen session called 'ipython' with IPython running inside.</p>
<p>If you like Emacs. There is <a href="http://ipython.scipy.org/dist/ipython.el" rel="noreferrer">good support</a> for IPython.</p> |
79,129 | Implementing Profile Provider in ASP.NET MVC | <p>For the life of me, I cannot get the SqlProfileProvider to work in an MVC project that I'm working on.</p>
<p>The first interesting thing that I realized is that Visual Studio does not automatically generate the ProfileCommon proxy class for you. That's not a big deal since it's simpy a matter of extending the ProfileBase class. After creating a ProfileCommon class, I wrote the following Action method for creating the user profile.</p>
<pre><code>[AcceptVerbs("POST")]
public ActionResult CreateProfile(string company, string phone, string fax, string city, string state, string zip)
{
MembershipUser user = Membership.GetUser();
ProfileCommon profile = ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;
profile.Company = company;
profile.Phone = phone;
profile.Fax = fax;
profile.City = city;
profile.State = state;
profile.Zip = zip;
profile.Save();
return RedirectToAction("Index", "Account");
}</code></pre>
<p>The problem that I'm having is that the call to ProfileCommon.Create() cannot cast to type ProfileCommon, so I'm not able to get back my profile object, which obviously causes the next line to fail since profile is null.</p>
<p>Following is a snippet of my web.config:</p>
<p><pre><code><profile defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="false" enabled="true">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="FirstName" type="string" />
<add name="LastName" type="string" />
<add name="Company" type="string" />
<add name="Phone" type="string" />
<add name="Fax" type="string" />
<add name="City" type="string" />
<add name="State" type="string" />
<add name="Zip" type="string" />
<add name="Email" type="string" >
</properties>
</profile></pre></code></p>
<p>The MembershipProvider is working without a hitch, so I know that the connection string is good.</p>
<p>Just in case it's helpful, here is my ProfileCommon class:</p>
<pre><code>public class ProfileCommon : ProfileBase
{
public virtual string Company
{
get
{
return ((string)(this.GetPropertyValue("Company")));
}
set
{
this.SetPropertyValue("Company", value);
}
}
public virtual string Phone
{
get
{
return ((string)(this.GetPropertyValue("Phone")));
}
set
{
this.SetPropertyValue("Phone", value);
}
}
public virtual string Fax
{
get
{
return ((string)(this.GetPropertyValue("Fax")));
}
set
{
this.SetPropertyValue("Fax", value);
}
}
public virtual string City
{
get
{
return ((string)(this.GetPropertyValue("City")));
}
set
{
this.SetPropertyValue("City", value);
}
}
public virtual string State
{
get
{
return ((string)(this.GetPropertyValue("State")));
}
set
{
this.SetPropertyValue("State", value);
}
}
public virtual string Zip
{
get
{
return ((string)(this.GetPropertyValue("Zip")));
}
set
{
this.SetPropertyValue("Zip", value);
}
}
public virtual ProfileCommon GetProfile(string username)
{
return ((ProfileCommon)(ProfileBase.Create(username)));
}
}</code></pre>
<p>Any thoughts on what I might be doing wrong? Have any of the rest of you successfully integrated a ProfileProvider with your ASP.NET MVC projects?</p>
<p>Thank you in advance...</p> | 434,793 | 4 | 0 | null | 2008-09-17 01:56:37.173 UTC | 44 | 2022-01-19 14:05:40.083 UTC | 2022-01-19 14:05:40.083 UTC | senfo | 4,294,399 | senfo | 10,792 | null | 1 | 63 | asp.net-mvc|profile|profile-provider | 38,274 | <p>Here's what you need to do:</p>
<p>1) In Web.config's section, add "inherits" attribute in addition to your other attribute settings:</p>
<pre><code><profile inherits="MySite.Models.ProfileCommon" defaultProvider="....
</code></pre>
<p>2) Remove entire <code><properties></code> section from Web.config, since you have already defined them in your custom ProfileCommon class and also instructed to inherit from your custom class in previous step</p>
<p>3) Change the code of your ProfileCommon.GetProfile() method to </p>
<pre><code>public virtual ProfileCommon GetProfile(string username)
{
return Create(username) as ProfileCommon;
}
</code></pre>
<p>Hope this helps.</p> |
45,367,588 | How to remove the ChildViewController from Parent View Controller in Swift 3 | <p>I am developing an IOS Application. I have added the <code>UIViewController</code> in View Pager. I want to reinitialize it when the language is changed. Here I want to remove all child <code>UIViewController</code> from <code>UIViewPager</code> and again back to add all <code>UIViewController</code> into Viewpager. How can I do that?</p>
<p><strong>Sample Code</strong></p>
<pre><code>let viewPager = ViewPagerController()
viewPager.options = options
viewPager.dataSource = self
viewPager.delegate = self
self.addChildViewController(viewPager)
</code></pre>
<p><strong>Swift 3.1</strong></p>
<p><strong>xcode 8.3.3</strong></p> | 45,369,638 | 9 | 0 | null | 2017-07-28 07:38:28.533 UTC | 5 | 2022-06-15 10:37:17.9 UTC | 2018-05-15 06:30:36.187 UTC | null | 5,020,932 | null | 3,026,347 | null | 1 | 34 | ios|xcode|swift3 | 43,825 | <p>After the long search to remove the view controllers from viewpager. I did it in the following way.</p>
<pre><code> if self.childViewControllers.count > 0{
let viewControllers:[UIViewController] = self.childViewControllers
for viewContoller in viewControllers{
viewContoller.willMove(toParentViewController: nil)
viewContoller.view.removeFromSuperview()
viewContoller.removeFromParentViewController()
}
}
</code></pre>
<p>here self is , Current UIViewController which has View Pager. I need to remove all the childview controllers from the view pager. So, i get the list of view controllers from Current UIViewController. Then i removed it from the Parent view.</p>
<p><strong>For swift 4.2</strong></p>
<pre><code> if self.children.count > 0{
let viewControllers:[UIViewController] = self.children
for viewContoller in viewControllers{
viewContoller.willMove(toParent: nil)
viewContoller.view.removeFromSuperview()
viewContoller.removeFromParent()
}
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>Remove top childview controller:</p>
<pre><code> func removeTopChildViewController(){
if self.children.count > 0{
let viewControllers:[UIViewController] = self.children
viewControllers.last?.willMove(toParent: nil)
viewControllers.last?.removeFromParent()
viewControllers.last?.view.removeFromSuperview()
}
}
</code></pre> |
32,671,484 | Is it better to have multiple s3 buckets or one bucket with sub folders? | <p>Is it better to have multiple s3 buckets per category of uploads or one bucket with sub folders OR a linked s3 bucket? I know for sure there will be more user-images than there will be profille-pics and that there is a 5TB limit per bucket and 100 buckets per account. I'm doing this using aws boto library and <a href="https://github.com/amol-/depot" rel="noreferrer">https://github.com/amol-/depot</a></p>
<p>Which is the structure my folders in which of the following manner?</p>
<pre><code>/app_bucket
/profile-pic-folder
/user-images-folder
OR
profile-pic-bucket
user-images-bucket
OR
/app_bucket_1
/app_bucket_2
</code></pre>
<p>The last one implies that its really a 10TB bucket where a new bucket is created when the files within bucket_1 exceeds 5TB. But all uploads will be read as if in one bucket. Or is there a better way of doing what I'm trying to do? Many thanks!</p>
<p>I'm not sure if this is correct... 100 buckets per account? </p>
<p><a href="https://www.reddit.com/r/aws/comments/28vbjs/requesting_increase_in_number_of_s3_buckets/" rel="noreferrer">https://www.reddit.com/r/aws/comments/28vbjs/requesting_increase_in_number_of_s3_buckets/</a></p> | 32,672,478 | 2 | 0 | null | 2015-09-19 17:55:56.113 UTC | 14 | 2020-06-06 13:54:23.503 UTC | null | null | null | null | 805,981 | null | 1 | 75 | amazon-web-services|amazon-s3|boto | 32,081 | <p>Yes, there is actually a 100 bucket limit per account. I asked the reason for that to an architect in an AWS event. He said this is to avoid people hosting unlimited static websites on S3 as they think this may be abused. But you can apply for an increase.</p>
<blockquote>
<p>By default, you can create up to 100 buckets in each of your AWS
accounts. If you need additional buckets, you can increase your bucket
limit by submitting a service limit increase.</p>
</blockquote>
<p>Source: <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html">http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html</a></p>
<p>Also, please note that there are actually no folders in S3, just a flat file structure:</p>
<blockquote>
<p>Amazon S3 has a flat structure with no hierarchy like you would see in
a typical file system. However, for the sake of organizational
simplicity, the Amazon S3 console supports the folder concept as a
means of grouping objects. Amazon S3 does this by using key name
prefixes for objects.</p>
</blockquote>
<p>Source: <a href="http://docs.aws.amazon.com/AmazonS3/latest/UG/FolderOperations.html">http://docs.aws.amazon.com/AmazonS3/latest/UG/FolderOperations.html</a></p>
<p>Finally, the 5TB limit only applies to a single object. There is no limit on the number of objects or total size of the bucket.</p>
<blockquote>
<p>Q: How much data can I store?</p>
<p>The total volume of data and number of objects you can store are
unlimited.</p>
</blockquote>
<p>Source: <a href="https://aws.amazon.com/s3/faqs/">https://aws.amazon.com/s3/faqs/</a></p>
<p>Also the documentation states there is no performance difference between using a single bucket or multiple buckets so I guess both option 1 and 2 would be suitable for you.</p>
<p>Hope this helps.</p> |
23,149,781 | Get currently selected value of UIPickerView | <p>I have been googling how to get the currently selected value in UIPickerView, but everywhere it's mentioned using row:0 and so on. </p>
<p>I have a UIPickerView populated with string values like "One","Two", etc. </p>
<p>Now when I select a value to let's say "Two", is there anyway I can get this text.</p>
<p>Like in UITextView where it is _textview.text</p> | 23,149,836 | 6 | 0 | null | 2014-04-18 07:47:31.933 UTC | 3 | 2020-11-20 19:31:26.027 UTC | null | null | null | null | 3,064,140 | null | 1 | 11 | ios|objective-c|uipickerview | 42,060 | <p>Every UIPickerView should have a delegate.</p>
<p>And you can ask this delegate for your picker's selected row title via something like:</p>
<pre><code> UIPickerViewDelegate *delegate = yourPickerView.delegate;
NSString *titleYouWant = [delegate pickerView:yourPickerView titleForRow:[yourPickerView selectedRowInComponent:0] forComponent:0];
</code></pre>
<p>(This is <strong><em>ASSUMING</em></strong> your component number is zero; your own implementation might be different).</p>
<p><a href="https://developer.apple.com/library/ios/documentation/uikit/reference/UIPickerViewDelegate_Protocol/Reference/UIPickerViewDelegate.html#//apple_ref/occ/intfm/UIPickerViewDelegate/pickerView%3atitleForRow%3aforComponent%3a">More documentation on the "<code>pickerView:titleForRow:forComponent</code>" method can be seen here</a>. </p> |
34,910,383 | Xcode - free to clear devices folder? | <p>I am deleting some folders and files to make more space on my drive. I know that in path:</p>
<pre><code>~/Library/Developer/CoreSimulator/Devices/
</code></pre>
<p>There are folders for each simulator and each version. This folder has around 11GB size for me. I know that I could delete simulators with old versions that I no longer use. But from that unique identifier I can't know which is the right one and which not. So my question is: Can I delete it all? It's okay if next time I wouldn't have any of my app in simulator but can I loose something more? Old versions of simulator? Or anything else? Thanks</p> | 34,914,591 | 4 | 0 | null | 2016-01-20 20:57:59.997 UTC | 75 | 2022-06-22 10:50:24.687 UTC | null | null | null | null | 367,593 | null | 1 | 103 | ios|xcode|macos|ios-simulator | 60,857 | <p>The <code>~/Library/Developer/CoreSimulator/Devices/</code> path is where Xcode stores most of the data needed for your individual simulator devices.</p>
<p>Beau Nouvelle's suggestion about deleting downloaded simulator versions would not change the size of these folders, as the runtimes are stored elsewhere.</p>
<p>If you go to the terminal, you can use the <strong>simctl</strong> tool (comes with Xcode 6+) to list all of the actual simulator devices you have, along with the ids so that you can figure out what folders to delete.</p>
<p><em>Note, you'll see me constantly use <strong>xcrun simctl</strong> in this answer. That adds a bit of abstraction to things by having xcrun go look up the appropriate version of simctl for your currently chosen Xcode. Depending on your system, you might get by with dropping the "xcrun" part and the commandline should still find the simctl tool.</em></p>
<p><code>xcrun simctl list devices</code></p>
<p>Here are some selected snippets of the output I received:</p>
<blockquote>
<p>== Devices ==</p>
<p>-- iOS 8.2 --</p>
<p>-- iOS 8.4 --</p>
<p>iPhone 6 Plus (23E36868-715A-48C8-ACC3-A735C1C83383) (Shutdown)</p>
<p>iPad Air (2928379B-70E3-4C59-B5BA-66187DDD3516) (Shutdown)</p>
<p>-- iOS 9.1 --</p>
<p>My Custom iPhone 4s (4F27F577-FFD0-42C1-8680-86BBA7394271)
(Shutdown)</p>
<p>iPad Retina (85717B35-313A-4161-850E-D99D5C8194A6) (Shutdown)</p>
<p>-- Unavailable: com.apple.CoreSimulator.SimRuntime.iOS-9-0 --</p>
<p>iPhone 4s (D24C18BC-268C-4F0B-9CD8-8EFFDE6619E3) (Shutdown)
(unavailable, runtime profile not found)</p>
</blockquote>
<p>From that you can see that I have no iOS 8.2 simulator devices. I have some 9.1 and 8.4 simulator devices. I do have a 9.0 simulator device made (a remnant of my work on Xcode 7.0), but I don't have the 9.0 simulator runtime itself. So that's a good candidate for deletion, or a reminder that I should go download the 9.0 simulator in Xcode.</p>
<p>If you want, you can use those ids to identify the folder for the device in question and delete it manually (in this case I would delete the "D24C18BC-268C-4F0B-9CD8-8EFFDE6619E3" folder), but you can also use the simctl tool to do that.</p>
<p>Usage according to the 7.1.1 version of simctl:</p>
<pre><code>xcrun simctl help delete
Usage: simctl delete <device> [... <device n>] | unavailable
</code></pre>
<p>So I can either delete the individual device(s):</p>
<p><code>xcrun simctl delete D24C18BC-268C-4F0B-9CD8-8EFFDE6619E3</code></p>
<p>or I can bulk delete all of the unavailable ones with:</p>
<p><code>xcrun simctl delete unavailable</code></p>
<p>There is also no need to limit yourself purely to unavailable simulators.</p>
<p>If you need any further help with the tool, it comes with a fairly straight forward help command:</p>
<p><code>xcrun simctl help</code></p>
<p>--</p>
<p>Later versions of Xcode have made the above steps less effective. I only know about Xcode 13.1 for sure. While deleting the simulators still clears up space in the <code>~/Library/Developer/CoreSimulator/Devices/</code> folder, sometimes this doesn't help as the files have just moved to live off under <code>/var/folders</code> in some folder called <code>Deleting-<guid></code>, which takes up about as much space as the device original did. But this location requires root privileges to clean up or a reboot, neither of which are desirable.
From some testing a colleague did, it seems if you delete the device folders first and then delete the device via <code>xcrun simctl delete</code>, this isn't an issue.</p> |
27,462,602 | Cannot read property 'module' of undefined | <p>I have a basic understanding of <code>Django</code> and <code>JS</code> and recently I started learning <code>Angular.js</code>. I wrote code for showing hardcoded <code>json</code> using <code>Angular</code> and failed. I got the following error:</p>
<pre><code>Uncaught TypeError: Cannot read property 'module' of undefined at line 10 of django-angular.js
</code></pre>
<p>I went through the file and saw this line:</p>
<pre><code>var djng_forms_module = angular.module('ng.django.forms', []);
</code></pre>
<p>I don't know what the error means by undefined. I went through some of the links having similar problems but with no success.</p> | 27,462,708 | 3 | 0 | null | 2014-12-13 19:10:36.573 UTC | 4 | 2016-09-24 12:58:16.983 UTC | null | null | null | null | 1,322,382 | null | 1 | 16 | javascript|django|angularjs | 52,607 | <p>Have you forgotten to load AngularJS before your script? The error means that the object <code>angular</code> hasn't been seen by Javascript yet and therefore <code>module</code> cannot be called on it.</p>
<p>(that's actually a simplification but it should illustrate what's going on)</p> |
59,225,879 | How to hide hover tooltips on Spyder 4 | <p>not sure where to ask:</p>
<p><strong>is there a way to not have the help tooltip/popup/hover window opening in spyder?</strong></p>
<p>since updating to 4.0 the window does not close when you change between windows:<a href="https://i.stack.imgur.com/PVD3q.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PVD3q.png" alt="screenshot of the problem"></a></p>
<p>guess something like this will be reported and delt with in future updates but for now i would be happy to just disable it</p>
<p>(using 64-bit windows-10 machine)</p> | 59,237,753 | 1 | 0 | null | 2019-12-07 12:19:11.027 UTC | 2 | 2022-01-13 19:13:33.183 UTC | 2019-12-10 15:14:45.19 UTC | null | 438,386 | null | 8,254,743 | null | 1 | 36 | python|windows-10|spyder | 10,631 | <p>(<em>Spyder maintainer here</em>) Yes, there is. You need to go to the menu</p>
<p><code>Tools > Preferences > Completion and linting > Introspection</code></p>
<p>and deactivate the option called <code>Enable hover hints</code>.</p>
<p><strong>Note</strong>: The issue you posted above with the hover not hiding when giving focus to other applications will be fixed in our next bugfix version (4.1), to be released in a couple of months.</p> |
62,345,805 | NameNotFoundException when calling getPackageInfo on Android 11 | <p>After setting <code>targetSdkVersion</code> to <code>30</code> (Android 11) I'm getting <code>android.content.pm.PackageManager$NameNotFoundException</code> when doing <code>packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)</code> on packages that I know exists.</p>
<p>The stacktrace is as follows:</p>
<pre><code>android.content.pm.PackageManager$NameNotFoundException: com.google.android.apps.maps
at android.app.ApplicationPackageManager.getPackageInfoAsUser(ApplicationPackageManager.java:202)
at android.app.ApplicationPackageManager.getPackageInfo(ApplicationPackageManager.java:174)
</code></pre> | 62,345,806 | 2 | 0 | null | 2020-06-12 13:59:51.783 UTC | 4 | 2022-04-27 07:02:13.903 UTC | null | null | null | null | 467,650 | null | 1 | 31 | android|android-permissions|android-11 | 15,245 | <p>As stated in <a href="https://developer.android.com/preview/privacy/package-visibility" rel="noreferrer">https://developer.android.com/preview/privacy/package-visibility</a>:</p>
<blockquote>
<p>Android 11 changes how apps can query and interact with other apps
that the user has installed on a device. Using the new
element, apps can define the set of other apps that they can access.
This element helps encourage the principle of least privilege by
telling the system which other apps to make visible to your app, and
it helps app stores like Google Play assess the privacy and security
that your app provides for users.</p>
<p>If your app targets Android 11, you might need to add the
element in your app's manifest file. Within the element, you
can specify apps by package name or by intent signature.</p>
</blockquote>
<p>So you either have to stop what you are doing, or request to access information about certain packages, or - if you have reasons for it - use the permission <a href="https://developer.android.com/reference/kotlin/android/Manifest.permission#query_all_packages" rel="noreferrer"><code>QUERY_ALL_PACKAGES</code></a>.</p>
<h1>Query and interact with specific packages</h1>
<p>To query and interact with specific packages you would update your <code>AndroidManifest.xml</code> like this:</p>
<pre><code><manifest ...>
...
<queries>
<package android:name="com.example.store" />
<package android:name="com.example.services" />
</queries>
...
<application ...>
...
</manifest>
</code></pre>
<h1>Query and interact with all apps</h1>
<p>I have an app that needs to be able to ask for information for all apps. All you have to do is to add the following to <code>AndroidManifest.xml</code>:</p>
<pre><code><manifest ...>
...
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
...
<application ...>
...
</manifest>
</code></pre> |
23,582,389 | Rails: NoMethodError (Undefined method _url for _controller. I can't seem to respond_with json properly after my create. Why? | <ol>
<li>List item</li>
</ol>
<p>My config/routes.rb file...</p>
<pre><code>Rails.application.routes.draw do
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
resources :hotels do
resources :rooms
end
end
end
</code></pre>
<p>My app/controllers/api/v1/hotels_controller.rb</p>
<pre><code>module Api
module V1
class HotelsController < ApplicationController
respond_to :json
skip_before_filter :verify_authenticity_token
def index
@hotels = Hotel.all
respond_with ({hotels: @hotels}.as_json)
#respond_with(@hotels)
end
def show
@hotel = Hotel.find(params[:id])
respond_with (@hotel)
end
def create
@hotel = Hotel.new(user_params)
if @hotel.save
respond_with (@hotel) #LINE 21
end
end
private
def user_params
params.require(:hotel).permit(:name, :rating)
end
end
end
end
</code></pre>
<p>When I go to POST through Postman, my data saves just fine, but I get this NoMethodError. Why is this? The issue seems to be occurring at line 21, which is the respond_with(@hotel) line. Should it not just be responding with json ouput for the newly created hotel, via the show method?</p>
<pre><code>(1.1ms) COMMIT
Completed 500 Internal Server Error in 76ms
NoMethodError (undefined method `hotel_url' for #<Api::V1::HotelsController:0x0000010332df58>):
app/controllers/api/v1/hotels_controller.rb:21:in `create'
Rendered /Users/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/actionpack-4.1.0/lib/action_dispatch/middleware/templates/rescues/_source.erb (1.0ms)
Rendered /Users/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/actionpack-4.1.0/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.7ms)
Rendered /Users/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/actionpack-4.1.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.4ms)
Rendered /Users/.rvm/gems/ruby-2.0.0-p451@railstutorial_rails_4_0/gems/actionpack-4.1.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (31.5ms)
</code></pre> | 23,583,414 | 1 | 1 | null | 2014-05-10 14:42:47.59 UTC | 15 | 2014-05-10 16:16:03.177 UTC | null | null | null | null | 1,652,166 | null | 1 | 28 | ruby-on-rails|json|post | 14,199 | <p>Because your route is in the API + v1 namespace, you actually need to redirect to the <code>api_v1_hotel_url(@hotel)</code> after you successfully create your resource. Of course, this is an API and there is no real redirecting, but the default Rails responder doesn't know that. It also doesn't know about your routing namespaces.</p>
<p>With just the default responder, you would have to do</p>
<p><code>respond_with :api, :v1, @hotel</code></p>
<p>So that Rails will build a URL that exists. Alternatively, you can create a custom responder that remove the <code>:location</code> option. Here is the default responder: <a href="http://api.rubyonrails.org/files/actionpack/lib/action_controller/metal/responder_rb.html" rel="noreferrer">http://api.rubyonrails.org/files/actionpack/lib/action_controller/metal/responder_rb.html</a></p>
<p>Reading through the source code for that class is very helpful in understanding <code>respond_with</code>. For example, you don't need to use <code>if record.save</code> before you use <code>respond_with</code> with this Responder. Rails will check if the record saved successfully for you and render a 422 with errors if it failed to save.</p>
<p>Anyway, you can see that the responder sets up a lot of variables in it's initializer:</p>
<pre><code>def initialize(controller, resources, options={})
@controller = controller
@request = @controller.request
@format = @controller.formats.first
@resource = resources.last
@resources = resources
@options = options
@action = options.delete(:action)
@default_response = options.delete(:default_response)
end
</code></pre>
<p>If you subclassed this responder, you could make something like this:</p>
<pre><code>class CustomResponder < ActionController::Responder
def initialize(*)
super
@options[:location] = nil
end
end
</code></pre>
<p>You can set a controller's responder using <code>responder=</code>:</p>
<pre><code>class AnyController < ActionController::Base
self.responder = CustomResponder
# ...
end
</code></pre>
<p>To be clear, let me recap:</p>
<ol>
<li>When you use <code>respond_with</code>, Rails will try to infer what route to redirect to after a successful create. Imagine you had a web UI where you can create hotels. After a hotel is created, you will be redirected to that hotel's <code>show</code> page in the standard Rails flow. That is what Rails is trying to do here.</li>
<li>Rails does not understand your route namespaces when inferring the route, so it attempts <code>hotel_url</code> - a route which does not exist!</li>
<li>Adding symbols in front of the resource will allow Rails to infer the route correctly, in this case <code>api_v1_hotel_url</code></li>
<li>In an API, you can make a custom responder which just sets the inferred location to <code>nil</code>, since you don't actually need to redirect anywhere with a simple JSON response. Custom responders can also be useful in many other ways. Check out the source code. </li>
</ol> |
23,734,686 | c# dictionary get the key of the min value | <p>probably a simple one for you today but I'm currently going round in circles. Consider this scenario:</p>
<pre><code>var tempDictionary = new Dictionary<string, int>();
tempDictionary.Add("user 1", 5);
tempDictionary.Add("user 2", 3);
tempDictionary.Add("user 3", 5);
Console.WriteLine(tempDictionary.Min(x => x.Key) + " => " tempDictionary.Min(x => x.Value);
</code></pre>
<p>The above returns "user 1 => 3".</p>
<p>How would you go about returning the key with the lowest value in a dictionary? The output I'm after would look like this instead: "user2 => 3"</p>
<p>Any ideas?</p> | 23,734,742 | 5 | 1 | null | 2014-05-19 09:52:31.52 UTC | 3 | 2017-01-13 01:19:54.353 UTC | null | null | null | null | 2,479,919 | null | 1 | 22 | c#|linq|dictionary | 38,805 | <p>using <a href="http://code.google.com/p/morelinq/wiki/OperatorsOverview" rel="noreferrer">morelinq</a></p>
<pre><code>var keyR = tempDictionary.MinBy(kvp => kvp.Value).Key;
</code></pre>
<p>or</p>
<pre><code> var min = tempDictionary.Aggregate((l, r) => l.Value < r.Value ? l : r).Key;
</code></pre>
<p>from <a href="https://stackoverflow.com/questions/2805703/good-way-to-get-the-key-of-the-highest-value-of-a-dictionary-in-c-sharp">Highest value of a Dictionary in C#</a></p> |
25,715,898 | What's the difference between Git ignoring directory and directory/*? | <p>I'm confused about what's the correct way to ignore the contents of a directory in git.</p>
<p>Assume I have the following directory structure:</p>
<pre><code>my_project
|--www
|--1.txt
|--2.txt
|--.gitignore
</code></pre>
<p>What's the difference between putting this:</p>
<pre><code>www
</code></pre>
<p>And this?</p>
<pre><code>www/*
</code></pre>
<p>The reason I'm asking this question is: In git, if a directory is empty, git won't include such empty directory in repository. So I was trying the solution that is add an extra .gitkeep file under the directory so that it won't be empty. When I was trying that solution, if in the .gitignore file, I write like below:</p>
<pre><code>www
!*.gitkeep
</code></pre>
<p>It doesn't work(My intention is to ignore all contents under www but keep the directory). But if I try the following:</p>
<pre><code>www/*
!*.gitkeep
</code></pre>
<p>Then it works! So I think it must has some differences between the two approaches.</p> | 25,716,803 | 4 | 1 | null | 2014-09-08 00:03:33.413 UTC | 19 | 2014-09-25 18:45:35.033 UTC | 2014-09-25 18:45:35.033 UTC | null | 2,174,742 | null | 2,303,252 | null | 1 | 109 | git|gitignore|notation|dotfiles | 4,974 | <p>There're differences among <code>www</code>, <code>www/</code> and <code>www/*</code>.</p>
<p><strong>Basically from the <a href="http://git-scm.com/docs/gitignore" rel="noreferrer">documentation</a> and my own tests, <code>www</code> find a match with a file or a directory, <code>www/</code> only matches a directory, while <code>www/*</code> matches directories and files inside <code>www</code>.</strong></p>
<p>I'll only discuss on the differences between <code>www/</code> and <code>www/*</code> here, since the differences between <code>www</code> and <code>www/</code> are obvious.</p>
<p>For <code>www/</code>, git ignores the directory <code>www</code> itself, which means git won't even look inside. But for <code>www/*</code>, git checks all files/folders inside <code>www</code>, and ignores all of them with the pattern <code>*</code>. It seems to lead to the same results since git won't track an empty folder <code>www</code> if all its child files/folders are ignored. And indeed the results will be no difference for OP's case with <code>www/</code> or <code>www/*</code> standalone. But it does make differences if it's combined with other rules. </p>
<p>For example, what if we want to only include <code>www/1.txt</code> but ignore all others inside <code>www</code>?</p>
<p>The following <code>.gitignore</code> won't work.</p>
<pre><code>www/
!www/1.txt
</code></pre>
<p>While the following <code>.gitignore</code> works, why?</p>
<pre><code>www/*
!www/1.txt
</code></pre>
<p>For the former, git just ignores the directory <code>www</code>, and won't even look inside to include <code>www/1.txt</code> again. The first rule excludes the parent directory <code>www</code> but not <code>www/1.txt</code>, and as a result <code>www/1.txt</code> cannot be "<strong>included again</strong>". </p>
<p>But for the latter, git first ignores all files/folers under <code>www</code>, and then includes one of them again which is <code>www/1.txt</code>.</p>
<p>For this example, the follwing lines in the documentation may help:</p>
<blockquote>
<p>An optional prefix "!" which negates the pattern; any matching file
excluded by a previous pattern will become included again. It is not
possible to re-include a file if a parent directory of that file is
excluded.</p>
</blockquote> |
29,665,183 | Using git to see all logs related to a specific file extension within subdirectories | <p>I am trying to see the commits in the history of a repository but just for files with an specific extension.</p>
<p>If this is the directory structure:</p>
<pre><code>$ tree
.
├── a.txt
├── b
└── subdir
├── c.txt
└── d
</code></pre>
<p>And this is the full history:</p>
<pre><code>$ git log --name-only --oneline
a166980 4
subdir/d
1a1eec6 3
subdir/c.txt
bc6a027 2
b
f8d4414 1
a.txt
</code></pre>
<p>If I want to see logs for file with .txt extension:</p>
<pre><code>$ git log --oneline *.txt
f8d4414 1
</code></pre>
<p>It returns only the file that is in the current directory, not in subdirectories. I want to include all possible subdirectories inside the current directory. </p>
<p>I've also tried:</p>
<pre><code>$ git log --oneline */*.txt
1a1eec6 3
</code></pre>
<p>And:</p>
<pre><code>$ git log --oneline *.txt */*.txt
1a1eec6 3
f8d4414 1
</code></pre>
<p>That works for this case, but it is not practical for more generic cases.</p>
<p>And:</p>
<pre><code>$ git log --oneline HEAD -- *.txt
f8d4414 1
</code></pre>
<p>Without success.</p> | 29,665,291 | 1 | 2 | null | 2015-04-16 04:09:22.627 UTC | 3 | 2019-01-07 22:32:44.903 UTC | null | null | null | null | 2,109,534 | null | 1 | 29 | git|git-log | 7,793 | <p>Try:</p>
<pre><code>git log --oneline -- '*.txt'
</code></pre>
<p>The <code>--</code> is used to indicate only positional arguments will follow. And <code>'*.txt'</code> searches all folders from the current directory on down. </p>
<p>Alternatively, you could limit the results by starting the search in a subdirectory, e.g. <code>-- 'sub/*.txt'</code>.</p> |
4,732,634 | How to set the header and footer for linear layout in android | <p>Can anybody tell me how to set a fixed header and footer for relative layout and center point? I want to add scrollable and adding array of webview dynamically when I want to scroll center point only scrollable in android. Can anybody give an example?</p>
<p>I tried but center part webview is not appearing properly, is there anything to change?</p>
<p>my xml code is </p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mainrelativelayout" android:layout_width="fill_parent" android:layout_height="fill_parent">
</code></pre>
<p>
</p>
<pre><code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/linear1" android:layout_height="wrap_content"
android:orientation="horizontal"
>
<TextView android:paddingRight="75dip" android:paddingLeft="20dip" android:text="Index" android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textStyle="bold"></TextView>
<TextView android:paddingRight="60dip" android:text="Last" android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textStyle="bold"></TextView>
<TextView android:text="Change" android:id="@+id/TextView03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textStyle="bold"></TextView>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/linear1" android:layout_height="6dip"
android:orientation="horizontal"
>
<ImageView android:id="@+id/ImageView08" android:layout_gravity="center" android:background="@drawable/line" android:layout_width="fill_parent" android:layout_height="wrap_content"></ImageView>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/linear2"
android:orientation="horizontal"
>
<ImageView android:id="@+id/ImageView05" android:paddingTop="5dip" android:layout_gravity="center" android:background="@drawable/down" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
<TextView android:paddingRight="30dip" android:paddingLeft="10dip" android:text="" android:id="@+id/txtindex0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textSize="12dip"></TextView>
<TextView android:paddingRight="55dip" android:text="" android:id="@+id/txtlast0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textSize="12dip"></TextView>
<TextView android:text="" android:id="@+id/txtchange0" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12dip" android:textColor="@color/red1"></TextView>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/linear3"
android:orientation="horizontal"
>
<ImageView android:id="@+id/ImageView02" android:layout_gravity="center" android:background="@drawable/up" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
<TextView android:paddingRight="46dip" android:paddingLeft="10dip" android:text="" android:id="@+id/txtindex1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textSize="12dip"></TextView>
<TextView android:paddingRight="64dip" android:text="" android:id="@+id/txtlast1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textSize="12dip"></TextView>
<TextView android:text="" android:id="@+id/txtchange1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12dip" android:textColor="@color/green1"></TextView>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/linear4"
android:orientation="horizontal"
>
<ImageView android:id="@+id/ImageView03" android:layout_gravity="center" android:background="@drawable/up" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
<TextView android:paddingRight="69dip" android:paddingLeft="10dip" android:text="" android:id="@+id/txtindex2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textSize="12dip"></TextView>
<TextView android:paddingRight="67dip" android:text="" android:id="@+id/txtlast2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textSize="12dip"></TextView>
<TextView android:text="" android:id="@+id/txtchange2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12dip" android:textColor="@color/green1"></TextView>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/linear4"
android:orientation="horizontal"
>
<ImageView android:id="@+id/ImageView04" android:layout_gravity="center" android:background="@drawable/up" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
<TextView android:paddingRight="61dip" android:paddingLeft="10dip" android:text="" android:id="@+id/txtindex3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textSize="12dip"></TextView>
<TextView android:paddingRight="65dip" android:text="" android:id="@+id/txtlast3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/black" android:textSize="12dip"></TextView>
<TextView android:text="" android:id="@+id/txtchange3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12dip" android:textColor="@color/green1"></TextView>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/linear1" android:layout_height="4dip"
android:orientation="horizontal"
>
<ImageView android:id="@+id/ImageView08" android:layout_gravity="center" android:background="@drawable/line" android:layout_width="fill_parent" android:layout_height="wrap_content"></ImageView>
</LinearLayout>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="15dip"
android:id="@+id/linear5"
android:orientation="horizontal"
>
<TextView android:text="Market data delayed at least 15 minutes " android:id="@+id/TextView16" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="12dip" android:textColor="@color/gray2"></TextView>
</LinearLayout>
</LinearLayout>
<------ finishing header-------->
</code></pre>
<p><---------- adding footer-----------></p>
<pre><code><LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/imglinear"
android:background="@color/white"
android:layout_alignParentBottom="true"
>
<ImageView android:id="@+id/ImageView15" android:src="@drawable/quest_i" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
</LinearLayout>
</code></pre>
<p><--------------finishing footer-------></p>
<p><------------ center point of screen---------></p>
<pre><code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@color/white"
android:id="@+id/mainlinear3"
android:layout_above="@+id/imglinear"
android:layout_below="@+id/mainlinear2"
>
<ScrollView android:id="@+id/ScrollView01"
android:layout_width="wrap_content" android:layout_height="wrap_content">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="@color/white"
android:id="@+id/relative3">
</RelativeLayout>
</ScrollView>
</RelativeLayout>
</code></pre>
<p><-----------center point finishing----------></p>
<pre><code></RelativeLayout>
</code></pre>
<p>thanks</p> | 4,743,923 | 1 | 2 | null | 2011-01-19 07:12:19.31 UTC | 10 | 2014-05-06 11:08:25.427 UTC | 2014-05-06 11:08:25.427 UTC | null | 3,338,050 | null | 426,344 | null | 1 | 15 | android|android-layout | 34,686 | <pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- HEADER -->
<include android:id="@+id/top_header"
android:layout_alignParentTop="true" layout="@layout/layout_header" />
<!-- FOOTER -->
<LinearLayout android:id="@+id/bottom_menu"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="vertical" android:layout_alignParentBottom="true">
<!-- menu bar -->
<include layout="@layout/layout_footer_menu" />
</LinearLayout>
<!-- MAIN PART -->
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:layout_below="@id/top_header" android:layout_above="@id/bottom_menu"
android:layout_weight="1"
android:id="@+id/sub_content_view"
android:paddingBottom="5sp" android:background="#EAEAEA">
</LinearLayout>
</RelativeLayout>
</code></pre>
<p>It is better to set to MAIN PART both:</p>
<p>android:layout_below="@id/top_header"
android:layout_above="@id/bottom_menu"</p>
<p>In your case content will be under the footer and scroll bar will be shown incorrect.</p>
<p>Also you need place footer in code above content - android want see ID's (@id/bottom_menu) if it wasn't define before.</p> |
54,837,854 | Expand widgets inside the Stack widget | <p>I have a stack widgets with two widgets inside.
One of them draws the background, the other one draws on top of that.
I want both widgets to have the same size.</p>
<p>I want the top widget, which is a column, to expand and fill the stack vertically to the size that is set by the background widget.
I tried setting the MainAxis <code>mainAxisSize: MainAxisSize.max</code> but it didn't work.</p>
<p>How can I make it work?</p> | 56,988,892 | 5 | 3 | null | 2019-02-23 03:06:25.233 UTC | 5 | 2022-09-11 17:37:59.76 UTC | 2022-03-17 03:05:49.797 UTC | user10563627 | null | null | 617,157 | null | 1 | 36 | flutter|expand|flutter-widget | 18,252 | <h1>Use <code>Positioned.fill</code></h1>
<pre><code> Stack(
children: [
Positioned.fill(
child: Column(
children: [
//...
],
),
),
//...
],
);
</code></pre>
<p>More info about <code>Positioned</code> in <a href="https://youtu.be/EgtPleVwxBQ" rel="noreferrer">Flutter Widget of the Week</a></p>
<h2>How does it work?</h2>
<p>This is all about constraints. Constraints are min/max width/height values that are passed from the parent to its children. In the case of <code>Stack</code>. The constraints it passes to its children state that they can size themselves as small as they want, which in the case of some widgets means they will be their "natural" size. After being sized, <code>Stack</code> will place its children in the top left corner.<br />
<code>Positioned.fill</code> gets the same constraints from <code>Stack</code> but passes different constraints to its child, stating the it (the child) must be of exact size (which meant to fill the <code>Stack</code>).</p>
<p><code>Positioned.fill()</code> is the same as:</p>
<pre><code>Positioned(
top: 0,
right: 0,
left: 0,
bottom:0,
child: //...
)
</code></pre>
<h2>For even more examples and info: <a href="https://www.fourmanalex.com/post/how-to-fill-a-stack-widget-and-why" rel="noreferrer">How to fill a Stack widget and why?</a> and <a href="https://flutter.dev/docs/development/ui/layout/constraints" rel="noreferrer">Understanding constraints.</a></h2> |
31,247,991 | How to programmatically select a row in UITableView in Swift | <p>I need to select a row in a UITableView programmatically using Swift 1.2. </p>
<p>This is the simple code:</p>
<pre><code>var index = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.selectRowAtIndexPath(index, animated: true, scrollPosition: UITableViewScrollPosition.Middle)
self.tableView(self.tableView, didSelectRowAtIndexPath: index)
</code></pre>
<p>The above gives me the following error:</p>
<blockquote>
<p><strong>Cannot invoke 'selectRowAtIndexPath' with an argument list of type '(NSIndexPath!, animated: Bool, scrollPosition: UITableViewScrollPosition)'</strong></p>
</blockquote>
<p>What is wrong with my Swift 1.2 code?</p>
<p>My UItableView has been created in IB in the UIViewController that I am trying to call the code above.
When I put the code in a UITableViewController the compiler does not give any errors.
Do I need to embed a UITableViewController in a container or is there another way?</p> | 31,272,322 | 7 | 6 | null | 2015-07-06 14:06:10.133 UTC | 11 | 2020-11-20 22:18:29.383 UTC | 2019-04-25 04:20:58.277 UTC | null | 1,033,581 | null | 3,655,065 | null | 1 | 69 | ios|swift|uitableview | 70,920 | <p>The statement</p>
<pre><code>self.tableView.selectRowAtIndexPath(index, animated: true, scrollPosition: UITableViewScrollPosition.Middle)
</code></pre>
<p>assumes that <code>tableView</code> is a property of the view controller, connected
to a table view in the Storyboard. A <code>UITableViewController</code>, for example, already has this
property. </p>
<p>In your case, the view controller is a not a table view controller
but a subclass of a <code>UIViewController</code>. It also has an outlet that is
connected to the table view, but it is not called
<code>tableView</code> but <code>menuTable</code>. Then of course you have to call</p>
<pre><code>self.menuTable.selectRowAtIndexPath(index, animated: true, scrollPosition: UITableViewScrollPosition.Middle)
</code></pre>
<p>to select a row of that table view.</p>
<p>The strange error messages are caused by the fact that
<code>self.tableView</code> can also be understood by the compiler as a
"curried function" (compare <a href="http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/">http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/</a>).</p> |
39,340,169 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" How does that work? | <p>I need to get the path of the script. I can do that using <code>pwd</code> if I am already in the same directory, I searched online and I found this</p>
<p><code>DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"</code></p>
<p>But I don't know how to use that.</p> | 39,340,259 | 1 | 5 | null | 2016-09-06 03:20:57.587 UTC | 28 | 2021-02-04 08:19:38.813 UTC | 2021-02-04 08:19:38.813 UTC | null | 6,294,371 | null | 5,357,095 | null | 1 | 68 | linux|bash|shell|unix|scripting | 51,435 | <p>Bash maintains a number of variables including <code>BASH_SOURCE</code> which is an array of source file pathnames.</p>
<p><code>${}</code> acts as a kind of quoting for variables.</p>
<p><code>$()</code> acts as a kind of quoting for commands but they're run in their own context.</p>
<p><code>dirname</code> gives you the path portion of the provided argument.</p>
<p><code>cd</code> changes the current directory.</p>
<p><code>pwd</code> gives the current path.</p>
<p><code>&&</code> is a logical <code>and</code> but is used in this instance for its side effect of running commands one after another.</p>
<p>In summary, that command gets the script's source file pathname, strips it to just the path portion, <code>cd</code>s to that path, then uses <code>pwd</code> to return the (effectively) full path of the script. This is assigned to <code>DIR</code>. After all of that, the context is unwound so you end up back in the directory you started at but with an environment variable <code>DIR</code> containing the script's path.</p> |
20,249,274 | Find and replace Android studio | <p>Is there a way to find and replace all occurrences of a word in an entire project( not just a single class using refactor -> rename) and also maintain case, either in android studio or using a command line script?</p>
<p>For example, Supplier has to go to Merchant, supplier -> merchant, SUPPLIER -> MERCHANT. My boss wants me to change all instances of supplier with merchant for a project im working on. Ive been doing it for about an hour and i know im wasting my time. Let me know of any time saving suggestions.</p> | 20,249,766 | 11 | 1 | null | 2013-11-27 17:34:52.707 UTC | 48 | 2022-04-15 19:52:34.333 UTC | 2018-10-19 19:29:31.463 UTC | null | 2,813,306 | null | 2,342,568 | null | 1 | 333 | android|android-studio|refactoring|renaming | 282,083 | <p>I think the shortcut that you're looking for is:</p>
<p><kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd> on Windows and Linux/Ubuntu</p>
<p><kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd> on macOS (IntelliJ IDEA Classic keymap)</p>
<p><kbd>Cmd</kbd>+<kbd>Shift</kbd>+<kbd>R</kbd> on macOS (macOS keymap)</p>
<p>ref: <a href="http://www.jetbrains.com/idea/webhelp/find-and-replace-in-path.html" rel="noreferrer">source</a></p> |
6,600,592 | Change lock screen background audio controls text? | <p>I have an iOS app that streams background audio using AVAudioSession. It is working correctly, but I am curious, is there any way to change the text on the lock screen audio controls? Right now it simply displays the name of my app, but I would like to change it to the name of the track. </p>
<p>Additionally, the multi-tasking bar has no text under the controls- is there a way to add the track name there, as the iPod app does?</p> | 7,797,712 | 2 | 1 | null | 2011-07-06 17:33:53.617 UTC | 10 | 2021-02-11 10:43:42.54 UTC | 2016-01-07 09:28:12.777 UTC | null | 3,908,884 | null | 625,709 | null | 1 | 27 | ios|objective-c|swift|avaudiosession|mpnowplayinginfocenter | 9,576 | <p>iOS 5 now supports setting the track title as well as an album art image in both the lock screen and the remote playback controls (the controls you get when you double-click the home button and swipe right). Take a look at the
<A HREF="https://developer.apple.com/library/ios/#documentation/MediaPlayer/Reference/MPNowPlayingInfoCenter_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40010927" rel="noreferrer"><code>MPNowPlayingInfoCenter</code></A> class. Of course, to maximize compatibility, you'd want to test whether <code>MPNowPlayingInfoCenter</code> is available, by doing something like:</p>
<pre><code>if ([MPNowPlayingInfoCenter class]) {
/* we're on iOS 5, so set up the now playing center */
UIImage *albumArtImage = [UIImage imageNamed:@"HitchHikersGuide"];
albumArt = [[MPMediaItemArtwork alloc] initWithImage:albumArtImage];
NSDictionary *currentlyPlayingTrackInfo = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"Life, the Universe and Everything", [NSNumber numberWithInt:42], albumArt, nil] forKeys:[NSArray arrayWithObjects:MPMediaItemPropertyTitle, MPMediaItemPropertyPlaybackDuration, MPMediaItemPropertyArtwork, nil]];
[MPNowPlayingInfoCenter defaultCenter].nowPlayingInfo = currentlyPlayingTrackInfo;
}
</code></pre> |
55,201,561 | Golang run on Windows without deal with the Firewall | <p>I'm working on a Rest API with Go, but everytime I try to run my application with</p>
<pre><code>go run main.go
</code></pre>
<p>the Windows Firewall tells me that has blocked some features of my app. I would like to know if there's some way to make my executions without have to <em>Accept</em> everytime.</p> | 65,393,403 | 9 | 1 | null | 2019-03-16 21:16:23.18 UTC | 3 | 2022-03-22 09:03:50.247 UTC | null | null | null | null | 2,093,371 | null | 1 | 31 | go|windows-firewall | 12,185 | <p>Hi I had the same problem:
Try that:</p>
<ol>
<li>Go to <strong>Windows Defender Firewall</strong>, in Left side menu you saw <strong>Inbound Rules</strong> click there, then Right Side menu you will see <strong>New Rule...</strong> click.</li>
<li><em>Choose Port</em> opened from window -> <strong>Next</strong>
<em>Select TCP</em>, then <em>define which ports you want</em> I choose 8080 click <strong>Next</strong> again, Choose <em>Allow the connection</em> <strong>Next</strong>, Check All <strong>Next</strong>, <em>Give any Name</em> Goland or anything you want and press <strong>Finish</strong>. Thats it</li>
</ol> |
7,247,202 | How to use variable in CSS? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/47487/create-a-variable-in-css-file-for-use-within-that-css-file">Create a variable in .CSS file for use within that .CSS file</a> </p>
</blockquote>
<p>I heard about that we can declare/define variable in CSS and use them like global variables like this:</p>
<pre><code>@nice-blue: #5B83AD;
#header { color: @nice-blue; }
</code></pre>
<p>So anyone knows how to use them?</p> | 7,247,226 | 3 | 4 | null | 2011-08-30 17:21:07.473 UTC | 6 | 2018-01-15 13:56:07.057 UTC | 2017-05-23 12:18:06.173 UTC | null | -1 | null | 690,873 | null | 1 | 26 | css|variables|global-variables | 79,186 | <p>For that you need to use <a href="http://lesscss.org/" rel="nofollow noreferrer"><strong>Less</strong></a> or <a href="http://sass-lang.com/" rel="nofollow noreferrer"><strong>Sass</strong></a> which are CSS Dynamic languages. </p>
<p>here's some <a href="https://web.archive.org/web/20130122062617/http://wrangl.com/sass-v-less" rel="nofollow noreferrer">comparison</a> between both technologies.</p> |
7,214,039 | How do you move a commit to the staging area in git? | <p>If you want to move a commit to the staging area - that is uncommit it and move all of the changes which were in it into the staging area (effectively putting the branch in the state that it would have been in prior to the commit) - how do you do it? Or is it something that you can't do?</p>
<p>The closest that I know how to do is to copy all of the files that were changed in the commit to somewhere else, reset the branch to the commit before the commit that you're trying to move into the staging area, move all of the copied files back into the repository, and then add them to the staging area. It works, but it's not exactly a nice solution. What I'd like to be able to do is just undo the commit and move its changing into the staging area. Can it be done? And if so, how?</p> | 7,214,061 | 3 | 0 | null | 2011-08-27 10:48:13.67 UTC | 53 | 2021-03-29 10:36:23.077 UTC | null | null | null | null | 160,887 | null | 1 | 223 | git|commit|staging | 112,763 | <pre><code>git reset --soft HEAD^
</code></pre>
<p>This will reset your index to <code>HEAD^</code> (the previous commit) but leave your changes in the staging area.</p>
<p>There are some <a href="https://git-scm.com/docs/git-reset#_discussion" rel="noreferrer">handy diagrams</a> in the <a href="http://git-scm.com/docs/git-reset" rel="noreferrer"><code>git-reset</code></a> docs</p>
<p>If you are on Windows you might need to use this format:</p>
<pre><code>git reset --soft HEAD~1
</code></pre> |
7,684,475 | Plotting labeled intervals in matplotlib/gnuplot | <p>I have a data sample which looks like this:</p>
<pre><code>a 10:15:22 10:15:30 OK
b 10:15:23 10:15:28 OK
c 10:16:00 10:17:10 FAILED
b 10:16:30 10:16:50 OK
</code></pre>
<p>What I want is to plot the above data in the following way:</p>
<pre><code>captions ^
|
c | *------*
b | *---* *--*
a | *--*
|___________________
time >
</code></pre>
<p>With the color of lines depending on the <code>OK/FAILED</code> status of the data point. Labels (<code>a/b/c/...</code>) may or may not repeat.</p>
<p>As I've gathered from documentation for <strong>gnuplot</strong> and <strong>matplotlib</strong>, this type of a plot should be easier to do in the latter as it's not a standard plot and would require some preprocessing. </p>
<p>The question is:</p>
<ol>
<li>Is there a standard way to do plots like this in any of the tools?</li>
<li>If not, how should I go about plotting this data (pointers to relevant tools/documentation/functions/examples which do something-kinda-like the thing described here)?</li>
</ol> | 7,685,336 | 4 | 0 | null | 2011-10-07 07:54:52.287 UTC | 12 | 2022-06-29 09:05:08.95 UTC | null | null | null | null | 193,033 | null | 1 | 28 | plot|matplotlib|gnuplot|intervals | 18,515 | <p>Updated: Now includes handling the data sample and uses mpl dates functionality.</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter, MinuteLocator, SecondLocator
import numpy as np
from StringIO import StringIO
import datetime as dt
### The example data
a=StringIO("""a 10:15:22 10:15:30 OK
b 10:15:23 10:15:28 OK
c 10:16:00 10:17:10 FAILED
b 10:16:30 10:16:50 OK
""")
#Converts str into a datetime object.
conv = lambda s: dt.datetime.strptime(s, '%H:%M:%S')
#Use numpy to read the data in.
data = np.genfromtxt(a, converters={1: conv, 2: conv},
names=['caption', 'start', 'stop', 'state'], dtype=None)
cap, start, stop = data['caption'], data['start'], data['stop']
#Check the status, because we paint all lines with the same color
#together
is_ok = (data['state'] == 'OK')
not_ok = np.logical_not(is_ok)
#Get unique captions and there indices and the inverse mapping
captions, unique_idx, caption_inv = np.unique(cap, 1, 1)
#Build y values from the number of unique captions.
y = (caption_inv + 1) / float(len(captions) + 1)
#Plot function
def timelines(y, xstart, xstop, color='b'):
"""Plot timelines at y from xstart to xstop with given color."""
plt.hlines(y, xstart, xstop, color, lw=4)
plt.vlines(xstart, y+0.03, y-0.03, color, lw=2)
plt.vlines(xstop, y+0.03, y-0.03, color, lw=2)
#Plot ok tl black
timelines(y[is_ok], start[is_ok], stop[is_ok], 'k')
#Plot fail tl red
timelines(y[not_ok], start[not_ok], stop[not_ok], 'r')
#Setup the plot
ax = plt.gca()
ax.xaxis_date()
myFmt = DateFormatter('%H:%M:%S')
ax.xaxis.set_major_formatter(myFmt)
ax.xaxis.set_major_locator(SecondLocator(interval=20)) # used to be SecondLocator(0, interval=20)
#To adjust the xlimits a timedelta is needed.
delta = (stop.max() - start.min())/10
plt.yticks(y[unique_idx], captions)
plt.ylim(0,1)
plt.xlim(start.min()-delta, stop.max()+delta)
plt.xlabel('Time')
plt.show()
</code></pre>
<p><img src="https://i.stack.imgur.com/qNEhE.png" alt="Resulting image"></p> |
7,559,205 | Are CSS selectors case-sensitive? | <p>I was recently updating a CMS site and a tab-navigation plugin had inserted the following markup:</p>
<pre><code><li id="News_tab">...
</code></pre>
<p>I've always written my CSS selectors in lowercase so when I tried to style this with <code>#news_tab</code>, it wouldn't apply, but <code>#News_tab</code> worked. </p>
<p>After all these years I'm surprised that I haven't run into this before, so I've always been under the impression that CSS was case-insensitive. Has CSS always been case-sensitive and I just haven't noticed thanks to my consistent code style?</p> | 7,559,251 | 4 | 3 | null | 2011-09-26 18:00:32.59 UTC | 6 | 2019-01-14 14:02:31.347 UTC | null | null | null | null | 61,439 | null | 1 | 31 | css|cross-browser|css-selectors | 18,681 | <p>CSS itself is case insensitive, but selectors from HTML (class and id) are case sensitive:</p>
<p><a href="http://www.w3.org/TR/CSS2/syndata.html#characters">CSS recommendation on case sensitivity</a></p>
<p><a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#adef-id">HTML recommendation, id attribute</a> (note the [CS])</p> |
7,823,346 | mvn tomcat7:run - How does it work? | <p>I just want to understand, because I got the code from another question, and it's working fine, but I don't understand the flow of this operation.</p>
<p>This is my understanding of Apache Maven Tomcat plugin for Tomcat 7, when using mvn tomcat7:run with following configuration:</p>
<pre><code><plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.0-SNAPSHOT</version>
<configuration>
<path>/${project.build.finalName}</path>
</configuration>
</plugin>
</code></pre>
<p>It creates a new Tomcat 7 instance with default configuration, then use project war file as a deployed project in this instance, am I right, please correct me if I am wrong, or someone please describe to me how this process is working, thanks in advance.</p> | 7,828,084 | 1 | 0 | null | 2011-10-19 14:59:33.27 UTC | 9 | 2011-10-19 21:02:27.303 UTC | 2011-10-19 21:00:50.94 UTC | null | 843,804 | null | 1,000,194 | null | 1 | 27 | tomcat|maven|tomcat7|maven-tomcat-plugin | 32,642 | <p><code>pom.xml</code> of the <code>tomcat7-maven-plugin</code> depends on Tomcat's bundles. Maven download them and the plugin starts an embedded Tomcat instance with the webproject.</p>
<p><code>mvn -X tomcat7:run</code> prints the configuration. Some interesting parts:</p>
<pre><code>[INFO] Preparing tomcat7:run
[DEBUG] (s) resources = [Resource {targetPath: null, filtering: false,
FileSet {directory: /workspace/webtest1/src/main/resources,
PatternSet [includes: {}, excludes: {}]}}]
...
[DEBUG] (f) additionalConfigFilesDir = /workspace/webtest1/src/main/tomcatconf
[DEBUG] (f) configurationDir = /workspace/webtest1/target/tomcat
...
[DEBUG] (f) path = /webtest1
...
[DEBUG] (f) port = 8080
[DEBUG] (f) project = ...:webtest1:0.0.1-SNAPSHOT @ /workspace/webtest1/pom.xml
...
[DEBUG] (f) warSourceDirectory = /workspace/webtest1/src/main/webapp
...
[INFO] Creating Tomcat server configuration at /workspace/webtest1/target/tomcat
...
[DEBUG] adding classPathElementFile file:/workspace/webtest1/target/classes/
[DEBUG] add dependency to webapploader org.slf4j:slf4j-api:1.5.6:compile
...
</code></pre>
<p><code>warSourceDirectory</code> points to <code>src</code> (not <code>target</code>), so it runs as an usual dynamic web project, you could change your JSPs, HTMLs and it will visible immediately. Because of that the <code>target/tomcat/webapps</code> folder is empty.</p>
<p>The site of v1.2 contains a more detailed documentation than the site of 2.0-SNAPSHOT about configuration: <a href="http://mojo.codehaus.org/tomcat-maven-plugin/plugin-info.html">http://mojo.codehaus.org/tomcat-maven-plugin/plugin-info.html</a>. </p> |
7,718,780 | how to undo git submodule update | <p>I accidentally checked in a wrong submodule update: ( as part of a bigger commit )</p>
<p>-Subproject commit 025ffc<br>
+Subproject commit f59250</p>
<p>It is already pushed to the remote..</p>
<p>How do I undo this update?</p> | 7,719,325 | 1 | 0 | null | 2011-10-10 21:15:54.377 UTC | 6 | 2011-10-10 22:28:31.533 UTC | null | null | null | null | 514,748 | null | 1 | 31 | git|undo|git-submodules | 12,953 | <p>Run <code>git checkout 025ffc</code> in the submodule directory and then <code>git add SubmoduleName; git commit -m 'Some message'</code> in the main directory.</p>
<p>(Remember that checking out a commit through its hash leaves you in "detached HEAD state", meaning that you're not on any branch. So if there already is a branch pointing to <code>025ffc</code> in the submodule repository, you should check out that branch; otherwise, you'll probably want to create a branch there and check it out.)</p> |
7,992,678 | What are the possible user.agent values in gwt.xml? | <p>I was wondering what are the possible user.agent values in gwt.xml. I found some of them but unfortunately not the complete list.<p></p>
<ul>
<li>Chrome - safari</li>
<li>Firefox - gecko1_8</li>
<li>Internet Explorer 6 - ie6 </li>
</ul>
<p>What are the others?? Opera, ie7, ie8, ... etc.</p> | 7,992,793 | 1 | 0 | null | 2011-11-03 09:33:51.537 UTC | 10 | 2016-10-18 20:59:58.76 UTC | 2014-01-27 08:53:46.063 UTC | null | 643,271 | null | 643,271 | null | 1 | 54 | xml|gwt|properties | 37,267 | <p>Depends on the version of GWT, but here's the latest: <a href="https://gwt.googlesource.com/gwt/+/master/user/src/com/google/gwt/useragent/UserAgent.gwt.xml" rel="noreferrer">https://gwt.googlesource.com/gwt/+/master/user/src/com/google/gwt/useragent/UserAgent.gwt.xml</a></p>
<p><strong>UPDATE</strong>: the module has moved from <code>com.google.gwt.user.UserAgent</code> to <code>com.google.gwt.useragent.UserAgent</code>, link above updated.</p>
<p><strong>UPDATE 2</strong>: GWT sources have moved to gwt.googlesource.com</p> |
59,435,293 | TypeORM Entity in NESTJS - Cannot use import statement outside a module | <p>Started new project with 'nest new' command. Works fine until I add entity file to it.</p>
<p>Got following error:</p>
<blockquote>
<p>import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';</p>
<p>^^^^^^</p>
<p>SyntaxError: Cannot use import statement outside a module</p>
</blockquote>
<p>What do I miss?</p>
<p>Adding Entity to Module:</p>
<pre><code>import { Module } from '@nestjs/common';
import { BooksController } from './books.controller';
import { BooksService } from './books.service';
import { BookEntity } from './book.entity';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [TypeOrmModule.forFeature([BookEntity])],
controllers: [BooksController],
providers: [BooksService],
})
export class BooksModule {}
</code></pre>
<p>app.module.ts:</p>
<pre><code>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Connection } from 'typeorm';
import { BooksModule } from './books/books.module';
@Module({
imports: [TypeOrmModule.forRoot()],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
</code></pre> | 59,607,836 | 26 | 4 | null | 2019-12-21 10:11:35.71 UTC | 21 | 2022-08-05 09:53:42.783 UTC | 2019-12-24 12:25:02.237 UTC | null | 1,811,410 | null | 1,811,410 | null | 1 | 99 | nestjs|typeorm | 89,408 | <p>My assumption is that you have a <code>TypeormModule</code> configuration with an <code>entities</code> property that looks like this:</p>
<pre><code>entities: ['src/**/*.entity.{ts,js}']
</code></pre>
<p>or like</p>
<pre><code>entities: ['../**/*.entity.{ts,js}']
</code></pre>
<p>The error you are getting is because you are attempting to import a <code>ts</code> file in a <code>js</code> context. So long as you aren't using webpack you can use this instead so that you get the correct files</p>
<pre><code>entities: [join(__dirname, '**', '*.entity.{ts,js}')]
</code></pre>
<p>where <code>join</code> is imported from the <code>path</code> module. Now <code>__dirname</code> will resolve to <code>src</code> or <code>dist</code> and then find the expected <code>ts</code> or <code>js</code> file respectively. let me know if there is still an issue going on.</p>
<h2>EDIT 1/10/2020</h2>
<p>The above assumes the configuration is done is a javascript compatible file (<code>.js</code> or in the <code>TypeormModule.forRoot()</code> passed parameters). If you are using an <code>ormconfig.json</code> instead, you should use</p>
<pre class="lang-json prettyprint-override"><code>entities: ["dist/**/*.entity.js"]
</code></pre>
<p>so that you are using the compiled js files and have no chance to use the ts files in your code.</p> |
2,194,284 | How to get the last column index reading excel file? | <p>How do i get the index of the last column when reading a <code>xlsx</code> file using the Apache POI API?</p>
<p>There's a <code>getLastRowNum</code> method, but I can't find nothing related to the number of columns...</p>
<p><br>
EDIT:
I'm dealing with <code>XLSX</code> files</p> | 2,194,695 | 4 | 0 | null | 2010-02-03 18:16:09.55 UTC | 3 | 2021-04-16 14:40:25.283 UTC | 2015-07-28 21:51:31.613 UTC | null | 685,641 | null | 181,915 | null | 1 | 17 | java|apache-poi|xssf | 55,119 | <p>I think you'll have to iterate through the rows and check <a href="http://poi.apache.org/apidocs/dev/org/apache/poi/hssf/usermodel/HSSFRow.html#getLastCellNum--" rel="nofollow noreferrer"><code>HSSFRow.getLastCellNum()</code></a> on each of them.</p> |
42,927,933 | How can I add a link/href/hyperlink in JSON script | <p>I want to create a dynamic array/script and I need to add some link in my JSON return so that, I can create a long array which inculude dynamic list or sources with a prepared JSON file.</p>
<p><img src="https://i.stack.imgur.com/5Fzj3.jpg" alt="My HTML's picture"></p>
<pre class="lang-html prettyprint-override"><code><table id="userdata" border="5">
<th>Revision Date</th>
<th>Document Name</th>
<th>Department </th>
<th>Description</th>
<th>Link</th>
</table>
</code></pre>
<pre class="lang-js prettyprint-override"><code>var data = {
"person": [{
"revisiondate": "21 April 2016",
"documentname": "1658MC",
"department": "Sales",
"description": "Available",
"link": "href=1658MC.pdf"
}, {
"revisiondate": "16 April 2016",
"documentname": "VCX16B",
"department": "Enginnering",
"description": "Not Available",
"link": "href=VCX16B.pdf"
}, {
"revisiondate": "15 March 2016",
"documentname": "AB36F",
"department": "Custumer Services",
"description": "Not Available",
"link": "href=AB36F.pdf"
}, {
"revisiondate": "12 Agust 2016",
"documentname": "FC25D",
"department": "Technical Support",
"description": "Not Available",
"link": "href=FC25D.pdf"
}]
}
//$.getJSON("new4.json", function(data) {
// console.log(data);
//$.getJSON('new4.json', function(data) {
$.each(data.person, function(i, person) {
var tblRow = "<tr><td>" + person.revisiondate +
"</td><td>" + person.documentname +
"</td><td>" + person.department +
"</td><td>" + person.description +
"</td><td>" + person.link +
"</td></tr>"
$(tblRow).appendTo("#userdata tbody");
});
</code></pre>
<p><img src="https://i.stack.imgur.com/QW8Ud.jpg" alt="Clicking on marking area"></p>
<p>How can I add a link to my script line such as when I click to this link this opened to my source like a PDF or HTML. I could do that in HTML but when I try to do with JSON I could not.</p>
<pre><code>"</td><td><a target='_blank' href='\\mustafa02\group\Manuals\Reviewed\ "+ person.documentname.split('href=')[0]+"' >"+person.documentname.split('href=')[0]+"</a></td>"
</code></pre>
<p>my pdfs is in the Reviewed Folder. So my folder path is shown above. <code>\\mustafa02\group\Manuals\Reviewed\</code></p> | 42,928,069 | 2 | 8 | null | 2017-03-21 13:01:05.217 UTC | null | 2019-09-24 06:10:25.817 UTC | 2017-04-11 12:20:37.9 UTC | null | 7,593,390 | null | 7,593,390 | null | 1 | 0 | javascript|jquery|html|json | 55,059 | <p>Add a <code><a></code> tag with <code>href</code> and <code>target="_black"</code> for opening the link in new tab and use split to remove the href from json.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<table id="userdata" border="5">
<th>Revision Date</th>
<th>Document Name</th>
<th>Department </th>
<th>Description</th>
<th>Link</th>
</table>
<script>
var data = {
"person": [{
"revisiondate": "21 April 2016",
"documentname": "1658MC",
"department": "Sales",
"description": "Available",
"link": "href=1658MC.pdf"
}, {
"revisiondate": "16 April 2016",
"documentname": "VCX16B",
"department": "Enginnering",
"description": "Not Available",
"link": "href=VCX16B.pdf"
}, {
"revisiondate": "15 March 2016",
"documentname": "AB36F",
"department": "Custumer Services",
"description": "Not Available",
"link": "href=AB36F.pdf"
}, {
"revisiondate": "12 Agust 2016",
"documentname": "FC25D",
"department": "Technical Support",
"description": "Not Available",
"link": "href=FC25D.pdf"
}]
}
//$.getJSON("new4.json", function(data) {
// console.log(data);
//$.getJSON('new4.json', function(data) {
$.each(data.person, function(i, person) {
var tblRow = "<tr><td>" + person.revisiondate +
"</td><td>" + person.documentname +
"</td><td>" + person.department +
"</td><td>" + person.description +
"</td><td><a target='_blank' href='"+ person.link.split('href=')[1]+"' >"+person.link.split('href=')[1]+"</a></td></tr>"
$(tblRow).appendTo("#userdata tbody");
});
//});
</script>
</body>
</html></code></pre>
</div>
</div>
</p> |
10,751,948 | Numbers passed as command line arguments in python not interpreted as integers | <p>I am familiar with C, and have started experimenting in python. My question is regarding the <code>sys.argv</code> command. I've read it is used for a command line interpreter, but when trying to execute a simple program I don't get the results I expect.</p>
<p>Code:</p>
<pre><code>import sys
a = sys.argv[1]
b = sys.argv[2]
print a, b
print a+b
</code></pre>
<p>Input:</p>
<pre><code>python mySum.py 100 200
</code></pre>
<p>Output: </p>
<pre><code>100 200
100200
</code></pre>
<p>When I add the two arguments they are concatenated instead of the two values being added together. It seems that the values are being taken as strings.</p>
<p>How can I interpret them as numerics?</p> | 10,751,972 | 6 | 2 | null | 2012-05-25 09:34:30.913 UTC | 3 | 2018-08-08 18:13:04.283 UTC | 2018-08-08 18:13:04.283 UTC | null | 14,122 | null | 1,284,227 | null | 1 | 31 | python|argv | 99,230 | <p>You can convert the arguments to integers using int()</p>
<pre><code>import sys
a = int(sys.argv[1]) b = int(sys.argv[2])
print a, b
print a+b
</code></pre>
<p>input: <code>python mySum.py 100 200</code></p>
<p>output:</p>
<pre><code>100 200
300
</code></pre> |
10,355,477 | Ruby: Is there an opposite of include? for Ruby Arrays? | <p>I've got the following logic in my code:</p>
<pre><code>if [email protected]?(p.name)
...
end
</code></pre>
<p><code>@players</code> is an array. Is there a method so I can avoid the <code>!</code>?</p>
<p>Ideally, this snippet would be:</p>
<pre><code>if @players.does_not_include?(p.name)
...
end
</code></pre> | 13,155,100 | 12 | 2 | null | 2012-04-27 17:51:24.78 UTC | 18 | 2022-02-03 19:06:27.477 UTC | 2021-08-10 20:50:11.44 UTC | null | 10,907,864 | null | 716,082 | null | 1 | 215 | ruby-on-rails|ruby | 156,552 | <pre><code>if @players.exclude?(p.name)
...
end
</code></pre>
<p>ActiveSupport adds the <a href="https://apidock.com/rails/Enumerable/exclude%3F" rel="noreferrer"><code>exclude?</code></a> method to <code>Array</code>, <code>Hash</code>, and <code>String</code>. This is not pure Ruby, but is used by a LOT of rubyists.</p>
<p>Source: <a href="https://guides.rubyonrails.org/active_support_core_extensions.html#exclude-questionmark" rel="noreferrer">Active Support Core Extensions (Rails Guides)</a></p> |
26,067,590 | Get body element of site using only javascript | <p>I would like to retrieve the following sites body content <a href="http://sports.espn.go.com/nhl/bottomline/scores?nhl_s_left1" rel="noreferrer">http://sports.espn.go.com/nhl/bottomline/scores?nhl_s_left1</a> and store it in a string, i know and am successful at retrieving this using php, however i want to restrict to using only javascript, is there a way just to take the string in the site and copy it and store it in a var?</p> | 26,068,094 | 3 | 1 | null | 2014-09-26 20:11:02.353 UTC | 8 | 2022-06-01 18:44:25.18 UTC | null | null | null | null | 3,942,595 | null | 1 | 64 | javascript | 90,280 | <p>Try this:</p>
<pre><code><script>
window.onload = function get_body() {
body = document.getElementsByTagName('body')[0];
}
</script>
</code></pre>
<p>Allow me to explain. The <code>window.onload</code> is so that the HTML loads before the script is executed. Even though there is only one body tag this is the method i use^. Basically, it finds the "first" body tag there is, then I tell it to just get the body element itself and not all the other attributes and child nodes that go along with it using an index of <code>[0]</code>. If you want everything to do with the body tag then lose the index of 0. Hope this Helps!</p> |
36,446,617 | Add columns to admin orders list in WooCommerce | <p>I am using WooCommerce plugin for one of my ecommerce WordPress websites. I want to add some columns to my order listing page in the WooCommerce admin area. I am not able to find out where to add that. </p>
<p>Can anyone advise which template page I need to amend in order to meet my requirement?</p> | 36,453,587 | 1 | 6 | null | 2016-04-06 09:15:19.373 UTC | 9 | 2019-03-26 04:50:27.923 UTC | 2019-03-26 04:50:27.923 UTC | null | 1,117,368 | null | 5,006,069 | null | 1 | 22 | php|wordpress|woocommerce|backend|orders | 29,406 | <blockquote>
<p><strong>Updated:</strong> 2018-03-30 - <em>added positioning feature to the new columns</em></p>
</blockquote>
<p>So you if you want to add some columns in the orders Admin list page (in backend):</p>
<p><strong>ADDING COLUMNS IN WOOCOMMERCE ADMIN ORDERS LIST</strong></p>
<p>In the example below, we add 2 new custom columns, before existing "Total" and "Actions" columns.</p>
<pre><code>// ADDING 2 NEW COLUMNS WITH THEIR TITLES (keeping "Total" and "Actions" columns at the end)
add_filter( 'manage_edit-shop_order_columns', 'custom_shop_order_column', 20 );
function custom_shop_order_column($columns)
{
$reordered_columns = array();
// Inserting columns to a specific location
foreach( $columns as $key => $column){
$reordered_columns[$key] = $column;
if( $key == 'order_status' ){
// Inserting after "Status" column
$reordered_columns['my-column1'] = __( 'Title1','theme_domain');
$reordered_columns['my-column2'] = __( 'Title2','theme_domain');
}
}
return $reordered_columns;
}
// Adding custom fields meta data for each new column (example)
add_action( 'manage_shop_order_posts_custom_column' , 'custom_orders_list_column_content', 20, 2 );
function custom_orders_list_column_content( $column, $post_id )
{
switch ( $column )
{
case 'my-column1' :
// Get custom post meta data
$my_var_one = get_post_meta( $post_id, '_the_meta_key1', true );
if(!empty($my_var_one))
echo $my_var_one;
// Testing (to be removed) - Empty value case
else
echo '<small>(<em>no value</em>)</small>';
break;
case 'my-column2' :
// Get custom post meta data
$my_var_two = get_post_meta( $post_id, '_the_meta_key2', true );
if(!empty($my_var_two))
echo $my_var_two;
// Testing (to be removed) - Empty value case
else
echo '<small>(<em>no value</em>)</small>';
break;
}
}
</code></pre>
<p>Code goes in function.php file of your active child theme (or active theme). Tested and works.</p>
<p><a href="https://i.stack.imgur.com/Kglxp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Kglxp.png" alt="enter image description here"></a></p>
<hr>
<p>Related answer (for products): <a href="https://stackoverflow.com/questions/45693818/add-custom-columns-to-admin-producs-list-in-woocommerce-backend/45695499#45695499">Add custom columns to admin producs list in WooCommerce backend</a></p> |
7,496,789 | how to include jquery in another javascript file | <p>I have a javascript file and I want to include jquery in this js file. Do you have a suggestion?</p> | 7,496,887 | 5 | 2 | null | 2011-09-21 08:31:19.37 UTC | 9 | 2016-06-06 08:23:46.03 UTC | null | null | null | null | 117,899 | null | 1 | 23 | javascript|jquery|include | 87,755 | <p>Simply include the JavaScript for jQuery before you include your own JavaScript:</p>
<pre><code><script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script src="path/to/your/script.js"></script>
</code></pre>
<p>Though others have suggested simply copying and pasting jQuery into your own JavaScript file, it's really better to include jQuery separately from a canonical source as that will allow you to take advantage of the caching that your browser and intermediate servers have done for that file.</p> |
7,318,768 | Process very big csv file without timeout and memory error | <p>At the moment I'm writing an import script for a very big CSV file. The Problem is most times it stops after a while because of an timeout or it throws an memory error.</p>
<p>My Idea was now to parse the CSV file in "100 lines" steps and after 100 lines recall the script automatically. I tried to achieve this with header (location ...) and pass the current line with get but it didn't work out as I want to.</p>
<p>Is there a better way to this or does someone have an idea how to get rid of the memory error and the timeout?</p> | 7,319,039 | 5 | 2 | null | 2011-09-06 10:57:30.823 UTC | 18 | 2018-05-24 07:56:19.757 UTC | 2011-09-06 11:15:26.507 UTC | null | 905,093 | null | 930,479 | null | 1 | 28 | php|csv|import|timeout | 58,334 | <p>I've used <a href="http://de2.php.net/manual/en/function.fgetcsv.php"><code>fgetcsv</code></a> to read a 120MB csv in a stream-wise-manner (is that correct english?). That reads in line by line and then I've inserted every line into a database. That way only one line is hold in memory on each iteration. The script still needed 20 min. to run. Maybe I try Python next time… Don't try to load a huge csv-file into an array, that really would consume a lot of memory.</p>
<pre><code>// WDI_GDF_Data.csv (120.4MB) are the World Bank collection of development indicators:
// http://data.worldbank.org/data-catalog/world-development-indicators
if(($handle = fopen('WDI_GDF_Data.csv', 'r')) !== false)
{
// get the first row, which contains the column-titles (if necessary)
$header = fgetcsv($handle);
// loop through the file line-by-line
while(($data = fgetcsv($handle)) !== false)
{
// resort/rewrite data and insert into DB here
// try to use conditions sparingly here, as those will cause slow-performance
// I don't know if this is really necessary, but it couldn't harm;
// see also: http://php.net/manual/en/features.gc.php
unset($data);
}
fclose($handle);
}
</code></pre> |
7,596,612 | Benchmarking (python vs. c++ using BLAS) and (numpy) | <p>I would like to write a program that makes extensive use of BLAS and LAPACK linear algebra functionalities. Since performance is an issue I did some benchmarking and would like know, if the approach I took is legitimate.</p>
<p>I have, so to speak, three contestants and want to test their performance with a simple matrix-matrix multiplication. The contestants are:</p>
<ol>
<li>Numpy, making use only of the functionality of <code>dot</code>.</li>
<li>Python, calling the BLAS functionalities through a shared object.</li>
<li>C++, calling the BLAS functionalities through a shared object.</li>
</ol>
<h2>Scenario</h2>
<p>I implemented a matrix-matrix multiplication for different dimensions <code>i</code>. <code>i</code> runs from 5 to 500 with an increment of 5 and the matricies <code>m1</code> and <code>m2</code> are set up like this:</p>
<pre><code>m1 = numpy.random.rand(i,i).astype(numpy.float32)
m2 = numpy.random.rand(i,i).astype(numpy.float32)
</code></pre>
<h2>1. Numpy</h2>
<p>The code used looks like this:</p>
<pre><code>tNumpy = timeit.Timer("numpy.dot(m1, m2)", "import numpy; from __main__ import m1, m2")
rNumpy.append((i, tNumpy.repeat(20, 1)))
</code></pre>
<h2>2. Python, calling BLAS through a shared object</h2>
<p>With the function</p>
<pre><code>_blaslib = ctypes.cdll.LoadLibrary("libblas.so")
def Mul(m1, m2, i, r):
no_trans = c_char("n")
n = c_int(i)
one = c_float(1.0)
zero = c_float(0.0)
_blaslib.sgemm_(byref(no_trans), byref(no_trans), byref(n), byref(n), byref(n),
byref(one), m1.ctypes.data_as(ctypes.c_void_p), byref(n),
m2.ctypes.data_as(ctypes.c_void_p), byref(n), byref(zero),
r.ctypes.data_as(ctypes.c_void_p), byref(n))
</code></pre>
<p>the test code looks like this:</p>
<pre><code>r = numpy.zeros((i,i), numpy.float32)
tBlas = timeit.Timer("Mul(m1, m2, i, r)", "import numpy; from __main__ import i, m1, m2, r, Mul")
rBlas.append((i, tBlas.repeat(20, 1)))
</code></pre>
<h2>3. c++, calling BLAS through a shared object</h2>
<p>Now the c++ code naturally is a little longer so I reduce the information to a minimum.<br>
I load the function with</p>
<pre><code>void* handle = dlopen("libblas.so", RTLD_LAZY);
void* Func = dlsym(handle, "sgemm_");
</code></pre>
<p>I measure the time with <code>gettimeofday</code> like this:</p>
<pre><code>gettimeofday(&start, NULL);
f(&no_trans, &no_trans, &dim, &dim, &dim, &one, A, &dim, B, &dim, &zero, Return, &dim);
gettimeofday(&end, NULL);
dTimes[j] = CalcTime(start, end);
</code></pre>
<p>where <code>j</code> is a loop running 20 times. I calculate the time passed with</p>
<pre><code>double CalcTime(timeval start, timeval end)
{
double factor = 1000000;
return (((double)end.tv_sec) * factor + ((double)end.tv_usec) - (((double)start.tv_sec) * factor + ((double)start.tv_usec))) / factor;
}
</code></pre>
<h2>Results</h2>
<p>The result is shown in the plot below: </p>
<p><img src="https://i.stack.imgur.com/6Yauw.png" alt="enter image description here"></p>
<h2>Questions</h2>
<ol>
<li>Do you think my approach is fair, or are there some unnecessary overheads I can avoid?</li>
<li>Would you expect that the result would show such a huge discrepancy between the c++ and python approach? Both are using shared objects for their calculations.</li>
<li>Since I would rather use python for my program, what could I do to increase the performance when calling BLAS or LAPACK routines?</li>
</ol>
<h2>Download</h2>
<p>The complete benchmark can be downloaded <a href="https://github.com/zed/woltan-benchmark/" rel="noreferrer">here</a>. (J.F. Sebastian made that link possible^^)</p> | 7,614,252 | 5 | 12 | null | 2011-09-29 11:23:25.333 UTC | 64 | 2021-12-18 02:04:40.52 UTC | 2011-10-21 11:42:06.297 UTC | null | 572,616 | null | 572,616 | null | 1 | 115 | c++|python|numpy|benchmarking|blas | 45,033 | <p>I've run <a href="https://github.com/zed/woltan-benchmark" rel="noreferrer">your benchmark</a>. There is no difference between C++ and numpy on my machine:</p>
<p><img src="https://i.stack.imgur.com/nGX9d.jpg" alt="woltan's benchmark"></p>
<blockquote>
<p>Do you think my approach is fair, or are there some unnecessary overheads I can avoid?</p>
</blockquote>
<p>It seems fair due to there is no difference in results.</p>
<blockquote>
<p>Would you expect that the result would show such a huge discrepancy between the c++ and python approach? Both are using shared objects for their calculations.</p>
</blockquote>
<p>No.</p>
<blockquote>
<p>Since I would rather use python for my program, what could I do to increase the performance when calling BLAS or LAPACK routines?</p>
</blockquote>
<p>Make sure that numpy uses optimized version of BLAS/LAPACK libraries on your system.</p> |
7,230,820 | Skip Git commit hooks | <p>I'm looking at a Git hook which looks for print statements in Python code. If a print statement is found, it prevents the Git commit.</p>
<p>I want to override this hook and I was told that there is a command to do so. I haven't been able to find it. Any thoughts?</p> | 7,230,886 | 7 | 2 | null | 2011-08-29 13:31:59.837 UTC | 98 | 2022-08-29 18:38:38.427 UTC | 2022-07-10 21:19:43.483 UTC | null | 63,550 | null | 558,699 | null | 1 | 867 | git|githooks|git-commit | 441,505 | <p>Maybe (from <a href="https://git-scm.com/docs/git-commit" rel="noreferrer"><code>git commit</code> man page</a>):</p>
<pre><code>git commit --no-verify -m "commit message"
^^^^^^^^^^^
-n
--no-verify
</code></pre>
<blockquote>
<p>This option bypasses the pre-commit and commit-msg hooks. See also <a href="http://git-scm.com/docs/githooks" rel="noreferrer">githooks(5)</a>.</p>
</blockquote>
<p>As commented by <a href="https://stackoverflow.com/users/451480/blaise">Blaise</a>, <code>-n</code> can have a different role for certain commands.<br />
For instance, <a href="http://git-scm.com/docs/git-push" rel="noreferrer"><code>git push -n</code></a> is actually a dry-run push.<br />
Only <code>git push --no-verify</code> would skip the hook.</p>
<hr />
<p>Note: Git 2.14.x/2.15 improves the <code>--no-verify</code> behavior:</p>
<p>See <a href="https://github.com/git/git/commit/680ee550d72150f27cdb3235462eee355a20038b" rel="noreferrer">commit 680ee55</a> (14 Aug 2017) by <a href="https://github.com/" rel="noreferrer">Kevin Willford (``)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/c3e034f0f0753126494285d1098e1084ec05d2c4" rel="noreferrer">commit c3e034f</a>, 23 Aug 2017)</sup></p>
<blockquote>
<h2><code>commit</code>: skip discarding the index if there is no <code>pre-commit</code> hook</h2>
</blockquote>
<blockquote>
<p>"<code>git commit</code>" used to discard the index and re-read from the filesystem
just in case the <code>pre-commit</code> hook has updated it in the middle; this
has been optimized out when we know we do not run the <code>pre-commit</code> hook.</p>
</blockquote>
<hr />
<p><a href="https://stackoverflow.com/users/462849/davi-lima">Davi Lima</a> points out <a href="https://stackoverflow.com/questions/7230820/skip-git-commit-hooks/7230886?noredirect=1#comment101929781_7230886">in the comments</a> the <a href="https://git-scm.com/docs/git-cherry-pick" rel="noreferrer"><code>git cherry-pick</code></a> does <em>not</em> support --no-verify.<br />
So if a cherry-pick triggers a pre-commit hook, you might, as in <a href="http://web-dev.wirt.us/info/git-drupal/git-continue-vs-no-verify" rel="noreferrer">this blog post</a>, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.</p>
<p>The same process would be necessary in case of a <code>git rebase --continue</code>, after a merge conflict resolution.</p>
<hr />
<p>With Git 2.36 (Q2 2022), the callers of <code>run_commit_hook()</code> to learn if it got "success" because the hook succeeded or because there wasn't any hook.</p>
<p>See <a href="https://github.com/git/git/commit/a8cc594333848713b8e772cccf8159196ea85ede" rel="noreferrer">commit a8cc594</a> (fixed with <a href="https://github.com/git/git/commit/4369e3a1a39895ab51c2bef2985255ad05957a20" rel="noreferrer">commit 4369e3a1</a>), <a href="https://github.com/git/git/commit/9f6e63b966e9876ca6f990819fabafc473a3c9b0" rel="noreferrer">commit 9f6e63b</a> (07 Mar 2022) by <a href="https://github.com/avar" rel="noreferrer">Ævar Arnfjörð Bjarmason (<code>avar</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/7431379a9c5ed4006603114b1991c6c6e98d5dca" rel="noreferrer">commit 7431379</a>, 16 Mar 2022)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/a8cc594333848713b8e772cccf8159196ea85ede" rel="noreferrer"><code>hooks</code></a>: fix an obscure <strong><a href="https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use" rel="noreferrer">TOCTOU</a></strong> "did we just run a hook?" race</h2>
<p><sup>Signed-off-by: Ævar Arnfjörð Bjarmason</sup></p>
</blockquote>
<blockquote>
<p>Fix a <a href="https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use" rel="noreferrer"><strong>Time-of-check to time-of-use</strong> (<strong>TOCTOU</strong>)</a> race in code added in <a href="https://github.com/git/git/commit/680ee550d72150f27cdb3235462eee355a20038b" rel="noreferrer">680ee55</a> ("<code>commit</code>: skip discarding the index if there is no pre-commit hook", 2017-08-14, Git v2.15.0-rc0 -- <a href="https://github.com/git/git/commit/c3e034f0f0753126494285d1098e1084ec05d2c4" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/ab86f93d680618f62ad6e3c2f37db76029cfce5e" rel="noreferrer">batch #3</a>).</p>
<p>This obscure race condition can occur if we e.g. ran the "<code>pre-commit</code>" hook and it modified the index, but <code>hook_exists()</code> returns false later on (e.g., because the hook itself went away, the directory became unreadable, etc.).<br />
Then we won't call <code>discard_cache()</code> when we should have.</p>
<p>The race condition itself probably doesn't matter, and users would have been unlikely to run into it in practice.<br />
This problem has been noted on-list when <a href="https://github.com/git/git/commit/680ee550d72150f27cdb3235462eee355a20038b" rel="noreferrer">680ee55</a> <a href="https://lore.kernel.org/git/[email protected]/" rel="noreferrer">was discussed</a>, but had not been fixed.</p>
<p>Let's also change this for the push-to-checkout hook.<br />
Now instead of checking if the hook exists and either doing a push to checkout or a push to deploy we'll always attempt a push to checkout.<br />
If the hook doesn't exist we'll fall back on push to deploy.<br />
The same behavior as before, without the TOCTOU race.<br />
See <a href="https://github.com/git/git/commit/0855331941b723b227e93b33955bbe0b45025659" rel="noreferrer">0855331</a> ("<code>receive-pack</code>: support push-to-checkout hook", 2014-12-01, Git v2.4.0-rc0 -- <a href="https://github.com/git/git/commit/cba07bb6ff58da5aa4538c4a2bbf70b717b172b3" rel="noreferrer">merge</a>) for the introduction of the previous behavior.</p>
<p>This leaves uses of <code>hook_exists()</code> in two places that matter.<br />
The "reference-transaction" check in <a href="https://github.com/git/git/blob/a8cc594333848713b8e772cccf8159196ea85ede/refs.c" rel="noreferrer"><code>refs.c</code></a>, see <a href="https://github.com/git/git/commit/675415976704459edaf8fb39a176be2be0f403d8" rel="noreferrer">6754159</a> ("<code>refs</code>: implement reference transaction hook", 2020-06-19, Git v2.28.0-rc0 -- <a href="https://github.com/git/git/commit/33a22c1a88d8e8cddd41ea0aa264ee213ce9c1d7" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/4a0fcf9f760c9774be77f51e1e88a7499b53d2e2" rel="noreferrer">batch #7</a>), and the "prepare-commit-msg" hook, see <a href="https://github.com/git/git/commit/66618a50f9c9f008d7aef751418f12ba9bfc6b85" rel="noreferrer">66618a5</a> ("<code>sequencer</code>: run 'prepare-commit-msg' hook", 2018-01-24, Git v2.17.0-rc0 -- <a href="https://github.com/git/git/commit/1772ad1125a6f8a5473d73bbd17162bb20ebd825" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/b2e45c695d09f6a31ce09347ae0a5d2cdfe9dd4e" rel="noreferrer">batch #2</a>).</p>
<p>In both of those cases we're saving ourselves CPU time by not preparing data for the hook that we'll then do nothing with if we don't have the hook.<br />
So using this <code>"invoked_hook"</code> pattern doesn't make sense in those cases.</p>
<p>The "<code>reference-transaction</code>" and "<code>prepare-commit-msg</code>" hook also aren't racy.<br />
In those cases we'll skip the hook runs if we race with a new hook being added, whereas in the TOCTOU races being fixed here we were incorrectly skipping the required post-hook logic.</p>
</blockquote> |
7,595,797 | Can't import javax.servlet.annotation.WebServlet | <p>I have started to write app that can run on Google App Engine.<br />
But when I wanted to use my code from Netbeans to Eclipse I had an errors on:</p>
<pre class="lang-java prettyprint-override"><code>import javax.servlet.annotation.WebServlet;
</code></pre>
<p>and</p>
<pre class="lang-java prettyprint-override"><code>@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
</code></pre>
<p>the errors are:</p>
<pre class="lang-none prettyprint-override"><code>The import javax.servlet.annotation cannot be resolved
WebServlet cannot be resolved to a type
</code></pre>
<p>I tried to import the <code>servlet-api.jar</code> to Eclipse but still the same, also tried to build and clean the project. I don't use Tomcat on my Eclipse only have it on my Netbeans. How can I solve the problem?</p> | 7,599,336 | 12 | 0 | null | 2011-09-29 10:13:03.617 UTC | 13 | 2020-08-21 06:45:39.343 UTC | 2020-08-21 06:45:39.343 UTC | user11141611 | null | null | 844,039 | null | 1 | 35 | java|eclipse|servlets|servlet-3.0 | 124,153 | <blockquote>
<p><em>I tried to import the servlet-api.jar to eclipse but still the same also tried to build and clean the project. I don't use tomcat on my eclipse only have it on my net-beans. How can I solve the problem.</em></p>
</blockquote>
<p>Do <strong>not</strong> put the <code>servlet-api.jar</code> in your project. This is only asking for trouble. You need to check in the <em>Project Facets</em> section of your project's properties if the <em>Dynamic Web Module</em> facet is set to version 3.0. You also need to ensure that your <code>/WEB-INF/web.xml</code> (if any) is been declared conform Servlet 3.0 spec. I.e. the <code><web-app></code> root declaration must match the following:</p>
<pre><code><web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
</code></pre>
<p>In order to be able to import <code>javax.servlet</code> stuff, you need to integrate a fullworthy servletcontainer like Tomcat in Eclipse and then reference it in <em>Targeted Runtimes</em> of the project's properties. You can do the same for <a href="http://code.google.com/appengine/docs/java/tools/eclipse.html" rel="noreferrer">Google App Engine</a>.</p>
<p>Once again, do <strong>not</strong> copy container-specific libraries into webapp project as others suggest. It would make your webapp unexecutabele on production containers of a different make/version. You'll get classpath-related errors/exceptions in all colors.</p>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/4076601/how-do-i-import-the-javax-servlet-api-in-my-eclipse-project">How do I import the javax.servlet API in my Eclipse project?</a></li>
</ul>
<hr />
<p><strong>Unrelated</strong> to the concrete question: GAE does <strong>not</strong> support Servlet 3.0. Its underlying Jetty 7.x container supports max Servlet 2.5 only.</p> |
7,151,543 | Convert dd-mm-yyyy string to date | <p>i am trying to convert a string in the format dd-mm-yyyy into a date object in JavaScript using the following:</p>
<pre><code> var from = $("#datepicker").val();
var to = $("#datepickertwo").val();
var f = new Date(from);
var t = new Date(to);
</code></pre>
<p><code>("#datepicker").val()</code> contains a date in the format dd-mm-yyyy.
When I do the following, I get "Invalid Date":</p>
<pre><code>alert(f);
</code></pre>
<p>Is this because of the '-' symbol? How can I overcome this?</p> | 7,151,607 | 15 | 1 | null | 2011-08-22 18:01:27.23 UTC | 55 | 2021-02-22 14:40:50.62 UTC | 2015-03-29 13:02:55.543 UTC | null | 3,187,556 | null | 559,142 | null | 1 | 209 | javascript|date | 785,639 | <p><strong>Split on "-"</strong></p>
<p>Parse the string into the parts you need:</p>
<pre><code>var from = $("#datepicker").val().split("-")
var f = new Date(from[2], from[1] - 1, from[0])
</code></pre>
<p><strong>Use regex</strong></p>
<pre><code>var date = new Date("15-05-2018".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3"))
</code></pre>
<p><strong>Why not use regex?</strong></p>
<p>Because you know you'll be working on a string made up of three parts, separated by hyphens.</p>
<p>However, if you were looking for that same string within another string, regex would be the way to go.</p>
<p><strong>Reuse</strong></p>
<p>Because you're doing this more than once in your sample code, and maybe elsewhere in your code base, wrap it up in a function:</p>
<pre><code>function toDate(dateStr) {
var parts = dateStr.split("-")
return new Date(parts[2], parts[1] - 1, parts[0])
}
</code></pre>
<p>Using as:</p>
<pre><code>var from = $("#datepicker").val()
var to = $("#datepickertwo").val()
var f = toDate(from)
var t = toDate(to)
</code></pre>
<p>Or if you don't mind jQuery in your function:</p>
<pre><code>function toDate(selector) {
var from = $(selector).val().split("-")
return new Date(from[2], from[1] - 1, from[0])
}
</code></pre>
<p>Using as:</p>
<pre><code>var f = toDate("#datepicker")
var t = toDate("#datepickertwo")
</code></pre>
<p><strong>Modern JavaScript</strong></p>
<p>If you're able to use more modern JS, array destructuring is a nice touch also:</p>
<pre><code>const toDate = (dateStr) => {
const [day, month, year] = dateStr.split("-")
return new Date(year, month - 1, day)
}
</code></pre> |
14,300,569 | OpenGL glBegin ... glEnd | <p>I wanted to know how badly my games will be affected by using <code>glBegin</code> and whatnot instead of GLSL and VBOs and VAOs and all that. They just look <strong>so</strong> difficult and ridiculous to achieve what I can do easier. What will the effect of my choices be?</p> | 14,300,622 | 1 | 2 | null | 2013-01-13 04:06:05.78 UTC | 9 | 2017-03-12 01:12:54.813 UTC | 2013-01-13 07:49:54.81 UTC | null | 44,729 | null | 1,136,733 | null | 1 | 16 | c++|opengl | 16,666 | <p>Badly.</p>
<p>The direct mode API with <code>glBegin()</code> and <code>glEnd()</code> is deprecated, largely for performance reasons. It doesn’t really support data parallelism, and relies heavily on the CPU—requiring at least one function call per vertex. That adds up quickly.</p>
<p>The direct mode API might be simpler and more pleasant for you to use in small projects, but using VBOs scales better, both in terms of performance and maintainability. It’s much easier to manage data than it is to manage state.</p>
<p>Also, learning the new API means you’re up to date on how OpenGL is and should be used in the real world. If you’re looking to work in the games industry, for example, that’s just plain useful knowledge.</p>
<p>Some useful learning materials:</p>
<ul>
<li><p><a href="http://duriansoftware.com/joe/An-intro-to-modern-OpenGL.-Table-of-Contents.html" rel="noreferrer">An Intro to Modern OpenGL</a></p></li>
<li><p><a href="https://web.archive.org/web/20140209181347/http://www.arcsynthesis.org/gltut/" rel="noreferrer">Learning Modern 3D Graphics Programming</a></p></li>
<li><p><a href="http://www.opengl-tutorial.org/" rel="noreferrer">OpenGL Tutorials</a> for OpenGL ≥3.3</p></li>
</ul> |
14,092,919 | How to show "Sliding Menu" on Activity launch? | <p>I am trying to use excellent library <a href="https://github.com/jfeinstein10/SlidingMenu" rel="nofollow noreferrer">Sliding Menu</a> by Jeremy Feinstein. </p>
<p>For my case it will be great if the activity is launched with Sliding Menu open like</p>
<p><img src="https://i.stack.imgur.com/QwlYm.png" alt="enter image description here"></p>
<p>instead of Sliding menu closed like</p>
<p><img src="https://i.stack.imgur.com/d7DqM.png" alt="enter image description here"></p>
<p>I have tried to put <code>toggle()</code> in the activity but no use.</p>
<p><strong>SlidingSherlockFragmentActivity</strong></p>
<p>It is same as <a href="https://github.com/jfeinstein10/SlidingMenu/blob/master/library/src/com/slidingmenu/lib/app/SlidingFragmentActivity.java" rel="nofollow noreferrer">SlidingFragmentActivity</a> except it extends SherlockFragmentActivity instead of FragmentActivity.</p>
<p><strong>BaseActivity</strong></p>
<pre><code>public class BaseActivity extends SlidingSherlockFragmentActivity {
private int mTitleRes;
protected ListFragment mFrag;
public BaseActivity(int titleRes) {
mTitleRes = titleRes;
}
private static final String TAG = "BaseActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(mTitleRes);
// set the Behind View
setBehindContentView(R.layout.menu_frame);
FragmentTransaction t = this.getSupportFragmentManager().beginTransaction();
mFrag = new SampleListFragment();
t.replace(R.id.menu_frame, mFrag);
t.commit();
// customize the SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sm.setOnOpenListener(new SlidingMenu.OnOpenListener() {
@Override
public void onOpen() {
Log.d(TAG, "onOpen");
}
});
sm.setOnOpenedListener(new SlidingMenu.OnOpenedListener() {
@Override
public void onOpened() {
Log.d(TAG, "onOpened");
}
});
sm.setOnCloseListener(new SlidingMenu.OnCloseListener() {
@Override
public void onClose() {
Log.d(TAG, "onClose");
}
});
sm.setOnClosedListener(new SlidingMenu.OnClosedListener() {
@Override
public void onClosed() {
Log.d(TAG, "onClosed");
}
});
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
}
return super.onOptionsItemSelected(item);
}
</code></pre>
<p>}</p>
<p><strong>FlipperCheck</strong></p>
<pre><code>public class FlipperCheck extends BaseActivity {
private ViewFlipper flipper;
private TextView secondaryText;
public FlipperCheck() {
super(R.string.app_name);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSlidingActionBarEnabled(true);
setContentView(R.layout.main);
flipper = (ViewFlipper) findViewById(R.id.voicerecorder_textflipper);
flipper.startFlipping();
flipper.setInAnimation(AnimationUtils
.loadAnimation(getApplicationContext(), android.R.anim.fade_in));
flipper.setOutAnimation(AnimationUtils
.loadAnimation(getApplicationContext(), android.R.anim.fade_out));
secondaryText = (TextView) findViewById(R.id.voicerecorder_secondarytext);
secondaryText.setText("Why cannot I see u...");
final TextView firstText = (TextView) findViewById(R.id.firsttext);
final TextView secondText = (TextView) findViewById(R.id.secondtext);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopFlipper();
flipper.setVisibility(View.INVISIBLE);
secondaryText.setVisibility(View.VISIBLE);
}
});
Button secondButton = (Button) findViewById(R.id.second_button);
secondButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
firstText.setText("Replaying");
secondText.setText("Replaying");
}
});
}
@Override
protected void onStart() {
super.onStart();
toggle();
}
private void stopFlipper() {
flipper.getInAnimation().setAnimationListener(new Animation.AnimationListener() {
public void onAnimationStart(Animation animation) {
}
public void onAnimationRepeat(Animation animation) {
}
public void onAnimationEnd(Animation animation) {
int displayedChild = flipper.getDisplayedChild();
int childCount = flipper.getChildCount();
if (displayedChild == childCount - 1) {
flipper.stopFlipping();
}
}
});
}
}
</code></pre>
<p><strong>[Edit 2]</strong></p>
<p>Look like <code>toggle()</code> in <code>onStart()</code> is activation both opening and closing of Sliding Menu before activity is displayed.</p>
<pre><code>01-01 19:27:53.780: D/BaseActivity(351): onOpen
01-01 19:27:53.780: D/BaseActivity(351): onOpened
01-01 19:27:53.780: D/BaseActivity(351): onClose
01-01 19:27:53.790: D/BaseActivity(351): onClosed
01-01 19:27:54.241: D/dalvikvm(351): GC_EXTERNAL_ALLOC freed 2725 objects / 223104 bytes in 80ms
01-01 19:27:54.370: D/dalvikvm(351): GC_EXTERNAL_ALLOC freed 290 objects / 12352 bytes in 75ms
01-01 19:27:54.520: I/ActivityManager(59): Displayed activity com.abc.FlipperCheck/.FlipperCheck: 3084 ms (total 3084 ms)
</code></pre>
<p><strong>My Question</strong></p>
<p>While using Android Library "Sliding Menu" how to launch an activity with Sliding Menu open?</p> | 14,111,326 | 3 | 2 | null | 2012-12-30 17:34:59.513 UTC | 13 | 2013-12-19 06:52:55.287 UTC | 2013-01-01 14:03:08.707 UTC | null | 932,307 | null | 932,307 | null | 1 | 18 | android|android-sliding | 16,700 | <p>You can use:</p>
<pre><code>@Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
toggle();
}
}, 1000);
}
</code></pre> |
14,050,824 | Add SUM of values of two LISTS into new LIST | <p>I have the following two lists:</p>
<pre><code>first = [1,2,3,4,5]
second = [6,7,8,9,10]
</code></pre>
<p>Now I want to add the items from both of these lists into a new list.</p>
<p>output should be </p>
<pre><code>third = [7,9,11,13,15]
</code></pre> | 14,050,853 | 22 | 0 | null | 2012-12-27 07:09:52.353 UTC | 56 | 2022-09-13 07:51:29.98 UTC | 2019-04-03 19:25:49.363 UTC | null | -1 | null | 1,850,358 | null | 1 | 169 | python|list|sum | 323,940 | <p>The <code>zip</code> function is useful here, used with a list comprehension.</p>
<pre><code>[x + y for x, y in zip(first, second)]
</code></pre>
<p>If you have a list of lists (instead of just two lists):</p>
<pre><code>lists_of_lists = [[1, 2, 3], [4, 5, 6]]
[sum(x) for x in zip(*lists_of_lists)]
# -> [5, 7, 9]
</code></pre> |
9,334,084 | Moveable/draggable <div> | <p>This is my updated and modified script, it works completely, except I would like to universalize it... observe the **** how can I make it so that I don't have to do <code>function(e){BOX.Draggable.elemen = e.target || e.srcElement; elementDraggable(e);</code> everytime I need to use the dragable function for a different element?</p>
<pre><code>window.onload = addListeners;
var BOX = function(){
return{
Draggable: function(){}
};
}();
function addListeners(){
document.getElementById('div').addEventListener('contextmenu', menumove, false);
**document.getElementById('div').addEventListener('mousedown', function(e){BOX.Draggable.elemen = e.target || e.srcElement; elementDraggable(e);}, false);**
}
function elementDraggable(e){
var e = e || window.event;
var div = BOX.Draggable.elemen;
BOX.Draggable.innerX = e.clientX + window.pageXOffset - div.offsetLeft;
BOX.Draggable.innerY = e.clientY + window.pageYOffset - div.offsetTop;
window.addEventListener('mousemove', elementMove, false);
window.addEventListener('mouseup', function(){
window.removeEventListener('mousemove', elementMove, false);
}, true);
function elementMove(e){
div.style.position = 'absolute';
div.style.left = e.clientX + window.pageXOffset - BOX.Draggable.innerX + 'px';
div.style.top = e.clientY + window.pageYOffset - BOX.Draggable.innerY + 'px';
}
}
</code></pre> | 9,334,106 | 9 | 1 | null | 2012-02-17 19:21:40.62 UTC | 33 | 2022-08-16 09:08:55.85 UTC | 2017-09-22 13:58:51.673 UTC | null | 1,175,431 | null | 1,175,431 | null | 1 | 64 | javascript|draggable|move|mousemove | 207,760 | <p>Is jQuery an option for you? It makes what you are doing really simple since the code already exists.</p>
<p><a href="http://jqueryui.com/demos/draggable/">http://jqueryui.com/demos/draggable/</a></p>
<p><strong><a href="http://jsfiddle.net/wfbY8/4/">Demo</a></strong></p>
<p>JavaScript Code</p>
<pre><code>window.onload = addListeners;
function addListeners(){
document.getElementById('dxy').addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);
}
function mouseUp()
{
window.removeEventListener('mousemove', divMove, true);
}
function mouseDown(e){
window.addEventListener('mousemove', divMove, true);
}
function divMove(e){
var div = document.getElementById('dxy');
div.style.position = 'absolute';
div.style.top = e.clientY + 'px';
div.style.left = e.clientX + 'px';
}
</code></pre> |
58,768,379 | How do I generate .proto files or use 'Code First gRPC' in C# | <p>I want to use gRPC with .NET in an asp.net core web application. How do I generate the necessary .proto file from an existing C# class and model objects? I don't want to re-write a .proto file that mirrors the existing code, I want the .proto file to be auto-generated from the class and model objects.</p>
<p>I call this method to register my service class.</p>
<pre><code>builder.MapGrpcService<MyGrpcService>();
public class MyGrpcService
{
public Task<string> ServiceMethod(ModelObject model, ServerCallContext context)
{
return Task.FromResult("It Worked");
}
}
</code></pre>
<p><code>ModelObject</code> has <code>[DataContract]</code> and <code>[DataMember]</code> with order attributes.</p>
<p>Is this possible? Every example I see online starts with a <code>.proto</code> file. I've already defined my desired service methods in the <code>MyGrpcService</code> class. But maybe this is just backwards to what is the standard way of doing things...</p>
<p>Something like the old .NET remoting would be ideal where you can just ask for an interface from a remote end point and it magically uses <code>gRPC</code> to communicate back and forth, but maybe that is too simplistic a view.</p> | 58,769,040 | 1 | 5 | null | 2019-11-08 14:23:25.363 UTC | 9 | 2021-01-12 20:40:59.17 UTC | 2021-01-12 20:40:59.17 UTC | null | 56,079 | null | 56,079 | null | 1 | 19 | c#|protocol-buffers|grpc|.net-5 | 9,726 | <p>You can use Marc Gravell’s <a href="https://github.com/protobuf-net/protobuf-net.Grpc" rel="noreferrer"><code>protobuf-net.Grpc</code></a> for this. Having a code-first experience when building gRPC services is the exact use case why he started working on it. It builds on top of <a href="https://github.com/protobuf-net/protobuf-net" rel="noreferrer"><code>protobuf-net</code></a> which already adds serialization capabilities between C# types and protobuf.</p>
<p>Check out the <a href="https://protobuf-net.github.io/protobuf-net.Grpc/gettingstarted.html" rel="noreferrer">documentation</a> to see how to get started using the library, or even watch Marc present this topic in one of the following recordings of his talk “Talking Between Services with gRPC and Other Tricks”:</p>
<ul>
<li><a href="https://youtu.be/ZM0XeSjuwbc" rel="noreferrer">Mark Gravell at .NET Oxford in September 2019</a></li>
<li><a href="https://youtu.be/W-bULzA0ki8" rel="noreferrer">Marc Gravell at .NET Core Summer Event in June 2019</a></li>
</ul>
<p>I think he actually updated the one in September for the release bits of .NET Core 3.0, so that would probably be the more updated version.</p>
<p>There are also a few <a href="https://github.com/protobuf-net/protobuf-net.Grpc/tree/master/examples/pb-net-grpc" rel="noreferrer">code samples</a> to see how this looks like when you set it up.</p> |
44,678,552 | React Native - navigation issue "undefined is not an object (this.props.navigation.navigate)" | <p>Im following this tutorial <a href="https://reactnavigation.org/docs/intro/" rel="noreferrer">https://reactnavigation.org/docs/intro/</a> and im running into a bit of issues.</p>
<p>Im using the Expo Client app to render my app every time and not a simulator/emulator.</p>
<p>my code is seen down below. </p>
<p>I originally had the "SimpleApp" const defined above "ChatScreen" component but that gave me the following error:</p>
<blockquote>
<p>Route 'Chat' should declare a screen. For example: ...etc</p>
</blockquote>
<p>so I moved the decleration of SimpleApp to just above "AppRegistry" and that flagged a new error </p>
<blockquote>
<p>Element type is invalid: expected string.....You likely forgot to export your component..etc</p>
</blockquote>
<p>the tutorial did not add the key words "export default" to any component which I think it may have to do with the fact that im running it on the Expo app? so I added "export default" to "HomeScreen" and the error went away.</p>
<p>The new error that I cant seem to get rid off(based on the code below) is the following:</p>
<blockquote>
<p>undefined is not an object (evaluating 'this.props.navigation.navigate')</p>
</blockquote>
<p>I can't get rid of it unless I remove the "{}" around "const {navigate}" but that will break the navigation when I press on the button from the home screen</p>
<pre><code>import React from 'react';
import {AppRegistry,Text,Button} from 'react-native';
import { StackNavigator } from 'react-navigation';
export default class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
};
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Hello, Chat App!</Text>
<Button
onPress={() => navigate('Chat')}
title="Chat with Lucy"
/>
</View>
);
}
}
class ChatScreen extends React.Component {
static navigationOptions = {
title: 'Chat with Lucy',
};
render() {
return (
<View>
<Text>Chat with Lucy</Text>
</View>
);
}
}
const SimpleApp = StackNavigator({
Home: { screen: HomeScreen },
Chat: { screen: ChatScreen },
});
AppRegistry.registerComponent('SimpleApp', () => SimpleApp);
</code></pre> | 44,680,599 | 6 | 4 | null | 2017-06-21 14:11:29.14 UTC | 7 | 2021-05-04 14:38:58.267 UTC | null | null | null | null | 3,676,224 | null | 1 | 28 | javascript|reactjs|react-native|expo | 79,944 | <p>With Expo you should't do the App registration your self instead you should let Expo do it, keeping in mind that you have to export default component always:
Also you need to import View and Button from react-native: please find below the full code:</p>
<pre><code>import React from 'react';
import {
AppRegistry,
Text,
View,
Button
} from 'react-native';
import { StackNavigator } from 'react-navigation';
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Welcome',
};
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Hello, Chat App!</Text>
<Button
onPress={() => navigate('Chat', { user: 'Lucy' })}
title="Chat with Lucy"
/>
</View>
);
}
}
class ChatScreen extends React.Component {
// Nav options can be defined as a function of the screen's props:
static navigationOptions = ({ navigation }) => ({
title: `Chat with ${navigation.state.params.user}`,
});
render() {
// The screen's current route is passed in to `props.navigation.state`:
const { params } = this.props.navigation.state;
return (
<View>
<Text>Chat with {params.user}</Text>
</View>
);
}
}
const SimpleAppNavigator = StackNavigator({
Home: { screen: HomeScreen },
Chat: { screen: ChatScreen }
});
const AppNavigation = () => (
<SimpleAppNavigator />
);
export default class App extends React.Component {
render() {
return (
<AppNavigation/>
);
}
}
</code></pre> |
44,615,987 | How to Compare a String with a Char | <p>Guys how do i compare a String with a char?</p>
<p>heres my code :</p>
<pre><code>private String s;
private char c;
public K(String string, char cc){
setS(string);
setC(cc);
}
public void setS(String string){
this.s = string;
}
public void setC(char cc){
this.c = cc;
}
public boolean equals(K other){
return s.equals(c);
}
public boolean try(){
return s.equals(c);
}
</code></pre>
<p>if i call my method <code>try</code>, it always returns me false even if i set
both <code>s = "s"</code> and <code>c = 's'</code>.</p> | 44,616,167 | 2 | 5 | null | 2017-06-18 14:27:06.1 UTC | 1 | 2020-03-05 14:13:34.487 UTC | 2020-03-05 14:13:34.487 UTC | null | 11,180,198 | null | 8,120,322 | null | 1 | 8 | java|compare|equals | 50,995 | <p>The first thing I would say to any of my junior devs is to not use the word "try" as a method name, because try is a reserved keyword in java.</p>
<p>Secondly think that there are a few things which you need to consider in your method.</p>
<p>If you compare things of two different types they will never be the same.
A String can be null.
How long the string is.
The first char.</p>
<p>I would write the method like :</p>
<pre><code>public boolean isSame() {
if (s != null && s.length() == 1 {
return s.charAt(0) == c;
}
return false;
}
</code></pre> |
32,812,916 | How to delete the first column ( which is in fact row names) from a data file in linux? | <p>I have data file with many thousands columns and rows. I want to delete the first column which is in fact the row counter. I used this command in linux:</p>
<pre><code>cut -d " " -f 2- input.txt > output.txt
</code></pre>
<p>but nothing changed in my output. Does anybody knows why it does not work and what should I do?</p>
<p>This is what my input file looks like:</p>
<pre><code>col1 col2 col3 col4 ...
1 0 0 0 1
2 0 1 0 1
3 0 1 0 0
4 0 0 0 0
5 0 1 1 1
6 1 1 1 0
7 1 0 0 0
8 0 0 0 0
9 1 0 0 0
10 1 1 1 1
11 0 0 0 1
.
.
.
</code></pre>
<p>I want my output look like this:</p>
<pre><code>col1 col2 col3 col4 ...
0 0 0 1
0 1 0 1
0 1 0 0
0 0 0 0
0 1 1 1
1 1 1 0
1 0 0 0
0 0 0 0
1 0 0 0
1 1 1 1
0 0 0 1
.
.
.
</code></pre>
<p>I also tried the <code>sed</code> command: </p>
<pre><code> sed '1d' input.file > output.file
</code></pre>
<p>But it deletes the first row not the first column.</p>
<p>Could anybody guide me?</p> | 49,381,092 | 5 | 4 | null | 2015-09-27 21:14:36.143 UTC | 8 | 2022-01-01 20:51:22.84 UTC | 2015-09-28 02:34:50.447 UTC | null | 5,335,523 | null | 5,335,523 | null | 1 | 40 | linux|bash|shell | 88,313 | <p>@Karafka I had CSV files so I added the "," separator (you can replace with yours</p>
<pre><code>cut -d"," -f2- input.csv > output.csv
</code></pre>
<p>Then, I used a loop to go over all files inside the directory</p>
<pre><code># files are in the directory tmp/
for f in tmp/*
do
name=`basename $f`
echo "processing file : $name"
#kepp all column excep the first one of each csv file
cut -d"," -f2- $f > new/$name
#files using the same names are stored in directory new/
done
</code></pre> |
24,706,364 | filter boolean variable in a twig template | <p>I have a boolean variable(0, 1) in my database and I want to filter it to a word 0 for 'NO', and 1 for 'Yes'. how can I do that in a twig template</p>
<p>I want something like <code>{{ bool_var | '??' }}</code> where the '??' is the filter </p> | 24,706,433 | 3 | 3 | null | 2014-07-11 20:50:54.523 UTC | 4 | 2022-07-05 06:43:29.967 UTC | null | null | null | null | 3,792,227 | null | 1 | 35 | symfony|twig | 29,568 | <p>Quick way to achieve that is to use the ternary operator:</p>
<pre><code>{{ bool_var ? 'Yes':'No' }}
</code></pre>
<p><a href="http://twig.sensiolabs.org/doc/templates.html#other-operators" rel="noreferrer">http://twig.sensiolabs.org/doc/templates.html#other-operators</a></p>
<p>You could also create a custom filter that would do this. Read about custom TWIG extensions - <a href="http://symfony.com/doc/current/cookbook/templating/twig_extension.html" rel="noreferrer">http://symfony.com/doc/current/cookbook/templating/twig_extension.html</a></p> |
915,318 | iPhone Modal View Smaller that the screen | <p>I'm trying to do something that shouldn't be that complicated, but I can't figure it out.
I have a UIViewController displaying a UITableView. I want to present a context menu when the user press on a row. I want this to be a semi-transparent view with labels and buttons.
I could use an AlertView, but I want full control on the format of the labels and buttons and will like to use Interface Builder.</p>
<p>So I created my small view 250x290, set the alpha to .75 and create a view controller with the outlets to handle the different user events.</p>
<p>Now I want to present it.
If I use presentModalViewController two (undesired) things happen
1) the view covers all of the screen (but the status bar).
2) It is semi-transparent, but what I see "behind" it its not the parent view but the applications root view.</p>
<p>Ive tried adding it as a subview, but nothing happens, so Im not doing something right:</p>
<pre><code>RestaurantContextVC* modalViewController = [[[RestaurantContextVC alloc] initWithNibName:@"RestaurantContextView" bundle:nil] autorelease];
[self.view addSubview:modalViewController.view];
</code></pre>
<p>Is it possible to do what I want?
Thanks in advance.</p>
<p>Gonso</p> | 993,975 | 5 | 1 | null | 2009-05-27 12:00:20.363 UTC | 12 | 2016-03-03 07:45:35.843 UTC | 2011-05-18 13:16:02.723 UTC | null | 578,852 | null | 104,291 | null | 1 | 11 | iphone|modal-dialog|modalviewcontroller | 28,439 | <p>I'm coding similar thing. My approach include.....</p>
<ol>
<li><p>Not using dismissModalViewControllerAnimated and presentModalViewController:animated.</p></li>
<li><p>Design a customized full sized view in IB. In its viewDidLoad message body, set the background color to clearColor, so that space on the view not covered by controllers are transparent.</p></li>
<li><p>I put a UIImageView under the controllers of the floating view. The UIImageView contains a photoshoped image, which has rounded corners and the background is set to transparent. This image view serves as the container.</p></li>
<li><p>I uses CoreAnimation to present/dismiss the floating view in the modal view style: (the FloatingViewController.m)</p>
<pre><code>- (void)viewDidLoad
{
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor clearColor]];
[UIView beginAnimations:nil context:nil];
[self.view setFrame:CGRectMake(0, 480, 320, 480)];
[UIView setAnimationDuration:0.75f];
[self.view setFrame:CGRectMake(0, 0, 320, 480)];
[UIView commitAnimations];
}
</code></pre></li>
</ol> |
425,039 | No Such Method Error when creating JUnit test | <p>I've tried figuring out this problem for the last 2 days with no luck. I'm simply trying to create an annotation based JUnit test using the spring framework along with hibernate.</p>
<p>My IDE is netbeans 6.5 and I'm using hibernate 3, spring 2.5.5 and JUnit 4.4.</p>
<p>Here's the error I'm getting:</p>
<pre><code>Testcase: testFindContacts(com.mycontacts.data.dao.MyContactHibernateDaoTransactionTest): Caused an ERROR
Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:203)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:255)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:93)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:130)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [shared-context.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1337)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:42)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:173)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:199)
Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V
at net.sf.cglib.core.DebuggingClassWriter.<init>(DebuggingClassWriter.java:47)
at net.sf.cglib.core.DefaultGeneratorStrategy.getClassWriter(DefaultGeneratorStrategy.java:30)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:24)
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:144)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:116)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.getProxyFactory(CGLIBLazyInitializer.java:117)
at org.hibernate.proxy.pojo.cglib.CGLIBProxyFactory.postInstantiate(CGLIBProxyFactory.java:43)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:162)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:135)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:55)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:56)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:295)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:434)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:109)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:55)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:226)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1294)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:814)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:732)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334)
</code></pre> | 425,153 | 5 | 2 | null | 2009-01-08 17:00:43.747 UTC | 4 | 2014-09-13 02:18:27.713 UTC | null | null | null | oneBelizean | 17,337 | null | 1 | 12 | java|hibernate|spring|junit|netbeans6.5 | 43,349 | <p>The <code>java.lang.NoSuchMethodError</code> always indicates that the version of a class that was on your compiler's classpath is different from the version of the class that is on your runtime classpath (had the method been missing at compile-time, the compile would have failed.)</p>
<p>In this case, you had a different version of <code>org.objectweb.asm.ClassWriter</code> on your classpath at compile time than is on your runtime classpath.</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.