qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
sequencelengths
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 order for the argument to be optional so to be able to call `f()` with no arguments. Now whenever in time I execute `f()` I get the same datetime A (which is wrong according to what I expect), but whenever in time I execute `f(datetime.datetime.now())` I get different datetimes (which is correct as expected). For example ``` >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f(datetime.datetime.now()) time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=37, tm_sec=1, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) ``` So why the fourth call returns me back to min 36 and sec 2 while the call was made before that? Why the first two calls give the same exact time even if I let plenty of time between them?
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_mon=6, tm_mday=20, tm_hour=15, tm_min=39, tm_sec=28, tm_wday=5, tm_yday=171, tm_isdst=-1) ``` **edit:** function is always evaluated in parameter. Solution: decouple it's assignment from the parameter ``` def f(t="now"): if t=="now": return datetime.datetime.now().timetuple() else: return t.timetuple() def main(ff=f): print ff print ff() import time main() time.sleep(3) main() ```
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 order for the argument to be optional so to be able to call `f()` with no arguments. Now whenever in time I execute `f()` I get the same datetime A (which is wrong according to what I expect), but whenever in time I execute `f(datetime.datetime.now())` I get different datetimes (which is correct as expected). For example ``` >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f(datetime.datetime.now()) time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=37, tm_sec=1, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) ``` So why the fourth call returns me back to min 36 and sec 2 while the call was made before that? Why the first two calls give the same exact time even if I let plenty of time between them?
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, 21, 0, 6, 10, 698000) >>> f() datetime.datetime(2015, 6, 21, 0, 6, 12, 269000) ``` Or you can pass in another function, here a test one, and override `t`. Calling f() calls the function passed in: ``` >>> def test(): ... return "hi" ... >>> f(t=test) 'hi' ```
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 order for the argument to be optional so to be able to call `f()` with no arguments. Now whenever in time I execute `f()` I get the same datetime A (which is wrong according to what I expect), but whenever in time I execute `f(datetime.datetime.now())` I get different datetimes (which is correct as expected). For example ``` >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f(datetime.datetime.now()) time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=37, tm_sec=1, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) ``` So why the fourth call returns me back to min 36 and sec 2 while the call was made before that? Why the first two calls give the same exact time even if I let plenty of time between them?
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, for the readers' benefit, you should try to use meaningful method and variable names.
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_mon=6, tm_mday=20, tm_hour=15, tm_min=39, tm_sec=28, tm_wday=5, tm_yday=171, tm_isdst=-1) ``` **edit:** function is always evaluated in parameter. Solution: decouple it's assignment from the parameter ``` def f(t="now"): if t=="now": return datetime.datetime.now().timetuple() else: return t.timetuple() def main(ff=f): print ff print ff() import time main() time.sleep(3) main() ```
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 order for the argument to be optional so to be able to call `f()` with no arguments. Now whenever in time I execute `f()` I get the same datetime A (which is wrong according to what I expect), but whenever in time I execute `f(datetime.datetime.now())` I get different datetimes (which is correct as expected). For example ``` >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f(datetime.datetime.now()) time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=37, tm_sec=1, tm_wday=5, tm_yday=171, tm_isdst=-1) >>> f() time.struct_time(tm_year=2015, tm_mon=6, tm_mday=20, tm_hour=15, tm_min=36, tm_sec=2, tm_wday=5, tm_yday=171, tm_isdst=-1) ``` So why the fourth call returns me back to min 36 and sec 2 while the call was made before that? Why the first two calls give the same exact time even if I let plenty of time between them?
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, for the readers' benefit, you should try to use meaningful method and variable names.
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, 21, 0, 6, 10, 698000) >>> f() datetime.datetime(2015, 6, 21, 0, 6, 12, 269000) ``` Or you can pass in another function, here a test one, and override `t`. Calling f() calls the function passed in: ``` >>> def test(): ... return "hi" ... >>> f(t=test) 'hi' ```
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('Init package1.module1') from . import module2 module2.py print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) from . import module1 ``` I get: ``` vic@ubuntu:~/Desktop/app2$ python3 start.py Init package1 Init package1.module1 Init package1.module2 {'__main__': <module '__main__' from 'start.py'>, ... 'package1': <module 'package1' from '/home/vic/Desktop/app2/package1/__init__.py'>, 'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>, 'package1.module2': <module 'package1.module2' from '/home/vic/Desktop/app2/package1/module2.py'>, ... Traceback (most recent call last): File "start.py", line 3, in <module> from package1 import module1 File "/home/vic/Desktop/app2/package1/module1.py", line 3, in <module> from . import module2 File "/home/vic/Desktop/app2/package1/module2.py", line 5, in <module> from . import module1 ImportError: cannot import name module1 vic@ubuntu:~/Desktop/app2$ ``` `import package1.module1` works, but i want to use `from . import module1` because i want to make `package1` portable for my other applications, that's why i want to use relative paths. I am using python 3. I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa. **In other words:** `sys.modules` contains `'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>`. I want to get a reference to it in form `from . import module1`, but it tries to get a name, not a package like in case `import package1.module1` (which works fine). I tried `import .module1 as m1` - but that's a syntax error. Also, `from . import module2` in `module1` works fine, but `from . import module1` in `module2` doesn't work... **UPDATE:** This hack works (but i am looking for the 'official' way): ``` print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) #from . import module1 parent_module_name = __name__.rpartition('.')[0] module1 = sys.modules[parent_module_name + '.module1'] ```
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 need circular imports. A function in module1 asserts that one of its > parameter is instance of a class defined in module2 and viceversa. > > > You could move one the classes to a separate module to resolve the circular dependency or make the import at a function level if you don't want to use absolute imports. ``` . ├── start.py # from package1 import module1 └── package1    ├── __init__.py # print("Init package1") # from . import module1, module2 ├── c1.py # print("Init package1.c1") # class C1: # pass    ├── module1.py # print("Init package1.module1") # from .c1 import C1 # from .module2 import C2    └── module2.py # print("Init package1.module2") # from .c1 import C1 # class C2: # pass # def f(): # from .module1 import C1 ``` ### Output ``` Init package1 Init package1.module1 Init package1.c1 Init package1.module2 ``` Another option that might be simpler than refactoring out `c1.py` is to merge `module{1,2}.py` into a single `common.py`. `module{1,2}.py` make the imports from `common` in this case.
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://bugs.python.org/issue17636)). > > > Looking through the bugreport, it seems that this not so much a buf fixed, as well as a new feature in the way imports work. Referring to [poke's answer above](https://stackoverflow.com/a/8030886/740048), he shows that `from . import foo` means to load `__init__.py` and get `foo` from it (possibly from the implicitly loaded list of submodules). Since python3.5, `from . import foo` will do the same, but if `foo` is not available as an attribute, it will fall back to looking through the lists of loaded modules (`sys.modules`) to see if it is already present there, which fixes this particular case. I'm not 100% sure I properly presented how this works, though.
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('Init package1.module1') from . import module2 module2.py print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) from . import module1 ``` I get: ``` vic@ubuntu:~/Desktop/app2$ python3 start.py Init package1 Init package1.module1 Init package1.module2 {'__main__': <module '__main__' from 'start.py'>, ... 'package1': <module 'package1' from '/home/vic/Desktop/app2/package1/__init__.py'>, 'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>, 'package1.module2': <module 'package1.module2' from '/home/vic/Desktop/app2/package1/module2.py'>, ... Traceback (most recent call last): File "start.py", line 3, in <module> from package1 import module1 File "/home/vic/Desktop/app2/package1/module1.py", line 3, in <module> from . import module2 File "/home/vic/Desktop/app2/package1/module2.py", line 5, in <module> from . import module1 ImportError: cannot import name module1 vic@ubuntu:~/Desktop/app2$ ``` `import package1.module1` works, but i want to use `from . import module1` because i want to make `package1` portable for my other applications, that's why i want to use relative paths. I am using python 3. I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa. **In other words:** `sys.modules` contains `'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>`. I want to get a reference to it in form `from . import module1`, but it tries to get a name, not a package like in case `import package1.module1` (which works fine). I tried `import .module1 as m1` - but that's a syntax error. Also, `from . import module2` in `module1` works fine, but `from . import module1` in `module2` doesn't work... **UPDATE:** This hack works (but i am looking for the 'official' way): ``` print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) #from . import module1 parent_module_name = __name__.rpartition('.')[0] module1 = sys.modules[parent_module_name + '.module1'] ```
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 need circular imports. A function in module1 asserts that one of its > parameter is instance of a class defined in module2 and viceversa. > > > You could move one the classes to a separate module to resolve the circular dependency or make the import at a function level if you don't want to use absolute imports. ``` . ├── start.py # from package1 import module1 └── package1    ├── __init__.py # print("Init package1") # from . import module1, module2 ├── c1.py # print("Init package1.c1") # class C1: # pass    ├── module1.py # print("Init package1.module1") # from .c1 import C1 # from .module2 import C2    └── module2.py # print("Init package1.module2") # from .c1 import C1 # class C2: # pass # def f(): # from .module1 import C1 ``` ### Output ``` Init package1 Init package1.module1 Init package1.c1 Init package1.module2 ``` Another option that might be simpler than refactoring out `c1.py` is to merge `module{1,2}.py` into a single `common.py`. `module{1,2}.py` make the imports from `common` in this case.
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 write your `import` statement using `.` notations, e.g. `from .package` or `from app.package`.
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('Init package1.module1') from . import module2 module2.py print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) from . import module1 ``` I get: ``` vic@ubuntu:~/Desktop/app2$ python3 start.py Init package1 Init package1.module1 Init package1.module2 {'__main__': <module '__main__' from 'start.py'>, ... 'package1': <module 'package1' from '/home/vic/Desktop/app2/package1/__init__.py'>, 'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>, 'package1.module2': <module 'package1.module2' from '/home/vic/Desktop/app2/package1/module2.py'>, ... Traceback (most recent call last): File "start.py", line 3, in <module> from package1 import module1 File "/home/vic/Desktop/app2/package1/module1.py", line 3, in <module> from . import module2 File "/home/vic/Desktop/app2/package1/module2.py", line 5, in <module> from . import module1 ImportError: cannot import name module1 vic@ubuntu:~/Desktop/app2$ ``` `import package1.module1` works, but i want to use `from . import module1` because i want to make `package1` portable for my other applications, that's why i want to use relative paths. I am using python 3. I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa. **In other words:** `sys.modules` contains `'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>`. I want to get a reference to it in form `from . import module1`, but it tries to get a name, not a package like in case `import package1.module1` (which works fine). I tried `import .module1 as m1` - but that's a syntax error. Also, `from . import module2` in `module1` works fine, but `from . import module1` in `module2` doesn't work... **UPDATE:** This hack works (but i am looking for the 'official' way): ``` print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) #from . import module1 parent_module_name = __name__.rpartition('.')[0] module1 = sys.modules[parent_module_name + '.module1'] ```
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://bugs.python.org/issue17636)). > > > Looking through the bugreport, it seems that this not so much a buf fixed, as well as a new feature in the way imports work. Referring to [poke's answer above](https://stackoverflow.com/a/8030886/740048), he shows that `from . import foo` means to load `__init__.py` and get `foo` from it (possibly from the implicitly loaded list of submodules). Since python3.5, `from . import foo` will do the same, but if `foo` is not available as an attribute, it will fall back to looking through the lists of loaded modules (`sys.modules`) to see if it is already present there, which fixes this particular case. I'm not 100% sure I properly presented how this works, though.
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('Init package1.module1') from . import module2 module2.py print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) from . import module1 ``` I get: ``` vic@ubuntu:~/Desktop/app2$ python3 start.py Init package1 Init package1.module1 Init package1.module2 {'__main__': <module '__main__' from 'start.py'>, ... 'package1': <module 'package1' from '/home/vic/Desktop/app2/package1/__init__.py'>, 'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>, 'package1.module2': <module 'package1.module2' from '/home/vic/Desktop/app2/package1/module2.py'>, ... Traceback (most recent call last): File "start.py", line 3, in <module> from package1 import module1 File "/home/vic/Desktop/app2/package1/module1.py", line 3, in <module> from . import module2 File "/home/vic/Desktop/app2/package1/module2.py", line 5, in <module> from . import module1 ImportError: cannot import name module1 vic@ubuntu:~/Desktop/app2$ ``` `import package1.module1` works, but i want to use `from . import module1` because i want to make `package1` portable for my other applications, that's why i want to use relative paths. I am using python 3. I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa. **In other words:** `sys.modules` contains `'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>`. I want to get a reference to it in form `from . import module1`, but it tries to get a name, not a package like in case `import package1.module1` (which works fine). I tried `import .module1 as m1` - but that's a syntax error. Also, `from . import module2` in `module1` works fine, but `from . import module1` in `module2` doesn't work... **UPDATE:** This hack works (but i am looking for the 'official' way): ``` print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) #from . import module1 parent_module_name = __name__.rpartition('.')[0] module1 = sys.modules[parent_module_name + '.module1'] ```
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('Init package1.module1') from . import module2 module2.py print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) from . import module1 ``` I get: ``` vic@ubuntu:~/Desktop/app2$ python3 start.py Init package1 Init package1.module1 Init package1.module2 {'__main__': <module '__main__' from 'start.py'>, ... 'package1': <module 'package1' from '/home/vic/Desktop/app2/package1/__init__.py'>, 'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>, 'package1.module2': <module 'package1.module2' from '/home/vic/Desktop/app2/package1/module2.py'>, ... Traceback (most recent call last): File "start.py", line 3, in <module> from package1 import module1 File "/home/vic/Desktop/app2/package1/module1.py", line 3, in <module> from . import module2 File "/home/vic/Desktop/app2/package1/module2.py", line 5, in <module> from . import module1 ImportError: cannot import name module1 vic@ubuntu:~/Desktop/app2$ ``` `import package1.module1` works, but i want to use `from . import module1` because i want to make `package1` portable for my other applications, that's why i want to use relative paths. I am using python 3. I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa. **In other words:** `sys.modules` contains `'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>`. I want to get a reference to it in form `from . import module1`, but it tries to get a name, not a package like in case `import package1.module1` (which works fine). I tried `import .module1 as m1` - but that's a syntax error. Also, `from . import module2` in `module1` works fine, but `from . import module1` in `module2` doesn't work... **UPDATE:** This hack works (but i am looking for the 'official' way): ``` print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) #from . import module1 parent_module_name = __name__.rpartition('.')[0] module1 = sys.modules[parent_module_name + '.module1'] ```
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 need circular imports. A function in module1 asserts that one of its > parameter is instance of a class defined in module2 and viceversa. > > > You could move one the classes to a separate module to resolve the circular dependency or make the import at a function level if you don't want to use absolute imports. ``` . ├── start.py # from package1 import module1 └── package1    ├── __init__.py # print("Init package1") # from . import module1, module2 ├── c1.py # print("Init package1.c1") # class C1: # pass    ├── module1.py # print("Init package1.module1") # from .c1 import C1 # from .module2 import C2    └── module2.py # print("Init package1.module2") # from .c1 import C1 # class C2: # pass # def f(): # from .module1 import C1 ``` ### Output ``` Init package1 Init package1.module1 Init package1.c1 Init package1.module2 ``` Another option that might be simpler than refactoring out `c1.py` is to merge `module{1,2}.py` into a single `common.py`. `module{1,2}.py` make the imports from `common` in this case.
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('Init package1.module1') from . import module2 module2.py print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) from . import module1 ``` I get: ``` vic@ubuntu:~/Desktop/app2$ python3 start.py Init package1 Init package1.module1 Init package1.module2 {'__main__': <module '__main__' from 'start.py'>, ... 'package1': <module 'package1' from '/home/vic/Desktop/app2/package1/__init__.py'>, 'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>, 'package1.module2': <module 'package1.module2' from '/home/vic/Desktop/app2/package1/module2.py'>, ... Traceback (most recent call last): File "start.py", line 3, in <module> from package1 import module1 File "/home/vic/Desktop/app2/package1/module1.py", line 3, in <module> from . import module2 File "/home/vic/Desktop/app2/package1/module2.py", line 5, in <module> from . import module1 ImportError: cannot import name module1 vic@ubuntu:~/Desktop/app2$ ``` `import package1.module1` works, but i want to use `from . import module1` because i want to make `package1` portable for my other applications, that's why i want to use relative paths. I am using python 3. I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa. **In other words:** `sys.modules` contains `'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>`. I want to get a reference to it in form `from . import module1`, but it tries to get a name, not a package like in case `import package1.module1` (which works fine). I tried `import .module1 as m1` - but that's a syntax error. Also, `from . import module2` in `module1` works fine, but `from . import module1` in `module2` doesn't work... **UPDATE:** This hack works (but i am looking for the 'official' way): ``` print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) #from . import module1 parent_module_name = __name__.rpartition('.')[0] module1 = sys.modules[parent_module_name + '.module1'] ```
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 you import `from .` where `.` is the current package. So all your `from . import X` imports go through the package’s `__init__.py`. You can make your problem a bit more visible, if you explicitely import your modules in the `__init__.py` and give them another name (and adjust the other imports to use those names of course): ``` print('Init package1') from . import module1 as m1 from . import module2 as m2 ``` Now when you are importing `m1` in `start.py`, the package first initializes `m1` and comes to the `from . import m2` line. At that point, there is no `m2` known in `__init__.py` so you get an import error. If you switch the import statements in `__init__.py` around (so you load `m2` first), then in `m2` it finds the `from . import m1` line, which fails for the same reason as before. If you don’t explicitely import the modules in `__init__.py` something similar still happens in the background. The difference is that you get a less flat structure (as the imports are no longer started from the package only). As such both `module1` and `module2` get “started” and you get the respective initialization prints. To make it work, you could do an absolute import in `module2`. That way you could avoid that the package needs to resolve everything first, and make it reuse the import from `start.py` (as it has the same import path). Or even better, you get rid of the circular import at all. It’s generally a sign that your application structure is not so good, if you have circular references. (I hope my explanation makes any sense, I already had difficulties writing it, but the general idea should be clear, I hope…) ### edit In response to your update; what you are doing there is that you use the full package name to get the reference to the module. This is equivalent (but much more complicated) to the first possible option to make it work; you use an absolute import using the same import path as in `start.py`.
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('Init package1.module1') from . import module2 module2.py print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) from . import module1 ``` I get: ``` vic@ubuntu:~/Desktop/app2$ python3 start.py Init package1 Init package1.module1 Init package1.module2 {'__main__': <module '__main__' from 'start.py'>, ... 'package1': <module 'package1' from '/home/vic/Desktop/app2/package1/__init__.py'>, 'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>, 'package1.module2': <module 'package1.module2' from '/home/vic/Desktop/app2/package1/module2.py'>, ... Traceback (most recent call last): File "start.py", line 3, in <module> from package1 import module1 File "/home/vic/Desktop/app2/package1/module1.py", line 3, in <module> from . import module2 File "/home/vic/Desktop/app2/package1/module2.py", line 5, in <module> from . import module1 ImportError: cannot import name module1 vic@ubuntu:~/Desktop/app2$ ``` `import package1.module1` works, but i want to use `from . import module1` because i want to make `package1` portable for my other applications, that's why i want to use relative paths. I am using python 3. I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa. **In other words:** `sys.modules` contains `'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>`. I want to get a reference to it in form `from . import module1`, but it tries to get a name, not a package like in case `import package1.module1` (which works fine). I tried `import .module1 as m1` - but that's a syntax error. Also, `from . import module2` in `module1` works fine, but `from . import module1` in `module2` doesn't work... **UPDATE:** This hack works (but i am looking for the 'official' way): ``` print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) #from . import module1 parent_module_name = __name__.rpartition('.')[0] module1 = sys.modules[parent_module_name + '.module1'] ```
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 packages, because either you have some code you should split off into another package (to make them both depend on that new package, but not each other), or you should merge them into one package. > > — Lasse V. Karlsen♦ > > > Maybe you should consider placing them in the same module. :)
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('Init package1.module1') from . import module2 module2.py print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) from . import module1 ``` I get: ``` vic@ubuntu:~/Desktop/app2$ python3 start.py Init package1 Init package1.module1 Init package1.module2 {'__main__': <module '__main__' from 'start.py'>, ... 'package1': <module 'package1' from '/home/vic/Desktop/app2/package1/__init__.py'>, 'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>, 'package1.module2': <module 'package1.module2' from '/home/vic/Desktop/app2/package1/module2.py'>, ... Traceback (most recent call last): File "start.py", line 3, in <module> from package1 import module1 File "/home/vic/Desktop/app2/package1/module1.py", line 3, in <module> from . import module2 File "/home/vic/Desktop/app2/package1/module2.py", line 5, in <module> from . import module1 ImportError: cannot import name module1 vic@ubuntu:~/Desktop/app2$ ``` `import package1.module1` works, but i want to use `from . import module1` because i want to make `package1` portable for my other applications, that's why i want to use relative paths. I am using python 3. I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa. **In other words:** `sys.modules` contains `'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>`. I want to get a reference to it in form `from . import module1`, but it tries to get a name, not a package like in case `import package1.module1` (which works fine). I tried `import .module1 as m1` - but that's a syntax error. Also, `from . import module2` in `module1` works fine, but `from . import module1` in `module2` doesn't work... **UPDATE:** This hack works (but i am looking for the 'official' way): ``` print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) #from . import module1 parent_module_name = __name__.rpartition('.')[0] module1 = sys.modules[parent_module_name + '.module1'] ```
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 write your `import` statement using `.` notations, e.g. `from .package` or `from app.package`.
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('Init package1.module1') from . import module2 module2.py print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) from . import module1 ``` I get: ``` vic@ubuntu:~/Desktop/app2$ python3 start.py Init package1 Init package1.module1 Init package1.module2 {'__main__': <module '__main__' from 'start.py'>, ... 'package1': <module 'package1' from '/home/vic/Desktop/app2/package1/__init__.py'>, 'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>, 'package1.module2': <module 'package1.module2' from '/home/vic/Desktop/app2/package1/module2.py'>, ... Traceback (most recent call last): File "start.py", line 3, in <module> from package1 import module1 File "/home/vic/Desktop/app2/package1/module1.py", line 3, in <module> from . import module2 File "/home/vic/Desktop/app2/package1/module2.py", line 5, in <module> from . import module1 ImportError: cannot import name module1 vic@ubuntu:~/Desktop/app2$ ``` `import package1.module1` works, but i want to use `from . import module1` because i want to make `package1` portable for my other applications, that's why i want to use relative paths. I am using python 3. I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa. **In other words:** `sys.modules` contains `'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>`. I want to get a reference to it in form `from . import module1`, but it tries to get a name, not a package like in case `import package1.module1` (which works fine). I tried `import .module1 as m1` - but that's a syntax error. Also, `from . import module2` in `module1` works fine, but `from . import module1` in `module2` doesn't work... **UPDATE:** This hack works (but i am looking for the 'official' way): ``` print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) #from . import module1 parent_module_name = __name__.rpartition('.')[0] module1 = sys.modules[parent_module_name + '.module1'] ```
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 you import `from .` where `.` is the current package. So all your `from . import X` imports go through the package’s `__init__.py`. You can make your problem a bit more visible, if you explicitely import your modules in the `__init__.py` and give them another name (and adjust the other imports to use those names of course): ``` print('Init package1') from . import module1 as m1 from . import module2 as m2 ``` Now when you are importing `m1` in `start.py`, the package first initializes `m1` and comes to the `from . import m2` line. At that point, there is no `m2` known in `__init__.py` so you get an import error. If you switch the import statements in `__init__.py` around (so you load `m2` first), then in `m2` it finds the `from . import m1` line, which fails for the same reason as before. If you don’t explicitely import the modules in `__init__.py` something similar still happens in the background. The difference is that you get a less flat structure (as the imports are no longer started from the package only). As such both `module1` and `module2` get “started” and you get the respective initialization prints. To make it work, you could do an absolute import in `module2`. That way you could avoid that the package needs to resolve everything first, and make it reuse the import from `start.py` (as it has the same import path). Or even better, you get rid of the circular import at all. It’s generally a sign that your application structure is not so good, if you have circular references. (I hope my explanation makes any sense, I already had difficulties writing it, but the general idea should be clear, I hope…) ### edit In response to your update; what you are doing there is that you use the full package name to get the reference to the module. This is equivalent (but much more complicated) to the first possible option to make it work; you use an absolute import using the same import path as in `start.py`.
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 need circular imports. A function in module1 asserts that one of its > parameter is instance of a class defined in module2 and viceversa. > > > You could move one the classes to a separate module to resolve the circular dependency or make the import at a function level if you don't want to use absolute imports. ``` . ├── start.py # from package1 import module1 └── package1    ├── __init__.py # print("Init package1") # from . import module1, module2 ├── c1.py # print("Init package1.c1") # class C1: # pass    ├── module1.py # print("Init package1.module1") # from .c1 import C1 # from .module2 import C2    └── module2.py # print("Init package1.module2") # from .c1 import C1 # class C2: # pass # def f(): # from .module1 import C1 ``` ### Output ``` Init package1 Init package1.module1 Init package1.c1 Init package1.module2 ``` Another option that might be simpler than refactoring out `c1.py` is to merge `module{1,2}.py` into a single `common.py`. `module{1,2}.py` make the imports from `common` in this case.
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('Init package1.module1') from . import module2 module2.py print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) from . import module1 ``` I get: ``` vic@ubuntu:~/Desktop/app2$ python3 start.py Init package1 Init package1.module1 Init package1.module2 {'__main__': <module '__main__' from 'start.py'>, ... 'package1': <module 'package1' from '/home/vic/Desktop/app2/package1/__init__.py'>, 'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>, 'package1.module2': <module 'package1.module2' from '/home/vic/Desktop/app2/package1/module2.py'>, ... Traceback (most recent call last): File "start.py", line 3, in <module> from package1 import module1 File "/home/vic/Desktop/app2/package1/module1.py", line 3, in <module> from . import module2 File "/home/vic/Desktop/app2/package1/module2.py", line 5, in <module> from . import module1 ImportError: cannot import name module1 vic@ubuntu:~/Desktop/app2$ ``` `import package1.module1` works, but i want to use `from . import module1` because i want to make `package1` portable for my other applications, that's why i want to use relative paths. I am using python 3. I need circular imports. A function in module1 asserts that one of its parameter is instance of a class defined in module2 and viceversa. **In other words:** `sys.modules` contains `'package1.module1': <module 'package1.module1' from '/home/vic/Desktop/app2/package1/module1.py'>`. I want to get a reference to it in form `from . import module1`, but it tries to get a name, not a package like in case `import package1.module1` (which works fine). I tried `import .module1 as m1` - but that's a syntax error. Also, `from . import module2` in `module1` works fine, but `from . import module1` in `module2` doesn't work... **UPDATE:** This hack works (but i am looking for the 'official' way): ``` print('Init package1.module2') import sys, pprint pprint.pprint(sys.modules) #from . import module1 parent_module_name = __name__.rpartition('.')[0] module1 = sys.modules[parent_module_name + '.module1'] ```
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://bugs.python.org/issue17636)). > > > Looking through the bugreport, it seems that this not so much a buf fixed, as well as a new feature in the way imports work. Referring to [poke's answer above](https://stackoverflow.com/a/8030886/740048), he shows that `from . import foo` means to load `__init__.py` and get `foo` from it (possibly from the implicitly loaded list of submodules). Since python3.5, `from . import foo` will do the same, but if `foo` is not available as an attribute, it will fall back to looking through the lists of loaded modules (`sys.modules`) to see if it is already present there, which fixes this particular case. I'm not 100% sure I properly presented how this works, though.
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(path, file) return None ``` Good luck!
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(candidate): candidates.append(candidate) return candidates ```
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: ``` >>> import shutil >>> shutil.which("bash") '/usr/bin/bash' ```
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(candidate): candidates.append(candidate) return candidates ```
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: ``` >>> import shutil >>> shutil.which("bash") '/usr/bin/bash' ```
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_path, os.X_OK): return full_path return None ```
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(path, file) return None ``` Good luck!
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: ``` >>> import shutil >>> shutil.which("bash") '/usr/bin/bash' ```
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: ``` >>> import shutil >>> shutil.which("bash") '/usr/bin/bash' ```
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(path, file) return None ``` Good luck!
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_path, os.X_OK): return full_path return None ```
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(path, file) return None ``` Good luck!
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://flask.pocoo.org/docs/installation/#installation> ``` $ adduser myapp $ sudo apt-get install python-setuptools $ sudo easy_install pip $ sudo pip install virtualenv /home/myapp/ -- www/ $ sudo pip install virtualenv /home/myapp/ -- www/ -- env/ $ . env/bin/activate $ easy_install Flask ``` MOD\_WSGI ========= <http://flask.pocoo.org/docs/deploying/mod_wsgi/> ``` $ sudo apt-get install apache2 $ sudo apt-get install libapache2-mod-wsgi ``` Creating WSGI file ================== ``` $ nano /home/myapp/www/myapp.wsgi --myapp.wsgi contents:-------------------------- activate_this = '/home/myapp/env/bin/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) from myapp import app as application /home/myapp/ -- www/ -- myapp.wsgi -- env/ ``` Configuring Apache ================== ``` $ nano /etc/apache2/sites-available/myapp.com -----myapp.com file contents --------------------- <VirtualHost *:80> ServerName myapp.com WSGIDaemonProcess myapp user=myapp group=myapp threads=5 python-path=/home/myapp/env/lib/python2.6/site-packages WSGIScriptAlias / /home/myapp/www/myapp.wsgi <Directory /home/myapp/www> WSGIProcessGroup myapp WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all </Directory> </VirtualHost> ``` Enable the virtual host file I just created =========================================== ``` $ cd /etc/apache2/sites-enabled $ ln -s ../sites-available/myapp.com ``` Restart Apache ============== ``` $ /etc/init.d/apache2 restart ``` Servers me a 500 server error page. Here's the latest error log: ``` mod_wsgi (pid=3514): Target WSGI script '/home/myapp/www/myapp.wsgi' cannot be loaded as Python module. mod_wsgi (pid=3514): Exception occurred processing WSGI script '/home/myapp/www/myapp.wsgi'. Traceback (most recent call last): File "/home/myapp/www/myapp.wsgi", line 4, in <module> from myapp import app as application ImportError: No module named myapp ``` The errors allude that it's something strikingly obvious, but I'm quite lost.
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-version']=platform.version() info['architecture']=platform.machine() info['hostname']=socket.gethostname() info['ip-address']=socket.gethostbyname(socket.gethostname()) info['mac-address']=':'.join(re.findall('..', '%012x' % uuid.getnode())) info['processor']=platform.processor() info['ram']=str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB" return json.dumps(info) except Exception as e: logging.exception(e) json.loads(getSystemInfo()) ``` --- Output Sample: ``` { 'platform': 'Linux', 'platform-release': '5.3.0-29-generic', 'platform-version': '#31-Ubuntu SMP Fri Jan 17 17:27:26 UTC 2020', 'architecture': 'x86_64', 'hostname': 'naret-vm', 'ip-address': '127.0.1.1', 'mac-address': 'bb:cc:dd:ee:bc:ff', 'processor': 'x86_64', 'ram': '4 GB' } ```
``` 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", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor def System_information(): 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.processor}") print(f"Processor: {cpuinfo.get_cpu_info()['brand_raw']}") print(f"Ip-Address: {socket.gethostbyname(socket.gethostname())}") print(f"Mac-Address: {':'.join(re.findall('..', '%012x' % uuid.getnode()))}") # Boot Time print("="*40, "Boot Time", "="*40) boot_time_timestamp = psutil.boot_time() bt = datetime.fromtimestamp(boot_time_timestamp) print(f"Boot Time: {bt.year}/{bt.month}/{bt.day} {bt.hour}:{bt.minute}:{bt.second}") # print CPU information print("="*40, "CPU Info", "="*40) # number of cores print("Physical cores:", psutil.cpu_count(logical=False)) print("Total cores:", psutil.cpu_count(logical=True)) # CPU frequencies cpufreq = psutil.cpu_freq() print(f"Max Frequency: {cpufreq.max:.2f}Mhz") print(f"Min Frequency: {cpufreq.min:.2f}Mhz") print(f"Current Frequency: {cpufreq.current:.2f}Mhz") # CPU usage print("CPU Usage Per Core:") for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)): print(f"Core {i}: {percentage}%") print(f"Total CPU Usage: {psutil.cpu_percent()}%") # Memory Information print("="*40, "Memory Information", "="*40) # get the memory details svmem = psutil.virtual_memory() print(f"Total: {get_size(svmem.total)}") print(f"Available: {get_size(svmem.available)}") print(f"Used: {get_size(svmem.used)}") print(f"Percentage: {svmem.percent}%") print("="*20, "SWAP", "="*20) # get the swap memory details (if exists) swap = psutil.swap_memory() print(f"Total: {get_size(swap.total)}") print(f"Free: {get_size(swap.free)}") print(f"Used: {get_size(swap.used)}") print(f"Percentage: {swap.percent}%") # Disk Information print("="*40, "Disk Information", "="*40) print("Partitions and Usage:") # get all disk partitions partitions = psutil.disk_partitions() for partition in partitions: print(f"=== Device: {partition.device} ===") print(f" Mountpoint: {partition.mountpoint}") print(f" File system type: {partition.fstype}") try: partition_usage = psutil.disk_usage(partition.mountpoint) except PermissionError: # this can be catched due to the disk that # isn't ready continue print(f" Total Size: {get_size(partition_usage.total)}") print(f" Used: {get_size(partition_usage.used)}") print(f" Free: {get_size(partition_usage.free)}") print(f" Percentage: {partition_usage.percent}%") # get IO statistics since boot disk_io = psutil.disk_io_counters() print(f"Total read: {get_size(disk_io.read_bytes)}") print(f"Total write: {get_size(disk_io.write_bytes)}") ## Network information print("="*40, "Network Information", "="*40) ## get all network interfaces (virtual and physical) if_addrs = psutil.net_if_addrs() for interface_name, interface_addresses in if_addrs.items(): for address in interface_addresses: print(f"=== Interface: {interface_name} ===") if str(address.family) == 'AddressFamily.AF_INET': print(f" IP Address: {address.address}") print(f" Netmask: {address.netmask}") print(f" Broadcast IP: {address.broadcast}") elif str(address.family) == 'AddressFamily.AF_PACKET': print(f" MAC Address: {address.address}") print(f" Netmask: {address.netmask}") print(f" Broadcast MAC: {address.broadcast}") ##get IO statistics since boot net_io = psutil.net_io_counters() print(f"Total Bytes Sent: {get_size(net_io.bytes_sent)}") print(f"Total Bytes Received: {get_size(net_io.bytes_recv)}") if __name__ == "__main__": System_information() ```
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 Family 6 Model 15 Stepping 6, GenuineIntel') >>> platform.system() 'Windows' >>> platform.processor() 'x86 Family 6 Model 15 Stepping 6, GenuineIntel' ```
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:36:25 EST 2008', 'i686') > > >
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-version']=platform.version() info['architecture']=platform.machine() info['hostname']=socket.gethostname() info['ip-address']=socket.gethostbyname(socket.gethostname()) info['mac-address']=':'.join(re.findall('..', '%012x' % uuid.getnode())) info['processor']=platform.processor() info['ram']=str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB" return json.dumps(info) except Exception as e: logging.exception(e) json.loads(getSystemInfo()) ``` --- Output Sample: ``` { 'platform': 'Linux', 'platform-release': '5.3.0-29-generic', 'platform-version': '#31-Ubuntu SMP Fri Jan 17 17:27:26 UTC 2020', 'architecture': 'x86_64', 'hostname': 'naret-vm', 'ip-address': '127.0.1.1', 'mac-address': 'bb:cc:dd:ee:bc:ff', 'processor': 'x86_64', 'ram': '4 GB' } ```
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:36:25 EST 2008', 'i686') > > >
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.processor}") ```
``` #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.processor}") ```
``` 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", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor def System_information(): 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.processor}") print(f"Processor: {cpuinfo.get_cpu_info()['brand_raw']}") print(f"Ip-Address: {socket.gethostbyname(socket.gethostname())}") print(f"Mac-Address: {':'.join(re.findall('..', '%012x' % uuid.getnode()))}") # Boot Time print("="*40, "Boot Time", "="*40) boot_time_timestamp = psutil.boot_time() bt = datetime.fromtimestamp(boot_time_timestamp) print(f"Boot Time: {bt.year}/{bt.month}/{bt.day} {bt.hour}:{bt.minute}:{bt.second}") # print CPU information print("="*40, "CPU Info", "="*40) # number of cores print("Physical cores:", psutil.cpu_count(logical=False)) print("Total cores:", psutil.cpu_count(logical=True)) # CPU frequencies cpufreq = psutil.cpu_freq() print(f"Max Frequency: {cpufreq.max:.2f}Mhz") print(f"Min Frequency: {cpufreq.min:.2f}Mhz") print(f"Current Frequency: {cpufreq.current:.2f}Mhz") # CPU usage print("CPU Usage Per Core:") for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)): print(f"Core {i}: {percentage}%") print(f"Total CPU Usage: {psutil.cpu_percent()}%") # Memory Information print("="*40, "Memory Information", "="*40) # get the memory details svmem = psutil.virtual_memory() print(f"Total: {get_size(svmem.total)}") print(f"Available: {get_size(svmem.available)}") print(f"Used: {get_size(svmem.used)}") print(f"Percentage: {svmem.percent}%") print("="*20, "SWAP", "="*20) # get the swap memory details (if exists) swap = psutil.swap_memory() print(f"Total: {get_size(swap.total)}") print(f"Free: {get_size(swap.free)}") print(f"Used: {get_size(swap.used)}") print(f"Percentage: {swap.percent}%") # Disk Information print("="*40, "Disk Information", "="*40) print("Partitions and Usage:") # get all disk partitions partitions = psutil.disk_partitions() for partition in partitions: print(f"=== Device: {partition.device} ===") print(f" Mountpoint: {partition.mountpoint}") print(f" File system type: {partition.fstype}") try: partition_usage = psutil.disk_usage(partition.mountpoint) except PermissionError: # this can be catched due to the disk that # isn't ready continue print(f" Total Size: {get_size(partition_usage.total)}") print(f" Used: {get_size(partition_usage.used)}") print(f" Free: {get_size(partition_usage.free)}") print(f" Percentage: {partition_usage.percent}%") # get IO statistics since boot disk_io = psutil.disk_io_counters() print(f"Total read: {get_size(disk_io.read_bytes)}") print(f"Total write: {get_size(disk_io.write_bytes)}") ## Network information print("="*40, "Network Information", "="*40) ## get all network interfaces (virtual and physical) if_addrs = psutil.net_if_addrs() for interface_name, interface_addresses in if_addrs.items(): for address in interface_addresses: print(f"=== Interface: {interface_name} ===") if str(address.family) == 'AddressFamily.AF_INET': print(f" IP Address: {address.address}") print(f" Netmask: {address.netmask}") print(f" Broadcast IP: {address.broadcast}") elif str(address.family) == 'AddressFamily.AF_PACKET': print(f" MAC Address: {address.address}") print(f" Netmask: {address.netmask}") print(f" Broadcast MAC: {address.broadcast}") ##get IO statistics since boot net_io = psutil.net_io_counters() print(f"Total Bytes Sent: {get_size(net_io.bytes_sent)}") print(f"Total Bytes Received: {get_size(net_io.bytes_recv)}") if __name__ == "__main__": System_information() ```
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:36:25 EST 2008', 'i686') > > >
``` 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", "G", "T", "P"]: if bytes < factor: return f"{bytes:.2f}{unit}{suffix}" bytes /= factor def System_information(): 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.processor}") print(f"Processor: {cpuinfo.get_cpu_info()['brand_raw']}") print(f"Ip-Address: {socket.gethostbyname(socket.gethostname())}") print(f"Mac-Address: {':'.join(re.findall('..', '%012x' % uuid.getnode()))}") # Boot Time print("="*40, "Boot Time", "="*40) boot_time_timestamp = psutil.boot_time() bt = datetime.fromtimestamp(boot_time_timestamp) print(f"Boot Time: {bt.year}/{bt.month}/{bt.day} {bt.hour}:{bt.minute}:{bt.second}") # print CPU information print("="*40, "CPU Info", "="*40) # number of cores print("Physical cores:", psutil.cpu_count(logical=False)) print("Total cores:", psutil.cpu_count(logical=True)) # CPU frequencies cpufreq = psutil.cpu_freq() print(f"Max Frequency: {cpufreq.max:.2f}Mhz") print(f"Min Frequency: {cpufreq.min:.2f}Mhz") print(f"Current Frequency: {cpufreq.current:.2f}Mhz") # CPU usage print("CPU Usage Per Core:") for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)): print(f"Core {i}: {percentage}%") print(f"Total CPU Usage: {psutil.cpu_percent()}%") # Memory Information print("="*40, "Memory Information", "="*40) # get the memory details svmem = psutil.virtual_memory() print(f"Total: {get_size(svmem.total)}") print(f"Available: {get_size(svmem.available)}") print(f"Used: {get_size(svmem.used)}") print(f"Percentage: {svmem.percent}%") print("="*20, "SWAP", "="*20) # get the swap memory details (if exists) swap = psutil.swap_memory() print(f"Total: {get_size(swap.total)}") print(f"Free: {get_size(swap.free)}") print(f"Used: {get_size(swap.used)}") print(f"Percentage: {swap.percent}%") # Disk Information print("="*40, "Disk Information", "="*40) print("Partitions and Usage:") # get all disk partitions partitions = psutil.disk_partitions() for partition in partitions: print(f"=== Device: {partition.device} ===") print(f" Mountpoint: {partition.mountpoint}") print(f" File system type: {partition.fstype}") try: partition_usage = psutil.disk_usage(partition.mountpoint) except PermissionError: # this can be catched due to the disk that # isn't ready continue print(f" Total Size: {get_size(partition_usage.total)}") print(f" Used: {get_size(partition_usage.used)}") print(f" Free: {get_size(partition_usage.free)}") print(f" Percentage: {partition_usage.percent}%") # get IO statistics since boot disk_io = psutil.disk_io_counters() print(f"Total read: {get_size(disk_io.read_bytes)}") print(f"Total write: {get_size(disk_io.write_bytes)}") ## Network information print("="*40, "Network Information", "="*40) ## get all network interfaces (virtual and physical) if_addrs = psutil.net_if_addrs() for interface_name, interface_addresses in if_addrs.items(): for address in interface_addresses: print(f"=== Interface: {interface_name} ===") if str(address.family) == 'AddressFamily.AF_INET': print(f" IP Address: {address.address}") print(f" Netmask: {address.netmask}") print(f" Broadcast IP: {address.broadcast}") elif str(address.family) == 'AddressFamily.AF_PACKET': print(f" MAC Address: {address.address}") print(f" Netmask: {address.netmask}") print(f" Broadcast MAC: {address.broadcast}") ##get IO statistics since boot net_io = psutil.net_io_counters() print(f"Total Bytes Sent: {get_size(net_io.bytes_sent)}") print(f"Total Bytes Received: {get_size(net_io.bytes_recv)}") if __name__ == "__main__": System_information() ```
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-version']=platform.version() info['architecture']=platform.machine() info['hostname']=socket.gethostname() info['ip-address']=socket.gethostbyname(socket.gethostname()) info['mac-address']=':'.join(re.findall('..', '%012x' % uuid.getnode())) info['processor']=platform.processor() info['ram']=str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB" return json.dumps(info) except Exception as e: logging.exception(e) json.loads(getSystemInfo()) ``` --- Output Sample: ``` { 'platform': 'Linux', 'platform-release': '5.3.0-29-generic', 'platform-version': '#31-Ubuntu SMP Fri Jan 17 17:27:26 UTC 2020', 'architecture': 'x86_64', 'hostname': 'naret-vm', 'ip-address': '127.0.1.1', 'mac-address': 'bb:cc:dd:ee:bc:ff', 'processor': 'x86_64', 'ram': '4 GB' } ```
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.processor}") ```
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 Family 6 Model 15 Stepping 6, GenuineIntel') >>> platform.system() 'Windows' >>> platform.processor() 'x86 Family 6 Model 15 Stepping 6, GenuineIntel' ```
``` #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:36:25 EST 2008', 'i686') > > >
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.processor}") ```
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:36:25 EST 2008', 'i686') > > >
``` #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__": fib(sys.argv[1]) ``` Now before I did sys.argv[1] or [1:] I was able to put in a sequence in n up to the number I wanted. I.e if I entered n as 12 I would get 0,1,1,3,5,8 which is correct. However I cannot get this to work. I did a print statement after the def fib(n): as print n. It would return my sys.argv pass in. Where am I going wrong? Thanks for your time.
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 fragment in range(len(response.files)): file_request = service.reports().getFile( reportId=response.id_, reportFragment=fragment) istream = io.BytesIO(file_request.execute()) if written_header: istream.readline() else: written_header = True ostream.write(istream.read()) ```
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')`, which returns unicode strings when you read from the file, or `open('file,txt', 'rb')`, which returns binary strings. The same applies for writing - you can't write strings correctly in mode `'wb'`, and can't write binary strings in mode `'w'`. In this case, your `istream` returns binary strings when read from, whereas your `ostream` expects to write a unicode string. The solution is to change encoding from one to the other, and do what sgDysregulation recommends: ``` ostream.write(istream.read().decode('utf-8')) ``` this assumes that the binary string is encoded in utf-8 format, which it probably is. You might have to use a different format otherwise.
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 fragment in range(len(response.files)): file_request = service.reports().getFile( reportId=response.id_, reportFragment=fragment) istream = io.BytesIO(file_request.execute()) if written_header: istream.readline() else: written_header = True ostream.write(istream.read()) ```
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 idle) and put them into a text file. Now i have looked for this on the world wide web and have found solutions for this, but on a windows computer. I have a mac with python 2.7. ANY HELP IS VERY MUCH APPRECIATED! My current code is below ``` from random import randrange def r(): while True: print randrange(1,10) ```
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], [7, 8, 9]]) ```
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 idle) and put them into a text file. Now i have looked for this on the world wide web and have found solutions for this, but on a windows computer. I have a mac with python 2.7. ANY HELP IS VERY MUCH APPRECIATED! My current code is below ``` from random import randrange def r(): while True: print randrange(1,10) ```
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 + " " + aa + " " + bb) ``` Last line from file is working
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 : ``` import numpy as np 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] arr = np.array(mydata) mask = (arr!=0).astype(np.int) #array that contains 1 for every non zero value, zero other wise padded_mask = np.pad(mask,(1,),"constant") #add a zero at the start and at the end to handle edge cases edge_mask = padded_mask[1:] - padded_mask[:-1] #diff between a value and the following one #if there's a 1 in edge mask it's a group start #if there's a -1 it's a group stop #where gives us the index of those starts and stops starts = np.where(edge_mask == 1)[0] stops = np.where(edge_mask == -1)[0] print(starts,stops) #we format groups and drop groups that are too small groups = [group for group in zip(starts,stops) if (group[0]+2 < group[1])] for group in groups: print("start,stop : {} middle : {}".format(group,(group[0]+group[1])/2) ) ``` And the output : ``` [ 5 7 19] [ 6 11 22] start,stop : (7, 11) middle : 9.0 start,stop : (19, 22) middle : 20.5 ```
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.0, 0.0, 0.0, 0.0, 0.33, 0.65, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0] y_smooth = smooth(mydata, 27) print(y_smooth) ``` Output: ``` [ 0.0469 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0684 0.1009 0.1119 0.1119 0.1119 0.1119 0.10475 0.10475 0.09375 0.087 0.065 0.06 0.06 0.06 0.06 0.06 0.06 ] ``` A way to find it in your original data would be: ``` def findGroups(data, minGrpSize=1): startpos = -1 endpos = -1 pospos = [] for idx,v in enumerate(mydata): if v > 0 and startpos == -1: startpos = idx elif v == 0.0: if startpos > -1: if idx < (len(mydata)-1) and mydata[idx+1] != 0.0: pass # ignore one 0.0 in a run else: endpos = idx if startpos > -1: if endpos >-1 or idx == len(mydata)-1: # both set or last one if (endpos - startpos) >= minGrpSize: pospos.append((startpos,endpos)) startpos = -1 endpos = -1 return pospos pos = findGroups(mydata,1) print(*map(lambda x: sum(x) // len(x), pos)) pos = findGroups(mydata,3) print(*map(lambda x: sum(x) // len(x), pos)) pos = findGroups(mydata,5) print(*map(lambda x: sum(x) // len(x), pos)) ``` Output: ``` 8 20 8 20 8 ```
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 + " " + aa + " " + bb) ``` Last line from file is working
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 : ``` import numpy as np 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] arr = np.array(mydata) mask = (arr!=0).astype(np.int) #array that contains 1 for every non zero value, zero other wise padded_mask = np.pad(mask,(1,),"constant") #add a zero at the start and at the end to handle edge cases edge_mask = padded_mask[1:] - padded_mask[:-1] #diff between a value and the following one #if there's a 1 in edge mask it's a group start #if there's a -1 it's a group stop #where gives us the index of those starts and stops starts = np.where(edge_mask == 1)[0] stops = np.where(edge_mask == -1)[0] print(starts,stops) #we format groups and drop groups that are too small groups = [group for group in zip(starts,stops) if (group[0]+2 < group[1])] for group in groups: print("start,stop : {} middle : {}".format(group,(group[0]+group[1])/2) ) ``` And the output : ``` [ 5 7 19] [ 6 11 22] start,stop : (7, 11) middle : 9.0 start,stop : (19, 22) middle : 20.5 ```
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: if mydata[i] and not mydata[i - 1]: last_start = i in_group = 1 else: # a group continued. if mydata[i]: last_end = i elif last_end - last_start > 1: # we have a group i.e. not single non-zero value mid_point = (last_end - last_start) + last_start groups.append(((last_end - last_start)//2) + last_start) last_start, last_end, in_group = (0, 0, 0) else: # it was just a single non-zero. last_start, last_end, in_group = (0, 0, 0) print(groups) ``` Output: ``` [8, 20] ```
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 + " " + aa + " " + bb) ``` Last line from file is working
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 : ``` import numpy as np 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] arr = np.array(mydata) mask = (arr!=0).astype(np.int) #array that contains 1 for every non zero value, zero other wise padded_mask = np.pad(mask,(1,),"constant") #add a zero at the start and at the end to handle edge cases edge_mask = padded_mask[1:] - padded_mask[:-1] #diff between a value and the following one #if there's a 1 in edge mask it's a group start #if there's a -1 it's a group stop #where gives us the index of those starts and stops starts = np.where(edge_mask == 1)[0] stops = np.where(edge_mask == -1)[0] print(starts,stops) #we format groups and drop groups that are too small groups = [group for group in zip(starts,stops) if (group[0]+2 < group[1])] for group in groups: print("start,stop : {} middle : {}".format(group,(group[0]+group[1])/2) ) ``` And the output : ``` [ 5 7 19] [ 6 11 22] start,stop : (7, 11) middle : 9.0 start,stop : (19, 22) middle : 20.5 ```
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.0, 0.0, 0.0]) # Find transitions between zero and nonzero non_zeros = input_data > 0 changes = np.ediff1d(non_zeros, to_begin=not non_zeros[0], to_end=not non_zeros[-1]) change_idxs = np.nonzero(changes)[0] # Filter out small holes holes = change_idxs.reshape(change_idxs.size//2, 2) hole_sizes = holes[:, 1]-holes[:, 0] big_holes = holes[hole_sizes > 1] kept_change_idxs = np.r_[0, big_holes.flatten(), input_data.size] # Get midpoints of big intervals intervals = kept_change_idxs.reshape(kept_change_idxs.size//2, 2) big_intervals = intervals[intervals[:, 1]-intervals[:, 0] >= 3] print((big_intervals[:, 0]+big_intervals[:, 1])//2) ```
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 + " " + aa + " " + bb) ``` Last line from file is working
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.0, 0.0, 0.0, 0.0, 0.33, 0.65, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0] y_smooth = smooth(mydata, 27) print(y_smooth) ``` Output: ``` [ 0.0469 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0684 0.1009 0.1119 0.1119 0.1119 0.1119 0.10475 0.10475 0.09375 0.087 0.065 0.06 0.06 0.06 0.06 0.06 0.06 ] ``` A way to find it in your original data would be: ``` def findGroups(data, minGrpSize=1): startpos = -1 endpos = -1 pospos = [] for idx,v in enumerate(mydata): if v > 0 and startpos == -1: startpos = idx elif v == 0.0: if startpos > -1: if idx < (len(mydata)-1) and mydata[idx+1] != 0.0: pass # ignore one 0.0 in a run else: endpos = idx if startpos > -1: if endpos >-1 or idx == len(mydata)-1: # both set or last one if (endpos - startpos) >= minGrpSize: pospos.append((startpos,endpos)) startpos = -1 endpos = -1 return pospos pos = findGroups(mydata,1) print(*map(lambda x: sum(x) // len(x), pos)) pos = findGroups(mydata,3) print(*map(lambda x: sum(x) // len(x), pos)) pos = findGroups(mydata,5) print(*map(lambda x: sum(x) // len(x), pos)) ``` Output: ``` 8 20 8 20 8 ```
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: if mydata[i] and not mydata[i - 1]: last_start = i in_group = 1 else: # a group continued. if mydata[i]: last_end = i elif last_end - last_start > 1: # we have a group i.e. not single non-zero value mid_point = (last_end - last_start) + last_start groups.append(((last_end - last_start)//2) + last_start) last_start, last_end, in_group = (0, 0, 0) else: # it was just a single non-zero. last_start, last_end, in_group = (0, 0, 0) print(groups) ``` Output: ``` [8, 20] ```
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 + " " + aa + " " + bb) ``` Last line from file is working
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.0, 0.0, 0.0, 0.0, 0.33, 0.65, 0.22, 0.0, 0.0, 0.0, 0.0, 0.0] y_smooth = smooth(mydata, 27) print(y_smooth) ``` Output: ``` [ 0.0469 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0519 0.0684 0.1009 0.1119 0.1119 0.1119 0.1119 0.10475 0.10475 0.09375 0.087 0.065 0.06 0.06 0.06 0.06 0.06 0.06 ] ``` A way to find it in your original data would be: ``` def findGroups(data, minGrpSize=1): startpos = -1 endpos = -1 pospos = [] for idx,v in enumerate(mydata): if v > 0 and startpos == -1: startpos = idx elif v == 0.0: if startpos > -1: if idx < (len(mydata)-1) and mydata[idx+1] != 0.0: pass # ignore one 0.0 in a run else: endpos = idx if startpos > -1: if endpos >-1 or idx == len(mydata)-1: # both set or last one if (endpos - startpos) >= minGrpSize: pospos.append((startpos,endpos)) startpos = -1 endpos = -1 return pospos pos = findGroups(mydata,1) print(*map(lambda x: sum(x) // len(x), pos)) pos = findGroups(mydata,3) print(*map(lambda x: sum(x) // len(x), pos)) pos = findGroups(mydata,5) print(*map(lambda x: sum(x) // len(x), pos)) ``` Output: ``` 8 20 8 20 8 ```
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.0, 0.0, 0.0]) # Find transitions between zero and nonzero non_zeros = input_data > 0 changes = np.ediff1d(non_zeros, to_begin=not non_zeros[0], to_end=not non_zeros[-1]) change_idxs = np.nonzero(changes)[0] # Filter out small holes holes = change_idxs.reshape(change_idxs.size//2, 2) hole_sizes = holes[:, 1]-holes[:, 0] big_holes = holes[hole_sizes > 1] kept_change_idxs = np.r_[0, big_holes.flatten(), input_data.size] # Get midpoints of big intervals intervals = kept_change_idxs.reshape(kept_change_idxs.size//2, 2) big_intervals = intervals[intervals[:, 1]-intervals[:, 0] >= 3] print((big_intervals[:, 0]+big_intervals[:, 1])//2) ```
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 have a simple code to read the analog input? The code I used is the following: ``` #!/usr/bin/env python # Written by Limor "Ladyada" Fried for Adafruit Industries, (c) 2015 # This code is released into the public domain import time import os import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) DEBUG = 1 # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7) def readadc(adcnum, clockpin, mosipin, misopin, cspin): if ((adcnum > 7) or (adcnum < 0)): return -1 GPIO.output(cspin, True) GPIO.output(clockpin, False) # start clock low GPIO.output(cspin, False) # bring CS low commandout = adcnum commandout |= 0x18 # start bit + single-ended bit commandout <<= 3 # we only need to send 5 bits here for i in range(5): if (commandout & 0x80): GPIO.output(mosipin, True) else: GPIO.output(mosipin, False) commandout <<= 1 GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout = 0 # read in one empty bit, one null bit and 10 ADC bits for i in range(12): GPIO.output(clockpin, True) GPIO.output(clockpin, False) adcout <<= 1 if (GPIO.input(misopin)): adcout |= 0x1 GPIO.output(cspin, True) adcout >>= 1 # first bit is 'null' so drop it return adcout # change these as desired - they're the pins connected from the # SPI port on the ADC to the Cobbler SPICLK = 18 SPIMISO = 23 SPIMOSI = 24 SPICS = 25 # set up the SPI interface pins GPIO.setup(SPIMOSI, GPIO.OUT) GPIO.setup(SPIMISO, GPIO.IN) GPIO.setup(SPICLK, GPIO.OUT) GPIO.setup(SPICS, GPIO.OUT) # 10k trim pot connected to adc #0 potentiometer_adc = 0; last_read = 0 # this keeps track of the last potentiometer value tolerance = 5 # to keep from being jittery we'll only change # volume when the pot has moved more than 5 'counts' while True: # we'll assume that the pot didn't move trim_pot_changed = False # read the analog pin trim_pot = readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS) # how much has it changed since the last read? pot_adjust = abs(trim_pot - last_read) if DEBUG: print "trim_pot:", trim_pot print "pot_adjust:", pot_adjust print "last_read", last_read if ( pot_adjust > tolerance ): trim_pot_changed = True if DEBUG: print "trim_pot_changed", trim_pot_changed if ( trim_pot_changed ): set_volume = trim_pot / 10.24 # convert 10bit adc0 (0-1024) trim pot read into 0-100 volume level set_volume = round(set_volume) # round out decimal value set_volume = int(set_volume) # cast volume as integer print 'Volume = {volume}%' .format(volume = set_volume) set_vol_cmd = 'sudo amixer cset numid=1 -- {volume}% > /dev/null' .format(volume = set_volume) os.system(set_vol_cmd) # set volume if DEBUG: print "set_volume", set_volume print "tri_pot_changed", set_volume # save the potentiometer reading for the next loop last_read = trim_pot # hang out and do nothing for a half second time.sleep(0.5) ```
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 values for **API Access>Client ID for web applications**. The **Google Drive SDK> OAuth Client ID** has also been set variously to the Drive SDK and web app Client IDs. What am I doing wrong?
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). Switch the Drive API service on for the project and try again. @lurking\_googlers I think a lot of people will fall for this, doesn't it make sense to enable the API when the SDK is enabled?
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 a piechart or any other different kind of graphic visualization. Are there any APIs available to create such a visualization or do i need to use any web service?
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 bindings for it. You would have to look at the documentation if it can create this style of graph.
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 a piechart or any other different kind of graphic visualization. Are there any APIs available to create such a visualization or do i need to use any web service?
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 bindings for it. You would have to look at the documentation if it can create this style of graph.
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 a piechart or any other different kind of graphic visualization. Are there any APIs available to create such a visualization or do i need to use any web service?
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-diagram-in-python)) and one interactive (<http://bost.ocks.org/mike/uberdata/>) which is more like the Census graphic.
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 bindings for it. You would have to look at the documentation if it can create this style of graph.
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 a piechart or any other different kind of graphic visualization. Are there any APIs available to create such a visualization or do i need to use any web service?
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 a piechart or any other different kind of graphic visualization. Are there any APIs available to create such a visualization or do i need to use any web service?
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-diagram-in-python)) and one interactive (<http://bost.ocks.org/mike/uberdata/>) which is more like the Census graphic.
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 project.html, loaded by my django apps views.py) now uses a form (instance of ModelForm) which asks the user to type in a "project" name, such as My Project. Normally, such an HTML form would use a Submit button, but because this is a Wizard, I need the Next button to act as the Submit button, hiding the Submit button entirely. Also, the arrow icons appear after the form ends. How would you do this? Sure, I could use jquery, but is there a better pythonic or django way? Some code: ``` #project.html {% extends "base.html" %} {% load i18n %} <h3><span>{% trans 'Project details' %}</span></h3> <p>{% trans 'What is the name of this project?' %} <form method="post" action=""> {{ form.as_table }} <input type="submit" value="Submit"/> </form> </p> {% endblock %} {% block buttonbar %} <a href="/"><img src="/static/img/Button-Previous-icon-50.png" width="50" height="50" alt="Previous"><span>{% trans 'Previous' %}</span></a> <a href="/profile"><img src="/static/img/Button-Next-icon-50.png" width="50" height="50" alt="Next button"><span>{% trans 'Next' %}</span></a> {% endblock %} ``` Thanks!
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 a module for FFT in python, and it already worked fine for 1D with helps from rosetta Code's site. ``` from cmath import exp, pi from math import log, ceil def fft(f): N = len(f) if N <= 1: return f even = fft(f[0::2]) odd = fft(f[1::2]) return [even[k] + exp(-2j*pi*k/N)*odd[k] for k in xrange(N/2)] + \ [even[k] - exp(-2j*pi*k/N)*odd[k] for k in xrange(N/2)] def pad(f): n = len(f) N = 2 ** int(ceil(log(n, 2))) F = f + [0] * (N - n) return F, n def unpad(F, n): return F[0 : n] def pad2(f): m, n = len(f), len(f[0]) M, N = 2 ** int(ceil(log(m, 2))), 2 ** int(ceil(log(n, 2))) F = [ [0]*N for _ in xrange(M) ] for i in range(0, m): for j in range(0, n): F[i][j] = f[i][j] return F, m, n def fft1D(f): Fu, n = pad(f) return fft(Fu), n def fft2D(f): F, m, n = pad2(f) M, N = len(F), len(F[0]) Fuv = [ [0]*N for _ in xrange(M) ] for i in range(0, M): Fxv = fft(F[i]) for j in range(0, N): Fuv[i][j] = (fft(Fxv))[j] return Fuv, [m, n] ``` I called this module with tis code: ``` from FFT import * f= [0, 2, 3, 4] F = fft1D(f) print f, F X, s = fft2D([[1,2,1,1],[2,1,2,2],[0,1,1,0], [0,1,1,1]]) for i in range(0, len(X)): print X[i] ``` It's output is : ``` [0, 2, 3, 4] ([(9+0j), (-3+2j), (-3+0j), (-3-2j)], 4) [(4+0j), (4-2.4492935982947064e-16j), (4+0j), (8+2.4492935982947064e-16j)] [(8+0j), (8+2.4492935982947064e-16j), (8+0j), (4-2.4492935982947064e-16j)] [0j, -2.33486982377251e-16j, (4+0j), (4+2.33486982377251e-16j)] [0j, (4+0j), (4+0j), (4+0j)] ``` The first one for 1d is fine as i verified result with Matlab's output but for 2nd one the Matlab's output is: ``` >> fft([1,2,1,1;2,1,2,2;0,1,1,0;0,1,1,1]) ans = 3.0000 5.0000 5.0000 4.0000 1.0000 - 2.0000i 1.0000 0 - 1.0000i 1.0000 - 1.0000i -1.0000 1.0000 -1.0000 -2.0000 1.0000 + 2.0000i 1.0000 0 + 1.0000i 1.0000 + 1.0000i ``` The output is different ,which means i'm doing something wrong in the code's logic.Please help without bothering as i have not studied FFT formally till now so i'm not able to understand the mathematics copmpletely, maybe after i studied it, i may figure the problem out.
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) -> f'(k, y) FT(f'(k, y), y) -> f''(k, w) ``` So what you want to do is take the FFT of each *row* (than is do N 1D FFTs) and shove the results into a new array (which takes you from `f(x, y) -> f'(k, y)`). Then take the FFT of each *column* of that result array (doing M 1D FFTs) and shove those results into another new array (which takes you from `f'(k, y) -> f''(k, w)`.
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 as script, I do get following error. ``` vsd@homeworks:~/homework/ws-python/movie-database$ sh Launcher.py from: can't read /var/mail/ui.MovieManager ``` I am not able to identify why this script is not picking up `MovieManager` module under the current folder? However when I execute command `python Launcher.py`, It works well.
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 to work your file needs to be marked as executable, though.
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 test case. Each case contains a pair of integers a and b where -1000000 <= a, b <= 1000000. The numbers are separated by a space. > > > Output > > > For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format. > > > Sample Input > > > -1000000 9 > > > Sample Output > > > -999,991 > > > This is my code below: ``` if __name__ == "__main__": aline = input() astr,bstr = aline.strip().split() a,b = int(astr),int(bstr) sum = a + b sumstr= str(sum) result = '' while sumstr: sumstr, aslice = sumstr[:-3], sumstr[-3:] if sumstr: result = ',' + aslice + result else: result = aslice + result print(result) ``` And the test result turn out to be : > > 时间(Time) 结果(test result) 得分(score) 题目(question number) > > > 语言(programe language) 用时(ms)[time consume] 内存(kB)[memory] 用户[user] > > > 8月22日 15:46 **部分正确[Partial Correct]**(Why?!!!) 11 1001 > > > Python (python3 3.4.2) 25 3184 polar9527 > > > 测试点[test point] 结果[result] 用时(ms)[time consume] 内存(kB)[memory] 得分[score]/满分[full credit] > > > 0 答案错误[wrong] 25 3056 0/9 > > > 1 答案正确[correct] 19 3056 1/1 > > > 10 答案正确[correct] 18 3184 1/1 > > > 11 答案正确[correct] 19 3176 1/1 > > > 2 答案正确[correct] 17 3180 1/1 > > > 3 答案正确[correct] 16 3056 1/1 > > > 4 答案正确[correct] 14 3184 1/1 > > > 5 答案正确[correct] 17 3056 1/1 > > > 6 答案正确[correct] 19 3168 1/1 > > > 7 答案正确[correct] 22 3184 1/1 > > > 8 答案正确[correct] 21 3164 1/1 > > > 9 答案正确[correct] 15 3184 1/1 > > >
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() astr,bstr = aline.strip().split() a,b = int(astr),int(bstr) sum = a + b print('{:,}'.format(sum))`
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__() self.initUI() def initUI(self): exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(QtGui.qApp.quit) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAction) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Menubar') self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` Excuse me if the indentation wouldn't be correct but I think it is.
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 your application.
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__() self.initUI() def initUI(self): exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(QtGui.qApp.quit) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAction) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Menubar') self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` Excuse me if the indentation wouldn't be correct but I think it is.
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__() self.initUI() def initUI(self): exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(QtGui.qApp.quit) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAction) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Menubar') self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` Excuse me if the indentation wouldn't be correct but I think it is.
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__() self.initUI() def initUI(self): exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(QtGui.qApp.quit) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAction) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Menubar') self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` Excuse me if the indentation wouldn't be correct but I think it is.
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 your application.
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__() self.initUI() def initUI(self): exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(QtGui.qApp.quit) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAction) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Menubar') self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` Excuse me if the indentation wouldn't be correct but I think it is.
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 your application.
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__() self.initUI() def initUI(self): exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(QtGui.qApp.quit) self.statusBar() menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(exitAction) self.setGeometry(300, 300, 300, 200) self.setWindowTitle('Menubar') self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main() ``` Excuse me if the indentation wouldn't be correct but I think it is.
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 rid of the error sign. Best regards, Peter
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 that communication (if so, usually there are entries in your error log -- see: <http://pydev.org/faq.html#when_i_do_a_code_completion_pydev_hangs_what_can> for more details).
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 rid of the error sign. Best regards, Peter
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 that communication (if so, usually there are entries in your error log -- see: <http://pydev.org/faq.html#when_i_do_a_code_completion_pydev_hangs_what_can> for more details).
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`, which doesn't collapse the math namespace, but allows you to refer to attributes of the math module by prepending math, followed by the dot and then the attribute name 2. Or use the attributes without prepending anything, as they are copied in your namespace and you can use them as if you had defined them in your script yourself. For example. 1. For the first case something like `math.sqrt()` should do 2. For the second case `sqrt()` should do.
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 rid of the error sign. Best regards, Peter
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 that communication (if so, usually there are entries in your error log -- see: <http://pydev.org/faq.html#when_i_do_a_code_completion_pydev_hangs_what_can> for more details).
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 function wash't properly registered.
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 glob import os P_Result_File_Path ="Path_To_the_Result_File" Folder_path =r'Path_To_my_numpy_files' os.chdir(Folder_path) npfiles= glob.glob("*.npy") npfiles.sort(key=os.path.getmtime) print (npfiles) loadedFiles = [np.load(npf) for npf in npfiles] PArray=np.concatenate(loadedFiles, axis=0 ) np.save(Power_Result_File_Path, PArray) ``` `P_Result_File_Path` file has a huge size, so I need to save it in a local server, the problem in this case that `Path_To_the_Result_File= /home/user/result.npy`, so this path is unknown, I need to connect to this server in order to create and put the resulted file.
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/laravel-echo/dist` and copy `echo.js` in your Laravel public folder (e.g. `your-project-folder/public/lib/js`). I use Grunt, so I automated this process, it's just for sake of simplicity. 3. Add the refer in your Blade template: `<script type="text/javascript" src="{{asset('lib/js/echo.js')}}"></script>` 4. At the beginning of your Blade Template, in the point marked below, insert this line of code (it's just to avoid a JS error using echo.js directly): ``` <script> window.Laravel = <?php echo json_encode([ 'csrfToken' => csrf_token(), ]); ?>; var module = { }; /* <-----THIS LINE */ </script> ``` 5. In your footer, after the inclusion of all the JS files, call Laravel Echo this way: ``` <script> window.Echo = new Echo({ broadcaster: 'pusher', key: '{{env("PUSHER_KEY")}}', cluster: 'eu', encrypted: true, authEndpoint: '{{env("APP_URL")}}/broadcasting/auth' }); </script> ``` 6. If you want to listen for a channel, e.g. the notifications one, you can do it like this: ``` <script> window.Echo.private('App.User.{{Auth::user()->id}}') .notification((notification) => { doSomeAmazingStuff(); }); </script> ```
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 glob import os P_Result_File_Path ="Path_To_the_Result_File" Folder_path =r'Path_To_my_numpy_files' os.chdir(Folder_path) npfiles= glob.glob("*.npy") npfiles.sort(key=os.path.getmtime) print (npfiles) loadedFiles = [np.load(npf) for npf in npfiles] PArray=np.concatenate(loadedFiles, axis=0 ) np.save(Power_Result_File_Path, PArray) ``` `P_Result_File_Path` file has a huge size, so I need to save it in a local server, the problem in this case that `Path_To_the_Result_File= /home/user/result.npy`, so this path is unknown, I need to connect to this server in order to create and put the resulted file.
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/pusher-js/dist*** and search for ***pusher.worker.js***, rename it to ***pusher.js*** and copy ***your-project-folder/public/js*** 4. To the new ***pusher.js renamed*** add "export" before the "var Pusher" in the first line of code like so : > > export var Pusher = > > > Or you can just use this echo.js and pusher.js file from my repository <https://github.com/HarenaGit/laravel-websockets-without-vuejs> 5. To where you want to listening for changes, you can listen like this ```html <script type="module"> import Echo from '{{asset('js/echo.js')}}' import {Pusher} from '{{asset('js/pusher.js')}}' window.Pusher = Pusher window.Echo = new Echo({ broadcaster: 'pusher', key: 'server-notification-key', wsHost: window.location.hostname, wsPort: 6001, forceTLS: false, disableStats: true, }); window.Echo.channel('your-channel') .listen('your-event-class', (e) => { console.log(e) }) console.log("websokets in use") </script> ```
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 glob import os P_Result_File_Path ="Path_To_the_Result_File" Folder_path =r'Path_To_my_numpy_files' os.chdir(Folder_path) npfiles= glob.glob("*.npy") npfiles.sort(key=os.path.getmtime) print (npfiles) loadedFiles = [np.load(npf) for npf in npfiles] PArray=np.concatenate(loadedFiles, axis=0 ) np.save(Power_Result_File_Path, PArray) ``` `P_Result_File_Path` file has a huge size, so I need to save it in a local server, the problem in this case that `Path_To_the_Result_File= /home/user/result.npy`, so this path is unknown, I need to connect to this server in order to create and put the resulted file.
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/laravel-echo/dist` and copy `echo.js` in your Laravel public folder (e.g. `your-project-folder/public/lib/js`). I use Grunt, so I automated this process, it's just for sake of simplicity. 3. Add the refer in your Blade template: `<script type="text/javascript" src="{{asset('lib/js/echo.js')}}"></script>` 4. At the beginning of your Blade Template, in the point marked below, insert this line of code (it's just to avoid a JS error using echo.js directly): ``` <script> window.Laravel = <?php echo json_encode([ 'csrfToken' => csrf_token(), ]); ?>; var module = { }; /* <-----THIS LINE */ </script> ``` 5. In your footer, after the inclusion of all the JS files, call Laravel Echo this way: ``` <script> window.Echo = new Echo({ broadcaster: 'pusher', key: '{{env("PUSHER_KEY")}}', cluster: 'eu', encrypted: true, authEndpoint: '{{env("APP_URL")}}/broadcasting/auth' }); </script> ``` 6. If you want to listen for a channel, e.g. the notifications one, you can do it like this: ``` <script> window.Echo.private('App.User.{{Auth::user()->id}}') .notification((notification) => { doSomeAmazingStuff(); }); </script> ```
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/pusher-js/dist*** and search for ***pusher.worker.js***, rename it to ***pusher.js*** and copy ***your-project-folder/public/js*** 4. To the new ***pusher.js renamed*** add "export" before the "var Pusher" in the first line of code like so : > > export var Pusher = > > > Or you can just use this echo.js and pusher.js file from my repository <https://github.com/HarenaGit/laravel-websockets-without-vuejs> 5. To where you want to listening for changes, you can listen like this ```html <script type="module"> import Echo from '{{asset('js/echo.js')}}' import {Pusher} from '{{asset('js/pusher.js')}}' window.Pusher = Pusher window.Echo = new Echo({ broadcaster: 'pusher', key: 'server-notification-key', wsHost: window.location.hostname, wsPort: 6001, forceTLS: false, disableStats: true, }); window.Echo.channel('your-channel') .listen('your-event-class', (e) => { console.log(e) }) console.log("websokets in use") </script> ```
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: csv_reader = csv.DictReader(csvf) primary_key_column_name = unique_column_name.lstrip() # remove leading space in string # Convert each row into a dictionary # and add it to data for rows in csv_reader: key = rows[primary_key_column_name] data[key] = rows # Open a json writer, and use the json.dumps() # function to dump data with open(json_file_path, 'w', encoding='utf-8') as jsonf: jsonf.write(json.dumps(data, indent=4)) return None ``` The code above will convert ALL the rows in the CSV file into json file. I want to convert only the last X number of rows into json. I am using python v3.
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'} ``` Basically add (change) these lines into your code: ``` from itertools import islice x = 5 data = dict(islice(data.items(), len(data) - x, len(data))) # Open a json writer, and use the json.dumps() # function to dump data with open(json_file_path, 'w', encoding='utf-8') as jsonf: jsonf.write(json.dumps(data, indent=4)) ```
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 = {} # Open a csv reader called DictReader with open(csv_file_path, encoding='utf-8') as csvf: csv_reader = csv.DictReader(csvf) primary_key_column_name = unique_column_name.lstrip() # remove leading space in string # Convert each row into a dictionary # and add it to data for rows in csv_reader: key = rows[primary_key_column_name] data[key] = rows data = dict(islice(data.items(), len(data) - no_of_rows_to_extract, len(data))) # Open a json writer, and use the json.dumps() # function to dump data with open(json_file_path, 'w', encoding='utf-8') as jsonf: jsonf.write(json.dumps(data, indent=4)) return None ```
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 dataframes? (without saving to another file format like csv) When would it be advantageous to use Julia Dataframes than Pandas other than extremely large datasets and running things with many loops(like neural networks)?
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 just a wrapper for pandas but you might be able to execute multiple functions using julia's parallel features. As for the which is better so far `pandas` has faster I/O according to this [reading csv in Julia is slow compared to Python](https://stackoverflow.com/questions/21890893/reading-csv-in-julia-is-slow-compared-to-python)
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 amazing functionality that I'm only beginning to understand. With large datasets, say over a couple gigs, both packages are pretty slow but again Pandas seems to have a slight edge (by no means would I consider my benchmarking to be definitive). Without a more nuanced understanding of what you are trying to achieve, it's difficult for me to envision a circumstance where you would even want to call a Pandas function while working with a Julia DataFrame or vice versa. Unless you are doing something pretty cerebral or working with really large datasets, I can't see going too wrong with either. When you say "output the data" what do you mean? Couldn't you write the Pandas data object to a file and then open/manipulate that file in a Julia DataFrame (as you mention)? Again, unless you have a really good machine reading gigs of data into either pandas or a Julia DataFrame is tedious and can be prohibitively slow.
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_Class>python APlusB.py 3 5<- pressed enter after this ``` but output is not coming until I hit ctrl+C (in windows) ``` C:\Python_Class>python APlusB.py 3 5 ['3', '5'] 8 Traceback (most recent call last): File "APlusB.py", line 20, in <module> print(a + b) KeyboardInterrupt ```
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 terminal treats the EOF correctly if it's not at the start of a line.) If you just want to read input until a newline, use [`input()`](https://docs.python.org/3/library/functions.html#input) instead of `sys.stdin.read()`.
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 asks for input is simply `input()`
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_Class>python APlusB.py 3 5<- pressed enter after this ``` but output is not coming until I hit ctrl+C (in windows) ``` C:\Python_Class>python APlusB.py 3 5 ['3', '5'] 8 Traceback (most recent call last): File "APlusB.py", line 20, in <module> print(a + b) KeyboardInterrupt ```
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 terminal treats the EOF correctly if it's not at the start of a line.) If you just want to read input until a newline, use [`input()`](https://docs.python.org/3/library/functions.html#input) instead of `sys.stdin.read()`.
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" log math's E -- logs (*2.718281828459*) set math's E to 10 log math's E -- logs (*10*) ``` So I tried searching for Applescript constants and came across [the official documentation](https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_classes.html#//apple_ref/doc/uid/TP40000983-CH1g-BBCECDHC), where it is stated, that `You cannot define constants in scripts; constants can be defined only by applications and by AppleScript.` Is there a clever workaround for this or would I have to write a .sdef file for this sort of thing? ### EDIT: I have now also tried this: ```applescript log pi -- logs (*3.14159265359*) set pi to 10 log pi -- logs (*10*) ``` `pi` is an Applescript constant. If you run the script a second time without compiling again, it looks something like this: ```applescript log pi -- logs (*10*) set pi to 10 log pi -- logs (*10*) ``` I don't want to mimic this behavior, but more so the behavior of other constants like `ask`, `yes`, `no`, etc. which complain, even if you try to set them to themselves.
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 code. For instance, if you want to assign constant values to the terms 'tau', 'gamma', and 'lambda', you define an enumeration like so: ``` <enumeration name="Constants" code="CVal" description="defined constant values."> <enumerator name="tau" code="tau&" description="tau constant."/> <enumerator name="gamma" code="gam&" description="gamma constant."/> <enumerator name="lambda" code="lmd!" description="lambda constant."/> </enumeration> ``` Then in code have a handler to resolve them, and call it when needed: ``` to resolveConstant(cnst) if cnst is tau then return pi/2 else if cnst is gamma then return 17.4683 else if cnst is lambda then return "wallabies forever" else return missing value end end resolveConstant ``` --- Create handlers for each of your constants, and call them as functions: ``` on tau() return pi/2 end tau set x to 2 * tau() * 3^2 -- x = 28.2743 ``` --- If you want *true* constants, you're going to have to shift away from a script library and code a faceless background app (like System Events or Image Events). From the perspective of an end-user it won't make much difference, save that they'll have to authorize having the application run, but it might mean a serious increase in labor on your end.
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 end constantPi get constantPi() --> 3.14159265359 set constantPi() to 10 --> Access not allowed ``` Note: do not remove parentheses in the last code line, otherways you create additional variable constantPi instead of your "constant"
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 ' ' around it so it turns out like INSERT INTO table\_name('12', ..., ..., ...) ... instead of INSERT INTO table\_name(12, ..., ..., ...) ... how can I make the string formatter leave the quotes out or remove them or something? It is causing a syntax error around the 12 because it doesn't need the single quotes.
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 write SQL query as multi-lines. * Also it allows you to use single and double qoutes without escaping from them. (It is beneficiary for complex SQL Queries but you don't need that on your case)
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}, {2}, {2}, {4})".format( table_name, exchange_rate, buy_rate, sell_rate, date) print x >INSERT INTO myTable (price, buy, sell, timestamp) VALUES (1, 2, 2, 123) ```
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 contain a subsequence Q that obeys certain rules. Now, let's suppose that I am searching for the subsequence `"abc"`. I want to match a substring of S that contains `'a'` followed at some point by `'b'` followed at some point by `'c'` with the restriction that no `'a'` follows `'a'`, and no `'a'` or `'b'` follows `'b'`. The regex I am using is as follows (in python): ``` regex = re.compile(r'a[^a]*?b[^ab]*?c') match = re.finditer(regex, string) for m in match: print m.group(0) ``` To me this breaks down and reads as follows: `a[^a]*?b`: `'a'` followed the smallest # of characters not including `'a'` and terminating with a `'b'` `[^ab]*?c`: the smallest # of characters not including `'a'` or `'b'` and terminating with a `'c'` So putting this all together, I assumed that I would match non-overlapping substrings of S that contain the subsequence "abc" that obeys my rules of exclusion. This **works fine** for something like: `S = "aqwertybwertcaabcc"`, which gives me `"aqwertybwertc"` and `"abc"`, but it **fails** to work for `S = "abbc"`, as in it matches to `"abbc"`.
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 it can to succeed on a string, including matching the literal `b` to a `b` after the first `b`, which is why `"abbc"` is matched. Only by specifically excluding `b` in the first character class can this be avoided and the `b` be made to match only the first `b` after the `a`.
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 ) # ------------------------------ a # 'a' [b-z]*? # [^a] b # 'b' [abd-z]*? # [^c] c # 'c' # Type 2, yours : # ( b or c can be between A,B ) # ( c can be between B,C ) # ------------------------------ a # 'a' [b-z]*? # [^a] b # 'b' [c-z]*? # [^ab] c # 'c' # Type 3 : # ( c can be between A,B ) # ------------------------------ a # 'a' [c-z]*? # [^ab] b # 'b' [d-z]*? # [^abc] c # 'c' # Type 4 : # ( distinct A,B,C ) : # ------------------------------ a # 'a' [d-z]*? # [^abc] b # 'b' [d-z]*? # [^abc] c # '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 code that I have: ``` print(max(declarationWords,key=len)) for word in declarationWords: if len(word) >= 5: declarationWords.remove(word) print(Counter(declarationWords).most_common()) ```
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; public float jumpSpeed = 8f; public float gravity = 9.8f; private float vSpeed = 0f; void Update() { if (Input.GetButton("Fire3")) { transform.Rotate(0, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime, 0); Vector3 vel = transform.forward * Input.GetAxis("Vertical") * runSpeed; if (controller.isGrounded) { vSpeed = 0; if (Input.GetButtonDown("Jump")) { vSpeed = jumpSpeed; } } vSpeed -= gravity * Time.deltaTime; vel.y = vSpeed; controller.Move(vel * Time.deltaTime); } else { speed = walkSpeed; transform.Rotate(0, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime, 0); Vector3 vel = transform.forward * Input.GetAxis("Vertical") * walkSpeed; if (controller.isGrounded) { vSpeed = 0; if (Input.GetButtonDown("Jump")) { vSpeed = jumpSpeed; } } vSpeed -= gravity * Time.deltaTime; vel.y = vSpeed; controller.Move(vel * Time.deltaTime); } ```
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; public float jumpHeight = 4f; if ((Input.GetButtonDown("Jump"))) { Vector3 antigravity = new Vector3(0, Mathf.Sqrt(jumpHeight * -2f * gravity), 0); controller.Move(antigravity); } if ((Input.GetAxis("Horizontal") != 0) || (Input.GetAxis("Vertical") != 0)) { float xInput = Input.GetAxis("Horizontal"); float zInput = Input.GetAxis("Vertical"); float running = Input.GetAxis("Fire3"); Vector3 move = transform.right * xInput + transform.forward * zInput; if (running > 0) { controller.Move((move * runSpeed * Time.deltaTime)); } else { controller.Move(move * walkSpeed * Time.deltaTime); } void Update() { transform.position = new Vector3(0, 15, 0); //Set your player position } } // If this doesn't help, tell me what's the problem. ```
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 code that I have: ``` print(max(declarationWords,key=len)) for word in declarationWords: if len(word) >= 5: declarationWords.remove(word) print(Counter(declarationWords).most_common()) ```
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() instead of Move() on the CharacterController internally if root motion is applied but Y is baked. Only solutions I can see are: 1. Set gravity to Zero in the project settings (not very flexible). 2. Don't bake the Y into your animations with root motion.
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; public float jumpHeight = 4f; if ((Input.GetButtonDown("Jump"))) { Vector3 antigravity = new Vector3(0, Mathf.Sqrt(jumpHeight * -2f * gravity), 0); controller.Move(antigravity); } if ((Input.GetAxis("Horizontal") != 0) || (Input.GetAxis("Vertical") != 0)) { float xInput = Input.GetAxis("Horizontal"); float zInput = Input.GetAxis("Vertical"); float running = Input.GetAxis("Fire3"); Vector3 move = transform.right * xInput + transform.forward * zInput; if (running > 0) { controller.Move((move * runSpeed * Time.deltaTime)); } else { controller.Move(move * walkSpeed * Time.deltaTime); } void Update() { transform.position = new Vector3(0, 15, 0); //Set your player position } } // If this doesn't help, tell me what's the problem. ```
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 code that I have: ``` print(max(declarationWords,key=len)) for word in declarationWords: if len(word) >= 5: declarationWords.remove(word) print(Counter(declarationWords).most_common()) ```
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() instead of Move() on the CharacterController internally if root motion is applied but Y is baked. Only solutions I can see are: 1. Set gravity to Zero in the project settings (not very flexible). 2. Don't bake the Y into your animations with root motion.
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; public float jumpSpeed = 8f; public float gravity = 9.8f; private float vSpeed = 0f; void Update() { if (Input.GetButton("Fire3")) { transform.Rotate(0, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime, 0); Vector3 vel = transform.forward * Input.GetAxis("Vertical") * runSpeed; if (controller.isGrounded) { vSpeed = 0; if (Input.GetButtonDown("Jump")) { vSpeed = jumpSpeed; } } vSpeed -= gravity * Time.deltaTime; vel.y = vSpeed; controller.Move(vel * Time.deltaTime); } else { speed = walkSpeed; transform.Rotate(0, Input.GetAxis("Horizontal") * turnSpeed * Time.deltaTime, 0); Vector3 vel = transform.forward * Input.GetAxis("Vertical") * walkSpeed; if (controller.isGrounded) { vSpeed = 0; if (Input.GetButtonDown("Jump")) { vSpeed = jumpSpeed; } } vSpeed -= gravity * Time.deltaTime; vel.y = vSpeed; controller.Move(vel * Time.deltaTime); } ```
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.0 then 1 else -1 end) ```
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 dict ``` desc = { "name" : "string", "age" : "int", "vol" : "double", "status" : "byte", "limit" : "int" } ``` I need to generate a message to be sent over in the following format : ``` [{"column": "name", "value": {"String": "John"}}, {"column": "age", "value": {"Int": 14}}, {"column": "vol", "value": {"Double": 12132.213}}, {"column": "status", "value": {"Byte": 89}}, {"column": "limit", "value": {"Int": 34}}, {"column": "name", "value": {"String": "Andrew"}}, {"column": "age", "value": {"Int": 23}}, {"column": "vol", "value": {"Double":2121.21}}, {"column": "status", "value": {"Byte": 78}}, {"column": "limit", "value": {"Int": 66}}] ``` I have two functions that generates this : ``` def get_value(data_type, res): if data_type == 'string': return {'String' : res.strip()} elif data_type == 'byte' : return {'Byte' : ord(res[0])} elif data_type == 'int': return {'Int' : int(res)} elif data_type == 'double': return {'Double' : float(res)} def generate_message(data, fields, desc): result = [] for row in data: for field, res in zip(fields, row): data_type = desc[field] val = {'column' : field, 'value' : get_value(data_type, res)} result.append(val) return result ``` However, the data is really large with a huge number of tuples (~200,000). It takes a lot of time to generate the above message format for each of them. Is there an efficient way of doing this. P.S Need such a message as i am sending this on a queue and the consumer is a C++ client that needs the type information.
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. But it should resolve your chicken and egg problem.
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 dict ``` desc = { "name" : "string", "age" : "int", "vol" : "double", "status" : "byte", "limit" : "int" } ``` I need to generate a message to be sent over in the following format : ``` [{"column": "name", "value": {"String": "John"}}, {"column": "age", "value": {"Int": 14}}, {"column": "vol", "value": {"Double": 12132.213}}, {"column": "status", "value": {"Byte": 89}}, {"column": "limit", "value": {"Int": 34}}, {"column": "name", "value": {"String": "Andrew"}}, {"column": "age", "value": {"Int": 23}}, {"column": "vol", "value": {"Double":2121.21}}, {"column": "status", "value": {"Byte": 78}}, {"column": "limit", "value": {"Int": 66}}] ``` I have two functions that generates this : ``` def get_value(data_type, res): if data_type == 'string': return {'String' : res.strip()} elif data_type == 'byte' : return {'Byte' : ord(res[0])} elif data_type == 'int': return {'Int' : int(res)} elif data_type == 'double': return {'Double' : float(res)} def generate_message(data, fields, desc): result = [] for row in data: for field, res in zip(fields, row): data_type = desc[field] val = {'column' : field, 'value' : get_value(data_type, res)} result.append(val) return result ``` However, the data is really large with a huge number of tuples (~200,000). It takes a lot of time to generate the above message format for each of them. Is there an efficient way of doing this. P.S Need such a message as i am sending this on a queue and the consumer is a C++ client that needs the type information.
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. But it should resolve your chicken and egg problem.
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 dict ``` desc = { "name" : "string", "age" : "int", "vol" : "double", "status" : "byte", "limit" : "int" } ``` I need to generate a message to be sent over in the following format : ``` [{"column": "name", "value": {"String": "John"}}, {"column": "age", "value": {"Int": 14}}, {"column": "vol", "value": {"Double": 12132.213}}, {"column": "status", "value": {"Byte": 89}}, {"column": "limit", "value": {"Int": 34}}, {"column": "name", "value": {"String": "Andrew"}}, {"column": "age", "value": {"Int": 23}}, {"column": "vol", "value": {"Double":2121.21}}, {"column": "status", "value": {"Byte": 78}}, {"column": "limit", "value": {"Int": 66}}] ``` I have two functions that generates this : ``` def get_value(data_type, res): if data_type == 'string': return {'String' : res.strip()} elif data_type == 'byte' : return {'Byte' : ord(res[0])} elif data_type == 'int': return {'Int' : int(res)} elif data_type == 'double': return {'Double' : float(res)} def generate_message(data, fields, desc): result = [] for row in data: for field, res in zip(fields, row): data_type = desc[field] val = {'column' : field, 'value' : get_value(data_type, res)} result.append(val) return result ``` However, the data is really large with a huge number of tuples (~200,000). It takes a lot of time to generate the above message format for each of them. Is there an efficient way of doing this. P.S Need such a message as i am sending this on a queue and the consumer is a C++ client that needs the type information.
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. But it should resolve your chicken and egg problem.
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 generated `.d.ts`; * The TSC version which generates your code is not supposed to be another moving part for the tests AND your consumers. You would test the generated output, not your source against many TSC versions. * By reducing the "moving parts" boundary by including the .js and .d.ts, you gain much more (= predictability) than what you lose (git history bloat).
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 dict ``` desc = { "name" : "string", "age" : "int", "vol" : "double", "status" : "byte", "limit" : "int" } ``` I need to generate a message to be sent over in the following format : ``` [{"column": "name", "value": {"String": "John"}}, {"column": "age", "value": {"Int": 14}}, {"column": "vol", "value": {"Double": 12132.213}}, {"column": "status", "value": {"Byte": 89}}, {"column": "limit", "value": {"Int": 34}}, {"column": "name", "value": {"String": "Andrew"}}, {"column": "age", "value": {"Int": 23}}, {"column": "vol", "value": {"Double":2121.21}}, {"column": "status", "value": {"Byte": 78}}, {"column": "limit", "value": {"Int": 66}}] ``` I have two functions that generates this : ``` def get_value(data_type, res): if data_type == 'string': return {'String' : res.strip()} elif data_type == 'byte' : return {'Byte' : ord(res[0])} elif data_type == 'int': return {'Int' : int(res)} elif data_type == 'double': return {'Double' : float(res)} def generate_message(data, fields, desc): result = [] for row in data: for field, res in zip(fields, row): data_type = desc[field] val = {'column' : field, 'value' : get_value(data_type, res)} result.append(val) return result ``` However, the data is really large with a huge number of tuples (~200,000). It takes a lot of time to generate the above message format for each of them. Is there an efficient way of doing this. P.S Need such a message as i am sending this on a queue and the consumer is a C++ client that needs the type information.
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. But it should resolve your chicken and egg problem.
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 transpiled code the file won't exist yet. Luckily, this cheesy step doesn't actually care if the file is usable or not, it just needs it to exist so it can `chmod` it without failure. My work-around for this problem is to simply checkin an empty `dist/index.js` file: `touch dist/index.js` Then add `dist` back to `.gitignore` as you don't want to checkin real builds of the file. In NPM 6 I would have used a `preinstall` script in `package.json` but this has broken in NPM 7, which I happen to be using and I'm not super interested in converting to hooks just to work around this issue. If you are using NPM 6 or earlier the `preinstall` script would look like this: ``` ... "scripts": { "preinstall": "mkdir -p dist/ && touch dist/index.js" } ... ```
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 dict ``` desc = { "name" : "string", "age" : "int", "vol" : "double", "status" : "byte", "limit" : "int" } ``` I need to generate a message to be sent over in the following format : ``` [{"column": "name", "value": {"String": "John"}}, {"column": "age", "value": {"Int": 14}}, {"column": "vol", "value": {"Double": 12132.213}}, {"column": "status", "value": {"Byte": 89}}, {"column": "limit", "value": {"Int": 34}}, {"column": "name", "value": {"String": "Andrew"}}, {"column": "age", "value": {"Int": 23}}, {"column": "vol", "value": {"Double":2121.21}}, {"column": "status", "value": {"Byte": 78}}, {"column": "limit", "value": {"Int": 66}}] ``` I have two functions that generates this : ``` def get_value(data_type, res): if data_type == 'string': return {'String' : res.strip()} elif data_type == 'byte' : return {'Byte' : ord(res[0])} elif data_type == 'int': return {'Int' : int(res)} elif data_type == 'double': return {'Double' : float(res)} def generate_message(data, fields, desc): result = [] for row in data: for field, res in zip(fields, row): data_type = desc[field] val = {'column' : field, 'value' : get_value(data_type, res)} result.append(val) return result ``` However, the data is really large with a huge number of tuples (~200,000). It takes a lot of time to generate the above message format for each of them. Is there an efficient way of doing this. P.S Need such a message as i am sending this on a queue and the consumer is a C++ client that needs the type information.
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 generated `.d.ts`; * The TSC version which generates your code is not supposed to be another moving part for the tests AND your consumers. You would test the generated output, not your source against many TSC versions. * By reducing the "moving parts" boundary by including the .js and .d.ts, you gain much more (= predictability) than what you lose (git history bloat).
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 dict ``` desc = { "name" : "string", "age" : "int", "vol" : "double", "status" : "byte", "limit" : "int" } ``` I need to generate a message to be sent over in the following format : ``` [{"column": "name", "value": {"String": "John"}}, {"column": "age", "value": {"Int": 14}}, {"column": "vol", "value": {"Double": 12132.213}}, {"column": "status", "value": {"Byte": 89}}, {"column": "limit", "value": {"Int": 34}}, {"column": "name", "value": {"String": "Andrew"}}, {"column": "age", "value": {"Int": 23}}, {"column": "vol", "value": {"Double":2121.21}}, {"column": "status", "value": {"Byte": 78}}, {"column": "limit", "value": {"Int": 66}}] ``` I have two functions that generates this : ``` def get_value(data_type, res): if data_type == 'string': return {'String' : res.strip()} elif data_type == 'byte' : return {'Byte' : ord(res[0])} elif data_type == 'int': return {'Int' : int(res)} elif data_type == 'double': return {'Double' : float(res)} def generate_message(data, fields, desc): result = [] for row in data: for field, res in zip(fields, row): data_type = desc[field] val = {'column' : field, 'value' : get_value(data_type, res)} result.append(val) return result ``` However, the data is really large with a huge number of tuples (~200,000). It takes a lot of time to generate the above message format for each of them. Is there an efficient way of doing this. P.S Need such a message as i am sending this on a queue and the consumer is a C++ client that needs the type information.
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 transpiled code the file won't exist yet. Luckily, this cheesy step doesn't actually care if the file is usable or not, it just needs it to exist so it can `chmod` it without failure. My work-around for this problem is to simply checkin an empty `dist/index.js` file: `touch dist/index.js` Then add `dist` back to `.gitignore` as you don't want to checkin real builds of the file. In NPM 6 I would have used a `preinstall` script in `package.json` but this has broken in NPM 7, which I happen to be using and I'm not super interested in converting to hooks just to work around this issue. If you are using NPM 6 or earlier the `preinstall` script would look like this: ``` ... "scripts": { "preinstall": "mkdir -p dist/ && touch dist/index.js" } ... ```
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 dict ``` desc = { "name" : "string", "age" : "int", "vol" : "double", "status" : "byte", "limit" : "int" } ``` I need to generate a message to be sent over in the following format : ``` [{"column": "name", "value": {"String": "John"}}, {"column": "age", "value": {"Int": 14}}, {"column": "vol", "value": {"Double": 12132.213}}, {"column": "status", "value": {"Byte": 89}}, {"column": "limit", "value": {"Int": 34}}, {"column": "name", "value": {"String": "Andrew"}}, {"column": "age", "value": {"Int": 23}}, {"column": "vol", "value": {"Double":2121.21}}, {"column": "status", "value": {"Byte": 78}}, {"column": "limit", "value": {"Int": 66}}] ``` I have two functions that generates this : ``` def get_value(data_type, res): if data_type == 'string': return {'String' : res.strip()} elif data_type == 'byte' : return {'Byte' : ord(res[0])} elif data_type == 'int': return {'Int' : int(res)} elif data_type == 'double': return {'Double' : float(res)} def generate_message(data, fields, desc): result = [] for row in data: for field, res in zip(fields, row): data_type = desc[field] val = {'column' : field, 'value' : get_value(data_type, res)} result.append(val) return result ``` However, the data is really large with a huge number of tuples (~200,000). It takes a lot of time to generate the above message format for each of them. Is there an efficient way of doing this. P.S Need such a message as i am sending this on a queue and the consumer is a C++ client that needs the type information.
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 generated `.d.ts`; * The TSC version which generates your code is not supposed to be another moving part for the tests AND your consumers. You would test the generated output, not your source against many TSC versions. * By reducing the "moving parts" boundary by including the .js and .d.ts, you gain much more (= predictability) than what you lose (git history bloat).
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 dict ``` desc = { "name" : "string", "age" : "int", "vol" : "double", "status" : "byte", "limit" : "int" } ``` I need to generate a message to be sent over in the following format : ``` [{"column": "name", "value": {"String": "John"}}, {"column": "age", "value": {"Int": 14}}, {"column": "vol", "value": {"Double": 12132.213}}, {"column": "status", "value": {"Byte": 89}}, {"column": "limit", "value": {"Int": 34}}, {"column": "name", "value": {"String": "Andrew"}}, {"column": "age", "value": {"Int": 23}}, {"column": "vol", "value": {"Double":2121.21}}, {"column": "status", "value": {"Byte": 78}}, {"column": "limit", "value": {"Int": 66}}] ``` I have two functions that generates this : ``` def get_value(data_type, res): if data_type == 'string': return {'String' : res.strip()} elif data_type == 'byte' : return {'Byte' : ord(res[0])} elif data_type == 'int': return {'Int' : int(res)} elif data_type == 'double': return {'Double' : float(res)} def generate_message(data, fields, desc): result = [] for row in data: for field, res in zip(fields, row): data_type = desc[field] val = {'column' : field, 'value' : get_value(data_type, res)} result.append(val) return result ``` However, the data is really large with a huge number of tuples (~200,000). It takes a lot of time to generate the above message format for each of them. Is there an efficient way of doing this. P.S Need such a message as i am sending this on a queue and the consumer is a C++ client that needs the type information.
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 transpiled code the file won't exist yet. Luckily, this cheesy step doesn't actually care if the file is usable or not, it just needs it to exist so it can `chmod` it without failure. My work-around for this problem is to simply checkin an empty `dist/index.js` file: `touch dist/index.js` Then add `dist` back to `.gitignore` as you don't want to checkin real builds of the file. In NPM 6 I would have used a `preinstall` script in `package.json` but this has broken in NPM 7, which I happen to be using and I'm not super interested in converting to hooks just to work around this issue. If you are using NPM 6 or earlier the `preinstall` script would look like this: ``` ... "scripts": { "preinstall": "mkdir -p dist/ && touch dist/index.js" } ... ```
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 dict ``` desc = { "name" : "string", "age" : "int", "vol" : "double", "status" : "byte", "limit" : "int" } ``` I need to generate a message to be sent over in the following format : ``` [{"column": "name", "value": {"String": "John"}}, {"column": "age", "value": {"Int": 14}}, {"column": "vol", "value": {"Double": 12132.213}}, {"column": "status", "value": {"Byte": 89}}, {"column": "limit", "value": {"Int": 34}}, {"column": "name", "value": {"String": "Andrew"}}, {"column": "age", "value": {"Int": 23}}, {"column": "vol", "value": {"Double":2121.21}}, {"column": "status", "value": {"Byte": 78}}, {"column": "limit", "value": {"Int": 66}}] ``` I have two functions that generates this : ``` def get_value(data_type, res): if data_type == 'string': return {'String' : res.strip()} elif data_type == 'byte' : return {'Byte' : ord(res[0])} elif data_type == 'int': return {'Int' : int(res)} elif data_type == 'double': return {'Double' : float(res)} def generate_message(data, fields, desc): result = [] for row in data: for field, res in zip(fields, row): data_type = desc[field] val = {'column' : field, 'value' : get_value(data_type, res)} result.append(val) return result ``` However, the data is really large with a huge number of tuples (~200,000). It takes a lot of time to generate the above message format for each of them. Is there an efficient way of doing this. P.S Need such a message as i am sending this on a queue and the consumer is a C++ client that needs the type information.
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 transpiled code the file won't exist yet. Luckily, this cheesy step doesn't actually care if the file is usable or not, it just needs it to exist so it can `chmod` it without failure. My work-around for this problem is to simply checkin an empty `dist/index.js` file: `touch dist/index.js` Then add `dist` back to `.gitignore` as you don't want to checkin real builds of the file. In NPM 6 I would have used a `preinstall` script in `package.json` but this has broken in NPM 7, which I happen to be using and I'm not super interested in converting to hooks just to work around this issue. If you are using NPM 6 or earlier the `preinstall` script would look like this: ``` ... "scripts": { "preinstall": "mkdir -p dist/ && touch dist/index.js" } ... ```
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 generated `.d.ts`; * The TSC version which generates your code is not supposed to be another moving part for the tests AND your consumers. You would test the generated output, not your source against many TSC versions. * By reducing the "moving parts" boundary by including the .js and .d.ts, you gain much more (= predictability) than what you lose (git history bloat).
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 import Widget class MyGrid(Widget): pass class MyApp(App): def build(self): return MyGrid() if __name__ == "__main__": MyApp().run() ``` and simple kivy file ``` #:kivy <MyGrid>: GridLayout: cols:1 size: root.width, root.height GridLayout: cols:2 Label: text: "Name: " TextInput: multinline:False Label: text: "Email: " TextInput: multiline:False Button: text:"Submit" ``` And when I'm trying to run python file I got *kivy.lang.parser.ParserException: Parser: File "c:\Users\Paweł\Documents\projects vscode\WeatherProject\my.kv", line 1: 1:#:kivy 2:: 3:GridLayout: Unknown directive* Google isn't helpful at all. Please tell me what should I do.
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: text: "Email: " TextInput: multiline:False Button: text:"Submit" ```
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 import Widget class MyGrid(Widget): pass class MyApp(App): def build(self): return MyGrid() if __name__ == "__main__": MyApp().run() ``` and simple kivy file ``` #:kivy <MyGrid>: GridLayout: cols:1 size: root.width, root.height GridLayout: cols:2 Label: text: "Name: " TextInput: multinline:False Label: text: "Email: " TextInput: multiline:False Button: text:"Submit" ``` And when I'm trying to run python file I got *kivy.lang.parser.ParserException: Parser: File "c:\Users\Paweł\Documents\projects vscode\WeatherProject\my.kv", line 1: 1:#:kivy 2:: 3:GridLayout: Unknown directive* Google isn't helpful at all. Please tell me what should I do.
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: text: "Email: " TextInput: multiline:False Button: text:"Submit" ```
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 import Widget class MyGrid(Widget): pass class MyApp(App): def build(self): return MyGrid() if __name__ == "__main__": MyApp().run() ``` and simple kivy file ``` #:kivy <MyGrid>: GridLayout: cols:1 size: root.width, root.height GridLayout: cols:2 Label: text: "Name: " TextInput: multinline:False Label: text: "Email: " TextInput: multiline:False Button: text:"Submit" ``` And when I'm trying to run python file I got *kivy.lang.parser.ParserException: Parser: File "c:\Users\Paweł\Documents\projects vscode\WeatherProject\my.kv", line 1: 1:#:kivy 2:: 3:GridLayout: Unknown directive* Google isn't helpful at all. Please tell me what should I do.
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 you might like it.
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** and set it to **"Markdown"**.
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 you might like it.
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 bold <s>italic bold strikethrough</s> <u>underline italic bold</u></i> bold</b> <a href="http://www.example.com/">inline URL</a> <a href="tg://user?id=123456789">inline mention of a user</a> <code>inline fixed-width code</code> <pre>pre-formatted fixed-width code block</pre> <pre><code class="language-python">pre-formatted fixed-width code block written in the Python programming language</code></pre> ```
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 bold <s>italic bold strikethrough</s> <u>underline italic bold</u></i> bold</b> <a href="http://www.example.com/">inline URL</a> <a href="tg://user?id=123456789">inline mention of a user</a> <code>inline fixed-width code</code> <pre>pre-formatted fixed-width code block</pre> <pre><code class="language-python">pre-formatted fixed-width code block written in the Python programming language</code></pre> ```
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** and set it to **"Markdown"**.
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 tie, the majority vote should return 0, e.g.: ``` x = [1, 1, 1, -1, -1, -1] ``` This should also return zero: ``` x = [1, 1, 0, 0, -1, -1] ``` The simplest case to get the majority vote seem to sum the list up and check whether it's negative, positive or 0. ``` >>> x = [-1, -1, -1, -1, 0] >>> sum(x) # So majority -> 0 -4 >>> x = [-1, 1, 1, 1, 0] >>> sum(x) # So majority -> 1 2 >>> x = [-1, -1, 1, 1, 0] >>> sum(x) # So majority is tied, i.e. -> 0 0 ``` After the sum, I could do this check to get the majority vote, i.e.: ``` >>> x = [-1, 1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 1 >>> x = [-1, -1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 0 ``` But as noted previously, it's ugly: [Python putting an if-elif-else statement on one line](https://stackoverflow.com/questions/14029245/python-putting-an-if-elif-else-statement-on-one-line) and not pythonic. So the solution seems to be ``` >>> x = [-1, -1, 1, 1, 0] >>> if sum(x) == 0: ... majority = 0 ... else: ... majority = -1 if sum(x) < 0 else 1 ... >>> majority 0 ``` --- EDITED ====== But there are cases that `sum()` won't work, @RobertB's e.g. ``` >>> x = [-1, -1, 0, 0, 0, 0] >>> sum(x) -2 ``` But in this case the majority vote should be 0!!
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 like: ``` from collections import Counter def find_majority(votes): vote_count = Counter(votes) top_two = vote_count.most_common(2) if len(top_two)>1 and top_two[0][1] == top_two[1][1]: # It is a tie return 0 return top_two[0][0] >>> find_majority([1,1,-1,-1,0]) # It is a tie 0 >>> find_majority([1,1,1,1, -1,-1,-1,0]) 1 >>> find_majority([-1,-1,0,0,0]) # Votes for zero win 0 >>> find_majority(['a','a','b',]) # Totally not asked for, but would work 'a' ```
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 ... majority 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 tie, the majority vote should return 0, e.g.: ``` x = [1, 1, 1, -1, -1, -1] ``` This should also return zero: ``` x = [1, 1, 0, 0, -1, -1] ``` The simplest case to get the majority vote seem to sum the list up and check whether it's negative, positive or 0. ``` >>> x = [-1, -1, -1, -1, 0] >>> sum(x) # So majority -> 0 -4 >>> x = [-1, 1, 1, 1, 0] >>> sum(x) # So majority -> 1 2 >>> x = [-1, -1, 1, 1, 0] >>> sum(x) # So majority is tied, i.e. -> 0 0 ``` After the sum, I could do this check to get the majority vote, i.e.: ``` >>> x = [-1, 1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 1 >>> x = [-1, -1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 0 ``` But as noted previously, it's ugly: [Python putting an if-elif-else statement on one line](https://stackoverflow.com/questions/14029245/python-putting-an-if-elif-else-statement-on-one-line) and not pythonic. So the solution seems to be ``` >>> x = [-1, -1, 1, 1, 0] >>> if sum(x) == 0: ... majority = 0 ... else: ... majority = -1 if sum(x) < 0 else 1 ... >>> majority 0 ``` --- EDITED ====== But there are cases that `sum()` won't work, @RobertB's e.g. ``` >>> x = [-1, -1, 0, 0, 0, 0] >>> sum(x) -2 ``` But in this case the majority vote should be 0!!
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 else 0 elif num_p1 > num_n1: return 1 if num_p1 > num_z else 0 else: return 0 ```
``` 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 tie, the majority vote should return 0, e.g.: ``` x = [1, 1, 1, -1, -1, -1] ``` This should also return zero: ``` x = [1, 1, 0, 0, -1, -1] ``` The simplest case to get the majority vote seem to sum the list up and check whether it's negative, positive or 0. ``` >>> x = [-1, -1, -1, -1, 0] >>> sum(x) # So majority -> 0 -4 >>> x = [-1, 1, 1, 1, 0] >>> sum(x) # So majority -> 1 2 >>> x = [-1, -1, 1, 1, 0] >>> sum(x) # So majority is tied, i.e. -> 0 0 ``` After the sum, I could do this check to get the majority vote, i.e.: ``` >>> x = [-1, 1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 1 >>> x = [-1, -1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 0 ``` But as noted previously, it's ugly: [Python putting an if-elif-else statement on one line](https://stackoverflow.com/questions/14029245/python-putting-an-if-elif-else-statement-on-one-line) and not pythonic. So the solution seems to be ``` >>> x = [-1, -1, 1, 1, 0] >>> if sum(x) == 0: ... majority = 0 ... else: ... majority = -1 if sum(x) < 0 else 1 ... >>> majority 0 ``` --- EDITED ====== But there are cases that `sum()` won't work, @RobertB's e.g. ``` >>> x = [-1, -1, 0, 0, 0, 0] >>> sum(x) -2 ``` But in this case the majority vote should be 0!!
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 ... majority 0 ```
``` 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.array([0,0,0,1,1,1])) print fn(np.array([1,1,1,1, -1,-1,-1,0])) print fn(np.array([-1, -1, -1, -1, 1, 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 tie, the majority vote should return 0, e.g.: ``` x = [1, 1, 1, -1, -1, -1] ``` This should also return zero: ``` x = [1, 1, 0, 0, -1, -1] ``` The simplest case to get the majority vote seem to sum the list up and check whether it's negative, positive or 0. ``` >>> x = [-1, -1, -1, -1, 0] >>> sum(x) # So majority -> 0 -4 >>> x = [-1, 1, 1, 1, 0] >>> sum(x) # So majority -> 1 2 >>> x = [-1, -1, 1, 1, 0] >>> sum(x) # So majority is tied, i.e. -> 0 0 ``` After the sum, I could do this check to get the majority vote, i.e.: ``` >>> x = [-1, 1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 1 >>> x = [-1, -1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 0 ``` But as noted previously, it's ugly: [Python putting an if-elif-else statement on one line](https://stackoverflow.com/questions/14029245/python-putting-an-if-elif-else-statement-on-one-line) and not pythonic. So the solution seems to be ``` >>> x = [-1, -1, 1, 1, 0] >>> if sum(x) == 0: ... majority = 0 ... else: ... majority = -1 if sum(x) < 0 else 1 ... >>> majority 0 ``` --- EDITED ====== But there are cases that `sum()` won't work, @RobertB's e.g. ``` >>> x = [-1, -1, 0, 0, 0, 0] >>> sum(x) -2 ``` But in this case the majority vote should be 0!!
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 else 0 elif num_p1 > num_n1: return 1 if num_p1 > num_z else 0 else: return 0 ```
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(counts[1])>1): majority=0 else: majority=counts.index(max(counts))-1 # subtract 1 as indexes start with 0 print majority ``` 3d line puts counts of respective votes in a new list, and counts.index() shows us which list position we find the max votes. I would dare to say that this should be about as pythonic as it can, without getting into eye-gouging oneliners. Upd: rewrote without text strings and updated to return 0 in case of several equal results (didnt notice this in the original post), added an IF for case if only one vote, eg votes=[-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 tie, the majority vote should return 0, e.g.: ``` x = [1, 1, 1, -1, -1, -1] ``` This should also return zero: ``` x = [1, 1, 0, 0, -1, -1] ``` The simplest case to get the majority vote seem to sum the list up and check whether it's negative, positive or 0. ``` >>> x = [-1, -1, -1, -1, 0] >>> sum(x) # So majority -> 0 -4 >>> x = [-1, 1, 1, 1, 0] >>> sum(x) # So majority -> 1 2 >>> x = [-1, -1, 1, 1, 0] >>> sum(x) # So majority is tied, i.e. -> 0 0 ``` After the sum, I could do this check to get the majority vote, i.e.: ``` >>> x = [-1, 1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 1 >>> x = [-1, -1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 0 ``` But as noted previously, it's ugly: [Python putting an if-elif-else statement on one line](https://stackoverflow.com/questions/14029245/python-putting-an-if-elif-else-statement-on-one-line) and not pythonic. So the solution seems to be ``` >>> x = [-1, -1, 1, 1, 0] >>> if sum(x) == 0: ... majority = 0 ... else: ... majority = -1 if sum(x) < 0 else 1 ... >>> majority 0 ``` --- EDITED ====== But there are cases that `sum()` won't work, @RobertB's e.g. ``` >>> x = [-1, -1, 0, 0, 0, 0] >>> sum(x) -2 ``` But in this case the majority vote should be 0!!
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)) < len(ballot) and values[-1] == values [-2]: # Return 0 if there's a tie return 0 else: # Return your winning vote if there isn't a tie return max(counters, key=counters.get) ```
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: counter[number] += 1 best_values = [i for i in (-1, 0, 1) if counter[i] == max(counter.values())] if len(best_values) == 1: majority = best_values[0] else: majority = 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 tie, the majority vote should return 0, e.g.: ``` x = [1, 1, 1, -1, -1, -1] ``` This should also return zero: ``` x = [1, 1, 0, 0, -1, -1] ``` The simplest case to get the majority vote seem to sum the list up and check whether it's negative, positive or 0. ``` >>> x = [-1, -1, -1, -1, 0] >>> sum(x) # So majority -> 0 -4 >>> x = [-1, 1, 1, 1, 0] >>> sum(x) # So majority -> 1 2 >>> x = [-1, -1, 1, 1, 0] >>> sum(x) # So majority is tied, i.e. -> 0 0 ``` After the sum, I could do this check to get the majority vote, i.e.: ``` >>> x = [-1, 1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 1 >>> x = [-1, -1, 1, 1, 0] >>> majority = -1 if sum(x) < 0 else 1 if sum(x)!=0 else 0 >>> majority 0 ``` But as noted previously, it's ugly: [Python putting an if-elif-else statement on one line](https://stackoverflow.com/questions/14029245/python-putting-an-if-elif-else-statement-on-one-line) and not pythonic. So the solution seems to be ``` >>> x = [-1, -1, 1, 1, 0] >>> if sum(x) == 0: ... majority = 0 ... else: ... majority = -1 if sum(x) < 0 else 1 ... >>> majority 0 ``` --- EDITED ====== But there are cases that `sum()` won't work, @RobertB's e.g. ``` >>> x = [-1, -1, 0, 0, 0, 0] >>> sum(x) -2 ``` But in this case the majority vote should be 0!!
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)) < len(ballot) and values[-1] == values [-2]: # Return 0 if there's a tie return 0 else: # Return your winning vote if there isn't a tie return max(counters, key=counters.get) ```
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] == counts[1][1]): ## Comparing top two candidates print 0 else: print counts[0][0] ``` We compare only two candidates because if there is a tie between two candidates it should return 0 and it doesn't depend on third candidate value