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
61,011,373
I'm trying to install indy-node on a fresh Ubuntu 18.04 machine in order to create a small network with 4 nodes. when following the [installation instructions](https://github.com/hyperledger/indy-node/blob/master/docs/source/start-nodes.md) I get the following error: ``` localhost:~$ sudo apt-get install indy-node T...
2020/04/03
[ "https://Stackoverflow.com/questions/61011373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786712/" ]
We've generated Docker images for Indy-Node using Ubuntu 18.04, but had to build libsodium from source. You can see the source dockerfile here although there are git URLs that get replaced by the build script: <https://github.com/PSPC-SPAC-buyandsell/von-image/blob/master/node-1.9/Dockerfile.ubuntu> The final images a...
The solution in the end was to downgrade to Ubuntu 16.04
14,049
49,738,443
I'm attempting to convert an array of strings to array of floats using : ``` arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]' a1 = arr_str.split() [int(x) for x in a1] ``` but throws error : < ``` ipython-input-57-f7f1eaba7ebd> in <listcomp>(.0) 3 a1 = arr_str.split() 4 ----> 5 [int(x) for x in a1]...
2018/04/09
[ "https://Stackoverflow.com/questions/49738443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470184/" ]
One way is to use `ast.literal_eval`. If you need a `numpy` integer array, the conversion is trivial. ``` import numpy as np from ast import literal_eval arr_str = '[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]' res = literal_eval(arr_str.replace(' ', ',')) # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1] res_np = np....
``` arr_str = arr_str.strip("[]") voila = [int(x) for x in arr_str.split()] ``` Edit 1: Being pedantic about variable assignment.
14,050
27,532,112
I'm using two python packages that have the same name. * <http://www.alembic.io/updates.html> * <https://pypi.python.org/pypi/alembic> Is there a canonical or pythonic way to handle installing two packages with conflicting names? So far, I've only occasionally needed one of the packages during development/building, ...
2014/12/17
[ "https://Stackoverflow.com/questions/27532112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1547004/" ]
You could use the --target option for pip and install to an alternate location: ``` pip install --target=/tmp/test/lib/python3.6/site-packages/alt_alembic alembic ``` Then when you import in python, do the first as usual and for the alt do an import from that namespace like this: ``` import alembic # alembic.io ve...
how about **absolute and relative imports.** <https://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports>
14,052
43,429,018
i have the following link: <https://webcache.googleusercontent.com/search?q=cache:jAc7OJyyQboJ>:**<https://cooking.nytimes.com/learn-to-cook>**+&cd=5&hl=en&ct=clnk I have multiple links in a dataset. Each link is of same pattern. I want to get a specific part of the link, for the above link i would be the bold part of...
2017/04/15
[ "https://Stackoverflow.com/questions/43429018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7872059/" ]
Instead of `var c = new Audio(src);` use `var c = document.createElement('audio'); c.src=src; c.play();`
You have to wait for the DOM to be ready. Since your are using jQuery, please encapsulate your code in that: ``` $(document).ready(function () { // Your code... }); ``` You can also use this syntax: ``` $(function () { // Your code... }); ``` *(Bonus tip: use the `switch` instruction in your code. `RoNBeta.js...
14,053
50,706,987
I've been trying for a couple of days with limited success to use TCP to make two ruby programs on the same or different machines communicate. I'm looking for example 'client' and 'server' scripts that will work straight away, once I've chosen ports that work. Client code I found that seems to work, shown below. But...
2018/06/05
[ "https://Stackoverflow.com/questions/50706987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336879/" ]
@adjam you haven't created a TcpServer, [TCPSocket](https://ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/TCPSocket.html) is used to create TCP/IP client socket To create TCP/IP server you have to use [TCPServer](https://ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/TCPServer.html) EX: Tcp/ip Server code: ``` require ...
Taking the documentation from <https://ruby-doc.org/stdlib-2.5.1/libdoc/socket/rdoc/Socket.html>, you seem to be looking for something like this: ``` require 'socket' server = TCPServer.new(1540) client = server.accept client.puts "GETHELLO" client.close server.close ``` More generally, if you'd like the server acce...
14,056
6,844,863
Relative import not working properly in python2.6.5 getting "ValueError: Attempted relative import in non-package". I am having all those `__init__.py` in proper place.
2011/07/27
[ "https://Stackoverflow.com/questions/6844863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/865438/" ]
I have seen that error before when running a script that is actually *inside* a package. To the interpreter, it appears as though the package is not a package. Try taking the script into another directory, putting your package inside your `pythonpath`, and import absolutely. Then, relative imports inside your package ...
``` main.py setup.py Main Package/ -> __init__.py subpackage_a/ -> __init__.py module_a.py subpackage_b/ -> __init__.py module_b.py ``` i) ``` 1.You run python main.py 2.main.py does: import app.package_a.module_a 3.module_a.py does import app.package_b.module_b ...
14,059
45,301,335
I am using Python + IPython for Data Science. I made a folder that contains all the modules I wrote, organised in packages, something like ``` python_workfolder | |---a | |---__init__.py | |---a1.py | |---a2.py | |---b | |---__init__.py | |---b1.py | |---b2.py | |---c | |---__init__.py | |---c1.py | ...
2017/07/25
[ "https://Stackoverflow.com/questions/45301335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2558671/" ]
Just type: ``` last root ``` This will give you details of the IP addresses of machines where users logged in as root.
Without knowing your Input\_file I am providing this solution, so could you please try following and let me know if this helps you. ``` awk '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/);array[substr($0,RSTART,RLENGTH)]} END{for(i in array){print i,array[i]}}' Input_file ``` If above is not helping you then kindly ...
14,060
32,031,111
I am trying to run a simple Python script with crontab, but I can’t get it to work. I can run a simple program in crontab when not using Python though. Here is the line I have in my Crontab file that does work: ``` * * * * * echo “cron test” >> /home/ftpuser/dev/mod_high_lows/hello.txt ``` I also can run this python...
2015/08/16
[ "https://Stackoverflow.com/questions/32031111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1087809/" ]
* cron runs commands in a limited environment. Only a few environment variables are automatically set. It loads the environment specified by `/etc/environment` and `/etc/security/pam_env.conf`, but not about the environment variables you might have set in your `.bashrc` or `.profile`. Set the crontab entry ``` * * ...
I'm not sure if this will help, but I've always successfully managed to get python scripts to run successfully from cron by adding this line to the end of the crontab file: ``` @reboot python /home/ftpuser/dev/mod_high_lows/testit.py & ``` The `&` is necessary at the end of the line. If this is what you need, and yo...
14,061
62,714,282
In the [ThreadPoolExecutor documentation](https://docs.python.org/3/library/concurrent.futures.html) it says: > > Changed in version 3.5: If `max_workers` is `None` or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that `ThreadPoolExecutor` is often used to overlap I/...
2020/07/03
[ "https://Stackoverflow.com/questions/62714282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13859123/" ]
You are writing `binascii.hexlify(self._public_key.exportKey(format='DER')).decode('ascii')` at the next line. Try writing it after the `return` keyword. Hope your error will go away
you should define a Clinet instance and then get it's \_public\_key: ``` binascii.hexlify(Client._public_key.exportKey(format='DER')).decode('ascii') ```
14,063
38,044,788
it's login is fine, but i am not able to track the issue, here the code below ``` while True: time.sleep(10) browser.get("https://www.instagram.com/accounts/edit/?wo=1") ``` I am getting this error when i ran project.py ``` Superuser$ python project.py user diabruxaneas1989 with proxy 192.126.1...
2016/06/27
[ "https://Stackoverflow.com/questions/38044788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6445447/" ]
You forgot to close the `href` attribute (double-quotes): ``` echo '<a href="directMessageRoom.php?directMessageRoomID='.$row3['id'].'"></a>'; right here ---^ ```
Be aware of lots of 'white-space' in your form field. Your submit button for example, you write this `<input type = "submit" ...>`. You are accidentally insert white space. It should be `<input type="submit" ...>`.
14,065
55,549,014
I get the syntax error: FileNotFoundError: [WinError 2] The system cannot find the file specified when running the below code. It is a little hard to find a good solution for this problem on windows which I am running as compared to UNIX which I can find working code for. ``` from subprocess import Popen, check_cal...
2019/04/06
[ "https://Stackoverflow.com/questions/55549014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6104634/" ]
A big problem there is that your width will be zero. The X and Y scales are factors. As in multipliers. Anything times Zero is zero. Hence ``` ScaleTransform(0, -1); ``` Will give you something with no width. You presumably want the same width and hence: ``` ScaleTransform(1, -1); ``` That might still have anoth...
Just set the PathGeometry's `Transform` property: ``` var myPathGeometry = new PathGeometry(); myPathGeometry.Figures.Add(myPathFigure); myPathGeometry.Transform = new ScaleTransform(1, -1); ``` Note that you may also need to set the ScaleTransform's `CenterY` property for a correct vertical alignment.
14,066
63,614,832
I've faced an global issue recently and I have no idea for this behavior in python: ``` # declaring some global variables variable = 'peter' list_variable_1 = ['a','b'] list_variable_2 = ['c','d'] def update_global_variables(): """without using global line""" variable = 'PETER' # won't update in global scope ...
2020/08/27
[ "https://Stackoverflow.com/questions/63614832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6756530/" ]
from [exitBeforeEnter](https://www.framer.com/api/motion/animate-presence/#animatepresenceprops.exitbeforeenter) docs > > If set to `true`, `AnimatePresence` will only render one component at a time. The exiting component will finished its exit animation before the entering component is rendered. > > > You have t...
That's normal if you will not add an `exit` animation to each and every routes. Main route with AnimatePresense ``` <AnimatePresence exitBeforeEnter> <Switch location={window.location} key={window.location.pathname}> <Route exact path='/' component={Home} /> <Route exact path='/about' component={About} /> ...
14,069
11,767,757
This issue just started, last week I had no issues with the particular source file. I'm using SQLAlchemy and Geoalchemy and the particular block of code that triggers Eclipse and Aptana to start pegging the cpu while simply editing the file is: ``` obsRecs = db.session.query(multi_obs)\ .join(sensor,sensor.row_id == m...
2012/08/01
[ "https://Stackoverflow.com/questions/11767757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1569769/" ]
I was running into the same problem but for a different, long query. I tried disabling auto-complete, tried the `-clean` thing, no luck. To fix, I waited for the memory leak to explode and used `jmap.exe` to dump the heap. I then ran Eclipse Memory Analyzer to see where my memory was going, the screenshot is attached ...
In the past I have had some success solving Eclipse insanity by starting with a clean workspace. It's kind of a shot in the dark, but try the following one by one: 1. Start eclipse with the `-clean` option and the existing workspace. 2. If the above does not work, try editing the same file in a new workspace. If yo...
14,075
394,500
In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread ...
2008/12/27
[ "https://Stackoverflow.com/questions/394500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9161/" ]
You should use the [Queue](http://docs.python.org/library/queue.html) module for sharing sequential data across threads. You would have to make a file-like Queue subclass, where .read and .write mutually block each other, with a buffer in-between. OTOH, I wonder why the first thread can't write to the real file in the...
I'm not clear what you're trying to do ehre. This sounds like a job for a regular old pipe, which is a file-like object. I'm guessing, however, that you mean you're got a stream of some other sort. It also sounds a lot like what you want is a python [Queue](http://docs.python.org/library/queue.html), or maybe a [tempf...
14,080
25,387,286
When I do `pip install statsmodels` it gives me `ImportError: statsmodels requires patsy. http://patsy.readthedocs.org`, but then I run `pip install patsy` and it says its successful, but running `pip install statsmodels` still gives me same error about requiring patsy. How can this be? --- ``` $ sudo pip install pa...
2014/08/19
[ "https://Stackoverflow.com/questions/25387286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3391108/" ]
What the error message doesn't tell you is that the module `six` not being there is really the problem. Found this out by doing `import patsy` and having it fail and tell me that I needed `six`. So I did `pip install six` and now the patsy import worked, as did the `pip install statsmodels`.
For me: ``` $python3 -m pip install --upgrade patsy $python3 -m pip install statsmodels ``` worked!
14,085
32,085,019
I am very new to Google App engine and was trying to understand bolb storage and api, but cant get it working. I followed the the below tutorial from goolge on using blobstore api <https://cloud.google.com/appengine/docs/python/blobstore/> Github: <https://github.com/GoogleCloudPlatform/appengine-blobstore-python/b...
2015/08/19
[ "https://Stackoverflow.com/questions/32085019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4822241/" ]
You are dealing with jQuery object, methods like removeChild() and [appendChild()](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild) belongs to dom element not to the jQuery object. To remove all contents of an element you can use [.empty()](http://api.jquery.com/empty) and to set the text content of ...
Did you wanna do somethin like this? ``` <html> <head> <title>STACK OVERFLOW TESTS</title> <style> </style> </head> <body> <span>HI, IM SOME TEXT</span> <input type = 'button' value = 'Click me!' onClick = 'changeText()'></input> <!-- Change the text with a button for example... --> <script...
14,090
45,031,524
I have a melted DataFrame I would like to pivot but cannot manage to do so using 2 columns as index. ``` import pandas as pd df = pd.DataFrame({'A': {0: 'XYZ', 1: 'XYZ', 2: 'XYZ', 3: 'XYZ', 4: 'XYZ', 5: 'XYZ', 6: 'XYZ', 7: 'XYZ', 8: 'XYZ', 9: 'XYZ', 10: 'ABC', 11: 'ABC', 12: 'ABC', 13: 'ABC', 14: 'ABC', 15: 'ABC', 16:...
2017/07/11
[ "https://Stackoverflow.com/questions/45031524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4947923/" ]
Is that what you want? ``` In [23]: df.pivot_table(index=['A','B'], columns='C', values='D', aggfunc='first') Out[23]: C Price Trading A B ABC 01/01/2017 50 Yes 02/01/2017 NaN No 03/01/2017 48 Yes 04/01/2017 47 Yes 05/01/2017 46 Yes XYZ 01/01/2017 100...
I found the following is possible: ``` df.set_index(['A', 'C', 'B']).unstack().T Out[59]: A ABC XYZ C Price Trading Price Trading B D 01/01/2017 50 Yes 100 Yes 02/01/2017 NaN No 101 Yes 03/01/2017 48 ...
14,091
40,712,887
I am confused with the time queryset uses its `_result_cache` or it directly hits the database. For example (in python shell): ``` user = User.objects.all() # User is one of my models print(user) # show data in database (hitting the database) print(user._result_cache) # output is None len(user) # output...
2016/11/21
[ "https://Stackoverflow.com/questions/40712887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6751999/" ]
A queryset will cache its data in `self._result_cache` whenever the *complete* queryset is evaluated. This includes iterating over the queryset, calling `bool()`, `len()` or `list()`, or pickling the queryset. The `print()` function indirectly calls `repr()` on the queryset. `repr()` will evaluate the queryset to incl...
There is an explanation for this behavior : When you use User.objects.all(),Database is not hit.When you do not iterate through the query set, the \_result\_cache is always None.But when you invoke len() function.The iteration will be done through query set, the database will be hit and resulting output will also set ...
14,092
46,994,144
I am a beginner in python. I have written the following python code: ``` import subprocess PIPE = subprocess.PIPE process = subprocess.Popen(['git', 'status'], stdout=PIPE, stderr=PIPE, cwd='my\git-repo\path',shell=True) stdout_str, stderr_str = process.communicate() print (stdout_str) print (stderr_str) ``` Upon e...
2017/10/28
[ "https://Stackoverflow.com/questions/46994144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8849445/" ]
You have to specify the full php binary path inside the cronjob. Assuming your php binary full path is `/usr/bin/php` then your cronjob will look like this: ``` /usr/bin/php -q /home/user/tracker.domain.com/cron/3.php ```
You should use php before -q in your cron jobs like this php -q /home/user/tracker.domain.com/cron/3.php
14,093
11,860,252
In a python script i do a gobject call. I need to know, when its finished. are there any possible ways to check this? Are there Functions or so on to check? My code is: ``` gobject.idle_add(main.process) class main: def process(): <-- needs some time to finish --> next.call.if.finished() ``` I want t...
2012/08/08
[ "https://Stackoverflow.com/questions/11860252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508490/" ]
``` for($i = 0; $i < count($key); $i++){ $query.=" AND (dealTitle rlike '[[:<:]]".$key[$i]."[[:>:]]' )"; } ``` Should use AND EDITED: ``` for($i = 0; $i < count($key); $i++){ $query.=" AND (dealTitle like '% ".$key[$i]." %' or dealTitle like '% ".$key[$i]."' or dealTitle like '".$key[$i]."%'...
try this: ``` AND (CONCAT(' ',dealTitle,' ') LIKE '% car %' and CONCAT(' ',dealTitle,' ') LIKE '% wash %' ) ```
14,094
20,289,373
I am developing a program in python and have reached a point I don't know how to solve. My intention is to use a `with` statement, an avoid the usage of try/except. So far, my idea is being able to use the `continue` statement as it would be used inside the `except`. However, I don't seem to succeed. Let's supposse t...
2013/11/29
[ "https://Stackoverflow.com/questions/20289373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
It's not possible. The only two options are (a) let the exception propagate by returning a false-y value or (b) swallow the exception by returning True. There is no way to resume the code block from where the exception was thrown. Either way, your `with` block is over.
You can't. The `with` statement's purpose is to handle cleanup automatically (which is why exceptions can be suppressed *when exiting it*), not to act as Visual Basic's infamous `On Error Resume Next`. If you want to continue the execution of a block after an exception is raised, you need to wrap whatever raises the e...
14,100
73,642,679
I have a function in C which is integrated into python as a library. The python looks something like this: ``` import ctypes import numpy as np lib=ctypes.cdll.LoadLibrary("./array.so") lib.eq.argtypes=(ctypes.c_int, ctypes.POINTER(ctypes.c_float), ctypes.POINTER(ctypes.c_float)) pa...
2022/09/08
[ "https://Stackoverflow.com/questions/73642679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18335909/" ]
You were close. The input arrays need to be `dtypes=np.float32` (or `ct.c_float`) to match the C 32-bit `float` parameters. `results` is changed in-place so print the updated `results` after the function call. You can also use `ndpointer` to declare the *exact* type of arrays expected, so `ctypes` can check the the co...
My suggestion: ```py import ctypes import numpy as np from os.path import abspath from ctypes import cdll, c_void_p, c_int params = np.ascontiguousarray(np.zeros(5, dtype=np.float64)) results = np.ascontiguousarray(np.zeros(5, dtype=np.float64)) lib = cdll.LoadLibrary(abspath('array.so')) # loading the compiled...
14,103
73,224,353
**Context** An empty list: `my_list = []` I also have a list of lists of strings: words\_list = `[['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']]` But note that there are some elements in the lists that are null. **Ideal output** I want to randomly choose a non null element from each list in `words_list`...
2022/08/03
[ "https://Stackoverflow.com/questions/73224353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10587373/" ]
Maybe you can try to start thinking this way: The idea is quite simple - just go through the list of words, and choose the non-empty word then passing to *choice*. ```py >>> for word in words_list: wd = choice([w for w in word if w]) # if w is non-null, choice will pick it... print(wd) # then just add thos...
Try below code and see if it works for you: ``` import random my_list = [] words_list = [['this', '', 'is'], ['a', 'list', ''], ['of', 'lists']] for sublist in words_list: filtered_list = list(filter(None, sublist)) my_list.append(random.choice(filtered_list)) print(my_list) ```
14,104
46,600,413
New to programming and currently working with python. I am trying to take a user inputted string (containing letters, numbers and special characters), I then need to split it multiple times at different points to reform new strings. I have done research on the splitting of strings (and lists) and feel I understand it b...
2017/10/06
[ "https://Stackoverflow.com/questions/46600413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8660214/" ]
change your jquery code to ``` $('#forgotPassword').click(function() { var base_url = '<?php echo base_url()?>'; $('#forgotPasswordEmailError').text(''); var email = $('#forgotPasswordEmail').val(); console.log(email); if(email == ''){ $('#forgotPasswordEmailError').text('Email is require...
Instead of ``` echo $email; ``` use: ``` $response = ["email" => $email]; return json_encode($response); ``` And parse JSON, on client side, using `JSON.parse`.
14,108
33,146,316
Sorry, I'm a newbie of nodejs. I'd like to try the package `win32ole` in nodejs under Windows7, but when I run the installation command `npm install win32ole` in a command prompt window opened as administrator, many errors pop up. My configuration is: * Windows 7 64 bit (version 6.1.7601) * Microsoft Visual Studio Ex...
2015/10/15
[ "https://Stackoverflow.com/questions/33146316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/694360/" ]
It's not possible with up to date node.js versions. Use [node winax](https://www.npmjs.com/package/winax)
First of all you have a **warning** due to the node version ``` npm WARN engine win32ole@0.1.3: wanted: {"node":">= 0.8.18 && < 0.9.0"} (current: {"node":"4.2.1","npm":"2.14.7"}) ``` It should be lower than 0.9.0 Have you installed **node-gyp**? I'm seeing a lot of error complaining it. If not you can install it wi...
14,110
6,119,038
I'm writing a bash script that fires up python and then enters some simple commands before exiting. I've got it firing up python ok, but how do I make the script simulate keyboard input in the python shell, as though a person were doing it?
2011/05/25
[ "https://Stackoverflow.com/questions/6119038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193601/" ]
Use a "here" document. It looks like this ``` command << HERE text that someone types in more text HERE ``` You don'th have to use "HERE", you can use something that has a little more meaning relative to the context of your code.
Have you tried `echo "Something for input" | python myPythonScript.py` ?
14,111
28,377,690
Complete noob with python 3. I have some code and can't figure out for the life of me why I keep getting the output I do. For some reason the elif statements aren't getting recognized. Here is the output first and the code down below: ``` 3 Your fortune for today is: Please press enter to end ``` ``` #Program for ...
2015/02/07
[ "https://Stackoverflow.com/questions/28377690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2288612/" ]
You are not assigning `varx` to `statement` (in some cases, 3, 4 and 5th cases), but comparing. Just change all: ``` statement == varx ``` To: ``` statement = var3 ``` Except from that, it seems to work.
The Problem is for example ```js statement == var5 ``` assignment statement. Good luck!
14,116
35,437,380
I installed Dato's `GraphLab Create` to run with `python 27` first directly from its executable then manually via `pip` ([instructions here](https://dato.com/products/create/)) for troubleshooting. Code: ``` import graphlab graphlab.SFrame() ``` Output: ``` [INFO] Start server at: ipc:///tmp/graphlab_server-4908 ...
2016/02/16
[ "https://Stackoverflow.com/questions/35437380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4992716/" ]
capitalization error, it should be SFrame, not Sframe
You can only load a graplab package ('file.gl') by `graphlab.SFrame()`. Instead to load a csv file use `csvf = graphlab.SFrame.read_csv('file.csv')` for more information and other data types read this docs <https://dato.com/products/create/docs/graphlab.data_structures.html>
14,119
49,651,351
I have a similar issues like [How to upload a bytes image on Google Cloud Storage from a Python script](https://stackoverflow.com/questions/46078088/how-to-upload-a-bytes-image-on-google-cloud-storage-from-a-python-script/47140336#comment86305324_47140336). I tried this ``` from google.cloud import storage import cv...
2018/04/04
[ "https://Stackoverflow.com/questions/49651351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9596737/" ]
As suggested by @A.Queue [in](https://pastebin.com/Jr6k3SW2)(gets deleted after 29 days) ``` from google.cloud import storage import cv2 from tempfile import TemporaryFile client = storage.Client() bucket = client.get_bucket('test-bucket') image=cv2.imread('example.jpg') with TemporaryFile() as gcs_image: image....
You are calling `blob = bucket.get_blob(gcs_image)` which makes no sense. `get_blob()` is supposed to get a string argument, namely the name of the blob you want to get. A *name*. But you pass a file object. I propose this code: ``` with TemporaryFile() as gcs_image: image.tofile(gcs_image) gcs_image.seek(0) ...
14,120
58,134,808
I'd like to install some special sub-package from a package. For example, I want to create package with pkg\_a and pkg\_b. But I want to allow the user to choose which he wants to install. What I'd like to do: ``` git clone https://github.com/pypa/sample-namespace-packages.git cd sample-namespace-packages touch setu...
2019/09/27
[ "https://Stackoverflow.com/questions/58134808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5872512/" ]
A solution for your use case seems to be similar to the one I gave here: <https://stackoverflow.com/a/58024830/11138259>, as well as the one you linked in your question: [Python install sub-package from package](https://stackoverflow.com/questions/45324189/python-install-sub-package-from-package). Here is an example.....
If the projects are not installed from an index such as *PyPI*, it is not possible to take advantage of the `install_requires` feature. Something like this could be done instead: ``` . ├── NmspcPing │   ├── nmspc.ping │   │   └── __init__.py │   └── setup.py ├── NmspcPong │   ├── nmspc.pong │   │   └── __init__.py │  ...
14,121
61,933,414
``` import tkinter as tk from tkinter import filedialog, Text from subprocess import call import os root = tk.Tk() def buttonClick(): print('Button is clicked') def openAgenda(): call("cd '/media/emilia/Linux/Programming/PycharmProjects/SmartschoolSelenium' && python3 SeleniumMain.py", shell=True) ...
2020/05/21
[ "https://Stackoverflow.com/questions/61933414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13588940/" ]
You should include the necessary JavaScript resource like this: ``` <script src='https://www.google.com/recaptcha/api.js'></script> ``` Besides, set the right site key in the `data-sitekey` attribute. The result is like this in IE: [![enter image description here](https://i.stack.imgur.com/mnuEK.png)](https://i.st...
Actually it was loading loading first time in IE. So, I tried with making url different everytime by appending current datetime. "<https://www.google.com/recaptcha/api.js?render=>" + EncodeUrl(SiteKey) + "&time="+CurrTime() It started working.
14,122
1,046,656
I have a very simple python script that **should** scan a text file, which contains lines formatted as *id*='*value*' and put them into a dict. the python module is called chval.py and the input file is in.txt. here's the code: ``` import os,sys from os import * from sys import * vals = {} f = open(sys.argv[1], 'r')...
2009/06/25
[ "https://Stackoverflow.com/questions/1046656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/125946/" ]
Also of note is that starting with Python 2.6 the built-in function open() is now an alias for the io.open() function. It was even considered removing the built-in open() in Python 3 and requiring the usage of io.open, in order to avoid accidental namespace collisions resulting from things such as "from blah import \*"...
Providing these parameters resolved my issue: ``` with open('tomorrow.txt', mode='w', encoding='UTF-8', errors='strict', buffering=1) as file: file.write(result) ```
14,123
1,597,732
Folks, I know there have been lots of threads about forcing the download dialog to pop up, but none of the solutions worked for me yet. My app sends mail to the user's email account, notifying them that "another user sent them a message". Those messages might have links to Excel files. When the user clicks on a link ...
2009/10/20
[ "https://Stackoverflow.com/questions/1597732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ]
This will check for versions of IE and set headers accordingly. ``` // assume you have a full path to file stored in $filename if (!is_file($filename)) { die('The file appears to be invalid.'); } $filepath = str_replace('\\', '/', realpath($filename)); $filesize = filesize($filepath); $filename = substr(strrchr('/'...
If you're trying to get the file to download every time, change the content type to 'application/octet-stream'. Try it without the pragma statement.
14,133
12,460,943
I have a list of log files, where each line in each file has a timestamp and the lines are pre-sorted ascending within each file. The different files can have overlapping time ranges, and my goal is to blend them together into one large file, sorted by timestamp. There can be ties in the sorting, in which case I want t...
2012/09/17
[ "https://Stackoverflow.com/questions/12460943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233446/" ]
Why roll your own if there is `heapq.merge()` in the standard library? Unfortunately it doesn't provide a key argument -- you have to do the decorate - merge - undecorate dance yourself: ``` from itertools import imap from operator import itemgetter import heapq def extract_timestamp(line): """Extract timestamp a...
You want to implement a file-based [merge sort](http://en.wikipedia.org/wiki/Merge_sort). Read a line from both files, output the older line, then read another line from that file. Once one of the files is exhausted, output all the remaining lines from the other file.
14,139
63,214,706
I'm working on a database with a graphical interface, I made an insert and delete method connected to the database, now I'm working on creating a search method but unfortunately not working for an unexpected error. The code Is a little bit long : ``` import sqlite3 from Tkinter import * global all,root, main_text, num...
2020/08/02
[ "https://Stackoverflow.com/questions/63214706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13421322/" ]
you can give your search function an input. global statement is for an outer scope. for example when you want to make a function in another function. you can [check here](https://www.python-course.eu/python3_global_vs_local_variables.php). and now about your code. here is a simple way that I have said the idea: ``...
I slightly redisigned your code, and it seems to work. I changed the location of the `root`, `search_ent` and `main_text`, now it's before the functions, so there won't be an error. ``` import sqlite3 from tkinter import * global all,root, main_text, num_ent, nom_ent, search_ent global search_ent root = Tk() root.con...
14,140
63,940,493
I want to compare every element of two matrices with the same dimensions. I want to know, if one of the elements in the first matrix is smaller than another with the same indices in the second one. I want to fill a third matrice with the values of the first, but every entry, where my criteria applies, should be a 0. Be...
2020/09/17
[ "https://Stackoverflow.com/questions/63940493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14285969/" ]
When you `map` over `question`: ``` question.map(function (quest){ ``` The `quest` variable will be each element of that array. Which in this case that element is: ``` [ { questions: "question1", answer1: "answer1", answer2: "answer2" }, { questions: "question2", answer1: "answer1", answer2:...
In short objects doesn't have .map() function. Do this instead: `question.map(function (quest){ return quest.questions; });`
14,141
19,405,223
I hope not to make a fool of myself by re-asking this question, but I just can't figure out why my fixtures are not loaded when running test. I am using python 2.7.5 and Django 1.5.3. I can load my fixtures with `python manage.py testserver test_winning_answers`, with a location of `survey/fixtures/test_winning_answer...
2013/10/16
[ "https://Stackoverflow.com/questions/19405223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1014862/" ]
This will perform well if you have index on VersionColumn ``` SELECT * FROM MainTable m INNER JOIN JoinedTable j on j.ForeignID = m.ID CROSS APPLY (SELECT TOP 1 * FROM SubQueryTable sq WHERE sq.ForeignID = j.ID ORDER BY VersionColumn DESC) sj ```
**Answer** : Hi, Below query I have created as per your requirement using Country, State and City tables. > > > ``` > SELECT * FROM ( > SELECT m.countryName, j.StateName,c.CityName , ROW_NUMBER() OVER(PARTITION BY c.stateid ORDER BY c.cityid desc) AS 'x' > FROM CountryMaster m > INNER JOIN StateMaster j on j.Coun...
14,142
8,373,710
I have recently started using a Mac OS X Lion system and tried to use Vim in terminal. I previously had a .vimrc file in my Ubuntu system and had `F2` and `F5` keys mapped to pastetoggle and run python interpreter. Here are the two lines I have for it: ``` set pastetoggle=<F2> map <buffer> <F5> :wa<CR>:!/usr/bin/env p...
2011/12/04
[ "https://Stackoverflow.com/questions/8373710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/501330/" ]
I finally got my function mappings working by resorting to adding mappings like this: ``` if has('mac') && ($TERM == 'xterm-256color' || $TERM == 'screen-256color') map <Esc>OP <F1> map <Esc>OQ <F2> map <Esc>OR <F3> map <Esc>OS <F4> map <Esc>[16~ <F5> map <Esc>[17~ <F6> map <Esc>[18~ <F7> map <Esc>[19~...
Regarding your colorscheme/solarized question - make sure you set up Terminal (or iTerm2, which I prefer) with the solarized profiles available in the full solarized distribution that you can download here: <http://ethanschoonover.com/solarized/files/solarized.zip>. Then the only other issue you may run into is makin...
14,143
67,712,314
Can anyone see what im doing wrong here? works fine locally, but when running it in docker it cant seem to find my modules ... The **init**.py files are emtpy if that info could help. Im no expert in docker and non of the tips I've googled/stackoverflowed so far has panned out, such as adding pythonpath env in the doc...
2021/05/26
[ "https://Stackoverflow.com/questions/67712314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14994913/" ]
After running `docker container run -it your-docker-container bash` and checked the files, it seems docker does not copy the file hierarchy as i expected. all files was under the same folder /app. none of my subfolder from the project in my local files were added, just the files those contained. No wonder i got ModuleN...
I had almost the same issue with this and I try to fix it not by changing the directory structure of my application or how I copy the files but by running the application directly using gunicorn. I run it with the following command : `gunicorn -k uvicorn.workers.UvicornWorker run:app` that can either be updated in t...
14,148
71,907,288
Question ======== What is the shortest and most efficient (preferrable most efficient) way of reading in a single depth folder and creating a file tree that consists of the longest substrings of each file? start with this --------------- ``` . ├── hello ├── lima_peru ├── limabeans ├── limes ├── limit ├── what_are_th...
2022/04/18
[ "https://Stackoverflow.com/questions/71907288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17356304/" ]
You are using the same input `ID` in `colorId` when you select the same group the second time. However, you need unique input `ID`s in shiny. I have added a counter to change it. Try this. ``` library(shinyjs) # useShinyjs library(ggplot2) library(RColorBrewer) library(shiny) ui <- fluidPage( titlePanel("Reprex"), ...
Following up with @YBS's response to my comment, I resorted to precomputing all the fields that could be made with the input file and using `conditionalPanel()` to selectively show them. This has the theoretical disadvantage that another file cannot be loaded in, but in practice I'm not seeing it. But I can use @YBS's...
14,149
3,510,846
Sorry if the question is bit confusing. This is similar to [this question](https://stackoverflow.com/questions/2553668/how-to-remove-list-of-words-from-strings) I think this the above question is close to what I want, but in Clojure. There is [another](https://stackoverflow.com/questions/3136689/find-and-replace-str...
2010/08/18
[ "https://Stackoverflow.com/questions/3510846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24382/" ]
Here is my stab at it. This uses regular expressions. ``` import re pattern = re.compile("(of|the|in|for|at)\W", re.I) phrases = ['of New York', 'of the New York'] map(lambda phrase: pattern.sub("", phrase), phrases) # ['New York', 'New York'] ``` Sans `lambda`: ``` [pattern.sub("", phrase) for phrase in phrases]...
``` >>> import re >>> noise_words_list = ['of', 'the', 'in', 'for', 'at'] >>> phrases = ['of New York', 'of the New York'] >>> noise_re = re.compile('\\b(%s)\\W'%('|'.join(map(re.escape,noise_words_list))),re.I) >>> [noise_re.sub('',p) for p in phrases] ['New York', 'New York'] ```
14,150
56,401,685
### Concepts of objects in python classes While reading about old style and new style classes in Python , term object occurs many times. What is exactly an object? Is it a base class or simply an object or a parameter ? for e.g. : New style for creating a class in python ``` class Class_name(object): pass ``` I...
2019/05/31
[ "https://Stackoverflow.com/questions/56401685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5084760/" ]
All objects in python are ultimately derived from "object". You don't need to be explicit about it in python 3, but it's common to explicitly derive from object.
Object is a generic term. It could be a class, a string, or any type. (and probably many other things) As an example look at the term OOP, "Object oriented programming". Object has the same meaning here.
14,156
63,046,777
I have in my utils.py the following functions which I use for debugging info ... ``` say = print log = print ``` I want to declare them in such a way, so that I can switch them ON/OFF. If possible on per module basis. F.e. let say I want to test something and enable/disable printing ... I don't want to use loggi...
2020/07/23
[ "https://Stackoverflow.com/questions/63046777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1019129/" ]
You can always redefine say/log to do nothing later on. ``` Python 3.8.2 (default, Apr 27 2020, 15:53:34) [GCC 9.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> say = print >>> say("hello") hello >>> def say(*args, **kwargs): ... return None ... >>> say("hello") >>> ```
You could used `sys.stdout.write("\033[K")` to overwrite/clear the previous line at the terminal when you don't want it logged or like: ``` def removeLine(dontWant): if dontWant == True: sys.stdout.write("\033[K") ``` where dontWant is set within the module or class or as a glob even or whatever based on...
14,161
55,437,583
I would like to convert HTML code to JavaScript. Currently I can send a message from the HTML file to a python server, which is then reversed and sent back to the HTML through socket io. I used this tutorial: <https://tutorialedge.net/python/python-socket-io-tutorial/> What I want to do now is rather than send the mes...
2019/03/31
[ "https://Stackoverflow.com/questions/55437583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8973785/" ]
Script tags don't work in node. You need to use require to import modules. You can use the [socket.io client](https://www.npmjs.com/package/socket.io-client) module to connect to socket io using node. Note that you'll have to `npm install` it before use Example connection code adapted from socket.io client readme: `...
`<script>` tags are HTML tags - you can't have them in a JavaScript file. Just place your JavaScript: ``` const socket = io("http://localhost:8080"); function sendMsg() { socket.emit("message", "HELLO WORLD"); } socket.on("message", function(data) { console.log(data); }); ```
14,163
27,925,447
I have the following dataframe. ``` c1 c2 v1 v2 0 a a 1 2 1 a a 2 3 2 b a 3 1 3 b a 4 5 5 c d 5 0 ``` I wish to have the following output. ``` c1 c2 v1 v2 0 a a 2 3 1 b a 4 5 2 c d 5 0 ``` The rule. First group dataframe by c1, c2. Then...
2015/01/13
[ "https://Stackoverflow.com/questions/27925447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2063033/" ]
I wanted to add a comment, but my reputation doesn't allow me :). So I will risk posting an incomplete answer here.. As a common practice, when you have a form to submit, you should use @using (Html.BeginForm()). This will take care of all the technicalities of having a form and avoid unnecessary errors (which I can't...
The proper way to redirect is to return RedirectResult. In your case it seems to be: ``` [HttpGet] public ActionResult Create(Clients client) { if (ModelState.IsValid) { _db.Clients.Add(client); _db.SaveChanges(); } return new Red...
14,164
15,587,311
``` def parabola(h, k, xCoordinates): ``` h is the x coordinate where the parabola touches the x axis and k is the y coordinate where the parabola intersects the y axis and xCoordinates is a list of x coordinates along the major axis. The function returns a list of y coordinates using the equation shown below. There ...
2013/03/23
[ "https://Stackoverflow.com/questions/15587311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` pricing::pricing(void) { m(10,0.0,0.01,50); } ``` This attempts to *call* `m` as though it were a function (if it had overloaded `operator()`, you would be able to do this, which is what the error is talking about). To initialise `m` instead, use the member initialization list: ``` pricing::pricing(void) : m(1...
pricing.cpp ``` #include "pricing.h" pricing::pricing() : m(10,0.0,0.01,50) { } double pricing::expectedValue() { return m.samplePaths[2][3]; } ``` pricing.h ``` #ifndef PRICING_H #define PRICING_H #include "monteCarlo.h" #include <vector> class pricing { public: pricing(); double euroCall(); ...
14,165
15,820,247
Raymond Hettinger surprised quite a few people when he showed slides 36 and 37. <https://speakerdeck.com/pyconslides/transforming-code-into-beautiful-idiomatic-python-by-raymond-hettinger> -- Many people knew that the with statement could be used for opening files, but not these new things. Looking at python 3.3 docs o...
2013/04/04
[ "https://Stackoverflow.com/questions/15820247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/411046/" ]
First, you don't ask if something is "withable", you ask if it's a "context manager".\* For example, in the docs you linked (which are from 3.1, not 3.3, by the way): > > Currently, `Lock`, `RLock`, `Condition`, `Semaphore`, and `BoundedSemaphore` objects may be used as `with` statement context managers. > > > M...
afaik any class/object that that implements `__exit__` method (you may also need to implement `__enter__`) ``` >>>dir(file) #notice it includes __enter__ and __exit__ ``` so ``` def supportsWith(some_ob): if "__exit__" in dir(some_ob): #could justas easily used hasattr return True ```
14,166
46,439,557
I have a .txt file, each line is in the format like this 1 2,10 3,20 2 6,87 . . . This file actually represents a graph, line 1 says that Vertex 1 have directed edge to vertex 2 and the length is 10, vertex 1 also have directed edge to vertex 3 and the length is 20. Line 2 says that Vertex 2 only have one directe...
2017/09/27
[ "https://Stackoverflow.com/questions/46439557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8680259/" ]
Providing you have a method that takes `[FromBody]TestStatus status` as a parameter. * Click on **Body** tab and select **raw**, then JSON(application/json). * Use this Json: ``` { "TestStatus": "expiredTest" } ``` * Send! I think above is your case as you stated: "take enum object as a body". Below are some mo...
Just pass 0,1,2... interger in the json body to pass enum objects. Choose 0 if required to pass the first enum object. Exmple: { "employee": 0 }
14,168
47,483,015
I have these settings ``` EMAIL_HOST = 'smtpout.secureserver.net' EMAIL_HOST_USER = 'username@domain.com' EMAIL_HOST_PASSWORD = 'password' DEFAULT_FROM_EMAIL = 'username@domain.com' SERVER_EMAIL = 'username@domain.com' EMAIL_PORT = 465 EMAIL_USE_TLS = True SMTP_SSL = True ``` Speaking to Godaddy I have found out th...
2017/11/25
[ "https://Stackoverflow.com/questions/47483015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333598/" ]
This worked for me with my GoDaddy email. Since GoDaddy sets up your email in Office365, you can use smtp.office365.com. settings.py ``` EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.office365.com' EMAIL_HOST_USER = 'myemail@GoDaddyDomain.com' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER E...
I found this code worked for me.. Hope this will be useful to somebody. I was using SMTP godaddy webmail..you can put this code into your django setting file. Since you cannot set Both SSL and TSL together... if you do so you get the error something as, **At one time either SSL or TSL can be true....** setting....
14,170
11,027,749
What's going on? I tried iPython and the regular Python interpreter, both show ^[[A and ^[[B for the up and down arrows instead of previous commands. **Platform:** Ubuntu 12.04. **Python:** 2.7.3 installed with pythonbrew **Terminal:** iTerm 2 on Mac OSX 10.6, connected over SSH. Has never worked in the Python shel...
2012/06/14
[ "https://Stackoverflow.com/questions/11027749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1377021/" ]
Since you installed Python with pythonbrew, you must install the `libreadline-dev` package in your package manager *then* recompile Python. The package is named `libreadline-dev` or something similar in most Linux distributions (Ubuntu, Debian, Fedora...). This step is not required on Gentoo or Arch systems, which alw...
`libreadline-dev` was not enough, what solved it for me is to install the `readline` package: ``` pip install readline ```
14,179
3,663,762
In my models.py, I want to have an optional field to a foreign key. I tried this: ``` field = models.ForeignKey(MyModel, null=True, blank=True, default=None) ``` I am getting this error: ``` model.mymodel_id may not be NULL ``` I am using sqlite. In case it is helpful, here is the exception location: ``` /usr/l...
2010/09/08
[ "https://Stackoverflow.com/questions/3663762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/440221/" ]
If it was previously not null and you synced it before then resyncing won't change it. Either drop the table, use a migration tool such as South, or alter the column in SQL directly.
I believe that it has to be both `null=True` and `blank=True`.
14,180
36,648,800
I have a BaseEntity class, which defines a bunch (a lot) of non-required properties and has most of functionality. I extend this class in two others, which have some extra methods, as well as initialize one required property. ``` class BaseEntity(object): def __init__(self, request_url): self.clearAllFilt...
2016/04/15
[ "https://Stackoverflow.com/questions/36648800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2521764/" ]
One way to do it: ``` import copy class A(object): def __init__(self, sth, blah): self.sth = sth self.blah = blah def do_sth(self): print(self.sth, self.blah) class B(A): def __init__(self, param): self.param = param def do_sth(self): print(self.param, self.s...
I had the same problem as the OP and was able to use the idea from Radosław Łazarz above of explicitly setting the **class** attribute of the object to the subclass, but without the deep copy: ``` class A: def __init__(a) : pass def amethod(a) : return 'aresult' class B(A): def __init__(b) : pass def ...
14,185
61,738,541
The first line works, but the second doesn't: ``` print(np.fromfunction(lambda x, y: 10 * x + y , (3, 5), dtype=int)) print(np.fromfunction(lambda x, y: str(10 * x + y), (3, 5), dtype=str)) [[ 0 1 2 3 4] [10 11 12 13 14] [20 21 22 23 24]] Traceback (most recent call last): File "<stdin>", line 1, in <modu...
2020/05/11
[ "https://Stackoverflow.com/questions/61738541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
They are both text files with code in them. The difference isn't in the files, but in how your webserver treats them. It is configured to run files with a `.php` extension though a PHP engine, and to serve up `.html` files directly.
You have to open the php file through an apache (or other php-handling) server. For instance, if you use XAMPP, and have index.php in the XAMPP directory, you would open a browser and go to localhost/index.php. The server then converts it into html, which a browser can handle.
14,186
24,821,340
First of all an introduction to my development environment: ``` OS: Windows. SDK: Microsoft Visual Studio 2008. ``` Earlier today I was facing the problem of trying to define a Timer inside a class. My class is interfacing a Python embedded module and a C++ backend, My problem is that I need to receive some time eve...
2014/07/18
[ "https://Stackoverflow.com/questions/24821340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3227543/" ]
Create a static map of your Class object: ``` static std::map<UINT_PTR, CMyClass*> m_CMyClassMap; //declaration ``` At the time of object creation insert the object in this map: ``` CMyClass myClassObj; CMyClassMap.insert(std::pair<int, CMyClass*>(0, &myClassObj)); ``` Now you can use it in static methods to acce...
So long as there is only one instance of this class, there is an easy (if somewhat ugly) solution: Declare your class object and then store a pointer to it in a global object. E.g., ``` MyClass myObject; MyClass* self = &myObject; ``` Then inside your static member, you can use self->myMethod() or self->myData to r...
14,187
14,140,902
I've run into a nasty little problem connecting to an Oracle schema via SQLAlchemy using a service name. Here is my code as a script. (items between angle brackets are place holders for real values for security reasons) ``` from sqlalchemy import create_engine if __name__ == "__main__": ...
2013/01/03
[ "https://Stackoverflow.com/questions/14140902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165435/" ]
I've found the answer you have to use the same connection string that would be used in a tnsnames.ora file in the connection string after the '@" like so ``` from sqlalchemy import create_engine if __name__ == "__main__": ...
cx\_Oracle supports the passing of a service\_name to the makedsn function. <http://cx-oracle.sourceforge.net/html/module.html?highlight=makedsn#cx_Oracle.makedsn> It would be nice if the create\_engine() API passed the service\_name through to the underlying call it makes to makedsn...something like this: ``` oracl...
14,188
36,234,988
I feel it is a more general question, but here is an example I am considering: I have a python class which during its initialization goes through a zip archive and extracts some data. Should the code-chunk below be written explicitly inside the "def init" or should it be made as a method outside which will be called ...
2016/03/26
[ "https://Stackoverflow.com/questions/36234988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3286832/" ]
If you want to execute the statements you are showing in more then one place, then there's really no discussion. Without a method or a function for this task, you will be violating the [DRY](http://c2.com/cgi/wiki?DontRepeatYourself) principle. Otherwise... well I'd write a method regardless. The task you are showing ...
It is perfectly fine for `__init__()` to call other functions, including methods of the same class.
14,193
52,827,722
What is the naming convention in python community to set names for project folders and subfolders? ``` my-great-python-project my_great_python_project myGreatPythonProject MyGreatPythonProject ``` I find mixed up in the github. Appreciate your expert opinion.
2018/10/16
[ "https://Stackoverflow.com/questions/52827722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5164382/" ]
There are three conventions, which you might find confusing. 1. The standard [PEP8](https://www.python.org/dev/peps/pep-0008/) defines a standard for how to name packages and modules: > > Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python pa...
> > Python packages should also have short, all-lowercase names, although the use of underscores is discouraged. [Pep 8 Style Guide](https://www.python.org/dev/peps/pep-0008/#naming-conventions) > > > This is the recommendation for packages, which is the main folder containing modules, for testing, setup, and scri...
14,194
58,475,837
I am trying to learn the functional programming way of doing things in python. I am trying to serialize a list of strings in python using the following code ``` S = ["geeks", "are", "awesome"] reduce(lambda x, y: (str(len(x)) + '~' + x) + (str(len(y)) + '~' + y), S) ``` I am expecting: ``` 5~geeks3~are7~awesome `...
2019/10/20
[ "https://Stackoverflow.com/questions/58475837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6101835/" ]
`reduce` function on each current iteration relies on previous item/calculation (the nature of all ***reduce*** routines), that's why you got `12` at the start of the resulting string: on the 1st pass the item was `5~geeks3~are` with length `12` and that was used/prepended on next iteration. Instead, you can go with s...
The `reduce` function is for aggregation. What you're trying to do is mapping instead. You can use the `map` function for the purpose: ``` ''.join(map(lambda x: str(len(x)) + '~' + x, S)) ``` This returns: ``` 5~geeks3~are7~awesome ```
14,197
70,765,867
I have been trying to use github actions to deploy a docker image to AWS ECR, but there is a step that is consistently failing. Here is the portion that is failing: ``` - name: Pulling ECR for updates and instantiating new updated containers. uses: appleboy/ssh-action@master with: host: ${{s...
2022/01/19
[ "https://Stackoverflow.com/questions/70765867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17970861/" ]
Welcome to StackOverflow and the joys of programming and the cloud! It seems that the AWS CLI is failing to configure the access key id and secret on the pipeline. In order to solve this and make it easier to manage in the long run, I would recommend using the pre-built actions from AWS to ease your pipeline's setup p...
Actually, I just had to install AWS CLI on my EC2 instance, but thank you so much for the help!
14,201
55,966,757
When (and why) was the Python `__new__()` function introduced? There are three steps in creating an instance of a class, e.g. `MyClass()`: * `MyClass.__call__()` is called. This method must be defined in the metaclass of `MyClass`. * `MyClass.__new__()` is called (by `__call__`). Defined on `MyClass` itself. This cre...
2019/05/03
[ "https://Stackoverflow.com/questions/55966757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2097/" ]
The blog post [**`The Inside Story on New-Style Classes`**](http://python-history.blogspot.com/2010/06/inside-story-on-new-style-classes.html) (from the aptly named **`http://python-history.blogspot.com`**) written by [**`Guido van Rossum`**](https://en.wikipedia.org/wiki/Guido_van_Rossum) (Python's BDFL) provides som...
I will not explain the history of `__new__` here because I have only used Python since 2005, so after it was introduced into the language. But here is the rationale behind it. The *normal* configuration method for a new object is the `__init__` method of its class. The object has already been created (usually via an i...
14,202
40,007,305
I am using kivy to create a small Gui for my python program. This Gui is not always visible. So I start it with these settings: ``` Config.set('graphics', 'borderless', True) Config.set('graphics', 'resizable', False) Config.set('graphics', 'window_state', 'hidden') ``` However: Somewhere in my program I want to mak...
2016/10/12
[ "https://Stackoverflow.com/questions/40007305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2129897/" ]
It seems that if you are using the SDL provider you have a **hide & show** functions on the Window object from the kivy.core.window docs: ``` hide() Added in 1.9.0 Hides the window. This method should be used on desktop platforms only. Note This feature requires the SDL2 window provider and is currently only support...
I'm not familiar with Kivy, but it looks like you just need to set it to visible. `window_state`: string , one of 'visible', 'hidden', 'maximized' \ or 'minimized' from: <https://kivy.org/docs/_modules/kivy/config.html> Looking at this github post: <https://github.com/kivy/kivy/issues/3637> The method they're usin...
14,203
9,724,872
I have a python (django) web application. It uses an external web service (Facebook Graph). All the code for making external (http) calls is wrapped in one extra function (called `facebook_api`), which takes some arguments and returns a parsed dict (it does some logging, checks for errors etc.) Around this function, I ...
2012/03/15
[ "https://Stackoverflow.com/questions/9724872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161922/" ]
I think you are looking for [Mock's side\_effect](http://www.voidspace.org.uk/python/mock/mock.html#mock.Mock.side_effect) . For example ``` def my_facebook_api(input): if input=='A': return 'X' elif input=='B': return 'D' facebook_api = Mock(side_effect=my_facebook_api) ```
I have been using mockito-python (<http://code.google.com/p/mockito-python/>) with a good success. It allows you to specify behaviour of mocks with simple syntax (straight from their documentation): ``` >>> dummy = mock() >>> when(dummy).reply("hi").thenReturn("hello") >>> when(dummy).reply("bye").thenReturn("good-bye...
14,204
11,021,853
The IPython documentation pages suggest that opening several different sessions of IPython notebook is the only way to interact with saved notebooks in different directories or subdirectories, but this is not explicitly confirmed anywhere. I am facing a situation where I might need to interact with hundreds of differe...
2012/06/13
[ "https://Stackoverflow.com/questions/11021853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567620/" ]
> > The IPython documentation pages suggest that opening several different sessions of IPython notebook is the only way to interact with saved notebooks in different directories or subdirectories, but this is not explicitly confirmed anywhere. > > > Yes, this is a current (*temporary*) limitation of the Notebook s...
The interface and architecture design issues for multiple directory support (and more generally for "project" support) for iPython notebook are important to get right. A design is described in [IPEP 16: Notebook multi directory dashboard and URL mapping](https://github.com/ipython/ipython/wiki/IPEP-16%3A-Notebook-mult...
14,206
13,586,153
**Objectives:** Implement a program (java or python) to retrieve data from videos that I published on my Youtube channel. This program will be launched daily (1:00 AM). **Solutions:** To retrieve data Youtube, including the number of views per day, YouTube Analytics API is in my opinion the best solution. I use the ...
2012/11/27
[ "https://Stackoverflow.com/questions/13586153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1856335/" ]
You can't use a service account when making a YouTube Analytics API request. You need to use an account that is either the owner of the YouTube channel or a content owner associated with the channel, and I don't believe a service account can be either of those things. Please go through the OAuth 2 flow once while signe...
Yes you can authenticate for any of Youtubes APIs using a Service Account. The service account and the account you want to work with, have to be in the same CMS. (note for Youtube-Partner-Channels you will also need to set their content-owner-ID, when calling the API). How it works for me: I generate an access\_token...
14,207
53,259,674
it 's possible to put a variable into the path in python/linux for example : ``` >>>counter = 0; >>>image = ClImage(file_obj=open('/home/user/image'counter'.jpeg', 'rb')) ``` I have syntax error when i do that.
2018/11/12
[ "https://Stackoverflow.com/questions/53259674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9100401/" ]
You could use an [f-string](https://www.python.org/dev/peps/pep-0498/) if you’re working in python 3.6+ This is the most efficient method. ``` counter = 0 filepath = f"/home/user/image{counter}.jpeg" image = ClImage(file_obj=open(filepath, 'rb')) ``` Otherwise the second best would be using the [.format()](https://...
You can use Python's [.format()](https://realpython.com/python-string-formatting/) method: ``` counter = 0 filepath = '/home/user/image{0}.jpeg'.format(counter) image = ClImage(file_obj=open(filepath, 'rb')) ```
14,208
36,551,531
**My Flume configuration** ``` source_agent.sources = tail source_agent.sources.tail.type = exec source_agent.sources.tail.command = python loggen.py source_agent.sources.tail.batchSize = 1 source_agent.sources.tail.channels = memoryChannel #memory-channel source_agent.channels = memoryChannel source_agent.channels...
2016/04/11
[ "https://Stackoverflow.com/questions/36551531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3536400/" ]
You can use --jars option if you are running the job using spark-submit For Ex: ``` spark-submit --jars ....../lib/spark-streaming_2.10-1.2.1‌​.2.2.6.0-2800.jar ``` or add this to your SBT configuration ``` libraryDependencies += "org.apache.spark" %% "spark-streaming-flume" % "2.1.0" ``` <https://spark.apache.o...
Add this to your build to get rid of this error: ``` <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-streaming-flume_2.10 --> <dependency> <groupId>org.apache.spark</groupId> <artifactId>spark-streaming-flume_2.10</artifactId> <version>2.0.0</version> ...
14,210
27,218,638
I need to replace `\` into `\\` with python from pattern matching. For example, `$$\a\b\c$$` should be matched replaced with `$$\\a\\b\\c$$`. I couldn't use the regular expression to find a match. ``` >>> import re >>> p = re.compile("\$\$([^$]+)\$\$") >>> a = "$$\a\b\c$$" >>> m = p.search(a) >>> m.group(1) '\x07\x...
2014/11/30
[ "https://Stackoverflow.com/questions/27218638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
The reason you're having trouble is because the string you're inputting is `$$\a\b\c$$`, which python translates to `'$$\x07\x08\\c$$'`, and the only back slash in the string is actually in the segment '\c' the best way to deal with this would be to input a as such ``` a=r'$$\a\b\c$$' ``` This will tell python to co...
Split the string with single backslashes, then join the resulting list with double backslashes. ``` s = r'$$\a\b\c$$' t = r'\\'.join(s.split('\\')) print('%s -> %s' % (s, t)) ```
14,211
67,687,962
I am trying to build a Word2vec model but when I try to reshape the vector for tokens, I am getting this error. Any idea ? ``` wordvec_arrays = np.zeros((len(tokenized_tweet), 100)) for i in range(len(tokenized_tweet)): wordvec_arrays[i,:] = word_vector(tokenized_tweet[i], 100) wordvec_df = pd.DataFrame(wordvec_a...
2021/05/25
[ "https://Stackoverflow.com/questions/67687962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8020986/" ]
As of Gensim 4.0 & higher, the `Word2Vec` model doesn't support subscripted-indexed access (the `['...']') to individual words. (Previous versions would display a deprecation warning,` Method will be removed in 4.0.0, use self.wv.**getitem**() instead`, for such uses.) So, when you want to access a specific word, do i...
use the following method: ``` model.wv.get_item() ```
14,212
58,945,475
I'm somewhat new to python: I'm trying to write a text file into a different format. Given a file of format: ``` [header] rho = 1.1742817531 mu = 1.71997e-05 q = 411385.1046712013 ... ``` I want: ``` [header] 1.1742817531, 1.71997e-05, 411385.1046712013, ... ``` and be able to write successive lines below...
2019/11/20
[ "https://Stackoverflow.com/questions/58945475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12400757/" ]
Cache the images on the filesystem when you first download them. When you load an image, check the cache, and download the images only if they're not yet cached. If they are, load them from the filesystem instead.
Try using glide or Picasso to load images in different list views. Glide internally caches images using their url as a key to retrieve cache. That way when your images are loaded once in any of your list view, they can be cached for future use in other list views. However, you will still need to create new instances of...
14,215
57,464,098
I am currently doing some exercises with Kernel Density Estimation and I am trying to run this piece of code: ```py from sklearn.datasets import load_digits from sklearn.model_selection import GridSearchCV digits = load_digits() bandwidths = 10 ** np.linspace(0, 2, 100) grid = GridSearchCV(KDEClassifier(), {'bandwid...
2019/08/12
[ "https://Stackoverflow.com/questions/57464098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11491321/" ]
It's simple, I also face the same problem, Just replace this line- ``` scores = [val.mean_test_score for val in grid.cv_results_] ``` with ``` scores = grid.cv_results_.get('mean_test_score').tolist() ``` Because, 'mean\_test\_score' is depricated and grid.cv\_results\_ is in dict format.
The [documentation](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html) of the object `GridSearchCV` specifies that the attribute `cv_results_` is a dictionary, therefore, iterating over a python dictionary returns the strings of the keys as you can se [here](https://realpython....
14,216
20,386,727
Currently I have data in the following format ``` A A -> B -> C -> D -> Z A -> B -> O A -> X ``` This is stored in a list [line1,line2, and so forth] Now I want to print this in the following manner ``` A |- X |- B |- O |- C |- D |- Z ``` I'm new to python so. I was thinking of find...
2013/12/04
[ "https://Stackoverflow.com/questions/20386727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2838679/" ]
1. You don't modify method parameters, you make copies of them. 2. You don't null-check/empty-check inside the loop, you do it first thing in the method. 3. The standard in a `for loop` is `i < size`, not `size > i`... meh ``` /** * Splits the string str into individual characters: Small becomes S m a l l */ public...
Ask yourself a question, where is **s** coming from? ``` char space = s.charAt(); ??? s ??? ``` A second question, character at? ``` public static String split(String str){ for(int i = 0; i < str.length(); i++) { if (str.length() > 0) { char space = str.charAt(i) } } return s...
14,217
54,174,950
**Context** I am trying to run my Django application and Postgres database in a docker development environment using docker-compose (it's my first time using Docker). I want to use my application with a custom role and database both named `teddycrepineau` (as opposed to using the default postgres user and db). **G...
2019/01/14
[ "https://Stackoverflow.com/questions/54174950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5022051/" ]
This happens because your pgsql db was launched without any envs. The pgsql docker image only uses the envs the first time you created the container, after that it won't recreate DB and users. The solution is to remove the pgsql volume so next time you `docker-compose up` you will have a fresh db with envs read. Simpl...
Change your env order like this. ``` POSTGRES_DB=teddycrepineau POSTGRES_USER=teddycrepineau POSTGRES_PASSWORD= ``` I find it at [this issue](https://github.com/docker-library/postgres/issues/41#issuecomment-382925263). I hope it works.
14,221
47,031,382
I am using PyTorch with python3. I tried the following while in ipdb mode: ``` regions = np.zeros([107,4], dtype='uint8') torch.from_numpy(regions) ``` This prints the tensor. However when trying: ``` regions = np.zeros([107,107,4], dtype='uint8') torch.from_numpy(regions) ``` I get the following error: ``` ***...
2017/10/31
[ "https://Stackoverflow.com/questions/47031382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683130/" ]
``` Pleas make sure our AWS S3 configuration : <CORSConfiguration> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CO...
One of your uploads is failing. You will need to catch the error from s3Client.uploadPart() and retry. I recommend the following improvements on the simple code below. 1) Add an increasing timeout for each retry. 2) Process the type of error to determine if a retry will make sense. For some errors you should just re...
14,226
55,210,888
I faced with problem when I installed python-pptx with conda on cleaned environment: conda install -c conda-forge python-pptx. After install was successfully finished I tried to import pptx module and got following error: > > > ``` > >>> import pptx > Traceback (most recent call last): > File "<stdin>", line 1, i...
2019/03/17
[ "https://Stackoverflow.com/questions/55210888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9869122/" ]
If you are allowed to use built-in functions, you could do this: ``` idx = s[::-1].find(c[::-1]) return len(s) - (idx + len(c)) if idx >= 0 else -1 ```
Your problem is this line: ``` last_position = next_position + len(c) ``` This is skipping potential matches. As it is, your code considers only the first, third, and fifth positions for matches. As you say, the right answer comes from checking the fourth position (index == 3). But you're skipping that because you m...
14,229
49,105,693
I have the following code: ``` import csv import requests from bs4 import BeautifulSoup import datetime with open("D:/python/sursa_alimentare.csv", "w+") as f: writer = csv.writer(f) writer.writerow(["Descriere", "Pret"])` ``` Because I run this quite often, I want to save the csv file with a na...
2018/03/05
[ "https://Stackoverflow.com/questions/49105693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8947024/" ]
you have to use `.strftime` ``` filename = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M.csv") with open(filename, "w+") as f: writer = csv.writer(f) writer.writerow(["Descriere", "Pret"])` ``` here is some details <https://www.tutorialspoint.com/python/time_strftime.htm>
I guess this might help you add datetime to your filename, ``` import csv import requests from bs4 import BeautifulSoup import datetime file_name = 'sursa_alimentare-'+str(datetime.datetime.now())+'.csv' with open(file_name, "w+") as f: writer = csv.writer(f) writer.writerow(["Descriere", "Pret"]) ``...
14,231
21,265,633
I need to read a huge (larger than memory) unquoted TSV file. Fields may contain the string "\n". However, python tries to be clever and split that string in two. So for example a row containing: ``` cat dog fish\nchips 4.50 ``` gets split into two lines: ``` ['cat', 'dog', 'fish'] ['chips', 4.5] ``` Wha...
2014/01/21
[ "https://Stackoverflow.com/questions/21265633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2400966/" ]
This already works correctly; for a file with a literal `\` followed by a literal `n` character (two bytes), will **never** be seen by Python as a newline. What you have, then, is a single `\n` character, an actual newline. The *rest* of your file is separated by the `\r\n` Windows conventional line separator. Use [`...
If your problem is .readline() and splitting on \t, try using the csv builtin: ``` import csv with open(path, 'r') as file: reader = csv.Reader(file, delimiter='\t') # Or DictReader - I like DictReader. reader.next() ``` It handles these things for us.
14,233
20,998,832
I've ran the brown-clustering algorithm from <https://github.com/percyliang/brown-cluster> and also a python implementation <https://github.com/mheilman/tan-clustering>. And they both give some sort of binary and another integer for each unique token. For example: ``` 0 the 6 10 chased 3 11...
2014/01/08
[ "https://Stackoverflow.com/questions/20998832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
If I understand correctly, the algorithm gives you a tree and you need to truncate it at some level to get clusters. In case of those bit strings, you should just take first `L` characters. For example, cutting at the second character gives you two clusters ``` 10 chased 11 dog 11 ...
My guess is: According to Figure 2 in [Brown et al 1992](http://acl.ldc.upenn.edu/J/J92/J92-4003.pdf), the clustering is hierarchical and to get from the root to each word "leaf" you have to make an up/down decision. If up is 0 and down is 1, you can represent each word as a bit string. From <https://github.com/mhei...
14,234
43,303,575
I am trying to install Cassandra on windows 10 localhost. I am getting error as `Can't detect Python version!` I am trying this way Downloaded and extracted Cassandra in `C:\wamp64\apache-cassandra-3.10` Set `Set-ExecutionPolicy Unrestricted` in Windows powershell From Windows CMD ``` cd C:\wamp64\apache-cassandra...
2017/04/09
[ "https://Stackoverflow.com/questions/43303575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have installed latest version of Apache Cassandra 3.11.9 for Windows, My python env variable is already set for python3 (Python 3.8), as I actively use python 3.8. I was continuously getting error, then I installed python2 inside 'Apache Cassandra 3.11.9\bin'. I need not to reset my env variable to python2. The more...
I think you are following wrong python installation procedures. **please uninstall all the python instances using programs and features section in control panel. then install python obtained from [python.org](https://www.python.org/). ensure add to path option is checked on the time of installation. verify python insta...
14,243
67,281,038
I have wrote a code for face recognition in python. My code works perfectly in `.py` file (without any errors or warning), but after making a `.exe` file out of it, through `pyinstaller` it won't work at all. I have searched through, for the same and tried the following methods, but it still won't work. first method i ...
2021/04/27
[ "https://Stackoverflow.com/questions/67281038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14332805/" ]
First of all, make sure your function app can be compiled. Second, the format of your publish url is no problem. So maybe this problem is not from the Visual Studio side. please make sure the function app is not stop or restarting, the scm site is not under the protection of NETWorking and you have login the right Mi...
In my case opening azure functions app in my browser helped. Until that it was giving error when I try to publish it in Visual Studio.
14,245
45,457,324
I have set up a spark cluster and all the nodes have access to network shared storage where they can access a file to read. I am running this in a python jupyter notebook. It was working a few days ago, and now it stopped working but I'm not sure why, or what I have changed. I have tried restarting the nodes and maste...
2017/08/02
[ "https://Stackoverflow.com/questions/45457324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8236204/" ]
From the error it looks like it is checking the file on your local system. Just make sure that you have file present on specified Path. Also try below suggestions. 1. try with file URI : file:///nas/file123.csv 2. Upload the file on HDFS and try to read the file from HDFS URI like hdfs:///... Hope this helps. Regard...
If you are loading the data from local directory, remember to make sure file exists in all of your worker nodes.
14,246
62,246,786
I would like to run my scrapy sprider from python script. I can call my spider with the following code, ``` subprocess.check_output(['scrapy crawl mySpider']) ``` Untill all is well. But before that, I instantiate the class of my spider by initializing the start\_urls, then the call to scrapy crawl doesn't work sin...
2020/06/07
[ "https://Stackoverflow.com/questions/62246786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13700256/" ]
``` stock = {'meat':100,'fish':100,'bread':100, 'milk':100,'chips':100} total = 0 for v in stock.values(): total += v ```
``` >>> from statistics import mean >>> stock={'meat':100,'fish':100,'bread':100, 'milk':100,'chips':100} >>> print(f"Total stock level : {mean(stock.values())*len(stock)}") Total stock level : 500 ```
14,247
56,128,397
I pulled the official mongo image from the Docker website and started a mongo container named `dataiomongo`. I now want to connect to the mongodb inside the container using pymongo. This is the python script I wrote: ``` from pprint import pprint from pymongo import MongoClient client = MongoClient('localhost', p...
2019/05/14
[ "https://Stackoverflow.com/questions/56128397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5684940/" ]
run mongo ========= First you need to run mongo ``` $ docker run --rm --name my-mongo -it -p 27017:27017 mongo:latest ``` as a daemon =========== ``` $ docker run --name my-mongo -d mongo:latest ``` connect to the previous container.. with another container =======================================================...
Make sure you bind the 27017 container port to host port via -p 27017:27017 flag.
14,251
56,803,812
I want to include a cron task in a MariaDB container, based on the latest image `mariadb`, but I'm stuck with this. I tried many things without success because I can't launch both MariaDB and Cron. Here is my actual dockerfile: ``` FROM mariadb:10.3 # DB settings ENV MYSQL_DATABASE=beurre \ MYSQL_ROOT_PASSWORD=...
2019/06/28
[ "https://Stackoverflow.com/questions/56803812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9678258/" ]
Elaborating on @k0pernikus's comment, I would recommend to use a separate container that runs cron. The cronjobs in that container can then work with your mysql database. Here's how I would approach it: 1. Create a Cron Docker Container ================================= You can set up a cron container fairly simply....
I recommend the [solution provided by fjc](https://stackoverflow.com/a/56804227/457268). Treat this as nice-to-know to understand why your approach is not working. --- Docker has `RUN` commands that are only being executed during build. Not on container startup. It also has a `CMD` (or ENTRYPOINT) for executing spec...
14,254
62,827,871
I'm looking for a compiler to compile '.py' file to a single '.exe' file. I've try already **auto-py-to-exe** but I'm not happy with it. I've tried **PyInstaller**, but one of its dependencies (PyCrypto, which I need) is not working/ maintained anymore and fails to install. <https://pyinstaller.readthedocs.io/en/stab...
2020/07/10
[ "https://Stackoverflow.com/questions/62827871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11943028/" ]
I had a similar issue to this, needing to run Python code on machines where Python could not be downloaded. I used py2exe, and it worked quite well. (<https://www.py2exe.org/>)
You could try these **steps to convert .py to .exe in Python 3.8** 1. Install [Python 3.8](https://www.python.org/downloads/). 2. Install cx\_Freeze, (open your command prompt and type `pip install cx_Freeze`. 3. Install idna, (open your command prompt and type `pip install idna`. 4. Write a `.py` a program named `myf...
14,255
64,764,650
Say that there are two iterators: ``` def genA(): while True: yield 1 def genB(): while True: yield 2 gA = genA() gB = genB() ``` According to [this SO answer](https://stackoverflow.com/a/8770796/3259896) they can be ***evenly*** interleaved using the [`itertools` recipes](https://docs.pyth...
2020/11/10
[ "https://Stackoverflow.com/questions/64764650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3259896/" ]
If you're okay with a deterministic approach (as I understand from your self-answer), you can add an argument which is the percentage of the first iterator and then just calculate each iterator's "part". For example, if you want `.75` from the first iterator - this translates to: *for every **three** elements from `ite...
``` def genA(): while True: yield 1 def genB(): while True: yield 2 gA = genA() gB = genB() import random def xyz(itt1, itt2): while True: if random.random() < .25: yield next(itt1) else: yield next(itt2) newGen = xyz(gA, gB) next(newGen) ``` T...
14,256
19,965,453
Im making a multipart POST using the python package requests. Im using xlrd to change some values in an Excel file save it then send that up in a multipart POST. This working fine when I run it locally on my mac but when I put the code on a remote machine and make the same request the body content type is blank where a...
2013/11/13
[ "https://Stackoverflow.com/questions/19965453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946337/" ]
The `files` parameter accepts a dictionary of keys to tuples, with the following form: ``` files = {'name': (<filename>, <file object>, <content type>, <per-part headers>)} ``` In your specific case, you could write this: ``` files = {'file': ('filename.xls', open('filename.xls'), 'application/vnd.ms-excel', {})} ...
I believe you can use the headers parameter, e.g ``` requests.post(url, data=my_data, headers={"Content-type": "application/vnd.ms-excel"}) ```
14,257
29,686,328
Edit: Rather than vote me down can you provide an url on where you would recommend a newbie learn Python? Be part of the solution versus problem. I'm trying to compile a basic program (for a class) that when specific if/elif/else conditions are met a specific roman numeral shows though I'm a bit confused on why I'm ge...
2015/04/16
[ "https://Stackoverflow.com/questions/29686328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4259649/" ]
``` else(number==3): print("The number is X") ``` Is incorret. You should use only ``` else : print("The number is X") ```
Just use `else:` instead of `else(number==3)`. `else:` doesn't take a condition. Also, you don't need to put parentheses around the conditions in Python.
14,258
67,017,354
**My problem**: starting a threaded function and, **asynchronously**, act upon the returned value I know how to: * start a threaded function with `threading`. The problem: no simple way to get the result back * [get the return value](https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-threa...
2021/04/09
[ "https://Stackoverflow.com/questions/67017354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/903011/" ]
You can use [`concurrent.futures.add_done_callback`](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.add_done_callback) as shown below. The callback must be a callable taking a single argument, the `Future` instance — and it must get the result from that as shown. The example also ad...
You can use [add\_done\_callback](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.add_done_callback) of `concurrent.futures` library, so you can modify your example like this: ```py def the_callback(something): print(f"the thread returned {something.result()}") with concurrent....
14,261
6,969,222
Every time I run my code in Python IDLE development environment, I get a Visual C++ runtime error/unhandled exception in pythonw.exe. ``` Figure 1: pythonw.exe - Application Error The exception unknown software exception (0x40000015) occurred in the application at location 0x1e0e1379. ``` I am using networkx and ...
2011/08/06
[ "https://Stackoverflow.com/questions/6969222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264970/" ]
The easiest fix for this is to open IDLE from the start menu and then opening your code files from there.
The solution to this problem was indeed to quit using IDLE. I got the Python stuff for Eclipse; I'd recommend that setup.
14,262
45,530,741
I'm trying to run my code with a multiprocessing function but mongo keep returning > > "MongoClient opened before fork. Create MongoClient with > connect=False, or create client after forking." > > > I really doesn't understand how i can adapt my code to this. Basically the structure is: ``` db = MongoClient()...
2017/08/06
[ "https://Stackoverflow.com/questions/45530741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3476027/" ]
db.authenticate will have to connect to mongo server and it will try to make a connection. So, even though connect=False is being used, db.authenticate will require a connection to be open. Why don't you create the mongo client instance after fork? That's look like the easiest solution.
Since `db.authenticate` must open the MongoClient and connect to the server, it creates connections which won't work in the forked subprocess. Hence, the error message. Try this instead: ``` db = MongoClient('mongodb://user:password@localhost', connect=False).database ``` Also, delete the Lock `l`. Acquiring a lock ...
14,263
21,687,643
I am working on a large scale project that involves giving a python script a first name and getting back a result as to what kind of gender it belongs to. My current program is written in Java and using Jython to interact with a Python script called "sex machine." It works great in most cases and I've tested it with sm...
2014/02/10
[ "https://Stackoverflow.com/questions/21687643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1461393/" ]
I don't know if it helps but this is what I did and it works for me. ``` public static void main(String[] args){ PythonInterpreter pI = new PythonInterpreter(); pI.exec("x = 3"); PyObject result = pI.get("x"); System.out.println(result); } ```
Not sure if you sorted this out, but have an extra apostrophe on ``` d.get_gender('Christinewazonek'') ``` Just like in Java, everything you open you need to close, and in this case you opened a string containing `)\n")` which was not closed. Depending on the interpreter you are using, this can be flagged easily. ...
14,265
34,132,484
i have a large string like ``` res = ["FAV_VENUE_CITY_NAME == 'Mumbai' & EVENT_GENRE == 'KIDS' & count_EVENT_GENRE >= 1", "FAV_VENUE_CITY_NAME == 'Mumbai' & EVENT_GENRE == 'FANTASY' & count_EVENT_GENRE >= 1", "FAV_VENUE_CITY_NAME =='Mumbai' & EVENT_GENRE == 'FESTIVAL' & count_EVENT_GENRE >= 1", "FAV_VENUE_CITY_NAME =...
2015/12/07
[ "https://Stackoverflow.com/questions/34132484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5533254/" ]
The latest d.ts file now has the component method. Update yours with `tsd update -o`
We had a kinda similar issue earlier today and it was to do with using Angular 1.5. Beta 1 which doesn't contain the component function. To fix it we had to upgrade to Angular 1.5 Beta 2 which does contain the component functon.
14,266
70,921,901
I have been trying to fetch the metadata from a KDB+ Database using python, basically, I installed a library called **`qpython`** and using this library we connect and query the KDB+ Database. I want to store the metadata for all the appropriate cols for a table/view in KDB+ Database using python. I am unable to separ...
2022/01/31
[ "https://Stackoverflow.com/questions/70921901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12553730/" ]
The metadata that you have returned from kdb is correct but is being displayed in python as a kdb dictionary format which I agree is not very useful. If you pass the pandas=True flag into your qconnection call then qPython will parse kdb datastructures, such as a table into pandas data structures or sensible python ty...
In the meantime, I have checked quite a bit of KBD documentation and found that the metadata provides the following as the output. You can see that here [kdb metadata](https://code.kx.com/q4m3/8_Tables/) `c | t f a` c-columns t-symbol f-foreign key association a-attributes associated with the column We can access th...
14,267
62,503,638
I have a data frame as shown below. which is a sales data of two health care product starting from December 2016 to November 2018. ``` product price sale_date discount A 50 2016-12-01 5 A 50 2017-01-03 4 B 200 2016-12-24 10 A ...
2020/06/21
[ "https://Stackoverflow.com/questions/62503638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8901845/" ]
The problem with the first query is that it returns no rows if there is 1 row (or less) in the table. It looks like they consider that an empty resultset is not the correct answer in this case. Instead, they always want one row as a result that contains a `null` value (which indicates the absence of the Nth salary in ...
This query: ``` SELECT DISTINCT Salary AS SecondHighestSalary -- (DISTINCT is really not needed) FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1 ``` in case the table has only 1 row, does not return `null`. It returns nothing (no rows). But when it is placed inside another query as a derived column: ``` S...
14,268
35,700,781
I have a small Python app that produces a form, the user enters some strings in and it collects them as an array and adds (or tries to) that array as a value of a key in Google's Memcache. This is the script: ``` import webapp2 from google.appengine.api import memcache MAIN_PAGE_HTML = """\ <html> <body> <form...
2016/02/29
[ "https://Stackoverflow.com/questions/35700781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3136727/" ]
Given that you work with system logs and their format is known and stable, my approach would be something like: * identify a set of keywords (either common, or one per log) * for each log, iterate line by line * once keywords match, add the relevant information from each line in e.g. a dictionary You could use shell ...
If you want ot use tool then you can use ELK(Elastic,Logstash and kibana). if no then you have to read first log file then apply regex according to your requirment.
14,269
36,913,153
When I do this calculation `2*(5+5/(3+3))*3` I get 30 in Python (2.7). But what it seems is that `2*(5+5/(3+3))*3`is equal to `35`. Can someone tell me why python gives me the answer of 30 instead of 35? I've tested with JavaScript, Lua and Mac Calculator and they show me 35. Why does Python calculate wrong? <http://...
2016/04/28
[ "https://Stackoverflow.com/questions/36913153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4841229/" ]
This happens because of the piece `5/(3 + 3)` which evalautes to 0. You need to use either of them as float.
Always assume it's an issue with something you're doing rather than with an entire coding language! It works fine for me in Python shell. 35 is the expected answer and 35 is what we get! Most likely something on your end or a mis-type / you've miss-commented something out. This is from copy pasting your code above. e...
14,271
52,958,847
I am trying to calculate a DTW distance matrix which will look into 150,000 time series each having between 13 to 24 observations - that is the produced distance matrix will be a list of the size of approximately (150,000 x 150,000)/2= 11,250,000,000. I am running this over a big data cluster of the size of 200GB but ...
2018/10/23
[ "https://Stackoverflow.com/questions/52958847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6235045/" ]
Thanks to @KacperMadej for this solution on [github](https://github.com/highcharts/highcharts-angular/issues/89). To load a theme simply add the following somewhere in the project: ```js import * as Highcharts from 'highcharts'; require('highcharts/themes/dark-blue')(Highcharts); ```
The theme factory is now the default export of `highcharts/themes/<theme-name>` so this will work: ``` import * as Highcharts from 'highcharts'; import theme from 'highcharts/themes/dark-unica'; theme(Highcharts); ```
14,272
32,492,183
When I run `python manage.py runserver`, everything starts out fine, but then I get a `SystemCheckError` stating that Pillow is not installed; however, Pillow is definitely installed on this machine. This is the error I receive: > > Performing system checks... > > > Unhandled exception in thread started by Traceba...
2015/09/10
[ "https://Stackoverflow.com/questions/32492183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4501444/" ]
This should do the trick: `/(?| (")((?:\\"|[^"])+)\1 | (')((?:\\'|[^'])+)\1 )/xg` [Demo](https://regex101.com/r/cG3qR3/2) --------------------------------------- BTW: [regex101.com](https://regex101.com/r/rX4rL7/1) is a great resource to use (which is where I got the regex above) Update ------ The first one I post...
Maybe I read your question incorrectly but this is working for me `/\".+\"/gm` <https://regex101.com/r/wF0yN4/1>
14,275
18,802,563
**Background**: My Python program handles relatively large quantities of data, which can be generated in-program, or imported. The data is then processed, and during one of these processes, the data is deliberately copied and then manipulated, cleaned for duplicates and then returned to the program for further use. T...
2013/09/14
[ "https://Stackoverflow.com/questions/18802563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1644700/" ]
You really want to use NumPy if you're handling large quantities of data. Here's how I would do it : Import NumPy : ``` import numpy as np ``` Generate 8000 high-precision floats (128-bits will be enough for your purposes, but note that I'm converting the 64-bits output of `random` to 128 just to fake it. Use your ...
Why don't you create a dict that maps the 14dp values to the corresponding full 16dp values: ``` d = collections.defaultdict(list) for x in l: d[round(x, 14)].append(x) ``` Now if you just want "unique" (by your definition) values, you can do ``` unique = [v[0] for v in d.values()] ```
14,278
67,541,366
I have a set of filter objects, which inherit the properties of a `Filter` base class ``` class Filter(): def __init__(self): self.filterList = [] def __add__(self,f): self.filterList += f.filterList def match(self, entry): for f in self.filterList: if not f(entry): ...
2021/05/14
[ "https://Stackoverflow.com/questions/67541366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4177926/" ]
I would go for something like this: ```py class Filter: def __init__(self, filter: Callable[[Any], bool]): self.filter = filter def __add__(self, added: Filter): return OrFilter(self, added) def __mul__(self, mult: Filter): return AndFilter(self, mult) def __invert__(self): return Filter(lam...
Thanks, @njzk2 for the solution. In my code I used `|` and `&`. To be backwards compatible I also kept the `.match()` instead of using `__call__()` and also added the `__add__` again. ``` class Filter: def __init__(self, filter: Callable[[Any], bool]): self.filter = filter def __or__(self, ored: Filte...
14,279