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
211,046
What's a good way to generate an icon in-memory in python? Right now I'm forced to use pygame to draw the icon, then I save it to disk as an .ico file, and then I load it from disk as an ICO resource... Something like this: ``` if os.path.isfile(self.icon): icon_flags = win32con.LR_LOADFROMFILE | win32con...
2008/10/17
[ "https://Stackoverflow.com/questions/211046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
You can use [wxPython](http://wxpython.org/) for this. ``` from wx import EmptyIcon icon = EmptyIcon() icon.CopyFromBitmap(your_wxBitmap) ``` The [wxBitmap](http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmap) can be generated in memory using [wxMemoryDC](http://docs.wxwidgets.org/stable/wx_wxmemorydc.html#wx...
You can probably create a object that mimics the python file-object interface. <http://docs.python.org/library/stdtypes.html#bltin-file-objects>
11,993
34,195,014
I have a dataframe that has aggregated people by location like so ``` location_id | score | number_of_males | number_of_females 1 | 20 | 2 | 1 2 | 45 | 1 | 2 ``` I want to create a new dataframe that unaggregated this one so I get something like ...
2015/12/10
[ "https://Stackoverflow.com/questions/34195014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1096662/" ]
Here is a way to get your result using `group_by`: ``` ids = ['location_id','score'] def foo(d): return pd.Series(d['number_of_males'].values*['male'] + d['number_of_females'].values*['female']) pd.melt(df.groupby(ids).apply(foo).reset_index(), id_vars=ids).drop('variable', 1) #Out[13]: # ...
Until this I could do in a pandas functions ``` print df location_id score number_of_males number_of_females 1 20 2 1 2 45 1 2 ``` Converting the two columns to one, ``` df.set_index(['location_id','score']).stack().reset_index() Out[1...
11,995
61,265,226
I use python boto3 when I upload file to s3,aws lambda will move the file to other bucket,I can get object url by lambda event,like `https://xxx.s3.amazonaws.com/xxx/xxx/xxxx/xxxx/diamond+white.side.jpg` The object key is `xxx/xxx/xxxx/xxxx/diamond+white.side.jpg` This is a simple example,I can replace "+" get object...
2020/04/17
[ "https://Stackoverflow.com/questions/61265226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11303583/" ]
You should use `urllib.parse.unquote` and then replace `+` with space. From my knowledge, `+` is the only exception from URL parsing, so you should be safe if you do that by hand.
I think this is what you want: ``` url_data = "https://xxx.s3.amazonaws.com/xxx/xxx/xxxx/xxxx/diamond+white.side.jpg".split("/")[3:] object_key = "/".join(url_data) ```
11,996
71,738,691
me is writing a simple code in python which should give me all the data available in my oracle table. Connection stuff are fine. ``` select column1,column2,column3 from table1. ``` column as following values [![enter image description here](https://i.stack.imgur.com/dWjEf.png)](https://i.stack.imgur.com/dWjEf.png) ...
2022/04/04
[ "https://Stackoverflow.com/questions/71738691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15238129/" ]
I think this is because Ubuntu 16.04 includes a fairly old version of git that does not support the `--progress` flag to the `git submodule update` command. I've [opened an issue](https://github.com/alire-project/alire/issues/966) against Alire to see if we might be able to remove this flag. In the meantime, I'd recom...
I *think* you need to say ``` alr index --update-all ``` `--update-all` is a bit misleading, but given that the error message mentions "index" it was the only likely thing in `alr index --help` (you find the possible commands, e.g. "index" here, by just `alr --help`).
11,997
65,390,129
I create a virtual environment; let's say test\_venv, and I activate it. All successful. HOWEVER, the path of the Python Interpreter doesn't not change. I have illustrated the situation below. For clarification, the python path SHOULD BE `~/Desktop/test_venv/bin/python`. ``` >>> python3 -m venv Desktop/test_venv >>...
2020/12/21
[ "https://Stackoverflow.com/questions/65390129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14392583/" ]
#### *Please make sure to read Note #2.* --- **This is what you should do if you don't want to create a new virtual environment**: In `venv/bin` folder there are 3 files that store your venv path explicitly and if the path is wrong they take the normal python path so you should change the path there to your new path...
It is not an answer specifically to your question, but it corresponds the title of the question. I faced similar problem and couldn't find solution on Internet. Maybe someone use my experience. I created virtual environment for my python project. Some time later my python interpreter also stopped changing after virtua...
11,998
55,378,150
I have a r Script with the code: ``` args = commandArgs(trailingOnly=TRUE) myData <- read.csv(file=args[0]) ``` I want to run this using a GUI and deliver a choosen csv file with this python code ``` from tkinter import filedialog from tkinter import * import subprocess window = Tk() window.geometry('500x200') win...
2019/03/27
[ "https://Stackoverflow.com/questions/55378150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2377949/" ]
With Java 8 streams: ``` List<Accout> accounts = accounts.values().stream() .filter(account -> account.getBalance() > threshold) .collect(Collectors.toList()) ``` With `foreach`: ``` List<Account> accountsWithMinimum = new ArrayList<>(); for (Account acccount : accounts.values() ) { if (account....
From information you provided best solution seems to be change data from HashMap to [LinkedHashMap](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html), that keep ordering. If you take a close took to javadoc, you can find following part useful: > > his implementation spares its clients from the ...
12,001
761,824
I need to convert markdown text to plain text format to display summary in my website. I want the code in python.
2009/04/17
[ "https://Stackoverflow.com/questions/761824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43056/" ]
The [Markdown](https://pypi.org/project/Markdown/) and [BeautifulSoup](https://pypi.org/project/beautifulsoup4/) (now called *beautifulsoup4*) modules will help do what you describe. Once you have converted the markdown to HTML, you can use a HTML parser to strip out the plain text. Your code might look something lik...
Commented and removed it because I finally think I see the rub here: It may be easier to convert your markdown text to HTML and remove HTML from the text. I'm not aware of anything to remove markdown from text effectively but there are many HTML to plain text solutions.
12,003
53,264,593
I have been trying this code to get a random seed, but it always fails. ``` import string import random import time import sys from random import seed possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:' target = input("Enter text: ") attemptThis = ''.join(random.choice...
2018/11/12
[ "https://Stackoverflow.com/questions/53264593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9199123/" ]
The `random.seed()` function always returns `None` but `time.sleep()` needs a number (the number of seconds to sleep). try `random.randint()` instead to generate a random integer: ``` import random time.sleep(random.randint(1, 50)) ```
Use also `random.randint(a, b)` function - to generate random integer number. `seed` function just initializes random numbers generator.
12,013
50,073,779
I am aware that [re.search(pattns,text)][1] in python method takes a regular expression pattern and a string and searches for that pattern within the string. If the search is successful, search() returns a match object or None otherwise. My problem however is, am trying to implement this using OOP (class) i want to re...
2018/04/28
[ "https://Stackoverflow.com/questions/50073779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4209906/" ]
The output of `re.search` returns a match object. It tells you whether the regex matches the string. You should identify the group to retrieve string from the match like so: ``` if result: return result.group(0) ``` Replace `return result` in your code with above code snippet. If you are not sure how [`group...
First, there is a subtle *bug* in your code: ``` def __bool__(self): for pattern in self.patterns: result = re.search(pattern,self.text) return result ``` As you return the result of the searched pattern at the end of the first iteration, others patterns are simply ignored. You probaly want someth...
12,015
44,262,833
I am facing some error while using classes in python 2.7 My class definition is: ``` class Timer(object): def __init__(self): self.msg = "" def start(self,msg): self.msg = msg self.start = time.time() def stop(self): t = time.time() - self.start return self.msg,...
2017/05/30
[ "https://Stackoverflow.com/questions/44262833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2450212/" ]
When you write `self.start = time.time()`, you replace the function `start()` with a variable named `start`, which has a float value. The next time you write `timer.start()`, start is a float, and you are trying to call it as a function. Just replace the name `self.start` with something else.
I think the problem is that you are using the same name for a method and for an attribute. I would refactor it like this: ``` class Timer(object): def __init__(self): self.msg = "" self.start_time = None #I prefer to declare it but you can avoid this def start(self,msg): self.msg = m...
12,016
52,743,872
I have been creating a game where an image moves according to player input with Keydown and Keyup methods. I want to add boundaries so that the user cannot move the image/character out of the display (I dont want a game over kind of thing if boundary is hit, just that the image/character wont be able to move past that ...
2018/10/10
[ "https://Stackoverflow.com/questions/52743872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10366920/" ]
**Root cause:** Your result is an array but your test is verifying an object. Thus, the postman will throw the exception since it could not compare. **Solution:** Use exactly value of an item in the list with if else command to compare. ``` var arr = pm.response.json(); console.log(arr.length) for (var i = 0; i < a...
You could also just do this: ``` pm.test('Check the response body properties', () => { _.each(pm.response.json(), (item) => { pm.expect(item.Verified).to.be.true pm.expect(item.VerifiedDate).to.be.a('string').and.match(/^\d{4}-\d{2}-\d{2}$/) }) }) ``` The check will do a few things for you, i...
12,019
61,924,960
I am querying (via sqlalchemy) *my\_table* with a conditional on a column and then retrieve distinct values in another column. Quite simply ``` selection_1 = session.query(func.distinct(my_table.col2)).\ filter(my_table.col1 == value1) ``` I need to do this repeatedly to get distinct values from different column...
2020/05/21
[ "https://Stackoverflow.com/questions/61924960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13583344/" ]
You don't really need a special class for this. Your existing code ``` selection_2 = session.query(func.distinct(my_table.col3)).\ filter(my_table.col1 == value1).\ filter(my_table.col2 == value2) ``` works because `filter` is returning a *new* query based on the original query, but with an additional filter...
For your `add_filter()` function to work as intended, you need your `set_distinct_col()` function to return a reference to itself (*an instance of `QueryProcessor`*). [`session.query()`](https://docs.sqlalchemy.org/en/13/orm/session_api.html#sqlalchemy.orm.session.Session.query) returns a `Query` object which doesn'...
12,020
30,909,627
I am tried to create a slice in django template and get an attribute. How can i do in django template something like this: python code: ``` somelist[1].name ``` please help
2015/06/18
[ "https://Stackoverflow.com/questions/30909627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3520178/" ]
If you are accessing a single element of a list, you don't need the `slice` filter, just use the dot notation. ``` {{ somelist.1.name }} ``` See [the docs](https://docs.djangoproject.com/en/1.8/ref/templates/language/#variables) for more info.
You can use the built-in tag [`slice`](https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#slice) with a combination of [`with`](https://docs.djangoproject.com/en/1.8/ref/templates/builtins/#with): ``` {% with somelist|slice:"1" as item %} {{ item.name }} {% endwith %} ```
12,021
49,913,084
All, I am trying to build a Docker image to run my python 2 App within an embedded system which has OS yocto. Since the embedded system has limited flash, I want to have a small Docker image. However, after I install all the python and other packages, I get an image with 730M, which is too big for me. I don't know how...
2018/04/19
[ "https://Stackoverflow.com/questions/49913084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227199/" ]
**Q:** How to reduce the size of my docker image? **A:** There are a few ways you can do this. The most prominent thing I can immediately spot from your Dockerfile is that you are installing packages using individual `RUN` command. While this can make your code look a bit cleaner but each `RUN` statement is an overhe...
You can use docker history command to see which layer is causing more disk space addition. ``` docker@default:~Example>> docker history {image-name}:{image-tag} docker@default:~$ docker history mysql IMAGE CREATED CREATED BY SIZE COMMENT 519...
12,022
54,419,118
I am trying to extract table from a PPT using `python-pptx`, however, the I am not sure how do I that using `shape.table`. ``` from pptx import Presentation prs = Presentation(path_to_presentation) # text_runs will be populated with a list of strings, # one for each text run in presentation text_runs = [] for slide in...
2019/01/29
[ "https://Stackoverflow.com/questions/54419118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1479974/" ]
This appears to work for me. ``` prs = Presentation((path_to_presentation)) # text_runs will be populated with a list of strings, # one for each text run in presentation text_runs = [] for slide in prs.slides: for shape in slide.shapes: if not shape.has_table: continue tbl = shape....
To read the values present inside ppt | This code worked for me ``` slide = Deck.slides[1] table = slide.shapes[1].table for r in range(0,len(table.rows)): for c in range(2,len(table.columns)): cell_value = (table.cell(r,c)).text_frame.text print(cell_value) ```
12,023
68,173,157
i have a List a ``` a = [["v1_0001.jpg","v1_00015.jpg","v1_0002.jpg"],["v2_0001.jpg","v2_0002.jpg","v2_00015.jpg"]] ``` i want to concatenate these list of list in one list and sort list by alphanumeric While i am try to sort concatenation list ``` ['v1_0001.jpg', 'v1_00015.jpg', 'v1_0002.jpg','v2_0001.jpg' 'v2_00...
2021/06/29
[ "https://Stackoverflow.com/questions/68173157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use `chain` from `itertools`, as so - ``` from itertools import chain a = [[0, 15, 30, 45, 75, 105],[0, 15, 30, 45, 75, 105]] b = list(chain(*a)) print(b) # [0, 15, 30, 45, 75, 105,0, 15, 30, 45, 75, 105] ```
Here is one way. You can do it with recursion ``` solution : ``` ``` import itertools a = [[0, 15, 30, 45, 75, 105],[0, 15, 30, 45, 75, 105]] print(list(itertools.chain.from_iterable(a))) ```
12,024
37,090,675
I am working with canbus in python (Pcan basic api) and would like to make it easier to use. Via the bus a lot of devices/modules are connected. They are all allowed to send data, if a collison would happen the lowest ID will win. The data Is organized in frames with ID, SubID, hexvalues To illustrate the problem ...
2016/05/07
[ "https://Stackoverflow.com/questions/37090675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using the [python-can](https://bitbucket.org/hardbyte/python-can/) library will get you the networking thread - giving you a buffered queue of incoming messages. The library supports the PCAN interface among others. Then you would create a middle-ware layer that converts and routes these `can.Message` types into pyqt ...
``` class MySimpleCanBus: def parse_message(self,raw_message): return MyMessageClass._create(*struct.unpack(FRAME_FORMAT,msg)) def recieve_message(self,filter_data): #code to recieve and parse a message(filtered by id) raw = canbus.recv(FRAME_SIZE) return self.parse_m...
12,026
41,033,115
I downloaded and installed datasheder using the below steps: ``` git clone https://github.com/bokeh/datashader.git cd datashader conda install -c bokeh --file requirements.txt python setup.py install ``` After that, I have run the code using terminal like `python data.py, but no graph is displayed; nothin is b...
2016/12/08
[ "https://Stackoverflow.com/questions/41033115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7113481/" ]
I haven't tried your code, but there is nothing in there that would actually display the image. Each shade() call creates an image in memory, but then nothing is done with it here. If you were in a Jupyter notebook environment and the shade() call were the last item in the cell, it would display automatically, but the ...
I was able to produce the plot one of the tf.shade in your code this way. ``` from datashader.utils import export_image img = tf.shade(canvas.points(df,'x','y',agg=reductions.count())) export_image(img=img, filename='test1', fmt=".png", export_path=".") ``` This is the plot in test1.png[![Points_plot](https://i.sta...
12,029
31,662,355
I am creating a simple GUI production calculator in python. I am using Tkinter and have a main frame with 10 tabs in it. I have created all the entries and functions do do the calculations we need and it all works. My problem is that i want these entries and labels on each tab line10 - line19. I could manually recreate...
2015/07/27
[ "https://Stackoverflow.com/questions/31662355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5111347/" ]
This can't be intentional, because it can't work. As you've seen, you can't create a table twice. You should delete one of the migrations, possibly merging from the one you delete into the other one. The only differences are the taggings\_count field and the indexes. There isn't enough to go on here to say whether you...
Get use to it. This error will happen often in the future. Usually, it happens when your migration failed in the middle, and for example your table was created, but later creation of indexes failed. Then when you are trying to rerun the migration the table already exists, and migration fails. There are several ways to...
12,030
51,591,025
I have used Django 1.11.14, python 2.7 and win 7 to build a website which could let registered user to login. however, when I log in, some page display login link again when it should be logout link. main page ```html <!DOCTYPE html> <html lang="en"> <head> {% block title %}<title>xxxxx</title>{% endblock %} ...
2018/07/30
[ "https://Stackoverflow.com/questions/51591025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9669628/" ]
Instead of `render_to_response` you should use [`render`](https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#render) function. This make request available in template. ``` def get(self, request): form = xx[![enter image description here][1]][1]Form() FW_list = FW.objects.all().order_by('approve_time'...
You have missed the point of using class based views here. You should rarely, if ever, be defining `get` (or `post`). In this case you should only define `get_context_data` to add your FW\_list, and let the view handle creating the form and rendering the template. ``` def get_context_data(self, **kwargs): kwargs['...
12,032
9,072,175
fellow earthians. I, relatively sane of body and mind, hereby give up understanding CSS positioning by myself. The online resources about CSS go to great length to explain that the "color" attribute lets you set the "color" of stuff. Unmöglish. Then, that if you want to put something to the left of something else ...
2012/01/30
[ "https://Stackoverflow.com/questions/9072175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77804/" ]
It seems most others have not quite understood the gist of your post. I'll break it down for you: CSS positiong is complex because it was designed by many different groups of people over a long period of time, with various versions, and legacy compatibility issues. The first attempts were to keep things simple. Just...
Have you checked out this great book? <http://shop.oreilly.com/product/9781565926226.do> just kidding. I don't think you need an entire resource devoted to this one question. It's rather simple once it clicks. Think of CSS positioning as a way to position items either relatively to themsevels (wherever they fall o...
12,033
25,237,039
I have some pickle files of deep learning models built on gpu. I'm trying to use them in production. But when i try to unpickle them on the server, i'm getting the following error. > > Traceback (most recent call last): > > File "score.py", line 30, in > > model = (cPickle.load(file)) > > File "/usr/loc...
2014/08/11
[ "https://Stackoverflow.com/questions/25237039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1505986/" ]
There is a script in pylearn2 which may do what you need: `pylearn2/scripts/gpu_pkl_to_cpu_pkl.py`
This works for me. Note: this doesn't work unless the following environment variable is set: `export THEANO_FLAGS='device=cpu'` ``` import os from pylearn2.utils import serial import pylearn2.config.yaml_parse as yaml_parse if __name__=="__main__": _, in_path, out_path = sys.argv os.environ['THEANO_FLAGS']="device=c...
12,043
33,157,597
I am trying to install rasterio into my python environment and am getting the following errors. I can do ``` conda install rasterio ``` No error comes up on the install but I come up with the following error when I try to import ``` from rasterio._base import eval_window, window_shape, window_index Im...
2015/10/15
[ "https://Stackoverflow.com/questions/33157597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4812453/" ]
I would suggest trying the ioos anaconda recipe (<https://anaconda.org/ioos/rasterio>). `conda install -c https://conda.anaconda.org/ioos rasterio`. I have run into the same DLL issue you are seeing when trying to install more recent versions of rasterio using the standard anaconda version.
I had the same issue. A reinstall solved it. ``` conda install -f rasterio ```
12,048
1,575,971
I'm making a stupid little game that saves your score in a highscores.txt file. My problem is sorting the lines. Here's what I have so far. Maybe an alphanumeric sorter for python would help? Thanks. ``` import os.path import string def main(): #Check if the file exists file_exists = os.path.exists("highs...
2009/10/16
[ "https://Stackoverflow.com/questions/1575971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/190983/" ]
after `words = f.readlines()`, try something like: ``` headers = words.pop(0) def myway(aline): i = 0 while aline[i].isdigit(): i += 1 score = int(aline[:i]) return score words.sort(key=myway, reverse=True) words.insert(0, headers) ``` The key (;-) idea is to make a function that returns the "sorting ...
Doing a simple string sort on your ``` new_score = str(score) + ".........." + name ``` items isn't going to work since, for example str(1000) < str(500). In other words, 1000 will come before 500 in an alphanumeric sort. Alex's answer is good in that it demonstrates the use of a sort key function, but here is ano...
12,051
26,645,502
The code is self-explained... ``` $ python3 Python 3.4.0 (default, Apr 11 2014, 13:05:18) [GCC 4.8.2] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import urllib.request as req >>> url = 'http://bangladeshbrands.com/342560550782-44083.html' >>> res = req.urlopen(url) >>> html = r...
2014/10/30
[ "https://Stackoverflow.com/questions/26645502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/907044/" ]
You need to give the dataset name and table name I am going to give you code which is work on my Machine Correctly ``` Dim ds As New DataSet Dim dt As New DataTable Dim RpDs1 As New Microsoft.Reporting.WinForms.ReportDataSource Dim SQL As String = "select * from mfcount" Dim da As New OleDbDataAdapte...
thanks basuraj kumbhar for your help to solve this problem. Here is the working codes for MyCql connection Report in vb.net ``` Dim ds As New DataSet Dim dt As New DataTable Dim RpDs1 As New Microsoft.Reporting.WinForms.ReportDataSource Dim SQL As String = "select * from tb_course" Dim da As New MySqlD...
12,058
38,703,423
I have been scouring the internet looking for the answer to this. Please not my python coding skills are not all that great. I am trying to create a command line script that will take the input from the command line like this: ``` $python GetHostID.py serverName.com ``` the last part is what I am wanting to pass ...
2016/08/01
[ "https://Stackoverflow.com/questions/38703423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6664141/" ]
The command line arguments are available as the list `sys.argv`, whose first element is the path to the program. There are a number of libraries you can use (argparse, optparse, etc.) to analyse the command line, but for your simple application you could do something like this: ``` import sys import sys, os import opt...
os.getenv('remoteserver') does not use the variable remoteserver as an argument. Instead it uses a string 'remoteserver'. Also, are you trying to take input as a command line argument? Or are you trying to take it as user input? Your problem description and implementation differ here. The easiest way would be to run y...
12,059
38,897,842
I have an app running on AWS and I need to save every "event" in a file. An "event" happens, for instance, when a user logs in to the app. When that happens I need to save this information on a file (presumably I would need to save a time stamp and the session id) I expect to have a lot of events (of the order of a mi...
2016/08/11
[ "https://Stackoverflow.com/questions/38897842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/863713/" ]
The `.*` in the lookaheads checks for the letter presence not only in the adjacent word, but later in the string. Use `[a-zA-Z]*`: ``` echo "hello 123 worLD" | grep -oP "\\b(?=[A-Za-z]*[a-z])(?=[A-Za-z]*[A-Z])[a-zA-Z]+" ``` See the [demo online](https://ideone.com/aGaXTA) I also added a word boundary `\b` at the st...
**Answer:** ``` echo "hello 123 worLD" | grep -oP "\b(?=[A-Z]+[a-z]|[a-z]+[A-Z])[a-zA-Z]*" ``` Demo: <https://ideone.com/HjLH5o> **Explanation:** First check if word starts with one or more uppercase letters followed by one lowercase letters or vice versa followed by any number of lowercase and uppercase letters ...
12,062
3,124,229
I'm trying to take a screenshot of the entire screen with C and GTK. I don't want to make a call to an external application for speed reasons. I've found Python code for this ([Take a screenshot via a python script. [Linux]](https://stackoverflow.com/questions/69645/take-a-screenshot-via-a-python-script-linux/782768#78...
2010/06/26
[ "https://Stackoverflow.com/questions/3124229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/287750/" ]
After looking at the GNOME-Screenshot code and a Python example, I came up with this: ``` GdkPixbuf * get_screenshot(){ GdkPixbuf *screenshot; GdkWindow *root_window; gint x_orig, y_orig; gint width, height; root_window = gdk_get_default_root_window (); gdk_drawable_get_size (root_window, &wid...
9 years passed and as mentioned above API is removed. As far as I understand, currently the bare minimum to do this at Linux is: ``` GdkWindow * root; GdkPixbuf * screenshot; gint x, y, width, height; root = gdk_get_default_root_window (); gdk_window_get_geometry (root, &x, &y, &width, &height); screenshot = gdk_pix...
12,063
6,457,102
I'm trying to load ~2GB of text files (approx 35K files) in my python script. I'm getting a memory error around a third of the way through on page.read(). I' ``` for f in files: page = open(f) pageContent = page.read().replace('\n', '') page.close() cFile_list.append(pageContent) ``` I've never deal...
2011/06/23
[ "https://Stackoverflow.com/questions/6457102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/812575/" ]
You are trying to load too much into memory at once. This can be because of the process size limit (especially on a 32 bit OS), or because you don't have enough RAM. A 64 bit OS (and 64 bit Python) would be able to do this ok given enough RAM, but maybe you can simply change the way your program is working so not ever...
Consider using generators, if possible in your case: ``` file_list = [] for file_ in files: file_list.append(line.replace('\n', '') for line in open(file_)) ``` file\_list now is a list of iterators which is more memory-efficient than reading the whole contents of each file into a string. As soon es you need the...
12,064
70,623,704
The following code: ``` from typing import Union def process(actions: Union[list[str], list[int]]) -> None: for pos, action in enumerate(actions): act(action) def act(action: Union[str, int]) -> None: print(action) ``` generates a mypy error: `Argument 1 to "act" has incompatible type "object"; ex...
2022/01/07
[ "https://Stackoverflow.com/questions/70623704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3139441/" ]
`enumerate.__next__` needs more context than is available to have a return type more specific than `Tuple[int, Any]`, so I believe `mypy` itself would need to be modified to make the inference that `enumerate(actions)` produces `Tuple[int,Union[str,int]]` values. Until that happens, you can explicitly cast the value o...
I don't know how it's affecting the types. I do know that using len() can work the same way. It is slower but if it solves the problem it might be worth it. Sorry that it's not much help
12,067
53,715,925
Greetings for the past week (or more) I've been struggling with a problem. **Scenario:** I am developing an app which will allow an expert to create a recipe using a provided image of something to be used as a base. The recipe consists of areas of interests. The program's purpose is to allow non experts to use it, pr...
2018/12/11
[ "https://Stackoverflow.com/questions/53715925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4789509/" ]
Your `DirectView` class must inherit from a `View` class in Django in order to use [`as_view`](https://docs.djangoproject.com/en/2.1/ref/class-based-views/base/#django.views.generic.base.View.as_view). ``` from django.views.generic import View class DirectView(mixins.CreateModelMixin, View): ``` If you're using the...
If we are looking into the [source code of **`mixins.CreateModelMixin`**](https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py#L14), we could see it's inherited from [**`object`**](https://stackoverflow.com/questions/4015417/python-class-inherits-object) (***builtin type***) and hence it...
12,069
69,108,130
I am trying to build a voice assistant. I am facing a problem with the playsound library. Please view my code snippet. ``` def respond(output): """ function to respond to user questions """ num=0 print(output) num += 1 response=gTTS(text=output, lang='en') file = str(num)+".mp3" res...
2021/09/08
[ "https://Stackoverflow.com/questions/69108130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16863358/" ]
Query * lookup with it self, join only with the type that the id=3 has. * empty join results => different type so they are filtered out [Test code here](https://mongoplayground.net/p/KnKpOBZYJy7) ```js db.collection.aggregate([ { "$lookup": { "from": "collection", "let": { "type": "$type" ...
You're basically mixing two separate queries: 1. Get an item by ID - returns a **single** item 2. Get a list of items, that have the same type as the type of the first item - returns a **list of items** Because of the difference of the queries, there's no super straightforward way to do so. Surely you can use [$aggre...
12,070
18,600,200
in python here is my multiprocessing setup. I subclassed the Process method and gave it a queue and some other fields for pickling/data purposes. This strategy works about 95% of the time, the other 5% for an unknown reason the queue just hangs and it never finishes (it's common that 3 of the 4 cores finish their job...
2013/09/03
[ "https://Stackoverflow.com/questions/18600200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1660802/" ]
Do a `time.sleep(0.001)` at the beginning of your `run()` method.
From my experience ``` time.sleep(0.001) ``` Is by far not long enough. I had a similar problem. It seems to happen if you call `get()` or `put()` on a queue "too early". I guess it somehow fails to initialize quick enough. Not entirely sure, but I'm speculating that it might have something to do with the ways a qu...
12,071
46,373,433
I am working in python, trying to be able to put in a data set (eg. (1, 6, 8) that returns a string (eg. 'NO+ F- NO+'). I think that maybe array is not the correct object. I want to be able to plug in large data sets (eg. (1, 1, 6, 1, ..., 8, 8, 6, 1) to return a string. ``` def protein(array): ligand = '' for...
2017/09/22
[ "https://Stackoverflow.com/questions/46373433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8658260/" ]
You probably want `def protein(*array):` This allows you to give in any number of arguments. You also must use `for i in array:` instead of `for i in range(array):`
If you call it like `protein(1, 6, 8)` you are **not** passing it a tuple: you pass it **three parameters**. Since you defined `protein` with *one* parameter: `array`, that errors. You can use arbitrary parameters, by using `*args`. But nevertheless this function is still not very elegant nor is it efficient: it will ...
12,072
55,253,980
How to debug the code written in python in container using azure dev spaces for kubernetes ?
2019/03/20
[ "https://Stackoverflow.com/questions/55253980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8267052/" ]
Debugging should be similar just like we have it in Dot net core.In dot net , we used to debug something like this **Setting and using breakpoints for debugging** If Visual Studio 2017 is still connected to your dev space, click the stop button. Open Controllers/HomeController.cs and click somewhere on line 20 to put...
Currently debugging in Azure Dev Spaces only lists Node.js, .NET Core, and Java as officially supported. The documentation for how to debug these 3 types of environments was written pretty recently (Quickstarts published on 7/7/2019). I am assuming that a guide for Python should be on the way shortly, but I have been u...
12,078
73,565,617
I'm making an age calculator and when calculating the months, I need numbers, not strings such as "January" etc. how do I make it that when the user's selecting their birth month, they see month strings ("Jan", "Feb"), and backend I return the month's number? thought this could be done with if statements, but it's sim...
2022/09/01
[ "https://Stackoverflow.com/questions/73565617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19517516/" ]
You can use list comprehension for that : ``` myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA'] result = [el.split(',') for el in myList...
``` myList = ['BUD', 'CDG', 'DEL', 'DOH', 'DSM,ORD', 'EWR,HND', 'EWR,HND,ICN', 'EWR,HND,JFK', 'EWR,HND,JFK,LGA', 'EWR,HND,JFK,LGA', 'EWY,LHR', 'EWY,LHR,SFO,DSM', 'EWY,LHR,SFO,DSM,ORD,BGI', 'EWY,LHR,SFO,DSM,ORD,BGI,LGA'] nested_list = [[element] for element in myList] ``` output : ``` [['BUD'], ['CD...
12,079
17,256,602
Does anyone know why I can't overwrite an existing endpoint function if i have two url rules like this ``` app.add_url_rule('/', view_func=Main.as_view('main'), methods=["GET"]) app.add_url_rule('/<page>/', view_func=Main.as_view('main'), methods=["G...
2013/06/23
[ "https://Stackoverflow.com/questions/17256602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2016434/" ]
This same issue happened to me when I had more than one API function in the module and tried to wrap each function with 2 decorators: 1. @app.route() 2. My custom @exception\_handler decorator I got this same exception because I tried to wrap more than one function with those two decorators: ``` @app.route("/path1"...
In case you are using flask on python notebook, you need to restart kernel everytime you make changes in code
12,084
28,418,677
i just began playing with python 3 and got a little stuck. I have this code: ``` person = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel'] for item in person: opinion = input("What do you think about "+person[0]+"? ") print(person[0]+" is a "+opinion+"") ``` And i do not know how to make it ask about e...
2015/02/09
[ "https://Stackoverflow.com/questions/28418677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3025008/" ]
You are assigning `item` to each value in `person`, use that variable. ``` for item in person: opinion = input("What do you think about "+item+"? ") print(item+" is a "+opinion+"") ``` When you called `person[0]`, you were setting it to the first value in `person` **every time**, which is not what yo...
What about ``` for item in person opinion = input("What do you think about "+item+"? ") print(item+" is a "+opinion+"") ``` And even better, if you want to make it more verbose: ``` # List with "s" to make it plural persons = ['George', 'Andrew', 'Ryan', 'Jack', 'Daniel'] # List item without the "s" for pe...
12,094
45,654,850
I would like to do a stuff like this in c++ : ``` for (int i = 0, i < 3; ++i) { const auto& author = {"pierre", "paul", "jean"}[i]; const auto& age = {12, 45, 43}[i]; const auto& object = {o1, o2, o3}[i]; print({"even", "without", "identifier"}[i]); ... } ``` Does everyone know how to do this kind of ...
2017/08/12
[ "https://Stackoverflow.com/questions/45654850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443456/" ]
Looks like you should have used a vector of your custom class with `author`, `age`, `object` and `whatever` attributes, put it in a vector and do range for-loop over it - that would be idiomatic in C++: ``` struct foo { std::string author; int age; object_t object; whatever_t whatever; }; std::vector<...
Creating an object like `{"pierre", "paul", "jean"}` results in a initializer list. Initializer list does not have any [] operator [Why doesn't `std::initializer\_list` provide a subscript operator?](https://stackoverflow.com/questions/17787394/why-doesnt-stdinitializer-list-provide-a-subscript-operator). So you should...
12,097
22,703,333
I'm working in python, trying to write a code that makes the Fibonacci sequence and return the results as a list. How would I go about doing so? I was able to write a code to return the set of values not as a list, but I'm unsure how I would go about writing a code to return a list. (Here's the code I have to return ...
2014/03/28
[ "https://Stackoverflow.com/questions/22703333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3471046/" ]
The `string` class is in the namespace `std`. You can remove the scoping for `std::`. You'd do best to include it inside the main function, so names don't colide if you use a library that uses the name string or `cout`, or such. ``` #include <iostream> #include <string> int main() { using namespace std; string a...
`string` is in `std` namespace, it's only valid to use `std::string` rather than `string` (the same for `std::cin`, `std::vector` etc). However, in practice, some compilers may let a program using `string` etc without `std::` prefix compile, which makes some programmers think it's OK to omit `std::`, but it's not in st...
12,098
841,096
I've recently hit a wall in a project I'm working on which uses PyQt. I have a QTreeView hooked up to a QAbstractItemModel which typically has thousands of nodes in it. So far, it works alright, but I realized today that selecting a lot of nodes is very slow. After some digging, it turns out that QAbstractItemModel.par...
2009/05/08
[ "https://Stackoverflow.com/questions/841096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103667/" ]
Try calling `setUniformRowHeights(true)` for your tree view: <https://doc.qt.io/qt-4.8/qtreeview.html#uniformRowHeights-prop> Also, there's a C++ tool called modeltest from qt labs. I'm not sure if there is something for python though: <https://wiki.qt.io/Model_Test>
I converted your very nice example code to PyQt5 and ran under Qt5.2 and can confirm that the numbers are still similar, i.e. inexplicably huge numbers of calls. Here for example is the top part of the report for start, cmd-A to select all, scroll one page, quit: ``` ncalls tottime percall cumtime percall filen...
12,099
71,398,447
In below code 21 is hour and 53 is min and 10 is wait time in this code I want to send message in loop frequently but I failed. I also tried for loop but it is not working. Any body know how to send 100 message in whatsapp using python please help me ``` import pywhatkit from flask import Flask while 1: pywhatkit.se...
2022/03/08
[ "https://Stackoverflow.com/questions/71398447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18126137/" ]
Use ``` final response = await http.post(Uri.parse(url), body: { "fecha_inicio": _fechaInicioBBDD, "fecha_fin": _fechaFinalBBDD, "latitud": _controllerLatitud.text, "longitud": _controllerLongitud.text, "calle": _controllerDireccion.text, "descripcion": _controllerDescripcion.text,...
The documentation for [`http.post`](https://pub.dev/documentation/http/latest/http/post.html) states: > > `body` sets the body of the request. It can be a `String`, a `List<int>` or a `Map<String, String>`. > > > Since you are passing a `Map`, all keys and values in your `Map` are required to be `String`s. You sh...
12,100
53,913,303
Im trying to implement a menu in my tool. But i couldn't implement a switch case in python. i know that python has only dictionary mapping. How to call parameterised methods in those switch case? For example, I have this program `def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 't...
2018/12/24
[ "https://Stackoverflow.com/questions/53913303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10829002/" ]
Switch cases can be implemented using dictionary mapping in Python like so: ``` def Choice(i): switcher = {1: subdomain, 2: reverseLookup} func = switcher.get(i, 'Invalid') if func != 'Invalid': print(func(host)) ``` There is a dictionary `switcher` which helps on mapping to the right function ba...
**try this ....** ``` def Choice(i): switcher = { 1: subdomain(host), 2: reverseLookup(host), 3: lambda: 'two' } func = switcher.get(i, lambda:'Invalid') print(func()) if __name__ == "__main__": argument=0 print Choice(argument) ```
12,103
40,527,051
I'm trying to make my program allow the user to input vectors of the form (x,y,z) using python's built in input() function. If entered normally in python with out using the input() function it indexes each vector separately. For example, ``` >>> z = (1,2,3), (4,5,6), (7,8,9) >>> z[1] (4, 5, 6) ``` But when I try to...
2016/11/10
[ "https://Stackoverflow.com/questions/40527051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7141092/" ]
In Python 3, `input` always returns a string. You need to convert the string. For this type of input I recommend using `liter_eval` from the module `ast`: ``` import ast vectors = ast.literal_eval('(1,2,3), (4,5,6), (7,8,9)') vectors[1] #(4, 5, 6) ```
In your example, `z` is just a string as input by the user. This string is: `"(1,2,3), (4,5,6), (7,8,9)"` so the second element, `z[1]` is just giving you `"1"`. If you want an actual vector object you would have to write code to parse the string input by the user. For example, you could delimit based on parentheses...
12,108
44,155,564
When trying to plot a graph with pyplot I am running the following code: ``` from matplotlib import pyplot as plt x = [6, 5, 4] y = [3, 4, 5] plt.plot(x, y) plt.show() ``` This is returning the following error: ``` --------------------------------------------------------------------------- AttributeError ...
2017/05/24
[ "https://Stackoverflow.com/questions/44155564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8058705/" ]
I had this exact error and in my case it turned out to be that both `pip` and `conda` had installed copies of `matplotlib`. In a 'mixed' environment with `pip` used to fill gaps in Anaconda, `pip` can automatically install upgrades to (already-installed) dependencies of the package you asked to install, creating duplic...
I have solved my problem although I am not entirely sure why this has solved it. I used `pip uninstall matplotlib`, to remove the python install, and also updated my `~/.zshrc` and `~/.bash_profile` paths to contain: HomeBrew: `export PATH=/usr/local/bin:$PATH` Python: `export PATH=/usr/local/share/python:$PATH` ...
12,111
18,153,913
I used `python -mtimeit` to test and found out it takes more time to `from Module import Sth` comparing to `import Module` E.g. ``` $ python -mtimeit "import math; math.sqrt(4)" 1000000 loops, best of 3: 0.618 usec per loop $ python -mtimeit "from math import sqrt; sqrt(4)" 1000000 loops, best of 3: 1.11 usec per loo...
2013/08/09
[ "https://Stackoverflow.com/questions/18153913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2325350/" ]
There are two issues here. The first step is to figure out which part is faster: the import statement, or the call. So, let's do that: ``` $ python -mtimeit 'import math' 1000000 loops, best of 3: 0.555 usec per loop $ python -mtimeit 'from math import sqrt' 1000000 loops, best of 3: 1.22 usec per loop $ python -mtim...
This is not an answer, but some information. It needed formatting so I didn't include it as a comment. Here is the bytecode for 'from math import sqrt': ``` >>> from math import sqrt >>> import dis >>> def f(n): return sqrt(n) ... >>> dis.dis(f) 1 0 LOAD_GLOBAL 0 (sqrt) 3 LOAD_F...
12,114
51,481,021
My friend told me about [Josephus problem](https://en.wikipedia.org/wiki/Josephus_problem), where you have `41` people sitting in the circle. Person number `1` has a sword, kills person on the right and passes the sword to the next person. This goes on until there is only one person left alive. I came up with this solu...
2018/07/23
[ "https://Stackoverflow.com/questions/51481021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9274224/" ]
I see two serious bugs. 1. I guarantee that `del ppList[::i]` does nothing resembling what you hope it does. 2. When you wrap around the circle, it is important to know if you killed the last person in the list (first in list kills again) or didn't (first person in list dies). And contrary to your assertion that it w...
The problem is you are not considering the guy in the end if he is not killed. Example, if there are 9 people, after killing 8, 9 has the sword, but you are just starting with 1, instead of 9 in the next loop. As someone mentioned already, it is not working for smaller numbers also. Actually if you look close, you're k...
12,115
61,975,308
I am trying to read the url code using URLLIB. Here is my code: ``` import urllib url = "https://www.facebook.com/fads0000fass" r = urllib.request.urlopen(url) p = r.code if(p == "HTTP Error 404: Not Found" ): print("hello") else: print("null") ``` The url I am using will show error code 404 but I...
2020/05/23
[ "https://Stackoverflow.com/questions/61975308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13288913/" ]
I'm not sure that's what you're asking. ``` import urllib.request url = "https://www.facebook.com/fads0000fass" try: r = urllib.request.urlopen(url) p = r.code except urllib.error.HTTPError: print("hello") ```
In order to reach your if statement, your code needs exception handling. An exception is being raised when you call `urlopen` on line 7. See the first step of your traceback. ``` File "gd.py", line 7, in <module> r = urllib.request.urlopen(url) ``` The exception happens here, which causes your code to exit, so fur...
12,116
71,902,562
I have started the Yolo5 Training with custom data The command I have used: ``` !python train.py --img 640 --batch-size 32 --epochs 5 --data /content/drive/MyDrive/yolov5_dataset/dataset_Trafic/data.yaml --cfg /content/drive/MyDrive/yolov5/models/yolov5s.yaml --name Model ``` Training started as below & completed:...
2022/04/17
[ "https://Stackoverflow.com/questions/71902562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2707200/" ]
#### Case 1 Here we consider the statement: ``` Animal a1 = func1(); ``` The call expression `func1()` is an **rvlalue** of type `Animal`. And from C++17 onwards, due to [mandatory copy elison](https://en.cppreference.com/w/cpp/language/copy_elision#Mandatory_elision_of_copy/move_operations): > > Under the follo...
In C++17 there is a new set of rules about temporary materialization. In a simple explanation an expression that evaluates to a prvalue (a temporary) doesn't immediately create an object, but is instead a recipe for creating an object. So in your example `Animal()` doesn't create an object straight away so that's why ...
12,117
4,175,697
I am writting a daemon server using python, sometimes there are python runtime errors, for example some variable type is not correct. That error will not cause the process to exit. Is it possible for me to redirect such runtime error to a log file?
2010/11/14
[ "https://Stackoverflow.com/questions/4175697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197036/" ]
It looks like you are asking two questions. To prevent your process from exiting on errors, you need to catch all [`exception`](http://www.python.org/doc//current/library/exceptions.html)s that are raised using [`try...except...finally`](http://www.python.org/doc//current/reference/compound_stmts.html#try). You also ...
Look at the `traceback` module. If you catch a `RuntimeError`, you can write it to the log (look at the `logging` module for that).
12,118
17,860,717
Spent almost more than 30 mins of my time in trying all different possibly. Finally now I'm exhausted. Can someone please help me on this quote problem ``` def remote_shell_func_execute(): with settings(host_string='user@XXX.yyy.com',warn_only=True): process = run("subprocess.Popen(\["/root/test/shell_...
2013/07/25
[ "https://Stackoverflow.com/questions/17860717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2436055/" ]
Just use a single quoted string. ``` run('subprocess.Popen(\["/root/test/shell_script_for_test.sh func2"\],shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)') ``` Or escape the inner `"`. ``` run("subprocess.Popen(\[\"/root/test/shell_script_for_test.sh func2\"\],shell=True,stdin=subpr...
When you escape quotes, the escape backslash must go directly before the quote character: ``` "[\"/..." ``` Alternatively, use single quotes for the string, this avoids the need for escaping at all: ``` '["/...' ```
12,119
7,314,925
I'm saving data to a PostgreSQL backend through Django. Many of the fields in my models are DecimalFields set to arbitrarily high max\_digits and decimal\_places, corresponding to numeric columns in the database backend. The data in each column have a precision (or number of decimal places) that is not known *a priori*...
2011/09/06
[ "https://Stackoverflow.com/questions/7314925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/929783/" ]
If you need perfect parity forwards and backwards, you'll need to use a CharField. Any number-based database field is going to interact with your data muxing it in some way or another. Now, I know you mentioned not being able to know the digit length of the data points, and a CharField requires some length. You can eit...
Since I asked this question awhile ago and the answer remains the same, I'll share what I found should it be helpful to anyone in a similar position. Django doesn't have the ability to take advantage of the PostgreSQL Numerical column type with arbitrary precision. In order to preserve the display precision of data I u...
12,120
46,258,924
I am trying to recreate some code from MatLab using numpy, and I cannot find out how to store a variable amount of matrices. In MatLab I used the following code: ``` for i = 1:rows K{i} = zeros(5,4); %create 5x4 matrix K{i}(1,1)= ET(i,1); %put knoop i in table K{i}(1,3)= ET(i,2); %put knoop j in table ...
2017/09/16
[ "https://Stackoverflow.com/questions/46258924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8620430/" ]
In the MATLAB code you are using a Cell array. Cells are generic containers. The equivalent in Python is a regular [list](https://docs.python.org/2/tutorial/introduction.html#lists) - not a numpy structure. You can create your numpy arrays and then store them in a list like so: ``` import numpy as np array1 = np.array...
How about something like this: ``` import numpy as np myList = [] for i in range(100): mtrx = np.zeros((5,4)) mtrx[1,2] = 7 mtrx[3,0] = -5 myList.append(mtrx) ```
12,121
1,242,904
I use CMake to build my application. How can I find where the python site-packages directory is located? I need the path in order to compile an extension to python. CMake has to be able to find the path on all three major OS as I plan to deploy my application on Linux, Mac and Windows. I tried using ``` include(Find...
2009/08/07
[ "https://Stackoverflow.com/questions/1242904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134397/" ]
You can execute external processes in cmake with [execute\_process](http://www.cmake.org/cmake/help/cmake2.6docs.html#command:execute_process) (and get the output into a variable if needed, as it would be here).
I suggest to use `get_python_lib(True)` if you are making this extension as a dynamic library. This first parameter should be true if you need the platform specific location (in 64bit linux machines, this could be `/usr/lib64` instead of `/usr/lib`)
12,122
55,598,548
I'm trying to update my Spyder to fix some error in my Spyder 3.2.3. But when I called `conda update spyder` mentioned in (<https://github.com/spyder-ide/spyder/issues/9019#event-2225858161>), the Anaconda prompt showed as follow: ![enter image description here](https://i.stack.imgur.com/IFWTL.png) and the Spyder wa...
2019/04/09
[ "https://Stackoverflow.com/questions/55598548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11335756/" ]
Fortunately I have fixed my Spyder by using command 'conda install --revision 2', and updated my Spyder to version 3.3.4 in the Anaconda Navigator. The `conda list --version` can show each rev before, so I used command `conda install --revision 2` to restore the environment to what it was before I updated conda. After...
I reinstalled the package that's causing inconsistency and then the problem is gone. My inconsistency error: [![My Inconsistency Error](https://i.stack.imgur.com/ACgYe.png)](https://i.stack.imgur.com/ACgYe.png) What I did: ``` conda install -c conda-forge mkl-service ```
12,127
64,832,243
I'm trying to install apache airflow with pip, so I enter "pip install apache-airflow". but somehow i got an error that i don't understand. Could you please help me with this? for a little bit context, I'm using macOS catalina and python 3.8.2. I have tried to upgrade my pip, but the error still there. These are the...
2020/11/14
[ "https://Stackoverflow.com/questions/64832243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14607085/" ]
I looked into similar errors and here are a few possible fixes: 1. If you installed Python3.8 via `Brew`, try to uninstall it and install a new version that you build from source. 2. Try `sudo python3.8 -m pip install apache-airflow`. 3. Upgrade to Python 3.8.5 as per [this post](https://stackoverflow.com/questions/64...
I faced exact same issue, here's how I solved it. I explicitly used python 3.8.5 as pointed in [Meghdeep Ray's answer](https://stackoverflow.com/a/64867996/2508468) I also exported the `export ARCHFLAGS="-arch x86_64"` environment variable still inspired by [Meghdeep Ray's answer](https://stackoverflow.com/a/64867996...
12,130
1,417,473
I'm trying to call a function in a Python script from my main C++ program. The python function takes a string as the argument and returns nothing (ok.. 'None'). It works perfectly well (never thought it would be that easy..) as long as the previous call is finished before the function is called again, otherwise there ...
2009/09/13
[ "https://Stackoverflow.com/questions/1417473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144746/" ]
When you say "as long as the previous call is finished before the function is called again", I can only assume that you have multiple threads calling from C++ into Python. The python is not thread safe, so this is going to fail! Read up on the Global Interpreter Lock (GIL) in the Python manual. Perhaps the following l...
Thank you for your help! Yes you're right, there are several C threads. Never thought I'd need mutex for the interpreter itself - the GIL is a completly new concept for me (and isn't even once mentioned in the whole tutorial). After reading the reference (for sure not the easiest part of it, although the PyGILState\_...
12,131
23,900,878
Is it possible to mock a module in python using `unittest.mock`? I have a module named `config`, while running tests I want to mock it by another module `test_config`. how can I do that ? Thanks. config.py: ``` CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" ``` test\_config.py: ``` CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test...
2014/05/28
[ "https://Stackoverflow.com/questions/23900878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2085665/" ]
If you're always accessing the variables in config.py like this: ``` import config ... config.VAR1 ``` You can replace the `config` module imported by whatever module you're actually trying to test. So, if you're testing a module called `foo`, and it imports and uses `config`, you can say: ``` from mock import patc...
Consider this following setup configuration.py: ``` import os class Config(object): CONF_VAR1 = "VAR1" CONF_VAR2 = "VAR2" class TestConfig(object): CONF_VAR1 = "test_VAR1" CONF_VAR2 = "test_VAR2" if os.getenv("TEST"): config = TestConfig else: config = Config ``` now everywhere else in yo...
12,132
50,601,935
I'm debugging my python application using VSCode. I have a main python file from where I start the debugger. I'm able to put breakpoints in this file, but if I want to put breakpoints in other files which are called by the main file, I get them as 'Unverified breakpoint' and the debugger ignores them. How can I chan...
2018/05/30
[ "https://Stackoverflow.com/questions/50601935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1616955/" ]
This may be a result of the "[justMyCode](https://code.visualstudio.com/docs/python/debugging#_justmycode)" configuration option, as it defaults to true. While the description from the provider is "...restricts debugging to user-written code only. Set to False to also enable debugging of standard library functions.", ...
The imports for the other modules were inside strings and called using the `execute` function. That's why VSCode couldn't very the breakpoints in the other files as it didn't know that these other files are used by the main file..
12,141
16,068,532
So this happened to me: ``` thing = ModelClass() thing.foo = bar() thing.do_Stuff() thing.save() #works fine thing.decimal_field = decimal_value thing.save() #error here ``` Traceback follows: ``` TypeError at /journey/collaborators/2/ unsupported operand type(s) for ** or pow(): 'Decimal' and 'str' 274. ...
2013/04/17
[ "https://Stackoverflow.com/questions/16068532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742082/" ]
Linking turned on will throw away any methods, attributes, properties... that are not used at the time of compilation. This is problem for example with reflection approach. Your problem - very large package can be solved by: 1. reducing library code - removing unused code manually and linking off - probably don't wan...
Use the Json.Net provided by the [Xamarin Component Store](http://components.xamarin.com/view/json.net/). I have used this component for multiple projects and my Release builds with linking enabled come in between 4-8 MB.
12,142
4,413,912
Why is `print` a keyword in python and not a function?
2010/12/10
[ "https://Stackoverflow.com/questions/4413912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538442/" ]
The `print` statement in Python 2.x has some special syntax which would not be available for an ordinary function. For example you can use a trailing `,` to suppress the output of a final newline or you can use `>>` to redirect the output to a file. But all this wasn't convincing enough even to Guido van Rossum himself...
I will throw in my thoughts on this: In Python 2.x `print` is not a statement by mistake, or because printing to `stdout` is such a basic thing to do. Everything else is so thought-through or has at least understandable reasons that a mistake of that order would seem odd. If communicating with `stdout` would have been...
12,144
71,214,931
I want to access items from a new dictionary called `conversations` by implementing a for loop. ``` {" conversations": [ {"tag": "greeting", "user": ["Hi", " What's your name?", " How are you?", "Hello", "Good day"], "response": ["Hello, my name is Rosie. Nice to see you", "Good to see you again", " How can I help you...
2022/02/22
[ "https://Stackoverflow.com/questions/71214931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18273393/" ]
You should use the `json` module to load in JSON data as opposed to reading in the file line-by-line. Whatever procedure you build yourself is likely to be fragile and less efficient. Here is the looping structure that you're looking for: ```py import json with open('input.json') as input_file: data = json.load(...
Try this out: ``` import json dialogue_text = json.load(open("dialogue.txt", encoding='utf8')) for conversation in dialogue_text[" conversations"]: for user in conversation['user']: print(user) ``` Output: ```none Hi What's your name? How are you? Hello Good day Bye See you Goodbye Thanks Thank you T...
12,154
72,393,418
I am working with python and numpy! I have a txt file with integers, space seperated, and each row of the file must be a row in an array or dataframe. The problem is that not every row has the same size! I know the size that i want them to have and i want to put to the missing values the number zero! As is not comma se...
2022/05/26
[ "https://Stackoverflow.com/questions/72393418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19207300/" ]
Forbidden often correlated to SSL/TLS certificate verification failure. Please try using the `requests.get` by setting the `verify=False` as following Fixing the SSL certificate issue ``` requests.get("https://www.example.com/insert.php?network=testnet&id=1245300&c=2803824&lat=7555457", verify=False) ``` Fixing the...
Somehow I overcomplicated it and when I tried the absolute minimum that works. ``` import requests headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36' } response = requests.get("http://www.example.com/insert.php?network=test...
12,155
62,801,244
I am working on a project where i have to use Mouse as a paintbrush. I have used `cv2.setMouseCallback()` function but it returned the following error. here is the part of my code ``` import cv2 import numpy as np # mouse callback function def draw_circle(event,x,y,flags,param): if event == cv2.EVENT_LBUTTONDBLCL...
2020/07/08
[ "https://Stackoverflow.com/questions/62801244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7976921/" ]
The error is resolved I removed the previously installed OpenCV (which is installed using pip `pip install opencv-python`) and reinstalled it using `sudo apt install libopencv-dev python3-opencv`
for me, also worked with the pip3 installations. Just made a fresh virtual env, and installed opencv-python and opencv-contrib-python.
12,156
30,013,383
I want to be able to get from `[2, 3]` and `3 : [2, 3, 2, 3, 2, 3]`. (Like `3 * a` in python where a is a list) Is there a quick and efficient way to do this in Javascript ? I do this with a `for` loop, but it lacks visibility and I guess efficiency. I would like for it to work with every types of element. For insta...
2015/05/03
[ "https://Stackoverflow.com/questions/30013383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4859055/" ]
You can use this (very readable :P) function: ``` function repeat(arr, n){ var a = []; for (var i=0;i<n;[i++].push.apply(a,arr)); return a; } ``` `repeat([2,3], 3)` returns an array `[2, 3, 2, 3, 2, 3]`. Basically, it's this: ``` function repeat(array, times){ var newArray = []; for (var i=0; i < times; ...
There is not. This is a very Pythonic idea. You could devise a function to do it, but I doubt there is any computational benefit because you would just be using a loop or some weird misuse of string functions.
12,159
28,314,014
I have written this code in python ``` import os files = os.listdir(".") x = "" for file in files: x = ("\"" + file + "\" ") f = open("files.txt", "w") f.write(x) f.close() ``` this works and I get a single string with all the files in a directory as `"foo.txt" "bar.txt" "baz.txt"` but I don't like the for loop....
2015/02/04
[ "https://Stackoverflow.com/questions/28314014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337134/" ]
1. You can write string literals using both `'single'` and `"double-quotes"`; you don't have to escape one inside the other. 2. You can use the `format` function to apply quotes before you `join`. 3. You should use the `with` statement when opening files to save you from having to `close` it explicitly. Thus: ``` imp...
``` import os files = os.listdir(".") x = " ".join('"%s"'%f for f in files) with open("files.txt", "w") as f: f.write(x) ```
12,160
58,223,422
I'm currently trying to find an effective way of running a machine learning task over a set amount of cores using `tensorflow`. From the information I found there were two main approaches to doing this. The first of which was using the two tensorflow variables intra\_op\_parallelism\_threads and inter\_op\_parallelism...
2019/10/03
[ "https://Stackoverflow.com/questions/58223422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8776042/" ]
**first check the index labels and columns** ``` fact.index fact.columns ``` If you need to convert index to columns use: Use: ``` fact.reset_index() ``` **Then you can use:** ``` fact.groupby(['store_id', 'month'])['quantity'].mean() ``` Output: ``` store_id month 174 8 1 354 7 1...
need to add "**as\_index=True**" ex: "count\_in = df.groupby(['time\_in','id'], **as\_index=True**)['time\_in'].count()"
12,163
58,791,530
I am making a poem generator in python, and I am currently working on how poems are outputted to the user. I would like to make it so every line that is outputted will have a comma follow after. I thought I could achieve this easily by using the .join function, but it seems to attach to letters rather than the end of t...
2019/11/10
[ "https://Stackoverflow.com/questions/58791530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12334091/" ]
Just use the `+` or `+=` operator for strings, for example: ``` trailing_punct = ',' # can be '!', '?', etc. line1 += trailing_punct # or line1 = line1 + trailing_punct ``` `+=` can be used to modify the string "in place" (note that under the covers, it does create a new object and assign to it, so `id(line1)` will...
It seems your `line1` and `line2`are lists of strings, so I'll start by assuming that: ``` line1 = ["Moonlight", "is", "winter"] line2 = ["The", "waters", "scent", "fallen", "snow"] ``` You are using the default behaviour of the `print` function when given several string arguments to add the space between words: `pr...
12,164
18,788,493
I would like to extract filename from url in R. For now I do it as follows, but maybe it can be done shorter like in python. assuming path is just string. ``` path="http://www.exanple.com/foo/bar/fooXbar.xls" ``` in R: ``` tail(strsplit(path,"[/]")[[1]],1) ``` in Python: ``` path.split("/")[-1:] ``` Maybe some...
2013/09/13
[ "https://Stackoverflow.com/questions/18788493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/953553/" ]
There's a function for that... ``` basename(path) [1] "fooXbar.xls" ```
@SimonO101 has the most robust answer IMO, but some other options: Since regular expressions are greedy, you can use that to your advantage ``` sub('.*/', '', path) # [1] "fooXbar.xls" ``` Also, you shouldn't need the `[]` around the `/` in your `strsplit`. ``` > tail(strsplit(path,"/")[[1]],1) [1] "fooXbar.xls" ...
12,165
68,608,899
I want python to be printing a bunch of numbers like 1 to 10000. Then I want to decide when to stop the numbers from printing and the last number printed will be my number. something like. ``` for item in range(10000): print (item) number = input("") ``` But the problem is that it waits for me to place the...
2021/08/01
[ "https://Stackoverflow.com/questions/68608899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13472873/" ]
Catch `KeyboardInterrupt` exception when you interrupts the code by `Ctrl`+`C`: ``` import time try: for item in range(10000): print(item) time.sleep(1) except KeyboardInterrupt: print(f'Last item: {item}') ```
You can use the keyboard module: ``` import keyboard # using module keyboard i=0 while i<10000: # making a loop try: # used try so that if user pressed other than the given key error will not be shown print(i) if keyboard.is_pressed('q'): # if key 'q' is pressed print('Last number:...
12,166
22,081,361
I'm wondering if there's a way to fill under a pyplot curve with a vertical gradient, like in this quick mockup: ![image](https://i.imgur.com/ZoWCwRb.png) I found this hack on StackOverflow, and I don't mind the polygons if I could figure out how to make the color map vertical: [How to fill rainbow color under a curv...
2014/02/27
[ "https://Stackoverflow.com/questions/22081361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2774479/" ]
There may be a better way, but here goes: ``` from matplotlib import pyplot as plt x = range(10) y = range(10) z = [[z] * 10 for z in range(10)] num_bars = 100 # more bars = smoother gradient plt.contourf(x, y, z, num_bars) background_color = 'w' plt.fill_between(x, y, y2=max(y), color=background_color) plt.show(...
There is an alternative solution closer to the sketch in the question. It's given on Henry Barthes' blog <http://pradhanphy.blogspot.com/2014/06/filling-between-curves-with-color.html>. This applies an imshow to each of the patches, I've copied the code in case the link changes, ``` import numpy as np import matplotli...
12,167
53,494,637
I'm trying to build a Flask app that has Kafka as an interface. I used a Python connector, [kafka-python](https://kafka-python.readthedocs.io/en/master/index.html) and a Docker image for Kafka, [spotify/kafkaproxy](https://hub.docker.com/r/spotify/kafkaproxy/) . Below is the docker-compose file. ``` version: '3.3' se...
2018/11/27
[ "https://Stackoverflow.com/questions/53494637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4306852/" ]
**UPDATE** As mentioned by cricket\_007, given that you are using the docker-compose provided below, you should use `kafka:29092` to connect to Kafka from another container. So your code would look like this: ``` from kafka import KafkaConsumer, KafkaProducer TOPICS = ['PROFILE_CREATED', 'IMG_RATED'] BOOTSTRAP_SERVE...
I managed to get this up-and-running using a [network](https://docs.docker.com/compose/networking/) named `stream_net` between all services. ``` # for local development version: "3.7" services: zookeeper: image: confluentinc/cp-zookeeper:latest environment: ZOOKEEPER_CLIENT_PORT: 2181 ZOOKEEPER_...
12,168
65,734,652
I open a binary file with Python3 and want to print byte-by-byte in hex. However, all online resource only mention printing a "byte array" in hex. Please tell me how to print only 1 single byte, thanks. ```py #!/usr/bin/env python3 if __name__ == "__main__": with open("./datasets/data.bin", 'rb') as file: ...
2021/01/15
[ "https://Stackoverflow.com/questions/65734652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1417929/" ]
Try this one: ```py print(hex(byte[0])) ```
Using an `f-string` like this just prints two hex digits for each byte: ```py print(f'{byte[0]:02x}') ```
12,169
26,897,208
``` from pythonds.basic.stack import Stack rStack = Stack() def toStr(n,base): convertString = "0123456789ABCDEF" while n > 0: if n < base: rStack.push(convertString[n]) else: rStack.push(convertString[n % base]) n = n // base res = "" while not rStack.i...
2014/11/12
[ "https://Stackoverflow.com/questions/26897208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3448561/" ]
You are right that this particular function is **not** recursive. However, the context is, that on the previous slide there was a recursive function, and in this one they want to show a glimpse of how it *behaves* internally. They later say: > > The previous example [i.e. the one in question - B.] gives us some insig...
Because you're using a stack structure. If you consider how function calling is implemented, recursion is essentially an easy way to get the compiler to manage a stack of invocations for you. This function does all the stack handling manually, but it is still conceptually a recursive function, just one where the stac...
12,170
15,196,321
my project is to identify a sentiment either positive or negative ( sentiment analysis ) in Arabic language,to do this task I used NLTK and python, when I enter tweets in arabic an error occurs ``` >>> pos_tweets = [(' أساند كل عون أمن شريف', 'positive'), ('ما أحلى الثورة التونسية', 'positive'), ...
2013/03/04
[ "https://Stackoverflow.com/questions/15196321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2048995/" ]
You're on the right track with your `delete_model` method. When the django admin performs an action on multiple objects at once it uses the [update function](https://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once). However, as you see in the docs these actions are performed at the da...
Your method should be ``` class profilesAdmin(admin.ModelAdmin): #... def _profile_delete(self, sender, instance, **kwargs): # do something def delete_model(self, request, object): # do something ``` You should add a reference to current object as the first argument in every method sign...
12,173
51,861,677
I am trying to solve the problem called [R2](https://open.kattis.com/problems/r2) on kattis but for some reason, while the program (written in python) runs in the IDLE, I am met with a run time error in kattis with the judgement being a valueerror. Here's my code: ``` R1 = int(input('input R1 ')) S = int(input('input...
2018/08/15
[ "https://Stackoverflow.com/questions/51861677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10216731/" ]
``` nums = input().split(' ') r2 = 2*int(nums[1]) - int(nums[0]) print(r2) ``` The problem states that the two numbers will be input on a single line. You are attempting to capture two numbers input on two separate lines by calling `input` twice.
Darrahts pointed one problem out. The 2nd Problem is: `input([prompt])` writes the prompt to the standard output, however you should only write your solution to standard output.
12,181
30,205,473
I have the following JSON structure. I am attempting to extract the following information from the "brow\_eventdetails" section. * ATime * SBTime * CTime My question is is there any easy way to do this without using regular expression. In other words my question is the a nested JSON format that I can extract by some ...
2015/05/13
[ "https://Stackoverflow.com/questions/30205473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/316082/" ]
You need to parse again the json string of `json_data['message']` then just access the desired values, one way to do it: ``` # since the string value of `message` itself isn't a valid json string # discard it, and parse it with json again brow_eventdetails = json.loads(json_data['message'].replace('brow_eventdetails:'...
Parse this string value using json.loads as you would with every other string that contains JSON.
12,182
34,818,960
I need to highlight a specific word in a text within a tkinter frame. In order to find the word, I put a balise like in html. So in a text like "hello i'm in the |house|" I want to highlight the word "house". My frame is defined like that: `class FrameCodage(Frame): self.t2Codage = Text(self, height=20, width=50)` ...
2016/01/15
[ "https://Stackoverflow.com/questions/34818960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5464538/" ]
Instead of this: ``` class FrameCodage(Frame): self.t2Codage = Text(self, height=20, width=50) ``` ... do this: ``` class FrameCodage(Frame): self.t2Codage = CustomText(self, height=20, width=50) ``` Next, create a "highlight" tag, and configure it however you want: ``` self.t2Codage.tag_configure("highl...
Below is widget I created to deal with this, hope it helps. ``` try: import tkinter as tk except ImportError: import Tkinter as tk class code_editor(tk.Text): def __init__(self, parent, case_insensetive = True, current_line_colour = '', word_end_at = r""" .,{}[]()=+-*/\|<>%""", tags = {}, *args, **kwargs): ...
12,183
14,670,768
Hi I'm new to django and python. I want to extend django `User` model and add a `create_user` method in a model, then I call this `create_user` method from view. However, I got an error msg. My model: ``` from django.db import models from django.contrib.auth.models import User class Basic(models.Model): user = m...
2013/02/03
[ "https://Stackoverflow.com/questions/14670768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204127/" ]
Try ``` Basic.create_ck_user('fb', fb_id, fb_token) ``` You don't assign to strings when you call a function/method. You assign to variables. But since you are using positional arguments in your function definition then you don't even need them. Assigning to a string will never work anyway... strings are immutable...
Just look here: <https://docs.djangoproject.com/en/dev/topics/auth/default/#creating-users> You can find a lot of answers just looking at the documentation.
12,184
30,183,795
I know the normal way to use APScheduler is "python setup.py install". But I want to embed it into my program directly, so the user don't need install it when using my program. ``` class BaseScheduler(six.with_metaclass(ABCMeta)): _trigger_plugins = dict((ep.name, ep) for ep in iter_entry_points('apscheduler.triggers...
2015/05/12
[ "https://Stackoverflow.com/questions/30183795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/620853/" ]
You can instantiate the triggers directly, without going through their aliases. That eliminates the need to install APScheduler or setuptools. Does this answer your question?
I find a way to work around this problem. 1. use 'pip install apscheduler' to install locally 2. goto the installed directory and cp that directory to your lib directory 3. use 'pip uninstall apscheduler' to remove it. 4. make you code to import the apscheduler from your lib directory. 5. done.
12,185
11,174,997
(Python 2.7)I need to print the bfs of a binary tree with a given preorder and inorder and a max lenght of the strings of preorder and inorder. I know how it works, for example: preorder:ABCDE inorder:CBDAE max length:5 ``` A / \ B E / \ C...
2012/06/24
[ "https://Stackoverflow.com/questions/11174997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1419828/" ]
I guess essentially the question is how to get all the parent-leftChild pairs and parent-rightChild pairs of the tree from given preorder and inorder To get the parent-leftChild pairs, you need to check: 1) if node1 is right after node2 in preorder; 2) if node2 is in front of node1 in inorder For your example preorde...
To add children to any node, just get the node that you want to add children to and call setLeftChild or setRightChild on it.
12,186
61,590,927
I have a rather simple program using `dask`: ``` import dask.array as darray import numpy as np X = np.array([[1.,2.,3.], [4.,5.,6.], [7.,8.,9.]]) arr = darray.from_array(X) arr = arr[:,0] a = darray.min(arr) b = darray.max(arr) quantiles = darray.linspace(a, b, 4) print(np.array(quantiles...
2020/05/04
[ "https://Stackoverflow.com/questions/61590927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595776/" ]
Simply use `dnf` ```sh dnf -y install gcc-toolset-9-gcc gcc-toolset-9-gcc-c++ source /opt/rh/gcc-toolset-9/enable ``` ref: <https://centos.pkgs.org/8/centos-appstream-x86_64/gcc-toolset-9-gcc-9.1.1-2.4.el8.x86_64.rpm.html> Note: `source` won't work inside a Dockerfile so prefer to use: ``` ENV PATH=/opt/rh/gcc-too...
this command work for me ``` dnf install gcc --best --allowerasing ```
12,189
55,422,150
This is my first time using python and matplotlib and I'd like to plot data from a CSV file. The CSV file is in the form of: ``` 10/03/2018 00:00,454.95,594.86 ``` with about 4000 rows. I'd like to plot the data from the second column vs the datetime for each row and the data from the third column vs the datetime ...
2019/03/29
[ "https://Stackoverflow.com/questions/55422150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11245101/" ]
Just use promises (or callbacks) ================================ I know that everyone hates JavaScript and so these anti-idiomatic transpilers and new language "features" exist to make JavaScript look like C# and whatnot but, honestly, it's just easier to use the language the way that it was originally designed (othe...
Here's my updated function that works properly and synchronously, getting the data one by one and adding it to the database before moving to the next one. I have made it by customizing @coolAJ86 answer and I've marked that as the correct one but thought it would be helpful for people stumbling across this thread to s...
12,190
48,685,715
The problem is very simple: I want to call a script from a rule and I would like that rule to both: * Perform stdout and stderr redirection * Access the snakemake variables from the script(variable can be both lists and literals) If I use the `shell:` then, I can perform the I/O redirection but I cannot use the `...
2018/02/08
[ "https://Stackoverflow.com/questions/48685715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1935611/" ]
If possible, I suggest you use the [argparse](https://docs.python.org/3/library/argparse.html) module to parse the input of your script, so that it can parse a list of arguments as such, using the `nargs="*"` option: ```python def main(): """Main function of the program.""" parser = argparse.ArgumentParser( ...
You can access the log filenames within the python script with the snakemake.log varaibale, which is a list containing both filenames: ``` snakemake.log = [ LOG_FILES+'/create_hdf5/sample_1.out', LOG_FILES+'/create_hdf5/sample_1.err' ] ``` you can thus use this within your script to create log files for logging, e.g...
12,191
65,095,357
When I am adding new functions to a file I can't import them neither if I just run the script in terminal or if I launch `ipython` and try importing a function there. I have no `.pyc` files. It looks as if there is some kind of caching going on. I never actually faced such an issue even though have been working with va...
2020/12/01
[ "https://Stackoverflow.com/questions/65095357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3815432/" ]
We can use `pd.to_datetime` here with `errors='coerce'` to ignore the faulty dates. Then use the `dt.year` to calculate the difference: ``` df['date_until'] = pd.to_datetime(df['date_until'], format='%d.%m.%y', errors='coerce') df['diff_year'] = df['date_until'].dt.year - df['year'] ``` ``` year date_until diff_...
For everybody who is trying to replace values just like I wanted to in the first place, here is how you could solve it: ``` for i in range(len(df)): if pd.isna(df['date_until'].iloc[i]): df['date_until'].iloc[i] = f'30.06.{df["year"].iloc[i] +1}' if df['date_until'].iloc[i] == '-': df['date_unt...
12,192
47,726,913
I am trying to run the following code here to save information to the database. I have seen other messages - but - it appears that the solutions are for older versions of `Python/DJango` (as they do not seem to be working on the versions I am using now: `Python 3.6.3` and `DJango 1.11.7` ``` if form.is_valid(): tr...
2017/12/09
[ "https://Stackoverflow.com/questions/47726913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2707727/" ]
Just change ``` str(e.message) ``` to ``` str(e) ```
**some change** > > str(e.message) > > > **to** > > HttpResponse(e.message) > > >
12,193
60,543,957
I have a project folder with different cloud functions folders e.g. ``` Project_Folder -Cloud-Function-Folder1 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder2 -main.py -requirements.txt -cloudbuild.yaml -Cloud-Function-Folder3 ...
2020/03/05
[ "https://Stackoverflow.com/questions/60543957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508416/" ]
It's more complex et you have to play with limit and constraint of Cloud Build. I do this: * get the directory updated since the previous commit * loop on this directory and do what I want --- **Hypothesis 1**: all the subfolders are deployed by using the same commands So, for this I put a `cloudbuild.yaml` at the...
If you create a single source repo and change your code as one cloud function you have to create a single ['cloudbuild.yaml' configuration file](https://cloud.google.com/cloud-build/docs/build-config). You need to connect this single repo to Cloud Build. Then create a [build trigger](https://cloud.google.com/cloud-buil...
12,194
30,857,579
To be more specific: Is there a way for a python program to continue running even after it's closed (like automatic open at a certain time)? Or like a gmail notification? This is for an alarm project, and I want it to ring/open itself even if the user closes the window. Is there a way for this to happen/get scripted? I...
2015/06/16
[ "https://Stackoverflow.com/questions/30857579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4343751/" ]
You can implement a global `operator>>` for your `Numbers` class, eg: ``` std::istream& operator>>(std::istream &strm, Number &n) { int value; strm >> value; // or however you need to read the value... n = Number(value); return strm; } ``` Or: ``` class Number { //... friend std::istream& op...
You will probably have to return `number` at the end of function `getNumbersFromUser` to avoid memory leakage. Secondly, the line `cin >> number[i]` means that you are taking input in a variable of type `Number` which is not allowed. It is only allowed for primitive data type (int, char double etc.) or some built in ob...
12,199
53,201,387
I am trying to write python code that organizes n-dimensional data into bins. To do this, I'm initializing a list of empty lists using the following function, which takes an array with the number of bins for each dimension as an argument: ``` def empties(b): invB = np.flip(b, axis=0) empty = [] for b in ...
2018/11/08
[ "https://Stackoverflow.com/questions/53201387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4976543/" ]
You can `reduce` into an array, iterating over each subarray, and then over each split number from the subarray items: ```js const a = [ ["1.31069258855609,103.848649478524", "1.31138534529796,103.848923050526"], ["1.31213221536436,103.848328363879", "1.31288473199114,103.849575392632"] ]; const [d, e] = a.red...
One approach to this problem would be to take advantage of the ordering of number values in your string arrays. First flatten the two arrays into a single array, and then reduce the result - per iteration of the reduce operation, split a string by `,` into it's two parts, and then put the number value for each part i...
12,200
39,290,932
How to change python code to **.exe** file using microsoft Visual Studio 2015 without installing any package? Under "Build" button, there is no convert to **.exe** file.
2016/09/02
[ "https://Stackoverflow.com/questions/39290932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6737263/" ]
Here is the complete fix for the issue: ``` private async Task<IEnumerable<byte[]>> GetAttachmentsAsByteArrayAsync(Activity activity) { var attachments = activity?.Attachments? .Where(attachment => attachment.ContentUrl != null) .Select(c => Tuple.Create(c.ContentType, c.ContentUrl)); ...
<https://github.com/Microsoft/BotBuilder/issues/662#issuecomment-232223965> you mean this fix? Did this work out for you?
12,208
16,002,862
I'm rather new at using python and especially numpy, and matplotlib. Running the code below (which works fine without the `\frac{}{}` part) yields the error: ``` Normalized Distance in Chamber ($ rac{x}{L}$) ^ Expected end of text (at char 32), (line:1, col:33) ...
2013/04/14
[ "https://Stackoverflow.com/questions/16002862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1411736/" ]
In many languages, backslash-letter is a way to enter otherwise hard-to-type characters. In this case it's a "form feed". Examples: ``` \n — newline \r — carriage return \t — tab character \b — backspace ``` To disable that, you either need to escape the backslash itself (backslash-backslash is a backslash) ``` 'No...
`"\f"` is a form-feed character in Python. TeX never sees the backslash because Python interprets the `\f` in your Python source, before the string is sent to TeX. You can either double the backslash, or make your string a raw string by using `r'Normalized Distance ... etc.'`.
12,211
31,438,147
it is my first post on stackoverflow so please go easy on me! :) I am also relatively new to python so bear with me :) With all that said here is my issue: I am writing a bit of code for fun which calls an API and grabs the latest Bitcoin Nonce data. I have managed to do this fine, however now I want to be able to sav...
2015/07/15
[ "https://Stackoverflow.com/questions/31438147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5120590/" ]
Not entirely. It's right that the rules are only based on classes, and it does not matter if it is the same instance or another instance and that was basically your question. However, you made a mistake about *protected* in general. From the documentation: > > Members declared protected can be accessed only within t...
Yes, it's right. The visibility rules are based only on classes, instances have no impact. So if a class has access to a particular member in the same instance, it also has access to that member in other instances of that class. It's not a quirk, it's a deliberate design choice, similar to many other OO languages (I...
12,214
52,033,549
I have a csv file mentioned as below screen shot ... [![enter image description here](https://i.stack.imgur.com/WAVzb.png)](https://i.stack.imgur.com/WAVzb.png) and i want to convert the whole file in the below format in python. [![enter image description here](https://i.stack.imgur.com/ladmh.png)](https://i.stack.i...
2018/08/27
[ "https://Stackoverflow.com/questions/52033549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8966278/" ]
You can try this after reading your CSV file correct file path. ``` import pandas as pd df = pd.read_csv("path/to/file", names=["Sentence", "Value"]) result = [(row["Sentence"], row["Value"]) for index, row in df.iterrows()] print(result) ```
It's a single line using `apply()` method of dataframe `df.apply(lambda x: x.tolist(), axis=1)` OR `df.values.tolist()` will also work
12,215
2,137,619
Is it possible to implement in Scala something equivalent to the Python `yield` statement where it remembers the local state of the function where it is used and "yields" the next value each time it is called? I wanted to have something like this to convert a recursive function into an iterator. Sort of like this: ``...
2010/01/26
[ "https://Stackoverflow.com/questions/2137619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/257449/" ]
While Python generators are cool, trying to duplicate them really isn't the best way to go about in Scala. For instance, the following code does the equivalent job to what you want: ```scala def classStream(clazz: Class[_]): Stream[Class[_]] = clazz match { case null => Stream.empty case _ => ( clazz #:: ...
To do this in a general way, I think you need the [continuations plugin](http://blog.richdougherty.com/search/label/continuations). A naive implementation (freehand, not compiled/checked): ``` def iterator = new { private[this] var done = false // Define your yielding state here // This generator yields: 3, 13...
12,216
69,978,383
everyone, beforehand - I'm a bloody but motivated developer beginner. I am currently trying to react to simple events (click on a button) in the HTML code in my Django project. Unfortunately without success ... HTML: ``` <form> {% csrf_token %} <button id="CSVDownload" type="button">CSV Download!</button> </...
2021/11/15
[ "https://Stackoverflow.com/questions/69978383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17420473/" ]
You should be able to use ``` delete a,b from `t ``` to delete in place (The backtick implies in place). Alternatively, for more flexibility you could use the functional form; ``` ![`t;();0b;`a`b] ```
The simplest way to achieve column deletion in place is using qSQL: `t:([]a:1 2 3;b:4 5 6;c:`d`e`f)` `delete a,b from `t` -- here, the backtick before `t` makes the change in place. ``` q)t c - d e f ```
12,225
45,096,654
I recently signed up and started playing with GAE for python. I was able to get their standard/flask/hello\_world project. But, when I tried to upload a simple cron job following the instructions at <https://cloud.google.com/appengine/docs/standard/python/config/cron>, I get an "Internal Server Error". My cron.yaml `...
2017/07/14
[ "https://Stackoverflow.com/questions/45096654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/593644/" ]
I was having this problem as well, at about the same timeline. Without any changes, the deploy worked this morning, so my guess is that this was a transient server problem on Google's part.
I was just struggling with this same issue. In my case, I am using the PHP standard environment and kept receiving the '500 Internal Server Error' when I tried to publish our cron.yaml file from the Google Cloud SDK with the command: ``` gcloud app deploy cron.yaml --project {PROJECT_NAME} ``` To fix it, I did the f...
12,228
74,041,729
I have a dataset like this ``` ID Year Day 1 2001 150 2 2001 140 3 2001 120 3 2002 160 3 2002 160 3 2017 75 3 2017 75 4 2017 80 ``` I would like to drop the duplicates within each year, but keep those were the year differs. End result would be...
2022/10/12
[ "https://Stackoverflow.com/questions/74041729", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12546311/" ]
add 'year' in your subset. ``` data.drop_duplicates(subset = ['ID','Year'], keep = 'first') ``` ``` ID Year Day 0 1 2001 150 1 2 2001 140 2 3 2001 120 3 3 2002 160 5 3 2017 75 7 4 2017 80 ```
Another possible solution: ``` df.groupby('Year').apply(lambda g: g.drop_duplicates()).reset_index(drop=True) ``` Output: ``` ID Year Day 0 1 2001 150 1 2 2001 140 2 3 2001 120 3 3 2002 160 4 3 2017 75 5 4 2017 80 ```
12,229
57,015,932
I'm developing an GUI for multi-robot system using ROS, but i'm freezing in the last thing i want in my interface: embedding the RVIZ, GMAPPING or another screen in my application. I already put an terminal in the interface, but i can't get around of how to add an external application window to my app. I know that PyQt...
2019/07/13
[ "https://Stackoverflow.com/questions/57015932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11595480/" ]
Solved it! just pass the style to the scrollableTabView style={{width: '100%' }}
Solved it! Replace DefaultTabBar with ScrollableTabBar (don't forget to import it)
12,230
27,780,868
I need to use Backpropagation Neural Netwrok for multiclass classification purposes in my application. I have found [this code](http://danielfrg.com/blog/2013/07/03/basic-neural-network-python/#disqus_thread) and try to adapt it to my needs. It is based on the lections of Machine Learning in Coursera from Andrew Ng. I...
2015/01/05
[ "https://Stackoverflow.com/questions/27780868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4202221/" ]
Try `$eval` on `attr.target` like ``` var data = $scope.$eval($attrs.target) ``` Or if your data is dynamic you can $watch the attr ``` var data = []; $scope.$watch($attrs.target, function(newValue, oldValue){ data = newValue; }) ``` Also correct your controller injection like below, else if you will get error...
What I went with was removing the `target` attribute altogether, and instead broadcasting on the `$rootScope`. Directive: ``` this.foo = function(){ $rootScope.$broadcast('sortButtons', { predicate: 'foo', reverse: false }); }; ``` Controller: ``` $rootScope.$on('sortButtons', function(e...
12,231
55,050,699
### Task I have a text file with alphanumeric filenames: ``` \abc1.txt. \abc2.txt \abc3.txt \abcde3.txt \Zxcv1.txt \mnbd2.txt \dhtdv.txt ``` I need to extract all `.txt` extensions from the file, which will be in the same line and also different line in the file in python. ### Desired Output: ...
2019/03/07
[ "https://Stackoverflow.com/questions/55050699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11167162/" ]
Another way to do this, is to wrap the `CupertinoDatePicker` in `CupertinoTheme`. ``` CupertinoTheme( data: CupertinoThemeData( textTheme: CupertinoTextThemeData( dateTimePickerTextStyle: TextStyle( fontSize: 16, ), ), ), child: CupertinoDatePicker(...
Finally got it, works as expected. ``` DefaultTextStyle.merge( style: TextStyle(fontSize: 20), child: CupertinoDatePicker(....) ) ```
12,232