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 |
|---|---|---|---|---|---|
47,659,731 | My code is running fine for first iteration but after that it outputs the following error:
```
ValueError: matrix must be 2-dimensional
```
To the best of my knowledge (which is not much in python), my code is correct. but I don't know, why it is not running correctly for all given iterations. Could anyone help me i... | 2017/12/05 | [
"https://Stackoverflow.com/questions/47659731",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5507715/"
] | In a comment, you said,
>
> Yes that is the structure however const items, references, and class items can't be initialized in the body of constructors or in a non-constructor method.
>
>
>
A [delegating constructor](http://www.stroustrup.com/C++11FAQ.html#delegating-ctor) can be used to initialize reference memb... | No. Unless you are using C++11, where you can initialize some of them in class definition:
```
struct B
{
B(int) {}
constexpr B(double) {}
};
class A
{
const B b1 = 1;
static constexpr B b2 = 2.0;
};
```
For const values constructed from constructor input parameters, you need to use [initializer lis... |
26,978,891 | Using Maven I want to create 1) a JAR file for my current project with the current version included in the file name, myproject-version.jar, and 2) an overall artifact in tar.gzip format containing the project's JAR file and all dependency JARs in a lib directory and various driver scripts in a bin directory, but witho... | 2014/11/17 | [
"https://Stackoverflow.com/questions/26978891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85248/"
] | Just use `${project.artifactId}` as the value for your `finalName` in your assembly configuration.
Example derived from your config (note the `finalName` element inside configuration):
```
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4.1</version>
<con... | I think you are looking for this:
<http://maven.apache.org/plugins/maven-assembly-plugin/single-mojo.html#finalName>
just put it in the configuration of the plugin.
however, i think you shouldn't remove the version if you planning to upload it to some repository. |
612,253 | I'm using parallel linq, and I'm trying to download many urls concurrently using essentily code like this:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel( threads ).ToDictionary( url => url, url => GetPage( url );
```
Since downloading web pages is Network bound rather than CPU bound, usi... | 2009/03/04 | [
"https://Stackoverflow.com/questions/612253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] | Do the URLs refer to the same server? If so, it could be that you are hitting the HTTP connection limit instead of the threading limit. There's an easy way to tell - change your code to:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel(threads)
.ToDictionary(url => url,
... | Monitor your network traffic. If the URLs are from the same domain it may be limiting the bandwidth. More connections might not actually provide any speed-up. |
612,253 | I'm using parallel linq, and I'm trying to download many urls concurrently using essentily code like this:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel( threads ).ToDictionary( url => url, url => GetPage( url );
```
Since downloading web pages is Network bound rather than CPU bound, usi... | 2009/03/04 | [
"https://Stackoverflow.com/questions/612253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] | Do the URLs refer to the same server? If so, it could be that you are hitting the HTTP connection limit instead of the threading limit. There's an easy way to tell - change your code to:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel(threads)
.ToDictionary(url => url,
... | By default, .Net has limit of 2 concurrent connections to an end service point (IP:port). Thats why you would not see a difference if all urls are to one and the same server.
It can be controlled using [ServicePointManager.DefaultPersistentConnectionLimit](http://msdn.microsoft.com/en-us/library/system.net.servicepoin... |
612,253 | I'm using parallel linq, and I'm trying to download many urls concurrently using essentily code like this:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel( threads ).ToDictionary( url => url, url => GetPage( url );
```
Since downloading web pages is Network bound rather than CPU bound, usi... | 2009/03/04 | [
"https://Stackoverflow.com/questions/612253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] | Do the URLs refer to the same server? If so, it could be that you are hitting the HTTP connection limit instead of the threading limit. There's an easy way to tell - change your code to:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel(threads)
.ToDictionary(url => url,
... | I think there are already good answers to the question, but I'd like to make one important point. Using PLINQ for tasks that are not CPU bound is in principle wrong design. Not to say that it won't work - it will, but using multiple threads when it is unnecessary can cause troubles.
Unfortunatelly, there is no good wa... |
612,253 | I'm using parallel linq, and I'm trying to download many urls concurrently using essentily code like this:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel( threads ).ToDictionary( url => url, url => GetPage( url );
```
Since downloading web pages is Network bound rather than CPU bound, usi... | 2009/03/04 | [
"https://Stackoverflow.com/questions/612253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] | By default, .Net has limit of 2 concurrent connections to an end service point (IP:port). Thats why you would not see a difference if all urls are to one and the same server.
It can be controlled using [ServicePointManager.DefaultPersistentConnectionLimit](http://msdn.microsoft.com/en-us/library/system.net.servicepoin... | Monitor your network traffic. If the URLs are from the same domain it may be limiting the bandwidth. More connections might not actually provide any speed-up. |
612,253 | I'm using parallel linq, and I'm trying to download many urls concurrently using essentily code like this:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel( threads ).ToDictionary( url => url, url => GetPage( url );
```
Since downloading web pages is Network bound rather than CPU bound, usi... | 2009/03/04 | [
"https://Stackoverflow.com/questions/612253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] | I think there are already good answers to the question, but I'd like to make one important point. Using PLINQ for tasks that are not CPU bound is in principle wrong design. Not to say that it won't work - it will, but using multiple threads when it is unnecessary can cause troubles.
Unfortunatelly, there is no good wa... | Monitor your network traffic. If the URLs are from the same domain it may be limiting the bandwidth. More connections might not actually provide any speed-up. |
612,253 | I'm using parallel linq, and I'm trying to download many urls concurrently using essentily code like this:
```
int threads = 10;
Dictionary<string, string> results = urls.AsParallel( threads ).ToDictionary( url => url, url => GetPage( url );
```
Since downloading web pages is Network bound rather than CPU bound, usi... | 2009/03/04 | [
"https://Stackoverflow.com/questions/612253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] | By default, .Net has limit of 2 concurrent connections to an end service point (IP:port). Thats why you would not see a difference if all urls are to one and the same server.
It can be controlled using [ServicePointManager.DefaultPersistentConnectionLimit](http://msdn.microsoft.com/en-us/library/system.net.servicepoin... | I think there are already good answers to the question, but I'd like to make one important point. Using PLINQ for tasks that are not CPU bound is in principle wrong design. Not to say that it won't work - it will, but using multiple threads when it is unnecessary can cause troubles.
Unfortunatelly, there is no good wa... |
20,424,426 | I have recently moved from Ubuntu to Mac osx. And my first thing is to bring my vim with me.
I downloaded source from vim.org and compiled with gcc.( I'll put the version output at the bottom of my post)
I added pathogen.vim to ~/.vim/autoload directory. But when I add the code in ~/.vim/vimrc:
```
execute pathogen#... | 2013/12/06 | [
"https://Stackoverflow.com/questions/20424426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1914683/"
] | I found the problem.
system vimrc file: "$VIM/vimrc"
user vimrc file: "$HOME/.vimrc"
2nd user vimrc file: "~/.vim/vimrc"
user exrc file: "$HOME/.exrc"
I set $VIM to ~/.vim, which is the same as the 2nd user vimrc file. So the vimrc file load twice.
After I change $VIM to /etc/vim, everything turns out be good. | I had a similar problem and found that I had not created the ~/.vim directory correctly. I created it in the root by changing directory there and typing mkdir /.vim but for some reason it was not working. Then I deleted this folder and did mkdir ~/.vim and was ably to install and use pathogen. |
33,512,243 | I am trying to understand what is a better design choice in the case when we have functions in a Class which does a bunch of things and should either return a string or raise a custom exception when a particular check fails.
Example :
Suppose I have a class like :-
```
#Division only for +ve numbers
class DivisionEr... | 2015/11/04 | [
"https://Stackoverflow.com/questions/33512243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1982483/"
] | Your problem was due to your adding the JScrollPane and the JTextArea both to the `thePanel` JPanel, and so you see both: a JTextArea **without** JScrollPanes and an empty JScrollPane.
* Don't add add the textArea itself to the JScrollPane and also to a JPanel, since you can only add a component to **one** container.... | >
> Try this :
>
>
>
```
textArea1 = new JTextArea();
textArea1.setColumns(20);
textArea1.setRows(5);
scroller.setViewportView(textArea1);
``` |
67,503,532 | When I try to run my localhost server I get the following error:
`FileNotFoundError: [Errno 2] No such file or directory: '/static/CSV/ExtractedTweets.csv'`
This error is due to the line the line
`with open(staticfiles_storage.url('/CSV/ExtractedTweets.csv'), 'r', newline='', encoding="utf8") as csvfile:`
This line... | 2021/05/12 | [
"https://Stackoverflow.com/questions/67503532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9403355/"
] | I never found a solution to getting the staticfile path however the find() function seems to be an alternative solution.
custommodule.py
`from django.contrib.staticfiles.finders import find`
`with open(find('CSV/ExtractedTweets.csv'), 'r', newline='', encoding="utf8") as csvfile:` | if you are not looking to deploy this project you can add :
```
from django.conf import settings
urlpatterns = [
path(....),
path(....),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
```
or you can try to add :
```
STATICFILES_DIRS = [
BASE_DIR / "static",
]
```
to... |
64,483,271 | I'm trying install packages through pip, but every package I try to install, it fails with
```
ERROR: Could not find a version that satisfies the requirement numpy (from versions: none)
ERROR: No matching distribution found for numpy
```
When running the same command with `-vvv` like `pip install numpy -vvv` it give... | 2020/10/22 | [
"https://Stackoverflow.com/questions/64483271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4601149/"
] | The main issue is the `alpha` argument together with `geom_line`. If you want the keys to show up as lines you set alpha to 1 in the legend via `guides(color = guide_legend(override.aes = list(alpha = c(1, 1, 1, 1))))`. If you want colored rectangles for the keys this could be achieved by adding `key_glyph = "rect"` to... | The `values` argument from `scale_color_manual` should have color names instead of the line names, which you don't need to pass. Example:
```
scale_color_manual(name="Educational Attainment", values = c("red","yellow","white",...))
``` |
64,483,271 | I'm trying install packages through pip, but every package I try to install, it fails with
```
ERROR: Could not find a version that satisfies the requirement numpy (from versions: none)
ERROR: No matching distribution found for numpy
```
When running the same command with `-vvv` like `pip install numpy -vvv` it give... | 2020/10/22 | [
"https://Stackoverflow.com/questions/64483271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4601149/"
] | The main issue is the `alpha` argument together with `geom_line`. If you want the keys to show up as lines you set alpha to 1 in the legend via `guides(color = guide_legend(override.aes = list(alpha = c(1, 1, 1, 1))))`. If you want colored rectangles for the keys this could be achieved by adding `key_glyph = "rect"` to... | This should work (No output included as no data was shared). If you want the legend filled, you must also enable inside `aes()` the option `fill`. After that you can scale the colors for filling with `scale_fill_manual()` and use `labs()` to give them a common name. Here the code:
```
library(ggplot2)
#Code
ggplot(df,... |
32,400,048 | I am trying to edit a .reg file in python to replace strings in a file. I can do this for any other file type such as .txt.
Here is the python code:
```
with open ("C:/Users/UKa51070/Desktop/regFile.reg", "r") as myfile:
data=myfile.read()
print data
```
It returns an empty string | 2015/09/04 | [
"https://Stackoverflow.com/questions/32400048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3473280/"
] | I am not sure why you are not seeing any output, perhaps you could try:
`print len(data)`
Depending on your version of Windows, your `REG` file will be saved using UTF-16 encoding, unless you specifically export it using the `Win9x/NT4` format.
You could try using the following script:
```
import codecs
with codec... | It's probably not a good idea to edit `.reg` files manually. My suggestion is to search for a Python package that handles it for you. I think the [\_winreg](https://docs.python.org/2/library/_winreg.html) Python built-in library is what you are looking for. |
64,256,474 | I have to deploy a python project on AWS Lambda function. When I create its zip package it occupies a memory of around 80 MB (Lambda allows upto 50 MB). Also I cannot upload it to s3 because the memory size of the uncompressed package is around 284 MB (S3 allows upto 250 MB).
Any idea how to tackle this problem or Is t... | 2020/10/08 | [
"https://Stackoverflow.com/questions/64256474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9920934/"
] | To work just include this jQuery, Popper.js, and bootstrap js CDN and it will work.
Note that jQuery must come first, then Popper.js, and then our JavaScript plugins.
for more info click [here](https://getbootstrap.com/docs/4.5/getting-started/download/)
```
<script src="https://code.jquery.com/jquery-3.5.1.slim.min... | You forgot to add the CDN Bootstrap or link your bootstrap javascript at the bottom of the body.
Here:
```
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.clo... |
60,197,890 | I'm new to python and running the command:
>
> pip install pysam
>
>
>
Which results in:
```
Collecting pysam
Using cached https://files.pythonhosted.org/packages/25/7e/098753acbdac54ace0c6dc1f8a74b54c8028ab73fb027f6a4215487d1fea/pysam-0.15.4.tar.gz
ERROR: Command errored out with exit status 1:
comma... | 2020/02/12 | [
"https://Stackoverflow.com/questions/60197890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1308743/"
] | There are many binary wheels [at PyPI](https://pypi.org/project/pysam/#files) but only for Linux and MacOS X. [The package at bioconda](https://anaconda.org/bioconda/pysam) is also compiled only for Linux and OS X.
When you try to install pysam at Windows `pip` downloads the source distribution `pysam-0.15.4.tar.gz`, ... | if you have anaconda, try this:
`conda install -c bioconda pysam` |
57,921,006 | I have flask application via python. In my page, there is three images but flask only shows one of them.
I could not figure out where is the problem.
Here is my code.
HTML
====
```
<div class="col-xs-4">
<img style="width:40%;padding:5px" src="static/tomato.png"/>
<br>
<button class="btn btn-warning"><a style="colo... | 2019/09/13 | [
"https://Stackoverflow.com/questions/57921006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11697825/"
] | You can change the route main to mainPage. Try below code
```
@app.route("/mainPage")
def index():
return render_template('gui2.html')
``` | The error message 404 clear tells that the resource you are looking for was not found in the given location. Make sure that the file exists on the path you give. Simply, as tomato.png file is displayed correctly, just make sure that other files are also in the same location as tomato.png
Try opening in Incognito or pr... |
32,075,662 | I'm facing a nearly-textbook diamond inheritance problem. The (rather artificial!) example below captures all its essential features:
```
# CAVEAT: error-checking omitted for simplicity
class top(object):
def __init__(self, matrix):
self.matrix = matrix # matrix must be non-empty and rectangular!
de... | 2015/08/18 | [
"https://Stackoverflow.com/questions/32075662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/559827/"
] | `bottom` simply inherits from both; there is nothing specific about your classes that would make this case special:
```
class bottom(middle_0, middle_1):
pass
```
Demo:
```
>>> class bottom(middle_0, middle_1):
... pass
...
>>> bottom(3, 3).foo()
15
```
This works as expected because Python arranges both... | I think the
>
> a class bottom that "gets"1 foo from middle\_0 and \_\_init\_\_ from middle\_1.
>
>
>
would be simply done by
```
class bottom(middle_0, middle_1):
pass
``` |
33,771,929 | **Definition**:
>
> [Bag or Multiset](https://xlinux.nist.gov/dads/HTML/bag.html) is a set data structure which allows duplicate elements, provided the order of retrieval is not significant.
>
>
>
Now as I read python documentation it is told that a [Counter](https://docs.python.org/2/library/collections.html#col... | 2015/11/18 | [
"https://Stackoverflow.com/questions/33771929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/867461/"
] | >
> Can we use List or Tuple as a Bag data structure?
>
>
>
Yes.
It would require some code to get the structure correct, and you'd likely want a list as they are mutable. But you can add duplicates to a list, count them and remove them. | No.
* The elements of a bag are unordered and non-unique.
* The elements of a Counter are unordered and non-unique.
* The elements of a set are unordered and unique.
* The elements of a list (and tuple) are ordered and non-unique.
A Counter behaves like a bag of m&m's. A list behaves like a pez dispenser - the order ... |
54,483,013 | I am using a ScanSnap scanner which generates PDF-1.3 where it will auto-correct the orientation (rotate 0 or 180 degrees) of scanned documents when the PDF is viewed within Adobe Reader. OCR is done by the scanning software and I am assuming the orientation is determined then and encoded into the PDF.
Note that I kno... | 2019/02/01 | [
"https://Stackoverflow.com/questions/54483013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297500/"
] | The image **Im0** in the resources of the page in "internetfile-180.pdf" is not rotated:
[](https://i.stack.imgur.com/DS43A.jpg)
But the image **Im0** in the resources of the page in "internetfile.pdf" is rotated:
[![enter image description here... | **mkl** answered the question correctly doing all the hard work decoding the PDF for me.
I thought I would add in my python (PyPDF2) code to search for the found rotation condition in case it helps someone else.
```py
input1 = PyPDF2.PdfFileReader(open(filepath, "rb"))
totalPages = input1.getNumPages()
for pgNum in r... |
54,044,022 | I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is `','`, for the numeric part `';'`. I want to construct a dataframe only out of the numeric part as efficiently as possible.
I have made 5 attempts: among them, utilising the `converters` argument of `pd.read_csv`, using... | 2019/01/04 | [
"https://Stackoverflow.com/questions/54044022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9209546/"
] | ### Use a command-line tool
By far the most efficient solution I've found is to use a specialist command-line tool to replace `";"` with `","` and *then* read into Pandas. Pandas or pure Python solutions do not come close in terms of efficiency.
Essentially, using CPython or a tool written in C / C++ is likely to out... | If this is an option, substituting the character `;` with `,` in the string is faster.
I have written the string `x` to a file `test.dat`.
```
def csv_reader_4(x):
with open(x, 'r') as f:
a = f.read()
return pd.read_csv(StringIO(unicode(a.replace(';', ','))), usecols=[3, 4, 5])
```
The `unicode()` fu... |
54,044,022 | I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is `','`, for the numeric part `';'`. I want to construct a dataframe only out of the numeric part as efficiently as possible.
I have made 5 attempts: among them, utilising the `converters` argument of `pd.read_csv`, using... | 2019/01/04 | [
"https://Stackoverflow.com/questions/54044022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9209546/"
] | How about using a generator to do the replacement, and combining it with an appropriate decorator to get a file-like object suitable for pandas?
```
import io
import pandas as pd
# strings in first 3 columns are of arbitrary length
x = '''ABCD,EFGH,IJKL,34.23;562.45;213.5432
MNOP,QRST,UVWX,56.23;63.45;625.234
'''*10*... | If this is an option, substituting the character `;` with `,` in the string is faster.
I have written the string `x` to a file `test.dat`.
```
def csv_reader_4(x):
with open(x, 'r') as f:
a = f.read()
return pd.read_csv(StringIO(unicode(a.replace(';', ','))), usecols=[3, 4, 5])
```
The `unicode()` fu... |
54,044,022 | I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is `','`, for the numeric part `';'`. I want to construct a dataframe only out of the numeric part as efficiently as possible.
I have made 5 attempts: among them, utilising the `converters` argument of `pd.read_csv`, using... | 2019/01/04 | [
"https://Stackoverflow.com/questions/54044022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9209546/"
] | ### Use a command-line tool
By far the most efficient solution I've found is to use a specialist command-line tool to replace `";"` with `","` and *then* read into Pandas. Pandas or pure Python solutions do not come close in terms of efficiency.
Essentially, using CPython or a tool written in C / C++ is likely to out... | How about using a generator to do the replacement, and combining it with an appropriate decorator to get a file-like object suitable for pandas?
```
import io
import pandas as pd
# strings in first 3 columns are of arbitrary length
x = '''ABCD,EFGH,IJKL,34.23;562.45;213.5432
MNOP,QRST,UVWX,56.23;63.45;625.234
'''*10*... |
54,044,022 | I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is `','`, for the numeric part `';'`. I want to construct a dataframe only out of the numeric part as efficiently as possible.
I have made 5 attempts: among them, utilising the `converters` argument of `pd.read_csv`, using... | 2019/01/04 | [
"https://Stackoverflow.com/questions/54044022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9209546/"
] | ### Use a command-line tool
By far the most efficient solution I've found is to use a specialist command-line tool to replace `";"` with `","` and *then* read into Pandas. Pandas or pure Python solutions do not come close in terms of efficiency.
Essentially, using CPython or a tool written in C / C++ is likely to out... | A very very very fast one, `3.51` is the result, simply just make `csv_reader_4` the below, it simply converts `StringIO` to `str`, then replaces `;` with `,`, and reads the dataframe with `sep=','`:
```
def csv_reader_4(x):
with x as fin:
reader = pd.read_csv(StringIO(fin.getvalue().replace(';',',')), sep... |
54,044,022 | I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is `','`, for the numeric part `';'`. I want to construct a dataframe only out of the numeric part as efficiently as possible.
I have made 5 attempts: among them, utilising the `converters` argument of `pd.read_csv`, using... | 2019/01/04 | [
"https://Stackoverflow.com/questions/54044022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9209546/"
] | ### Use a command-line tool
By far the most efficient solution I've found is to use a specialist command-line tool to replace `";"` with `","` and *then* read into Pandas. Pandas or pure Python solutions do not come close in terms of efficiency.
Essentially, using CPython or a tool written in C / C++ is likely to out... | In my environment (Ubuntu 16.04, 4GB RAM, Python 3.5.2) the fastest method was (the prototypical1) `csv_reader_5` (taken from [U9-Forward's answer](https://stackoverflow.com/a/54166567/6394138)) which ran only less than 25% slower than reading the entire CSV file with no conversions. I improved that approach by impleme... |
54,044,022 | I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is `','`, for the numeric part `';'`. I want to construct a dataframe only out of the numeric part as efficiently as possible.
I have made 5 attempts: among them, utilising the `converters` argument of `pd.read_csv`, using... | 2019/01/04 | [
"https://Stackoverflow.com/questions/54044022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9209546/"
] | ### Use a command-line tool
By far the most efficient solution I've found is to use a specialist command-line tool to replace `";"` with `","` and *then* read into Pandas. Pandas or pure Python solutions do not come close in terms of efficiency.
Essentially, using CPython or a tool written in C / C++ is likely to out... | Python has powerfull features to manipulate data, but don't expect performance using python.When performance is needed , C and C++ are your friend .
Any fast library in python is written in C/C++. It is quite easy to use C/C++ code in python, have a look at swig utility (<http://www.swig.org/tutorial.html>) . You can w... |
54,044,022 | I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is `','`, for the numeric part `';'`. I want to construct a dataframe only out of the numeric part as efficiently as possible.
I have made 5 attempts: among them, utilising the `converters` argument of `pd.read_csv`, using... | 2019/01/04 | [
"https://Stackoverflow.com/questions/54044022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9209546/"
] | How about using a generator to do the replacement, and combining it with an appropriate decorator to get a file-like object suitable for pandas?
```
import io
import pandas as pd
# strings in first 3 columns are of arbitrary length
x = '''ABCD,EFGH,IJKL,34.23;562.45;213.5432
MNOP,QRST,UVWX,56.23;63.45;625.234
'''*10*... | A very very very fast one, `3.51` is the result, simply just make `csv_reader_4` the below, it simply converts `StringIO` to `str`, then replaces `;` with `,`, and reads the dataframe with `sep=','`:
```
def csv_reader_4(x):
with x as fin:
reader = pd.read_csv(StringIO(fin.getvalue().replace(';',',')), sep... |
54,044,022 | I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is `','`, for the numeric part `';'`. I want to construct a dataframe only out of the numeric part as efficiently as possible.
I have made 5 attempts: among them, utilising the `converters` argument of `pd.read_csv`, using... | 2019/01/04 | [
"https://Stackoverflow.com/questions/54044022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9209546/"
] | How about using a generator to do the replacement, and combining it with an appropriate decorator to get a file-like object suitable for pandas?
```
import io
import pandas as pd
# strings in first 3 columns are of arbitrary length
x = '''ABCD,EFGH,IJKL,34.23;562.45;213.5432
MNOP,QRST,UVWX,56.23;63.45;625.234
'''*10*... | In my environment (Ubuntu 16.04, 4GB RAM, Python 3.5.2) the fastest method was (the prototypical1) `csv_reader_5` (taken from [U9-Forward's answer](https://stackoverflow.com/a/54166567/6394138)) which ran only less than 25% slower than reading the entire CSV file with no conversions. I improved that approach by impleme... |
54,044,022 | I have an awkward CSV file which has multiple delimiters: the delimiter for the non-numeric part is `','`, for the numeric part `';'`. I want to construct a dataframe only out of the numeric part as efficiently as possible.
I have made 5 attempts: among them, utilising the `converters` argument of `pd.read_csv`, using... | 2019/01/04 | [
"https://Stackoverflow.com/questions/54044022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9209546/"
] | How about using a generator to do the replacement, and combining it with an appropriate decorator to get a file-like object suitable for pandas?
```
import io
import pandas as pd
# strings in first 3 columns are of arbitrary length
x = '''ABCD,EFGH,IJKL,34.23;562.45;213.5432
MNOP,QRST,UVWX,56.23;63.45;625.234
'''*10*... | Python has powerfull features to manipulate data, but don't expect performance using python.When performance is needed , C and C++ are your friend .
Any fast library in python is written in C/C++. It is quite easy to use C/C++ code in python, have a look at swig utility (<http://www.swig.org/tutorial.html>) . You can w... |
21,616,994 | I apologize if this question has been answered elsewhere. I havn't been able to find an answer yet through the search here or in the Pandas documentation (quite possible I've just missed it though).
I'm trying to import a html file into python through pandas and am unsure how to obtain the data I need from the result.... | 2014/02/07 | [
"https://Stackoverflow.com/questions/21616994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3264279/"
] | `History[0]` will give you the first element.
FYI, generally uppercase names are used for classes; variable names are `like_this`
These are just conventions; History is a legal identifier. | For each dataframe column you wish to convert to a list, you can transpose the values, and then convert it to a list as follows.
Here is an arbitrary DataFrame with one column (if there is more than one column, then slice into columns, and do this for each column):
```
s=DataFrame({'column 1':random.sample(range(10),... |
56,867,659 | While debugging `cmd is not recognized` is displayed and program is not debugged.
What can be the problem?
I have already checked the `path` and `pythonpath` variables and those seem to be just fine
```
bash
C:\Users\rahul\Desktop\vscode\.vscode>cd c:\Users\rahul\Desktop\vscode\.vscode &&
cmd /C "set "PYTHONIOEN... | 2019/07/03 | [
"https://Stackoverflow.com/questions/56867659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8306141/"
] | >
> TL;DR: `cmd` is not in your Windows Environment Path.
> [](https://i.stack.imgur.com/9hZxD.png)
> add `%SystemRoot%\system32` to your *System Variables* and restart VSCode.
>
>
>
---
Visual Studio Code has actually brought native support fo... | It means that `cmd` is not in your path. Either:
* Add the path to the system or user variables in the control panel
* Use the full path to `cmd` instead (typically `C:\Windows\System32\cmd.exe`), meaning something like:
`cd c:\Users\rahul\Desktop\vscode\.vscode && C:\Windows\System32\cmd.exe /C "set "PYTHONIOENCODIN... |
56,867,659 | While debugging `cmd is not recognized` is displayed and program is not debugged.
What can be the problem?
I have already checked the `path` and `pythonpath` variables and those seem to be just fine
```
bash
C:\Users\rahul\Desktop\vscode\.vscode>cd c:\Users\rahul\Desktop\vscode\.vscode &&
cmd /C "set "PYTHONIOEN... | 2019/07/03 | [
"https://Stackoverflow.com/questions/56867659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8306141/"
] | >
> TL;DR: `cmd` is not in your Windows Environment Path.
> [](https://i.stack.imgur.com/9hZxD.png)
> add `%SystemRoot%\system32` to your *System Variables* and restart VSCode.
>
>
>
---
Visual Studio Code has actually brought native support fo... | If cmd is in your Windows Environment Path, that means that, probably, your default integrated shell is set to wsl bash.
Change it and set
"terminal.integrated.shell.windows": "C:\Windows\System32\cmd.exe"
in your settings json
You may need to restart VSCode for this to take effect. |
14,506,717 | I need to print some information directly (without user confirmation) and I'm using Python and the `win32print` module.
I've already read the whole [Tim Golden win32print page](http://timgolden.me.uk/python/win32_how_do_i/print.html) (even read the [win32print doc](http://timgolden.me.uk/pywin32-docs/win32print.html)... | 2013/01/24 | [
"https://Stackoverflow.com/questions/14506717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1814970/"
] | I'm still looking for the best way to do this, but I found an answer that satisfy myself for the problem that I have. In Tim Golden's site (linked in question) you can find this example:
```
import win32ui
import win32print
import win32con
INCH = 1440
hDC = win32ui.CreateDC ()
hDC.CreatePrinterDC (win32print.GetDefa... | ```
# U must install pywin32 and import modules:
import win32print, win32ui, win32con
# X from the left margin, Y from top margin
# both in pixels
X=50; Y=50
# Separate lines from Your string
# for example:input_string and create
# new string for example: multi_line_string
multi_line_string = input_string.splitli... |
14,506,717 | I need to print some information directly (without user confirmation) and I'm using Python and the `win32print` module.
I've already read the whole [Tim Golden win32print page](http://timgolden.me.uk/python/win32_how_do_i/print.html) (even read the [win32print doc](http://timgolden.me.uk/pywin32-docs/win32print.html)... | 2013/01/24 | [
"https://Stackoverflow.com/questions/14506717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1814970/"
] | I'm still looking for the best way to do this, but I found an answer that satisfy myself for the problem that I have. In Tim Golden's site (linked in question) you can find this example:
```
import win32ui
import win32print
import win32con
INCH = 1440
hDC = win32ui.CreateDC ()
hDC.CreatePrinterDC (win32print.GetDefa... | The problem is the driver Version. If the Version is 4 you need to give XPS\_PASS instead of RAW, here is a sample.
```
drivers = win32print.EnumPrinterDrivers(None, None, 2)
hPrinter = win32print.OpenPrinter(printer_name)
printer_info = win32print.GetPrinter(hPrinter, 2)
for driver in drivers:
if driver["Name"] =... |
14,506,717 | I need to print some information directly (without user confirmation) and I'm using Python and the `win32print` module.
I've already read the whole [Tim Golden win32print page](http://timgolden.me.uk/python/win32_how_do_i/print.html) (even read the [win32print doc](http://timgolden.me.uk/pywin32-docs/win32print.html)... | 2013/01/24 | [
"https://Stackoverflow.com/questions/14506717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1814970/"
] | ```
# U must install pywin32 and import modules:
import win32print, win32ui, win32con
# X from the left margin, Y from top margin
# both in pixels
X=50; Y=50
# Separate lines from Your string
# for example:input_string and create
# new string for example: multi_line_string
multi_line_string = input_string.splitli... | The problem is the driver Version. If the Version is 4 you need to give XPS\_PASS instead of RAW, here is a sample.
```
drivers = win32print.EnumPrinterDrivers(None, None, 2)
hPrinter = win32print.OpenPrinter(printer_name)
printer_info = win32print.GetPrinter(hPrinter, 2)
for driver in drivers:
if driver["Name"] =... |
56,612,386 | I am trying to use the pre-made estimator `tf.estimator.DNNClassifier` to use on the MNIST dataset. I load the dataset from `tensorflow_dataset`.
I pursue the following four steps: first building the dataset pipeline and defining the input function:
```py
## Step 1
mnist, info = tfds.load('mnist', with_info=True)
ds... | 2019/06/15 | [
"https://Stackoverflow.com/questions/56612386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2191236/"
] | I think the graph construction gets weird if you load a tensorflow\_datasets dataset outside the `input_fn`. I followed the TF2.0 migration guide example and this does not give errors. Please note that I have not tested for model correctness and you will have to modify `input_fn` logic a bit to get the function for eva... | Answer by @dgumo is correct. I just wanted to add a basic example.
All tensors returned by the input function must be created within the input function.
```py
#Raw data can be outside
data_x = [0.0, 1.0, 2.0, 3.0, 4.0]
data_y = [3.0, 4.9, 7.3, 8.65, 10.75]
def supply_input():
#Tensors must be created inside the fu... |
17,363,611 | My code works perfectly, but I want it to write the values to a text file. When I try to do it, I get 'invalid syntax'. When I use a python shell, it works. So I don't understand why it isn't working in my script.
I bet it's something silly, but why wont it output the data to a text file??
```
#!/usr/bin/env python
... | 2013/06/28 | [
"https://Stackoverflow.com/questions/17363611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2519572/"
] | `lis` is an empty list, *any* index will raise an exception.
If you wanted to add elements to that list, use `lis.append()` instead.
Note that you can loop over sequences *directly*, there is no need to keep your own counter:
```
def front_x(words):
lis = []
words.sort()
for word in words:
if wo... | >
> i need to sort the list but the words starting with x should be the first ones.
>
>
>
Complementary to the custom search key in @Martijn's extended answer, you could also try this, which is closer to your original approach and might be easier to understand:
```
def front_x(words):
has_x, hasnt = [], []
... |
9,570,637 | Working on getting Celery setup (following the basic tutorial) with a mongodb broker as backend. Following the configuration guidelines set out in the official docs, my `celeryconfig.py` is setup as follows:
```
CELERY_RESULT_BACKEND = "mongodb"
BROKER_BACKEND = "mongodb"
BROKER_URL = "mongodb://user:[email protected]... | 2012/03/05 | [
"https://Stackoverflow.com/questions/9570637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/215608/"
] | I think it's a bug. Celery passed hostname instead of server\_uri to kombu, thus cause this problem. After tracing the code, I found the following conf to bypass the bug before they fixed it.
```
CELERY_RESULT_BACKEND = 'mongodb'
BROKER_HOST = "subdomain.mongolab.com"
BROKER_PORT = 123456
BROKER_TRANSPORT = 'mongodb'
... | Would it help if you remove "user", "pass", "port", and "database" from the CELERY\_MONGODB\_BACKEND\_SETTINGS dict, and do:
```
BROKER_URL = "mongodb://user:[email protected]:123456/testdb"
CELERY_MONGODB_BACKEND_SETTINGS = {
"host":BROKER_URL,
"taskmeta_collection":"taskmeta",
}
``` |
23,320,954 | how to replace '1c' to '\x1c' in python. I have a list with elements like '12','13' etc and want to replace with '\x12', '\x13' etc.
here is what i tried and failed
```
letters=[]
for i in range(10,128,1):
a=(str(hex(i))).replace('0x','\x')
letters.append(a)
print letters
```
**I need is '31' t... | 2014/04/27 | [
"https://Stackoverflow.com/questions/23320954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3559830/"
] | You need to use the built-in function [`chr`](https://docs.python.org/2/library/functions.html#chr) to return the correct ascii code (which is the string you are after):
```
>>> [chr(i) for i in range(10,20,1)]
['\n', '\x0b', '\x0c', '\r', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13']
``` | Your code is fine, you just need to escape the `\` with a `\`.
```
letters=[]
for i in range(10,128,1):
a=(str(hex(i))).replace('0x','\\x') #you have to escape the \
letters.append(a)
print letters
```
[DEMO
----](http://repl.it/Rvl/1) |
23,320,954 | how to replace '1c' to '\x1c' in python. I have a list with elements like '12','13' etc and want to replace with '\x12', '\x13' etc.
here is what i tried and failed
```
letters=[]
for i in range(10,128,1):
a=(str(hex(i))).replace('0x','\x')
letters.append(a)
print letters
```
**I need is '31' t... | 2014/04/27 | [
"https://Stackoverflow.com/questions/23320954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3559830/"
] | You need to use the built-in function [`chr`](https://docs.python.org/2/library/functions.html#chr) to return the correct ascii code (which is the string you are after):
```
>>> [chr(i) for i in range(10,20,1)]
['\n', '\x0b', '\x0c', '\r', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13']
``` | Best way to do your task is using string formatting, then you don't have to replace anything, and the code looks clearer:
```
letters = ['\\x%x' % i for i in range(10, 128)]
print letters
``` |
4,740,473 | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | 2011/01/19 | [
"https://Stackoverflow.com/questions/4740473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62255/"
] | **Minimal example**
```
from setuptools import setup, find_packages
setup(
name="foo",
version="1.0",
packages=find_packages(),
)
```
More info in [docs](https://packaging.python.org/tutorials/packaging-projects/) | Here you will find the simplest possible example of using distutils and setup.py:
<https://docs.python.org/2/distutils/introduction.html#distutils-simple-example>
This assumes that all your code is in a single file and tells how to package a project containing a single module. |
4,740,473 | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | 2011/01/19 | [
"https://Stackoverflow.com/questions/4740473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62255/"
] | Complete walkthrough of writing `setup.py` scripts [here](http://docs.python.org/distutils/setupscript.html). (with some examples)
If you'd like a real-world example, I could point you towards the `setup.py` scripts of a couple major projects. Django's is [here](http://code.djangoproject.com/browser/django/trunk/setup... | Look at this complete example <https://github.com/marcindulak/python-mycli> of a small python package. It is based on packaging recommendations from <https://packaging.python.org/en/latest/distributing.html>, uses setup.py with distutils and in addition shows how to create RPM and deb packages.
The project's setup.py ... |
4,740,473 | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | 2011/01/19 | [
"https://Stackoverflow.com/questions/4740473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62255/"
] | Complete walkthrough of writing `setup.py` scripts [here](http://docs.python.org/distutils/setupscript.html). (with some examples)
If you'd like a real-world example, I could point you towards the `setup.py` scripts of a couple major projects. Django's is [here](http://code.djangoproject.com/browser/django/trunk/setup... | **Minimal example**
```
from setuptools import setup, find_packages
setup(
name="foo",
version="1.0",
packages=find_packages(),
)
```
More info in [docs](https://packaging.python.org/tutorials/packaging-projects/) |
4,740,473 | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | 2011/01/19 | [
"https://Stackoverflow.com/questions/4740473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62255/"
] | **READ THIS FIRST** <https://packaging.python.org/en/latest/current.html>
>
> Installation Tool Recommendations
> =================================
>
>
> 1. Use pip to install Python packages
> from PyPI.
> 2. Use virtualenv, or pyvenv to isolate application specific dependencies from a shared Python installation.... | Here you will find the simplest possible example of using distutils and setup.py:
<https://docs.python.org/2/distutils/introduction.html#distutils-simple-example>
This assumes that all your code is in a single file and tells how to package a project containing a single module. |
4,740,473 | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | 2011/01/19 | [
"https://Stackoverflow.com/questions/4740473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62255/"
] | Complete walkthrough of writing `setup.py` scripts [here](http://docs.python.org/distutils/setupscript.html). (with some examples)
If you'd like a real-world example, I could point you towards the `setup.py` scripts of a couple major projects. Django's is [here](http://code.djangoproject.com/browser/django/trunk/setup... | **READ THIS FIRST** <https://packaging.python.org/en/latest/current.html>
>
> Installation Tool Recommendations
> =================================
>
>
> 1. Use pip to install Python packages
> from PyPI.
> 2. Use virtualenv, or pyvenv to isolate application specific dependencies from a shared Python installation.... |
4,740,473 | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | 2011/01/19 | [
"https://Stackoverflow.com/questions/4740473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62255/"
] | Look at this complete example <https://github.com/marcindulak/python-mycli> of a small python package. It is based on packaging recommendations from <https://packaging.python.org/en/latest/distributing.html>, uses setup.py with distutils and in addition shows how to create RPM and deb packages.
The project's setup.py ... | Here is the utility I wrote to generate a simple *setup.py* file (template) with useful comments and links. I hope, it will be useful.
Installation
------------
```sh
sudo pip install setup-py-cli
```
Usage
-----
To generate *setup.py* file just type in the terminal.
```sh
setup-py
```
Now *setup.py* file shoul... |
4,740,473 | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | 2011/01/19 | [
"https://Stackoverflow.com/questions/4740473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62255/"
] | **READ THIS FIRST** <https://packaging.python.org/en/latest/current.html>
>
> Installation Tool Recommendations
> =================================
>
>
> 1. Use pip to install Python packages
> from PyPI.
> 2. Use virtualenv, or pyvenv to isolate application specific dependencies from a shared Python installation.... | Look at this complete example <https://github.com/marcindulak/python-mycli> of a small python package. It is based on packaging recommendations from <https://packaging.python.org/en/latest/distributing.html>, uses setup.py with distutils and in addition shows how to create RPM and deb packages.
The project's setup.py ... |
4,740,473 | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | 2011/01/19 | [
"https://Stackoverflow.com/questions/4740473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62255/"
] | Complete walkthrough of writing `setup.py` scripts [here](http://docs.python.org/distutils/setupscript.html). (with some examples)
If you'd like a real-world example, I could point you towards the `setup.py` scripts of a couple major projects. Django's is [here](http://code.djangoproject.com/browser/django/trunk/setup... | I recommend the [setup.py](https://github.com/pypa/sampleproject/blob/master/setup.py) of the [Python Packaging User Guide](https://packaging.python.org/)'s example project.
The Python Packaging User Guide "aims to be the authoritative resource on how to package, publish and install Python distributions using current ... |
4,740,473 | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | 2011/01/19 | [
"https://Stackoverflow.com/questions/4740473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62255/"
] | **Minimal example**
```
from setuptools import setup, find_packages
setup(
name="foo",
version="1.0",
packages=find_packages(),
)
```
More info in [docs](https://packaging.python.org/tutorials/packaging-projects/) | Here is the utility I wrote to generate a simple *setup.py* file (template) with useful comments and links. I hope, it will be useful.
Installation
------------
```sh
sudo pip install setup-py-cli
```
Usage
-----
To generate *setup.py* file just type in the terminal.
```sh
setup-py
```
Now *setup.py* file shoul... |
4,740,473 | After studying this page:
<http://docs.python.org/distutils/builtdist.html>
I am hoping to find some setup.py files to study so as to make my own (with the goal of making a fedora rpm file).
Could the s.o. community point me towards some good examples? | 2011/01/19 | [
"https://Stackoverflow.com/questions/4740473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62255/"
] | **READ THIS FIRST** <https://packaging.python.org/en/latest/current.html>
>
> Installation Tool Recommendations
> =================================
>
>
> 1. Use pip to install Python packages
> from PyPI.
> 2. Use virtualenv, or pyvenv to isolate application specific dependencies from a shared Python installation.... | I recommend the [setup.py](https://github.com/pypa/sampleproject/blob/master/setup.py) of the [Python Packaging User Guide](https://packaging.python.org/)'s example project.
The Python Packaging User Guide "aims to be the authoritative resource on how to package, publish and install Python distributions using current ... |
46,229,543 | I have written a fraction adder in Python for my computer science class. However, I am running into problems with the final answer reduction procedure.
The procedure uses the "not equal" comparison operator **!=** at the start of a **for** loop to test whether, when dividing the numerator and denominator, there will b... | 2017/09/14 | [
"https://Stackoverflow.com/questions/46229543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8580749/"
] | The error you see is derived by the wrong usage of `for` where `while` is the right type of loop (`for` is for iteration, `while` for condition).
Nevertheless, your logic at deciding the common denominators is flawed, and leads to an infinite loop. Please read about [least common multiple](https://en.wikipedia.org/wik... | You are trying to write a greatest-common-denominator finder, and your terminating condition is wrong. [Euclid's Algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm) repeatedly takes takes the modulo difference of the two numbers until the result is 0; then the next-to-last result is the GCD. The standard pyth... |
16,514,570 | I can get matplotlib to work in pylab (ipython --pylab), but when I execute the same command in a python script a plot does not appear. My workspace focus changes from a fullscreened terminal to a Desktop when I run my script, which suggests that it is trying to plot something but failing.
The following code works in ... | 2013/05/13 | [
"https://Stackoverflow.com/questions/16514570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3749393/"
] | I believe you need `plt.show()` . | You need to add `plt.show()` after `plt.plot(...)`.
`plt.plot()` just makes the plot, `plt.show()` takes the plot you made and displays it on the screen. |
44,057,032 | my python program isn't working properly and it's something with the submit button and it gives me an error saying:
```
TypeError: 'str' object is not callable
```
help please. Here is the part of the code that doesn't work:
```
def submit():
g_name = ent0.get()
g_surname = ent1.get()
g_dob = ent2.get()... | 2017/05/18 | [
"https://Stackoverflow.com/questions/44057032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8033270/"
] | `childByAutoId()` is for the iOS SDK. For `admin.Database()`, use [push()](https://firebase.google.com/docs/reference/admin/node/admin.database.Reference#push).
```
var reference = admin.database().ref(path).push();
``` | It should work like this:
```
exports.addPersonalRecordHistory = functions.database.ref('/personalRecords/{userId}/current/{exerciseId}').onWrite(event => {
var path = 'personalRecords/' + event.params.userId + '/history/' + event.params.exerciseId;
return admin.database().ref(path).set({
username: "asd",
... |
14,626,189 | >
> **Possible Duplicate:**
>
> [python looping seems to not follow sequence?](https://stackoverflow.com/questions/4123266/python-looping-seems-to-not-follow-sequence)
>
> [In what order does python display dictionary keys?](https://stackoverflow.com/questions/4458169/in-what-order-does-python-display-dictionary... | 2013/01/31 | [
"https://Stackoverflow.com/questions/14626189",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1990185/"
] | A dictionary is a mapping of keys to values; it does not have an order.
You want a `collections.OrderedDict`:
```
collections.OrderedDict([('x', 9), ('y', 10), ('z', 20)])
Out[175]: OrderedDict([('x', 9), ('y', 10), ('z', 20)])
for key in Out[175]:
print Out[175][key]
```
Note, however, that dictionary orderin... | A dictionary is a collection that is not ordered. So in theory the order of the elements may change on each operation you perform on it. If you want the keys to be printed in order, you will have to sort them before printing(i.e. collect the keys and then sort them). |
70,023,042 | I was wondering if anyone can help. I'm trying to take a CSV from a GCP bucket, run it into a dataframe, and then output the file to another bucket in the project, however using this method my dag is running but i dont im not getting any outputs into my designated bucket? My dag just takes ages to run. Any insight on t... | 2021/11/18 | [
"https://Stackoverflow.com/questions/70023042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12176250/"
] | With broadcasting
```
res = np.where(arr0[...,None] == entries, arr1[...,None], 0).max(axis=(0, 1))
```
The result of `np.where(...)` is a (3, 3, 4) array, where slicing `[...,0]` would give you the same 3x3 array you get by manually doing the `np.where` with just `entries[0]`, etc. Then taking the max of each 3x3 s... | It's more convenient to work in 1D case. You need to sort your `arr0` then find starting indices for every group and use `np.maximum.reduceat`.
```
arr0_1D = np.array([[0,3,0],[1,3,2],[1,2,0]]).ravel()
arr1_1D = np.array([[4,5,6],[6,2,4],[3,7,9]]).ravel()
arg_idx = np.argsort(arr0_1D)
>>> arr0_1D[arg_idx]
array([0, 0,... |
35,346,971 | I'm having some problems with inheritance. I need to import simplejson or install if it can't be found and import. I'm doing this in a another class and sending it via inheritance where needed. The way I'm doing it here works in python 2.6+ but not in 2.4.
```
# This class will hold all things needed over in all class... | 2016/02/11 | [
"https://Stackoverflow.com/questions/35346971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4840281/"
] | I know this is not the question, but you should not be using subprocess.popen for this. Use pip. It's great.
```
try:
import simplejson as json
except ImportError:
import pip
try:
import os
isAdmin = os.getuid() == 0
except AttributeError:
import ctypes
isAdmin = ctypes.... | `apt-get install` won't guarantee that you are installing `simplejson` for all versions of python. It will only work for the *system installed* version of Python which may or may not be 2.4. That's going to depend highly on what underlying version of Linux or Ubuntu or Debian you are using. If you want to be portable a... |
35,346,971 | I'm having some problems with inheritance. I need to import simplejson or install if it can't be found and import. I'm doing this in a another class and sending it via inheritance where needed. The way I'm doing it here works in python 2.6+ but not in 2.4.
```
# This class will hold all things needed over in all class... | 2016/02/11 | [
"https://Stackoverflow.com/questions/35346971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4840281/"
] | I know this is not the question, but you should not be using subprocess.popen for this. Use pip. It's great.
```
try:
import simplejson as json
except ImportError:
import pip
try:
import os
isAdmin = os.getuid() == 0
except AttributeError:
import ctypes
isAdmin = ctypes.... | I have a ton to say about what's going on here, but I think the other comments have that covered.
It looks like `simplejson` simply isn't supported in python versions below 2.5: <https://github.com/simplejson/simplejson>. And I'm sure if you're using apt-get, you're installing the latest. Try just using python 2.4's n... |
35,346,971 | I'm having some problems with inheritance. I need to import simplejson or install if it can't be found and import. I'm doing this in a another class and sending it via inheritance where needed. The way I'm doing it here works in python 2.6+ but not in 2.4.
```
# This class will hold all things needed over in all class... | 2016/02/11 | [
"https://Stackoverflow.com/questions/35346971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4840281/"
] | `apt-get install` won't guarantee that you are installing `simplejson` for all versions of python. It will only work for the *system installed* version of Python which may or may not be 2.4. That's going to depend highly on what underlying version of Linux or Ubuntu or Debian you are using. If you want to be portable a... | I have a ton to say about what's going on here, but I think the other comments have that covered.
It looks like `simplejson` simply isn't supported in python versions below 2.5: <https://github.com/simplejson/simplejson>. And I'm sure if you're using apt-get, you're installing the latest. Try just using python 2.4's n... |
1,900,956 | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ... | 2009/12/14 | [
"https://Stackoverflow.com/questions/1900956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55366/"
] | the `repr` function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.
```
>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'on... | You could do:
```
import inspect
mydict = {'one': 1, 'two': 2}
source = inspect.getsourcelines(inspect.getmodule(inspect.stack()[0][0]))[0]
print([x for x in source if x.startswith("mydict = ")])
```
Also: make sure not to shadow the dict builtin! |
1,900,956 | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ... | 2009/12/14 | [
"https://Stackoverflow.com/questions/1900956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55366/"
] | You could do:
```
import inspect
mydict = {'one': 1, 'two': 2}
source = inspect.getsourcelines(inspect.getmodule(inspect.stack()[0][0]))[0]
print([x for x in source if x.startswith("mydict = ")])
```
Also: make sure not to shadow the dict builtin! | The default string representation for a dictionary seems to be just right:
```
>>> a={3: 'foo', 17: 'bar' }
>>> a
{17: 'bar', 3: 'foo'}
>>> print a
{17: 'bar', 3: 'foo'}
>>> print "a=", a
a= {17: 'bar', 3: 'foo'}
```
Not sure if you can get at the "variable name", since variables in Python are just labels for values... |
1,900,956 | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ... | 2009/12/14 | [
"https://Stackoverflow.com/questions/1900956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55366/"
] | You can use `pickle`
```
import pickle
data = {'one': 1, 'two': 2}
file = open('dump.txt', 'wb')
pickle.dump(data, file)
file.close()
```
and to read it again
```
file = open('dump.txt', 'rb')
data = pickle.load(file)
```
EDIT: Guess I misread your question, sorry ... but pickle might help all the same. :) | Do you just want to know how to write a line to a [file](http://docs.python.org/library/stdtypes.html#file-objects)? First, you need to open the file:
```
f = open("filename.txt", 'w')
```
Then, you need to write the string to the file:
```
f.write("dict = {'one': 1, 'two': 2}" + '\n')
```
You can repeat this for... |
1,900,956 | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ... | 2009/12/14 | [
"https://Stackoverflow.com/questions/1900956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55366/"
] | Is something like this what you're looking for?
```
def write_vars_to_file(f, **vars):
for name, val in vars.items():
f.write("%s = %s\n" % (name, repr(val)))
```
Usage:
```
>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}
``` | The default string representation for a dictionary seems to be just right:
```
>>> a={3: 'foo', 17: 'bar' }
>>> a
{17: 'bar', 3: 'foo'}
>>> print a
{17: 'bar', 3: 'foo'}
>>> print "a=", a
a= {17: 'bar', 3: 'foo'}
```
Not sure if you can get at the "variable name", since variables in Python are just labels for values... |
1,900,956 | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ... | 2009/12/14 | [
"https://Stackoverflow.com/questions/1900956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55366/"
] | Do you just want to know how to write a line to a [file](http://docs.python.org/library/stdtypes.html#file-objects)? First, you need to open the file:
```
f = open("filename.txt", 'w')
```
Then, you need to write the string to the file:
```
f.write("dict = {'one': 1, 'two': 2}" + '\n')
```
You can repeat this for... | 1) Make the dictionary:
```
X = {'a': 1}
```
2) Write to a new file:
```
file = open('X_Data.py', 'w')
file.write(str(X))
file.close()
```
Lastly, in the file that you want the variable to be, read that file and make a new variable with the data from the data file:
```
import ast
file = open('X_Data.py', 'r')
f ... |
1,900,956 | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ... | 2009/12/14 | [
"https://Stackoverflow.com/questions/1900956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55366/"
] | Is something like this what you're looking for?
```
def write_vars_to_file(f, **vars):
for name, val in vars.items():
f.write("%s = %s\n" % (name, repr(val)))
```
Usage:
```
>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}
``` | I found an easy way to get the dictionary value, **and its name as well**! I'm not sure yet about reading it back, I'm going to continue to do research and see if I can figure that out.
Here is the code:
```
your_dict = {'one': 1, 'two': 2}
variables = [var for var in dir() if var[0:2] != "__" and var[-1:-2] != "__"... |
1,900,956 | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ... | 2009/12/14 | [
"https://Stackoverflow.com/questions/1900956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55366/"
] | the `repr` function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.
```
>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'on... | Is something like this what you're looking for?
```
def write_vars_to_file(f, **vars):
for name, val in vars.items():
f.write("%s = %s\n" % (name, repr(val)))
```
Usage:
```
>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}
``` |
1,900,956 | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ... | 2009/12/14 | [
"https://Stackoverflow.com/questions/1900956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55366/"
] | the `repr` function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.
```
>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'on... | Do you just want to know how to write a line to a [file](http://docs.python.org/library/stdtypes.html#file-objects)? First, you need to open the file:
```
f = open("filename.txt", 'w')
```
Then, you need to write the string to the file:
```
f.write("dict = {'one': 1, 'two': 2}" + '\n')
```
You can repeat this for... |
1,900,956 | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ... | 2009/12/14 | [
"https://Stackoverflow.com/questions/1900956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55366/"
] | the `repr` function will return a string which is the exact definition of your dict (except for the order of the element, dicts are unordered in python). unfortunately, i can't tell a way to automatically get a string which represent the variable name.
```
>>> dict = {'one': 1, 'two': 2}
>>> repr(dict)
"{'two': 2, 'on... | I found an easy way to get the dictionary value, **and its name as well**! I'm not sure yet about reading it back, I'm going to continue to do research and see if I can figure that out.
Here is the code:
```
your_dict = {'one': 1, 'two': 2}
variables = [var for var in dir() if var[0:2] != "__" and var[-1:-2] != "__"... |
1,900,956 | Let's say I have the following dictionary in a small application.
```
dict = {'one': 1, 'two': 2}
```
What if I would like to write the exact code line, with the dict name and all, to a file. Is there a function in python that let me do it? Or do I have to convert it to a string first? Not a problem to convert it, ... | 2009/12/14 | [
"https://Stackoverflow.com/questions/1900956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55366/"
] | Is something like this what you're looking for?
```
def write_vars_to_file(f, **vars):
for name, val in vars.items():
f.write("%s = %s\n" % (name, repr(val)))
```
Usage:
```
>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}
``` | 1) Make the dictionary:
```
X = {'a': 1}
```
2) Write to a new file:
```
file = open('X_Data.py', 'w')
file.write(str(X))
file.close()
```
Lastly, in the file that you want the variable to be, read that file and make a new variable with the data from the data file:
```
import ast
file = open('X_Data.py', 'r')
f ... |
62,933,026 | I am new to python and I am trying to loop through the list of urls in a `csv` file and grab the website `title`using `BeautifulSoup`, which I would like then to save to a file `Headlines.csv`. But I am unable to grab the webpage `title`. If I use a variable with single url as follows:
```
url = 'https://www.space.com... | 2020/07/16 | [
"https://Stackoverflow.com/questions/62933026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13122812/"
] | As the previous answer has already mentioned about the "\ufeff", you would need to change the encoding.
The second issue is that when you read a CSV file, you will get a list containing all the columns for each row. The keyword here is list. You are passing the request a list instead of a string.
Based on the example... | You have a byte order mark `\\ufeff` on the URL you parse from your file.
It looks like your file is a signature file and has encoding like utf-8-sig.
You need to read with the file with `encoding='utf-8-sig'`
Read more [here](https://stackoverflow.com/a/49150749/7502914). |
31,039,972 | I am trying to run a Python script from another Python script, and getting its `pid` so I can kill it later.
I tried `subprocess.Popen()` with argument `shell=True', but the`pid`attribute returns the`pid` of the parent script, so when I try to kill the subprocess, it kills the parent.
Here is my code:
```py
proc = s... | 2015/06/25 | [
"https://Stackoverflow.com/questions/31039972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4759209/"
] | `shell=True` starts a new shell process. `proc.pid` is the pid of that shell process. `kill -9` kills the shell process making the grandchild python process into an orphan.
If the grandchild python script can spawn its own child processes and you want to kill the whole process tree then see [How to terminate a python ... | So run it directly without a shell:
```
proc = subprocess.Popen(['python', './script.py'])
```
By the way, you may want to consider changing the hardcoded `'python'` to [`sys.executable`](https://docs.python.org/3.5/library/sys.html#sys.executable). Also, you can use [`proc.kill()`](https://docs.python.org/3.5/libra... |
47,403,218 | -I am successfully logged into my Virtual Machine and I have uploaded my files to the AWS as well (Amazon EC2). What I wish to do is execute my python code on the server but it says that the dependencies are not installed. When I run a pip install command, it returns the following error:
PermissionError: [Errno 13] Pe... | 2017/11/21 | [
"https://Stackoverflow.com/questions/47403218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8888799/"
] | Assuming you have the number 3 in cell A1 on Sheet2, the following will display the value of column A in the row that has rank 3 in Sheet1
This can be copied down in Sheet2 if you have other numbers in the rows below
```
=INDEX(Sheet1!A:AH,MATCH($A1,Sheet1!$AH:$AH,0),1)
``` | Sounds like you need `INDEX/MATCH` like this
`=INDEX(Sheet1!A:A,MATCH(3,Sheet1!AH:AH,0))`
The `MATCH` function finds the position of 3 in column `AH` and then the `INDEX` function returns the value from column `A` in the same row.
Is that what you need? |
45,046,601 | I have this weird problem that can be reproduced with the [simple tutorial](https://docs.docker.com/compose/django/) from Docker.
If I follow the tutorial exactly, everything would work fine, i.e. after `docker-compose up` command, the web container would run and connect nicely to the db container.
However, if I ch... | 2017/07/12 | [
"https://Stackoverflow.com/questions/45046601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814824/"
] | Use [wait-for-it.sh](https://github.com/vishnubob/wait-for-it) to wait for Postgres to be ready:
Download this well known script: <https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh>
```
version: '3'
services:
db:
image: postgres
web:
build: .
command: /wait-for-it.sh db:54... | You can use [healthcheck](https://docs.docker.com/compose/compose-file/#healthcheck).
example from: [peter-evans/docker-compose-healthcheck: How to wait for container X before starting Y using docker-compose healthcheck](https://github.com/peter-evans/docker-compose-healthcheck#waiting-for-postgresql-to-be-healthy)
`... |
45,046,601 | I have this weird problem that can be reproduced with the [simple tutorial](https://docs.docker.com/compose/django/) from Docker.
If I follow the tutorial exactly, everything would work fine, i.e. after `docker-compose up` command, the web container would run and connect nicely to the db container.
However, if I ch... | 2017/07/12 | [
"https://Stackoverflow.com/questions/45046601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3814824/"
] | As documentation say [depends\_on](https://docs.docker.com/compose/compose-file/#depends_on) `depends_on` it express dependency between containers but that does not mean that a container will wait to other to be ready, a possible solution is to add within of `docker-compose` a bit sleep, something like this:
```
com... | You can use [healthcheck](https://docs.docker.com/compose/compose-file/#healthcheck).
example from: [peter-evans/docker-compose-healthcheck: How to wait for container X before starting Y using docker-compose healthcheck](https://github.com/peter-evans/docker-compose-healthcheck#waiting-for-postgresql-to-be-healthy)
`... |
40,062,854 | i want to see some info and get info about my os with python as in my tutorial but actually can't run this code:
```
import os
F = os.popen('dir')
```
and this :
```
F.readline()
' Volume in drive C has no label.\n'
F = os.popen('dir') # Read by sized blocks
F.read(50)
' Volume in drive C has no labe... | 2016/10/15 | [
"https://Stackoverflow.com/questions/40062854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4716040/"
] | The problem is you can't save your custom array in NSUserDefaults. To do that you should change them to NSData then save it in NSUserDefaults
Here is the code I used in my project it's in swift 2 syntax and I don't think it's going be hard to convert it to swift 3
```
let data = NSKeyedArchiver.archivedDataWithRootObj... | The closest type to a Swift struct that UserDefaults supports might be an NSDictionary. You could copy the struct elements into an Objective C NSDictionary object before saving the data. |
40,062,854 | i want to see some info and get info about my os with python as in my tutorial but actually can't run this code:
```
import os
F = os.popen('dir')
```
and this :
```
F.readline()
' Volume in drive C has no label.\n'
F = os.popen('dir') # Read by sized blocks
F.read(50)
' Volume in drive C has no labe... | 2016/10/15 | [
"https://Stackoverflow.com/questions/40062854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4716040/"
] | The problem is you can't save your custom array in NSUserDefaults. To do that you should change them to NSData then save it in NSUserDefaults
Here is the code I used in my project it's in swift 2 syntax and I don't think it's going be hard to convert it to swift 3
```
let data = NSKeyedArchiver.archivedDataWithRootObj... | I was able to program a solution based on @ahruss ([How to save an array of custom struct to NSUserDefault with swift?](https://stackoverflow.com/questions/38406457/how-to-save-an-array-of-custom-struct-to-nsuserdefault-with-swift?rq=1)). However, I modified it for swift 3 and it also shows how to implement this soluti... |
40,062,854 | i want to see some info and get info about my os with python as in my tutorial but actually can't run this code:
```
import os
F = os.popen('dir')
```
and this :
```
F.readline()
' Volume in drive C has no label.\n'
F = os.popen('dir') # Read by sized blocks
F.read(50)
' Volume in drive C has no labe... | 2016/10/15 | [
"https://Stackoverflow.com/questions/40062854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4716040/"
] | Saving objects in `UserDefaults` have very specific restrictions:
>
> [set(\_:forKey:) reference:](https://developer.apple.com/reference/foundation/userdefaults/1414067-set)
>
>
> The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSD... | The closest type to a Swift struct that UserDefaults supports might be an NSDictionary. You could copy the struct elements into an Objective C NSDictionary object before saving the data. |
40,062,854 | i want to see some info and get info about my os with python as in my tutorial but actually can't run this code:
```
import os
F = os.popen('dir')
```
and this :
```
F.readline()
' Volume in drive C has no label.\n'
F = os.popen('dir') # Read by sized blocks
F.read(50)
' Volume in drive C has no labe... | 2016/10/15 | [
"https://Stackoverflow.com/questions/40062854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4716040/"
] | Saving objects in `UserDefaults` have very specific restrictions:
>
> [set(\_:forKey:) reference:](https://developer.apple.com/reference/foundation/userdefaults/1414067-set)
>
>
> The value parameter can be only property list objects: NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For NSArray and NSD... | I was able to program a solution based on @ahruss ([How to save an array of custom struct to NSUserDefault with swift?](https://stackoverflow.com/questions/38406457/how-to-save-an-array-of-custom-struct-to-nsuserdefault-with-swift?rq=1)). However, I modified it for swift 3 and it also shows how to implement this soluti... |
65,849,470 | I am writing a unit test in python for a function that takes an object from an S3 bucket as the input parameter.
The input parameter is of type `boto3.resources.factory.s3.ObjectSummary`.
I don't want my unit test to access S3.
I am writing a test that reads a .csv file into an object of type
`pandas.core.frame.Dat... | 2021/01/22 | [
"https://Stackoverflow.com/questions/65849470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15061060/"
] | The answer is you shouldn't have a `loadingData()` Redux action in the first place. Loading or not is, as you correctly pointed out, every component's "local" state, so you should store it appropriately - inside each component's "normal" state.
Redux store is designed for storing the data that is mutual to several com... | There is good practice that you have `loading` for each `subject` you're calling a backend `api`, for example a `loading` for calling `books` api, a `loading` for calling `movies` api and so on.
I recommend you create a `loadings` object in your state and fill it with different loadings that you need like this:
```
l... |
65,849,470 | I am writing a unit test in python for a function that takes an object from an S3 bucket as the input parameter.
The input parameter is of type `boto3.resources.factory.s3.ObjectSummary`.
I don't want my unit test to access S3.
I am writing a test that reads a .csv file into an object of type
`pandas.core.frame.Dat... | 2021/01/22 | [
"https://Stackoverflow.com/questions/65849470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15061060/"
] | The answer is you shouldn't have a `loadingData()` Redux action in the first place. Loading or not is, as you correctly pointed out, every component's "local" state, so you should store it appropriately - inside each component's "normal" state.
Redux store is designed for storing the data that is mutual to several com... | It is perfectly fine to handle a loading state either in local component state, the part of your redux state where you will finally store the data, or a completely different part.
There is no "one size fits all" solution and different applications handle it differently.
If you want to track that state globally, it is ... |
65,849,470 | I am writing a unit test in python for a function that takes an object from an S3 bucket as the input parameter.
The input parameter is of type `boto3.resources.factory.s3.ObjectSummary`.
I don't want my unit test to access S3.
I am writing a test that reads a .csv file into an object of type
`pandas.core.frame.Dat... | 2021/01/22 | [
"https://Stackoverflow.com/questions/65849470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15061060/"
] | It is perfectly fine to handle a loading state either in local component state, the part of your redux state where you will finally store the data, or a completely different part.
There is no "one size fits all" solution and different applications handle it differently.
If you want to track that state globally, it is ... | There is good practice that you have `loading` for each `subject` you're calling a backend `api`, for example a `loading` for calling `books` api, a `loading` for calling `movies` api and so on.
I recommend you create a `loadings` object in your state and fill it with different loadings that you need like this:
```
l... |
10,572,671 | I'm new to c/c++ and I've been working with python for a long time, I didn't take any tutorials, but I got this error when I tried to declare an array of strings.
code:
```
QString months[12]={'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'};
```
error:
invalid conversion from 'int' to ... | 2012/05/13 | [
"https://Stackoverflow.com/questions/10572671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1164958/"
] | Use double quotes for strings (`"`). `'` is for character literals. | In the Python is not difference between `'` and `"`(are strings) , but in the C++ They are different:
```
char c = 'c';
string str = "string";
```
Don't forget the C++ has not `'''`, while it was as string in Python.
Your code:
```
... "Oct", "Nov", "Dec"};
``` |
63,381,325 | i am using a python script with regex module trying to process 2 files and create a final output as required but getting some errors.
cat links.txt
```
https://videos-a.jwpsrv.com/content/conversions/7kHOkkQa/videos/XXXXJD8C-32313922.mp4.m3u8?hdnts=exp=1596554537~acl=*/bGxpJD8C-32313922.mp4.m3u8~hmac=2ac95222f1693d11... | 2020/08/12 | [
"https://Stackoverflow.com/questions/63381325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13516930/"
] | If you are using regular expressions anyway, why not use them to pull out this information, too?
```py
import re
base = 'https://cdn.jwplayer.com/videos/'
kek = re.compile(r'(?<=\/)[\w\-\.]+(?=.m3u8)')
nre = re.compile(r'(.*)\s+Lecture (\d+)(.*)')
with open('name.txt') as b:
lecture = []
for line in b:
parse... | The issue is with the last line of cat names.txt.
```
>>> line = "Labour Costing Lecture 352 (Classroom Lecture)"
>>> [c for c in line.rpartition(' ')[2]]
['L', 'e', 'c', 't', 'u', 'r', 'e', ')']
```
Clearly not what you are intending to extract. Since none of these is a number, it returns an empty string which cann... |
45,026,566 | i was try to use python API but its not working if i try to use multiple parameter
**Not working**
```
from flask import Flask, request
@app.route('/test', methods=['GET', 'POST'])
def test():
req_json = request.get_json(force=True)
UserName = req_json['username']
UserPassword = req... | 2017/07/11 | [
"https://Stackoverflow.com/questions/45026566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6472692/"
] | as you can see in the logs ,the app crashed due to indentation error.
please check indentation of account\_sid variable in your code. | The hint is in your logs.
```
2017-07-11T06:44:16.078195+00:00 app[web.1]: File "server.py", line 29
2017-07-11T06:44:16.078211+00:00 app[web.1]: account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID)
2017-07-11T06:44:16.078211+00:00 app[web.1]: ^
2017-07-11T06:44:16.078213+00:00 app[web.1]: IndentationErr... |
45,026,566 | i was try to use python API but its not working if i try to use multiple parameter
**Not working**
```
from flask import Flask, request
@app.route('/test', methods=['GET', 'POST'])
def test():
req_json = request.get_json(force=True)
UserName = req_json['username']
UserPassword = req... | 2017/07/11 | [
"https://Stackoverflow.com/questions/45026566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6472692/"
] | I honestly can't tell where the issue w/ your indents is and whether that is a misunderstanding how whitespacing works in python or posting code blocks on stackoverflow (my guess is a combo of both). So I took your code and put it in PyCharm and properly indented it and pasted that code into this nice [tool](http://wit... | as you can see in the logs ,the app crashed due to indentation error.
please check indentation of account\_sid variable in your code. |
45,026,566 | i was try to use python API but its not working if i try to use multiple parameter
**Not working**
```
from flask import Flask, request
@app.route('/test', methods=['GET', 'POST'])
def test():
req_json = request.get_json(force=True)
UserName = req_json['username']
UserPassword = req... | 2017/07/11 | [
"https://Stackoverflow.com/questions/45026566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6472692/"
] | I honestly can't tell where the issue w/ your indents is and whether that is a misunderstanding how whitespacing works in python or posting code blocks on stackoverflow (my guess is a combo of both). So I took your code and put it in PyCharm and properly indented it and pasted that code into this nice [tool](http://wit... | The hint is in your logs.
```
2017-07-11T06:44:16.078195+00:00 app[web.1]: File "server.py", line 29
2017-07-11T06:44:16.078211+00:00 app[web.1]: account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID)
2017-07-11T06:44:16.078211+00:00 app[web.1]: ^
2017-07-11T06:44:16.078213+00:00 app[web.1]: IndentationErr... |
28,619,302 | I'M using pycharm (python) (and mapnik)on windows 7, I just wanted to test if everything is in place after installation. I used an example from the net here is it , and I have a frame error. Could it be an installation problem ? compiler ?? I'M very new to python. thanks in advance for your time.
```
"""
This is a sim... | 2015/02/19 | [
"https://Stackoverflow.com/questions/28619302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4586167/"
] | A little insight on your code first: `all` will fetch ALL records from the database and pass it to your ruby code, this is resource and time consuming. Then the `shuffle`, `sort_by` and `reverse` are all executed by ruby. You will quickly hit performance issues as your database grow.
Your solution is to let your datab... | Hmm, here's a fun hack that *should* work:
```
@articles = Article.
all.
sort_by{|t| (t.date_published.beginning_of_day.to_i * 1000) + rand(100)}
```
This works by forcing all the dates to be the beginning of the day (so that everything published on '2015-02-19' for example will have the same `to_i` value. Then ... |
12,121,260 | I've run into a specific problem and thought of an solution. But since the solution is pretty involved, I was wondering if others have encountered something similar and could comment on best practises or propose alternatives.
The problem is as follows:
I have a webapp written in Django which has some screen in which d... | 2012/08/25 | [
"https://Stackoverflow.com/questions/12121260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1227852/"
] | I tried something similar and you might be interested in the solution. Here is my question:
[python Socket.IO client for sending broadcast messages to TornadIO2 server](https://stackoverflow.com/questions/10950365/python-socket-io-client-for-sending-broadcast-messages-to-tornadio2-server)
And this is the answer:
<ht... | The scheme Google implemented for the now abandoned Wave product's concurrent editing features is documented, <http://www.waveprotocol.org/whitepapers/operational-transform>. This aspect of Wave seemed like a success, even though Wave itself was quickly abandoned.
As far as the questions you asked about implementing y... |
40,499,702 | I‘m studying the tensoflow, and want to test the example of slim. When I command ./scripts/train\_lenet\_on\_mnist.sh, The program run to eval\_image\_classifier give a Type Error, The Error information as follows:
```
I tensorflow/stream_executor/dso_loader.cc:111] successfully opened CUDA library libcublas.so.8.0 lo... | 2016/11/09 | [
"https://Stackoverflow.com/questions/40499702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7134638/"
] | The problem is the compatible of `python2` and `python3`. As I used `python3` for interpretation, but the the Keys From a Dictionary is different from p`ython2` and `python3`.
In `Python2`, simply calling `keys()` on a dictionary object will return what you expect, however, in `Python3`, `keys()` no longer returns a ... | The other python3 change for eval\_image\_classifier.py is
```
for name, value in names_to_values.iteritems():
to
for name, value in names_to_values.items():
``` |
56,689,803 | I'm trying to remove some part of text in the given string. So the problem is as follows. I have a string. Say HTML code like this.
```
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a ... | 2019/06/20 | [
"https://Stackoverflow.com/questions/56689803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7928692/"
] | You put the `$` which means end of string. try this:
```
x = re.sub('<style>.*?</style>', '', text, flags=re.DOTALL)
print(x)
```
You can check out [this website](https://regex101.com/r/Fti1aD/1), has a nice regex demo.
**A little note**: I am not extremely familiar with CSS so if there are nested `<style>` tags it... | Note particularly the `?` character in the `<style>(.*?)</style>` portion of the RegExp expression so as not to be "too greedy". Otherwise, in the example below, it would also remove the `<title>` HTML tag.
```
import re
text = """
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
... |
33,984,889 | I want to use an array and its first derivative (diff) as features for training. Since the diff array is of an smaller size I would like to fill it up so that I don't have problems with sizes when I stack them and use both as features.
If I fill the diff(array) with a 0, How should I align them? Do I put the 0 at the... | 2015/11/29 | [
"https://Stackoverflow.com/questions/33984889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1978146/"
] | Instead of left- or right-sided finite differences, you could use a centered finite difference (which is equivalent to taking the average of the left- and right-sided differences), and then pad both ends with appropriate approximations of the derivatives there. This will keep the estimation of the derivative aligned wi... | According to the [documentation](http://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html), diff is simply doing `out[n] = a[n+1] - a[n]`. This means that it is not a derivative approximated by finite difference, but the discrete difference. To calculate the finite difference, you need to divide by the step ... |
38,596,674 | I bet I am doing something very simple wrong. I want to start with an empty 2D numpy array and append arrays to it (with dimensions 1 row by 4 columns).
```
open_cost_mat_train = np.matrix([])
for i in xrange(10):
open_cost_mat = np.array([i,0,0,0])
open_cost_mat_train = np.vstack([open_cost_mat_train,open_co... | 2016/07/26 | [
"https://Stackoverflow.com/questions/38596674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3948664/"
] | If `open_cost_mat_train` is large I would encourage you to replace the for loop by a **vectorized algorithm**. I will use the following funtions to show how efficiency is improved by vectorizing loops:
```
def fvstack():
import numpy as np
np.random.seed(100)
ocmt = np.matrix([]).reshape((0, 4))
for i ... | You need to reshape your original matrix so that the number of columns match the appended arrays:
```
open_cost_mat_train = np.matrix([]).reshape((0,4))
```
After which, it gives:
```
open_cost_mat_train
# matrix([[ 0., 0., 0., 0.],
# [ 1., 0., 0., 0.],
# [ 2., 0., 0., 0.],
# [ 3.,... |
23,280,253 | I have the following code -
```
from sys import version
class ExampleClass(object):
def get_sys_version(self):
return version
x = ExampleClass()
print x.get_sys_version()
```
and it gets parsed by this code -
```
import ast
source = open("input.py")
code = source.read()
node = ast.parse(... | 2014/04/24 | [
"https://Stackoverflow.com/questions/23280253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/827401/"
] | This is because you're using `mode='eval'`, which only works for single expressions. Your code has multiple statements, so use `mode='exec'` instead. (It's the default)
See the [documentation for `compile()`](https://docs.python.org/2/library/functions.html#compile) for explanation of the `mode` argument, since that's... | It's not related to `ast`.
You get same error, when try:
```
In [1]: eval('from sys import version')
File "<string>", line 1
from sys import version
^
SyntaxError: invalid syntax
```
Try `exec` mode:
```
In [1]: exec('from sys import version')
In [2]:
``` |
48,821,856 | I would like to clean a list from leading occurrences of `'a'`. That is, `['a', 'a', 'b', 'b']` should become `['b', 'b']` and at the same time `['b', 'a', 'a', 'b']` should be kept unchanged.
```
def remove_leading_items(l):
if len(l) == 1 or l[0] != 'a':
return l
else:
return remove_leading_i... | 2018/02/16 | [
"https://Stackoverflow.com/questions/48821856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/671013/"
] | Yes. Immediately, you should be using a for loop. Recursion is generally not Pythonic. Second, use built in tools:
```
from itertools import dropwhile
def remove_leading_items(l, item):
return list(dropwhile (lambda x: x == item, l))
```
Or
```
return list(dropwhile(item.__eq__, l))
```
### Edit
Out of curi... | ### Code:
```
def remove_leading(a_list, to_remove):
i = 0
while i < len(a_list) and a_list[i] == to_remove:
i += 1
return a_list[i:]
```
### Test Code:
```
print(remove_leading(list('aabb'), 'a'))
print(remove_leading(list('baab'), 'a'))
print(remove_leading([], 'a'))
```
### Results:
```
[... |
48,821,856 | I would like to clean a list from leading occurrences of `'a'`. That is, `['a', 'a', 'b', 'b']` should become `['b', 'b']` and at the same time `['b', 'a', 'a', 'b']` should be kept unchanged.
```
def remove_leading_items(l):
if len(l) == 1 or l[0] != 'a':
return l
else:
return remove_leading_i... | 2018/02/16 | [
"https://Stackoverflow.com/questions/48821856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/671013/"
] | Yes. Immediately, you should be using a for loop. Recursion is generally not Pythonic. Second, use built in tools:
```
from itertools import dropwhile
def remove_leading_items(l, item):
return list(dropwhile (lambda x: x == item, l))
```
Or
```
return list(dropwhile(item.__eq__, l))
```
### Edit
Out of curi... | You can try this also:-
```
s = ['a', 'a', 'b', 'b','a','a','b']
def check(ls):
new_ls = ls
count = 0
while ls[0]=='a':
new_ls = ls[(count+1):]
ls = new_ls
return new_ls
print(check(s))
``` |
48,821,856 | I would like to clean a list from leading occurrences of `'a'`. That is, `['a', 'a', 'b', 'b']` should become `['b', 'b']` and at the same time `['b', 'a', 'a', 'b']` should be kept unchanged.
```
def remove_leading_items(l):
if len(l) == 1 or l[0] != 'a':
return l
else:
return remove_leading_i... | 2018/02/16 | [
"https://Stackoverflow.com/questions/48821856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/671013/"
] | Yes. Immediately, you should be using a for loop. Recursion is generally not Pythonic. Second, use built in tools:
```
from itertools import dropwhile
def remove_leading_items(l, item):
return list(dropwhile (lambda x: x == item, l))
```
Or
```
return list(dropwhile(item.__eq__, l))
```
### Edit
Out of curi... | Code:
```
my_list = ['a', 'a', 'b', 'b', 'a', 'b']
item_i_hate = 'a'
for index in range(len(my_list)):
if my_list[index] != item_i_hate:
my_list = my_list[index:]
break
``` |
50,534,429 | I made a FC neural network with numpy based on the video's of welch's lab but when I try to train it I seem to have exploding gradients at launch, which is weird, I will put down the whole code which is testable in python 3+. only costfunctionprime seem to break the gradient descent stuff going but I have no idea what ... | 2018/05/25 | [
"https://Stackoverflow.com/questions/50534429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7974205/"
] | This conversion works.
```
#string[] path = File.ReadLines("C:\\Users\\M\\numb.txt").ToArray();
String[] path = {"1","2","3"};
int[] numb = Array.ConvertAll(path,int.Parse);
for (int i = 0; i < path.Length; i++)
{
Console.WriteLine(path[i]);
}
for (int i = 0; i < numb.Length; i++)
{
Console.WriteLine(num... | I can't imagine this wouldn't work:
```
string[] path = File.ReadAllLines("C:\\Users\\M\\numb.txt");
int[] numb = new int[path.Length];
for (int i = 0; i < path.Length; i++)
{
numb[i] = int.Parse(path[i]);
}
```
I think your issue is that you are using `File.ReadLines`, which reads each line into a single strin... |
50,534,429 | I made a FC neural network with numpy based on the video's of welch's lab but when I try to train it I seem to have exploding gradients at launch, which is weird, I will put down the whole code which is testable in python 3+. only costfunctionprime seem to break the gradient descent stuff going but I have no idea what ... | 2018/05/25 | [
"https://Stackoverflow.com/questions/50534429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7974205/"
] | It is better to use TryParse instead of parse. Also it is easier to work with List, than with array.
```
using System;
using System.Collections.Generic;
namespace StringToInt
{
class Program
{
static void Main(string[] args)
{
String[] path = { "1", "2", "3", "a", "b7" };
... | I can't imagine this wouldn't work:
```
string[] path = File.ReadAllLines("C:\\Users\\M\\numb.txt");
int[] numb = new int[path.Length];
for (int i = 0; i < path.Length; i++)
{
numb[i] = int.Parse(path[i]);
}
```
I think your issue is that you are using `File.ReadLines`, which reads each line into a single strin... |
45,916,726 | here is my output.txt file
```
4f337d5000000001
4f337d5000000001
0082004600010000
0082004600010000
334f464600010000
334f464600010000
[... many values omitted ...]
334f464600010000
334f464600010000
4f33464601000100
4f33464601000100
```
how i can change these values into decimal with the help of python and save into a... | 2017/08/28 | [
"https://Stackoverflow.com/questions/45916726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8523601/"
] | Since the values are 16 hex digits long I assume these are 64-bit integers you want to play with. If the file is reasonably small then you can use `read` to bring in the whole string and `split` to break it into individual values:
```
with open("newfile.txt", 'w') as out_file, open("outfile,txt") as in_file:
for h... | You can do this:
```
with open('output.txt') as f:
new_file = open("new_file.txt", "w")
for item in f.readlines():
new_file.write(str(int(item, 16)) + "\n")
new_file.close()
``` |
45,916,726 | here is my output.txt file
```
4f337d5000000001
4f337d5000000001
0082004600010000
0082004600010000
334f464600010000
334f464600010000
[... many values omitted ...]
334f464600010000
334f464600010000
4f33464601000100
4f33464601000100
```
how i can change these values into decimal with the help of python and save into a... | 2017/08/28 | [
"https://Stackoverflow.com/questions/45916726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8523601/"
] | Since the values are 16 hex digits long I assume these are 64-bit integers you want to play with. If the file is reasonably small then you can use `read` to bring in the whole string and `split` to break it into individual values:
```
with open("newfile.txt", 'w') as out_file, open("outfile,txt") as in_file:
for h... | One of the comments mentioned a shell command. This is how a Python one-liner can be invoked from the shell command line (Linux bash in this example). I/O redirection is handled by the shell.
```
$ python -c $'import sys\nfor line in sys.stdin: print(int(line,16))' <hex.txt >dec.txt
``` |
45,916,726 | here is my output.txt file
```
4f337d5000000001
4f337d5000000001
0082004600010000
0082004600010000
334f464600010000
334f464600010000
[... many values omitted ...]
334f464600010000
334f464600010000
4f33464601000100
4f33464601000100
```
how i can change these values into decimal with the help of python and save into a... | 2017/08/28 | [
"https://Stackoverflow.com/questions/45916726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8523601/"
] | You can do this:
```
with open('output.txt') as f:
new_file = open("new_file.txt", "w")
for item in f.readlines():
new_file.write(str(int(item, 16)) + "\n")
new_file.close()
``` | One of the comments mentioned a shell command. This is how a Python one-liner can be invoked from the shell command line (Linux bash in this example). I/O redirection is handled by the shell.
```
$ python -c $'import sys\nfor line in sys.stdin: print(int(line,16))' <hex.txt >dec.txt
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.