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
63,442,333
When running `npm start`, my code shows a blank page, without favicon either, and the browse console shows ``` Loading failed for the <script> with source β€œhttp://localhost:3000/short_text_understanding/static/js/bundle.js”. bundle.js:23:1 Loading failed for the <script> with source β€œhttp://localhost:3000/short_text_u...
2020/08/16
[ "https://Stackoverflow.com/questions/63442333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1780570/" ]
``` /// <summary> /// Passengers array /// </summary> public Passenger[] Passengers = new Passenger[10]; public class Passenger { public int Age { get; set; } public Passenger(int age) { Age = age; } } public void AddPassenger() { ...
You can try: ``` public void AddPassengers(Passenger[] passengers) { int i = Array.IndexOf(passengers, null); if (i < 0) { Console.WriteLine("The array is full."); return; } Console.WriteLine("How old is the passenger?"); int age = Int3...
1,939
73,225,062
I am trying to use `multiprocessing.Queue` to manage some tasks that are sent by the main process and picked up by "worker" processes (`multiprocessing.Process`). The workers then run the task and put the results into a result queue. Here is my main script: ```py from multiprocessing import Process, Queue, freeze_sup...
2022/08/03
[ "https://Stackoverflow.com/questions/73225062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19102984/" ]
``` import pandas as pd import numpy as np rng = np.random.default_rng(92) df = pd.DataFrame({'a':rng.integers(0,5, 10), 'b':rng.integers(0,5, 10), 'c':rng.integers(0,5, 10)}) df ### a b c 0 2 3 1 1 3 4 0 2 4 1 1 3 0 0 1 4 2 3 3 5 1 0 2 6 2 2 2 7 1 3 2 ...
here is one way to do it. If you post the data to reproduce, i would have posted the result set. ``` window=5 df[df['Column']!=0]['Column'].rolling(window).mean() ```
1,943
60,155,158
I'm using selenium in python and trying to click an element that is not a button class. I'm using Google Chrome as my browser/web driver Here is my code: ``` from selenium import webdriver from bs4 import BeautifulSoup driver = webdriver.Chrome(executable_path="/Users/ep9k/Desktop/SeleniumTest/drivers/chromedriver"...
2020/02/10
[ "https://Stackoverflow.com/questions/60155158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9305645/" ]
The element doesn't need to be a button to be clickable. after I ran your code, I've added: ```py results = driver.find_elements_by_class_name('SearchResults') first_result = results[0] first_result.click() ``` And it worked perfectly fine for me. Most probably you tried to click on some different element and that...
Clicking the first row with xpath - see below. Assuming you want to parse each of the results(parcels) after that, make use of the navigation buttons; this is a structure you could use: ``` table = driver.find_elements_by_xpath("//table[@id='searchResults']") table[0].click() # Extract the total number of parcels fr...
1,945
34,645,978
I am new to python and would like to have a script that looks at a feature class and compares the values in two text fields and then populates a third field with a `Y` or `N` depending on if the values are the same or not. I think I need to use an UpdateCursor with an if statement. I have tried the following but I get ...
2016/01/07
[ "https://Stackoverflow.com/questions/34645978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5755063/" ]
Try splitting up the for loop that goes through each item and the actual get\_multi call itself. So something like: ``` all_values = ndb.get_multi(all_keys) for counter in all_values: # Insert amazeballs codes here ``` I have a feeling it's one of these: 1. The generator pattern (yield from for loop) is causing...
When I've dug into similar issues, one thing I've learned is that `get_multi` can cause multiple RPCs to be sent from your application. It looks like the default in the SDK is set to 1000 keys per get, but the batch size I've observed in production apps is much smaller: something more like 10 (going from memory). I su...
1,947
61,135,030
I'm running a few tasks on the same terminal in bash. Is there a way I can stream all the logs I'm seeing on the bash terminal to a log file? I know can technically pipe the logs of individual tasks, but wondering if there's a more elegant way. So far this is what I'm doing: ``` $> python background1.py > logs/bg1.log...
2020/04/10
[ "https://Stackoverflow.com/questions/61135030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/499363/" ]
Sorry I didn't understand your question :D For this case you can use an input to specify what do you need: type=int(input("What Type Of Def You Want To Use? ")) And then you can put an IF for you selection: if(type==1): command.a(args) elif(type==2): command.b(args) elif(type==3): command.c(args) else: print(...
You can use `input`: ``` name = input ("What's your name") print ("Hello, ", name ) ``` If you're writing a command line tool, it's very doable with the [click package](https://click.palletsprojects.com/en/7.x/). See their Hello World example: ``` import click @click.command() @click.option('--count', default=1, h...
1,948
69,555,581
This might be heavily related to similar questions as [Python 3.3: Split string and create all combinations](https://stackoverflow.com/questions/22911367/python-3-3-split-string-and-create-all-combinations/22911505) , but I can't infer a pythonic solution out of this. Question is: Let there be a str such as `'hi|guys...
2021/10/13
[ "https://Stackoverflow.com/questions/69555581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6042172/" ]
An approach, once you have split the string is to use `itertools.combinations` to define the split points in the list, the other positions should be fused again. ``` def lst_merge(lst, positions, sep='|'): '''merges a list on points other than positions''' '''A, B, C, D and 0, 1 -> A, B, C|D''' a = -1 ...
One approach using [`combinations`](https://docs.python.org/3/library/itertools.html#itertools.combinations) and [`chain`](https://docs.python.org/3/library/itertools.html#itertools.chain) ``` from itertools import combinations, chain def partition(alist, indices): # https://stackoverflow.com/a/1198876/4001592 ...
1,949
64,163,749
I have asyncio crawler, that visits URLs and collects new URLs from HTML responses. I was inspired that great tool: <https://github.com/aio-libs/aiohttp/blob/master/examples/legacy/crawl.py> Here is a very simplified piece of workflow, how it works: ``` import asyncio import aiohttp class Requester: def __init_...
2020/10/01
[ "https://Stackoverflow.com/questions/64163749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14376515/" ]
I have created an example in Node.js that is based on the steps from my previous answer to this question. The first action expects a valid apikey in `params.apikey` as input parameter and returns a bearer token: ```js /** * * main() will be run when you invoke this action * * @param Cloud Functions actions accept...
I can't guide you the full way right now, but I hope the information that I can provide will guide you into the right direction. First you'll need to identify the authorization endpoint: `curl http://api.us-south.cf.cloud.ibm.com/info` With that and a valid IAM API token for your account you can get the bearer token...
1,953
53,098,413
I am storing discount codes with different prefixes and unique digits at the end (`10OFF<abc>`, `25OFF<abc>`, `50OFF<abc>`, etc.) in a file, and then loading that file into a list. I am trying to make a function so that when they are redeemed, they are removed from the list, and the file is overwritten. Right now what...
2018/11/01
[ "https://Stackoverflow.com/questions/53098413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10142229/" ]
this should do what you want ``` list_of_codes=open('codes.txt','rt').read().split('\n') while True: code=input('enter code to remove:') if code in list_of_codes: break else: print('code you entered is not in the list') continue list_of_codes.pop(list_of_codes.index(code)) with open...
This code promps the user to input all the code he whishes to remove, then it reads the current file and overwrites the file with only the code that were NOT input by the user. The file considers the whole content of a line as a code (must contain prefix + unique digits). The code also leaves the old file as a backup,...
1,954
40,703,228
I am trying to run a Flask REST service on CentOS Apache2 using WSGI. The REST service requires a very small storage. So i decided to use SQLite with `sqlite3` python package. The whole application worked perfectly well on my local system and on the CentOS server when ran using `app.run()`. But when i used WSGI to host...
2016/11/20
[ "https://Stackoverflow.com/questions/40703228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6935236/" ]
In addition to changing the database file permissions, you need also to change permissions for the directory that hosts the database file. You can try the following command: ``` chmod 664 /path/to/your/directory/ ``` You can also change the directory's owner as follows: ``` chown apache:apache /path/to/your/directo...
What worked for me (I don't have sudo) was removing the database file and all migrations and starting again, as described here: [How do I delete DB (sqlite3) in Django 1.9 to start from scratch?](https://stackoverflow.com/questions/42150499/how-do-i-delete-db-sqlite3-in-django-1-9-to-start-from-scratch/42150639)
1,956
13,984,423
I am very new to python, this is my first program that I am trying. This function reads the password from the standard input. ``` def getPassword() : passwordArray =[] while 1: char = sys.stdin.read(1) if char == '\\n': break pas...
2012/12/21
[ "https://Stackoverflow.com/questions/13984423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1731553/" ]
Your indentation is not correct. Your `while` should be indented the same as the line above it.
Python uses indentation to "separate" stuff and the thing with that is you need to have the same kind of indentation across the file. Having a fixed kind of indentation in the code you write is good practice. You might want to consider a tab or four spaces(The later being the suggestion in the PEP8 style guide)
1,959
43,380,783
I wrote a MoviePy script that takes an input video, does some processing, and outputs a video file. I want to run this through an entire folder of videos. Any help or direction is appreciated. Here's what I tried... ``` for f in *; do python resize.py $f; done ``` and resize.py source code here: ``` from moviepy.e...
2017/04/12
[ "https://Stackoverflow.com/questions/43380783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7859068/" ]
I know you have an answer [on Github](https://github.com/Zulko/moviepy/issues/542#issuecomment-293735347), but I'll add my own solution. First, you'll want to put your code inside a function: ``` def process_video(input): """Parameter input should be a string with the full path for a video""" clip = VideoFil...
I responded on your [Github issue #542](https://github.com/Zulko/moviepy/issues/542#issuecomment-293843765), but I copied it here for future reference! First off, the below example isn't ironclad, but it should do what you need. You can achieve this via something like this: ``` #!/usr/bin/env python # -*- coding: utf...
1,961
37,124,342
I am "using" `Statsmodel`for less than 2 days and am not at all familiar with the import commands etc. I want to run a simple `variance_inflation_factor` from [here](http://statsmodels.sourceforge.net/devel/generated/statsmodels.stats.outliers_influence.variance_inflation_factor.html) but am having some issues. My code...
2016/05/09
[ "https://Stackoverflow.com/questions/37124342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5211377/" ]
The function `variance_inflation_factor` is found in `statsmodels.stats.outlier_influence` as seen [in the docs](http://statsmodels.sourceforge.net/devel/_modules/statsmodels/stats/outliers_influence.html), so to use it you must import correctly, an option would be ``` from statsmodels.stats import outliers_influence...
``` a = df1.years_exp b = df1.leg_totalbills c = df1.log_diff_rgdp d = df1.unemployment e = df1.expendituresfor f = df1.direct_expenditures g = df1.indirect_expenditures ck=np.array([a,b,c,d,e,f,g]) outliers_influence.variance_inflation_factor(ck, 6) ```
1,962
11,809,643
I have some python code with many lines like this: ``` print "some text" + variables + "more text and special characters .. etc" ``` I want to modify this to put everything after print within brackets, like this: ``` print ("some text" + variables + "more text and special characters .. etc") ``` How to do this in...
2012/08/04
[ "https://Stackoverflow.com/questions/11809643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1338814/" ]
Use this substitute: ``` %s/print \(.*$\)/print (\1) ``` `\(.*$\)` matches everything up to the end of the line and captures it in a group using the escaped parentheses. The replacement includes this group using `\1`, surrounded by literal parentheses.
``` :%s/print \(.*\)/print(\1)/c ``` OR if you visually select multiple lines ``` :'<,'>s/print \(.*\)/print(\1)/c ``` `%` - every line `'<,'>` - selected lines `s` - substitute `c` - confirm - show you what matched before you convert `print \(.*\)` - exactly match print followed by a space then group ...
1,964
20,553,695
I'm fairly green in Python and trying to get django working to build a simple website. I've installed Django 1.6 under Python 2.7.6 but can't get django-admin to run. According to the tutorial I should create a project as follows, but I get a syntax error: ``` Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 ...
2013/12/12
[ "https://Stackoverflow.com/questions/20553695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1324833/" ]
``` django-admin.py startproject Nutana ``` should be run in the command line, and not in the django shell. If the second case is not working 1. If you are using a virtual-env, did you forget to activate it ? 2. Make sure you add `C:\Python27\Scripts` to the path, and you would not face this issue.
Try this `$ django-admin.py startproject mysite` You don't need the python statement in front.
1,965
26,721,113
I have an equation 'a\*x+logx-b=0,(a and b are constants)', and I want to solve x. The problem is that I have numerous constants a(accordingly numerous b). How do I solve this equation by using python?
2014/11/03
[ "https://Stackoverflow.com/questions/26721113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4211557/" ]
You could check out something like <http://docs.scipy.org/doc/scipy-0.13.0/reference/optimize.nonlin.html> which has tools specifically designed for these kinds of equations.
Cool - today I learned about Python's numerical solver. ``` from math import log from scipy.optimize import brentq def f(x, a, b): return a * x + log(x) - b for a in range(1,5): for b in range(1,5): result = brentq(lambda x:f(x, a, b), 1e-10, 20) print a, b, result ``` `brentq` provides es...
1,966
26,906,586
**Background:** I have an OpenShift Python 2.7 gear containing my Django 1.6 application. I used django-openshift-quickstart.git as a starting point for my own project and it works well. However, if I have a syntax error in my code or some other exception I have no way of finding it. I can do a tail of the logs via: ...
2014/11/13
[ "https://Stackoverflow.com/questions/26906586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3538533/" ]
I don't know zilch about OpenShift, but 1. you may have to configure your loggers (<https://docs.djangoproject.com/en/1.6/topics/logging/#configuring-logging>) and 2. you have to restart the wsgi processes when you make some changes to your settings. Now I strongly advise you to NOT set `DEBUG=True` on a production ...
To my horror... it turns out I simply hadn't set DEBUG=True! I could have sworn I had set it in settings.py at some point but my commit history strongly suggests I'm wrong. With DEBUG=True in my wsgi/settings.py I can now debug my application on OpenShift. Apologies for the noise. Doug
1,967
63,802,423
I have troubles checking the user token inside of middleware. I'm getting token from cookies and then I need to query database to check if this token exists and belongs to user that made a request. **routing.py** ``` from channels.routing import ProtocolTypeRouter, URLRouter import game.routing from authentication.ut...
2020/09/08
[ "https://Stackoverflow.com/questions/63802423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9631956/" ]
Works on my machine. Hard to say without knowing what the data looks like, so I took a stab below: ```js const value = { expenses: [{amount: 1}, {amount: 2}] } const totalExpense = value.expenses.length > 0 ? ( value.expenses.reduce((acc, curr) => { acc += curr.amount return acc }, 0)) : 0; console.lo...
``` {value => { const totalExpense = value.expenses.length > 0 ? ( value.expenses.reduce((acc, curr) => { acc += parseInt(curr.amount) return acc }, 0)) : 0; console.log(totalExpense); console.log(value.e...
1,968
48,688,693
New to Django framework. Mostly reading through documentations. But this one i am unable to crack. Trying to add a URL to an headline, that will be forwarded to the 'headlines' post. The Error: > > NoReverseMatch at / Reverse for 'assignment\_detail' with arguments > '('',)' not found. 1 pattern(s) tried: ['assign...
2018/02/08
[ "https://Stackoverflow.com/questions/48688693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8929670/" ]
Your url does not imply that you have to pass an id, but you're passing one in the template: ``` <a href="{% url 'assignment_detail' post_id %}"><h3>{{ post.title }}</h3></a> ``` It should be: ``` url(r'^assignment_detail/(?P<post_id>[0-9]+)', views.assignment_detail,name='assignment_detail'), ```
That error is Django telling you that it can't find any URLs named 'assignment\_detail' that have an argument to pass in. This is because your url entry in `myproject/urls.py` is missing the argument (`post_id`) that you use in your view. You'll need to update that url line to something similar to this: ``` url(r'^as...
1,969
36,620,175
I am receiving a warning and I want to check if this will break. I am using np.where like this in a lot of cases (it is similar, for me, to an if statement in excel). Is there a better or more pythonic or pandas way to do this? I'm trying to turn one dimension into something I can easily do mathematical operations on. ...
2016/04/14
[ "https://Stackoverflow.com/questions/36620175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3966601/" ]
This warning occurs when comparing "int" and "str" in your dataset. Add .astype(int) to your comparison dataset. Try: ``` df['closed_item'] = np.where(df['result'].astype(str)=='Action Taken', 1, 0) ```
The issue that you mentioned is actually quite complex, so let me divide it into parts using your words: > > I am receiving a warning and I want to check if this will *break* > > > A `Warning` is a statement that is telling you to be cautious with how you handle your coding logic. A well-designed warning is not g...
1,970
4,976,776
In my vim plugin, I have two files: ``` myplugin/plugin.vim myplugin/plugin_helpers.py ``` I would like to import plugin\_helpers from plugin.vim (using the vim python support), so I believe I first need to put the directory of my plugin on python's sys.path. How can I (in vimscript) get the path to the currently e...
2011/02/12
[ "https://Stackoverflow.com/questions/4976776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144135/" ]
``` " Relative path of script file: let s:path = expand('<sfile>') " Absolute path of script file: let s:path = expand('<sfile>:p') " Absolute path of script file with symbolic links resolved: let s:path = resolve(expand('<sfile>:p')) " Folder in which script resides: (not safe for symlinks) let s:path = expand('<sf...
Found it: ``` let s:current_file=expand("<sfile>") ```
1,971
74,266,511
I am making a blackjack simulator with python and are having problems with when the player want another card. To begin with the player gets a random sample of two numbers from a list and then get the option to take another card or not to. When the answer is yes another card is added to the random sample but it gets add...
2022/10/31
[ "https://Stackoverflow.com/questions/74266511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19321160/" ]
`random.sample(kortlek,1)` `random.sample` returns a list, so you end up `append`ing a list to `handspelare` (which creates the sublists). You could change `append` to `extend`, but `random.sample(..., 1)` is just `random.choice`, so it makes more sense to use `handspelare.append(random.choice(kortlek))`.
Use list concatenation rather than append. ``` handspelare += random.sample(kortlek,1) ``` `append` will not unbundle its argument ``` a = [1] a.append([2]) # [1, [2]] a = [1] a += [2] # [1, 2] ```
1,977
19,616,168
I am new to Django and I try to follow the official tutorial. since I want to connect to mysql (installed on my computer, and i checked mysql module does exit in python command line), I set the ENGINE in setting.py to be django.db.backends.mysql . and then I tried to run ``` python manage.py syncdb ``` then I g...
2013/10/27
[ "https://Stackoverflow.com/questions/19616168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2379736/" ]
You need to download the [windows binary installer](http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python) for the MySQL drivers for Python. Installing from source will not work since you do not have the development headers in Windows.
You need to install the mysql python connector sudo apt-get install python-mysqldb
1,980
13,877,907
``` # python enter code herePython 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os,sys >>> import setup .......... .......... .......... >>> reload(setup) <module 'setup' from 'setup.pyc'> >>> ```...
2012/12/14
[ "https://Stackoverflow.com/questions/13877907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468198/" ]
`reload` reloads a module, but doesn't recompile it. ``` >>> reload(setup) <module 'setup' from 'setup.pyc'> ``` It is reloading from the compiled `setup.pyc`, not `setup.py`. The easiest way to get around this is simply to delete `setup.pyc` after making changes. Then when it reloads `setup.py` it will first recom...
Try assigning the value returned by `reload` to the same variable: ``` setup = reload(setup) ```
1,981
49,844,925
I have the following python code to write processed words into excel file. The words are about 7729 ``` From openpyxl import * book=Workbook () sheet=book.active sheet.title="test" for x in range (7729): sheet.cell (row=1,column=x+1).value=x book.save ('test.xlsx') ``` This is the what the code I used looks like...
2018/04/15
[ "https://Stackoverflow.com/questions/49844925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8616724/" ]
**Try this :** This code works for me . ``` from openpyxl import * book=Workbook () sheet=book.active sheet.title="test" x = 0 with open("temp.txt") as myfile : text = myfile.readline() while text !="": sheet.cell (row=1,column=x+1).value=str(text).encode("ascii",errors="ignore") x+=1 ...
You missed to add the value for cell `sheet.cell (row=1,column=x+1).value =` Try like this ``` from openpyxl import * book = Workbook () sheet = book.active sheet.title = "test" for x in range (7): sheet.cell (row=1,column=x+1).value = "Hello" book.save ('test.xlsx') ```
1,982
58,007,418
I've got a CASIO fx-CG50 with python running extended version of micropython 1.9.4 Decided to make a game but I really need a sleep function, I cannot use any imports as everything is pretty barebones. Any help would be greatly appreciated. I've tried downloading utilities but they're just extra applications, nothing...
2019/09/19
[ "https://Stackoverflow.com/questions/58007418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8402836/" ]
If you cannot import time (or utime) in your code, you could always implement a simple function that loops for a certain number of steps: ``` def wait(step): for i in range(step): pass wait(999999) ``` In that case, the actual time spent in the function will depend on the computational power of your d...
I am trying to do the same exact things and I was trying to benchmark a wait function by animating a square accross the scree. Here is what I have come up width: ``` from casioplot import * def wait(milli): time = milli*50 for i in range(time): pass def drawSquare(x,y,l): for i in range(l): ...
1,988
65,559,632
Seems to be impossible currently with Anaconda as well as with Xcode 12. Via idle, it runs via Rosetta. There seems to be no discussion of this so either I'm quite naive or maybe this will be useful to others as well. Python says: "As of 3.9.1, Python now fully supports building and running on macOS 11.0 (Big Sur) and...
2021/01/04
[ "https://Stackoverflow.com/questions/65559632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14936216/" ]
You can now install python 3.9.1 through multiple pathways now but the most comprehensive build environment for the full data-science suite for python at the moment (Feb 2021) on M1 ARM architecture is via miniforge. e.g. ``` brew install --cask miniforge conda init zsh conda activate conda install numpy scipy scikit...
I am using python3.9.4. I installed it using homebrew only. ``` brew install python@3.9 ```
1,989
23,936,239
Strings are iterable. Lists are iterable. And with a List of Strings, both the List and the Strings can be iterated through with a nested loop. For Example: ``` input = [ 'abcdefg', 'hijklmn', 'opqrstu'] for item in input: for letter in item: print letter ``` Out: ``` a b c d e f g h i j k l m n o p q...
2014/05/29
[ "https://Stackoverflow.com/questions/23936239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1851961/" ]
You can use [`itertools.chain.from_iterable()`](https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable): ``` >>> from itertools import chain >>> input = ['abcdefg', 'hijklmn', 'opqrstu'] >>> >>> for letter in chain.from_iterable(input): ... print letter ... a b c d e f g h i j k l m n o p ...
Use `itertools.chain`: ``` for letter in itertools.chain(*input): print letter ```
1,994
14,610,459
Go's time package claims giving a nanosecond precision. <http://golang.org/src/pkg/time/time.go> I'm wondering how it is implemented and if I can trust it. My doubts come from Python, which clearly documents its difficulties and limitations with time: > > *From <http://docs.python.org/2/library/time.html>* > > > T...
2013/01/30
[ "https://Stackoverflow.com/questions/14610459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/520159/" ]
Well as for the implementation, `time.Now()` falls back to a function implemented in the runtime. You can review the [C time implementation](http://code.google.com/p/go/source/browse/src/pkg/runtime/time.goc) and the implementation for [`timeΒ·now` in assembly](http://code.google.com/p/go/source/browse/src/pkg/runtime/...
One of the problems with Python's [time.time](http://docs.python.org/2/library/time.html#time.time) function is that it returns a [float](http://docs.python.org/2/library/functions.html#float). A float is an [IEEE 754 double-precision number](http://en.wikipedia.org/wiki/Double-precision_floating-point_format) which ha...
1,999
12,172,934
(not to be confused with itertools.chain) I was reading the following: <http://en.wikipedia.org/wiki/Method_chaining> My question is: **what is the best way to implement method chaining in python?** Here is my attempt: ``` class chain(): def __init__(self, my_object): self.o = my_object def __getat...
2012/08/29
[ "https://Stackoverflow.com/questions/12172934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632088/" ]
There is a very handy [`Pipe`](https://github.com/JulienPalard/Pipe) library which may be the answer to your question. For example:: ``` seq = fib() | take_while(lambda x: x < 1000000) \ | where(lambda x: x % 2) \ | select(lambda x: x * x) \ | sum() ```
There isn't going to be any general way of allowing any method of any object to be chained, since you can't know what sort of value that method returns and why without knowing how that particular method works. Methods might return `None` for any reason; it doesn't always mean the method has modified the object. Likewis...
2,002
61,748,604
I have two pandas series with DateTimeIndex. I'd like to join these two series such that the resulting DataFrame uses the index of the first series and "matches" the values from the second series accordingly (using a linear interpolation in the second series). First Series: ``` 2020-03-01 1 2020-03-03 2 2020-...
2020/05/12
[ "https://Stackoverflow.com/questions/61748604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5554921/" ]
Use [`concat`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html) with inner join: ``` df = pd.concat([s1, s2], axis=1, keys=('s1','s2'), join='inner') print (df) s1 s2 2020-03-01 1 20 2020-03-05 3 25 2020-03-07 4 36 ``` Solution with interpolate of `s2` Series and th...
### Construct combined dataframe ``` # there are many ways to construct a dataframe from series, this uses the constructor: df = pd.DataFrame({'s1': s1, 's2': s2}) s1 s2 2020-03-01 1.0 20.0 2020-03-02 NaN 22.0 2020-03-03 2.0 NaN 2020-03-05 3.0 25.0 2020-03-06 NaN 35.0 2020-03-07 4.0 36.0 2...
2,010
73,386,405
``` infile = open('results1', 'r') lines = infile.readlines() import re for line in lines: if re.match("track: 1,", line): print(line) ``` question solved by using python regex below
2022/08/17
[ "https://Stackoverflow.com/questions/73386405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19783767/" ]
I suggest you use Regular Expressions library (re) which gives you all you need to extract the data from text files. I ran a simple code to solve your current problem: ``` import re # Customize path as the file's address on your system text_file = open('path/sample.txt','r') # Read the file line by line using .readlin...
Given that all your target lines follow the exact same pattern, a much simpler way to extract the value between parentheses would be: ``` from ast import literal_eval as make_tuple infile = open('results1', 'r') lines = infile.readlines() import re for line in lines: if re.match("Id of the track: 1,", line): ...
2,011
5,738,339
I have a specific use. I am preparing for GRE. Everytime a new word comes, I look it up at www.mnemonicdictionary.com, for its meanings and mnemonics. I want to write a script in python preferably ( or if someone could provide me a pointer to an already existing thing as I dont know python much but I am learning now) w...
2011/04/21
[ "https://Stackoverflow.com/questions/5738339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/169210/" ]
If you have Bash (version 4+) and `wget`, an example ``` #!/bin/bash template="http://www.mnemonicdictionary.com/include/ajaxSearch.php?word=%s&event=search" while read -r word do url=$(printf "$template" "$word") data=$(wget -O- -q "$url") data=${data#*&nbsp;} echo "$word: ${data%%<*}" done < file ``...
Use [curl](http://curl.haxx.se/) and sed from a Bash shell (either Linux, Mac, or Windows with Cygwin). If I get a second I will write a quick script ... gotta give the baby a bath now though.
2,012
49,766,071
I'm new to python, and I know there must be a better way to do this, especially with numpy, and without appending to arrays. Is there a more concise way to do something like this in python? ```py def create_uniform_grid(low, high, bins=(10, 10)): """Define a uniformly-spaced grid that can be used to discretize a s...
2018/04/11
[ "https://Stackoverflow.com/questions/49766071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1097028/" ]
`np.ogrid` is similar to your function. Differences: 1) It will keep the endpoints; 2) It will create a column and a row, so its output is 'broadcast ready': ``` >>> np.ogrid[-1:1:11j, -5:5:11j] [array([[-1. ], [-0.8], [-0.6], [-0.4], [-0.2], [ 0. ], [ 0.2], [ 0.4],...
Maybe the `numpy.meshgrid` is what you want. Here is an example to create the grid and do math on it: ``` #!/usr/bin/python3 # 2018.04.11 11:40:17 CST import numpy as np import matplotlib.pyplot as plt x = np.arange(-5, 5, 0.1) y = np.arange(-5, 5, 0.1) xx, yy = np.meshgrid(x, y, sparse=True) z = np.sin(xx**2 + yy*...
2,013
25,067,927
So I have a line here that is meant to dump frames from a movie via python and ffmpeg. ``` subprocess.check_output([ffmpeg, "-i", self.moviefile, "-ss 00:01:00.000 -t 00:00:05 -vf scale=" + str(resolution) + ":-1 -r", str(framerate), "-qscale:v 6", self.processpath + "/" + self.filetitles + "-output%03d.jpg"]) ``` A...
2014/07/31
[ "https://Stackoverflow.com/questions/25067927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The subprocess module does almost never allow any whitespace characters in its parameters, unless you run it in shell mode. Try this: ``` subprocess.check_output(["ffmpeg", "-i", self.moviefile, "-ss", "00:01:00.000", "-t", "00:00:05", "-vf", "scale=" + str(resolution) + ":-1", "-r", str(framerate), "-qscale:v", "6", ...
The argument array you pass to `check_call` is not correctly formatted. Every argument to `ffmpeg` needs to be a single element in the argument list, for example ``` ... "-ss 00:01:00.000 -t 00:00:05 -vf ... ``` should be ``` ... "-ss", "00:01:00.000", "-t", "00:00:05", "-vf", ... ``` The complete resulting args ...
2,014
4,002,660
In my MySQL database I have dates going back to the mid 1700s which I need to convert somehow to ints in a format similar to Unix time. The value of the int isn't important, so long as I can take a date from either my database or from user input and generate the same int. I need to use MySQL to generate the int on the ...
2010/10/23
[ "https://Stackoverflow.com/questions/4002660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/64911/" ]
This is my idea, create a filter in your web application , when u receive a request like `/area.jsp?id=1` , in `doFilter` method , forward the request to `http://example.com/newyork`. In `web.xml`: ``` <filter> <filter-name>RedirectFilter</filter-name> <filter-class> com.filters.RedirectFilter </...
In your database where you store these area IDs, add a column called "slug" and populate it with the names you want to use. The "slug" for id 1 would be "newyork". Now when a request comes in for one of these URLs, look up the row by "slug" instead of by id.
2,015
64,415,588
Given 2 data frames like the link example, I need to add to df1 the "index income" from df2. I need to search by the df1 combined key in df2 and if there is a match return the value into a new column in df1. There is not an equal number of instances in df1 and df2 and there are about 700 rows in df1 1000 rows in df2. ...
2020/10/18
[ "https://Stackoverflow.com/questions/64415588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14473305/" ]
This should solve your issue: ``` df1.merge(df2, how='left', on='combind_key') ``` This (`left` join) will give you all the records of `df1` and matching records from `df2`.
<https://www.geeksforgeeks.org/how-to-do-a-vlookup-in-python-using-pandas/> Here is an answer using joins. I modified my df2 to only include useful columns then used pandas left join. ``` Left_join = pd.merge(df, zip_df, on ='State County', how ='le...
2,018
66,996,373
I'm trying to install and use Pillow with Python 3.9.2 (managed with pyenv). I'm using Poetry to manage my virtual environments and dependencies, so I ran `poetry add pillow`, which successfully added `Pillow = "^8.2.0"` to my pyproject.toml. Per the Pillow docs, I added `from PIL import Image` in my script, but when I...
2021/04/08
[ "https://Stackoverflow.com/questions/66996373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4430379/" ]
I couldn't find a way to solve this either (using poetry 1.1.13). Ultimately, I resorted to a workaround of `poetry add pillow && pip install pillow` so I could move on with my life. :P `poetry add pillow` gets the dependency in to the TOML, so consumers of the package *should* be OK.
capitalizing "Pillow" solved it for me: `poetry add Pillow`
2,019
30,558,917
Using the pandas library for python I am reading a csv, then grouping the results with a sum. ``` grouped = df[['Organization Name','Views']].groupby('Organization Name').sum().sort(columns='Views',ascending=False).head(10) #Bar Chart Section print grouped.to_string() ``` Unfortunately I get the following result for...
2015/05/31
[ "https://Stackoverflow.com/questions/30558917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1760634/" ]
Because you grouped on 'Organization Name', this is being used as the name for your index, you can set this to `None` using: ``` grouped.index.name = None ``` Will then remove the line, this is just a display issue, your data is not in some funny shape Alternatively if you don't want 'Organization Name' to become t...
`grouped.reset_index()` should fix this. This happened because you have grouped the data and aggregated on a column.
2,020
67,511,611
I am new to Python socket server programming, I am following this [example](https://docs.python.org/3/library/socketserver.html#examples) to setup a server using the socketserver framework. Based on the comment, pressing Ctrl-C will stop the server but when I try to run it again, I get `OSError: [Errno 98] Address alr...
2021/05/12
[ "https://Stackoverflow.com/questions/67511611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10733376/" ]
Just split the string and add map over the `stringArray` and add `<b>` just before the `beginOffset` and `</b>` after the `endOffset`. ```js var indices = [{ beginOffset: 2, endOffset: 8, }, { beginOffset: 42, endOffset: 48, }, { beginOffset: 58, endOffset: 63, }, ]; var teststring =...
Sort the indices from highest to lowest. Then when you insert `<b>` and `</b>` it won't affect the indexes in subsequent iterations. ```js var indices = [{ beginOffset: 2, endOffset: 8 }, { beginOffset: 42, endOffset: 48 }, { beginOffset: 58, endOffset: 63 } ]; var teststring = "a lo...
2,021
45,477,478
I have a group of images and some separate heatmap data which (imperfectly) explains where subject of the image is. The heatmap data is in a numpy array with shape (224,224,3). I would like to generate bounding box data from this heatmap data. The heatmaps are not always perfect, So I guess I'm wondering if anyone can...
2017/08/03
[ "https://Stackoverflow.com/questions/45477478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3539683/" ]
this is not a good piece of code. I would not know where to start on the bad practices... This function defines a function that it is not reachable from any other scope, and not reusable, just to return its call with the data argument. The outer return could be simple as ``` return self.change('groupTo', groupExp, d...
if you call `getData()` function without passing any parameter then value of the data variable in function is undefined. So at this Line ternary operator is used. ``` data = (data === undefined) ? this.defaultData() : data; ``` So it will check whether `data === undefined` condition which is true. therefore it will ...
2,023
34,490,117
C code: ``` #include "Python.h" #include <windows.h> __declspec(dllexport) PyObject* getTheString() { auto p = Py_BuildValue("s","hello"); char * s = PyString_AsString(p); MessageBoxA(NULL,s,"s",0); return p; } ``` Python code: ``` import ctypes import sys sys.path.append('./') dll = ctypes.CDLL('py...
2015/12/28
[ "https://Stackoverflow.com/questions/34490117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680359/" ]
> > By default functions are assumed to return the C `int` type. Other > return types can be specified by setting the `restype` attribute of the > function object. > [(ref)](https://docs.python.org/2/library/ctypes.html#return-types) > > > Define the type returned by your function like that: ``` >>> from ctype...
`int` is the default return type, to specify another type you need to set the function object's `restype` attribute. See [Return types](https://docs.python.org/2/library/ctypes.html#return-types) in the `ctype` docs for details.
2,025
61,959,745
I want to merge all files with the extension `.asc` in my current working directory to be merged into a file called `outfile.asc`. My problem is, I don't know how to exclude a specific file (`"BigTree.asc"`) and how to overwrite an existing `"outfile.asc"` if there is one in the directory. ``` if len(sys.argv) < 2: ...
2020/05/22
[ "https://Stackoverflow.com/questions/61959745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13461656/" ]
As suggested in a comment, here's my simplified (simplistic?) solution to make it such that specific flask end points in google app engine are only accessibly by application code or app engine service accounts. The answer is based on the documentation regarding [validating cron requests](https://cloud.google.com/appeng...
It still works in Python 3.x, I use the original approach in my own Flask AppEngine app running Python 3.8 Here is a simplified version of my `app.yaml` with everything you need: ``` runtime: python38 app_engine_apis: true handlers: - url: /admin/.* secure: always script: auto login: admin - url: /.* secure...
2,026
49,625,350
I have a zip file structure like - B.zip/org/note.txt I want to directly list the files inside org folder without going to other folders in B.zip I have written the following code but it is listing all the files and directories available inside the B.zip file ``` f = zipfile.ZipFile('D:\python\B.jar') for name in f....
2018/04/03
[ "https://Stackoverflow.com/questions/49625350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can filter the yields by startwith function.(Using Python 3) ``` import os import zipfile with zipfile.ZipFile('D:\python\B.jar') as z: for filename in z.namelist(): if filename.startswith("org"): print(filename) ```
How to list all files that are inside ZIP files of a certain folder ------------------------------------------------------------------- > > Everytime I came into this post making a similar question... But different at the same time. Cause of this, I think other users can have the same doubt. If you got to this post t...
2,027
53,605,066
I know there are lots of Q&As to extract datetime from string, such as [dateutil.parser](https://stackoverflow.com/questions/3276180/extracting-date-from-a-string-in-python), to extract datetime from a string ``` import dateutil.parser as dparser dparser.parse('something sep 28 2017 something',fuzzy=True).date() outp...
2018/12/04
[ "https://Stackoverflow.com/questions/53605066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1165964/" ]
Extend to the discussion with @Paul and following the solution from @alecxe, I have proposed the following solution, which works on a number of testing cases, I've made the problem slight challenger: **Step 1: get excluded tokens** ``` import dateutil.parser as dparser ostr = 'something sep 28 2017 something abcd' _...
Interesting problem! There is no direct way to get the parsed out date string out of the bigger string with `dateutil`. The problem is that `dateutil` parser does not even have this string available as an intermediate result as it really builds parts of the future `datetime` object on the fly and character by character...
2,028
16,874,010
I am trying to write out a line to a new file based on input from a csv file, with elements from different rows and different columns for example test.csv: ``` name1, value1, integer1, integer1a name2, value2, integer2, integer2a name3, value3, integer3, integer3a ``` desired output: ``` command integer1:integer1a...
2013/06/01
[ "https://Stackoverflow.com/questions/16874010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443424/" ]
For an array you can use the std::vector class. ``` std::vector<account *>MyAccounts; MyAccounts.push_back(new account()); ``` Then you can use it like an array accessing it normally. ``` MyAccounts[i]->accountFunction(); ``` **update** I don't know enough about your code, so I give just some general examples he...
You can do something like below ``` class Bank { public: int AddAccount(Account act){ m_vecAccts.push_back(act);} .... private: ... std:vector<account> m_vecAccts; } ``` Update: This is just a Bank class with vector of accounts as private member variable. AddAccount is public function which can add account to vec...
2,029
45,823,884
So I'm working a quiz on Python as a project for an Intro to Programming course. My quiz works as intended except in the case that the quiz variable is not being affected by the new values of the blank array. On the run\_quiz function I want to make the quiz variable update itself by changing the blanks to the correct...
2017/08/22
[ "https://Stackoverflow.com/questions/45823884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8501849/" ]
The problem is that your variable, `quiz`, is just a fixed string, and although it looks like it has something to do with `blanks`, it actually doesn't. What you want is 'string interpolation'. Python allows this with the `.format` method of `str` objects. This is really the crux of your question, and using string inte...
Only now have I read your question properly. You first make your strings quiz1, quiz2 an quiz3. You only do that once. After that you change your blanks array. But you don't reconstruct your strings. So they still have the old values. Note that a copy of elements of the blanks array is made into e.g. quiz1. That copy...
2,031
72,011,497
I am reading data remote .dat files for EDI data processing. Original Data is some string bytes: ``` b'MDA1MDtWMjAxOS44LjAuMDtWMjAxOS44LjAuMDsyMDIwMD.........' ``` Used decode as below... ``` byte_data = base64.b64decode(byte_data) ``` Gave me this below byte data. Is there a better way to process below bytes da...
2022/04/26
[ "https://Stackoverflow.com/questions/72011497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6837224/" ]
It didn't work with 'utf-8' because it's not 'utf-8', it's probably 'ISO-8859-1' (latin-1) ```py text = byte_data.decode('ISO-8859-1') ``` because `\xf6` is `ΓΆ` in 'ISO-8859-1'
Is it definitely utf-8 encoded? This might help guide to what decoder to use: ``` import chardet print(cardet.detect(byte_data)) ```
2,032
45,209,068
I'm new to python, and now I need to use it to work with some data in a txt file. Here is a sample data, where after each `'&'`, is a new index: ``` uid=aaa&sid=bbb&bid=ccc&cid=ddd&pid=eee&ver=fff... uid=aaa2&sid=bbb2&bid=ccc2&cid=ddd2&pid=eee2&ver=fff2... ... ``` The end result is to have a DataFrame (with pandas)...
2017/07/20
[ "https://Stackoverflow.com/questions/45209068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8336506/" ]
This is a URL querystring. You should use the `urllib` module in the standard library to parse it. ``` from urllib.parse import parse_qs # python3 from urlparse import parse_qs # python2 parse_qs('uid=aaa2&sid=bbb2&bid=ccc2&cid=ddd2&pid=eee2&ver=fff2') ``` Output: ``` {'bid': ['ccc2'], 'cid': ['ddd2'], 'pid': ...
You can use `regex` to create a `list` of all the columns and values and then use it to create your `dataframe`, for example: ``` import re st = 'uid=aaa&sid=bbb&bid=ccc&cid=ddd&pid=eee&ver=fffuid=aaa2&sid=bbb2&bid=ccc2&cid=ddd2&pid=eee2&ver=fff2' myData = re.findall(r'(\wid)=(\w+)', st) prit myData ``` output: ```...
2,033
37,061,089
I installed Jupyter notebooks in Ubuntu 14.04 via Anaconda earlier, and just now I installed TensorFlow. I would like TensorFlow to work regardless of whether I am working in a notebook or simply scripting. In my attempt to achieve this, I ended up installing TensorFlow twice, once using Anaconda, and once using pip. T...
2016/05/05
[ "https://Stackoverflow.com/questions/37061089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4556722/" ]
I installed PIP with Conda `conda install pip` instead of `apt-get install python-pip python-dev`. Then installed tensorflow use [Pip Installation](https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html#test-the-tensorflow-installation): ``` # Ubuntu/Linux 64-bit, CPU only, Python 2.7 $ export TF_BINARY_...
``` pip install tensorflow ``` This worked for me in my conda virtual environment. I was trying to use `conda install tensorflow` in a conda virtual environment where jupyter notebooks was already installed, resulting in many conflicts and failure. But pip install worked fine.
2,035
10,559,144
I am trying to use `suptitle` to print a title, and I want to occationally replace this title. Currently I am using: ``` self.ui.canvas1.figure.suptitle(title) ``` where figure is a matplotlib figure (canvas1 is an mplCanvas, but that is not relevant) and title is a python string. Currently, this works, except for...
2012/05/11
[ "https://Stackoverflow.com/questions/10559144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/402632/" ]
`figure.suptitle` returns a `matplotlib.text.Text` instance. You can save it and set the new title: ``` txt = fig.suptitle('A test title') txt.set_text('A better title') plt.draw() ```
Resurrecting this old thread because I recently ran into this. There is a references to the Text object returned by the original setting of suptitle in figure.texts. You can use this to change the original until this is fixed in matplotlib.
2,045
12,451,124
So I've already graduated and received all credits for my compsci degree. But my professor from my last quarter just sent me an email saying he found something interesting in one of my homework assignments. I forget the context, but I don't think it matters. I'll post the email exchange. --- From: PROF To: ME S...
2012/09/16
[ "https://Stackoverflow.com/questions/12451124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1676273/" ]
Think about how you would call `swap` in Python, versus how you would call a swap function in C. For example, in C, ``` swap(&a, &b); ``` is valid and swaps the memory in `a` with the memory in `b` (assuming the implementation of `swap` is right). But, in Python, ``` swap(a, b) ``` ...does nothing! You'd have t...
I guess his point is that inside a function there's no need to do the swap at all - because the return values of the function aren't tied to the values passed in, so this would do as well: ``` def swap(i, j): return j, i ``` So in fact there's no point in having the function, it doesn't add anything at all. You'...
2,048
32,328,778
Suppose I want to match a string like this: > > 123(432)123(342)2348(34) > > > I can match digits like `123` with `[\d]*` and `(432)` with `\([\d]+\)`. How can match the whole string by repeating either of the 2 patterns? *I tried `[[\d]* | \([\d]+\)]+`, but this is incorrect.* *I am using python re module.*
2015/09/01
[ "https://Stackoverflow.com/questions/32328778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954376/" ]
I think you need this regex: ``` "^(\d+|\(\d+\))+$" ``` and to avoid catastrophic backtracking you need to change it to a regex like this: ``` "^(\d|\(\d+\))+$" ```
You can use a character class to match the whole of string : ``` [\d()]+ ``` But if you want to match the separate parts in separate groups you can use `re.findall` with a spacial regex based on your need, for example : ``` >>> import re >>> s="123(432)123(342)2348(34)" >>> re.findall(r'\d+\(\d+\)',s) ['123(432)', ...
2,053
32,870,262
I am trying to create a program in python in which the user enters a sentence and the reversed sentenced is printed. The code I have so far is: ``` sentence = raw_input('Enter the sentence') length = len(sentence) for i in sentence[length:0:-1]: a = i print a, ``` When the program is run it misses out the l...
2015/09/30
[ "https://Stackoverflow.com/questions/32870262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5342974/" ]
You need to remove the `0` from your indices range, but instead you can use : ``` sentence[length::-1] ``` Also not that then you don't need to loop over your string and use extra assignments and even the `length` you can simply print the reversed string. So the following code will do the job for you : ``` print ...
The second argument of the slice notation means "up to, but not including", so `sentence[length:0:-1]` will loop up to 0, but not at 0. The fix is to explicitly change the 0 to -1, or leave it out (preferred). ``` for i in sentence[::-1]: ```
2,056
10,621,615
I was playing around with iterables and more specifically the `yield` operator in Python. While using test driven development to start writing a new iterable, I wondered what is the shortest code that could make this simple test for an iterable to pass: ```py def test(): for x in my_iterable(): pass ``` ...
2012/05/16
[ "https://Stackoverflow.com/questions/10621615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457/" ]
Yes, there is: ``` return iter([]) ```
``` def do_yield(): return yield None ``` if usage of `yield` is important for you, one of the other answers otherwise.
2,063
64,523,282
I installed anaconda from the [official website](https://www.anaconda.com/) and I want to integrate it with sublime text 3. I tried to build a sublime-build json file like this: ``` { "cmd": ["C:/Users/Minh Duy/anaconda3/python.exe", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", ...
2020/10/25
[ "https://Stackoverflow.com/questions/64523282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12074366/" ]
The DLLs of the mkl-service that it's tried to load are by default located in the following directory: **C:/Users/<username>/anaconda3/Library/bin** since that path isn't in the PATH Environment Variable, it can't find them and raises the ImportError. To fix this, you can: 1. Add the mentioned path to the PATH Envir...
first configure it with python. write python in your cmd to get python path. then configure it with anaconda. ``` { "cmd": ["C:/Users/usr_name/AppData/Local/Programs/Python/Python37-32/python.exe", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python" } ```
2,073
64,708,800
I have been able to successfully detect an object(face and eye) using haar cascade classifier in python using opencv. When the object is detected, a rectangle is shown around the object. I want to get coordinates of mid point of the two eyes. and want to store them in a array. Can any one help me? how can i do this. an...
2020/11/06
[ "https://Stackoverflow.com/questions/64708800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11828549/" ]
Haskell doesn't allow this because it would be ambiguous. The value constructor `Prop` is effectively a function, which may be clearer if you ask GHCi about its type: ``` > :t Const Const :: Bool -> Prop ``` If you attempt to add one more `Const` constructor in the same module, you'd have two 'functions' called `Con...
This is somewhat horrible, but will basically let you do what you want: ```hs {-# LANGUAGE PatternSynonyms, TypeFamilies, ViewPatterns #-} data Prop = PropConst Bool | PropVar Char | PropNot Prop | PropOr Prop Prop | PropAnd Prop Prop | PropImply Prop Prop data Formu...
2,074
53,014,961
It seems like a trivial task however, I can't find a solution for doing this using python. Given the following string: ``` "Lorem/ipsum/dolor/sit amet consetetur" ``` I would like to output ``` "Lorem/ipsum/dolor/sit ametconsetetur" ``` Hence, removing the single whitespace between `amet` and `c...
2018/10/26
[ "https://Stackoverflow.com/questions/53014961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6341510/" ]
use regex and word boundary: ``` >>> s="Lorem/ipsum/dolor/sit amet consetetur" >>> import re >>> re.sub(r"\b \b","",s) 'Lorem/ipsum/dolor/sit ametconsetetur' >>> ``` This technique also handles the more general case: ``` >>> s="Lorem/ipsum/dolor/sit amet consetetur adipisci velit" >>> r...
``` s[::-1].replace(' ', '', 1)[::-1] ``` * Reverse the string * Delete the first space * Reverse the string back
2,075
68,588,398
I would like to define python function which takes a list of dictionaries in which some keys could be lists and then returns a list of list of dictionaries in which each key is a single value, which corresponds to all the combinations of options (an option is picking a single value from each list). Consider the follow...
2021/07/30
[ "https://Stackoverflow.com/questions/68588398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13613091/" ]
If you have all vec lists in a single list of lists using, you can unpack this list when passing it to the product function: ``` list_vecs = [vec, vec2, vec3, vec4] list(product(*list_vecs, repeat=1)) ``` Concerning the \* (star-notation) see the python docs [here](https://docs.python.org/3/tutorial/controlflow.htm...
This solution is almost the same as @mcsoini, but a little more explanation: Here, ``` vec=[['A1','A2','A3'], ['B1','B2'], ['C1','C2','C3'],vec4] ``` `vec` is a list of lists. The first 3 lists are `vec1,2,3`. `vec4` can be added later on. Also, you can add more lists to `vec` using `vec.append(<list>)` Now, instea...
2,078
44,948,661
I am new to python and word2vec and keep getting a "you must first build vocabulary before training the model" error. What is wrong with my code? Here is my code: ``` file_object=open("SupremeCourt.txt","w") from gensim.models import word2vec data = word2vec.Text8Corpus('SupremeCourt.txt') model = word2vec.Word2Vec(...
2017/07/06
[ "https://Stackoverflow.com/questions/44948661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8264914/" ]
Have a look at this: <https://tweepy.readthedocs.io/en/v3.5.0/cursor_tutorial.html> And try this: ``` import tweepy auth = tweepy.OAuthHandler(CONSUMER_TOKEN, CONSUMER_SECRET) api = tweepy.API(auth) for tweet in tweepy.Cursor(api.search, q='#python', rpp=100).items(): # Do something pass ``` In your case ...
Check twitter api documentation, probably it allows just 300 tweets to parse. I would recommend to forget api, make it with requests with streaming. The api is an implementation of requests with limitations.
2,079
55,013,809
OK I was afraid to use the terminal, so I installed the python-3.7.2-macosx10.9 package downloaded from python.org Ran the certificate and shell profile scripts, everything seems fine. Now the "which python3" has changed the path from 3.6 to the new 3.7.2 So everything seems fine, correct? My question (of 2) is what'...
2019/03/06
[ "https://Stackoverflow.com/questions/55013809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9291766/" ]
Yes, you can install Python 3.7 or Python 3.8 using installer that you can download from [python.org](https://www.python.org/downloads/). It doesn't automatically delete the older version that you can keep using the older version. For example, if you have `python3.7` and `python3.8`, you can run either one on your te...
Each version of the Python installation is independent of each other. So its safe to delete the version you don't want, but be cautious of this because it can lead to broken dependencies :-). You can run any version by adding the specific version i.e $python3.6 or $python3.7 The best approach is to use virtual enviro...
2,085
32,736,350
I did found quite a lot about this error, but somehow none of the suggested solutions resolved the problem. I am trying to use JNA bindings for libgphoto2 under Ubuntu in Eclipse (moderate experience with Java on Eclipse, none whatsoever on Ubuntu, I'm afraid). The bindings in question I want to use are here: <http://...
2015/09/23
[ "https://Stackoverflow.com/questions/32736350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4428658/" ]
In addition to what @Paul Whelan has said. You might have better luck by just get the missing jar directly. Get the missing library [here](https://github.com/java-native-access/jna), set the classpath and then re-run the application again and see whether it will run fine or not.
What version of java are you using com/sun/jna/Structure may only work with certain JVMs. In general, packages such as sun.*, that are outside of the Java platform, can be different across OS platforms (Solaris, Windows, Linux, Macintosh, etc.) and can change at any time without notice with SDK versions (1.2, 1.2.1, 1...
2,086
45,384,065
I am looking for a way to run a method every second, regardless of how long it takes to run. In looking for help with that, I ran across [Run certain code every n seconds](https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds) and in trying it, found that it doesn't work correctly. It appears t...
2017/07/29
[ "https://Stackoverflow.com/questions/45384065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8217211/" ]
1. Don't use a `threading.Timer` if you don't actually need a new thread each time; to run a function periodically `sleep` in a loop will do (possibly in a single separate thread). 2. Whatever method you use to schedule the next execution, don't wait for the exact amount of time you use as interval - execution of the o...
I'm pretty sure the problem with that code is that it takes Python some time (apparently around .3s) to execute the call to your function `woof`, instantiate a new `threading.Timer` object, and print the current time. So basically, after your first call to the function, and the creation of a `threading.Timer`, Python w...
2,088
6,686,576
What i'm trying to achieve is playing a guitar chord from my python application. I know (or can calculate) the frequencies in the chord if needed. I'm thinking that even if I do the low level leg work of producing multiple sine waves at the right frequencies it wont sound right due to the envelope needing to be correc...
2011/07/13
[ "https://Stackoverflow.com/questions/6686576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384388/" ]
a) The hackish way is to spawn a background subprocess to run each `play` command. Since a background subprocess doesn't make the shell wait for it to finish, you can have multiple `play`s running at once. Something like this would work: ``` for p in "C3" "E3" "G3"; do ( play -n synth 3 pluck $p & ); done ``` I see ...
*a) is it possible to shoehorn the play command to do a whole chord... ?* If your sound architecture supports it, you can run multiple commands that output audio at the same time. If you're using ALSA, you need dmix or other variants in your `~/.asoundrc`. Use `subprocess.Popen` to spawn many child processes. If this ...
2,089
27,643,383
I am trying to install the elastic beanstalk CLI on an EC2 instance (running AMI) using these instructions: <http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-getting-started.html> I have python 2.7.9 installed, pip and eb. However, when I try to run eb I get the error below. It looks like it is still usi...
2014/12/25
[ "https://Stackoverflow.com/questions/27643383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536188/" ]
Pip is probably set up with Python 2.6 instead of python 2.7. ``` pip --version ``` You can reinstall pip with Python 2.7, then reinstall 2.6 ``` pip uninstall awsebcli wget https://bootstrap.pypa.io/get-pip.py python get-pip.py pip install awsebcli ```
The "smartest" solution for me was to install python-dev tools sudo apt install python-dev found here: <http://ericbenson.azurewebsites.net/deployment-on-aws-elastic-beanstalk-for-ubuntu/>
2,092
69,437,836
I was trying to make a program that can make classification between runway and taxiway using mask rcnn. after importing custom dataset in json format I am getting key error ``` class CustomDataset(utils.Dataset): def load_custom(self, dataset_dir, subset): """Load a subset of the Horse-Man dataset. ...
2021/10/04
[ "https://Stackoverflow.com/questions/69437836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16702137/" ]
I think it should be `name`, not `names`, based on the file format in the comment: ``` { 'filename': '28503151_5b5b7ec140_b.jpg', 'regions': { '0': { 'region_attributes': {}, 'shape_attributes': { 'all_points_x': [...], 'all_points_y': [...], ...
i resolved this error by rechecking my annotations in VGG tool and found that i double labeled (wrongly labeled) two file. so my suggestion is to recheck all files in VGG Annotation Tool and check for missing or multiple times labelled files. Thanks
2,095
13,352,296
The following works and returns a list of all users ``` ldapsearch -x -b "ou=lunchbox,dc=office,dc=lbox,dc=com" -D "OFFICE\Administrator" -h ad.office.lbox.com -p 389 -W "(&(objectcategory=person)(objectclass=user))" ``` I'm trying to do the same in Python and I'm getting `Invalid credentials` ``` #!/usr/bin/env py...
2012/11/12
[ "https://Stackoverflow.com/questions/13352296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1039166/" ]
You're using different credentials for the bind from the command line and the python script. The command line is using the bind dn of `OFFICE\Administrator` while the script is using the bind dn of `cn=Administrator,dc=office,dc=lbox,dc=com` On Active Directory, the built-in account `Administrator` doesn't reside at ...
The python-ldap library does not parse the user name, neither does ldapsearch. In you code, simply use the same username `OFFICE\Administrator` and let Active Directory handle it. Also it is not uncommon for ActiveDirectory to refuse simple bind over ldap. You must use LDAPS. Add this line to bypass certificat checkin...
2,096
53,157,921
Please excuse my silly question as I am really new to python. I have 20 different .txt files (eg `"myfile_%s"` with `s` having been attributed to an integer in range=1,21). So I load them as follows: ``` runs=range(1,21) for i in runs: Myfile=np.loadtxt("myfile_%s.txt" %i, delimiter=',', unpack=True) ``` Hen...
2018/11/05
[ "https://Stackoverflow.com/questions/53157921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10042405/" ]
You can split using your delimiter and load into a native python list: ``` my_files = [] for i in range(1,21): with open("my_file_{0}.txt".format(i), 'r') as f: my_files.append(f.read().split(',')) ``` Now you have a list of lists. You can get the max overall, or get the max of each list, like so: ``` ...
Are your lists of equal length? If yes, you can do everything in one numpy array: ``` a = np.zeros((100,20)) for i in range(1,21): a[i-1,:]=np.loadtxt("myfile_%s.txt" %i, delimiter=',', unpack=True) ``` Now you can do all `numpy` functions on the resulting array such as ``` b = np.sum(a,axis=0) ```
2,097
56,066,816
I have several data frames (with equal # columns but different names). I'm trying to create one data frame with rows stacked below each other. I don't care now about the column names (I can always rename them later). I saw different SO links but they don't address this problem completely. Note I've 21 data frames and...
2019/05/09
[ "https://Stackoverflow.com/questions/56066816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9473446/" ]
Assuming your DataFrames are stored in some list `df_l`: Rename the columns and concat: ``` df_l = [df1, df2, df3] for df in df_l: df.columns = df_l[0].columns # Just chose any DataFrame pd.concat(df_l) # Columns named with above DataFrame # Index is preserved ``` Or construct a new DataFram...
Once you put all the data frames into a list, try this code. ``` import pandas as pd df = [df1, df2, df3] result = pd.DataFrame(columns=df1.columns) for df in df: result = pd.concat([result,df.rename(columns=df1.columns)], ignore_index=True) ```
2,098
6,774,561
I have a python code treating a lot of apache logs (decompress, parse, crunching numbers, regexping etc). One parent process which takes a list of files (up to few millions), and sends a list of files to parse to workers, using multiprocess pool. I wonder, if there is any guidelines / benchmarks / advices which can h...
2011/07/21
[ "https://Stackoverflow.com/questions/6774561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/129289/" ]
> > I wonder, if there is any guidelines / benchmarks / advices which can help me to estimate ideal number of child process ? > > > No. > > having one process per core is better than launching few hundreds of them? > > > You can never know *in advance*. There are too many degrees of freedom. You can only...
I'll address the last question first. In CPython, it is next to impossible to make sizeable performance gains by distributing CPU-bound load across threads. This is due to the [Global Interpreter Lock](http://en.wikipedia.org/wiki/Global_Interpreter_Lock). In that respect [`multiprocessing`](http://docs.python.org/libr...
2,101
28,191,221
I used SQL to convert a social security number to MD5 hash. I am wondering if there is a module or function in python/pandas that can do the same thing. My sql script is: ``` CREATE OR REPLACE FUNCTION MD5HASH(STR IN VARCHAR2) RETURN VARCHAR2 IS V_CHECKSUM VARCHAR2(32); BEGIN V_CHECKSUM := LOWER(RAWTOHEX(UTL_RAW...
2015/01/28
[ "https://Stackoverflow.com/questions/28191221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2201603/" ]
Using the standard hashlib module: ``` import hashlib hash = hashlib.md5() hash.update('555555555') print hash.hexdigest() ``` **output** ``` 3665a76e271ada5a75368b99f774e404 ``` As mentioned in timkofu's comment, you can also do this more simply, using ``` print hashlib.md5('555555555').hexdigest() ``` The ...
hashlib with `md5` might be of your interest. ``` import hashlib hashlib.md5("Nobody inspects the spammish repetition").hexdigest() ``` output: ``` bb649c83dd1ea5c9d9dec9a18df0ffe9 ``` Constructors for hash algorithms that are always present in this module are `md5(), sha1(), sha224(), sha256(), sha384(), and sh...
2,105
39,361,496
I am a python coder but recently started a forey into Java. I am trying to understand a specific piece of code but am running into difficulties which I believe are associated with not knowing Java too well, yet. Something that stood out to me is that sometimes inside class definitions methods are called twice. I am wo...
2016/09/07
[ "https://Stackoverflow.com/questions/39361496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2439540/" ]
The class is really not instantiating itself twice. Rather, the default constructor `ApplicationCreator()` (i.e. the one which takes no parameters), is simply calling the constructor which accepts an input string. This ensures that an `ApplicationCreator` object will always have a type. When a type is not specified th...
Here this class has two constructor. When class name "method" name are same you can understand those are constructor. Here constructor is over loaded . Based on parameter classes will be instantiated. Here user have a choice based on need .
2,106
4,088,471
I have a dictionary in the view layer, that I am passing to my templates. The dictionary values are (mostly) lists, although a few scalars also reside in the dictionary. The lists if present are initialized to None. The None values are being printed as 'None' in the template, so I wrote this little function to clean o...
2010/11/03
[ "https://Stackoverflow.com/questions/4088471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/461722/" ]
Have you looked at `defaultdict` within collections? You'd have a dictionary formed via ``` defaultdict(list) ``` which initializes an empty list when a key is queried and that key does not exist.
``` filtered_dict = dict((k, v) for k, v in table.items() if v is not None) ``` or in Python 2.7+, use the dictionary comprehension syntax: ``` filtered_dict = {k: v for k, v in table.items() if v is not None} ```
2,116
45,125,441
I have a dataframe that has a column of boroughs visited (among many other columns): ``` Index User Boroughs_visited 0 Eminem Manhattan, Bronx 1 BrSpears NaN 2 Elvis Brooklyn 3 Adele Queens, Brooklyn ``` **I want to create a third column that shows which User visited Brooklyn**, so I...
2017/07/16
[ "https://Stackoverflow.com/questions/45125441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8005777/" ]
Let use `.str` accessor with `contains` and `fillna`: ``` df['Brooklyn'] = (df.Boroughs_visited.str.contains('Brooklyn') * 1).fillna(0) ``` Or another format of the same statement: ``` df['Brooklyn'] = df.Boroughs_visited.str.contains('Brooklyn').mul(1, fill_value=0) ``` Output: ``` Index User Borou...
You can get all Boroughs for the price of one ``` df.join(df.Boroughs_visited.str.get_dummies(sep=', ')) Index User Boroughs_visited Bronx Brooklyn Manhattan Queens 0 0 Eminem Manhattan, Bronx 1 0 1 0 1 1 BrSpears NaN 0 0 0 ...
2,117
13,409,559
I'm trying to replace all single quotes with double quotes, but leave behind all escaped single quotes. Does anyone know a simple way to do this with python regexs? ``` Input: "{ 'name': 'Skrillex', 'Genre':'Dubstep', 'Bass': 'Heavy', 'thoughts': 'this\'s ahmazing'}" output: "{ "name": "Skrillex", "Genre": "Dubstep"...
2012/11/16
[ "https://Stackoverflow.com/questions/13409559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432960/" ]
This is kind of...odd, but it may work. Remember to preface your string with `r` to denote a raw string so that we can remove the backslashes: ``` In [19]: s = r"{ 'name': 'Skrillex', 'Genre':'Dubstep', 'Bass': 'Heavy', 'thoughts': 'this\'s ahmazing'}" In [20]: s.replace("\\'", 'REPLACEMEOHYEAH').replace("'", '"').rep...
1. replace all the \' into a magic word 2. replace all the ' into " 3. replace all the magic words back to \'
2,118
68,570,102
Basically, I'm trying to build a code to get the largest number from the user's inputs. This is my 1st time using a for loop and I'm pretty new to python. This is my code: ``` session_live = True numbers = [] a = 0 def largest_num(arr, n): #Create a variable to hold the max number max = arr[0] #Using for...
2021/07/29
[ "https://Stackoverflow.com/questions/68570102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16420917/" ]
The error in your `largest_num` function is that it returns in the first iteration -- hence it will only return the larger of the first two numbers. Using the builtin `max()` function makes life quite a bit easier; any time you reimplement a function that already exists, you're creating work for yourself and (as you'v...
I made it without using the built-in function 'max'. It is a way to update the 'maxNum' variable with the largest number by comparing through the for statement. ```py numbers = [] while True: print("Tell us a number") numbers.append(int(input())) print("Continue? (Y/N)") confirm = input() i...
2,119
5,633,067
I have a pylons project where I need to update some in-memory structures periodically. This should be done on-demand. I decided to come up with a signal handler for this. User sends `SIGUSR1` to the main pylons thread and it is handled by the project. This works except after handling the signal, the server crashes wi...
2011/04/12
[ "https://Stackoverflow.com/questions/5633067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/408426/" ]
Yes, it is possible, but not easy using the stock Python libraries. This is due to Python translating all OS errors to exceptions. However, EINTR should really cause a retry of the system call used. Whenever you start using signals in Python you will see this error sporadically. I have [code that fixes this](http://co...
A fix, at least works for me, from an [12 year old python-dev list post](http://mail.python.org/pipermail/python-dev/2000-October/009671.html) ``` while True: try: readable, writable, exceptional = select.select(inputs, outputs, inputs, timeout) except select.error, v: if v[...
2,121
57,507,832
I'm facing an issue with allocating huge arrays in numpy on Ubuntu 18 while not facing the same issue on MacOS. I am trying to allocate memory for a numpy array with shape `(156816, 36, 53806)` with ``` np.zeros((156816, 36, 53806), dtype='uint8') ``` and while I'm getting an error on Ubuntu OS ``` >>> import num...
2019/08/15
[ "https://Stackoverflow.com/questions/57507832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5123537/" ]
I had this same problem on Window's and came across this solution. So if someone comes across this problem in Windows the solution for me was to increase the [pagefile](https://whatis.techtarget.com/definition/pagefile) size, as it was a Memory overcommitment problem for me too. Windows 8 1. On the Keyboard Press the...
change the data type to another one which uses less memory works. For me, I change the data type to numpy.uint8: ``` data['label'] = data['label'].astype(np.uint8) ```
2,122
10,643,982
Is there a way in python to truncate the decimal part at 5 or 7 digits? If not, how can i avoid a float like e\*\*(-x) number to get too big in size? Thanks
2012/05/17
[ "https://Stackoverflow.com/questions/10643982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308318/" ]
Either catch the `OverflowError` or use the `decimal` module. Python is not going to assume you were okay with the overflow. ``` >>> 0.0000000000000000000000000000000000000000000000000000000000000001**-30 Traceback (most recent call last): File "<stdin>", line 1, in <module> OverflowError: (34, 'Result too large') >...
The "Result too large" doesn't refer to the number of characters in the decimal representation of the number, it means that the number that resulted from your exponential function is large enough to overflow whatever type python uses internally to store floating point values. You need to either use a different type to...
2,132
56,814,981
the following code gives me the python error 'failed to parse' addon.xml: (I've used an online checker and it says "error on line 33 at column 15: Opening and ending tag mismatch: description line 0 and extension" - which is the very end of the /extension end tag at the end of the document). Any advice would be appre...
2019/06/29
[ "https://Stackoverflow.com/questions/56814981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11611598/" ]
Your "XML" file is not well-formed, so it cannot be parsed. Find out how it was created, correct the process so the problem does not occur again, and then regenerate the file. Files that are vaguely XML-like but not well-formed are pretty well useless. Repair is sometimes possible if the errors are very systematic, bu...
Most of the time a "failed to parse" error msg is due to the XML File itself. Check you're XML File for the correct formatting. I once forgot the root tag and had the same error message.
2,135
55,197,425
Ok so here is what I am trying to archieve: 1. Call a URL with a list of dynamically filtered search results 2. Click on the first search result (5/page) 3. Scrape the headlines, paragraphs and images and store them as a json object in a a seperate file e.g. { "Title": "Headline element of the individual entry", ...
2019/03/16
[ "https://Stackoverflow.com/questions/55197425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4536968/" ]
You can use only `requests` and `BeautifulSoup` to scrape, without Selenium. It will be much faster and will consume much less resources: ``` import json import requests from bs4 import BeautifulSoup # Get 1000 results params = {"$filter": "TemplateName eq 'Application Article'", "$orderby": "ArticleDate desc", "$top...
You aren’t using your link variable anywhere in your loop, just telling the driver to find the top link and click it. (When you use the singular find\_element selector and there are multiple results selenium just grabs the first one). I think all you need to do is replace these lines ``` searchResult = driver.find_e...
2,136
34,771,191
I just upgraded to the latest stable release of `matplotlib` (1.5.1) and everytime I import matplotlib I get this message: ``` /usr/local/lib/python2.7/dist-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment. warnings.warn('Matplotlib is ...
2016/01/13
[ "https://Stackoverflow.com/questions/34771191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497180/" ]
This worked for me on Ubuntu **16.04 LST** with **Python 3.5.2 | Anaconda 4.2.0 (64-bit)**. I deleted all of the files in `~/.cache/matplotlib/`. ``` sudo rm -r fontList.py3k.cache tex.cache ``` At first I thought it wouldn't work, because I got the warning afterward. But after the cache files were rebuilt the warn...
This worked for me: ``` sudo apt-get install libfreetype6-dev libxft-dev ```
2,140
68,616,659
I am trying to find all instance of a number within an equation. And for that, I wrote this python script: ``` re.findall(fr"([\-\+\*\/\(]|^)({val})([\-\+\*\/\)]|$)", equation) ``` Now, when I give it this: `20+5-20`, and search for `20`, the output is as expected: `[('', '20', '+'), ('-', '20', '')]` But, when I si...
2021/08/02
[ "https://Stackoverflow.com/questions/68616659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8754028/" ]
The reason your pattern initially does not work for `20+20-5` is that the character class after matching the first occurrence of 20 actually consumes the `+` After consuming it, for the second occurrence of 20 right after it, this part of the pattern `[\-\+\*\/\(]|^)` can not match as there is no character to match wi...
I suggest just searching for all numbers (integer + decimal) in your expression, and then filtering for certain values: ```py inp = "20+5-20*3.20" matches = re.findall(r'\d+(?:\.\d+)?', inp) matches = [x for x in matches if x == '20'] print(matches) # ['20', '20'] ``` Every number in your formula should *only* be s...
2,150
51,132,025
I want to create a folder after an hour of the current time in python. I know how to get the current time and date and to create a folder. But how to create a folder at a time specified by me. Any help would be appreciated. ``` from datetime import datetime from datetime import timedelta import os while True: now...
2018/07/02
[ "https://Stackoverflow.com/questions/51132025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10020438/" ]
Try this simple code ``` import os import time while True: time.sleep(3600) # pending for 1 hour (3600 seconds) os.makedirs(your directory) # create the directory ``` EDIT (using parallel programming) ``` import os import time from datetime import datetime from multiprocessing import Pool def create_folde...
check this post for better explanation,you can create a function which will run after given time and you can use this function for creating a folder by simple one line code os.makedirs("path\directory name") [Python - Start a Function at Given Time](https://stackoverflow.com/questions/11523918/python-start-a-function-a...
2,152
42,696,635
I am trying to use the owlready library in Python. I downloaded the file from link(<https://pypi.python.org/pypi/Owlready>) but when I am importing owlready I am getting following error: ``` >>> from owlready import * Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named '...
2017/03/09
[ "https://Stackoverflow.com/questions/42696635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5879314/" ]
Try installing it using `pip` instead. Run the command `pip install <module name here>` to do so. If you are using python3, run `pip3 install <module name here>`. If neither of these work you may also try: `python -m pip install <module name here>` or `python3 -m pip install <module name here>` If you don't yet ...
You need installed library: ``` C:\PythonX.X\Scripts pip install owlready Successfully installed Owlready-0.3 ```
2,154
69,969,792
So, I have to write a code in python that will draw four squares under a function called draw\_square that will take four arguments: the canvas on which the square will be drawn, the color of the square, the side length of the square, and the position of the center of the square. This function should draw the square an...
2021/11/15
[ "https://Stackoverflow.com/questions/69969792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17414982/" ]
Use `my_canvas.create_rectangle(...)`. You were calling a draw rectangle from your function rather than the canvas itself. Extra info: [Tkinter Canvas creating rectangle](https://stackoverflow.com/questions/42039564/tkinter-canvas-creating-rectangle)
you need to do following: my\_canvas.create\_rectangle(...) my\_canvas.pack() ... ... after you finish for all 4 squares drawing and packing you need to call function like following: draw\_square() root.mainloop()
2,155
50,505,067
I have a simple DAG ``` from airflow import DAG from airflow.contrib.operators.bigquery_operator import BigQueryOperator with DAG(dag_id='my_dags.my_dag') as dag: start = DummyOperator(task_id='start') end = DummyOperator(task_id='end') sql = """ SELECT * FROM 'another_dataset...
2018/05/24
[ "https://Stackoverflow.com/questions/50505067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5715610/" ]
You first need to create an Empty partitioned destination table. Follow instructions here: [link](https://cloud.google.com/bigquery/docs/creating-column-partitions#creating_an_empty_partitioned_table_with_a_schema_definition) to create an empty partitioned table and then run below airflow pipeline again. You can try c...
The main issue here is that I don't have access to the new version of google cloud python API, the prod is using version [0.27.0](https://gcloud-python.readthedocs.io/en/stable/bigquery/usage.html). So, to get the job done, I made something bad and dirty: * saved the query result in a sharded table, let it be `table_...
2,156
69,795,302
I am a beginner in python so please be gentle and if you do have an answer please provide details. I just installed the most recent python version 3.10 after making sure to delete all previous installations (including anaconda). I am positive my system is clear of any prior installation. after installing python 3.10 ...
2021/11/01
[ "https://Stackoverflow.com/questions/69795302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5159404/" ]
You can refer to this answer solution with the highest upvotes - [Windows reports error when trying to install package using pipenv](https://stackoverflow.com/questions/46041719/windows-reports-error-when-trying-to-install-package-using-pipenv/46041892#46041892) Or refer to this GitHub issue on pipenv - <https://githu...
Did follow the suggested steps, but did not work, Later, set the `C:\Users\xxxxxxx\AppData\Roaming\Python\Python310\Scripts` to "PATH" environment variable and relaunched the cmd. It worked like a charm... Note: During the installation itself it warns to set the `C:\Users\xxxxxxx\AppData\Roaming\Python\Python310\Scri...
2,159
20,590,331
On my local PC I can do "python manage.py runserver" and the site runs perfectly, CSS and all. I just deployed the site to a public server and while most things work, CSS (and the images) are not loading into the templates. I found some other questions with a similar issue, but my code did not appear to suffer from an...
2013/12/15
[ "https://Stackoverflow.com/questions/20590331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1803100/" ]
In Winforms(or even in WPF) only the thread who create the component can update it you should make your code thread-safe. For this reason the debugger raises an InvalidOperationException with the message, "Control control name accessed from a thread other than the thread it was created on." which is encapsulated as Agg...
Another option to use a Task result within the calling thread is using `async/await` key word. This way compiler do the work of capture the right `TaskScheduler` for you. Look code below. You need to add `try/catch` statements for Exceptions handling. This way, code is still asynchronous but looks like a synchronous o...
2,164
69,628,226
I have made an browser with python. I converted it into exe file with pyinstaller. But it's size is 109,426kb!!! I need to upload it to some places and it is showing "Please try to upload files under 25md". What will I do? How to change this big exe file 24mb file?
2021/10/19
[ "https://Stackoverflow.com/questions/69628226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15622728/" ]
If you have task that is re-run with the same "Execution Date", using Airflow Variables is your best choice. XCom will be deleted by definition when you re-run the same task with the same execution date and it won't change. Basically what you want to do is to store the "state" of task execution and it's kinda "against...
You could use XComs with `include_prior_dates` parameter. [Docs](https://airflow.apache.org/docs/apache-airflow/stable/_api/airflow/models/taskinstance/index.html#airflow.models.taskinstance.TaskInstance.xcom_pull) state the following: > > **include\_prior\_dates** (bool) -- If False, only XComs from the current exec...
2,166
68,653,388
I want to replace the values in manifest.json. My manifest.json file looks like ``` { "uat1": { "database": { "artifact_version": "0.0.1", "date": "sysdate" }, "services1": { "artifact_version": "0.0.1", "date": "sysdate" }, "p_database": { "artifact_version": "0....
2021/08/04
[ "https://Stackoverflow.com/questions/68653388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4632240/" ]
Just parse it, update the necessary value, and write it back to the file. ``` with open("manifest.json") as f: d = json.load(f) d[env][script] = {"artifact_version": ..., "date": ...} with tempfile.NamedTemporaryFile(delete=False) as f: try: json.dump(d, f) except Exception: raise els...
No, to 'edit' a `json` file, you have to load the whole file in with: `data = json.load(f1)`, then perform the transform, then write the write the whole lot out again: ```py with open("C:/Users/lohapri/PycharmProjects/RFOS/manifest.json", "r") as f1: data = json.load(f1) #no close needed #print(data) for k1, v1 i...
2,167
59,939,819
I am trying to run Django unit tests in the VSCode Test Explorer, also, I want the CodeLens 'Run Tests' button to appear above each test. [enter image description here](https://i.stack.imgur.com/kTTjN.png) However, in the Test Explorer, When I press the Play button, an error displays: "No Tests were Ran" [No Tests were...
2020/01/27
[ "https://Stackoverflow.com/questions/59939819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12064691/" ]
Please consider the following checks: 1. you should have `__init__.py` in your test directory 2. in vscode on test configuration use pytest framework 3. use: `pip install pytest-django` 4. copy `pytest.ini` in the root with this content: ``` # -- FILE: pytest.ini (or tox.ini) [pytest] DJANGO_SETTINGS_MODULE = <your-w...
I've been looking into this as well. The thing is that python unittest pytest and nose are not alternative to Django tests, because they would not be able to load everything Django tests do. Django Test Runner might work for you: <https://marketplace.visualstudio.com/items?itemName=Pachwenko.django-test-runner> -- I ...
2,170
33,551,878
I'm having a problem to read partitioned parquet files generated by Spark in Hive. I'm able to create the external table in hive but when I try to select a few lines, hive returns only an "OK" message with no rows. I'm able to read the partitioned parquet files correctly in Spark, so I'm assuming that they were genera...
2015/11/05
[ "https://Stackoverflow.com/questions/33551878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5529573/" ]
I finally found the problem. When you create tables in Hive, where partitioned data already exists in S3 or HDFS, you need to run a command to update the Hive Metastore with the table's partition structure. Take a look here: <https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DDL#LanguageManualDDL-RecoverP...
Even though this Question was answered already, the following point may also help the users who are still not able to solve the issue just by `MSCK REPAIR TABLE table_name;` I have an hdfs file system which is partitioned as below: `<parquet_file>/<partition1>/<partition2>` eg: `my_file.pq/column_5=test/column_6=5` ...
2,173
12,177,405
Dear python 3 experts, with python2, one could do the following (I know this is a bit hairy, but that's not the point here :p): ``` class A(object): def method(self, other): print self, other class B(object): pass B.method = types.MethodType(A().method, None, B) B.method() # print both A and B instances ``` ...
2012/08/29
[ "https://Stackoverflow.com/questions/12177405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853679/" ]
``` B.method = lambda o: A.method(o,A()) b = B() b.method() ``` the line `b.method()` then calls `A.method(b,A())`. This means a A is initialized each time. To avoid this: ``` a = A() B.method = lambda o: A.method(o,a) ``` now every time you call b.method() on any instance of B the same instance of A is passed as...
Well, your code doesn't work in Python 2 either, but I get what you are trying to do. And you can use lambda, as in Sheena's answer, or functools.partial. ``` >>> import types >>> from functools import partial >>> class A(object): ... def method(self, other): ... print self, other ... >>> class B(object): pass...
2,174
46,395,273
First post here at stack overflow. Please forgive my posting errors. I have spent a lot of time at this. I started with the 500 server error. This long is stating python not found. My app is JS, CSS, and HTML only. (at this point) I have included the yaml, because I cant rule out for myself if I have errors there ...
2017/09/24
[ "https://Stackoverflow.com/questions/46395273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4907940/" ]
If your app is only HTML, CSS, and JS, you can remove the catch-all pointer to the Python script all together and instead use an `app.yaml` format like the one shown in the [Hosting a Static Website on App Engine tutorial](https://cloud.google.com/appengine/docs/standard/python/getting-started/hosting-a-static-website#...
Your `script: main.py` statement in the `handlers` section of the `app.yaml` file is wrong, it should be `script: main.app`. From the `script` row in the [Handlers element](https://cloud.google.com/appengine/docs/standard/python/config/appref#handlers_element) table (sadly not properly formatted, including the quote ...
2,175
61,206,895
the python script does execute well manually through the terminal: ``` sudo python3 /home/pi/Documents/AlarmClock/alarm.py ``` but it does not work automatically by the crontab. Here is the cronjob (crontab -e) in the /tmp/crontab.iGf7md/crontab file: ``` 32 13 2 * * sudo python3 /home/pi/Documents/AlarmClock/alarm...
2020/04/14
[ "https://Stackoverflow.com/questions/61206895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use `array_keys` with search value [PHP Doc](https://www.php.net/manual/en/function.array-keys.php) [Demo](https://3v4l.org/kfTZH) ``` array_keys($arr,3) ``` --- > > `array_keys()` returns the keys, numeric and string, from the array. > > > If a search\_value is specified, then only the keys for that va...
With that solution you can create complex filters. In this case we compare every value to be the number three (=== operator). The filter returns the index, when the comparision true, else it will be dropped. ``` $a = [1,2,3,4,3,3,5,6]; $threes = array_filter($a, function($v, $k) { return $v === 3 ? $k : false; }, ...
2,176
43,967,051
What is an alternative to firebase for user management/auth for python apps. I know I can use node.js w/ firebase but, I would rather authenticate users through a managed 3rd party API in python using HTTPS requests,if possible. Appery.io has this feature but, I do not need all that comes with appery.io
2017/05/14
[ "https://Stackoverflow.com/questions/43967051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7317396/" ]
Check out [Amazon Cognito](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&ved=0ahUKEwjphrjN7-PXAhUEhuAKHSABA14QFggnMAA&url=https%3A%2F%2Faws.amazon.com%2Fcognito%2F&usg=AOvVaw0IxXy-fQjM_msyj67tH2wG) . They offer a quite nice package for small projects. [Backendless](http://backendless.co...
You could try using [Auth0](https://auth0.com/) for pure authentication management. The Auth0 python package can be found [here](https://github.com/auth0/auth0-python).
2,178
16,973,236
I recently installed Emacs 24.3 and try to use it coding for Python (v3.3.2 x86-64 MSI installer). (I'm new to Emacs). Then i try to install emacs-for-python by unpack the zip to ``` "C:\Users\mmsc\AppData\Roaming\.emacs.d\emacs-for-python" ``` folder and add ``` : (load-file "~/.emacs.d/emacs-for-python/epy-ini...
2013/06/06
[ "https://Stackoverflow.com/questions/16973236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2118555/" ]
This was a little too much for a comment: ``` (let ((process (apply 'start-process "pymacs" buffer (let ((python (getenv "PYMACS_PYTHON"))) (if (or (null python) (equal python "")) pymacs-python-command python)) ...
I had the same symptoms but what my problem turned out to be was an old pymacs.el and a new Pymacs. Evidently Pymacs changed the module interface and I had to go hunt down the stray pymacs.el. So the pymacs.el was installed by apt-get in an odd location. You have to make sure the byte code file is gone too.
2,181
55,784,213
Noob, trying to create a simple form, and validate the inputs on same. However, I don't know how to properly select each input in js, so nothing is happening. I am just learning html, bootstrap and javascript, so simpler (pythonic) answers are preferred to more complex ones. I've read the documentation, and a number ...
2019/04/21
[ "https://Stackoverflow.com/questions/55784213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8519006/" ]
The reason for partial match is that engine doesn't know exactly where it should start from regarding your requirements. You tell engine by including `\d` in character class: ``` (?<![[:space:][:punct:]\d])\d+ ^^ ```
[This RegEx](https://regex101.com/r/ruSstp/1/) might help you to divide your string input into two groups, where the second group (`$2`) is the target number and group one (`$1`) is the non-digit behind it: ``` ([A-Za-z_+-]+)([0-9]+) ``` [![RegEx](https://i.stack.imgur.com/ubaKl.png)](https://i.stack.imgur.com/ubaKl...
2,182
58,211,638
I want to connect to Twitch server. But Godot adds binary characters in front of my data as you can see in the pictures. This happens everytime no matter the data type. Why is this happenning and how can I prevent this happening? [![python socket server output image](https://i.stack.imgur.com/14N2l.png)](https://i.s...
2019/10/03
[ "https://Stackoverflow.com/questions/58211638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10558295/" ]
You can use shapes as well with your background modifier instead using a Color. Change ``` }.overlay( RoundedRectangle(cornerRadius: 40) .stroke(Color.green, lineWidth: 1) ).background(Color.gray) ``` to ``` }.overlay( RoundedRectangle(cornerRadius: 40) .stroke(Color.green, lineWidth: 1)...
What you need is one more modifier to cut off anything outside the thin green outline, add this after `.background`: ``` .clipShape(RoundedRectangle(cornerRadius: 40)) ``` **EDIT** Capsule is a better shape to use in place of RoundedRectangle to achieve matching curves: ``` var body: some View { HStack { ...
2,183
31,154,087
I am developing flask app. I made one table which will populate with JSON data. For Front end I am using Angularjs and for back-end I am using flask. But I am not able to populate the table and getting error like "**UndefinedError: 'task' is undefined.**" **Directory of flask project** flask\_project/ rest-server....
2015/07/01
[ "https://Stackoverflow.com/questions/31154087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4884941/" ]
i think it's because you have two ng-app definitions in your index.html remove the definition in your html tag and try again ``` <html ng-app="tableJson"> ``` into ``` <html> ```
Try this ``` $scope.tasks = data; ``` it works for me
2,184