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 |
|---|---|---|---|---|---|---|
19,017,840 | I have two large python dictionaries in the following form, and I want to compare them and report their mismatches at **identical indices**, for the **same key**. The dictionaries have the same keys, but the tuples do not have equal lengths.
```
d1 = {'a':(1,2,3,4,66,6,6,64), 'b':(3,2,5,3,2,1,1,1)}
d2 = {'a':(1,2,4,3,... | 2013/09/26 | [
"https://Stackoverflow.com/questions/19017840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2621263/"
] | **SOLUTION**
The trick is to run the VM without GUI. With this you can easily run VM on WIN server like a service too.
Prerequired is that exist some VM, you have some already. Below put its name instead `{vm_name}`.
---
**1) At first we use build-in executable file "VBoxHeadless.exe".**
Create file
```
vm.run.ba... | If you do not mind operating the application once manually, to end with OS running in background; here are the options:
Open Virtual Box.
Right Click on your Guest OS > Choose: Start Headless.
Wait for a while till the OS boots.
Then close the Virtual Box application. | 14,527 |
72,751,658 | I have written a python program for printing a diamond. It is working properly except that it is printing an extra kite after printing a diamond. May someone please help me to remove this bug? I can't find it and please give a fix from this code please.
CODE:
```
limitRows = int(input("Enter the maximum number of rows... | 2022/06/25 | [
"https://Stackoverflow.com/questions/72751658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19409398/"
] | You have an extra while loop in the second half of your code.
Try this
```
limitRows = int(input("Enter the maximum number of rows: "))
maxRows = limitRows + (limitRows - 1)
currentRow = 0
while currentRow <= limitRows:
spaces = limitRows - currentRow
while spaces > 0:
print(" ", end='')
space... | You can make this less complex by using just one loop as follows:
```
def make_row(n):
return ' '.join(['*'] * n)
rows = input('Number of rows: ')
if (nrows := int(rows)) > 0:
diamond = [make_row(nrows)]
j = len(diamond[0])
for i in range(nrows-1, 0, -1):
j -= 1
diamond.append(make_ro... | 14,537 |
59,529,038 | I am using [nameko](https://nameko.readthedocs.io/en/stable/) to build an ETL pipeline with a micro-service architecture, and I do not want to wait for a reply after making a RPC request.
```
from nameko.rpc import rpc, RpcProxy
class Scheduler(object):
name = "scheduler"
task_runner = RpcProxy('task_runner')
... | 2019/12/30 | [
"https://Stackoverflow.com/questions/59529038",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8776121/"
] | I had the same problem; you need to replace the `async` method with the `call_async` one, and retrieve the data with `result()`.
[Documentation](https://nameko.readthedocs.io/en/stable/built_in_extensions.html)
[GitHub issue](https://github.com/nameko/nameko/pull/318) | use call\_async instead async or for better result use event
from nameko.events import EventDispatcher, event\_handler
```
@event_handler("service_a", "event_emit_name")
def get_result(self, payload):
#do_something...
```
and in other service
```
from nameko.events import EventDispatcher, event_handler
@... | 14,538 |
31,196,412 | I am new to the world of map reduce, I have run a job and it seems to be taking forever to complete given that it is a relatively small task, I am guessing something has not gone according to plan. I am using hadoop version 2.6, here is some info gathered I thought could help. The map reduce programs themselves are str... | 2015/07/02 | [
"https://Stackoverflow.com/questions/31196412",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1285948/"
] | If a job is in `ACCEPTED` state for long time and not changing to `RUNNING` state, It could be due to the following reasons.
Nodemanager(slave service) is either dead or unable to communicate with resource manager. if the `Active nodes` in the Yarn resource manager [Web ui main page](http://mymacbook.home:8088/) is z... | Have you partitioned your data the same way you query it ? Basically, you don't want to query all your data, which is what you may be doing at the moment. That could explain why it's taking such a long time to run.
You want to query a subset of your whole data set. For instance, if you partition over dates, you really... | 14,539 |
32,959,770 | In python, I can do this to get the current file's path:
```
os.path.dirname(os.path.abspath(__file__))
```
But if I run this on a thread say:
```
def do_stuff():
class RunThread(threading.Thread):
def run(self):
print os.path.dirname(os.path.abspath(__file__))
a = RunThread()
a.start()
... | 2015/10/06 | [
"https://Stackoverflow.com/questions/32959770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1515864/"
] | ```
import inspect
print(inspect.stack()[0][1])
```
[inspect](https://docs.python.org/2/library/inspect.html) | I apologise for my previous answer. I was half asleep and replied stupidly.
Every time I've done what you're trying to do, I have used it in the inverse order. E.g. `os.path.abspath(os.path.dirname(__file__))` | 14,540 |
48,047,495 | ```
Collecting jws>=0.1.3 (from python-jwt==2.0.1->pyrebase)
Using cached https://files.pythonhosted.org/packages/01/9e/1536d578ed50f5fe8196310ddcc921a3cd8e973312d60ac74488b805d395/jws-0.1.3.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>",... | 2018/01/01 | [
"https://Stackoverflow.com/questions/48047495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8272238/"
] | I've just solved this.
[MyGitHub.io](https://wesely.github.io/pip,%20python,%20pip/Fix-'cp950'-Error-when-using-'pip-install'/)
It's a bug from `jws` package, it should consider the encoding problem in its `setup.py`.
My Solution : install `jws` first
* use `pip download jws` instead of `pip install`
* use 7z open... | I solved this problem by deleting Visual Studio Community 2017 including python dev. option | 14,541 |
12,646,883 | I've been trying to make a simple blackjack game in python and I seem to be stuck, my code is as follows:
```
from random import choice
def deck():
cards = range(1, 12)
return choice(cards)
def diack():
card1= deck()
card2 = deck()
hand = card1 + card2
print hand
if hand < 21:
pr... | 2012/09/28 | [
"https://Stackoverflow.com/questions/12646883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1689672/"
] | `if "hit"` just tests if the string `"hit"` exists, and it does. Thus, the `elif` statement is never executed.
You need to capture the user input in a variable and test against that instead:
```
choice = raw_input("Would you like to hit or stand?")
print choice
if choice == "hit":
return hand + deck()
elif choice... | Assuming you get the indentation right:
```
print raw_input("Would you like to hit or stand?")
if "hit":
return hand + deck()
elif "stand":
return hand
```
Your `if` is just checking whether the string `"hit"` is true. All non-empty strings are true, and `"hit"` is non-empty, so this will always succeed.
W... | 14,543 |
43,983,127 | I wish to find all words that start with "Am" and this is what I tried so far with python
```
import re
my_string = "America's mom, American"
re.findall(r'\b[Am][a-zA-Z]+\b', my_string)
```
but this is the output that I get
```
['America', 'mom', 'American']
```
Instead of what I want
```
['America', 'American']... | 2017/05/15 | [
"https://Stackoverflow.com/questions/43983127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/863713/"
] | The `[Am]`, a positive [character class](http://www.regular-expressions.info/charclass.html), matches either `A` or `m`. To match a *sequence* of chars, you need to use them one after another.
Remove the brackets:
```
import re
my_string = "America's mom, American"
print(re.findall(r'\bAm[a-zA-Z]+\b', my_string))
# =... | Don't use character class:
```
import re
my_string = "America's mom, American"
re.findall(r'\bAm[a-zA-Z]+\b', my_string)
``` | 14,544 |
65,376,345 | I had started scrapy with Official Tutorial, but I can't go with it successfully.My code is totally same with official one.
```
import scrapy
class QuotesSpider(scrapy.Spider):
name = 'Quotes';
def start_requests(self):
urls = [
'http://quotes.toscrape.com/page/1/',
]
for u... | 2020/12/20 | [
"https://Stackoverflow.com/questions/65376345",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14482346/"
] | There is a `IndentationError`.Need to fix code indentation. Its work fine. | You might find a solution for your issue here
>
> [Scrapy installed, but won't run from the command line](https://stackoverflow.com/questions/37757233/scrapy-installed-but-wont-run-from-the-command-line)
>
>
> | 14,546 |
12,634,452 | I have 2 dictionaries
```
a = {'I': [1,2], 'II': [1,2], 'III': [1,2]}
b = {'I': [3,4], 'II': [3,4], 'IV': [3,4]}
```
how can i merge them such that i get the following result
```
c = merge_dicts(a,b)
```
where c is `{'I': [1,2,3,4], 'II': [1,2,3,4], 'III': [1,2], 'IV': [3,4]}`
Is there a good pythonic way of do... | 2012/09/28 | [
"https://Stackoverflow.com/questions/12634452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1742869/"
] | Are you sure they have the same keys? You could do:
```
c = dict( (k,a[k]+b[k]) for k in a )
```
Addition of lists concatenates so `a[k] + b[k]` gives you something like `[1,2]+[3,4]` which equals `[1,2,3,4]`. The `dict` constructor can take a series of 2-element iterables which turn into `key` - `value` pairs.
If ... | ```
>>> a = {'I': [1,2], 'II': [1,2]}
>>> b = {'I': [3,4], 'II': [3,4]}
>>> {key:a[key]+b[key] for key in a}
{'I': [1, 2, 3, 4], 'II': [1, 2, 3, 4]}
```
Note that this only works if they share keys exactly. | 14,548 |
38,921,815 | I am using python 3.5.
When I tried to return a generator function instance and i am getting a StopIteration error. Why?
here is my code:
```
>>> def gen(start, end):
... '''generator function similar to range function'''
... while start <= end:
... yield start
... start += 1
...
>>> def check(ingen, f... | 2016/08/12 | [
"https://Stackoverflow.com/questions/38921815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In Python, if `yield` is present in a function, then Python treats it as a generator. In a generator, any return will raise `StopIteration` with the returned value. This is a new feature in Python 3.3: see [PEP 380](https://www.python.org/dev/peps/pep-0380/) and [here](https://stackoverflow.com/a/16780113/2097780). `ch... | When a generator hits its `return` statement (explicit or not) it raises `StopIteration`. So when you `return ingen` you end the iteration.
`check_v2` is not a generator, since it does not contain the `yield` statement, that's why it works. | 14,553 |
57,484,399 | I'm new to Python and am using Anaconda on Windows 10 to learn how to implement machine learning. Running this code on Spyder:
```py
import sklearn as skl
```
Originally got me this:
```
Traceback (most recent call last):
File "<ipython-input-1-7135d3f24347>", line 1, in <module>
runfile('C:/Users/julia/.spy... | 2019/08/13 | [
"https://Stackoverflow.com/questions/57484399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7385274/"
] | I ended up fixing this by uninstalling my current version of Anaconda and installing a version from a few months ago. I didn't get the "ordinal 242" error nor the issues with scikit-learn. | I encountered the same error after letting my PC sit for 4 days unattended. Restarting the kernel solved it.
This probably won't work for everyone, but it might save someone a little agony. | 14,559 |
66,436,933 | I am working with sequencing data and need to count the number of reads that match to a grna library in python. Simplified my data looks like this:
```
reads = ['abc', 'abc','def', 'ghi']
grnas = ['abc', 'ghi']
```
The grnas list is unique, while the reads list can contain entries that are not of interest and don't ... | 2021/03/02 | [
"https://Stackoverflow.com/questions/66436933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8413867/"
] | Your case cannot be less of O(n).
Using single process the best solution is:
```
[x for x in reads if x in set(grnas)]
or
[x for x in reads if x in dict.fromkeys(grnas)]
```
but this is a simple case to parallelyze, you can reduce input data in some bunch of works and append all results. | as the worst case of complexity search in both `set` & `dict` in python is some how `O(N)` so the complexity of the program would be `O(N * M)`. it would not be efficient to use them. so use the `Counter` object which will do the search in `O(1)` so the whole program would be done in
`O(max(N, M))` complexity.
```py
f... | 14,560 |
58,774,718 | I'm writing multi-process code, which runs perfectly in Python 3.7. Yet I want one of the parallel process to execute an IO process take stakes for ever using AsyncIO i order to get better performance, but have not been able to get it to run.
Ubuntu 18.04, Python 3.7, AsyncIO, pipenv (all pip libraries installed)
The... | 2019/11/08 | [
"https://Stackoverflow.com/questions/58774718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/982446/"
] | As it seems from the *Traceback* log it is look like you are trying to add tasks to not running *event loop*.
>
> /.pyenv/versions/3.7.4/lib/python3.7/multiprocessing/process.py:313:
> RuntimeWarning: coroutine
> '.\_get\_filter\_collateral..read\_task' **was never
> awaited**
>
>
>
The *loop* was just created... | Use `asyncio.ensure_future` instead. See <https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future> | 14,561 |
6,286,579 | Is there some module or command that'll let me send the current region to shell?
I want to have something like Python-mode's `python-send-region` which sends the selected region to the currently running Python shell. | 2011/06/08 | [
"https://Stackoverflow.com/questions/6286579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/419116/"
] | Ok, wrote an easy bit. Will probably spend some time to write a complete minor mode.
For time being the following function will send current line (or region if the mark is active). Does quite a good job for me:
```
(defun sh-send-line-or-region (&optional step)
(interactive ())
(let ((proc (get-process "shell"))
... | `M-x` `append-to-buffer` `RET` | 14,562 |
41,565,091 | I'm calling xgboost via its scikit-learn-style Python interface:
```
model = xgboost.XGBRegressor()
%time model.fit(trainX, trainY)
testY = model.predict(testX)
```
Some sklearn models tell you which importance they assign to features via the attribute `feature_importances`. This doesn't seem to exist for the `XGB... | 2017/01/10 | [
"https://Stackoverflow.com/questions/41565091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/626537/"
] | How did you install xgboost? Did you build the package after cloning it from github, as described in the doc?
<http://xgboost.readthedocs.io/en/latest/build.html>
As in this answer:
[Feature Importance with XGBClassifier](https://stackoverflow.com/questions/38212649/feature-importance-with-xgbclassifier)
There al... | This is useful for you,maybe.
`xgb.plot_importance(bst)`
And this is the link:[plot](http://xgboost.readthedocs.io/en/latest/python/python_intro.html#plotting) | 14,572 |
73,966,292 | By "Google Batch" I'm referring to the new service Google launched about a month or so ago.
<https://cloud.google.com/batch>
I have a Python script which takes a few minutes to execute at the moment. However with the data it will soon be processing in the next few months this execution time will go from minutes to **... | 2022/10/05 | [
"https://Stackoverflow.com/questions/73966292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13379101/"
] | EDIT -- added the "55 difference columns" part at the bottom.
---
Adjusting data to be column pairs:
```
df <- data.frame(matrix(sample(1:10, 200, replace = TRUE), ncol = 20, nrow = 10))
names(df) <- paste0("var", rep(1:10, each = 2), "_", rep(c("apple", "banana")))
names(df)
[1] "var1_apple" "var1_banana" "var2... | I think @Tom's comment is spot-on. Restructuring the data probably makes sense if you are working with paired data. E.g.:
```
od <- names(df)[c(TRUE,FALSE)]
ev <- names(df)[c(FALSE,TRUE)]
data.frame(
odd = unlist(df[od]),
oddname = rep(od,each=nrow(df)),
even = unlist(df[ev]),
evenname = rep... | 14,575 |
73,937,555 | I have a folder named `deployment`, under deployment there are two sibling folders: `folder1` and `folder2`.
i need to move folder2 with its sub contents to folder1 with python scrips, so from:
```
.../deployment/folder1/...
/folder1/...
```
to
```
.../deployment/folder1/...
/folder1/... | 2022/10/03 | [
"https://Stackoverflow.com/questions/73937555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4483819/"
] | Settings are empty, maybe they are not exported correctly. Check your settings file. | I think you're not using the find API call for MongoDB properly,
find usually takes up a filter object and an object of properties as a second argument.
Check the syntax required for find(){} function and probably you'll get through with it.
Hope it helps.
Happy coding!! | 14,577 |
41,836,353 | I have a project in which I run multiple data through a specific function that `"cleans"` them.
The cleaning function looks like this:
Misc.py
```
def clean(my_data)
sys.stdout.write("Cleaning genes...\n")
synonyms = FileIO("raw_data/input_data", 3, header=False).openSynonyms()
clean_genes = {}
for... | 2017/01/24 | [
"https://Stackoverflow.com/questions/41836353",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3008400/"
] | Use a class with a \_\_call\_\_ operator. You can call objects of this class and store data between calls in the object. Some data probably can best be saved by the constructor. What you've made this way is known as a 'functor' or 'callable object'.
Example:
```
class Incrementer:
def __init__ (self, increment):
... | I think the cleanest way to do this would be to decorate your "`clean`" (pun intended) function with another function that provides the `synonyms` local for the function. this is iamo cleaner and more concise than creating another custom class, yet still allows you to easily change the "input\_data" file if you need to... | 14,578 |
13,152,085 | Hi im trying to use regex in python 2.7 to search for text inbetween two quotation marks such as "hello there". Right now im using:
```
matchquotes = re.findall(r'"(?:\\"|.)*?"', text)
```
It works great but only finds quotes using this character: **"**
However I'm finding sometimes that some text that im parsing... | 2012/10/31 | [
"https://Stackoverflow.com/questions/13152085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1495000/"
] | Using character classes might work, or might break everything for you:
```
matchquotes = re.findall(r'[“”"](?:\\[“”"]|.)*?[“”"]', text)
```
If you don't care a lot about matching pairs always lining up, this will probably do what you want. The case where they use the third type inside the other two is always going t... | Depending on what other processing you are doing and where the text is coming from, it would be better to convert all quotation marks to " rather than handle each case. | 14,580 |
71,232,402 | First of all, thank you for the time you took to answer me.
To give **a little example**, I have a huge dataset (n instances, 3 features) like that:
`data = np.array([[7.0, 2.5, 3.1], [4.3, 8.8, 6.2], [1.1, 5.5, 9.9]])`
It's labeled in another array:
`label = np.array([0, 1, 0])`
**Questions**:
1. I know that I c... | 2022/02/23 | [
"https://Stackoverflow.com/questions/71232402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18285419/"
] | You could start from and easier variant of this problem:
***Given `arr` and its label, could you find a minimum and maximum values of `arr` items in each group of labels?***
For instance:
```
arr = np.array([55, 7, 49, 65, 46, 75, 4, 54, 43, 54])
label = np.array([1, 3, 2, 0, 0, 2, 1, 1, 1, 2])
```
Then you woul... | it has already been answered, you can go to this link for your answer [python numpy access list of arrays without for loop](https://stackoverflow.com/questions/36530446/python-numpy-access-list-of-arrays-without-for-loop) | 14,583 |
50,221,468 | This question comes from "Automate the boring stuff with python" book.
```
atRegex1 = re.compile(r'\w{1,2}at')
atRegex2 = re.compile(r'\w{1,2}?at')
atRegex1.findall('The cat in the hat sat on the flat mat.')
atRegex2.findall('The cat in the hat sat on the flat mat.')
```
I thought the question market ? should c... | 2018/05/07 | [
"https://Stackoverflow.com/questions/50221468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8370526/"
] | There's nothing wrong (that is, ordinary assignment in P6 is designed to do as it has done) but at a guess you were hoping that making the structure on the two sides the same would result in `$a` getting `1`, `$b` getting `2` and `$c` getting `3`.
For that, you want "binding assignment" (aka just "binding"), not ordin... | If you want to have the result be `1, 2, 3`, you must `Slip` the list:
```
my ($a, $b, $c) = |(1, 2), 3;
```
This is a consequence of the single argument rule: <https://docs.raku.org/type/Signature#Single_Argument_Rule_Slurpy>
This is also why this just works:
```
my ($a, $b, $c) = (1, 2, 3);
```
Even though `(1... | 14,584 |
66,779,282 | I would like to print the rating result for different user in separate array. It can be solved by creating many arrays, but I didn't want to do so, because I have a lot of user in my Json file, so how can I do this programmatically?
python code
```
with open('/content/user_data.json') as f:
rating = []
js = json.... | 2021/03/24 | [
"https://Stackoverflow.com/questions/66779282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10275606/"
] | Don't only append all ratings to one list, but create a list for every user:
```py
with open('a.json') as f:
ratings = [] #to store ratings of all user
js = json.load(f)
for a in js['Rating']:
rating = [] #to store ratings of single user
for rate in a['rating']:
rating.append(rate['rating'])
ra... | A simple one-liner
```
all_ratings = [list(map(lambda x: x['rating'], r['rating'])) for r in js['Rating']]
```
Explanation
```
all_ratings = [
list( # Converts map to list
map(lambda x: x['rating'], r['rating']) # Get attribute from list of dict
) for r in j... | 14,587 |
54,623,084 | I'm trying to create a function in python that will print out the anagrams of words in a text file using dictionaries. I've looked at what feels like hundreds of similar questions, so I apologise if this is a repetition, but I can't seem to find a solution that fits my issue.
I understand what I need to do (at least, ... | 2019/02/11 | [
"https://Stackoverflow.com/questions/54623084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11041870/"
] | I'm not sure about the output format. In my implementation, all anagrams are printed out in the end.
```
with open('words.txt', 'r') as fp:
line = fp.readlines()
def make_anagram_dict(line):
d = {} # avoid using 'dict' as variable name
for word in line:
word = word.lower() # call lower() only o... | Your code is pretty much there, just needs some tweaks:
```
import re
def make_anagram_dict(words):
d = {}
for word in words:
word = word.lower() # call lower() only once
key = ''.join(sorted(word)) # make the key
if key in d: # check if it's in dictionary already
... | 14,590 |
57,876,971 | I have a project for one of my college classes that requires me to pull all URLs from a page on the U.S. census bureau website and store them in a CSV file. For the most part I've figured out how to do that but for some reason when the data gets appended to the CSV file, all the entries are being inserted horizontally.... | 2019/09/10 | [
"https://Stackoverflow.com/questions/57876971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10912876/"
] | You can try:
```
colSums(df1[,2:4]>0)
```
Output:
```
var1 var2 var3
4 4 5
``` | One brutal solution is with `apply` function
```
apply(df1[ ,2:ncol(df1)], 2, function(x){sum(x != 0)})
``` | 14,593 |
48,402,276 | I am taking a Udemy course. The problem I am working on is to take two strings and determine if they are 'one edit away' from each other. That means you can make a single change -- change one letter, add one letter, delete one letter -- from one string and have it become identical to the other.
Examples:
```
s1a = "a... | 2018/01/23 | [
"https://Stackoverflow.com/questions/48402276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7535419/"
] | This fails to pass this test, because you only look at *unique characters*:
```
>>> s1 = 'abc'
>>> s2 = 'bcc'
>>> set(s1).symmetric_difference(s2)
{'a'}
```
That's a set of length 1, but there are **two** characters changed. By converting to a set, you only see that there is at least one `'c'` character in the `s2` ... | Here's a solution using differences found by list comprehension.
```
def one_away(s1, s2):
diff1 = [el for el in s1 if el not in s2]
diff2 = [el for el in s2 if el not in s1]
if len(diff1) < 2 and len(diff2) < 2:
return True
return False
```
Unlike a set-based solution, this one doesn't lose ... | 14,598 |
54,938,607 | I have already read answer of this question [Image.open() cannot identify image file - Python?](https://stackoverflow.com/q/19230991/9235408), that question was solved by using `from PIL import Image`, but my situation is different. I am using `image_slicer`, and there I am getting these errors:
```
Traceback (most re... | 2019/03/01 | [
"https://Stackoverflow.com/questions/54938607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9235408/"
] | [Image slicer](https://image-slicer.readthedocs.io/en/latest/) is not intended for reading `nii` format. Here is the [list](https://pillow.readthedocs.io/en/5.1.x/handbook/image-file-formats.html#image-file-formats) of supported formats. | This error also occurs whenever the image file itself is corrupted. I once accidentally was in the process of deleting the subject image, until canceling mid-way through.
TL;DR - open image file to see if it's ok. | 14,601 |
3,561,221 | this is similar to the question in [merge sort in python](https://stackoverflow.com/questions/3559807/merge-sort-in-python)
I'm restating because I don't think I explained the problem very well over there.
basically I have a series of about 1000 files all containing domain names. altogether the data is > 1gig so I'm ... | 2010/08/24 | [
"https://Stackoverflow.com/questions/3561221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/410296/"
] | Whether you're able to keep 1000 files at once is a separate issue and depends on your OS and its configuration; if not, you'll have to proceed in two steps -- merge groups of N files into temporary ones, then merge the temporary ones into the final-result file (two steps should suffice, as they let you merge a total o... | You want to use merge sort, e.g. `heapq.merge`. I'm not sure if your OS allows you to open 1000 files simultaneously. If not you may have to do it in 2 or more passes. | 14,602 |
15,351,515 | I wrote my own implementation of the `ISession` [interface](http://docs.pylonsproject.org/projects/pyramid/en/1.0-branch/_modules/pyramid/interfaces.html#ISession) of Pyramid which should store the Session in a database. Everything works real nice, but somehow `pyramid_tm` throws up on this. As soon as it is activated ... | 2013/03/12 | [
"https://Stackoverflow.com/questions/15351515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1326104/"
] | I believe what you're seeing here is a quirk to the fact that response callbacks and finished callbacks are actually executed after tweens. They are positioned just between your app's egress, and middleware. `pyramid_tm`, being a tween, is committing the transaction before your response callback executes - causing the ... | I first tried with registering a tween and it worked somehow, but the data did not get saved. I then stumpled upon the [SQLAlchemy Event System](http://docs.sqlalchemy.org/en/latest/core/event.html). I found the [after\_commit](http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.SessionEvents.aft... | 14,611 |
51,118,801 | i am very new in python (and programming in general) and here is my issue. i would like to replace (or delete) a part of a string from a txt file which contains hundreds or thousands of lines. each line starts with the very same string which i want to delete.
i have not found a method to delete it so i tried a replac... | 2018/06/30 | [
"https://Stackoverflow.com/questions/51118801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8741601/"
] | >
> each line starts with the very same string which i want to delete.
>
>
>
The problem is you're passing a string `"text_to_replace"` rather than the variable `text_to_replace`.
But, for this specific problem, you could just remove the first *n* characters from each line:
```
text_to_replace = "Chart: Bar Back... | If you quote a variable it becomes a string literal and won't be evaluated as a variable.
Change your line for replacement to:
```
new_line = each_line.replace(text_to_replace, " ")
``` | 14,612 |
69,054,921 | I want to run a docker container for `Ganache` on my MacBook M1, but get the following error:
```
The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
```
After this line nothing else will happen anymore and the whole process i... | 2021/09/04 | [
"https://Stackoverflow.com/questions/69054921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6727976/"
] | On M1 MacBook Pro, I've had success using `docker run --platform linux/amd64`
**Example**
```
docker run --platform linux/amd64 node
``` | With docker-compose you also have the `platform` option.
```
version: "2.4"
services:
zookeeper:
image: confluentinc/cp-zookeeper:7.1.1
hostname: zookeeper
container_name: zookeeper
platform: linux/amd64
ports:
- "2181:2181"
``` | 14,613 |
49,924,302 | I have couple of date string with following pattern MM DD(st, nd, rd, th) YYYY HH:MM am. what is the most pythonic way for me to replace (st, nd, rd, th) as empty string ''?
```
s = ['st', 'nd', 'rd', 'th']
string = 'Mar 1st 2017 00:00 am'
string = 'Mar 2nd 2017 00:00 am'
string = 'Mar 3rd 2017 00:00 am'
string = 'Mar... | 2018/04/19 | [
"https://Stackoverflow.com/questions/49924302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6373357/"
] | The most pythonic way is to use `dateutil`.
```
from dateutil.parser import parse
import datetime
t = parse("Mar 2nd 2017 00:00 am")
# you can access the month, hour, minute, etc:
t.hour # 0
t.minute # 0
t.month # 3
```
And then, you can use `t.strftime()`, where the formatting of the resulting string is any of th... | You could use a regular expression as follows:
```
import re
strings = ['Mar 1st 2017 00:00 am', 'Mar 2nd 2017 00:00 am', 'Mar 3rd 2017 00:00 am', 'Mar 4th 2017 00:00 am']
for string in strings:
print(re.sub('(.*? \d+)(.*?)( .*)', r'\1\3', string))
```
This would give you:
```none
Mar 1 2017 00:00 am
... | 14,623 |
30,522,420 | I'm going through the new book "Data Science from Scratch: First Principles with Python" and I think I've found an errata.
When I run the code I get `"TypeError: 'int' object has no attribute '__getitem__'".` I think this is because when I try to select `friend["friends"]`, `friend` is an integer that I can't subset. ... | 2015/05/29 | [
"https://Stackoverflow.com/questions/30522420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469211/"
] | Yes, you've found an incorrect piece of code in the book.
Implementation for `friends_of_friend_ids_bad` function should be like this:
```
def friends_of_friend_ids_bad(user):
#foaf is friend of friend
return [users[foaf]["id"]
for friend in user["friends"]
for foaf in users[friend]["friends"... | The error is on:
```
return [foaf["id"] for friend in user["friends"] for foaf in friend["friends"]]
```
In the second for loop, you're trying to access `__getitem__` of `users[0]["friends"]`, which is exactly 5 (ints don't have `__getitem__`).
You're trying to store on the list `foaf["id"]` for each friend in `use... | 14,624 |
65,154,521 | When I want to selenium click this code button , selenium write me this error
This is my code:
```
#LOGIN IN WEBSITE
browser = webdriver.Firefox()
browser.get("http://class.apphafez.ir/")
username_input = browser.find_element_by_css_selector("input[name='UserName']")
password_input = browser.find_ele... | 2020/12/05 | [
"https://Stackoverflow.com/questions/65154521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13937766/"
] | You were close enough. The value of the *class* attribute is **`btn btn-palegreen enterClassBtn`** but not `btn btn- palegreen enterClassBtn` and you can't add extra spaces within the attribute value.
---
Solution
--------
To click on the element you need to induce [WebDriverWait](https://stackoverflow.com/questions... | Multiple class names for css values are tough to handle. usually easiest way is to use a css selector:
```
button.btn.btn-palegreen.enterClassBtn
```
Specifically:
```
go_to_class = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR , ("button.btn.btn-palegreen.enterClassBtn"))))
```
See also [How to get elem... | 14,625 |
33,801,170 | Let's say I have an ndarray with 100 elements, and I want to select the first 4 elements, skip 6 and go ahead like this (in other words, select the first 4 elements every 10 elements).
I tried with python slicing with step but I think it's not working in my case. How can I do that? I'm using Pandas and numpy, can the... | 2015/11/19 | [
"https://Stackoverflow.com/questions/33801170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5580662/"
] | You could reshape the array to a `10x10`, then use slicing to pick the first 4 elements of each row. Then flatten the reshaped, sliced array:
```
In [46]: print a
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
50 ... | Use `% 10`:
```
print [i for i in range(100) if i % 10 in (0, 1, 2, 3)]
[0, 1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 23, 30, 31, 32, 33, 40, 41, 42, 43, 50, 51, 52, 53, 60, 61, 62, 63, 70, 71, 72, 73, 80, 81, 82, 83, 90, 91, 92, 93]
``` | 14,626 |
51,500,519 | I can't use boto3 to connect to S3 with a role arn provided 100% programmatically.
```python
session = boto3.Session(role_arn="arn:aws:iam::****:role/*****",
RoleSessionName="****")
s3_client = boto3.client('s3',
aws_access_key_id="****",
aws_s... | 2018/07/24 | [
"https://Stackoverflow.com/questions/51500519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6227500/"
] | You need to understand how temporary credentials are created.
First you need to create a client using your current access keys. These credentials are then used to verify that you have the permissions to call assume\_role and have the rights to issue credentials from the IAM role.
If someone could do it your way, ther... | Firstly, *never* put an Access Key and Secret Key in your code. Always store credentials in a `~/.aws/credentials` file (eg via `aws configure`). This avoids embarrassing situations where your credentials are accidentally released to the world. Also, if you are running on an Amazon EC2 instance, then simply assign an I... | 14,635 |
9,433,021 | Is there a way to group names together in python, to repeatedly assign to them *en masse*?
While we can do:
```
a,b,c = (1,2,3)
```
I would like to be able to do something like:
```
names = a,b,c
*names = (3,2,1) # this syntax doesn't work
a,b,c == (3,2,1) #=> True
```
Is there a built-in syntax for this? If n... | 2012/02/24 | [
"https://Stackoverflow.com/questions/9433021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21640/"
] | You should go one level up in your data abstraction. You are not trying to access the entries by their individual names -- you rather use `names` to denote the whole collection of values, so a simple list might be what you want.
If you want both, a name for the collection *and* names for the individual items, then a d... | You should use a [**`dict`**](http://docs.python.org/library/stdtypes.html#mapping-types-dict):
```
>>> d = {"a": 1, "b": 2, "c": 3}
>>> d.update({"a": 8})
>>> print(d)
{"a": 8, "c": 3, "b": 2}
``` | 14,636 |
40,367,569 | I am trying to set up a Python extension (Gambit, <http://gambit.sourceforge.net/gambit13/build.html>) and am getting an error when trying to build setup.py:
>
> Traceback (most recent call last): File "setup.py", line 32, in <module>
>
>
> m.Extension.**dict** = m.\_Extension.**dict**
>
>
> AttributeError: attri... | 2016/11/01 | [
"https://Stackoverflow.com/questions/40367569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2537443/"
] | You are getting **[NullPointerException](https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html)** at ***[android.support.v4.widget.drawerlayout](https://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html)***
>
> NullPointerException is thrown when an application attemp... | ```
android{
buildTypes{
release{
minifyEnabled false
}
}
}
```
Try this in your build.grade.
Or
Try to restart your Android Studio as well as your computer.As is known to all,Android Studio may perform stupid occasionally. | 14,646 |
55,373,867 | I have very basic producer-consumer code written with pika framework in python. The problem is - consumer side runs too slow on messages in queue. I ran some tests and found out that i can speed up the workflow up to 27 times with multiprocessing. The problem is - I don't know what is the right way to add multiprocessi... | 2019/03/27 | [
"https://Stackoverflow.com/questions/55373867",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7047471/"
] | Pika has extensive [example code](https://github.com/pika/pika/blob/0.13.1/examples/basic_consumer_threaded.py) that I recommend you check out. Note that this code is for **example** use only. In the case of doing work on threads, you will have to use a more intelligent way to manage your threads.
The goal is to not b... | ```
import pika
import json
from multiprocessing import Process
from datetime import datetime
from functions import download_xmls
import multiprocessing
import concurrent.futures
def do_job(body):
body = json.loads(body)
type = body[-1]['Type']
print('Object type in work currently ' + type)
cnums = [x[... | 14,651 |
42,740,284 | I have question that I am having a hard time understanding what the code might look like so I will explain the best I can. I am trying to view and search a NUL byte and replace it with with another NUL type byte, but the computer needs to be able to tell the difference between the different NUL bytes. an Example would ... | 2017/03/11 | [
"https://Stackoverflow.com/questions/42740284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7620511/"
] | If you are on Python 3, you should really work with `bytes` objects. Python 3 strings are sequences of unicode code points. To work with byte-strings, use `bytes` (which is pretty much the same as a Python 2 string, which used the "sequence of bytes" model).
```
>>> bytes([97, 98, 99])
b'abc'
>>>
```
Note, to write ... | another equivalent way to get the value of `\x00` in python is `chr(0)` i like that way a little better over the literal versions | 14,652 |
33,697,263 | i try to install snap7 (to read from a S7-1200) with it's python-snap7 0.4 wrapper but i get always a traceback with the following simple code.
```
from time import sleep
import snap7
from snap7.util import *
import struct
plc = snap7.client.Client()
```
Traceback:
```
>>>
Traceback (most recent call last):
Fi... | 2015/11/13 | [
"https://Stackoverflow.com/questions/33697263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4801693/"
] | After some try and error experiments and with some infos of snap7 involved developers, i fixed the problem. The folder where the snap7.dll and .lib file are located must be present in the Enviroment variables of Windows. Alternative you can copy the files to the Python install dir if you have checked the "add path" opt... | Try this:
Search the snap7 folder for snap7.dll and snap7.lib files
Copy the snap7.dll and snap7.lib into the "C:/PythonXX/site-packages/snap7 " directory and run you code again. You can figure out this in the common.py file in the same directory. | 14,653 |
39,457,209 | I am trying to do some white blob detection using OpenCV. But my script failed to detect the big white block which is my goal while some small blobs are detected. I am new to OpenCV, and am i doing something wrong when using simpleblobdetection in OpenCV? [Solved partially, please read below]
And here is the script:
... | 2016/09/12 | [
"https://Stackoverflow.com/questions/39457209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6779632/"
] | If you just want to detect the white rectangle you can try to set a higher threshold, e.g. 253, erase small object with an opening and take the biggest blob. I first smoothed your image, then thresholding it:
[](https://i.stack.imgur.com/UrrBT.png)
a... | You could try setting params.maxArea to something obnoxiously large (somewhere in the tens of thousands): the default may be something lower than the area of the rectangle you're trying to detect. Also, I don't know how true this is or not, but I've heard that detection by color is bugged with a logic error, so it may ... | 14,658 |
68,010,585 | I can edit python code in a folder located in a Docker Volume. I use Visual Studio Code and in general lines it works fine.
The only problem that I have is that the libraries (such as pandas and numpy) are not installed in the container that Visual Studio creates to mount the volume, so I get warning errors.
How to i... | 2021/06/16 | [
"https://Stackoverflow.com/questions/68010585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1362485/"
] | you can use this way. Put a img in div tag and use text-aling: center. There are many ways you can do this.
```css
.fotos-block{
text-align: center;
}
```
```html
<div class="fotos-block">
<img src = "https://www.imagemhost.com.br/images/2021/06/13/mail.png" class="fotos" id="foto1f">
</div>
``` | And you can also use this way to center the img.
```css
.fotos{
display: block;
margin: auto;
text-align: center;
}
``` | 14,659 |
69,726,911 | I need to return within this FOR only values equal to or less than 6 in each column.
```
colunas = list(df2.columns[8:19])
colunas
['Satisfação geral',
'Comunicação',
'Expertise da industria',
'Inovação',
'Parceira',
'Proatividade',
'Qualidade',
'responsividade',
'Pessoas',
'Expertise técnico',
'Pontuali... | 2021/10/26 | [
"https://Stackoverflow.com/questions/69726911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17161157/"
] | I found the solution: seems like AWS is using the term "Subnet Group" in multiple services. I created the group in the service "ElastiCache" but it needs to be created in service "DocumentDB" (see screenshot below).
[](https://i.stack.imgur.com/NGPT3.... | I had a similar issue. Before you create the cluster, you need to have a Security Group setup, and there, you should be able to change the VPC selected by default.
[](https://i.stack.imgur.com/lsPTl.png)
Additional info [here](https://docs.aws.amazon... | 14,660 |
68,736,258 | We successfully trained a TensorFlow model based on five climate features and one binary (0 or 1) label. We want an output for an outside input of five new climate variable values that will be inputted into model.predict(). However, we got an error when we tried to input an array of five values. Thanks in advance!
```... | 2021/08/11 | [
"https://Stackoverflow.com/questions/68736258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16637888/"
] | This is because of the non-blocking, asynchronous nature of the `con.query()` function call. It starts the asynchronous operation and then executes the lines of code after it. Then, sometime LATER, it calls its callback. So, in this code of yours with my adding logging:
```
router.post('/login', (req, res) => {
co... | It can be sometimes that the express session is saved when the out direct handler/function finished.
On that situation, if you want to save your session within a new async function, you should add the `next` function variable in your handler.
Then use it as the callback function to save you session.
It should look l... | 14,661 |
55,392,952 | I have a Python script that runs selenium webdriver that executes in the following steps:
1) Execute a for loop that runs for x number of times
2) Within the main for loop, selenium web driver finds buttons on the page using xpath
3) For each button found by selenium, the nested for loop clicks each button
4) Once a b... | 2019/03/28 | [
"https://Stackoverflow.com/questions/55392952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/601787/"
] | Finally instead of:
```py
conn2 = conn.connect_as_project(project_id)
```
I used:
```py
conn2 = openstack.connection.Connection(
region_name='RegionOne',
auth=dict(
auth_url='http://controller:5000/v3',
username=u_name,
password=password,
project_id=project_id,
user_d... | I did this just fine...the only difference is that the project is a new project and I have to give credentials to the user I was using.
It was something like that:
```py
project = sconn.create_project(
name=name, domain_id='default')
user_id = conn.current_user_id
user = conn.get_user(user_id)
roles = conn.list_r... | 14,662 |
40,307,635 | In the R xgboost package, I can specify `predictions=TRUE` to save the out-of-fold predictions during cross-validation, e.g.:
```
library(xgboost)
data(mtcars)
xgb_params = list(
max_depth = 1,
eta = 0.01
)
x = model.matrix(mpg~0+., mtcars)
train = xgb.DMatrix(x, label=mtcars$mpg)
res = xgb.cv(xgb_params, train, 1... | 2016/10/28 | [
"https://Stackoverflow.com/questions/40307635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/345660/"
] | I'm not sure if this is what you want, but you can accomplish this by using the sklearn wrapper for xgboost: (I know I'm using iris dataset as regression problem -- which it isn't but this is for illustration).
```
import xgboost as xgb
from sklearn.cross_validation import cross_val_predict as cvp
from sklearn import ... | This is possible with `xgboost.cv()` but it is a bit hacky. It uses the callbacks and ... a global variable which I'm told is not desirable.
```
def oof_prediction():
"""
Dirty global variable callback hack.
"""
global cv_prediction_dict
def callback(env):
"""internal function"""
... | 14,663 |
33,879,523 | is there a way in python to generate a continuous series of beeps in increasing amplitude and export it into a WAV file? | 2015/11/23 | [
"https://Stackoverflow.com/questions/33879523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5192982/"
] | I've based this on the answer to the previous question and added a lot of comments. Hopefully this makes it clear. You'll probably want to introduce a for loop to control the number of beeps and the increasing volume.
```
#!/usr/bin/python
# based on : www.daniweb.com/code/snippet263775.html
import math
import wave
... | I added minor improvements to the [JCx](https://stackoverflow.com/users/3818191/jcx) code above. As author said, its not cool to use global variables. So I wrapped his solution into class, and it works just fine:
```
import math
import wave
import struct
class BeepGenerator:
def __init__(self):
# Audio wi... | 14,666 |
3,263,665 | I am trying to create a line-by-line filter in python. However, `stdin.readlines()` reads all lines in before starting to process, and python runs out of memory (`MemoryError`).
How can I have *just one line* in memory at a time?
The kind of code I have:
```
for line in sys.stdin.readlines():
if( filter.apply( l... | 2010/07/16 | [
"https://Stackoverflow.com/questions/3263665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6610/"
] | ```
for line in sys.stdin:
...
```
Or call `.readline()` in a loop. | ```
import sys
while 1:
line = sys.stdin.readline()
if not line:
break
if (filter.apply(line)):
print(line)
``` | 14,667 |
62,232,923 | I'm pretty new to python but I need some help parsing a string with a unique structure. I have a CSV file with a column with the following structure:
```
[Chakroff, Alek; Young, Liane] Boston Coll, Chestnut Hill, MA 02167 USA; [Russell, Pascale Sophie] Univ Surrey, Guildford, Surrey, England; [Piazza, Jared] Univ Lanc... | 2020/06/06 | [
"https://Stackoverflow.com/questions/62232923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13694393/"
] | You can take advantage of the unique substring before the elements you want:
```
# split string on substring '; ['
for i in s.split('; ['):
# split each resulting string on space char, return last element of array
print(i.split()[-1])
USA
England
England
``` | You can use the split() method for strings
```
states = [person_record.split(",")[-1] for person_record in records.split("; [")]
```
Where records is the string you get from your input. | 14,668 |
51,688,822 | Can anybody help me please? I am new to machine learning Studio.
I am using free azure machine learning studio workspace
trying to use in cell run all got the following error.
```
ValueError Traceback (most recent call last)
<ipython-input-1-17afe06b8f16> in <module>()
1 from azur... | 2018/08/04 | [
"https://Stackoverflow.com/questions/51688822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5892761/"
] | I have same problem as you. I have contacted tech support so once I get an answer, I will update this post. Meanwhile, you can use this **WORKAROUND**:
Get missing parameters and input them as Strings.
```
ws = Workspace("[WORKSPACE_ID]", "[AUTH_TOKEN]")
```
Where to get them:
[WOKRSPACE\_ID]: Azure ML Studio ... | the easiest way is to right click on the data set you have and choose Generate Data Access Code, the system will do it for you and all you have to do is to copy it to the frame and it all will be there.
I hope this helps! | 14,670 |
46,230,413 | I'm trying to run DMelt programs (<http://jwork.org/dmelt/>) program using Java9 (JDK9), and it gives me errors such as:
```
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.python.core.PySystemState (file:/dmelt/jehep/lib/jython/jython.jar) to method java.io.Conso... | 2017/09/15 | [
"https://Stackoverflow.com/questions/46230413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8612074/"
] | To avoid this error, you need to redefine `maven-war-plugin` to a newer one. For example:
```xml
<plugins>
. . .
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
</plugins>
```
---
Works for `jdk-12`... | Since the Java update 9, the "illegal reflective access operation has occurred" warning occurs.
To remove the warning message. You can replace maven-compiler-plugin with maven-war-plugin and/or updating the maven-war-plugin with the latest version in your pom.xml. Following are 2 examples:
Change version from:
```xm... | 14,672 |
17,586,599 | Using win32com.client, I'm attempting to create a simple shortcut in a folder. The shortcut however I would like to have arguments, except I keep getting the following error.
```
Traceback (most recent call last):
File "D:/Projects/Ms/ms.py", line 153, in <module>
scut.TargetPath = '"C:/python27/python.exe" "D:/... | 2013/07/11 | [
"https://Stackoverflow.com/questions/17586599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/721386/"
] | Your code works for me without error. (Windows XP 32bit, Python 2.7.5, pywin32-216).
(I slightly modified your code because `TargetPath` should contain only executable path.)
```
import win32com.client
ws = win32com.client.Dispatch("wscript.shell")
scut = ws.CreateShortcut('run_idle.lnk')
scut.TargetPath = '"c:/pytho... | "..TargetPath should contain only [an] executable path." is incorrect in two ways :
1. The target may also contain the executable's arguments.
For instance, I have a file [ D:\DATA\CCMD\Expl.CMD ] whose essential line of code is
START Explorer.exe "%Target%"
An example of its use is
D:\DATA\CCMD\Expl.CMD "D:\DATA\... | 14,682 |
59,209,756 | I'm new to Django 1.11 LTS and I'm trying to solve this error from a very long time. Here is my code where the error is occurring:
model.py:
```
name = models.CharField(db_column="name", db_index=True, max_length=128)
description = models.TextField(db_column="description", null=True, blank=True)
created =... | 2019/12/06 | [
"https://Stackoverflow.com/questions/59209756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5368168/"
] | <https://www.anylogic.com/files/anylogic-professional-8.3.3.exe>
For any version, just put the version you want and you will likely be able to download it
if using mac:
<https://www.anylogic.com/files/anylogic-professional-8.3.3.dmg> | In addition to Felipe's answer, you can always ask
>
> support@anylogic.com
>
>
>
if you need *very* old versions. I believe that AL7.x is not available online anymore but they happily send the installers if you need them. | 14,683 |
7,454,590 | I'm trying to unit test a handler with webapp2 and am running into what has to be just a stupid little error.
I'd like to be able to use webapp2.uri\_for in the test, but I can't seem to do that:
```
def test_returns_200_on_home_page(self):
response = main.app.get_response(webapp2.uri_for('index'))
... | 2011/09/17 | [
"https://Stackoverflow.com/questions/7454590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/233242/"
] | I think the only option is to set a dummy request just to be able to create URIs for the test:
```
def test_returns_200_on_home_page(self):
// Set a dummy request just to be able to use uri_for().
req = webapp2.Request.blank('/')
req.app = main.app
main.app.set_globals(app=main.app, request=req)
r... | `webapp2.uri_for()` assumes that you are in a web request context and it fails because it cannot find the `request` object.
Instead of working around this you could think of your application as a black box and call it using literal URIs, like `'/'` as you mention it. After all, you want to simulate a normal web reques... | 14,684 |
45,949,105 | I had used created a GUI by wxpython to run stats model using statsmodels SARIMAX(). I put all five scripts in one file and tried to use
```
pyinstaller --onedir <mainscript.py>
```
to create compiled application.
After the pyinstaller process completed, I ran the generated application in dist file but it gave thi... | 2017/08/29 | [
"https://Stackoverflow.com/questions/45949105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644284/"
] | If you have dark background in your application and want to use light colors for your ngx charts then you can use this method. It will use official code for ngx dark theme and show light colors for the chart labels. You can also change the color code in sccss variables and things work as you need.
I solved it using th... | Axis ticks formatting can be done like this
<https://github.com/swimlane/ngx-charts/blob/master/demo/app.component.html>
this has individual element classes. | 14,685 |
30,489,449 | How can I see a warning again without restarting python. Now I see them only once.
Consider this code for example:
```
import pandas as pd
pd.Series([1]) / 0
```
I get
```
RuntimeWarning: divide by zero encountered in true_divide
```
But when I run it again it executes silently.
**How can I see the warni... | 2015/05/27 | [
"https://Stackoverflow.com/questions/30489449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3549680/"
] | >
> How can I see the warning again without restarting python?
>
>
>
As long as you do the following at the beginning of your script, you will not need to restart.
```
import pandas as pd
import numpy as np
import warnings
np.seterr(all='warn')
warnings.simplefilter("always")
```
At this point every time you a... | `warnings` is a pretty awesome standard library module. You're going to enjoy getting to know it :)
A little background
-------------------
The default behavior of `warnings` is to only show a particular warning, coming from a particular line, on its first occurrence. For instance, the following code will result in t... | 14,690 |
15,784,537 | Purpose: Given a PDB file, prints out all pairs of Cysteine residues forming disulfide bonds in the tertiary protein structure. Licence: GNU GPL Written By: Eric Miller
```
#!/usr/bin/env python
import math
def getDistance((x1,y1,z1),(x2,y2,z2)):
d = math.sqrt(pow((x1-x2),2)+pow((y1-y2),2)+pow((z1-z2),2));
retu... | 2013/04/03 | [
"https://Stackoverflow.com/questions/15784537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2176228/"
] | For me the indentation is broken within 'prettyPrint' and in '**main**'. Also no need to use ';'. Try this:
```
#!/usr/bin/env python
import math
# Input: Two 3D points of the form (x,y,z).
# Output: Euclidean distance between the points.
def getDistance((x1, y1, z1), (x2, y2, z2)):
d = math.sqrt(pow((x1 - x2), 2)... | This:
```
if __name__ == "__main__":
main()
```
Should be:
```
if __name__ == "__main__":
main()
```
Also, the python interpreter will give you information on the IndentationError *down to the line*. I strongly suggest reading the error messages provided, as developers write them for a reason. | 14,691 |
72,060,798 | In python I am trying to lookup the relevant price depending on qty from a list of scale prices. For example when getting a quotation request:
```
Product Qty Price
0 A 6
1 B 301
2 C 1
3 D 200
4 E 48
```
Price list with scale prices:
```
Product Scale Qty Scale Price... | 2022/04/29 | [
"https://Stackoverflow.com/questions/72060798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18991198/"
] | Try with `merge_asof`:
```
output = (pd.merge_asof(df2.sort_values("Qty"),df1.sort_values("Scale Qty"),left_on="Qty",right_on="Scale Qty",by="Product")
.sort_values("Product", ignore_index=True)
.drop("Scale Qty", axis=1)
.rename(columns={"Scale Price":"Price"}))
>>> output
Product Qt... | Assuming `df1` and `df2`, use `merge_asof`:
```
pd.merge_asof(df1.sort_values(by='Qty'),
df2.sort_values(by='Scale Qty').rename(columns={'Scale Price': 'Price'}),
by='Product', left_on='Qty', right_on='Scale Qty')
```
output:
```
Product Qty Scale Qty Price
0 C 1 1... | 14,693 |
58,143,742 | I'm working on a project using keras (python 3), and I've encountered a problem - I've installed using pip tensorflow, and imported it into my prject, but whenether I try to run it, I get an error saying:
```
ModuleNotFoundError: No module named 'tensorflow'
```
it seems my installation completed successfully, and I... | 2019/09/28 | [
"https://Stackoverflow.com/questions/58143742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9126289/"
] | Use [`Series.str.replace`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html) with replace `uppercase` by same vales with space before and then remove first space:
```
df = pd.DataFrame({'U.N.Region':['WestAfghanistan','NorthEastAfghanistan']})
df['U.N.Region'] = df['U.N.Region'... | Another option would be,
```
import pandas as pd
import re
df = pd.DataFrame({'U.N.Region': ['WestAfghanistan', 'NorthEastAfghanistan']})
df['U.N.Region'] = df['U.N.Region'].str.replace(
r"(?<=[a-z])(?=[A-Z])", " ")
print(df)
``` | 14,694 |
40,138,090 | My data is organized in a dataframe:
```
import pandas as pd
import numpy as np
data = {'Col1' : [4,5,6,7], 'Col2' : [10,20,30,40], 'Col3' : [100,50,-30,-50], 'Col4' : ['AAA', 'BBB', 'AAA', 'CCC']}
df = pd.DataFrame(data=data, index = ['R1','R2','R3','R4'])
```
Which looks like this (only much bigger):
```
Co... | 2016/10/19 | [
"https://Stackoverflow.com/questions/40138090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2301970/"
] | The tint property does not affect the color of the title. To set the title color (along with other attributes like font) globally, you can set the `titleTextAttributes` property of the `UINavigationBar` appearance to suit your needs. Just place this code in your AppDelegate or somewhere else appropriate that gets calle... | No you work correctly. But you should to set color for second view. You can use this code to solve your problem.
In second view write this code to set color and font for your navigation title.
---
```
navigationController!.navigationBar.titleTextAttributes = ([NSFontAttributeName: UIFont(name: "Helvetica", size: 25)!... | 14,697 |
29,035,115 | I am working with an existing SQLite database and experiencing errors due to the data being encoded in CP-1252, when Python is expecting it to be UTF-8.
```
>>> import sqlite3
>>> conn = sqlite3.connect('dnd.sqlite')
>>> curs = conn.cursor()
>>> result = curs.execute("SELECT * FROM dnd_characterclass WHERE id=802")
Tr... | 2015/03/13 | [
"https://Stackoverflow.com/questions/29035115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1191425/"
] | SQLAlchemy and SQLite are behaving normally. The solution is to fix the non-UTF-8 data in the database.
I wrote the below, drawing inspiration from <https://stackoverflow.com/a/2395414/1191425> . It:
* loads up the target SQLite database
* lists all columns in all tables
* if the column is a `text`, `char`, or `clob`... | If you have a connection URI then you can add the following options to your DB connection URI:
```
DB_CONNECTION = mysql+pymysql://{username}:{password}@{host}/{db_name}?{options}
DB_OPTIONS = {
"charset": "cp-1252",
"use_unicode": 1,
}
connection_uri = DB_CONNECTION.format(
username=???,
...,
opti... | 14,698 |
58,647,020 | I am trying to run the cvxpy package in an AWS lambda function. This package isn't in the SDK, so I've read that I'll have to compile the dependencies into a zip, and then upload the zip into the lambda function.
I've done some research and tried out the links below, but when I try to pip install cvxpy I get error mes... | 2019/10/31 | [
"https://Stackoverflow.com/questions/58647020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10756193/"
] | For installing `cvxpy` on windows it requires c++ build tools (please refer: <https://buildmedia.readthedocs.org/media/pdf/cvxpy/latest/cvxpy.pdf>)
On Windows:
-----------
* I created a lambda layer python directory structure `python/lib/python3.7/site-packages` (refer: <https://docs.aws.amazon.com/lambda/latest/dg/c... | You can wrap all your dependencies along with lambda source into a single zipfile and deploy it. Doing this, you will end up having additional repetitive code in multiple lambda functions. Suppose, if more than one of your lambda functions needs the same package `cvxpy`, you will have to package it twice for both the f... | 14,699 |
13,391,444 | I'm trying to use [PySide](http://qt-project.org/wiki/PySideDocumentation) so I did a `brew install pyside pyside-tools`. However, I get the following error:
```
>>> from PySide.QtGui import QApplication
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/Library/Python/2.7/si... | 2012/11/15 | [
"https://Stackoverflow.com/questions/13391444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/384964/"
] | I was getting the same error, and I'm using Python installed via Homebrew. I found two PySide libraries in /Library/Python/2.7/site-packages/ . Moving them out of the way, and re-building/installing PySide through Homebrew worked. | I tried the import you gave - I am using same system environment. It worked fine. try: brew update and re-install. | 14,700 |
61,698,002 | From python in a nutshell,
>
> Where C is a class, the statement `x=C(23)` is equivalent to:
>
>
>
> ```
> x = C.__new__(C, 23)
> if isinstance(x, C): type(x).__init__(x, 23)
>
> ```
>
>
From my understanding `object.__new__` creates a new, uninitialized instance of the class it receives as its first argumen... | 2020/05/09 | [
"https://Stackoverflow.com/questions/61698002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13432122/"
] | >
> Isn't it obvious that `__new__` will return a object of type C.
>
>
>
Not at all. The following is valid:
```
>>> class C:
... def __new__(cls):
... return "not a C"
... def __init__(self):
... print("Never called")
...
>>> C()
'not a C'
```
When you override `__new__`, you will *probably* retur... | [isinstance(a, b)](https://docs.python.org/3/library/functions.html#isinstance) is used to check if a is instance of b. Not sure why you checking it after creation. Magical methods can be redefined. Although in normal cases isinstance() is needed to check dynamic data. | 14,702 |
44,718,204 | I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.
```
log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
```
On next day I want to create a new log file with next day's date -
```
log file name - my_app_20... | 2017/06/23 | [
"https://Stackoverflow.com/questions/44718204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6102259/"
] | You have to create a `TimedRotatingFileHandler`:
```
from logging.handlers import TimedRotatingFileHandler
logname = "my_app.log"
handler = TimedRotatingFileHandler(logname, when="midnight", interval=1)
handler.suffix = "%Y%m%d"
logger.addHandler(handler)
```
This piece of code will create a `my_app.log` but the log... | I suggest you take a look at `logging.handlers.TimedRotatingFileHandler`.
I think it's what you're looking for. | 14,703 |
60,949,588 | I have a python script that does some GUI test on a chromium application. Sometimes this application does not load up correctly and for this reason the GUI test will not pass, but a simple restart of this application can fix the problem.
What I currently have is something like this:
```
def test():
...do some set... | 2020/03/31 | [
"https://Stackoverflow.com/questions/60949588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12200507/"
] | In OpenCV, the given threshold options (e.g. cv.THRESH\_BINARY or cv.THRESH\_BINARY\_INV) are actually constant integer values. You are trying to use strings instead of these integer values. That is the reason why you get the Type Error. If you want to apply all these different thresholds in a loop, one option is to cr... | This might be related: [OpenCV Thresholding example](https://docs.opencv.org/master/d7/d4d/tutorial_py_thresholding.html)
First off, there is no need to use `range`, you can simply do `for flag in titles:` and pass `flag`. Have you checked if your image is loaded correctly? Are you sure that your flag is repsonsible f... | 14,712 |
29,959,550 | I'm trying to fetch forms for floorplans for individual property's. I can check that the object exists in the database, but when I try to create a form with an instance of it I receive this error:
```
Traceback:
File "/Users/balrog911/Desktop/mvp/mvp_1/lib/python2.7/site-packages/django/core/handlers/base.py" in get_r... | 2015/04/30 | [
"https://Stackoverflow.com/questions/29959550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4847831/"
] | ```
NSString *n = [NSString stringWithFormat:@"%@",@"http://somedomain.com/api/x?q={\"order_by\":[{\"field\":\"t\",\"direction\":\"desc\"}]}"];
NSURL *url = [NSURL URLWithString:[n stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@",url);
``` | The proper way to compose a URL from strings is to use [NSURLComponents](https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLComponents_class/index.html) helper class.
The reason for this seemingly elaborate approach is that each component of a URL (see [RFC 3986](https://www.rfc-editor.org... | 14,714 |
58,472,090 | I am trying to load a pickle object in R, using the following process found online.
First, I create a Python file called: "pickle\_reader.py":
```py
import pandas as pd
def read_pickle_file(file):
pickle_data = pd.read_pickle(file)
return pickle_data
```
Then, I run the following R code:
```
install.packag... | 2019/10/20 | [
"https://Stackoverflow.com/questions/58472090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11898786/"
] | If you want to insert a python package into a different environment, which in this case is R, you must search how to install python packages in R. In this case, looking at the [CRAN webpage](https://cran.r-project.org/web/packages/reticulate/vignettes/python_packages.html) you can see that in order to install pandas in... | Make sure that pandas installed. I suggest using conda environment. I read the pickle applying below steps:
* Create conda environment and install necessary packages.
* Then in R, you can set the right python (which is python in your conda env)
```
Sys.setenv(RETICULATE_PYTHON = "~/anaconda3/envs/your_env/bin/pyt... | 14,715 |
19,427,685 | i have problems with the array indexes in python.
at function readfile it crashes and prints: **"list index out of range"**
```
inputarr = []
def readfile(filename):
lines = readlines(filename)
with open(filename, 'r') as f:
i = 0
j= 0
k = 0
for line in f:
li... | 2013/10/17 | [
"https://Stackoverflow.com/questions/19427685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2890530/"
] | I added the javafx runtime separately to the pom as below and it worked:
```
<dependency>
<groupId>javafx</groupId>
<artifactId>jfxrt</artifactId>
<version>${javafx.min.version}</version>
<scope>system</scope>
<systemPath>${java.home}\lib\jfxrt.jar</systemPath>
</depend... | From [*What is JavaFX?*](http://docs.oracle.com/javafx/2/overview/jfxpub-overview.htm#A1095238):
>
> JavaFX 2.2 and later releases are fully integrated with the Java SE 7 Runtime Environment (JRE) and the Java Development Kit (JDK).
>
>
>
This means you should be able to just use the `javafx.*` packages without a... | 14,718 |
53,961,912 | Using django and python, I am building a web app that tracks prices. The user is a manufacturer and will want reports. Each of their products has a recommended price. Each product could have more than one seller, and each seller could have more than one product. My question is, where do I store the prices, especially t... | 2018/12/28 | [
"https://Stackoverflow.com/questions/53961912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5096832/"
] | You're not adequately representing the one-to-many relationship between products and sellers. Your product table has the seller\_id and the seller\_price, but if one product is sold by many sellers, it cannot.
Instead of duplicating product entries so the same product can have multiple sellers, what you need is a tabl... | This is a Data Warehouse question.
I would recommend putting prices on a Fact as measures and having only attributes on the Dimensions.
Dimensions:
* Product
* Seller
* Manufacturer
Fact (Columns):
* List item
* Seller Price
* List item
* MRSP
* Product ID
* Seller ID
* Manufacturer ID
* Timestamp | 14,720 |
8,584,377 | G'Day,
I have a number of Django projects and a number of other Python projects as git repositories. I have pre-commit hook that runs Pylint on my code before allowing me to commit it - this hook doesn't know whether the project is a Django application or a vanilla Python project.
For all my Django projects, I have... | 2011/12/21 | [
"https://Stackoverflow.com/questions/8584377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/47825/"
] | Take a look at init\_hook in pylint configuration file.
```
init-hook=import sys; sys.path.insert(0, 'my_django_project/apps');
```
You will obviously need a configuration file per Django application, and run pylint as, e.g.
```
pylint --rcfile=pylint.conf my_django_project
``` | Maybe this doesn't fully answer your question, but I suggest to use [django-lint](http://chris-lamb.co.uk/projects/django-lint/), to avoid warnings like:
```
F: 4: Unable to import 'myapp.views'
E: 15: MyClass.my_function: Class 'MyClass' has no 'objects' member
E: 77: MyClass.__unicode__: Instance of 'MyClass' has n... | 14,723 |
61,986,195 | I have this python code that predicts the trade calls with the Bollinger band values and the Close Price.
```html
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
lr1 = LogisticRegression()
x = df[['Lower_Band','Upp... | 2020/05/24 | [
"https://Stackoverflow.com/questions/61986195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9471113/"
] | As described by KolaB, you should use the `random_state` parameter of `train_test_split` to make results reproducible. But actually, you mentioned that your results vary between 0.3 and 0.8 in accuracy score. This is a strong indicator that your results depend on a particular random choice for the test set. I would, th... | Your problem is most probably in `train_test_split`. You are not initialising the random state that ensures you get reproducible results. Try changing the line with this function to:
```
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3, random_state=1)
```
Also see scikit learn documentation on the [... | 14,725 |
26,450,336 | I have this python code. And whenever i start the webbserver and go to the website i don't get the message " test ", just internal server error. How come? what am i doing wrong. Whenever i go to the website its a GET request right, so it should go into domain() function and give me the text " test "
```
@app.route("/... | 2014/10/19 | [
"https://Stackoverflow.com/questions/26450336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4153021/"
] | I am also new to Android Reversing , and I have spent some time searching for simple understanding of Smali code and found this :
note class structure is L;
==========================
```
Lcom/breakapp/dd/mymod/Processor;->l:I
```
original java file name
=======================
```
.source "example.java"
```
the... | You may want to read the dalvik bytecode doc's since they are more detailed then the documentation you can find about smali.
Anyway, I am also in the process of learning smali so, probably, I can't give you the best answer but maybe this will help.
Let's start by looking at what iput does:
>
> iput vx,vy, field\_id
>... | 14,726 |
61,442,421 | I am using the combination of **request** and **beautifulsoup** to develop a web-scraping program in python.
Unfortunately, I got 403 problem (even using **header**).
Here my code:
```
from bs4 import BeautifulSoup
from requests import get
headers_m = ({'User-Agent':
'Mozilla/5.0 (Windows NT 6.1) AppleWe... | 2020/04/26 | [
"https://Stackoverflow.com/questions/61442421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13378861/"
] | This is not general python question. The site blocks such straightforward attempts of **scraping**, you need to find a set of headers (specific for this site) that will pass validation.
Regards, | Simply use `Chrome` as `User-Agent`.
```
from bs4 import BeautifulSoup
BeautifulSoup(requests.get("https://...", headers={"User-Agent": "Chrome"}).content, 'html.parser')
``` | 14,727 |
66,254,984 | I have a list of dicts in python which look like these:
```py
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
```
I want to sort them by day of week such that the result is
```py
[{'day' : 'Monday' , 'workers' : ['Kelly']},
{'day' : 'Wednesday' , 'workers' : ... | 2021/02/18 | [
"https://Stackoverflow.com/questions/66254984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6415973/"
] | Use a lambda function that extracts the weekday name from the dictionary and then returns the index as in your linked question.
```
weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"]
list_of_dicts =
[{'day' : 'Wednesday' , 'workers' : ['John' , 'Smith']} ,
{'day' : 'Monday' , 'workers' : ['Kelly']}]
list_of_dic... | The same basic approach that the example you link to uses will work for your list of dictionaries case. The trick is, you need to extract the day value from the dictionaries within the list to make it work. A `lambda` expression used for the `key` parameter is one way to do that.
Example:
```
day_order = ["Monday", "... | 14,728 |
12,343,261 | OK, so I went on <http://wiki.vg/Protocol>, but I don't understand how to send the packets through a socket to a Minecraft server. I would like to know if it is possible, and if it is how, to send Minecraft packets through a Python socket to a Minecraft server, as if the socket was the Minecraft client. I want to see i... | 2012/09/09 | [
"https://Stackoverflow.com/questions/12343261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1983840/"
] | Well I'd start with [this](https://gist.github.com/1209061) which sends a packet. It's linked to from the same page you mention. Then adjust the packet ID and the data you add to the stream. | No, as a Minecraft server is nothing but a host listening to a TCP socket.
You're better off looking for a Python TCP/sockets tutorial in general, or a Minecraft client/bot library. | 14,734 |
59,416,899 | We use ndb datastore in our current python 2.7 standard environment. We migrating this application to python 3.7 standard environment with firestore (native mode).
We use pagination on ndb datastore and construct our query using fetch.
```
query_results , next_curs, more_flag = query_structure.fetch_page(10)
```
T... | 2019/12/19 | [
"https://Stackoverflow.com/questions/59416899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3647998/"
] | There is no direct equivalent in Firestore pagination. What you can do instead is fetch one more document than the N documents that the page requires, then use the presence of the N+1 document to determine if there is "more". You would omit the N+1 document from the displayed page, then start the next page at that N+1 ... | I build a custom firestore API not long ago to fetch records with pagination. You can take a look at the [repository](https://github.com/vwt-digital/firestore-api). This is the story of the learning cycle I went through:
My first attempt was to use limit and offset, this seemed to work like a charm, but then I walked ... | 14,735 |
1,668,223 | I am in the process of coding an app which has to get the metadata (author,version..etc) out of several modules (.py files) and display them. The user selects a script and the script is executed. (New scripts can be added and old ones be taken of from the target folder just like a plugin system).
Firstly I import a sc... | 2009/11/03 | [
"https://Stackoverflow.com/questions/1668223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200816/"
] | i think [this post](http://mail.python.org/pipermail/tutor/2006-August/048596.html) should help you
edit:
to secure the availability of this information (in case the link dies or something similar) i will include the original message from the [tutor mailing list](http://mail.python.org/mailman/listinfo/tutor) here:
-... | Suggestion: Import your modules dynamically using `__import__`
E.g.
```
module_list = ['os', 'decimal', 'random']
for module in module_list:
x = __import__(module)
print 'name: %s - module_obj: %s' % (x.__name__, x)
```
Will produce:
```
name: os - module_obj: <module 'os' from '/usr/lib64/python2.4/os.pyc... | 14,736 |
55,767,411 | I have an potentially infinite python 'while' loop that I would like to keep running even after the main script/process execution has been completed. Furthermore, I would like to be able to later kill this loop from a unix CLI if needed (ie. kill -SIGTERM PID), so will need the pid of the loop as well. How would I acco... | 2019/04/19 | [
"https://Stackoverflow.com/questions/55767411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998671/"
] | In python, parent processes attempt to kill all their daemonic child processes when they exit. However, you can use `os.fork()` to create a completely new process:
```
import os
pid = os.fork()
if pid:
#parent
print("Parent!")
else:
#child
print("Child!")
``` | `Popen` returns an object which has the `pid`. According to the [doc](https://docs.python.org/3/library/subprocess.html#subprocess.Popen)
>
> Popen.pid
> The process ID of the child process.
>
>
> Note that if you set the shell argument to True, this is the process ID of the spawned shell.
>
>
>
You would need... | 14,741 |
10,649,623 | I have a web app that uses google app engine .In ubuntu ,I start the app engine using
```
./dev_appserver.py /home/me/dev/mycode
```
In the mycode folder ,I have app.yml and the python files of the web app.In the web app code,I have used logging to write values of some variables like
```
import logging
LOG_FILENAM... | 2012/05/18 | [
"https://Stackoverflow.com/questions/10649623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1291096/"
] | Did you read this <https://developers.google.com/appengine/articles/logging> as I understand you must not declare your own log file | I have the same environment (Ubuntu, python, gae) and ran into similar issues with logging.
You can't log to local file as stated here: <https://developers.google.com/appengine/docs/python/overview>
>
> "The sandbox ensures that apps can only perform actions that do not interfere with the performance and scalability... | 14,742 |
6,069,690 | I have a basic python question. I'm working on a class `foo` and I use `__init__():` to do some actions on a value:
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
```
When I execute the code I get: `NameError: name ... | 2011/05/20 | [
"https://Stackoverflow.com/questions/6069690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/760797/"
] | Wrong indentation, it should be this instead, otherwise you're exiting the function.
```
class foo():
def __init__(self,bar=None):
self.bar=bar
if bar is None:
isSet=False
else:
isSet=True
print isSet
``` | The indentation of the final line makes it execute in the context of the class and not `__init__`. Indent it one more time to make your program work. | 14,743 |
37,906,459 | I have a text file. The guts of it look like this/ all of it looks like this (has been edited. This was also not what it initially looked like)
```
(0, 16, 0)
(0, 17, 0)
(0, 18, 0)
(0, 19, 0)
(0, 20, 0)
(0, 21, 0)
(0, 22, 0)
(0, 22, 1)
(0, 22, 2)
(0, 23, 0)
(0, 23, 4)
(0, 24, 0)
(0, 25, 0)
(0, 25, 1)
(0... | 2016/06/19 | [
"https://Stackoverflow.com/questions/37906459",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6306510/"
] | As @TimPietzcker suggested and trusting the file to only have these fixed representations of integers in comma separated triplets, surrounded by parentheses, a simple parser in one go (OP's question also had a greed "read" of file into memors):
```
#! /usr/bin/env python
from __future__ import print_function
infile =... | Only need small modification.You can try this.
```
om_set = set(eval(open('abc.txt').read()))
```
**Result**
```
{(0, 19, 0),
(0, 20, 0),
(0, 21, 1),
(0, 22, 0),
(0, 24, 3),
(0, 27, 0),
(0, 29, 2),
(0, 35, 2)}
```
**Edit**
Here is the working of code in in `IPython` prompt.
```
In [1]: file_ = open('abc.... | 14,751 |
59,538,746 | A use case of the `super()` builtin in python is to call an overridden method. Here is a simple example of using `super()` to call `Parent` class's `echo` function:
```py
class Parent():
def echo(self):
print("in Parent")
class Child(Parent):
def echo(self):
super().echo()
print("in Ch... | 2019/12/31 | [
"https://Stackoverflow.com/questions/59538746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3411556/"
] | If you don't pass the arguments, Python 3 makes an effort to provide them for you. It's a little kludgy, but it *usually* works. Essentially, it just assumes the first parameter to your method is `self` (the second argument to `super`), and when the class definition completes, it provides a virtual closure scope for an... | In Python 3, `super()` with zero arguments is already the shortcut for `super(__class__, self)`. See [PEP3135](https://www.python.org/dev/peps/pep-3135/) for complete explanation.
This is not the case for Python 2, so I guess that most code examples you found were actually written for Python 2 (or Python2+3 compatible... | 14,752 |
65,784,777 | I have a python script which pushes data to another system. If it cannot push data for whatever reason then it will exit with non-zero status code otherwise it will not.
I am using my python script in my below shell script.
```
export NAME="${CI_COMMIT_REF_NAME//\//-}-1${CI_PIPELINE_IID}"
for environment in dev stage... | 2021/01/19 | [
"https://Stackoverflow.com/questions/65784777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14431930/"
] | Use a conditional operator to set a variable.
```
failed=false
for environment in dev stage; do
FILE_NAME="${NAME}-${environment}.tgz";
python helper.py push ${environment} master "${FILE_NAME}" || failed=true
python helper.py push ${environment} slave "${FILE_NAME}" || failed=true
done
if [ "$failed" = true ]
t... | >
> Basically somehow I need to store exit code of all the possible python line
>
>
>
Try this
```
declare -A result
for env in dev stage; do
FILE_NAME="$NAME-$env.tgz"
python helper.py push "$env" master "$FILE_NAME"; result["$FILE_NAME"]=$?
python helper.py push "$env" slave "$FILE_NAME"; result["$FILE_N... | 14,753 |
44,771,837 | I looked at some answers, including [this](https://stackoverflow.com/questions/37457277/remove-non-ascii-characters-from-csv-file-using-python) but none seem to answer my question.
Here are some example lines from CSV:
```
_id category
ObjectId(56266da778d34fdc048b470b) [{"group":"Home","id":"53cea0be763f4a6f4a8b459... | 2017/06/27 | [
"https://Stackoverflow.com/questions/44771837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1472743/"
] | As you open the input csv file in `rb` mode, I assume that you are using a Python2.x version. The good news is that you have no problem in the csv part because the csv reader will read plain bytes without trying to interpret them. But the `json` module will insist in decoding the text into unicode and by default uses u... | Most probably you have certain non-ascii characters in your csv content.
```
import re
def remove_unicode(text):
if not text:
return text
if isinstance(text, str):
text = str(text.decode('ascii', 'ignore'))
else:
text = text.encode('ascii', 'ignore')
remove_ctrl_chars_regex =... | 14,754 |
36,222,454 | Trying to solve a problem I asked earlier that couldn't be done with postgres sql query. So I moved on to trying to find another way to do it.
Essentially - what I have directory lets call it **server** that has multiple CSV files in it with the UUID as the name of the csv.
```
localhost Server]$ tree
.
├── 50333694... | 2016/03/25 | [
"https://Stackoverflow.com/questions/36222454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5992247/"
] | It sounds like you need something like this (untested):
```
mv server server.bk &&
mkdir server &&
awk -F, '
NR==FNR { map["server.bk/"$2".csv"]=$1; next }
FNR==1 { close(out); out="server/"map[FILENAME]".csv"; print "date,"map[FILENAME] > out }
{ print > out }
' servers.csv server.bk/*.csv
```
At the end of running... | Here's something I threw together in Python:
```
import csv
import os
import sys
# This is mostly for convenience. Python convention is that all caps
# are "constants", but there's nothing that enforces that ... | 14,755 |
41,237,314 | I have a python function (**pyfunc**):
```
def pyfunc(x):
...
return someString
```
I want to apply this function to every item in a mysql table column,
something like:
```
UPDATE tbl SET mycol=pyfunc(mycol);
```
This update includes tens of millions of records.
Is there an efficient way to do this?
**No... | 2016/12/20 | [
"https://Stackoverflow.com/questions/41237314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7319653/"
] | Even simplier (but for php5.5 and php7):
```
$numery = array_column(
$command->queryAll(),
'phone_number'
);
``` | Use below loop to get desired result
```
$numery = $command->queryAll();
$number_arr = array();
foreach($numery as $number)
{
array_push($number_arr,$number['phone_number']);
}
print_r($number_arr);
``` | 14,757 |
72,274,548 | When I run any kubectl command I get following WARNING:
```
W0517 14:33:54.147340 46871 gcp.go:120] WARNING: the gcp auth plugin is deprecated in v1.22+, unavailable in v1.25+; use gcloud instead.
To learn more, consult https://cloud.google.com/blog/products/containers-kubernetes/kubectl-auth-changes-in-gke
```
I ... | 2022/05/17 | [
"https://Stackoverflow.com/questions/72274548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1869399/"
] | I fixed this problem by adding the correct export in `.bashrc`
```
export USE_GKE_GCLOUD_AUTH_PLUGIN=True
```
After sourcing `.bashrc` with `. ~/.bashrc` and reloading cluster config with:
```
gcloud container clusters get-credentials clustername
```
the warning dissapeared:
```
user@laptop:/$ k get svc -A
NAMES... | Got a similar issue, while connecting to a fresh Kubernetes cluster having a version `v1.22.10-gke.600`
```
gcloud container clusters get-credentials my-cluster --zone europe-west6-b --project project
```
and got the below error, as seems like now its become error for the newer version
```
Fetching cluster endpoint... | 14,758 |
56,335,217 | I have already install mysql 5.1 on my windows 10 machine , and I can connect mysql from python by :
```
import pymysql
conn=pymysql.connect(host='localhost',user='root',password='MYSQLTB',db='shfuture')
```
then I download django frame and try to use it to connect mysql , what I do is :
create a my.cnf file cont... | 2019/05/28 | [
"https://Stackoverflow.com/questions/56335217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2031764/"
] | Yes, of course.You need to install 'mysqlclient' package or 'mysql-connector-python' package, with pip. | I guess you dont have `mysqlclient` python library installed in virtual environment.
Since you are using Windows, you need to download and install `mysqlclient` python library from [here](https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient) | 14,760 |
36,188,632 | this code works on the command line.
```
python -c 'import base64,sys; u,p=sys.argv[1:3]; print base64.encodestring("%s\x00%s\x00%s" % (u,u,p))' user pass
```
output is
dXNlcgB1c2VyAHBhc3M=
I am trying to get this to work in my script
```
test = base64.encodestring("{0}{0}{1}").format(acct_name,pw)
print test
`... | 2016/03/23 | [
"https://Stackoverflow.com/questions/36188632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3954080/"
] | You have a mistake in parenthesis. Instead of:
```
test = base64.encodestring("{0}{0}{1}").format(acct_name,pw)
```
(which first encodes "{0}{0}{1}" in base64 and **then** tries to substitute variables using `format`),
you should have
```
test = base64.encodestring("{0}{0}{1}".format(acct_name,pw))
```
(which fi... | Thanks SZYM i am all set. This is the code that gets it to work
```
test = base64.encodestring("{0}\x00{0}\x00{1}".format(acct_name,pw))
```
Turns out the hex \x00 is needed so program getting the hash knows where username stops and password begins.
-ALF | 14,768 |
14,800,708 | I am using the PyScripter integrated development environment and taking courses using Python 2.7.
Why does `number = input("some input text")` immediately display the python input dialog when the program is ran? Wouldn't we have to execute it? Because really, it's just setting a variable to a python input. It never sa... | 2013/02/10 | [
"https://Stackoverflow.com/questions/14800708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2059278/"
] | Indeed `number` is variable and nothing more. See [documentation on input()](http://docs.python.org/release/3.2/library/functions.html#input). | python is just kind off a simple language, it does not need variable declaration for example.
But it's better that it automatically asks your input instead that you have to write the code for starting the variable | 14,769 |
69,633,739 | I am pretty new to python, coming from Java and I want to update a variable in an initialized class
This is my full code
```
import datetime import time import threading
from tkinter import * from ibapi.client import EClient, TickAttribBidAsk from ibapi.wrapper import EWrapper, TickTypeEnum from ibapi.contract im... | 2021/10/19 | [
"https://Stackoverflow.com/questions/69633739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12496189/"
] | I played with tk a few years ago, this is how I structured my code. I make a tkinter window and connect to TWS from the tkinter class.
```
from tkinter import *
import threading
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper #just for decorator
from ibapi.common import *
... | It would probably help if you did something like this:
```
class TkinterClass:
def __init__(self):
self.ibkrConnection = Application()
self.root = Tk()
self.root.title("test")
self.root.grid_columnconfigure((0, 1), weight=1)
self.titleTicker = Label(root, text="TICKER", bg='... | 14,770 |
56,697,108 | I am trying to read a shapefile using geopandas, for which I used `gp.read_file`
```
import geopandas as gp
fl="M:/rathore/vic_5km/L2_data/L2_data/DAMSELFISH_distributions.shp"
data=gp.read_file(fl)
```
I am getting the following error:
`TypeError: invalid path: UnparsedPath(path='M:/rathore/vic_5km/L2_data/L2_data/... | 2019/06/21 | [
"https://Stackoverflow.com/questions/56697108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10705248/"
] | After so many tries, I have created an [issue](https://issuetracker.google.com/issues/135865377) on Google Issue Tracker under [component](https://issuetracker.google.com/issues?q=componentid:409906), also submitted the code sample to the team and they replied as:
>
> Your Worker is package protected, and hence we ca... | This seems something similar to what has already been reported on some devices from this OEM. Here's a similar bug on [WorkManager's issuetracker](https://issuetracker.google.com/113676489), there's not much that WorkManager can do in these cases.
As commented in this bug:
>
> ...if a device manufacturer has decided... | 14,771 |
6,548,996 | Eventhough I write in python I think the abstract concept is more interesting to me and others. So pseudocode please if you like :)
I have a list with items from one of my classes. Lets do it with strings and numbers here, it really doesn't matter. Its nested to any depth. (Its not really a list but a container class ... | 2011/07/01 | [
"https://Stackoverflow.com/questions/6548996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/824997/"
] | One solution would be to store current index and/or depth information and use it to traverse the nested list. But that seems like a solution that would do a lot of complicated forking -- testing for ends of lists, and so on. Instead, I came up with a compromise. Instead of flattening the list of lists, I created a gene... | Essentially I would base my own solution on recursion. I would extend the container class with the following:
1. `cursor_position` - Property that stores the index of the highlighted element (or the element that contains the element that contains the highlighted element, or any level of recursion beyond that).
2. `rep... | 14,774 |
46,942,411 | I'm analyzing revision histories, using `git-archive` to get the files at a particular revision (see <https://stackoverflow.com/a/40811494/1168342>).
The approach works, but I'm trying to optimize for projects with many revisions. Much processing is wasted archiving (via tar) and back to a files in another directory ... | 2017/10/25 | [
"https://Stackoverflow.com/questions/46942411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1168342/"
] | Use:
```
mkdir <path> &&
GIT_INDEX_FILE=<path>/.git git --work-tree=<path> checkout <revision> -- . &&
rm <path>/.git
```
The `git checkout` step will overwrite the index, so to make this parallelize well, we can just point the index file into the target. There's one file name that's pretty sure to be safe: `.git`!
... | In JGit the `ArchiveCommand` implements what `git archive` does and also provides several archive file formats out of the box. However, the `ArchiveCommand` can be extended with custom archive formats.
A custom format needs to implement the `Format` interface and register it with `ArchiveCommand::registerFormat`. Even... | 14,779 |
4,234,823 | I am trying to open a serial port with python. This is on Ubuntu. I import the openinterface.py and enter in this
```
ser = openinterface.CreateBot(com_port = "/dev/ttyUSB1", mode="full")
```
I get an error saying "unsupported operand types for -: 'str' and 'int'" I tried the same call with single quotes instead of ... | 2010/11/20 | [
"https://Stackoverflow.com/questions/4234823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/508530/"
] | According to [this page in Russian](http://rus-linux.net/lib.php?name=/MyLDP/hard/irobot/irobot.html), there's a bug with the `openinterface.py` file that tries to subtract one from the port argument. It suggests making this change (removing the `- 1` on line 803) with `sed`:
```
sed -ie "803s/ - 1//" openinterface.py... | This is what you want if you are using python 3:
```
import serial #import pyserial lib
ser = serial.Serial("/dev/ttyS0", 9600) #specify your port and braudrate
data = ser.read() #read byte from serial device
print(data) #display the ... | 14,780 |
44,777,408 | I want to mock a method of a class and use `wraps`, so that it is actually called, but I can inspect the arguments passed to it. I have seen at several places ([here](https://stackoverflow.com/questions/25608107/python-mock-patching-a-method-without-obstructing-implementation) for example) that the usual way to do that... | 2017/06/27 | [
"https://Stackoverflow.com/questions/44777408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1264820/"
] | In short, you can't do this using `Mock` instances alone.
`patch.object` creates `Mock`'s for the specified instance (Potato), i.e. it replaces `Potato.foo` with a single Mock the moment it is called. Therefore, there is no way to pass instances to the `Mock` as the mock is created before any instances are. To my kno... | Do you control creation of `Potato` instances, or at least have access to these instances after creating them? You should, else you'd not be able to check particular arg lists.
If so, you can wrap methods of individual instances using
```
spud = dig_out_a_potato()
with mock.patch.object(spud, "foo", wraps=spud.foo) a... | 14,781 |
57,943,053 | When EMR machine is trying to run a step that includes boto3 initialisation it sometimes get the following error:
`ValueError: Invalid endpoint: https://s3..amazonaws.com`
When I'm trying to set up a new machine it can suddenly work.
Attached the full error:
```
self.client = boto3.client("s3")
File "/usr/local/lib... | 2019/09/15 | [
"https://Stackoverflow.com/questions/57943053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6359988/"
] | It looks like you have an invalid region.
[Check](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/setup-credentials.html) your ~/.aws/config | In my case, even though `~/.aws/config` had the region set,
```
$ cat ~/.aws/config
[default]
region = us-east-1
```
the env var `AWS_REGION` was set to an empty string
```
$ env | grep -i aws
AWS_REGION=
```
unset this env var and all was good again
```
$ unset AWS_REGION
$ aws sts get-caller-identity --output... | 14,783 |
28,572,764 | I've been reading through the source for the cpython HTTP package for fun and profit, and noticed that in server.py they have the `__all__` variable set but also use a leading underscore for the function `_quote_html(html)`.
Isn't this redundant? Don't both serve to limit what's imported by `from HTTP import *`?
Why ... | 2015/02/17 | [
"https://Stackoverflow.com/questions/28572764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1029146/"
] | Aside from the *"private-by-convention"* functions with `_leading_underscores`, there are:
* Quite a few `import`ed names;
* Four class names;
* Three function names *without* leading underscores;
* Two string *"constants"*; and
* One local variable (`nobody`).
If `__all__` wasn't defined to cover only the classes, a... | `__all__` indeed serves as a limit when doing `from HTTP import *`; prefixing `_` to the name of a function or method is a convention for informing the user that that item should be considered private and thus used at his/her own risk. | 14,785 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.