qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 29 22k | response_k stringlengths 26 13.4k | __index_level_0__ int64 0 17.8k |
|---|---|---|---|---|---|---|
58,738,629 | I'm trying to convert string to date using `arrow` module.
During the conversion, I received this error:
`arrow.parser.ParserMatchError: Failed to match '%A %d %B %Y %I:%M:%S %p %Z' when parsing 'Wednesday 06 November 2019 03:05:42 PM CDT'`
The conversion is done using one simple line according to this [documentation]... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58738629",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4193208/"
] | This looks like a [regex](https://www.regular-expressions.info/) kind of problem to me so use [Pattern](https://docs.oracle.com/javase/9/docs/api/java/util/regex/Pattern.html) class. By positively matching what we want, it implicitly ignores files that don't conform (like your `._` example)
```
final Pattern p = Patte... | What if instead of looking at the end of the filename, you inspected the beginning? It looks like the first part of the filename is consistently YYYY-MM, you could then parse out the year and the month using `.substring()` like so:
```
String year = pdfBills.substring(0, 4);
String month = pdfBills.substring(5, 7);
`... | 7,229 |
52,996,227 | I have a JSON file that looks like this:
```
{
"authors": [
{
"name": "John Steinbeck",
"description": "An author from Salinas California"
},
{
"name": "Mark Twain",
"description": "An icon of american literature",
"publications": [
{
"book": "Huckleberry Fin"
},
{
"book": "The Myster... | 2018/10/25 | [
"https://Stackoverflow.com/questions/52996227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4163962/"
] | >
> "Use the force, Linq!" - Obi Enum Kenobi
>
>
>
```
using System.Linq;
List<Int32> numbers = new List<Int32>()
{
1,
2,
3,
4
};
String asString = String
.Join(
", ",
numbers.Select( n => n.ToString( CultureInfo.InvariantCulture ) )
);
List<Int32> fromString = asString
... | The easiest way is to make a new list each time and casting each item as you iterate. | 7,230 |
1,168,687 | Right now I'm working on a scripting language that doesn't yet have a FFI. I'd like to know what's the most convenient way to get it in, assuming that I'd like to write it like cool geeks do - I'd like to write the FFI in the scripting language itself.
The programming language I need to interface is C. So for basics I... | 2009/07/22 | [
"https://Stackoverflow.com/questions/1168687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21711/"
] | I think an appropiate answer requires a [detailed essay](http://vmathew.in/dnc.html).
Basically, there should be wrappers for the library loading and symbol searching facilities provided by the host OS. If the core datatypes of your language are internally represented with a single C data structure, then a requiremen... | Check out <http://sourceware.org/libffi/>
Remember the calling conventions are going to be different on different architectures, i.e. what order function variables are popped onto the stack. I don't know about writing it in your own scripting language, I do know that Java JNI uses libffi. | 7,233 |
63,966,342 | ```
import pandas as pd
import datetime as dt
from pandas_datareader import data as web
import yfinance as yf
yf.pdr_override()
```
filename=r'C:\Users\User\Desktop\from\_python\data\_from\_python.xlsx'
```
yeah = pd.read_excel(filename, sheet_name='entry')
stock = []
stock = list(yeah['name'])
stock = [ s.repla... | 2020/09/19 | [
"https://Stackoverflow.com/questions/63966342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13933399/"
] | You can try this answer using a package called [yahooquery](https://github.com/dpguthrie/yahooquery). Disclaimer: I am the author of the package.
```
from yahooquery import Ticker
import pandas as pd
symbols = ['^GSPC', 'NQ=F', 'AAU', 'ALB', 'AOS', 'APPS', 'AQB', 'ASPN', 'ATHM', 'AZRE', 'BCYC', 'BGNE', 'CAT', 'CC', '... | It processes stocks and sectors at the same time. However, some stocks do not have a sector, so an error countermeasure is added.
Since the issue column name consists of sector and issue name, we change it to a hierarchical column and update the retrieved data frame. Finally, I save it in CSV format to import it into E... | 7,234 |
18,828,124 | I am running my django web app in httpd .
In httpd.conf this is what I have.
```
Listen 8090
User ctaftest
Group ctaftest
```
And after starting httpd server when I do
`netstat -anp |grep httpd`
I get
```
root 31621 1 1 17:23 ? 00:00:00 /usr/local/httpd-python/bin/httpd -k start
ctaftest 31625 31... | 2013/09/16 | [
"https://Stackoverflow.com/questions/18828124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1371989/"
] | What does your WSGIDaemonProcess configuration in the rest of your Apache config look like? You can set the user there.
```
WSGIDaemonProcess mysite user=ctaftest group=ctaftest threads=5
``` | To start with, if you call:
```
os.path.expanduser("dir_path")
```
it should return just:
```
dir_path
```
Did you instead mean:
```
os.path.expanduser("~/dir_path")
```
Anyway, when you use embedded mode of mod\_wsgi, your code runs in the Apache child worker processes. These processes can be shared with othe... | 7,235 |
48,171,851 | I can't find a command example for archiving a set of files from a given prefix in S3 into a given vault in Glacier using ONLY COMMAND LINE, i.e. no Lifecycles, no python+boto. Thanks.
This doc has a lot of examples but none fit my request:
<https://docs.aws.amazon.com/cli/latest/reference/s3/mv.html> | 2018/01/09 | [
"https://Stackoverflow.com/questions/48171851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1872286/"
] | That's because you can't. As described in the [Amazon's S3 Documentation](https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-class-intro.html):
>
> You cannot specify GLACIER as the storage class at the time that you create an object. You create GLACIER objects by first uploading objects using STANDARD, RRS, or ... | You're looking for this:
<https://aws.amazon.com/premiumsupport/knowledge-center/restore-s3-object-glacier-storage-class/>
```
aws s3 cp s3://bucketname/key/file s3://bucketname/key/file --storage-class GLACIER
```
optionally use --recursive instead of a specific file name. | 7,238 |
27,712,101 | I am trying to sort dictionaries in MongoDB. However, I get the value error "too many values to unpack" because I think it's implying that there are too many values in each dictionary (there are 16 values in each one). This is my code:
```
FortyMinute.find().sort(['Rank', 1])
```
Anyone know how to get around this?
... | 2014/12/30 | [
"https://Stackoverflow.com/questions/27712101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4392607/"
] | You pass the arguments and values in **unpacked** as so:
```
FortyMinute.find().sort('Rank', 1)
```
---
It is only when you're passing **multiple sort parameters** that you group arguments and values using lists, and then too you must surround all your parameters with a tuple as so:
```
FortyMinute.find().sort([(R... | If you want mong/pymongo to sort:
```
FortyMinute.find().sort('Rank', 1)
```
If you want to sort using multiple fields:
```
FortyMinute.find().sort([('Rank': 1,), ('other', -1,)])
```
You also have constants to make it more clear what you're doing:
```
FortyMinute.find().sort('Rank',pymongo.DESCENDING)
```
If ... | 7,239 |
50,208,381 | I'm experimenting with developing python flask app, and would like to configure the app to apache as a daemon, so I wouldn't need to restart apache after every change. The configuration is now like [instructed here](https://code.google.com/archive/p/modwsgi/wikis/QuickConfigurationGuide.wiki#Mounting_At_Root_Of_Site%20... | 2018/05/07 | [
"https://Stackoverflow.com/questions/50208381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364931/"
] | You can use `sapply` or `lapply` to accomplish it .
```
#supposing your data.frame is called 'df'
sapply(df, unique)
#$x1
#[1] 1 2 3 4 6 7 8
#
#$x2
#[1] 2 5 7 8 9 0
#
#$x3
#[1] 6 5 1 2 3 4
```
or
```
lapply(df, unique)
#$x1
#[1] 1 2 3 4 6 7 8
#
#$x2
#[1] 2 5 7 8 9 0
#
#$x3
#[1] 6 5 1 2 3 4
``` | ```
# Imagine D is your data.frame object
apply(D,1, function(x) rle(x)$values)
``` | 7,240 |
56,034,831 | I am using Keras with `fit_generator()`. My generator connects to a Database (MongoDB in my case) to fetch data for each batch. If I use the multiprocessing flag of `fit_generator()` I get this Warning:
```
UserWarning: MongoClient opened before fork. Create MongoClient only after forking.
```
I am connecting to the... | 2019/05/08 | [
"https://Stackoverflow.com/questions/56034831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3531894/"
] | I don't have a mongo DB to test on but this might work - you can get the collection (connection?) on the first get-item of each process.
```py
class MyCustomGenerator(tf.keras.utils.Sequence):
def __init__(self, ...):
self.collection = None
def __len__(self):
...
def __getitem__(self, idx... | if you're using Python 3.7 you could use [os.register\_at\_fork](https://docs.python.org/3/library/os.html#os.register_at_fork) to trigger creating the database connection
for example you could do something like:
```
from os import register_at_fork
def reinit_dbcon():
generator_obj.collection = MagicMongoDBConne... | 7,243 |
13,927,122 | Trying to get this line of code to work, I keep running into issues no matter how I change the formatting around:
```
if not os.path.exists(os.path.join(IncludeSettings.FILE_URL, [str(x) for x in [year, month, day]])):
```
(year, month, day) can be either ints or strings.
Traceback:
```
Traceback (most recent cal... | 2012/12/18 | [
"https://Stackoverflow.com/questions/13927122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1247832/"
] | You are missing the '\*' here:
```
>>> os.path.join('foo', *['a','b'])
'foo/a/b'
```
You have to use the star operator here in order to pass the list items as unpacked variable argument list to the method. | add \* before `[str(x) for x in [year, month, day]]`
`*[str(x) for x in [year, month, day]]` | 7,244 |
36,637,428 | Strange error from numpy via matplotlib when trying to get a histogram of a tiny toy dataset. I'm just not sure how to interpret the error, which makes it hard to see what to do next.
Didn't find much related, though [this nltk question](https://stackoverflow.com/questions/35013726/typeerror-ufunc-add-did-not-contain-... | 2016/04/15 | [
"https://Stackoverflow.com/questions/36637428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201350/"
] | I got the same error, but in my case I am subtracting dict.key from dict.value. I have fixed this by subtracting dict.value for corresponding key from other dict.value.
```
cosine_sim = cosine_similarity(e_b-e_a, w-e_c)
```
here I got error because e\_b, e\_a and e\_c are embedding vector for word a,b,c respectively... | I ran into the same issue, but in my case it was just a Python list instead of a Numpy array used. Using two Numpy arrays solved the issue for me. | 7,249 |
18,624,148 | I'm struggling to find documentation on what the ^ does in python.
EX.
>
>
> >
> >
> > >
> > > 6^1 =
> > > 7
> > >
> > >
> > > 6^2 =
> > > 4
> > >
> > >
> > > 6^3 =
> > > 5
> > >
> > >
> > > 6^4 =
> > > 2
> > >
> > >
> > > 6^5 =
> > > 3
> > >
> > >
> > > 6^6 =
> > > 0
> > >
> > >
> > >
> >
> ... | 2013/09/04 | [
"https://Stackoverflow.com/questions/18624148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2748552/"
] | It is the [bitwise exclusive-or operator](https://en.wikipedia.org/wiki/Xor#Bitwise_operation), often called "xor". For each pair of corresponding bits in the operands, the corresponding bit in the result is 0 if the operand bits are the same, 1 if they are different.
Consider `6^4`:
```
6 = 0b0110
4 = 0b0100
6^4... | for more information on XOR , please react the documentation on Python.org at here:
<http://docs.python.org/2/library/operator.html> | 7,259 |
38,943,673 | I am new to python and I am working on a project that needs to write a dictionary into a text file. The format is like:
```
{'17': [('25', 5), ('23', 3)], '12': [('28', 3), ('22', 3)], '13': [('28', 3), ('23', 3)], '16': [('22', 3), ('21', 3)], '11': [('28', 3), ('29', 1)], '14': [('22', 3), ('23', 3)], '15': [('26',... | 2016/08/14 | [
"https://Stackoverflow.com/questions/38943673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6715128/"
] | You can achieve this using separate routes, or change your parameters to be optional.
When using 3 attributes, you add separate routes for each of the options that you have - when no parameters are specified, when only `movieId` is specified, and when all 3 parameters are specified.
```
[Route("Everything/MovieCustom... | >
> Keep in mind that neither sample supports the case where you provide only customerId.
>
>
>
Check it out. I think you can use the multiple route method with EVEN ANOTHER route like this if you do want to provide only customerId:
```
[Route("Everything/MovieCustomer/null/{customerId}")]
``` | 7,260 |
47,117,625 | I want to split any matrix (most likely will be a 3x4) into two. One part will be the left hand and then the right hand - only the last column.
```
[[1,0,0,4], [[1,0,0], [4,
[1,0,0,2], ---> A= [1,0,0], B = 2,
[4,3,1,6]] [4,3,1]] 6]
```
Is there a way to do this in ... | 2017/11/05 | [
"https://Stackoverflow.com/questions/47117625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8606331/"
] | Yes, you could do like this:
```
def split_last_col(mat):
"""returns a tuple of two matrices corresponding
to the Left and Right parts"""
A = [line[:-1] for line in mat]
B = [line[-1] for line in mat]
return A, B
split_last_col([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
```
### output:
```
([[1, 2], [... | You could create A and B manually, like this:
```
def split(matrix):
a = list()
b = list()
for row in matrix:
row_length = len(row)
a_row = list()
for index, col in enumerate(row):
if index == row_length - 1:
b.append(col)
else:
a_row.append(col)
a.append(a_row)
re... | 7,262 |
59,363,950 | I'm trying to get started with Tensorflow-Hub to extract feature vectors from images. However, I'm not sure how one is meant to convert Tensorflow-Hub outputs (Tensors) to numpy vectors. Here's a simple example:
```
from keras.preprocessing.image import load_img
import tensorflow_hub as hub
import tensorflow as tf
imp... | 2019/12/16 | [
"https://Stackoverflow.com/questions/59363950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1727392/"
] | The following should work. But I did not check if the output is meaningful. But it is returning consistent results over multiple runs.
```
im = load_img('sample.png')
im = np.expand_dims(im.resize((299,299)), 0)
module = hub.Module("https://tfhub.dev/google/imagenet/inception_v3/feature_vector/1")
out = module(im)
... | You can use
```py
out.numpy()
type(out)
# <class 'tensorflow.python.framework.ops.EagerTensor'>
type(out.numpy()
# <class 'numpy.ndarray'>
``` | 7,263 |
44,805,535 | I am an anaconda user and Jupyter is a neat tool to run python code. However, for my macbook, I can't open it in Chrome (This page isn’t working
localhost didn’t send any data.),but it works in Safari, I have tried to reinstall chrome, but I still can't fix it. My system is Mac OS 10.11.5.
Who knows how I can fix it?
... | 2017/06/28 | [
"https://Stackoverflow.com/questions/44805535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3013618/"
] | You could change your approach to avoid fixed padding values:
```css
#secondary-menu {
background: #007dc5;
width: 80%;
}
ul#topnav {
list-style: none;
padding: 0;
height: 70px;
display: flex;
align-items: center;
justify-content: center;
}
ul#topnav li a {
text-transform: uppercase;
... | Add `overflow:hidden` to your `ul#topnav` rules:
```
ul#topnav {
list-style: none;
margin: 0 auto;
height: 70px;
display: flex;
align-items: center;
overflow:hidden;
}
```
```css
#secondary-menu {
background: #007dc5;
width: 80%;
}
ul#topnav {
list-style: none;
margin: 0 auto;
height: 7... | 7,264 |
54,411,732 | So far I'm able to print at the end if the user selects 'n' to not order another hard drive, but need to write to a file. I've tried running the code as 'python hdorders.py >> orders.txt', but it won't prompt for the questions; only shows a blank line and if I break out using Ctrl-C, it writes blank entries and while l... | 2019/01/28 | [
"https://Stackoverflow.com/questions/54411732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9638138/"
] | No. One team project has one process template. You can customize that process template however you wish, of course. | What you could do is create an inherited process in order to make your customizations, and change every Team Project to that Process.
You have to take into account that the customizations you have made to your Team Project could be affected when you change to a inherited process.
Test carefully with some test Team Pr... | 7,265 |
35,719,165 | I have a python program with one main thread and let's say 2 other threads (or maybe even more, probably doesn't matter). I would like to let the main thread sleep until ONE of the other threads is finished. It's easy to do with polling (by calling t.join(1) and waiting for one second for every thread t).
Is it possi... | 2016/03/01 | [
"https://Stackoverflow.com/questions/35719165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2384856/"
] | Here is an example of using condition object.
```
from threading import Thread, Condition, Lock
from time import sleep
from random import random
_lock = Lock()
def run(idx, condition):
sleep(random() * 3)
print('thread_%d is waiting for notifying main thread.' % idx)
_lock.acquire()
with condition:
... | You can create a Thread Class and the main thread keeps a reference to it. So you can check whether the thread has finished and make your main thread continue again easily.
If that doesn't helped you, I suggest you to look at the **Queue** library!
```
import threading
import time, random
#THREAD CLASS#
class Thread... | 7,266 |
35,667,252 | I have installed the python 3.5 interpretor in my device (Windows).
Can anybody guide me through the process of using packages to run it like `SublimeREPL`? | 2016/02/27 | [
"https://Stackoverflow.com/questions/35667252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5987890/"
] | Yes, you can use any Python version you want to run programs from Sublime - you just need to define a new [build system](http://sublimetext.info/docs/en/reference/build_systems.html). Select **`Tools -> Build System -> New Build System`**, then delete its contents and replace it with:
```js
{
"cmd": ["C:/Python35/... | if you have installed python3 and SublimeREPL, you can try setting up key bindings with the correct path to the python3 file.
```
[
{
"keys":["super+ctrl+r"],
"command": "repl_open",
"caption": "Python 3.6 - Open File",
"id": "repl_python",
... | 7,269 |
36,142,393 | In the terminal, after I enter the python interpreter I use `help('modules')` to see which modules are installed but Numpy, matplotlib and scipy are not listed.
When I try to import them, I get the following:
>
> ImportError: no module named xxx.
>
>
>
However, when I try to install these modules using `apt-get... | 2016/03/21 | [
"https://Stackoverflow.com/questions/36142393",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5255941/"
] | You have a typo in the iframe rule - that might be the cause, since the absolute positioning won't work as expected:
```
iframe{
...
possition: absolute; ---> must be "position"
}
``` | You have position spelled wrong in your CSS. | 7,270 |
58,724,581 | Below is my playbook which has a variable `running_processes` which contains a list of pids(one or more)
Next, I read the user ids for each of the pids. All good so far.
I then try to print the list of user ids in `curr_user_ids` variable using `-debug module` is when i get the error: 'dict object' has no attribute '... | 2019/11/06 | [
"https://Stackoverflow.com/questions/58724581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11143113/"
] | Few points to note why your solution didn't work.
The task `Get running processes list from remote host` returns a newline splitted `\n` string. So you will need to process this and turn the output into a propper list object first.
The task `Gather USER IDs from processes id before killing.` is returning a dictionary... | The variable *curr\_user\_ids* registers results of each iteration
```
register: curr_user_ids
with_items: "{{ running_processes.stdout_lines }}"
```
The list of the results is stored in
```
curr_user_ids.results
```
Take a look at the variable
```
- debug:
var: curr_user_ids
```
and loop the stdout\_lines... | 7,271 |
29,634,019 | I'm not sure what I'm doing wrong here, and am hoping someone else has the same problem. I don't get any error, and my json matches what should be correct both on Jira's docs and jira-python questions online. My versions are valid Jira versions. I also have no problem doing this directly through the API, but we are re-... | 2015/04/14 | [
"https://Stackoverflow.com/questions/29634019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797963/"
] | Here's a code example of how I got it working for anyone who comes across this later...
```
fixVersions = []
issue = jira.issue('issue_key')
for version in issue.fields.fixVersions:
if version.name != 'version_to_remove':
fixVersions.append({'name': version.name})
fixVersions.append... | I did it other way:
1. Create version in the target project.
2. Update ticket.
ver = jira.create\_version(name='version\_name', project='PROJECT\_NAME')
issue = jira.issue('ISSUE\_NUM')
i.update(fields={'fixVersions': [{'name': ver.name}]})}
In my case that worked. | 7,272 |
16,209,640 | Here is strange issue I'm facing with wxpython on Mac. Though this works completely fine with wxpython on Windows7. I'm trying to update wx.StaticText label before and after time.sleep() like this:
```
self.lblStatus = wx.StaticText(self, label="", pos=(180, 80))
self.lblStatus.SetLabel("Processing....")
time.sleep(10... | 2013/04/25 | [
"https://Stackoverflow.com/questions/16209640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1324914/"
] | I have never seen time.sleep() NOT block the GUI on Windows. The sleep function blocks wx's main loop, plain and simple. As JHolta mentioned, you can put the sleep into a thread and update the GUI from there, assuming you use a threadsafe method, such as wx.CallAfter, wx.CallLater or wx.PostEvent.
But if you just want... | The wxPython gui is a loop, to make a part of the code sleep without causing the gui to sleep one would need to multithread.
I would write a function that calls a threaded function, now this is a dirty example but should show you what needs to be done:
```
import wx
from threading import Thread
import time
from wx.li... | 7,275 |
39,024,816 | ```
#####################################
# Portscan TCP #
# #
#####################################
# -*- coding: utf-8 -*-
#!/usr/bin/python3
import socket
ip = input("Digite o IP ou endereco: ")
ports = []
count = 0
while count < 10:
ports.append(int(input("Digite a porta: ")))
count += 1
for por... | 2016/08/18 | [
"https://Stackoverflow.com/questions/39024816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6693417/"
] | As @Upsampled mentioned, you might use raw sockets (<https://en.wikipedia.org/>) as you only need a subset of TCP protocol (send **SYN** and recieve **RST-ACK** or **SYN-ACK**
).
As coding something like <http://www.binarytides.com/raw-socket-programming-in-python-linux/>
could be a good excersice, I would also sugges... | First, you will have to generate your own SYN packets using RAW sockets. You can find an example [here](http://www.binarytides.com/raw-socket-programming-in-python-linux/)
Second, you will need to listen for SYN-ACKs from the scanned host in order to determine which ports actually try to start the TCP Handshake (SYN,S... | 7,276 |
59,159,462 | I want to find the largest value in a JSON file, using python (so it would be a dictionary).
My JSON has this shape:
```
[{
"probability": 0.623514056,
"boundingBox": { "left": 36, "top": 1, "width": 403, "height": 95 }
},
{
"probability": 0.850905955,
"boundingBox": { "left": 42, "top": 200, "width": 412, "he... | 2019/12/03 | [
"https://Stackoverflow.com/questions/59159462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11476888/"
] | The cleanest solution is probably:
```
widths = [d['boundingBox']['width'] for d in json_file]
min_value = min(widths)
max_value = max(widths)
```
However, `min` and `max` just use loops under the hood, which you mentioned may be slow. Test the above solution first, and if that is too slow for your needs, you can co... | That's fairly easy to do:
```
max_width = max(d["boundingBox"]["width"] for d in dicts)
min_width = min(d["boundingBox"]["height"] for d in dicts)
``` | 7,277 |
25,060,752 | Okay I got a file container that is a product of a Webcrawler containing a lot of different file types, likely but not all are HTML XML JPG PNG PDF. Most of the container is HTML text so I tried to open it with:
```
with open(fname) as f:
content = f.readlines()
```
which basically fails when I hit a PDF. The fi... | 2014/07/31 | [
"https://Stackoverflow.com/questions/25060752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3749379/"
] | You can [retrieve changes](http://msdn.microsoft.com/en-us/library/thc1eetk.aspx) in a `DataTable` using `GetChanges`.
So you can use this code with a `DataGridView`:
```
CType(YourDataGridView.DataSource, DataTable).GetChanges(DataRowState.Modified).Rows
``` | I have come up with a working solution in C# where I account for a user editing the current cell then performing a Save/Update without moving out of the edited row. The call to `GetChanges()` won't recognize the current edited row due to its `RowState` still being marked as "`Unchanged`". I also make a call to move to ... | 7,280 |
13,452,761 | i have a table with add/remove buttons, those buttons add and remove rows from the table, the buttons are also added with each new row
here what i have as html
```
<table>
<tr>
<th>catalogue</th>
<th>date</th>
<th>add</th>
<th>remove</th>
</tr>
<- target row ->
<tr id="cat_row">
<td>something</td>
<... | 2012/11/19 | [
"https://Stackoverflow.com/questions/13452761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/747201/"
] | **SOLVED**
Because my service was running in separate process i had to add this flag when accesing shared preference
```
private final static int PREFERENCES_MODE = Context.MODE_MULTI_PROCESS;
```
and change like this
```
sharedPrefs = this.getSharedPreferences("preference name", PREFERENCES_MODE);
``` | Ensure you write your data to shared preferences correctly, specifically you `commit()` your changes, [as docs say](http://developer.android.com/reference/android/content/SharedPreferences.Editor.html):
>
> All changes you make in an editor are batched, and not copied back to
> the original SharedPreferences until y... | 7,283 |
16,844,182 | This is my first time delving into web development in python. My only other experience is PHP, and I never used a framework before, so I'm finding this very intimidating and confusing.
I'm interested in learning CherryPy/Jinja2 to make a ZFS Monitor for my NAS. I've read through the basics of the docs on CherryPy/Jinj... | 2013/05/30 | [
"https://Stackoverflow.com/questions/16844182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2437919/"
] | Congratulations on choosing Python, I'm sure you'll learn to love it as have I.
Regarding CherryPy, I'm not an expert, but was also in the same boat as you a few days ago and I'd agree that the tutorials are a little disjointed in parts.
For integrating Jinja2, as in their [doc page](http://docs.cherrypy.org/stable/p... | Application structure
=====================
First about standard directory structure of a project. There is none, as CherryPy doesn't mandate it, neither it tells you what data layer, form validation or template engine to use. It's all up to you and your requirements. And of course as this is a great flexibility as it... | 7,285 |
39,971,929 | Python 3.6 is about to be released. [PEP 494 -- Python 3.6 Release Schedule](https://www.python.org/dev/peps/pep-0494/) mentions the end of December, so I went through [What's New in Python 3.6](https://docs.python.org/3.6/whatsnew/3.6.html) to see they mention the *variable annotations*:
>
> [PEP 484](https://www.py... | 2016/10/11 | [
"https://Stackoverflow.com/questions/39971929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983854/"
] | Everything between `:` and the `=` is a type hint, so `primes` is indeed defined as `List[int]`, and initially set to an empty list (and `stats` is an empty dictionary initially, defined as `Dict[str, int]`).
`List[int]` and `Dict[str, int]` are not part of the next syntax however, these were already defined in the Py... | >
> *What are variable annotations?*
>
>
>
Variable annotations are just the next step from `# type` comments, as they were defined in `PEP 484`; the rationale behind this change is highlighted in the [respective section of PEP 526](https://www.python.org/dev/peps/pep-0526/#rationale).
So, instead of hinting the... | 7,286 |
6,943,172 | What does the [] mean?
Also how can I identify variables as empty arrays in python?
Thanks!
```
perl: xcoords = ()
```
How do I translate that? | 2011/08/04 | [
"https://Stackoverflow.com/questions/6943172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | [] - is an empty list in Python and is the same as calling list() e.g. [] == list()
To check that list is empty you can use len(l) or:
```
listV = [] # an empty list
if listV:
# do something if list is not empty
else:
# do something if list is really empty
```
To read more about list you can use [the followi... | Lists are like C++ arrays with some difference. One of difference is they can cary different types even lists. to check if lists is empty
```
lists = []
len(lists)
lists[0]= "More of me"
len(lists)
```
More check [Python official](http://docs.python.org/tutorial/introduction.html#lists) tutorial and above Docs | 7,287 |
62,763,634 | I currently have a dictionary that I have imported from a csv file, that I have converted into a list of variables. The original dictionary looks like this:
* server01, server01.fqdn:port
* server02, server02.fqdn:port
* server03, server03.fqdn:port
* server04, server04.fqdn:port
What I'd like to do is create another... | 2020/07/06 | [
"https://Stackoverflow.com/questions/62763634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13795713/"
] | The [`format`](https://trino.io/docs/current/functions/conversion.html#format) function accepts any of the Java [format string specifiers](https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax):
```
presto> select format('%.2f%%', 0.18932 * 100);
_col0
--------
18.93%
(1 row)
``` | For those of you who, like me, came here looking to round a `decimal` or `double` field down to `n` decimal places but didn't care about the `%` sign, you have a few other options than Martin's answer.
If you want the output to be type `double` then [`truncate(x,n)`](https://prestodb.io/docs/current/functions/math.htm... | 7,288 |
71,293,767 | I need to get the value from one element using several others as filters using Selenium on a dynamic website ([LogTrail](https://github.com/sivasamyk/logtrail) using [Kibana](https://en.wikipedia.org/wiki/Kibana)).
I got this:
```python
from selenium import webdriver
import time
from selenium.webdriver.common.keys im... | 2022/02/28 | [
"https://Stackoverflow.com/questions/71293767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17914605/"
] | Given a dataframe with a `DatetimeIndex` which doesn't have any missing days like this
```
df = pd.DataFrame(
{"A": range(500)}, index=pd.date_range("2022-03-01", periods=500, freq="1D")
)
A
2022-03-01 0
2022-03-02 1
... ...
2023-07-12 498
2023-07-13 499
```
you could do the follow... | We can use [`relativedelta`](https://dateutil.readthedocs.io/en/stable/relativedelta.html), [`pandas.to_datetime`](https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html) and [`pandas.DataFrame.apply`](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.apply.html).
```
from dateutil.relativede... | 7,289 |
15,136,456 | I want to parse dxf file for obtain objects (line, point, text and so on) with dxfgrabber library.
The code is as below
```
#!/usr/bin/env python
import dxfgrabber
dxf = dxfgrabber.readfile("1.dxf")
print ("DXF version : {}".format(dxf.dxfversion))
```
But it gets some error...
```
Traceback (most recent call las... | 2013/02/28 | [
"https://Stackoverflow.com/questions/15136456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1761178/"
] | I contacted the developer and he says that in current version 0.5.1 make line 49 of `__init__.py` the following: `with io.open(filename) as fp:`.
Then it works (`io` was missing).
He will make this correction official in version 0.5.2 soon. | You can only read dxf made in AutoCAD format!
Try "DraftSight" which is a free AutoCAD clone which exports dxf quite well. Try dxf R12 format.
This will solve your problems. | 7,290 |
35,737,178 | Thanks in advance for the help.
I'm relatively new to python and am trying to write a python script to load partial csv files from 1000 files. For example, I have 1000 files that have this format
```
x,y
1,2
2,4
2,2
3,9
...
```
I would like to load only lines, for example, where `x=2`. I've seen a lot of posts on h... | 2016/03/02 | [
"https://Stackoverflow.com/questions/35737178",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2736423/"
] | Try [pandas](https://github.com/pydata/pandas) library. It has an interoperability with numpy and way more flexible. With this library you do next thing:
```py
data = pandas.read_csv('file.csv')
# keep only rows with x equals to 2
data = data[data['x'] == 2]
# convert to numpy array
arr = numpy.asarray(data)
```
Yo... | The csv library comes with python and it allows for partial reading of a file.
```
import csv
def partial_load(filename):
ds = []
c = csv.reader( open(filename) )
legend = next( c )
for row in c:
row = [float(r) for r in row]
if len(row) > 0:
if row[0] > 2:
... | 7,291 |
17,406,453 | I have started a month ago with GAE and have successfully deployed our current startup via Flask on GAE. It works fantastically well. Now being all too exited about GAE, I am thinking about porting a couple of my older Django apps on GAE as well.
To my surprise the documentation of it is surprisingly inconsistent and ... | 2013/07/01 | [
"https://Stackoverflow.com/questions/17406453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/92153/"
] | you can easily use `@request.getHeader("referer")` in your Templates, for example if you have a cancel button that should redirect you to the previous page, use this :
```
<a href="@request.getHeader("referer")">Cancel</a>
```
in this way, you don't need to pass any extra information to your templates. (tested with... | This is what I came up with in the end, although it isn't particularly elegant, and I'd be interested in better ways of doing it. I added a hidden input to my form with the current page URL:
```
@(implicit request: RequestHeader)
...
<form action="@routes.Controller.doStuff()" method="post">
<input type="hidden" n... | 7,292 |
43,852,802 | Python 3.6
I have a program that is generating a list of dictionaries.
If I print it to the screen with:
```
print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
```
It prints out exactly as I want to see it:
```
[
{
"runts": 0,
"giants": 0,
"throttles": 0,
... | 2017/05/08 | [
"https://Stackoverflow.com/questions/43852802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7535419/"
] | I think all you need is `json.dump` with `indent` and it should be fine:
```
outputfile = ("d:\\mark\\python\\Projects\\error_detect\\" + hostname)
# print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
# output_lines.append(json.dumps(output_lines, indent=4, separators=(',', ': ')))
# del output_lines[-1... | Try simply outputting the formatted `json.dumps`, rather than running it through `json.dump` again.
```
with open(outputfile, 'w') as f:
f.write(output_lines)
``` | 7,295 |
8,461,306 | I'm tracking a linux filesystem (that could be any type) with pyinotify module for python (which is actually the linux kernel behind doing the job). Many directories/folders/files (as much as the user want to) are being tracked with my application and now i would like track the md5sum of each file and store them on a d... | 2011/12/11 | [
"https://Stackoverflow.com/questions/8461306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952870/"
] | You could use this:
```
string q = Regex.Replace(query, @"[:#/\\]", ".");
q = Regex.Replace(q, @""|['"",&?%\.*-]", " ");
```
EDIT:
=====
On closer inspection of what you're doing, your code is translating several characters into `.`, and *then* translating all `.` into spaces. So you could just do this:
```
s... | Try this.
```
string pattern = @"[^a-zA-Z0-9]";
string test = Regex.Replace("abc*&34567*opdldld(aododod';", pattern, " ");
``` | 7,298 |
11,191,946 | I have spent many hours trying to build RDKit on ubuntu 11.10 for
Python 2.7 (rdkit\_201106+dfsg.orig.tar.gz) using a precompiled version
of boost 1.49. And I am failing miserably.
The recurring error is in the CMake GUI:
```
CMake Error at CMakeLists.txt:11 (install):
install FILES given no DESTINATION!
CMake... | 2012/06/25 | [
"https://Stackoverflow.com/questions/11191946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395874/"
] | make sure you have the environment variables set:
(you might need to fix the paths with what you have): using bash on mac:
```
export RDBASE=/usr/local/share/RDKit
export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages
```
you might want to add those lines to a bash script to automate the process. | For Ubuntu 12.04.2 LTS setting this environment variables works for me
```
export RDBASE=/usr/share/RDKit
export PYTHONPATH=$PYTHONPATH:/usr/lib/pymodules/python2.7
``` | 7,299 |
6,966,205 | I want to convert some base64 encoded png images to jpg using python. I know how to decode from base64 back to raw:
```
import base64
pngraw = base64.decodestring(png_b64text)
```
but how can I convert this now to jpg? Just writing pngraw to a file obviously only gives me a png file. **I know I can use PIL, but HOW... | 2011/08/06 | [
"https://Stackoverflow.com/questions/6966205",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/561766/"
] | You can use [PIL](http://www.pythonware.com/products/pil/):
```
data = b'''iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0NAAAAAXNSR0IArs4c6QAAAIBJRE
FUOMvN08ENgCAMheG/TGniEo7iEiZuqTeiUkoLHORK++Ul8ODPZ92XS2ZiADITmwI+sWHwi
w2BGtYN1jCAZF1GMYDkGfJix3ZK8g57sJywteTFClBbjmAq+ESiGIBEX9nCqgl7sfyxIykt
... | Right from the PIL tutorial:
>
> To save a file, use the save method of the Image class. When saving files, the name becomes important. Unless you specify the format, the library uses the filename extension to discover which file storage format to use.
>
>
>
Convert files to JPEG
---------------------
```
import... | 7,300 |
48,504,746 | I am trying to add a **GUI** input box and I found out that the way you do that is by using a module called `tkinter`. While I was trying to install it on my arch linux machine through the `ActivePython` package I got the following error:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ... | 2018/01/29 | [
"https://Stackoverflow.com/questions/48504746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9219560/"
] | All you need to do is to install the tkinter package. Now universal precompiled packages such as ActivePython will not work, well at least it didn't work for me. I don't know if this problem occurs in other OSes but I know the solution for Linux: Install the Tk package from the terminal.
In Arch, Tk is available in th... | I'm on Manjaro, use Gnome3 on Wayland. After installed `tk` I got an error about Xorg. So I use Google, and found I need to install `python-pygubu` from [Visual editor for creating GUI in Python 3 tkinter](https://bbs.archlinux.org/viewtopic.php?id=221077).
And then another error like: [Gtk-WARNING \*\*: Unable to loc... | 7,301 |
58,702,300 | I have python script for SharePoint login (using python office365-rest-python-client) and download a file. I would like to convert script to executable file so i can share it with non-technical people. Python code run fine but when i convert it to exe using Pyinstaller and try to run, it gives me FileNotFoundError.
I ... | 2019/11/04 | [
"https://Stackoverflow.com/questions/58702300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10777463/"
] | Create a copy of `SAML.xml` (in my test case, right next to my python script `test0.py`); you can copy/paste from [this page](https://raw.githubusercontent.com/vgrem/Office365-REST-Python-Client/master/office365/runtime/auth/providers/templates/SAML.xml). Then run:
```
pyinstaller --onefile --add-data "SAML.xml;office... | The `_MEI66362` folder is created when you execute a `Pyinstaller` created `.exe`. It will contain everything that `Pyinstaller` determined is needed by your application. However, it cannot deduce every file that your app needs. In some cases, you must tell `Pyinstaller` about needed resources. You can use the `-add-da... | 7,306 |
62,054,092 | I have looked [here](https://stackoverflow.com/questions/1475123/easiest-way-to-turn-a-list-into-an-html-table-in-python) but the solution is still not working out for me...
I have `2 lists`
```py
list1 = ['src_table', 'error_response_code', 'error_count', 'max_dt']
list2 = ['src_periods_43200', 404, 21, datetime.dat... | 2020/05/27 | [
"https://Stackoverflow.com/questions/62054092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3107664/"
] | This Should do it
```
import pandas as pd
import datetime
list1 = ['src_table', 'error_response_code', 'error_count', 'max_dt']
list2 = [
'src_periods_43200', 404, 21, datetime.datetime(2020, 5, 26, 21, 10, 7),
'src_periods_86400', 404, 19, datetime.datetime(2020, 5, 25, 21, 10, 7)
]
index_break = len(list1... | You can easily write your function for that
Something like:
```py
import datetime
list1 = ['src_table', 'error_response_code', 'error_count', 'max_dt']
list2 = ['src_periods_43200', 404, 21, datetime.datetime(2020, 5, 26, 21, 10, 7), 'src_periods_86400', 404, 19, datetime.datetime(2020, 5, 25, 21, 10, 7)]
print('<t... | 7,307 |
48,529,567 | This is my code:
```
while True:
chosenUser = raw_input("Enter a username: ")
with open("userDetails.txt", "r") as userDetailsFile:
for line in userDetailsFile:
if chosenUser in line:
print "\n"
print chosenUser, "has taken previous tests. "
... | 2018/01/30 | [
"https://Stackoverflow.com/questions/48529567",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9244343/"
] | As others have noted, the primary problem is that the `break` only breaks from the inner `for` loop, not from the outer `while` loop, which can be fixed using e.g. a boolean variable or `return`.
But unless you want the "not registered" line to be printed for *every* line that does not contain the user's name, you sho... | The easiest way to work around this is to make the outer `while` alterable by using a boolean variable, and toggling it:
```
loop = True
while loop:
for x in y:
if exit_condition:
loop = False
break
```
That way you can stop the outer loop from within an inner one. | 7,308 |
1,465,036 | I have a shell that runs CentOS.
For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4.
From what I've read, a number of things will break if you upgrade to 2.5.
I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred ... | 2009/09/23 | [
"https://Stackoverflow.com/questions/1465036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/168500/"
] | ```
# yum groupinstall "Development tools"
# yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel
```
**Download and install Python 3.3.0**
```
# wget http://python.org/ftp/python/3.3.0/Python-3.3.0.tar.bz2
# tar xf Python-3.3.0.tar.bz2
# cd Python-3.3.0
# ./configure -... | I unistalled the original version of python (2.6.6) and install 2.7(with option `make && make altinstall`) but when I tried install something with yum didn't work.
So I solved this issue as follow:
1. `# ln -s /usr/local/bin/python /usr/bin/python`
2. Download the RPM package python-2.6.6-36.el6.i686.rpm from <http:/... | 7,310 |
71,036,475 | There
<https://www.amazon.de/sp?marketplaceID=A1PA6795UKMFR9&seller=A135E02VGPPVQ&isAmazonFulfilled=1&ref=dp_merchant_link>
I just can access on browser as well, but python requests returns 404 error status.
Until yesterday, this page worked as well with python requests. but from today, it does not work for me and i... | 2022/02/08 | [
"https://Stackoverflow.com/questions/71036475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | It works just fine to me. Maybe you can try changing your user agent.
```
import requests
from fake_useragent import UserAgent # fake user agent library
# random user-agent
ua = UserAgent()
user_agent = ua.random
headers = {
'Connection': 'keep-alive',
'rtt': '300',
'downlink': '0.4',
'ect': '3g',
... | I suggest you add a **referer url in header** and generally I don't think Amazon allow scraping but use selenium if you want to scrape it easily (sure it may be overkill) but has more customization | 7,320 |
67,464,761 | I am using python flask framework to develop Apis. I am planning to use mongodb as backend database. How can I connect mongodb database to python? Is there any in built in library? | 2021/05/10 | [
"https://Stackoverflow.com/questions/67464761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15882833/"
] | You almost there. It is better to keep control over appearance/disappearance inside menu view. Find below fixed parts, places are highlighted with comments in code.
Tested with Xcode 12.5 / iOS 14.5
*Note: demo prepared with turned on "Simulator > Debug > Slow Animations" for better visibility*
[
Declare ContentView and MenuView in SceneDelegate:
```
import KYDrawerController
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
let drawerController = KYDrawerController(drawerDir... | 7,321 |
12,816,464 | I am using web.py framework to create a simple web application
I want to create a radio button so I wrote the following code
```
from web import form
from web.contrib.auth import DBAuth
import MySQLdb as mdb
render = web.template.render('templates/')
urls = (
'/project_details', 'Project_Details',
)
class Pro... | 2012/10/10 | [
"https://Stackoverflow.com/questions/12816464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1342109/"
] | Looking at the [source](https://github.com/webpy/webpy/blob/master/web/form.py#L291), it looks like you have to use one `Radio` constructor for all of your items as the same `Radio` object will actually generate multiple `<input>` elements.
Try something like::
```
project_details = form.Form(
form.Radio('detail... | Here's what I was able to decipher. checked='checked' seems to select a random (last?) item in the list. Without a default selection, my testing was coming back with a NoneType, if none of the radio-buttons got selected.
```
project_details = form.Form(
form.Radio('selections', ['Home Page', 'Content', 'Contact Us',... | 7,322 |
30,226,891 | I am new at both, python and stackoverflow, so please have that on mind. I tried to do this myself and manage to do it, but it works only if i hardcode hash number of previous version like this one in hash1, and then compare with hash number of currently version. I wolud like that program every time save hash number of... | 2015/05/13 | [
"https://Stackoverflow.com/questions/30226891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4897764/"
] | Just simply save the hash to a file like file.txt and then when you need to compare a hash just read from your file.txt and compare the two strings.
Here is an example of how to read and write to files in python.
<http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python> | For relatively simple comparisons, use [filecmp](https://docs.python.org/2/library/filecmp.html). For finer control and feedback, use [difflib](https://docs.python.org/2/library/difflib.html#module-difflib), which is similar to the \*nix utility, `diff`. | 7,323 |
62,776,024 | I simply want to reorder the rows of my pandas dataframe such that `col1` matches the order of the external list elements in `my_order`.
```
d = {'col1': ['A', 'B', 'C'], 'col2': [1,2,3]}
df = pd.DataFrame(data=d)
my_order = ['B', 'C', 'A']
```
This post [sorting by a custom list in pandas](https://stackoverflow.com... | 2020/07/07 | [
"https://Stackoverflow.com/questions/62776024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7273115/"
] | ```
{{ json.Date.strftime('%Y-%m-%d') }}
``` | strftime converts a date object into a string by specifying a format you want to use
you can do
```
now = datetime.now() # <- datetime object
now_string = now.strftime('%d.%m.%Y')
```
however, if you already converted your datetime object into a string (or getting strings from an api or something), you can convert ... | 7,324 |
5,635,054 | I have a really large excel file and i need to delete about 20,000 rows, contingent on meeting a simple condition and excel won't let me delete such a complex range when using a filter. The condition is:
**If the first column contains the value, X, then I need to be able to delete the entire row.**
I'm trying to auto... | 2011/04/12 | [
"https://Stackoverflow.com/questions/5635054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704039/"
] | You can use,
```
sh.Range(sh.Cells(1,1),sh.Cells(20000,1)).EntireRow.Delete()
```
will delete rows 1 to 20,000 in an open Excel spreadsheet so,
```
if sh.Cells(1,1).Value == 'X':
sh.Cells(1,1).EntireRow.Delete()
``` | I have achieved this using Pandas package....
```
import pandas as pd
#Read from Excel
xl= pd.ExcelFile("test.xls")
#Parsing Excel Sheet to DataFrame
dfs = xl.parse(xl.sheet_names[0])
#Update DataFrame as per requirement
#(Here Removing the row from DataFrame having blank value in "Name" column)
dfs = dfs[dfs['Nam... | 7,325 |
74,245,242 | I want to perform the selection of a group of lines in a text file to get all jobs related to an ipref
The test file is like this :
job numbers : (1,2,3), ip ref : (10,12,10)
text file :
1
... (several lines of text)
xxx 10
2
... (several lines of text)
xxx 12
3
... (several lines of text)
xxx 10
i want to select job... | 2022/10/29 | [
"https://Stackoverflow.com/questions/74245242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20365230/"
] | You can write the pattern in this way, repeating the newline and asserting not xxx followed by 1 or more digits:
```
^\d(?:\n(?!xxx \d+$).*)*\nxxx 10$
```
The pattern matches:
* `^` Start of string
* `\d` Match a single digit (or `\d+` for 1 or more)
* `(?:` Non capture group
+ `\n` Match a newline
+ `(?!xxx \d+$... | Good day to you :) and Thank you very much for your quick response!!
i give you below the result
Note : i have modified re.DOTALL by re.DOTALL|re.MULTILINE (because the result is none without that... Sorry for the previous presentation ... it wat not very clear)
Text file :
```
1
a
b
xxx 10
1
a
b
xxx 12
1
a
b
xxx 10
... | 7,335 |
24,309,586 | This is similar to this [question](https://stackoverflow.com/questions/20403387/how-to-remove-a-package-from-pypi) with one exception. I want to remove a few specific versions of the package from our local pypi index, which I had uploaded with the following command in the past.
```
python setup.py sdist upload -r <ind... | 2014/06/19 | [
"https://Stackoverflow.com/questions/24309586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/251096/"
] | Removing packages from local pypi index **depends on type of pypi index you use**.
removing package from `devpi` index
===================================
`devpi` allows [removing packages](http://doc.devpi.net/latest/userman/devpi_packages.html#removing-a-release-file-or-project) only from so called volatile indexes... | I'm using [pypiserver](https://pypi.org/project/pypiserver/) and had to remove a bad package so I just SSH'd in and removed the bad packages and restarted the service.
The commands were roughly:
```
ssh root@pypiserver
cd ~pypiserver/pypiserver/packages
rm bad-package*
systemctl restart pypiserver.service
```
That ... | 7,340 |
17,321,910 | I have a file with a correspondence key -> value:
```
sort keyFile.txt | head
ENSMUSG00000000001 ENSMUSG00000000001_Gnai3
ENSMUSG00000000003 ENSMUSG00000000003_Pbsn
ENSMUSG00000000003 ENSMUSG00000000003_Pbsn
ENSMUSG00000000028 ENSMUSG00000000028_Cdc45
ENSMUSG00000000028 ENSMUSG00000000028_Cdc45
ENSMUSG00000000028... | 2013/06/26 | [
"https://Stackoverflow.com/questions/17321910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1274242/"
] | Use awk command like this:
```
awk 'NR==FNR {a[$1]=$2;next} {
split($1, b, ":");
if (b[1] in a)
print a[b[1]] ":" b[2], $2;
else
print $0;
}' keyFile.txt temp.txt
``` | Another awk option
```
awk -F: 'NR == FNR{split($0, a, " "); x[a[1]]=a[2]; next}{print x[$1]":"$2}' keyFile.txt temp.txt
``` | 7,342 |
34,994,130 | Looking through several projects recently, I noticed some of them use `platforms` argument to `setup()` in `setup.py`, though with only one value of `any`, i.e.
```
#setup.py file in project's package folder
...
setup(
...,
platforms=['any'],
...
)
```
OR
```
#setup.py file in project's packag... | 2016/01/25 | [
"https://Stackoverflow.com/questions/34994130",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5738152/"
] | `platforms` is an argument the `setuptools` package inherits from `distutils`; see the [*Additional meta-data* section](https://docs.python.org/2/distutils/setupscript.html#additional-meta-data) in the `distutils` documentation:
>
> *Meta-Data*: `platforms`
>
> *Description*: a list of platforms
>
> *Value*: li... | Just an update to provide more information for anyone interested.
I found an accurate description of `platforms` in a [PEP](https://www.python.org/dev/peps/pep-0345/#platform-multiple-use).
So, "*There's a PEP for that!*":
[PEP-0345](https://www.python.org/dev/peps/pep-0345/) lists all possible arguments to `setup... | 7,347 |
48,465,325 | I am trying to build my container image using docker\_image module of Ansible.
**My host machine details:**
```
OS: Lubuntu 17.10
ansible 2.4.2.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/home/myuser/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python modu... | 2018/01/26 | [
"https://Stackoverflow.com/questions/48465325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3592502/"
] | Your client (presumably) would not have Sequelize installed and cannot pass a Sequelize operator via JSON, so what you are trying to do is not exactly possible. You would probably to get the client to send string (e.g. `or`, `and` and then you would have to map those string to Sequelize operators) [1].
```
"filters":... | In the end I found out from the sequelize slack group that the old operator method is still in the codebase. I don't know how long it will stay, but since it is the only way of sending via json, it may well stay.
So the way it works is that rather than using [Op.or] you can use $or.
Example:
```
"filters": {"week": ... | 7,348 |
65,363,105 | I am using making use of some user\_types in my application which are is\_admin and is\_landlord. I want it that whenever a user is created using the `python manage.py createsuperuser`. he is automatically assigned is\_admin.
models.py
```
class UserManager(BaseUserManager):
def _create_user(self, email, passwor... | 2020/12/18 | [
"https://Stackoverflow.com/questions/65363105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14434294/"
] | You can automatically construct a `user_type` model in the `create_superuser` function:
```
class UserManager(BaseUserManager):
# …
def create_superuser(self, email, password, **extra_fields):
user = self._create_user(email, password, True, True, **extra_fields)
user.save(using=self._db)
... | So I have tried a method that works not so efficiently but manageably.
What I do is a simple trick.
views.py
```
def Dashboard(request, pk):
user = User.objects.get(id=request.user.pk)
landlord = user.is_staff & user.is_active
if not landlord:
reservations = Tables.objects.all()
... | 7,350 |
68,286,395 | I am trying to create a Toplevel window, however, this Toplevel is called from a different file in the same directory within a function.
Apologies I am by no means a tkinter or python guru. Here are the two parts of the code. (snippets)
#File 1 (Main)
```
import tkinter as tk
from tkinter import *
import comm1
from ... | 2021/07/07 | [
"https://Stackoverflow.com/questions/68286395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11911902/"
] | No, don't make it `static`. If you want you can make it an instance field, but making it a class field is not optimal. E.g. see the note on thread-safety on the `Random` class that it has been derived from:
>
> Instances of `java.util.Random` are threadsafe. However, the concurrent use of the same `java.util.Random` ... | I totally agree with Maartens's answer. However one can notice that java.util classes create statics for SecureRandom themselfes.
```
public final class UUID implements java.io.Serializable, Comparable<UUID> {
...
/*
* The random number generator used by this class to create random
* based UUIDs. I... | 7,351 |
63,306,561 | File/Directory Structure:
```
main/home/script.py
main/home/a/.init
main/home/b/.init
```
I want to setup my `gitignore` to exclude everything in the home directory but to include specific file types.
What i tried:
```
home/* #exclude everything in the home directory and subdirectories
!home/*.py #include py... | 2020/08/07 | [
"https://Stackoverflow.com/questions/63306561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | If you want to create, e.g., `home/foo/.init` and have this file be put into Git's *index* (for more about the index, see below), you will need to tell Git *not* to cut off searches into the `home/*/` directories:
```
!home/*/
```
Then, as [Fady Adal noted](https://stackoverflow.com/a/63306691/1256452) (but I've adj... | It should be
```
home/* #exclude everything in the home directory and subdirectories
!home/*.py #include python files immediately in the home directory
!**/*.init #include .init files in all directories and subdirectories.
``` | 7,352 |
58,187,677 | i've worked with tensorflow for a while and everything worked properly until i tried to switch to the gpu version.
Uninstalled previous tensorflow,
pip installed tensorflow-gpu (v2.0)
downloaded and installed visual studio community 2019
downloaded and installed CUDA 10.1
downloaded and installed cuDNN
tested with ... | 2019/10/01 | [
"https://Stackoverflow.com/questions/58187677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12149136/"
] | SOLVED, it's mostly an alchemy of versions to avoid conflicts.
Here's what i've done (order matters as far as i know)
1. uninstall everything (tf, cuda, visual studio)
2. pip install tensorflow-gpu
3. download and install visual studio community 2017 (2019 won't work)
4. I also have installed the c++ workload from vis... | tensorflow-gpu v2.0.0 is [now available on conda](https://anaconda.org/anaconda/tensorflow-gpu), and is very easy to install with:
`conda install -c anaconda tensorflow-gpu`. No additional downloads or cuda installs required. | 7,353 |
63,887,379 | I'm using **Visual Studio Code** with **Cloud Code** extension. When I try to "**Deploy to Cloud Run**", I'm having this error:
>
> Automatic image build detection failed. Error: Component map not
> found. Consider adding a Dockerfile to the workspace and try again.
>
>
>
But I already have a Dockerfile:
```
# P... | 2020/09/14 | [
"https://Stackoverflow.com/questions/63887379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5411494/"
] | I wasn't able to repro the issue, but I checked in with the Cloud Code team and it sounds like there could have been an underlying issue with gcloud that wasn't your fault.
I don't think you'll see this error again, but if you do, it would be awesome if you could file an issue at the [Cloud Code VS Code repo](https://... | I don't know why, but after connecting in a different network and running the commands below, the error is gone.
```
gcloud auth revoke
gcloud auth login
gcloud init
``` | 7,356 |
63,544,127 | I'm occasionally learning Java. As a person from python background, I'd like to know whether there exists something like `sorted(iterable, key=function)` of python in java.
For exmaple, in python I can sort a list ordered by an element's specific character, such as
```
>>> a_list = ['bob', 'kate', 'jaguar', 'mazda', ... | 2020/08/23 | [
"https://Stackoverflow.com/questions/63544127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11790764/"
] | Use a custom comparator to compare two strings.
```
Arrays.sort(a_list, Comparator.comparing(s -> s.charAt(1)));
```
This compares two strings by the string's second character.
This will result in
```
[kate, jaguar, mazda, civic, bob, honda, grasshopper]
```
I see that `jaguar` and `kate` are switched in your ou... | You can supply a lambda function to [`Arrays.sort`](https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort(T%5B%5D,%20java.util.Comparator)). For your example, you could use:
```
Arrays.sort(a_list, (String a, String b) -> a.charAt(1) - b.charAt(1));
```
Assuming you have first sorted the array alphabe... | 7,357 |
33,241,842 | I'm using TextBlob for python to do some sentiment analysis on tweets. The default analyzer in TextBlob is the PatternAnalyzer which works resonably well and is appreciably fast.
```
sent = TextBlob(tweet.decode('utf-8')).sentiment
```
I have now tried to switch to the NaiveBayesAnalyzer and found the runtime to be ... | 2015/10/20 | [
"https://Stackoverflow.com/questions/33241842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3174668/"
] | Yes, Textblob will train the analyzer before each run. You can use following code to avoid train the analyzer everytime.
```
from textblob import Blobber
from textblob.sentiments import NaiveBayesAnalyzer
tb = Blobber(analyzer=NaiveBayesAnalyzer())
print tb("sentence you want to test")
``` | Adding to Alan's very useful answer if you have table data in a dataframe and want to use textblob's NaiveBayesAnalyzer then this works. Just change out `word_list` for your relevant series of strings.
```
import textblob
import pandas as pd
tb = textblob.Blobber(analyzer=NaiveBayesAnalyzer())
for index, row in df.it... | 7,359 |
68,441,299 | I'm trying to get the number of commits of github repos using python and beautiful soup
html code:
```
<div class="flex-shrink-0">
<h2 class="sr-only">Git stats</h2>
<ul class="list-style-none d-flex">
<li class="ml-0 ml-md-3">
<a data-pjax href="..." class="pl-3 pr-3 py-3 p-md-0... | 2021/07/19 | [
"https://Stackoverflow.com/questions/68441299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | ```
from bs4 import BeautifulSoup as bs
html="""<span class="d-none d-sm-inline">
<strong>26</strong>
<span aria-label="Commits on master" class="color-text-secondary d-none d-lg-inline">
commits
</span>
</span>
... | You can use the [`find_next()`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all-next-and-find-next) method to look for a `<strong>` after the class `d-none d-sm-inline`.
In your case:
```
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
for tag in soup.find_all("span", class_=... | 7,361 |
23,184,410 | I have jobs scheduled thru `apscheduler`. I have 3 jobs so far, but soon will have many more. i'm looking for a way to scale my code.
Currently, each job is its own `.py` file, and in the file, I have turned the script into a function with `run()` as the function name. Here is my code.
```
from apscheduler.scheduler... | 2014/04/20 | [
"https://Stackoverflow.com/questions/23184410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1744744/"
] | ```
import urllib
import threading
import datetime
pages = ['http://google.com', 'http://yahoo.com', 'http://msn.com']
#------------------------------------------------------------------------------
# Getting the pages WITHOUT threads
#------------------------------------------------------------------------------
def... | Look @
<http://furius.ca/pubcode/pub/conf/bin/python-recursive-import-test>
This will help you import all python / .py files.
while importing you can create a list which keeps keeps a function call, for example.
[job1.run(),job2.run()]
Then iterate through them and call function :)
Thanks Arjun | 7,363 |
29,413,719 | When I input the variable a
```
a = int(1388620800)*1000
```
(of course) this variable is returned
```
1388620800000
```
But in the Google Appengine Server, this variable is changed by <https://cloud.google.com/appengine/docs/python/datastore/typesandpropertyclasses#int>
```
1388620800000L
```
How to convert 1... | 2015/04/02 | [
"https://Stackoverflow.com/questions/29413719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1474183/"
] | Maven has a [standard directory layout](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html). The directory `src/main/resources` is intended for such application resources. Place your text files into it.
You now basically have two options where exactly to place your files:
... | I tried to reproduce your problem given the MWE you provided, but did not succeed. I uploaded my project including a pom.xml (you mentioned you used maven) here: <http://www.filedropper.com/stackoverflow>
This is what my lookup class looks like (also showing how to use the getResourceAsStream method):
```
public class... | 7,364 |
74,127,611 | I am unsure if this is one of those problems that is impossible or not, in my mind it seems like it should be possible. ***Edit** - We more or less agree it is impossible*
Given a range specified by two integers (i.e. `n1 ... n2`), is it possible to create a python generator that yields a random integer from the range... | 2022/10/19 | [
"https://Stackoverflow.com/questions/74127611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8627756/"
] | As I stated in the comment above, what you are seeking is some of the facilities of reactive programming paradigm. (not to be confounded with the JavaScript library which borrows its name from there).
It is possible to instrument objects in Python to do so - I think the minimum setup here would be a specialized target... | You can try using lambdas and calling the value on return. Like this:
```
FOO = {'foo': 1}
BAR = {'test': lambda: FOO['foo'] }
FOO['foo'] = 2
print(BAR['test']()) # Outputs 2
``` | 7,365 |
48,903,304 | I am naive in Big data, I am trying to connect kafka to spark.
Here is my producer code
```python
import os
import sys
import pykafka
def get_text():
## This block generates my required text.
text_as_bytes=text.encode(text)
producer.produce(text_as_bytes)
if __name__ == "__main__":
client = pykaf... | 2018/02/21 | [
"https://Stackoverflow.com/questions/48903304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9369585/"
] | The same issue happened to me. I was unable to solve it using jsonp. What i ended up doing was to make an action in the controller that recieved the json from external url and send it to the ajax call.
For exmaple
```
return $.ajax({
type: "post",
url: "/ActionInProject/ProjectController",
});
`... | I tried your request with Postman
and I found it not valid json in the respone you can find below what is returned of the server
```
<!DOCTYPE html><html dir="ltr"><head><title>Duolingo</title><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"><meta name="robots"... | 7,367 |
26,106,358 | I have this code at the top of my Google App Engine program:
```
from google.appengine.api import urlfetch
urlfetch.set_default_fetch_deadline(60)
```
I am using an opener to load stuff:
```
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor( cj ) )
opener.addheaders = [... | 2014/09/29 | [
"https://Stackoverflow.com/questions/26106358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/847663/"
] | Did you try setting the timeout on the `.open()` call?
```
resp = opener.open('http://example.com', None, 60)
```
If you reach the timeout as specified by `set_default_fetch_deadline`, Python will throw a `DownloadError` or `DeadlineExceededErrors` exception: <https://cloud.google.com/appengine/docs/python/urlfetch/... | You can also patch the httplib2 library and set the deadline to 60 seconds
```
httplib2/__init__.py:
def fixed_fetch(url, payload=None, method="GET", headers={},
allow_truncated=False, follow_redirects=True,
deadline=60):
return fetch(url, payload=payload, me... | 7,368 |
13,583,649 | We're using EngineYard which has Python installed by default. But when we enabled SSL we received the following error message from our logentries chef recipe.
"WARNING: The "ssl" module is not present. Using unreliable workaround, host identity cannot be verified. Please install "ssl" module or newer version of Python... | 2012/11/27 | [
"https://Stackoverflow.com/questions/13583649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421709/"
] | I just wrote a recipe for this, and now am able to run the latest Logentries client on EngineYard. Here you go:
```
file_dir = "/mnt/src/python-ssl"
file_name = "ssl-1.15.tar.gz"
file_path = File.join(file_dir,file_name)
uncompressed_file_dir = File.join(file_dir, file_name.split(".tar.gz").first)
directory file_dir ... | You could install a new Python using PythonBrew: <https://github.com/utahta/pythonbrew>. Just make you install libssl before you build, or it still won't be able to use SSL. However, based on the warning, it seems that SSL *might* work, but it won't be able to verify host. Of course, that is one major purposes of SSL, ... | 7,369 |
65,534,980 | This is a little niche, but I want to click on a discord reaction with selenium (python), but only the reaction that has a specific img src.
I had it working where it would be clicking on reactions however it was clicking on every reaction not just the one I wanted.
I've tried to make it only click on the certain ele... | 2021/01/02 | [
"https://Stackoverflow.com/questions/65534980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14924745/"
] | The characters allowed in XML element names are given by the [W3C XML BNF for component names](https://www.w3.org/TR/xml/#NT-NameStartChar):
>
>
> ```
> NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] |
> [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] |
> [#... | Right: Letter, digit, hyphen, underscore and period.
One may use any Unicode letter.
And of course one may prefix the names with *name space* + colon. | 7,372 |
8,281,119 | So I am trying to do this problem where I have to find the most frequent 6-letter string within some lines in python, so I realize one could do something like this:
```
>>> from collections import Counter
>>> x = Counter("ACGTGCA")
>>> x
Counter({'A': 2, 'C': 2, 'G': 2, 'T': 1})
```
Now then, the data I'm using is ... | 2011/11/26 | [
"https://Stackoverflow.com/questions/8281119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1067233/"
] | Let us go through a slightly modified version of your test code as it is seen by `irb` and as a stand alone script:
```
def test_method;end
symbols = Symbol.all_symbols # This is already a "fixed" array, no need for map
puts symbols.include?(:test_method)
puts symbols.include?('test_method_nonexistent'.to_sym)
puts sy... | The reason you have to convert symbols to strings when checking for existence of a symbol is that it will always return true otherwise. The argument being passed to the `include?` method gets evaluated first, so if you pass it a symbol, the a new symbol is instantiated and added into the heap, so `Symbol.all_symbols` d... | 7,373 |
9,917,628 | I'm attempting to follow Heroku's python quickstart guide but am running into repeated problems. At the moment, "git push heroku master" is failing because it cannot install Bonjour. Does anyone know if this is a truly necessary requirement, and whether I can change the version required, or somehow otherwise fix this? ... | 2012/03/29 | [
"https://Stackoverflow.com/questions/9917628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/723212/"
] | Are you trying to push the example app from the quickstart? Many of the requirements you're trying to install aren't required at all.
I suspect that you created your requirements file outside of the recommended virtualenv, and that twisted and bonjour-py are packages install in your system python installation. | Why is `bonjour-py` in your requirements.txt file? Removing it should fix your problem.
Furthermore, I can't seem to install it either, so it's no wonder Heroku fails there.
```
(so)modocache $ pip install bonjour-py
Downloading/unpacking bonjour-py
Could not find any downloads that satisfy the requirement bonjour-... | 7,374 |
6,632,954 | [Why is else clause needed for try statement in python ?](https://stackoverflow.com/questions/4836139/why-is-else-clause-needed-for-try-statement-in-python)
Taking it forward:
```
try:
f = open('foo', 'r')
except IOError as e:
error_log.write('Unable to open foo : %s\n' % e)
else:
data = f.read()
f.close()
... | 2011/07/09 | [
"https://Stackoverflow.com/questions/6632954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1140524/"
] | `try..except..else` may not be *needed*, but it can be nice. In this case, the `try..except..else` form is distinctly nicer, in my opinion.
Just because you can do without an element of syntax, doesn't make it useless. Decorator syntax is purely syntax sugar (the most obvious example, I think), `for` loops are just gl... | Actually, is not always needed you can simply do:
```
f = None
try:
f = open('foo', 'r')
except IOError:
error_log.write('Unable to open foo\n')
if f:
data = f.read()
f.close()
``` | 7,379 |
70,108,696 | So i was solving a question that is in my Lab practical Syllabus. Below is the question:-
>
> Write a python class to reverse a sentence (initialized via
> constructor) word by word. Example: “I am here” should be reversed as
> “here am I”. Create instances of this class for each of the three
> strings input by the u... | 2021/11/25 | [
"https://Stackoverflow.com/questions/70108696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16369432/"
] | You are calling `getVowelCount()` twice. Instead you can use the variable instead of calling in the print command
```
for i in range (len(sorted_item)):
print('Reversed String: ',sorted_item[i].reverser(),'Vowel count: ',sorted_item[i].vowelCount)
``` | This is because you don't reset vowel count in the method. So if you execute the method once (here in sort), you'll get correct count. If you execute it twice (in printing), you will get twice as much. If you execute it once more, you'll get 3x correct amount. And so on.
The solution is to reset the number:
```py
d... | 7,380 |
2,971,198 | In one of my Django projects that use MySQL as the database, I need to have a *date* fields that accept also "partial" dates like only year (YYYY) and year and month (YYYY-MM) plus normal date (YYYY-MM-DD).
The *date* field in MySQL can deal with that by accepting *00* for the month and the day. So *2010-00-00* is val... | 2010/06/04 | [
"https://Stackoverflow.com/questions/2971198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146481/"
] | You could store the partial date as an integer (preferably in a field named for the portion of the date you are storing, such as `year,` `month` or `day`) and do validation and conversion to a date object in the model.
**EDIT**
If you need real date functionality, you probably need real, not partial, dates. For insta... | Can you store the date together with a flag that tells how much of the date is valid?
Something like this:
```
YEAR_VALID = 0x04
MONTH_VALID = 0x02
DAY_VALID = 0x01
Y_VALID = YEAR_VALID
YM_VALID = YEAR_VALID | MONTH_VALID
YMD_VALID = YEAR_VALID | MONTH_VALID | DAY_VALID
```
Then, if you have a date like 2010-00-00... | 7,381 |
50,389,852 | My Visual Studio Code's Intellisense is not working properly. Every time I try to use it with `Ctrl + Shift`, it only displays a loading message. I'm using Python (with Django) and have installed `ms-python.python`. I also have `Djaneiro`. It is still not working.
[ conversation) was adding
```
"python.analysis.extraPaths": [
"./src/lib"
],
```
(where `.src/lib/` contains your modules and an `__init__.py` file) to your `settin... | 7,389 |
54,493,369 | I am running a DB job using Maven liquibase plugin on circle ci. I need to read the parameters like username,password, dburl etc from AWS Parameter store.But when I try to set the value returned by aws cli to a custom variable, its always blank/empty. I know the value exists because the same command on mac terminal ret... | 2019/02/02 | [
"https://Stackoverflow.com/questions/54493369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3553141/"
] | According to
[their official documentation](https://circleci.com/docs/2.0/env-vars/), you need to **echo** the "export foo=bar" into $BASH\_ENV (which is just a file that runs when the a bash session starts):
so in your env-setup.sh file:
```sh
echo "export dbPasswordDev=$dbPassword" >> $BASH_ENV
``` | Here is a more advanced case where variables can be loaded from `.env` file.
```
version: 2
aliases:
- &step_process_dotenv
run:
name: Process .env file variables
command: echo "export $(grep -v '^#' .env | xargs)" >> $BASH_ENV
jobs:
build:
working_directory: ~/project
docker:
... | 7,399 |
71,637,890 | I use python and pandas to analyze big data set. I have a several arrays with different length. I need to insert values to specific column. If some values are not present for column it should be 'not defined'. Input data looks like row in dataframe with different positions.
Expected output:

.getPropertyValue("line-height");
``` | you need to set the `line-height` via `style` prop to get by script. But bear in mind, `15` and `15px` are different things for `line-height` attribute.
If we remove the style attribute, even we specify the `line-height` in CSS class, we cannot get its value as `12px` and it will be empty as same as your case.
```c... | 7,400 |
35,092,571 | I am trying to create a dashboard where I can analyse my model's data (Article) using the library [plotly](https://plot.ly/python/).
The Plotly bar chart is not showing on my template, I am wondering if I am doing something wrong since there's no error with the code below :
**models.py**
```
from django.db import mo... | 2016/01/29 | [
"https://Stackoverflow.com/questions/35092571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4859971/"
] | The result of
```
py.plot(data, filename='basic-bar')
```
is to generate a offline HTML file and return a local URL of this file
e.g. file:///your\_project\_pwd/temp-plot.html
If you want to render it in Django framework, you need to
* use `<iframe>` and restructure of your folder in Django settings
OR
* use pl... | The above answer was very useful, I am in fact watching for parent resize, I am working in angular and I used the below code to achieve the resize, I am having a similar problem and this line of code was useful
```
<div class="col-lg-12" ng-if="showME" style="padding:0px">
<div id="graphPlot" ng-bind-html="myHTML">... | 7,401 |
1,718,251 | I am using the macports version of python on a Snow Leopard computer, and using cmake to build a cross-platform extension to it. I search for the python interpreter and libraries on the system using the following commands in CMakeLists.txt
```
include(FindPythonInterp)
include(FindPythonLibs )
```
However, while cm... | 2009/11/11 | [
"https://Stackoverflow.com/questions/1718251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/134397/"
] | Adding the following in `~/.bash_profile`
```
export DYLD_FRAMEWORK_PATH=/opt/local/Library/Frameworks
```
fixes the problem at least temporarily. Apparently, this inconsistency between the python interpreter and the python framework used by cmake is a bug that should be hopefully fixed in the new version. | I am not intimately familiar with CMake, but with the Apple version of gcc/ld, you can pass the `-F` flag to specify a new framework search path. For example, `-F/opt/local/Library/Frameworks` will search in MacPorts' frameworks directory. If you can specify such a flag using CMake, it may solve your problem. | 7,402 |
69,102,892 | I have a class object which has the task of running a file. When I was developing, my class object was in the same file as the code I used to run the file.
Now I am refactoring and making this a real package so I moved the code to a file called `class_objects.py`.
I have installed this package locally, but now when I... | 2021/09/08 | [
"https://Stackoverflow.com/questions/69102892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444023/"
] | Just use boolean logic:
```
WHERE (:IP_TYPE = 'HIGH' AND (TYPE = 'HIGH' OR TYPE = '' OR TYPE IS NULL)
) OR
(:IP_TYPE = 'LOW' AND TYPE = 'LOW')
```
Or more succinctly:
```
WHERE :IP_TYPE = TYPE OR
(:IP_TYPE = 'HIGH' AND (TYPE = '' OR TYPE IS NULL))
``` | In Oracle, an empty string `''` is the same as `NULL`; so your filter can simply be:
```sql
SELECT *
FROM PAYRECORDS
WHERE :ip_type = type
OR (:ip_type = 'HIGH' AND type IS NULL);
``` | 7,403 |
21,529,118 | I'm trying to use flask-migrate to version my database locally and then reflect the changes in production (Heroku). So far I managed to successfully version the local database and upgrade it, so now I wanted to reflect this on Heroku. To do this I pushed the latest code state to Heroku together with the newly created *... | 2014/02/03 | [
"https://Stackoverflow.com/questions/21529118",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/703809/"
] | I was struggling with this for some time and even posted on the Heroku python forums, but no replies so far. To solve the issue I decided not to run the migration remotely on Heroku, but to run the migration on my development machine and pass the production database address instead. So I do this:
1. Sync the developme... | I haven't tried this with Heroku, but ran into the same error and symptoms. The issue for me was that when running locally, my current working directory was set to the project root directory, and when running remotely, it was set to the user's home directory.
Try either cd'ing to the right starting directory first, or... | 7,406 |
10,524,842 | I have a multithreaded mergesorting program in C, and a program for benchmark testing it with 0, 1, 2, or 4 threads. I also wrote a program in Python to do multiple tests and aggregate the results.
The weird thing is that when I run the Python, the tests always run in about half the time compared to when I run them di... | 2012/05/09 | [
"https://Stackoverflow.com/questions/10524842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1325447/"
] | Turns out I was passing sys.maxint to the subprocess as the modulus for generating random numbers. C was truncating the 64-bit integer and interpreting it as signed, i.e., -1 in two's complement, so every random number was being mod'd by that and becoming 0. So, sorting all the same values seems to take about half as m... | wrapping this in a shell script will probably have the same effect. if so its the console operations | 7,411 |
20,694,338 | I am trying to play around with some more of function programming parts of python and for a test I thought I would print out the sum of the first n integers for all numbers between 1 and 100.
```
for i in map(lambda n: (n*(n+1))/2, range(1,101)):
print "sum of the first %d integers: %d" % (i,i)
```
The last lin... | 2013/12/20 | [
"https://Stackoverflow.com/questions/20694338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1761521/"
] | You can return tuple with (index, value) from your lambda, like that:
```
for i,s in map(lambda n: (n,(n*(n+1))/2), range(1,101)):
print "sum of the first %d integers: %d" % (i,s)
``` | Your code doesn't define a variable that holds an index. In the outermost scope, there is just the variable (sometimes called a "name" when talking about Python) "i".
If you'd like an index, you can use the built-in function enumerate()
```
for i,x in enumerate([5,10,15]):
print i, x
``` | 7,412 |
62,670,991 | I'm trying to read multiple CSV files from blob storage using python.
The code that I'm using is:
```
blob_service_client = BlobServiceClient.from_connection_string(connection_str)
container_client = blob_service_client.get_container_client(container)
blobs_list = container_client.list_blobs(folder_root)
for blob in ... | 2020/07/01 | [
"https://Stackoverflow.com/questions/62670991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6153466/"
] | You could download the file from blob storage, then read the data into a pandas DataFrame from the downloaded file.
```
from azure.storage.blob import BlockBlobService
import pandas as pd
import tables
STORAGEACCOUNTNAME= <storage_account_name>
STORAGEACCOUNTKEY= <storage_account_key>
LOCALFILENAME= <local_file_name>... | ```
import pandas as pd
data = pd.read_csv('blob_sas_url')
```
The Blob SAS Url can be found by right clicking on the azure portal's blob file that you want to import and selecting Generate SAS. Then, click Generate SAS token and URL button and copy the SAS url to above code in place of blob\_sas\_url. | 7,418 |
936,933 | If you raise a KeyboardInterrupt while trying to acquire a semaphore, the threads that also try to release the same semaphore object hang indefinitely.
Code:
```
import threading
import time
def worker(i, sema):
time.sleep(2)
print i, "finished"
sema.release()
sema = threading.BoundedSemaphore(value=5)
... | 2009/06/01 | [
"https://Stackoverflow.com/questions/936933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41613/"
] | You can use the signal module to set a flag that tells the main thread to stop processing:
```
import threading
import time
import signal
import sys
sigint = False
def sighandler(num, frame):
global sigint
sigint = True
def worker(i, sema):
time.sleep(2)
print i, "finished"
sema.release()
signal.signal(s... | In this case, it looks like you might just want to use a thread pool to control the starting and stopping of your threads. You could use [Chris Arndt's threadpool library](http://www.chrisarndt.de/projects/threadpool/) in a manner something like this:
```
pool = ThreadPool(5)
try:
# enqueue 100 worker threads
... | 7,425 |
48,561,126 | I installed opencv on my Ubuntu 14.04 system system with
```
pip install python-opencv
```
my Python version is 2.7.14
```
import cv2
cv2.__version__
```
tells me that I have the OpenCV version 3.4.0.
After that I wanted to follow the tutorial on the OpenCV website
```
import numpy as np
import cv2 as cv
img =... | 2018/02/01 | [
"https://Stackoverflow.com/questions/48561126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3977420/"
] | Apparently
```
pip install python-opencv
```
is not working at all and should not be used. After I installed Opencv from their website it worked | Try checking if the image you are reading is loading
```
image = cv2.imread(filepath,0) #0 for gray scale
if image is None:
print "Cant Load Image"
else:
cv2.imshow("Image", image)
cv2.waitKey(0)
``` | 7,432 |
30,324,474 | **Using the "re" i compile the datas of a handshake like this:**
```
piece_request_handshake = re.compile('13426974546f7272656e742070726f746f636f6c(?P<reserved>\w{16})(?P<info_hash>\w{40})(?P<peer_id>\w{40})')
handshake = piece_request_handshake.findall(hex_data)
```
*Then i print it*
**I'm unable to add image b... | 2015/05/19 | [
"https://Stackoverflow.com/questions/30324474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872475/"
] | `re.findall()` returns a list of tuples, each containing the matching strings that correspond to the named groups in the re pattern. This example (using a simplified pattern) demonstrates that you can access the required item with indexing:
```
import re
prefix = 'prefix'
pattern = re.compile('%s(?P<reserved>\w{4})(?... | `re.findall` will return a list of tuples. The `group()` call works on `Match` objects, returned by some other functions in `re`:
```
for match in re.finditer(needle, haystack):
print match.group('info_hash')
```
Also, you might not need `findall` if you're just matching a single handshake. | 7,435 |
30,542,336 | I am new to python and trying to learn the recursion.
I'm trying to display all possible outcomes by changing 'a' to either number 7 or 8
For example,
```
user_type = 40aa
```
so it will display:
```
4077
4078
4087
4088
```
thank you
it doesn't have to be 40aa, it can be a4a0, aaa0, etc
this code is only r... | 2015/05/30 | [
"https://Stackoverflow.com/questions/30542336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4955371/"
] | ```
pattern = "40aa"
options = [7, 8]
def replace(left, right):
if len(right) > 0:
if right[0] == "a":
results = []
for i in options:
results.extend(replace(left + str(i), right[1:]))
return results
else:
return replace(left + right[0], right[1:])
else... | I don't know Python very well, but I can help with the recursion.
The basic idea is that you will loop through each character in the string, and each time you hit an 'a', you will replace it with a 7 and an 8, and pass both of those values to your recursive method.
Here is an example:
Suppose you have the string "Bast... | 7,436 |
22,770,352 | I am trying to predict weekly sales using ARMA ARIMA models. I could not find a function for tuning the order(p,d,q) in `statsmodels`. Currently R has a function `forecast::auto.arima()` which will tune the (p,d,q) parameters.
How do I go about choosing the right order for my model? Are there any libraries availabl... | 2014/03/31 | [
"https://Stackoverflow.com/questions/22770352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1483927/"
] | ```
def evaluate_arima_model(X, arima_order):
# prepare training dataset
train_size = int(len(X) * 0.90)
train, test = X[0:train_size], X[train_size:]
history = [x for x in train]
# make predictions
predictions = list()
for t in range(len(test)):
model = ARIMA(history, order=arima_or... | I wrote these utility functions to directly calculate pdq values
*get\_PDQ\_parallel* require three inputs data which is series with timestamp(datetime) as index. n\_jobs will provide number of parallel processor. output will be dataframe with aic and bic value with order=(P,D,Q) in index
p and q range is [0,12] while... | 7,438 |
68,562,020 | This is my code
```
import pandas as pd
keys = ['phone match', 'account match']
d = {k: [] for k in keys}
df = pd.DataFrame(data=[[1,2,3],[4,5,6]],columns=['A','B','C'])
df['D'] = [d for _ in range(df.shape[0])]
df.at[0, 'D']['phone match'].append(4)
```
But instead of appending only on the dictionary at index 0 i... | 2021/07/28 | [
"https://Stackoverflow.com/questions/68562020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16546771/"
] | You need to create multiple `dict` in order to make each of them have different object ID
```
keys = ['phone match', 'account match']
df = pd.DataFrame(data=[[1,2,3],[4,5,6]],columns=['A','B','C'])
df['D'] = [{k: [] for k in keys} for _ in range(df.shape[0])] # Change here
df.at[0, 'D']['phone match'].append(4)
df
Ou... | `dict` objects are passed by reference in python.
In order to achieve what you want, you can use the following line which creates a copy of d for every line:
```
df['D'] = [d.copy() for _ in range(df.shape[0])]
``` | 7,448 |
31,518,864 | I am currently generating 8 random values each time I run a program on Python. These 8 values are different each time I run the program, and I would like to be able to now save these 8 values each time I run the program to a text file in 8 separate columns. When saving these values for future runs, though, I would like... | 2015/07/20 | [
"https://Stackoverflow.com/questions/31518864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5135338/"
] | ```
import csv
from tempfile import NamedTemporaryFile
from shutil import move
from itertools import chain
with open("in.csv") as f, NamedTemporaryFile(dir=".", delete=False) as temp:
r = csv.reader(f)
new = [9, 10, 11, 12, 13, 14, 15, 16]
wr = csv.writer(temp)
wr.writerows(zip(chain.from_iterable(r), n... | what about
```
a = [1, 2, 3, 4, 5, 6, 7, 8]
f = open('myFile.txt', 'a')
for n in a:
f.write('%d\t'%n)
f.write('\n')
f.close()
```
and you get as file content after running it 4 times
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8
======= EDIT =========
Try this, its ugly but works... | 7,449 |
66,602,674 | I have two e2e automation framework , one is python based other is protractor based. I need to write a docker-compose file to run these two projects in different containers and fetch reports and their console to my local system.
below are the contents of my docker-compose.yml file
```
version: '3'
services:
e2e-Tes... | 2021/03/12 | [
"https://Stackoverflow.com/questions/66602674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7074479/"
] | Try to rename: `Dockerfile` instead of `DockerFile`.
**Edit:**
When the docker file name is not provided explicitly, it will look for the file `Dockerfile` with a small `f`. My issue was as simple that. | My issue was related to registry access issues. It works fine now. | 7,450 |
53,402,349 | i build regex expression that matches
2 letters or 2 letters folowed by '/' and next 2 letters for example:
```
rt bl/ws se gn/wd wk bl/rt
/^(((\s+)?[a-zA-Z]{2}(\/[a-zA-Z]{2})?)(\s+|$))+$/i
```
and that works without problems.
Next problem what I have is match all "word" not containing '/' character.
and replace a... | 2018/11/20 | [
"https://Stackoverflow.com/questions/53402349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1743688/"
] | A list comprehension should do the trick:
```
>>> NUM_ITEMS = 5
>>> my_array = [[0, 1] for _ in range(NUM_ITEMS)]
>>> my_array
[[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]
``` | Since you tagged arrays, here's an alternative `numpy` solution using [`numpy.tile`](https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.tile.html).
```
>>> import numpy as np
>>> NUM_ITEMS = 10
>>> np.tile([0, 1], (NUM_ITEMS, 1))
array([[0, 1],
[0, 1],
[0, 1],
[0, 1],
[0, 1],... | 7,451 |
49,695,050 | I'm trying to write a csv file into an S3 bucket using AWS Lambda, and for this I used the following code:
```
data=[[1,2,3],[23,56,98]]
with open("s3://my_bucket/my_file.csv", "w") as f:
f.write(data)
```
And this raises the following error:
```
[Errno 2] No such file or directory: u's3://my_bucket/my_file.csv'... | 2018/04/06 | [
"https://Stackoverflow.com/questions/49695050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6598781/"
] | Better to answer later than never. There are four steps to get your data in S3:
* Call the S3 bucket
* Load the data into Lambda using the requests library (if you don't have it installed, you are gonna have to load it as a layer)
* Write the data into the Lambda '/tmp' file
* Upload the file into s3
Something like t... | ```
with open("s3://my_bucket/my_file.csv", "w+") as f:
```
instead of
```
with open("s3://my_bucket/my_file.csv", "w") as f:
```
notice the "w" has changed to "w+" this means that it will write to the file, and if it does not exist it will create it. | 7,452 |
51,400,332 | I want the insertion query do nothing if it's nothing new in csv file , In Case it is , i want to insert only this one and not again all the csv, any suggestion would be great!
PS: it's not duplicate with other questions because here we have "%s" no stable values and in python it's different the syntax!
```
curs... | 2018/07/18 | [
"https://Stackoverflow.com/questions/51400332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9855183/"
] | You should do something like this:
```
class eventCell: UICollectionViewCell {
@IBOutlet private weak var eventTitle: UILabel!
@IBOutlet private weak var descriptionLabel:UILabel!
@IBOutlet private weak var eventImage: UIImageView!
typealias Event = (title:String, location:String, lat:CLLocationDegree... | Why not creating some `Struct`?
Simple like this:
```
struct Event {
var title: String
var location: String
var lat: CLLocationDegrees
var long: CLLocationDegrees
}
```
Then just do that:
```
var eventArray = [Event]()
```
And call it like that:
```
for event in eventArray{
event.title = eventTitle... | 7,454 |
68,714,450 | I have 2 dataframes:
**users**
```
user_id position
0 201 Senior Engineer
1 207 Senior System Architect
2 223 Senior account manage
3 212 Junior Manager
4 112 junior Engineer
5 311 junior python developer
```
```
df1 = pd.DataFrame({'user_id': ['201', '207', '223', '212', '112', '311'],
... | 2021/08/09 | [
"https://Stackoverflow.com/questions/68714450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16580145/"
] | You can use `str.extract()`+`merge()`:
```
pat='('+'|'.join(df2['role_position'].str.strip('%').unique())+')'
df1['role_position']='%'+df1['position'].str.lower().str.extract(pat,expand=False)+'%'
df1=df1.merge(df2,on='role_position',how='left')
```
output of `df1`:
```
user_id position role_id role... | Possibilities:
* [fuzzy words](https://www.google.com/search?q=fuzzy%20in%20pandas&rlz=1C5CHFA_enPL889PL889&oq=fuzzy%20in%20pandas&aqs=chrome..69i57j0i10i22i30j0i22i30.2529j0j7&sourceid=chrome&ie=UTF-8)
* [Sequence Matcher](https://towardsdatascience.com/sequencematcher-in-python-6b1e6f3915fc)
* [.extract](https://www... | 7,455 |
61,253,507 | I am parsing json file that has the following data subset.
```
"title": "Revert \"testcase for check\""
```
In my python script I do the following:
```
with open('%s/staging_area/pr_info.json' % cwd) as data_file:
pr_info = json.load(data_file)
pr_title=pr_info["title"]... | 2020/04/16 | [
"https://Stackoverflow.com/questions/61253507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9828901/"
] | If you really need it, you should escape it again with json and remove first and last quote:
```py
pr_title = json.dumps(pr_title)[1:-1]
```
but escape characters is for escaping, raw value of string is still `Revert "testcase for check"`. So escaping function will depend on where you data is applied (DB, HTML, XML,... | If your goal is to print pr\_title, then you can probably use json.dumps() to print the original text.
```
>>> import json
>>> j = '{"name": "\"Bob\""}'
>>> print(j)
{"name": ""Bob""}
>>> json.dumps(j)
'"{\\"name\\": \\"\\"Bob\\"\\"}"'
``` | 7,459 |
62,618,261 | I have 4 figures (y1,y2,y3,y4) that i want to plot on a common x axis (yr1,yr2,yr3,m1,m2,m3,m4,m5). In this code however i have kept axaxis as separate since i am trying to get the basics right first.
```
import matplotlib.pyplot as plt
import numpy as np
plt.figure(1)
xaxis = ['y1','y2','y3','m1','m2','m3', 'm4', 'm... | 2020/06/28 | [
"https://Stackoverflow.com/questions/62618261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5866905/"
] | Small mistake. You have put `plt.subplot` instead of `plt.plot`. This should work now:
```
import matplotlib.pyplot as plt
import numpy as np
plt.figure(1)
xaxis = ['y1','y2','y3','m1','m2','m3', 'm4', 'm5']
y1 = np.array([.73,.74,.71,.75,.72,.75,.74,.74])
y2 = np.array([.82,.80,.77,.81,.72,.81,.77,.77])
y3 = np.arra... | Try this:
```
fig, ax = plt.subplots(4, 1,sharex=True,gridspec_kw= {'height_ratios':[3,1,1,1]})
ax[0].plot(xais,y1)
ax[1].plot(xais,y1)
ax[2].plot(xais,y1)
ax[3].plot(xais,y1)
```
for 4 figures stacked on top of each other with shared x-axis.
for 2x2:
```
fig, ax = plt.subplots(2,2)
ax[0,0].plot(xaxis,y1)
ax[0,1].... | 7,461 |
45,063,974 | I have a sqlite table with 3 columns named ID (integer), N (integer) and V (real). The pair (ID, N) is unique.
Using the python module sqlite3, I would like to perform a recursive selection with the form
```
select ID from TABLE where N = 0 and V between ? and ? and ID in
(select ID from TABLE where N = 7 and V... | 2017/07/12 | [
"https://Stackoverflow.com/questions/45063974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2660966/"
] | Unwrap the recursion, do it in reverse order and do it in Python. For this I created a table consisting of 100 records, each with an Id between 0 and 99, N=3 and V=5. Arbitrarily I selected the entire collection of records as the innermost.
You need to imagine having a list of values for N and V indexed so that the v... | Indexing the triplet (ID, N, V) instead of only the (N, V) doublet made the join approach fast enough for being considered
```
create index I on TABLE(ID, N, V)
```
and then
```
select ID from
(select ID from TABLE where N = 0 and V between ? and ?)
join (select ID from TABLE where N = 7 and V betw... | 7,463 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.