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
30,421,267
I'm currently having troubles in setting `is_active` field from `False` back to `True` in Django. I have a custom Account model which is inhereted from `AbstractBaseUser` and is managed by `class AccountManager(BaseUserManager)`. By default, I override the `is_active` field to be False. However, when I try to reactiva...
2015/05/24
[ "https://Stackoverflow.com/questions/30421267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3773879/" ]
In Java, we have a class named `String` which has a method called `length()`. In C, you need to have a `\0` at the end of your string so you could know where your string ends. But in Java, this problem handled with the method`length()`.
C doesn't have strings as an actual data type and the convention is just that character arrays ending in a null character can be used as strings. That's what you get when you use string literals in the language and that's what you have to recreate when you don't use them. The underlying issue is that C wanted to save ...
7,718
72,923,752
I am learning python. For the code below, how to convert for loop to while loop in an efficient way? ``` import pandas as pd transactions01 = [] file=open('raw-data1.txt','w') file.write('HotDogs,Buns\nHotDogs,Buns\nHotDogs,Coke,Chips\nChips,Coke\nChips,Ketchup\nHotDogs,Coke,Chips\n') file.close() file=open('raw...
2022/07/09
[ "https://Stackoverflow.com/questions/72923752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19517608/" ]
Code : ``` i = 0 while i<len(lines): items = lines[i][:-1].split(',') has_item = {} j = 0 while j<len(items): has_item[items[j]]=1 j+=1 transactions01.append(has_item) i+=1 ```
It looks like you could just take your, use the csv module to parse the file as you've got an inconsistent number of rows per column, then turn it into a dataframe, use `pd.get_dummies` to get 0/1's per item present, then aggregate back to a row level to product your final output, eg: ``` import pandas as pd import cs...
7,727
38,000,412
I'm just new to python and I can't seem to find a solution to my problem, since it seems to be pretty simple. I have a geometry on paraview, I'm saving it as a vtk file and I'm trying to use python to calculate it's volume. This is the code I'm using: ``` import vtk reader = vtk.vtkPolyDataReader() reader.SetFileName...
2016/06/23
[ "https://Stackoverflow.com/questions/38000412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6505466/" ]
Depending on your version of `vtk` package you may want to test the following syntax if your version <= `5`: ``` Mass.SetInput(polydata.GetOutput()); ``` Otherwise, the actual syntax is: ``` Mass.SetInputData(polydata.GetOutputPort()); ``` PS: you can check the python-wrapped `vtk` version by running: ``` im...
You have assigned `reader.GetOutput()` in `polydata`. From `polydata`, I believe you need to do, `polydata.GetOutputPort()`
7,728
32,157,861
I use this in python: ``` test = zlib.compress(test, 1) ``` And now I want to use this in java, but I don't know how. At the end I need to convert the result to a string... I wait your help! thx
2015/08/22
[ "https://Stackoverflow.com/questions/32157861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3363949/" ]
You need to be more specific in describing what you want to achieve. Are you just seeking to decompress a zlib-compressed piece of data? Or are you seeking for a way to exchange data between Python and Java, possibly by transferring it across a network? For the former, it's basically sticking the compressed datastrea...
You can try using a RPC to create a server. <https://github.com/irmen/Pyro4> And access that server using java. <https://github.com/irmen/Pyrolite>
7,731
66,129,119
Trying to install freeradius package on Debian 10 buster and it fails. ``` $ sudo apt install freeradius Reading package lists... Done Building dependency tree... Done Reading state information... Done Suggested packages: freeradius-krb5 freeradius-ldap freeradius-mysql freeradius-postgresql freeradius-python3 The f...
2021/02/10
[ "https://Stackoverflow.com/questions/66129119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11966276/" ]
when removing freeradius (either by `apt remove freeradius` or `apt purge freeradius`) mind that config files are a seperate package called `freeradius-config` so to completely wipe freeradius and do a reinstall do: ``` apt purge freeradius freeradius-config rm -rf /etc/freeradius/ apt install freeradius ```
After installation of freeradius, add the following lines at the end of the client.conf file to set the access of your client: ``` #vi /etc/freeradius/3.0/clients.conf ``` For Example : ``` client SWITCH-01 { ipaddr = 192.168.0.10 secret = kamisama123 } client LINUX-01 { ipaddr = 192.168.0.20 secret = ve...
7,732
71,397,984
I have successfully installed Pillow: chris@MBPvonChristoph sources % python3 -m pip install --upgrade Pillow Collecting Pillow Using cached Pillow-9.0.1-1-cp310-cp310-macosx\_11\_0\_arm64.whl (2.7 MB) Installing collected packages: Pillow Successfully installed Pillow-9.0.1 but when i try to use it in pycharm got: ...
2022/03/08
[ "https://Stackoverflow.com/questions/71397984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8457280/" ]
looks like you may need to repoint your pycharm to your installed python interpreter. --- 1. go to command line and find out python interpreter path. On windows you can `where python` in your command line an it will give you where your python and packages are installed.. You could also activate python directly in co...
first ``` pip uninstall PIL ``` after uninstall ``` python3 -m pip install --upgrade pip python3 -m pip install --upgrade Pillow ``` or ``` brew install Pillow ```
7,733
61,941,471
i'm still new to the field of deep learning using keras and wanted to ask if it is possible to take a model after training the network and run the network again with the variables of that model? in other words, say i train the network and reach an accuracy of 90%, can i train the network again starting with the variab...
2020/05/21
[ "https://Stackoverflow.com/questions/61941471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12139083/" ]
For me I just had to add `./mongo_data` to `.dockerignore` and the Dockerfile would ignore this directory while building `api`. I did this for all my volumes and things work fine now, no permission errors.
I had the same problem. I assume that you didn't have this permission error at your first time of docker-compose up. The The file "mongo\_data/diagnostic.data" did not exist either. The mongo container will create the file when starting, and the file belongs to a user, it's 999:root in my case(postgres). ``` drwx----...
7,734
32,925,532
I had already looked through this post: [Python: building new list from existing by dropping every n-th element](https://stackoverflow.com/questions/16406772/python-building-new-list-from-existing-by-dropping-every-n-th-element), but for some reason it does not work for me: I tried this way: ``` def drop(mylist, n): ...
2015/10/03
[ "https://Stackoverflow.com/questions/32925532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4786305/" ]
The output is correct, you are removing the the elements with index 0, n, 2n, ... . So 1 and 3 are removed, 2 and 4 are left. So if you want to print the 0, n, 2n, ... element, just write ``` print(mylist[::n]) ```
your first approach looks good to me - you just have to adapt your start index if you want to drop the elements 1, 1+n, 1+2n, ... (as seems to be the case): ``` lst = list(range(1, 5)) del lst[1::2] print(lst) ```
7,735
67,972,487
I want to get a script to: a) check if a number within the user defined range is prime or not b) print the result of a check c) print amount of numbers checked and how many of these numbers were primes d) print the last prime number Here is what I have so far: ``` lower = int(input("Lower boundry: ")) upper = int(inp...
2021/06/14
[ "https://Stackoverflow.com/questions/67972487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16223545/" ]
The indentation of your `else` clause is wrong. It should belong to the `for` loop. This means it will be executed when the loop is not terminated by the `break` statement. I can't answer your question about the error message, because I don't know the test tool in question. To keep track of the number of primes found...
How about this . ``` # define a flag variable lower = int(input("Lower boundry: ")) upper = int(input("Upper boundry: ")) prime_list=[] for num in range(lower,upper+1): flag = False # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2, num): if (num % i)...
7,744
52,767,072
I am trying psql and getting an error. ``` $ psql psql: FATAL: "myilmaz" role not available ``` Then I try ``` $ createdb python_getting_started createdb: Unable to connect to template1 database: FATAL: "myilmaz" does not have access to the system ``` I run `export DATABASE_URL=postgres://$(whoami)` as indicated ...
2018/10/11
[ "https://Stackoverflow.com/questions/52767072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10398711/" ]
The part you haven't understood is that every method - in fact, every call to every method - has its own collection of local variables. That means that * the `winnings` variable declared in `main` is NOT the same variable as the `winnings` variable declared in `determineWinnings`; * the `bet` variable declared in `ma...
To avoid skipping if in execution use `bet = getBet(inScanner, currentPool); highLow = getHighLow(inScanner); winnings = determineWinnings(highLow, bet, roll);` instead of directly calling `getBet(inScanner, currentPool); getHighLow(inScanner); determineWinnings(highLow, bet, roll);` Reson for skipping if stateme...
7,746
74,436,487
I am using OR-Tools to solve a problem similar to the Nurse Scheduling problem. The difference in my case is that when I schedule a "Nurse" for a shift, they must then work consecutive days (i.e., there can be no gaps between days worked). Most of the similar questions point to this [code](https://github.com/google/or...
2022/11/14
[ "https://Stackoverflow.com/questions/74436487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18497033/" ]
[Select-String](https://learn.microsoft.com/en-gb/powershell/module/microsoft.powershell.utility/select-string): *By default, the output is a set of `MatchInfo` objects with one for each match found.* Apply `.substring` method to the `$_.Line` string, e.g. as follows: ``` Select-String -Path "DatabaseBackup - USER_DA...
[`Select-String`](https://learn.microsoft.com/en-us/dotnet/api/microsoft.powershell.commands.matchinfo?view=powershellsdk-7.2.0) is returning a `MatchInfo` object so you would need to iterate over the `Matches` property of that object. So you could do something like this: ``` (Select-String -Path "DatabaseBackup - US...
7,747
68,769,200
by no means am i an expert when it comes to python but i have tried my best. I have written a short code in python that reads a text file from a blob storage and appends it with some column names and outputs it to target folder. The code executes correctly when i run from VS Code. When i try to run it via Azure Functi...
2021/08/13
[ "https://Stackoverflow.com/questions/68769200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4511169/" ]
You have to revert the order of your aggregation operations since your `$project` will only leave one property `title` so there is no way to filter by `year` afterwards: ``` db.collection.aggregate([ { "$match": { "year": { "$gt": 1967, "$lt": 2020 } ...
``` db.movies.find({year: {$gte:1967, $lte:1995} },{title:1,year:1,"director.last_name":1 }).sort({year:1}) ```
7,748
4,834,036
I need to have an array of python objects to be used in creating a trie datastructure. I need a structure that will be fixed-length like a tuple and mutable like a list. I don't want to use a list because I want to be able to ensure that the list is *exactly* the right size (if it starts allocating extra elements, the ...
2011/01/28
[ "https://Stackoverflow.com/questions/4834036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
If you only need few fixed sizes of such a structure, I'd look at making classes with uniformly named `__slots__`, including one `size` slot to store the size. You'll need to declare a separate class for each size (number of slots). Define a `cdecl` function to access slots by index. Access performance will probably be...
How about this? ``` class TrieNode(): def __init__(self, length = 32): self.members = list() self.length = length for i in range(length): self.members.append(None) def set(self, idx, item): if idx < self.length and idx >= 0: self.members[idx] = item else: ...
7,749
49,868,348
I'm trying to install sklearn onm an AWS DeepLearning AMI, with Conda and an assortment of backends pre-installed. I'm following ScikitLearn's website instructions: ``` $ conda install -c anaconda scikit-learn $ source activate python3 $ jupyter notebook ``` In Jupyter notebook: ``` import numpy as np import panda...
2018/04/17
[ "https://Stackoverflow.com/questions/49868348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8268013/" ]
You need to start the virtual environment **first** "source activate python3", then install scikit-learn. Without activating the virtual environment, you are installing into the base python and not into the virtual environment. Cheers
And in case anybody didn't know how to install packages in each conda environment, it is (as in this case my environment of choice was `Tensorflow` in *Python 3.6*) here is the command I used my *mac bash*, and in my EC2 environment: ``` ubuntu@ip ***.***.**.***:~$ source activate tensorflow_p36 ``` and then: ``` u...
7,752
57,277,513
I'm generating the pictures of my latex document with the following program `genimg.py`: ``` #!/usr/bin/env python3 def figCircle(): print('generate circle picture') def figSquare(): print('generate square picture') def main(): for key, value in globals().items(): if callable(value) and key.start...
2019/07/30
[ "https://Stackoverflow.com/questions/57277513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11811021/" ]
You could call your code recursively for imported modules. Something like ``` import types def call_functions(module_dict): for key, value in module_dict.items(): if callable(value) and key.startswith('fig'): value() elif isinstance(value, types.ModuleType): call_functions(v...
``` import glob for fname in glob.glob("genimg*.py"): # get all the relevant files mod = gname.rsplit('.',1)([0]) mod = __import__(mod) # import the module for k,v in mod.__dict__.items(): if callable(v): v() # if a module attribute is a function, call it ```
7,755
62,670,115
I have text file containing employee details and various other details. Below is the consolidated data as shown below. ``` Data file created on 4 Jun 2020 GROUPCASEINSENSITIVE ON #KCT-User-Group GROUP KCT ALopp190 e190 ARaga789 Lshastri921 GROUP KCT DPatel592 ANaidu026 e026 KRam161 e161 #KBN-User-Group GROUP KBN ...
2020/07/01
[ "https://Stackoverflow.com/questions/62670115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13761107/" ]
As others have mentioned, you can source your `.vimrc`, but that doesn't completely reset Vim. If you want to just restart Vim, then you can do so by re-execing it. Vim doesn't provide a built-in way to exec processes from within it, since typically one doesn't want to replace one's editor with another process, but it...
I don't know if you had tried this but you can source your vimrc file from vim itself by typing > > :so $MYVIMRC > > >
7,756
28,769,698
I am learning python. I have a file like this ``` str1 str2 str3 str4 str1 str2 str7 str8 *** str9 str10 str12 str13 str9 str10 str16 str17 **** str 18 str19 str20 str21 *** ``` and so on. I want to change it to this format-> ``` str1 str2 str3 str4 str2 str7 str8 str9 str10 str12 str13 str10 str16 str17 str 1...
2015/02/27
[ "https://Stackoverflow.com/questions/28769698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/612258/" ]
A class diagram shows classes in their relation and their properties and methods. A state diagram visualizes a class's states and how they can change over time. In both cases you are talking about diagrams which are only a window into the model. The class relations define how the single classes relate to each other. ...
A state diagram shows the behavior of the class. A class model shows the relationship between two or more classes. It includes its properties/attributes... A state is an allowable sequence of changes of objects of a class model.
7,758
69,325,145
Suppose I have a string of A's and B's. I can either remove a character from either end of the string for a cost of 1, or I can remove any character from the middle for a cost of 2. What's the minimum cost to create a string of only A's? For example, if I have the string "BBABAA", then the minimum cost to remove is 4,...
2021/09/25
[ "https://Stackoverflow.com/questions/69325145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11228246/" ]
All `B`s must be removed. If we remove one `B` from the middle, we split the string into two sections. For the section on the right, none of the characters could be deleted from the left since otherwise we would have deleted the `B` from the left at a lower cost for that deletion. Mirror for the section on the left. A ...
Let `C` be an array where `C[i]` Is the optimal cost for the substring `s[0:i+1]`(assuming right sise Is exclusive]. Consider another game, exactly the same, EXCEPT eating from the right costs 2 instead of 1. Let `D` be the associated cost array of this new game, this cost is helpful to keep track of situations where ...
7,760
61,190,064
I am trying to create a docker image with opencv in order to display a video. I have the following Dockerfile: ``` FROM python:3 ADD testDocker_1.py / ADD video1.mp4 / RUN pip install opencv-python CMD [ "python", "./testDocker_1.py" ] ``` And the following python script: ``` import cv2 import os if __name__ == '_...
2020/04/13
[ "https://Stackoverflow.com/questions/61190064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11266804/" ]
Try this ``` xhost + sudo docker run -ti --rm -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix test1 ``` Although it would solve this particular use case, but you need to make a note of the following: > > **Basically, the xhost + allows everybody to use your host x server;** > > > [Refrence](https://marcos...
Kapil Khandelwal, your solution works for me. But only using the docker image on ubuntu, when I try to share it with windows it does not work.+
7,762
18,744,584
Right, I am trying to setup a django dev site based on a current live site. I've setup the new virtualenv and installed all of the dependencies. I've also made a copy of the database and done a fresh DB dump. I'm now getting the error above and I have no idea why. My django.wsgi file seems to be pointing at the virtal...
2013/09/11
[ "https://Stackoverflow.com/questions/18744584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256637/" ]
In this stanza: ``` # URL that handles pages media and uses <MEDIA_ROOT>/pages by default. _media_url = getattr(settings, "STATIC_URL", settings.MEDIA_URL) PAGES_MEDIA_URL = getattr(settings, 'PAGES_MEDIA_URL', join(_media_url, 'pages/')) ``` `STATIC_URL` is not in settings, and `settings.MEDIA_URL` is `None`. L...
in this line, ``` ile "/usr/lib/python2.6/posixpath.py" in join 67. elif path == '' or path.endswith('/'): ``` path is None. so a nonetype("path") has to attribute .endswith i would suggest like the other users said to put the full traceback error and check your code and see why path is None.
7,763
24,589,241
I just wrote a Google Cloud Endpoints API using Python (using the latest Mac OS), and now need to create an Android Client by following this: <https://developers.google.com/appengine/docs/python/endpoints/endpoints_tool> In the instructions, it says that there's a file called endpointscfg.py under google\_appengine, b...
2014/07/05
[ "https://Stackoverflow.com/questions/24589241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3108752/" ]
After a lot of trial and error I figured out the solution. All in all you need two different things in your project: **1) A class that inherits from ProminentProjectAction:** ``` import hudson.model.ProminentProjectAction; public class MyProjectAction implements ProminentProjectAction { @Override public St...
As it happens, there was a [plugin workshop](http://jenkins-ci.org/content/get-drunk-code-juc-boston) by Steven Christou at the recent [Jenkins User Conference](http://www.cloudbees.com/jenkins/juc-2014/boston) in Boston, which covered this case. You need to add a new RootAction, as shown in the following code from the...
7,764
56,674,284
I am trying to use beautiful soup to scrape data from [this](https://www.pro-football-reference.com/play-index/play_finder.cgi?request=1&match=summary_all&year_min=2018&year_max=2018&game_type=R&game_num_min=0&game_num_max=99&week_num_min=0&week_num_max=99&quarter%5B%5D=4&minutes_max=15&seconds_max=00&minutes_min=00&se...
2019/06/19
[ "https://Stackoverflow.com/questions/56674284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5657167/" ]
You can use `selenium` to hover over the "Share & more" link to display the menu, from which you can click the "Get table as csv": ``` from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from bs4 import BeautifulSoup as soup d = webdriver.Chrome('/path/to/chromedriver') d.ge...
You could just use pandas ``` import pandas as pd table = pd.read_html('https://www.pro-football-reference.com/play-index/play_finder.cgi?request=1&match=summary_all&year_min=2018&year_max=2018&game_type=R&game_num_min=0&game_num_max=99&week_num_min=0&week_num_max=99&quarter%5B%5D=4&minutes_max=15&seconds_max=00&minu...
7,772
44,299,462
I run below commands after unzipping that python 3.6 tar.xz file. ``` ./configure make make install ``` Error log: ``` ranlib libpython3.6m.a gcc -pthread -Xlinker -export-dynamic -o python Programs/python.o libpython3.6m.a -lpthread -ldl -lutil -lrt -lm if test "no-framework" = "no-framework" ; then \ ...
2017/06/01
[ "https://Stackoverflow.com/questions/44299462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4909084/" ]
Have you tried running the above commands using `sudo` powers? original answer: <https://askubuntu.com/q/865554/667903> `sudo make install` **or** If you are using Ubuntu 16.10 or 17.04, then Python 3.6 is in the universe repository, so you can just run ``` sudo apt-get update sudo apt-get install python3.6 ```
Try after installing build essentials whic contains compilers,package dev tools and libs: sudo apt-get install build-essential
7,773
52,929,872
I am trying to read the text in a cheque using pytesseract OCR. I have installed the required python packages required for this task e.g. pip install pytesseract. However when I try to use the package to read the file I get the following error: ``` pytesseract.image_to_string(im, lang='eng') Traceback (most recent c...
2018/10/22
[ "https://Stackoverflow.com/questions/52929872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10122096/" ]
The documentation for tesseract makes this clear. <https://pypi.org/project/pytesseract/> ``` # If you don't have tesseract executable in your PATH, include the following: pytesseract.pytesseract.tesseract_cmd = r'<full_path_to_your_tesseract_executable>' ```
You need to install teserract executable file and include the path into the program then it won't gives any error
7,775
41,419,093
I am fairly new to Python and started learning. I am trying to automate data entry. I am stuck at the "save" button. How do I find the right information and click it to save? Thank you so much PyGuy --- Element ``` <input type="submit" value="Save"> ``` Xpath ``` //*[@id="decorated-admin-content"]/div/div/form...
2017/01/01
[ "https://Stackoverflow.com/questions/41419093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7363397/" ]
If you're using python, the syntax is not right. Python uses snake\_case and By uses CONSTANT convention ``` from selenium import webdriver from selenium.webdriver.common.by import By driver.find_element(By.XPATH, "//input[@type='submit' and @value='save']").click() ``` It's actually suggested to use the individual...
Did you try with other parameter than xpath ? I also had some difficulties with selenium, you can try the following line : ``` driver.findElement(By.tagName("form")).submit() ``` It's works for me and is useful to validate forms
7,776
57,567,892
Previously I asked a similar question: [cx\_Freeze unable fo find mkl: MKL FATAL ERROR: Cannot load mkl\_intel\_thread.dll](https://stackoverflow.com/questions/57493584/cx-freeze-unable-fo-find-mkl-mkl-fatal-error-cannot-load-mkl-intel-thread-dll) But now I have a subtle difference. I want to run the program without i...
2019/08/20
[ "https://Stackoverflow.com/questions/57567892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1612432/" ]
Maybe another DLL necessary for MKL, such as `libiomp5md.dll` for example, is missing and causes the error. See [Cannot load mkl\_intel\_thread.dll on python executable](https://stackoverflow.com/q/54337644/8516269), my answer there and its comments. If this still does not solve your problem, try to manually copy othe...
Recently I faced the same error in python3.7 . I did not have the option of moving Dll, I Solved the problem by just doing. ``` conda install cython ``` After the cython install all dll's were in proper place.
7,777
62,501,832
I was using following code to download the NSE stock data(indian stocks) : ``` from alpha_vantage.timeseries import TimeSeries ts = TimeSeries(key='my api key',output_format='pandas') data, meta_data = ts.get_daily_adjusted(symbol='VEDL.NS', outputsize='full') data.to_csv('/content/gdrive/My Drive/ColabNotebooks/NSE...
2020/06/21
[ "https://Stackoverflow.com/questions/62501832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13787047/" ]
there are several ways to do this, and the one I will offer are not the best or the nicest ones, but hope that they will help **1) Simply write all your data to table** You can just insert all your data to the table setting the [ConflictAlgorithm](https://pub.dev/documentation/sqflite_common/latest/sql/ConflictAlgori...
WHAT ABOUT Read Data from Sqflite and Show in datatable?
7,785
39,067,203
This seems to work fine - ``` %time a = "abc" print(a) CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 19.1 µs abc ``` This doesn't - ``` def func(): %time b = "abc" print(b) func() CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 31 µs ---------------------------------------------------...
2016/08/21
[ "https://Stackoverflow.com/questions/39067203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1500929/" ]
POST data is given in a protected Map getParams () and not the URL: ``` @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String, String>(); params.put("parametr1","value1"); params.put("parametr2","value2"); params.put("parametr3","value3"); return params;...
You want to parse a array into a boolean, you have to loop through the array like this: ``` JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray= jsonObject.getJSONArray("example"); if (jsonArray.length() != 0) { ...
7,786
70,582,851
I'm trying to create a webscraping Flask app that creates a new Webdriver instance for each user session, so that different users can scrape content from different pages. This would be simpler if the `driver.get()` and data collection happened in the same API call, but they can't due to the nature of the scraping I'll ...
2022/01/04
[ "https://Stackoverflow.com/questions/70582851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13592179/" ]
I advise you to follow many good techniques when developing a responsive webpage, here I explain to you: * **Replacing in your CSS absolute units such as px for percentages or em**. It is always much better to work with relative measurements rather than absolute ones. From my experience, I always try to work with em, ...
This is a common problem I would advise that you read up on what `viewports` are on [w3schools.com](https://www.w3schools.com/css/css_rwd_viewport.asp). A viewport is basically the visible area on a user’s device. As we both know, the visible area of a desktop is different from that of a notebook, tablet, and mobile ...
7,787
15,572,171
The python syntax of `for x in y:` to iterate over a list must somehow remember what element the pointer is at currently right? How would we access that value as I am trying to solve this without resorting to `for index, x in enumerate(y):` The technical reason why I want to do this is that I assume that `enumerate()`...
2013/03/22
[ "https://Stackoverflow.com/questions/15572171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1093485/" ]
You cannot. `for` uses the [Python iteration protocol](http://docs.python.org/2/glossary.html#term-iterator), which for lists means it'll create a *private* iterator object. That object keeps track of the position in the list. Even if you were to create the iterator explicitly with [`iter()`](http://docs.python.org/2/...
No, it uses the underlying **iterator**, which is not forced to keep track of a current index. Unless you manually incerement a counter, this is not possible: ``` idx = 0 for x in y: idx+=1 # ... ``` so, just keep with `enumerate()`
7,790
52,729,841
I have only very rudimentary experience in Python. I am trying to install the package `pyslim` (see [here on the pypi website](https://pypi.org/project/pyslim/)). I did ``` $ pip install pyslim Requirement already satisfied: pyslim in ./Library/Python/2.7/lib/python/site-packages/pyslim-0.1-py2.7.egg (0.1) Requiremen...
2018/10/09
[ "https://Stackoverflow.com/questions/52729841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2051137/" ]
Take a look to [this other question](https://stackoverflow.com/questions/49228744/attributeerror-module-attr-has-no-attribute-s) that is related to the `attrs` package. In your case, you have `attr` and `attrs` installed at the same time, and they are incompatible between them, so python is unable to resolve the packa...
First uninstall pyslim. Use "pip uninstall pyslim". Then try installing again using "conda install -c conda-forge pyslim" Refer <https://anaconda.org/conda-forge/pyslim>
7,793
1,075,905
My first attempt at jython is a java/jython project I'm writing in eclipse with pydev. I created a java project and then made it a pydev project by the RightClick project >> pydev >> set as... you get the idea. I then added two source folders, one for java and one for jython, and each source folder has a package. And ...
2009/07/02
[ "https://Stackoverflow.com/questions/1075905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Jythonc doesn't exist anymore, it has been forked off to another project called [Clamp](http://github.com/groves/clamp/), but with that said... > > ...you can pre-compile > your python scripts to .class files > using: > > > jython [jython home]/Lib/compileall.py > [the directory where you keep your > python cod...
Following the "Accessing Jython from Java Without Using jythonc" tutorial it became possible to use the jython modules inside java code. The only tricky point is that the \*.py modules do not get compiled to \*.class files. So it turns out to be exotic scripting inside java. The performance may of course degrade vs jyt...
7,794
68,654,385
This is my code to read the LDS sensor. LDS sensor is used to estimate the distance from robot to walls. I can print the data(estimate distance) in the terminal but I cant write it in the csv file automatically. I would like to write about 1000 data into csv file by using python code [enter image description here](http...
2021/08/04
[ "https://Stackoverflow.com/questions/68654385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16594158/" ]
Outputting a topic formatted as csv is built into `rostopic echo`, the -p flag [rostopic\_echo](http://wiki.ros.org/rostopic#rostopic_echo). You can redirect the terminal output to a file instead of the terminal with `>` So to save `/scan` to csv you could just run the following in a terminal: ``` rostopic echo -p /s...
In a more classic ROS style, do all your setup in the "main" function, have global variables for either the returned values of callbacks or for initialized parameters, and do the processing for all your received msgs in your callbacks or timers. ```py #! /usr/bin/env python # lds_to_csv_node.py import rospy import cs...
7,795
17,891,704
What does the [None] do in this code? ``` public class Example { //Java public Example (int _input, int _outputs){ //Java scratch = [None] * (_input + _outputs); //Python Code ``` I'm porting a python implementation into Java and need to better understand what this means....
2013/07/26
[ "https://Stackoverflow.com/questions/17891704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2624276/" ]
``` scratch = [None] * (_input + _outputs) ``` This makes a list of length `_input + _outputs`. Each element in this list is a `None` object. This list is assigned to a variable, named `scratch`
``` [value] * number ``` means list of `number` elements, each of them is `value`. So your code means list of `(_input + _outputs)` `None`'s `null` is closest thing to Python's `None` I know.
7,796
3,330,280
I'm weaving my c code in python to speed up the loop: ``` from scipy import weave from numpy import * #1) create the array a=zeros((200,300,400),int) for i in range(200): for j in range(300): for k in range(400): a[i,j,k]=i*300*400+j*400+k #2) test on c code to access the array code=""" fo...
2010/07/25
[ "https://Stackoverflow.com/questions/3330280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389799/" ]
You could replace the 3 for-loops with ``` grid=np.ogrid[0:200,0:300,0:400] a=grid[0]*300*400+grid[1]*400+grid[2] ``` The following suggests this may result in a ~68x (or better? see below) speedup: ``` % python -mtimeit -s"import test" "test.m1()" 100 loops, best of 3: 17.5 msec per loop % python -mtimeit -s"impor...
The problem is that you are printing out 2.4 million numbers to the screen in your C code. This is of course going to take a while because the numbers have to be converted into strings and then printed to the screen. Do you really need to print them all to the screen? What is your end goal here? For a comparison, I tr...
7,798
74,091,484
I am trying to complete a project with javascript for which I need to import a library, however, npm is giving me errors whenever I try to use it. the error: ``` npm WARN deprecated [email protected]: this library is no longer supported npm WARN deprecated [email protected]: Please upgrade to version 7 or higher. Older ...
2022/10/17
[ "https://Stackoverflow.com/questions/74091484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17289555/" ]
You wrote that you need a *"function that sorts a List of integers"*, but in your code you pass a list **of lists** to `binsort`. This only makes sense if those sublists represent digits of a number. It makes no more sense when these digits are no single digits anymore. Either: * You sort a list of integers like `[142...
``` def bucketsort(a): # Create empty buckets buckets = [[] for _ in range(10)] # Sort into buckets for i in a: buckets[i].append(i) # Flatten buckets a.clear() for bucket in buckets: a.extend(bucket) return a ```
7,803
26,709,731
I'm writing a Google App Engine project in Python with Flask. Here's my directory structure for a Hello, World! app (contents of third party libraries ommitted for brevity's sake): ``` project_root/ flask/ jinja2/ markupsafe/ myapp/ __init__.py simplejson/ werkzeug/ app.yaml its...
2014/11/03
[ "https://Stackoverflow.com/questions/26709731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2752467/" ]
try to add the full path to your lib, like here `sys.path[0:0] = ['/home/user/project_root/lib']`
I've actually run into this problem a number of time when writing my own Google App Engine® products before. My solution was to cat the files together to form one large python file. The command to do this is: ``` cat *.py ``` Of course, you may need to fix up the import statements inside the individual files. This c...
7,804
22,752,521
I'm trying to setup an application webserver using uWSGI + Nginx, which runs a Flask application using SQLAlchemy to communicate to a Postgres database. When I make requests to the webserver, every other response will be a 500 error. The error is: ``` Traceback (most recent call last): File "/var/env/argos/lib/pyt...
2014/03/31
[ "https://Stackoverflow.com/questions/22752521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1097920/" ]
The issue ended up being uwsgi's forking. When working with multiple processes with a master process, uwsgi initializes the application in the master process and then copies the application over to each worker process. The problem is if you open a database connection when initializing your application, you then have m...
As an alternative you might dispose the engine. This is how I solved the problem. Such issues may happen if there is a query during the creation of the app, that is, in the module that creates the app itself. If that states, the engine allocates a pool of connections and then uwsgi forks. By invoking 'engine.dispose(...
7,809
28,511,485
I am not super experienced in writing code. Could someone help me out? I am trying to write some simple python to work with some GPS coordinates. Basically I want it to check if the gps is +or- ten feet to my a point then print if it is true. Think I got that part figured out but I am not sure about this part. After t...
2015/02/14
[ "https://Stackoverflow.com/questions/28511485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2798178/" ]
Just wrap it in a condition check within the if. Not language specific, but the general idea ``` if <in coord condition> if <not printed condition> print set print condition else clear print condition ```
If your syntax &c were corrected (those strings are definitely wrong) you'd be checking for a square, not a circle. Assuming `point_lat`, `gps_lat`, &c, are all numbers (not strings), and expressed in feet (and assuming `_log` is a typo for `_lon`, standing for "longitude"), you'd need: ``` import math if math.hypot...
7,815
32,884,277
The code is: ``` import sys execfile('test.py') ``` In test.py I have: ``` import zipfile with zipfile.ZipFile('test.jar', 'r') as z: z.extractall("C:\testfolder") ``` This code produces: ``` AttributeError ( ZipFile instance has no attribute '__exit__' ) # edited ``` The code from "test.py" works when ru...
2015/10/01
[ "https://Stackoverflow.com/questions/32884277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3438538/" ]
I made my code on python 2.7 but when I put it on my server which use 2.6 I have this error : `AttributeError: ZipFile instance has no attribute '__exit__'` For solve this problems I use Sebastian's answer on this post : [Making Python 2.7 code run with Python 2.6](https://stackoverflow.com/questions/21268470/making-...
According to the Python documentation, [`ZipFile.extractall()`](https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.extractall) was added in version 2.6. I expect that you'll find that you are running a different, older (pre 2.6), version of Python than that which idle is using. You can find out which versio...
7,820
41,991,602
I have been trying to make a program that runs over a dictionary which makes anagrams from an inputted string. I found most of the code to this problem here [Algorithm to generate anagrams](https://stackoverflow.com/questions/55210/algorithm-to-generate-anagrams) but i need to have the program only output a line of max...
2017/02/01
[ "https://Stackoverflow.com/questions/41991602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7503133/" ]
This is a slight work around, however if you only want to *filter* out words that have a length shorter than a specified argument, then you could make a change in your programs main. Your program currently says: ``` for word in words.anagram(letters): print word ``` You could change your program to say: ``` for...
I don't like to make programs `for` programmers, usually. To the best of my understanding: ``` import random word = "scramble" scramble = list(word) for i in range(len(scramble)): char = scramble.pop(i) scramble.insert(random.randint(0,len(word)),char) print(''.join(scramble)) ``` This will scramble the `...
7,821
4,145,331
I am tring to call the cmd command "move" from python. ``` cmd1 = ["move", spath , npath] startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen(cmd1, startupinfo=startupinfo) ``` While the comammand works in the cmd. I can move files. With this py...
2010/11/10
[ "https://Stackoverflow.com/questions/4145331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354399/" ]
`move` is built-in into the `cmd` shell, so it's not a file command that you can call this way. You could use [`shutil.move()`](http://docs.python.org/library/shutil.html#shutil.move), but this "forgets" all alternate data stream, ACLs etc.
try to use `cmd1 = ["cmd", "/c", "move", spath, npath]`
7,822
74,053,822
I want to calculate QTD values from different columns based on months in a pandas dataframe. Code: ``` data = {'month': ['April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'January', 'February', 'March'], 'kpi': ['sales', 'sales quantity', 'sales', 'sales', 'sales', 'sales',...
2022/10/13
[ "https://Stackoverflow.com/questions/74053822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16134366/" ]
Use [`numpy.select`](https://numpy.org/doc/stable/reference/generated/numpy.select.html) for new column and then use [`GroupBy.cumsum`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.GroupBy.cumsum.html): ``` g = pd.to_datetime(df['month'], format='%B').dt.to_period('Q') m1 = df['month'...
You can use a dictionary to map the quarter to your columns, then [indexing lookup](https://pandas.pydata.org/docs/user_guide/indexing.html#indexing-lookup) and [`groupby.cumsum`](https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.cumsum.html): ``` quarters = {1: 're9+3', 2: 're', 3: 're...
7,823
46,756,555
I made a dictionary using python ``` dictionary = {'key':'a', 'key':'b'}) print(dictionary) print (dictionary.get("key")) ``` When run this code then shows the last value of dictionary, Is there any way to access the first value of dictionary if keys of both elements of dictionary are same.
2017/10/15
[ "https://Stackoverflow.com/questions/46756555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4450400/" ]
It seems I ran into existing [issue](https://github.com/spring-projects/spring-boot/issues/10647) So I used the solution provided by [@wilkinsona](https://github.com/wilkinsona) to resolve it. I added `configuration` with `mainClass` and project was successfully built. ``` <build> <plugins> <plugin> ...
You can use this way . You add a configuration to pom but this way only works in the compiler. It doesnt work real world. If you want to use .jar or .war . It will not work. **You must add com.lapots.breed.hero.journey file under java file.** Then It always works
7,824
60,927,188
Having recently upgraded a Django project from 2.x to 3.x, I noticed that the `mysql.connector.django` backend (from `mysql-connector-python`) no longer works. The last version of Django that it works with is 2.2.11. It breaks with 3.0. I am using `mysql-connector-python==8.0.19`. When running `manage.py runserver`, t...
2020/03/30
[ "https://Stackoverflow.com/questions/60927188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6619548/" ]
For `Django 3.0` and `Django 3.1` I managed to have it working with `mysql-connector-python 8.0.22`. See this <https://dev.mysql.com/doc/relnotes/connector-python/en/news-8-0-22.html>.
Connector/Python still supports Python 2.7, which was dropped by Django 3. We are currently working on adding support for Django 3, stay tunned.
7,830
11,144,245
I realize that this is a known [problem](http://python.6.n6.nabble.com/Internationalization-and-caching-not-working-td84364.html), [problem](http://www.mail-archive.com/[email protected]/msg63780.html) but I still have not found and adequate solution. I want to use the @cache\_page for a some views in my D...
2012/06/21
[ "https://Stackoverflow.com/questions/11144245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791335/" ]
1. How long is a string? It depends on how the server is configured. And "application" could be a single form or hundreds. Only a test can tell. In general: build a [high performance server](http://www.wissel.net/blog/d6plinks/SHWL-7RB3P5) preferably with 64Bit architecture and lots of RAM. Make that RAM [available for...
1. It depends on the server setup, I have i.e XPage extranet with 12000 registered users spanning over aprox 20 XPage applications. That runs on 1 Windows 2003 server with 4GB Ram and quad core cpu. Data aount is about 60GB over these 20 applications. No Daos, no beans just SSJS. Performance is excellent. So when I upg...
7,833
62,552,693
I'm a newbie when it comes to Python. I have some python code in an azure sql notebook which gets run by a scheduled job. The job notebook runs a couple of sql notebooks. If the 1st notebook errors I want an exception to be thrown so that the scheduled job shows as failed and I don't want the subsequent sql notebook to...
2020/06/24
[ "https://Stackoverflow.com/questions/62552693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989075/" ]
**Option 1**: Simply don't catch the exception. Just run the first command without the `try` ... `except`, and let the exception bubble up in the normal way. If it is raised (i.e. thrown), then the second command (or anything after it) will not be run. You would then only catch exceptions with the second command. ``` ...
Sorry - I did not read the question carefully enough. My original answer is not what you are looking for. I wrote: > > Add a `return` statement: > > > > ``` > try: > # ... > except Exception as error: > print f'Failure in STA_1S ({error})' > return > > ``` > > But you not only want to leave the ...
7,834
11,026,205
I'm currently concatenating adjacent cells in excel to repeat common HTML elements and divs - it feels like I've gone down a strange excel path in developing my webpage, and I was wondering if an experienced web designer could let me know how I might accomplish my goals for the site with a more conventional method (aim...
2012/06/14
[ "https://Stackoverflow.com/questions/11026205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1152532/" ]
Wow, that sounds really painful. If all you have is 40 images that you want to generate HTML for, and the rest of your site is static, it may be simplest just to have a single text file with each line containing an image file path. Then, use Python to look at each line, generate the appropriate HTML, and concatenate i...
You could keep these and only these images in their own directory and then use simple shell scripts to generate that section of static html. Assuming you already put the files in place maybe like this: ``` cp <all_teh_kitteh_images> images/grid ``` This command will generate html ``` for file in images/grid/*.jpg ...
7,837
24,294,015
I tried to install psycopg2 for python2.6 but my system also has 2.7 installed. I did ``` >sudo -E pip install psycopg2 Downloading/unpacking psycopg2 Downloading psycopg2-2.5.3.tar.gz (690kB): 690kB downloaded Running setup.py (path:/private/var/folders/yw/qn50zv_151bfq2vxhc60l8s5vkymm3/T/pip_build_root/psycopg2...
2014/06/18
[ "https://Stackoverflow.com/questions/24294015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1312080/" ]
You can use [shoryuken](https://github.com/phstc/shoryuken/). It will consume your messages continuously until your queue has messages. ``` shoryuken -r your_worker.rb -C shoryuken.yml \ -l log/shoryuken.log -p shoryuken.pid -d ```
As you've probably already discovered, there isn't one obvious **right way™** to handle this kind of thing. It depends a lot on what work you do for each job, the size of your app and infrastrucure, and your personal preferences on APIs, message queuing philosophies, and architecture. That said, I'd probably lean towa...
7,838
46,582,577
I need help. I'm trying to filter out and write to another csv file that consists of data which collected after 10769s in the column elapsed\_seconds together with the acceleration magnitude. However, I'm getting KeyError: 0... ``` import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_...
2017/10/05
[ "https://Stackoverflow.com/questions/46582577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2995019/" ]
change this line ``` csv.write( str(data[data.elapsed_seconds > 10769][i]) + ", " + str(data[data.m][i]) + "\n" ) ``` To this: ``` csv.write( str(data[data.elapsed_seconds > 10769].iloc[i]) + ", " + str(data[data.m].iloc[i]) +"\n" ) ``` Also, notice that you are not increasing `i`, like this `i += 1...
I had the same issue, which was resolved by following this [recommendation](https://github.com/influxdata/influxdb-python/issues/497). In short, instead of `df[0]`, do an explicit `df['columnname']`
7,839
72,429,361
Hello I am beginner programmer in python and I am having trouble with this code. It is a rock paper scissors game I am not finished yet but it is supposed to print "I win" if the user does not pick rock when the program picks scissors. But when the program picks paper and the user picks rock it does not print "I win". ...
2022/05/30
[ "https://Stackoverflow.com/questions/72429361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19223648/" ]
I had same issue with "testImplementation 'io.cucumber:cucumber-java8:7.3.3'" (gradle). I changed to "testImplementation 'io.cucumber:cucumber-java8:7.0.0'" and when I changed it and ran again test then I got a correct error message about the real problem that was "Unrecognized field 'programId'" (for example) and the...
I installed Jackson JDK8 repository in my pom.xml file and it fixed this problem: <https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jdk8>
7,840
71,979,765
If I have python list like ```py pyList=[‘[email protected]’,’[email protected]’] ``` And I want it to convert it to json array and add `{}` around every object, it should be like that : ```py arrayJson=[{“email”:”[email protected]”},{“ email”:”[email protected]”}] ``` any idea how to do that ?
2022/04/23
[ "https://Stackoverflow.com/questions/71979765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18918903/" ]
You can achieve this by using built-in [json](https://docs.python.org/3/library/json.html#json.dumps) module ``` import json arrayJson = json.dumps([{"email": item} for item in pyList]) ```
Try to Google this kind of stuff first. :) ``` import json array = [1, 2, 3] jsonArray = json.dumps(array) ``` By the way, the result you asked for can not be achieved with the list you provided. You need to use python dictionaries to get json objects. The conversion is like below ``` Python -> JSON list -> array...
7,841
34,328,759
I'd like to put together a command that will print out a string of 32 hexadecimal digits. I've got a Python script that works: ``` python -c 'import random ; print "".join(map(lambda t: format(t, "02X"), [random.randrange(256) for x in range(16)]))' ``` This generates output like: ``` 6EF6B30F9E557F948C402C89002C7C...
2015/12/17
[ "https://Stackoverflow.com/questions/34328759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1002430/" ]
If you are looking for a single command and have openssl installed, see below. Generate random 16 bytes (32 hex symbols) and encode in hex (also -base64 is supported). ``` openssl rand -hex 16 ```
If you want to generate output of **arbitrary length, including even/odd number of characters**: ```sh cat /dev/urandom | hexdump --no-squeezing -e '/1 "%x"' | head -c 31 ``` Or to maximize efficiency over readability/composeability: ``` hexdump --no-squeezing -e '/1 "%x"' -n 15 /dev/urandom ```
7,843
62,175,053
I'm working on Windows 7 64bits with Anaconda 3. On my environment Nifti, I have installed Tensorflow 2.1.0, Keras 2.3.1 and Python 3.7.7. On Visual Studio Code there is a problem with all of these imports: ``` from tensorflow.python.keras.models import Model from tensorflow.keras.layers import Input, Dense, Conv2D, ...
2020/06/03
[ "https://Stackoverflow.com/questions/62175053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68571/" ]
I had tried your code, and my suggestion is to switch from pylint to other lintings. Keep away from that stupid linting. Maybe you can take a try of flake8: "python.linting.pylintEnabled": false, "python.linting.flake8Enabled": true, This problem occurs because the pylint can't search the path of Anaconda, as 'tensorf...
**If you're using Anaconda Virtual Environment** 1. Close all **Open Terminals** in VS Code 2. Open a new terminal 3. Write the path to your activate folder of Anaconda in Terminal > > Example: `E:/Softwares/AnacondaFolder/Scripts/activate` > > > This should now show **(base)** written at the start of your folde...
7,853
14,737,499
I followed the top solution to Flattening an irregular list of lists in python ([Flatten (an irregular) list of lists](https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists-in-python)) using the following code: ``` def flatten(l): for el in l: if isinstance(el, collections.Iterable...
2013/02/06
[ "https://Stackoverflow.com/questions/14737499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1009215/" ]
Add a `data-select` attribute to those links: ``` <a href="#contact" data-select="[email protected]">Send a mail to mother!</a> <a href="#contact" data-select="[email protected]">Send a mail to father!</a> <a href="#contact" data-select="[email protected]">Send a mail to sister!</a> <a href="#contact" data-select="brother@m...
If the order is allways the same you can do this ``` $("a").click(function(){ $("#recipient").prop("selectedIndex", $(this).index()); }); ``` Otherwise do this by defining the index on the link: ``` <a href="#contact" data-index="0">Send a mail to mother!</a> <a href="#contact" data-index="1">Send a mail to fat...
7,854
50,925,488
so I have some problems with my dictionaries in python. For example I have dictionary like below: ``` d1 = {123456:xyz, 892019:kjl, 102930491:{[plm,kop]} d2= {xyz:987, kjl: 0902, plm: 019240, kop:09829} ``` And I would like to have nested dictionary that looks something like that. ``` d={123456 :{xyz:987}, 892019:{...
2018/06/19
[ "https://Stackoverflow.com/questions/50925488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9961204/" ]
If you have two DNS names that can be used as a active/active or active/passive for your API endpoints, you can add them to a Traffic Manager profile and set the routing method you want to use. As indicated in an earlier answer, use only the DNS name and not the protocol identifier (http/https) when you add an endpoint...
Traffic manager only wants the DNS name (FQDN) for external endpoints not the protocol. So drop the http: or https: from your API management address and it will accept that as an external endpoint. Or is your problem not with adding the endpoint, but with the health endpoint monitoring? That can happen as the endpoin...
7,857
45,199,083
I am new to python and I had no difficulty with one example of learning try and except blocks: ``` try: 2 + "s" except TypeError: print "There was a type error!" ``` Which outputs what one would expect: ``` There was a type error! ``` However, when trying to catch a syntax error like this: ``` try: p...
2017/07/19
[ "https://Stackoverflow.com/questions/45199083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5941556/" ]
The reason you can not use a try/except block to capture SyntaxErrors is that these errors happen before your code executes. High level steps of Python code execution 1. Python interpreter translates the Python code into executable instructions. (Syntax Error Raised) 2. Instructions are executed. (Try/Except block ex...
The answer is easy cake: The `SyntaxError` nullifies the `except` and `finally` statement because they are inside of a string.
7,858
44,503,913
This is literally day 1 of python for me. I've coded in VBA, Java, and Swift in the past, but I am having a particularly hard time following guides online for coding a pdf scraper. Since I have no idea what I am doing, I keep running into a wall every time I want to test out some of the code I've found online. **Basi...
2017/06/12
[ "https://Stackoverflow.com/questions/44503913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8149767/" ]
It seems that the tutorials you are following make use of python 2. There are usually few noticable differences, the the biggest is that in python 3, print became a funtion so ``` print() ``` I would recomment either changing you version of python or finding a tutorial for python 3. Hope this helps
Here [Pdfminer python 3.5](https://stackoverflow.com/questions/39854841/pdfminer-python-3-5/40877143#40877143) an example, how to extract informations from a PDF. But it does not solve the problem with tables you want to export to Excel. Commercial products are probably better in doing that...
7,859
61,365,111
friends. Yesterday I used the below python piece of code to retrieve some comments on youtube videos sucessfully: ``` !pip install --upgrade google-api-python-client import os import googleapiclient.discovery DEVELOPER_KEY = "my_key" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" youtube = googleap...
2020/04/22
[ "https://Stackoverflow.com/questions/61365111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13380927/" ]
The problem is on the server side as discussed [here](https://github.com/googleapis/google-api-python-client/issues/882). Until the server problem is fixed, this solution may help (as suggested by [@busunkim96](https://github.com/googleapis/google-api-python-client/issues/882#issuecomment-618514530)): First, download ...
I was able to resolve this issue by putting making putting `static_discovery=False` into the build command Examples: **Previous Code** `self.youtube = googleapiclient.discovery.build(API_SERVICE_NAME, API_VERSION, credentials=creds` **New Code** `self.youtube = googleapiclient.discovery.build(API_SERVICE_NAME, API_V...
7,861
47,043,606
I created and saved simple nn in tensorflow: ``` import tensorflow as tf import numpy as np x = tf.placeholder(tf.float32, [1, 1],name='input_placeholder') y = tf.placeholder(tf.float32, [1, 1],name='input_placeholder') W = tf.get_variable('W', [1, 1]) layer = tf.matmul(x, W, name='layer') loss = tf.subtract(y,layer)...
2017/10/31
[ "https://Stackoverflow.com/questions/47043606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1700890/" ]
Just add `save_relative_paths=True` when creating `tf.train.Saver()`: ``` # original code: all_saver = tf.train.Saver() all_saver = tf.train.Saver(save_relative_paths=True) ``` Please refer to [official doc](https://www.tensorflow.org/api_docs/python/tf/train/Saver) for more details.
You could try to restore by: ``` with tf.Session() as sess: saver = tf.train.import_meta_graph(/path/to/test.meta) saver.restore(sess, "path/to/checkpoints/test") ``` In this case, because you put the name of the checkpoint is "test" so you got 3 files: ``` test.data-00000-of-00001 test.index test.meta ```...
7,862
45,385,832
I downloaded nitroshare.tar.gz file as i want to install it on my Kali Linux. I followed up instructions as said on there github page to install it & downloaded all the packages that are required for the installation. When i use cmake command it is showing me this error: ``` Unknown cmake command qt5_wrap_ui ``` H...
2017/07/29
[ "https://Stackoverflow.com/questions/45385832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8282220/" ]
CMake doesn't know the function `qt5_wrap_ui` because you did not import Qt5 or any of the functions it defines. Before calling `qt5_wrap_ui`, add this: ``` find_package(Qt5 COMPONENTS Widgets REQUIRED) ```
I used this line find\_package(Qt5Widgets) In my Cmakelist.txt file I found this on their Document Page of Qt5
7,864
16,300,464
I have two classes in a python source file. ``` class A: def func(self): pass class B: def func(self): pass def run(self): self.func() ``` When my cursor is in class B's `'self.func()'` line, if press `CTRL`+`]`, it goes to class A's func method. But instead I would like it to go B's ...
2013/04/30
[ "https://Stackoverflow.com/questions/16300464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323000/" ]
The `<C-]>` command jumps to the *first* tag match, but it also takes a `[count]` to jump to another one. Alternatively, you can use the `g<C-]>` command, which (like the `:tjump` Ex command) will list all matches and query you for where you want to jump to (when there are multiple matches).
Have a look at [Jedi-Vim](https://github.com/davidhalter/jedi-vim). It defines a new “go to definition” command, that will properly handle those situations.
7,865
3,040,716
I have a list of regexes in python, and a string. Is there an elegant way to check if the at least one regex in the list matches the string? By elegant, I mean something better than simply looping through all of the regexes and checking them against the string and stopping if a match is found. Basically, I had this co...
2010/06/14
[ "https://Stackoverflow.com/questions/3040716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363078/" ]
``` import re regexes = [ "foo.*", "bar.*", "qu*x" ] # Make a regex that matches if any of our regexes match. combined = "(" + ")|(".join(regexes) + ")" if re.match(combined, mystring): print "Some regex matched!" ```
``` import re regexes = [ # your regexes here re.compile('hi'), # re.compile(...), # re.compile(...), # re.compile(...), ] mystring = 'hi' if any(regex.match(mystring) for regex in regexes): print 'Some regex matched!' ```
7,866
71,649,019
I've went through multiple excamples of data classification however either I didn't get it or those are not applicable in my case. I have a list of values: ``` values = [-130,-110,-90,-80,-60,-40] ``` All I need to do is to classify `input` integer value to appropriate "bin". E.g., `input=-97` should get `index 1`...
2022/03/28
[ "https://Stackoverflow.com/questions/71649019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11191256/" ]
One of your `classes`-props is a `boolean`. You cannot push a `boolean` (true/false) to `className`. You could `console.log(classes)`, then you will see, which prop causes the warning.
It means at least one of the className values is boolean instead of string. we can not say anything more with this piece of code.
7,876
47,508,790
I have the following JSON saved in a text file called test.xlsx.txt. The JSON is as follows: ``` {"RECONCILIATION": {0: "Successful"}, "ACCOUNT": {0: u"21599000"}, "DESCRIPTION": {0: u"USD to be accrued. "}, "PRODUCT": {0: "7500.0"}, "VALUE": {0: "7500.0"}, "AMOUNT": {0: "7500.0"}, "FORMULA": {0: "3 * 2500 "}} ``` T...
2017/11/27
[ "https://Stackoverflow.com/questions/47508790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3163920/" ]
Your txt file does not contain valid JSON. For starters, keys must be strings, not numbers. The `u"..."` notation is not valid either. You should fix your JSON first (maybe run it through a linter such as <https://jsonlint.com/> to make sure it's valid).
As Mike mentioned, your text file is not a valid JSON. It should be like: ``` {"RECONCILIATION": {"0": "Successful"}, "ACCOUNT": {"0": "21599000"}, "DESCRIPTION": {"0": "USD to be accrued. "}, "PRODUCT": {"0": "7500.0"}, "VALUE": {"0": "7500.0"}, "AMOUNT": {"0": "7500.0"}, "FORMULA": {"0": "3 * 2500 "}} ``` Note: k...
7,879
31,303,728
Using pandas 0.16.2 on python 2.7, OSX. I read a data-frame from a csv file like this: ``` import pandas as pd data = pd.read_csv("my_csv_file.csv",sep='\t', skiprows=(0), header=(0)) ``` The output of `data.dtypes` is: ``` name object weight float64 ethnicity object dtype: object ``` I was expecting...
2015/07/08
[ "https://Stackoverflow.com/questions/31303728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/228177/" ]
There is probably whitespace in your strings, for example, ``` data = pd.DataFrame({'ethnicity':[' Asian', ' Asian']}) data.loc[data['ethnicity'].str.contains('Asian'), 'ethnicity'].tolist() # [' Asian', ' Asian'] print(data[data['ethnicity'].str.contains('Asian')]) ``` yields ``` ethnicity 0 Asian 1 As...
You might try this: ``` data[data['ethnicity'].str.strip()=='Asian'] ```
7,880
56,191,697
What is the `__weakrefoffset__` attribute for? What does the integer value signify? ``` >>> int.__weakrefoffset__ 0 >>> class A: ... pass ... >>> A.__weakrefoffset__ 24 >>> type.__weakrefoffset__ 368 >>> class B: ... __slots__ = () ... >>> B.__weakrefoffset__ 0 ``` All types seem to have this attribu...
2019/05/17
[ "https://Stackoverflow.com/questions/56191697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674039/" ]
In CPython, the layout of a simple type like `float` is three fields: its type pointer, its reference count, and its value (here, a `double`). For `list`, the value is three variables (the pointer to the separately-allocated array, its capacity, and the used size). These types do not support attributes or weak referenc...
It is referenced in [PEP 205](https://www.python.org/dev/peps/pep-0205/) here: > > Many built-in types will participate in the weak-reference management, and any extension type can elect to do so. **The type structure will contain an additional field which provides an offset into the instance structure which contains...
7,881
47,013,083
I am trying to establish a Web-Socket connection to a server and enter into receive mode.Once the client starts receiving the data, it immediately closes the connection with below exception ``` webSoc_Received = await websocket.recv() File "/root/envname/lib/python3.6/site-packages/websockets/protocol.py", line...
2017/10/30
[ "https://Stackoverflow.com/questions/47013083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3913710/" ]
You can use hidden property or `*ngIf` directive : ```html <app-form></app-form> <app-results *ngIf="isOn"></app-results> <app-contact-primary *ngIf="!isOn"></<app-contact-primary> <app-contact-second *ngIf="!isOn"></app-contact-second> <button pButton label="Contact" (click)="isOn= false">Contact</button> <button pB...
Just make the variable true and false ```html <button pButton label="Contact" (click)="isOn = true">Contact</button> <button pButton label="Results" (click)="isOn = false">Results</button> ```
7,882
73,003,060
I made a simple example of taking a screenshot. I debugged this, but there was an error. cord ``` import pyautogui import PIL pyautogui.screenshot('screenshot.png') ``` error ``` The Pillow package is required to use this function. ``` I've already set up a pillow and version is 9.2.0(lastest version) I'm using...
2022/07/16
[ "https://Stackoverflow.com/questions/73003060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19560998/" ]
I've just installed everything new and it's fixed!
Try this, it should work perfectly on my side. ``` import pyautogui myScreenshot = pyautogui.screenshot() myScreenshot.save(r'D:\\image.png') ``` [![enter image description here](https://i.stack.imgur.com/7aGpM.png)](https://i.stack.imgur.com/7aGpM.png)
7,884
57,813,557
I would like to multiply every element in a numpy array by a constant raised to the power of the index of the array element without a for loop. I am using python 2.7. I am new to this and can use a for loop by trying to not do that for no real reason. This for loop would solve the problem ```py x = 3 for i in range...
2019/09/05
[ "https://Stackoverflow.com/questions/57813557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12027672/" ]
What you want is something like this: ``` data = [ [{'Status': 'active', 'id': '0f1fb86da9c7ee380'}], [{'Status': 'active', 'id': '0d6b330e4960c3382'}, {'Status': 'active', 'id': '033cfb634e595ccfa'}], [{'Status': 'active', 'id': '0457f623cbb9f7c95'}], [{'Status': 'active', 'id': '01b69eb6a3048f749...
You can also use list comprehension to achieve this. ``` output = [[item["id"] for item in items] for items in data] ```
7,885
1,653,460
What would be the best way to handle lightweight crash recovery for my program? I have a Python program that runs a number of test cases and the results are stored in a dictionary which serves as a cache. If I could save (and then restore) each item that is added to the dictionary, I could simply run the program agai...
2009/10/31
[ "https://Stackoverflow.com/questions/1653460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165495/" ]
There's no good way to guard against "your program crashing **while** writing a checkpoint to a file", but why should you worry so much about **that**?! What ELSE is your program doing at that time BESIDES "saving checkpoint to a file", that could easily cause it to crash?! It's hard to beat `pickle` (or `cPickle`) fo...
The pickle module supports serializing objects to a file (and loading from file): <http://docs.python.org/library/pickle.html>
7,888
34,460,369
I had a bunch of bash scripts in a directory that I "backed up" doing `$ tail -n +1 -- *.sh` The output of that tail is something like: ``` ==> do_stuff.sh <== #! /bin/bash cd ~/my_dir source ~/my_dir/bin/activate python scripts/do_stuff.py ==> do_more_stuff.sh <== #! /bin/bash cd ~/my_dir python scripts/do_more_stu...
2015/12/25
[ "https://Stackoverflow.com/questions/34460369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/845169/" ]
Presume your backup file is named backup.txt ``` perl -ne "if (/==> (\S+) <==/){open OUT,'>',$1;next}print OUT $_" backup.txt ``` Above version is for Windows fixed version on \*nix: ``` perl -ne 'if (/==> (\S+) <==/){open OUT,">",$1;next}print OUT $_' backup.txt ```
``` #!/bin/bash while read -r line; do if [[ $line =~ ^==\>[[:space:]](.*)[[:space:]]\<==$ ]]; then out="${BASH_REMATCH[1]}" continue fi printf "%s\n" "$line" >> "$out" done < backup.txt ``` Drawback: extra blank line at the end of every created file except the last one.
7,895
14,075,337
I have a csv file with date, time., price, mag, signal. 62035 rows; there are 42 times of day associated to each unique date in the file. For each date, when there is an 'S' in the signal column append the corresponding price at the time the 'S' occurred. Below is the attempt. ``` from pandas import * from numpy imp...
2012/12/28
[ "https://Stackoverflow.com/questions/14075337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1374969/" ]
Try something like this: ``` for i in range(len(idf.index)): value = idf.index[i][0] ``` Same thing for the iteration with the `j` index variable. As has been pointed, you can't reference the iteration index in the expression to be iterated, and besides you need to perform a very specific iteration (traversing ove...
It's because `i` is not yet defined, just like the error message says. In this line: ``` for i in idf.index[i][0]: ``` You are telling the Python interpreter to iterate over all the values yielded by the list returning from the expression `idf.index[i][0]` but you have not yet defined what `i` is (although you are ...
7,896
70,352,477
I am wondering if it is possible to do grouping of lists in python in a simple way without importing any libraries. and example of input could be: ```py a="0 0 1 2 1" ``` and output ``` [(0,0),(1,1),(2)] ``` I am thinking something like the implementation of itertools groupby ```py class groupby: # [k for k...
2021/12/14
[ "https://Stackoverflow.com/questions/70352477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12868928/" ]
I just realized how to do it. ```py {k:[v for v in a.split() if v == k] for k in set(a.split())} ``` or ```py [tuple(v for v in a.split() if v == k) for k in set(a.split())] ``` however - this solution can not be used on dictionaties because dicts are not hashable - so maybe thats one of the reasons why the itert...
How about using `a.split(' ')` then using for loop to do that?
7,901
63,315,233
If I have two matrices a and b, is there any function I can find the matrix x, that when dot multiplied by a makes b? Looking for python solutions, for matrices in the form of numpy arrays.
2020/08/08
[ "https://Stackoverflow.com/questions/63315233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12818944/" ]
This problem of finding X such as `A*X=B` is equivalent to search the "inverse of A", i.e. a matrix such as `X = Ainverse * B`. For information, in math `Ainverse` is noted `A^(-1)` ("A to the power -1", but you can say "A inverse" instead). In numpy, this is a builtin function to find the inverse of a matrix `a`: `...
if `A` is a full rank, square matrix ``` import numpy as np from numpy.linalg import inv X = inv(A) @ B ``` if not, then such a matrix does not exist, but we can approximate it ``` import numpy as np from numpy.linalg import inv X = inv(A.T @ A) @ A.T @ B ```
7,903
3,292,643
Which is the most pythonic way to convert a list of tuples to string? I have: ``` [(1,2), (3,4)] ``` and I want: ``` "(1,2), (3,4)" ``` My solution to this has been: ``` l=[(1,2),(3,4)] s="" for t in l: s += "(%s,%s)," % t s = s[:-1] ``` Is there a more pythonic way to do this?
2010/07/20
[ "https://Stackoverflow.com/questions/3292643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/170912/" ]
How about: ``` >>> tups = [(1, 2), (3, 4)] >>> ', '.join(map(str, tups)) '(1, 2), (3, 4)' ```
The most pythonic solution is ``` tuples = [(1, 2), (3, 4)] tuple_strings = ['(%s, %s)' % tuple for tuple in tuples] result = ', '.join(tuple_strings) ```
7,904
14,897,426
My XML file test.xml contains the following tags ``` <?xml version="1.0" encoding="ISO-8859-1"?> <AppName> <author>Subho Halder</author> <description> Description</description> <date>2012-11-06</date> <out>Output 1</out> <out>Output 2</out> <out>Output 3</out> </AppName> ``` I wan...
2013/02/15
[ "https://Stackoverflow.com/questions/14897426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122840/" ]
Try [`len(dom.getElementsByTagName('out'))`](http://docs.python.org/2/library/xml.dom.html#document-objects) ``` from xml.dom.minidom import parseString file = open('test.xml','r') data = file.read() file.close() dom = parseString(data) print len(dom.getElementsByTagName('out')) ``` gives ``` 3 ```
I would recommend using lxml ``` import lxml.etree doc = lxml.etree.parse(test.xml) count = doc.xpath('count(//out)') ``` You can look up more information on XPATH [here](http://infohost.nmt.edu/tcc/help/pubs/pylxml/web/xpath.html).
7,914
56,911,541
I am new to python/flask so need your help. I have multiselect dropdown like below I have a multiselect in html file like this: ``` <select multiple id="mymultiselect" name="mymultiselect"> <option value="1">India</option> <option value="2">USA</option> <option value="3"...
2019/07/06
[ "https://Stackoverflow.com/questions/56911541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11746629/" ]
One way would be to create a pipe in the parent process. Each child process closes the write end of the pipe, then calls `read` (which blocks). When the parent process is ready, it closes both ends of its pipe. This makes all the children return from `read` and they can now close their read end of the pipe and proceed ...
For situations like this, I sometimes use [atomic](https://en.cppreference.com/w/c/atomic) operation. You can use atomic flags to notify sub-process, but it creates busy-waiting. So you can use it on a very special cases. Other method is to create an event with something like `pthread_cond_broadcast()` and `pthread_co...
7,916
45,734,960
I want to write my own small mailserver application in python with **aiosmtpd** a) for educational purpose to better understand mailservers b) to realize my own features So my question is, what is missing (besides aiosmtpd) for an **Mail-Transfer-Agent**, that can send and receive emails to/from other full MTAs ...
2017/08/17
[ "https://Stackoverflow.com/questions/45734960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6002171/" ]
The most important thing about running your own SMTP server is that you **must not be an open relay**. That means you must not accept messages from strangers and relay them to any destination on the internet, since that would enable spammers to send spam through your SMTP server -- which would quickly get you blocked. ...
You may consider the following features: * Message threading * Support for Delivery status * Support for POP and IMAP protocols * Supports for protocols such as RFC 2821 SMTP and RFC 2033 LMTP email message transport * Support Multiple message tagging * Support for PGP/MIME (RFC2015) * Support list-reply * Lets each u...
7,917
34,147,515
When playing around with the Python interpreter, I stumbled upon this conflicting case regarding the `is` operator: If the evaluation takes place in the function it returns `True`, if it is done outside it returns `False`. ``` >>> def func(): ... a = 1000 ... b = 1000 ... return a is b ... >>> a = 1000 >...
2015/12/08
[ "https://Stackoverflow.com/questions/34147515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4952130/" ]
tl;dr: ------ As the [reference manual](https://docs.python.org/3.5/reference/executionmodel.html#structure-of-a-program) states: > > A block is a piece of Python program text that is executed as a unit. > The following are blocks: a module, a function body, and a class definition. > **Each command typed interactive...
At the interactive prompt, entry are [compiled in a *single* mode](https://docs.python.org/3/library/functions.html#compile) which processes one complete statement at a time. The compiler itself (in [Python/compile.c](https://hg.python.org/cpython/file/tip/Python/compile.c)) tracks the constants in a dictionary called ...
7,920
23,819,117
I use python 3.4 and I can format strings in two ways: ``` print("%d %d" %(1, 2)) ``` and ``` print("{:d} {:d}".format(1, 2)) ``` In [documentation](https://docs.python.org/2/library/string.html) they show examples only using 'format'. Do it mean that using '%' is not good, or it does not matter which version to...
2014/05/23
[ "https://Stackoverflow.com/questions/23819117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3654650/" ]
Quoting from the [official documentation](https://docs.python.org/2/library/stdtypes.html#str.format), > > This method of string formatting is the new standard in Python 3, and should be preferred to the % formatting described in String Formatting Operations in new code. > > > So, `format` is the recommended way ...
In addition to the recommendations on the official site the format() method is more flexible, powerful and readable than operator '%'. For example: ``` >>> '{2}, {1}, {0}'.format(*'abc') 'c, b, a' >>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'} >>> 'Coordinates: {latitude}, {longitude}'.format(**coord) '...
7,921
61,417,765
Disclaimer. I am new to python and trying to learn. I have a list of dictionaries containing address information I would like to iterate over and then pass into a function as arguments. `print(data)` `[{'firstName': 'John', 'lastName': 'Smith', 'address': '123 Lane', 'country': 'United States', 'state': 'TX', 'city':...
2020/04/24
[ "https://Stackoverflow.com/questions/61417765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3950634/" ]
You already have all the logic to process a *single* data point, just expand it to *multiple* data points as shown below using a loop. ``` from usps import USPSApi, Address for item in data: kwargs = dict() kwargs['name'] = item['lastName'] kwargs['address_1'] = item['address'] kwargs['city'] = item[...
If the intention is to get the key's values in a variable: ``` d_data = [{'firstName': 'John', 'lastName': 'Smith', 'address': '123 Lane', 'country': 'United States', 'state': 'TX', 'city': 'Springfield', 'zip': '12345'}, {'firstName': 'Mary', 'lastName': 'Smith', 'address': '321 Lanet', 'country': 'United States', 's...
7,922
55,239,297
I'm never done development in a career as a software programmer I'm given this domain name on NameCheap with the server disk. Now I design Django app and trying to deploy on the server but I had problems (stated below) ``` [ E 2019-03-19 06:23:19.7356 598863/T2n age/Cor/App/Implementation.cpp:221 ]: Could not spawn p...
2019/03/19
[ "https://Stackoverflow.com/questions/55239297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10865416/" ]
When you setup a python app in cpanel, you specify the folder where you have setup the app. That will be the folder that will contain your passenger\_wsgi.py file. You have to upload your django project to that same folder. To make sure they you have uploaded to the right directory, just have this simple check\_ your `...
The answer very simple, my server is using a programme name passenger, the official website for more information: <https://www.phusionpassenger.com/> Now error very simply; **passenger can't find my application**, All I did was move my project and app folder on the same layer passenger\_wsgi.py and it works like charm...
7,923
62,903,138
Here is my attempt: ``` int* globalvar = new int[8]; void cpp_init(){ for (int i = 0; i < 8; i++) globalvar[i] = 0; } void writeAtIndex(int index, int value){ globalvar[index] = value; } int accessIndex(int index){ return globalvar[index]; } BOOST_PYTHON_MODULE(MpUtils){ def("cpp_init", &cpp_in...
2020/07/14
[ "https://Stackoverflow.com/questions/62903138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11627201/" ]
Processes can generally access only their own memory space. You can possibly use the [shared\_memory](https://docs.python.org/3/library/multiprocessing.shared_memory.html#multiprocessing.shared_memory.SharedMemory) module of multiprocessing to share the same array across processes. See example in the linked page.
The following loop will create a list of processes with consecutive first `args`, from `0` to `9`. (First process has `0`, second one `1` and so on.) ``` for i in range(0, 10): processes.append( Process( target=do_stuff, args=(i,) ) ) ``` The writing may take a list of numbers, but the call to `writeAtIn...
7,924
33,697,379
Now this could be me being **very** stupid here but please see the below code. I am trying to work out what percentage of my carb goal I've already consumed at the point I run the script. I get the totals and store them in `carbsConsumed` and `carbsGoal`. `carbsPercent` then calculates the percentage consumed. Howeve...
2015/11/13
[ "https://Stackoverflow.com/questions/33697379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4461239/" ]
Try this: ``` carbsPercent = (float(carbsConsumed) / carbsGoal) * 100 ``` The problem is that in Python 2.7, the default division mode is integer division, so 1000/1200 = 0. The way you force Python to change that is to cast at least one operand IN THE DIVISION operation to a float.
For easily portable code, in `python2`, see <https://stackoverflow.com/a/10768737/610569>: ``` from __future__ import division carbsPercent = (carbsConsumed / carbsGoal) * 100 ``` E.g. ``` $ python >>> from __future__ import division >>> 6 / 5 1.2 $ python3 >>> 6 / 5 1.2 ```
7,925
46,520,136
Is there any way to run a function from python and a function from java in one app in parallel and get the result of each function to do another process?
2017/10/02
[ "https://Stackoverflow.com/questions/46520136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6700881/" ]
There are at least three ways to achieve that. a) You could use `java.lang.Runtime` (as in `Runtime.getRuntime().exec(...)`) to launch an external process (from Java side), the external process being your Python script. b) You could do the same as a), just using Python as launcher. c) You could use some Python-Java ...
You should probably look for **[jython](https://wiki.python.org/jython/WhyJython)**. This support `Java` and `Python`.
7,926
40,239,866
I'm trying to list the containers under an azure account using the python sdk - why do I get the following? ``` >>> azure.storage.blob.baseblobservice.BaseBlobService(account_name='x', account_key='x').list_containers() >>> <azure.storage.models.ListGenerator at 0x7f7cf935fa58> ``` Surely the above is a call to the ...
2016/10/25
[ "https://Stackoverflow.com/questions/40239866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693831/" ]
you get the following according to [source code](https://github.com/Azure/azure-storage-python/blob/54e60c8c029f41d2573233a70021c4abf77ce67c/azure-storage-blob/azure/storage/blob/baseblobservice.py#L609) it return `ListGenerator(resp, self._list_containers, (), kwargs)` you can access what you want as follow: python2...
for python 3 and more recent distribution of `azure` libraries, you can do: ``` from azure.storage.blob import BlockBlobService block_blob_service = BlockBlobService(account_name=account_name, account_key=account_key) containers = block_blob_service.list_containers() for c in containers: print(c.name) ```
7,927
67,401,326
i have json file as below .Using python i want a fetch a record for source\_name = 'Abc' . How i can achieve it ---json file: file.json ``` [{ "source_name" :"Abc", "target_table" : "TABLE1", "schema": "col1 string, col2 string" }, { "source_name" :"xyz", "target_table" : "TABLE2", "schema"...
2021/05/05
[ "https://Stackoverflow.com/questions/67401326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4050708/" ]
You can use list comprehensions, which is considered to be more pythonic since the initial data is a list of dictionaries. ``` # using list comprehension result = [element for element in json.load(json_file) if element['source_name'] == "Abc"] # without using list comprehension for element in json.load(json_file): ...
Try this. ``` data = [{ "source_name" :"Abc", "target_table" : "TABLE1", "schema": "col1 string, col2 string" }, { "source_name" :"xyz", "target_table" : "TABLE2", "schema": "col3 string, col4 string" } ] l = len(data) n = 0 while n < l: if (data[n]["source_name"] == "Abc"): pr...
7,930
4,128,462
I just started working in an environment that uses multiple programming languages, doesn't have source control and doesn't have automated deploys. I am interested in recommending VSS for source control and using CruiseControl.net for automated deploys but I have only used CC.NET with ASP.NET applications. Is it possib...
2010/11/08
[ "https://Stackoverflow.com/questions/4128462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/226897/" ]
Yes you can. CC .net is written in .Net but can handle any project. Your project langage does not matter, you can still use Batch, Powershell, Nant or MsBuild scripts. You may also use Cruise Control or Hudson, as you like. As for the source control provider, I would prefer svn (or even git) but that's more a matter ...
VSS is [unsafe for any source](http://www.developsense.com/testing/VSSDefects.html) and is damn near useless outside visual studio. And cruise control is painful to learn and make work at best. Your heart is in the right place, but you probably want slightly different technical solutions. For SCM, you probably want eit...
7,931
39,615,436
When using LDA model, I get different topics each time and I want to replicate the same set. I have searched for the similar question in Google such as [this](https://groups.google.com/forum/#!topic/gensim/s1EiOUsqT8s). I fix the seed as shown in the article by `num.random.seed(1000)` but it doesn't work. I read the `...
2016/09/21
[ "https://Stackoverflow.com/questions/39615436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6858032/" ]
First: there is no problem. For international sites Unicode is often the preferred choice, as it can combine all possible scripts on one page (if the fonts can display them). For a Chinese-only site, say combined with plain ASCII, you can display the page in a Chinese encoding. Now the XML can be in UTF-8, a Unicode...
use dom4j and reload xml file; ``` org.dom4j.io.SAXReader reader=new SAXReader(); org.dom4j.Document doc=reader.read(new File(yourFilePath)); org.dom4j.io.OutputFormat format=new OutputFormat(); format.setEncoding("utf-8"); org.dom4j.io.XMLWriter writer=new XMLWriter(new FileOutputStream(path),format); writer.write(...
7,932
12,201,498
I am a beginer python learner. I am trying to create a basic dictionary where random meaning of words will come and user have to input the correct word. I used the following method, but random doesn't work. I always get the first word first and when the last word finishes, I get infinite 'none' until I kill it. Using p...
2012/08/30
[ "https://Stackoverflow.com/questions/12201498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1570162/" ]
``` #!/usr/bin/env perl use strict; use warnings; my $data = <<END; Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 152.225.244.1 DHCP Server . . . . . . . . . . . : 10.204.40.57 DNS Servers . . . . . . . . . . . : 10.204.127.11 10.207.2.50 ...
I would use [`unpack`](http://perldoc.perl.org/functions/unpack.html) instead of regular expressions for parsing column-based data: ``` #!/usr/bin/env perl use strict; use warnings; while (<DATA>) { my ($ip) = unpack 'x36 A*'; print "$ip\n"; } __DATA__ DNS Servers . . . . . . . . . . . : 10.204.127.11 ...
7,933
58,801,994
I have images with Borders like the below. Can I use OpenCV or python to remove the borders like this in images? I used the following code to crop, but it didn't work. ``` copy = Image.fromarray(img_final_bin) try: bg = Image.new(copy.mode, copy.size, copy.getpixel((0, 0))) except: return None diff = ImageCho...
2019/11/11
[ "https://Stackoverflow.com/questions/58801994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9186998/" ]
Here's an approach using thresholding + contour filtering. The idea is to threshold to obtain a binary image. From here we find contours and filter using a maximum area threshold. We draw all contours that pass this filter onto a blank mask then perform bitwise operations to remove the border. Here's the result with th...
You could also use Werk24's API for reading Technical Drawings: [www.werk24.io](https://werk24.io) ```py from werk24 import W24TechreadClient, W24AskCanvasThumbnail async with W24TechreadClient.make_from_env() as session: response = await session.read_drawing(document_bytes,[W24AskCanvasThumbnail()]) ``` It al...
7,937
70,972,961
I have this list of objects which have p1, and p2 parameter (and some other stuff). ``` Job("J1", p1=8, p2=3) Job("J2", p1=7, p2=11) Job("J3", p1=5, p2=12) Job("J4", p1=10, p2=5) ... Job("J222",p1=22,p2=3) ``` With python, I can easily get max value of p2 by ``` (max(job.p2 for job in instance.jobs)) ``` but how ...
2022/02/03
[ "https://Stackoverflow.com/questions/70972961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18110528/" ]
You can do it like this: ```html <style> .input-wrapper { display: flex; position: relative; } .input-wrapper .icon { position: absolute; top: 50%; transform: translateY(-50%); padding: 0 10px; } .input-wrapper input { padding: 0 0 0 25px; height: 50px; } </style> <div class="input-wrapper"> <i cl...
There are two styling options you can use. These are block and flex. Block will not be responsive while flex will be responsive. I hope this solve your issue.
7,938
70,777,985
I'm trying to create a pandas multiIndexed dataframe that is a summary of the unique values in each column. Is there an easier way to have this information summarized besides creating this dataframe? Either way, it would be nice to know how to complete this code challenge. Thanks for your help! Here is the toy datafr...
2022/01/19
[ "https://Stackoverflow.com/questions/70777985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17119804/" ]
Well, there are many ways to handle errors, it really depends on what you want to do in case of an error. In your current setup, the solution is straightforward: **first, `NotificationException` should extend `RuntimeException`**, thus, in case of an HTTP error, `.block()` will throw a `NotificationException`. It is a...
Using imperative/blocking style you can surround it with a try-catch: ```java try { webClient.post() .uri("http://localhost:9000/api") .body(BodyInserters.fromValue(notification)) .retrieve() .onStatus(HttpStatus::isError, clientResponse -> Mono.error(NotificationExc...
7,939
25,737,589
I run a django app via gunicorn, supervisor and nginx as reverse proxy and struggle to make my gunicorn access log show the actual ip instead of 127.0.0.1: Log entries look like this at the moment: ``` 127.0.0.1 - - [09/Sep/2014:15:46:52] "GET /admin/ HTTP/1.0" ... ``` supervisord.conf ``` [program:gunicorn] comma...
2014/09/09
[ "https://Stackoverflow.com/questions/25737589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/640916/" ]
The problem is that you need to configure [`gunicorn`'s logging](http://docs.gunicorn.org/en/0.17.0/configure.html#logging), because it will (by default) not display any custom headers. From the documentation, we find out that the default access log format is controlled by [`access_log_format`](http://docs.gunicorn.or...
Note that headers containing `-` should be referred to here by replacing `-` with `_`, thus `X-Forwarded-For` becomes `%({X_Forwarded_For}i)s`.
7,940
16,640,610
So I tried to use parses generator [waxeye](http://waxeye.org/), but as I try to use tutorial example of program in python using generated parser I get error: ``` AttributeError: 'module' object has no attribute 'Parser' ``` Here's part of code its reference to: ``` import waxeye import parser p = parser.Parser() ...
2013/05/19
[ "https://Stackoverflow.com/questions/16640610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1334531/" ]
can you try this code and then please tell me result. be sure you check all file names. ``` @Override protected void onCreate(Bundle savedInstanceState) { //....... DatabaseHelper dbHelper = new DatabaseHelper(this); dbHelper.createDatabase(); dbHelper.openDatabase(); // do stuff Cursor da...
remove **.db** extension from both **DB\_NAME** and **.open("database.db")** It looks ugly but currently same thing is working for me.... And before installing new apk please do ***Clear Data*** for earlier installed apk And still if it won't work, please mention your database size.
7,941
48,630,957
I'm using subprocess in Python and passing ec2 instance id at runtime..while giving instance id it is taking as a string and throwing error saying instance id is not valid. Please don't suggest boto3 package as my company restricted of using it.My question is how can I send the character+integer+special character at ru...
2018/02/05
[ "https://Stackoverflow.com/questions/48630957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9318698/" ]
Are you intending to pass the literal string `"instanceid"`? Surely you mean to use its value? ``` subprocess.call(["aws", "ec2", "describe-instances", "--instance-ids", f'"{instanceid}"']) ``` or ``` subprocess.call(["aws", "ec2", "describe-instances", "--instance-ids", '"{}"'.format(instanceid)]) ``` if not usi...
This has nothing to do with "passing integer or character types", whatever that means. You are passing the literal value `"instanceid"`, complete with quotes, rather than the value of the instanceid argument to your script. You did do both sets of quotes. (And really, you should take up this silly "restriction" abou...
7,942
17,436,045
I'm sure this is something easy to do for someone with programming skills (unlike me). I am playing around with the Google Sites API. Basically, I want to be able to batch-create a bunch of pages, instead of having to do them one by one using the slow web form, which is a pain. I have installed all the necessary file...
2013/07/02
[ "https://Stackoverflow.com/questions/17436045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2544281/" ]
Variable 'initialization' will always trigger an event. From the last Verilog standard([IEEE 1364-2005](http://standards.ieee.org/findstds/standard/1364-2005.html)): > > If a variable declaration assignment is used (see 6.2.1), the variable > shall take this value as if the assignment occurred in a blocking > assig...
A good reference for order of events is this paper: <http://www.sunburst-design.com/papers/CummingsSNUG2000SJ_NBA_rev1_2.pdf> page 6 has a diagram of the order of events as far as evaluation of variables and triggering goes.
7,943
28,379,373
In python is there any way at all to get a function to use a variable and return it without passing it in as an argument?
2015/02/07
[ "https://Stackoverflow.com/questions/28379373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3983128/" ]
What you ask **is** possible. If a function doesn't re-bind (e.g, assign to) a name, but uses it, that name is taken as a *global* one, e.g: ``` def f(): print(foo) foo = 23 f() ``` will do what you ask. However, it's a dubious idea already: why not just `def f(foo):` and call `f(23)`, so much more direct and c...
As @Alex Martelli pointed out, you *can*... but *should* you? That's the more relevant question, IMO. I understand the *appeal* of what you're asking. It seems like it should *just be* good form because otherwise you'd have to pass the variables everywhere, which of course seems wasteful. I won't presume to know how...
7,944
46,318,530
Hello all I'm very new to python, so just bear with me. I have a sample json file in this format. ``` [{ "5":"5", "0":"0", "1":"1"},{ "14":"14", "11":"11", "15":"15"},{ "25":"25", "23":"23", "22":"22"}] ``` I would like to convert the json file to csv in a specific way. All the values in 1 map i.e., `{` and `}` in t...
2017/09/20
[ "https://Stackoverflow.com/questions/46318530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7923318/" ]
`bytes(iterator)` create bytes object from iterator using internal C-API `_PyBytes_FromIterator` function, which use special `_PyBytes_Writer` protocol. It internaly use a buffer, which resize when it overflows using a rule: ``` bufsize += bufsize / OVERALLOCATE_FACTOR ``` For linux OVERALLOCATE\_FACTOR=4, for wind...
this is probably more a remark or discussion start than an answer but I think it's better to format it like this. I just hooking in 'cause I find this topic very inteeresting as well. I would recommend to paste the real call and generator mock. Since imho the generator expression example does not fit really well for y...
7,945