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
30,958,835
I would like to have a function as an optional argument of another function in python but it is not clear for me how I can do that. For example I define the following function: ``` import os, time, datetime def f(t=datetime.datetime.now()): return t.timetuple() ``` I have placed `t=datetime.datetime.now()` in ...
2015/06/20
[ "https://Stackoverflow.com/questions/30958835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/805417/" ]
You can prevent the function from being evaluated by assigning the function when loading it into your second function. ``` import datetime def f(t = datetime.datetime.now()): return t.timetuple() def main(ff=f): print ff print ff() >>> main() <function f at 0x10a4e6938> time.struct_time(tm_year=2015, tm...
The default parameter value is evaluated only once when the function is defined.
30,958,835
I would like to have a function as an optional argument of another function in python but it is not clear for me how I can do that. For example I define the following function: ``` import os, time, datetime def f(t=datetime.datetime.now()): return t.timetuple() ``` I have placed `t=datetime.datetime.now()` in ...
2015/06/20
[ "https://Stackoverflow.com/questions/30958835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/805417/" ]
Here, the optional parameter is the *function* for datetime now - no parentheses, as @jonsharpe was recommending. Calling f calls the default function, and calling it twice returns two different times: ``` >>> import datetime >>> def f(t=datetime.datetime.now): ... return t() ... >>> f() datetime.datetime(2015, 6...
The default parameter value is evaluated only once when the function is defined.
30,958,835
I would like to have a function as an optional argument of another function in python but it is not clear for me how I can do that. For example I define the following function: ``` import os, time, datetime def f(t=datetime.datetime.now()): return t.timetuple() ``` I have placed `t=datetime.datetime.now()` in ...
2015/06/20
[ "https://Stackoverflow.com/questions/30958835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/805417/" ]
As mentioned by flask, the default value is evaluated when the function is parsed, so it will be set to one time. The typical solution to this, is to not have the default a mutable value. You can do the followings: ``` def f(t=None): if not t: t = datetime.datetime.now() return t.timetuple() ``` BTW...
You can prevent the function from being evaluated by assigning the function when loading it into your second function. ``` import datetime def f(t = datetime.datetime.now()): return t.timetuple() def main(ff=f): print ff print ff() >>> main() <function f at 0x10a4e6938> time.struct_time(tm_year=2015, tm...
30,958,835
I would like to have a function as an optional argument of another function in python but it is not clear for me how I can do that. For example I define the following function: ``` import os, time, datetime def f(t=datetime.datetime.now()): return t.timetuple() ``` I have placed `t=datetime.datetime.now()` in ...
2015/06/20
[ "https://Stackoverflow.com/questions/30958835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/805417/" ]
As mentioned by flask, the default value is evaluated when the function is parsed, so it will be set to one time. The typical solution to this, is to not have the default a mutable value. You can do the followings: ``` def f(t=None): if not t: t = datetime.datetime.now() return t.timetuple() ``` BTW...
Here, the optional parameter is the *function* for datetime now - no parentheses, as @jonsharpe was recommending. Calling f calls the default function, and calling it twice returns two different times: ``` >>> import datetime >>> def f(t=datetime.datetime.now): ... return t() ... >>> f() datetime.datetime(2015, 6...
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
Your update emulates what the absolute import does: `import package1.module1` if you do it while `module1` being imported. If you'd like to use a dynamic parent package name then to import `module1` in the `module2.py`: ``` import importlib module1 = importlib.import_module('.module1', __package__) ``` --- > > I n...
I ran into this same issue today, and it seems this is indeed broken in python3.4, but works in python3.5. The [changelog](https://docs.python.org/3/whatsnew/3.5.html) has an entry: > > Circular imports involving relative imports are now supported. (Contributed by Brett Cannon and Antoine Pitrou in [bpo-17636](https...
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
Your update emulates what the absolute import does: `import package1.module1` if you do it while `module1` being imported. If you'd like to use a dynamic parent package name then to import `module1` in the `module2.py`: ``` import importlib module1 = importlib.import_module('.module1', __package__) ``` --- > > I n...
Make sure your `package1` is a folder. Create a class in `__init__.py` -- say `class1`. Include your logic in a method under `class1` -- say `method1`. Now, write the following code - ``` from .package1 import class1 class1.method1() ``` This was my way of resolving it. To summarize, your root directory is `.` so...
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
``` module2.py import module1 ``` Works too.
I ran into this same issue today, and it seems this is indeed broken in python3.4, but works in python3.5. The [changelog](https://docs.python.org/3/whatsnew/3.5.html) has an entry: > > Circular imports involving relative imports are now supported. (Contributed by Brett Cannon and Antoine Pitrou in [bpo-17636](https...
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
A better solution for your problem is to put package1 in it's own separate package. Of course then it can't import package2, but then again if it is reusable, why would it?
``` module2.py import module1 ``` Works too.
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
A better solution for your problem is to put package1 in it's own separate package. Of course then it can't import package2, but then again if it is reusable, why would it?
Your update emulates what the absolute import does: `import package1.module1` if you do it while `module1` being imported. If you'd like to use a dynamic parent package name then to import `module1` in the `module2.py`: ``` import importlib module1 = importlib.import_module('.module1', __package__) ``` --- > > I n...
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
A better solution for your problem is to put package1 in it's own separate package. Of course then it can't import package2, but then again if it is reusable, why would it?
Circular imports should be generally avoided, see also [this answer to a related question](https://stackoverflow.com/questions/1556387/circular-import-dependency-in-python/1556444#1556444), or [this article on effbot.org](http://effbot.org/zone/import-confusion.htm#circular-imports). In this case the problem is that y...
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
A better solution for your problem is to put package1 in it's own separate package. Of course then it can't import package2, but then again if it is reusable, why would it?
The accepted answer to [Circular import dependency in Python](https://stackoverflow.com/questions/1556387/circular-import-dependency-in-python) makes a good point: > > If a depends on c and c depends on a, aren't they actually the same unit then? > > > You should really examine why you have split a and c into two p...
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
A better solution for your problem is to put package1 in it's own separate package. Of course then it can't import package2, but then again if it is reusable, why would it?
Make sure your `package1` is a folder. Create a class in `__init__.py` -- say `class1`. Include your logic in a method under `class1` -- say `method1`. Now, write the following code - ``` from .package1 import class1 class1.method1() ``` This was my way of resolving it. To summarize, your root directory is `.` so...
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
Circular imports should be generally avoided, see also [this answer to a related question](https://stackoverflow.com/questions/1556387/circular-import-dependency-in-python/1556444#1556444), or [this article on effbot.org](http://effbot.org/zone/import-confusion.htm#circular-imports). In this case the problem is that y...
Your update emulates what the absolute import does: `import package1.module1` if you do it while `module1` being imported. If you'd like to use a dynamic parent package name then to import `module1` in the `module2.py`: ``` import importlib module1 = importlib.import_module('.module1', __package__) ``` --- > > I n...
8,030,264
Python imports drive me crazy (my experience with python imports sometime doesn't correspond at all to idiom 'Explicit is better than implicit' :( ): ``` [app] start.py from package1 import module1 [package1] __init__.py print('Init package1') module1.py print('I...
2011/11/06
[ "https://Stackoverflow.com/questions/8030264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248296/" ]
A better solution for your problem is to put package1 in it's own separate package. Of course then it can't import package2, but then again if it is reusable, why would it?
I ran into this same issue today, and it seems this is indeed broken in python3.4, but works in python3.5. The [changelog](https://docs.python.org/3/whatsnew/3.5.html) has an entry: > > Circular imports involving relative imports are now supported. (Contributed by Brett Cannon and Antoine Pitrou in [bpo-17636](https...
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There's not a command to do that, but you can iterate over `environ["PATH"]` and look if the file exists, which is actually what `which` does. ``` import os def which(file): for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(os.path.join(path, file)): return os.path.join(p...
You could try something like the following: ``` import os import os.path def which(filename): """docstring for which""" locations = os.environ.get("PATH").split(os.pathsep) candidates = [] for location in locations: candidate = os.path.join(location, filename) if os.path.isfile(candidat...
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I know this is an older question, but if you happen to be using Python 3.3+ you can use `shutil.which(cmd)`. You can find the documentation [here](https://docs.python.org/3/library/shutil.html?highlight=.which#shutil.which). It has the advantage of being in the standard library. An example would be like so: ``` >>> i...
You could try something like the following: ``` import os import os.path def which(filename): """docstring for which""" locations = os.environ.get("PATH").split(os.pathsep) candidates = [] for location in locations: candidate = os.path.join(location, filename) if os.path.isfile(candidat...
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I know this is an older question, but if you happen to be using Python 3.3+ you can use `shutil.which(cmd)`. You can find the documentation [here](https://docs.python.org/3/library/shutil.html?highlight=.which#shutil.which). It has the advantage of being in the standard library. An example would be like so: ``` >>> i...
This is the equivalent of the which command, which not only checks if the file exists, but also whether it is executable: ``` import os def which(file_name): for path in os.environ["PATH"].split(os.pathsep): full_path = os.path.join(path, file_name) if os.path.exists(full_path) and os.access(full_...
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There's not a command to do that, but you can iterate over `environ["PATH"]` and look if the file exists, which is actually what `which` does. ``` import os def which(file): for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(os.path.join(path, file)): return os.path.join(p...
If you use `shell=True`, then your command will be run through the system shell, which will automatically find the binary on the path: ``` p = subprocess.Popen("abc", stdout=subprocess.PIPE, shell=True) ```
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
If you use `shell=True`, then your command will be run through the system shell, which will automatically find the binary on the path: ``` p = subprocess.Popen("abc", stdout=subprocess.PIPE, shell=True) ```
Here's a one-line version of earlier answers: ``` import os which = lambda y: next(filter(lambda x: os.path.isfile(x) and os.access(x,os.X_OK),[x+os.path.sep+y for x in os.getenv("PATH").split(os.pathsep)]),None) ``` used like so: ``` >>> which("ls") '/bin/ls' ```
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There is [`distutils.spawn.find_executable()`](https://docs.python.org/3.5/distutils/apiref.html#module-distutils.spawn).
I know this is an older question, but if you happen to be using Python 3.3+ you can use `shutil.which(cmd)`. You can find the documentation [here](https://docs.python.org/3/library/shutil.html?highlight=.which#shutil.which). It has the advantage of being in the standard library. An example would be like so: ``` >>> i...
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There is [`distutils.spawn.find_executable()`](https://docs.python.org/3.5/distutils/apiref.html#module-distutils.spawn).
Here's a one-line version of earlier answers: ``` import os which = lambda y: next(filter(lambda x: os.path.isfile(x) and os.access(x,os.X_OK),[x+os.path.sep+y for x in os.getenv("PATH").split(os.pathsep)]),None) ``` used like so: ``` >>> which("ls") '/bin/ls' ```
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
I know this is an older question, but if you happen to be using Python 3.3+ you can use `shutil.which(cmd)`. You can find the documentation [here](https://docs.python.org/3/library/shutil.html?highlight=.which#shutil.which). It has the advantage of being in the standard library. An example would be like so: ``` >>> i...
Here's a one-line version of earlier answers: ``` import os which = lambda y: next(filter(lambda x: os.path.isfile(x) and os.access(x,os.X_OK),[x+os.path.sep+y for x in os.getenv("PATH").split(os.pathsep)]),None) ``` used like so: ``` >>> which("ls") '/bin/ls' ```
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There's not a command to do that, but you can iterate over `environ["PATH"]` and look if the file exists, which is actually what `which` does. ``` import os def which(file): for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(os.path.join(path, file)): return os.path.join(p...
This is the equivalent of the which command, which not only checks if the file exists, but also whether it is executable: ``` import os def which(file_name): for path in os.environ["PATH"].split(os.pathsep): full_path = os.path.join(path, file_name) if os.path.exists(full_path) and os.access(full_...
5,226,958
I need to setup environment with the path to a binary. In the shell, I can use `which` to find the path. Is there an equivalent in python? This is my code. ```py cmd = ["which","abc"] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) res = p.stdout.readlines() if len(res) == 0: return False return True ```
2011/03/08
[ "https://Stackoverflow.com/questions/5226958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
There's not a command to do that, but you can iterate over `environ["PATH"]` and look if the file exists, which is actually what `which` does. ``` import os def which(file): for path in os.environ["PATH"].split(os.pathsep): if os.path.exists(os.path.join(path, file)): return os.path.join(p...
Here's a one-line version of earlier answers: ``` import os which = lambda y: next(filter(lambda x: os.path.isfile(x) and os.access(x,os.X_OK),[x+os.path.sep+y for x in os.getenv("PATH").split(os.pathsep)]),None) ``` used like so: ``` >>> which("ls") '/bin/ls' ```
4,420,218
I have a VPS running a fresh install of Ubuntu 10.04 LTS. I'm trying to set up a live application using the Flask microframework, but it's giving me trouble. I took notes while I tried to get it running and here's my play-by-play in an effort to pinpoint exactly where I went wrong. INSTALLATION ============ <http://f...
2010/12/12
[ "https://Stackoverflow.com/questions/4420218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511200/" ]
Obviously, it cannot find your "`myapp`" package. You should add it to the path in your `myapp.wsgi` file like this: ``` import sys sys.path.append(DIRECTORY_WHERE_YOUR_PACKAGE_IS_LOCATED) from myapp import app ``` Also, if `myapp` module is a package, you should put and empty `__init__.py` file into its directory.
Edit line `sys.path.append`, it needs to be a string. ``` import sys sys.path.append('directory/where/package/is/located') ``` **Notice** the single quotes.
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
``` #Shamelessly combined from google and other stackoverflow like sites to form a single function import platform,socket,re,uuid,json,psutil,logging def getSystemInfo(): try: info={} info['platform']=platform.system() info['platform-release']=platform.release() info['platform-vers...
``` import psutil import platform from datetime import datetime import cpuinfo import socket import uuid import re def get_size(bytes, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "...
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
some of these could be obtained from the [`platform`](http://docs.python.org/library/platform.html) module: ``` >>> import platform >>> platform.machine() 'x86' >>> platform.version() '5.1.2600' >>> platform.platform() 'Windows-XP-5.1.2600-SP2' >>> platform.uname() ('Windows', 'name', 'XP', '5.1.2600', 'x86', 'x86 Fam...
The [os module](http://docs.python.org/library/os.html) has the uname function to get information about the os & version: ``` >>> import os >>> os.uname() ``` For my system, running CentOS 5.4 with 2.6.18 kernel this returns: > > ('Linux', 'mycomputer.domain.user','2.6.18-92.1.22.el5PAE', '#1 SMP Tue > Dec 16 12:...
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
``` #Shamelessly combined from google and other stackoverflow like sites to form a single function import platform,socket,re,uuid,json,psutil,logging def getSystemInfo(): try: info={} info['platform']=platform.system() info['platform-release']=platform.release() info['platform-vers...
The [os module](http://docs.python.org/library/os.html) has the uname function to get information about the os & version: ``` >>> import os >>> os.uname() ``` For my system, running CentOS 5.4 with 2.6.18 kernel this returns: > > ('Linux', 'mycomputer.domain.user','2.6.18-92.1.22.el5PAE', '#1 SMP Tue > Dec 16 12:...
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
Found this Simple code ``` import platform print("="*40, "System Information", "="*40) uname = platform.uname() print(f"System: {uname.system}") print(f"Node Name: {uname.node}") print(f"Release: {uname.release}") print(f"Version: {uname.version}") print(f"Machine: {uname.machine}") print(f"Processor: {uname.processo...
``` #This should work import os for item in os.environ: print(f'{item}{" : "}{os.environ[item]}') ```
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
Found this Simple code ``` import platform print("="*40, "System Information", "="*40) uname = platform.uname() print(f"System: {uname.system}") print(f"Node Name: {uname.node}") print(f"Release: {uname.release}") print(f"Version: {uname.version}") print(f"Machine: {uname.machine}") print(f"Processor: {uname.processo...
``` import psutil import platform from datetime import datetime import cpuinfo import socket import uuid import re def get_size(bytes, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "...
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
The [os module](http://docs.python.org/library/os.html) has the uname function to get information about the os & version: ``` >>> import os >>> os.uname() ``` For my system, running CentOS 5.4 with 2.6.18 kernel this returns: > > ('Linux', 'mycomputer.domain.user','2.6.18-92.1.22.el5PAE', '#1 SMP Tue > Dec 16 12:...
``` import psutil import platform from datetime import datetime import cpuinfo import socket import uuid import re def get_size(bytes, suffix="B"): """ Scale bytes to its proper format e.g: 1253656 => '1.20MB' 1253656678 => '1.17GB' """ factor = 1024 for unit in ["", "K", "M", "...
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
``` #Shamelessly combined from google and other stackoverflow like sites to form a single function import platform,socket,re,uuid,json,psutil,logging def getSystemInfo(): try: info={} info['platform']=platform.system() info['platform-release']=platform.release() info['platform-vers...
Found this Simple code ``` import platform print("="*40, "System Information", "="*40) uname = platform.uname() print(f"System: {uname.system}") print(f"Node Name: {uname.node}") print(f"Release: {uname.release}") print(f"Version: {uname.version}") print(f"Machine: {uname.machine}") print(f"Processor: {uname.processo...
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
some of these could be obtained from the [`platform`](http://docs.python.org/library/platform.html) module: ``` >>> import platform >>> platform.machine() 'x86' >>> platform.version() '5.1.2600' >>> platform.platform() 'Windows-XP-5.1.2600-SP2' >>> platform.uname() ('Windows', 'name', 'XP', '5.1.2600', 'x86', 'x86 Fam...
``` #This should work import os for item in os.environ: print(f'{item}{" : "}{os.environ[item]}') ```
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
The [os module](http://docs.python.org/library/os.html) has the uname function to get information about the os & version: ``` >>> import os >>> os.uname() ``` For my system, running CentOS 5.4 with 2.6.18 kernel this returns: > > ('Linux', 'mycomputer.domain.user','2.6.18-92.1.22.el5PAE', '#1 SMP Tue > Dec 16 12:...
Found this Simple code ``` import platform print("="*40, "System Information", "="*40) uname = platform.uname() print(f"System: {uname.system}") print(f"Node Name: {uname.node}") print(f"Release: {uname.release}") print(f"Version: {uname.version}") print(f"Machine: {uname.machine}") print(f"Processor: {uname.processo...
3,103,178
I need to get the info under what environment the software is running. Does python have a library for this purpose? I want to know the following info. * OS name/version * Name of the CPU, clock speed * Number of CPU core * Size of memory
2010/06/23
[ "https://Stackoverflow.com/questions/3103178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260127/" ]
The [os module](http://docs.python.org/library/os.html) has the uname function to get information about the os & version: ``` >>> import os >>> os.uname() ``` For my system, running CentOS 5.4 with 2.6.18 kernel this returns: > > ('Linux', 'mycomputer.domain.user','2.6.18-92.1.22.el5PAE', '#1 SMP Tue > Dec 16 12:...
``` #This should work import os for item in os.environ: print(f'{item}{" : "}{os.environ[item]}') ```
13,337,140
Brand new to using python, need help figuring out why my command line is spitting out huge strings of numbers and not the fib sequence up to the var I pass in. Here is what I have so far: ``` import sys def fib(n): a, b = 0, 1 while a < n: print a a, b = b, a+b if __name__ == "__main__": ...
2012/11/12
[ "https://Stackoverflow.com/questions/13337140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816962/" ]
Don't forget to convert the input argument (a string) into an integer type: ``` fib(int(sys.argv[1])) ```
Try `fib(int(sys.argv[1]))`, that might be the problem, but I didn't try it.
52,557,158
I am new to python. I got this pre written code that downloads data in to report. But I am getting the error > > "write() argument must be str, not bytes". > > > See below code ``` def _download_report(service, response, ostream): logger.info('Downloading keyword report') written_header = False for...
2018/09/28
[ "https://Stackoverflow.com/questions/52557158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10429839/" ]
you'll need to change the last line to ``` ostream.write(istream.read().decode('utf-8')) ``` PS. you may need to replace `'utf-8`` with whatever encoding the data is in
To elaborate more on @sgDysregulation's answer: One peculiarity with python 3 is that strings (`'hello, world'`) and binary strings (`b'hello, world'`) are basically incompatible. As an example, if you're familiar with basic file I/O, there are two types of modes to read a file in - you could use `open('file.txt', 'r'...
52,557,158
I am new to python. I got this pre written code that downloads data in to report. But I am getting the error > > "write() argument must be str, not bytes". > > > See below code ``` def _download_report(service, response, ostream): logger.info('Downloading keyword report') written_header = False for...
2018/09/28
[ "https://Stackoverflow.com/questions/52557158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10429839/" ]
you'll need to change the last line to ``` ostream.write(istream.read().decode('utf-8')) ``` PS. you may need to replace `'utf-8`` with whatever encoding the data is in
You have to decode the BytesIO object to get a string that can be written to the file: ``` ostream.write(istream.read().decode('utf-8')) ```
21,322,568
This is my first time asking a question. I am just starting to get into programming, so i am beginning with Python. So I've basically got a random number generator inside of a while loop, thats inside of my "r()' function. What I want to do is take all of the numbers (basically like an infinite amount until i shut down...
2014/01/24
[ "https://Stackoverflow.com/questions/21322568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701400/" ]
You can use ``` numpy.stack(arrays, axis=0) ``` if you have an array of arrays. You can specify the axis in case you want to stack columns and not rows.
You can just call `np.array` on the list of 1D arrays. ``` >>> import numpy as np >>> arrs = [np.array([1,2,3]), np.array([4,5,6]), np.array([7,8,9])] >>> arrs [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9])] >>> arr2d = np.array(arrs) >>> arr2d.shape (3, 3) >>> arr2d array([[1, 2, 3], [4, 5, 6], [...
21,322,568
This is my first time asking a question. I am just starting to get into programming, so i am beginning with Python. So I've basically got a random number generator inside of a while loop, thats inside of my "r()' function. What I want to do is take all of the numbers (basically like an infinite amount until i shut down...
2014/01/24
[ "https://Stackoverflow.com/questions/21322568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701400/" ]
You can use ``` numpy.stack(arrays, axis=0) ``` if you have an array of arrays. You can specify the axis in case you want to stack columns and not rows.
The array may be recreated: ``` a = np.array(a.tolist()) ```
48,683,238
I have this error ``` onecheck(sys.argv[1],sys.argv[2],sys.argv[3]) IndexError: list index out of range ``` I try to make loop a python script . This is code : ``` with open(file) as k: for line in k: aa, bb, cc = line.split(':') time.sleep(5) os.system("python checkfile.py " + cc...
2018/02/08
[ "https://Stackoverflow.com/questions/48683238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8868451/" ]
A fairly simple way of finding groups as you described would be to convert data to a boolean array with ones for data inside groups and 0 for data outside the groups and compute the difference of two consecutive value, this way you'll have 1 for the start of a group and -1 for the end. Here's an example of that : ```...
Your smoothed data has no zeros left: ``` import numpy as np def smooth(y, box_pts): box = np.ones(box_pts)/box_pts print(box) y_smooth = np.convolve(y, box, mode='same') return y_smooth mydata = [0.0, 0.0, 0.0, 0.0,-0.2, 0.143, 0.0, 0.22, 0.135, 0.44, 0.1, 0.0, 0.0, 0.0, 0.0, 0...
48,683,238
I have this error ``` onecheck(sys.argv[1],sys.argv[2],sys.argv[3]) IndexError: list index out of range ``` I try to make loop a python script . This is code : ``` with open(file) as k: for line in k: aa, bb, cc = line.split(':') time.sleep(5) os.system("python checkfile.py " + cc...
2018/02/08
[ "https://Stackoverflow.com/questions/48683238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8868451/" ]
A fairly simple way of finding groups as you described would be to convert data to a boolean array with ones for data inside groups and 0 for data outside the groups and compute the difference of two consecutive value, this way you'll have 1 for the start of a group and -1 for the end. Here's an example of that : ```...
Part 2 - find the group midpoint: ``` mydata = [0.0, 0.0, 0.0, 0.0, 0.0, 0.143, 0.0, 0.22, 0.135, 0.44, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.33, 0.65, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0] groups = [] last_start = 0 last_end = 0 in_group = 0 for i in range(1, len(mydata) - 1): if not in_group: ...
48,683,238
I have this error ``` onecheck(sys.argv[1],sys.argv[2],sys.argv[3]) IndexError: list index out of range ``` I try to make loop a python script . This is code : ``` with open(file) as k: for line in k: aa, bb, cc = line.split(':') time.sleep(5) os.system("python checkfile.py " + cc...
2018/02/08
[ "https://Stackoverflow.com/questions/48683238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8868451/" ]
A fairly simple way of finding groups as you described would be to convert data to a boolean array with ones for data inside groups and 0 for data outside the groups and compute the difference of two consecutive value, this way you'll have 1 for the start of a group and -1 for the end. Here's an example of that : ```...
Full numpy solution would be something like this: (not fully optimized) ``` import numpy as np input_data = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.143, 0.0, 0.22, 0.135, 0.44, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.33, 0.65, 0.22, 0.0, 0.0, 0....
48,683,238
I have this error ``` onecheck(sys.argv[1],sys.argv[2],sys.argv[3]) IndexError: list index out of range ``` I try to make loop a python script . This is code : ``` with open(file) as k: for line in k: aa, bb, cc = line.split(':') time.sleep(5) os.system("python checkfile.py " + cc...
2018/02/08
[ "https://Stackoverflow.com/questions/48683238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8868451/" ]
Your smoothed data has no zeros left: ``` import numpy as np def smooth(y, box_pts): box = np.ones(box_pts)/box_pts print(box) y_smooth = np.convolve(y, box, mode='same') return y_smooth mydata = [0.0, 0.0, 0.0, 0.0,-0.2, 0.143, 0.0, 0.22, 0.135, 0.44, 0.1, 0.0, 0.0, 0.0, 0.0, 0...
Part 2 - find the group midpoint: ``` mydata = [0.0, 0.0, 0.0, 0.0, 0.0, 0.143, 0.0, 0.22, 0.135, 0.44, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.33, 0.65, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0] groups = [] last_start = 0 last_end = 0 in_group = 0 for i in range(1, len(mydata) - 1): if not in_group: ...
48,683,238
I have this error ``` onecheck(sys.argv[1],sys.argv[2],sys.argv[3]) IndexError: list index out of range ``` I try to make loop a python script . This is code : ``` with open(file) as k: for line in k: aa, bb, cc = line.split(':') time.sleep(5) os.system("python checkfile.py " + cc...
2018/02/08
[ "https://Stackoverflow.com/questions/48683238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8868451/" ]
Your smoothed data has no zeros left: ``` import numpy as np def smooth(y, box_pts): box = np.ones(box_pts)/box_pts print(box) y_smooth = np.convolve(y, box, mode='same') return y_smooth mydata = [0.0, 0.0, 0.0, 0.0,-0.2, 0.143, 0.0, 0.22, 0.135, 0.44, 0.1, 0.0, 0.0, 0.0, 0.0, 0...
Full numpy solution would be something like this: (not fully optimized) ``` import numpy as np input_data = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.143, 0.0, 0.22, 0.135, 0.44, 0.1, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.33, 0.65, 0.22, 0.0, 0.0, 0....
37,646,174
I need to read an analog signal in raspberry and for this purpose I bought an MCP3002 circuit. i plug it in with the correct connections and i have found sample codes over the internet but it doesn't work. Do I need to have an interface or I can do the job without it? Do you have any ideas what can go wrong? Do you ...
2016/06/05
[ "https://Stackoverflow.com/questions/37646174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3254786/" ]
My `pagesize` was set to `0`. I don't know why this would cause the column headers to disappear, but it did. If someone can explain better than me, I'll gladly accept their answer in leu of mine. I set `pagesize` to `14`, and my column headers appeared.
SQL\*Plus has changed the default behavior in ORACLE 12c. With ``` SQL> set head on ``` you get back to the previous behavior. With ``` SQL> set pagesize *n* ``` every *n* rows the header will be repeated.
10,368,678
I'm attempting to install the DrEdit sample app for python onto GAE. The app runs, but saving or opening a file results in an **HTTP 403 "Access Not Configured Error"**. **client.json** has **client\_id** and **client\_secret** set per the **API Access>Client ID for Drive SDK values**. I have also attempted to use the...
2012/04/29
[ "https://Stackoverflow.com/questions/10368678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363559/" ]
In the services section of the Google API console there are two services relating to drive development, SDK and API. When you create a new Drive SDK entry, Drive API service is not automatically enabled (which doesn't make sense, I don't see when you'd create a drive enabled application without using the drive API). Sw...
And your must also identify in your code the following ``` DriveService.Scope.DriveFile, DriveService.Scope.Drive ``` good luck
25,190,026
Link shows a graphic visualization taken form census website. Link for the same is shared below. I want to create graphic visualization of the same kind in my python program. Link for the graphic visualization: <http://www.census.gov/dataviz/visualizations/stem/stem-html/> Which kind of visualization is this? is it...
2014/08/07
[ "https://Stackoverflow.com/questions/25190026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3888977/" ]
I don't see a graph that is exactly like the one listed, but matplotlib provides a huge number of options. <http://matplotlib.org/gallery.html> It supports Sankey graphs as well: <http://matplotlib.org/api/sankey_api.html?highlight=sankey#module-matplotlib.sankey>
It's essentially a [weighted graph](http://en.wikipedia.org/wiki/Weighted_graph#Weighted_graphs_and_networks). It looks a lot like a [Sankey diagram](http://en.wikipedia.org/wiki/Sankey_diagram). There is specialized software for visualizing graphs, e.g. [graphviz](http://www.graphviz.org/). There are several Python b...
25,190,026
Link shows a graphic visualization taken form census website. Link for the same is shared below. I want to create graphic visualization of the same kind in my python program. Link for the graphic visualization: <http://www.census.gov/dataviz/visualizations/stem/stem-html/> Which kind of visualization is this? is it...
2014/08/07
[ "https://Stackoverflow.com/questions/25190026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3888977/" ]
This tzpe of graph is called a `chord diagram`. a related question on stackoverflow can be found [here](https://stackoverflow.com/questions/19105801/chord-diagram-in-python). Bad news is there is no answer. And, unfortunately, looking around on the internet doesn't bring much.
It's essentially a [weighted graph](http://en.wikipedia.org/wiki/Weighted_graph#Weighted_graphs_and_networks). It looks a lot like a [Sankey diagram](http://en.wikipedia.org/wiki/Sankey_diagram). There is specialized software for visualizing graphs, e.g. [graphviz](http://www.graphviz.org/). There are several Python b...
25,190,026
Link shows a graphic visualization taken form census website. Link for the same is shared below. I want to create graphic visualization of the same kind in my python program. Link for the graphic visualization: <http://www.census.gov/dataviz/visualizations/stem/stem-html/> Which kind of visualization is this? is it...
2014/08/07
[ "https://Stackoverflow.com/questions/25190026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3888977/" ]
As [edouard](https://stackoverflow.com/users/1115377/edouard) mentioned, it is a Chord diagram. The [D3js.org](http://D3js.org) site has two examples - one static (<http://bl.ocks.org/mbostock/4062006> - which was listed in [the other question edouard mentioned](https://stackoverflow.com/questions/19105801/chord-diagra...
It's essentially a [weighted graph](http://en.wikipedia.org/wiki/Weighted_graph#Weighted_graphs_and_networks). It looks a lot like a [Sankey diagram](http://en.wikipedia.org/wiki/Sankey_diagram). There is specialized software for visualizing graphs, e.g. [graphviz](http://www.graphviz.org/). There are several Python b...
25,190,026
Link shows a graphic visualization taken form census website. Link for the same is shared below. I want to create graphic visualization of the same kind in my python program. Link for the graphic visualization: <http://www.census.gov/dataviz/visualizations/stem/stem-html/> Which kind of visualization is this? is it...
2014/08/07
[ "https://Stackoverflow.com/questions/25190026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3888977/" ]
This tzpe of graph is called a `chord diagram`. a related question on stackoverflow can be found [here](https://stackoverflow.com/questions/19105801/chord-diagram-in-python). Bad news is there is no answer. And, unfortunately, looking around on the internet doesn't bring much.
I don't see a graph that is exactly like the one listed, but matplotlib provides a huge number of options. <http://matplotlib.org/gallery.html> It supports Sankey graphs as well: <http://matplotlib.org/api/sankey_api.html?highlight=sankey#module-matplotlib.sankey>
25,190,026
Link shows a graphic visualization taken form census website. Link for the same is shared below. I want to create graphic visualization of the same kind in my python program. Link for the graphic visualization: <http://www.census.gov/dataviz/visualizations/stem/stem-html/> Which kind of visualization is this? is it...
2014/08/07
[ "https://Stackoverflow.com/questions/25190026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3888977/" ]
This tzpe of graph is called a `chord diagram`. a related question on stackoverflow can be found [here](https://stackoverflow.com/questions/19105801/chord-diagram-in-python). Bad news is there is no answer. And, unfortunately, looking around on the internet doesn't bring much.
As [edouard](https://stackoverflow.com/users/1115377/edouard) mentioned, it is a Chord diagram. The [D3js.org](http://D3js.org) site has two examples - one static (<http://bl.ocks.org/mbostock/4062006> - which was listed in [the other question edouard mentioned](https://stackoverflow.com/questions/19105801/chord-diagra...
9,548,139
Disclaimer: I am new to python and django but have programmed in Drupal I am developing a web-based Wizard (like on Microsoft Windows installation screens) with explanatory text followed by Previous and Next buttons (which are big green left and right arrows). So far, so good. However, my current Wizard page (in proj...
2012/03/03
[ "https://Stackoverflow.com/questions/9548139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1231693/" ]
`<input type="submit" value="Next"/>` This gives you a button with the value 'Next' which acts as a submit button. If this is not what you've wanted, rephrase your question and/or give an example of what action should take place after pressing next.
You might want to use the Django Form wizard, in this case: <https://docs.djangoproject.com/en/dev/ref/contrib/formtools/form-wizard/>
15,187,184
I am trying to extend the fft code that works fine for 1D arrays in python for images. Actually i know the problem is in logic in extension. I don't know much about FFTs and i have to submit assignments for Image Processing. I will be thankful for any hints or solutions Here is the code, Actually, I'm trying to create...
2013/03/03
[ "https://Stackoverflow.com/questions/15187184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1442667/" ]
Your code is a little hard to follow, but it looks like you are taking the FFT along the same direction both times. Look up the integral from of the FT, you will see that the `x` and `y` integrations are independent. That is (sorry, this notation is awful, `'` indicates a function in Fourier space) ``` FT(f(x, y), x) ...
I agree with isedev that you should use numpy. It already has a great fft package that can do transforms in n-dimensions. <http://docs.scipy.org/doc/numpy/reference/routines.fft.html> <http://docs.scipy.org/doc/numpy-1.4.x/reference/generated/numpy.fft.fft.html>
7,233,991
I have created a `FileManager` for my personal files. The launcher for this manager is launched by following script. ``` #!/usr/bin/python from ui.MovieManager import MovieManager MovieManager().showView() ``` Movie manager and other modules are situated in the `ui` and `core` packages, but when executing the file...
2011/08/29
[ "https://Stackoverflow.com/questions/7233991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/275097/" ]
It's not python which generates the error. Check this out: ``` blubb@nemo:~$ from ui.MovieManager import MovieManager from: can't read /var/mail/ui.MovieManager ``` Mind you, this is the console, which is a logical consequence of you calling the script with `sh Launcher.py`. Instead, use `./Launcher.py`. For this t...
Have you tried going to the folder where Launcher.py is and running ``` ./Launcher.py ```
39,075,309
what I met is a code question below: <https://www.patest.cn/contests/pat-a-practise/1001> > > Calculate a + b and output the sum in standard format -- that is, the digits must be separated into groups of three by commas (unless there are less than four digits). > > > Input > > > Each input file contains one t...
2016/08/22
[ "https://Stackoverflow.com/questions/39075309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6419115/" ]
I can give you a simple that doesn't match answer, when you enter -1000000, 9 as a, b in your input, you'll get -,999,991.which is wrong. To get the right answer, you really should get to know format in python. To solve this question, you can just write your code like this. `if __name__ == "__main__": aline = input...
Notice the behavior of your code when you input -1000 and 1. You need to handle the minus sign, because it is not a digit.
21,346,725
I am using python with Pyqt4 for building app on Ubuntu and seems I have trouble with menubar that doesn't show up, thanks for any help. here is the code: ``` import sys from PyQt4 import QtGui class Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() ...
2014/01/25
[ "https://Stackoverflow.com/questions/21346725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1233240/" ]
In ubuntu menubar is outside the application . You can find it in global menu
There is nothing wrong in your code. First you should run your code and maximize your GUI(Graphical User Interface) and you can see that your code run fine and you can understand what actually happen in Ubuntu. Actually Ubuntu always show the menu bar (also your GUI) at the top of the screen no matter what the size of ...
21,346,725
I am using python with Pyqt4 for building app on Ubuntu and seems I have trouble with menubar that doesn't show up, thanks for any help. here is the code: ``` import sys from PyQt4 import QtGui class Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() ...
2014/01/25
[ "https://Stackoverflow.com/questions/21346725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1233240/" ]
In ubuntu menubar is outside the application . You can find it in global menu
Actually there is your menu. You can just full screen your application and it would be on the top of the window if you hover your mouse on that. This is Ubuntu mode of visualisation, exactly like your browser that if you hover your mouse over the menu bar, you can see it!
21,346,725
I am using python with Pyqt4 for building app on Ubuntu and seems I have trouble with menubar that doesn't show up, thanks for any help. here is the code: ``` import sys from PyQt4 import QtGui class Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() ...
2014/01/25
[ "https://Stackoverflow.com/questions/21346725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1233240/" ]
In ubuntu menubar is outside the application . You can find it in global menu
Try This: ``` menuBar = self.menuBar() menuBar.setNativeMenuBar(False) ```
21,346,725
I am using python with Pyqt4 for building app on Ubuntu and seems I have trouble with menubar that doesn't show up, thanks for any help. here is the code: ``` import sys from PyQt4 import QtGui class Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() ...
2014/01/25
[ "https://Stackoverflow.com/questions/21346725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1233240/" ]
There is nothing wrong in your code. First you should run your code and maximize your GUI(Graphical User Interface) and you can see that your code run fine and you can understand what actually happen in Ubuntu. Actually Ubuntu always show the menu bar (also your GUI) at the top of the screen no matter what the size of ...
Actually there is your menu. You can just full screen your application and it would be on the top of the window if you hover your mouse on that. This is Ubuntu mode of visualisation, exactly like your browser that if you hover your mouse over the menu bar, you can see it!
21,346,725
I am using python with Pyqt4 for building app on Ubuntu and seems I have trouble with menubar that doesn't show up, thanks for any help. here is the code: ``` import sys from PyQt4 import QtGui class Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() ...
2014/01/25
[ "https://Stackoverflow.com/questions/21346725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1233240/" ]
Try This: ``` menuBar = self.menuBar() menuBar.setNativeMenuBar(False) ```
There is nothing wrong in your code. First you should run your code and maximize your GUI(Graphical User Interface) and you can see that your code run fine and you can understand what actually happen in Ubuntu. Actually Ubuntu always show the menu bar (also your GUI) at the top of the screen no matter what the size of ...
21,346,725
I am using python with Pyqt4 for building app on Ubuntu and seems I have trouble with menubar that doesn't show up, thanks for any help. here is the code: ``` import sys from PyQt4 import QtGui class Example(QtGui.QMainWindow): def __init__(self): super(Example, self).__init__() ...
2014/01/25
[ "https://Stackoverflow.com/questions/21346725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1233240/" ]
Try This: ``` menuBar = self.menuBar() menuBar.setNativeMenuBar(False) ```
Actually there is your menu. You can just full screen your application and it would be on the top of the window if you hover your mouse on that. This is Ubuntu mode of visualisation, exactly like your browser that if you hover your mouse over the menu bar, you can see it!
13,903,467
I am using Win 8, Eclipse and Pydev. I installed Pydev and it can run simple python script. Unfortunately I want to use math module and it gets error sign next to math command. ![enter image description here](https://i.stack.imgur.com/iEN1s.png) Undefined variable. I would be very thankful if you can help me to get...
2012/12/16
[ "https://Stackoverflow.com/questions/13903467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619324/" ]
'math' should be marked as a 'forced builtin' in window > preferences > pydev > interpreter - python (if it's not, that's your problem). If it's properly configured, it probably means that PyDev wasn't able to spawn a shell to inspect the math module, in which case it usually means that there's some firewall blocking ...
I cannot see the screenshot very well, but i see you are doing on the first line: ``` from math import * ``` and then ``` print math.whatever ``` Clearly `math` is an undefined variable here, as you should have used `import math` instead of `from math import *`
13,903,467
I am using Win 8, Eclipse and Pydev. I installed Pydev and it can run simple python script. Unfortunately I want to use math module and it gets error sign next to math command. ![enter image description here](https://i.stack.imgur.com/iEN1s.png) Undefined variable. I would be very thankful if you can help me to get...
2012/12/16
[ "https://Stackoverflow.com/questions/13903467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619324/" ]
'math' should be marked as a 'forced builtin' in window > preferences > pydev > interpreter - python (if it's not, that's your problem). If it's properly configured, it probably means that PyDev wasn't able to spawn a shell to inspect the math module, in which case it usually means that there's some firewall blocking ...
When you are doing `from math import *` you are essentially collapsing the math `namespace` onto the current `namespace` (`global namespace`). This means that you do not need to prepend the name `math` in front of attributes that were imported this way. So you have two possible solutions: 1. Either `import math`, whi...
13,903,467
I am using Win 8, Eclipse and Pydev. I installed Pydev and it can run simple python script. Unfortunately I want to use math module and it gets error sign next to math command. ![enter image description here](https://i.stack.imgur.com/iEN1s.png) Undefined variable. I would be very thankful if you can help me to get...
2012/12/16
[ "https://Stackoverflow.com/questions/13903467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619324/" ]
'math' should be marked as a 'forced builtin' in window > preferences > pydev > interpreter - python (if it's not, that's your problem). If it's properly configured, it probably means that PyDev wasn't able to spawn a shell to inspect the math module, in which case it usually means that there's some firewall blocking ...
In the PyDev Interpreter configuration pane you need to make sure that PyDev knows where to find the python packages. Go to Preferences -> PyDev -> Interpreter - Python (or whatever interpreter is good for you). After selecting the interpreter, click on the Apply button. This may resolve your issue if the ceil functio...
43,407,522
I am used to connect to a local server by using putty. But now I need to create a file by using a script python, this file has a huge size, so I must put it in local server; by using puty, I must entre my host adresse, password, name and the port. How do I do that? This is my script: ``` import numpy as np import...
2017/04/14
[ "https://Stackoverflow.com/questions/43407522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6690199/" ]
In the end, I figured out myself how to achieve Laravel Echo working with Pusher but without Vue.js 1. Follow all the instructions found [here](https://laravel.com/docs/5.4/broadcasting). 2. Assuming you have Pusher installed and configured and Laravel Echo installed via npm, go to `your-project-folder/node_modules/la...
First create event for broadcasting data as per the laravel document. And check console debug that your data being broadcasted or not. If your data is broadcasting than use javascript to listening data as given in pusher document. Here you can check example : <https://pusher.com/docs/javascript_quick_start>
43,407,522
I am used to connect to a local server by using putty. But now I need to create a file by using a script python, this file has a huge size, so I must put it in local server; by using puty, I must entre my host adresse, password, name and the port. How do I do that? This is my script: ``` import numpy as np import...
2017/04/14
[ "https://Stackoverflow.com/questions/43407522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6690199/" ]
I am using laravel websockets but I think it should be the same with the original Pusher. So : 1. Install laravel-echo and pusher with npm 2. Go to ***your-project-folder/node\_modules/laravel-echo/dist*** and copy ***echo.js*** to ***your-project-folder/public/js*** 3. Go to ***your-project-folder/node\_modules/pushe...
First create event for broadcasting data as per the laravel document. And check console debug that your data being broadcasted or not. If your data is broadcasting than use javascript to listening data as given in pusher document. Here you can check example : <https://pusher.com/docs/javascript_quick_start>
43,407,522
I am used to connect to a local server by using putty. But now I need to create a file by using a script python, this file has a huge size, so I must put it in local server; by using puty, I must entre my host adresse, password, name and the port. How do I do that? This is my script: ``` import numpy as np import...
2017/04/14
[ "https://Stackoverflow.com/questions/43407522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6690199/" ]
In the end, I figured out myself how to achieve Laravel Echo working with Pusher but without Vue.js 1. Follow all the instructions found [here](https://laravel.com/docs/5.4/broadcasting). 2. Assuming you have Pusher installed and configured and Laravel Echo installed via npm, go to `your-project-folder/node_modules/la...
I am using laravel websockets but I think it should be the same with the original Pusher. So : 1. Install laravel-echo and pusher with npm 2. Go to ***your-project-folder/node\_modules/laravel-echo/dist*** and copy ***echo.js*** to ***your-project-folder/public/js*** 3. Go to ***your-project-folder/node\_modules/pushe...
69,658,798
I have the following python code to convert csv file into json file. ``` def make_json_from_csv(csv_file_path, json_file_path, unique_column_name): import csv import json # create a dictionary data = {} # Open a csv reader called DictReader with open(csv_file_path, encoding='utf-8') as csvf: ...
2021/10/21
[ "https://Stackoverflow.com/questions/69658798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848207/" ]
In Python 3.6+ the dict keep the insertion order, so to fetch the last rows of a dictionary, just do: ``` from itertools import islice x = 5 d = {} for i, v in enumerate("abcdedfghi"): d[i] = v d = dict(islice(d.items(), len(d) - x, len(d))) print(d) ``` **Output** ``` {5: 'd', 6: 'f', 7: 'g', 8: 'h', 9: 'i'}...
I would like to answer my own question by building on Dani Mesejo's answer. The credit goes entirely to him. ``` def make_json(csv_file_path, json_file_path, unique_column_name, no_of_rows_to_extract): import csv import json from itertools import islice # create a dictionary data = {}...
23,322,025
I am currently using python `pandas` and want to know if there is a way to output the data from pandas into julia `Dataframes` and vice versa. (I think you can call python from Julia with `Pycall` but I am not sure if it works with dataframes) Is there a way to call Julia from python and have it take in `panda`s datafr...
2014/04/27
[ "https://Stackoverflow.com/questions/23322025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3159981/" ]
So there is a library developed for this `PyJulia` is a library used to interface with Julia using Python 2 and 3 <https://github.com/JuliaLang/pyjulia> It is experimental but somewhat works Secondly Julia also has a front end for `pandas` which is `pandas.jl` <https://github.com/malmaud/Pandas.jl> It looks to be...
I'm a novice at this sort of thing but have definitely been using both as of late. Truth be told, they seem very quite comparable but there is far more documentation, Stack Overflow questions, etc pertaining to Pandas so I would give it a slight edge. Do not let that fact discourage you however because Julia has some a...
40,452,603
I have written a simple Python3 program like below: ``` import sys input = sys.stdin.read() tokens = input.split() print (tokens) a = int(tokens[0]) b = int(tokens[1]) if ((a + b)> 18): print ("Input numbers should be between 0 and 9") else: print(a + b) ``` but while running this like below: ``` C:\Python_...
2016/11/06
[ "https://Stackoverflow.com/questions/40452603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7123148/" ]
`sys.stdin.read()` will read until an EOF (end of file) is encountered. That's why "pressing enter" doesn't seem to do anything. You can send an EOF on Windows by typing `Ctrl`+`Z`, or on \*nix systems with `Ctrl`+`D`. (Note that you probably still need to hit `Enter` before hitting `Ctrl`+`Z`. I don't think the termi...
This happens because `sys.stdin.read` attempts to read *all the data* that the standard input can provide, including new lines, spaces, tabs, *whatever*. It will stop reading only if the interpreter's interrupted or it hits an EndOfFile (Ctrl+D on UNIX-like systems and Ctrl+Z on Windows). The standard function that as...
40,452,603
I have written a simple Python3 program like below: ``` import sys input = sys.stdin.read() tokens = input.split() print (tokens) a = int(tokens[0]) b = int(tokens[1]) if ((a + b)> 18): print ("Input numbers should be between 0 and 9") else: print(a + b) ``` but while running this like below: ``` C:\Python_...
2016/11/06
[ "https://Stackoverflow.com/questions/40452603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7123148/" ]
`sys.stdin.read()` will read until an EOF (end of file) is encountered. That's why "pressing enter" doesn't seem to do anything. You can send an EOF on Windows by typing `Ctrl`+`Z`, or on \*nix systems with `Ctrl`+`D`. (Note that you probably still need to hit `Enter` before hitting `Ctrl`+`Z`. I don't think the termi...
you can read user's input using **input()** function. Example Code ------------ ``` user_input = input("Please input a number !") # Rest of the code ```
69,425,666
I'm currently working on an Applescript math library, which mimics the python `math` module. The python `math` module has some constants, such as [Euler's number](https://en.wikipedia.org/wiki/E_%28mathematical_constant%29) and others. Currently, you can do something like this: ```applescript set math to script "Math"...
2021/10/03
[ "https://Stackoverflow.com/questions/69425666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15209993/" ]
There is no way to explicitly define a constant in AppleScript. There are three approaches that might suffice, depending on what you're trying to achieve. --- If you're using a Scripting Definition (sdef) in your library, you can add an enumeration to define terms you want to reserve, then handle them by cases in cod...
Every handler name with parameters is constant in the AppleScript. You can use this fact. Here, you can't change the name of the handler, so you can consider it like your constant pi identifier. It is true constant because you can't set it, but you can get it whatever you want: ``` on constantPi() 3.14159265359 en...
47,724,709
I am trying to insert into a postgresql database in python 3.6 and currently am trying to execute this line ``` cur.execute("INSERT INTO "+table_name+"(price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)",(exchange_rate, buy_rate, sell_rate, date)) ``` but every time it tries to run the table name has ' ' ...
2017/12/09
[ "https://Stackoverflow.com/questions/47724709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1771791/" ]
Use it with triple quotes. Also you may pass table\_name as a element of second parameter, too. ``` cur.execute("""INSERT INTO %s (price, buy, sell, timestamp) VALUES (%s, %s, %s, %s)""",(table_name, exchange_rate, buy_rate, sell_rate, date)) ``` More detailed approach; * Triple qoutes give developers a change to ...
Use the new string formatting to have a clean representation. `%s` is explicitly converting to a string, you don't want that. Format chooses the most fitting type for you. ``` table_name = "myTable" exchange_rate = 1 buy_rate = 2 sell_rate = 3 date = 123 x = "INSERT INTO {0} (price, buy, sell, timestamp) VALUES ({1}, ...
19,612,822
I know that there are different ways to do this, but I just want to know why my regex isn't working. This isn't actually something that I need to do, I just wanted to see if I could do this with a regex, and I have no idea why my code isn't working. Given a string S, I want to find all non-overlapping substrings that ...
2013/10/26
[ "https://Stackoverflow.com/questions/19612822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2073001/" ]
Assuming what you actually want is for the subsequence Q to contain no `a`s between the first `a` and the first `b` and no `a`s or `b`s between the first `b` and the first `c` after the first `b`, the correct regex to use is: ``` r'a[^ab]*b[^abc]*c' ``` The regex that you're currently using will do everything that i...
It could help if you look at the inverse class. In all cases `abc` is the trivial solution. And, in this case non-greedy probably doesn't apply because there are fixed sets of characters used in the example inverse classes. ``` # Type 1 : # ( b or c can be between A,B ) # ( a or b can be between B,C ) ...
64,146,892
I'm trying to create a word counter in python that prints the longest word, then sorts all words over 5 letters by frequency. The longest word works, and the counter works, I just can't figure out how to make it check only over 5 letters. If I run it, it works, but the words under 5 letters are still there. Here's the...
2020/09/30
[ "https://Stackoverflow.com/questions/64146892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14370546/" ]
Okay, so I took a different approach and changed my code, the following code is now functional although I have no idea what was causing the original issue still. ``` public CharacterController controller; private float speed; public float walkSpeed = 5f; public float runSpeed = 10f; public float turnSpeed = 90f; pub...
This happens because the character controller has a gravity so when you enable it, it uses gravity to the player and drag your player down. To fix this, you will need to write in the script that the player's position is upwards. ``` public float walkSpeed = 3f; public float runSpeed = 6f; public float gravity = -9.81f...
64,146,892
I'm trying to create a word counter in python that prints the longest word, then sorts all words over 5 letters by frequency. The longest word works, and the counter works, I just can't figure out how to make it check only over 5 letters. If I run it, it works, but the words under 5 letters are still there. Here's the...
2020/09/30
[ "https://Stackoverflow.com/questions/64146892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14370546/" ]
I just discovered the same issue, "normally" the character controller does not apply gravity.... all the information and tutorials will tell you to roll your own which I have. But if you apply root motion and bake the Y into the animation it does apply Physics.Gravity... I can only guess that it is applying SimpleMove...
This happens because the character controller has a gravity so when you enable it, it uses gravity to the player and drag your player down. To fix this, you will need to write in the script that the player's position is upwards. ``` public float walkSpeed = 3f; public float runSpeed = 6f; public float gravity = -9.81f...
64,146,892
I'm trying to create a word counter in python that prints the longest word, then sorts all words over 5 letters by frequency. The longest word works, and the counter works, I just can't figure out how to make it check only over 5 letters. If I run it, it works, but the words under 5 letters are still there. Here's the...
2020/09/30
[ "https://Stackoverflow.com/questions/64146892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14370546/" ]
I just discovered the same issue, "normally" the character controller does not apply gravity.... all the information and tutorials will tell you to roll your own which I have. But if you apply root motion and bake the Y into the animation it does apply Physics.Gravity... I can only guess that it is applying SimpleMove...
Okay, so I took a different approach and changed my code, the following code is now functional although I have no idea what was causing the original issue still. ``` public CharacterController controller; private float speed; public float walkSpeed = 5f; public float runSpeed = 10f; public float turnSpeed = 90f; pub...
32,162,757
I am using mongoDB with python . I want user to enter a document in the JSON format so that i can insert that into some collection in my db .How can this be done ?
2015/08/23
[ "https://Stackoverflow.com/questions/32162757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4784437/" ]
Just use conditional aggregation: ``` select Id, (sum(case when Value > 3.0 then 1 else 0 end) - sum(case when Value < 3.0 then 1 else 0 end) -- or maybe 2.9 ) as TotalVotes from [Ratings] group by Id order by Id desc; ``` Alternatively, you could write: ``` select id, sum(case when Value > 3...
SQL Server allows you to specify condition in aggregate functions.In your case, you need to use SUM with conditions.. So, this is how your final query looks like ``` select Id, Value,SUM(CASE WHEN Value>3.0 THEN 1 ELSE -1 END) AS VoteCount from [Ratings] group by Id order by Id desc ```
50,616,254
I need to do the following operation in python: I have a list of tuples ``` data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)] ``` I have a list of fields: ``` fields = ["name", "age", "vol", "status", "limit"] ``` Each tuple of the data is for each of the fields in order. I have a dic...
2018/05/31
[ "https://Stackoverflow.com/questions/50616254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434649/" ]
I don't remember having this problem but in at least one case I did something that will work around the issue. I put an index.js in the root folder that runs the actual dependency in dist. Then the bin that npm looks for is a file that's present, and it shouldn't freak out. It won't work until tsc is run, of course....
It looks like `preinstall` script is what you need Add in your `package.json` file as ``` { "scripts": { "preinstall" : "tsc ..." // < build stuff } } ``` Reference <https://docs.npmjs.com/misc/scripts>
50,616,254
I need to do the following operation in python: I have a list of tuples ``` data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)] ``` I have a list of fields: ``` fields = ["name", "age", "vol", "status", "limit"] ``` Each tuple of the data is for each of the fields in order. I have a dic...
2018/05/31
[ "https://Stackoverflow.com/questions/50616254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434649/" ]
I don't remember having this problem but in at least one case I did something that will work around the issue. I put an index.js in the root folder that runs the actual dependency in dist. Then the bin that npm looks for is a file that's present, and it shouldn't freak out. It won't work until tsc is run, of course....
I would check-in a file `./lib/cli` the file contents are ``` #!/usr/bin/env node require('../dist/cli.js') ``` and just run npm normally followed by tsc.
50,616,254
I need to do the following operation in python: I have a list of tuples ``` data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)] ``` I have a list of fields: ``` fields = ["name", "age", "vol", "status", "limit"] ``` Each tuple of the data is for each of the fields in order. I have a dic...
2018/05/31
[ "https://Stackoverflow.com/questions/50616254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434649/" ]
I don't remember having this problem but in at least one case I did something that will work around the issue. I put an index.js in the root folder that runs the actual dependency in dist. Then the bin that npm looks for is a file that's present, and it shouldn't freak out. It won't work until tsc is run, of course....
Absolutely not your answer, but I usually just prefer to commit the javascript. Downside: Tons of additional git history/bloat. My points: * In the end you are producing a javascript project. So one should test the javascript runtime, and if that project is supposed to also be consumed from typescript, test the gene...
50,616,254
I need to do the following operation in python: I have a list of tuples ``` data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)] ``` I have a list of fields: ``` fields = ["name", "age", "vol", "status", "limit"] ``` Each tuple of the data is for each of the fields in order. I have a dic...
2018/05/31
[ "https://Stackoverflow.com/questions/50616254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434649/" ]
I don't remember having this problem but in at least one case I did something that will work around the issue. I put an index.js in the root folder that runs the actual dependency in dist. Then the bin that npm looks for is a file that's present, and it shouldn't freak out. It won't work until tsc is run, of course....
The answer from @wkrueger is close. The goal here is to just allows a cheesy step to work without actually making it do anything useful. That cheesy step is making the file references by `bin` executable, during the install step, which for a local module only makes sense for non-transpiled JavaScript, as for transpile...
50,616,254
I need to do the following operation in python: I have a list of tuples ``` data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)] ``` I have a list of fields: ``` fields = ["name", "age", "vol", "status", "limit"] ``` Each tuple of the data is for each of the fields in order. I have a dic...
2018/05/31
[ "https://Stackoverflow.com/questions/50616254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434649/" ]
It looks like `preinstall` script is what you need Add in your `package.json` file as ``` { "scripts": { "preinstall" : "tsc ..." // < build stuff } } ``` Reference <https://docs.npmjs.com/misc/scripts>
Absolutely not your answer, but I usually just prefer to commit the javascript. Downside: Tons of additional git history/bloat. My points: * In the end you are producing a javascript project. So one should test the javascript runtime, and if that project is supposed to also be consumed from typescript, test the gene...
50,616,254
I need to do the following operation in python: I have a list of tuples ``` data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)] ``` I have a list of fields: ``` fields = ["name", "age", "vol", "status", "limit"] ``` Each tuple of the data is for each of the fields in order. I have a dic...
2018/05/31
[ "https://Stackoverflow.com/questions/50616254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434649/" ]
It looks like `preinstall` script is what you need Add in your `package.json` file as ``` { "scripts": { "preinstall" : "tsc ..." // < build stuff } } ``` Reference <https://docs.npmjs.com/misc/scripts>
The answer from @wkrueger is close. The goal here is to just allows a cheesy step to work without actually making it do anything useful. That cheesy step is making the file references by `bin` executable, during the install step, which for a local module only makes sense for non-transpiled JavaScript, as for transpile...
50,616,254
I need to do the following operation in python: I have a list of tuples ``` data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)] ``` I have a list of fields: ``` fields = ["name", "age", "vol", "status", "limit"] ``` Each tuple of the data is for each of the fields in order. I have a dic...
2018/05/31
[ "https://Stackoverflow.com/questions/50616254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434649/" ]
I would check-in a file `./lib/cli` the file contents are ``` #!/usr/bin/env node require('../dist/cli.js') ``` and just run npm normally followed by tsc.
Absolutely not your answer, but I usually just prefer to commit the javascript. Downside: Tons of additional git history/bloat. My points: * In the end you are producing a javascript project. So one should test the javascript runtime, and if that project is supposed to also be consumed from typescript, test the gene...
50,616,254
I need to do the following operation in python: I have a list of tuples ``` data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)] ``` I have a list of fields: ``` fields = ["name", "age", "vol", "status", "limit"] ``` Each tuple of the data is for each of the fields in order. I have a dic...
2018/05/31
[ "https://Stackoverflow.com/questions/50616254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434649/" ]
I would check-in a file `./lib/cli` the file contents are ``` #!/usr/bin/env node require('../dist/cli.js') ``` and just run npm normally followed by tsc.
The answer from @wkrueger is close. The goal here is to just allows a cheesy step to work without actually making it do anything useful. That cheesy step is making the file references by `bin` executable, during the install step, which for a local module only makes sense for non-transpiled JavaScript, as for transpile...
50,616,254
I need to do the following operation in python: I have a list of tuples ``` data = [("John", 14, 12132.213, "Y", 34), ("Andrew", 23, 2121.21, "N", 66)] ``` I have a list of fields: ``` fields = ["name", "age", "vol", "status", "limit"] ``` Each tuple of the data is for each of the fields in order. I have a dic...
2018/05/31
[ "https://Stackoverflow.com/questions/50616254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3434649/" ]
The answer from @wkrueger is close. The goal here is to just allows a cheesy step to work without actually making it do anything useful. That cheesy step is making the file references by `bin` executable, during the install step, which for a local module only makes sense for non-transpiled JavaScript, as for transpile...
Absolutely not your answer, but I usually just prefer to commit the javascript. Downside: Tons of additional git history/bloat. My points: * In the end you are producing a javascript project. So one should test the javascript runtime, and if that project is supposed to also be consumed from typescript, test the gene...
56,501,297
I'm trying to setup Visual Studio Code for python and everything is good except Kivy. I have simple code ``` import kivy from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.widget...
2019/06/07
[ "https://Stackoverflow.com/questions/56501297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7869295/" ]
Maybe it should fix it! ``` MyGrid: <MyGrid>: GridLayout: cols:1 size: root.width, root.height GridLayout: cols:2 Label: text: "Name: " TextInput: multinline:False Label: ...
remove the indent from GridLayout:
56,501,297
I'm trying to setup Visual Studio Code for python and everything is good except Kivy. I have simple code ``` import kivy from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.widget...
2019/06/07
[ "https://Stackoverflow.com/questions/56501297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7869295/" ]
Maybe it should fix it! ``` MyGrid: <MyGrid>: GridLayout: cols:1 size: root.width, root.height GridLayout: cols:2 Label: text: "Name: " TextInput: multinline:False Label: ...
Solution from the OPs comment: I haven't saved the file after editing :)
56,501,297
I'm trying to setup Visual Studio Code for python and everything is good except Kivy. I have simple code ``` import kivy from kivy.app import App from kivy.uix.label import Label from kivy.uix.gridlayout import GridLayout from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.widget...
2019/06/07
[ "https://Stackoverflow.com/questions/56501297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7869295/" ]
Solution from the OPs comment: I haven't saved the file after editing :)
remove the indent from GridLayout:
46,999,929
I want to create a Telegram Messenger bot with framework *python-telegram-bot*! Now, the bot must send a message with a specific font. This means the bot sends a message with a different and beautiful font - a font different from the Telegram Messenger font. How can I do it?
2017/10/29
[ "https://Stackoverflow.com/questions/46999929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8444979/" ]
No one (even you the official) can send messages in a different font/color, but you can make a suggestion to [@Telegram](https://twitter.com/telegram). They will consider adding this as a feature. There have limited [formatting options](https://core.telegram.org/bots/api#formatting-options) in the message text, and yo...
The only color that you can use is red or set the background color to gray. ``` str = "`Hello`" #this will turn the text red on Telegram. str = "```Hello```" #this will turn the background color gray of the text on Telegram ``` Then at the **sendMessage** function, you need to add the parameter **parse\_mode** a...
46,999,929
I want to create a Telegram Messenger bot with framework *python-telegram-bot*! Now, the bot must send a message with a specific font. This means the bot sends a message with a different and beautiful font - a font different from the Telegram Messenger font. How can I do it?
2017/10/29
[ "https://Stackoverflow.com/questions/46999929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8444979/" ]
No one (even you the official) can send messages in a different font/color, but you can make a suggestion to [@Telegram](https://twitter.com/telegram). They will consider adding this as a feature. There have limited [formatting options](https://core.telegram.org/bots/api#formatting-options) in the message text, and yo...
These HTML tags are currently supported by Telegram: <https://core.telegram.org/bots/api#formatting-options> ``` <b>bold</b>, <strong>bold</strong> <i>italic</i>, <em>italic</em> <u>underline</u>, <ins>underline</ins> <s>strikethrough</s>, <strike>strikethrough</strike>, <del>strikethrough</del> <b>bold <i>italic bol...
46,999,929
I want to create a Telegram Messenger bot with framework *python-telegram-bot*! Now, the bot must send a message with a specific font. This means the bot sends a message with a different and beautiful font - a font different from the Telegram Messenger font. How can I do it?
2017/10/29
[ "https://Stackoverflow.com/questions/46999929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8444979/" ]
These HTML tags are currently supported by Telegram: <https://core.telegram.org/bots/api#formatting-options> ``` <b>bold</b>, <strong>bold</strong> <i>italic</i>, <em>italic</em> <u>underline</u>, <ins>underline</ins> <s>strikethrough</s>, <strike>strikethrough</strike>, <del>strikethrough</del> <b>bold <i>italic bol...
The only color that you can use is red or set the background color to gray. ``` str = "`Hello`" #this will turn the text red on Telegram. str = "```Hello```" #this will turn the background color gray of the text on Telegram ``` Then at the **sendMessage** function, you need to add the parameter **parse\_mode** a...
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
I am assuming that votes for 0 count as votes. So `sum` is not a reasonable option. Try a Counter: ``` >>> from collections import Counter >>> x = Counter([-1,-1,-1, 1,1,1,1,0,0,0,0,0,0,0,0]) >>> x Counter({0: 8, 1: 4, -1: 3}) >>> x.most_common(1) [(0, 8)] >>> x.most_common(1)[0][0] 0 ``` So you could write code li...
You can [count occurences](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python) of 0 and test if they are majority. ``` >>> x = [1, 1, 0, 0, 0] >>> if sum(x) == 0 or x.count(0) >= len(x) / 2.0: ... majority = 0 ... else: ... majority = -1 if (sum(x) < 0) else 1...
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
I believe this works for all provided test cases. Please let me know if I did something wrong. ``` from collections import Counter def fn(x): counts = Counter(x) num_n1 = counts.get(-1, 0) num_p1 = counts.get(1, 0) num_z = counts.get(0, 0) if num_n1 > num_p1: return -1 if num_n1 > num_z el...
``` from collections import Counter def find_majority_vote(votes): counter = Counter(votes) most_common = counter.most_common(2) if len(most_common)==2: return 0 if most_common[0][1] == most_common[1][1] else most_common[0][0] else: return most_common[0][0] ```
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
You can [count occurences](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item-in-python) of 0 and test if they are majority. ``` >>> x = [1, 1, 0, 0, 0] >>> if sum(x) == 0 or x.count(0) >= len(x) / 2.0: ... majority = 0 ... else: ... majority = -1 if (sum(x) < 0) else 1...
``` import numpy as np def fn(vote): n=vote[np.where(vote<0)].size p=vote[np.where(vote>0)].size ret=np.sign(p-n) z=vote.size-p-n if z>=max(p,n): ret=0 return ret # some test cases print fn(np.array([-1,-1, 1,1,1,1,0,0,0,0,0,0,0,0])) print fn(np.array([-1, -1, -1, 1,1,1,0,0])) print fn(np.arra...
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
I believe this works for all provided test cases. Please let me know if I did something wrong. ``` from collections import Counter def fn(x): counts = Counter(x) num_n1 = counts.get(-1, 0) num_p1 = counts.get(1, 0) num_z = counts.get(0, 0) if num_n1 > num_p1: return -1 if num_n1 > num_z el...
You don't need anything but built-in list operators and stuff, no need to import anything. ``` votes = [ -1,-1,0,1,0,1,-1,-1] # note that we don't care about ordering counts = [ votes.count(-1),votes.count(0),votes.count(1)] if (counts[0]>0 and counts.count(counts[0]) > 1) or (counts[1]>0 and counts.count...
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
``` # These are your actual votes votes = [-1, -1, -1, -1, 0] # These are the options on the ballot ballot = (-1, 0, 1) # This is to initialize your counters counters = {x: 0 for x in ballot} # Count the number of votes for vote in votes: counters[vote] += 1 results = counters.values().sort() if len(set(values...
An obvious approach is making a counter and updating it according to the data list `x`. Then you can get the list of numbers (from -1, 0, 1) that are the most frequent. If there is 1 such number, this is what you want, otherwise choose 0 (as you requested). ``` counter = {-1: 0, 0: 0, 1: 0} for number in x: counte...
33,511,259
**How to find the majority votes for a list that can contain -1s, 1s and 0s?** For example, given a list of: ``` x = [-1, -1, -1, -1, 0] ``` The majority is -1 , so the output should return `-1` Another example, given a list of: ``` x = [1, 1, 1, 0, 0, -1] ``` The majority vote would be `1` And when we have a...
2015/11/03
[ "https://Stackoverflow.com/questions/33511259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/610569/" ]
``` # These are your actual votes votes = [-1, -1, -1, -1, 0] # These are the options on the ballot ballot = (-1, 0, 1) # This is to initialize your counters counters = {x: 0 for x in ballot} # Count the number of votes for vote in votes: counters[vote] += 1 results = counters.values().sort() if len(set(values...
This works with any number of candidates. If there is a tie between two candidates it returns zero else it returns candidate with most votes. ``` from collections import Counter x = [-1, -1, 0, 0, 0, 0] counts = list((Counter(x).most_common())) ## Array in descending order by votes if len(counts)>1 and (counts[0][1] =...