qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
8,117,249 | I think I might be repeating the question but I didn't find any of the answers suited to my requirement.
Pardon my ignorance.
I have a program running which continuously spits out some binary data from a server.It never stops until it's killed.
I want to wrap it in a python script to read the output and process it as... | 2011/11/14 | [
"https://Stackoverflow.com/questions/8117249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044911/"
] | Read with a length limit:
```
proc = subprocess.Popen(args, stdin=None, stdout=subprocess.PIPE, stderr=None)
while True:
chunk = proc.stdout.read(1024)
# chunk is <= 1024 bytes
```
---
This is the code from your comment, slightly modified. It works for me:
```
import subprocess
class container(object):
... | You could run the other program with its output directed to a file and then use Python's *f.readline()* to tail the file. |
8,117,249 | I think I might be repeating the question but I didn't find any of the answers suited to my requirement.
Pardon my ignorance.
I have a program running which continuously spits out some binary data from a server.It never stops until it's killed.
I want to wrap it in a python script to read the output and process it as... | 2011/11/14 | [
"https://Stackoverflow.com/questions/8117249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044911/"
] | Read with a length limit:
```
proc = subprocess.Popen(args, stdin=None, stdout=subprocess.PIPE, stderr=None)
while True:
chunk = proc.stdout.read(1024)
# chunk is <= 1024 bytes
```
---
This is the code from your comment, slightly modified. It works for me:
```
import subprocess
class container(object):
... | It sounds like you could use an [asynchronous version of the subprocess module](http://code.google.com/p/subprocdev/source/browse/subprocess.py). For more information, check out the developer's [blog](http://subdev.blogspot.com/). |
54,469,599 | Here's the code, it's from <https://plot.ly/python/line-and-scatter/>
=====================================================================
```
import plotly.plotly as py
import plotly.graph_objs as go
# Create random data with numpy
import numpy as np
N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.ra... | 2019/01/31 | [
"https://Stackoverflow.com/questions/54469599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9493894/"
] | You can try this code:
```
Sub Sample()
' Define object variables
Dim listRange As Range
Dim cellValue As Range
' Define other variables
Dim itemsQuantity As Integer
Dim stringResult As String
Dim separator As String
Dim counter As Integer
' Define the range where the options are... | Column to Sentence
==================
Features
--------
* At least two cells of data in Range, or else "" is returned.
* Only first column of Range is processed (`Resize`).
Usage in Excel
--------------
[](https://i.stack.imgur.com/FnDPU.jpg)
The ... |
54,469,599 | Here's the code, it's from <https://plot.ly/python/line-and-scatter/>
=====================================================================
```
import plotly.plotly as py
import plotly.graph_objs as go
# Create random data with numpy
import numpy as np
N = 100
random_x = np.linspace(0, 1, N)
random_y0 = np.random.ra... | 2019/01/31 | [
"https://Stackoverflow.com/questions/54469599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9493894/"
] | You can try this code:
```
Sub Sample()
' Define object variables
Dim listRange As Range
Dim cellValue As Range
' Define other variables
Dim itemsQuantity As Integer
Dim stringResult As String
Dim separator As String
Dim counter As Integer
' Define the range where the options are... | **Array solution via `Join` with simple transposition**
* Your post assumes a flexible range in column `A:A`, so the first step `[1]` gets the last row number and defines the data range.
* In step `[2]` you assign the found data range to an **array** which has to be variant. The `Application.Transpose` function change... |
6,978,204 | I made a set of XMLRPC client-server programs in python and set up a little method for authenticating my clients. However, after coding pretty much the whole thing, I realized that once a client was authenticated, the flag I had set for it was global in my class i.e. as long as one client is authenticated, all clients ... | 2011/08/08 | [
"https://Stackoverflow.com/questions/6978204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400612/"
] | Something like this would work:
```
class SomeClass(object):
authenticated = {}
def authenticate(self, username, password):
#do something here
if authenticate(username, password):
# make unique token can probably be just a hash
# of the millisecond time and the username
... | You have to decide. If you really want to use one instance for all clients, you have to store the "authenticated" state somewhere else. I am not familiar with SimpleXMLRPCServer(), but if you could get the conection object somewhere, or at least its source address, you could establish a set() where all authenticated cl... |
70,102,585 | I'm [using Nikola](https://getnikola.com/), a static website generator, to build a website. I am automating its building through [Github Actions](https://github.com/getnikola/nikola-action). I also wanted to use [Pandoc](https://pandoc.org) to help convert my markdown to html, but I noted that Pandoc was not included i... | 2021/11/24 | [
"https://Stackoverflow.com/questions/70102585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17501797/"
] | `pandoc` is not a Python package. It is a separate and very powerful command line tool. `nikola` invokes the command line tool to do its work. You need to install it using the `sudo apt install pandoc` command line that they suggest. | I discovered that the system was unable to find Pandoc as the entirety of the project was run in a Docker container; I had previously installed Pandoc on the system itself and failed. I was able to solve the problem by modifying the [shell script](https://github.com/getnikola/nikola-action/blob/master/entrypoint.sh) to... |
25,851,090 | The results from the code below in Python 2.7 struck me as a contradiction. The `is` operator is supposed to work with object identity and so is `id`. But their results diverge when I'm looking at a user-defined method. Why is that?
```
py-mach >>class Hello(object):
... def hello():
... pass
...
py-mach >>Hello.h... | 2014/09/15 | [
"https://Stackoverflow.com/questions/25851090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1988435/"
] | The Python documentation for the [id function](https://docs.python.org/2/library/functions.html#id) states:
>
> Return the "identity" of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. **Two objects with non-overlapping lifetimes may h... | This is a "simple" consequence of how the memory allocator works. It is very similar to the case:
```
>>> id([]) == id([])
True
```
Basically python doesn't guarantee that ID's don't get reused -- it only guarantees that the id is unique *as long as the object is alive*. In this case, the first object being passed t... |
58,040,654 | I have this json dataset. From this dataset i only want "column\_names" keys and its values and "data" keys and its values.Each values of column\_names corresponds to values of data. How do i combine only these two keys in python for analysis
```
{"dataset":{"id":42635350,"dataset_code":"MSFT","column_names":
["Date",... | 2019/09/21 | [
"https://Stackoverflow.com/questions/58040654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10331731/"
] | ```
data = {
"dataset": {
"id":42635350,"dataset_code":"MSFT",
"column_names": ["Date","Open","High","Low","Close","Volume","Dividend","Split","Adj_Open","Adj_High","Adj_Low","Adj_Close","Adj_Volume"],
"frequency":"daily",
"type":"Time Series",
"data":[
["2017-12-28",85.9,85.93... | The following snippet should work for you
```py
import pandas as pd
df = pd.DataFrame(data['dataset']['data'],columns=data['dataset']['column_names'])
```
Check the following link to learn more
<https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html> |
58,040,654 | I have this json dataset. From this dataset i only want "column\_names" keys and its values and "data" keys and its values.Each values of column\_names corresponds to values of data. How do i combine only these two keys in python for analysis
```
{"dataset":{"id":42635350,"dataset_code":"MSFT","column_names":
["Date",... | 2019/09/21 | [
"https://Stackoverflow.com/questions/58040654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10331731/"
] | ```
data = {
"dataset": {
"id":42635350,"dataset_code":"MSFT",
"column_names": ["Date","Open","High","Low","Close","Volume","Dividend","Split","Adj_Open","Adj_High","Adj_Low","Adj_Close","Adj_Volume"],
"frequency":"daily",
"type":"Time Series",
"data":[
["2017-12-28",85.9,85.93... | ```
cols = data['dataset']['column_names']
data = data['dataset']['data']
```
It's quite simple
```
labeled_data = [dict(zip(cols, d)) for d in data]
``` |
21,585,730 | I want to launch a program from python, in this case abaqus (a finite element analysis software), using:
```
os.system('abaqus job=' + JobName + ' user=' + UELname + ' interactive')
```
After say 5 minutes running the program I want to execute a python script that monitors some output files generated by abaqus. If a... | 2014/02/05 | [
"https://Stackoverflow.com/questions/21585730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1262767/"
] | Did you try [subprocess](http://docs.python.org/2/library/subprocess.html) module? | Logic seems fine, i would suggest you to use [subprocess](http://docs.python.org/2/library/subprocess.html), instead of os.system. Since you are calling commands, you can run all these commands at once like this
```
cmdToRun = '\'abaqus job=\' + JobName + \' user=\' + UELname + \' interactive\' ; sleep 300; abaqus cae... |
749,680 | I tried using the Process class as always but that didn't work. All I am doing is trying to run a Python file like someone double clicked it.
Is it possible?
EDIT:
Sample code:
```
string pythonScript = @"C:\callme.py";
string workDir = System.IO.Path.GetDirectoryName ( pythonScript );
Process proc = new Process ... | 2009/04/14 | [
"https://Stackoverflow.com/questions/749680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51816/"
] | Here's my code for executing a python script from C#, with a redirected standard input and output ( I pass info in via the standard input), copied from an example on the web somewhere. Python location is hard coded as you can see, can refactor.
```
private static string CallPython(string script, string pyArgs, str... | [Process.Start](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx) should work. if it doesn't, would you post your code and the error you are getting? |
749,680 | I tried using the Process class as always but that didn't work. All I am doing is trying to run a Python file like someone double clicked it.
Is it possible?
EDIT:
Sample code:
```
string pythonScript = @"C:\callme.py";
string workDir = System.IO.Path.GetDirectoryName ( pythonScript );
Process proc = new Process ... | 2009/04/14 | [
"https://Stackoverflow.com/questions/749680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51816/"
] | [Process.Start](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx) should work. if it doesn't, would you post your code and the error you are getting? | You forgot proc.Start() at the end. The code you have should work if you call Start(). |
749,680 | I tried using the Process class as always but that didn't work. All I am doing is trying to run a Python file like someone double clicked it.
Is it possible?
EDIT:
Sample code:
```
string pythonScript = @"C:\callme.py";
string workDir = System.IO.Path.GetDirectoryName ( pythonScript );
Process proc = new Process ... | 2009/04/14 | [
"https://Stackoverflow.com/questions/749680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51816/"
] | Here's my code for executing a python script from C#, with a redirected standard input and output ( I pass info in via the standard input), copied from an example on the web somewhere. Python location is hard coded as you can see, can refactor.
```
private static string CallPython(string script, string pyArgs, str... | You forgot proc.Start() at the end. The code you have should work if you call Start(). |
20,503,671 | Ok so I'm trying to run a C program from a python script. Currently I'm using a test C program:
```
#include <stdio.h>
int main() {
while (1) {
printf("2000\n");
sleep(1);
}
return 0;
}
```
To simulate the program that I will be using, which takes readings from a sensor constantly.
Then ... | 2013/12/10 | [
"https://Stackoverflow.com/questions/20503671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2836175/"
] | Your program isn't hung, it just runs very slowly. Your program is using buffered output; the `"2000\n"` data is not being written to stdout immediately, but will eventually make it. In your case, it might take `BUFSIZ/strlen("2000\n")` seconds (probably 1638 seconds) to complete.
After this line:
```
printf("2000\n... | See [readline docs](http://docs.python.org/2/library/io.html#io.TextIOBase.readline).
Your code:
```
process.stdout.readline
```
Is waiting for EOF or a newline.
I cannot tell what you are ultimately trying to do, but adding a newline to your printf, e.g., `printf("2000\n");`, should at least get you started. |
20,503,671 | Ok so I'm trying to run a C program from a python script. Currently I'm using a test C program:
```
#include <stdio.h>
int main() {
while (1) {
printf("2000\n");
sleep(1);
}
return 0;
}
```
To simulate the program that I will be using, which takes readings from a sensor constantly.
Then ... | 2013/12/10 | [
"https://Stackoverflow.com/questions/20503671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2836175/"
] | It is a block buffering issue.
What follows is an extended for your case version of my answer to [Python: read streaming input from subprocess.communicate()](https://stackoverflow.com/a/17698359/4279) question.
Fix stdout buffer in C program directly
---------------------------------------
`stdio`-based programs as ... | See [readline docs](http://docs.python.org/2/library/io.html#io.TextIOBase.readline).
Your code:
```
process.stdout.readline
```
Is waiting for EOF or a newline.
I cannot tell what you are ultimately trying to do, but adding a newline to your printf, e.g., `printf("2000\n");`, should at least get you started. |
20,503,671 | Ok so I'm trying to run a C program from a python script. Currently I'm using a test C program:
```
#include <stdio.h>
int main() {
while (1) {
printf("2000\n");
sleep(1);
}
return 0;
}
```
To simulate the program that I will be using, which takes readings from a sensor constantly.
Then ... | 2013/12/10 | [
"https://Stackoverflow.com/questions/20503671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2836175/"
] | It is a block buffering issue.
What follows is an extended for your case version of my answer to [Python: read streaming input from subprocess.communicate()](https://stackoverflow.com/a/17698359/4279) question.
Fix stdout buffer in C program directly
---------------------------------------
`stdio`-based programs as ... | Your program isn't hung, it just runs very slowly. Your program is using buffered output; the `"2000\n"` data is not being written to stdout immediately, but will eventually make it. In your case, it might take `BUFSIZ/strlen("2000\n")` seconds (probably 1638 seconds) to complete.
After this line:
```
printf("2000\n... |
55,352,756 | From a user given input of job description, i need to extract the keywords or phrases, using python and its libraries. I am open for suggestions and guidance from the community of what libraries work best and if in case, its simple, please guide through.
Example of user input:
`user_input = "i want a full stack deve... | 2019/03/26 | [
"https://Stackoverflow.com/questions/55352756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10486777/"
] | Well, a good keywords set is a good method. But, the key is how to build it. There are many way to do it.
Firstly, the simplest one is searching open keywords set in the web. It's depend on your luck and your knowledge. Your keywords (likes "python, java, machine learing") are common tags in Stackoverflow, Recruitment... | Well, i answered my own question. Thanks anyways for those who replied.
```
keys = ['python', 'full stack developer','java','machine learning']
keywords = []
for i in range(len(keys)):
word = keys[i]
if word in keys:
keywords.append(word)
else:
continue
print(keywords)
```
Output was as ... |
55,373,000 | I wanted to import `train_test_split` to split my dataset into a test dataset and a training dataset but an import error has occurred.
I tried all of these but none of them worked:
```
conda upgrade scikit-learn
pip uninstall scipy
pip3 install scipy
pip uninstall sklearn
pip uninstall scikit-learn
pip install sklea... | 2019/03/27 | [
"https://Stackoverflow.com/questions/55373000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11264930/"
] | `train_test_split` isn't in `preprocessing`, it is in `model_selection` and `cross_validation`, so you meant:
```
from sklearn.model_selection import train_test_split
```
Or:
```
from sklearn.cross_validation import train_test_split
``` | test\_train\_split is not present in preprocessing.
It is present in model\_selection module so try.
```
from sklearn.model_selection import train_test_split
```
it will work. |
46,210,757 | Assume I have a python dictionary with 2 keys.
```
dic = {0:'Hi!', 1:'Hello!'}
```
What I want to do is to extend this dictionary by duplicating itself, but change the key value.
For example, if I have a code
```
dic = {0:'Hi!', 1:'Hello'}
multiplier = 3
def DictionaryExtend(number_of_multiplier, dictionary):
... | 2017/09/14 | [
"https://Stackoverflow.com/questions/46210757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3794041/"
] | It's not immediately clear why you might want to do this. If the keys are always consecutive integers then you probably just want a list.
Anyway, here's a snippet:
```
def dictExtender(multiplier, d):
return dict(zip(range(multiplier * len(d)), list(d.values()) * multiplier))
``` | I don't think you need to use inheritance to achieve that. It's also unclear what the keys should be in the resulting dictionary.
If the keys are always consecutive integers, then why not use a list?
```
origin = ['Hi', 'Hello']
extended = origin * 3
extended
>> ['Hi', 'Hello', 'Hi', 'Hello', 'Hi', 'Hello']
extended... |
46,210,757 | Assume I have a python dictionary with 2 keys.
```
dic = {0:'Hi!', 1:'Hello!'}
```
What I want to do is to extend this dictionary by duplicating itself, but change the key value.
For example, if I have a code
```
dic = {0:'Hi!', 1:'Hello'}
multiplier = 3
def DictionaryExtend(number_of_multiplier, dictionary):
... | 2017/09/14 | [
"https://Stackoverflow.com/questions/46210757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3794041/"
] | You can try `itertools` to repeat the values and `OrderedDict` to maintain input order.
```
import itertools as it
import collections as ct
def extend_dict(multiplier, dict_):
"""Return a dictionary of repeated values."""
return dict(enumerate(it.chain(*it.repeat(dict_.values(), multiplier))))
d = ct.Ordered... | I don't think you need to use inheritance to achieve that. It's also unclear what the keys should be in the resulting dictionary.
If the keys are always consecutive integers, then why not use a list?
```
origin = ['Hi', 'Hello']
extended = origin * 3
extended
>> ['Hi', 'Hello', 'Hi', 'Hello', 'Hi', 'Hello']
extended... |
46,210,757 | Assume I have a python dictionary with 2 keys.
```
dic = {0:'Hi!', 1:'Hello!'}
```
What I want to do is to extend this dictionary by duplicating itself, but change the key value.
For example, if I have a code
```
dic = {0:'Hi!', 1:'Hello'}
multiplier = 3
def DictionaryExtend(number_of_multiplier, dictionary):
... | 2017/09/14 | [
"https://Stackoverflow.com/questions/46210757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3794041/"
] | You can try `itertools` to repeat the values and `OrderedDict` to maintain input order.
```
import itertools as it
import collections as ct
def extend_dict(multiplier, dict_):
"""Return a dictionary of repeated values."""
return dict(enumerate(it.chain(*it.repeat(dict_.values(), multiplier))))
d = ct.Ordered... | It's not immediately clear why you might want to do this. If the keys are always consecutive integers then you probably just want a list.
Anyway, here's a snippet:
```
def dictExtender(multiplier, d):
return dict(zip(range(multiplier * len(d)), list(d.values()) * multiplier))
``` |
46,210,757 | Assume I have a python dictionary with 2 keys.
```
dic = {0:'Hi!', 1:'Hello!'}
```
What I want to do is to extend this dictionary by duplicating itself, but change the key value.
For example, if I have a code
```
dic = {0:'Hi!', 1:'Hello'}
multiplier = 3
def DictionaryExtend(number_of_multiplier, dictionary):
... | 2017/09/14 | [
"https://Stackoverflow.com/questions/46210757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3794041/"
] | It's not immediately clear why you might want to do this. If the keys are always consecutive integers then you probably just want a list.
Anyway, here's a snippet:
```
def dictExtender(multiplier, d):
return dict(zip(range(multiplier * len(d)), list(d.values()) * multiplier))
``` | You don't need to extend anything, you need to pick a better input format or a more appropriate type.
As others have mentioned, you need a list, not an extended dict or OrderedDict. Here's an example with `lines.txt`:
```
1:Hello!
0: Hi.
2: pylang
```
And here's a way to parse the lines in the correct order:
```
d... |
46,210,757 | Assume I have a python dictionary with 2 keys.
```
dic = {0:'Hi!', 1:'Hello!'}
```
What I want to do is to extend this dictionary by duplicating itself, but change the key value.
For example, if I have a code
```
dic = {0:'Hi!', 1:'Hello'}
multiplier = 3
def DictionaryExtend(number_of_multiplier, dictionary):
... | 2017/09/14 | [
"https://Stackoverflow.com/questions/46210757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3794041/"
] | You can try `itertools` to repeat the values and `OrderedDict` to maintain input order.
```
import itertools as it
import collections as ct
def extend_dict(multiplier, dict_):
"""Return a dictionary of repeated values."""
return dict(enumerate(it.chain(*it.repeat(dict_.values(), multiplier))))
d = ct.Ordered... | You don't need to extend anything, you need to pick a better input format or a more appropriate type.
As others have mentioned, you need a list, not an extended dict or OrderedDict. Here's an example with `lines.txt`:
```
1:Hello!
0: Hi.
2: pylang
```
And here's a way to parse the lines in the correct order:
```
d... |
40,914,325 | I'm beginner to python and I would like to start with automation.
Below is the task I'm trying to do.
```
ssh -p 2024 [email protected]
[email protected]'s password:
```
I try to ssh to a particular machine and its prompting for password. But I have no clue how to give the input to this console. I have tried this
```... | 2016/12/01 | [
"https://Stackoverflow.com/questions/40914325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3275349/"
] | I have implemented through pexpect. You may need to `pip install pexpect` before you run the code:
```
import pexpect
from pexpect import pxssh
accessDenied = None
unreachable = None
username = 'someuser'
ipaddress = 'mymachine'
password = 'somepassword'
command = 'ls -al'
try:
ssh = pexpect.spawn('ssh %s@%s' % (... | I have implemented through paramiko. You may need to `pip install paramiko` before you run the code:
```
import paramiko
username = 'root'
password = 'calvin'
host = '192.168.0.1'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=str(username), password=st... |
42,207,798 | When I using lxml library in python to get data on a html page (Youtube video title), It not return text correctly It return a text Like this "à·à·à¶½à¶±à·à¶§à¶ºà¶±à"
Here my code,
```
page = requests.get("https://www.youtube.com/watch?v=MZMapfEg5g8")
source = html.fromstring(page.content)
links = source.xpath('//li... | 2017/02/13 | [
"https://Stackoverflow.com/questions/42207798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6440193/"
] | Because your `on` clause is `1 = 0` nothing matches, so all rows are inserted.
Changing your `on` clause to `a = b` will yield your expected results of `2,4,5,1,3`.
rextester for `on a = b`: <http://rextester.com/OPLL86727>
It might be helpful to be more explicit with aliasing your source and target:
```
declare @t... | You are matching on 1=0 which will always fire the insert. You should use On Source.a = @t2.b |
55,877,915 | I am trying to gather weather data from an API and then store that Data in a Database for use later.
I have been able to access the data and print it out using a for loop, but I would like to assign each iteration of that for loop to a variable to be stored in a different location in a database.
How would I be able t... | 2019/04/27 | [
"https://Stackoverflow.com/questions/55877915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6908101/"
] | IMO you need some sort of dynamic length data structure to which you can append the data inside a `for` loop and then access it using `index`.
Therefore, you can create a `list` and then append all the values of `for` lop into it as shown below:
```
list = []
for i in dailyTHigh:
list.append(i['temperatureHig... | IMO you can use a stack data structure and store the data in the FILO (First In Last Out) form. This way, you can also manage data in more efficient way, even it get's bigger in size (in future) |
55,877,915 | I am trying to gather weather data from an API and then store that Data in a Database for use later.
I have been able to access the data and print it out using a for loop, but I would like to assign each iteration of that for loop to a variable to be stored in a different location in a database.
How would I be able t... | 2019/04/27 | [
"https://Stackoverflow.com/questions/55877915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6908101/"
] | IMO you need some sort of dynamic length data structure to which you can append the data inside a `for` loop and then access it using `index`.
Therefore, you can create a `list` and then append all the values of `for` lop into it as shown below:
```
list = []
for i in dailyTHigh:
list.append(i['temperatureHig... | Just to neaten up on my above comment to the accepted answer
```
#Everthing above this line works as expected, I am focusing on the below code
dailyTHigh = (weather['daily']['data'])
list = []
for i in dailyTHigh:
list.append(i['temperatureHigh'])
for i in range(0,len(list)):
var1 = list[0]
... |
55,877,915 | I am trying to gather weather data from an API and then store that Data in a Database for use later.
I have been able to access the data and print it out using a for loop, but I would like to assign each iteration of that for loop to a variable to be stored in a different location in a database.
How would I be able t... | 2019/04/27 | [
"https://Stackoverflow.com/questions/55877915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6908101/"
] | Just to neaten up on my above comment to the accepted answer
```
#Everthing above this line works as expected, I am focusing on the below code
dailyTHigh = (weather['daily']['data'])
list = []
for i in dailyTHigh:
list.append(i['temperatureHigh'])
for i in range(0,len(list)):
var1 = list[0]
... | IMO you can use a stack data structure and store the data in the FILO (First In Last Out) form. This way, you can also manage data in more efficient way, even it get's bigger in size (in future) |
38,326,357 | **following is my code in python for the scraping and output efforts**
```
html = urlopen("http://www.imdb.com/news/top")
wineReviews = BeautifulSoup(html)
lines = []
for headLine in imdbNews.findAll("h2"):
#headLine.encode('ascii', 'ignore')
imdb_news = headLine.get_text()
lines.append(imdb_news)
... | 2016/07/12 | [
"https://Stackoverflow.com/questions/38326357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6578757/"
] | To avoid reflection, you can use a generic method:
```
public void DoSomething(MyClass a) => MakeSomeStaff(a, () => { /* Do method body */ });
private void MakeSomeStaff<T>(T item, Action action) where T: class
{
if (item == null)
throw new Exception();
action();
}
``` | **EDIT: Had an idea that abuses operator overloading, original answer at the bottom:**
Use operator overloading to throw on null
```
public struct Some<T> where T : class {
public T Value { get; }
public Some(T value)
{
if (ReferenceEquals(value, null))
throw new Exception();
V... |
25,824,417 | Before Django 1.7 I used to define a per-project `fixtures` directory in the settings:
```
FIXTURE_DIRS = ('myproject/fixtures',)
```
and use that to place my `initial_data.json` fixture storing the default **groups** essential for the whole project. This has been working well for me as I could keep the design clean... | 2014/09/13 | [
"https://Stackoverflow.com/questions/25824417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2263517/"
] | If you absolutely want to use fixtures, just use `RunPython`and `call_command` in your data migrations.
```
from django.db import migrations
from django.core.management import call_command
def add_data(apps, schema_editor):
call_command('loaddata', 'thefixture.json')
def remove_data(apps, schema_editor):
cal... | I recommend using factories instead of fixtures, they are a mess and difficult to maintain, better to use FactoryBoy with Django. |
28,250,578 | how to set proper document root for vagrant. Now it takes docroot from the wrong place. I'm trying to run laravel project, so it has to be not /var/www/project but /vae/www/project/public...
My YAML file:
```
---
vagrantfile-local:
vm:
box: puphpet/debian75-x64
box_url: puphpet/debian75-x64
... | 2015/01/31 | [
"https://Stackoverflow.com/questions/28250578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470912/"
] | I can see you have:
`vhosts:
495wa1uc3p0z:
servername: projectx.dev
serveraliases:
- www.projectx.dev
docroot: /var/www/projectx/public
port: '80'
setenv:
- 'APP_ENV dev'
directories:
8yngfatheg7u:
provider: directory
path: /var/www/projectx/public
options:
- Indexes
- FollowSymlinks
- MultiViews
allo... | It was right that I needed to run "vagran provision" after modifications, but another thing that config should look like this
```
vhosts:
495wa1uc3p0z:
servername: projectx.dev
docroot: /var/www/projectx/public
port: '80'
setenv:
- 'APP_ENV dev'
... |
57,417,939 | I am currently running a python script in a batch file. In the python, I have some print function to monitor the running code. The printed information then will be shown in the command window. In the meantime, I also want to save all these print-out text to a log-file, so I can track them in the long run.
Currently, t... | 2019/08/08 | [
"https://Stackoverflow.com/questions/57417939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11730027/"
] | For a better solution in the long run, consider the built in [logging module](https://docs.python.org/3/library/logging.html). You can give multiple destinations, such as stdout and files, log rotation, formatting, and importance levels.
Example:
```py
import logging
logging.basicConfig(filename='log_file', filemode... | Just make a function
```
def print_and_log(text):
print(text)
with open("logfile.txt", "a") as logfile:
logfile.write(text+"\n")
```
Then wherever you need to print, use this function and it will also log. |
47,979,852 | I just do this:
```
t = Variable(torch.randn(5))
t =t.cuda()
print(t)
```
but it takes 5 to 10 minitues,everytime.
I used cuda samples to test bandwidth, it's fine.
Then I used pdb to find which takes the most time.
I find in `/anaconda3/lib/python3.6/site-packages/torch/cuda/__init__`:
```
def _lazy_new(cls, *args... | 2017/12/26 | [
"https://Stackoverflow.com/questions/47979852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9141892/"
] | There’s a cuda version mismatch between the cuda my pytorch was compiled with the cuda I'm running.I divided the official installation commond
>
> conda install pytorch torchvision cuda90 -c pytorch
>
>
>
into two section:
>
> conda install -c soumith magma-cuda90
>
>
> conda install pytorch torchvision -c so... | Try doing it this way:
```
torch.cuda.synchronize()
t = Variable(torch.randn(5))
t =t.cuda()
print(t)
```
Then, it should be *blazing fast* depending on your GPU memory, at least on every *re-run* it should be. |
45,468,073 | I have successfully installed Pandas through Anaconda in PyCharm. Unfortunately when I run Import Pandas this is what I get as the output:
```
/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7
"/Users/PycharmProjects/Security upload/Security
upload.py"
Traceback (most recent call last):
File "/U... | 2017/08/02 | [
"https://Stackoverflow.com/questions/45468073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7678127/"
] | According to [here](https://github.com/opencobra/cobrapy/issues/490) and [here](https://github.com/awslabs/aws-shell/issues/161), you need to fix your dateutil package.
```
pip uninstall python-dateutil
pip install python-dateutil --upgrade
```
Maybe this:
```
sudo pip uninstall python-dateutil
sudo pip install pyt... | Was facing the same issue and started installing jupyter and got few errors
reinstalling ipython worked for me
```
sudo -H pip install --ignore-installed -U ipython
```
I also needed to reinstall pyzmq
```
sudo -H pip install --ignore-installed -U pyzmq
```
after this I re-ran import pandas in ipython and it wo... |
66,996,203 | I am trying to flip the lat long in a exported csv but am having a hard time getting python to recognize the rows to reorder them. Need the below data to read W#### N#####, W#### N#### so that QGIS's WKT layer import will work correctly later after I finish the formatting for WKT using Linestring().
```
Example Data:
... | 2021/04/08 | [
"https://Stackoverflow.com/questions/66996203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15578731/"
] | -For the `Access Key ID` you can find in `IAM` user management
-The `Secret Access Key` is the private SSH key you have created/you can create to log into your account, you would register the public key on IAM and keep the secret key to use the aws cli
-You can find the `Region` in the information for the bucket that... | * For region -> just check your upper right of the console you can choose any one, the default region when you access a resource from the AWS Management Console is US East (Ohio) (us-east-2).
* For Bucket `s3 -> navigation pane ->buckets -> search your buckets if not then create one in a specific region`. If you want a... |
3,211,031 | ```
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
fo.read(3)
fo.close()
file_open("file_ro.py")
```
I expect above program to return first 3 bytes from file . But it returns nothing. When I ran these in interactive python command prompt - I get expected output! | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246365/"
] | `fo.read()` *returns* the data that was read and you never assign it to anything. You are talking about 'output', but your code isn't supposed to output anything. Are you trying to print those three bytes? In that case you are looking for something like
```
f = open('file_ro.py', 'r')
print f.read(3)
```
You are get... | ```
import sys
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
read_data=fo.read(3)
fo.close()
print read_data
file_open("file.py")
``` |
3,211,031 | ```
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
fo.read(3)
fo.close()
file_open("file_ro.py")
```
I expect above program to return first 3 bytes from file . But it returns nothing. When I ran these in interactive python command prompt - I get expected output! | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246365/"
] | While your own answer *prints* the bytes read, it doesn't *return* them, so you won't be able to use the result somewhere else. Also, there's room for a few other improvements:
* `file_open` isn't a good name for the function, since it reads and returns bytes from a file rather than just opening it.
* You should make ... | ```
import sys
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
read_data=fo.read(3)
fo.close()
print read_data
file_open("file.py")
``` |
3,211,031 | ```
def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
fo.read(3)
fo.close()
file_open("file_ro.py")
```
I expect above program to return first 3 bytes from file . But it returns nothing. When I ran these in interactive python command prompt - I get expected output! | 2010/07/09 | [
"https://Stackoverflow.com/questions/3211031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/246365/"
] | While your own answer *prints* the bytes read, it doesn't *return* them, so you won't be able to use the result somewhere else. Also, there's room for a few other improvements:
* `file_open` isn't a good name for the function, since it reads and returns bytes from a file rather than just opening it.
* You should make ... | `fo.read()` *returns* the data that was read and you never assign it to anything. You are talking about 'output', but your code isn't supposed to output anything. Are you trying to print those three bytes? In that case you are looking for something like
```
f = open('file_ro.py', 'r')
print f.read(3)
```
You are get... |
60,827,864 | I am trying to have a master dag which will create further dags based on my need.
I have the following python file inside the *dags\_folder* in *airflow.cfg*.
This code creates the master dag in database. This master dag should read a text file and should create dags for each line in the text file. But the dags created... | 2020/03/24 | [
"https://Stackoverflow.com/questions/60827864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3211801/"
] | You have 2 options:
1. **Use SubDagOperator**: [Example DAG](https://github.com/apache/airflow/blob/1.10.9/airflow/operators/subdag_operator.py). Use it if your Schedule Interval can be the same.
2. **Write a Python DAG File**: From you master DAG, create Python files in your AIRFLOW\_HOME containing DAGs. You can use... | Have a look at the TriggerDagRunOperator:
<https://airflow.apache.org/docs/stable/_api/airflow/operators/dagrun_operator/index.html>
Example usage:
<https://github.com/apache/airflow/blob/master/airflow/example_dags/example_trigger_controller_dag.py> |
52,345,911 | I'm working on a python(3.6) project in which I need to clone a GitHub repo which will have the directory structure as:
```
|parent_DIR
|--sub_DIR
|file1....
|file2....
|--sub_DIR2
|file1...
```
Now I need to get the following info:
```
1. Parent directory name
2. How many subdirectories are
3. names of... | 2018/09/15 | [
"https://Stackoverflow.com/questions/52345911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644562/"
] | You can try your pop-over viewController's modalPresentationStyle to either `.overCurrentContext` or `.overFullScreen`.
>
> case overCurrentContext:
>
>
>
> >
> > A presentation style where the content is displayed over another view controller’s content.
> >
> >
> >
>
>
>
This means it will present the nex... | You need to set your new view controller's
```
modalPresentationStyle = .overCurrentContext
```
Do this when you initialise your view controller, or in the storyboard. |
37,888,565 | I'm having an issue with ctypes. I think my type conversion is correct and the error isn't making sense to me.
Error on line " arg - ct.c\_char\_p(logfilepath) "
TypeError: bytes or integer address expected instead of str instance
I tried in both python 3.5 and 3.4.
function i'm calling:
```
stream_initialize('stre... | 2016/06/17 | [
"https://Stackoverflow.com/questions/37888565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5344673/"
] | `c_char_p` takes `bytes` object so you have to convert your `string` to `bytes` first:
```
ct.c_char_p(logfilepath.encode('utf-8'))
```
Another solution is using the `c_wchar_p` type which takes a `string`. | *For completeness' sake*:
It is also possible to call it as `stream_initialize(b'stream_log.txt')`. Note the `b` in front of the string, which causes it to be interpreted as a `bytes` object. |
42,441,687 | I use `pyspark.sql.functions.udf` to define a UDF that uses a class imported from a .py module written by me.
```
from czech_simple_stemmer import CzechSimpleStemmer #this is my class in my module
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType
...some code here...
def clean_one_raw_doc... | 2017/02/24 | [
"https://Stackoverflow.com/questions/42441687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4985473/"
] | SparkContext.addPyFile("my\_module.py") will do it. | from the spark-submit [documentation](http://spark.apache.org/docs/2.0.1/submitting-applications.html)
>
> For Python, you can use the --py-files argument of spark-submit to add
> .py, .zip or .egg files to be distributed with your application. If
> you depend on multiple Python files we recommend packaging them i... |
47,944,185 | It's my first post, I hope it will be well done.
I'm trying to run the following ZipLine Algo with local AAPL data :
```
import pandas as pd
from collections import OrderedDict
import pytz
from zipline.api import order, symbol, record, order_target
from zipline.algorithm import TradingAlgorithm
data = OrderedDict()... | 2017/12/22 | [
"https://Stackoverflow.com/questions/47944185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9131416/"
] | Only reference and workaround I found regarding this issue is [here](https://github.com/pydata/pandas-datareader/issues/394):
```py
from pandas_datareader.google.daily import GoogleDailyReader
@property
def url(self):
return 'http://finance.google.com/finance/historical'
GoogleDailyReader.url = url
``` | do:
```
pip install fix_yahoo_finance
```
then modify the file: zipline/lib/pythonx.x/site-packages/zipline/data/benchmarks.py
add the following two statements to the file:
```
import fix_yahoo_finance as yf
yf.pdr_override ()
```
then change following instruction:
```
data = pd_reader.DataReader (symbol, 'Goog... |
56,057,132 | I define some func here, it will change all user defined attribtutes into upper case
```
def up(name, parent, attr):
user_defined_attr = ((k, v) for k, v in attr.items() if not k.startswith('_'))
up_attr = {k.upper(): v for k,v in user_defined_attr}
return type(name, parent, up_attr)
```
For example:
``... | 2019/05/09 | [
"https://Stackoverflow.com/questions/56057132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5245972/"
] | Okay, seems like this behaviour cannot be avoided, so you should parse dates manually. But the way to parse it is pretty simple.
If we are parsing date in ISO 8601 format, the mask of date string looks like this:
```
<yyyy>-<mm>-<dd>T<hh>:<mm>:<ss>(.<ms>)?(Z|(+|-)<hh>:<mm>)?
```
1. Getting date and time separately
... | This might be the case when all browsers follow their own standards for encoding date formats (but I am not sure on this part). Anyways a simple fix for this is to apply the `toISOString` method.
```js
const today = new Date();
console.log(today.toISOString());
``` |
19,202,921 | Here is my input:
```
>>> from decimal import Decimal
>>> Decimal('114.3')
Decimal('114.3')
>>> Decimal(114.3)
Decimal('114.2999999999999971578290569595992565155029296875')
```
I thought those two instances of Decimal have to be equal but Decimal with float arg seems to loose precision. Why is this? My python versio... | 2013/10/05 | [
"https://Stackoverflow.com/questions/19202921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/699931/"
] | The second line is giving you the exact decimal value of the binary floating-point number which approximates 114.3. This is almost all about binary floating point, not much about Decimal. See [the docs](http://docs.python.org/2/tutorial/floatingpoint.html) for details.
Later: if using Python 3, see [these docs](http:/... | When you do `Decimal(114.3)`, you are creating a regular float object and then passing it to Decimal. The accuracy is lost due to binary floating-point imprecision when the float 114.3 is created, before Decimal ever gets to see it. There's no way to get that accuracy back. That's why Decimal accepts string representat... |
16,739,894 | I've found [this Library](https://github.com/pythonforfacebook/facebook-sdk/) it seems it is the official one, then [found this](https://stackoverflow.com/questions/10488913/how-to-obtain-a-user-access-token-in-python), but everytime i find an answer the half of it are links to [Facebook API Documentation](https://deve... | 2013/05/24 | [
"https://Stackoverflow.com/questions/16739894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861487/"
] | Javascript and PHP can be used as web development languages. You need a web front end for the user to grant permission so that you can obtain the access token.
Rephrased: **You cannot obtain the access token programmatically, there must be manual user interaction**
In Python it will involve setting up a web server, f... | here is a Gist i tried to make using `Tornado` since the answer uses `web.py`
<https://gist.github.com/abdelouahabb/5647185> |
16,739,894 | I've found [this Library](https://github.com/pythonforfacebook/facebook-sdk/) it seems it is the official one, then [found this](https://stackoverflow.com/questions/10488913/how-to-obtain-a-user-access-token-in-python), but everytime i find an answer the half of it are links to [Facebook API Documentation](https://deve... | 2013/05/24 | [
"https://Stackoverflow.com/questions/16739894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861487/"
] | Javascript and PHP can be used as web development languages. You need a web front end for the user to grant permission so that you can obtain the access token.
Rephrased: **You cannot obtain the access token programmatically, there must be manual user interaction**
In Python it will involve setting up a web server, f... | Not sure if this helps anyone, but I was able to get an oauth\_access\_token by following this code.
```
from facepy import utils
app_id = 134134134134 # must be integer
app_secret = "XXXXXXXXXXXXXXXXXX"
oath_access_token = utils.get_application_access_token(app_id, app_secret)
```
Hope this helps. |
16,739,894 | I've found [this Library](https://github.com/pythonforfacebook/facebook-sdk/) it seems it is the official one, then [found this](https://stackoverflow.com/questions/10488913/how-to-obtain-a-user-access-token-in-python), but everytime i find an answer the half of it are links to [Facebook API Documentation](https://deve... | 2013/05/24 | [
"https://Stackoverflow.com/questions/16739894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861487/"
] | Not sure if this helps anyone, but I was able to get an oauth\_access\_token by following this code.
```
from facepy import utils
app_id = 134134134134 # must be integer
app_secret = "XXXXXXXXXXXXXXXXXX"
oath_access_token = utils.get_application_access_token(app_id, app_secret)
```
Hope this helps. | here is a Gist i tried to make using `Tornado` since the answer uses `web.py`
<https://gist.github.com/abdelouahabb/5647185> |
54,958,169 | I have the three following dataframes:
```
df_A = pd.DataFrame( {'id_A': [1, 1, 1, 1, 2, 2, 3, 3],
'Animal_A': ['cat','dog','fish','bird','cat','fish','bird','cat' ]})
df_B = pd.DataFrame( {'id_B': [1, 2, 2, 3, 4, 4, 5],
'Animal_B': ['dog','cat','fish','dog','fish','cat','cat... | 2019/03/02 | [
"https://Stackoverflow.com/questions/54958169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11139882/"
] | Not sure if it is faster or more pythonic, but it avoids the for loop :)
```
import pandas as pd
df_A = pd.DataFrame( {'id_A': [1, 1, 1, 1, 2, 2, 3, 3],
'Animal_A': ['cat','dog','fish','bird','cat','fish','bird','cat' ]})
df_B = pd.DataFrame( {'id_B': [1, 2, 2, 3, 4, 4, 5],
... | You can try the below:
```
df_A.merge(df_B, left_on = ['Animal_A'], right_on = ['Animal_B'] ).groupby(['id_A' ,'id_B']).count().reset_index().merge(df_P).drop('Animal_B', axis = 1).rename(columns = {'Animal_A': 'count'})
``` |
42,282,577 | I have this HTML
```html
<div class="callout callout-accordion" style="background-image: url("/images/expand.png");">
<span class="edit" data-pk="bandwidth_bar">Bandwidth Settings</span>
<span class="telnet-arrow"></span>
</div>
```
I'm trying to select **span** with text = `Bandwidth Settings`, an... | 2017/02/16 | [
"https://Stackoverflow.com/questions/42282577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480164/"
] | One way would be to use `find_element_by_xpath(xpath)` like this:
```
if driver.find_element_by_xpath("//span[contains(.,'Bandwidth Settings')]") is None:
print "Not found"
else:
print "Found"
...
```
For an exact match (as you asked for in your comment), use `"//span[text()='Bandwidth Settings']"`
On your... | The code that you need to use:
```
from selenium.common.exceptions import NoSuchElementException
try:
span = driver.find_element_by_xpath('//span[text()="Bandwidth Settings"]')
print "Found"
except NoSuchElementException:
print "Not found"
```
If you need to select the parent `div` element:
```
div = s... |
42,282,577 | I have this HTML
```html
<div class="callout callout-accordion" style="background-image: url("/images/expand.png");">
<span class="edit" data-pk="bandwidth_bar">Bandwidth Settings</span>
<span class="telnet-arrow"></span>
</div>
```
I'm trying to select **span** with text = `Bandwidth Settings`, an... | 2017/02/16 | [
"https://Stackoverflow.com/questions/42282577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4480164/"
] | One way would be to use `find_element_by_xpath(xpath)` like this:
```
if driver.find_element_by_xpath("//span[contains(.,'Bandwidth Settings')]") is None:
print "Not found"
else:
print "Found"
...
```
For an exact match (as you asked for in your comment), use `"//span[text()='Bandwidth Settings']"`
On your... | If you have sizzle on the page ([jQuery](https://en.wikipedia.org/wiki/JQuery)) you can select spans by their text like so:
```javascript
$("span:contains('Bandwidth Settings')")
```
Which would be selected like so using the [C#](https://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29) bindings:
```csharp
... |
24,857,779 | I used os.rename() method to rename the directory in my python script. This script called automatically by the scheduler every day. Sometimes the os.rename() function returns the error,
```
[Error 5] Access is denied
```
But all other times its working fine.
Code,
```
try:
if(os.path.exists(Downloaded_Path)):
... | 2014/07/21 | [
"https://Stackoverflow.com/questions/24857779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553605/"
] | The error means that the user account that the scheduler uses to run the program does not have permissions to rename that directory.
One common reason for the fact that it sometimes works and sometimes does not is that the program creates some of the directories it needs to rename but not others.
* The directories c... | This will also fail if the host names are not "network qualified" the same way.
```
>>> os.renames(r'\\host.domain.com\joan\rocks', r'\\host\joan\jett\rocks')
WindowsError: [Error 5] Access is denied
>>> os.renames(r'\\host\joan\rocks', r'\\host\joan\jett\rocks')
>>>
>>> os.renames(r'\\host.domain.com\joan\rocks', r... |
24,857,779 | I used os.rename() method to rename the directory in my python script. This script called automatically by the scheduler every day. Sometimes the os.rename() function returns the error,
```
[Error 5] Access is denied
```
But all other times its working fine.
Code,
```
try:
if(os.path.exists(Downloaded_Path)):
... | 2014/07/21 | [
"https://Stackoverflow.com/questions/24857779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553605/"
] | I had a similar problem on Windows 10: sometimes my python script could not rename a directory even though I could manually rename it without a problem.
I used Sysinternal's handle.exe tool to find that explorer.exe had a handle to a sub-directory of the directory I was trying to rename. It turns out explorer was addi... | The error means that the user account that the scheduler uses to run the program does not have permissions to rename that directory.
One common reason for the fact that it sometimes works and sometimes does not is that the program creates some of the directories it needs to rename but not others.
* The directories c... |
24,857,779 | I used os.rename() method to rename the directory in my python script. This script called automatically by the scheduler every day. Sometimes the os.rename() function returns the error,
```
[Error 5] Access is denied
```
But all other times its working fine.
Code,
```
try:
if(os.path.exists(Downloaded_Path)):
... | 2014/07/21 | [
"https://Stackoverflow.com/questions/24857779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553605/"
] | The error means that the user account that the scheduler uses to run the program does not have permissions to rename that directory.
One common reason for the fact that it sometimes works and sometimes does not is that the program creates some of the directories it needs to rename but not others.
* The directories c... | So if you have any file, application or folder that is open in the directory you are trying to rename you'll get that error. You to close them so that windows removes them from the quick access list. This worked for me. |
24,857,779 | I used os.rename() method to rename the directory in my python script. This script called automatically by the scheduler every day. Sometimes the os.rename() function returns the error,
```
[Error 5] Access is denied
```
But all other times its working fine.
Code,
```
try:
if(os.path.exists(Downloaded_Path)):
... | 2014/07/21 | [
"https://Stackoverflow.com/questions/24857779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553605/"
] | I had a similar problem on Windows 10: sometimes my python script could not rename a directory even though I could manually rename it without a problem.
I used Sysinternal's handle.exe tool to find that explorer.exe had a handle to a sub-directory of the directory I was trying to rename. It turns out explorer was addi... | This will also fail if the host names are not "network qualified" the same way.
```
>>> os.renames(r'\\host.domain.com\joan\rocks', r'\\host\joan\jett\rocks')
WindowsError: [Error 5] Access is denied
>>> os.renames(r'\\host\joan\rocks', r'\\host\joan\jett\rocks')
>>>
>>> os.renames(r'\\host.domain.com\joan\rocks', r... |
24,857,779 | I used os.rename() method to rename the directory in my python script. This script called automatically by the scheduler every day. Sometimes the os.rename() function returns the error,
```
[Error 5] Access is denied
```
But all other times its working fine.
Code,
```
try:
if(os.path.exists(Downloaded_Path)):
... | 2014/07/21 | [
"https://Stackoverflow.com/questions/24857779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553605/"
] | So if you have any file, application or folder that is open in the directory you are trying to rename you'll get that error. You to close them so that windows removes them from the quick access list. This worked for me. | This will also fail if the host names are not "network qualified" the same way.
```
>>> os.renames(r'\\host.domain.com\joan\rocks', r'\\host\joan\jett\rocks')
WindowsError: [Error 5] Access is denied
>>> os.renames(r'\\host\joan\rocks', r'\\host\joan\jett\rocks')
>>>
>>> os.renames(r'\\host.domain.com\joan\rocks', r... |
24,857,779 | I used os.rename() method to rename the directory in my python script. This script called automatically by the scheduler every day. Sometimes the os.rename() function returns the error,
```
[Error 5] Access is denied
```
But all other times its working fine.
Code,
```
try:
if(os.path.exists(Downloaded_Path)):
... | 2014/07/21 | [
"https://Stackoverflow.com/questions/24857779",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1553605/"
] | I had a similar problem on Windows 10: sometimes my python script could not rename a directory even though I could manually rename it without a problem.
I used Sysinternal's handle.exe tool to find that explorer.exe had a handle to a sub-directory of the directory I was trying to rename. It turns out explorer was addi... | So if you have any file, application or folder that is open in the directory you are trying to rename you'll get that error. You to close them so that windows removes them from the quick access list. This worked for me. |
36,428,178 | Even with the most basic of code, my .txt file is coming out empty, and I can't understand why. I'm running this subroutine in `python 3` to gather information from the user. When I open the .txt file in both notepad and N++, I get an empty file.
Here's my code :
```
def Setup():
fw = open('AutoLoader.txt', 'a')
... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36428178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Try replacing fw.close with fw.close() | It's working on python 3.4
```
def Setup():
fw = open('AutoLoader3.4.txt', 'a+')
x = True
while x == True:
print("Enter new location to enter")
new_entry = str(input('Start with \'web\' if it\'s a web page\n'))
fw.write(new_entry)
y = input('New Data? Y/N\n')
if y == 'N' or y == 'n':
... |
36,428,178 | Even with the most basic of code, my .txt file is coming out empty, and I can't understand why. I'm running this subroutine in `python 3` to gather information from the user. When I open the .txt file in both notepad and N++, I get an empty file.
Here's my code :
```
def Setup():
fw = open('AutoLoader.txt', 'a')
... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36428178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | Try replacing fw.close with fw.close() | Not knowing what `Start()` does, it must be ignored in answers, so far...
I wouldn't bother to close the file myself, but let a `with` statement do the job properly.
Following script works at least:
```
#!/usr/bin/env python3
def Setup():
with open('AutoLoader.txt', 'a') as fw:
while True:
p... |
36,428,178 | Even with the most basic of code, my .txt file is coming out empty, and I can't understand why. I'm running this subroutine in `python 3` to gather information from the user. When I open the .txt file in both notepad and N++, I get an empty file.
Here's my code :
```
def Setup():
fw = open('AutoLoader.txt', 'a')
... | 2016/04/05 | [
"https://Stackoverflow.com/questions/36428178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | It's working on python 3.4
```
def Setup():
fw = open('AutoLoader3.4.txt', 'a+')
x = True
while x == True:
print("Enter new location to enter")
new_entry = str(input('Start with \'web\' if it\'s a web page\n'))
fw.write(new_entry)
y = input('New Data? Y/N\n')
if y == 'N' or y == 'n':
... | Not knowing what `Start()` does, it must be ignored in answers, so far...
I wouldn't bother to close the file myself, but let a `with` statement do the job properly.
Following script works at least:
```
#!/usr/bin/env python3
def Setup():
with open('AutoLoader.txt', 'a') as fw:
while True:
p... |
26,506,642 | if d is a dict, python docs provide us with this method:
```
dict.get = get(...)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
```
Another famous pattern is:
```
try:
D[k]:
except:
d
```
But in my benchmarks (done with timeit), i have found that the following approach is the best:
```
... | 2014/10/22 | [
"https://Stackoverflow.com/questions/26506642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3599101/"
] | Looks like the `D[k] if k in D else d` pattern is about twice faster than .get, at least for some usages.
.get
```
$ python -m timeit -s 'D={}; k=xrange(0,100000)' 'D.get(k)'
10000000 loops, best of 3: 0.0934 usec per loop
```
if/else
```
$ python -m timeit -s 'D={}; k=xrange(0,100000)' 'D[k] if k in D else None'
... | Maybe you should give `pypy` a try and compile that on your embedded system. `if-then-else` and `get` have similar results. Some benchmarks:
PyPy:
```
$ pypy3 -m timeit -s 'd={}; k=0' 'd[k] if k in d else None'
1000000000 loops, best of 3: 0.0008 usec per loop
$ pypy3 -m timeit -s 'd={}; k=0' 'd.get(k)' ... |
37,033,709 | I know that it's often [best practice](https://softwareengineering.stackexchange.com/questions/213935/why-use-classes-when-programming-a-tkinter-gui-in-python) to write Tkinter GUI code using object-oriented programming (OOP), but I'm trying to keep things simple because I'm new to Python.
I have written the following... | 2016/05/04 | [
"https://Stackoverflow.com/questions/37033709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6030297/"
] | `MyLabel` is local to `main()` so the way you can not access it that way from `ChangeLabelText()`.
If you do not want to change the design of your program, then you will need to change the definition of `ChangeLabelText()` like what follows:
```
def ChangeLabelText(m):
m.config(text = 'You pressed the button!')
... | *but I'm trying to keep things simple because I'm new to Python* Hopefully this helps in understanding that classes are the simple way, otherwise you have to jump through hoops and manually keep track of many variables. Also, the Python Style Guide suggests that CamelCase is used for class names and lower\_case\_with\_... |
37,033,709 | I know that it's often [best practice](https://softwareengineering.stackexchange.com/questions/213935/why-use-classes-when-programming-a-tkinter-gui-in-python) to write Tkinter GUI code using object-oriented programming (OOP), but I'm trying to keep things simple because I'm new to Python.
I have written the following... | 2016/05/04 | [
"https://Stackoverflow.com/questions/37033709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6030297/"
] | `MyLabel` is local to `main()` so the way you can not access it that way from `ChangeLabelText()`.
If you do not want to change the design of your program, then you will need to change the definition of `ChangeLabelText()` like what follows:
```
def ChangeLabelText(m):
m.config(text = 'You pressed the button!')
... | Are your sure you don't want to do it as a class (i think it makes the code a bit more clean as your project grows)? Here is a way to accomplish what you'e looking for:
```
#!/usr/bin/python3
from tkinter import *
from tkinter import ttk
class myWindow:
def __init__(self, master):
self.MyLabel = ttk.Label... |
37,033,709 | I know that it's often [best practice](https://softwareengineering.stackexchange.com/questions/213935/why-use-classes-when-programming-a-tkinter-gui-in-python) to write Tkinter GUI code using object-oriented programming (OOP), but I'm trying to keep things simple because I'm new to Python.
I have written the following... | 2016/05/04 | [
"https://Stackoverflow.com/questions/37033709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6030297/"
] | Are your sure you don't want to do it as a class (i think it makes the code a bit more clean as your project grows)? Here is a way to accomplish what you'e looking for:
```
#!/usr/bin/python3
from tkinter import *
from tkinter import ttk
class myWindow:
def __init__(self, master):
self.MyLabel = ttk.Label... | *but I'm trying to keep things simple because I'm new to Python* Hopefully this helps in understanding that classes are the simple way, otherwise you have to jump through hoops and manually keep track of many variables. Also, the Python Style Guide suggests that CamelCase is used for class names and lower\_case\_with\_... |
39,026,120 | I have a python string that I need to remove parentheses. The standard way is to use `text = re.sub(r'\([^)]*\)', '', text)`, so the content within the parentheses will be removed.
However, I just found a string that looks like `(Data with in (Boo) And good luck)`. With the regex I use, it will still have `And good lu... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294529/"
] | With the re module (replace the innermost parenthesis until there's no more replacement to do):
```
import re
s = r'Sainte Anne -(Data with in (Boo) And good luck) Charenton'
nb_rep = 1
while (nb_rep):
(s, nb_rep) = re.subn(r'\([^()]*\)', '', s)
print(s)
```
With the [regex module](https://pypi.python.org/py... | First I split the line into tokens that do not contain the parenthesis, for later on joining them into a new line:
```
line = "(Data with in (Boo) And good luck)"
new_line = "".join(re.split(r'(?:[()])',line))
print ( new_line )
# 'Data with in Boo And good luck'
``` |
39,026,120 | I have a python string that I need to remove parentheses. The standard way is to use `text = re.sub(r'\([^)]*\)', '', text)`, so the content within the parentheses will be removed.
However, I just found a string that looks like `(Data with in (Boo) And good luck)`. With the regex I use, it will still have `And good lu... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294529/"
] | First I split the line into tokens that do not contain the parenthesis, for later on joining them into a new line:
```
line = "(Data with in (Boo) And good luck)"
new_line = "".join(re.split(r'(?:[()])',line))
print ( new_line )
# 'Data with in Boo And good luck'
``` | No regex...
```
>>> a = 'Hi this is a test ( a b ( c d) e) sentence'
>>> o = ['(' == t or t == ')' for t in a]
>>> o
[False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, True, False, False,
False, False, False, True, False, False, False, Fals... |
39,026,120 | I have a python string that I need to remove parentheses. The standard way is to use `text = re.sub(r'\([^)]*\)', '', text)`, so the content within the parentheses will be removed.
However, I just found a string that looks like `(Data with in (Boo) And good luck)`. With the regex I use, it will still have `And good lu... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294529/"
] | First I split the line into tokens that do not contain the parenthesis, for later on joining them into a new line:
```
line = "(Data with in (Boo) And good luck)"
new_line = "".join(re.split(r'(?:[()])',line))
print ( new_line )
# 'Data with in Boo And good luck'
``` | Assuming (1) there are always matching parentheses and (2) we only remove the parentheses and everything in between them (ie. surrounding spaces around the parentheses are untouched), the following should work.
It's basically a state machine that maintains the current depth of nested parentheses. We keep the character... |
39,026,120 | I have a python string that I need to remove parentheses. The standard way is to use `text = re.sub(r'\([^)]*\)', '', text)`, so the content within the parentheses will be removed.
However, I just found a string that looks like `(Data with in (Boo) And good luck)`. With the regex I use, it will still have `And good lu... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294529/"
] | First I split the line into tokens that do not contain the parenthesis, for later on joining them into a new line:
```
line = "(Data with in (Boo) And good luck)"
new_line = "".join(re.split(r'(?:[()])',line))
print ( new_line )
# 'Data with in Boo And good luck'
``` | Referenced from [here](https://www.w3resource.com/python-exercises/re/python-re-exercise-50.php)
```
import re
item = "example (.com) w3resource github (.com) stackoverflow (.com)"
### Add lines in case there are non-ascii problem:
# -*- coding: utf-8 -*-
item = item .decode('ascii', errors = 'ignore').encode()
prin... |
39,026,120 | I have a python string that I need to remove parentheses. The standard way is to use `text = re.sub(r'\([^)]*\)', '', text)`, so the content within the parentheses will be removed.
However, I just found a string that looks like `(Data with in (Boo) And good luck)`. With the regex I use, it will still have `And good lu... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294529/"
] | With the re module (replace the innermost parenthesis until there's no more replacement to do):
```
import re
s = r'Sainte Anne -(Data with in (Boo) And good luck) Charenton'
nb_rep = 1
while (nb_rep):
(s, nb_rep) = re.subn(r'\([^()]*\)', '', s)
print(s)
```
With the [regex module](https://pypi.python.org/py... | No regex...
```
>>> a = 'Hi this is a test ( a b ( c d) e) sentence'
>>> o = ['(' == t or t == ')' for t in a]
>>> o
[False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, True, False, False,
False, False, False, True, False, False, False, Fals... |
39,026,120 | I have a python string that I need to remove parentheses. The standard way is to use `text = re.sub(r'\([^)]*\)', '', text)`, so the content within the parentheses will be removed.
However, I just found a string that looks like `(Data with in (Boo) And good luck)`. With the regex I use, it will still have `And good lu... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294529/"
] | With the re module (replace the innermost parenthesis until there's no more replacement to do):
```
import re
s = r'Sainte Anne -(Data with in (Boo) And good luck) Charenton'
nb_rep = 1
while (nb_rep):
(s, nb_rep) = re.subn(r'\([^()]*\)', '', s)
print(s)
```
With the [regex module](https://pypi.python.org/py... | Assuming (1) there are always matching parentheses and (2) we only remove the parentheses and everything in between them (ie. surrounding spaces around the parentheses are untouched), the following should work.
It's basically a state machine that maintains the current depth of nested parentheses. We keep the character... |
39,026,120 | I have a python string that I need to remove parentheses. The standard way is to use `text = re.sub(r'\([^)]*\)', '', text)`, so the content within the parentheses will be removed.
However, I just found a string that looks like `(Data with in (Boo) And good luck)`. With the regex I use, it will still have `And good lu... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294529/"
] | With the re module (replace the innermost parenthesis until there's no more replacement to do):
```
import re
s = r'Sainte Anne -(Data with in (Boo) And good luck) Charenton'
nb_rep = 1
while (nb_rep):
(s, nb_rep) = re.subn(r'\([^()]*\)', '', s)
print(s)
```
With the [regex module](https://pypi.python.org/py... | Referenced from [here](https://www.w3resource.com/python-exercises/re/python-re-exercise-50.php)
```
import re
item = "example (.com) w3resource github (.com) stackoverflow (.com)"
### Add lines in case there are non-ascii problem:
# -*- coding: utf-8 -*-
item = item .decode('ascii', errors = 'ignore').encode()
prin... |
39,026,120 | I have a python string that I need to remove parentheses. The standard way is to use `text = re.sub(r'\([^)]*\)', '', text)`, so the content within the parentheses will be removed.
However, I just found a string that looks like `(Data with in (Boo) And good luck)`. With the regex I use, it will still have `And good lu... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294529/"
] | No regex...
```
>>> a = 'Hi this is a test ( a b ( c d) e) sentence'
>>> o = ['(' == t or t == ')' for t in a]
>>> o
[False, False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, True, False, False,
False, False, False, True, False, False, False, Fals... | Referenced from [here](https://www.w3resource.com/python-exercises/re/python-re-exercise-50.php)
```
import re
item = "example (.com) w3resource github (.com) stackoverflow (.com)"
### Add lines in case there are non-ascii problem:
# -*- coding: utf-8 -*-
item = item .decode('ascii', errors = 'ignore').encode()
prin... |
39,026,120 | I have a python string that I need to remove parentheses. The standard way is to use `text = re.sub(r'\([^)]*\)', '', text)`, so the content within the parentheses will be removed.
However, I just found a string that looks like `(Data with in (Boo) And good luck)`. With the regex I use, it will still have `And good lu... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39026120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1294529/"
] | Assuming (1) there are always matching parentheses and (2) we only remove the parentheses and everything in between them (ie. surrounding spaces around the parentheses are untouched), the following should work.
It's basically a state machine that maintains the current depth of nested parentheses. We keep the character... | Referenced from [here](https://www.w3resource.com/python-exercises/re/python-re-exercise-50.php)
```
import re
item = "example (.com) w3resource github (.com) stackoverflow (.com)"
### Add lines in case there are non-ascii problem:
# -*- coding: utf-8 -*-
item = item .decode('ascii', errors = 'ignore').encode()
prin... |
3,433,806 | I was reading on web2py framework for a hobby project of mine I am doing. I learned how to program in Python when I was younger so I do have a grasp on it. Right now I am more of a PHP dev but kindda loathe it.
I just have this doubt that pops in: Is there a way to use "Vanilla" python on the backend? I mean Vanilla l... | 2010/08/08 | [
"https://Stackoverflow.com/questions/3433806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399621/"
] | There is no reason to do that :) but if you insist you can write on top of [WSGI](http://wsgi.org/wsgi/)
I suggest that you can try a micro-framework such as web.py if u like it Vanilla style | without a framework, you use WSGI. to do this, you write a function `application` like so:
```
def application(environment, start_response):
start_response("200 OK", [('Content-Type', 'text/plain')])
return "hello world"
```
`environment` contains cgi variables and other stuff. Normally what happens is appli... |
3,433,806 | I was reading on web2py framework for a hobby project of mine I am doing. I learned how to program in Python when I was younger so I do have a grasp on it. Right now I am more of a PHP dev but kindda loathe it.
I just have this doubt that pops in: Is there a way to use "Vanilla" python on the backend? I mean Vanilla l... | 2010/08/08 | [
"https://Stackoverflow.com/questions/3433806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/399621/"
] | There is no reason to do that :) but if you insist you can write on top of [WSGI](http://wsgi.org/wsgi/)
I suggest that you can try a micro-framework such as web.py if u like it Vanilla style | The mixing of logic, content, and presentation as naïvely encouraged by PHP is an abomination. It is the polar opposite of good design practice, and should not be imported to other languages (it shouldn't even be used in PHP, and thankfully the PHP world in general is ever so slowly moving away from it).
You should le... |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | I was facing the same issue and even customizing the log\_dir option using datetime didn't work. Check this page: <https://github.com/tensorflow/tensorboard/issues/2819> which helped me. I just added the 'profile\_batch = 100000000' in this callback as:
TensorBoard(log\_dir=log\_dir, .., profile\_batch = 100000000) | I faced with issue becuase of mixed slashes in tensorboard logdir (on Windows).
This happened when I used:
```
logdir_path = os.path.join(r'D:something\models', 'model1')
```
Solved using:
```
logdir_path = os.path.normpath(os.path.join(r'D:something\models', 'model1'))
callbacks = [tf.keras.callbacks.TensorBoard(... |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | I was facing the same issue and even customizing the log\_dir option using datetime didn't work. Check this page: <https://github.com/tensorflow/tensorboard/issues/2819> which helped me. I just added the 'profile\_batch = 100000000' in this callback as:
TensorBoard(log\_dir=log\_dir, .., profile\_batch = 100000000) | ```
callbacks = [tensorflow.keras.callbacks.TensorBoard(log_dir=logdir, histogram_freq=1, profile_batch = 100000000)]
```
Simply this solved my problem. Adding the profile batch.
The problem mostly mainly occurs in `Tensorflow V2.1` and in `Windows`. |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | I was facing the same issue and even customizing the log\_dir option using datetime didn't work. Check this page: <https://github.com/tensorflow/tensorboard/issues/2819> which helped me. I just added the 'profile\_batch = 100000000' in this callback as:
TensorBoard(log\_dir=log\_dir, .., profile\_batch = 100000000) | Proposed suggestions to set 'profile\_batch = 100000000' work. But, the original point of was to enable profile (which is essentially disabled when you set it to 100000000)
What made it work for me with with any profile\_batch was installing 2019 C++, from this link (I'm on windows 10):
<https://support.microsoft.com/... |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | Proposed suggestions to set 'profile\_batch = 100000000' work. But, the original point of was to enable profile (which is essentially disabled when you set it to 100000000)
What made it work for me with with any profile\_batch was installing 2019 C++, from this link (I'm on windows 10):
<https://support.microsoft.com/... | I faced with issue becuase of mixed slashes in tensorboard logdir (on Windows).
This happened when I used:
```
logdir_path = os.path.join(r'D:something\models', 'model1')
```
Solved using:
```
logdir_path = os.path.normpath(os.path.join(r'D:something\models', 'model1'))
callbacks = [tf.keras.callbacks.TensorBoard(... |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | ```
callbacks = [tensorflow.keras.callbacks.TensorBoard(log_dir=logdir, histogram_freq=1, profile_batch = 100000000)]
```
Simply this solved my problem. Adding the profile batch.
The problem mostly mainly occurs in `Tensorflow V2.1` and in `Windows`. | [](https://i.stack.imgur.com/0wRMl.png)
Add this to your code
```
callbacks = [tensorflow.keras.callbacks.TensorBoard(log_dir=logdir, histogram_freq=1, profile_batch = 100000000)]
``` |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | I assume you run this code on windows & I think you might ran into this issue: <https://github.com/tensorflow/tensorboard/issues/2279#issuecomment-512089344>
Just use backslashes as path delimiter:
```
log_dir="logs\\fit\\" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
``` | [](https://i.stack.imgur.com/0wRMl.png)
Add this to your code
```
callbacks = [tensorflow.keras.callbacks.TensorBoard(log_dir=logdir, histogram_freq=1, profile_batch = 100000000)]
``` |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | I assume you run this code on windows & I think you might ran into this issue: <https://github.com/tensorflow/tensorboard/issues/2279#issuecomment-512089344>
Just use backslashes as path delimiter:
```
log_dir="logs\\fit\\" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
``` | Proposed suggestions to set 'profile\_batch = 100000000' work. But, the original point of was to enable profile (which is essentially disabled when you set it to 100000000)
What made it work for me with with any profile\_batch was installing 2019 C++, from this link (I'm on windows 10):
<https://support.microsoft.com/... |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | ```
callbacks = [tensorflow.keras.callbacks.TensorBoard(log_dir=logdir, histogram_freq=1, profile_batch = 100000000)]
```
Simply this solved my problem. Adding the profile batch.
The problem mostly mainly occurs in `Tensorflow V2.1` and in `Windows`. | I faced with issue becuase of mixed slashes in tensorboard logdir (on Windows).
This happened when I used:
```
logdir_path = os.path.join(r'D:something\models', 'model1')
```
Solved using:
```
logdir_path = os.path.normpath(os.path.join(r'D:something\models', 'model1'))
callbacks = [tf.keras.callbacks.TensorBoard(... |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | I was facing the same issue and even customizing the log\_dir option using datetime didn't work. Check this page: <https://github.com/tensorflow/tensorboard/issues/2819> which helped me. I just added the 'profile\_batch = 100000000' in this callback as:
TensorBoard(log\_dir=log\_dir, .., profile\_batch = 100000000) | [](https://i.stack.imgur.com/0wRMl.png)
Add this to your code
```
callbacks = [tensorflow.keras.callbacks.TensorBoard(log_dir=logdir, histogram_freq=1, profile_batch = 100000000)]
``` |
56,663,388 | I'm trying to learn and use tensorboard and followed [these guideline codes](https://www.tensorflow.org/tensorboard/r2/get_started) with a few modifications.
When I run the code
```
model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test),
callbacks=[tf.k... | 2019/06/19 | [
"https://Stackoverflow.com/questions/56663388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11668817/"
] | I assume you run this code on windows & I think you might ran into this issue: <https://github.com/tensorflow/tensorboard/issues/2279#issuecomment-512089344>
Just use backslashes as path delimiter:
```
log_dir="logs\\fit\\" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
``` | ```
callbacks = [tensorflow.keras.callbacks.TensorBoard(log_dir=logdir, histogram_freq=1, profile_batch = 100000000)]
```
Simply this solved my problem. Adding the profile batch.
The problem mostly mainly occurs in `Tensorflow V2.1` and in `Windows`. |
58,320,969 | I’m working on the below script on my MacbookAir and I’m unclear where this syntax error comes from and tried searching on google why it breaks at the = sign in the print function.
I understood there are different functions to print and tried many of them. But am unclear if I’m using the correct Python version (both ... | 2019/10/10 | [
"https://Stackoverflow.com/questions/58320969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12194431/"
] | There's a few issues to fix here.
Firstly don't use `id` attributes in content which can be dynamically appended multiple times. You'll end up with duplicate ids which is invalid and will cause issues in your JS. Use common `class` attributes instead.
Secondly you can attach an event handler to all of the elements wi... | You need event delegation for this. Also it's not ideal to use an id with a fixed number for each of your operations. If your table has 1000 rows, you don't want to copy-paste your function 1000 times.
I created an example based on classes:
```js
$(document).ready(function() {
$(".btn-add").click(function() {
... |
58,320,969 | I’m working on the below script on my MacbookAir and I’m unclear where this syntax error comes from and tried searching on google why it breaks at the = sign in the print function.
I understood there are different functions to print and tried many of them. But am unclear if I’m using the correct Python version (both ... | 2019/10/10 | [
"https://Stackoverflow.com/questions/58320969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12194431/"
] | I have written code which will add tr at last (by clicking add button) and remove last added raw(by clicking remove button).
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var rowCount = $('#myTable tr').length;
$("table#myT... | You need event delegation for this. Also it's not ideal to use an id with a fixed number for each of your operations. If your table has 1000 rows, you don't want to copy-paste your function 1000 times.
I created an example based on classes:
```js
$(document).ready(function() {
$(".btn-add").click(function() {
... |
14,109,915 | I am currently playing around with an example from the book Violent Python. You can see my implementation [here](https://github.com/igniteflow/violent-python/blob/master/pwd-crackers/unix-pwd-crack.py)
I am now trying to implement the same script in Go to compare performance, note I am completely new to Go. Opening t... | 2013/01/01 | [
"https://Stackoverflow.com/questions/14109915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/343223/"
] | `crypt` is very easy to wrap with cgo, eg
```
package main
import (
"fmt"
"unsafe"
)
// #cgo LDFLAGS: -lcrypt
// #define _GNU_SOURCE
// #include <crypt.h>
// #include <stdlib.h>
import "C"
// crypt wraps C library crypt_r
func crypt(key, salt string) string {
data := C.struct_crypt_data{}
ckey := C.... | E.g.
```
package main
import (
"crypto/des"
"fmt"
"log"
)
func main() {
b, err := des.NewCipher([]byte("abcdefgh"))
if err != nil {
log.Fatal(err)
}
msg := []byte("Hello!?!")
fmt.Printf("% 02x: %q\n", msg, msg)
b.Encrypt(msg, ms... |
14,109,915 | I am currently playing around with an example from the book Violent Python. You can see my implementation [here](https://github.com/igniteflow/violent-python/blob/master/pwd-crackers/unix-pwd-crack.py)
I am now trying to implement the same script in Go to compare performance, note I am completely new to Go. Opening t... | 2013/01/01 | [
"https://Stackoverflow.com/questions/14109915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/343223/"
] | `crypt` is very easy to wrap with cgo, eg
```
package main
import (
"fmt"
"unsafe"
)
// #cgo LDFLAGS: -lcrypt
// #define _GNU_SOURCE
// #include <crypt.h>
// #include <stdlib.h>
import "C"
// crypt wraps C library crypt_r
func crypt(key, salt string) string {
data := C.struct_crypt_data{}
ckey := C.... | I believe there isn't currently any publicly available package for Go which implements the old-fashioned Unix "salted" DES based `crypt()` functionality. This is different from the normal symmetrical DES encryption/decryption which is implemented in the `"crypto/des"` package (as you have discovered).
You would have t... |
14,109,915 | I am currently playing around with an example from the book Violent Python. You can see my implementation [here](https://github.com/igniteflow/violent-python/blob/master/pwd-crackers/unix-pwd-crack.py)
I am now trying to implement the same script in Go to compare performance, note I am completely new to Go. Opening t... | 2013/01/01 | [
"https://Stackoverflow.com/questions/14109915",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/343223/"
] | `crypt` is very easy to wrap with cgo, eg
```
package main
import (
"fmt"
"unsafe"
)
// #cgo LDFLAGS: -lcrypt
// #define _GNU_SOURCE
// #include <crypt.h>
// #include <stdlib.h>
import "C"
// crypt wraps C library crypt_r
func crypt(key, salt string) string {
data := C.struct_crypt_data{}
ckey := C.... | Good news! There's actually an open source implementation of what you're looking for. [Osutil](https://github.com/kless/osutil "Osutil") has a crypt package that reimplements `crypt` in pure Go.
<https://github.com/kless/osutil/tree/master/user/crypt> |
21,892,080 | I'm using Python's [Watchdog](http://pythonhosted.org/watchdog/) to monitor a given directory for new files being created. When a file is created, some code runs that spawns a subprocess shell command to run different code to process this file. This should run for every new file that is created. I've tested this out wh... | 2014/02/19 | [
"https://Stackoverflow.com/questions/21892080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3329870/"
] | Here's what I ended up doing, which solved my problem. I used multiprocessing to start a separate watchdog monitoring process to watch for each file separately. Watchdog already queues up new files for me, which is fine for me.
As for point 2 above, I needed, e.g. a file2 to process before a file1, even though file1 ... | I'm not sure it would make much sense to do a thread per file. The [GIL](https://wiki.python.org/moin/GlobalInterpreterLock) will probably eliminate any advantage you'd see from doing that and might even impact performance pretty badly and lead to some unexpected behavior. I haven't personally found `watchdog` to be ve... |
25,663,543 | I'm trying to run celery worker in OS X (Mavericks). I activated virtual environment (python 3.4) and tried to start Celery with this argument:
```
celery worker --app=scheduling -linfo
```
Where `scheduling` is my celery app.
But I ended up with this error: `dbm.error: db type is dbm.gnu, but the module is not ava... | 2014/09/04 | [
"https://Stackoverflow.com/questions/25663543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493329/"
] | try this :-
```
var value=$(this).attr("href");
```
[Demo](http://jsfiddle.net/rmbvo9oh/2/) | In JavaScript, when you bind an event to an element, the `this` variable is being available (of course depending on the element and event). So, when you click an element and bind a function, within that function scope the clicked element is referenced as `this`. Writing `$(this)` you make a jQuery object out of it:
``... |
11,301,863 | I have a django FileField, which i use to store wav files on the Amazon s3 server. I have set up the celery task to read that file and convert it to mp3 and store it to another FileField. Problem i am facing is that i am unable to pass the input file to ffmpeg as the file is not the physical file on the hard disk drive... | 2012/07/02 | [
"https://Stackoverflow.com/questions/11301863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/867365/"
] | Use [`subprocess.Popen.communicate`](http://docs.python.org/library/subprocess.html?highlight=popen.communicate#subprocess.Popen.communicate) to pass the input to your subprocess:
```
command = ['ffmpeg', '-y', '-i', '-', output_file.name]
process = subprocess.Popen(command, stdin=subprocess.PIPE)
process.communicate(... | You need to create a pipe, pass the read end of the pipe to the subprocess, and dump the data into the write end. |
211,046 | What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource...
Something like this:
```
if os.path.isfile(self.icon):
icon_flags = win32con.LR_LOADFROMFILE | win32con... | 2008/10/17 | [
"https://Stackoverflow.com/questions/211046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] | You can use [wxPython](http://wxpython.org/) for this.
```
from wx import EmptyIcon
icon = EmptyIcon()
icon.CopyFromBitmap(your_wxBitmap)
```
The [wxBitmap](http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmap) can be generated in memory using [wxMemoryDC](http://docs.wxwidgets.org/stable/wx_wxmemorydc.html#wx... | You can probably create a object that mimics the python file-object interface.
<http://docs.python.org/library/stdtypes.html#bltin-file-objects> |
211,046 | What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource...
Something like this:
```
if os.path.isfile(self.icon):
icon_flags = win32con.LR_LOADFROMFILE | win32con... | 2008/10/17 | [
"https://Stackoverflow.com/questions/211046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] | You can use [wxPython](http://wxpython.org/) for this.
```
from wx import EmptyIcon
icon = EmptyIcon()
icon.CopyFromBitmap(your_wxBitmap)
```
The [wxBitmap](http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmap) can be generated in memory using [wxMemoryDC](http://docs.wxwidgets.org/stable/wx_wxmemorydc.html#wx... | This is working for me and doesn't require wx.
```
from ctypes import *
from ctypes.wintypes import *
CreateIconFromResourceEx = windll.user32.CreateIconFromResourceEx
size_x, size_y = 32, 32
LR_DEFAULTCOLOR = 0
with open("my32x32.png", "rb") as f:
png = f.read()
hicon = CreateIconFromResourceEx(png, len(png), 1... |
34,195,014 | I have a dataframe that has aggregated people by location like so
```
location_id | score | number_of_males | number_of_females
1 | 20 | 2 | 1
2 | 45 | 1 | 2
```
I want to create a new dataframe that unaggregated this one so I get something like
... | 2015/12/10 | [
"https://Stackoverflow.com/questions/34195014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1096662/"
] | Here is a way to get your result using `group_by`:
```
ids = ['location_id','score']
def foo(d):
return pd.Series(d['number_of_males'].values*['male'] +
d['number_of_females'].values*['female'])
pd.melt(df.groupby(ids).apply(foo).reset_index(), id_vars=ids).drop('variable', 1)
#Out[13]:
# ... | Until this I could do in a pandas functions
```
print df
location_id score number_of_males number_of_females
1 20 2 1
2 45 1 2
```
Converting the two columns to one,
```
df.set_index(['location_id','score']).stack().reset_index()
Out[1... |
61,265,226 | I use python boto3
when I upload file to s3,aws lambda will move the file to other bucket,I can get object url by lambda event,like
`https://xxx.s3.amazonaws.com/xxx/xxx/xxxx/xxxx/diamond+white.side.jpg`
The object key is `xxx/xxx/xxxx/xxxx/diamond+white.side.jpg`
This is a simple example,I can replace "+" get object... | 2020/04/17 | [
"https://Stackoverflow.com/questions/61265226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11303583/"
] | You should use `urllib.parse.unquote` and then replace `+` with space.
From my knowledge, `+` is the only exception from URL parsing, so you should be safe if you do that by hand. | I think this is what you want:
```
url_data = "https://xxx.s3.amazonaws.com/xxx/xxx/xxxx/xxxx/diamond+white.side.jpg".split("/")[3:]
object_key = "/".join(url_data)
``` |
71,738,691 | me is writing a simple code in python which should give me all the data available in my oracle table. Connection stuff are fine.
```
select column1,column2,column3 from table1.
```
column as following values
[](https://i.stack.imgur.com/dWjEf.png)
... | 2022/04/04 | [
"https://Stackoverflow.com/questions/71738691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15238129/"
] | I think this is because Ubuntu 16.04 includes a fairly old version of git that does not support the `--progress` flag to the `git submodule update` command. I've [opened an issue](https://github.com/alire-project/alire/issues/966) against Alire to see if we might be able to remove this flag.
In the meantime, I'd recom... | I *think* you need to say
```
alr index --update-all
```
`--update-all` is a bit misleading, but given that the error message mentions "index" it was the only likely thing in `alr index --help` (you find the possible commands, e.g. "index" here, by just `alr --help`). |
65,390,129 | I create a virtual environment; let's say test\_venv, and I activate it. All successful.
HOWEVER, the path of the Python Interpreter doesn't not change. I have illustrated the situation below.
For clarification, the python path SHOULD BE `~/Desktop/test_venv/bin/python`.
```
>>> python3 -m venv Desktop/test_venv
>>... | 2020/12/21 | [
"https://Stackoverflow.com/questions/65390129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14392583/"
] | #### *Please make sure to read Note #2.*
---
**This is what you should do if you don't want to create a new virtual environment**:
In `venv/bin` folder there are 3 files that store your venv path explicitly
and if the path is wrong they take the normal python path so you should change the path there to your new path... | It is not an answer specifically to your question, but it corresponds the title of the question. I faced similar problem and couldn't find solution on Internet. Maybe someone use my experience.
I created virtual environment for my python project. Some time later my python interpreter also stopped changing after virtua... |
65,390,129 | I create a virtual environment; let's say test\_venv, and I activate it. All successful.
HOWEVER, the path of the Python Interpreter doesn't not change. I have illustrated the situation below.
For clarification, the python path SHOULD BE `~/Desktop/test_venv/bin/python`.
```
>>> python3 -m venv Desktop/test_venv
>>... | 2020/12/21 | [
"https://Stackoverflow.com/questions/65390129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14392583/"
] | It is not an answer specifically to your question, but it corresponds the title of the question. I faced similar problem and couldn't find solution on Internet. Maybe someone use my experience.
I created virtual environment for my python project. Some time later my python interpreter also stopped changing after virtua... | Check the value of VIRTUAL\_ENV in /venv/bin/activate . If you renamed your project directory or moved it, then the value may still be the old value. PyCharm doesn't update your venv files if you used PyCharm to rename the project. You can delete the venv and recreate a new one if the path is wrong, or try the answer t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.