qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
2,040,616
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
2010/01/11
[ "https://Stackoverflow.com/questions/2040616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247873/" ]
If you want to fix it James definitely has the right answer, but in case you want to just turn off deprecation warnings, you can run python like so: ``` $ python -Wignore::DeprecationWarning Python 2.6.2 (r262:71600, Sep 20 2009, 20:47:22) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "cred...
Use the built-in `set` instead of importing and using `sets` module. From [documentation](http://docs.python.org/whatsnew/2.6.html): > > The sets module has been deprecated; > it’s better to use the built-in set > and frozenset types. > > >
2,040,616
When I run my python script I get the following warning ``` DeprecationWarning: the sets module is deprecated ``` How do I fix this?
2010/01/11
[ "https://Stackoverflow.com/questions/2040616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247873/" ]
History: Before Python 2.3: no set functionality Python 2.3: `sets` module arrived Python 2.4: `set` and `frozenset` built-ins introduced Python 2.6: `sets` module deprecated You should change your code to use `set` instead of `sets.Set`. If you still wish to be able to support using Python 2.3, you can do...
If you want to fix it James definitely has the right answer, but in case you want to just turn off deprecation warnings, you can run python like so: ``` $ python -Wignore::DeprecationWarning Python 2.6.2 (r262:71600, Sep 20 2009, 20:47:22) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "cred...
5,118,608
I'm novice in python and got a problem in which I would appreciate some help. The problem in short: 1. ask for a string 2. check if all letter in a predefined list 3. if any letter is not in the list then ask for a new string, otherwise go to next step 4. ask for a second string 5. check again whether the second strin...
2011/02/25
[ "https://Stackoverflow.com/questions/5118608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/634333/" ]
I suggest you start here: <http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming> And continue to next chapter: <http://docs.python.org/tutorial/controlflow.html>
You have a couple of options, you could use iteration, or recursion. For this kind of problem I would go with iteration. If you don't know what iteration and recursion are, and how they work in Python then you should use the links Kugel suggested.
5,118,608
I'm novice in python and got a problem in which I would appreciate some help. The problem in short: 1. ask for a string 2. check if all letter in a predefined list 3. if any letter is not in the list then ask for a new string, otherwise go to next step 4. ask for a second string 5. check again whether the second strin...
2011/02/25
[ "https://Stackoverflow.com/questions/5118608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/634333/" ]
I suggest you start here: <http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming> And continue to next chapter: <http://docs.python.org/tutorial/controlflow.html>
This sounds like a job for a while loop <http://www.tutorialspoint.com/python/python_while_loop.htm> pseudo code is ``` list=[a,b,c,d] declare boolean passes = false while (!passes) passes = true String1 = raw_input("first:") foreach char in string1 if !list.contains(char) passes = fal...
5,118,608
I'm novice in python and got a problem in which I would appreciate some help. The problem in short: 1. ask for a string 2. check if all letter in a predefined list 3. if any letter is not in the list then ask for a new string, otherwise go to next step 4. ask for a second string 5. check again whether the second strin...
2011/02/25
[ "https://Stackoverflow.com/questions/5118608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/634333/" ]
I suggest you start here: <http://docs.python.org/tutorial/introduction.html#first-steps-towards-programming> And continue to next chapter: <http://docs.python.org/tutorial/controlflow.html>
Another good place to start is by looking for common sequences of action and putting them in a separate subroutine. ``` # ignore this bit - it's here for compatibility try: inp = raw_input # Python 2.x except NameError: inp = input # Python 3.x # this wraps the 'ask for a string, check if all characters...
52,345,375
i'm new with python and wants to do the following: 1. search inside text to check if token exists 2. token cannot be substring inside the text - must be "as is" (string11111 is not string1) ``` file = "string11111 aaaaa string1 bbbbb" token = "string1" if token in file: print "NOT yay!" ``` 3. token needs to be...
2018/09/15
[ "https://Stackoverflow.com/questions/52345375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1596023/" ]
First tokenize your `file` variable ``` tokens = file.split() ``` Then look for your token ``` if token in tokens: # do your thing ```
hoping the below solution meets your need - ``` file = "string11111 aaaaa string1 bbbbb" token = "string1" token_matched = [file_token for file_token in file.split()[::-1] if token in file_token and len(token) == len(file_token)] print('Matched tokens (reverse order) - ', token_matched) if len(token_matched) > 1: ...
52,345,375
i'm new with python and wants to do the following: 1. search inside text to check if token exists 2. token cannot be substring inside the text - must be "as is" (string11111 is not string1) ``` file = "string11111 aaaaa string1 bbbbb" token = "string1" if token in file: print "NOT yay!" ``` 3. token needs to be...
2018/09/15
[ "https://Stackoverflow.com/questions/52345375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1596023/" ]
First tokenize your `file` variable ``` tokens = file.split() ``` Then look for your token ``` if token in tokens: # do your thing ```
Try this one, using regex ``` file = "string11111 aaaaa string1 bbbbb"[::-1] token = "string1" regex = r"\b" + re.escape(token) + r"\b" match = re.findall(regex , file)[0] if match in file: print "NOT yay!" ```
58,603,894
I am trying to convert the below mentioned json string to python dictionary. I am using python 3's json package for the same. Here is the code that I am using : ``` a = "[{'id': 35, 'name': 'Comedy'}, {'id': 18, 'name': 'Drama'}, {'id': 10751, 'name': 'Family'}, {'id': 10749, 'name': 'Romance'}]" b = json.loads(json.d...
2019/10/29
[ "https://Stackoverflow.com/questions/58603894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4720757/" ]
The json string that you are trying to convert is not properly formatted. Also, you need to only call json.loads to convert string into `dict` or `list`. The updated code would look like: ``` import json a = '[{"id": 35, "name": "Comedy"}, {"id": 18, "name": "Drama"}, {"id": 10751, "name": "Family"}, {"id": 10749, "n...
**JSON Array** is enclosed in `[ ]` while **JSON object** is enclosed in `{ }` > > The string in `a` is a *json array* so you can change that into a *list* only. > > > > Your *key and value should be enclosed with double quotes*, that's the requirement to use json library of python. > > `b = json.loads(a)` w...
44,780,952
So I'm writing a Python program that reads lines of serial data, and compares them to a dictionary of line codes to figure out which specific lines are being transmitted. I am attempting to use a Regular Expression in order to filter out the extra garbage line serial read string has on it, but I'm having a bit of an is...
2017/06/27
[ "https://Stackoverflow.com/questions/44780952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3711832/" ]
Your problem is threefold: 1) your string contains extra `\r` (Carriage Return character) before `\n` (New Line character); this is common in Windows and in network communication protocols; it is probably best to remove any trailing whitespace from your string: ``` regexString = regexString.rstrip() ``` 2) as ment...
There are several ways to get rid of the "\r", but first a little analysis of your code : 1. the special charakter for the end is just '$' not '$\' in python. 2. re.sub will substitute the matched pattern with a string ( '' in your case) wich would substitute the string you want to get with an empty string and you are ...
44,780,952
So I'm writing a Python program that reads lines of serial data, and compares them to a dictionary of line codes to figure out which specific lines are being transmitted. I am attempting to use a Regular Expression in order to filter out the extra garbage line serial read string has on it, but I'm having a bit of an is...
2017/06/27
[ "https://Stackoverflow.com/questions/44780952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3711832/" ]
Your problem is threefold: 1) your string contains extra `\r` (Carriage Return character) before `\n` (New Line character); this is common in Windows and in network communication protocols; it is probably best to remove any trailing whitespace from your string: ``` regexString = regexString.rstrip() ``` 2) as ment...
Just match what you want to find. Couple of examples: ``` import re data = '''lots of otherT12F8B0A2212F8garbage T12F8B0A2234F8around T12F8B0A22ABF8the stringsT12F8B0A22CDF8 ''' print(re.findall('T12F8B0A22..F8',data)) ``` > > ['T12F8B0A2212F8', 'T12F8B0A2234F8', 'T12F8B0A22ABF8', 'T12F8B0A22CDF8'] > > > ``` ...
25,518,623
I wonder why the python magic method (**str**) always looking for the return statement rather a print method ? ``` class test: def __init__(self): print("constructor called") def __call__(self): print("callable") def __str__(self): return "string method" obj=test() ## print const...
2014/08/27
[ "https://Stackoverflow.com/questions/25518623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2199012/" ]
This is more to enable the conversion of an object into a `str` - your users don't necessary want all that stuff be printed into the terminal whenever they want to do something like ``` text = str(obj_instance) ``` They want `text` to contain the result, not printed out onto the terminal. Doing it your way, the cod...
Because `__str__()` is used when you `print` the object, so the user is already calling `print` which needs the String that represent the Object - as a variable to pass back to the user's `print` In the example you provided above, if `__str__` would print you would get: ``` print(obj) ``` translated into: ``` prin...
56,063,686
I've just recently switched to PyTorch after getting frustrated in debugging tf and understand that it is equivalent to coding in numpy almost completely. My question is what are the permitted python aspects we can use in a PyTorch model (to be put completely on GPU) eg. if-else has to be implemented as follows in tens...
2019/05/09
[ "https://Stackoverflow.com/questions/56063686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7779411/" ]
The problem is that if it can only contain one of those words, then where it doesn't contain one of the keywords the SEARCH function will return an error. Capture that using IFERROR to set errors (values not found) to 0, and then get the MAX to find the position of the word that was found (if any). If no values are fou...
You can use the normally entered function: ``` =AGGREGATE(14,6,SEARCH({"Success","Unknown","Failed"},Q_DTL_GetAll__3[@MESSAGE]),1) ``` Your `SEARCH` is returning an array of values. In the given case: `{#VALUE!,42,#VALUE!}` So you need some way of only returning the non-error value. `AGGREGATE` can do that. This ...
28,532,672
I have N 10-dimensional vectors where each element can have value of 0,1 or 2. For example, `vector v=(0,1,1,2,0,1,2,0,1,1)` is one of the vectors. Is there an algorithm (preferably in python) that compresses these vectors into a minimum number of Cartesian products. If not perfect solution, is there a algorithm that a...
2015/02/15
[ "https://Stackoverflow.com/questions/28532672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4570066/" ]
Another alternative way is using [.one()](http://api.jquery.com/one/) (the handler is executed at most once per element per event type), something like this, ``` $(".done p").one('click', function() { $(this).parent().attr("class", "item not-done"); $(this).parent().hide().prependTo('.list').fadeIn('.5s'); }); ``...
You just need to unbind the click handler, so the following should work: ``` $(".done p").click(function() { $(this).parent().attr("class", "item not-done"); $(this).parent().hide().prependTo('.list').fadeIn('.5s'); $(this).unbind('click'); }); ```
28,532,672
I have N 10-dimensional vectors where each element can have value of 0,1 or 2. For example, `vector v=(0,1,1,2,0,1,2,0,1,1)` is one of the vectors. Is there an algorithm (preferably in python) that compresses these vectors into a minimum number of Cartesian products. If not perfect solution, is there a algorithm that a...
2015/02/15
[ "https://Stackoverflow.com/questions/28532672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4570066/" ]
You just need to unbind the click handler, so the following should work: ``` $(".done p").click(function() { $(this).parent().attr("class", "item not-done"); $(this).parent().hide().prependTo('.list').fadeIn('.5s'); $(this).unbind('click'); }); ```
Try ``` $(document).ready(function() { // Handles new entry submissions $('.entry-form').submit(function(event) { var entryValue = $(".entry").val(); // if `entryValue` _not_ have class `not-done` , // prepend `done` having `entryValue` to `.list` , // add class `not-done` ...
28,532,672
I have N 10-dimensional vectors where each element can have value of 0,1 or 2. For example, `vector v=(0,1,1,2,0,1,2,0,1,1)` is one of the vectors. Is there an algorithm (preferably in python) that compresses these vectors into a minimum number of Cartesian products. If not perfect solution, is there a algorithm that a...
2015/02/15
[ "https://Stackoverflow.com/questions/28532672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4570066/" ]
Another alternative way is using [.one()](http://api.jquery.com/one/) (the handler is executed at most once per element per event type), something like this, ``` $(".done p").one('click', function() { $(this).parent().attr("class", "item not-done"); $(this).parent().hide().prependTo('.list').fadeIn('.5s'); }); ``...
Try ``` $(document).ready(function() { // Handles new entry submissions $('.entry-form').submit(function(event) { var entryValue = $(".entry").val(); // if `entryValue` _not_ have class `not-done` , // prepend `done` having `entryValue` to `.list` , // add class `not-done` ...
39,191,252
I'm running Spark 1.5.1 in standalone (client) mode using Pyspark. I'm trying to start a job that seems to be memory heavy (in python that is, so that should not be part of the executor-memory setting). I'm testing on a machine with 96 cores and 128 GB of RAM. I have a master and worker running, started using the star...
2016/08/28
[ "https://Stackoverflow.com/questions/39191252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/696992/" ]
Check or set the value for spark.executor.instances. The default is 2, which may explain why you get 2 executors. Since your server has 96 cores, and you set defaultcores to 40, you only have room for 2 executors since 2\*40 = 80. The remaining 16 cores are insufficient for another executor and the driver also requir...
> > I expect there to be 1 executor. However, 2 executors are started > > > I think the one executor you see, it's actually the driver. So one master, one slave (2 nodes in totals). You can add to your script these configuration flags: ``` --conf spark.executor.cores=8 <-- will set it 8, you probably wan...
27,798,829
I have installed PySide in my Ubuntu 12.04. When I try to use import PySide in the python console I am getting the following error. ``` import PySide Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named PySide ``` My Python Path is : ``` print sys.path ['', '/usr/lib/p...
2015/01/06
[ "https://Stackoverflow.com/questions/27798829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2871542/" ]
To use python 3, just follow the instructions here: <https://wiki.qt.io/PySide_Binaries_Linux> which in ubuntu 12.04 means just typing one line in the console: ``` sudo apt-get install python3-pyside ```
The latest build and install instructions for PySide are here: <http://pyside.readthedocs.org/en/latest/building/linux.html>
27,798,829
I have installed PySide in my Ubuntu 12.04. When I try to use import PySide in the python console I am getting the following error. ``` import PySide Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: No module named PySide ``` My Python Path is : ``` print sys.path ['', '/usr/lib/p...
2015/01/06
[ "https://Stackoverflow.com/questions/27798829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2871542/" ]
To use python 3, just follow the instructions here: <https://wiki.qt.io/PySide_Binaries_Linux> which in ubuntu 12.04 means just typing one line in the console: ``` sudo apt-get install python3-pyside ```
Now, the `ModuleNotFoundError: No module named 'PySide'` - issue can be solved for `python` versions > 3.4x with `pip install pyside2` like so: ``` andylu@andylu-Lubuntu-PC:~$ pip install pyside2 Collecting pyside2 Downloading PySide2-5.15.2-5.15.2-cp35.cp36.cp37.cp38.cp39-abi3-manylinux1_x86_64.whl (164.3 MB) ...
70,922,066
I am building a docker image to run a flask app, which is named dp-offsets for context. This flask app uses matplotlib. I have been unable to fully install matlplotlib despite including all of the necessary dependencies (i think). The code seems to be erroring on timestamp **791.9**s due to bdist\_wheel. I'm not sure w...
2022/01/31
[ "https://Stackoverflow.com/questions/70922066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18075955/" ]
You have to rearrange the whole thing in your required format. To do that you have to access the data to it's specific position. You did something awkward there in your code at the second array base. you should specify your section somewhere else,maybe the next line. To access it you have to write: ``` obj.name //Fo...
Objects are defined like this: {key1: value1, key2: value2} Keys are the identifiers of your values. When you are assigning section: 'A', section: 'B', section: 'C', you are using the same key, so the previous values are overwritten and only the last is stored. That's why it logs 'C'. You can try changing the keys or m...
70,186,395
I have uploaded my databricks notebooks to a repo and replace %run sentences with import using the new databrick public available features (Repo integration and python import): <https://databricks.com/blog/2021/10/07/databricks-repos-is-now-generally-available.html> But its seems its not working I already activate th...
2021/12/01
[ "https://Stackoverflow.com/questions/70186395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075163/" ]
You can use a hierarchical query and `CONNECT_BY_ROOT`. Either starting at the root of the hierarchy and working down: ```sql SELECT id, CONNECT_BY_ROOT(id) AS root_id FROM entry WHERE id IN (6, 3) START WITH parent_id IS NULL CONNECT BY PRIOR id = parent_id; ``` Or, from the entry back up to the root: `...
You can use recursive CTE to walk the graph and find the initial parent. For example: ``` with n (starting_id, current_id, parent_id, v) as ( select id, id, parent_id, 0 from entry where id in (6, 3) union all select n.starting_id, e.id, e.parent_id, n.v - 1 from n join entry e on e.id = n.parent_id ) select ...
18,541,648
I have a table in a database which contains query statements in the columns. I need to update this. Is there any way I can update this It seems to be giving me an error: ``` UPDATE Items SET Query = 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status='O' and Doc in ('CK') {SLLocCode}' ...
2013/08/30
[ "https://Stackoverflow.com/questions/18541648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2684009/" ]
You need to use 2 single quotes ('') around each literal value ``` 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status=''O'' and Doc in (''CK'') {SLLocCode}' ```
You need to escape the single quotes in the query string. In SQL Server, you just double the single quotes: ``` UPDATE Items SET Query = 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status=''O'' and Doc in (''CK'') {SLLocCode}' WHERE ID = '111'; ```
18,541,648
I have a table in a database which contains query statements in the columns. I need to update this. Is there any way I can update this It seems to be giving me an error: ``` UPDATE Items SET Query = 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status='O' and Doc in ('CK') {SLLocCode}' ...
2013/08/30
[ "https://Stackoverflow.com/questions/18541648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2684009/" ]
You need to use 2 single quotes ('') around each literal value ``` 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status=''O'' and Doc in (''CK'') {SLLocCode}' ```
you would need to escape `'`(single quotes) in the query. This can be done by simplly doubling it. ``` UPDATE Items SET Query = 'SELECT isnull((sum(OrigDocAmt) ),0) amount from AP where Acct in (1234) and Status=''O'' and Doc in (''CK'') {SLLocCode}'' WHERE ID=''111'; ```
49,781,303
I'm trying to write in a microsoft azure jupyter python notebook and I am receiving an error when I try to import the Tweepy module. Please take a look at the simple code below and let me know your thoughts. Thank you. I'm working on a chromebook if that helps, but I'm not sure it's relevant. ``` import tweepy as tw...
2018/04/11
[ "https://Stackoverflow.com/questions/49781303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9631959/" ]
From the [Azure Notebooks docs](https://notebooks.azure.com/help/jupyter-notebooks/package-installation/python): > > The simplest way to install packages is to do it from within a Jupyter Python notebook. Inside of the notebook your path will be setup to have both pip and conda on it pointing to the proper version of...
I had the same error when I was trying to use tweepy. You can try using these commands instead: `from tweepy import OAuthHandler from tweepy import API from tweepy import Cursor`
46,509,906
This code is supposed to find the number which is biggest and then it should print out how many is there, but for some reason this commented if statement doesn't work. ``` #!/bin/python3 import sys def birthdayCakeCandles(n, ar): j=1 b=0 f=0 maxn=0 for f in range(0,n-1,1): b=ar[f] #...
2017/10/01
[ "https://Stackoverflow.com/questions/46509906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6659439/" ]
I found the **almost** perfect working answer in [Levi Fuller's blog](https://medium.com/@levifuller/how-to-deploy-an-angular-cli-application-built-on-asp-net-1fa03c0ca365). You can get it working with a minor change: unlike what Levi states, you really need **only a single** npm task 1. set up the **npm task** * by ...
There isn’t the build template that you use directly, the template is convenient to use, you need to modify it per to detail requirement. Refer to these steps: 1. Go to build page of team project (e.g. `https://XXX.visualstudio.com/[teamproject]/_build`) 2. Click +New button to create a build definition with ASP.NET ...
31,234,170
So I am a bit new to Java and Eclipse. I am more used to python. Using IDLE in python I am able to run my program from it's file and and then continue to use the variables. For example, if I have all the code written out defining a function, in idle I can just write it there. ``` x = foo() print x ``` However, in Ja...
2015/07/05
[ "https://Stackoverflow.com/questions/31234170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4967646/" ]
Java is a compiled language, python is a scripting language. You could use scala, or jython (or another scripting language) to get the behavior you want. It's also possible to use a [*Scrapbook page*](http://help.eclipse.org/luna/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-create_scrapbook_page.htm) in e...
Your environment is one that sounds like its a python based environment. in this case you are storing the variables into your IDE's runtime variable pool. thats why you can later go and act on a variable you set up. in eclipse when you run your program you are launching a new instance of java that is disconnected (from...
399,991
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 ``` Then I execute the file and get the data. Since the program is all on my machin...
2008/12/30
[ "https://Stackoverflow.com/questions/399991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46634/" ]
``` vinko@mithril$ more a.py def foo(a): print a vinko@mithril$ more b.py import a import inspect a.foo(89) print inspect.getsource(a.foo) vinko@mithril$ python b.py 89 def foo(a): print a ```
Are you asking about this? ``` def writeoptions(directory): options="" options+="starting_length=%s%s"%(starting_length,os.linesep) options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep) options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep) options+="def pippo(a,b):%s" % ...
399,991
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 ``` Then I execute the file and get the data. Since the program is all on my machin...
2008/12/30
[ "https://Stackoverflow.com/questions/399991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46634/" ]
``` vinko@mithril$ more a.py def foo(a): print a vinko@mithril$ more b.py import a import inspect a.foo(89) print inspect.getsource(a.foo) vinko@mithril$ python b.py 89 def foo(a): print a ```
While it is possible to do what you ask (as Vinko has shown), I'd say it is cleaner to *share code*. Put `pippo` and his buddies in a submodule that both programs can access.
399,991
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 ``` Then I execute the file and get the data. Since the program is all on my machin...
2008/12/30
[ "https://Stackoverflow.com/questions/399991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46634/" ]
``` vinko@mithril$ more a.py def foo(a): print a vinko@mithril$ more b.py import a import inspect a.foo(89) print inspect.getsource(a.foo) vinko@mithril$ python b.py 89 def foo(a): print a ```
Instead of diving into the subject of [disassemblers](http://docs.python.org/library/dis.html) and bytecodes (e.g [inspect](http://docs.python.org/library/inspect.html)), why don't you just save the generated Python source in a module (*file.py*), and later, import it? I would suggest looking into a more standard way ...
399,991
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 ``` Then I execute the file and get the data. Since the program is all on my machin...
2008/12/30
[ "https://Stackoverflow.com/questions/399991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46634/" ]
``` vinko@mithril$ more a.py def foo(a): print a vinko@mithril$ more b.py import a import inspect a.foo(89) print inspect.getsource(a.foo) vinko@mithril$ python b.py 89 def foo(a): print a ```
You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. ...
399,991
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 ``` Then I execute the file and get the data. Since the program is all on my machin...
2008/12/30
[ "https://Stackoverflow.com/questions/399991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46634/" ]
You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. ...
Are you asking about this? ``` def writeoptions(directory): options="" options+="starting_length=%s%s"%(starting_length,os.linesep) options+="starting_cell_size=%s%s"%(starting_cell_size,os.linesep) options+="LengthofExperiments=%s%s"%(LengthofExperiments,os.linesep) options+="def pippo(a,b):%s" % ...
399,991
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 ``` Then I execute the file and get the data. Since the program is all on my machin...
2008/12/30
[ "https://Stackoverflow.com/questions/399991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46634/" ]
You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. ...
While it is possible to do what you ask (as Vinko has shown), I'd say it is cleaner to *share code*. Put `pippo` and his buddies in a submodule that both programs can access.
399,991
When I pass the options in the program (a computational biology experiment) I usually pass them through a .py file. So I have this .py file that reads like: ``` starting_length=9 starting_cell_size=1000 LengthofExperiments=5000000 ``` Then I execute the file and get the data. Since the program is all on my machin...
2008/12/30
[ "https://Stackoverflow.com/questions/399991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46634/" ]
You might also consider some other means of data persistence. In my own (astronomy) research, I've been experimenting with two different means of storing scripts for reproducibility. The first is to have them exclusively inside a subversion repository, and then have the job submission script automatically commit them. ...
Instead of diving into the subject of [disassemblers](http://docs.python.org/library/dis.html) and bytecodes (e.g [inspect](http://docs.python.org/library/inspect.html)), why don't you just save the generated Python source in a module (*file.py*), and later, import it? I would suggest looking into a more standard way ...
51,007,893
I have a homework to draw a spiral(from inside to outside) in python with turtle, but I cant think of a way to do that, beside what I did its need to be like this: [![enter image description here](https://i.stack.imgur.com/UQCW8.gif)](https://i.stack.imgur.com/UQCW8.gif) I tried to do it like that, but its not workin...
2018/06/24
[ "https://Stackoverflow.com/questions/51007893", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7528938/" ]
As described in this link : [Create Deep Links](https://developer.android.com/training/app-links/deep-linking) You should add this in your manifest : ``` <activity android:name="com.example.android.GizmosActivity" android:label="@string/title_gizmos" > <intent-filter android:label="@string/filter_view_htt...
Yes it is possible by handling adding state parms in your url and then redirecting to play store from your server side code. eg - your app generates url which points to some user profile - <https://www.yourSocialNewtwork.com/profile/sandeshDahake> Step 1 - Create a deep link in your app with intent filter. This w...
70,431,040
I think the title gives the general idea of what I am looking for, but to be more specific I will give an example with code. So let's say I have a Python class with a few required position variables that also takes an arbitrary number of keyword arguments. The class has many data members, and some of them will be defi...
2021/12/21
[ "https://Stackoverflow.com/questions/70431040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16043632/" ]
It would be easier to find the answer if you explained the purpose for the requirement. From my experience one common task is to distinguish `authorization_code` and `client_credentials` flow use for the same client, but that's easy: the second one does not contain user information (`sub` and `sid` claims). Also do...
One option is to have different client definitions for the different flows and then use a [ClientClaim](https://docs.duendesoftware.com/identityserver/v5/fundamentals/claims/#client-claims) to indicate what type of client it is: To set the client claims in the client definition just set it like: ``` ClientClaimsPrefi...
10,062,967
Is there an idiomatic way of encoding and decoding a string in Clojure as hexadecimal? Example from Python: ```python 'Clojure'.encode('hex') # ⇒ '436c6f6a757265' '436c6f6a757265'.decode('hex') # ⇒ 'Clojure' ``` To show some effort on my part: ```clj (defn hexify [s] (apply str (map #(format "%02x" (int %)) s...
2012/04/08
[ "https://Stackoverflow.com/questions/10062967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165806/" ]
Your implementation(s) don't work for non-ascii characters, ```clj (defn hexify [s] (apply str (map #(format "%02x" (int %)) s))) (defn unhexify [hex] (apply str (map (fn [[x y]] (char (Integer/parseInt (str x y) 16))) (partition 2 hex)))) (= "\u2195" (unhexify(hexify "\u2195"))) false ;...
I believe your `unhexify` function is as idiomatic as it can be. However, `hexify` can be written in a simpler way: ``` (defn hexify [s] (format "%x" (new java.math.BigInteger (.getBytes s)))) ```
10,062,967
Is there an idiomatic way of encoding and decoding a string in Clojure as hexadecimal? Example from Python: ```python 'Clojure'.encode('hex') # ⇒ '436c6f6a757265' '436c6f6a757265'.decode('hex') # ⇒ 'Clojure' ``` To show some effort on my part: ```clj (defn hexify [s] (apply str (map #(format "%02x" (int %)) s...
2012/04/08
[ "https://Stackoverflow.com/questions/10062967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165806/" ]
Since all posted solutions have some flaws, I'm sharing my own: ```clj (defn hexify "Convert byte sequence to hex string" [coll] (let [hex [\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \a \b \c \d \e \f]] (letfn [(hexify-byte [b] (let [v (bit-and b 0xFF)] [(hex (bit-shift-right v 4)) (hex (bit-and v 0x0F))]...
I believe your `unhexify` function is as idiomatic as it can be. However, `hexify` can be written in a simpler way: ``` (defn hexify [s] (format "%x" (new java.math.BigInteger (.getBytes s)))) ```
10,062,967
Is there an idiomatic way of encoding and decoding a string in Clojure as hexadecimal? Example from Python: ```python 'Clojure'.encode('hex') # ⇒ '436c6f6a757265' '436c6f6a757265'.decode('hex') # ⇒ 'Clojure' ``` To show some effort on my part: ```clj (defn hexify [s] (apply str (map #(format "%02x" (int %)) s...
2012/04/08
[ "https://Stackoverflow.com/questions/10062967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165806/" ]
Your implementation(s) don't work for non-ascii characters, ```clj (defn hexify [s] (apply str (map #(format "%02x" (int %)) s))) (defn unhexify [hex] (apply str (map (fn [[x y]] (char (Integer/parseInt (str x y) 16))) (partition 2 hex)))) (= "\u2195" (unhexify(hexify "\u2195"))) false ;...
Sadly the "idiom" appears to be using the [Apache Commons Codec](http://commons.apache.org/proper/commons-codec/), e.g. as [done in `buddy`](https://github.com/funcool/buddy-core/blob/master/src/buddy/core/codecs.clj): ``` (ns name-of-ns (:import org.apache.commons.codec.binary.Hex)) (defn str->bytes "Convert str...
10,062,967
Is there an idiomatic way of encoding and decoding a string in Clojure as hexadecimal? Example from Python: ```python 'Clojure'.encode('hex') # ⇒ '436c6f6a757265' '436c6f6a757265'.decode('hex') # ⇒ 'Clojure' ``` To show some effort on my part: ```clj (defn hexify [s] (apply str (map #(format "%02x" (int %)) s...
2012/04/08
[ "https://Stackoverflow.com/questions/10062967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165806/" ]
Since all posted solutions have some flaws, I'm sharing my own: ```clj (defn hexify "Convert byte sequence to hex string" [coll] (let [hex [\0 \1 \2 \3 \4 \5 \6 \7 \8 \9 \a \b \c \d \e \f]] (letfn [(hexify-byte [b] (let [v (bit-and b 0xFF)] [(hex (bit-shift-right v 4)) (hex (bit-and v 0x0F))]...
Sadly the "idiom" appears to be using the [Apache Commons Codec](http://commons.apache.org/proper/commons-codec/), e.g. as [done in `buddy`](https://github.com/funcool/buddy-core/blob/master/src/buddy/core/codecs.clj): ``` (ns name-of-ns (:import org.apache.commons.codec.binary.Hex)) (defn str->bytes "Convert str...
57,318,921
I'm trying to use xtensor-python example found [here](https://xtensor-python.readthedocs.io/en/latest/). I have xtensor-python, pybind11, and xtensor installed and also created a CMakeLists.txt. from /build I ran. $ cmake .. $ make and it builds without errors. My CMakeLists.txt looks like this. ``` cmake_minimu...
2019/08/02
[ "https://Stackoverflow.com/questions/57318921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11395552/" ]
This is actually really simple and done in a few lines ```c# public GameObject prefab; public float radius; public float amount; // Start is called before the first frame update private void Start() { var angle = 0f; for (var i = 0; i <= amount; i++) { var y = Mathf.Sin(Mathf.Deg2Rad * angle) * ...
Ok, so this is more of a math problem then anything else really. Now assuming that you are not a total beginner with Unity I will not write you code for your solution, but just generaly describe it. First thing you need to be inputed is radius, this will determine how far away from the center of the circle should your...
48,825,312
I am new to python, I have written test cases for my class , I am using `python -m pytest --cov=azuread_api` to get code coverage. I am getting coverage on the console as [![enter image description here](https://i.stack.imgur.com/iKRNP.png)](https://i.stack.imgur.com/iKRNP.png) How do I get which lines are missed b...
2018/02/16
[ "https://Stackoverflow.com/questions/48825312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3556028/" ]
If you check the [documentation for reporting](https://pytest-cov.readthedocs.io/en/latest/reporting.html) in pytest-cov, you can see how to manipulate the report and generate extra versions. For example, adding the option `--cov-report term-missing` you'll get the missing lines printed in the terminal. A more user f...
In addition to the [answer from Ignacio](https://stackoverflow.com/a/48825483/149900), one can also set [`show_missing = true`](https://coverage.readthedocs.io/en/latest/config.html#config-report-show-missing) in `.coveragerc`, as pytest-cov reads that config file as well.
30,987,825
I have a list of lists in python. I want to group similar lists together. That is, if first three elements of each list are the same then those three lists should go in one group. For eg ``` [["a", "b", "c", 1, 2], ["d", "f", "g", 8, 9], ["a", "b", "c", 3, 4], ["d","f", "g", 3, 4], ["a", "b", "c", 5, 6]] ``` I w...
2015/06/22
[ "https://Stackoverflow.com/questions/30987825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4378672/" ]
You can use [`itertools.groupby`](https://docs.python.org/3.4/library/itertools.html#itertools.groupby) : ``` >>> A=[["a", "b", "c", 1, 2], ... ["d", "f", "g", 8, 9], ... ["a", "b", "c", 3, 4], ... ["d","f", "g", 3, 4], ... ["a", "b", "c", 5, 6]] >>> from operator import itemgetter >>> [list(g) for _,g in ...
You don't need to sort, you can group in a dict using a tuple of the first three elements from each list as the key: ``` from collections import OrderedDict l=[ ["a", "b", "c", 1, 2], ["d", "f", "g", 8, 9], ["a", "b", "c", 3, 4], ["d","f", "g", 3, 4], ["a", "b", "c", 5, 6] ] od = Ordere...
24,272,228
I am using ArgParse for giving commandline parameters in Python. ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("--quality", type=int,help="enter some quality limit") args = parser.parse_args() qual=args.quality if args.quality: qual=0 $ python a.py --quality a.py: error: argument --q...
2014/06/17
[ "https://Stackoverflow.com/questions/24272228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2596951/" ]
Use `nargs='?'` to allow `--quality` to be used with 0 or 1 value supplied. Use `const=0` to handle `script.py --quality` without a value supplied. Use `default=0` to handle bare calls to `script.py` (without `--quality` supplied). ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("--quality",...
Have a loot at <https://docs.python.org/2/howto/argparse.html#id1>. Simply add the argument `default` to your add\_argument call. `parser.add_argument("--quality", type=int, default=0, nargs='?', help="enter some quality limit")` If you want to use `--quality` as a flag you should use `action="store_true"`. This will...
24,272,228
I am using ArgParse for giving commandline parameters in Python. ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("--quality", type=int,help="enter some quality limit") args = parser.parse_args() qual=args.quality if args.quality: qual=0 $ python a.py --quality a.py: error: argument --q...
2014/06/17
[ "https://Stackoverflow.com/questions/24272228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2596951/" ]
Have a loot at <https://docs.python.org/2/howto/argparse.html#id1>. Simply add the argument `default` to your add\_argument call. `parser.add_argument("--quality", type=int, default=0, nargs='?', help="enter some quality limit")` If you want to use `--quality` as a flag you should use `action="store_true"`. This will...
With `docopt` use `[default: 0]` in docstring ============================================= Deliberately ignoring the `argparse` part of your question, here is how you could define default using `docopt`. With `docopt` you define default value (and almost all the rest) as part of docstring. First, install `docopt` a...
24,272,228
I am using ArgParse for giving commandline parameters in Python. ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("--quality", type=int,help="enter some quality limit") args = parser.parse_args() qual=args.quality if args.quality: qual=0 $ python a.py --quality a.py: error: argument --q...
2014/06/17
[ "https://Stackoverflow.com/questions/24272228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2596951/" ]
Use `nargs='?'` to allow `--quality` to be used with 0 or 1 value supplied. Use `const=0` to handle `script.py --quality` without a value supplied. Use `default=0` to handle bare calls to `script.py` (without `--quality` supplied). ``` import argparse parser = argparse.ArgumentParser() parser.add_argument("--quality",...
With `docopt` use `[default: 0]` in docstring ============================================= Deliberately ignoring the `argparse` part of your question, here is how you could define default using `docopt`. With `docopt` you define default value (and almost all the rest) as part of docstring. First, install `docopt` a...
4,858,733
Python has this magic [`__call__`](http://docs.python.org/reference/datamodel.html#object.__call__) method that gets called when the object is called like a function. Does C# support something similar? --- Specifically, I was hoping for a way to use delegates and objects interchangeably. Trying to design an API where...
2011/02/01
[ "https://Stackoverflow.com/questions/4858733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
Sure, if you inherit from [DynamicObject](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx). I think you're after [TryInvoke](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvoke.aspx) which executes on `obj(...)`, but there are several other method you can override to...
I bow to Simon Svensson - who shows a way to do it if you inherit from DynamicObject - for a more strait forward non dynamic point of view: Sorry but no - but there are types of objects that can be called - delegates for instance. ``` Func<int, int> myDelagate = x=>x*2; int four = myDelagate(2) ``` There is a...
4,858,733
Python has this magic [`__call__`](http://docs.python.org/reference/datamodel.html#object.__call__) method that gets called when the object is called like a function. Does C# support something similar? --- Specifically, I was hoping for a way to use delegates and objects interchangeably. Trying to design an API where...
2011/02/01
[ "https://Stackoverflow.com/questions/4858733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65387/" ]
Sure, if you inherit from [DynamicObject](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx). I think you're after [TryInvoke](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvoke.aspx) which executes on `obj(...)`, but there are several other method you can override to...
This would be akin to overloading the function call operator (as is possible in C++). Unfortunately, this is not something which is supported in C#. The only objects that can be called like methods are instances of delegates.
21,377,656
Why is the self.year twice? I am having trouble to find out the logic of the line. Can some one help me with this? ``` return (self.year and self.year == date.year or True) ``` I am going through <http://www.openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html> and encountered the line ... And of course I have no pro...
2014/01/27
[ "https://Stackoverflow.com/questions/21377656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2770850/" ]
Assuming these are parallel arrays (the first entry in `eenhedennamen` uses the first entry in `value`), you can loop through with jQuery's [`$.each`](http://api.jquery.com/jQuery.each), which gives you the index and the entry for each entry, and build the object from the loop. ``` var obj = {}; $.each(eenhedennamen, ...
``` var eenhedennamen = [ 'unit1', 'unit2', 'unit3' ]; var value = [ 1, 2, 3 ]; var z = new Array(); for ( var i = 0; i < eenhedennamen.length; i++) { z[eenhedennamen[i]]=value[i]; } ``` The previous answer is better.
21,377,656
Why is the self.year twice? I am having trouble to find out the logic of the line. Can some one help me with this? ``` return (self.year and self.year == date.year or True) ``` I am going through <http://www.openp2p.com/pub/a/python/2004/12/02/tdd_pyunit.html> and encountered the line ... And of course I have no pro...
2014/01/27
[ "https://Stackoverflow.com/questions/21377656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2770850/" ]
Assuming these are parallel arrays (the first entry in `eenhedennamen` uses the first entry in `value`), you can loop through with jQuery's [`$.each`](http://api.jquery.com/jQuery.each), which gives you the index and the entry for each entry, and build the object from the loop. ``` var obj = {}; $.each(eenhedennamen, ...
You can use [`Array.prototype.reduce`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) Try this: ``` var eenhedennamen = ['unit1', 'unit2', 'unit3']; var value = [1,2,3]; var arr3 = eenhedennamen.reduce(function(obj, val, i) { obj[val] = value[i]; return obj; }, ...
33,106,871
I have a batch script runs python script continuously in a loop. ``` :start python log_capture.py > log.txt goto start ``` I want to print the output of each iteration in a .txt file. I am using following command get output from log\_capture.py to a log.txt file. ``` python log_capture.py >log.txt ``` But in the...
2015/10/13
[ "https://Stackoverflow.com/questions/33106871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5138377/" ]
I have used this service in the past and I noticed today that text messages sent were not received. Looking into this a bit further it seems something happened due to folks using this service to spam... and it's not working at present. Not sure what the future holds... See: [issue listed on textbelt](https://github.com...
2-563-567-890 doesn't look like a valid US phone number, so I would double-check that. There is also an international endpoint, `/intl`, but it tends to be less reliable.
20,307,590
I am trying to make an HTTP POST request using javascript and connecting it to an onclick event. For example, if someone clicks on a button then make a HTTP POST request to `http://www.example.com/?test=test1&test2=test2`. It just needs to hit the url and can close the connection. I've messed around in python and go...
2013/12/01
[ "https://Stackoverflow.com/questions/20307590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2159019/" ]
You need to use `XMLHttpRequest` (see [MDN](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)). ``` var xhr = new XMLHttpRequest(); xhr.open("POST", url, false); xhr.onload = // something document.getElementById("your_button's_ID").addEventListener("click", function() {xhr.send(data)}, false ); ...
If you can include the JQuery library, then I'd suggest you look in to the jQuery .ajax() method (<http://api.jquery.com/jQuery.ajax/>): ``` $.ajax("http://www.example.com/", { type: 'POST', data: { test: 'test1', test2: 'test2' } }) ```
17,793,742
I want to profile python code on Widnows 7. I would like to use something a little more user friendly than the raw dump of cProfile. In that search I found the GUI RunSnakeRun, but I cannot find a way to download RunSnakeRun on Windows. Is it possible to use RunSnakeRun on windows or what other tools could I use? **Ed...
2013/07/22
[ "https://Stackoverflow.com/questions/17793742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417902/" ]
The standard solution is to use cProfile (which is in the standard library) and then open the profiles in RunSnakeRun: <http://www.vrplumber.com/programming/runsnakerun/> cProfile, however only profiles at the per-functions level. If you want line by line profiling try line profiler: <https://github.com/rkern/line_pro...
I installed runsnake following these [installation instructions](http://www.vrplumber.com/programming/runsnakerun/). The step `python runsnake.py profile.pfl` failed because the installation step (`easy_install SquareMap RunSnakeRun`) did not create a file `runsnake.py`. For me (on Ubuntu), the installation step cre...
17,793,742
I want to profile python code on Widnows 7. I would like to use something a little more user friendly than the raw dump of cProfile. In that search I found the GUI RunSnakeRun, but I cannot find a way to download RunSnakeRun on Windows. Is it possible to use RunSnakeRun on windows or what other tools could I use? **Ed...
2013/07/22
[ "https://Stackoverflow.com/questions/17793742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417902/" ]
The standard solution is to use cProfile (which is in the standard library) and then open the profiles in RunSnakeRun: <http://www.vrplumber.com/programming/runsnakerun/> cProfile, however only profiles at the per-functions level. If you want line by line profiling try line profiler: <https://github.com/rkern/line_pro...
There's also [py-spy](https://github.com/benfred/py-spy), written in Rust, safe to use even in production, without modifying any code. Works on Windows, to install run `pip install py-spy`. From there you can run `py-spy record -o profile.svg -- python myprogram.py` which produces nice flame graphs.
72,452,208
I'm trying to make a publisher for a Ublox GPS sensor, but I'm getting this ROS error: > > ubuntu@fieldrover:~/field-rover-gps/gps/gps\_pkg$ cd > ~/field-rover-gps/gps/gps\_pkg/ && colcon build && . install/setup.bash > && ros2 run gps\_pkg gps > > > Starting >>> gps\_pkg Finished <<< gps\_pkg [2.98s] > > > Summa...
2022/05/31
[ "https://Stackoverflow.com/questions/72452208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12497264/" ]
As it already has been pointed outed both in the comments and the answer by *@AbhinavMathur*, in order to improve performance you need to implement [*Doubly linked list*](https://en.wikipedia.org/wiki/Doubly_linked_list) data structure. Note that it's mandatory to create your *own implementation* that will maintain a ...
Using an array, you're setting the "removed" elements as `-1`; repeatedly skipping them in each traversal causes the performance penalty. Instead of an array, use a [doubly linked list](https://www.geeksforgeeks.org/doubly-linked-list/). Each removal can be easily done in `O(1)` time, and each left/right operation wou...
52,787,147
I want to use CTR mode in DES algorithm in python by using PyCryptodome package. My code presented at the end of this post. However I got this error: "TypeError: Impossible to create a safe nonce for short block sizes". It is worth to mention that, this code work well for AES algorithm but it does not work for DES, DES...
2018/10/12
[ "https://Stackoverflow.com/questions/52787147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9982452/" ]
The library [defines the nonce](https://www.pycryptodome.org/en/latest/src/cipher/classic.html#ctr-mode) as that part of the counter block that is not incremented. Since the block is only 64 bits long, it is hard to securely define how long that nonce should be, given the danger of wraparound (if you encrypt a lot of ...
``` bs = DES.block_size plen = bs - len(plaintext) % bs padding = [plen] * plen padding = pack('b' * plen, *padding) key = get_random_bytes(8) nonce = Random.get_random_bytes(4) ctr = Counter.new(32, prefix=nonce) cipher = DES.new(key, DES.MODE_CTR,counter=ctr) ciphertext = cipher.encrypt(plaintext+padding) ```
52,416,852
I am trying to use your project named dask-spark proposed by Matthew Rocklin. When adding the dask-spark into my project, I have a problem: Waiting for workers as shown in the following figure. Here, I run two worker nodes (dask) as dask-worker tcp://ubuntu8:8786 and tcp://ubuntu9:8786 and run two worker nodes (spar...
2018/09/20
[ "https://Stackoverflow.com/questions/52416852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have revised the program in core.py, as: ``` def spark_to_dask(sc, loop=None): """ Launch a Dask cluster from a Spark Context """ cluster = LocalCluster(n_workers=None, loop=loop, threads_per_worker=None) rdd = sc.parallelize(range(1000)) address = cluster.scheduler.address ``` Following which,...
As noted in the README of the project, dask-spark is not mature. It was a weekend project and I do not recommend its use. Instead, I recommend launching Dask directly using one of the mechanisms described here: <http://dask.pydata.org/en/latest/setup.html> If you have to use Mesos then I'm not sure I'll be of much h...
59,697,566
My input is a list, say `l` It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`. If the list has only 4 elements then the third variable (`c`) should be `None`. If python had an increment (++) operator I could do something like this. ``` l = [4 or 5 string inp...
2020/01/11
[ "https://Stackoverflow.com/questions/59697566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11316253/" ]
You're trying to use a C solution because you're unfamiliar with Python's tools. Using unpacking is much cleaner than trying to emulate `++`: ``` a, b, *c, d, e = l c = c[0] if c else None ``` The `*c` target receives a list of all elements of `l` that weren't unpacked into the other targets. If this list is nonempt...
I can't see that you really need to be incrementing at all since you have fixed positions for each variable subject to your c condition. ``` l = [4 or 5 string inputs] a = l[0] b = l[1] if len(l) > 4: c = l[2] d = l[3] e = l[4] else: c = None d = l[2] e = l[3] ```
59,697,566
My input is a list, say `l` It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`. If the list has only 4 elements then the third variable (`c`) should be `None`. If python had an increment (++) operator I could do something like this. ``` l = [4 or 5 string inp...
2020/01/11
[ "https://Stackoverflow.com/questions/59697566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11316253/" ]
In the specific case of this question, [list unpacking is the best solution](https://stackoverflow.com/a/59697622/1399279). For other users needing to emulate `++` for other purposes (typically the desire to increment without an explicit `i += 1` statement), they can use [`itertools.count`](https://docs.python.org/3/l...
I can't see that you really need to be incrementing at all since you have fixed positions for each variable subject to your c condition. ``` l = [4 or 5 string inputs] a = l[0] b = l[1] if len(l) > 4: c = l[2] d = l[3] e = l[4] else: c = None d = l[2] e = l[3] ```
59,697,566
My input is a list, say `l` It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`. If the list has only 4 elements then the third variable (`c`) should be `None`. If python had an increment (++) operator I could do something like this. ``` l = [4 or 5 string inp...
2020/01/11
[ "https://Stackoverflow.com/questions/59697566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11316253/" ]
You're trying to use a C solution because you're unfamiliar with Python's tools. Using unpacking is much cleaner than trying to emulate `++`: ``` a, b, *c, d, e = l c = c[0] if c else None ``` The `*c` target receives a list of all elements of `l` that weren't unpacked into the other targets. If this list is nonempt...
There is no ++ operator in Python. A similar question to this was answered here [Behaviour of increment and decrement operators in Python](https://stackoverflow.com/questions/1485841/behaviour-of-increment-and-decrement-operators-in-python)
59,697,566
My input is a list, say `l` It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`. If the list has only 4 elements then the third variable (`c`) should be `None`. If python had an increment (++) operator I could do something like this. ``` l = [4 or 5 string inp...
2020/01/11
[ "https://Stackoverflow.com/questions/59697566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11316253/" ]
You're trying to use a C solution because you're unfamiliar with Python's tools. Using unpacking is much cleaner than trying to emulate `++`: ``` a, b, *c, d, e = l c = c[0] if c else None ``` The `*c` target receives a list of all elements of `l` that weren't unpacked into the other targets. If this list is nonempt...
In the specific case of this question, [list unpacking is the best solution](https://stackoverflow.com/a/59697622/1399279). For other users needing to emulate `++` for other purposes (typically the desire to increment without an explicit `i += 1` statement), they can use [`itertools.count`](https://docs.python.org/3/l...
59,697,566
My input is a list, say `l` It can either contain 4 or 5 elements. I want to assign it to 5 variables , say `a`, `b`, `c`, `d` and `e`. If the list has only 4 elements then the third variable (`c`) should be `None`. If python had an increment (++) operator I could do something like this. ``` l = [4 or 5 string inp...
2020/01/11
[ "https://Stackoverflow.com/questions/59697566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11316253/" ]
In the specific case of this question, [list unpacking is the best solution](https://stackoverflow.com/a/59697622/1399279). For other users needing to emulate `++` for other purposes (typically the desire to increment without an explicit `i += 1` statement), they can use [`itertools.count`](https://docs.python.org/3/l...
There is no ++ operator in Python. A similar question to this was answered here [Behaviour of increment and decrement operators in Python](https://stackoverflow.com/questions/1485841/behaviour-of-increment-and-decrement-operators-in-python)
66,593,382
To run `pytest` within GitHub Actions, I have to pass some `secrets` for Python running environ. e.g., ``` - name: Test env vars for python run: python -c 'import os;print(os.environ)' env: TEST_ENV: 'hello world' TEST_SECRET: ${{ secrets.MY_TOKEN }} ``` However, the output is as follows, ``` ...
2021/03/12
[ "https://Stackoverflow.com/questions/66593382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/482899/" ]
There are three types of secrets within GitHub Actions. 1. Organization secrets 2. Repository secrets 3. Environment secrets To access Environment secrets, you have to [referencing an environment](https://docs.github.com/en/actions/reference/environments#referencing-an-environment) in your job. (Thanks to @riQQ) [![...
You try the things below: ``` - name: Test env vars for python run: TEST_SECRET=${{ secrets.MY_TOKEN }} python -c 'import os;print(os.environ['TEST_SECRET']) ``` This will pass `${{ secrets.MY_TOKEN }}` directly as an environment variable to the python process and not share with other processes. Then you can u...
12,763,015
Sorry if my title is not correct. Below is the explanation of what i'm looking for. I've coded a small GUI game (let say a snake game) in python, and I want it to be run on Linux machine. I can run this program by just run command "python snake.py" in the terminal. However, I want to combine all my .py files into one...
2012/10/06
[ "https://Stackoverflow.com/questions/12763015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1058861/" ]
You can use [Freeze](http://wiki.python.org/moin/Freeze) for Unix, or [py2exe](http://wiki.python.org/moin/Py2Exe) for Windows. [cx\_freeze](http://cx-freeze.sourceforge.net/), [PyInstaller](http://www.pyinstaller.org/), [bbfreeze](http://www.jroller.com/alessiopace/entry/python_standalone_executables_with_bbfreeze) ...
If you only want it to run on a Linux machine, using Python eggs is the simplest way. python snake.egg will try to execute the **main**.py inside the egg. Python eggs are meant to be packages, and basically is a zip file with metadata files included.
57,035,263
I'm trying RSA encrypt text with JSEncrypt(javascript) and decrypt with python crypto (python3.7). Most of the time, it works. But sometimes, python cannot decrypt. ```js const encrypt = new JSEncrypt() encrypt.setPublicKey(publicKey) encrypt.encrypt(data) ``` ```py from base64 import b64decode from Crypto.Cipher im...
2019/07/15
[ "https://Stackoverflow.com/questions/57035263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11784926/" ]
If the ciphertext is Base64-decoded, the reason becomes clearer: The ciphertext doesn't have the length of the modulus (128 byte), but only 127 byte, i.e. it isn't padded to the length of the modulus with leading `0x00` values. This ciphertext is invalid (see [RFC8017](https://www.rfc-editor.org/rfc/rfc8017#section-7.2...
Thanks to Topaco, it solved. ``` from base64 import b64decode, b16decode from Crypto.Cipher import PKCS1_v1_5 as Cipher_PKCS1_v1_5 from Crypto.PublicKey import RSA crypt_text = \ "R247QGAFEeSW1wwXQuNf/cm/K/tnW5xwXLb5MuHW6/Fr8SRklM0n6Rmj07TgFwApeN72j/avXAvpoR70U92ehOJsDnnZguYN4u2bMXHDyTNmAXuJw9xPm59bSGcvgRm1X+V0Zq...
54,813,438
I am looking to extract content from [a page](https://app.updateimpact.com/treeof/org.json4s/json4s-native_2.11/3.5.2) that is requires a list node to be selected. I have retrieve the page html using python and Selenium. Passing the page source to BS4 I can parse out the content that I am looking for using ``` ope...
2019/02/21
[ "https://Stackoverflow.com/questions/54813438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2033214/" ]
``` =Unique(A:B) ``` should be enough to return non-duplicate rows <https://support.google.com/docs/answer/3093198?hl=en> [![enter image description here](https://i.stack.imgur.com/w77Gm.png)](https://i.stack.imgur.com/w77Gm.png) You can also use Sortn: ``` =sortn(A:B,9E+99,2,1,true,2,true) ```
``` =QUERY(QUERY(A1:B, "select A, B, count(A) group by A, B", 1), "select Col1, Col2 where Col1 is not null", 1) ``` [![](https://i.stack.imgur.com/oQyB2.png)](https://i.stack.imgur.com/oQyB2.png)
54,813,438
I am looking to extract content from [a page](https://app.updateimpact.com/treeof/org.json4s/json4s-native_2.11/3.5.2) that is requires a list node to be selected. I have retrieve the page html using python and Selenium. Passing the page source to BS4 I can parse out the content that I am looking for using ``` ope...
2019/02/21
[ "https://Stackoverflow.com/questions/54813438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2033214/" ]
``` =QUERY(QUERY(A1:B, "select A, B, count(A) group by A, B", 1), "select Col1, Col2 where Col1 is not null", 1) ``` [![](https://i.stack.imgur.com/oQyB2.png)](https://i.stack.imgur.com/oQyB2.png)
You can also install my add-on called [Flookup](https://gsuite.google.com/marketplace/app/flookup/593806014962) and use the function below: ``` ULIST(colArray, [indexNum], [threshold]) ``` * **colArray** The range from which you want to return unique values. * **indexNum** The column index to analyse for unique valu...
54,813,438
I am looking to extract content from [a page](https://app.updateimpact.com/treeof/org.json4s/json4s-native_2.11/3.5.2) that is requires a list node to be selected. I have retrieve the page html using python and Selenium. Passing the page source to BS4 I can parse out the content that I am looking for using ``` ope...
2019/02/21
[ "https://Stackoverflow.com/questions/54813438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2033214/" ]
``` =Unique(A:B) ``` should be enough to return non-duplicate rows <https://support.google.com/docs/answer/3093198?hl=en> [![enter image description here](https://i.stack.imgur.com/w77Gm.png)](https://i.stack.imgur.com/w77Gm.png) You can also use Sortn: ``` =sortn(A:B,9E+99,2,1,true,2,true) ```
You can also install my add-on called [Flookup](https://gsuite.google.com/marketplace/app/flookup/593806014962) and use the function below: ``` ULIST(colArray, [indexNum], [threshold]) ``` * **colArray** The range from which you want to return unique values. * **indexNum** The column index to analyse for unique valu...
31,695,910
I'm parsing the US Patent XML files (downloaded from [Google patent dumps](https://www.google.com/googlebooks/uspto-patents-redbook.html)) using Python and Beautifulsoup; parsed data is exported to MYSQL database. Each year's data contains close to 200-300K patents - which means parsing 200-300K xml files. The server...
2015/07/29
[ "https://Stackoverflow.com/questions/31695910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2404998/" ]
Here is a [tutorial on multi-threading](http://www.tutorialspoint.com/python/python_multithreading.htm), because currently that code will run on 1 thread, 1 core. Remove all try/except statements and handle the code properly. Exceptions are expensive. Run a [profiler](http://docs.python.org/2/library/profile.html) to...
So, you're doing two things wrong. First, you're using BeautifulSoup, which is slow, and second, you're using a "find" call, which is also slow. As a first cut, look at `lxml`'s [ability to pre-compile xpath queries](https://lxml.de/xpathxslt.html) (Look at the heading "The Xpath class). That will give you a **huge** ...
11,707,151
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. i have seen questions regarding this particular problem on here before - but i hav...
2012/07/29
[ "https://Stackoverflow.com/questions/11707151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560582/" ]
Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example, ``` import re first = str(input()) second = str(input()) regex = first[:-1] + '(?=' + first[-1] + ')' print(len(re.findall(regex, second))) ```
**Answer** ``` needle=input() haystack=input() counter=0 for i in range(0,len(haystack)): if(haystack[i:len(needle)+i]!=needle): continue counter=counter+1 print(counter) ```
11,707,151
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. i have seen questions regarding this particular problem on here before - but i hav...
2012/07/29
[ "https://Stackoverflow.com/questions/11707151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560582/" ]
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution: ``` first = str(input()) second = str(input()) def count_needle(first, second): location = str.find(second,first) if location == -1: return 0 # none whatsoever e...
As mentioned by Matthew Adams the best way to do it is using python'd re module [Python re module](http://docs.python.org/library/re.html). For your case the solution would look something like this: ``` import re def find_needle_in_heystack(needle, heystack): return len(re.findall(needle, heystack)) ``` Since yo...
11,707,151
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. i have seen questions regarding this particular problem on here before - but i hav...
2012/07/29
[ "https://Stackoverflow.com/questions/11707151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560582/" ]
Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example, ``` import re first = str(input()) second = str(input()) regex = first[:-1] + '(?=' + first[-1] + ')' print(len(re.findall(regex, second))) ```
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution: ``` first = str(input()) second = str(input()) def count_needle(first, second): location = str.find(second,first) if location == -1: return 0 # none whatsoever e...
11,707,151
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. i have seen questions regarding this particular problem on here before - but i hav...
2012/07/29
[ "https://Stackoverflow.com/questions/11707151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560582/" ]
Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example, ``` import re first = str(input()) second = str(input()) regex = first[:-1] + '(?=' + first[-1] + ')' print(len(re.findall(regex, second))) ```
``` needle = "ss" haystack = "ssi lass 2 vecess estan ss." print 'needle occurs %d times in haystack.' % haystack.count(needle) ```
11,707,151
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. i have seen questions regarding this particular problem on here before - but i hav...
2012/07/29
[ "https://Stackoverflow.com/questions/11707151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560582/" ]
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution: ``` first = str(input()) second = str(input()) def count_needle(first, second): location = str.find(second,first) if location == -1: return 0 # none whatsoever e...
even your aproach could be imo simplified (which uses the fact, that find returns -1, while you aks it to search from non existent offset): ``` >>> x = 'xoxoxo' >>> start = x.find('o') >>> indexes = [] >>> while start > -1: ... indexes.append(start) ... start = x.find('o',start+1) >>> indexes [1, 3, 5] ```
11,707,151
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. i have seen questions regarding this particular problem on here before - but i hav...
2012/07/29
[ "https://Stackoverflow.com/questions/11707151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560582/" ]
Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example, ``` import re first = str(input()) second = str(input()) regex = first[:-1] + '(?=' + first[-1] + ')' print(len(re.findall(regex, second))) ```
As mentioned by Matthew Adams the best way to do it is using python'd re module [Python re module](http://docs.python.org/library/re.html). For your case the solution would look something like this: ``` import re def find_needle_in_heystack(needle, heystack): return len(re.findall(needle, heystack)) ``` Since yo...
11,707,151
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. i have seen questions regarding this particular problem on here before - but i hav...
2012/07/29
[ "https://Stackoverflow.com/questions/11707151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560582/" ]
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution: ``` first = str(input()) second = str(input()) def count_needle(first, second): location = str.find(second,first) if location == -1: return 0 # none whatsoever e...
``` needle = "ss" haystack = "ssi lass 2 vecess estan ss." print 'needle occurs %d times in haystack.' % haystack.count(needle) ```
11,707,151
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. i have seen questions regarding this particular problem on here before - but i hav...
2012/07/29
[ "https://Stackoverflow.com/questions/11707151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560582/" ]
Check out regular expressions, python's `re` module (http://docs.python.org/library/re.html). For example, ``` import re first = str(input()) second = str(input()) regex = first[:-1] + '(?=' + first[-1] + ')' print(len(re.findall(regex, second))) ```
even your aproach could be imo simplified (which uses the fact, that find returns -1, while you aks it to search from non existent offset): ``` >>> x = 'xoxoxo' >>> start = x.find('o') >>> indexes = [] >>> while start > -1: ... indexes.append(start) ... start = x.find('o',start+1) >>> indexes [1, 3, 5] ```
11,707,151
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. i have seen questions regarding this particular problem on here before - but i hav...
2012/07/29
[ "https://Stackoverflow.com/questions/11707151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560582/" ]
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution: ``` first = str(input()) second = str(input()) def count_needle(first, second): location = str.find(second,first) if location == -1: return 0 # none whatsoever e...
**Answer** ``` needle=input() haystack=input() counter=0 for i in range(0,len(haystack)): if(haystack[i:len(needle)+i]!=needle): continue counter=counter+1 print(counter) ```
11,707,151
allow me to preface this by saying that i am learning python on my own as part of my own curiosity, and i was recommended a free online computer science course that is publicly available, so i apologize if i am using terms incorrectly. i have seen questions regarding this particular problem on here before - but i hav...
2012/07/29
[ "https://Stackoverflow.com/questions/11707151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1560582/" ]
I think Matthew and darshan have the best solution. I will just post a variation which is based on your solution: ``` first = str(input()) second = str(input()) def count_needle(first, second): location = str.find(second,first) if location == -1: return 0 # none whatsoever e...
Here you go : ``` first = str(input()) second = str(input()) x=len(first) counter=0 for i in range(0,len(second)): if first==second[i:(x+i)]: counter=counter+1 print(counter) ```
53,844,589
I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result. Step 1: Code: ``` class Avengers(object): def __init__(self): print('hello') avenger1 = Avengers() avenger1.__init__(self) ``` Step 2: ``` ctrl + B ``` Step 3: Result: ***Repl Closed***
2018/12/19
[ "https://Stackoverflow.com/questions/53844589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983752/" ]
That's because you're only declaring a class, not instantiating it. Your variable avenger1 exists within the **init** function, therefore it isn't being called. Indentation matters in python. Try this: ``` class Avengers(object): def __init__(self): print('hello') if __name__ == "__main__": avenger1 = Avenger...
You are not instantiating the class. Try something like: ``` class Avengers(object): def __init__(self): print('hello') avenger1 = Avengers() avenger1.__init__(self) avengers = Avengers() # Initiates the class ``` When you instantiate a class like this, it will execute the `__init__` function for that...
53,844,589
I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result. Step 1: Code: ``` class Avengers(object): def __init__(self): print('hello') avenger1 = Avengers() avenger1.__init__(self) ``` Step 2: ``` ctrl + B ``` Step 3: Result: ***Repl Closed***
2018/12/19
[ "https://Stackoverflow.com/questions/53844589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983752/" ]
You are not instantiating the class. Try something like: ``` class Avengers(object): def __init__(self): print('hello') avenger1 = Avengers() avenger1.__init__(self) avengers = Avengers() # Initiates the class ``` When you instantiate a class like this, it will execute the `__init__` function for that...
The previous answers are correct, but also note that Avengers class in its constructor is initializing another instance of Avengers. This means when an Avengers object is created, it is creating another Avengers object which is creating another Avengers object and so on. The `__init__` function is falling into an inf...
53,844,589
I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result. Step 1: Code: ``` class Avengers(object): def __init__(self): print('hello') avenger1 = Avengers() avenger1.__init__(self) ``` Step 2: ``` ctrl + B ``` Step 3: Result: ***Repl Closed***
2018/12/19
[ "https://Stackoverflow.com/questions/53844589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983752/" ]
That's because you're only declaring a class, not instantiating it. Your variable avenger1 exists within the **init** function, therefore it isn't being called. Indentation matters in python. Try this: ``` class Avengers(object): def __init__(self): print('hello') if __name__ == "__main__": avenger1 = Avenger...
First, let me fix the code ``` class Avengers(object): def __init__(self): print('hello') avenger1 = Avengers() avenger1.init(self) ``` okay, here you creating a class called Avengers. why its not produce anything? because you never initialize that class (creating an object). so here we go: ``` clas...
53,844,589
I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result. Step 1: Code: ``` class Avengers(object): def __init__(self): print('hello') avenger1 = Avengers() avenger1.__init__(self) ``` Step 2: ``` ctrl + B ``` Step 3: Result: ***Repl Closed***
2018/12/19
[ "https://Stackoverflow.com/questions/53844589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983752/" ]
That's because you're only declaring a class, not instantiating it. Your variable avenger1 exists within the **init** function, therefore it isn't being called. Indentation matters in python. Try this: ``` class Avengers(object): def __init__(self): print('hello') if __name__ == "__main__": avenger1 = Avenger...
The previous answers are correct, but also note that Avengers class in its constructor is initializing another instance of Avengers. This means when an Avengers object is created, it is creating another Avengers object which is creating another Avengers object and so on. The `__init__` function is falling into an inf...
53,844,589
I wrote the below python script in sublime text3 on executing it ( ctrl + B ) it is not giving any result. Step 1: Code: ``` class Avengers(object): def __init__(self): print('hello') avenger1 = Avengers() avenger1.__init__(self) ``` Step 2: ``` ctrl + B ``` Step 3: Result: ***Repl Closed***
2018/12/19
[ "https://Stackoverflow.com/questions/53844589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9983752/" ]
First, let me fix the code ``` class Avengers(object): def __init__(self): print('hello') avenger1 = Avengers() avenger1.init(self) ``` okay, here you creating a class called Avengers. why its not produce anything? because you never initialize that class (creating an object). so here we go: ``` clas...
The previous answers are correct, but also note that Avengers class in its constructor is initializing another instance of Avengers. This means when an Avengers object is created, it is creating another Avengers object which is creating another Avengers object and so on. The `__init__` function is falling into an inf...
21,369,607
I am trying to convert the following python extract to C ``` tvip = "192.168.0.3" myip = "192.168.0.7" mymac = "00-0c-29-3e-b1-4f" appstring = "iphone..iapp.samsung" tvappstring = "iphone.UE55C8000.iapp.samsung" remotename = "Python Samsung Remote" ipencoded = base64.b64encode(myip) macencoded = base64.b64encode(mym...
2014/01/26
[ "https://Stackoverflow.com/questions/21369607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/126280/" ]
`fragment` lexer rules can only be used by other lexer rules: these will never become a token on their own. Therefor, you cannot use `fragment` rules in parser rules.
The `fragment` is not the root cause. First, try to reproduce your errors: ------------------------------------ When compiling your Test.g4, it will appear warnings below: ``` warning(156): Test.g4:11:21: invalid escape sequence \" warning(156): Test.g4:123:59: invalid escape sequence \" warning(146): Test.g4:11:0: ...
59,415,503
I am trying to run the object detection API in tensorflow following this tutorial / accompanying code: <https://gilberttanner.com/blog/creating-your-own-objectdetector> When I type `python2 generate_tfrecord.py --csv_input=images_train.csv --image_dir=images\train --output_path=train.record` into the terminal, I see a...
2019/12/19
[ "https://Stackoverflow.com/questions/59415503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11756066/" ]
What you have here is an async function that performs an async operation, where that operation does *not* use promises. This means that you need to setup a function that manages and returns a promise explicitly. You don't need the `async` keyword here, since you want to explicitly `return` a `Promise` that you create, ...
Basically, you are trying to write an `async` function without having anything in that function to await. You use async/await when there is some asynchronous-ness in the code, while in yours, there isn't. This is an example that might be useful: ``` const getItemsAsync = async () => { const res = await DoSomethin...
63,664,484
I have to create a function called read\_data that takes a filename as its only parameter. This function must then open the file with the given name and return a dictionary where the keys are the location names in the file and the values are a list of the readings. The result of the first function works and displays: ...
2020/08/31
[ "https://Stackoverflow.com/questions/63664484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14001036/" ]
Given: ``` di={'Monday': [67 , 43], 'Tuesday': [14, 26], 'Wednesday': [68, 44], 'Thursday':[15, 35],'Friday':[70, 31],'Saturday':[34, 39],'Sunday':[22, 18]} ``` You can do: ``` >>> {k:sum(v)/len(v) for k,v in di.items()} {'Monday': 55.0, 'Tuesday': 20.0, 'Wednesday': 56.0, 'Thursday': 25.0, 'Friday': 50.5, 'Saturda...
You were close but had at least one problem. One was this: `Friday’:[50.50],’Saturday’;[36.50],’Sunday’: [22, 18]` Notice ’Saturday’ is followed by a semicolon, not a colon. That's in both examples. Also, notice your text changes color from red to blue. That usually (this case included) means that you switched from s...
46,078,088
I want to upload an image on Google Cloud Storage from a python script. This is my code: ``` from oauth2client.service_account import ServiceAccountCredentials from googleapiclient import discovery scopes = ['https://www.googleapis.com/auth/devstorage.full_control'] credentials = ServiceAccountCredentials.from_json_k...
2017/09/06
[ "https://Stackoverflow.com/questions/46078088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7219743/" ]
If you want to upload your image from file. ``` import os from google.cloud import storage def upload_file_to_gcs(bucket_name, local_path, local_file_name, target_key): try: client = storage.Client() bucket = client.bucket(bucket_name) full_file_path = os.path.join(local_path, local_file_n...
`MediaIoBaseUpload` expects an [`io.Base`](https://docs.python.org/3/library/io.html#io.IOBase)-like object and raises following error: ``` 'numpy.ndarray' object has no attribute 'seek' ``` upon receiving a ndarray object. To solve it I am using `TemporaryFile` and `numpy.ndarray().tofile()` ``` from oauth2clien...
46,078,088
I want to upload an image on Google Cloud Storage from a python script. This is my code: ``` from oauth2client.service_account import ServiceAccountCredentials from googleapiclient import discovery scopes = ['https://www.googleapis.com/auth/devstorage.full_control'] credentials = ServiceAccountCredentials.from_json_k...
2017/09/06
[ "https://Stackoverflow.com/questions/46078088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7219743/" ]
In my case, I wanted to upload a PDF document to Cloud Storage from bytes. When I tried the below, it created a text file with my byte string in it. ``` blob.upload_from_string(bytedata) ``` In order to create an actual PDF file using the byte string I had to do: ``` blob.upload_from_string(bytedata, content_type...
`MediaIoBaseUpload` expects an [`io.Base`](https://docs.python.org/3/library/io.html#io.IOBase)-like object and raises following error: ``` 'numpy.ndarray' object has no attribute 'seek' ``` upon receiving a ndarray object. To solve it I am using `TemporaryFile` and `numpy.ndarray().tofile()` ``` from oauth2clien...
46,078,088
I want to upload an image on Google Cloud Storage from a python script. This is my code: ``` from oauth2client.service_account import ServiceAccountCredentials from googleapiclient import discovery scopes = ['https://www.googleapis.com/auth/devstorage.full_control'] credentials = ServiceAccountCredentials.from_json_k...
2017/09/06
[ "https://Stackoverflow.com/questions/46078088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7219743/" ]
In my case, I wanted to upload a PDF document to Cloud Storage from bytes. When I tried the below, it created a text file with my byte string in it. ``` blob.upload_from_string(bytedata) ``` In order to create an actual PDF file using the byte string I had to do: ``` blob.upload_from_string(bytedata, content_type...
If you want to upload your image from file. ``` import os from google.cloud import storage def upload_file_to_gcs(bucket_name, local_path, local_file_name, target_key): try: client = storage.Client() bucket = client.bucket(bucket_name) full_file_path = os.path.join(local_path, local_file_n...
46,078,088
I want to upload an image on Google Cloud Storage from a python script. This is my code: ``` from oauth2client.service_account import ServiceAccountCredentials from googleapiclient import discovery scopes = ['https://www.googleapis.com/auth/devstorage.full_control'] credentials = ServiceAccountCredentials.from_json_k...
2017/09/06
[ "https://Stackoverflow.com/questions/46078088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7219743/" ]
If you want to upload your image from file. ``` import os from google.cloud import storage def upload_file_to_gcs(bucket_name, local_path, local_file_name, target_key): try: client = storage.Client() bucket = client.bucket(bucket_name) full_file_path = os.path.join(local_path, local_file_n...
Here is how to directly upload a PIL Image from memory: ```py from google.cloud import storage import io from PIL import Image # Define variables bucket_name = XXXXX destination_blob_filename = XXXXX # Configure bucket and blob client = storage.Client() bucket = client.bucket(bucket_name) im = Image.open("test.jpg"...
46,078,088
I want to upload an image on Google Cloud Storage from a python script. This is my code: ``` from oauth2client.service_account import ServiceAccountCredentials from googleapiclient import discovery scopes = ['https://www.googleapis.com/auth/devstorage.full_control'] credentials = ServiceAccountCredentials.from_json_k...
2017/09/06
[ "https://Stackoverflow.com/questions/46078088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7219743/" ]
In my case, I wanted to upload a PDF document to Cloud Storage from bytes. When I tried the below, it created a text file with my byte string in it. ``` blob.upload_from_string(bytedata) ``` In order to create an actual PDF file using the byte string I had to do: ``` blob.upload_from_string(bytedata, content_type...
Here is how to directly upload a PIL Image from memory: ```py from google.cloud import storage import io from PIL import Image # Define variables bucket_name = XXXXX destination_blob_filename = XXXXX # Configure bucket and blob client = storage.Client() bucket = client.bucket(bucket_name) im = Image.open("test.jpg"...
35,144,550
My ubuntu is 14.04 LTS. When I install cryptography, the error is: ``` Installing egg-scripts. uses namespace packages but the distribution does not require setuptools. Getting distribution for 'cryptography==0.2.1'. no previously-included directories found matching 'documentation/_build' zip_safe flag not set; anal...
2016/02/02
[ "https://Stackoverflow.com/questions/35144550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2890633/" ]
The answer is on the docs of `cryptography`'s [installation section](https://cryptography.io/en/latest/installation/#building-cryptography-on-linux) which pretty much reflects Angelos' answer: Quoting it: > > For Debian and **Ubuntu**, the following command will ensure that the > required dependencies are installed...
I had the same problem when pip installing the cryptography module on Ubuntu 14.04. I solved it by installing libffi-dev: ``` apt-get install -y libffi-dev ``` Then I got the following error: ``` build/temp.linux-x86_64-3.4/_openssl.c:431:25: fatal error: openssl/aes.h: No such file or directory #include <openssl/...
35,144,550
My ubuntu is 14.04 LTS. When I install cryptography, the error is: ``` Installing egg-scripts. uses namespace packages but the distribution does not require setuptools. Getting distribution for 'cryptography==0.2.1'. no previously-included directories found matching 'documentation/_build' zip_safe flag not set; anal...
2016/02/02
[ "https://Stackoverflow.com/questions/35144550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2890633/" ]
I had the same problem when pip installing the cryptography module on Ubuntu 14.04. I solved it by installing libffi-dev: ``` apt-get install -y libffi-dev ``` Then I got the following error: ``` build/temp.linux-x86_64-3.4/_openssl.c:431:25: fatal error: openssl/aes.h: No such file or directory #include <openssl/...
Installing libssl-dev and python-dev was enough for me on ubuntu 16.04.
35,144,550
My ubuntu is 14.04 LTS. When I install cryptography, the error is: ``` Installing egg-scripts. uses namespace packages but the distribution does not require setuptools. Getting distribution for 'cryptography==0.2.1'. no previously-included directories found matching 'documentation/_build' zip_safe flag not set; anal...
2016/02/02
[ "https://Stackoverflow.com/questions/35144550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2890633/" ]
The answer is on the docs of `cryptography`'s [installation section](https://cryptography.io/en/latest/installation/#building-cryptography-on-linux) which pretty much reflects Angelos' answer: Quoting it: > > For Debian and **Ubuntu**, the following command will ensure that the > required dependencies are installed...
Installing libssl-dev and python-dev was enough for me on ubuntu 16.04.
70,021,042
``` import spacy nlp = spacy.load('en_core_web_sm') from spacy.lemmatizer import Lemmatizer from spacy.lang.en import LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES lemmatizer = Lemmatizer(LEMMA_INDEX, LEMMA_EXC, LEMMA_RULES) lemmattizer('chunkles', 'NOUN') ``` Can anyone help me? I'm using Version 3 of python
2021/11/18
[ "https://Stackoverflow.com/questions/70021042", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17447993/" ]
The official document shows that after spacy 3.0, the lemmatizer has become a standalone pipeline component. Therefore, you should install the spacy whose version is smaller than 3.0. The link is as follow: <https://spacy.io/api/lemmatizer>
try: doc = nlp('chuckles') doc[0].lemma\_
9,345,250
I have tried: ``` >>> l = [1,2,3] >>> x = 1 >>> x in l and lambda: print("Foo") x in l && print "Horray" ^ SyntaxError: invalid syntax ``` A bit of googling revealed that `print` is a statement in `python2` whereas it's a function in `python3`. But, I have tried the above snipped in `python3` and it...
2012/02/18
[ "https://Stackoverflow.com/questions/9345250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218583/" ]
``` l = [1, 2, 3] x = 1 if x in l: print "Foo" ``` I'm not being a smart ass, this is the way to do it in **one line**. Or, if you're using Python3: ``` if x in l: print("Foo") ```
Getting rid of the shortcomings of print as a statement in Python2.x using `from __future__ import print_function` is the first step. Then the following all work: ``` x in l and (lambda: print("yes"))() # what an overkill! (x in l or print("no")) and print("yes") # note the order, print returns None print("yes"...
9,345,250
I have tried: ``` >>> l = [1,2,3] >>> x = 1 >>> x in l and lambda: print("Foo") x in l && print "Horray" ^ SyntaxError: invalid syntax ``` A bit of googling revealed that `print` is a statement in `python2` whereas it's a function in `python3`. But, I have tried the above snipped in `python3` and it...
2012/02/18
[ "https://Stackoverflow.com/questions/9345250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218583/" ]
``` l = [1, 2, 3] x = 1 if x in l: print "Foo" ``` I'm not being a smart ass, this is the way to do it in **one line**. Or, if you're using Python3: ``` if x in l: print("Foo") ```
1. If you want to print something different in both true and false cases, use a conditional **expression** to create the value to print: `print ('foo' if x in l else 'bar')`. 2. If you just want a function in Python 2 that outputs, you can try `sys.stdout.write` (after you first `import sys` of course), but keep in min...
9,345,250
I have tried: ``` >>> l = [1,2,3] >>> x = 1 >>> x in l and lambda: print("Foo") x in l && print "Horray" ^ SyntaxError: invalid syntax ``` A bit of googling revealed that `print` is a statement in `python2` whereas it's a function in `python3`. But, I have tried the above snipped in `python3` and it...
2012/02/18
[ "https://Stackoverflow.com/questions/9345250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218583/" ]
`lambda` creates, well a lambda. It needs to be *called* to execute it. You cannot do this that way, because Python doesn't allow statements in this context, only expressions (including function calls). To make `print` a function in Python 2.x, try: ``` from __future__ import print_function x in l and print('foo') `...
Getting rid of the shortcomings of print as a statement in Python2.x using `from __future__ import print_function` is the first step. Then the following all work: ``` x in l and (lambda: print("yes"))() # what an overkill! (x in l or print("no")) and print("yes") # note the order, print returns None print("yes"...
9,345,250
I have tried: ``` >>> l = [1,2,3] >>> x = 1 >>> x in l and lambda: print("Foo") x in l && print "Horray" ^ SyntaxError: invalid syntax ``` A bit of googling revealed that `print` is a statement in `python2` whereas it's a function in `python3`. But, I have tried the above snipped in `python3` and it...
2012/02/18
[ "https://Stackoverflow.com/questions/9345250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218583/" ]
`lambda` creates, well a lambda. It needs to be *called* to execute it. You cannot do this that way, because Python doesn't allow statements in this context, only expressions (including function calls). To make `print` a function in Python 2.x, try: ``` from __future__ import print_function x in l and print('foo') `...
1. If you want to print something different in both true and false cases, use a conditional **expression** to create the value to print: `print ('foo' if x in l else 'bar')`. 2. If you just want a function in Python 2 that outputs, you can try `sys.stdout.write` (after you first `import sys` of course), but keep in min...
61,642,246
What I want to make is angrybirds game. There is a requirement 1.Draw a rectangle randomly between 100 and 200 in length and length 10 in length. 2. Receive the user inputting the launch speed and the launch angle. 3. Project shells square from origin (0,0). 4. If the shell is hit, we'll end it, or we'll continue from ...
2020/05/06
[ "https://Stackoverflow.com/questions/61642246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13483726/" ]
the local declaration has to be like this way, ``` int (*localArr)[M][N]; //pointer to an MxN array //int * localArr[m][N];//An MxN array of pointer to int ```
What do you want to achieve? If you just want to print your 2d array then why don't you use this approach? ``` void print(int localArr[M][N]) { for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { cout << localArr[i][j]; } } } ``` If there are some constraints then Nithees...
61,642,246
What I want to make is angrybirds game. There is a requirement 1.Draw a rectangle randomly between 100 and 200 in length and length 10 in length. 2. Receive the user inputting the launch speed and the launch angle. 3. Project shells square from origin (0,0). 4. If the shell is hit, we'll end it, or we'll continue from ...
2020/05/06
[ "https://Stackoverflow.com/questions/61642246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13483726/" ]
the local declaration has to be like this way, ``` int (*localArr)[M][N]; //pointer to an MxN array //int * localArr[m][N];//An MxN array of pointer to int ```
If we change the sizes to make it easier to fit: ``` #define M 2 #define N 3 ``` Then somewhat graphically the variable `arr` is something like this: ``` +-----+ +--------+--------+--------+--------+--------+--------+ | arr | ---> | [0][0] | [0][1] | [0][2] | [1][0] | [1][1] | [1][2] | +-----+ +--------+...