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
56,181,987
I installed PySpark on Amazon AWS using instructions: <https://medium.com/@josemarcialportilla/getting-spark-python-and-jupyter-notebook-running-on-amazon-ec2-dec599e1c297> This works fine: ```py Import pyspark as SparkContext ``` This gives error: ``` sc = SparkContext() TypeError ...
2019/05/17
[ "https://Stackoverflow.com/questions/56181987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11270319/" ]
You can just use the copy constructor of `ArrayList` which accepts a `Collection<? extends E>`: ``` List<GtbEtobsOYenibelge> listOnayStatu = servis.listOnayStatus4Belge(user.getBirimId().getId()); List<GtbEtobsOYenibelge> cloneOnayStatu = new ArrayList<>(listOnayStatu); ``` That way you create a copy of `listOnaySta...
The method `servis.listOnayStatus4Belge` returns a [Vector](https://docs.oracle.com/javase/8/docs/api/index.html). A `Vector` implements the `List` interface but is not an `ArrayList`. Therefore you can't cast it to one. Looking at the problematic statement: ``` cloneOnayStatu = ((List) ((ArrayList) listOnayStatu).c...
12,705
41,492,878
I tried to install "scholarly" package, but I keep receiving this error: ``` x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c build/temp.li...
2017/01/05
[ "https://Stackoverflow.com/questions/41492878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5413088/" ]
I had the same problem. This one helped me: ``` sudo apt-get install build-essential libssl-dev libffi-dev python-dev ``` If you are using `python3`, try to replace `python-dev` with `python3-dev`
Install lib32ncurses5-dev: ``` sudo apt-get install lib32ncurses5-dev ```
12,707
39,983,159
This is the code that results in an error message: ``` import urllib import xml.etree.ElementTree as ET url = raw_input('Enter URL:') urlhandle = urllib.urlopen(url) data = urlhandle.read() tree = ET.parse(data) ``` The error: ![error msg screenshot](https://i.stack.imgur.com/eMKS2.png) I'm new to python. I di...
2016/10/11
[ "https://Stackoverflow.com/questions/39983159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6938631/" ]
`data` is a reference to the XML content as a string, but the [`parse()`](https://docs.python.org/2.7/library/xml.etree.elementtree.html#xml.etree.ElementTree.parse) function expects a filename or [file object](https://docs.python.org/2/glossary.html#term-file-object) as argument. That's why there is an an error. `url...
The error message indicates that your code is trying to open a file, who's name is stored in the variable source. It's failing to open that file (IOError) because the variable source contains a bunch of XML, not a file name.
12,713
55,436,590
I am a beginner trying to learn Python. I wrote a program using Geany and would like to build and execute it but I keep getting this error: "The system cannot find the path specified". I believe I added the right info to the Path though: ``` Compile C:\Python373\python -m py_compile "%f" Execute C:\Python373\python "...
2019/03/30
[ "https://Stackoverflow.com/questions/55436590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10286420/" ]
You can try this solution First open `sdkmanager.bat` with any text editor Then find this line ``` %JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %SDKMANAGER_OPTS% ``` And change it to this line ``` %JAVA_EXE%" %DEFAULT_JVM_OPTS% --add-modules java.xml.bind %JAVA_OPTS% %SDKMANAGER_OPTS% ``` I hope this solve...
I had to do the following to fix this error on Windows 10: 1. Install JDK 8. I had JDK 12 installed but it did not seem to work with that version. 2. Add Java to my environment variable Path To add Java to your environment variable Path do the following: `Go to Computer -> Advanced system settings -> Environment var...
12,716
17,260,338
I'm trying to deploy a Flask app to Heroku however upon pushing the code I get the error ``` 2013-06-23T11:23:59.264600+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch ``` I'm not sure what to try, I've tried changing the port from 5000 to 33507, but...
2013/06/23
[ "https://Stackoverflow.com/questions/17260338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970323/" ]
In my Flask app hosted on Heroku, I use this code to start the server: ```py if __name__ == '__main__': # Bind to PORT if defined, otherwise default to 5000. port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port) ``` When developing locally, this will use port 5000, in production Her...
Your `main.py` script cannot bind to a specific port, it needs to bind to the port number set in the `$PORT` environment variable. Heroku sets the port it wants in that variable prior to invoking your application. The error you are getting suggests you are binding to a port that is not the one Heroku expects.
12,719
60,136,547
I can't figure out how to use multithreading/multiprocessing in python to speed up this scraping process getting all the usernames from the hashtag 'cats' on instagram. My goal is to make this as fast as possible because currently the process is kinda slow ``` from instaloader import Instaloader HASHTAG = 'cats' ...
2020/02/09
[ "https://Stackoverflow.com/questions/60136547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12867155/" ]
The `LockedIterator` is inspired from [here](https://stackoverflow.com/questions/1131430/are-generators-threadsafe). ``` import threading from instaloader import Instaloader class LockedIterator(object): def __init__(self, it): self.lock = threading.Lock() self.it = it.__iter__() def __iter__...
**Goal is to have an input file and seperated output.txt files, maybe you can help me here to** It should be something with line 45 And i'm not really advanced so my try may contains some wrong code, I don't know As an example hashtags for input.txt I used the: *wqddt & d2deltas* ``` from instaloader import Insta...
12,725
20,763,448
EDITED HEAVILY with some new information (and a bounty) I am trying to create a plug in in python for gimp. (on windows) this page <http://gimpbook.com/scripting/notes.html> suggests running it from the shell, or looking at ~/.xsession-errors neither work. I am able to run it from the cmd shell, as > > gimp-2.8.e...
2013/12/24
[ "https://Stackoverflow.com/questions/20763448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1456530/" ]
> > 1- can i refresh a plugin without restarting gimp ? (so at least my > slow-morph will be faster ) > > > You must restart GIMP when you add a script or change register(). No need to restart when changing other parts of the script -- it runs as a separate process and will be re-read from disk each time. help...
as noted in [How do I output info to the console in a Gimp python script?](https://stackoverflow.com/questions/9955834/how-do-i-output-info-to-the-console-in-a-gimp-python-script/15637932#15637932) add ``` import sys sys.stderr = open( 'c:\\temp\\gimpstderr.txt', 'w') sys.stdout = open( 'c:\\temp\\gimpstdout.txt', ...
12,726
55,841,631
So i have a question to create a matrix, but I'm unsure why the values are shared? Not sure if its due to the sequence being a reference type or not? If you write this code in pythontutor, you'll find that the main tuple all points to the same 'row' tuple and is shared. I understand that if I did `return row*n` it'd b...
2019/04/25
[ "https://Stackoverflow.com/questions/55841631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11245768/" ]
The reason why your query isn't working as expected is because you are not actually targeting the specific array element you want to update. Here's how I would write the query: ``` patients.findOneAndUpdate( {_id: "5cb939a3ba1d7d693846136c"}, {$set: {"myArray.$[el].value": 424214 } }, { arrayFilters: [{ "...
Ok i found out and managed to update but the right answer from Frank Rose is better cause it worked in my other projects but not the current one Because i was using version 4.4 of mongoose, only version 5 and above can use arrayfilter For mongoose version < 5: ``` patients.findOneAndUpdate( { _id: "5cb939a3ba1...
12,728
50,913,172
Big hello to the Stackoverflow community, I am trying to read in a .csv file with 1370 rows and two columns: `Time` and `Speed`. ``` Time Speed 0 1 1 4 2 7 3 8 ``` I want to find the difference in `Speed` between two time steps (e.g. `Time` `2` and `1`, which is `3`) for the entire len...
2018/06/18
[ "https://Stackoverflow.com/questions/50913172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9957516/" ]
You can just use [`pd.Series.diff`](http://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.Series.diff.html): ``` df['ds'] = df['Speed'].diff() print(df) Time Speed ds 0 0 1 NaN 1 1 4 3.0 2 2 7 3.0 3 3 8 1.0 ``` The loop method you've attempted is not recom...
Use: ``` df['Speed_avg'] = df['Speed'].rolling(2, min_periods=2).mean() df['ds'] = df['Speed'].diff() ``` Output: ``` Time Speed Speed_avg ds 0 0 1 NaN NaN 1 1 4 2.5 3.0 2 2 7 5.5 3.0 3 3 8 7.5 1.0 ```
12,729
46,501,292
I'm building a data extract using [scrapy](https://scrapy.org/) and want to normalize a raw string pulled out of an HTML document. Here's an example string: ``` Sapphire RX460 OC 2/4GB ``` Notice two groups of two whitespaces preceeding the string literal and between `OC` and `2`. Python provides trim as describ...
2017/09/30
[ "https://Stackoverflow.com/questions/46501292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/712334/" ]
You can use: ``` " ".join(s.split()) ``` where `s` is your string.
You can use a function like below with regular expression to scan for continuous spaces and replace them by 1 space ``` import re def clean_data(data): return re.sub(" {2,}", " ", data.strip()) product_title = clean(product.css('h3::text').extract_first()) ``` And then improve clean function anyway you like it
12,730
37,336,875
I have a 2 set of data i crawled from a html table using regex expression data: ``` <div class = "info"> <div class="name"><td>random</td></div> <div class="hp"><td>123456</td></div> <div class="email"><td>random@mail.com</td></div> </div> <div class = "info"> <div class="name"><td>random123</td><...
2016/05/20
[ "https://Stackoverflow.com/questions/37336875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797825/" ]
You should not be parsing HTML with regex. It's just a mess, do it with BS4. Doing it the right way: ``` soup = BeautifulSoup(match3, "html.parser") names = [] allTds = soup.find_all("td") for i,item in enumerate(allTds[::3]): # firstname hp email names.append((item.text, allTds[(i*...
As @Racialz pointed out, you should look into [using HTML parsers instead of regular expressions](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). Let's take [`BeautifulSoup`](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) as well as @Racialz did, but build ...
12,733
39,679,940
I have two lists: ``` list1=['lo0','lo1','te123','te234'] list2=['lo0','first','lo1','second','lo2','third','te123','fourth'] ``` I want to write a python code to print the next element of list2 where item of list1 is present in list2,else write "no-match",i.e, I want the output as: ``` first second no-match fourth...
2016/09/24
[ "https://Stackoverflow.com/questions/39679940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6708941/" ]
You're absolutely right - `messagePolling` is a function. However, `messagePolling()` is *not* a function. You can see that right in your console: ``` // assume messagePolling is a function that doesn't return anything messagePolling() // -> undefined ``` So, when you do this: ``` setTimeout(messagePolling(), 1000)...
Written as `setTimeout(messagePolling(),1000)` the function is executed **immediately** and a `setTimeout` is set to call `undefined` (the value returned by your function) after one second. (this should actually throw an error if ran inside Node.js, as `undefined` is not a valid function) Written as `setTimeout(messa...
12,734
52,608,069
a python Newbie here. I am currently trying to figure out how to parse all the msg files I have stored in a specific folder and then save the body text to a csv file. ``` import win32com.client outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") msg = outlook.OpenSharedItem(r"C:\Users\XY\Do...
2018/10/02
[ "https://Stackoverflow.com/questions/52608069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10445933/" ]
You can try something like this to iterate through every file with '.msg' extension in a directory: ``` import os pathname = os.fsencode('Pathname as string') for file in os.listdir(pathname): filename = os.fsdecode(file) if filename.endswith(".msg"): #Do something continue else: ...
You can use `pathlib` to iterate over the contents of the directory. Try this: ``` from pathlib import Path import win32com.client outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") # Assuming \Documents\Email Reader is the directory containg files for p in Path(r'C:\Users\XY\Documents...
12,739
39,280,060
So I was messing around in python, and developed a problem. I start out with a string like the following: ``` a = "1523467aa252aaa98a892a8198aa818a18238aa82938a" ``` For every number, you have to add it to a `sum` variable.Also, with every encounter of a letter, the index iterator must move back 2. My program keeps ...
2016/09/01
[ "https://Stackoverflow.com/questions/39280060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6421595/" ]
This part is not doing what you think: ``` for i in a: if isinstance(a[i], int): ``` Since `i` is an iterator, there is no need to use `a[i]`, it will confuse Python. Also, since `a` is a string, no element of it will be an `int`, they will all be `string`. You want something like this: ``` for i in a: if ...
You have a few problems with your code. You don't seem to understand how `for... in` loops work, but @Will already addressed that problem in his answer. Furthermore, you have a misunderstanding of how `isinstance()` works. As the numbers are characters of a string, when you iterate over that string each character will ...
12,740
8,329,601
I am a beginner in python and cant understand why this is happening: ``` from math import * print "enter the number" n=int(raw_input()) d=2 s=0 while d<n : if n%d==0: x=math.log(d) s=s+x print d d=d+1 print s,n,float(n)/s ``` Running it in Python and inputing a non prime gives the err...
2011/11/30
[ "https://Stackoverflow.com/questions/8329601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/855763/" ]
Change ``` from math import * ``` to ``` import math ``` Using `from X import *` is generally not a good idea as it uncontrollably pollutes the global namespace and could present other difficulties.
You need to `import math` rather than `from math import *`.
12,741
49,709,826
I am on Windows 10, and I run the following Python file: ``` import subprocess subprocess.call("dir") ``` But I get the following error: ``` File "A:/python-tests/subprocess_test.py", line 10, in <module> subprocess.call(["dir"]) File "A:\anaconda\lib\subprocess.py", line 267, in call with Popen(*pope...
2018/04/07
[ "https://Stackoverflow.com/questions/49709826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3486684/" ]
dir is a command implemented in cmd.exe so there is no dir.exe windows executable. You must call the command through cmd. ``` subprocess.call(['cmd', '/c', 'dir']) ```
You ***must*** set `shell=True` when calling `dir`, since `dir` isn't an executable (there's no such thing as dir.exe). `dir` is an [internal command](https://www.computerhope.com/jargon/i/intecomm.htm) that was loaded with cmd.exe. As you can see from the [documentation](https://docs.python.org/dev/library/subprocess...
12,746
48,213,605
So I have a csv file that looks like this.. ``` 1 a 2 b 3 c ``` And I want to make it look like this.. ``` 1 2 3 a b c ``` I'm at a loss for how to do this with python3, anyone have any ideas? Really appreciate it
2018/01/11
[ "https://Stackoverflow.com/questions/48213605", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8761965/" ]
Are you reading the csv with pandas? you can always use numpy or pandas transpose ``` import numpy as np ar1 = np.array([[1,2,3], ['a','b','c']]) ar2 = np.transpose(ar1) Out[22]: array([['1', 'a'], ['2', 'b'], ['3', 'c']], dtype='<U11') ```
As others have mentioned, `pandas` and `transpose()` is the way to go here. Here is an example: ``` import pandas as pd input_filename = "path/to/file" # I am using space as the sep because that is what you have shown in the example # Also, you need header=None since your file doesn't have a header df = pd.read_csv(...
12,747
5,188,285
I need to get some debugging libraries/tools to trace back the stack information print out to the stdout. Python's [traceback](http://docs.python.org/library/traceback.html) library can be an example. What can be the C++ equivalent to Python's traceback library?
2011/03/04
[ "https://Stackoverflow.com/questions/5188285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
This is platform-specific, and also depends on how you're compiling code. If you compile code with gcc using `-fomit-frame-pointer` it's very hard to get a useful backtrace, generally requiring heuristics. If you're using any libraries that use that flag you'll also run into problems--it's often used for heavily optimi...
Try [google core dumper](http://code.google.com/p/google-coredumper/), it will give you a core dump when you need it.
12,748
14,962,289
I am running a django app with nginx & uwsgi. Here's how i run uwsgi: ``` sudo uwsgi -b 25000 --chdir=/www/python/apps/pyapp --module=wsgi:application --env DJANGO_SETTINGS_MODULE=settings --socket=/tmp/pyapp.socket --cheaper=8 --processes=16 --harakiri=10 --max-requests=5000 --vacuum --master --pidfile=/tmp/pyapp-...
2013/02/19
[ "https://Stackoverflow.com/questions/14962289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202690/" ]
**EDIT 1** Seen the comment that you have 1 virtual core, adding commentary through on all relavant points **EDIT 2** More information from Maverick, so I'm eliminating ideas ruled out and developing the confirmed issues. **EDIT 3** Filled out more details about uwsgi request queue and scaling options. Improved gramm...
Adding more workers and getting less r/s means that your request "is pure CPU" and there is no IO waits that another worker can use to serve another request. If you want to scale you will need to use another server with more (or faster) cpu's. However this is a synthetic test, the number of r/s you get are the upper ...
12,756
47,943,854
I'm new to waf build tool and I've googled for answers but very few unhelpful links. Does anyone know? As wscript is essentially a python script, I suppose I could use the `os` package?
2017/12/22
[ "https://Stackoverflow.com/questions/47943854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5556905/" ]
Don't use the `os` module, instead use the `DEST_*` variables: ```py ctx.load('compiler_c') print (ctx.env.DEST_OS, ctx.env.DEST_CPU, ctx.env.DEST_BINFMT) ``` On my machine this would print `('linux', 'x86_64', 'elf')`. Then you can dispatch on that.
You can use `import` at every point where you could use it any other python script. I prefer using `platform` for programming a function os-agnostic instead on evaluate some attributes of `os`. Writing the [Build-related commands](https://waf.io/book/#_build_related_commands) example in the [waf book](https://waf.io/...
12,759
37,400,078
I am trying to translate an if-else statement written in c++ to a corresponding chunk of python code. For a C++ map dpt2, I am attempting to translate: ``` if (dpt2.find(key_t) == dpt2.end()) { dpt2[key_t] = rat; } else { dpt2.find(key_t) -> second = dpt2.find(key_t) -> second + rat; } ``` I'm not super familiar wit...
2016/05/23
[ "https://Stackoverflow.com/questions/37400078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3396878/" ]
First of all, in C++ you'd write that as: ``` dpt[key_t] += rat; ``` That will do only one map lookup - as opposed to the code you wrote which does 2 lookups in the case that `key_t` isn't in the map and 3 lookups in the case that it is. --- And in Python, you'd write it much the same way - assuming you declare `...
Something like this? ``` dpt2[key_t] = dpt2.get(key_t, 0) + rat ```
12,760
17,093,322
I have a large data set of urls and I need a way to parse words from the urls eg: ``` realestatesales.com -> {"real","estate","sales"} ``` I would prefer to do it in python. This seems like it should be possible with some kind of english language dictionary. There might be some ambiguous cases, but I feel like there...
2013/06/13
[ "https://Stackoverflow.com/questions/17093322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1893354/" ]
This is a problem is word segmentation, and an efficient dynamic programming solution exists. [This](http://thenoisychannel.com/2011/08/08/retiring-a-great-interview-problem/) page discusses how you could implement it. I have also answered this question on SO before, but I can't find a link to the answer. Please feel f...
This might be of use to you: <http://www.clips.ua.ac.be/pattern> It's a set of modules which, depending on your system, might already be installed. It does all kinds of interesting stuff, and even if it doesn't do exactly what you need it might get you started on the right path.
12,761
14,441,412
I have python scripts and shell scripts in the same folder which both need configuration. I currently have a config.py for my python scripts but I was wondering if it is possible to have a single configuration file which can be easily read by both python scripts and also shell scripts. Can anyone give an example of th...
2013/01/21
[ "https://Stackoverflow.com/questions/14441412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738522/" ]
I think the simplest solution will be : ``` key1="value1" key2="value2" key3="value3" ``` in [shell](/questions/tagged/shell "show questions tagged 'shell'") you just have to source this env file and in Python, it's easy to parse. Spaces are not allowed around `=` For Python, see this post : [Emulating Bash 'sourc...
This is valid in both shell and python: ``` NUMBER=42 STRING="Hello there" ``` what else do you need?
12,763
680,320
Consider the following skeleton of a models.py for a space conquest game: ``` class Fleet(models.Model): game = models.ForeignKey(Game, related_name='planet_set') owner = models.ForeignKey(User, related_name='planet_set', null=True, blank=True) home = models.ForeignKey(Planet, related_name='departing_fleet...
2009/03/25
[ "https://Stackoverflow.com/questions/680320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51100/" ]
Django's ORM does not implement an [identity map](http://en.wikipedia.org/wiki/Identity_map) (it's in the [ticket tracker](http://code.djangoproject.com/ticket/17), but it isn't clear if or when it will be implemented; at least one core Django committer has [expressed opposition to it](http://spreadsheets.google.com/cc...
This is perhaps what you are looking for: <https://web.archive.org/web/20121126091406/http://simonwillison.net/2009/May/7/mmalones/>
12,769
41,931,719
I am learning Python and I am reading the "Think Python" and doing some simple exercises included in the book. I am asked "Define a new function called do\_four that takes a function object and a value and calls the function four times, passing the value as a parameter." I am trying to compose this function with one ...
2017/01/30
[ "https://Stackoverflow.com/questions/41931719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7128498/" ]
`do_twice` gets a function on the first argument, and doesn't return anything. So there is no reason to pass `do_twice` the result of `do_twice`. You need to pass it `a function`. This would do what you meant: ``` def do_four(f, v): do_twice(f, v) do_twice(f, v) ``` Very similar to how you defined `do_twice...
> > > ``` > do_twice(do_twice(f, v), v) > ^^^^^^^^^^^^^^ > > ``` > > Slightly rewritten: ``` result = do_twice(f, v) do_twice(result, v) ``` You're passing the return value of `do_twice(...)` as the first parameter to `do_twice(...)`. That parameter is supposed to be a function object. `do_twice` does...
12,770
24,029,634
I ran into this today and can't figure out why. I have several functions chained together that perform some time consuming operations as part of a larger pipeline. I've included these here, pared down to a test example, as best as I could. The issue is that when I call a function directly, I get the expected output (e....
2014/06/04
[ "https://Stackoverflow.com/questions/24029634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1027577/" ]
I solved this one, with a point in the right direction from @mgilson. In fact, it was a random number problem, just not in python - in R (sigh). The state of R is copied when the Pool is created, meaning so is its random seed. To fix, just a little rpy2 as below calling R's set.seed function (with some process specific...
I'm not 100% familiar with these libraries, however, on Linux, (IIRC) `multiprocessing` uses `os.fork`. This means that the state of the random module (which you're using) will also be forked and that each of your processes will generate *the same sequence of random numbers* resulting in a not-so-random `_get_random_st...
12,771
1,770,789
I'm trying to write a python script which follows the common unix command line pattern of accepting input from stdin if no file name is given. This is what I've been using: ``` if __name__ == "__main__": if len(sys.argv) > 1: stream = open(sys.argv[1]) else: stream = sys.stdin ``` Is there a ...
2009/11/20
[ "https://Stackoverflow.com/questions/1770789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/170340/" ]
The [fileinput](http://docs.python.org/library/fileinput.html) module is perfect for this.
similar but one-line solution ``` stream = sys.argv[1] if len(sys.argv)>1 else sys.stdin ```
12,772
45,703,959
When trying to deploy an Flask application to my LAMP server, I got an error from [flipflop](https://github.com/Kozea/flipflop), a FastCGI/WSGI gateway which enables my application to speak the FastCGI protocol. > > ~/minimal/run.py > > > ``` from flask import Flask from flipflop import WSGIServer app = Flask(_...
2017/08/16
[ "https://Stackoverflow.com/questions/45703959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5399734/" ]
I've managed to run your example, but there are some tweaking involved to make it work. You might need to change paths on your system, because from your logs it seems that you're using system that runs `python2.6` and older `apache` version which still uses `httpd` file. If it is possible I would advise you to up...
You can't run the fastcgi script from the terminal. This script is supposed to be executed by Apache. Typically you have it configured in a `ScriptAlias` directive in your Apache config file.
12,778
33,874,089
I am trying to integrate Alipay Gateway with my website using [this](https://github.com/liuyug/django-alipay). I am getting the payment form but on redirecting to Alipay's website I am getting the `ILLEGAL_PARTNER_EXTERFACE` (pic attached) error. [![enter image description here](https://i.stack.imgur.com/3ppU1.png)](h...
2015/11/23
[ "https://Stackoverflow.com/questions/33874089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3442820/" ]
According to the official documentation [here](https://cshall.alipay.com/support/help_detail.htm?help_id=397107), the possible reasons for that error code are: * You did not apply for this particular payment gateway type * You did apply for this payment gateway type, but it has not been approved yet * You did apply fo...
Which you use Alipay gateway API? It appears you have not applied for the relevant interface privillege or incorrect **partner\_id** param. Whatever you use anyone language,they just it's based on common http request. Alipay provides a sandbox enviroment.But them use a common **partner\_id**. As far as I know none p...
12,781
56,768,320
It often occurs to me when I try to manipulate data, for example **"UnicodeDecodeError: 'gbk' codec can't decode byte 0x91 in position 2196: illegal multibyte sequence".** I have found a way to bypass this error but my curiosity drives me to investigate what is in position 2196. ### **Here comes the question**: How ...
2019/06/26
[ "https://Stackoverflow.com/questions/56768320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6632083/" ]
You need to subscribe to the post observable returned by `method` function. It is done like this. ``` this.method().subscribe( res => { // Handle success response here }, err => { // Handle error response here } ...
you are getting the 400 bad request error, the payload keys are mis matching with the middle wear. please suggest pass the correct params into Request object.
12,782
3,331,850
I generated a SQL script from a C# application on Windows 7. The name entries have utf8 characters. It works find on Windows machine where I use a python script to populate the db. Now the same script fails on Linux platform complaining about those special characters. Similar things happened when I generated XML file ...
2010/07/26
[ "https://Stackoverflow.com/questions/3331850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243655/" ]
Please give a small example of a script with "utf8 characters" in the "name entries". Are you sure that they are `utf8` and not some windows encoding like `cp1252'? What makes you sure? Try this in Python at the command prompt: ``` ... python -c "print repr(open('small_script.sql', 'rb').read())" ``` The interesting...
Assuming you're using python, make sure you are using [Unicode strings](http://evanjones.ca/python-utf8.html). For example: ``` s = "Hello world" # Regular String u = u"Hello Unicode world" # Unicdoe String ``` Edit: Here's an example of reading from a UTF-8 file from the linked site: ``` import codecs...
12,784
63,397,618
I'm currently trying to run an application using Docker but get the following error message when I start the application: ```py error while loading shared libraries: libopencv_highgui.so.4.4: cannot open shared object file: No such file or directory ``` I assume that something is going wrong in the docker file and ...
2020/08/13
[ "https://Stackoverflow.com/questions/63397618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13460282/" ]
I was facing the same issue before when installing OpenCV in Docker with Python image. You probably don't need this much dependencies but it's an option. I will have a lightweight version that fits my case. Please give a try for the following code: **Heavy-loaded version:** ``` FROM python:3.7 RUN apt-get update \ ...
```sh apt-get update -y apt install -y libsm6 libxext6 apt update pip install pyglview apt install -y libgl1-mesa-glx ```
12,785
40,828,531
This is a little bit a newbie question I know. But however I couldn't find an answer to this question. I have made some websites that leverage the functionality of automatic emailling. I have made this websites using PHP. Every website I do, in the mailling part, I come accross some "redundancies". Let me give an exam...
2016/11/27
[ "https://Stackoverflow.com/questions/40828531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4966877/" ]
First comments on your net's way of working: * there is no arrow back to the `off` state. So once you switch on your washing machine, won't you never be able to switch it off again ? * `drain` and `dry` both conduct back to `idle`. But when idle has a token, it will either go to delicate or to T1. The conditions ("pr...
Apparently you're missing some condition to stop the process. Now once you start your washing will continue in an endless loop.
12,787
48,108,469
I am doing some PCA using sklearn.decomposition.PCA. I found that if the input matrix X is big, the results of two different PCA instances for PCA.transform will not be the same. For example, when X is a 100x200 matrix, there will not be a problem. When X is a 1000x200 or a 100x2000 matrix, the results of two different...
2018/01/05
[ "https://Stackoverflow.com/questions/48108469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7439635/" ]
There's a `svd_solver` param in PCA and by default it has value "auto". Depending on the input data size, it chooses most efficient solver. Now as for your case, when size is larger than 500, it will choose `randomized`. > > svd\_solver : string {‘auto’, ‘full’, ‘arpack’, ‘randomized’} > > > **auto** : > > > th...
I had a similar problem even with the same trial number but on different machines I was getting different result setting the svd\_solver to '`arpack`' solved the problem
12,789
45,890,001
I want to capture only the lines that end with two asterisks using the following code: ``` import re total_lines = 0 processed_lines = 0 regexp = re.compile(r'[*][\s]+[*]$') for line in open('testfile.txt', 'r'): total_lines += 1 if regexp.search(line): print'Line not parsed. Format not defined yet' ...
2017/08/25
[ "https://Stackoverflow.com/questions/45890001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2579896/" ]
Open the file in universal newline mode `rU` to support I/O on files which have a newline format that is not the native format on the platform in python 2.x, then the $ in your regex will match the EOL. ``` import re total_lines = 0 processed_lines = 0 regexp = re.compile(r'[*][\s]+[*]$') for line in open('testfi...
The test file you offered doesn't contain any lines that end with two asterisks? This regex should match all lines that end with two asterisks: .\*\\*{2}$
12,790
62,131,355
I am trying to create all subset of a given string **recursively**. Given string = 'aab', we generate all subsets for the characters being distinct. The answer is: `["", "b", "a", "ab", "ba", "a", "ab", "ba", "aa", "aa", "aab", "aab", "aba", "aba", "baa", "baa"]`. I have been looking at several solutions such as [this ...
2020/06/01
[ "https://Stackoverflow.com/questions/62131355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11469782/" ]
``` from itertools import * def recursive_product(s,r=None,i=0): if r is None: r = [] if i>len(s): return r for c in product(s, repeat=i): r.append("".join(c)) return recursive_product(s,r,i+1) print(recursive_product('ab')) print(recursive_product('abc')) ``` Output: `['', ...
This is the [powerset](https://stackoverflow.com/questions/1482308/how-to-get-all-subsets-of-a-set-powerset) of the set of characters in the string. ``` from itertools import chain, combinations s = set('ab') #split string into a set of characters # combinations gives the elements of the powerset of a given length ...
12,791
40,279,577
using python package "xlsxwriter", I want to highlight cells in the following conditional range; value > 1 or value <-1 However, some cells have -inf/inf values and it fill colors them too (to yellow). Is thare any way to unhighlight them? I tried "conditional\_format" function to uncolor them, but it doesn't work. ...
2016/10/27
[ "https://Stackoverflow.com/questions/40279577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7079128/" ]
required\_param means that the parameter must exist (or Moodle will throw an immediate, fatal error). If the parameter is optional, then use optional\_param('name of param', 'default value', PARAM\_TEXT) instead. Then you can check to see if this has the 'default value' (I usually use null as the default value). In e...
You should compare the result of `required_param('LType',PARAM_ALPHA)` with the value you spect, instead of using isset. For example: ``` if(required_param('LType',PARAM_ALPHA) != 'some value'){ echo "salaam";exit; } ``` Or: ``` if(required_param('LType',PARAM_ALPHA) === false){ echo "salaam";exit; } ```
12,793
54,360,408
i am writing a python application that is sending continously UDP messages to a predefined network with other hosts and fixed IPs. I wrote the python application and dockerized it. The application works fine in the docker, no problems there. Unfortunately i am failing to send the UDP messages from my docker to the hos...
2019/01/25
[ "https://Stackoverflow.com/questions/54360408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7864140/" ]
So i experimented a lot and i figured out, that i just need to run the docker container with the network configuration as host. The UDP socket in my container is bound to the IP adress of my host and therefore just needs to be linked to the Network of the host. Everyone who is struggeling the same issue, just run ``` ...
Build your own bridge --------------------- 1.Configure the new bridge. ``` $ sudo ip link set dev br0 up $ sudo ip addr add 192.168.5.1/24 dev bridge0 $ sudo ip link set dev bridge0 up ``` Confirm the new bridge’s settings. ``` $ ip addr show bridge0 4: bridge0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state ...
12,794
54,524,124
I put together a VAE using Dense Neural Networks in Keras. During `model.fit` I get a dimension mismatch, but not sure what is throwing the code off. Below is what my code looks like ``` from keras.layers import Lambda, Input, Dense from keras.models import Model from keras.datasets import mnist from keras.losses impo...
2019/02/04
[ "https://Stackoverflow.com/questions/54524124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1491639/" ]
According to [Keras: What if the size of data is not divisible by batch\_size?](https://stackoverflow.com/questions/37974340/keras-what-if-the-size-of-data-is-not-divisible-by-batch-size), one should better use `model.fit_generator` rather than `model.fit` here. To use `model.fit_generator`, one should define one's ow...
Just tried to replicate and found out that when you define `x = Input(batch_shape=(batch_size, original_dim))` you're setting the batch size and it's causing a mismatch when it starts to validate. Change to ``` x = Input(shape=input_shape) ``` and you should be all set.
12,795
30,005,876
When creating a derived class, what is actually being inherited from `pygame.sprite.Sprite`? It's something that doesn't need to be set up anywhere else in a class, so what is it? Are there actual methods included with it or does python/pygame just know what do with it?
2015/05/02
[ "https://Stackoverflow.com/questions/30005876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4515529/" ]
[Use the source, Luke!!!](https://www.youtube.com/watch?v=o2we_B6hDrY) @ [pygame.sprite.Sprite](https://bitbucket.org/pygame/pygame/src/dc57da440ac3415ff679c0e9a1d6d75d949b2db9/lib/sprite.py?at=default#cl-106) inherits `object` ![enter image description here](https://i.stack.imgur.com/pIAT7.jpg)
Look it up on the original pygame website: <http://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Sprite>
12,796
14,521,414
I'm currently working on a small python script, for controlling my home PC (really just a hobby project - nothing serious). Inside the script, there is two threads running at the same time using thread (might start using threading instead) like this: ``` thread.start_new_thread( Function, (Args) ) ``` Its works as ...
2013/01/25
[ "https://Stackoverflow.com/questions/14521414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1995290/" ]
Just kill the loader from the main program if it really bothers you. Here's one way to do it. ``` import os import win32com.client proc_name = 'MyProgram.exe' my_pid = os.getpid() wmi = win32com.client.GetObject('winmgmts:') all_procs = wmi.InstancesOf('Win32_Process') for proc in all_procs: if proc.Properties_(...
Python code does not need to be "compiled with pyinstaller" Products like "Pyinstaller" or "py2exe" are usefull to create a single executable file that you can distribute to third parties, or relocate inside your computer without worrying about the Python instalation - however, they don add "speed" nor is the resultin...
12,797
49,992,781
I have the following code in python2. I wanted to know if inheritance works or basic class works if we don't pass 'self' or don't have an init method in the class. here is the code ``` class Animal: def whoAmi(): print "Animal" >>> class Dog(Animal): pass ... >>> d= Dog() >>> d.whoAmi <boun...
2018/04/24
[ "https://Stackoverflow.com/questions/49992781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7406832/" ]
Lets first tackle why doesn't it print "Animal". The clue is is in the error message: > > TypeError: whoAmi() takes no arguments (**1 given**) > > > When you do `d.whoAmi()`, really what Python is doing is `Dog.whoAmi(d)`. Since your method does not take any arguments, you get that exception. By convention (as ...
Since you’re are effectively initiating Dog, you’re creating a `self`. So, when you write `d.whoAmi()`, the interpreter inserts `self` as a function argument. If you tried: ``` d = Dog d.whoAmi() ``` It should work as expected. By the way, you should put the decorator `@staticmethod` in he top of your `whoAmi` fun...
12,798
47,261,255
I'm trying to execute a dag which needs to be run only once. So I placed the dag execution interval as '@once'. However, I'm getting the error as mentioned in this link - <https://issues.apache.org/jira/browse/AIRFLOW-1400> Now i'm trying to pass the exact date of execution as below: ``` default_args = { 'owner': 'a...
2017/11/13
[ "https://Stackoverflow.com/questions/47261255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7229291/" ]
Grouping by either "TransactionCategory" or "TranCatID" will give you the desired result shown as follows: ``` SELECT TransactionCategory.TransCatName, SUM( `Value`) AS Value FROM Transactions JOIN TransactionCategory on Transactions.TransactionCategory = TransactionCategory.TranCatID GROUP BY TransactionCategory.Tra...
This should do the trick ``` SELECT TransactionCategory.TransCatName, SUM(Transactions.Value) as Value FROM Transactions LEFT JOIN TransactionCategory ON TransactionCategory.TranCatID = Transaction.TransactionCategory ```
12,799
54,376,661
**To who voted to close because of unclear what I'm asking, here are the questions in my post:** 1. Can anyone tell me what's the result of `y`? 2. Is there anything called sum product in Mathematics? 3. Is `x` subject to broadcasting? 4. Why is `y` a column/row vector? 5. What if `x=np.array([[7],[2],[3]])`? ``` w=n...
2019/01/26
[ "https://Stackoverflow.com/questions/54376661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/746461/" ]
Since you mentioned you can use **lodash** you can use [`merge`](https://lodash.com/docs/4.17.11#merge) like so: `_.merge(obj1, obj2)` to get your desired result. See working example below: ```js const a = { 1: { foo: 1 }, 2: { bar: 2, fooBar: 3 }, 3: { fooBar: 3 }, }, b = { 1: { foo: 1, bar: 2 }, ...
you can use Object.assign and and assign object properties to empty object. ``` var a = {books: 2}; var b = {notebooks: 1}; var c = Object.assign( {}, a, b ); console.log(c); ``` or You could use merge method from Lodash library. can check here : <https://www.npmjs.com/package/lodash>
12,801
37,297,472
I use Linux Mint 17 'Quiana' and I want to install Watchman to use later Ember.js. Here were my steps: ``` $ git clone https://github.com/facebook/watchman.git ``` then ``` $ cd watchman $ ./autogen.sh $ ./configure.sh ``` and, when I ran `make` to compile files, it returned the following error: ``` pywatchman/b...
2016/05/18
[ "https://Stackoverflow.com/questions/37297472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5846366/" ]
Usually its the `python-dev` libs missing. Are you sure the configure uses the python 3 instead of python 2? Because if thats the case you should install `python-dev` instead of `python3-dev`.
Same problem if you build watchman under rasbian/raspberry. Install "python-dev". -- ``` git clone https://github.com/facebook/watchman.git cd watchman ./autogen.sh ./configure make sudo make install ```
12,811
51,811,662
in a python program I have a list that I would like to modify: ``` a = [1,2,3,4,5,1,2,3,1,4,5] ``` Say every time I see 1 in the list, I would like to replace it with 10, 9, 8. My goal is to get: ``` a = [10,9,8,2,3,4,5,10,9,8,2,3,10,9,8,4,5] ``` What's a good way to program this? Currently I have to do a 'replac...
2018/08/12
[ "https://Stackoverflow.com/questions/51811662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759486/" ]
You **cannot** modify your state object or any of the objects it contains directly; you must instead use `setState`. And when you're setting state based on existing state, you must use the callback version of it; [details](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous). So in your...
In React, you must never assign to `this.state` directly. Use `this.setState()` instead. The reason is that otherwise React would not know you had changed the state. The only exception to this rule where you assign directly to `this.state` is in your component's constructor.
12,816
19,882,594
I am trying to pull company information from the following website: <http://www.theglobeandmail.com/globe-investor/markets/stocks/summary/?q=T-T> I see from there page source that there are nested span statements like: ``` <li class="clearfix"> <span class="label">Low</span> <span class="giw-a-t-sc-data">36.39</span...
2013/11/09
[ "https://Stackoverflow.com/questions/19882594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2974790/" ]
I have faced this problem. The solution is very simple (after a lot of testing and error) You must add id attribute to your tag, for instance: ``` <p:calendar id="date_selector" value="#{dpnl.fechaHasta}" pattern="dd/MM/yyyy" /> ```
At the facet named output use the tag h:outputText instead of p:inputText
12,817
53,474,065
I am trying to `upgrade` `matplotlib`. I'm doing this via `!pip` and it seems to work. When I check the list in the `IPython console`: ``` !pip list ``` It returns the latest version of `matplotlib` ``` matplotlib 3.0.2 ``` But when I check the version in the editor it returns ``` 2.2.2 ``` The very first lin...
2018/11/26
[ "https://Stackoverflow.com/questions/53474065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using `str.len` ``` df[df.iloc[:,0].astype(str).str.len()!=7] A 1 1.222222 2 1.222200 ``` dput : ``` df=pd.DataFrame({'A':[1.22222,1.222222,1.2222]}) ```
See if this works `df1 = df['ZipCode'].astype(str).map(len)==5`
12,819
62,823,948
I have a dataframe with two levels of columns index. Reproducible Dataset. --------------------- ``` df = pd.DataFrame( [ ['Gaz','Gaz','Gaz','Gaz'], ['X','X','X','X'], ['Y','Y','Y','Y'], ['Z','Z','Z','Z']], columns=pd.MultiIndex.from_arrays([['A','A','C','D'], ['Name','Name','...
2020/07/09
[ "https://Stackoverflow.com/questions/62823948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13875213/" ]
If I understand well you look for a mechanism, that allows you to display a terminal on a web server. Then you want to run an interactive python script on that terminal, right. So in the end the solution to share a terminal does not necessarily have to be written in python, right? (Though I must admit that I prefer p...
*>> Insert security disclaimer here <<* Easiest most hacktastic way to do it is to create a `div` element where you'll store your output and an `input` element to enter commands. Then you can ajax `POST` the command to a back-end controller. The controller would take the command and run it while capturing the output ...
12,822
64,267,498
I try to upload a big file (4GB) with a PUT on a DRF viewset. During the upload my memory is stable. At 100%, the python runserver process takes more and more RAM and is killed by the kernel. I have a logging line in the `put` method of this `APIView` but the process is killed before this method call. I use this sett...
2020/10/08
[ "https://Stackoverflow.com/questions/64267498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5877122/" ]
TL;DR: ------ Neither a DRF nor a Django issue, it's a [2.5 years known Daphne issue](https://github.com/django/daphne/issues/126). The solution is to use uvicorn, hypercorn, or something else for the time being. Explanations ------------ What you're seeing here is not coming from Django Rest Framework as: * The Fi...
I don't know if it works with django rest, but you can try to chunk de file. ``` [...] anexo_files = request.FILES.getlist('anexo_file_'+str(k)) index = 0 for file in anexo_files: index = index + 1 extension = os.path.splitext(str(file))[1] nome_arqui...
12,823
57,420,008
Recently I came across logging in python. I have the following code in test.py file ``` import logging logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) logger.addHandler(logging.StreamHandler()) logger.debug("test Message") ``` Now, is there any way I can print the resulting `Logrecord` object g...
2019/08/08
[ "https://Stackoverflow.com/questions/57420008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2897115/" ]
There is no return in `debug()` ``` # Here is the snippet for the source code def debug(self, msg, *args, **kwargs): if self.isEnabledFor(DEBUG): self._log(DEBUG, msg, args, **kwargs) ``` If you wanna get LogRecord return, you need to redefine a `debug()`, you can overwrite like this: ``` im...
You can create a handler that instead of formatting the LogRecord instance to a string, just save it in a list to be viewed and inspected later: ``` import logging import sys # A new handler to store "raw" LogRecords instances class RecordsListHandler(logging.Handler): """ A handler class which stores LogReco...
12,824
69,497,348
I'm new to python I got a question that might be easy but i can't get it. i wanted to make aprogram that user gives email as username and password as password ,the program should check if email is in corect format and if its not it **should print something and get email again** so i used regex (Im giving this inputs to...
2021/10/08
[ "https://Stackoverflow.com/questions/69497348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16260312/" ]
here is a working code for you: ```py import re regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' def check(email): if (re.fullmatch(regex, email)): return True else: print("invalid input! correct format is like amireza@gmail.com") return False while __name__ == '__main_...
You could change your function `check` to return a boolean output that tells you whether the check was successful, as in ``` def check(email): if (re.fullmatch(regex, email)): return True else: print("corect format is like amireza@gmail.com") return False ``` And then add a loop to ...
12,825
58,752,089
I was writing on VisualCode studio, but I keep getting the same error message. > > selenium.common.exceptions.WebDriverException: Message: 'chromedriver.exe' executable needs to be in PATH. > > > Is it simply because you just can't run webdriver on vscode studio? I've already tried ``` from selenium import web...
2019/11/07
[ "https://Stackoverflow.com/questions/58752089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8836876/" ]
I had te same problem and there is two ways to solve this issue. The main reason of this "*unreachable*" path is that visual studio code desn't have permissions to run from the path environment unlike any other system installed programs. So by installing VS Code but the **System Installer** version would be enough. An...
If you're on Windows, go into CMD (Command Prompt) and type in "chromedriver.exe." If chromedriver is executable in PATH, the system will print out "Starting Chromedriver [version]..." Else, you need to chromedriver to path. Then again, it could just be a fault of the IDE, try using Python's built-in IDLE...
12,826
3,778,486
I have visited Vim website , script section and found several synthax checkers for python. But which one to choose ? I would prefer something that supports python 3 as well, even though I code in python 2.6 currently. Do all these checkers need a module like pychecker and pyflakes ? I could install the most popular...
2010/09/23
[ "https://Stackoverflow.com/questions/3778486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/453642/" ]
These two websites really boosted my Vim productivity with all languages: <http://nvie.com/posts/how-i-boosted-my-vim/> <http://stevelosh.com/blog/2010/09/coming-home-to-vim/>
Whether or not wavy red lines are displayed is related to the theme you're using, not the syntax checker or language. So long as your syntax file (try <http://www.vim.org/scripts/script.php?script_id=790> ) checks for errors, you can show the errors with something like: ``` :hi Error guifg=#ff0000 gui=underc...
12,827
35,224,675
I'm preparing a toy `spark.ml` example. `Spark version 1.6.0`, running on top of `Oracle JDK version 1.8.0_65`, pyspark, ipython notebook. First, it hardly has anything to do with [Spark, ML, StringIndexer: handling unseen labels](https://stackoverflow.com/questions/34681534/spark-ml-stringindexer-handling-unseen-labe...
2016/02/05
[ "https://Stackoverflow.com/questions/35224675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3868574/" ]
Okay I think I got this. At least I got this working. Caching the dataframe(including train/test partes) solves the problem. That's what I found in this JIRA issue: <https://issues.apache.org/jira/browse/SPARK-12590>. So it's not a bug, just the fact that `randomSample` might yield a different result on the same, bu...
`Unseen label` [is a generic message which doesn't correspond to a specific column](https://github.com/apache/spark/blob/branch-1.6/mllib/src/main/scala/org/apache/spark/ml/feature/StringIndexer.scala#L157). Most likely problem is with a following stage: ``` StringIndexer(inputCol='lang', outputCol='lang_idx') ``` w...
12,836
38,385,983
As a beginner creating a simple python text editor I have encountered a confusing bug in which I am able to print out the text file with the read\_file() function when I first open it, but after I amend the text file using write\_file(), reading the file again simple returns whitespace. Additionally, any critique of ...
2016/07/15
[ "https://Stackoverflow.com/questions/38385983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335429/" ]
First, **file** is a predefined package; please don't use it for a variable name, or you may have trouble getting to some of the facilities. Try **my\_file** or just the C-language **fp** (for "file pointer"). After you write new information to the file, your position pointer (bookmark) is likely at the end of the fil...
When it comes to reading and writing files in python, if you do not call the method `(filename).close()` after making a change to a file, it will not save anything to it because it thinks you're still a) writing to it or b) still reading it! Hope this helps!
12,837
2,301,163
I am looking for a way to create html files dynamically in python. I am writing a gallery script, which iterates over directories, collecting file meta data. I intended to then use this data to automatically create a picture gallery, based on html. Something very simple, just a table of pictures. I really don't think...
2010/02/20
[ "https://Stackoverflow.com/questions/2301163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106534/" ]
I think, if i understand you correctly, you can see [here, "Templating in Python"](http://wiki.python.org/moin/Templating).
Use a templating engine such as [Genshi](http://genshi.edgewall.org/) or [Jinja2](https://jinja.palletsprojects.com/en/2.11.x/).
12,838
37,536,868
Not a maths major or a cs major, I just fool around with python (usually making scripts for simulations/theorycrafting on video games) and I discovered just how bad random.randint is performance wise. It's got me wondering why random.randint or random.randrange are used/made the way they are. I made a function that pro...
2016/05/31
[ "https://Stackoverflow.com/questions/37536868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5511209/" ]
`random.randint()` and others are calling into `random.getrandbits()` which may be less efficient that direct calls to `random()`, but for good reason. It is actually more correct to use a `randint` that calls into `random.getrandbits()`, as it can be done in an unbiased manner. You can see that using random.random ...
This is probably rarely a problem but `randint(0,10**1000)` works while `fastrandint(0,10**1000)` crashes. The slower time is probably the price you need to pay to have a function that works for all possible cases...
12,847
38,101,112
I'm trying to create an iOS Titanium Module using a pre-compiled CommonJS module. As the README file says: > > All JavaScript files in the assets directory are IGNORED except if you create a > file named "com.moduletest.js" in this directory in which case it will be > wrapped by native code, compiled, and used as y...
2016/06/29
[ "https://Stackoverflow.com/questions/38101112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1272263/" ]
There are 2 solutions. 1) Don't put it in assets, but in the `/app/lib` folder as others have mentioned. 2) wrap it as an actual commonjs module, like the [module I wrote](http://github.com/Topener/To.ImageCache) In both cases, you can just use `require('modulename')`. In case 2 you will need to add it to the `tiapp...
I use a slightly different pattern that works excellent: First a small snippet from my "module": ``` Stopwatch = function(listener) { this.totalElapsed = 0; // * elapsed number of ms in total this.listener = (listener != undefined ? listener : null); // * function to receive onTick events }; Stopwatch.protot...
12,849
71,821,635
I have installed two frameworks of Python 3.10. There is `wxPython310` for 64-bit Python. But there aren't any `wxPython` for 32-bit Python. I tried to install `wxPython` with `https://wxpython.org/Phoenix/snapshot-builds/wxPython-4.1.2a1.dev5259+d3bdb143.tar.gz`, but it shows me the error code like this. ``` Runni...
2022/04/11
[ "https://Stackoverflow.com/questions/71821635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15512931/" ]
There are some issues with Python 3.10. The easiest way to deal with this situation is to downgrade your python version to 3.9.13. The last wxPython came before Python 3.10 if I am not mistaken. I was going through the same situation and tried a couple of solutions because I did not want to downgrade my python versio...
Common problem with installing various versions is python interpreters that used for the installation Make sure you use compatible version of python to install wxPython310 What IDE you use ? for all case scenarios I would recommend to make sure that the installation done with the right Python version , if you don't k...
12,850
13,827,543
I like to know what was the local variable names when they are passed to a function. I'm not sure whether this is possible at all. Let's consider this example: function definition: ``` def show(x): print(x) ``` usage: ``` a = 10 show(a) ``` this prints 10. But I like to print "a = 10". Is this possible in pyth...
2012/12/11
[ "https://Stackoverflow.com/questions/13827543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/624074/" ]
I like the [answer to this question](http://docs.python.org/2/faq/programming.html#how-can-my-code-discover-the-name-of-an-object) that's found in the Python programming FAQ, quoting Fredrik Lundh: > > The same way as you get the name of that cat you found on your porch: > the cat (object) itself cannot tell you it...
Here's an answer that only became possible as of Python 3.6 with f-strings: ``` x = 10 print(f'{x=}') # Outputs x=10 ```
12,851
60,877,741
I'm trying to write a script with python/numpy/scipy for data manipulation, fitting and plotting of angle dependent magnetoresistance measurements. I'm new to Python, got the frame code from my PhD advisor, and managed to add few hundred lines of code to the frame. After a while I noticed that some measurements had mul...
2020/03/26
[ "https://Stackoverflow.com/questions/60877741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13131921/" ]
If you only want to consider the valid entries, you can use the inverse of the mask as an index: ``` x = ma.masked_array([1,2,3,4,5,6,7,8,9,10], mask=[0,0,0,0,0,1,1,1,1,1]) # changed mask y = ma.masked_array([1,2,3,4,5,30,35,40,45,50], mask=[0,0,0,0,0,1,1,1,1,1]) fitParamsFunk, fitCovariancesFunk = curve_fit(Funk, x...
The use of mask in numerical calculus is equivalent to the use of the Heaviside step function in analytical calculus. For example this becomes very simple by application for piecewise linear regression: [![enter image description here](https://i.stack.imgur.com/Zg2Z3.gif)](https://i.stack.imgur.com/Zg2Z3.gif) They a...
12,861
46,497,838
We have a Python client that connects to the Amazon S3 via a VPC endpoint. Our code uses boto and we are able to connect and download from S3. After migration from boto to boto3, we noticed that the VPC endpoint connection no longer works. Below is a copy snippet that can reproduce the problem. ```sh python -c "impor...
2017/09/29
[ "https://Stackoverflow.com/questions/46497838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456481/" ]
This is most likely a configuration error in your VPC endpoint policies. If your policies are correct, then Boto3 never knows exactly how it's able to reach the S3 location, it really is up to the policies to allow/forbid this type of traffic. Here's a quick walkthrough of what you can do for troubleshooting: <https:/...
It depends on your AWS policies and roles defined. Shortest way to make your code run is to make the S3 bucket Public [ not recommended] else add your IP in the security policies and then re-run the code. Details of it can be found here. <https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/authorizing-access-to-an-ins...
12,863
50,648,152
I want to install a rpm package, (e.g. python 3), and all of its dependencies in a linux server that does not have internet connection. How can I do that?
2018/06/01
[ "https://Stackoverflow.com/questions/50648152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128078/" ]
Assuming you already downloaded the package before from another machine that has internet access and FTP the files to your server, you can use the following command to install a rpm ``` rpm -ivh package_name_x85_64.rpm ``` options: * i = This installs a new package. * v = Print verbose information * h = Print 50 ha...
There is a way, but it is quite tricky and might mess up your servers, so be **very careful**. Nomenclature: * **online** : your system that is connected to the repositories * **offline**: your system that is not connected Steps: Compress your rpm database from the **offline** system and transfer it to the **online...
12,864
71,300,876
Using python elasticsearch-dsl: ``` class Record(Document): tags = Keyword() tags_suggest = Completion(preserve_position_increments=False) def clean(self): self.tags_suggest = { "input": self.tags } class Index: name = 'my-index' settings = { "n...
2022/02/28
[ "https://Stackoverflow.com/questions/71300876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9016861/" ]
With `bash` version >= 3.0 and a regex: ``` [[ "$string" =~ _(.+)\. ]] && echo "${BASH_REMATCH[1]}" ```
This is easy, except that it includes the initial underscore: ``` ls | grep -o "_[^.]*" ```
12,867
49,889,323
I have a script named `patchWidth.py` and it parses command line arguments with `argparse`: ``` # read command line arguments -- the code is able to process multiple files parser = argparse.ArgumentParser(description='angle simulation trajectories') parser.add_argument('filenames', metavar='filename', type=str, nargs=...
2018/04/18
[ "https://Stackoverflow.com/questions/49889323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2112406/" ]
Yes, you can use the sys module: ``` import sys str(sys.argv) # arguments as string ``` Note that `argv[0]` is the script name. For more information, take a look at the [sys module documentation](https://docs.python.org/3/library/sys.html#sys.argv).
I do not know if it would be the best option, but... ``` import sys " ".join(sys.argv) ``` Will return a string like `/the/path/of/file/my_file.py arg1 arg2 arg3`
12,877
70,899,538
Right now I have an Arraylist in java. When I call ``` myarraylist.get(0) myarraylist.get(1) myarraylist.get(2) [0, 5, 10, 16] [24, 29, 30, 35, 41, 45, 50] [0, 6, 41, 45, 58] ``` are all different lists. What I need to do is get the first and second element of each of these lists, and put it in a list, like so: ``...
2022/01/28
[ "https://Stackoverflow.com/questions/70899538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17215849/" ]
`List<Integer> sublist = myarraylist.subList(0, 2);` For `List#subList(int fromIndex, int toIndex)` the `toIndex` is exclusive. Therefore, to get the first two elements (indexes 0 and 1), the `toIndex` value has to be 2.
Try reading about Java 8 Stream API, specifically: * [map method](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function-) * [collect method](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#collect-java.util.stream.Collector-) This should help you...
12,880
24,090,225
Best way to remove all characters of a string until new line character is met python? ``` str = 'fakeline\nfirstline\nsecondline\nthirdline' into str = 'firstline\nsecondline\nthirdline' ```
2014/06/06
[ "https://Stackoverflow.com/questions/24090225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3388884/" ]
Get the index of the newline and use it to [slice](https://stackoverflow.com/questions/509211/pythons-slice-notation) the string: ``` >>> s = 'fakeline\nfirstline\nsecondline\nthirdline' >>> s[s.index('\n')+1:] # add 1 to get the character after the newline 'firstline\nsecondline\nthirdline' ``` Also, don't name you...
str.split("\n") gives a list of all the newline delimited segments. You can simply append the ones you want with + afterwards. For your case, you can use a slice ``` newstr = "".join(str.split("\n")[1::]) ```
12,882
42,136,707
Hello I'm trying to make an live info screen to a school project, I'm reading through a file which does a lot of different thing which depending of what line it's reading. ``` dclist = [] interface = "" vrfmem = "" db = sqlite3.connect('data/main.db') cursor = db.cursor() cursor.execute('''SELECT r1 FROM routers''') ...
2017/02/09
[ "https://Stackoverflow.com/questions/42136707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4448852/" ]
You install `gulp` globally for using simple `gulp` command in your terminal and install `gulp` locally (with `package.json` dependency) in order not to lose the dependency, because you can install your project to any computer, call `npm i` and access `gulp` with `./node_modules/.bin/gulp` without any additional instal...
You don't even need to have installed `gulp` globaly. Just have it locally and put gulp commands in package.json scripts like this: ``` "scripts": { "start": "gulp", "speed-test": "gulp speed-test -v", "build-prod": "gulp build-prod", "test": "NODE_ENV=test jasmine JASMINE_CONFIG_PATH=spec/support/ja...
12,884
60,445,740
I have an excel file which generates chart based on the data available, the chart name is `thisChart`. I want to copy `thisChart` from excel file to the ppt file. Now I know the 2 ways to do that ie VBA and python(using win32com.client). The problem with VBA is that its really time consuming and it randomly crashes th...
2020/02/28
[ "https://Stackoverflow.com/questions/60445740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6372189/" ]
You can use `CASE` clause to differential which Unit need to be displayed. For example: ``` SELECT (CASE WHEN price_col >= 1000000 THEN CONCAT(price_col/100000,'B') WHEN price_col >= 100000 THEN CONCAT(price_col/100000,'M') WHEN price_col >= 1000 THEN CONCAT(price_col/1000,'K') ELSE price_col END) as new_price_col FR...
SELECT (CASE WHEN length(price)=9 THEN CONCAT(price/100000,'M') ELSE (CASE WHEN lenght(price)=10 THEN CONCAT(price/1000000,'B' END) END) AS price
12,885
49,059,461
I have the following Python dict: ``` { 'parameter_010': False, 'parameter_009': False, 'parameter_008': False, 'parameter_005': 'C<sub>MAX</sub>', 'parameter_004': 'L', 'parameter_007': False, 'parameter_006': 'R', 'parameter_001': 'Foo', 'id': 7542, 'parameter_003': 'D', 'parameter_00...
2018/03/01
[ "https://Stackoverflow.com/questions/49059461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5328289/" ]
So, assuming you know that you are working with a JSON and how to deserialize: ``` >>> import json >>> s = """{ ... "parameter_010": false, ... "parameter_009": false, ... "parameter_008": false, ... "parameter_005": "CMAX", ... "parameter_004": "L", ... "parameter_007": false, ... "parameter_006": "R", ...
Here is one solution: ``` list(zip(*sorted(i for i in d.items() if i[0].startswith('parameter') and i[1])))[1] # ('Foo', 'M', 'D', 'L', 'C<sub>MAX</sub>', 'R') ``` **Explanation** * We filter for 2 conditions: key starts with 'parameter' and value is Truthy. * `sorted` on `d.items()` returns a list of tuples sorte...
12,886
13,637,150
I am trying to call an .exe file that's not in my local Python directory using `subprocess.call()`. The command (as I type it into cmd.exe) is exactly as follows: `"C:\Program Files\R\R-2.15.2\bin\Rscript.exe" --vanilla C:\python\buyback_parse_guide.r` The script runs, does what I need to do, and I have confirmed the ...
2012/11/30
[ "https://Stackoverflow.com/questions/13637150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489426/" ]
To quote [the docs](http://docs.python.org/2/library/subprocess.html#popen-constructor): > > If shell is True, it is recommended to pass args as a string rather than as a sequence. > > > Splitting it up (either manually, or via `shlex`) just so `subprocess` can recombine them so the shell can split them again is ...
According to [the docs](http://stat.ethz.ch/R-manual/R-patched/library/utils/html/Rscript.html), Rscript: > > … is an alternative front end for use in #! scripts and other scripting applications. > > > … is convenient for writing #! scripts… (The standard Windows command line has no concept of #! scripts, but Cygwi...
12,888
63,106,413
I'm trying to find a python solution to extract the length of a specific sequence within a fasta file using the full header of the sequence as the query. The full header is stored as a variable earlier in the pipeline (i.e. "CONTIG"). I would like to save the output of this script as a variable to then use later on in ...
2020/07/26
[ "https://Stackoverflow.com/questions/63106413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7614836/" ]
You can do it this way: ``` import Bio.SeqIO as IO record_dict = IO.to_dict(IO.parse("genome.fa", "fasta")) print(len(record_dict["chr1"])) ``` or ``` import Bio.SeqIO as IO record_dict = IO.to_dict(IO.parse("genome.fa", "fasta")) seq = record_dict["chr1"] print(len(seq)) ``` EDIT: Alternative code ``` import Bi...
This works, just changed the "CONTIG" variable to a string. Thanks Lucía for all your help the last couple of days! ``` import Bio.SeqIO as IO record_dict = IO.to_dict(IO.parse(ORIGINAL_GENOME, "fasta")) #not the subsample with open(GENOME_SUBSAMPLE, 'r') as FIN: for LINE in FIN: if LINE.startswith('>'):...
12,889
35,846,943
I was creating a function to compute trimmed mean. To do this I removed highest and lowest percent of data and then the mean is computed as usual. What I have so far is : ``` def trimmed_mean(data, percent): from numpy import percentile if percent < 50: data_trimmed = [i for i in data ...
2016/03/07
[ "https://Stackoverflow.com/questions/35846943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4408820/" ]
You can take a look at this related question:[Trimmed Mean with Percentage Limit in Python?](https://stackoverflow.com/questions/19441730/trimmed-mean-with-percentage-limit-in-python) In short for scipy version > 0.14.0 the following does the job ``` from scipy import stats m = stats.trim_mean(X, percentage) ``` If...
I would suggest sorting the array first and then just take a "slice in the the middle." ``` #some "fancy" numpy sort or even just plain old sorted() #sorted_data = sorted(data) #uncomment to use plain python sorted n = len(sorted_data) outliers = n*percent/100 #may want some rounding logic if n is small trimmed_data ...
12,890
73,603,035
We know we can use `sep.join()` or `+=` to concatenate strings. For example, ``` a = ["123f", "asd", "y] print("".join(a)) # output: 1234asdy ``` In Java, stringbuilder would creat a new string, and put the two string on the both sides of plus together, so it will cost `O(n^2)`. But in Python, how will `join` method...
2022/09/04
[ "https://Stackoverflow.com/questions/73603035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16395591/" ]
for cpython version 3.X you can see the source code [here](https://github.com/python/cpython/blob/main/Objects/stringlib/join.h) and it does indeed calculate the total length beforehand and only does 1 allocation. On a side note, if your application is limited by the speed of joining strings such that you have to thin...
The operation is O(n). `join` takes an iterable. If its not already a sequence, `join` will create one. Then, using the size of the the separator and the size of each string in the list, a new string object is created. A series of `memcpy` then creates the object. Creating the list, getting the sizes and doing the `mem...
12,893
20,169,509
Can I import a word document into a python program so that its content can be read and questions can be answered using the data in the document. what would be procedure of using the data in the file ``` with open('animal data.txt', 'r') ``` i used this but is not working
2013/11/24
[ "https://Stackoverflow.com/questions/20169509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2994135/" ]
XE16 supports OpenGL in live cards. Use the class GlRenderer: <https://developers.google.com/glass/develop/gdk/reference/com/google/android/glass/timeline/GlRenderer>
I would look at your app and determine if you want to have more user input or not and whether you want it to live in a specific part of your Timeline or just have it be launched when the user wants it. Specifically, since Live Cards live in the Timeline, they will not be able to capture the swipe backward or swipe for...
12,894
10,443,295
So I have a set of data which I am able to convert to form separate numpy arrays of R, G, B bands. Now I need to combine them to form an RGB image. I tried 'Image' to do the job but it requires 'mode' to be attributed. I tried to do a trick. I would use Image.fromarray() to take the array to image but it attains 'F...
2012/05/04
[ "https://Stackoverflow.com/questions/10443295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1372149/" ]
Your distortion i believe is caused by the way you are splitting your original image into its individual bands and then resizing it again before putting it into merge; ``` ` image=Image.open("your image") print(image.size) #size is inverted i.e columns first rows second eg: 500,250 #convert to array li_r=list(image...
If using PIL Image convert it to array and then proceed with the below, else using matplotlib or cv2 perform directly. ``` image = cv2.imread('')[:,:,::-1] image_2 = image[10:150,10:100] print(image_2.shape) img_r = image_2[:,:,0] img_g = image_2[:,:,1] img_b = image_2[:,:,2] image_2 = img_r*0.2989 + 0.587*img_g + 0...
12,895
58,642,357
I am trying to automate the login to the following page using selenium: <https://services.cal-online.co.il/Card-Holders/SCREENS/AccountManagement/Login.aspx?ReturnUrl=%2fcard-holders%2fScreens%2fAccountManagement%2fHomePage.aspx> Trying to find the elements of username and password using both id, css selector and xpat...
2019/10/31
[ "https://Stackoverflow.com/questions/58642357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9608607/" ]
To automate the login to the [page](https://services.cal-online.co.il/Card-Holders/SCREENS/AccountManagement/Login.aspx?ReturnUrl=%2fcard-holders%2fScreens%2fAccountManagement%2fHomePage.aspx) using [Selenium](https://stackoverflow.com/questions/54459701/what-is-selenium-and-what-is-webdriver/54482491#54482491) as the ...
found a solution to the problem. the problem really was that the object is inside an iframe. I tried to use the solution suggested in [Get element from within an iFrame](https://stackoverflow.com/questions/1088544/get-element-from-within-an-iframe) but got a security error. the solution is to switch frame the follwoin...
12,905
29,574,698
I'm looking to split a given string into a list with elements of equal length, I have found a code segment that works in versions earlier than python 3 which is the only version I am familiar with. ``` string = "abcdefghijklmnopqrstuvwx" string = string.Split(0 - 3) print(string) >>> ["abcd", "efgh", "ijkl", "mnop",...
2015/04/11
[ "https://Stackoverflow.com/questions/29574698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4776196/" ]
You could try the `.clip()` function. You can use `.save()` to save the state to `.restore()` after the clip so it isn't destructive. You can set the path to whatever you would like and it will create a vector mask of that shape. ``` var canvas = document.getElementById('myCanvas'); var context = canvas.getContext('2d...
Try something like this ``` context.fillStyle = "rgba(255, 255, 255, 1)"; context.fillRect(0, 100, 400, 400); context.fillStyle = "rgba(255, 255, 255, 1)"; context.fillRect(100, 0, 400, 400); ``` <http://jsfiddle.net/xqzxawyb/1/>
12,906
68,402,859
I am using python API to save and download model from MinIO. This is a MinIO installed on my server. The data is in binary format. ``` a = 'Hello world!' a = pickle.dumps(a) client.put_object( bucket_name='my_bucket', object_name='my_object', data=io.BytesIO(a), ...
2021/07/16
[ "https://Stackoverflow.com/questions/68402859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8797308/" ]
Try with response.data.decode()
The response is a `urllib3.response.HTTPResponse` object. See [urllib3 Documentation](https://urllib3.readthedocs.io/en/latest/reference/urllib3.response.html): > > Backwards-compatible with http.client.HTTPResponse but the response body is loaded and decoded on-demand when the data property is accessed. > > > ...
12,911
45,406,332
I am very new to SQLAlchemy. I am having some difficulty setting up a one to many relationship between two models in my application. I have two models User `Photo'. A user has only one role associated with it and a role has many users associated with it. This is the code that I have in my data\_generator.py file: ```...
2017/07/31
[ "https://Stackoverflow.com/questions/45406332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7954998/" ]
There might be three relationships between User and Role: * One to One(One user has only one Role) * Many to One(One user has many roles) * Many to Many(Many user has many roles) For One to One: ``` class Role(Base): id = Column(Integer, primary_key=True) # ... user_id = Column(Integer, ForeignKey("us...
I made a low-level mistake because of my lack of database and SQL alchemy. First of all, this is a typical "one to many" problem.Relationship connects two rows from two tables by users' foreign key. The role\_id is defined as the foreign key, which builds the connections. The parameter "roles.id" in "ForeignKey()" clar...
12,912
10,213,509
I have a **Django** site, hosted on **Heroku**. One of the models has an image field, that takes uploaded images, resizes them, and pushes them to Amazon S3 so that they can be stored persistently. This is working well, using **PIL** ``` def save(self, *args, **kwargs): # Save this one super(Product, self)...
2012/04/18
[ "https://Stackoverflow.com/questions/10213509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267757/" ]
I use this PIL fork in requirements.txt: ``` -e hg+https://bitbucket.org/etienned/pil-2009-raclette/#egg=PIL ``` and can use JPEG without issues: ``` -------------------------------------------------------------------- PIL 1.2a0 SETUP SUMMARY ----------------------------------------------------...
Also please consider using [Pillow](https://pypi.python.org/pypi/Pillow), the "friendly" PIL fork which offers: * Setuptools compatibility * Python 3 compatibility * Frequent release cycle * Many bug fixes
12,913
25,433,921
I need to run this file: ``` from apps.base.models import Event from apps.base.models import ProfileActiveUntil from django.template import Context from django.db.models import Q import datetime from django.core.mail import EmailMultiAlternatives from bonzer.settings import SITE_HOST import smtplib from email.mime.mul...
2014/08/21
[ "https://Stackoverflow.com/questions/25433921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3216697/" ]
`cron` does not read rc shell files so you need to define the enviroment variable PYTHONPATH to include the location of the `apps` package and all other module files that are required by the script. ``` PYTHONPATH=/usr/local/lib/python2.7:/usr/lib/python2.7 */2 * * * * /usr/local/bin/python2.7 /home/nezap/webapps/bonz...
I would assume this is a problem with your cwd (current working directory). An easy way to test this would be to go to the root (cd /) then run: ``` python2.7 /home/nezap/webapps/bonzer/bonzer/apps/base/alert.py ``` You should get the same error. The path you will want to use will depend on the place where you norma...
12,914
25,496,012
The answers to [this question](https://stackoverflow.com/questions/14043886/python-2-3-convert-integer-to-bytes-cleanly) make it seem like there are two ways to convert an integer to a `bytes` object in Python 3. They show `s = str(n).encode()` and ``` n = 5 bytes( [n] ) ``` Being the same. However, testing th...
2014/08/25
[ "https://Stackoverflow.com/questions/25496012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3291506/" ]
Those two examples are *not* equivalent. `str(n).encode()` takes whatever you give it, turns it into its string representation, and then encodes using a character codec like utf8. `bytes([..])` will form a bytestring with the byte values of the array given. The representation `\xFF` is in fact the hexadecimal represent...
`b'8'` is a `bytes` object which contains a single byte with value of the character `'8'` which is equal to `56`. `b'\x08'` is a `bytes` object which contains a single byte with value `8`, which is the same as `0x8`.
12,915
30,637,387
I'm running Notebook server on remote machine and want to somehow protect it. Unfortunately I cannot use password authentication (because if I do so then I can't use `ein`, an emacs package for ipython notebooks). The other obvious solution is to make IPython Notebook accept connections only from my local machine's ip...
2015/06/04
[ "https://Stackoverflow.com/questions/30637387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2500596/" ]
You can set the port for iPython to a port that will only be used by iPython. And then restrict access to that port to only you local machine's IP. To set the port: Edit the ipython\_notebook\_config.py file and insert or edit the line: ``` c.NotebookApp.port = 7777 ``` where you change 7777 to the port of your ch...
I dont found anything about other authentication way on ipython website, then you can have right. Here <http://ipython.org/ipython-doc/3/notebook/security.html> is something about ipython trust. Maybe it will be sufficient for you.
12,916
56,476,940
I have successfully installed z3 on a remote server where I am not root. when I try to run my python code I get : ``` ModuleNotFoundError: No module named 'z3' ``` I understand that I have to add it to PYTHONPATH in order to work and so I went ahead and done that like this: > > export PYTHONPATH=$HOME/usr/lib/pyth...
2019/06/06
[ "https://Stackoverflow.com/questions/56476940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10881142/" ]
Did you pass the `--python` flag when you called `scripts/mk_make.py`? See the instructions on <https://github.com/Z3Prover/z3/blob/master/README.md> on how to exactly enable Python (about all the way down in that page). Here's an example invocation: ``` python scripts/mk_make.py --prefix=/home/leo --python --pypkgdi...
For Windows users that just downloaded and unzipped the compiled Z3 binary into some arbitrary directory, adding the location of the python directory in the directory where Z3 was installed to PYTHONPATH did the trick. ie in Cygwin : `$ export PYTHONPATH=<location of z3>/bin/python:$PYTHONPATH` (or the equivalent in a ...
12,917
43,168,078
I am trying to extract how many songs are release in every year from csv. my data looks like this ``` no,artist,name,year "1","Bing Crosby","White Christmas","1942" "2","Bill Haley & his Comets","Rock Around the Clock","1955" "3","Sinead O'Connor","Nothing Compares 2 U","1990","35.554" "4","Celine Dion","My Heart Wil...
2017/04/02
[ "https://Stackoverflow.com/questions/43168078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7438144/" ]
2 very simple lines of code: ``` import pandas as pd my_csv=pd.read_csv(filename) ``` and to get the number of songs per year: ``` songs_per_year= my_csv.groupby('year')['name'].count() ```
You can use a `Counter` object from the [`collections`](https://docs.python.org/2/library/collections.html) module.. ``` >>> from collections import Counter >>> from csv import reader >>> >>> YEAR = 3 >>> with open('file.txt') as f: ... next(f, None) # discard header ... year2rel = Counter(int(line[YEAR]) for...
12,918
70,946,840
Is it possible to make a dot function that is var.function() that changes var? I realise that i can do: ``` class Myclass: def function(x): return 2 Myclass.function(1): ``` But i want to change it like the default python function. ``` def function(x): return(3) x=1 x.function() print(x) ``` and it re...
2022/02/01
[ "https://Stackoverflow.com/questions/70946840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18093990/" ]
You can use Pandas `.shift()` to compare the values of the series with the next row, build up a session value based on the "hops", and then group by that session value. ``` import pandas as pd df = pd.DataFrame({ 'name' : ['John', 'John', 'John', 'John', 'John', 'Emily', 'Emily', 'John'], 'app' : ['Excel...
One solution would be to add a column to define hops. Then group by that column ``` hop_id = 1 for i in df.index: df.loc[i,'hop_id'] = hop_id if (df.loc[i,'Name']!= df.loc[i+1,'Name']) or (df.loc[i,'Application'] != df.loc[i+1,'Application']): hop_id = hop_id +1 df.groupby('hop_id')['Duration'].sum() ...
12,919
67,415,482
I created a Sudoku class in python, I want to solve the board and also keep an instance variable with the original board, but when I use the `solve()` method which uses the recursive backtracking algorithm `self.board` changes together with `self.solved_board` why is that, and how can I keep a variable with the origina...
2021/05/06
[ "https://Stackoverflow.com/questions/67415482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7311644/" ]
`self.solved_board = board[:]` does indeed create a new list, but it references the same inner lists as `board`. You need to go one level deeper: ``` self.solved_board = [row[:] for row in board] ```
Yeah, `board[:]` does create a new list -- of all those old inner lists: ```py In [23]: board = [[1], [2]] In [24]: board2 = board[:] In [25]: board2[0] is board[0] Out[25]: True In [26]: board2[0][0] += 10 In [28]: board Out[28]: [[11], [2]] ``` You'd need to deepcopy it; e.g., ```py solved_board = [row[:] for...
12,920
308,254
I am running an Ubuntu 8.10, using Python 2.5 out of the box. This is fine from the system point of view, but I need Python2.4 since I dev on Zope / Plone. Well, installing python2.4 is no challenge, but I can't find a (clean) way to make iPython use it : no option in the man nor in the config file. Before, there was...
2008/11/21
[ "https://Stackoverflow.com/questions/308254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
Ok, I answer my own question : I'm dumb :-) ``` ls /usr/bin/ipython* /usr/bin/ipython /usr/bin/ipython2.4 /usr/bin/ipython2.5 ``` Now it's built-in...
To complement on @Peter's answer, I might add that the ipython "executable" you run are simply python script that launch the ipython shell. So a solution that worked for me was to change the python version that runs that script: ```bash $ cp ipython ipython3 $ nano ipython3 ``` Here is what the script looks like: `...
12,923
5,784,791
I installed MySQL on my Mac OS 10.6 about a week ago, and, after some playing around, got it to work just fine. It integrated with python MySQLdb and I also got Sequel Pro to connect to the database. However, php wouldn't access the server. Even after I added a php.ini file to /etc/ and directed it toward the same sock...
2011/04/26
[ "https://Stackoverflow.com/questions/5784791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/321838/" ]
I was also getting this error on a fresh install of XAMPP. For those not comfortable with the command line, there is another way. Based on the advice above (thank you), I used my old standard "Easy Find" to locate the latest version of my.cnf. Upon opening the file in an editor I discovered that the socket file was ...
If you have installed mysql through homebrew, simple `brew services restart mysql` may help.
12,933
61,261,306
I recently started exploring VS Code for developing Python code and I’m running into an issue when I try to import a module from a subfolder. The exact same code runs perfectly when I execute it in a Jupyter notebook (the subfolders contain the `__init__.py` files etc.) I believe I followed the instructions for setting...
2020/04/16
[ "https://Stackoverflow.com/questions/61261306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1952633/" ]
Stefan‘s method worked for me. Taking as example filesystem: workspaceFolder/folder/subfolder1/subfolder2/bar.py I wasn't able to import subfolders like: `from folder.subfolder1.subfolder2 import bar` It said: `ModuleNotFoundError: No module named 'folder'` I added to .vscode/settings.json the following: ``` "termi...
I think I finally figured out the answer myself: The integrated terminal does not scan the `PYTHONPATH` from the `.env`-file. When running the file in an integrated window, the `PYTHONPATH` is correctly taken from `.env`, however. So in order to run my script in the terminal I had to add the `terminal.integrated.env.*`...
12,943
61,279,933
In python, I run this simple code: ```py print('number is %.15f'%1.6) ``` which works fine (Output: `number is 1.600000000000000`), but when I take the decimal places to `16>=`, I start getting random numbers at the end. For example: ```py print('number is %.16f'%1.6) ``` Output: `number is 1.6000000000000001` an...
2020/04/17
[ "https://Stackoverflow.com/questions/61279933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13159127/" ]
Work-around 1. Open Hyper-V Manager under Windows Administrative Tools 2. Note DockerDesktopVM is not running under Virtual Machines 3. Under the Actions pane, click Stop Service, then click Start Service 4. Restart Docker Desktop Its worked for me
Make sure that the VT-X virtualization is enabled in your BIOS
12,944
19,616,205
I'm trying to run a macro via python but I'm not sure how to get it working... I've got the following code so far, but it's not working. ``` import win32com.client xl=win32com.client.Dispatch("Excel.Application") xl.Workbooks.Open(Filename="C:\test.xlsm",ReadOnly=1) xl.Application.Run("macrohere") xl.Workbooks(1).Clo...
2013/10/27
[ "https://Stackoverflow.com/questions/19616205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2487602/" ]
I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result: ```py #Import the following library to make use of the DispatchEx to run the macro import win32com.client as wincl def runMacro(): if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_app...
I suspect you haven't authorize your Excel installation to run macro from an automated Excel. It is a security protection by default at installation. To change this: 1. File > Options > Trust Center 2. Click on Trust Center Settings... button 3. Macro Settings > Check Enable all macros
12,947
73,111,056
I am fairly new at writing code and trying to teach myself python and pyspark based on searching the web for answers to my problems. I am trying to build a historical record set based on daily changes. I periodically have to bump the semantic version, but do not want to lose my already collected historical data. If the...
2022/07/25
[ "https://Stackoverflow.com/questions/73111056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19213719/" ]
You use the 'IncrementalTransformContext' of the transform to determine whether it is running incrementally. This can be seen in the code below. ``` @incremental() @transform( x=Output(), y=Input(), z=Input(), ) def compute(ctx, x, y, z): if ctx.is_incremental: ## Some Code else: #...
In an incremental transform, there is a boolean flag property called 'is\_incremental' in the [incremental transform context object](https://www.palantir.com/docs/foundry/transforms-python/incremental-reference/#incrementaltransformcontext). Therefore, I think you can do a single incremental transform definition and b...
12,957
4,827,244
I'm trying to get an implementation of github flavored markdown working in python, with no luck... I don't have much in the way of regex skills. Here's the ruby code from [github](https://github.com/github/github-flavored-markdown/blob/gh-pages/code.rb#L17): ``` # in very clear cases, let newlines become <br /> tags...
2011/01/28
[ "https://Stackoverflow.com/questions/4827244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73831/" ]
That Ruby version has **multiline modifier** in the regex, so you need to do the same in python: ``` def newline_callback(matchobj): return re.sub(re.compile(r'^(.+)$', re.M),r'\1 ',matchobj.group(0)) text = re.sub(re.compile(r'(\A|^$\n)(^\w[^\n]*\n)(^\w[^\n]*$)+', re.M), newline_callback, text) ``` So th...
``` return re.sub(r'^(.+)$',r'\1 ',matchobj.group(0)) ^^^--------------------------- you forgot this. ```
12,958
3,115,448
this html is [here](https://mail.google.com/mail/?ui=2&ik=a0b1e46c9c&view=att&th=1296be43b8e3bbd9&attid=0.1&disp=inline&zw) : ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><META http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body> <div bgcolor="#48486c"> ...
2010/06/25
[ "https://Stackoverflow.com/questions/3115448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234322/" ]
[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) gets you almost all the way there: ``` >>> import BeautifulSoup >>> f = open('a.html') >>> soup = BeautifulSoup.BeautifulSoup(f) >>> f.close() >>> g = open('a.xml', 'w') >>> print >> g, soup.prettify() >>> g.close() ``` This closes all tags properly. The...
lxml works well: ``` from lxml import html, etree doc = html.fromstring(open('a.html').read()) out = open('a.xhtml', 'wb') out.write(etree.tostring(doc)) ```
12,959
6,987,413
I started using the protocol buffer library, but noticed that it was using huge amounts of memory. pympler.asizeof shows that a single one of my objects is about 76k! Basically, it contains a few strings, some numbers, and some enums, and some optional lists of same. If I were writing the same thing as a C-struct, I wo...
2011/08/08
[ "https://Stackoverflow.com/questions/6987413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/189456/" ]
Object instances have a bigger memory footprint in python than in compiled languages. For example, the following code, which creates very simple classes mimicking your proto displays 1440: ``` class A: def __init__(self): self.a = 0.0 class B: def __init__(self): self.b = 0.0 class C: def __init__(self...
Edit: This isn't likely your actual issue here, but we've just been experiencing a 45MB protobuf message taking > 4GB ram when decoding. It appears to be this: <https://github.com/google/protobuf/issues/156> which was known about in protobuf 2.6 and a fix was only merged onto master march 7 this year: <https://github...
12,962
69,495,394
input file.csv ``` ['NE,PORT,EVENT,TIME,VALUE', 'NODE,13,MAX,2021-08-30 09:15:00+01:00 DST,-10.9', 'NODE,13,MIN,2021-08-30 09:15:00+01:00 DST,-11.0', 'NODE,13,CUR,2021-08-30 09:15:00+01:00 DST,-10.9', 'NODE,13,MAX,2021-08-30 10:30:00+01:00 DST,-12.9', 'NODE,13,MIN,2021-08-30 10:30:00+01:00 DST,-10.0', 'NODE,13,CU...
2021/10/08
[ "https://Stackoverflow.com/questions/69495394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17106118/" ]
One way to do this is by creating a pivot table. ``` csv = ['NE,PORT,EVENT,TIME,VALUE', 'NODE,13,MAX,2021-08-30 09:15:00+01:00 DST,-10.9', 'NODE,13,MIN,2021-08-30 09:15:00+01:00 DST,-11.0', 'NODE,13,CUR,2021-08-30 09:15:00+01:00 DST,-10.9', 'NODE,13,MAX,2021-08-30 10:30:00+01:00 DST,-12.9', 'NODE,13,MIN,2021-08-30...
i'll correct just your first step. your logic was good, but there was a lot of confusion due to too many lists ``` for lista in check: lista=lista.split(",") lista.extend(['MAX','MIN','CUR']) if lista[2]==('MAX'): lista[5] = lista[4] elif lista[2]==('MIN'): lista[6] = lista[4] elif ...
12,963
685,758
I have hardly ever noticed a python program that uses else in a for loop. I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope. What is the pythonic way to use an else in a for loop? Are there any notable use cases? And, yea. I dislike using break statemen...
2009/03/26
[ "https://Stackoverflow.com/questions/685758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55562/" ]
Basically, it simplifies any loop that uses a boolean flag like this: ``` found = False # <-- initialize boolean for divisor in range(2, n): if n % divisor == 0: found = True # <-- update boolean break # optional, but continuing would be a waste of time if found: ...
Without using `break`, `else` blocks have no benefit for `for` and `while` statements. The following two examples are equivalent: ``` for x in range(10): pass else: print "else" for x in range(10): pass print "else" ``` The only reason for using `else` with `for` or `while` is to do something after the loop i...
12,964