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
35,869,561
For a task I am to use ConditionalProbDist using LidstoneProbDist as the estimator, adding +0.01 to the sample count for each bin. I thought the following line of code would achieve this, but it produces a value error ``` fd = nltk.ConditionalProbDist(fd,nltk.probability.LidstoneProbDist,0.01) ``` I'm not sure how ...
2016/03/08
[ "https://Stackoverflow.com/questions/35869561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3255571/" ]
I found [the probability tutorial](http://www.nltk.org/howto/probability.html) on the NLTK website quite helpful as a reference. As mentioned in the answer above, using a lambda expression is a good idea, since the `ConditionalProbDist` will generate a frequency distribution (`nltk.FreqDist`) on the fly that's passed ...
You probably don't need this anymore as the question is very old, but still, you can pass LidstoneProbDist arguments to ConditionalProbDist with the help of lambda: ``` estimator = lambda fdist, bins: nltk.LidstoneProbDist(fdist, 0.01, bins) cpd = nltk.ConditionalProbDist(fd, estimator, bins) ```
2,442
68,293,321
In Python/Pandas, I want to create a column in my dataframe that shows the average number of days between customer visits at a venue. That is, for each customer, what are the average number of days between that customer's visits? Data looks like [Image of My Data](https://i.stack.imgur.com/NPFMU.png) Sorry I'm reall...
2021/07/07
[ "https://Stackoverflow.com/questions/68293321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14814034/" ]
On windows linking DLLs goes through a trampoline library (.lib file) which generates the right bindings. The convention for these is to prefix the function names with `__imp__` ([there is a related C++ answer](https://stackoverflow.com/a/5159395/1818675)). There is an [open issue](https://github.com/rust-lang/referen...
This is not my ideal answer, but it is how I solve the problem. What I'm still looking for is a way to get the Microsoft Linker (I believe) to output full verbosity in the rust build as it can do when doing C++ builds. There are options to the build that might trigger this but I haven't found them yet. That plus this ...
2,443
13,217,434
I'm planning to insert data to bellow CF that has compound keys. ``` CREATE TABLE event_attend ( event_id int, event_type varchar, event_user_id int, PRIMARY KEY (event_id, event_type) #compound keys... ); ``` But I can't insert data to this CF from python using cql. (http://code.google.com/a/apac...
2012/11/04
[ "https://Stackoverflow.com/questions/13217434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797779/" ]
It looks like you are trying to follow the example in: <http://pypi.python.org/pypi/cql/1.4.0> ``` import cql con = cql.connect(host, port, keyspace) cursor = con.cursor() cursor.execute("CQL QUERY", dict(kw='Foo', kw2='Bar', kwn='etc...')) ``` However, if you only need to insert one row (like in your question), jus...
For python 2.7, 3.3, 3.4, 3.5, and 3.6 for installation you can use ``` $ pip install cassandra-driver ``` And in python: ``` import cassandra ``` Documentation can be found under <https://datastax.github.io/python-driver/getting_started.html#passing-parameters-to-cql-queries>
2,445
41,351,431
Suppose I have the following numpy structured array: ``` In [250]: x Out[250]: array([(22, 2, -1000000000, 2000), (22, 2, 400, 2000), (22, 2, 804846, 2000), (44, 2, 800, 4000), (55, 5, 900, 5000), (55, 5, 1000, 5000), (55, 5, 8900, 5000), (55, 5, 11400, 5000), (33, 3, 14500, 3000), (33, 3, 40550,...
2016/12/27
[ "https://Stackoverflow.com/questions/41351431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2407231/" ]
This answer is a bit long and rambling. I started with what I knew from previous work on taking array views, and then tried to relate that to your functions. ================ In your case, all fields are 4 bytes long, both floats and ints. I can then view it as all ints or all floats: ``` In [1431]: x Out[1431]: ar...
hpaulj was right in saying that the problem is that the subset of the structured array is not contiguous. Interestingly, I figured out a way to make the array subset contiguous with the following function: ``` def view_fields(a, fields): """ `a` must be a numpy structured array. `names` is th...
2,446
62,980,784
I'm importing skimage in a python code. ``` from skimage.feature import greycomatrix, greycoprops ``` and I get this error > > ***No module named 'skimage'*** > > > Although I've already installed the scikit-image. Can anyone help ? This is the output of pip freeze [![enter image description here](https://i....
2020/07/19
[ "https://Stackoverflow.com/questions/62980784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8151481/" ]
You can use `pip install scikit-image`. Also, see the [recommended procedure](http://scikit-image.org/docs/dev/install.html).
If you are using python3 you should install the package using `python3 -m pip install package_name` or `pip3 install package_name` Using the `pip` binary will install the package for `python2` on some systems.
2,447
69,465,428
I have a dictionary that looks like this: d = {key1 : {(key2,key3) : value}, ...} so it is a dictionary of dictionaries and in the inside dict the keys are tuples. I would like to get a triple nested dict: {key1 : {key2 : {key3 : value}, ...} I know how to do it with 2 loops and a condition: ``` new_d = {} for key1,...
2021/10/06
[ "https://Stackoverflow.com/questions/69465428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11930768/" ]
You could use the common trick for nesting dicts arbitrarily, using `collections.defaultdict`: ``` from collections import defaultdict tree = lambda: defaultdict(tree) new_d = tree() for k1, dct in d.items(): for (k2, k3), val in dct.items(): new_d[k1][k2][k3] = val ```
If I understand the problem correctly, for this case you can wrap all the looping up in a dict comprehension. This assumes that your data is unique: ```py data = {"key1": {("key2", "key3"): "val"}} {k: {keys[0]: {keys[1]: val}} for k,v in data.items() for keys, val in v.items()} ```
2,450
52,029,026
i am developing a python script for my telegram right now. The problem is: How do I know when my bot is added to a group? Is there an Event or something else for that? I want the Bot to send a message to the group he´s beeing added to which says hi and the functions he can. I dont know if any kind of handler is abl...
2018/08/26
[ "https://Stackoverflow.com/questions/52029026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4847304/" ]
Very roughly, you would need to do something like this: register an handler that filters only service messages about new chat members. Then check if the bot is one of the new chat members. ``` from telegram.ext import Updater, MessageHandler, Filters def new_member(bot, update): for member in update.message.new_c...
With callbacks (preferred) ========================== As of version 12, the preferred way to handle updates is via callbacks. To use them prior to version 13 state `use_context=True` in your `Updater`. Version 13 will have this as default. ``` from telegram.ext import Updater, MessageHandler, Filters def new_member(...
2,451
58,491,838
I was setting up to use Numba along with my AMD GPU. I started out with the most basic example available on their website, to calculate the value of Pi using the Monte-Carlo simulation. I made some changes to the code so that it can run on GPU first and then on the CPU. By doing this, I just wanted to compare the tim...
2019/10/21
[ "https://Stackoverflow.com/questions/58491838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8726146/" ]
I've reorganized your code a bit: ``` import numpy from numba import jit import random from timeit import default_timer as timer @jit(nopython=True) def monte_carlo_pi(nsamples): random.seed(0) acc = 0 for i in range(nsamples): x = random.random() y = random.random() if (x ** 2 + ...
> > **Q** : *Can anyone explain as to **why** this difference comes up?* > > > The availability and almost pedantic care of systematic use of re-setting the same state via the PRNG-of-choice **`.seed( aRepeatableExperimentSeedNUMBER )`**-method is the root-cause of all these surprises. Proper seeding works **if...
2,452
43,810,256
In DOS or batch file on windows we can access multiple consecutive files fieldgen1.txt, fieldgen2.txt, etc. as follows: ``` for /L %%i in (1,1,250) do ( copy fieldgen%%i.txt hk.ref Process the file and go to next file. ``` I have 250 files name like fieldgen1.ref, fieldgen2.ref, etc. Now I want to access one...
2017/05/05
[ "https://Stackoverflow.com/questions/43810256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6210264/" ]
Yes, you can access and process consecutive files in python ``` for i in range(1, 251): with open('fieldgen%s.txt' % i, 'r') as fp: lines = fp.readlines() # Do all your processing here ``` The code will loop and read each file. You can then do your processing once you have read all the lines. You...
You could do something like ``` import os files = os.listdir(".") for f in files: print (str(f)) ``` This will print all files and directories in the current run directory. Once you have the file name you can use that to process the content.
2,453
52,621,859
I am a new python learner and I want to write a program which reads a text file, and save value of a line contains "width" and print it. The file looks like: ``` width: 10128 nlines: 7101 ``` I am trying something like: ``` filename = "text.txtr" # open the file for reading filehandle ...
2018/10/03
[ "https://Stackoverflow.com/questions/52621859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9084038/" ]
Your approach to opening the file is not good, try using with statement whenever opening a file. Afterwards you can iterate over each line from the file and check if it contains width, and if it does you need to extract the number, which can be done using regex. See the code below. ``` import re filename = "text.txtr...
It's not returning results because of the line `if " width " in line:`. As you can see from your file, there is not a line with `" width "` in there, maybe you want: ``` if "width:" in line: #Do things ``` Also note there are a few issues with the code, for example that your program will never finish becasu...
2,455
56,561,072
I'm trying to upgrade pip, and also install pywinusb, but I'm getting the error: "**UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 8: ordinal not in range(128)**". Pip upgrade: ``` PS C:\Python27> pip --version pip 18.1 from c:\python27\lib\site-packages\pip (python 2.7) PS C:\Python27> python ...
2019/06/12
[ "https://Stackoverflow.com/questions/56561072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6078511/" ]
Seems to be a specific issue concerning `Button` when contained in a `List` row. **Workaround**: ```swift List { HStack { Text("One").onTapGesture { print("One") } Text("Two").onTapGesture { print("Two") } } } ``` This yields the desired output. You can also use a `Group` instead of `Text` to have a so...
One of the differences with SwiftUI is that you are not creating specific instances of, for example UIButton, because you might be in a Mac app. With SwiftUI, you are requesting a button type thing. In this case since you are in a list row, the system gives you a full size, tap anywhere to trigger the action, button. ...
2,459
45,906,144
I was trying to open stackoverflow and search for a query and then click the search button. almost everything went fine except I was not able to click submit button I encountered error > > WebDriverException: unknown error: Element ... is not clickable at point (608, 31). Other element would > receive the click: (S...
2017/08/27
[ "https://Stackoverflow.com/questions/45906144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7698247/" ]
``` <button type="submit" class="btn js-search-submit"> <svg role="icon" class="svg-icon iconSearch" width="18" height="18" viewBox="0 0 18 18"> <path d="..."></path> </svg> </button> ``` You are trying to click on the `svg`. That icon is not clickable, but the button is. So change the button selecto...
Click the element with right locator, your button locator is wrong. Other code is looking good try this ``` browser=webdriver.Chrome() browser.get("https://stackoverflow.com/questions/19035186/how-to-select-element-with-selenium-python-xpath") z=browser.find_element_by_css_selector(".f-input.js-search-field")#use .f...
2,465
16,647,186
I have a bunch of functions that I've written in C and I'd like some code I've written in Python to be able to access those functions. I've read several questions on here that deal with a similar problem ([here](https://stackoverflow.com/questions/145270/calling-c-c-from-python) and [here](https://stackoverflow.com/q...
2013/05/20
[ "https://Stackoverflow.com/questions/16647186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1765768/" ]
You should call C from Python by writing a **ctypes** wrapper. Cython is for making python-like code run faster, ctypes is for making C functions callable from python. What you need to do is the following: 1. Write the C functions you want to use. (You probably did this already) 2. Create a shared object (.so, for lin...
It'll be easier to call C from python. Your scenario sounds weird - normally people write most of the code in python except for the processor-intensive portion, which is written in C. Is the two-dimensional FFT the computationally-intensive part of your code?
2,468
50,874,453
Hi I am both new to python and q/KDB. I am using qpython to get results from a kdb database doing the following: ``` q = qconnection.QConnection(host=self.host, port=self.port, username=self.username, password=self.password) results = q.sync(query) ``` The result is a qtable. I need to convert the qtable into a stri...
2018/06/15
[ "https://Stackoverflow.com/questions/50874453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9946190/" ]
You might just want to string the table on the way out from kdb rather than in python. It'll get you what you want but the data won't be easy or efficient to deal with on the python side ``` q)csv 0: select from t "col1,col2" "a,1" "b,2" "c,3" ``` Try issuing `q.sync("csv 0: select from t")`
Converting the numerical columns to `string` can achieve the results you are after. ``` results = q.sync('t:([] 2?.z.d;2?.z.t;2?`3;p:2?100.);update string d, string t, string p from t') for item in results: t = () for x in item: t = t + (x.decode(),) print(t) ('2017.05.31', '16:46:10.161...
2,478
51,434,538
I am looking for a way to understand [ioloop in tornado](http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop), since I read the official doc several times, but can't understand it. Specifically, why it exists. ``` from tornado.concurrent import Future from tornado.httpclient import AsyncHTTPClient f...
2018/07/20
[ "https://Stackoverflow.com/questions/51434538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/887103/" ]
Rather to say it is `IOLoop`, maybe `EventLoop` is clearer for you to understand. `IOLoop.current()` doesn't really return an IO device but just a pure python event loop which is basically the same as `asyncio.get_event_loop()` or the underlying event loop in `nodejs`. The reason why you need event loop to just do a ...
> > I never heard of IO loop in javascript nodejs. > > > In node.js, the equivalent concept is the [event loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/). The node event loop is mostly invisible because all programs use it - it's what's running in between your callbacks. In Python, most ...
2,479
68,472,830
Today I have tried to send email with python: ``` import smtplib EMAIL_HOST = 'smtp.google.com' EMAIL_PORT = 587 EMAIL_FROM_LOGIN = 'sender@gmail.com' EMAIL_FROM_PASSWORD = 'password' MESSAGE = 'Hi!' EMAIL_TO_LOGIN = 'recipient@gmail.com' print('starting...') server = smtplib.SMTP(EMAIL_HOST, EMAIL_PORT) server.s...
2021/07/21
[ "https://Stackoverflow.com/questions/68472830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10872199/" ]
Enable lower security in your gmail account and fix your smtp address: '**smtp.gmail.com**': My sample: ``` import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText mail_content = 'Sample text' sender_address = 'xxx@xxx' sender_pass = 'xxxx' receiver_address = 'xxx@xxx' me...
--- Have you checked your code? there is **smtp.google.com** instead of **smtp.gmail.com**. Before executing the script --- 1. First of all, ensure that you logged in by that mail you are going to use to send mail in your script. 2. The second thing and important you must have on your [Less Security App](https://my...
2,480
46,143,079
I have wriiten a code for linear search in python language. The code is working fine for single digit numbers but its not working for double digit numbers or for numbers more than that. Here is my code. ``` def linear_search(x,sort_lst): i = 0 c= 0 for i in range(len(sort_lst)): if sort_lst[i] == x...
2017/09/10
[ "https://Stackoverflow.com/questions/46143079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8279672/" ]
`redux-promise` will handle only a promise but ``` { pass : Promise, fail : Promise, exempt : Promise, } ``` is not a promise. You have to convert it to single promise so that `redux-promise` can handle it. I think you need `Promise.all` for this task. Try something like: ``` const payload = Promise.all...
**Edit**: the answer of [Raghavgarg](https://stackoverflow.com/users/3439731/raghavgarg) is probably better if you already have logic that depends on your final payload (the one in the reducer) having the same structure as before. The middle-ware you use for promises probably expects the payload to be a promise, not a...
2,481
73,513,397
I am having issues with emails address and with a small correction, they are can be converted to valid email addresses. For Ex: ``` %20adi@gmail.com, --- Not valid 'sam@tell.net, --- Not valid (hi@telligen.com), --- Not valid (gii@weerte.com), --- Not valid :qwert34@embright.com, --- Not valid //24adifrmaes@micro...
2022/08/27
[ "https://Stackoverflow.com/questions/73513397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17867413/" ]
You can do this (I basically check if the elements in the email are alpha characters or a point, and remove them if not so): ``` emails = [ 'sam@tell.net', '(hi@telligen.com)', '(gii@weerte.com)', ':qwert34@embright.com', '//24adifrmaes@microsot.com', 'tellei@apple.com' ] def correct...
Data clean-up is messy but I found the approach of defining a set of rules to be an easy way to manage this (order of the rules matters): ``` rules = [ lambda s: s.replace('%20', ' '), lambda s: s.strip(" ,'"), ] addresses = [ '%20adi@gmail.com,', 'sam@tell.net,' ] for a in addresses:...
2,482
20,262,552
I have an embedded system using a python interface. Currently the system is using a (system-local) XML-file to persist data in case the system gets turned off. But normally the system is running the entire time. When the system starts, the XML-file is read in and information is stored in python-objects. The information...
2013/11/28
[ "https://Stackoverflow.com/questions/20262552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2127432/" ]
You can use [FileVersionInfo](http://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo%28v=vs.110%29.aspx) class to get the version of another program. ``` FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(Environment.SystemDirectory + "\\Notepad.exe"); Console.WriteLine("File: " + ...
If I'm not wrong, you are trying to fetch the version number of a file using c#. You can try the below example: ``` using System; using System.IO; using System.Diagnostics; class Class1 { public static void Main(string[] args) { // Get the file version for the notepad. // Use either of the two foll...
2,485
9,598,739
I have two versions of python installed on Win7. (Python 2.5 and Python 2.7). These are located in 'C:/Python25' and 'C:/Python27' respectively. I am trying to run a file using Python 2.5 but by default Cygwin picks up 2.7. How do I change which version Cygwin uses?
2012/03/07
[ "https://Stackoverflow.com/questions/9598739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145456/" ]
The fast way is to reorder your $PATH so that 2.5 is picked up first. The correct way is to use virtualenv to create a jail environment that's specific to a python version.
As an addition to Bon's post, if you're not sand-boxing your not doing it right. Why would you want to put your global install of Python at risk of anything? With Virtualenv you can select which Python interpreter is used for that particular sand-box. Virtualenv and Virtualenvwrapper(or custom solution) are two of the ...
2,487
38,967,402
I'm trying to multiply two pandas dataframes with each other. Specifically, I want to multiply every column with every column of the other df. The dataframes are one-hot encoded, so they look like this: ``` col_1, col_2, col_3, ... 0 1 0 1 0 0 0 0 1 ... ``` I could just iterat...
2016/08/16
[ "https://Stackoverflow.com/questions/38967402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3950550/" ]
``` # use numpy to get a pair of indices that map out every # combination of columns from df_1 and columns of df_2 pidx = np.indices((df_1.shape[1], df_2.shape[1])).reshape(2, -1) # use pandas MultiIndex to create a nice MultiIndex for # the final output lcol = pd.MultiIndex.from_product([df_1.columns, df_2.columns], ...
You can use numpy. Consider this example code, I did modify the variable names, but `Test1()` is essentially your code. I didn't bother create the correct column names in that function though: ``` import pandas as pd import numpy as np A = [[1,0,1,1],[0,1,1,0],[0,1,0,1]] B = [[0,0,1,0],[1,0,1,0],[1,1,0,0],[1,0,0,1],...
2,490
23,237,692
I use PyDev in Eclipse and have a custom source path for my Python project: *src/main/python*/. The path is added to the PythonPath. Now, i want to use the library pyMIR: <https://github.com/jsawruk/pymir>, which doesn't has any install script. So I downloaded it and and included it direclty into my project as a Pydev...
2014/04/23
[ "https://Stackoverflow.com/questions/23237692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I tried to download and install the pymir package. There is one project structure that works for me: ``` project/music/ project/music/pymir/ project/music/pymir/AudioFile project/music/pymir/... project/music/audio_files/01.wav project/music/test.py ``` The test.py: ``` import numpy from pymir import AudioFile file...
add **"\_\_init\_\_.py"** empty file in base folder location and it works
2,493
20,154,490
I am trying to use `RotatingHandler` for our logging purpose in Python. I have kept backup files as 500 which means it will create maximum of 500 files I guess and the size that I have set is 2000 Bytes (not sure what is the recommended size limit is). If I run my below code, it doesn't log everything into a file. I w...
2013/11/22
[ "https://Stackoverflow.com/questions/20154490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
> > It doesn't print out INFO, DEBUG message into the file somehow.. Any > thoughts why it is not working out? > > > you don't seem to set a loglevel, so the default (warning) is used from <http://docs.python.org/2/library/logging.html> : > > Note that the root logger is created with level WARNING. > > > a...
I know, it is very late ,but I just got same error, and while searching that are I got your problem. I am able to resolve my problem, and I thought it might be helpful for some other user also : you have created a logger object and trying to access **my\_logger.config.fileConfig('log.conf')** which is wrong you should...
2,495
20,420,937
I have python script that set the IP4 address for my wireless and wired interfaces. So far, I use `subprocess` command like : ``` subprocess.call(["ip addr add local 192.168.1.2/24 broadcast 192.168.1.255 dev wlan0"]) ``` How can I set the IP4 address of an interface using python libraries? and if there is any way ...
2013/12/06
[ "https://Stackoverflow.com/questions/20420937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2468276/" ]
Set an address via the older `ioctl` interface: ``` import socket, struct, fcntl SIOCSIFADDR = 0x8916 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def setIpAddr(iface, ip): bin_ip = socket.inet_aton(ip) ifreq = struct.pack('16sH2s4s8s', iface, socket.AF_INET, '\x00' * 2, bin_ip, '\x00' * 8) f...
You have multiple options to do it from your python program. One could use the `ip` tool like you showed. While this is not the best option at all this usualy does the job while being a little bit slow and arkward to program. Another way would be to do the things `ip` does on your own by using the kernel netlink inte...
2,496
48,756,249
I have 2 models `Task` and `TaskImage` which is a collection of images belonging to `Task` object. What I want is to be able to add multiple images to my `Task` object, but I can only do it using 2 models. Currently, when I add images, it doesn't let me upload them and save new objects. **settings.py** ``` MEDIA_ROO...
2018/02/12
[ "https://Stackoverflow.com/questions/48756249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4729764/" ]
**Description for the issue** The origin of the exception was a `KeyError`, because of this statement ``` images_data = validated_data.pop('images') ``` This is because the validated data has no key `images`. This means the images input doesn't validate the image inputs from postman. Django post request store `In...
You have `read_only` set to true in `TaskImageSerializer` nested field. So there will be no validated\_data there.
2,498
7,461,570
I'm trying to build the most recent version of OpenCV on a minimal enough VPS but am running into trouble with CMake. I'm not familiar with CMake so I'm finding it difficult to interpret the log output and thus how to proceed to debug the problem. From the command line (x11 isn't installed) and within devel/OpenCV/-2....
2011/09/18
[ "https://Stackoverflow.com/questions/7461570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413797/" ]
Check your CMake version. Support for `set_property(CACHE ... )` was implemented in 2.8.0. If upgrading CMake is not an option for you - I guess it's safe to comment line #44. It seems to be used to create values for drop-down list in GUI. <http://www.kitware.com/blog/home/post/82> <http://blog.bethcodes.com/cmake-...
I've experienced lots of error building opencv that were caused by the wrong version of OpenCV. I successfully built opencv 3.0 using cmake 3.0 (though cmake 2.6 did not work for me). Then when I found I had to downgrade to opencv 2.4.9 I had to go back to my system's default cmake 2.6, as cmake 3.0 did not work. The f...
2,499
24,044,734
I'm looking for a way to use pandas and python to combine several columns in an excel sheet with known column names into a new, single one, keeping all the important information as in the example below: input: ``` ID,tp_c,tp_b,tp_p 0,transportation - cars,transportation - boats,transportation - planes 1,checked,-,...
2014/06/04
[ "https://Stackoverflow.com/questions/24044734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3700450/" ]
OK a more dynamic method: ``` In [63]: # get a list of the columns col_list = list(df.columns) # remove 'ID' column col_list.remove('ID') # create a dict as a lookup col_dict = dict(zip(col_list, [df.iloc[0][col].split(' - ')[1] for col in col_list])) col_dict Out[63]: {'tp_b': 'boats', 'tp_c': 'cars', 'tp_p': 'planes...
Here is one way: ``` newCol = pandas.Series('',index=d.index) for col in d.ix[:, 1:]: name = '+' + col.split('-')[1].strip() newCol[d[col]=='checked'] += name newCol = newCol.str.strip('+') ``` Then: ``` >>> newCol 0 cars 1 boats 2 cars+boats 3 boats+planes 4...
2,500
43,470,010
I am getting acquainted to Haskell, currently writing my third "homework" to some course I found on the web. The homework assignment needs to be presented\* in a file, named `Golf.hs`, starting with `module Golf where`. All well and good, this seems to be idiomatic in the language. However, I am used to python modules...
2017/04/18
[ "https://Stackoverflow.com/questions/43470010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1145760/" ]
Firstly, you are using **imgpt1** in every case which should not be the scenario. Rather use ``` v.getTag.equals("xxx") ``` After resolving that try to use the best android practice for comparison of strings. Best practice while checking the strings in android(Java) first check the null and empty string using ```...
You should check the tag of the `view` not the static item as they will be always true! look at your first condition. `imgpt1` tag is "`frontbumpers`" thus that condition is always true! hence it shows the same message every time. ``` @Override public void onClick(View v) { String message=""; //for y...
2,502
17,659,010
I'm trying to use the ctypes module to call, from within a python program, a (fortran) library of linear algebra routines that I have written. I have successfully imported the library and can call my *subroutines* and functions that return a single value. My problem is calling functions that return an array of doubles....
2013/07/15
[ "https://Stackoverflow.com/questions/17659010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1733205/" ]
The compiler may return a pointer to the array, or the array descriptor... So, when mixing languages, you should always use `bind(C)` except when the wrapper specifically supports Fortran. And (not surprisingly) `bind(C)` functions cannot return arrays. You could theoretically allocate the array and return `type(c_ptr)...
With gfortran the function call has a hidden argument: ``` >>> from ctypes import * >>> testlib = CDLL('./libutils.so') >>> cross = testlib.cross_product_ >>> a = (c_double * 3)(*[0.0, 1.0, 2.0]) >>> b = (c_double * 3)(*[1.0, 3.0, 2.0]) >>> c = (c_double * 3)() >>> pc = pointer(c) >>> cross(byref(pc), a, b) 3 >>> c[...
2,512
5,762,766
I've created a little helper application using Python and GTK. I've never used GTK before. As per the comment on <http://www.pygtk.org/> I used the PyGObject interface. Now I would like to add spell checking to my Gtk.TextBuffer. I found a library called GtkSpell and an associated python-gtkspell in the package manag...
2011/04/23
[ "https://Stackoverflow.com/questions/5762766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471/" ]
I wrote one, yesterday because I had the same problem, so it's a bit alpha but it works fine. You could get the source from: <https://github.com/koehlma/pygtkspellcheck>. It requires [pyenchant](http://packages.python.org/pyenchant/) and I only test it with Python 3 on Archlinux. If something doesn't work feel free to ...
I'm afraid that the PyGObject interface is new enough that GtkSpell hasn't been updated to use it yet. As far as I know there is no other premade GTK spell checker.
2,513
61,893,719
I am trying to load my saved model from `s3` using `joblib` ``` import pandas as pd import numpy as np import json import subprocess import sqlalchemy from sklearn.externals import joblib ENV = 'dev' model_d2v = load_d2v('model_d2v_version_002', ENV) def load_d2v(fname, env): model_name = fname if env == 'd...
2020/05/19
[ "https://Stackoverflow.com/questions/61893719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13114945/" ]
Maybe your code is outdated. For anyone who aims to use `fetch_mldata` in digit handwritten project, you should `fetch_openml` instead. ([link](https://stackoverflow.com/questions/47324921/cant-load-mnist-original-dataset-using-sklearn/52297457)) In old version of sklearn: ``` from sklearn.externals import joblib mni...
When getting error: **from sklearn.externals import joblib** it deprecated older version. For new version follow: 1. conda install -c anaconda scikit-learn (install using "Anaconda Promt") 2. import joblib (Jupyter Notebook)
2,514
65,590,149
I am trying to make a python script that will make payment automatically on [this](https://www.audiobooks.com/signup) site. I am able to get credit-card-number input but i can't access expirty month or CVV. **Code I tried** I used this to get credit card number field below ``` WebDriverWait(browser, 20).until(EC....
2021/01/06
[ "https://Stackoverflow.com/questions/65590149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10830982/" ]
if you switch to one iframe you have to swithc to default content before you can interact with another iframe outside the current iframe in which the code focus is use ``` WebDriverWait(browser, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='braintree-hosted-field-number']"))) WebDriverWa...
[![Try switch first, then catch the xpath](https://i.stack.imgur.com/Pp7gY.png)](https://i.stack.imgur.com/Pp7gY.png) Try to switch to the iframe first, then you can identify the column with xpath
2,524
54,058,184
I'm new to GCS and Cloud Functions and would like to understand how I can do an lightweight ETL using these two technologies combined with Python (3.7). I have a GCS bucket called 'Test\_1233' containing 3 files (all structurally identical). When a new file is added to this gcs bucket, I would like the following pyth...
2019/01/06
[ "https://Stackoverflow.com/questions/54058184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7638546/" ]
``` document.getElementById("loginField").getAttribute("name") ```
You can easily get it by attr method: ``` var name = $("#id").attr("name"); ```
2,526
23,653,147
I need to run a command as a different user in the %post section of an RPM. At the moment I am using a bit of a hack via python but it can't be the best way (it does feel a little dirty) ... ``` %post -p /usr/bin/python import os, pwd, subprocess os.setuid(pwd.getpwnam('apache')[2]) subprocess.call(['/usr/bin/somethi...
2014/05/14
[ "https://Stackoverflow.com/questions/23653147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2245703/" ]
If `/usr/bin/something` is something you are installing as part of the package, install it with something like ``` attr(4755, apache, apache) /usr/bin/something ``` When installed like this, `/usr/bin/something` will *always* run as user `apache`, regardless of what user actually runs it.
The accepted answer here is wrong IMO. It is not often at all you want to set attributes to allow *anyone* execute something as the owner. If you want to run something as a specific user, and that user doesn't have a shell set, you can use `su -s` to set the shell to use. For example: `su -s /bin/bash apache -c "/usr...
2,527
7,988,772
I have already created a 64-bit program for windows using cx freeze on a 64-bit machine. I am using Windows 7 64-bit Home premium. py2exe is not working because as i understand it does not work with python 3.2.2 yet. Is there an option i have to specify in cx freeze to compile in 32-bit instead of 64-bit. Thanks!
2011/11/02
[ "https://Stackoverflow.com/questions/7988772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1026738/" ]
To produce 32 bit executables you need to install 32-bit versions of Python and cx\_freeze.
All the "produce an executable from Python code" methods I know of basically create a file that bundles up the Python interpreter with the Python code you want to execute inside a single file. It is nothing at all like compiling C code to an executable; Python is just about impossible to compile to machine code in any ...
2,528
41,448,447
I am trying to run a **list of tasks** (*here running airflow but it could be anything really*) that require to be executed in a existing Conda environment. I would like to do these tasks: ``` - name: activate conda environment # does not work, just for the sake of understanding command: source activate my_conda_e...
2017/01/03
[ "https://Stackoverflow.com/questions/41448447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7370442/" ]
Each of your commands will be executed in a different process. `source` command, on the other hand, is used for reading the environment variables into the current process only (and its children), so it will apply only to the `activate conda environment` task. What you can try to do is: ``` - name: initialize the dat...
Was looking out for something similar. Found a neater solution than having multiple actions: ``` - name: Run commands in conda environment shell: source activate my_conda_env && airflow {{ item }} with_items: - initdb - webserver -p {{ airflow_webserver_port }} - scheduler ```
2,531
51,273,827
I thought I read somewhere that python (3.x at least) is smart enough to handle this: ``` x = 1.01 if 1 < x < 0: print('out of range!') ``` However it is not working for me. I know I can use this instead: ``` if ((x > 1) | (x < 0)): print('out of range!') ``` ... but is it possible to fix the version ab...
2018/07/10
[ "https://Stackoverflow.com/questions/51273827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3126298/" ]
It works well, it is your expression that is always False; try this one instead: ``` x = .99 if 1 > x > 0: print('out of range!') ```
You can do it in one *compound* expression, as you've already noted, and others have commented. You cannot do it in an expression with an implied conjunction (and / or), as you're trying to do with `1 < x < 0`. Your expression requires an `or` conjunction, but Python's implied operation in this case is `and`. Therefor...
2,532
63,739,587
I've been following along to [Corey Schafer's awesome youtube tutorial](https://www.youtube.com/watch?v=MwZwr5Tvyxo&list=PL-osiE80TeTs4UjLw5MM6OjgkjFeUxCYH) on the basic flaskblog. In addition to Corey's code, I`d like to add a logic, where users have to verify their email-address before being able to login. I've figur...
2020/09/04
[ "https://Stackoverflow.com/questions/63739587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13828684/" ]
The key to your question is this: > > My question is: how do I best identify the user (for whom to alter the email\_confirmed Column) when he clicks on his custom url? > > > The answer can be seen [in the example on URL safe serialisation using itsdangerous](https://itsdangerous.palletsprojects.com/en/1.1.x/url_s...
Thanks to @exhuma. Here is how I eventually got it to work - also in addition I'm posting the previously missing part of email-sending. **User Class in my models.py** ``` class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), unique=True, nullable=Fal...
2,535
17,457,608
I'm trying to time several things in python, including upload time to Amazon's S3 Cloud Storage, and am having a little trouble. I can time my hash, and a few other things, but not the upload. I thought [this](https://stackoverflow.com/questions/7523767/how-to-use-python-timeit-when-passing-variables-to-functions) post...
2013/07/03
[ "https://Stackoverflow.com/questions/17457608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2407064/" ]
I know this is heresy in the Python community, but I actually recommend *not* to use `timeit`, especially for something like this. For your purposes, I believe it will be good enough (and possibly even better than `timeit`!) if you simply use `time.time()` to time things. In other words, do something like ``` from tim...
You can use the command line interface to `timeit`. Just save your code as a module without the timing stuff. For example: ``` # file: test.py data = range(5) def foo(l): return sum(l) ``` Then you can run the timing code from the command line, like this: ``` $ python -mtimeit -s 'import test;' 'test.foo(test....
2,536
48,344,035
**Scenario:** I am trying to work out a way to send a quick test message in skype with a python code. From the documentations (<https://pypi.python.org/pypi/SkPy/0.1>) I got a snippet that should allow me to do that. **Problem:** I refilled the information as expected, but I am getting an error when trying to create t...
2018/01/19
[ "https://Stackoverflow.com/questions/48344035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7321700/" ]
It might look like you have been blocked from your server's IP if you logged in elsewhere recently. This works for me. ``` from skpy import Skype loggedInUser = Skype("userName", "password") print(loggedInUser.users) // loggedIn user info print(loggedInUser.contacts) // loggedIn user contacts ...
try this: ``` def connect_skype(user, pwd, token): s = Skype(connect=False) s.conn.setTokenFile(token) try: s.conn.readToken() except SkypeAuthException: s.conn.setUserPwd(user, pwd) s.conn.getSkypeToken() s.conn.writeToken() finally: sk = Skype(user, pwd, to...
2,537
34,004,510
I'm a beginner in the Python language. Is there a "try and except" function in python to check if the input is a LETTER or multiple LETTERS. If it isn't, ask for an input again? (I made one in which you have to enter an integer number) ``` def validation(i): try: result = int(i) return(result) except ValueErro...
2015/11/30
[ "https://Stackoverflow.com/questions/34004510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5622261/" ]
You can just call the same function again, in the try/except clause - to do that, you'll have to adjust your logic a bit: ``` def validate_integer(): x = input('Please enter a number: ') try: int(x) except ValueError: print('Sorry, {} is not a valid number'.format(x)) return validate_integer...
Don't use recursion in Python when simple iteration will do. ``` def validate(i): try: result = int(i) return result except ValueError: pass def start(): z = None while z is None: x = input("Please enter a number: ") z = validate(x) print("Success") start(...
2,538
4,393,830
In the process of trying to write a Python script that uses PIL today, I discovered I don't seem have it on my local machine (OS X 10.5.8, default 2.5 Python install). So I run: ``` easy_install --prefix=/usr/local/python/ pil ``` and it complains a little about /usr/local/python/lib/python2.5/site-packages not yet...
2010/12/09
[ "https://Stackoverflow.com/questions/4393830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87170/" ]
You are using the Apple-supplied Python 2.5 in OS X; it's a framework build and, by default, uses `/Library/Python/2.5/site-packages` as the location for installed packages, not `/usr/local`. Normally you shouldn't need to specify `--prefix` with an OS X framework build. Also beware that the `setuptools` (`easy_install...
Why did you specify `--prefix` in your `easy_install` invocation? Did you try just: ``` sudo easy_install pil ``` If you're only trying to install PIL to the default location, I would think `easy_install` could work out the correct path. (Clearly, `/usr/local/python` isn't it...) **EDIT**: Someone down-voted this a...
2,539
40,373,609
I am actually reading [Oracle-cx\_Oracle](http://www.oracle.com/technetwork/articles/dsl/python-091105.html) tutorial. There I came across non-pooled connections and DRCP, Basically I am not a DBA so I searched with google but couldn't found any thing. So could somebody help me understand what are they and how they a...
2016/11/02
[ "https://Stackoverflow.com/questions/40373609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293013/" ]
The error means that you're navigating to a view whose model is declared as typeof `Foo` (by using `@model Foo`), but you actually passed it a model which is typeof `Bar` (note the term *dictionary* is used because a model is passed to the view via a `ViewDataDictionary`). The error can be caused by **Passing the wro...
**Passing the model value that is populated from a controller method to a view** ``` public async Task<IActionResult> Index() { //Getting Data from Database var model= await _context.GetData(); //Selecting Populated Data from the Model and passing to view return View(model.Value); } ```
2,540
54,706,513
According to the xgboost documentation (<https://xgboost.readthedocs.io/en/latest/python/python_api.html#module-xgboost.training>) the xgboost returns feature importances: > > **feature\_importances\_** > > > Feature importances property > > > **Note** > > > Feature importance is defined only for tree boosters....
2019/02/15
[ "https://Stackoverflow.com/questions/54706513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8270077/" ]
If you set: ``` "moment": "^2.22.2" ``` the user will download almost the `v2.22.2`. In this case you will download the `v2.24.0` If you set: ``` "moment": "2.22.2" ``` the user will download exactly that version If you set: ``` "moment": "~2.22.1" ``` the user will download almost the `v2.22.1`. In this cas...
> > can we use any of version 2.x.x functionality( i.e. we can use the new functions provided by 2.9.9 in our app, though we installed 2.22.2 on our computer) > > > Just to avoid confusion. You will not install version 2.22.2 on your computer. By saying ^2.22.2, npm will look what is the highest version of 2.x.x a...
2,550
50,750,688
In python I can do: ``` >>> 5 in [2,4,6] False >>> 5 in [4,5,6] True ``` to determine if the give value `5` exists in the list. I want to do the same concept in `jq`. But, there is no `in`. Here is an example with a more realistic data set, and how I can check for 2 values. In my real need I have to check for a few ...
2018/06/07
[ "https://Stackoverflow.com/questions/50750688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117471/" ]
using `,` --------- I don't know where in <https://stedolan.github.io/jq/manual/v1.5/> this is documented. But the answer is in that `jq` does implicit one-to-many and many-to-one munging. ``` jq '.[] | select(.PrivateIpAddress == ("172.31.6.209", "172.31.6.229")) | .Pri...
> > But, there is no `in`. > > > You could use `index/1`, as documented in the manual. Even better would be to use `IN`, which however was only introduced after the release of jq 1.5. If your jq does not have it, you can use this definition for `IN/1`: ``` # return true or false as . is in the stream s def IN(s)...
2,551
3,221,314
Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take?
2010/07/11
[ "https://Stackoverflow.com/questions/3221314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/282307/" ]
Take a look here: [Asynchronous Programming in Python](http://xph.us/2009/12/10/asynchronous-programming-in-python.html) [An Introduction to Asynchronous Programming and Twisted](http://krondo.com/blog/?p=1247) Worth checking out: [asyncio (previously Tulip) has been checked into the Python default branch](https://...
The other respondents are pointing you to Twisted, which is a great and very comprehensive framework but in my opinion it has a very un-pythonic design. Also, AFAICT, you have to use the Twisted main loop, which may be a problem for you if you're already using something else that provides its own loop. Here is a contr...
2,552
59,860,579
I used postman to get urls from an api so I can look at certain titles. The response was saved as a .json file. A snippet of my response.json file looks like this: ``` { "apiUrl":"https://api.ft.com/example/83example74-3c9b-11ea-a01a-example547046735", "title": { "title": "Example title example title...
2020/01/22
[ "https://Stackoverflow.com/questions/59860579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11197012/" ]
If you are using materialize CSS framework make sure you initialize the select again, after appending new options. This worked for me ``` $.each(jsonArray , (key , value)=>{ var option = new Option(value.name , value.id) $('#subcategory').append(option) }) $('select').formSelect(); ```
Try This : ``` function PopulateDropDown(jsonArray) { if (jsonArray != null && jsonArray.length > 0) { $("#subcategory").removeAttr("disabled"); $.each(jsonArray, function () { $("#subcategory").append($("<option></option>").val(this['id']).html(this['name'])); }); } } ```
2,562
49,091,870
I want a model with 5 choices, but I cannot enforce them and display the display value in template. I am using CharField(choice=..) instead of ChoiceField or TypeChoiceField as in the [docs](https://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.get_FOO_display). I tried the solutions [here]...
2018/03/04
[ "https://Stackoverflow.com/questions/49091870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3592827/" ]
Well this is the common issue even when I started with django. So first let's look at django's feature that you can do it like below (Note: your choice case's value are going to be store as integer so you should use `models.IntegerField` instead of `models.CharField`): * [get\_FOO\_display()](https://docs.djangoprojec...
You can also use `models.CharField` but you have to set field option `choices` to your tuples. For exapmle: ``` FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' LEVELS = ( (FRESHMAN, 'Freshman'), (SOPHOMORE, 'Sophomore'), (JUNIOR, 'Junior'), (SENIOR, 'Senior'), ) level = models.CharField(...
2,563
53,520,300
Using the python bindings for libVLC in a urwid music player I am building. libVLC keeps outputting some errors about converting time and such when pausing and resuming a mp3 file. As far as I can gather from various posts on the vlc mailing list and forums, these errors appear in mp3 files all the time and as long as ...
2018/11/28
[ "https://Stackoverflow.com/questions/53520300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150033/" ]
This is just a macro `Privileged_Data` doing nothing. The compiler will not even see it after the preprocessor pass. It's probably a readability or company standards decision to tag some variables like this.
A preprocessor macro can be defined without an associated value. When that is the case, the macro is substituted with nothing after preprocessing. So given this: ``` #define Privileged_Data ``` Then this: ``` Privileged_Data static int dVariable ``` Becomes this after preprocessing: ``` static int dVariable ``...
2,564
43,714,967
I found (lambda \*\*x: x) is very useful for defining a dict in a succinct way, e.g. ``` xxx = (lambda **x: x)(a=1, b=2, c=3) ``` Is there any pre-defined python function does that?
2017/05/01
[ "https://Stackoverflow.com/questions/43714967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4927088/" ]
The `dict` function/constructor can be used in the same manner. ``` >>> (lambda **x: x)(a=1, b=2, c=3) == dict(a=1, b=2, c=3) True ``` See `help(dict)` for more ways to instantiate `dict`s. You are not limited to just defining them with `{'a': 1, 'b': 2, 'c': 3}`.
Try the `{}` literal dictionary syntax. It is quite succinct. See [5.5. *Dictionaries*](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) in the **Data Structures tutorial**. ``` >>> xxx = {'a': 1, 'b': 2, 'c': 3} >>> xxx {'a': 1, 'b': 2, 'c': 3} ```
2,565
48,103,343
I was a little surprised to find that: ``` # fast_ops_c.pyx cimport cython cimport numpy as np @cython.boundscheck(False) # turn off bounds-checking for entire function @cython.wraparound(False) # turn off negative index wrapping for entire function @cython.nonecheck(False) def c_iseq_f1(np.ndarray[np.double_t, ndi...
2018/01/04
[ "https://Stackoverflow.com/questions/48103343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48956/" ]
Current versions of Cython (at least >=0.29.20) produce similar performant C-code for both variants. The answer bellow holds for older Cython-versions. --- The reason for this surprise is that `x[i]` is more subtle as it looks. Let's take a look at the following cython function: ``` %%cython def cy_sum(x): cdef ...
Cython can translate `range(len(x))` loops into nearly onLy C Code: ``` for i in range(len(x)): ``` Generated code: ``` __pyx_t_6 = PyObject_Length(((PyObject *)__pyx_v_x)); if (unlikely(__pyx_t_6 == -1)) __PYX_ERR(0, 17, __pyx_L1_error) for (__pyx_t_7 = 0; __pyx_t_7 < __pyx_t_6; __pyx_t_7+=1) { __pyx_v_i =...
2,566
51,584,994
In python if my list is ``` TheTextImage = [["111000"],["222999"]] ``` How would one loop through this list creating a new one of ``` NewTextImage = [["000111"],["999222"]] ``` Can use `[:]` but not `[::-1]`, and cannot use `reverse()`
2018/07/29
[ "https://Stackoverflow.com/questions/51584994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10092065/" ]
You may not use `[::-1]` but you can multiply each range index by -1. ``` t = [["111000"],["222999"]] def rev(x): return "".join(x[(i+1)*-1] for i in range(len(x))) >>> [[rev(x) for x in z] for z in t] [['000111'], ['999222']] ``` --- If you may use the `step` arg in `range`, can do AChampions suggestion: ``...
If you can't use any standard functionality such as `reversed` or `[::-1]`, you can use `collections.deque` and `deque.appendleft` in a loop. Then use a list comprehension to apply the logic to multiple items. ``` from collections import deque L = [["111000"], ["222999"]] def reverser(x): out = deque() for i...
2,567
8,377,157
I want to find the fastest way to do the job of `switch` in C. I'm writing some Python code to replace C code, and it's all working fine except for a bottleneck. This code is used in a tight loop, so it really is quite crucial that I get the best performance. **Optimsation Attempt 1:** First attempt, as per previous q...
2011/12/04
[ "https://Stackoverflow.com/questions/8377157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148423/" ]
I think others are right to suggest numpy or pure c; but for pure python, here are some timings, for what they're worth. Based on these, I'm a bit surprised that `array.array` performed so much better than a `dict`. Are you creating these tables on the fly inside the loop? Or have I misunderstood something else about y...
Branch logic in general can be painfully slow in python when used in this type of application and you basically struck on one of the better ways of doing this for a tight inner loop where you are converting between integers. A few more things to experiment with: You might try would be working with [np.array](http://do...
2,571
19,174,634
**I found a better error message (see below).** I have a model called App in core/models.py. The error occurs when trying to access a specific app object in django admin. Even on an empty database (after syncdb) with a single app object. Seems core\_app\_history is something django generated. Any help is appreciated....
2013/10/04
[ "https://Stackoverflow.com/questions/19174634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1252307/" ]
i Think this is not valid JSON JSON should be like ``` [ { "id": 1, "src": "src1", "name": "name1" }, { "id": 2, "src": "src2", "name": "name2" }, { "id": 3, "src": "src3", "name": "name3" }, { "id": 4, ...
Your outer object in json does not have a key where the internal list is stored in. Also, your strings in json should be quoted. `src1`, `name1` are unquoted.
2,572
54,761,993
Passing the file as an argument and storing to an object reference seems very straightforward and easy to understand for the open() function, however the read () function does not take the argument in, and is using the format file.read() instead. Why does the read function not take in the file as arguments, such as rea...
2019/02/19
[ "https://Stackoverflow.com/questions/54761993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11000101/" ]
It's not included there because it's not a *function*, it's a *method* of the object that's exposing a file-oriented API, which is, in this case, `in_file`.
Because you have file reference by `in_file = open(from_file)` so when you do `in_file.read()` you are calling the read on the reference itself which is equivalent of `self` it means the object in this case file object
2,573
49,314,270
stuck with create dbf file in python3 with dbf lib. im tried this - ``` import dbf Tbl = dbf.Table( 'sample.dbf', 'ID N(6,0); FCODE C(10)') Tbl.open('read-write') Tbl.append() with Tbl.last_record as rec: rec.ID = 5 rec.FCODE = 'GA24850000' ``` and have next error: ``` Traceback (most recent call ...
2018/03/16
[ "https://Stackoverflow.com/questions/49314270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9394255/" ]
I had the same error. In the older versions of the dbf module, I was able to write dbf files by opening them just with `Tbl.open()` However, with the new version (dbf.0.97), I have to open the files with `Tbl.open(mode=dbf.READ_WRITE)` in order to be able to write them.
here's an append example: ``` table = dbf.Table('sample.dbf', 'cod N(1,0); name C(30)') table.open(mode=dbf.READ_WRITE) row_tuple = (1, 'Name') table.append(row_tuple) ```
2,574
14,633,952
I'm new to Elastic Search and to the non-SQL paradigm. I've been following ES tutorial, but there is one thing I couldn't put to work. In the following code (I'me using [PyES](http://packages.python.org/pyes/) to interact with ES) I create a single document, with a nested field (subjects), that contains another nested...
2013/01/31
[ "https://Stackoverflow.com/questions/14633952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/759733/" ]
Ok, after trying a tone of combinations, I finally got it using the following query: ``` query3 = { "nested": { "path": "subjects", "score_mode": "avg", "query": { "bool": { "must": [ { "text": {"subjects.concepts.name"...
Shot in the dark since I haven't tried this personally, but have you tried the fully qualified path to Concepts? ``` query2 = { "nested": { "path": "subjects.concepts", "score_mode": "avg", "query": { "bool": { "must": [ ...
2,575
22,444,378
I am looking for a simple solution to display thumbnails using wxPython. This is not about creating the thumbnails. I have a directory of thumbnails and want to display them on the screen. I am purposely not using terms like (Panel, Frame, Window, ScrolledWindow) because I am open to various solutions. Also note I hav...
2014/03/16
[ "https://Stackoverflow.com/questions/22444378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381864/" ]
I would recommend using the ThumbNailCtrl widget: <http://wxpython.org/Phoenix/docs/html/lib.agw.thumbnailctrl.html>. There is a good example in the wxPython demo. Or you could use this one from the documentation. Note that the ThumbNailCtrl requires the Python Imaging Library to be installed. ``` import os import wx...
I would just display them as wx.Image inside a frame. <http://www.wxpython.org/docs/api/wx.Image-class.html> From the class: "A platform-independent image class. An image can be created from data, or using wx.Bitmap.ConvertToImage, or loaded from a file in a variety of formats. Functions are available to set and get ...
2,578
39,053,393
I'm using the formula "product of two number is equal to the product of their GCD and LCM". Here's my code : ``` # Uses python3 import sys def hcf(x, y): while(y): x, y = y, x % y return x a,b = map(int,sys.stdin.readline().split()) res=int(((a*b)/hcf(a,b))) print(res) ``` It works great for s...
2016/08/20
[ "https://Stackoverflow.com/questions/39053393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6032875/" ]
Elaborating on the comments. In Python 3, true division, `/`, converts its arguments to floats. In your example, the true answer of `lcm(226553150, 1023473145)` is `46374212988031350`. By looking at `bin(46374212988031350)` you can verify that this is a 56 bit number. When you compute `226553150*1023473145/5` (5 is the...
You should use a different method to find the **GCD** that will be the issue: Use: ``` def hcfnaive(a, b): if(b == 0): return abs(a) else: return hcfnaive(b, a % b) ``` You can try one more method: ``` import math a = 13 b = 5 print((a*b)/math.gcd(a,b)) ```
2,581
46,996,102
python is new to me and I'm facing this little, probably for most of you really easy to solve, problem. I am trying for the first time to use a class so I dont have to make so many functions and just pick one out of the class!! so here is what I have writen so far: ``` from tkinter import * import webbrowser cla...
2017/10/29
[ "https://Stackoverflow.com/questions/46996102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8839994/" ]
You need to initiate a class first variable = web\_open3(). The **init** is a magic function that is ran when you create an instance of the class. This is to show how to begin writing a class in python. ``` from tkinter import * import webbrowser class web_open3: def __init__(self): self.A = "http://www.googl...
In programming, a class is an object. What is an object? It's an instance. In order to use your object, you first have to create it. You do that by instantiating it, `web = web_open3()`. Then, you can use the `open()` function. Now, objects may also be static. A static object, is an object that you don't instantiate....
2,582
57,270,642
I have a program that uploads videos to via the vimeo api. But everytime I click run, the program that runs is not the current one, its an old program, which I have now deleted and even deleted from recycle bin, yet everytime I run my vimeo code it runs a completely different program that shouldnt even exist its drivin...
2019/07/30
[ "https://Stackoverflow.com/questions/57270642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8066094/" ]
I suspect you have a script cached somewhere. To troubleshoot please do the following: * Restart VScode * Restart PC (if on windows 10 use `shutdown/r /f /t 000` in cmd to force a full restart and avoid windows fast-boot saving anything.) * check what happens if you run the script manually via `python *your script*` a...
If you are importing any module like "import some\_module" you could change it to "from some\_module import \*", or the specific function you want.
2,583
10,076,075
I have a data structure like this: ``` { 'key1':[ [1,1,'Some text'], [2,0,''], ... ], ... 'key99':[ [1,1,'Some text'], [2,1,'More text'], ... ], } ``` The size of this will be only like 100 keys and 100 lists in each key. I like to store it and re...
2012/04/09
[ "https://Stackoverflow.com/questions/10076075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126463/" ]
You should use a [`ObservableCollection<SomeType>`](http://msdn.microsoft.com/en-us/library/ms668604.aspx) for this instead. `ObservableCollection<T>` provides the `CollectionChanged` event which you can subscribe to - the [`CollectionChanged`](http://msdn.microsoft.com/en-us/library/ms653375.aspx) event fires when an...
`List` does not expose any events for that. You should consider using [`ObservableCollection`](http://msdn.microsoft.com/en-us/library/ms653375.aspx) instead. It has `CollectionChanged` event which occurs when an item is added, removed, changed, moved, or the entire list is refreshed.
2,584
70,234,520
I am new at python, im trying to write a code to print several lines after an if statement. for example, I have a file "test.txt" with this style: ``` Hello how are you? fine thanks how old are you? 24 good how old are you? i am 26 ok bye. Hello how are you? fine how old are you? 13 good how old are you? i am 34 ok b...
2021/12/05
[ "https://Stackoverflow.com/questions/70234520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17594775/" ]
You can use `readlines()` function that returnes lines of a file as a list and use `enumerate()` function to loop through list elements: ``` lines = open('test.txt').readlines() for i,line in enumerate(lines): if line.startswith('how old are you?'): print(lines[i+1], line[i+2]) ```
You could convert the file to a list and use a variable which increases by 1 for each line: ```py fhandle = list(open('test.txt')) i = 1 for line in fhandle: if line.startswith('how old are you?') print(fhandle[i]) i += 1 ```
2,593
2,009,379
``` import re from decimal import * import numpy from scipy.signal import cspline1d, cspline1d_eval import scipy.interpolate import scipy import math import numpy from scipy import interpolate Y1 =[0.48960000000000004, 0.52736099999999997, 0.56413900000000006, 0.60200199999999993, 0.640...
2010/01/05
[ "https://Stackoverflow.com/questions/2009379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/240524/" ]
I believe it's due to the X1 values not being ordered from smallest to largest plus also you have one duplicate x point, i.e, you need to sort the values for X1 and Y1 before you can use the splrep and remove duplicates. splrep from the docs seem to be low level access to FITPACK libraries which expects a sorted, non-...
The X value 0.029999999999999999 occurs twice, with two different Y coordinates. It wouldn't surprise me if that caused a problem trying to fit a polynomial spline segment....
2,596
70,639,556
Recently I have started to use [hydra](https://hydra.cc/docs/intro/) to manage the configs in my application. I use [Structured Configs](https://hydra.cc/docs/tutorials/structured_config/intro/) to create schema for .yaml config files. Structured Configs in Hyda uses [dataclasses](https://docs.python.org/3/library/data...
2022/01/09
[ "https://Stackoverflow.com/questions/70639556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10943470/" ]
For those of you wondering how this works exactly, here is an example of it: ```py import hydra from hydra.core.config_store import ConfigStore from omegaconf import OmegaConf from pydantic.dataclasses import dataclass from pydantic import validator @dataclass class MyConfigSchema: some_var: float @validator...
See [pydantic.dataclasses.dataclass](https://pydantic-docs.helpmanual.io/usage/dataclasses/), which are a drop-in replacement for the standard-library dataclasses with some extra type-checking.
2,597
31,460,152
I am writing a python code that will work as a dameon in a Raspberry pi. However, the person I am writing this for want to see the raw output it gets while it is running, not just my log files. My first idea to do this was to use a bash script using the Screen program, but that has some features in it that I CANNOT ha...
2015/07/16
[ "https://Stackoverflow.com/questions/31460152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3346931/" ]
In the latest seaborn, you can use the `countplot` function: ``` seaborn.countplot(x='reputation', data=df) ``` To do it with `barplot` you'd need something like this: ``` seaborn.barplot(x=df.reputation.value_counts().index, y=df.reputation.value_counts()) ``` You can't pass `'reputation'` as a column name to `x...
Using just `countplot` you can get the bars in the same order as `.value_counts()` output too: ``` seaborn.countplot(data=df, x='reputation', order=df.reputation.value_counts().index) ```
2,598
35,230,093
When a terminal is opened, the environmental shell is set. If I then type "csh" it starts running a c shell as a program within the bash terminal. My question is, from a python script, how can I check to determine if csh has been executed prior to starting the python script. THanks
2016/02/05
[ "https://Stackoverflow.com/questions/35230093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5889345/" ]
You can check the shell environment by using ``` import os shell = os.environ['SHELL'] ``` Then you can make sure `shell` is set to `/bin/csh`
You can use `os.getppid()` to find the [parent PID](https://unix.stackexchange.com/q/18166/3330), and `ps` to find the name of the command: ``` import subprocess import os ppid = os.getppid() out = subprocess.check_output(['ps', '--format', '%c', '--pid', str(ppid)]) print(out.splitlines()[-1]) ``` --- ``` % csh % ...
2,599
44,453,416
I'm packing python application into docker with nix's `dockerTools` and all is good except of the image size. Python itself is about 40Mb, and if you add `numpy` and `pandas` it would be few hundreds of megabytes, while the application code is only ~100Kb. The only solution I see is to pack dependencies in separate im...
2017/06/09
[ "https://Stackoverflow.com/questions/44453416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1307593/" ]
After googling a bit and reading `dockerTools` code I ended with this solution: ``` let deps = pkgs.dockerTools.buildImage { name = "deps"; content = [ list of all deps here ]; }; in pkgs.dockertools.buildImage { name = "app"; fromImage = deps; } ``` This will build two layer docker image, one of them ...
There is no need to package your dependencies in a separate image and inherit it, although that can't do harm. All you need to do is make sure that you add your application code as one of the last steps in the Dockerfile. Each command will have its own layer, so if you only change your application code, all layers abo...
2,600
60,397,004
Hi new to python and programming in general I'm trying to find an element in an array based on user input here's what i've done ``` a =[31,41,59,26,41,58] input = input("Enter number : ") for i in range(1,len(a),1) : if input == a[i] : print(i) ``` problem is that it doesn't print out anything. what am...
2020/02/25
[ "https://Stackoverflow.com/questions/60397004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12932148/" ]
`input` returns a string. To make them integers wrap them in `int`. ``` inp=int(input('enter :')) for i in range(0,len(a)-1): if inp==a[i]: print(i) ``` Indices in `list` start from *0* to *len(list)-1*. Instead of using `range(0,len(a)-1)` it's preferred to use `enumerate`. ``` for idx,val in enumera...
`input` returns a string; `a` contains integers. Your loop starts at 1, so it will never test against `a[0]` (in this case, 31). And you shouldn't re-define the name `input`.
2,601
26,532,216
I am trying to install some additional packages that do not come with Anaconda. All of these packages can be installed using `pip install PackageName`. However, when I type this command at the Anaconda Command Prompt, I get the following error: ``` Fatal error in launcher: Unable to create process using '"C:\Python27\...
2014/10/23
[ "https://Stackoverflow.com/questions/26532216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4174494/" ]
When installing anaconda, you are asked if you want to include the installed python to your system PATH variable. Make sure you have it in your PATH. If everything is set up correct, you can run pip from your regular command prompt aswell.
There is a way around the use of pip From the anaconda terminal window you can run: ``` conda install PackageName ``` Because MechanicalSoup isn't in one of anaconda's package channels you will have to do a bit of editing See instructions near the bottom [on their blog](http://www.continuum.io/blog/conda)
2,604
61,302,203
``` File "<ipython-input-6-b985bbbd8c62>", line 21 cv2.rectangle(img,(ix,iy),(x,y),(255,0,0),-1) ^ IndentationError: expected an indented block ``` my code ``` import cv2 import numpy as np #variables #True while mouse button down, False while mouse button up drawing = False ix,iy = -1 #Function de...
2020/04/19
[ "https://Stackoverflow.com/questions/61302203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12148825/" ]
launch `npm install` and in your body add the class `<body class="mat-app-background">`, or if you want you can try to add `import { MatSidenavModule } from "@angular/material/sidenav";` in your app.module.ts and put your html code in `<mat-sidenav-container>`
Try add `@import '@angular/material/prebuilt-themes/pink-bluegrey.css';` in your `styles.css` file.
2,609
38,274,695
Can anybody help me with this? I'm a beginner in python and programming. Thanks very much. I got this TypeError: 'dict' object is not callable when I execute this function. ``` def goodVsEvil(good, evil): GoodTeam = {'Hobbits':1, 'Men':2, 'Elves':3, 'Dwarves':3, 'Eagles':4, 'Wizards':10} EvilTeam = {'Orcs':1, 'Men':2,...
2016/07/08
[ "https://Stackoverflow.com/questions/38274695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6566925/" ]
Those parenthesis are unnecessary. You intend to use `.items()` which allows you to iterate on the keys and values of your dictionary: ``` for k, val in GoodTeam.items(): # your code ``` You should replicate this change for `EvilTeam` also.
Like the error says, `GoodTeam` is a dict, but you're trying to call it. I think you mean to call its `items` method: ``` for k, val in GoodTeam.items(): ``` The same is true for BadTeam. Note you have other errors; you're using the string format method but haven't given it anything to actually format.
2,610
34,090,999
With pythons [`logging`](https://docs.python.org/2/library/logging.html) module, is there a way to **collect multiple events into one log entry**? An ideal solution would be an extension of python's `logging` module or a **custom formatter/filter** for it so collecting logging events of the same kind happens in the bac...
2015/12/04
[ "https://Stackoverflow.com/questions/34090999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/789308/" ]
You should probably be writing a message aggregate/statistics class rather than trying to hook onto the logging system's [singletons](https://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python) but I guess you may have an existing code base that uses logging. I'd also sugge...
Create a counter and only log it for `count=1`, then increment thereafter and write out in a finally block (to ensure it gets logged no matter how bad the application crashes and burns). This could of course pose an issue if you have the same exception for different reasons, but you could always search for the line num...
2,611
57,907,518
So i'm trying to login web-client wifi login page with python. The web-client keep generating special octal character for every login session. So what i'm trying to do is: requests.get(web-client).text -> get the octal code by looping the text index -> combine with the password the problem is: -if i write ``` pas...
2019/09/12
[ "https://Stackoverflow.com/questions/57907518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11561888/" ]
You need to order comments. in micropost view: ``` <% @post.comments.order(created_at: :asc).each do |comment| %> .. <% end %> ```
Inside your show method: ``` @post = Micropost.find(params[:id]) @comments = @post.includes(:comments).order('comments.created_at DESC') ``` Then you can iterate @comments in your HTML files.
2,616
73,770,461
I am using the Twitter API StreamingClient using the python module Tweepy. I am currently doing a short stream where I am collecting tweets and saving the entire ID and text from the tweet inside of a json object and writing it to a file. My goal is to be able to collect the Twitter handle from each specific tweet and...
2022/09/19
[ "https://Stackoverflow.com/questions/73770461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11977945/" ]
So a couple of things Firstly, I'd recommend using `on_response` rather than `on_data` because StreamClient already defines a `on_data` function to parse the json. (Then it will fire `on_tweet`, `on_response`, `on_error`, etc) Secondly, `json_obj.user.screen_name` is part of API v1 I believe, which is why it doesn't ...
```py KEY_FILE = './keys/bearer_token' DURATION = 10 def on_data(json_data): json_obj = json.loads(json_data.decode()) print('Received tweet:', json_obj) with open('./collected_tweets/tweets.json', 'a') as out: json.dump(json_obj, out) bearer_token = open(KEY_FILE).read().strip() streaming_client ...
2,617
4,618,373
How do I tell Selenium to use HTMLUnit? I'm running selenium-server-standalone-2.0b1.jar as a Selenium server in the background, and the latest Python bindings installed with "pip install -U selenium". Everything works fine with Firefox. But I'd like to use HTMLUnit, as it is lighter weight and doesn't need X. This i...
2011/01/06
[ "https://Stackoverflow.com/questions/4618373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/284340/" ]
As of the 2.0b3 release of the python client you can create an HTMLUnit webdriver via a remote connection like so: ``` from selenium import webdriver driver = webdriver.Remote( desired_capabilities=webdriver.DesiredCapabilities.HTMLUNIT) driver.get('http://www.google.com') ``` You can also use the `HTMLUNITWITHJS`...
I use it like this: ``` from selenium.remote import connect b = connect('htmlunit') ...
2,618
41,599,600
(The question was edited based on feedback received. I will continue to edit it based on input received until the issue is resolved) I am learning Pyhton and beautiful soup in particular and I am doing the Google Exercise on Regex using the set of html files that contains popular baby names for different years (e.g. b...
2017/01/11
[ "https://Stackoverflow.com/questions/41599600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7128498/" ]
Your test is failing because those strings are not in ascending order. It fails at `word-e` of first string and `wordc` of second string where `c` is before `e` and hyphen is ignored by default. If you want to include the hyphen in ordering use `StringComparer.Ordinal`: ``` Assert.That(anotherList, Is.Ordered.Ascendin...
Thanks, abdul In some cases, if your collection has an UpperCase item, you should use StringComparer.OrdinalIgnoreCase instead of StringComparer.Ordinal
2,620
55,296,584
I am new to python. I want to get the ipaddress of the system. I am connected in LAN. When i use the below code to get the ip, it shows 127.0.1.1 instead of 192.168.1.32. Why it is not showing the LAN ip. Then how can i get my LAN ip. Every tutorials shows this way only. I also checked via connecting with mobile hotspo...
2019/03/22
[ "https://Stackoverflow.com/questions/55296584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11090395/" ]
I got this same problem with my raspi. ``` host_name = socket.gethostname()` host_addr = socket.gethostbyname(host_name) ``` and now if i print host\_addr, it will print 127.0.1.1. So i foundthis: <https://www.raspberrypi.org/forums/viewtopic.php?t=188615#p1187999> ``` host_addr = socket.gethostbyname(host_name + ...
i get the same problem what your are facing. but I get the solution with help of my own idea, And don't worry it is simple to use. if you familiar to linux you should heard the `ifconfig` command which return the informations about the network interfaces, and also you should understand about `grep` command which filter...
2,621
46,004,408
I bought a Raspberry Pi yesterday and I am facing quite a large problem. I can't sudo apt-get update. I think this error comes from my dns because I am connected via ethernet (Physically). so the message it prints when I execute the command is that: ``` pi@raspberrypi:~ $ sudo apt-get update Err:1 http://goddess-gate....
2017/09/01
[ "https://Stackoverflow.com/questions/46004408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7767248/" ]
Type following at the command line in order to edit `resolv.conf` which is the linux configuration file where **domain-name to IP mapping** is stored for the purpose of **DNS resolution**. ```sh sudo nano /etc/resolv.conf ``` then add these 2 lines: ``` nameserver 8.8.8.8 nameserver 8.8.4.4 ``` hope it will hel...
The ip-adress range 169.254.0.0 to 169.254.255.255 is used by zeroconf. Probably there is no active DHCP server in the LAN. Mostly the router is also a DHCP server. You also have no public IPv6 address. But this could also come from a IPv4 only internet connection. Try to configure the interface completly manual with c...
2,631
62,585,234
It seems that the output of [`zlib.compress`](https://docs.python.org/3/library/zlib.html#zlib.compress) uses all possible byte values. Is this possible to use 255 of 256 byte values (for example avoid using `\n`)? Note that I just use the python manual as a reference, but the question is not specific to python (i.e. ...
2020/06/25
[ "https://Stackoverflow.com/questions/62585234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1424739/" ]
No, this is not possible. Apart from the compressed data itself, there is standardized control structures which contain integers. Those integers may accidentially lead to any 8-bit character ending up in the bytestream. Your only chance would be to encode the zlib bytestream into another format, e.g. base64.
As [@ypnos says](https://stackoverflow.com/a/62585291/3798897), this isn't possible within zlib itself. You mentioned that base64 encoding is too inefficient, but it's pretty easy to use an escape character to encode a character you want to avoid (like newlines). This isn't the most efficient code in the world (and yo...
2,634
1,984,759
Is there any solution to force the RawConfigParser.write() method to export the config file with an alphabetical sort? Even if the original/loaded config file is sorted, the module mixes the section and the options into the sections arbitrarily, and is really annoying to edit manually a huge unsorted config file. PD:...
2009/12/31
[ "https://Stackoverflow.com/questions/1984759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235709/" ]
Three solutions: 1. Pass in a dict type (second argument to the constructor) which returns the keys in your preferred sort order. 2. Extend the class and overload `write()` (just copy this method from the original source and modify it). 3. Copy the file ConfigParser.py and add the sorting to the method `write()`. See...
The first method looked as the most easier, and safer way. But, after looking at the source code of the ConfigParser, it creates an empty built-in dict, and then copies all the values from the "second parameter" one-by-one. That means it won't use the OrderedDict type. An easy work around can be to overload the Create...
2,636
36,958,167
I need to update a document in an array inside another document in Mongo DB. ``` { "_id" : ObjectId("51cff693d342704b5047e6d8"), "author" : "test", "body" : "sdfkj dsfhk asdfjad ", "comments" : [ { "author" : "test", "body"...
2016/04/30
[ "https://Stackoverflow.com/questions/36958167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3123752/" ]
The moment you give your HTTP/HTTPS endpoint and create subscription from aws console, what happens is , the Amazon sends a subscription msg to that endpoint. Now this is a rest call, and your app must have a handler for this endpoint, otherwise you miss catching this subscription message. The httpRequest object that y...
There are 3 types of messages with SNS. Subscribe, Unsubscribe, and Notification. You will not get any Notification messages until you have correctly handled the subscribe message. Which involves making an API request to AWS when you receive the Subscribe request. The call in this case is ConfirmSubscription: <http:/...
2,645
67,347,499
I've error in Python Selenium. I'm trying to download all songs with Selenium, but there is some error. Here is code: ``` from selenium import webdriver import time driver = webdriver.Chrome('/home/tigran/Documents/chromedriver/chromedriver') url = 'https://sefon.pro/genres/shanson/top/' driver.get(url) songs = dri...
2021/05/01
[ "https://Stackoverflow.com/questions/67347499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14646178/" ]
You can try to use Image.fromarray: ``` Image.fromarray(matrice, mode=couleur) ```
Sorry for my longtime answer. The problem is in the type being used and converting it to the image. If you use a single-byte type for an image, then the matrix type must also be single-byte. Example: ``` from PIL import Image import numpy as np size_x = 50 size_y = 8 m = "L" matrix = np.array([[255] * 50 for _ in ra...
2,650
53,719,606
Without changing any code, the graph plotted will be different. Correct at the first run in a fresh bash, disordered in the next runs. (maybe it can cycle back to correct order) To be specific: Environment: MacOS Mojave 10.14.2, python3.7.1 installed through homebrew. To do: Plot `scatter` for two or three sets of ...
2018/12/11
[ "https://Stackoverflow.com/questions/53719606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6823079/" ]
Since your code is incomplete it is difficult to say for sure, but it seems that the order of markers is being messed up by the `cycle` iterator. Why don't you just try: ``` markerTypes = ['o', 's', '^'] strainLegends = [] for strain, markerType in zip(strains, markerTypes): strainSamples = [sample for sample in ...
I found this issue caused by a de-replication process I made in `strains`. ``` # wrong code: strains = list(set([idx.split('_')[0] for idx in pca2Plot.index])) # correct code: strains = list(OrderedDict.fromkeys([idx.split('_')[0] for idx in pca2Plot.index])) ``` Thus the question I asked was not a valid question. ...
2,651
56,937,573
How do they run these python commands in python console within their django project. Here is [example](https://docs.djangoproject.com/en/2.2/intro/overview/#enjoy-the-free-api). I'm using Windows 10, PyCharm and python 3.7. I know how to run the project. But when I run the project, - console opens, which gives regular...
2019/07/08
[ "https://Stackoverflow.com/questions/56937573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7402089/" ]
When you run the project you're using a management command: `python manage.py runserver`. To enter a console that has access to all your Django apps, the ORM, etc., use another management command: `python manage.py shell`. That will allow you to import models as shown in your example. As an additional tip, consider in...
Django has a [Shell](https://docs.djangoproject.com/en/2.2/ref/django-admin/#shell) management command that allows you to open a Python shell with all the Django stuff bootstrapped and ready to be executed. So by using `./manage.py shell` you will get an interactive python shell where you can write code.
2,652
59,530,439
I am trying to [`save`](https://code.kx.com/q/ref/save/) a [matrix](https://code.kx.com/q4m3/3_Lists/#3112-formal-definition-of-matrices) to file in binary format in KDB as per below: ``` matrix: (til 10)*/:til 10; save matrix; ``` However, I get the error `'type`. I guess `save` only works with tables? In which c...
2019/12/30
[ "https://Stackoverflow.com/questions/59530439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681681/" ]
`save` does work, you just have to reference it by name. ``` save`matrix ``` You can also save using ``` `:matrix set matrix; `:matrix 1: matrix; ``` But I don't think you'll be able to read this into python directly using numpy as it is stored in kdb format. It could be read into python using one of the python-...
Another option is to save in KDB+ IPC format and then read it into Python with [qPython](https://github.com/exxeleron/qPython) as a Pandas DataFrame. On the KDB+ side you can save it with ``` matrix:(til 10)*/:til 10; `:matrix.ipc 1: -8!matrix; ``` On the Python side you do ``` from pandas import DataFrame from qp...
2,653
3,526,748
Sometimes, when fetching data from the database either through the python shell or through a python script, the python process dies, and one single word is printed to the terminal: `Killed` That's literally all it says. It only happens with certain scripts, but it always happens for those scripts. It consistently happ...
2010/08/19
[ "https://Stackoverflow.com/questions/3526748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/836/" ]
Only one thing I could think of that will kill automatically a process on Linux - the OOM killer. What's in the system logs?
If psycopg is being used the issue is probably that the db connection isn't being closed. As per the psycopg [docs](http://initd.org/psycopg/docs/usage.html) example: ``` # Connect to an existing database >>> conn = psycopg2.connect("dbname=test user=postgres") # Open a cursor to perform database operations >>> cur ...
2,654
2,876,337
I am currently learning PHP and want to learn about OOP. 1. I know Python is a well-organized and is all OOP, so would learning Python be a wise choose to learn OOP? The thing is I am more towards web development then just general programming, and I know Python is just a general purpose language, but there is Djang...
2010/05/20
[ "https://Stackoverflow.com/questions/2876337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/345690/" ]
As long as you stay within their quota Google Apps Engine provides free hosting for Python. Django is a great framework when you want to do webdevelopment with Python. Django also has great documention with <http://www.djangobook.com/> and the official Django website.
You could learn using books, but nothing beats practical hands-on approach - so make sure you have Python installed in a computer to help you learn. If you decide to buy a Python book, I strongly suggest you **DO NOT** buy a copy of Vernon Ceder's [Python Book](http://valashiya.wordpress.com/2010/04/22/the-quick-python...
2,655
55,031,604
So I haven't been doing python for a while and haven't needed to deal with this before so if i'm making some stupid mistake don't go crazy. I have a list that is pulled from an SQLite database with `.fetchall()` on the end and it returns a list of one tuple and inside that tuple are all the results: ``` [('Bob', 'Sci...
2019/03/06
[ "https://Stackoverflow.com/questions/55031604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6635590/" ]
If there is always going to be exactly only one tuple in the returning list, you can unpack it into meaningfully named variables, the number of which should match the number of output columns in your query: ``` (name, test, description, subject, updated, created, flags, score), = cursor.fetchall() ``` Note the comma...
I suggest going from the most outside element to the inner one. At the beginning you have a list with one tuple. ``` >>>> result = [('Bob', 'Science Homework Test', 'Science homework is a test about Crude Oil development', 'Science-Chemistry', '2019-03-06', '2019-02-27', None, 0)] ``` To get the tuple, just get the ...
2,665
10,971,468
Similar posts such as the following do not answer my question. [Convert a string to integer with decimal in Python](https://stackoverflow.com/questions/1094717/convert-a-string-to-integer-with-decimal-in-python) Consider the following Python code. ``` >>> import decimal >>> s = '23.456' >>> d = decimal.Decimal(s) >...
2012/06/10
[ "https://Stackoverflow.com/questions/10971468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322885/" ]
If you want to stay in `decimal` numbers, safest is to convert everything: ``` >>> s = '23.456' >>> d = decimal.Decimal(s) >>> d - decimal.Decimal('1') Decimal('22.456') >>> d - decimal.Decimal('1.0') Decimal('22.456') ``` In Python 2.7, there's an implicit conversion for integers, but not floats. ``` >>> d - 1 De...
Use the bultin float function: ``` >>> d = float('23.456') >>> d 23.456 >>> d - 1 22.456 ``` See the docs here: <http://docs.python.org/library/functions.html#float>
2,667
49,519,789
I want to have a black box in python where * The input is a list A. * There is a random number C for the black box which is randomly selected the first time the black box is called and stays the same for the next times the black box is called. * Based on list A and number C, the output is a list B. I was thinking of ...
2018/03/27
[ "https://Stackoverflow.com/questions/49519789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9559925/" ]
Make it a Class so C will persist. ``` class BlackBox(): def __init__(self): self.C = rand.randint(100) etc... ``` *As a side note, using some pretty cool Python functionality...* You can make objects of this class callable by implementing `__call__()` for your new class. ``` #inside the BlackB...
> > the issue is that a function cannot keep the selected number C for next calls. > > > This may be true in other languages, but not so in Python. Functions in Python are objects like any other, so you can store things on them. Here's a minimal example of doing so. ``` import random def this_function_stores_a_v...
2,677
66,030,433
I am having trouble setting up a GStreamer pipeline to forward a video stream over UDP via OpenCV. I have a laptop, and an AGX Xavier connected to the same network. The idea is to forward the webcam video feed to AGX which will do some OpenCV optical flow estimation on the GPU (in Python), draw flow vectors on the orig...
2021/02/03
[ "https://Stackoverflow.com/questions/66030433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15008550/" ]
you were very close to the solution. The problem lies in the warning you yourself noticed `warning: Invalid component`. The problem is that rtp jpeg payloader gets stuck due to not supporting video format it is getting. Check [this](http://gstreamer-devel.966125.n4.nabble.com/ximagesrc-to-jpegenc-td4669619.html) Howev...
Note: I cannot write a comment due to the low reputation. According to your problem description, it is difficult to understand what your problem is. Simply, you will run two bash scripts (`servevideo.bash` and `receivevideo.bash`) on your laptop, which may receive and send web-cam frames from the laptop (?), while a ...
2,682
53,055,563
The python `collections.Counter` object keeps track of the counts of objects. ``` >> from collections import Counter >> myC = Counter() >> myC.update("cat") >> myC.update("cat") >> myC["dogs"] = 8 >> myC["lizards"] = 0 >> print(myC) {"cat": 2, "dogs": 8, "lizards": 0} ``` Is there an analogous C++ object where I can...
2018/10/30
[ "https://Stackoverflow.com/questions/53055563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5843327/" ]
You could use an `std::map` like: ``` #include <iostream> #include <map> int main() { std::map<std::string,int> counter; counter["dog"] = 8; counter["cat"]++; counter["cat"]++; counter["1"] = 0; for (auto pair : counter) { cout << pair.first << ":" << pair.second << std::endl; } }...
You can use [std::unordered\_map](https://en.cppreference.com/w/cpp/container/unordered_map) if you want constant on average lookup complexity (as you get using collections.Counter). [std::map](https://en.cppreference.com/w/cpp/container/map) "usually implemented as red-black trees", so complexity for lookup is logarit...
2,683
54,726,459
I'm working through an Exploit Development course on Pluralsight and in the lab I'm currently on we are doing a basic function pointer overwrite. The python script for the lab essentially runs the target executable with a 24 byte string input ending with the memory address of the "jackpot" function. Here's the code: `...
2019/02/16
[ "https://Stackoverflow.com/questions/54726459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9919300/" ]
The way this works is by processing the string from the end, each time you look at a character you check it's position in the array (I use a flipped array as it's more efficient than using `array_search()` each time). Then if the character is at the end of the array, then set it to the 0th element of the alphabet and i...
I ended up with something like this: ```php $string = 'ccc'; $alphabet = ['a', 'b', 'c']; $numbers = array_keys($alphabet); $numeric = str_replace($alphabet, $numbers, $string); $base = count($alphabet) + 1; $decimal = base_convert($numeric, $base, 10); $string = base_convert(++$decimal, 10, $base); strlen($decimal) ...
2,689
46,716,912
I am new to scala. As title, I would like to create a mutable map `Map[Int,(Int, Int)]` and with default value as tuple (0,0) if key not exist. In python the "defaultdict" make such effort easy. what is the elegant way to do it in Scala?
2017/10/12
[ "https://Stackoverflow.com/questions/46716912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1269298/" ]
Use `withDefaultValue` after creating the map: ``` import scala.collection.mutable val map = mutable.Map[Int,(Int, Int)]().withDefaultValue((0, 0)) ```
you are probably lookign for `.getOrElseUpdate` which takes the key, if not present updates with given value. ``` scala> val googleMap = Map[Int, (Int, Int)]().empty googleMap: scala.collection.mutable.Map[Int,(Int, Int)] = Map() scala> googleMap.getOrElseUpdate(100, (0, 0)) res3: (Int, Int) = (0,0) scala> googleMap...
2,690
31,110,801
I am learning recursion in python. I wrote a program but it is not working correctly. I am a beginner in python. I have two functions **scrabbleScore()** and **letterScore()**. **scrabbleScore()** calls **letterscore()** and itself also. Here is my code: ``` def letterScore( let ): if let in ['a','e','i','l','n','...
2015/06/29
[ "https://Stackoverflow.com/questions/31110801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3222665/" ]
I would rewrite your scrabbleScore to something like this ``` def scrabbleScore(S): def helper(S, p): if S == "": return p else: p += letterScore(S[0]) return helper(S[1:], p) return helper(S, 0) ``` this is how you could write it. `p` is called a akkumula...
Your variable `p` should be initialized to zero again after each call to `scrabbleScore(S)`. This will solve your problem. Example: ``` print "scrabbleScore('quetzal'): 25 ==", scrabbleScore('quetzal') p=0 print "scrabbleScore('jonquil'): 23 ==", scrabbleScore('jonquil') ```
2,693
1,826,824
On my ubuntu server I run the following command: ``` python -c 'import os; os.kill(5555, 0)' ``` This is done so that I can see if pid 5555 is running. From my understanding this should raise an OSError if the pid is not running. This is not raising an OSError for me which means it should be a running process. Howev...
2009/12/01
[ "https://Stackoverflow.com/questions/1826824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205114/" ]
Try installing htop (sudo apt-get install htop), it sometimes displays process that ps doesn't.
I don't know why that OSError is not raised in some cases, but it's important to note that there is a max pid value on linux and unix based OS: ``` $> cat /proc/sys/kernel/pid_max 32768 ```
2,695
6,091,688
I have a Tkinter program and running it like: `python myWindow.py` starts it all right, but the window is behind the terminal that I use to start it. Is there a way to make it grab the focus and be the foreground application? Does it depend on the platform?
2011/05/23
[ "https://Stackoverflow.com/questions/6091688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175461/" ]
This might be a feature of your particular window manager. One thing to try is for your app to call `focus_force` at startup, after all the widgets have been created.
Have you tried this at the end of your script ? ``` root.iconify() root.update() root.deiconify() root.mainloop() ```
2,700
68,230,917
this is what I did. The code is down bellow. I have the music.csv dataset. The error is Found input variables with inconsistent numbers of samples: [4, 1]. The error details is after the code. ```py # importing Data import pandas as pd music_data = pd.read_csv('music.csv') music_data # split into training and testin...
2021/07/02
[ "https://Stackoverflow.com/questions/68230917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14672478/" ]
I don't have your tables so I'll demonstrate it on Scott's EMP. ``` SQL> select empno, ename, to_char(hiredate, 'dd.mm.yyyy, dy') hiredate 2 from emp 3 where to_char(hiredate, 'dy', 'nls_date_language = english') in ('sat', 'sun'); EMPNO ENAME HIREDATE ---------- ---------- ------------------------ ...
You may use ISO week as a starting point, which is culture independent: ``` select * from your_table where trunc(created_date) - trunc(created_date, 'IW') in (5,6) ``` ISO week starts on Monday.
2,702
32,016,428
I'm getting following error while running the script and the script is to get the SPF records for a list of domains from a file and i'm not sure about the error,Can any one please help me on this issue ? ``` #!/usr/bin/python import sys import socket import dns.resolver import re def getspf (domain): answers = d...
2015/08/14
[ "https://Stackoverflow.com/questions/32016428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5093018/" ]
`domain` is a list, not a string. You want to pass *elements* of `domain` to `getspf`, not the entire list. ``` f=open('Input_Domains.txt','r') a=f.readlines() domain=a print domain x=0 while x<len(domain): # domain[x], not domain full_spf=getspf(domain[x]) print 'Initial SPF string : ', full_s...
When you run `getspf (domain)`, `domain` is the whole list of domains in your file. Instead of ``` f=open('Input_Domains.txt','r') a=f.readlines() domain=a print domain x=0 while x<len(domain): full_spf=getspf(domain) print 'Initial SPF string : ', full_spf x=x+1 f.close() ``` do ``` with open('Input_D...
2,705