qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
73,064,635 | I was trying to capture a video in kivy/android using camera4kivy. but it seems that this function won't work. I tried capture video with location, subdir and filename (kwarg\*\*) but still nothing happend.
```
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from came... | 2022/07/21 | [
"https://Stackoverflow.com/questions/73064635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19499522/"
] | You can use `Map` collection:
```
new Map(fooArr.map(i => [i.name, i.surname]));
```
As [mdn says about `Map` collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map):
>
> The Map object holds key-value pairs and remembers the original
> insertion order of the keys. Any val... | When dealing with objects you can use `Object.keys()`, `Object.values()` and `Object.entries()`, which do a similar thing than their similarly named python counterparts. (`keys()`, `values()`, `pairs()`)
```
const obj = { person: 'John' }
console.log(Object.entries(obj)) // ['person', 'John']
```
Some differences fr... |
53,900,909 | I’m new to python. Why is this code not printing the top50 films?
```
#!/usr/bin/python3
import requests
from bs4 import BeautifulSoup
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module='bs4')
# website
url = "https://www.imdb.com/search/title?release_date="
year = input("Enter you're fav... | 2018/12/23 | [
"https://Stackoverflow.com/questions/53900909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10222187/"
] | You haven't yet issued a request, then you can parse the response content.
This should get the full list:
```
r = requests.get(output)
soup = BeautifulSoup(r.text, "lxml")
# Display the top 50 films
movieList = soup.find_all('div', attrs={'class': 'lister-item mode-advanced'})
for n, x in enumerate(movieList, 1):
... | Thanks Guys for the help but i already solved it.
```
i = 1
movieList = soup.find_all('div', attrs={'class': 'lister-item mode-advanced'})
for x in tqdm(movieList):
div = x.find('div', attrs={'class': 'lister-item-content'})
# print(str(i) + '.')
header = x.findChild('h3', attrs={'class': 'lister-item-he... |
3,413,144 | I am using Selenium RC to do some test now. And the driver I use is python.
But now, I faced a problem, that is: every time Selenium RC runs, and open a url, it opens 2 windows, one is for logging and the other one is for showing HTML content. But I can't close them all in script.
Here is my script:
```
#!/usr/bin/e... | 2010/08/05 | [
"https://Stackoverflow.com/questions/3413144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411728/"
] | I've fix this problem.
It happens because I installed firefox-bin not firefox.
Now I've removed firefox-bin and have installed firefox, it works now.
stop() will close all windows that selenium opened.
Thank you for your reminds [AutomatedTester](https://stackoverflow.com/users/108827/automatedtester) | I may suggest to make a system command with python to close the firefox windows
Bussiere |
3,413,144 | I am using Selenium RC to do some test now. And the driver I use is python.
But now, I faced a problem, that is: every time Selenium RC runs, and open a url, it opens 2 windows, one is for logging and the other one is for showing HTML content. But I can't close them all in script.
Here is my script:
```
#!/usr/bin/e... | 2010/08/05 | [
"https://Stackoverflow.com/questions/3413144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411728/"
] | I had a similar case where my program opened many windows when scraping a webpage. here is a sample code:
```
#!/usr/bin/python
import webbrowser
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Fire... | I may suggest to make a system command with python to close the firefox windows
Bussiere |
3,413,144 | I am using Selenium RC to do some test now. And the driver I use is python.
But now, I faced a problem, that is: every time Selenium RC runs, and open a url, it opens 2 windows, one is for logging and the other one is for showing HTML content. But I can't close them all in script.
Here is my script:
```
#!/usr/bin/e... | 2010/08/05 | [
"https://Stackoverflow.com/questions/3413144",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/411728/"
] | I had a similar case where my program opened many windows when scraping a webpage. here is a sample code:
```
#!/usr/bin/python
import webbrowser
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Fire... | I've fix this problem.
It happens because I installed firefox-bin not firefox.
Now I've removed firefox-bin and have installed firefox, it works now.
stop() will close all windows that selenium opened.
Thank you for your reminds [AutomatedTester](https://stackoverflow.com/users/108827/automatedtester) |
11,479,955 | I started learning python today from the tutorial on the official site.
When reading about **filter(function, sequence)** i thought of making a function that returns if a number is prime to use it with the filter.
```
notDividedBy = [2,3,4,5,6,7,8,9]
def prime(num):
"""True if num is prime, false otherwise""" ... | 2012/07/14 | [
"https://Stackoverflow.com/questions/11479955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596298/"
] | Creating many many copies of lists is not a particularly efficient way of doing things. Instead use the `xrange()` (Python 2.x) or `range()` (Python 3) iterator. Here's one (naive) way you could implement a primality test:
```
from math import sqrt
def isPrime(n):
if n < 2: return False
if n == 2: return True... | One thing off the bat, if you are going to implement prime testing in this fashion, there's no reason to use an auxillary array
```
def prime(num):
"""True if num is prime, false otherwise"""
check = True
#if num in copy:
# copy.remove(num)
for x in range(2,x-1):
if num % x == 0:
... |
11,479,955 | I started learning python today from the tutorial on the official site.
When reading about **filter(function, sequence)** i thought of making a function that returns if a number is prime to use it with the filter.
```
notDividedBy = [2,3,4,5,6,7,8,9]
def prime(num):
"""True if num is prime, false otherwise""" ... | 2012/07/14 | [
"https://Stackoverflow.com/questions/11479955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596298/"
] | Creating many many copies of lists is not a particularly efficient way of doing things. Instead use the `xrange()` (Python 2.x) or `range()` (Python 3) iterator. Here's one (naive) way you could implement a primality test:
```
from math import sqrt
def isPrime(n):
if n < 2: return False
if n == 2: return True... | Here's a 2 liner using filter().
```
def prime(num):
"""True if num is prime, false otherwise"""
if num < 2:
return False
return len(filter(lambda x: num % x == 0, range(2, num))) == 0
``` |
11,479,955 | I started learning python today from the tutorial on the official site.
When reading about **filter(function, sequence)** i thought of making a function that returns if a number is prime to use it with the filter.
```
notDividedBy = [2,3,4,5,6,7,8,9]
def prime(num):
"""True if num is prime, false otherwise""" ... | 2012/07/14 | [
"https://Stackoverflow.com/questions/11479955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596298/"
] | How about this one:
```
def is_prime(num):
return not any(num%i == 0 for i in xrange(2,num/2+1))
for i in xrange(10):
print i, is_prime(i)
```
**Explanation**
start with:
```
(num%i==0 for i in xrange(2,num/2+1))
```
This is a generator expression. I could have made it a list comprehension:
```
[num%i=... | One thing off the bat, if you are going to implement prime testing in this fashion, there's no reason to use an auxillary array
```
def prime(num):
"""True if num is prime, false otherwise"""
check = True
#if num in copy:
# copy.remove(num)
for x in range(2,x-1):
if num % x == 0:
... |
11,479,955 | I started learning python today from the tutorial on the official site.
When reading about **filter(function, sequence)** i thought of making a function that returns if a number is prime to use it with the filter.
```
notDividedBy = [2,3,4,5,6,7,8,9]
def prime(num):
"""True if num is prime, false otherwise""" ... | 2012/07/14 | [
"https://Stackoverflow.com/questions/11479955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596298/"
] | One thing off the bat, if you are going to implement prime testing in this fashion, there's no reason to use an auxillary array
```
def prime(num):
"""True if num is prime, false otherwise"""
check = True
#if num in copy:
# copy.remove(num)
for x in range(2,x-1):
if num % x == 0:
... | Here's a 2 liner using filter().
```
def prime(num):
"""True if num is prime, false otherwise"""
if num < 2:
return False
return len(filter(lambda x: num % x == 0, range(2, num))) == 0
``` |
11,479,955 | I started learning python today from the tutorial on the official site.
When reading about **filter(function, sequence)** i thought of making a function that returns if a number is prime to use it with the filter.
```
notDividedBy = [2,3,4,5,6,7,8,9]
def prime(num):
"""True if num is prime, false otherwise""" ... | 2012/07/14 | [
"https://Stackoverflow.com/questions/11479955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/596298/"
] | How about this one:
```
def is_prime(num):
return not any(num%i == 0 for i in xrange(2,num/2+1))
for i in xrange(10):
print i, is_prime(i)
```
**Explanation**
start with:
```
(num%i==0 for i in xrange(2,num/2+1))
```
This is a generator expression. I could have made it a list comprehension:
```
[num%i=... | Here's a 2 liner using filter().
```
def prime(num):
"""True if num is prime, false otherwise"""
if num < 2:
return False
return len(filter(lambda x: num % x == 0, range(2, num))) == 0
``` |
25,204,021 | I'm using Continuum's Anaconda Spyder for python.
All of a sudden it's giving me this error, although it's supposed to be free:
```
Vendor: Continuum Analytics, Inc.
Package: mkl
Message: trial mode EXPIRED 14 days ago
You cannot run mkl without a license any longer.
A license can be purchased it at: http://... | 2014/08/08 | [
"https://Stackoverflow.com/questions/25204021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961627/"
] | There is a free trial that starts when you `conda install mkl`. If you want to remove it, use `conda remove --features mkl`. | The MKL optimizations are not free: <https://store.continuum.io/cshop/mkl-optimizations/>.
There is a trial period but after that it costs you money. Interesting that you used it for a while. Maybe it's an issue with license checking or there was no mechanism to actually check for a license. When you install the packa... |
25,204,021 | I'm using Continuum's Anaconda Spyder for python.
All of a sudden it's giving me this error, although it's supposed to be free:
```
Vendor: Continuum Analytics, Inc.
Package: mkl
Message: trial mode EXPIRED 14 days ago
You cannot run mkl without a license any longer.
A license can be purchased it at: http://... | 2014/08/08 | [
"https://Stackoverflow.com/questions/25204021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961627/"
] | Update as of 5 Feb 2016:
Anaconda now includes an `mkl` package by default, which is in a trial mode unless you get a license. (There is also a free license for personal use.)
To get a license, go to: <http://docs.continuum.io/mkl-optimizations/index> and follow the link the "Add Ons"
For details on this change (an... | The MKL optimizations are not free: <https://store.continuum.io/cshop/mkl-optimizations/>.
There is a trial period but after that it costs you money. Interesting that you used it for a while. Maybe it's an issue with license checking or there was no mechanism to actually check for a license. When you install the packa... |
25,204,021 | I'm using Continuum's Anaconda Spyder for python.
All of a sudden it's giving me this error, although it's supposed to be free:
```
Vendor: Continuum Analytics, Inc.
Package: mkl
Message: trial mode EXPIRED 14 days ago
You cannot run mkl without a license any longer.
A license can be purchased it at: http://... | 2014/08/08 | [
"https://Stackoverflow.com/questions/25204021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/961627/"
] | There is a free trial that starts when you `conda install mkl`. If you want to remove it, use `conda remove --features mkl`. | Update as of 5 Feb 2016:
Anaconda now includes an `mkl` package by default, which is in a trial mode unless you get a license. (There is also a free license for personal use.)
To get a license, go to: <http://docs.continuum.io/mkl-optimizations/index> and follow the link the "Add Ons"
For details on this change (an... |
26,152,787 | i'm just starting to learn python and I need to solve this problem but i'm stuck. We've been given a function (lSegInt)to find the intersections of lines. What I need to do is to format the data properly inorder to pass it through this function too find how many time two polylines intersect.
Here's the data:
```
pt1... | 2014/10/02 | [
"https://Stackoverflow.com/questions/26152787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4099447/"
] | There are a couple of flaws with your CSS code but the biggest one causing the display issue is:
```
.box2 {
float: middle;
```
}
There is no `float: middle;` property. You need to either set them all to `float:left;` (or `float:right;`) or use an entirely different approach. (like using `display: table-cell;`) | <http://jsfiddle.net/rishabh66/kLfb2wet/> .
Add `float: left;` to all divs
to make horizontally align boxes inside parent div. |
26,152,787 | i'm just starting to learn python and I need to solve this problem but i'm stuck. We've been given a function (lSegInt)to find the intersections of lines. What I need to do is to format the data properly inorder to pass it through this function too find how many time two polylines intersect.
Here's the data:
```
pt1... | 2014/10/02 | [
"https://Stackoverflow.com/questions/26152787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4099447/"
] | Hey I simplified your code, just using a unique class for the three divs, and display them `inline-block`, please see below:
```css
.parentbox {
width: 1120px;
padding: 40px 40px 40px 40px;
align: center;
height: auto;
}
.box {
display:inline-block;
/* vertical-align:top; you might need this prope... | <http://jsfiddle.net/rishabh66/kLfb2wet/> .
Add `float: left;` to all divs
to make horizontally align boxes inside parent div. |
40,521,707 | Whenever I am trying to perform normalization over the array obtained from the csv file . My code wont work because i have n't provided the custom file.
I an getting an error message as :
```
x = np.myarray
```
**AttributeError: 'module' object has no attribute'myarray'**
As I am new to python ,can anyone please... | 2016/11/10 | [
"https://Stackoverflow.com/questions/40521707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6302830/"
] | The answer is simply, it's the maximum that field can hold.
>
> MySQL retrieves and displays TIME values in 'HH:MM:SS' format (or
> 'HHH:MM:SS' format for large hours values). TIME values may range from
> '-838:59:59' to '838:59:59'. The hours part may be so large because
> the TIME type can be used not only to re... | You are using **strtotime()**
strtotime() - Parse English textual datetimes into Unix timestamps:
Eg:
```
echo(strtotime("3 October 2005"));
output as 1128312000
```
**HERE TRY THIS**
```
$epoch_time_out_user =strtotime($_POST['timeout'])- (300*60);
$dt = new DateTime("@$epoch_time_out_user");
$time_out_us... |
70,640,586 | I have a shred library `libcustum.so` in a non standard folder, and a python package where I use `ctypes.cdll.LoadLibrary("libcustom.so")`.
How can I set `libcustum.so` path at build time (something similar to rpath) ?
```
env LD_LIBRARY_PATH=/path/to/custum/lib python3 -c "import mypackage"
```
work fine, but I do... | 2022/01/09 | [
"https://Stackoverflow.com/questions/70640586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5940776/"
] | This might be somewhat related to [this question](https://stackoverflow.com/questions/32998502/python-importerror-no-module-named-crypto-publickey-rsa).
/e:
Ok, since you are using [this firebase package](https://pypi.org/project/firebase/), I can hopefully help you out.
First of all, it's the package's fault that it ... | I found a workaround for this. I simply used another module to read from the firebase db. Instead of using `firebase` I used `firebase_admin` as mentioned in the [firebase documentation](https://firebase.google.com/docs/database/admin/start#python). `firebase_admin` doesn't use Crypto so there's no more problem from th... |
66,355,390 | I'm trying to make a flask pipeline which receives data from a python file and sends the data to react which display them.
I currently am stuck trying to receive the data in flask after sending them via post to the URL: `localhost:5000/weather-data`
The data is being posted with this Code:
```
dummy_data = {'data': ... | 2021/02/24 | [
"https://Stackoverflow.com/questions/66355390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15275815/"
] | If the files requested are big consider use spawn instead of exec.
```
const http = require('http');
const exec = require('child_process').exec;
const DOWNLOAD_DIR = './downloads/';
const generate_width_and_height = function() {
const random = Math.floor((Math.random() * 100) + 200);
console.log(random);
retur... | You can use [Javascript Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) to download multiple files with node and wget.
First wrap your inner code in a promise:
```js
const downloadFile = (url) => {
return new Promise((resolve) => {
console.log(`wget ${ur... |
2,399,812 | Is there a way to create a 'kiosk mode' in wxpython under Windows (98 - 7) where the application disables you from breaking out of the app using Windows keys, alt-tab, alt-f4, and ctrl+alt+delete? | 2010/03/08 | [
"https://Stackoverflow.com/questions/2399812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/204535/"
] | If an application could do that it would make a great denial-of-service attack on the machine.
In particular Ctrl+Alt+Delete is the [Secure Attention Sequence](http://technet.microsoft.com/en-us/library/cc780332(WS.10).aspx). Microsoft goes to great lengths to insure that when the user hits those keys, they switch to ... | wxPython alone cannot be done with that.
You need to do Low Level Keyboard Hook with C/C++ or with equivalent ctypes, for
Windows keys, alt-tab, alt-f4,
but Ctrl-Alt-Del, I don't think so for Windows XP and above. |
28,911,296 | I want convert nametuple to dict with python:
I have:
```
CommentInfo(stt=1, gid=12, uid=222)
```
Now I want:
```
{"stt":1,"gid":12,"uid":222}
```
Please help me! Thanks very much! | 2015/03/07 | [
"https://Stackoverflow.com/questions/28911296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3214584/"
] | You need to use `_asdict()` function to convert the named tuples into a dictionary.
**Example:**
```
>>> CommentInfo = namedtuple('CommentInfo', ["stt", "gid", "uid"])
>>> x = CommentInfo(stt=1,gid=12,uid=222)
>>> x._asdict()
OrderedDict([('stt', 1), ('gid', 12), ('uid', 222)])
``` | namedtuples has a `._asdict()` method to convert it to an OrderedDict, so if you have an instance in a variable `comment` you can use `comment._asdict()` |
48,842,401 | I'm using python 3.6 and selenium 3.8.1, Chrome browser to simulate users entering an order. The app we use has a particularly frustrating implementation for automation - a loading modal will pop up whenever a filter for a product is loading, but it does not truly cover elements underneath it. Additionally, load time f... | 2018/02/17 | [
"https://Stackoverflow.com/questions/48842401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2252481/"
] | If you want to wait until modal disappeared and avoid using `time.sleep()` you can try [ExplicitWait](http://selenium-python.readthedocs.io/waits.html#explicit-waits):
```
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as wait
wait(driver, 10).... | As you mentioned in your question *a loading modal will pop up whenever a filter for a product is loading* irespective of the loader *cover elements underneath it* or not you can simply `wait` for the next intended element with which you want to interact with. Following this approach you can completely get rid of the f... |
67,499,322 | i am trying to control my browser using python, what I need is I give commands in terminal that should work on the browser like opening and searching for something(like scorling the bowser) and closing the browser
currently I am done with opening the browser and closing | 2021/05/12 | [
"https://Stackoverflow.com/questions/67499322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15904381/"
] | A conflict might occur when both of you are changing the same file in the same branch(or while pulling a different branch to your local branch). In such cases, sometimes git would be able to automatically merge the changes when you try to pull your friend's commit. But if the changes are mostly on the same/nearby lines... | It depends if you are working on the same git branch or not. Even If you are working on the same branch but you modify different files you won't get conflicts. You will only get conflicts if you both change the same file. |
48,028,274 | this is the code just to find some sort of product :print the product of all the number in this array Modulo 10^9+7
```
n=int(input())
answer=1
b=10**9
array_1=[]
for i in range(n):
array_1.append(int(input()))
for j in range(n):
... | 2017/12/29 | [
"https://Stackoverflow.com/questions/48028274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7756559/"
] | >
> array\_1.append(int(input())) by using this i m trying get an array of int by
> taking value one by one from user input –
>
>
>
But it looks like you are entering the numbers one after the other as a single string with each number separated by a space. In that case, you should use split to get the individual... | I'm not completely sure what you are trying to achieve here, but just based on looking at it, your code would not accept any of the inputs after `1 2`
If you are running this from a terminal, there should be a new line between each input, i.e.
```
./your_program.py
4
4
3
2
1
``` |
34,207,898 | I am having an issue selecting data from a pandas DataFrame with between\_time. When the start and end dates of the query are between two days the result is empty. I am using pandas 0.17.1 (python 2.7)
I have the following data frame:
```
mydf = pd.DataFrame.from_dict({'azi': {Timestamp('2015-05-12 00:00:14.348000'):... | 2015/12/10 | [
"https://Stackoverflow.com/questions/34207898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5665206/"
] | From the [documentation](http://search.cpan.org/~peco/Email-Send-SMTP-Gmail-0.1.1/lib/Email/Send/SMTP/Gmail.pm): put commas between the email addresses.
>
> send(-to=>'', [-subject=>'', -cc=>'', -bcc=>'', -replyto=>'', -body=>'', -attachments=>''])
>
> It composes and sends the email in one shot
>
>
> to, cc, ... | Simple add all recipients as a comma separated list:
```
(-to=>'[email protected],[email protected]' ...
``` |
66,604,878 | I am new to CI/CD and Gitlab. I have a CI/CD script to test, build and deploy and I use 2 branches and 2 EC2. My goal is to have a light and not redundant script to build and deploy my changes in functions of the branch.
Currently my script looks like this but after looking the Gitlab doc I saw many conditionals keywor... | 2021/03/12 | [
"https://Stackoverflow.com/questions/66604878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15306690/"
] | The first is creating an anonymous subclass of `MyRunnable`.
The second is creating an anonymous subclass of `Thread`, which requires that `MyRunnable` is instantiable; and `MyRunnable` wouldn't actually then be used at all, because it's not invoked in the `run()` method you're defining in the `Thread` subclass.
Ther... | You can also use a lambda expression to start a thread.
```
Thread myRunnableThread3 = new Thread(()-> {
System.out.println(Thread.currentThread().getName());
System.out.println("myRunnableThread3!");},"MyThread");
myRunnableThread3.start();
```
Prints
```
MyThread
myRunnableThread3!
``` |
20,115,972 | I tried to use Ambari to manage the installation and maintenance of the Hadoop cluster.
After I started ambari server, I use the web page to set up Hadoop cluster.
But at the 3rd step-- confirm hosts, the error shows below
And I check the log at /var/log/ambari-server, I found:
>
> INFO:root:BootStrapping hosts ['... | 2013/11/21 | [
"https://Stackoverflow.com/questions/20115972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951132/"
] | Do you provide ssh rsa private key or paste it?
and from the place you are installing, make sure you can ssh to any hosts without typing any password.
If still the same error, try
ambari-server reset
ambari-server setup | Pls restart ambari-server
**ambari-server restart**
and then try accessing Ambari
It would work. |
20,115,972 | I tried to use Ambari to manage the installation and maintenance of the Hadoop cluster.
After I started ambari server, I use the web page to set up Hadoop cluster.
But at the 3rd step-- confirm hosts, the error shows below
And I check the log at /var/log/ambari-server, I found:
>
> INFO:root:BootStrapping hosts ['... | 2013/11/21 | [
"https://Stackoverflow.com/questions/20115972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2951132/"
] | Do you provide ssh rsa private key or paste it?
and from the place you are installing, make sure you can ssh to any hosts without typing any password.
If still the same error, try
ambari-server reset
ambari-server setup | Make sure you can ssh to every single host on the list, including all master hosts.
To do this, ensure that Ambari host's .ssh/id\_rsa.pub entry is included in every hosts' .ssh/authorized\_keys file. Then ssh from Ambari's host to every single server - and check if it is asking for your password. You can use a tutori... |
67,219,194 | So recently I've been doing a project whera as optimisation I want to use numpy arrays instead of python list built-in. It would be a 2d array with fixed length in both axes. I also want to maximasie cashe use so that code is as fast as it can be. However when playing with id(var) function I gor unexpected results:
co... | 2021/04/22 | [
"https://Stackoverflow.com/questions/67219194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13757444/"
] | `id(var)` does not work as you think it is. Indeed, `id(var)` returns a unique ID for the specified object `var`, but `var` is not a cell of `a`. **`var` is a Python object referencing a cell of `a`**. Note that `a` does not contains such objets as it would be too inefficient (and data would not be contiguous as reques... | The kinds of arrays that you really want are unclear, nor is the purpose. But talk of contiguous (or continuous) and caching, suggests that you aren't clear about how Python works.
First, Python is object oriented, all the way down. Integers, strings, lists are all objects of some class, with associated methods, and a... |
3,312,436 | Running GNU Emacs 22.2.1 on Ubuntu 9.04.
When editing python code in emacs, if a docstring contains an apostrophe, emacs highlights all following code as a comment, until another apostrophe is used. Really annoying!
In other words, if I have a docstring like this:
```
''' This docstring has an apostrophe ' '''
```
... | 2010/07/22 | [
"https://Stackoverflow.com/questions/3312436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/316963/"
] | This appears to work correctly in GNU Emacs 23.2.1. If it's not practical to upgrade, you might be able to copy `python.el` out of the Emacs 23 source code, or perhaps just the relevant pieces of it (python-quote-syntax, python-font-lock-syntactic-keywords, and the code that uses the latter, I think - I'm not much of a... | It may be an emacs bug, but it could also be by purpose. If you insert doctests in your docstrings, as I often do to explain API, I could even wish to have the full python syntax highlighting inside docstrings.
But it's probably a bug... (probably emacs syntax highlighter just care of simple and double quotes and igno... |
48,080,359 | I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people.
One possible solutio... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6181928/"
] | You may use `pandas` packages.
By defining the data frame :
```
import pandas as pd
df = pd.DataFrame([['men', 2, '1945-Truman.txt'],
['women', 2, '1945-Truman.txt'],
['people', 10, '1945-Truman.txt'],
['men', 12, '1946-Truman.txt'],
['women'... | You can use `itertools.groupby`:
```
import itertools
new_data = [(a, list(b)) for a, b in itertools.groupby(sorted(data, key=lambda x:x[0]), key=lambda x:x[0])]
new_final_data = [max(b, key=lambda x:x[1]) for a, b in new_data]
```
Output:
```
[['men', 12, '1946-Truman.txt'], ['people', 49, '1946-Truman.txt'], ['wo... |
48,080,359 | I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people.
One possible solutio... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6181928/"
] | `pandas` is a good one, but you can just use `max` and `lambda`:
```
men = max(data, key=lambda x: x[1] if x[0] == 'men' else 0)
women = max(data, key=lambda x: x[1] if x[0] == 'women' else 0)
people = max(data, key=lambda x: x[1] if x[0] == 'people' else 0)
``` | You can use `itertools.groupby`:
```
import itertools
new_data = [(a, list(b)) for a, b in itertools.groupby(sorted(data, key=lambda x:x[0]), key=lambda x:x[0])]
new_final_data = [max(b, key=lambda x:x[1]) for a, b in new_data]
```
Output:
```
[['men', 12, '1946-Truman.txt'], ['people', 49, '1946-Truman.txt'], ['wo... |
48,080,359 | I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people.
One possible solutio... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6181928/"
] | `pandas` is a good one, but you can just use `max` and `lambda`:
```
men = max(data, key=lambda x: x[1] if x[0] == 'men' else 0)
women = max(data, key=lambda x: x[1] if x[0] == 'women' else 0)
people = max(data, key=lambda x: x[1] if x[0] == 'people' else 0)
``` | You can use `pandas`, I suppose **data** is a list of list:
```
import pandas as pd
df = pd.DataFrame(data)
df.loc[df.groupby([0])[1].idxmax()]
0 1 2
3 men 12 1946-Truman.txt
5 people 49 1946-Truman.txt
4 women 7 1946-Truman.txt
```
For a result in the same format:
```
df.l... |
48,080,359 | I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people.
One possible solutio... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6181928/"
] | `pandas` is a good one, but you can just use `max` and `lambda`:
```
men = max(data, key=lambda x: x[1] if x[0] == 'men' else 0)
women = max(data, key=lambda x: x[1] if x[0] == 'women' else 0)
people = max(data, key=lambda x: x[1] if x[0] == 'people' else 0)
``` | If you are using a list of lists such as:
```
lst=[['men', 2123, '1945-Truman.txt'],
['women', 2, '1945-Truman.txt'],
['people', 10, '1945-Truman.txt'],
['men', 12, '1946-Truman.txt'],
['women', 7, '1946-Truman.txt'],
['people', 49, '1946-Truman.txt'],
['men', 7, '1947-Truman.txt'],
['women', 2, '1947-Truman.txt']]
... |
48,080,359 | I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people.
One possible solutio... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6181928/"
] | You may use `pandas` packages.
By defining the data frame :
```
import pandas as pd
df = pd.DataFrame([['men', 2, '1945-Truman.txt'],
['women', 2, '1945-Truman.txt'],
['people', 10, '1945-Truman.txt'],
['men', 12, '1946-Truman.txt'],
['women'... | You could create a set out of the first column and find the maximum value afterwards:
```
data = [
['men', 2, '1945-Truman.txt'],
['women', 2, '1945-Truman.txt'],
...
]
keys = set([col[0] for col in data])
for k in keys:
print (k, max([col[1] for col in data if col[0] == k]))
```
Returns:
```
... |
48,080,359 | I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people.
One possible solutio... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6181928/"
] | `pandas` is a good one, but you can just use `max` and `lambda`:
```
men = max(data, key=lambda x: x[1] if x[0] == 'men' else 0)
women = max(data, key=lambda x: x[1] if x[0] == 'women' else 0)
people = max(data, key=lambda x: x[1] if x[0] == 'people' else 0)
``` | You may use `pandas` packages.
By defining the data frame :
```
import pandas as pd
df = pd.DataFrame([['men', 2, '1945-Truman.txt'],
['women', 2, '1945-Truman.txt'],
['people', 10, '1945-Truman.txt'],
['men', 12, '1946-Truman.txt'],
['women'... |
48,080,359 | I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people.
One possible solutio... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6181928/"
] | `pandas` is a good one, but you can just use `max` and `lambda`:
```
men = max(data, key=lambda x: x[1] if x[0] == 'men' else 0)
women = max(data, key=lambda x: x[1] if x[0] == 'women' else 0)
people = max(data, key=lambda x: x[1] if x[0] == 'people' else 0)
``` | You could create a set out of the first column and find the maximum value afterwards:
```
data = [
['men', 2, '1945-Truman.txt'],
['women', 2, '1945-Truman.txt'],
...
]
keys = set([col[0] for col in data])
for k in keys:
print (k, max([col[1] for col in data if col[0] == k]))
```
Returns:
```
... |
48,080,359 | I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people.
One possible solutio... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6181928/"
] | `pandas` is a good one, but you can just use `max` and `lambda`:
```
men = max(data, key=lambda x: x[1] if x[0] == 'men' else 0)
women = max(data, key=lambda x: x[1] if x[0] == 'women' else 0)
people = max(data, key=lambda x: x[1] if x[0] == 'people' else 0)
``` | ```
men = [t for t in yourlist if t[0] == 'men']
women = [t for t in yourlist if t[0] == 'women']
people = [t for t in yourlist if t[0] == 'people']
sorted(men, key=operator.itemgetter(1), reverse=True)[0][1]
sorted(women, key=operator.itemgetter(1), reverse=True)[0][1]
sorted(people, key=operator.itemgetter(1), reve... |
48,080,359 | I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people.
One possible solutio... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6181928/"
] | You may use `pandas` packages.
By defining the data frame :
```
import pandas as pd
df = pd.DataFrame([['men', 2, '1945-Truman.txt'],
['women', 2, '1945-Truman.txt'],
['people', 10, '1945-Truman.txt'],
['men', 12, '1946-Truman.txt'],
['women'... | If you are using a list of lists such as:
```
lst=[['men', 2123, '1945-Truman.txt'],
['women', 2, '1945-Truman.txt'],
['people', 10, '1945-Truman.txt'],
['men', 12, '1946-Truman.txt'],
['women', 7, '1946-Truman.txt'],
['people', 49, '1946-Truman.txt'],
['men', 7, '1947-Truman.txt'],
['women', 2, '1947-Truman.txt']]
... |
48,080,359 | I am new to python. I want to find the max value from col2 with respect to the values 'men', 'women' and 'people' in col1 of the list. Like, `['men', 12, '1946-Truman.txt'], ['women', 7, '1946-Truman.txt']`and`['people', 49, '1946-Truman.txt']` contain max values of col2 for men, women and people.
One possible solutio... | 2018/01/03 | [
"https://Stackoverflow.com/questions/48080359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6181928/"
] | You may use `pandas` packages.
By defining the data frame :
```
import pandas as pd
df = pd.DataFrame([['men', 2, '1945-Truman.txt'],
['women', 2, '1945-Truman.txt'],
['people', 10, '1945-Truman.txt'],
['men', 12, '1946-Truman.txt'],
['women'... | ```
men = [t for t in yourlist if t[0] == 'men']
women = [t for t in yourlist if t[0] == 'women']
people = [t for t in yourlist if t[0] == 'people']
sorted(men, key=operator.itemgetter(1), reverse=True)[0][1]
sorted(women, key=operator.itemgetter(1), reverse=True)[0][1]
sorted(people, key=operator.itemgetter(1), reve... |
42,776,454 | I have multiple series of "start" and "stop" times in a set of data, and would like to see if a particular set of dates/times does or does not fall between a given set of "start/stop" times. I'm using pandas in python, and I've tried having the data as dataframes or as timeseries- haven't gotten either to work. I've be... | 2017/03/14 | [
"https://Stackoverflow.com/questions/42776454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7697187/"
] | Put `saveFileDialog1.ShowDialog();` inside some button event handler which lets the user save the document. Double-click on the `SaveFileDialog` icon in your Visual Studio designer window as well to add the FileOk event handler and within event handler, put your code like this:
```
private void saveFileDialog1_Fil... | To do this:
```
private void btn_approve_Click(object sender, EventArgs e)
{
saveFileDialog1.Title = "Save As";
saveFileDialog1.Filter = "DocX|*.docx";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
var doc = DocX.Create(saveFileDialog1.FileName);
doc.InsertParagraph("This is my first para... |
41,467,654 | I have a python script on a machine.
I could run it from both **ssh connection** and the **console** of the machine.
Because the script changes some IP config stuff, I want to disconnect the ssh before doing the IP changing - that way the ssh won't hang and will be closed properly before the IP changes.
**So** - is ... | 2017/01/04 | [
"https://Stackoverflow.com/questions/41467654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1662033/"
] | You can add header info as a dict on 4 arguments. As far as know is not possible embed in the BODY.
```
import http.client
BODY = "***filecontents***"
conn = http.client.HTTPConnection("127.0.0.1", 5000)
conn.connect()
conn.request("PUT", "/file", BODY, {"someheadername":"someheadervalues",
"someothe... | The command:
```
conn.request("PUT", "/file", BODY)
```
Is overloaded as below as well, so its pretty straight forward :)
```
conn.request("PUT", "url", payload, headers)
``` |
57,717,100 | By "comparable", I mean "able to mutually perform the comparison operations `>`, `<`, `>=`, `<=`, `==`, and `!=` without raising a `TypeError`". There are a number of different classes for which this property does hold:
```py
1 < 2.5 # int and float
2 < decimal.Decimal(4) # int and Decimal
"alice" < "bob" # str and... | 2019/08/29 | [
"https://Stackoverflow.com/questions/57717100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648811/"
] | Since it is impossible to know beforehand whether a comparison operation can be performed on two specific types of operands until you actually perform such an operation, the closest thing you can do to achieving the desired behavior of avoiding having to catch a `TypeError` is to cache the known combinations of the ope... | What you could do is use `isinstance` before the comparison, and deal with the exceptions yourself.
```
if(isinstance(date_1,datetime) != isinstance(date_2,datetime)):
#deal with the exception
``` |
53,581,563 | Currently, I'm trying to make a game and in the game I would like it so if the character is on top of an object, it picks it up. This is what I have so far:
```
import turtle
import time
default = turtle.clone()
scar = turtle.clone()
def pickupScar():
if default.distance(-7,48) > 5.0:
default.changeshape... | 2018/12/02 | [
"https://Stackoverflow.com/questions/53581563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10735185/"
] | Since I don't have your images, nor recognize what your game is about, below is an example of the functionality you describe. On the screen is a black circle and pink square. You can drag the circle and if you drag it onto the square, it will sprout a head and legs becoming a turtle. Dragging off the square, it reverts... | I dont know the `turtle-graphics`, but in real world to determine the distance between two points (for 2D surfaces) we use **Pythagorean theorem**.
If some object is at `(x1, y1)` and another at `(x2, y2)`, the distance is
```
dist=sqrt((x1-x2)^2 + (y1-y2)^2)
```
So, if `dist <= R`, turtle (or whatever) is `in R r... |
29,871,209 | I have compressed a file using python-snappy and put it in my hdfs store. I am now trying to read it in like so but I get the following traceback. I can't find an example of how to read the file in so I can process it. I can read the text file (uncompressed) version fine. Should I be using sc.sequenceFile ? Thanks!
``... | 2015/04/25 | [
"https://Stackoverflow.com/questions/29871209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4833015/"
] | The issue here is that python-snappy is not compatible with Hadoop's snappy codec, which is what Spark will use to read the data when it sees a ".snappy" suffix. They are based on the same underlying algorithm but they aren't compatible in that you can compress with one and decompress with another.
You can make this w... | Alright I found a solution!
Build this...
<https://github.com/liancheng/snappy-utils>
On ubuntu 14.10 I had to install gcc-4.4 to get it to build commented on my error I was seeing here
<https://code.google.com/p/hadoop-snappy/issues/detail?id=9>
I can now compress the text files using snappy at the command line lik... |
29,871,209 | I have compressed a file using python-snappy and put it in my hdfs store. I am now trying to read it in like so but I get the following traceback. I can't find an example of how to read the file in so I can process it. I can read the text file (uncompressed) version fine. Should I be using sc.sequenceFile ? Thanks!
``... | 2015/04/25 | [
"https://Stackoverflow.com/questions/29871209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4833015/"
] | The issue here is that python-snappy is not compatible with Hadoop's snappy codec, which is what Spark will use to read the data when it sees a ".snappy" suffix. They are based on the same underlying algorithm but they aren't compatible in that you can compress with one and decompress with another.
You can make this w... | Not sure exactly which `snappy` codec my files have, but `spark.read.text` worked without incident for me. |
29,871,209 | I have compressed a file using python-snappy and put it in my hdfs store. I am now trying to read it in like so but I get the following traceback. I can't find an example of how to read the file in so I can process it. I can read the text file (uncompressed) version fine. Should I be using sc.sequenceFile ? Thanks!
``... | 2015/04/25 | [
"https://Stackoverflow.com/questions/29871209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4833015/"
] | The issue here is that python-snappy is not compatible with Hadoop's snappy codec, which is what Spark will use to read the data when it sees a ".snappy" suffix. They are based on the same underlying algorithm but they aren't compatible in that you can compress with one and decompress with another.
You can make this w... | The accepted answer is now outdated. You can use python-snappy to compress hadoop-snappy, but the documentation is virtually absent.
Example:
```
import snappy
with open('test.json.snappy', 'wb') as out_file:
data=json.dumps({'test':'somevalue','test2':'somevalue2'}).encode('utf-8')
compressor = snappy.hadoop_... |
29,871,209 | I have compressed a file using python-snappy and put it in my hdfs store. I am now trying to read it in like so but I get the following traceback. I can't find an example of how to read the file in so I can process it. I can read the text file (uncompressed) version fine. Should I be using sc.sequenceFile ? Thanks!
``... | 2015/04/25 | [
"https://Stackoverflow.com/questions/29871209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4833015/"
] | Not sure exactly which `snappy` codec my files have, but `spark.read.text` worked without incident for me. | Alright I found a solution!
Build this...
<https://github.com/liancheng/snappy-utils>
On ubuntu 14.10 I had to install gcc-4.4 to get it to build commented on my error I was seeing here
<https://code.google.com/p/hadoop-snappy/issues/detail?id=9>
I can now compress the text files using snappy at the command line lik... |
29,871,209 | I have compressed a file using python-snappy and put it in my hdfs store. I am now trying to read it in like so but I get the following traceback. I can't find an example of how to read the file in so I can process it. I can read the text file (uncompressed) version fine. Should I be using sc.sequenceFile ? Thanks!
``... | 2015/04/25 | [
"https://Stackoverflow.com/questions/29871209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4833015/"
] | The accepted answer is now outdated. You can use python-snappy to compress hadoop-snappy, but the documentation is virtually absent.
Example:
```
import snappy
with open('test.json.snappy', 'wb') as out_file:
data=json.dumps({'test':'somevalue','test2':'somevalue2'}).encode('utf-8')
compressor = snappy.hadoop_... | Alright I found a solution!
Build this...
<https://github.com/liancheng/snappy-utils>
On ubuntu 14.10 I had to install gcc-4.4 to get it to build commented on my error I was seeing here
<https://code.google.com/p/hadoop-snappy/issues/detail?id=9>
I can now compress the text files using snappy at the command line lik... |
29,871,209 | I have compressed a file using python-snappy and put it in my hdfs store. I am now trying to read it in like so but I get the following traceback. I can't find an example of how to read the file in so I can process it. I can read the text file (uncompressed) version fine. Should I be using sc.sequenceFile ? Thanks!
``... | 2015/04/25 | [
"https://Stackoverflow.com/questions/29871209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4833015/"
] | The accepted answer is now outdated. You can use python-snappy to compress hadoop-snappy, but the documentation is virtually absent.
Example:
```
import snappy
with open('test.json.snappy', 'wb') as out_file:
data=json.dumps({'test':'somevalue','test2':'somevalue2'}).encode('utf-8')
compressor = snappy.hadoop_... | Not sure exactly which `snappy` codec my files have, but `spark.read.text` worked without incident for me. |
56,436,777 | Referencing this question: [What's the canonical way to check for type in Python?](https://stackoverflow.com/questions/152580/whats-the-canonical-way-to-check-for-type-in-python)
It is said that the best way to check for inputs is to not check them - that is to let try/except blocks take care of bad inputs.
My quest... | 2019/06/04 | [
"https://Stackoverflow.com/questions/56436777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4992644/"
] | there you go
```
For Each row As DataGridViewRow In DataGridView1.Rows
For Each nextrow As DataGridViewRow In DataGridView1.Rows
If row.Index <> nextrow.Index Then
If row.Cells(0).Value = nextrow.Cells(0).Value Then
MsgBox("Duplicate on col 0, index = " & row.In... | ```
For Each row As DataGridViewRow In dtg3.Rows
For Each nextrow As DataGridViewRow In dtg3.Rows
If row.Index <> nextrow.Index Then
If row.Cells(0).Value = nextrow.Cells(0).Value AndAlso
row.Cells(2).Value = nextrow.Cells(2).Value AndAlso row.Cells(3).Value =
nextrow.C... |
9,014,991 | So let's say i have this python code:
```
def loopForEachFileInDirectory(self, conn):
for filename in os.listdir(uploadedFilesDirectory):
try:
self.insertNewEntryForStagingFile(conn, filename)
self.copyFilesToStagingDirectory(filename)
except: ???
def copyFilesToStagingDire... | 2012/01/26 | [
"https://Stackoverflow.com/questions/9014991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1061426/"
] | >
> what is the rule for bubbling up a generic exception? Do i just raise on its own?
>
>
>
Yes. The short answer is to just use `raise`.
>
> And if so, how do i generically throw an exception...
>
>
>
The above answer the other submitter posted is correct, but it doesn't provide much in the way of context.
... | ```
#!/usr/bin/python
try:
print 'Youll see me first.'
try:
1[90]
except Exception,e:
print "************ UTOH!",str(e)
raise e
except Exception,e:
print ">>>>>>>>>>>> I concur, THE JIG IS UP!",str(e)
raise e
``` |
9,014,991 | So let's say i have this python code:
```
def loopForEachFileInDirectory(self, conn):
for filename in os.listdir(uploadedFilesDirectory):
try:
self.insertNewEntryForStagingFile(conn, filename)
self.copyFilesToStagingDirectory(filename)
except: ???
def copyFilesToStagingDire... | 2012/01/26 | [
"https://Stackoverflow.com/questions/9014991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1061426/"
] | A short Python 3 extension to what other posters have written. In most cases, the bare `raise` is enough. It re-raises the original exception which is what you want to do in most cases.
But there are cases when you want to raise a new exception instead - perhaps to add more info to the original one (say the id of the ... | ```
#!/usr/bin/python
try:
print 'Youll see me first.'
try:
1[90]
except Exception,e:
print "************ UTOH!",str(e)
raise e
except Exception,e:
print ">>>>>>>>>>>> I concur, THE JIG IS UP!",str(e)
raise e
``` |
9,014,991 | So let's say i have this python code:
```
def loopForEachFileInDirectory(self, conn):
for filename in os.listdir(uploadedFilesDirectory):
try:
self.insertNewEntryForStagingFile(conn, filename)
self.copyFilesToStagingDirectory(filename)
except: ???
def copyFilesToStagingDire... | 2012/01/26 | [
"https://Stackoverflow.com/questions/9014991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1061426/"
] | >
> what is the rule for bubbling up a generic exception? Do i just raise on its own?
>
>
>
Yes. The short answer is to just use `raise`.
>
> And if so, how do i generically throw an exception...
>
>
>
The above answer the other submitter posted is correct, but it doesn't provide much in the way of context.
... | A short Python 3 extension to what other posters have written. In most cases, the bare `raise` is enough. It re-raises the original exception which is what you want to do in most cases.
But there are cases when you want to raise a new exception instead - perhaps to add more info to the original one (say the id of the ... |
21,819,649 | What's the difference between a namespace Python package (no `__init__.py`) and a regular Python package (has an `__init__.py`), especially when `__init__.py` is empty for a regular package?
I am curious because recently I've been forgetting to make `__init__.py` in packages I make, and I never noticed any problems. I... | 2014/02/17 | [
"https://Stackoverflow.com/questions/21819649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/469721/"
] | Namespace packages
------------------
As of [Python 3.3](https://docs.python.org/3/whatsnew/3.3.html#pep-420-implicit-namespace-packages), we get namespace packages. These are a special kind of package that allows you to unify two packages with the same name at different points on your Python-path. For example, consid... | 1. Having `__init__.py` makes it so you can import that package elsewhere.
2. Also, the `__init__.py` file can contain code you want executed each time the module is loaded. |
21,819,649 | What's the difference between a namespace Python package (no `__init__.py`) and a regular Python package (has an `__init__.py`), especially when `__init__.py` is empty for a regular package?
I am curious because recently I've been forgetting to make `__init__.py` in packages I make, and I never noticed any problems. I... | 2014/02/17 | [
"https://Stackoverflow.com/questions/21819649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/469721/"
] | Reading [link](http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages) from Aaron, and [PEP420](http://www.python.org/dev/peps/pep-0420/), it appears that the fundamental difference between a namespace package and a regular package, beside the obvious difference that a regular package may contain various... | 1. Having `__init__.py` makes it so you can import that package elsewhere.
2. Also, the `__init__.py` file can contain code you want executed each time the module is loaded. |
21,819,649 | What's the difference between a namespace Python package (no `__init__.py`) and a regular Python package (has an `__init__.py`), especially when `__init__.py` is empty for a regular package?
I am curious because recently I've been forgetting to make `__init__.py` in packages I make, and I never noticed any problems. I... | 2014/02/17 | [
"https://Stackoverflow.com/questions/21819649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/469721/"
] | Namespace packages
------------------
As of [Python 3.3](https://docs.python.org/3/whatsnew/3.3.html#pep-420-implicit-namespace-packages), we get namespace packages. These are a special kind of package that allows you to unify two packages with the same name at different points on your Python-path. For example, consid... | Reading [link](http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages) from Aaron, and [PEP420](http://www.python.org/dev/peps/pep-0420/), it appears that the fundamental difference between a namespace package and a regular package, beside the obvious difference that a regular package may contain various... |
21,272,497 | I'm trying to see if this is the most efficient way to sort a bubble list in python or if there are better ways some people tell me to use two loops, what are the benefits of doing like that vs the below
```
def sort_bubble(blist):
n = 0
while n < len(blist) - 1:
if blist[n] > blist[n + 1]:
... | 2014/01/22 | [
"https://Stackoverflow.com/questions/21272497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3221614/"
] | Your algorithm is technically a bubble sort in that it does exactly the swaps that it should. However, it's a *very inefficient* bubble sort, in that it does a *lot* more compares than are necessary.
How can you *know* that? It's pretty easy to instrument your code to count the number of compares and swaps. And meanwh... | This is how I would do it if I was forced to use bubble sort, you should probably always just use the default sort() function in python, it's very fast.
```
def BubbleSort(A):
end = len(A)-1
swapped = True
while swapped:
swapped = False
for i in range(0, end):
if A[i] > A[i+1]:
... |
21,272,497 | I'm trying to see if this is the most efficient way to sort a bubble list in python or if there are better ways some people tell me to use two loops, what are the benefits of doing like that vs the below
```
def sort_bubble(blist):
n = 0
while n < len(blist) - 1:
if blist[n] > blist[n + 1]:
... | 2014/01/22 | [
"https://Stackoverflow.com/questions/21272497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3221614/"
] | This is how I would do it if I was forced to use bubble sort, you should probably always just use the default sort() function in python, it's very fast.
```
def BubbleSort(A):
end = len(A)-1
swapped = True
while swapped:
swapped = False
for i in range(0, end):
if A[i] > A[i+1]:
... | You could test it out yourself. Other things remaining the same, just counting the number of iterations will give you an idea, what is faster. Here is what I wrote:
```
def sort_bubble(blist):
ops=0
n = 0
while n < len(blist) - 1:
if blist[n] > blist[n + 1]:
n1 = blist[n]
n2... |
21,272,497 | I'm trying to see if this is the most efficient way to sort a bubble list in python or if there are better ways some people tell me to use two loops, what are the benefits of doing like that vs the below
```
def sort_bubble(blist):
n = 0
while n < len(blist) - 1:
if blist[n] > blist[n + 1]:
... | 2014/01/22 | [
"https://Stackoverflow.com/questions/21272497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3221614/"
] | Your algorithm is technically a bubble sort in that it does exactly the swaps that it should. However, it's a *very inefficient* bubble sort, in that it does a *lot* more compares than are necessary.
How can you *know* that? It's pretty easy to instrument your code to count the number of compares and swaps. And meanwh... | You could test it out yourself. Other things remaining the same, just counting the number of iterations will give you an idea, what is faster. Here is what I wrote:
```
def sort_bubble(blist):
ops=0
n = 0
while n < len(blist) - 1:
if blist[n] > blist[n + 1]:
n1 = blist[n]
n2... |
48,689,158 | I want to send commands to run a python script to the Linux terminal. I have a list of python files which I want to run and I want to run them one after the other as we read the list sequentially. Once the first file is finished, it should send the second one to run and so on. | 2018/02/08 | [
"https://Stackoverflow.com/questions/48689158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4782295/"
] | I would suggest gsl-like syntactic sugar to mark that it is not the pointer you manage. Something like:
```
template<class T>
using observer = T;
observer<library_managed_object *> foo = nullptr;
```
You can also use, as sugested elsewhere the `observer_ptr`.
And one final word - in world of C++11 and so forth - u... | You can try [gsl::owner](https://github.com/Microsoft/GSL/blob/master/include/gsl/pointers) defined in the GSL project.
Its not a type but more of a tag to define ownership.
The [CPP core guidelines](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Ri-raw) define the use case of `gsl::owner... |
39,185,797 | In Node.js when I want to quickly check the value of something rather than busting out the debugger and stepping through, I quickly add a console.log(foo) and get a beautiful:
```
{
lemmons: "pie",
number: 9,
fetch: function(){..}
elements: {
fire: 99.9
}
}
```
Very clear! In Python I get this:
... | 2016/08/27 | [
"https://Stackoverflow.com/questions/39185797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5947872/"
] | Actually, there is a way to stop Java GC. Just use the Epsilon GC algorithm that was introduced as an experimental feature in Java 11. Just add the following two arguments to your JVM's startup script:
```
-XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC
```
All or Nothing
--------------
Now just keep in mind tha... | By default the JVM runs the JVM only needed. This means you can't turn off the GC or your program will fail.
The simplest way to avoid stopping the JVM is;
* use a very small eden size so when it stops it will be less than some acceptable time.
* or make the eden size very large and delay the GC until it hardly matte... |
14,817,210 | I have quite a simple question here. In Tkinter (python), I was wondering who to use a button to go to different pages of my application, e.g a register page, and a login page. I am aware that GUI does not have 'pages' like websites do, I've seen a few different ways, but what is the best way to make links to different... | 2013/02/11 | [
"https://Stackoverflow.com/questions/14817210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2061989/"
] | Make each page a frame. Then, all your buttons need to do is hide whatever is visible, then make the desired frame visible.
A simple method to do this is to stack the frames on top of each other (this is one time when `place` makes sense) and then ,`lift()` the frame you want to be visible. This technique works best w... | Could you do something like this?
```
import tkinter
def page1():
page2text.pack_forget()
page1text.pack()
def page2():
page1text.pack_forget()
page2text.pack()
window = tkinter.Tk()
page1btn = tkinter.Button(window, text="Page 1", command=page1)
page2btn = tkinter.Button(window, text="Page 2", com... |
14,817,210 | I have quite a simple question here. In Tkinter (python), I was wondering who to use a button to go to different pages of my application, e.g a register page, and a login page. I am aware that GUI does not have 'pages' like websites do, I've seen a few different ways, but what is the best way to make links to different... | 2013/02/11 | [
"https://Stackoverflow.com/questions/14817210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2061989/"
] | Make each page a frame. Then, all your buttons need to do is hide whatever is visible, then make the desired frame visible.
A simple method to do this is to stack the frames on top of each other (this is one time when `place` makes sense) and then ,`lift()` the frame you want to be visible. This technique works best w... | ```
import tkinter as tk
root=tk.Tk()
root.geometry("360x360")
frame=tk.Frame(root,bg='lightblue')
frame.place(relx=0.2,rely=0.2,relheight=0.6,relwidth=0.6)
def page1():
label=tk.Label(frame,text='this is the page1')
label.place(relx=0.3,rely=0.4)
def page2():
label=tk.Label(frame,text='this is the page2... |
14,817,210 | I have quite a simple question here. In Tkinter (python), I was wondering who to use a button to go to different pages of my application, e.g a register page, and a login page. I am aware that GUI does not have 'pages' like websites do, I've seen a few different ways, but what is the best way to make links to different... | 2013/02/11 | [
"https://Stackoverflow.com/questions/14817210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2061989/"
] | Could you do something like this?
```
import tkinter
def page1():
page2text.pack_forget()
page1text.pack()
def page2():
page1text.pack_forget()
page2text.pack()
window = tkinter.Tk()
page1btn = tkinter.Button(window, text="Page 1", command=page1)
page2btn = tkinter.Button(window, text="Page 2", com... | ```
import tkinter as tk
root=tk.Tk()
root.geometry("360x360")
frame=tk.Frame(root,bg='lightblue')
frame.place(relx=0.2,rely=0.2,relheight=0.6,relwidth=0.6)
def page1():
label=tk.Label(frame,text='this is the page1')
label.place(relx=0.3,rely=0.4)
def page2():
label=tk.Label(frame,text='this is the page2... |
56,642,128 | I have a data set with columns titled as product name, brand,rating(1:5),review text, review-helpfulness. What I need is to propose a recommendation algorithm using reviews. I have to use python for coding here. data set is in .csv format.
To identify the nature of the data set I need to use kmeans on the data set. H... | 2019/06/18 | [
"https://Stackoverflow.com/questions/56642128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9725182/"
] | You did not plot anything.
So nothing shows up. | Unless you are more specific about what you are trying to achieve we won't be able to help. Figure out what exactly you want to predict. Do you just want to cluster products according to their sentiment score which isn't especially promising or do you want to predict actual product preferences on a new dataset?
If you... |
69,557,664 | I have a custom python logger
```
# logger.py
import logging
#logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
c_handler = logging.StreamHandler()
c_handler.setLevel(logging.DEBUG)
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
c_handler.setFormatter(c_format)
... | 2021/10/13 | [
"https://Stackoverflow.com/questions/69557664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3070181/"
] | TL;DR Use `logger.setLevel(logging.DEBUG)`
---
According to [Python documentation](https://docs.python.org/3/library/logging.html#logging.Logger.setLevel), a handler processes messages with a level equal to or higher than the handler is set to (via `.setLevel()`).
But also note, emphasis mine:
>
> When a logger is... | Having read the [docs](https://docs.python.org/3/library/logging.html#logging.Logger.setLevel) again I realise that *propagate* is the attribute that I need to use to turn off the ancestor *logging* output. So my logger becomes
```
# logger.py
import logging
logging.basicConfig(level=logging.DEBUG)
logger.propagate =... |
65,343,093 | I am working on a pipeline where the majority of code is within a python script that I call in the pipeline. In the script I would like to use the predefined variable System.AccessToken to make a call to the DevOps API that sets the status of a pull request.
However, when I try to get the token using `os.environ['Syst... | 2020/12/17 | [
"https://Stackoverflow.com/questions/65343093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11090784/"
] | After reviewing the page that Mani posted I found the answer. For most variables, something like System.AccessToken would have a corresponding SYSTEM\_ACCESSTOKEN.
However, with a secret variable this is not the case. I was able to make it accessible to my python script by adding:
```
env:
SYSTEM_ACCESSTOKEN: $(S... | with this documentation it can work: <https://learn.microsoft.com/de-de/azure/developer/python/azure-sdk-authenticate?tabs=cmd>
Just change the language to "read in english"
There must be a vault and a present Secret aka SAS Token.
And I have to say your code above is curl not python.
---
```
import os
from azure.i... |
65,343,093 | I am working on a pipeline where the majority of code is within a python script that I call in the pipeline. In the script I would like to use the predefined variable System.AccessToken to make a call to the DevOps API that sets the status of a pull request.
However, when I try to get the token using `os.environ['Syst... | 2020/12/17 | [
"https://Stackoverflow.com/questions/65343093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11090784/"
] | After reviewing the page that Mani posted I found the answer. For most variables, something like System.AccessToken would have a corresponding SYSTEM\_ACCESSTOKEN.
However, with a secret variable this is not the case. I was able to make it accessible to my python script by adding:
```
env:
SYSTEM_ACCESSTOKEN: $(S... | Can you use `os.environ['SYSTEM_ACCESSTOKEN']` . As mentioned in <https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#environment-variables> the **case/format of the environment variables** is different |
6,600,039 | I'm trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object? | 2011/07/06 | [
"https://Stackoverflow.com/questions/6600039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234723/"
] | If you're using Django 1.3, take a look at the included [RequestFactory](https://docs.djangoproject.com/en/1.3/topics/testing/#the-request-factory). | Sounds like you want the django test client <https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client> |
6,600,039 | I'm trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object? | 2011/07/06 | [
"https://Stackoverflow.com/questions/6600039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234723/"
] | The `django.test.client` would be the way to go.
From the [django docs](https://docs.djangoproject.com/en/1.1/topics/testing/#default-test-client)
```
from django.test.client import Client
c = Client()
response = c.post('/login/', {'username': 'john', 'password': 'smith'})
response.status_code
``` | Sounds like you want the django test client <https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client> |
6,600,039 | I'm trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object? | 2011/07/06 | [
"https://Stackoverflow.com/questions/6600039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234723/"
] | You should check out django.test.client.Client or django.test.client.RequestFactory which are documented in django's unit testing facility: <https://docs.djangoproject.com/en/1.3/topics/testing/>
I also suggest using template responses in your views since they let you inspect the context used to render the template: <... | Sounds like you want the django test client <https://docs.djangoproject.com/en/dev/topics/testing/#module-django.test.client> |
6,600,039 | I'm trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object? | 2011/07/06 | [
"https://Stackoverflow.com/questions/6600039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234723/"
] | The `django.test.client` would be the way to go.
From the [django docs](https://docs.djangoproject.com/en/1.1/topics/testing/#default-test-client)
```
from django.test.client import Client
c = Client()
response = c.post('/login/', {'username': 'john', 'password': 'smith'})
response.status_code
``` | If you're using Django 1.3, take a look at the included [RequestFactory](https://docs.djangoproject.com/en/1.3/topics/testing/#the-request-factory). |
6,600,039 | I'm trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object? | 2011/07/06 | [
"https://Stackoverflow.com/questions/6600039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234723/"
] | If you're using Django 1.3, take a look at the included [RequestFactory](https://docs.djangoproject.com/en/1.3/topics/testing/#the-request-factory). | You should check out django.test.client.Client or django.test.client.RequestFactory which are documented in django's unit testing facility: <https://docs.djangoproject.com/en/1.3/topics/testing/>
I also suggest using template responses in your views since they let you inspect the context used to render the template: <... |
6,600,039 | I'm trying to figure out if there is a quick way to test my django view functions form either the python or django shell. How would I go about instantiating and passing in faux HTTPrequest object? | 2011/07/06 | [
"https://Stackoverflow.com/questions/6600039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234723/"
] | The `django.test.client` would be the way to go.
From the [django docs](https://docs.djangoproject.com/en/1.1/topics/testing/#default-test-client)
```
from django.test.client import Client
c = Client()
response = c.post('/login/', {'username': 'john', 'password': 'smith'})
response.status_code
``` | You should check out django.test.client.Client or django.test.client.RequestFactory which are documented in django's unit testing facility: <https://docs.djangoproject.com/en/1.3/topics/testing/>
I also suggest using template responses in your views since they let you inspect the context used to render the template: <... |
19,130,113 | I've got a database full of BlobKeys that were previously uploaded through the standard Google App Engine [create\_upload\_url()](https://developers.google.com/appengine/docs/python/blobstore/functions#create_upload_url) process, and each of the uploads went to the same Google Cloud Storage bucket by setting the `gs_bu... | 2013/10/02 | [
"https://Stackoverflow.com/questions/19130113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361897/"
] | You can get the cloudstorage filename only in the upload handler (fileInfo.gs\_object\_name) and store it in your database. After that it is lost and it seems not to be preserved in BlobInfo or other metadata structures.
>
> Google says: Unlike BlobInfo metadata FileInfo metadata is not
> persisted to datastore. (Th... | From the statement in the docs, it looks like the generated GCS filenames are lost. You'll have to use gsutil to manually browse your bucket.
<https://developers.google.com/storage/docs/gsutil/commands/ls> |
19,130,113 | I've got a database full of BlobKeys that were previously uploaded through the standard Google App Engine [create\_upload\_url()](https://developers.google.com/appengine/docs/python/blobstore/functions#create_upload_url) process, and each of the uploads went to the same Google Cloud Storage bucket by setting the `gs_bu... | 2013/10/02 | [
"https://Stackoverflow.com/questions/19130113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361897/"
] | From the statement in the docs, it looks like the generated GCS filenames are lost. You'll have to use gsutil to manually browse your bucket.
<https://developers.google.com/storage/docs/gsutil/commands/ls> | If you have blobKeys you can use: ImagesServiceFactory.[makeImageFromBlob](https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/images/IImagesServiceFactory.html#makeImageFromBlob) |
19,130,113 | I've got a database full of BlobKeys that were previously uploaded through the standard Google App Engine [create\_upload\_url()](https://developers.google.com/appengine/docs/python/blobstore/functions#create_upload_url) process, and each of the uploads went to the same Google Cloud Storage bucket by setting the `gs_bu... | 2013/10/02 | [
"https://Stackoverflow.com/questions/19130113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/361897/"
] | You can get the cloudstorage filename only in the upload handler (fileInfo.gs\_object\_name) and store it in your database. After that it is lost and it seems not to be preserved in BlobInfo or other metadata structures.
>
> Google says: Unlike BlobInfo metadata FileInfo metadata is not
> persisted to datastore. (Th... | If you have blobKeys you can use: ImagesServiceFactory.[makeImageFromBlob](https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/images/IImagesServiceFactory.html#makeImageFromBlob) |
66,921,090 | I am trying to create SparkContext in jupyter notebook but I am getting following Error:
**Py4JError: org.apache.spark.api.python.PythonUtils.getPythonAuthSocketTimeout does not exist in the JVM**
Here is my code
```
from pyspark import SparkContext, SparkConf
conf = SparkConf().setMaster("local").setAppName("Grocer... | 2021/04/02 | [
"https://Stackoverflow.com/questions/66921090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7527164/"
] | Python's pyspark and spark cluster versions are inconsistent and this error is reported.
Uninstall the version that is consistent with the current pyspark, then install the same version as the spark cluster. My spark version is 3.0.2 and run the following code:
```
pip3 uninstall pyspark
pip3 install pyspark==3.0.2
`... | I have had the same error today and resolved it with the below code:
Execute this in a separate cell before you have your spark session builder
```
from pyspark import SparkContext,SQLContext,SparkConf,StorageLevel
from pyspark.sql import SparkSession
from pyspark.conf import SparkConf
SparkSession.bu... |
66,921,090 | I am trying to create SparkContext in jupyter notebook but I am getting following Error:
**Py4JError: org.apache.spark.api.python.PythonUtils.getPythonAuthSocketTimeout does not exist in the JVM**
Here is my code
```
from pyspark import SparkContext, SparkConf
conf = SparkConf().setMaster("local").setAppName("Grocer... | 2021/04/02 | [
"https://Stackoverflow.com/questions/66921090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7527164/"
] | We need to uninstall the default/exsisting/latest version of PySpark from PyCharm/Jupyter Notebook or any tool that we use.
Then check the version of Spark that we have installed in PyCharm/ Jupyter Notebook / CMD. Using the command `spark-submit --version` (In CMD/Terminal).
Then Install PySpark which matches the ve... | I have had the same error today and resolved it with the below code:
Execute this in a separate cell before you have your spark session builder
```
from pyspark import SparkContext,SQLContext,SparkConf,StorageLevel
from pyspark.sql import SparkSession
from pyspark.conf import SparkConf
SparkSession.bu... |
66,921,090 | I am trying to create SparkContext in jupyter notebook but I am getting following Error:
**Py4JError: org.apache.spark.api.python.PythonUtils.getPythonAuthSocketTimeout does not exist in the JVM**
Here is my code
```
from pyspark import SparkContext, SparkConf
conf = SparkConf().setMaster("local").setAppName("Grocer... | 2021/04/02 | [
"https://Stackoverflow.com/questions/66921090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7527164/"
] | Python's pyspark and spark cluster versions are inconsistent and this error is reported.
Uninstall the version that is consistent with the current pyspark, then install the same version as the spark cluster. My spark version is 3.0.2 and run the following code:
```
pip3 uninstall pyspark
pip3 install pyspark==3.0.2
`... | We need to uninstall the default/exsisting/latest version of PySpark from PyCharm/Jupyter Notebook or any tool that we use.
Then check the version of Spark that we have installed in PyCharm/ Jupyter Notebook / CMD. Using the command `spark-submit --version` (In CMD/Terminal).
Then Install PySpark which matches the ve... |
4,787,291 | I'm writing an application. No fancy GUI:s or anything, just a plain old console application. This application, lets call it App, needs to be able to load plugins on startup. So, naturally, i created a class for the plugins to inherit from:
```
class PluginBase(object):
def on_load(self):
pass
def on_u... | 2011/01/24 | [
"https://Stackoverflow.com/questions/4787291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/350784/"
] | You would make this a lot easier if you forced some constraints on the plugin writer, for example that all plugins must be packages that contain a `load_plugin( app, config)` function that returns a Plugin instance. Then all you have to do is try to import these packages and run the function. | Could you use execfile() instead of import with a specified namespace dict, then iterate over that namespace with issubclass, etc? |
4,787,291 | I'm writing an application. No fancy GUI:s or anything, just a plain old console application. This application, lets call it App, needs to be able to load plugins on startup. So, naturally, i created a class for the plugins to inherit from:
```
class PluginBase(object):
def on_load(self):
pass
def on_u... | 2011/01/24 | [
"https://Stackoverflow.com/questions/4787291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/350784/"
] | You might do something like this:
```
for c in candidates:
modname = os.path.splitext(c)[0]
try:
module=__import__(modname) #<-- You can get the module this way
except (ImportError,NotImplementedError):
continue
for cls in dir(module): #<-- Loop over all objects in the module... | Could you use execfile() instead of import with a specified namespace dict, then iterate over that namespace with issubclass, etc? |
4,787,291 | I'm writing an application. No fancy GUI:s or anything, just a plain old console application. This application, lets call it App, needs to be able to load plugins on startup. So, naturally, i created a class for the plugins to inherit from:
```
class PluginBase(object):
def on_load(self):
pass
def on_u... | 2011/01/24 | [
"https://Stackoverflow.com/questions/4787291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/350784/"
] | Here is a meta-classier way to register the plugins:
Define `PluginBase` to be of type `PluginType`.
`PluginType` automatically registers any instance (class) in the `plugins` set.
**plugin.py:**
```
plugins=set()
class PluginType(type):
def __init__(cls, name, bases, attrs):
super(PluginType, cls).__ini... | Could you use execfile() instead of import with a specified namespace dict, then iterate over that namespace with issubclass, etc? |
4,787,291 | I'm writing an application. No fancy GUI:s or anything, just a plain old console application. This application, lets call it App, needs to be able to load plugins on startup. So, naturally, i created a class for the plugins to inherit from:
```
class PluginBase(object):
def on_load(self):
pass
def on_u... | 2011/01/24 | [
"https://Stackoverflow.com/questions/4787291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/350784/"
] | You might do something like this:
```
for c in candidates:
modname = os.path.splitext(c)[0]
try:
module=__import__(modname) #<-- You can get the module this way
except (ImportError,NotImplementedError):
continue
for cls in dir(module): #<-- Loop over all objects in the module... | You would make this a lot easier if you forced some constraints on the plugin writer, for example that all plugins must be packages that contain a `load_plugin( app, config)` function that returns a Plugin instance. Then all you have to do is try to import these packages and run the function. |
4,787,291 | I'm writing an application. No fancy GUI:s or anything, just a plain old console application. This application, lets call it App, needs to be able to load plugins on startup. So, naturally, i created a class for the plugins to inherit from:
```
class PluginBase(object):
def on_load(self):
pass
def on_u... | 2011/01/24 | [
"https://Stackoverflow.com/questions/4787291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/350784/"
] | You might do something like this:
```
for c in candidates:
modname = os.path.splitext(c)[0]
try:
module=__import__(modname) #<-- You can get the module this way
except (ImportError,NotImplementedError):
continue
for cls in dir(module): #<-- Loop over all objects in the module... | Here is a meta-classier way to register the plugins:
Define `PluginBase` to be of type `PluginType`.
`PluginType` automatically registers any instance (class) in the `plugins` set.
**plugin.py:**
```
plugins=set()
class PluginType(type):
def __init__(cls, name, bases, attrs):
super(PluginType, cls).__ini... |
29,463,921 | A frog wants to cross a river.
There are 3 stones in the river she can jump to.
She wants to choose among all possible paths the one that leads to the smallest longest jump.
Ie. each of the possible paths will have one jump that is the longest. She needs to find the path where this longest jump is smallest.
The 2... | 2015/04/06 | [
"https://Stackoverflow.com/questions/29463921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4542063/"
] | I would use `Array()` to normalize the input and then there is only on case left:
```
work.map! do |w|
element = Array(w).first
console.button_map[element] || element
end
``` | I settled on this, not sure if it can be cleaner:
```
work.map! do |w|
if w.is_a? Array
w.tap{|x| x[0] = console.button_map[x[0]] || x[0] }
else
console.button_map[w] || w ... |
29,463,921 | A frog wants to cross a river.
There are 3 stones in the river she can jump to.
She wants to choose among all possible paths the one that leads to the smallest longest jump.
Ie. each of the possible paths will have one jump that is the longest. She needs to find the path where this longest jump is smallest.
The 2... | 2015/04/06 | [
"https://Stackoverflow.com/questions/29463921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4542063/"
] | I settled on this, not sure if it can be cleaner:
```
work.map! do |w|
if w.is_a? Array
w.tap{|x| x[0] = console.button_map[x[0]] || x[0] }
else
console.button_map[w] || w ... | ```
work = [[3, 1], 4, [3, 3, 4], 4, :sync, 1, 2, [5]]
work.map! do |w|
val = my_method [*w].first
case w
when Array then [val, *w[1..-1]]
else val
end
end
def my_method(n)
case n
when Fixnum then n+4
else n.to_s
end
end
work
#=> [[7, 1], 8, [7, 3, 4], 8, "sync", 5, 6, [9]]
```
Note:
```
[*[1,... |
29,463,921 | A frog wants to cross a river.
There are 3 stones in the river she can jump to.
She wants to choose among all possible paths the one that leads to the smallest longest jump.
Ie. each of the possible paths will have one jump that is the longest. She needs to find the path where this longest jump is smallest.
The 2... | 2015/04/06 | [
"https://Stackoverflow.com/questions/29463921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4542063/"
] | I would use `Array()` to normalize the input and then there is only on case left:
```
work.map! do |w|
element = Array(w).first
console.button_map[element] || element
end
``` | ```
work = [[3, 1], 4, [3, 3, 4], 4, :sync, 1, 2, [5]]
work.map! do |w|
val = my_method [*w].first
case w
when Array then [val, *w[1..-1]]
else val
end
end
def my_method(n)
case n
when Fixnum then n+4
else n.to_s
end
end
work
#=> [[7, 1], 8, [7, 3, 4], 8, "sync", 5, 6, [9]]
```
Note:
```
[*[1,... |
49,582,981 | I have a flask app in a docker container that writes to a local copy of SQLite db.
what I want to do is move the db out of the container and have it reside on my host.
how do I setup docker to run the python code from the container and read and write to the sql lite db on the host. | 2018/03/31 | [
"https://Stackoverflow.com/questions/49582981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9577029/"
] | Use bind-mount to share host file to container.
If you have the SQLite DB file as `app.db`, you can run your container with the `-v` flag (or the `--mount` flag):
```
docker run -v /absolute/path/to/app.db:/flask/app/app.db <IMAGE>
```
Docs: <https://docs.docker.com/storage/bind-mounts/> | You have either
* setup ownership privileges of your host directory to match `uid`:`gid` of the user in the container
or
* change `uid`:`gid` of the user in the container to match numerically `uid`:`gid` of your host user who owns directory with sqlite db file
Great answers for both approaches are described [here]... |
52,710,878 | I created conda environment and install pytorch and fastai (Mac OS Mojave) as below:
```
conda create -n fai_course python=3.7
source activate fai_course
conda install -c pytorch pytorch-nightly-cpu
conda install -c fastai torchvision-nightly-cpu
jupyter notebook
```
When I import a package from jupyter notebook, I... | 2018/10/08 | [
"https://Stackoverflow.com/questions/52710878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3899975/"
] | The comments say you "should" do a print, but nothing says you cannot print anything else after the print. Nothing even *forces* you to do a print, otherwise it would be a *shall*.
---
To be honest, reading questions about homework like this one makes me unhappy.
To me, the whole thing is useless, ugly, and does not... | The method stringLengt() should return "7" when you pass it the string "request", a different value when you pass it an empty string and another different value, when you pass null. Maybe you should take a look on control structures, especially selections. Also your stringLength method needs to return values of type St... |
32,042,679 | I saw a [twitter post](https://twitter.com/kssreeram/status/627477751797121024) pointing out that -12/10 = -2 in Python. What causes this? I thought the answer should (mathematically) be one. Why does python "literally" round down like this?
```
>>> -12/10
-2
>>> 12/10
1
>>> -1*12/10
-2
>>> 12/10 * -1
-1
``` | 2015/08/17 | [
"https://Stackoverflow.com/questions/32042679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3474956/"
] | This is due to [int](https://docs.python.org/2/library/functions.html#int) rounding down divisions. (aka [Floor division](http://python-history.blogspot.com.br/2010/08/why-pythons-integer-division-floors.html))
```
>>> -12/10
-2
>>> -12.0/10
-1.2
>>> 12/10
1
>>> 12.0/10
1.2
``` | This is known as floor division (aka int division). In Python 2, this is the default behavior for `-12/10`. In Python 3, the default behavior is to use floating point division. To enable this behavior in Python 2, use the following import statement:
```
from __future__ import division
```
To use floor division in Py... |
27,102,518 | I need to optimize this regular expression.
```
^(.+?)\|[\w\d]+?\s+?(\d\d\/\d\d\/\d\d\d\d\s+?\d\d:\d\d:\d\d\.\d\d\d)[\s\d]+?\s+?(\d+?)\s+?\d+?\s+?(\d+?)$
```
The input is something like this:
```
-tpf0q16|856B 11/20/2014 00:00:00.015 0 0 0 0 0 689 ... | 2014/11/24 | [
"https://Stackoverflow.com/questions/27102518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42371/"
] | The first step is to get rid of the unneeded reluctant (a.k.a. "lazy") quantifiers. According to RegexBuddy, your regex:
```
^(.+?)\|[\w\d]+?\s+?(\d\d\/\d\d\/\d\d\d\d\s+?\d\d:\d\d:\d\d\.\d\d\d)[\s\d]+?\s+?(\d+?)\s+?\d+?\s+?(\d+?)$
```
...takes 6425 steps to match your sample string. This one:
```
^(.+?)\|[\w\d]+\s+... | A bit more optimized.
```
>>> import re
>>> s = "-tpf0q16|856B 11/20/2014 00:00:00.015 0 0 0 0 0 689 14 689 703 702 701 700"
>>> re.findall(r'(?m)^([^|]+)\|[\w\d]+?\s+?(\d{2}\/\d{2}\/\d{4}\s+\d{2}:\d{2}:\d{2}\... |
24,995,438 | I can run iPython, but when I try to initiate a notebook I get the following error:
```
~ ipython notebook
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 8, in <module>
load_entry_point('ipython==2.1.0', 'console_scripts', 'ipython')()
File "/Library/Python/2.7/site-... | 2014/07/28 | [
"https://Stackoverflow.com/questions/24995438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54564/"
] | Arg. The *ipython* install is a little idiosyncratic. Here's what I had to do to resolve this:
```
$ pip uninstall ipython
$ pip install "ipython[all]"
```
The issue is that notebooks have their own set of dependencies, which aren't installed with `pip install ipython`. However, having installed *ipython*, pip doesn... | For me (Ubuntu 14.04.2) worked installation by synaptic package manager: the package is called python3-zmq, with this package will be installed libzmq3.
After that check if pyzmq is correctly installed:
```
pip list
```
Then I installed ipython:
```
pip install "ipython[all]"
``` |
24,995,438 | I can run iPython, but when I try to initiate a notebook I get the following error:
```
~ ipython notebook
Traceback (most recent call last):
File "/usr/local/bin/ipython", line 8, in <module>
load_entry_point('ipython==2.1.0', 'console_scripts', 'ipython')()
File "/Library/Python/2.7/site-... | 2014/07/28 | [
"https://Stackoverflow.com/questions/24995438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/54564/"
] | Arg. The *ipython* install is a little idiosyncratic. Here's what I had to do to resolve this:
```
$ pip uninstall ipython
$ pip install "ipython[all]"
```
The issue is that notebooks have their own set of dependencies, which aren't installed with `pip install ipython`. However, having installed *ipython*, pip doesn... | Using
```
ipython2.7 notebook
```
Instead of
```
ipython notebook
```
Did the trick for me. |
48,452,294 | I have a python script that accepts a `-f` flag, and appends multiple uses of the flag.
For example, if I run `python myscript -f file1.txt -f file2.txt`, I would have a list of files, `files=['file1.txt', 'files2.txt']`. This works great, but am wondering how I can automatically use the results of a find command to a... | 2018/01/25 | [
"https://Stackoverflow.com/questions/48452294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4509191/"
] | With the caveat that this will fail if there are more files than will fit on a single command line (whereas `xargs` would run `myscript.py` multiple times, each with a subset of the full list of arguments):
```
#!/usr/bin/env bash
args=( )
while IFS= read -r -d '' name; do
args+=( -f "$name" )
done < <(find . -inam... | Your title seems to imply that you can modify the script. In that case, use the `nargs` (number of args) option to allow more arguments for the `-f` flag:
```
parser = argparse.ArgumentParser()
parser.add_argument('--files', '-f', nargs='+')
args = parser.parse_args()
print(args.files)
```
Then you can use your find... |
22,597,089 | There are a lot of questions about installing matplotlib on mac, but as far as I can tell I've installed it correctly using pip and it's just not working. When I try and run a script with matplotlib.pyplot.plot(x, y) nothing happens. No error, no nothing.
```
import matplotlib.pyplot
x = [1,2,3,4]
y = [4,3,2,1]
mat... | 2014/03/23 | [
"https://Stackoverflow.com/questions/22597089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2930596/"
] | You need to call the `show` function.
```
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [4,3,2,1]
plt.plot(x, y)
plt.show()
``` | It's likely that the plot is hidden behind the editor window or the spyder window on the screen. Instead of changing matplotlib settings, just learn the trackpack gestures of the mac, "app exposé" is the one you need to make your plots visible (see system preferences, trackpack). Then click on the figure to raise it to... |
14,938,541 | I use matplotlib to plot a scatter chart:

And label the bubble using a transparent box according to the tip at [How to annotate point on a scatter automatically placed arrow](https://stackoverflow.com/q/9074996/7758804)
Here is the code:
```
if sh... | 2013/02/18 | [
"https://Stackoverflow.com/questions/14938541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1072888/"
] | It is a little rough around the edges (I can't quite figure out how to scale the relative strengths of the spring network vs the repulsive force, and the bounding box is a bit screwed up), but this is a decent start:
```
import networkx as nx
N = 15
scatter_data = rand(3, N)
G=nx.Graph()
data_nodes = []
init_pos = {... | We can use plotly for this. But we can't help placing overlap correctly if there is lot of data. Instead we can zoom in and zoom out.
```
import plotly.express as px
df = px.data.tips()
df = px.data.gapminder().query("year==2007 and continent=='Americas'")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", text="count... |
14,938,541 | I use matplotlib to plot a scatter chart:

And label the bubble using a transparent box according to the tip at [How to annotate point on a scatter automatically placed arrow](https://stackoverflow.com/q/9074996/7758804)
Here is the code:
```
if sh... | 2013/02/18 | [
"https://Stackoverflow.com/questions/14938541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1072888/"
] | It is a little rough around the edges (I can't quite figure out how to scale the relative strengths of the spring network vs the repulsive force, and the bounding box is a bit screwed up), but this is a decent start:
```
import networkx as nx
N = 15
scatter_data = rand(3, N)
G=nx.Graph()
data_nodes = []
init_pos = {... | Just created another quick solution that is also very fast: [textalloc](https://github.com/ckjellson/textalloc)
In this case you could do something like this:
```
import textalloc as ta
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2022)
N = 30
scatter_data = np.random.rand(N, 3)*10
fig, ax = pl... |
14,938,541 | I use matplotlib to plot a scatter chart:

And label the bubble using a transparent box according to the tip at [How to annotate point on a scatter automatically placed arrow](https://stackoverflow.com/q/9074996/7758804)
Here is the code:
```
if sh... | 2013/02/18 | [
"https://Stackoverflow.com/questions/14938541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1072888/"
] | The following builds on [tcaswell's answer](https://stackoverflow.com/a/15859652/190597).
Networkx layout methods such as `nx.spring_layout` rescale the positions so that they all fit in a unit square (by default). Even the position of the fixed `data_nodes` are rescaled. So, to apply the `pos` to the original `scatt... | We can use plotly for this. But we can't help placing overlap correctly if there is lot of data. Instead we can zoom in and zoom out.
```
import plotly.express as px
df = px.data.tips()
df = px.data.gapminder().query("year==2007 and continent=='Americas'")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", text="count... |
14,938,541 | I use matplotlib to plot a scatter chart:

And label the bubble using a transparent box according to the tip at [How to annotate point on a scatter automatically placed arrow](https://stackoverflow.com/q/9074996/7758804)
Here is the code:
```
if sh... | 2013/02/18 | [
"https://Stackoverflow.com/questions/14938541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1072888/"
] | The following builds on [tcaswell's answer](https://stackoverflow.com/a/15859652/190597).
Networkx layout methods such as `nx.spring_layout` rescale the positions so that they all fit in a unit square (by default). Even the position of the fixed `data_nodes` are rescaled. So, to apply the `pos` to the original `scatt... | Just created another quick solution that is also very fast: [textalloc](https://github.com/ckjellson/textalloc)
In this case you could do something like this:
```
import textalloc as ta
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2022)
N = 30
scatter_data = np.random.rand(N, 3)*10
fig, ax = pl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.