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
21,310,125
I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation? I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. Thanks in advance.
2014/01/23
[ "https://Stackoverflow.com/questions/21310125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112656/" ]
**AWS Beanstalk:** It is Deploy and manage applications in the AWS cloud without worrying about the infrastructure that runs yor web applications with Elastic Beanstalk. No need to worry about EC2 or else installations. **AWS OpsWorks** AWS OpsWorks is nothing but an application management service that makes it easy for the new DevOps users to model & manage the entire their application
Just use terraform and ECS or EKS. opsworks, elastic beanstalk and cloudformation old tech now. -)
21,310,125
I would like to know what are the advantages and disadvantages of using AWS OpsWorks vs AWS Beanstalk and AWS CloudFormation? I am interested in a system that can be auto scaled to handle any high number of simultaneous web requests (From 1000 requests per minute to 10 million rpm.), including a database layer that can be auto scalable as well. Instead of having a separate instance for each app, Ideally I would like to share some hardware resources efficiently. In the past I have used mostly an EC2 instance + RDS + Cloudfront + S3 The stack system will host some high traffic ruby on rails apps that we are migrating from Heroku, also some python/django apps and some PHP apps as well. Thanks in advance.
2014/01/23
[ "https://Stackoverflow.com/questions/21310125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1112656/" ]
**AWS OpsWorks** - This is a part of AWS management service. It helps to configure the application using scripting. It uses Chef as the devops framework for this application management and operation. There are templates which can be used for configuration of server, database, storage. The templates can also be customized to perform any other task. DevOps Engineers have control on application's dependencies and infrastructure. **AWS Beanstalk** - It provides the environment for language like Java, Node Js, Python, Ruby Go. Elastic Bean stalk provide the resource to run the application. Developers not to worry about the infrastructure and they don't have control on infrastructure. **AWS CloudFormation** - CloudFormation has sample templates to manage the AWS resources in order.
You should use OpsWorks in place of CloudFormation if you need to deploy an application that requires updates to its EC2 instances. If your application uses a lot of AWS resources and services, including EC2, use a combination of CloudFormation and OpsWorks If your application will need other AWS resources, such as database or storage service. In this scenario, use CloudFormation to deploy Elastic Beanstalk along with the other resources.
46,044,003
I'm trying to write a function that guesses a type of a variable represented as a string. So if I've got a variable of some type then in order to find out what type of a variable it is I can use python's `type()` function like this `type(var)`. But how do I concisely and pythonicaly convert the output of this function into a string so that the output would be like 'int' in case of the integer, 'bool' in case of the bool etc. The only way I see I can do this is first use `str(type(var))` and then use a regular expression to strip the part indicating the type. So basically I could write a simple type guessing python function as follows: ``` import ast import re def guess_type(var): return re.findall('\w+',str(type(ast.literal_eval(var))))[1] ``` where var is of type `str`. But my question is "Is there a more simple way to get the same result?" Speaking of performance: ``` In [156]: %timeit guess_type 10000000 loops, best of 3: 28.1 ns per loop. ```
2017/09/04
[ "https://Stackoverflow.com/questions/46044003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8243859/" ]
``` >>> type(0).__name__ 'int' >>> type('').__name__ 'str' >>> type({}).__name__ 'dict' ```
What are you actually trying to do? If you just want to get the name of the class of the object you could use: ``` type(var).__name__ ``` This will give you the name of the class of the object `var`.
7,389,567
I have a webpage generated from python that works as it should, using: ``` print 'Content-type: text/html\n\n' print "" # blank line, end of headers print '<link href="default.css" rel="stylesheet" type="text/css" />' print "<html><head>" ``` I want to add images to this webpage, but when I do this: ``` sys.stdout.write( "Content-type: image/png\n\n" + file("11.png","rb").read() ) print 'Content-type: text/html\n\n' print "" # blank line, end of headers print '<link href="default.css" rel="stylesheet" type="text/css" />' ... ``` All I get is the image, then if I place the image code below my html/text header all I get is the text from the image, ie: ``` <Ï#·öÐδÝZºm]¾|‰k×®]žòåËÛ¶ÃgžyFK–,ÑôéÓU½zuIÒ}÷ݧ&MšH’V¯^­?üð¼1±±±zýõ×%IñññÚºu«*W®¬wß}W.—K3gÎÔÌ™ÿw‹Ú””I’¹w¤¥hdÒd½q÷X•Šˆ²m¿þfïÞ½*]º´éÈs;¥¤¤Ø¿ILLÔˆ#rÊ ``` Also, if I try: ``` print "<img src='11.png'>" ``` I get a broken image in the browser, and browing directly to the image produces a 500 internal server error, with my apache log saying: ``` 8)Exec format error: exec of './../../11.png' failed Premature end of script headers: 11.png ```
2011/09/12
[ "https://Stackoverflow.com/questions/7389567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/828573/" ]
You can use this code to directly embed the image in your HTML: Python 3 ``` import base64 data_uri = base64.b64encode(open('Graph.png', 'rb').read()).decode('utf-8') img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri) print(img_tag) ``` Python 2.7 ``` data_uri = open('11.png', 'rb').read().encode('base64').replace('\n', '') img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri) print(img_tag) ``` Alternatively for Python <2.6: ``` data_uri = open('11.png', 'rb').read().encode('base64').replace('\n', '') img_tag = '<img src="data:image/png;base64,%s">' % data_uri print(img_tag) ```
Images in web pages are typically a second request to the server. The HTML page itself has no images in it, simply references to images like `<img src='the_url_to_the_image'>`. Then the browser makes a second request to the server, and gets the image data. The only option you have to serve images and HTML together is to use a `data:` url in the `img` tag.
7,389,567
I have a webpage generated from python that works as it should, using: ``` print 'Content-type: text/html\n\n' print "" # blank line, end of headers print '<link href="default.css" rel="stylesheet" type="text/css" />' print "<html><head>" ``` I want to add images to this webpage, but when I do this: ``` sys.stdout.write( "Content-type: image/png\n\n" + file("11.png","rb").read() ) print 'Content-type: text/html\n\n' print "" # blank line, end of headers print '<link href="default.css" rel="stylesheet" type="text/css" />' ... ``` All I get is the image, then if I place the image code below my html/text header all I get is the text from the image, ie: ``` <Ï#·öÐδÝZºm]¾|‰k×®]žòåËÛ¶ÃgžyFK–,ÑôéÓU½zuIÒ}÷ݧ&MšH’V¯^­?üð¼1±±±zýõ×%IñññÚºu«*W®¬wß}W.—K3gÎÔÌ™ÿw‹Ú””I’¹w¤¥hdÒd½q÷X•Šˆ²m¿þfïÞ½*]º´éÈs;¥¤¤Ø¿ILLÔˆ#rÊ ``` Also, if I try: ``` print "<img src='11.png'>" ``` I get a broken image in the browser, and browing directly to the image produces a 500 internal server error, with my apache log saying: ``` 8)Exec format error: exec of './../../11.png' failed Premature end of script headers: 11.png ```
2011/09/12
[ "https://Stackoverflow.com/questions/7389567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/828573/" ]
Images in web pages are typically a second request to the server. The HTML page itself has no images in it, simply references to images like `<img src='the_url_to_the_image'>`. Then the browser makes a second request to the server, and gets the image data. The only option you have to serve images and HTML together is to use a `data:` url in the `img` tag.
You can't just dump image data into HTML. You need to either have the file served and link to it or embed the image encoded in base64.
7,389,567
I have a webpage generated from python that works as it should, using: ``` print 'Content-type: text/html\n\n' print "" # blank line, end of headers print '<link href="default.css" rel="stylesheet" type="text/css" />' print "<html><head>" ``` I want to add images to this webpage, but when I do this: ``` sys.stdout.write( "Content-type: image/png\n\n" + file("11.png","rb").read() ) print 'Content-type: text/html\n\n' print "" # blank line, end of headers print '<link href="default.css" rel="stylesheet" type="text/css" />' ... ``` All I get is the image, then if I place the image code below my html/text header all I get is the text from the image, ie: ``` <Ï#·öÐδÝZºm]¾|‰k×®]žòåËÛ¶ÃgžyFK–,ÑôéÓU½zuIÒ}÷ݧ&MšH’V¯^­?üð¼1±±±zýõ×%IñññÚºu«*W®¬wß}W.—K3gÎÔÌ™ÿw‹Ú””I’¹w¤¥hdÒd½q÷X•Šˆ²m¿þfïÞ½*]º´éÈs;¥¤¤Ø¿ILLÔˆ#rÊ ``` Also, if I try: ``` print "<img src='11.png'>" ``` I get a broken image in the browser, and browing directly to the image produces a 500 internal server error, with my apache log saying: ``` 8)Exec format error: exec of './../../11.png' failed Premature end of script headers: 11.png ```
2011/09/12
[ "https://Stackoverflow.com/questions/7389567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/828573/" ]
You can use this code to directly embed the image in your HTML: Python 3 ``` import base64 data_uri = base64.b64encode(open('Graph.png', 'rb').read()).decode('utf-8') img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri) print(img_tag) ``` Python 2.7 ``` data_uri = open('11.png', 'rb').read().encode('base64').replace('\n', '') img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri) print(img_tag) ``` Alternatively for Python <2.6: ``` data_uri = open('11.png', 'rb').read().encode('base64').replace('\n', '') img_tag = '<img src="data:image/png;base64,%s">' % data_uri print(img_tag) ```
You can't just dump image data into HTML. You need to either have the file served and link to it or embed the image encoded in base64.
19,330,790
I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window. I'm trying to use :!python % but I get the following error message: E499: Empty file name for '%' or '#', only works with ":p:h" Anyone have any suggestions?
2013/10/12
[ "https://Stackoverflow.com/questions/19330790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use splits to have both vim and a bash prompt in the same terminal window. I would highly recommend switching from the default `Terminal` app to [`iTerm2`](http://www.iterm2.com/). It's a terminal with [many nice features](http://www.iterm2.com/#/section/features), including 256 colours, tmux integration, and vertical splits. Vertical splits are much nicer for looking at code and output together in the same window than the horizontal splits available in `Terminal`. ![screenshot](https://i.stack.imgur.com/RwObu.png) You can also map shortcut keys to quickly switch between the splits.
You can execute command line arguments inside vim by starting the argument with a "!" from the command mode. Also, in command mode, "%" means the current file. Thus, you can execute the current file that you are editing like this: ``` :!python % ``` I should probably also add, as another option, that you can split the terminal pane in OS X by pressing Command+d. Then you can run commands in the bottom half, and edit in the top half
19,330,790
I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window. I'm trying to use :!python % but I get the following error message: E499: Empty file name for '%' or '#', only works with ":p:h" Anyone have any suggestions?
2013/10/12
[ "https://Stackoverflow.com/questions/19330790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can't execute a file if that file doesn't exist. Write the file with `:w filename.py` (further writes only need `:w`) and execute your script with `:!python %`. Learning programming *and* Vim at the same time is not a very good idea: Vim is a complex beast and trying to handle both learning curves won't be easy. As much as I love Vim, I'd suggest you use another text editor, at least in the beginning, like Sublime Text or TextMate. In short, focus on programming first by using a simple and intuitive editor and learn Vim once you are comfortable enough in your craft. Or don't, Vim is the greatest text editor but you can definitely be a successful programmer without it.
You can execute command line arguments inside vim by starting the argument with a "!" from the command mode. Also, in command mode, "%" means the current file. Thus, you can execute the current file that you are editing like this: ``` :!python % ``` I should probably also add, as another option, that you can split the terminal pane in OS X by pressing Command+d. Then you can run commands in the bottom half, and edit in the top half
19,330,790
I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window. I'm trying to use :!python % but I get the following error message: E499: Empty file name for '%' or '#', only works with ":p:h" Anyone have any suggestions?
2013/10/12
[ "https://Stackoverflow.com/questions/19330790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can execute command line arguments inside vim by starting the argument with a "!" from the command mode. Also, in command mode, "%" means the current file. Thus, you can execute the current file that you are editing like this: ``` :!python % ``` I should probably also add, as another option, that you can split the terminal pane in OS X by pressing Command+d. Then you can run commands in the bottom half, and edit in the top half
in vim type :w yourfilenamehere.py and press enter
19,330,790
I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window. I'm trying to use :!python % but I get the following error message: E499: Empty file name for '%' or '#', only works with ":p:h" Anyone have any suggestions?
2013/10/12
[ "https://Stackoverflow.com/questions/19330790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use splits to have both vim and a bash prompt in the same terminal window. I would highly recommend switching from the default `Terminal` app to [`iTerm2`](http://www.iterm2.com/). It's a terminal with [many nice features](http://www.iterm2.com/#/section/features), including 256 colours, tmux integration, and vertical splits. Vertical splits are much nicer for looking at code and output together in the same window than the horizontal splits available in `Terminal`. ![screenshot](https://i.stack.imgur.com/RwObu.png) You can also map shortcut keys to quickly switch between the splits.
You can use "[quickrun](https://github.com/thinca/vim-quickrun)" plugin. This plugin run a command and show its result quickly. install this one, then type `<Leader>r`(default `\r`) to run program. or Use [tmux](http://tmux.sourceforge.net/).This tool is a terminal multiplexer.can split window in the same terminal.
19,330,790
I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window. I'm trying to use :!python % but I get the following error message: E499: Empty file name for '%' or '#', only works with ":p:h" Anyone have any suggestions?
2013/10/12
[ "https://Stackoverflow.com/questions/19330790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can't execute a file if that file doesn't exist. Write the file with `:w filename.py` (further writes only need `:w`) and execute your script with `:!python %`. Learning programming *and* Vim at the same time is not a very good idea: Vim is a complex beast and trying to handle both learning curves won't be easy. As much as I love Vim, I'd suggest you use another text editor, at least in the beginning, like Sublime Text or TextMate. In short, focus on programming first by using a simple and intuitive editor and learn Vim once you are comfortable enough in your craft. Or don't, Vim is the greatest text editor but you can definitely be a successful programmer without it.
You can use splits to have both vim and a bash prompt in the same terminal window. I would highly recommend switching from the default `Terminal` app to [`iTerm2`](http://www.iterm2.com/). It's a terminal with [many nice features](http://www.iterm2.com/#/section/features), including 256 colours, tmux integration, and vertical splits. Vertical splits are much nicer for looking at code and output together in the same window than the horizontal splits available in `Terminal`. ![screenshot](https://i.stack.imgur.com/RwObu.png) You can also map shortcut keys to quickly switch between the splits.
19,330,790
I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window. I'm trying to use :!python % but I get the following error message: E499: Empty file name for '%' or '#', only works with ":p:h" Anyone have any suggestions?
2013/10/12
[ "https://Stackoverflow.com/questions/19330790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use splits to have both vim and a bash prompt in the same terminal window. I would highly recommend switching from the default `Terminal` app to [`iTerm2`](http://www.iterm2.com/). It's a terminal with [many nice features](http://www.iterm2.com/#/section/features), including 256 colours, tmux integration, and vertical splits. Vertical splits are much nicer for looking at code and output together in the same window than the horizontal splits available in `Terminal`. ![screenshot](https://i.stack.imgur.com/RwObu.png) You can also map shortcut keys to quickly switch between the splits.
in vim type :w yourfilenamehere.py and press enter
19,330,790
I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window. I'm trying to use :!python % but I get the following error message: E499: Empty file name for '%' or '#', only works with ":p:h" Anyone have any suggestions?
2013/10/12
[ "https://Stackoverflow.com/questions/19330790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can't execute a file if that file doesn't exist. Write the file with `:w filename.py` (further writes only need `:w`) and execute your script with `:!python %`. Learning programming *and* Vim at the same time is not a very good idea: Vim is a complex beast and trying to handle both learning curves won't be easy. As much as I love Vim, I'd suggest you use another text editor, at least in the beginning, like Sublime Text or TextMate. In short, focus on programming first by using a simple and intuitive editor and learn Vim once you are comfortable enough in your craft. Or don't, Vim is the greatest text editor but you can definitely be a successful programmer without it.
You can use "[quickrun](https://github.com/thinca/vim-quickrun)" plugin. This plugin run a command and show its result quickly. install this one, then type `<Leader>r`(default `\r`) to run program. or Use [tmux](http://tmux.sourceforge.net/).This tool is a terminal multiplexer.can split window in the same terminal.
19,330,790
I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window. I'm trying to use :!python % but I get the following error message: E499: Empty file name for '%' or '#', only works with ":p:h" Anyone have any suggestions?
2013/10/12
[ "https://Stackoverflow.com/questions/19330790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use "[quickrun](https://github.com/thinca/vim-quickrun)" plugin. This plugin run a command and show its result quickly. install this one, then type `<Leader>r`(default `\r`) to run program. or Use [tmux](http://tmux.sourceforge.net/).This tool is a terminal multiplexer.can split window in the same terminal.
in vim type :w yourfilenamehere.py and press enter
19,330,790
I'm writing Python code using Vim inside Terminal (typing command "vim" to start up Vim). I've been trying to find a way to execute the code through the mac terminal in the same window. I'm trying to use :!python % but I get the following error message: E499: Empty file name for '%' or '#', only works with ":p:h" Anyone have any suggestions?
2013/10/12
[ "https://Stackoverflow.com/questions/19330790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can't execute a file if that file doesn't exist. Write the file with `:w filename.py` (further writes only need `:w`) and execute your script with `:!python %`. Learning programming *and* Vim at the same time is not a very good idea: Vim is a complex beast and trying to handle both learning curves won't be easy. As much as I love Vim, I'd suggest you use another text editor, at least in the beginning, like Sublime Text or TextMate. In short, focus on programming first by using a simple and intuitive editor and learn Vim once you are comfortable enough in your craft. Or don't, Vim is the greatest text editor but you can definitely be a successful programmer without it.
in vim type :w yourfilenamehere.py and press enter
18,118,226
I am new python. I have some predefined xml files. I have a script which generate new xml files. I want to write an automated script which compares xmls files and stores the name of differing xml file names in output file? Thanks in advance
2013/08/08
[ "https://Stackoverflow.com/questions/18118226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2286286/" ]
I think you're looking for the [`filecmp` module](http://docs.python.org/2/library/filecmp.html). You can use it like this: ``` import filecmp cmp = filecmp.cmp('f1.xml', 'f2.xml') # Files are equal if cmp: continue else: out_file.write('f1.xml') ``` Replace `f1.xml` and `f2.xml` with your xml files.
Building on @Xaranke's answer: ``` import filecmp out_file = open("diff_xml_names.txt") # Not sure what format your filenames will come in, but here's one possibility. filePairs = [('f1a.xml', 'f1b.xml'), ('f2a.xml', 'f2b.xml'), ('f3a.xml', 'f3b.xml')] for f1, f2 in filePairs: if not filecmp.cmp(f1, f2): # Files are not equal out_file.write(f1+'\n') out_file.close() ```
18,118,226
I am new python. I have some predefined xml files. I have a script which generate new xml files. I want to write an automated script which compares xmls files and stores the name of differing xml file names in output file? Thanks in advance
2013/08/08
[ "https://Stackoverflow.com/questions/18118226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2286286/" ]
I think you're looking for the [`filecmp` module](http://docs.python.org/2/library/filecmp.html). You can use it like this: ``` import filecmp cmp = filecmp.cmp('f1.xml', 'f2.xml') # Files are equal if cmp: continue else: out_file.write('f1.xml') ``` Replace `f1.xml` and `f2.xml` with your xml files.
What about the following snippet : ``` def separator(self): return "!@#$%^&*" # Very ugly separator def _traverseXML(self, xmlElem, tags, xpaths): tags.append(xmlElem.tag) for e in xmlElem: self._traverseXML(e, tags, xpaths) text = '' if (xmlElem.text): text = xmlElem.text.strip() xpaths.add("/".join(tags) + self.separator() + text) tags.pop() def _xmlToSet(self, xml): xpaths = set() # output tags = list() root = ET.fromstring(xml) self._traverseXML(root, tags, xpaths) return xpaths def _areXMLsAlike(self, xml1, xml2): xpaths1 = self._xmlToSet(xml1) xpaths2 = self._xmlToSet(xml2) return xpaths1 == xpaths2 ```
18,118,226
I am new python. I have some predefined xml files. I have a script which generate new xml files. I want to write an automated script which compares xmls files and stores the name of differing xml file names in output file? Thanks in advance
2013/08/08
[ "https://Stackoverflow.com/questions/18118226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2286286/" ]
Do you speak of comparing them byte-wise or for semantic equality? (Is `<tag attr1="1" attr2="2" />` equal to `<tag attr2="2" attr1="1" />`?) If you want to check for semantic equality have a look at [Xml comparison in Python](https://stackoverflow.com/questions/3007330/xml-comparison-in-python) When generating xml especially if using normal dicts for the attributes somewhere attribute order can be mixed up even sometimes when you use the same script with the same input. > > [items()](https://docs.python.org/2.7/library/stdtypes.html#dict.items) > ----------------------------------------------------------------------- > > > ... > > > **CPython implementation detail:** Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. > > >
Building on @Xaranke's answer: ``` import filecmp out_file = open("diff_xml_names.txt") # Not sure what format your filenames will come in, but here's one possibility. filePairs = [('f1a.xml', 'f1b.xml'), ('f2a.xml', 'f2b.xml'), ('f3a.xml', 'f3b.xml')] for f1, f2 in filePairs: if not filecmp.cmp(f1, f2): # Files are not equal out_file.write(f1+'\n') out_file.close() ```
18,118,226
I am new python. I have some predefined xml files. I have a script which generate new xml files. I want to write an automated script which compares xmls files and stores the name of differing xml file names in output file? Thanks in advance
2013/08/08
[ "https://Stackoverflow.com/questions/18118226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2286286/" ]
Do you speak of comparing them byte-wise or for semantic equality? (Is `<tag attr1="1" attr2="2" />` equal to `<tag attr2="2" attr1="1" />`?) If you want to check for semantic equality have a look at [Xml comparison in Python](https://stackoverflow.com/questions/3007330/xml-comparison-in-python) When generating xml especially if using normal dicts for the attributes somewhere attribute order can be mixed up even sometimes when you use the same script with the same input. > > [items()](https://docs.python.org/2.7/library/stdtypes.html#dict.items) > ----------------------------------------------------------------------- > > > ... > > > **CPython implementation detail:** Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. > > >
What about the following snippet : ``` def separator(self): return "!@#$%^&*" # Very ugly separator def _traverseXML(self, xmlElem, tags, xpaths): tags.append(xmlElem.tag) for e in xmlElem: self._traverseXML(e, tags, xpaths) text = '' if (xmlElem.text): text = xmlElem.text.strip() xpaths.add("/".join(tags) + self.separator() + text) tags.pop() def _xmlToSet(self, xml): xpaths = set() # output tags = list() root = ET.fromstring(xml) self._traverseXML(root, tags, xpaths) return xpaths def _areXMLsAlike(self, xml1, xml2): xpaths1 = self._xmlToSet(xml1) xpaths2 = self._xmlToSet(xml2) return xpaths1 == xpaths2 ```
44,513,308
Can I use macros with the PythonOperator? I tried following, but I was unable to get the macros rendered: ``` dag = DAG( 'temp', default_args=default_args, description='temp dag', schedule_interval=timedelta(days=1)) def temp_def(a, b, **kwargs): print '{{ds}}' print '{{execution_date}}' print 'a=%s, b=%s, kwargs=%s' % (str(a), str(b), str(kwargs)) ds = '{{ ds }}' mm = '{{ execution_date }}' t1 = PythonOperator( task_id='temp_task', python_callable=temp_def, op_args=[mm , ds], provide_context=False, dag=dag) ```
2017/06/13
[ "https://Stackoverflow.com/questions/44513308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4116268/" ]
Macros only get processed for templated fields. To get Jinja to process this field, extend the `PythonOperator` with your own. ```py class MyPythonOperator(PythonOperator): template_fields = ('templates_dict','op_args') ``` I added `'templates_dict'` to the `template_fields` because the `PythonOperator` itself has this field templated: [PythonOperator](https://airflow.incubator.apache.org/_modules/python_operator.html) Now you should be able to use a macro within that field: ```py ds = '{{ ds }}' mm = '{{ execution_date }}' t1 = MyPythonOperator( task_id='temp_task', python_callable=temp_def, op_args=[mm , ds], provide_context=False, dag=dag) ```
In my opinion a more native Airflow way of approaching this would be to use the included PythonOperator and use the `provide_context=True` parameter as such. ```py t1 = MyPythonOperator( task_id='temp_task', python_callable=temp_def, provide_context=True, dag=dag) ``` Now you have access to all of the macros, airflow metadata and task parameters in the `kwargs` of your callable ```py def temp_def(**kwargs): print 'ds={}, execution_date={}'.format((str(kwargs['ds']), str(kwargs['execution_date'])) ``` If you had some custom defined `params` associated with the task you could access those as well via `kwargs['params']`
3,853,136
The following code runs fine in my IDE (PyScripter), however it won't run outside of it. When I go into computer then python26 and double click the file (a .pyw in this case) it fails to run. I have no idea why it's doing this, can anyone please shed some light? This is in windows 7 BTW. My code: ``` #!/usr/bin/env python import matplotlib from mpl_toolkits.mplot3d import axes3d,Axes3D import matplotlib.pyplot as plt from matplotlib import cm import numpy as np from numpy import arange, sin, pi from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter import Tkinter import sys class E(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.protocol("WM_DELETE_WINDOW", self.dest) self.main() def main(self): self.fig = plt.figure() self.fig = plt.figure(figsize=(4,4)) ax = Axes3D(self.fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) t = ax.plot_surface(x, y, z, rstride=4, cstride=4,color='lightgreen',linewidth=1) self.frame = Tkinter.Frame(self) self.frame.pack(padx=15,pady=15) self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame) self.canvas.get_tk_widget().pack(side='top', fill='both') self.canvas._tkcanvas.pack(side='top', fill='both', expand=1) self.btn = Tkinter.Button(self,text='button',command=self.alt) self.btn.pack() def alt (self): print 9 def dest(self): self.destroy() sys.exit() if __name__ == "__main__": app = E(None) app.title('Embedding in TK') app.mainloop() ``` **EDIT:** I tried to import the module in the command line and got the following warning. ``` Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import matplotlib Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\lib\site-packages\matplotlib\__init__.py", line 129, in <module> from rcsetup import defaultParams, validate_backend, validate_toolbar File "C:\Python26\lib\site-packages\matplotlib\rcsetup.py", line 19, in <module> from matplotlib.colors import is_color_like File "C:\Python26\lib\site-packages\matplotlib\colors.py", line 54, in <module> import matplotlib.cbook as cbook File "C:\Python26\lib\site-packages\matplotlib\cbook.py", line 168, in <module> class Scheduler(threading.Thread): AttributeError: 'module' object has no attribute 'Thread' >>> ``` **EDIT(2)** I tried what McSmooth said and got the following output. ``` Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import threading >>> print threading.__file__ threading.pyc >>> threading.Thread Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'Thread' >>> ```
2010/10/04
[ "https://Stackoverflow.com/questions/3853136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433417/" ]
unless you've been messing around with your standard library, it seems that you have a file named `threading.py` somewhere on your python path that is replacing the standard one. Try: ``` >>>import threading >>>print threading.__file__ ``` and make sure that it's the one in your python lib directory (it should be`C:\python26\lib`). If it's not the right file that's getting imported, then you'll have to rename the fake one to something else. If it is the right file, then try: ``` >>>threading.Thread ``` and see if that throws an exception in the REPL. update ------ That's weird. on my system, it gives the name of the source file. either save as a file or run at the command line the following code to find it. ``` import os.path as op import sys files = (op.join(path, 'threading.py') for path in sys.path) print filter(op.exists, files) ```
You most likely need to adjust your [PYTHONPATH](http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH); this is a list of directories Python uses to find modules. See also [How to add to the pythonpath in windows 7?](https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows-7).
3,853,136
The following code runs fine in my IDE (PyScripter), however it won't run outside of it. When I go into computer then python26 and double click the file (a .pyw in this case) it fails to run. I have no idea why it's doing this, can anyone please shed some light? This is in windows 7 BTW. My code: ``` #!/usr/bin/env python import matplotlib from mpl_toolkits.mplot3d import axes3d,Axes3D import matplotlib.pyplot as plt from matplotlib import cm import numpy as np from numpy import arange, sin, pi from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter import Tkinter import sys class E(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.protocol("WM_DELETE_WINDOW", self.dest) self.main() def main(self): self.fig = plt.figure() self.fig = plt.figure(figsize=(4,4)) ax = Axes3D(self.fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) t = ax.plot_surface(x, y, z, rstride=4, cstride=4,color='lightgreen',linewidth=1) self.frame = Tkinter.Frame(self) self.frame.pack(padx=15,pady=15) self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame) self.canvas.get_tk_widget().pack(side='top', fill='both') self.canvas._tkcanvas.pack(side='top', fill='both', expand=1) self.btn = Tkinter.Button(self,text='button',command=self.alt) self.btn.pack() def alt (self): print 9 def dest(self): self.destroy() sys.exit() if __name__ == "__main__": app = E(None) app.title('Embedding in TK') app.mainloop() ``` **EDIT:** I tried to import the module in the command line and got the following warning. ``` Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import matplotlib Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\lib\site-packages\matplotlib\__init__.py", line 129, in <module> from rcsetup import defaultParams, validate_backend, validate_toolbar File "C:\Python26\lib\site-packages\matplotlib\rcsetup.py", line 19, in <module> from matplotlib.colors import is_color_like File "C:\Python26\lib\site-packages\matplotlib\colors.py", line 54, in <module> import matplotlib.cbook as cbook File "C:\Python26\lib\site-packages\matplotlib\cbook.py", line 168, in <module> class Scheduler(threading.Thread): AttributeError: 'module' object has no attribute 'Thread' >>> ``` **EDIT(2)** I tried what McSmooth said and got the following output. ``` Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import threading >>> print threading.__file__ threading.pyc >>> threading.Thread Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'Thread' >>> ```
2010/10/04
[ "https://Stackoverflow.com/questions/3853136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433417/" ]
unless you've been messing around with your standard library, it seems that you have a file named `threading.py` somewhere on your python path that is replacing the standard one. Try: ``` >>>import threading >>>print threading.__file__ ``` and make sure that it's the one in your python lib directory (it should be`C:\python26\lib`). If it's not the right file that's getting imported, then you'll have to rename the fake one to something else. If it is the right file, then try: ``` >>>threading.Thread ``` and see if that throws an exception in the REPL. update ------ That's weird. on my system, it gives the name of the source file. either save as a file or run at the command line the following code to find it. ``` import os.path as op import sys files = (op.join(path, 'threading.py') for path in sys.path) print filter(op.exists, files) ```
From Windows command shell get into python shell by typing python binary (you should get something like '>>>'). Here type **import matplotlib** (your package name which you are trying to import), if you get an error like **ImportError: No module named matplotlib** that means as Matthew F suggested you need to update your PYTHONPATH (either in User specific env or in Windows System env) otherwise post the error message that you are getting while running the script.
64,405,461
Trying to add Densenet121 functional block to the model. I need Keras model to be written in this format, not using ``` model=Sequential() model.add() ``` method What's wrong the function, build\_img\_encod ``` --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-62-69dd207148e0> in <module>() ----> 1 x = build_img_encod() 3 frames /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/input_spec.py in assert_input_compatibility(input_spec, inputs, layer_name) 164 spec.min_ndim is not None or 165 spec.max_ndim is not None): --> 166 if x.shape.ndims is None: 167 raise ValueError('Input ' + str(input_index) + ' of layer ' + 168 layer_name + ' is incompatible with the layer: ' AttributeError: 'Functional' object has no attribute 'shape' ``` ``` def build_img_encod( ): base_model = DenseNet121(input_shape=(150,150,3), include_top=False, weights='imagenet') for layer in base_model.layers: layer.trainable = False flatten = Flatten(name="flatten")(base_model) img_dense_encoder = Dense(1024, activation='relu',name="img_dense_encoder", kernel_regularizer=regularizers.l2(0.0001))(flatten) model = keras.models.Model(inputs=base_model, outputs = img_dense_encoder) return model ```
2020/10/17
[ "https://Stackoverflow.com/questions/64405461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14309081/" ]
The reason why you get that error is that you need to provide the `input_shape` of the `base_model`, instead of the `base_model` per say. Replace this line: `model = keras.models.Model(inputs=base_model, outputs = img_dense_encoder)` with: `model = keras.models.Model(inputs=base_model.input, outputs = img_dense_encoder)`
``` def build_img_encod( ): dense = DenseNet121(input_shape=(150,150,3), include_top=False, weights='imagenet') for layer in dense.layers: layer.trainable = False img_input = Input(shape=(150,150,3)) base_model = dense(img_input) flatten = Flatten(name="flatten")(base_model) img_dense_encoder = Dense(1024, activation='relu',name="img_dense_encoder", kernel_regularizer=regularizers.l2(0.0001))(flatten) model = keras.models.Model(inputs=img_input, outputs = img_dense_encoder) return model ``` This worked..
39,612,416
I have a linux machine to which i installed Anaconda. I am following: <https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html> pip instaltion part. To be more specific: ``` which python ``` gives ``` /home/user/anaconda2/bin/python ``` After which i entered: ``` export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.10.0-cp27-none-linux_x86_64.whl ``` And after: ``` sudo pip install --upgrade $TF_BINARY_URL ``` However, while trying: ``` python -c "import tensorflow" ``` I get an import error: ``` ImportError: No module named tensorflow ```
2016/09/21
[ "https://Stackoverflow.com/questions/39612416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6857504/" ]
The problem is here: ``` xs foldLeft((0,0,0))(logic _) ``` Never go for the dotless notation unless it's for an operator. This way it works. ``` xs.foldLeft((0,0,0))(logic _) ``` Without a context I believe this is idiomatic enough.
I don't get the goal of your code but the problem you described can be solved this way: ``` val to = xs.foldLeft((0,0,0))(logic) ```
39,612,416
I have a linux machine to which i installed Anaconda. I am following: <https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html> pip instaltion part. To be more specific: ``` which python ``` gives ``` /home/user/anaconda2/bin/python ``` After which i entered: ``` export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.10.0-cp27-none-linux_x86_64.whl ``` And after: ``` sudo pip install --upgrade $TF_BINARY_URL ``` However, while trying: ``` python -c "import tensorflow" ``` I get an import error: ``` ImportError: No module named tensorflow ```
2016/09/21
[ "https://Stackoverflow.com/questions/39612416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6857504/" ]
The problem is here: ``` xs foldLeft((0,0,0))(logic _) ``` Never go for the dotless notation unless it's for an operator. This way it works. ``` xs.foldLeft((0,0,0))(logic _) ``` Without a context I believe this is idiomatic enough.
Try this ``` xs.foldLeft((0,0,0), logic) ```
39,612,416
I have a linux machine to which i installed Anaconda. I am following: <https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html> pip instaltion part. To be more specific: ``` which python ``` gives ``` /home/user/anaconda2/bin/python ``` After which i entered: ``` export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.10.0-cp27-none-linux_x86_64.whl ``` And after: ``` sudo pip install --upgrade $TF_BINARY_URL ``` However, while trying: ``` python -c "import tensorflow" ``` I get an import error: ``` ImportError: No module named tensorflow ```
2016/09/21
[ "https://Stackoverflow.com/questions/39612416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6857504/" ]
The problem is here: ``` xs foldLeft((0,0,0))(logic _) ``` Never go for the dotless notation unless it's for an operator. This way it works. ``` xs.foldLeft((0,0,0))(logic _) ``` Without a context I believe this is idiomatic enough.
`foldLeft` is a curried function so it requires a `.` - go for `xs.foldLeft` and it will work.
61,858,954
I'm trying to get two attributes at the time from my json data and add them as an item on my python list. However, when trying to add those two: `['emailTypeDesc']['createdDate']` it throws an error. Could someone help with this? thanks in advance! json: ``` { 'readOnly': False, 'senderDetails': {'firstName': 'John', 'lastName': 'Doe', 'emailAddress': 'johndoe@gmail.com', 'emailAddressId': 123456, 'personalId': 123, 'companyName': 'ACME‘}, 'clientDetails': {'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe@gmail.com', 'emailAddressId': 654321, 'personalId': 456, 'companyName': 'Lorem Ipsum‘}}, 'notesSection': {}, 'emailList': [{'requestId': 12345667, 'emailId': 9876543211, 'emailType': 3, 'emailTypeDesc': 'Email-In', 'emailTitle': 'SampleTitle 1', 'createdDate': '15-May-2020 11:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe@gmail.com',}]}, {'requestId': 12345667, 'emailId': 14567775, 'emailType': 3, 'emailTypeDesc': 'Email-Out', 'emailTitle': 'SampleTitle 2', 'createdDate': '16-May-2020 16:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe@gmail.com',}]}, {'requestId': 12345667, 'emailId': 12345, 'emailType': 3, 'emailTypeDesc': 'Email-In', 'emailTitle': 'SampleTitle 3', 'createdDate': '17-May-2020 20:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe@gmail.com',}] } ``` python: ``` final_list = [] data = json.loads(r.text) myId = [(data['emailList'][0]['requestId'])] for each_req in myId: final_list.append(each_req) myEmailList = [mails['emailTypeDesc']['createdDate'] for mails in data['emailList']] for each_requ in myEmailList: final_list.append(each_requ) return final_list ``` This error comes up when I run the above code: ``` TypeError: string indices must be integers ``` Desired output for `final_list`: ``` [12345667, 'Email-In', '15-May-2020 11:15:52', 'Email-Out', '16-May-2020 16:15:52', 'Email-In', '17-May-2020 20:15:52'] ``` My problem is definetely in this line: ``` myEmailList = [mails['emailTypeDesc']['createdDate'] for mails in data['emailList']] ``` because when I run this without the second attribute `['createdDate']` it would work, but I need both attributes on my `final_list`: ``` myEmailList = [mails['emailTypeDesc'] for mails in data['emailList']] ```
2020/05/17
[ "https://Stackoverflow.com/questions/61858954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9488179/" ]
I think you're misunderstanding the syntax. `mails['emailTypeDesc']['createdDate']` is looking for the key `'createdDate'` *inside* the object `mails['emailTypeDesc']`, but in fact they are two items at the same level. Since `mails['emailTypeDesc']` is a string, not a dictionary, you get the error you have quoted. It seems that you want to add the two items `mails['emailTypeDesc']` and `mails['createdDate']` to your list. I'm not sure if you'd rather join these together into a single string or create a sub-list or something else. Here's a sublist option. ``` myEmailList = [[mails['emailTypeDesc'], mails['createdDate']] for mails in data['emailList']] ```
Strings in JSON must be in double quotes, not single. Edit: As well as names.
74,558,107
Is it possible to calculate an expression using python but without entering python shell? What I want to achieve is to use python in a following manner: ``` tail file.txt -n `python 123*456` ``` instead of having to calculate 123\*456 in a separate step.
2022/11/24
[ "https://Stackoverflow.com/questions/74558107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4746861/" ]
I don't understand your question: you say "I would like to do something using Python", but when you show what you want to do, Python seems not to be needed for achieving that. Let me show you: what you want to achieve, can be done as follows: ``` tail -f file.txt -n $((123*456)) ``` The `$((...))` notation is capable of performing integer calculations, as you can imagine. Is this what you are looking for, or are you really forced to use Python, and if so, why do you think that?
You can try the `-c` option. For e.g, `tail test_log.txt -n `python -c "print(1 + 2)"``
58,165,158
I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript: ``` C:\WINDOWS\system32> pip install pinyin_utils Collecting pinyin_utils Using cached https://files.pythonhosted.org/packages/eb/26/95b2d80eae03dfe7698e9e5a83b49f75e769895a4e0bb8048a42c18c7109/pinyin_utils-0.1.0-py3-none-any.whl Installing collected packages: pinyin-utils Successfully installed pinyin-utils-0.1.0 C:\WINDOWS\system32> python Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from pinyin_utils import convertPinyin Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'pinyin_utils' >>> ``` On Windows 10, Python 3.7.4
2019/09/30
[ "https://Stackoverflow.com/questions/58165158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738579/" ]
You could take [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) and spread the items. ```js let array = [[1,2], [10, 15], [30, 40], [-1, -50]], max = array.map(a => Math.max(...a)); console.log(max); ```
Empty numeric values wouldn't help you either using your logic, because you are setting wrong initial values for comparison. See this, same as yours, with minor fix: ``` let arr = [[1,2], [10, 15], [30, 40], [-1, -50]]; let newArr = [arr[0][0], arr[1][0], arr[2][0], arr[3][0]]; for (let x = 0; x < arr.length; x++) { for (let y = 0; y < arr[x].length; y++) { if (newArr[x] < arr[x][y]) { newArr[x] = arr[x][y]; } } } ```
58,165,158
I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript: ``` C:\WINDOWS\system32> pip install pinyin_utils Collecting pinyin_utils Using cached https://files.pythonhosted.org/packages/eb/26/95b2d80eae03dfe7698e9e5a83b49f75e769895a4e0bb8048a42c18c7109/pinyin_utils-0.1.0-py3-none-any.whl Installing collected packages: pinyin-utils Successfully installed pinyin-utils-0.1.0 C:\WINDOWS\system32> python Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from pinyin_utils import convertPinyin Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'pinyin_utils' >>> ``` On Windows 10, Python 3.7.4
2019/09/30
[ "https://Stackoverflow.com/questions/58165158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738579/" ]
Your issue is that `-1` is not smaller than `0`, and so your array will not be updated, instead, start your `newArr` with `-Infinity`s instead of `0` such that any number will be bigger than it like so: ```js let arr = [ [1, 2], [10, 15], [30, 40], [-1, -50] ]; let newArr = []; for (let x = 0; x < arr.length; x++) { newArr.push(-Infinity); // populate it with `-Infinity` for (let y = 0; y < arr[x].length; y++) { if (newArr[x] < arr[x][y]) { newArr[x] = arr[x][y]; } } } console.log(newArr) // 2,15,40,-1 ```
You could take [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) and spread the items. ```js let array = [[1,2], [10, 15], [30, 40], [-1, -50]], max = array.map(a => Math.max(...a)); console.log(max); ```
58,165,158
I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript: ``` C:\WINDOWS\system32> pip install pinyin_utils Collecting pinyin_utils Using cached https://files.pythonhosted.org/packages/eb/26/95b2d80eae03dfe7698e9e5a83b49f75e769895a4e0bb8048a42c18c7109/pinyin_utils-0.1.0-py3-none-any.whl Installing collected packages: pinyin-utils Successfully installed pinyin-utils-0.1.0 C:\WINDOWS\system32> python Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from pinyin_utils import convertPinyin Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'pinyin_utils' >>> ``` On Windows 10, Python 3.7.4
2019/09/30
[ "https://Stackoverflow.com/questions/58165158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738579/" ]
You could take [`Math.max`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max) and spread the items. ```js let array = [[1,2], [10, 15], [30, 40], [-1, -50]], max = array.map(a => Math.max(...a)); console.log(max); ```
You can use the initial value as the 1st element or sub-array. ```js let arr = [[1,2], [10, 15], [30, 40], [-1, -50]]; newArr = [] // Instead of 0 I need an empty numeric for (let x = 0; x < arr.length; x++) { newArr[x] = arr[x][0] for (let y = 0; y < arr[x].length; y++) { if (newArr[x] < arr[x][y]) { newArr[x] = arr[x][y]; } } } console.log(newArr) // 2,15,40,0 ``` Or you can use map function to return the max values. ```js let arr = [[1,2], [10, 15], [30, 40], [-1, -50]]; let newArr = arr.map(subArr => Math.max(...subArr)) console.log(newArr) ```
58,165,158
I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript: ``` C:\WINDOWS\system32> pip install pinyin_utils Collecting pinyin_utils Using cached https://files.pythonhosted.org/packages/eb/26/95b2d80eae03dfe7698e9e5a83b49f75e769895a4e0bb8048a42c18c7109/pinyin_utils-0.1.0-py3-none-any.whl Installing collected packages: pinyin-utils Successfully installed pinyin-utils-0.1.0 C:\WINDOWS\system32> python Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from pinyin_utils import convertPinyin Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'pinyin_utils' >>> ``` On Windows 10, Python 3.7.4
2019/09/30
[ "https://Stackoverflow.com/questions/58165158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738579/" ]
Your issue is that `-1` is not smaller than `0`, and so your array will not be updated, instead, start your `newArr` with `-Infinity`s instead of `0` such that any number will be bigger than it like so: ```js let arr = [ [1, 2], [10, 15], [30, 40], [-1, -50] ]; let newArr = []; for (let x = 0; x < arr.length; x++) { newArr.push(-Infinity); // populate it with `-Infinity` for (let y = 0; y < arr[x].length; y++) { if (newArr[x] < arr[x][y]) { newArr[x] = arr[x][y]; } } } console.log(newArr) // 2,15,40,-1 ```
Empty numeric values wouldn't help you either using your logic, because you are setting wrong initial values for comparison. See this, same as yours, with minor fix: ``` let arr = [[1,2], [10, 15], [30, 40], [-1, -50]]; let newArr = [arr[0][0], arr[1][0], arr[2][0], arr[3][0]]; for (let x = 0; x < arr.length; x++) { for (let y = 0; y < arr[x].length; y++) { if (newArr[x] < arr[x][y]) { newArr[x] = arr[x][y]; } } } ```
58,165,158
I went through a tutorial to show me how to install a Python package that I developed to PyPI, so it could be installed by pip. Everything seemed to work great, but after installing with pip, I get an error trying to use the library. Here is a transcript: ``` C:\WINDOWS\system32> pip install pinyin_utils Collecting pinyin_utils Using cached https://files.pythonhosted.org/packages/eb/26/95b2d80eae03dfe7698e9e5a83b49f75e769895a4e0bb8048a42c18c7109/pinyin_utils-0.1.0-py3-none-any.whl Installing collected packages: pinyin-utils Successfully installed pinyin-utils-0.1.0 C:\WINDOWS\system32> python Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from pinyin_utils import convertPinyin Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'pinyin_utils' >>> ``` On Windows 10, Python 3.7.4
2019/09/30
[ "https://Stackoverflow.com/questions/58165158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1738579/" ]
Your issue is that `-1` is not smaller than `0`, and so your array will not be updated, instead, start your `newArr` with `-Infinity`s instead of `0` such that any number will be bigger than it like so: ```js let arr = [ [1, 2], [10, 15], [30, 40], [-1, -50] ]; let newArr = []; for (let x = 0; x < arr.length; x++) { newArr.push(-Infinity); // populate it with `-Infinity` for (let y = 0; y < arr[x].length; y++) { if (newArr[x] < arr[x][y]) { newArr[x] = arr[x][y]; } } } console.log(newArr) // 2,15,40,-1 ```
You can use the initial value as the 1st element or sub-array. ```js let arr = [[1,2], [10, 15], [30, 40], [-1, -50]]; newArr = [] // Instead of 0 I need an empty numeric for (let x = 0; x < arr.length; x++) { newArr[x] = arr[x][0] for (let y = 0; y < arr[x].length; y++) { if (newArr[x] < arr[x][y]) { newArr[x] = arr[x][y]; } } } console.log(newArr) // 2,15,40,0 ``` Or you can use map function to return the max values. ```js let arr = [[1,2], [10, 15], [30, 40], [-1, -50]]; let newArr = arr.map(subArr => Math.max(...subArr)) console.log(newArr) ```
59,307,815
I am currently developing a python project where I am concerned with performance because my CPU is always using like 90-98% of its computing capacity. So I was thinking about what could I change in my code to make it faster, and noticed that I have a string variable which always receives one of two values: ``` state = "ok" state = "notOk" ``` Since it only has 2 values, I tought about changing it to a boolean like: ``` isStateOk = True isStateOk = False ``` Does it make any sense to do that? Is there a big difference, or any difference at all, in the speed of attributing a string to a variable and attributing a boolean to a variable? I should also mention that I am using this variable in like 30 **if comparisons** in my code, so maybe the **speed of comparison** would be a benefit? ``` if (state == "ok) # Original comparison if (isStateOk) # New comparison ```
2019/12/12
[ "https://Stackoverflow.com/questions/59307815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619301/" ]
To parse HTML and XML documents (page source) and get elements with locators, you can use [beautifulsoup](/questions/tagged/beautifulsoup "show questions tagged 'beautifulsoup'"), [how to use it](https://pypi.org/project/beautifulsoup4/). Regular expression do not parsing HTML documents. You get **NULL** because `Checkpath = re.search(d,src)` is `None`. Here is example how you can get status without loop and parsing page source. ``` from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) p = wait.until(EC.visibility_of_all_elements_located((By.XPATH, '//*[@id="General"]/fieldset/dl/dd'))) status = "NULL" r = range(0, len(p)) if 15 in r: status = p[8].text elif 14 in r: status = p[7].text elif 13 in r: status = p[6].text elif 12 in r: status = p[5].text ```
From the code you have posted, the strings you have hardcoded are all the same other than the index of the DD element. Since the Status index is always 7 less than the index of Checkpath, you can just loop through 15-12, do your search, and then Status is just 15-7. The code is below. ``` src = driver.page_source loop = [15,14,13,12] for d in loop: Checkpath = re.search('//*[@id="General"]/fieldset/dl/dd[' + str(d) + ']',src) Status = driver.find_element_by_xpath('//*[@id="General"]/fieldset/dl/dd[' + str(d - 7) + ']').text print(Status) ```
59,307,815
I am currently developing a python project where I am concerned with performance because my CPU is always using like 90-98% of its computing capacity. So I was thinking about what could I change in my code to make it faster, and noticed that I have a string variable which always receives one of two values: ``` state = "ok" state = "notOk" ``` Since it only has 2 values, I tought about changing it to a boolean like: ``` isStateOk = True isStateOk = False ``` Does it make any sense to do that? Is there a big difference, or any difference at all, in the speed of attributing a string to a variable and attributing a boolean to a variable? I should also mention that I am using this variable in like 30 **if comparisons** in my code, so maybe the **speed of comparison** would be a benefit? ``` if (state == "ok) # Original comparison if (isStateOk) # New comparison ```
2019/12/12
[ "https://Stackoverflow.com/questions/59307815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619301/" ]
My solution to this bug is listed below I was able to perform a nest while loop within a for loop. My list XpathLoop shows the numerical values of the dd items. This loops through until it finds my desired dt 'Status Date'. After it finds the desired text it enteres a while loop until the status date format appears. The dd items are completely independent of the dt items on the webpage. ``` XPATHLoop=[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18] for d in XPATHLoop: try: findtool = driver.find_element_by_xpath('//[@id="General"]/fieldset/dl/dt['+str(d)+']') if findtool.text == 'Status Date': Status=driver.find_element_by_xpath('//[@id="General"]/fieldset/dl/dd['+str((d))+']').text i=1 while re.search(r'(\d{4})',Status) == None: Status= driver.find_element_by_xpath('//*[@id="General"]/fieldset/dl/dd['+str((d+i))+']').text i=i+1 except: pass print(Status) ```
From the code you have posted, the strings you have hardcoded are all the same other than the index of the DD element. Since the Status index is always 7 less than the index of Checkpath, you can just loop through 15-12, do your search, and then Status is just 15-7. The code is below. ``` src = driver.page_source loop = [15,14,13,12] for d in loop: Checkpath = re.search('//*[@id="General"]/fieldset/dl/dd[' + str(d) + ']',src) Status = driver.find_element_by_xpath('//*[@id="General"]/fieldset/dl/dd[' + str(d - 7) + ']').text print(Status) ```
8,275,650
I am stuck trying to perform this task and while trying I can't help thinking there will be a nicer way to code it than the way I have been trying. I have a line of text and a keyword. I want to make a new list going down each character in each list. The keyword will just repeat itself until the end of the list. If there are any non-alpha characters the keyword letter will not be used. For example: ``` Keyword="lemon" Text="hi there!" ``` would result in ``` ('lh', 'ei', ' ', 'mt' , 'oh', 'ne', 'lr', 'ee', '!') ``` Is there a way of telling python to keep repeating over a string in a loop, ie keep repeating over the letters of lemon? I am new to coding so sorry if this isn't explained well or seems strange!
2011/11/26
[ "https://Stackoverflow.com/questions/8275650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066430/" ]
You've got two questions mashed into one. The first is: how do you remove non-alphanumeric chars from a string? You can do it a few ways, but regular expression substitution is a nice way. ``` import re def removeWhitespace( s ): return re.sub( '\s', '', s ) ``` The second part of the question is about how to keep looping through the keyword, until the text line is consumed. You can write this as: ``` def characterZip( keyword, textline ): res = [] textline = removeWhitespace(textline) textlen = len(textline) for i in xrange(textlen)): res.append( '%s%s' % (keyword[i%len(keyword)], textline[i]) ) return res ``` Most pythonistas will look at this and see opportunity for refactoring. The patten that this code is trying to achieve is in functional programming termed a `zip`. The quirk is that in this case you're doing something slightly non-normative with the repeating characters of the keyword, this too has an equivalent, the [cycle](http://docs.python.org/library/itertools.html#itertools.cycle) function in the itertools module. ``` from itertools import cycle, islice, izip def characterZip( keyword, textline ): textline = removeWhitespace(textline) textlen = len(textline) it = islice( izip(cycle(keyword), textline), textlen ) return [ '%s%s' % val for val in it ] ```
I think you could use `enumerate` in that situation: ``` # remove unwanted stuff l = [ c for c in Text if c.isalpha() ] for n,k in enumerate(l): print n, (Keyword[n % len(Keyword)], Text[l]) ``` that gives you: ``` 0 ('l', 'h') 1 ('e', 'i') 2 ('m', 't') 3 ('o', 'h') 4 ('n', 'e') 5 ('l', 'r') 6 ('e', 'e') ``` You could use that as the basis for your manipulation.
8,275,650
I am stuck trying to perform this task and while trying I can't help thinking there will be a nicer way to code it than the way I have been trying. I have a line of text and a keyword. I want to make a new list going down each character in each list. The keyword will just repeat itself until the end of the list. If there are any non-alpha characters the keyword letter will not be used. For example: ``` Keyword="lemon" Text="hi there!" ``` would result in ``` ('lh', 'ei', ' ', 'mt' , 'oh', 'ne', 'lr', 'ee', '!') ``` Is there a way of telling python to keep repeating over a string in a loop, ie keep repeating over the letters of lemon? I am new to coding so sorry if this isn't explained well or seems strange!
2011/11/26
[ "https://Stackoverflow.com/questions/8275650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066430/" ]
Here's a solution: ``` import itertools def task(kw,text): i = itertools.cycle(kw) return tuple(next(i)+t if t.isalpha() else t for t in text) print(task('lemon','hi there!')) ``` ### Output ``` ('lh', 'ei', ' ', 'mt', 'oh', 'ne', 'lr', 'ee', '!') ``` [itertools.cycle](http://docs.python.org/library/itertools.html#itertools.cycle) iterates over a sequence repeatedly (a string is a sequence of characters). [next](http://docs.python.org/library/functions.html#next) gets the next character from the repeating sequence. The [generator expression](http://docs.python.org/reference/expressions.html#generator-expressions) selects the pair of next keyword letter and text character if the text character is alphabetic, else it just selects the non-alphabetic character alone.
You've got two questions mashed into one. The first is: how do you remove non-alphanumeric chars from a string? You can do it a few ways, but regular expression substitution is a nice way. ``` import re def removeWhitespace( s ): return re.sub( '\s', '', s ) ``` The second part of the question is about how to keep looping through the keyword, until the text line is consumed. You can write this as: ``` def characterZip( keyword, textline ): res = [] textline = removeWhitespace(textline) textlen = len(textline) for i in xrange(textlen)): res.append( '%s%s' % (keyword[i%len(keyword)], textline[i]) ) return res ``` Most pythonistas will look at this and see opportunity for refactoring. The patten that this code is trying to achieve is in functional programming termed a `zip`. The quirk is that in this case you're doing something slightly non-normative with the repeating characters of the keyword, this too has an equivalent, the [cycle](http://docs.python.org/library/itertools.html#itertools.cycle) function in the itertools module. ``` from itertools import cycle, islice, izip def characterZip( keyword, textline ): textline = removeWhitespace(textline) textlen = len(textline) it = islice( izip(cycle(keyword), textline), textlen ) return [ '%s%s' % val for val in it ] ```
8,275,650
I am stuck trying to perform this task and while trying I can't help thinking there will be a nicer way to code it than the way I have been trying. I have a line of text and a keyword. I want to make a new list going down each character in each list. The keyword will just repeat itself until the end of the list. If there are any non-alpha characters the keyword letter will not be used. For example: ``` Keyword="lemon" Text="hi there!" ``` would result in ``` ('lh', 'ei', ' ', 'mt' , 'oh', 'ne', 'lr', 'ee', '!') ``` Is there a way of telling python to keep repeating over a string in a loop, ie keep repeating over the letters of lemon? I am new to coding so sorry if this isn't explained well or seems strange!
2011/11/26
[ "https://Stackoverflow.com/questions/8275650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1066430/" ]
Here's a solution: ``` import itertools def task(kw,text): i = itertools.cycle(kw) return tuple(next(i)+t if t.isalpha() else t for t in text) print(task('lemon','hi there!')) ``` ### Output ``` ('lh', 'ei', ' ', 'mt', 'oh', 'ne', 'lr', 'ee', '!') ``` [itertools.cycle](http://docs.python.org/library/itertools.html#itertools.cycle) iterates over a sequence repeatedly (a string is a sequence of characters). [next](http://docs.python.org/library/functions.html#next) gets the next character from the repeating sequence. The [generator expression](http://docs.python.org/reference/expressions.html#generator-expressions) selects the pair of next keyword letter and text character if the text character is alphabetic, else it just selects the non-alphabetic character alone.
I think you could use `enumerate` in that situation: ``` # remove unwanted stuff l = [ c for c in Text if c.isalpha() ] for n,k in enumerate(l): print n, (Keyword[n % len(Keyword)], Text[l]) ``` that gives you: ``` 0 ('l', 'h') 1 ('e', 'i') 2 ('m', 't') 3 ('o', 'h') 4 ('n', 'e') 5 ('l', 'r') 6 ('e', 'e') ``` You could use that as the basis for your manipulation.
8,912,338
I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via ``` (gdb) python mystruct = gdb.parse_and_eval("mystruct") ``` Now I got this variable called mystruct which is a GDB.Value object. And I can access all the members of the struct by simply using this object as a dictionary (like`mystruct['member']`). The problem is, that my script doesn't know which members a certain struct has. So I wanted to get the keys (or even the values) from this GDB.Value object. But neither `mystruct.values()` nor `mystruct.keys()` is working here. Is there no possibility to access this information? I think it's highly unlikely that you can't access this information, but I didn't found it anywhere. A `dir(mystruct)` showed me that there also is no keys or values function. I can see all the members by printing the mystruct, but isn't there a way to get the members in python?
2012/01/18
[ "https://Stackoverflow.com/questions/8912338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1154311/" ]
From GDB [documentation](http://sourceware.org/gdb/onlinedocs/gdb/Values-From-Inferior.html#Values-From-Inferior): You can get the type of `mystruct` like so: ``` tp = mystruct.type ``` and iterate over the [fields](http://sourceware.org/gdb/onlinedocs/gdb/Types-In-Python.html#Types-In-Python) via `tp.fields()` No evil workarounds required ;-) **Update:** GDB 7.4 has just been released. From the [announcement](http://sourceware.org/ml/gdb-announce/2012/msg00001.html): > > Type objects for struct and union types now allow access to > the fields using standard Python dictionary (mapping) methods. > > >
Evil workaround: ``` python print eval("dict(" + str(mystruct)[1:-2] + ")") ``` I don't know if this is generalisable. As a demo, I wrote a minimal example `test.cpp` ``` #include <iostream> struct mystruct { int i; double x; } mystruct_1; int main () { mystruct_1.i = 2; mystruct_1.x = 1.242; std::cout << "Blarz"; std::cout << std::endl; } ``` Now I run `g++ -g test.cpp -o test` as usual and fire up `gdb test`. Here is a example session transcript: ``` (gdb) break main Breakpoint 1 at 0x400898: file test.cpp, line 11. (gdb) run Starting program: ... Breakpoint 1, main () at test.cpp:11 11 mystruct_1.i = 2; (gdb) step 12 mystruct_1.x = 1.242; (gdb) step 13 std::cout << "Blarz"; (gdb) python mystruct = gdb.parse_and_eval("mystruct_1") (gdb) python print mystruct {i = 2, x = 1.242} (gdb) python print eval("dict(" + str(mystruct)[1:-2] + ")") {'i': 2, 'x': 1.24} (gdb) python print eval("dict(" + str(mystruct)[1:-2] + ")").keys() ['i', 'x'] ```
8,912,338
I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via ``` (gdb) python mystruct = gdb.parse_and_eval("mystruct") ``` Now I got this variable called mystruct which is a GDB.Value object. And I can access all the members of the struct by simply using this object as a dictionary (like`mystruct['member']`). The problem is, that my script doesn't know which members a certain struct has. So I wanted to get the keys (or even the values) from this GDB.Value object. But neither `mystruct.values()` nor `mystruct.keys()` is working here. Is there no possibility to access this information? I think it's highly unlikely that you can't access this information, but I didn't found it anywhere. A `dir(mystruct)` showed me that there also is no keys or values function. I can see all the members by printing the mystruct, but isn't there a way to get the members in python?
2012/01/18
[ "https://Stackoverflow.com/questions/8912338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1154311/" ]
Evil workaround: ``` python print eval("dict(" + str(mystruct)[1:-2] + ")") ``` I don't know if this is generalisable. As a demo, I wrote a minimal example `test.cpp` ``` #include <iostream> struct mystruct { int i; double x; } mystruct_1; int main () { mystruct_1.i = 2; mystruct_1.x = 1.242; std::cout << "Blarz"; std::cout << std::endl; } ``` Now I run `g++ -g test.cpp -o test` as usual and fire up `gdb test`. Here is a example session transcript: ``` (gdb) break main Breakpoint 1 at 0x400898: file test.cpp, line 11. (gdb) run Starting program: ... Breakpoint 1, main () at test.cpp:11 11 mystruct_1.i = 2; (gdb) step 12 mystruct_1.x = 1.242; (gdb) step 13 std::cout << "Blarz"; (gdb) python mystruct = gdb.parse_and_eval("mystruct_1") (gdb) python print mystruct {i = 2, x = 1.242} (gdb) python print eval("dict(" + str(mystruct)[1:-2] + ")") {'i': 2, 'x': 1.24} (gdb) python print eval("dict(" + str(mystruct)[1:-2] + ")").keys() ['i', 'x'] ```
These days: ``` (gdb) python import sys; print(sys.version) 3.10.8 (main, Oct 15 2022, 19:00:40) [GCC 12.2.0 64 bit (AMD64)] ``` ... it got a lot easier, properties are keys in dict - here is an example: `test_struct.c`: ```c #include <stdint.h> #include <stdio.h> struct mystruct_s { uint8_t member; uint8_t list[5]; }; typedef struct mystruct_s mystruct_t; mystruct_t mystruct = { .member = 0, .list = { 10, 20, 30, 40, 50 }, }; int main(void) { printf("mystruct.member %d\n", mystruct.member); for(uint8_t ix=0; ix<sizeof(mystruct.list); ix++) { printf("mystruct.list[%d]: %d\n", ix, mystruct.list[ix]); } } ``` Then compile and enter gdb: ```bash gcc -g -o test_struct.exe test_struct.c gdb --args ./test_struct.exe ``` ... then in gdb: ```none (gdb) b main Breakpoint 1 at 0x140001591: file test_struct.c, line 16. (gdb) python ms = gdb.parse_and_eval("mystruct") (gdb) python print(ms) {member = 0 '\000', list = "\n\024\036(2"} (gdb) python print(ms['member']) 0 '\000' (gdb) python print(ms['list']) "\n\024\036(2" (gdb) python for ix in range(0,5): print("mystruct.list[{}]: {}".format(ix, ms['list'][ix])) mystruct.list[0]: 10 '\n' mystruct.list[1]: 20 '\024' mystruct.list[2]: 30 '\036' mystruct.list[3]: 40 '(' mystruct.list[4]: 50 '2' ```
8,912,338
I have a struct in GDB and want to run a script which examines this struct. In Python GDB you can easily access the struct via ``` (gdb) python mystruct = gdb.parse_and_eval("mystruct") ``` Now I got this variable called mystruct which is a GDB.Value object. And I can access all the members of the struct by simply using this object as a dictionary (like`mystruct['member']`). The problem is, that my script doesn't know which members a certain struct has. So I wanted to get the keys (or even the values) from this GDB.Value object. But neither `mystruct.values()` nor `mystruct.keys()` is working here. Is there no possibility to access this information? I think it's highly unlikely that you can't access this information, but I didn't found it anywhere. A `dir(mystruct)` showed me that there also is no keys or values function. I can see all the members by printing the mystruct, but isn't there a way to get the members in python?
2012/01/18
[ "https://Stackoverflow.com/questions/8912338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1154311/" ]
From GDB [documentation](http://sourceware.org/gdb/onlinedocs/gdb/Values-From-Inferior.html#Values-From-Inferior): You can get the type of `mystruct` like so: ``` tp = mystruct.type ``` and iterate over the [fields](http://sourceware.org/gdb/onlinedocs/gdb/Types-In-Python.html#Types-In-Python) via `tp.fields()` No evil workarounds required ;-) **Update:** GDB 7.4 has just been released. From the [announcement](http://sourceware.org/ml/gdb-announce/2012/msg00001.html): > > Type objects for struct and union types now allow access to > the fields using standard Python dictionary (mapping) methods. > > >
These days: ``` (gdb) python import sys; print(sys.version) 3.10.8 (main, Oct 15 2022, 19:00:40) [GCC 12.2.0 64 bit (AMD64)] ``` ... it got a lot easier, properties are keys in dict - here is an example: `test_struct.c`: ```c #include <stdint.h> #include <stdio.h> struct mystruct_s { uint8_t member; uint8_t list[5]; }; typedef struct mystruct_s mystruct_t; mystruct_t mystruct = { .member = 0, .list = { 10, 20, 30, 40, 50 }, }; int main(void) { printf("mystruct.member %d\n", mystruct.member); for(uint8_t ix=0; ix<sizeof(mystruct.list); ix++) { printf("mystruct.list[%d]: %d\n", ix, mystruct.list[ix]); } } ``` Then compile and enter gdb: ```bash gcc -g -o test_struct.exe test_struct.c gdb --args ./test_struct.exe ``` ... then in gdb: ```none (gdb) b main Breakpoint 1 at 0x140001591: file test_struct.c, line 16. (gdb) python ms = gdb.parse_and_eval("mystruct") (gdb) python print(ms) {member = 0 '\000', list = "\n\024\036(2"} (gdb) python print(ms['member']) 0 '\000' (gdb) python print(ms['list']) "\n\024\036(2" (gdb) python for ix in range(0,5): print("mystruct.list[{}]: {}".format(ix, ms['list'][ix])) mystruct.list[0]: 10 '\n' mystruct.list[1]: 20 '\024' mystruct.list[2]: 30 '\036' mystruct.list[3]: 40 '(' mystruct.list[4]: 50 '2' ```
66,079,303
I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel. I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main. After the publishing on main `nginx` forward requests to test and that is the issue. Restarting the `nginx` fixes the problem, so how can I fix the issue permanantly without restarting `nginx` after each publish on the main environement. `docker-compose.yml` : ```yaml version: '3.7' services: main-mongo: image: mongo:4.2.3 container_name: main-mongo volumes: - mongodb:/data/db - mongoconfig:/data/configdb main_service: image: project container_name: main_service restart: on-failure volumes: - ./views:/project/views - ./public:/project/public depends_on: - main-mongo test_service: image: test_project container_name: test_service restart: on-failure volumes: - ./test_view/views:/project/views - ./test_view/public:/project/public environment: - ENV=test depends_on: - main-mongo test_panel: image: test_panel container_name: test_panel restart: on-failure environment: - ENV=test depends_on: - main-mongo main_panel: image: panel container_name: main_panel restart: on-failure depends_on: - main-mongo python_backend_test: image: python_backend_test container_name: python_backend_test restart: on-failure volumes: - /tmp:/tmp nginx: image: nginx:1.17 container_name: nginx restart: on-failure ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d/ - ./panel_front:/usr/share/panel depends_on: - main_panel - test_panel - test_service - main_service volumes: mongodb: mongoconfig: ``` `nginx.conf`: ``` server { listen 80; listen [::]:80; server_name domain.com; location /api { proxy_pass http://main_panel:3000; } location /account { root /usr/share/panel/live; try_files $uri $uri/ /index.html; } location / { proxy_pass http://main_service:3000; } } server { listen 80; listen [::]:80; server_name test.domain.com; location /netflix { proxy_pass http://python_backend_test:5000; } location /api { proxy_pass http://test_panel:3000; } location /account { alias /usr/share/panel/test/; try_files $uri $uri/ /index.html; } location / { proxy_pass http://test_service:3000; } } ```
2021/02/06
[ "https://Stackoverflow.com/questions/66079303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12535379/" ]
There are four solutions. In all of them, x = 0x4121, y = 0x48ab. There are four options for z (two of its bits are free to be 0 or 1), namely 0x1307, 0x1387, 0x1707, 0x1787. This can be calculated by treating the variables are arrays of 16 bits and implementing the bitwise operations on them in terms of operations on booleans. That could probably be done in Prolog, or it could be done with a SAT solver or with binary decisions diagrams, I used [this website](http://haroldbot.nl/?q=%28%28y+%7C+x%29+%3D%3D+0x49ab%29+%26%26+%28%28%28y+%3E%3E+2%29+%5E+x%29+%3D%3D+0x530b%29+%26%26+%28%28%28z+%3E%3E+1%29+%26+y%29+%3D%3D+0x0883%29+%26%26+%28%28%28%28x+%3C%3C+2%29+%26+0xFFFF%29+%7C+z%29+%3D%3D+0x1787%29) which uses BDDs internally.
Here is one using SWI-Prolog's [`library(clpb)`](https://eu.swi-prolog.org/pldoc/man?section=clpb) to solve constraints over boolean variables (thanks Markus Triska!). Very simple translation (I have never used this library but it's rather straightforward): ```none :- use_module(library(clpb)). % sat(Expr) sets up a constraint over variables % labeling(ListOfVariables) fixes 0,1 values for variables (several solutions possible) % atomic_list_concat/3 builds the bitstrings find(X,Y,Z) :- sat( *([~(X15 + Y15), % Y | X = 0X49ab (0100100110101011) (X14 + Y14), ~(X13 + Y13), ~(X12 + Y12), (X11 + Y11), ~(X10 + Y10), ~(X09 + Y09), (X08 + Y08), (X07 + Y07), ~(X06 + Y06), (X05 + Y05), ~(X04 + Y04), (X03 + Y03), ~(X02 + Y02), (X01 + Y01), (X00 + Y00), ~(0 # X15), % (Y >> 2) ^ X = 0X530b (0101001100001011) (0 # X14), ~(Y15 # X13), (Y14 # X12), ~(Y13 # X11), ~(Y12 # X10), (Y11 # X09), (Y10 # X08), ~(Y09 # X07), ~(Y08 # X06), ~(Y07 # X05), ~(Y06 # X04), (Y05 # X03), ~(Y04 # X02), (Y03 # X01), (Y02 # X00), ~(0 * Y15), % (Z >> 1) & Y = 0X0883 (0000100010000011) ~(Z15 * Y14), ~(Z14 * Y13), ~(Z13 * Y12), (Z12 * Y11), ~(Z11 * Y10), ~(Z10 * Y09), ~(Z09 * Y08), (Z08 * Y07), ~(Z07 * Y06), ~(Z06 * Y05), ~(Z05 * Y04), ~(Z04 * Y03), ~(Z03 * Y02), (Z02 * Y01), (Z01 * Y00), ~(X13 + Z15), % (X << 2) | Z = 0X1787 (0001011110000111) ~(X12 + Z14), ~(X11 + Z13), (X10 + Z12), ~(X09 + Z11), (X08 + Z10), (X07 + Z09), (X06 + Z08), (X05 + Z07), ~(X04 + Z06), ~(X03 + Z05), ~(X02 + Z04), ~(X01 + Z03), (X00 + Z02), ( 0 + Z01), ( 0 + Z00) ])), labeling([X15,X14,X13,X12,X11,X10,X09,X08,X07,X06,X05,X04,X03,X02,X01,X00, Y15,Y14,Y13,Y12,Y11,Y10,Y09,Y08,Y07,Y06,Y05,Y04,Y03,Y02,Y01,Y00, Z15,Z14,Z13,Z12,Z11,Z10,Z09,Z08,Z07,Z06,Z05,Z04,Z03,Z02,Z01,Z00]), atomic_list_concat([X15,X14,X13,X12,X11,X10,X09,X08,X07,X06,X05,X04,X03,X02,X01,X00],X), atomic_list_concat([Y15,Y14,Y13,Y12,Y11,Y10,Y09,Y08,Y07,Y06,Y05,Y04,Y03,Y02,Y01,Y00],Y), atomic_list_concat([Z15,Z14,Z13,Z12,Z11,Z10,Z09,Z08,Z07,Z06,Z05,Z04,Z03,Z02,Z01,Z00],Z). ``` We find several solutions in 0.007 seconds, with the translations to hexadecimal (manual work) added: ```none ?- find(X,Y,Z). X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001001100000111' ; % 1307 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001001110000111' ; % 1387 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001011100000111' ; % 1707 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001011110000111'. % 1787 ```
66,079,303
I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel. I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main. After the publishing on main `nginx` forward requests to test and that is the issue. Restarting the `nginx` fixes the problem, so how can I fix the issue permanantly without restarting `nginx` after each publish on the main environement. `docker-compose.yml` : ```yaml version: '3.7' services: main-mongo: image: mongo:4.2.3 container_name: main-mongo volumes: - mongodb:/data/db - mongoconfig:/data/configdb main_service: image: project container_name: main_service restart: on-failure volumes: - ./views:/project/views - ./public:/project/public depends_on: - main-mongo test_service: image: test_project container_name: test_service restart: on-failure volumes: - ./test_view/views:/project/views - ./test_view/public:/project/public environment: - ENV=test depends_on: - main-mongo test_panel: image: test_panel container_name: test_panel restart: on-failure environment: - ENV=test depends_on: - main-mongo main_panel: image: panel container_name: main_panel restart: on-failure depends_on: - main-mongo python_backend_test: image: python_backend_test container_name: python_backend_test restart: on-failure volumes: - /tmp:/tmp nginx: image: nginx:1.17 container_name: nginx restart: on-failure ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d/ - ./panel_front:/usr/share/panel depends_on: - main_panel - test_panel - test_service - main_service volumes: mongodb: mongoconfig: ``` `nginx.conf`: ``` server { listen 80; listen [::]:80; server_name domain.com; location /api { proxy_pass http://main_panel:3000; } location /account { root /usr/share/panel/live; try_files $uri $uri/ /index.html; } location / { proxy_pass http://main_service:3000; } } server { listen 80; listen [::]:80; server_name test.domain.com; location /netflix { proxy_pass http://python_backend_test:5000; } location /api { proxy_pass http://test_panel:3000; } location /account { alias /usr/share/panel/test/; try_files $uri $uri/ /index.html; } location / { proxy_pass http://test_service:3000; } } ```
2021/02/06
[ "https://Stackoverflow.com/questions/66079303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12535379/" ]
There are four solutions. In all of them, x = 0x4121, y = 0x48ab. There are four options for z (two of its bits are free to be 0 or 1), namely 0x1307, 0x1387, 0x1707, 0x1787. This can be calculated by treating the variables are arrays of 16 bits and implementing the bitwise operations on them in terms of operations on booleans. That could probably be done in Prolog, or it could be done with a SAT solver or with binary decisions diagrams, I used [this website](http://haroldbot.nl/?q=%28%28y+%7C+x%29+%3D%3D+0x49ab%29+%26%26+%28%28%28y+%3E%3E+2%29+%5E+x%29+%3D%3D+0x530b%29+%26%26+%28%28%28z+%3E%3E+1%29+%26+y%29+%3D%3D+0x0883%29+%26%26+%28%28%28%28x+%3C%3C+2%29+%26+0xFFFF%29+%7C+z%29+%3D%3D+0x1787%29) which uses BDDs internally.
Here is an implementation in Picat with my experimental bitwise module (<http://hakank.org/picat/bitwise.pi> ) using constraint programming. It took 0.007s on my machine. The model is also here: <http://hakank.org/picat/bit_patterns.pi> ``` import bitwise. import cp. main => go. go ?=> Size = 16, Type = unsigned, println("Answers should be:"), println([x = 0x4121, y = 0x48ab]), println(z=[0x1307, 0x1387, 0x1707, 0x1787]), nl, X = bitvar2(Size,Type), Y = bitvar2(Size,Type), Z = bitvar2(Size,Type), % Y \/ X = 0x49ab, Y.bor(X).v #= 0x49ab, % (Y >> 2) ^ X = 0x530b, Y.right_shift(2).bxor(X).v #= 0x530b, % (Z >> 1) /\ Y = 0x0883, Z.right_shift(1).band(Y).v #= 0x0883, % (X << 2) \/ Z = 0x1787, X.left_shift(2).bor(Z).v #= 0x1787, Vars = [X.get_av,Y.get_av,Z.get_av], println(solve), solve(Vars), println(dec=[x=X.v,y=Y.v,z=Z.v]), println(hex=[x=X.v.to_hex_string,y=Y.v.to_hex_string,z=Z.v.to_hex_string]), println(bin=[x=X.v.to_binary_string,y=Y.v.to_binary_string,z=Z.v.to_binary_string]), nl, fail, nl. go => true. ``` The output: ``` Answers should be: [x = 16673,y = 18603] z = [4871,4999,5895,6023] dec = [x = 16673,y = 18603,z = 4871] hex = [x = 4121,y = 48AB,z = 1307] bin = [x = 100000100100001,y = 100100010101011,z = 1001100000111] dec = [x = 16673,y = 18603,z = 4999] hex = [x = 4121,y = 48AB,z = 1387] bin = [x = 100000100100001,y = 100100010101011,z = 1001110000111] dec = [x = 16673,y = 18603,z = 5895] hex = [x = 4121,y = 48AB,z = 1707] bin = [x = 100000100100001,y = 100100010101011,z = 1011100000111] dec = [x = 16673,y = 18603,z = 6023] hex = [x = 4121,y = 48AB,z = 1787] bin = [x = 100000100100001,y = 100100010101011,z = 1011110000111] ```
66,079,303
I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel. I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main. After the publishing on main `nginx` forward requests to test and that is the issue. Restarting the `nginx` fixes the problem, so how can I fix the issue permanantly without restarting `nginx` after each publish on the main environement. `docker-compose.yml` : ```yaml version: '3.7' services: main-mongo: image: mongo:4.2.3 container_name: main-mongo volumes: - mongodb:/data/db - mongoconfig:/data/configdb main_service: image: project container_name: main_service restart: on-failure volumes: - ./views:/project/views - ./public:/project/public depends_on: - main-mongo test_service: image: test_project container_name: test_service restart: on-failure volumes: - ./test_view/views:/project/views - ./test_view/public:/project/public environment: - ENV=test depends_on: - main-mongo test_panel: image: test_panel container_name: test_panel restart: on-failure environment: - ENV=test depends_on: - main-mongo main_panel: image: panel container_name: main_panel restart: on-failure depends_on: - main-mongo python_backend_test: image: python_backend_test container_name: python_backend_test restart: on-failure volumes: - /tmp:/tmp nginx: image: nginx:1.17 container_name: nginx restart: on-failure ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d/ - ./panel_front:/usr/share/panel depends_on: - main_panel - test_panel - test_service - main_service volumes: mongodb: mongoconfig: ``` `nginx.conf`: ``` server { listen 80; listen [::]:80; server_name domain.com; location /api { proxy_pass http://main_panel:3000; } location /account { root /usr/share/panel/live; try_files $uri $uri/ /index.html; } location / { proxy_pass http://main_service:3000; } } server { listen 80; listen [::]:80; server_name test.domain.com; location /netflix { proxy_pass http://python_backend_test:5000; } location /api { proxy_pass http://test_panel:3000; } location /account { alias /usr/share/panel/test/; try_files $uri $uri/ /index.html; } location / { proxy_pass http://test_service:3000; } } ```
2021/02/06
[ "https://Stackoverflow.com/questions/66079303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12535379/" ]
There are four solutions. In all of them, x = 0x4121, y = 0x48ab. There are four options for z (two of its bits are free to be 0 or 1), namely 0x1307, 0x1387, 0x1707, 0x1787. This can be calculated by treating the variables are arrays of 16 bits and implementing the bitwise operations on them in terms of operations on booleans. That could probably be done in Prolog, or it could be done with a SAT solver or with binary decisions diagrams, I used [this website](http://haroldbot.nl/?q=%28%28y+%7C+x%29+%3D%3D+0x49ab%29+%26%26+%28%28%28y+%3E%3E+2%29+%5E+x%29+%3D%3D+0x530b%29+%26%26+%28%28%28z+%3E%3E+1%29+%26+y%29+%3D%3D+0x0883%29+%26%26+%28%28%28%28x+%3C%3C+2%29+%26+0xFFFF%29+%7C+z%29+%3D%3D+0x1787%29) which uses BDDs internally.
However, for doing these kind of bit calculation, z3 (<https://github.com/Z3Prover/z3> ) is probably the way to go, both in terms of modelling and features: it handle arbitrary long sizes, etc. Here's a z3 model using the Python interface (also here: <http://hakank.org/z3/bit_patterns.py> ): ``` from z3 import * solver = Solver() x = BitVec('x', 16) y = BitVec('y', 16) z = BitVec('z', 16) solver.add(y | x == 0x49ab) solver.add((y >> 2) ^ x == 0x530b) solver.add((z >> 1) & y == 0x0883) solver.add((x << 2) | z == 0x1787) num_solutions = 0 print("check:", solver.check()) while solver.check() == sat: num_solutions += 1 m = solver.model() xval = m.eval(x) yval = m.eval(y) zval = m.eval(z) print([xval,yval,zval]) solver.add(Or([x!=xval,y!=yval,z!=zval])) print("num_solutions:", num_solutions) ``` Output: ``` [16673, 18603, 4871] [16673, 18603, 4999] [16673, 18603, 6023] [16673, 18603, 5895] num_solutions: 4 ```
66,079,303
I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel. I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main. After the publishing on main `nginx` forward requests to test and that is the issue. Restarting the `nginx` fixes the problem, so how can I fix the issue permanantly without restarting `nginx` after each publish on the main environement. `docker-compose.yml` : ```yaml version: '3.7' services: main-mongo: image: mongo:4.2.3 container_name: main-mongo volumes: - mongodb:/data/db - mongoconfig:/data/configdb main_service: image: project container_name: main_service restart: on-failure volumes: - ./views:/project/views - ./public:/project/public depends_on: - main-mongo test_service: image: test_project container_name: test_service restart: on-failure volumes: - ./test_view/views:/project/views - ./test_view/public:/project/public environment: - ENV=test depends_on: - main-mongo test_panel: image: test_panel container_name: test_panel restart: on-failure environment: - ENV=test depends_on: - main-mongo main_panel: image: panel container_name: main_panel restart: on-failure depends_on: - main-mongo python_backend_test: image: python_backend_test container_name: python_backend_test restart: on-failure volumes: - /tmp:/tmp nginx: image: nginx:1.17 container_name: nginx restart: on-failure ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d/ - ./panel_front:/usr/share/panel depends_on: - main_panel - test_panel - test_service - main_service volumes: mongodb: mongoconfig: ``` `nginx.conf`: ``` server { listen 80; listen [::]:80; server_name domain.com; location /api { proxy_pass http://main_panel:3000; } location /account { root /usr/share/panel/live; try_files $uri $uri/ /index.html; } location / { proxy_pass http://main_service:3000; } } server { listen 80; listen [::]:80; server_name test.domain.com; location /netflix { proxy_pass http://python_backend_test:5000; } location /api { proxy_pass http://test_panel:3000; } location /account { alias /usr/share/panel/test/; try_files $uri $uri/ /index.html; } location / { proxy_pass http://test_service:3000; } } ```
2021/02/06
[ "https://Stackoverflow.com/questions/66079303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12535379/" ]
There are four solutions. In all of them, x = 0x4121, y = 0x48ab. There are four options for z (two of its bits are free to be 0 or 1), namely 0x1307, 0x1387, 0x1707, 0x1787. This can be calculated by treating the variables are arrays of 16 bits and implementing the bitwise operations on them in terms of operations on booleans. That could probably be done in Prolog, or it could be done with a SAT solver or with binary decisions diagrams, I used [this website](http://haroldbot.nl/?q=%28%28y+%7C+x%29+%3D%3D+0x49ab%29+%26%26+%28%28%28y+%3E%3E+2%29+%5E+x%29+%3D%3D+0x530b%29+%26%26+%28%28%28z+%3E%3E+1%29+%26+y%29+%3D%3D+0x0883%29+%26%26+%28%28%28%28x+%3C%3C+2%29+%26+0xFFFF%29+%7C+z%29+%3D%3D+0x1787%29) which uses BDDs internally.
A Python solution using BDDs and bitvectors, with the package [`omega`](https://pypi.org/project/omega/): ```py """Solve a problem of bitwise arithmetic using binary decision diagrams.""" import pprint from omega.symbolic import temporal as trl def solve(values): """Encode and solve the problem.""" aut = trl.Automaton() bit_width = 16 max_value = 2**bit_width - 1 dom = (0, max_value) # range of integer values 0..max_value aut.declare_constants(x=dom, y=dom, z=dom) # declares in the BDD manager bits x_0, x_1, ..., x_15, etc. # the declarations can be read with: # `print(aut.vars)` # prepare values bitvalues = [int_to_bitvalues(v, 16) for v in values] bitvalues = [reversed(b) for b in bitvalues] # Below we encode each bitwise operator and shifts by directly mentioning # the bits that encode the declared integer-valued variables. # # form first conjunct conjunct_1 = r' /\ '.join( rf'((x_{i} \/ y_{i}) <=> {to_boolean(b)})' for (i, b) in enumerate(bitvalues[0])) # form second conjunct c = list() for i, b in enumerate(bitvalues[1]): # right shift by 2 if i < 14: e = f'y_{i + 2}' else: e = 'FALSE' s = f'((~ ({e} <=> x_{i})) <=> {to_boolean(b)})' # The TLA+ operator /= means "not equal to", # and for 0, 1 has the same effect as using ^ in `omega` c.append(s) conjunct_2 = '/\\'.join(c) # form third conjunct c = list() for i, b in enumerate(bitvalues[2]): # right shift by 1 if i < 15: e = f'z_{i + 1}' else: e = 'FALSE' s = rf'(({e} /\ y_{i}) <=> {to_boolean(b)})' c.append(s) conjunct_3 = r' /\ '.join(c) # form fourth conjunct c = list() for i, b in enumerate(bitvalues[3]): # left shift by 2 if i > 1: e = f'x_{i - 2}' else: e = 'FALSE' s = rf'(({e} \/ z_{i}) <=> {to_boolean(b)})' c.append(s) conjunct_4 = '/\\'.join(c) # conjoin formulas to form problem description formula = r' /\ '.join( f'({u})' for u in [conjunct_1, conjunct_2, conjunct_3, conjunct_4]) print(formula) # create a BDD `u` that represents the formula u = aut.add_expr(formula) care_vars = {'x', 'y', 'z'} # count and enumerate the satisfying assignments of `u` (solutions) n_solutions = aut.count(u, care_vars=care_vars) solutions = list(aut.pick_iter(u, care_vars=care_vars)) print(f'{n_solutions} solutions:') pprint.pprint(solutions) def to_boolean(x): "Return BOOLEAN constant that corresponds to `x`.""" if x == '0': return 'FALSE' elif x == '1': return 'TRUE' else: raise ValueError(x) def int_to_bitvalues(x, bitwidth): """Return bitstring of `bitwidth` that corresponds to `x`. @type x: `int` @type bitwidth: `int` Reference ========= This computation is from the module `omega.logic.bitvector`, specifically: https://github.com/tulip-control/omega/blob/ 0627e6d0cd15b7c42a8c53d0bb3cfa58df9c30f1/omega/logic/bitvector.py#L1159 """ assert bitwidth > 0, bitwidth return bin(x).lstrip('-0b').zfill(bitwidth) if __name__ == '__main__': values = [0x49ab, 0x530b, 0x0883, 0x1787] solve(values) ``` The output gives the solutions: ``` 4 solutions: [{'x': 16673, 'y': 18603, 'z': 4871}, {'x': 16673, 'y': 18603, 'z': 4999}, {'x': 16673, 'y': 18603, 'z': 5895}, {'x': 16673, 'y': 18603, 'z': 6023}] ``` which agree with the other answers posted here. The package `omega` can be installed from [PyPI](https://pypi.org/project/omega/) using [`pip`](https://pip.pypa.io/en/stable/) as follows: ```sh pip install omega ``` The output also includes the [TLA+](https://lamport.azurewebsites.net/tla/tla.html) formula that encodes the problem: ``` (((x_0 \/ y_0) <=> TRUE) /\ ((x_1 \/ y_1) <=> TRUE) /\ ((x_2 \/ y_2) <=> FALSE) /\ ((x_3 \/ y_3) <=> TRUE) /\ ((x_4 \/ y_4) <=> FALSE) /\ ((x_5 \/ y_5) <=> TRUE) /\ ((x_6 \/ y_6) <=> FALSE) /\ ((x_7 \/ y_7) <=> TRUE) /\ ((x_8 \/ y_8) <=> TRUE) /\ ((x_9 \/ y_9) <=> FALSE) /\ ((x_10 \/ y_10) <=> FALSE) /\ ((x_11 \/ y_11) <=> TRUE) /\ ((x_12 \/ y_12) <=> FALSE) /\ ((x_13 \/ y_13) <=> FALSE) /\ ((x_14 \/ y_14) <=> TRUE) /\ ((x_15 \/ y_15) <=> FALSE)) /\ (((~ (y_2 <=> x_0)) <=> TRUE)/\((~ (y_3 <=> x_1)) <=> TRUE)/\((~ (y_4 <=> x_2)) <=> FALSE)/\((~ (y_5 <=> x_3)) <=> TRUE)/\((~ (y_6 <=> x_4)) <=> FALSE)/\((~ (y_7 <=> x_5)) <=> FALSE)/\((~ (y_8 <=> x_6)) <=> FALSE)/\((~ (y_9 <=> x_7)) <=> FALSE)/\((~ (y_10 <=> x_8)) <=> TRUE)/\((~ (y_11 <=> x_9)) <=> TRUE)/\((~ (y_12 <=> x_10)) <=> FALSE)/\((~ (y_13 <=> x_11)) <=> FALSE)/\((~ (y_14 <=> x_12)) <=> TRUE)/\((~ (y_15 <=> x_13)) <=> FALSE)/\((~ (FALSE <=> x_14)) <=> TRUE)/\((~ (FALSE <=> x_15)) <=> FALSE)) /\ (((z_1 /\ y_0) <=> TRUE) /\ ((z_2 /\ y_1) <=> TRUE) /\ ((z_3 /\ y_2) <=> FALSE) /\ ((z_4 /\ y_3) <=> FALSE) /\ ((z_5 /\ y_4) <=> FALSE) /\ ((z_6 /\ y_5) <=> FALSE) /\ ((z_7 /\ y_6) <=> FALSE) /\ ((z_8 /\ y_7) <=> TRUE) /\ ((z_9 /\ y_8) <=> FALSE) /\ ((z_10 /\ y_9) <=> FALSE) /\ ((z_11 /\ y_10) <=> FALSE) /\ ((z_12 /\ y_11) <=> TRUE) /\ ((z_13 /\ y_12) <=> FALSE) /\ ((z_14 /\ y_13) <=> FALSE) /\ ((z_15 /\ y_14) <=> FALSE) /\ ((FALSE /\ y_15) <=> FALSE)) /\ (((FALSE \/ z_0) <=> TRUE)/\((FALSE \/ z_1) <=> TRUE)/\((x_0 \/ z_2) <=> TRUE)/\((x_1 \/ z_3) <=> FALSE)/\((x_2 \/ z_4) <=> FALSE)/\((x_3 \/ z_5) <=> FALSE)/\((x_4 \/ z_6) <=> FALSE)/\((x_5 \/ z_7) <=> TRUE)/\((x_6 \/ z_8) <=> TRUE)/\((x_7 \/ z_9) <=> TRUE)/\((x_8 \/ z_10) <=> TRUE)/\((x_9 \/ z_11) <=> FALSE)/\((x_10 \/ z_12) <=> TRUE)/\((x_11 \/ z_13) <=> FALSE)/\((x_12 \/ z_14) <=> FALSE)/\((x_13 \/ z_15) <=> FALSE)) ```
66,079,303
I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel. I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main. After the publishing on main `nginx` forward requests to test and that is the issue. Restarting the `nginx` fixes the problem, so how can I fix the issue permanantly without restarting `nginx` after each publish on the main environement. `docker-compose.yml` : ```yaml version: '3.7' services: main-mongo: image: mongo:4.2.3 container_name: main-mongo volumes: - mongodb:/data/db - mongoconfig:/data/configdb main_service: image: project container_name: main_service restart: on-failure volumes: - ./views:/project/views - ./public:/project/public depends_on: - main-mongo test_service: image: test_project container_name: test_service restart: on-failure volumes: - ./test_view/views:/project/views - ./test_view/public:/project/public environment: - ENV=test depends_on: - main-mongo test_panel: image: test_panel container_name: test_panel restart: on-failure environment: - ENV=test depends_on: - main-mongo main_panel: image: panel container_name: main_panel restart: on-failure depends_on: - main-mongo python_backend_test: image: python_backend_test container_name: python_backend_test restart: on-failure volumes: - /tmp:/tmp nginx: image: nginx:1.17 container_name: nginx restart: on-failure ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d/ - ./panel_front:/usr/share/panel depends_on: - main_panel - test_panel - test_service - main_service volumes: mongodb: mongoconfig: ``` `nginx.conf`: ``` server { listen 80; listen [::]:80; server_name domain.com; location /api { proxy_pass http://main_panel:3000; } location /account { root /usr/share/panel/live; try_files $uri $uri/ /index.html; } location / { proxy_pass http://main_service:3000; } } server { listen 80; listen [::]:80; server_name test.domain.com; location /netflix { proxy_pass http://python_backend_test:5000; } location /api { proxy_pass http://test_panel:3000; } location /account { alias /usr/share/panel/test/; try_files $uri $uri/ /index.html; } location / { proxy_pass http://test_service:3000; } } ```
2021/02/06
[ "https://Stackoverflow.com/questions/66079303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12535379/" ]
Here is one using SWI-Prolog's [`library(clpb)`](https://eu.swi-prolog.org/pldoc/man?section=clpb) to solve constraints over boolean variables (thanks Markus Triska!). Very simple translation (I have never used this library but it's rather straightforward): ```none :- use_module(library(clpb)). % sat(Expr) sets up a constraint over variables % labeling(ListOfVariables) fixes 0,1 values for variables (several solutions possible) % atomic_list_concat/3 builds the bitstrings find(X,Y,Z) :- sat( *([~(X15 + Y15), % Y | X = 0X49ab (0100100110101011) (X14 + Y14), ~(X13 + Y13), ~(X12 + Y12), (X11 + Y11), ~(X10 + Y10), ~(X09 + Y09), (X08 + Y08), (X07 + Y07), ~(X06 + Y06), (X05 + Y05), ~(X04 + Y04), (X03 + Y03), ~(X02 + Y02), (X01 + Y01), (X00 + Y00), ~(0 # X15), % (Y >> 2) ^ X = 0X530b (0101001100001011) (0 # X14), ~(Y15 # X13), (Y14 # X12), ~(Y13 # X11), ~(Y12 # X10), (Y11 # X09), (Y10 # X08), ~(Y09 # X07), ~(Y08 # X06), ~(Y07 # X05), ~(Y06 # X04), (Y05 # X03), ~(Y04 # X02), (Y03 # X01), (Y02 # X00), ~(0 * Y15), % (Z >> 1) & Y = 0X0883 (0000100010000011) ~(Z15 * Y14), ~(Z14 * Y13), ~(Z13 * Y12), (Z12 * Y11), ~(Z11 * Y10), ~(Z10 * Y09), ~(Z09 * Y08), (Z08 * Y07), ~(Z07 * Y06), ~(Z06 * Y05), ~(Z05 * Y04), ~(Z04 * Y03), ~(Z03 * Y02), (Z02 * Y01), (Z01 * Y00), ~(X13 + Z15), % (X << 2) | Z = 0X1787 (0001011110000111) ~(X12 + Z14), ~(X11 + Z13), (X10 + Z12), ~(X09 + Z11), (X08 + Z10), (X07 + Z09), (X06 + Z08), (X05 + Z07), ~(X04 + Z06), ~(X03 + Z05), ~(X02 + Z04), ~(X01 + Z03), (X00 + Z02), ( 0 + Z01), ( 0 + Z00) ])), labeling([X15,X14,X13,X12,X11,X10,X09,X08,X07,X06,X05,X04,X03,X02,X01,X00, Y15,Y14,Y13,Y12,Y11,Y10,Y09,Y08,Y07,Y06,Y05,Y04,Y03,Y02,Y01,Y00, Z15,Z14,Z13,Z12,Z11,Z10,Z09,Z08,Z07,Z06,Z05,Z04,Z03,Z02,Z01,Z00]), atomic_list_concat([X15,X14,X13,X12,X11,X10,X09,X08,X07,X06,X05,X04,X03,X02,X01,X00],X), atomic_list_concat([Y15,Y14,Y13,Y12,Y11,Y10,Y09,Y08,Y07,Y06,Y05,Y04,Y03,Y02,Y01,Y00],Y), atomic_list_concat([Z15,Z14,Z13,Z12,Z11,Z10,Z09,Z08,Z07,Z06,Z05,Z04,Z03,Z02,Z01,Z00],Z). ``` We find several solutions in 0.007 seconds, with the translations to hexadecimal (manual work) added: ```none ?- find(X,Y,Z). X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001001100000111' ; % 1307 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001001110000111' ; % 1387 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001011100000111' ; % 1707 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001011110000111'. % 1787 ```
Here is an implementation in Picat with my experimental bitwise module (<http://hakank.org/picat/bitwise.pi> ) using constraint programming. It took 0.007s on my machine. The model is also here: <http://hakank.org/picat/bit_patterns.pi> ``` import bitwise. import cp. main => go. go ?=> Size = 16, Type = unsigned, println("Answers should be:"), println([x = 0x4121, y = 0x48ab]), println(z=[0x1307, 0x1387, 0x1707, 0x1787]), nl, X = bitvar2(Size,Type), Y = bitvar2(Size,Type), Z = bitvar2(Size,Type), % Y \/ X = 0x49ab, Y.bor(X).v #= 0x49ab, % (Y >> 2) ^ X = 0x530b, Y.right_shift(2).bxor(X).v #= 0x530b, % (Z >> 1) /\ Y = 0x0883, Z.right_shift(1).band(Y).v #= 0x0883, % (X << 2) \/ Z = 0x1787, X.left_shift(2).bor(Z).v #= 0x1787, Vars = [X.get_av,Y.get_av,Z.get_av], println(solve), solve(Vars), println(dec=[x=X.v,y=Y.v,z=Z.v]), println(hex=[x=X.v.to_hex_string,y=Y.v.to_hex_string,z=Z.v.to_hex_string]), println(bin=[x=X.v.to_binary_string,y=Y.v.to_binary_string,z=Z.v.to_binary_string]), nl, fail, nl. go => true. ``` The output: ``` Answers should be: [x = 16673,y = 18603] z = [4871,4999,5895,6023] dec = [x = 16673,y = 18603,z = 4871] hex = [x = 4121,y = 48AB,z = 1307] bin = [x = 100000100100001,y = 100100010101011,z = 1001100000111] dec = [x = 16673,y = 18603,z = 4999] hex = [x = 4121,y = 48AB,z = 1387] bin = [x = 100000100100001,y = 100100010101011,z = 1001110000111] dec = [x = 16673,y = 18603,z = 5895] hex = [x = 4121,y = 48AB,z = 1707] bin = [x = 100000100100001,y = 100100010101011,z = 1011100000111] dec = [x = 16673,y = 18603,z = 6023] hex = [x = 4121,y = 48AB,z = 1787] bin = [x = 100000100100001,y = 100100010101011,z = 1011110000111] ```
66,079,303
I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel. I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main. After the publishing on main `nginx` forward requests to test and that is the issue. Restarting the `nginx` fixes the problem, so how can I fix the issue permanantly without restarting `nginx` after each publish on the main environement. `docker-compose.yml` : ```yaml version: '3.7' services: main-mongo: image: mongo:4.2.3 container_name: main-mongo volumes: - mongodb:/data/db - mongoconfig:/data/configdb main_service: image: project container_name: main_service restart: on-failure volumes: - ./views:/project/views - ./public:/project/public depends_on: - main-mongo test_service: image: test_project container_name: test_service restart: on-failure volumes: - ./test_view/views:/project/views - ./test_view/public:/project/public environment: - ENV=test depends_on: - main-mongo test_panel: image: test_panel container_name: test_panel restart: on-failure environment: - ENV=test depends_on: - main-mongo main_panel: image: panel container_name: main_panel restart: on-failure depends_on: - main-mongo python_backend_test: image: python_backend_test container_name: python_backend_test restart: on-failure volumes: - /tmp:/tmp nginx: image: nginx:1.17 container_name: nginx restart: on-failure ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d/ - ./panel_front:/usr/share/panel depends_on: - main_panel - test_panel - test_service - main_service volumes: mongodb: mongoconfig: ``` `nginx.conf`: ``` server { listen 80; listen [::]:80; server_name domain.com; location /api { proxy_pass http://main_panel:3000; } location /account { root /usr/share/panel/live; try_files $uri $uri/ /index.html; } location / { proxy_pass http://main_service:3000; } } server { listen 80; listen [::]:80; server_name test.domain.com; location /netflix { proxy_pass http://python_backend_test:5000; } location /api { proxy_pass http://test_panel:3000; } location /account { alias /usr/share/panel/test/; try_files $uri $uri/ /index.html; } location / { proxy_pass http://test_service:3000; } } ```
2021/02/06
[ "https://Stackoverflow.com/questions/66079303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12535379/" ]
Here is one using SWI-Prolog's [`library(clpb)`](https://eu.swi-prolog.org/pldoc/man?section=clpb) to solve constraints over boolean variables (thanks Markus Triska!). Very simple translation (I have never used this library but it's rather straightforward): ```none :- use_module(library(clpb)). % sat(Expr) sets up a constraint over variables % labeling(ListOfVariables) fixes 0,1 values for variables (several solutions possible) % atomic_list_concat/3 builds the bitstrings find(X,Y,Z) :- sat( *([~(X15 + Y15), % Y | X = 0X49ab (0100100110101011) (X14 + Y14), ~(X13 + Y13), ~(X12 + Y12), (X11 + Y11), ~(X10 + Y10), ~(X09 + Y09), (X08 + Y08), (X07 + Y07), ~(X06 + Y06), (X05 + Y05), ~(X04 + Y04), (X03 + Y03), ~(X02 + Y02), (X01 + Y01), (X00 + Y00), ~(0 # X15), % (Y >> 2) ^ X = 0X530b (0101001100001011) (0 # X14), ~(Y15 # X13), (Y14 # X12), ~(Y13 # X11), ~(Y12 # X10), (Y11 # X09), (Y10 # X08), ~(Y09 # X07), ~(Y08 # X06), ~(Y07 # X05), ~(Y06 # X04), (Y05 # X03), ~(Y04 # X02), (Y03 # X01), (Y02 # X00), ~(0 * Y15), % (Z >> 1) & Y = 0X0883 (0000100010000011) ~(Z15 * Y14), ~(Z14 * Y13), ~(Z13 * Y12), (Z12 * Y11), ~(Z11 * Y10), ~(Z10 * Y09), ~(Z09 * Y08), (Z08 * Y07), ~(Z07 * Y06), ~(Z06 * Y05), ~(Z05 * Y04), ~(Z04 * Y03), ~(Z03 * Y02), (Z02 * Y01), (Z01 * Y00), ~(X13 + Z15), % (X << 2) | Z = 0X1787 (0001011110000111) ~(X12 + Z14), ~(X11 + Z13), (X10 + Z12), ~(X09 + Z11), (X08 + Z10), (X07 + Z09), (X06 + Z08), (X05 + Z07), ~(X04 + Z06), ~(X03 + Z05), ~(X02 + Z04), ~(X01 + Z03), (X00 + Z02), ( 0 + Z01), ( 0 + Z00) ])), labeling([X15,X14,X13,X12,X11,X10,X09,X08,X07,X06,X05,X04,X03,X02,X01,X00, Y15,Y14,Y13,Y12,Y11,Y10,Y09,Y08,Y07,Y06,Y05,Y04,Y03,Y02,Y01,Y00, Z15,Z14,Z13,Z12,Z11,Z10,Z09,Z08,Z07,Z06,Z05,Z04,Z03,Z02,Z01,Z00]), atomic_list_concat([X15,X14,X13,X12,X11,X10,X09,X08,X07,X06,X05,X04,X03,X02,X01,X00],X), atomic_list_concat([Y15,Y14,Y13,Y12,Y11,Y10,Y09,Y08,Y07,Y06,Y05,Y04,Y03,Y02,Y01,Y00],Y), atomic_list_concat([Z15,Z14,Z13,Z12,Z11,Z10,Z09,Z08,Z07,Z06,Z05,Z04,Z03,Z02,Z01,Z00],Z). ``` We find several solutions in 0.007 seconds, with the translations to hexadecimal (manual work) added: ```none ?- find(X,Y,Z). X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001001100000111' ; % 1307 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001001110000111' ; % 1387 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001011100000111' ; % 1707 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001011110000111'. % 1787 ```
However, for doing these kind of bit calculation, z3 (<https://github.com/Z3Prover/z3> ) is probably the way to go, both in terms of modelling and features: it handle arbitrary long sizes, etc. Here's a z3 model using the Python interface (also here: <http://hakank.org/z3/bit_patterns.py> ): ``` from z3 import * solver = Solver() x = BitVec('x', 16) y = BitVec('y', 16) z = BitVec('z', 16) solver.add(y | x == 0x49ab) solver.add((y >> 2) ^ x == 0x530b) solver.add((z >> 1) & y == 0x0883) solver.add((x << 2) | z == 0x1787) num_solutions = 0 print("check:", solver.check()) while solver.check() == sat: num_solutions += 1 m = solver.model() xval = m.eval(x) yval = m.eval(y) zval = m.eval(z) print([xval,yval,zval]) solver.add(Or([x!=xval,y!=yval,z!=zval])) print("num_solutions:", num_solutions) ``` Output: ``` [16673, 18603, 4871] [16673, 18603, 4999] [16673, 18603, 6023] [16673, 18603, 5895] num_solutions: 4 ```
66,079,303
I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel. I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main. After the publishing on main `nginx` forward requests to test and that is the issue. Restarting the `nginx` fixes the problem, so how can I fix the issue permanantly without restarting `nginx` after each publish on the main environement. `docker-compose.yml` : ```yaml version: '3.7' services: main-mongo: image: mongo:4.2.3 container_name: main-mongo volumes: - mongodb:/data/db - mongoconfig:/data/configdb main_service: image: project container_name: main_service restart: on-failure volumes: - ./views:/project/views - ./public:/project/public depends_on: - main-mongo test_service: image: test_project container_name: test_service restart: on-failure volumes: - ./test_view/views:/project/views - ./test_view/public:/project/public environment: - ENV=test depends_on: - main-mongo test_panel: image: test_panel container_name: test_panel restart: on-failure environment: - ENV=test depends_on: - main-mongo main_panel: image: panel container_name: main_panel restart: on-failure depends_on: - main-mongo python_backend_test: image: python_backend_test container_name: python_backend_test restart: on-failure volumes: - /tmp:/tmp nginx: image: nginx:1.17 container_name: nginx restart: on-failure ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d/ - ./panel_front:/usr/share/panel depends_on: - main_panel - test_panel - test_service - main_service volumes: mongodb: mongoconfig: ``` `nginx.conf`: ``` server { listen 80; listen [::]:80; server_name domain.com; location /api { proxy_pass http://main_panel:3000; } location /account { root /usr/share/panel/live; try_files $uri $uri/ /index.html; } location / { proxy_pass http://main_service:3000; } } server { listen 80; listen [::]:80; server_name test.domain.com; location /netflix { proxy_pass http://python_backend_test:5000; } location /api { proxy_pass http://test_panel:3000; } location /account { alias /usr/share/panel/test/; try_files $uri $uri/ /index.html; } location / { proxy_pass http://test_service:3000; } } ```
2021/02/06
[ "https://Stackoverflow.com/questions/66079303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12535379/" ]
Here is one using SWI-Prolog's [`library(clpb)`](https://eu.swi-prolog.org/pldoc/man?section=clpb) to solve constraints over boolean variables (thanks Markus Triska!). Very simple translation (I have never used this library but it's rather straightforward): ```none :- use_module(library(clpb)). % sat(Expr) sets up a constraint over variables % labeling(ListOfVariables) fixes 0,1 values for variables (several solutions possible) % atomic_list_concat/3 builds the bitstrings find(X,Y,Z) :- sat( *([~(X15 + Y15), % Y | X = 0X49ab (0100100110101011) (X14 + Y14), ~(X13 + Y13), ~(X12 + Y12), (X11 + Y11), ~(X10 + Y10), ~(X09 + Y09), (X08 + Y08), (X07 + Y07), ~(X06 + Y06), (X05 + Y05), ~(X04 + Y04), (X03 + Y03), ~(X02 + Y02), (X01 + Y01), (X00 + Y00), ~(0 # X15), % (Y >> 2) ^ X = 0X530b (0101001100001011) (0 # X14), ~(Y15 # X13), (Y14 # X12), ~(Y13 # X11), ~(Y12 # X10), (Y11 # X09), (Y10 # X08), ~(Y09 # X07), ~(Y08 # X06), ~(Y07 # X05), ~(Y06 # X04), (Y05 # X03), ~(Y04 # X02), (Y03 # X01), (Y02 # X00), ~(0 * Y15), % (Z >> 1) & Y = 0X0883 (0000100010000011) ~(Z15 * Y14), ~(Z14 * Y13), ~(Z13 * Y12), (Z12 * Y11), ~(Z11 * Y10), ~(Z10 * Y09), ~(Z09 * Y08), (Z08 * Y07), ~(Z07 * Y06), ~(Z06 * Y05), ~(Z05 * Y04), ~(Z04 * Y03), ~(Z03 * Y02), (Z02 * Y01), (Z01 * Y00), ~(X13 + Z15), % (X << 2) | Z = 0X1787 (0001011110000111) ~(X12 + Z14), ~(X11 + Z13), (X10 + Z12), ~(X09 + Z11), (X08 + Z10), (X07 + Z09), (X06 + Z08), (X05 + Z07), ~(X04 + Z06), ~(X03 + Z05), ~(X02 + Z04), ~(X01 + Z03), (X00 + Z02), ( 0 + Z01), ( 0 + Z00) ])), labeling([X15,X14,X13,X12,X11,X10,X09,X08,X07,X06,X05,X04,X03,X02,X01,X00, Y15,Y14,Y13,Y12,Y11,Y10,Y09,Y08,Y07,Y06,Y05,Y04,Y03,Y02,Y01,Y00, Z15,Z14,Z13,Z12,Z11,Z10,Z09,Z08,Z07,Z06,Z05,Z04,Z03,Z02,Z01,Z00]), atomic_list_concat([X15,X14,X13,X12,X11,X10,X09,X08,X07,X06,X05,X04,X03,X02,X01,X00],X), atomic_list_concat([Y15,Y14,Y13,Y12,Y11,Y10,Y09,Y08,Y07,Y06,Y05,Y04,Y03,Y02,Y01,Y00],Y), atomic_list_concat([Z15,Z14,Z13,Z12,Z11,Z10,Z09,Z08,Z07,Z06,Z05,Z04,Z03,Z02,Z01,Z00],Z). ``` We find several solutions in 0.007 seconds, with the translations to hexadecimal (manual work) added: ```none ?- find(X,Y,Z). X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001001100000111' ; % 1307 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001001110000111' ; % 1387 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001011100000111' ; % 1707 X = '0100000100100001', % 4121 Y = '0100100010101011', % 48AB Z = '0001011110000111'. % 1787 ```
A Python solution using BDDs and bitvectors, with the package [`omega`](https://pypi.org/project/omega/): ```py """Solve a problem of bitwise arithmetic using binary decision diagrams.""" import pprint from omega.symbolic import temporal as trl def solve(values): """Encode and solve the problem.""" aut = trl.Automaton() bit_width = 16 max_value = 2**bit_width - 1 dom = (0, max_value) # range of integer values 0..max_value aut.declare_constants(x=dom, y=dom, z=dom) # declares in the BDD manager bits x_0, x_1, ..., x_15, etc. # the declarations can be read with: # `print(aut.vars)` # prepare values bitvalues = [int_to_bitvalues(v, 16) for v in values] bitvalues = [reversed(b) for b in bitvalues] # Below we encode each bitwise operator and shifts by directly mentioning # the bits that encode the declared integer-valued variables. # # form first conjunct conjunct_1 = r' /\ '.join( rf'((x_{i} \/ y_{i}) <=> {to_boolean(b)})' for (i, b) in enumerate(bitvalues[0])) # form second conjunct c = list() for i, b in enumerate(bitvalues[1]): # right shift by 2 if i < 14: e = f'y_{i + 2}' else: e = 'FALSE' s = f'((~ ({e} <=> x_{i})) <=> {to_boolean(b)})' # The TLA+ operator /= means "not equal to", # and for 0, 1 has the same effect as using ^ in `omega` c.append(s) conjunct_2 = '/\\'.join(c) # form third conjunct c = list() for i, b in enumerate(bitvalues[2]): # right shift by 1 if i < 15: e = f'z_{i + 1}' else: e = 'FALSE' s = rf'(({e} /\ y_{i}) <=> {to_boolean(b)})' c.append(s) conjunct_3 = r' /\ '.join(c) # form fourth conjunct c = list() for i, b in enumerate(bitvalues[3]): # left shift by 2 if i > 1: e = f'x_{i - 2}' else: e = 'FALSE' s = rf'(({e} \/ z_{i}) <=> {to_boolean(b)})' c.append(s) conjunct_4 = '/\\'.join(c) # conjoin formulas to form problem description formula = r' /\ '.join( f'({u})' for u in [conjunct_1, conjunct_2, conjunct_3, conjunct_4]) print(formula) # create a BDD `u` that represents the formula u = aut.add_expr(formula) care_vars = {'x', 'y', 'z'} # count and enumerate the satisfying assignments of `u` (solutions) n_solutions = aut.count(u, care_vars=care_vars) solutions = list(aut.pick_iter(u, care_vars=care_vars)) print(f'{n_solutions} solutions:') pprint.pprint(solutions) def to_boolean(x): "Return BOOLEAN constant that corresponds to `x`.""" if x == '0': return 'FALSE' elif x == '1': return 'TRUE' else: raise ValueError(x) def int_to_bitvalues(x, bitwidth): """Return bitstring of `bitwidth` that corresponds to `x`. @type x: `int` @type bitwidth: `int` Reference ========= This computation is from the module `omega.logic.bitvector`, specifically: https://github.com/tulip-control/omega/blob/ 0627e6d0cd15b7c42a8c53d0bb3cfa58df9c30f1/omega/logic/bitvector.py#L1159 """ assert bitwidth > 0, bitwidth return bin(x).lstrip('-0b').zfill(bitwidth) if __name__ == '__main__': values = [0x49ab, 0x530b, 0x0883, 0x1787] solve(values) ``` The output gives the solutions: ``` 4 solutions: [{'x': 16673, 'y': 18603, 'z': 4871}, {'x': 16673, 'y': 18603, 'z': 4999}, {'x': 16673, 'y': 18603, 'z': 5895}, {'x': 16673, 'y': 18603, 'z': 6023}] ``` which agree with the other answers posted here. The package `omega` can be installed from [PyPI](https://pypi.org/project/omega/) using [`pip`](https://pip.pypa.io/en/stable/) as follows: ```sh pip install omega ``` The output also includes the [TLA+](https://lamport.azurewebsites.net/tla/tla.html) formula that encodes the problem: ``` (((x_0 \/ y_0) <=> TRUE) /\ ((x_1 \/ y_1) <=> TRUE) /\ ((x_2 \/ y_2) <=> FALSE) /\ ((x_3 \/ y_3) <=> TRUE) /\ ((x_4 \/ y_4) <=> FALSE) /\ ((x_5 \/ y_5) <=> TRUE) /\ ((x_6 \/ y_6) <=> FALSE) /\ ((x_7 \/ y_7) <=> TRUE) /\ ((x_8 \/ y_8) <=> TRUE) /\ ((x_9 \/ y_9) <=> FALSE) /\ ((x_10 \/ y_10) <=> FALSE) /\ ((x_11 \/ y_11) <=> TRUE) /\ ((x_12 \/ y_12) <=> FALSE) /\ ((x_13 \/ y_13) <=> FALSE) /\ ((x_14 \/ y_14) <=> TRUE) /\ ((x_15 \/ y_15) <=> FALSE)) /\ (((~ (y_2 <=> x_0)) <=> TRUE)/\((~ (y_3 <=> x_1)) <=> TRUE)/\((~ (y_4 <=> x_2)) <=> FALSE)/\((~ (y_5 <=> x_3)) <=> TRUE)/\((~ (y_6 <=> x_4)) <=> FALSE)/\((~ (y_7 <=> x_5)) <=> FALSE)/\((~ (y_8 <=> x_6)) <=> FALSE)/\((~ (y_9 <=> x_7)) <=> FALSE)/\((~ (y_10 <=> x_8)) <=> TRUE)/\((~ (y_11 <=> x_9)) <=> TRUE)/\((~ (y_12 <=> x_10)) <=> FALSE)/\((~ (y_13 <=> x_11)) <=> FALSE)/\((~ (y_14 <=> x_12)) <=> TRUE)/\((~ (y_15 <=> x_13)) <=> FALSE)/\((~ (FALSE <=> x_14)) <=> TRUE)/\((~ (FALSE <=> x_15)) <=> FALSE)) /\ (((z_1 /\ y_0) <=> TRUE) /\ ((z_2 /\ y_1) <=> TRUE) /\ ((z_3 /\ y_2) <=> FALSE) /\ ((z_4 /\ y_3) <=> FALSE) /\ ((z_5 /\ y_4) <=> FALSE) /\ ((z_6 /\ y_5) <=> FALSE) /\ ((z_7 /\ y_6) <=> FALSE) /\ ((z_8 /\ y_7) <=> TRUE) /\ ((z_9 /\ y_8) <=> FALSE) /\ ((z_10 /\ y_9) <=> FALSE) /\ ((z_11 /\ y_10) <=> FALSE) /\ ((z_12 /\ y_11) <=> TRUE) /\ ((z_13 /\ y_12) <=> FALSE) /\ ((z_14 /\ y_13) <=> FALSE) /\ ((z_15 /\ y_14) <=> FALSE) /\ ((FALSE /\ y_15) <=> FALSE)) /\ (((FALSE \/ z_0) <=> TRUE)/\((FALSE \/ z_1) <=> TRUE)/\((x_0 \/ z_2) <=> TRUE)/\((x_1 \/ z_3) <=> FALSE)/\((x_2 \/ z_4) <=> FALSE)/\((x_3 \/ z_5) <=> FALSE)/\((x_4 \/ z_6) <=> FALSE)/\((x_5 \/ z_7) <=> TRUE)/\((x_6 \/ z_8) <=> TRUE)/\((x_7 \/ z_9) <=> TRUE)/\((x_8 \/ z_10) <=> TRUE)/\((x_9 \/ z_11) <=> FALSE)/\((x_10 \/ z_12) <=> TRUE)/\((x_11 \/ z_13) <=> FALSE)/\((x_12 \/ z_14) <=> FALSE)/\((x_13 \/ z_15) <=> FALSE)) ```
66,079,303
I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel. I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main. After the publishing on main `nginx` forward requests to test and that is the issue. Restarting the `nginx` fixes the problem, so how can I fix the issue permanantly without restarting `nginx` after each publish on the main environement. `docker-compose.yml` : ```yaml version: '3.7' services: main-mongo: image: mongo:4.2.3 container_name: main-mongo volumes: - mongodb:/data/db - mongoconfig:/data/configdb main_service: image: project container_name: main_service restart: on-failure volumes: - ./views:/project/views - ./public:/project/public depends_on: - main-mongo test_service: image: test_project container_name: test_service restart: on-failure volumes: - ./test_view/views:/project/views - ./test_view/public:/project/public environment: - ENV=test depends_on: - main-mongo test_panel: image: test_panel container_name: test_panel restart: on-failure environment: - ENV=test depends_on: - main-mongo main_panel: image: panel container_name: main_panel restart: on-failure depends_on: - main-mongo python_backend_test: image: python_backend_test container_name: python_backend_test restart: on-failure volumes: - /tmp:/tmp nginx: image: nginx:1.17 container_name: nginx restart: on-failure ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d/ - ./panel_front:/usr/share/panel depends_on: - main_panel - test_panel - test_service - main_service volumes: mongodb: mongoconfig: ``` `nginx.conf`: ``` server { listen 80; listen [::]:80; server_name domain.com; location /api { proxy_pass http://main_panel:3000; } location /account { root /usr/share/panel/live; try_files $uri $uri/ /index.html; } location / { proxy_pass http://main_service:3000; } } server { listen 80; listen [::]:80; server_name test.domain.com; location /netflix { proxy_pass http://python_backend_test:5000; } location /api { proxy_pass http://test_panel:3000; } location /account { alias /usr/share/panel/test/; try_files $uri $uri/ /index.html; } location / { proxy_pass http://test_service:3000; } } ```
2021/02/06
[ "https://Stackoverflow.com/questions/66079303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12535379/" ]
Here is an implementation in Picat with my experimental bitwise module (<http://hakank.org/picat/bitwise.pi> ) using constraint programming. It took 0.007s on my machine. The model is also here: <http://hakank.org/picat/bit_patterns.pi> ``` import bitwise. import cp. main => go. go ?=> Size = 16, Type = unsigned, println("Answers should be:"), println([x = 0x4121, y = 0x48ab]), println(z=[0x1307, 0x1387, 0x1707, 0x1787]), nl, X = bitvar2(Size,Type), Y = bitvar2(Size,Type), Z = bitvar2(Size,Type), % Y \/ X = 0x49ab, Y.bor(X).v #= 0x49ab, % (Y >> 2) ^ X = 0x530b, Y.right_shift(2).bxor(X).v #= 0x530b, % (Z >> 1) /\ Y = 0x0883, Z.right_shift(1).band(Y).v #= 0x0883, % (X << 2) \/ Z = 0x1787, X.left_shift(2).bor(Z).v #= 0x1787, Vars = [X.get_av,Y.get_av,Z.get_av], println(solve), solve(Vars), println(dec=[x=X.v,y=Y.v,z=Z.v]), println(hex=[x=X.v.to_hex_string,y=Y.v.to_hex_string,z=Z.v.to_hex_string]), println(bin=[x=X.v.to_binary_string,y=Y.v.to_binary_string,z=Z.v.to_binary_string]), nl, fail, nl. go => true. ``` The output: ``` Answers should be: [x = 16673,y = 18603] z = [4871,4999,5895,6023] dec = [x = 16673,y = 18603,z = 4871] hex = [x = 4121,y = 48AB,z = 1307] bin = [x = 100000100100001,y = 100100010101011,z = 1001100000111] dec = [x = 16673,y = 18603,z = 4999] hex = [x = 4121,y = 48AB,z = 1387] bin = [x = 100000100100001,y = 100100010101011,z = 1001110000111] dec = [x = 16673,y = 18603,z = 5895] hex = [x = 4121,y = 48AB,z = 1707] bin = [x = 100000100100001,y = 100100010101011,z = 1011100000111] dec = [x = 16673,y = 18603,z = 6023] hex = [x = 4121,y = 48AB,z = 1787] bin = [x = 100000100100001,y = 100100010101011,z = 1011110000111] ```
A Python solution using BDDs and bitvectors, with the package [`omega`](https://pypi.org/project/omega/): ```py """Solve a problem of bitwise arithmetic using binary decision diagrams.""" import pprint from omega.symbolic import temporal as trl def solve(values): """Encode and solve the problem.""" aut = trl.Automaton() bit_width = 16 max_value = 2**bit_width - 1 dom = (0, max_value) # range of integer values 0..max_value aut.declare_constants(x=dom, y=dom, z=dom) # declares in the BDD manager bits x_0, x_1, ..., x_15, etc. # the declarations can be read with: # `print(aut.vars)` # prepare values bitvalues = [int_to_bitvalues(v, 16) for v in values] bitvalues = [reversed(b) for b in bitvalues] # Below we encode each bitwise operator and shifts by directly mentioning # the bits that encode the declared integer-valued variables. # # form first conjunct conjunct_1 = r' /\ '.join( rf'((x_{i} \/ y_{i}) <=> {to_boolean(b)})' for (i, b) in enumerate(bitvalues[0])) # form second conjunct c = list() for i, b in enumerate(bitvalues[1]): # right shift by 2 if i < 14: e = f'y_{i + 2}' else: e = 'FALSE' s = f'((~ ({e} <=> x_{i})) <=> {to_boolean(b)})' # The TLA+ operator /= means "not equal to", # and for 0, 1 has the same effect as using ^ in `omega` c.append(s) conjunct_2 = '/\\'.join(c) # form third conjunct c = list() for i, b in enumerate(bitvalues[2]): # right shift by 1 if i < 15: e = f'z_{i + 1}' else: e = 'FALSE' s = rf'(({e} /\ y_{i}) <=> {to_boolean(b)})' c.append(s) conjunct_3 = r' /\ '.join(c) # form fourth conjunct c = list() for i, b in enumerate(bitvalues[3]): # left shift by 2 if i > 1: e = f'x_{i - 2}' else: e = 'FALSE' s = rf'(({e} \/ z_{i}) <=> {to_boolean(b)})' c.append(s) conjunct_4 = '/\\'.join(c) # conjoin formulas to form problem description formula = r' /\ '.join( f'({u})' for u in [conjunct_1, conjunct_2, conjunct_3, conjunct_4]) print(formula) # create a BDD `u` that represents the formula u = aut.add_expr(formula) care_vars = {'x', 'y', 'z'} # count and enumerate the satisfying assignments of `u` (solutions) n_solutions = aut.count(u, care_vars=care_vars) solutions = list(aut.pick_iter(u, care_vars=care_vars)) print(f'{n_solutions} solutions:') pprint.pprint(solutions) def to_boolean(x): "Return BOOLEAN constant that corresponds to `x`.""" if x == '0': return 'FALSE' elif x == '1': return 'TRUE' else: raise ValueError(x) def int_to_bitvalues(x, bitwidth): """Return bitstring of `bitwidth` that corresponds to `x`. @type x: `int` @type bitwidth: `int` Reference ========= This computation is from the module `omega.logic.bitvector`, specifically: https://github.com/tulip-control/omega/blob/ 0627e6d0cd15b7c42a8c53d0bb3cfa58df9c30f1/omega/logic/bitvector.py#L1159 """ assert bitwidth > 0, bitwidth return bin(x).lstrip('-0b').zfill(bitwidth) if __name__ == '__main__': values = [0x49ab, 0x530b, 0x0883, 0x1787] solve(values) ``` The output gives the solutions: ``` 4 solutions: [{'x': 16673, 'y': 18603, 'z': 4871}, {'x': 16673, 'y': 18603, 'z': 4999}, {'x': 16673, 'y': 18603, 'z': 5895}, {'x': 16673, 'y': 18603, 'z': 6023}] ``` which agree with the other answers posted here. The package `omega` can be installed from [PyPI](https://pypi.org/project/omega/) using [`pip`](https://pip.pypa.io/en/stable/) as follows: ```sh pip install omega ``` The output also includes the [TLA+](https://lamport.azurewebsites.net/tla/tla.html) formula that encodes the problem: ``` (((x_0 \/ y_0) <=> TRUE) /\ ((x_1 \/ y_1) <=> TRUE) /\ ((x_2 \/ y_2) <=> FALSE) /\ ((x_3 \/ y_3) <=> TRUE) /\ ((x_4 \/ y_4) <=> FALSE) /\ ((x_5 \/ y_5) <=> TRUE) /\ ((x_6 \/ y_6) <=> FALSE) /\ ((x_7 \/ y_7) <=> TRUE) /\ ((x_8 \/ y_8) <=> TRUE) /\ ((x_9 \/ y_9) <=> FALSE) /\ ((x_10 \/ y_10) <=> FALSE) /\ ((x_11 \/ y_11) <=> TRUE) /\ ((x_12 \/ y_12) <=> FALSE) /\ ((x_13 \/ y_13) <=> FALSE) /\ ((x_14 \/ y_14) <=> TRUE) /\ ((x_15 \/ y_15) <=> FALSE)) /\ (((~ (y_2 <=> x_0)) <=> TRUE)/\((~ (y_3 <=> x_1)) <=> TRUE)/\((~ (y_4 <=> x_2)) <=> FALSE)/\((~ (y_5 <=> x_3)) <=> TRUE)/\((~ (y_6 <=> x_4)) <=> FALSE)/\((~ (y_7 <=> x_5)) <=> FALSE)/\((~ (y_8 <=> x_6)) <=> FALSE)/\((~ (y_9 <=> x_7)) <=> FALSE)/\((~ (y_10 <=> x_8)) <=> TRUE)/\((~ (y_11 <=> x_9)) <=> TRUE)/\((~ (y_12 <=> x_10)) <=> FALSE)/\((~ (y_13 <=> x_11)) <=> FALSE)/\((~ (y_14 <=> x_12)) <=> TRUE)/\((~ (y_15 <=> x_13)) <=> FALSE)/\((~ (FALSE <=> x_14)) <=> TRUE)/\((~ (FALSE <=> x_15)) <=> FALSE)) /\ (((z_1 /\ y_0) <=> TRUE) /\ ((z_2 /\ y_1) <=> TRUE) /\ ((z_3 /\ y_2) <=> FALSE) /\ ((z_4 /\ y_3) <=> FALSE) /\ ((z_5 /\ y_4) <=> FALSE) /\ ((z_6 /\ y_5) <=> FALSE) /\ ((z_7 /\ y_6) <=> FALSE) /\ ((z_8 /\ y_7) <=> TRUE) /\ ((z_9 /\ y_8) <=> FALSE) /\ ((z_10 /\ y_9) <=> FALSE) /\ ((z_11 /\ y_10) <=> FALSE) /\ ((z_12 /\ y_11) <=> TRUE) /\ ((z_13 /\ y_12) <=> FALSE) /\ ((z_14 /\ y_13) <=> FALSE) /\ ((z_15 /\ y_14) <=> FALSE) /\ ((FALSE /\ y_15) <=> FALSE)) /\ (((FALSE \/ z_0) <=> TRUE)/\((FALSE \/ z_1) <=> TRUE)/\((x_0 \/ z_2) <=> TRUE)/\((x_1 \/ z_3) <=> FALSE)/\((x_2 \/ z_4) <=> FALSE)/\((x_3 \/ z_5) <=> FALSE)/\((x_4 \/ z_6) <=> FALSE)/\((x_5 \/ z_7) <=> TRUE)/\((x_6 \/ z_8) <=> TRUE)/\((x_7 \/ z_9) <=> TRUE)/\((x_8 \/ z_10) <=> TRUE)/\((x_9 \/ z_11) <=> FALSE)/\((x_10 \/ z_12) <=> TRUE)/\((x_11 \/ z_13) <=> FALSE)/\((x_12 \/ z_14) <=> FALSE)/\((x_13 \/ z_15) <=> FALSE)) ```
66,079,303
I have a `docker-compose.yml` file of a project server.It contains a `mongo` container, `nginx` service and a panel. I have to containerize my service and the panel for both test and main environements.Firstly I publish on test, afterwards I publish on main. After the publishing on main `nginx` forward requests to test and that is the issue. Restarting the `nginx` fixes the problem, so how can I fix the issue permanantly without restarting `nginx` after each publish on the main environement. `docker-compose.yml` : ```yaml version: '3.7' services: main-mongo: image: mongo:4.2.3 container_name: main-mongo volumes: - mongodb:/data/db - mongoconfig:/data/configdb main_service: image: project container_name: main_service restart: on-failure volumes: - ./views:/project/views - ./public:/project/public depends_on: - main-mongo test_service: image: test_project container_name: test_service restart: on-failure volumes: - ./test_view/views:/project/views - ./test_view/public:/project/public environment: - ENV=test depends_on: - main-mongo test_panel: image: test_panel container_name: test_panel restart: on-failure environment: - ENV=test depends_on: - main-mongo main_panel: image: panel container_name: main_panel restart: on-failure depends_on: - main-mongo python_backend_test: image: python_backend_test container_name: python_backend_test restart: on-failure volumes: - /tmp:/tmp nginx: image: nginx:1.17 container_name: nginx restart: on-failure ports: - 80:80 volumes: - ./nginx:/etc/nginx/conf.d/ - ./panel_front:/usr/share/panel depends_on: - main_panel - test_panel - test_service - main_service volumes: mongodb: mongoconfig: ``` `nginx.conf`: ``` server { listen 80; listen [::]:80; server_name domain.com; location /api { proxy_pass http://main_panel:3000; } location /account { root /usr/share/panel/live; try_files $uri $uri/ /index.html; } location / { proxy_pass http://main_service:3000; } } server { listen 80; listen [::]:80; server_name test.domain.com; location /netflix { proxy_pass http://python_backend_test:5000; } location /api { proxy_pass http://test_panel:3000; } location /account { alias /usr/share/panel/test/; try_files $uri $uri/ /index.html; } location / { proxy_pass http://test_service:3000; } } ```
2021/02/06
[ "https://Stackoverflow.com/questions/66079303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12535379/" ]
However, for doing these kind of bit calculation, z3 (<https://github.com/Z3Prover/z3> ) is probably the way to go, both in terms of modelling and features: it handle arbitrary long sizes, etc. Here's a z3 model using the Python interface (also here: <http://hakank.org/z3/bit_patterns.py> ): ``` from z3 import * solver = Solver() x = BitVec('x', 16) y = BitVec('y', 16) z = BitVec('z', 16) solver.add(y | x == 0x49ab) solver.add((y >> 2) ^ x == 0x530b) solver.add((z >> 1) & y == 0x0883) solver.add((x << 2) | z == 0x1787) num_solutions = 0 print("check:", solver.check()) while solver.check() == sat: num_solutions += 1 m = solver.model() xval = m.eval(x) yval = m.eval(y) zval = m.eval(z) print([xval,yval,zval]) solver.add(Or([x!=xval,y!=yval,z!=zval])) print("num_solutions:", num_solutions) ``` Output: ``` [16673, 18603, 4871] [16673, 18603, 4999] [16673, 18603, 6023] [16673, 18603, 5895] num_solutions: 4 ```
A Python solution using BDDs and bitvectors, with the package [`omega`](https://pypi.org/project/omega/): ```py """Solve a problem of bitwise arithmetic using binary decision diagrams.""" import pprint from omega.symbolic import temporal as trl def solve(values): """Encode and solve the problem.""" aut = trl.Automaton() bit_width = 16 max_value = 2**bit_width - 1 dom = (0, max_value) # range of integer values 0..max_value aut.declare_constants(x=dom, y=dom, z=dom) # declares in the BDD manager bits x_0, x_1, ..., x_15, etc. # the declarations can be read with: # `print(aut.vars)` # prepare values bitvalues = [int_to_bitvalues(v, 16) for v in values] bitvalues = [reversed(b) for b in bitvalues] # Below we encode each bitwise operator and shifts by directly mentioning # the bits that encode the declared integer-valued variables. # # form first conjunct conjunct_1 = r' /\ '.join( rf'((x_{i} \/ y_{i}) <=> {to_boolean(b)})' for (i, b) in enumerate(bitvalues[0])) # form second conjunct c = list() for i, b in enumerate(bitvalues[1]): # right shift by 2 if i < 14: e = f'y_{i + 2}' else: e = 'FALSE' s = f'((~ ({e} <=> x_{i})) <=> {to_boolean(b)})' # The TLA+ operator /= means "not equal to", # and for 0, 1 has the same effect as using ^ in `omega` c.append(s) conjunct_2 = '/\\'.join(c) # form third conjunct c = list() for i, b in enumerate(bitvalues[2]): # right shift by 1 if i < 15: e = f'z_{i + 1}' else: e = 'FALSE' s = rf'(({e} /\ y_{i}) <=> {to_boolean(b)})' c.append(s) conjunct_3 = r' /\ '.join(c) # form fourth conjunct c = list() for i, b in enumerate(bitvalues[3]): # left shift by 2 if i > 1: e = f'x_{i - 2}' else: e = 'FALSE' s = rf'(({e} \/ z_{i}) <=> {to_boolean(b)})' c.append(s) conjunct_4 = '/\\'.join(c) # conjoin formulas to form problem description formula = r' /\ '.join( f'({u})' for u in [conjunct_1, conjunct_2, conjunct_3, conjunct_4]) print(formula) # create a BDD `u` that represents the formula u = aut.add_expr(formula) care_vars = {'x', 'y', 'z'} # count and enumerate the satisfying assignments of `u` (solutions) n_solutions = aut.count(u, care_vars=care_vars) solutions = list(aut.pick_iter(u, care_vars=care_vars)) print(f'{n_solutions} solutions:') pprint.pprint(solutions) def to_boolean(x): "Return BOOLEAN constant that corresponds to `x`.""" if x == '0': return 'FALSE' elif x == '1': return 'TRUE' else: raise ValueError(x) def int_to_bitvalues(x, bitwidth): """Return bitstring of `bitwidth` that corresponds to `x`. @type x: `int` @type bitwidth: `int` Reference ========= This computation is from the module `omega.logic.bitvector`, specifically: https://github.com/tulip-control/omega/blob/ 0627e6d0cd15b7c42a8c53d0bb3cfa58df9c30f1/omega/logic/bitvector.py#L1159 """ assert bitwidth > 0, bitwidth return bin(x).lstrip('-0b').zfill(bitwidth) if __name__ == '__main__': values = [0x49ab, 0x530b, 0x0883, 0x1787] solve(values) ``` The output gives the solutions: ``` 4 solutions: [{'x': 16673, 'y': 18603, 'z': 4871}, {'x': 16673, 'y': 18603, 'z': 4999}, {'x': 16673, 'y': 18603, 'z': 5895}, {'x': 16673, 'y': 18603, 'z': 6023}] ``` which agree with the other answers posted here. The package `omega` can be installed from [PyPI](https://pypi.org/project/omega/) using [`pip`](https://pip.pypa.io/en/stable/) as follows: ```sh pip install omega ``` The output also includes the [TLA+](https://lamport.azurewebsites.net/tla/tla.html) formula that encodes the problem: ``` (((x_0 \/ y_0) <=> TRUE) /\ ((x_1 \/ y_1) <=> TRUE) /\ ((x_2 \/ y_2) <=> FALSE) /\ ((x_3 \/ y_3) <=> TRUE) /\ ((x_4 \/ y_4) <=> FALSE) /\ ((x_5 \/ y_5) <=> TRUE) /\ ((x_6 \/ y_6) <=> FALSE) /\ ((x_7 \/ y_7) <=> TRUE) /\ ((x_8 \/ y_8) <=> TRUE) /\ ((x_9 \/ y_9) <=> FALSE) /\ ((x_10 \/ y_10) <=> FALSE) /\ ((x_11 \/ y_11) <=> TRUE) /\ ((x_12 \/ y_12) <=> FALSE) /\ ((x_13 \/ y_13) <=> FALSE) /\ ((x_14 \/ y_14) <=> TRUE) /\ ((x_15 \/ y_15) <=> FALSE)) /\ (((~ (y_2 <=> x_0)) <=> TRUE)/\((~ (y_3 <=> x_1)) <=> TRUE)/\((~ (y_4 <=> x_2)) <=> FALSE)/\((~ (y_5 <=> x_3)) <=> TRUE)/\((~ (y_6 <=> x_4)) <=> FALSE)/\((~ (y_7 <=> x_5)) <=> FALSE)/\((~ (y_8 <=> x_6)) <=> FALSE)/\((~ (y_9 <=> x_7)) <=> FALSE)/\((~ (y_10 <=> x_8)) <=> TRUE)/\((~ (y_11 <=> x_9)) <=> TRUE)/\((~ (y_12 <=> x_10)) <=> FALSE)/\((~ (y_13 <=> x_11)) <=> FALSE)/\((~ (y_14 <=> x_12)) <=> TRUE)/\((~ (y_15 <=> x_13)) <=> FALSE)/\((~ (FALSE <=> x_14)) <=> TRUE)/\((~ (FALSE <=> x_15)) <=> FALSE)) /\ (((z_1 /\ y_0) <=> TRUE) /\ ((z_2 /\ y_1) <=> TRUE) /\ ((z_3 /\ y_2) <=> FALSE) /\ ((z_4 /\ y_3) <=> FALSE) /\ ((z_5 /\ y_4) <=> FALSE) /\ ((z_6 /\ y_5) <=> FALSE) /\ ((z_7 /\ y_6) <=> FALSE) /\ ((z_8 /\ y_7) <=> TRUE) /\ ((z_9 /\ y_8) <=> FALSE) /\ ((z_10 /\ y_9) <=> FALSE) /\ ((z_11 /\ y_10) <=> FALSE) /\ ((z_12 /\ y_11) <=> TRUE) /\ ((z_13 /\ y_12) <=> FALSE) /\ ((z_14 /\ y_13) <=> FALSE) /\ ((z_15 /\ y_14) <=> FALSE) /\ ((FALSE /\ y_15) <=> FALSE)) /\ (((FALSE \/ z_0) <=> TRUE)/\((FALSE \/ z_1) <=> TRUE)/\((x_0 \/ z_2) <=> TRUE)/\((x_1 \/ z_3) <=> FALSE)/\((x_2 \/ z_4) <=> FALSE)/\((x_3 \/ z_5) <=> FALSE)/\((x_4 \/ z_6) <=> FALSE)/\((x_5 \/ z_7) <=> TRUE)/\((x_6 \/ z_8) <=> TRUE)/\((x_7 \/ z_9) <=> TRUE)/\((x_8 \/ z_10) <=> TRUE)/\((x_9 \/ z_11) <=> FALSE)/\((x_10 \/ z_12) <=> TRUE)/\((x_11 \/ z_13) <=> FALSE)/\((x_12 \/ z_14) <=> FALSE)/\((x_13 \/ z_15) <=> FALSE)) ```
41,129,921
I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise. I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1) [questions](https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python/30696682#30696682) that provide different ways of *parsing* datetime strings, but I want to return `True` in the case of ISO-8601 format only. Parsing doesn't help me unless I can get it to throw an error for formats that don't match ISO-8601. (I am using the nice [arrow](https://github.com/crsmithdev/arrow) library elsewhere in my code. A solution that uses `arrow` would be welcome.) --- **EDIT:** It appears that a general solution to "is this string a valid ISO 8601 datetime" does not exist among the common Python datetime packages. So, to make this question narrower, more concrete and answerable, I will settle for a format string that will validate a datetime string in this form: ``` '2016-12-13T21:20:37.593194+00:00' ``` Currently I am using: ``` format_string = '%Y-%m-%dT%H:%M:%S.%f%z' datetime.datetime.strptime(my_timestamp, format_string) ``` This gives: ``` ValueError: time data '2016-12-13T21:20:37.593194+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' ``` The problem seems to lie with the colon in the UTC offset (`+00:00`). If I use an offset without a colon (e.g. `'2016-12-13T21:20:37.593194+0000'`), this parses properly as expected. This is apparently because `datetime`'s `%z` token [does not respect the UTC offset form that has a colon](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior), only the form without, even though [both are valid per the spec](https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC).
2016/12/13
[ "https://Stackoverflow.com/questions/41129921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332936/" ]
Here is a crude but functional solution (for the narrower question) using `datetime.strptime()`: ``` import datetime def is_expected_datetime_format(timestamp): format_string = '%Y-%m-%dT%H:%M:%S.%f%z' try: colon = timestamp[-3] if not colon == ':': raise ValueError() colonless_timestamp = timestamp[:-3] + timestamp[-2:] datetime.datetime.strptime(colonless_timestamp, format_string) return True except ValueError: return False ```
Given the constraints you've put on the problem, you could easily solve it with a regular expression. ``` >>> import re >>> re.match(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}[+-]\d\d:\d\d$', '2016-12-13T21:20:37.593194+00:00') <_sre.SRE_Match object; span=(0, 32), match='2016-12-13T21:20:37.593194+00:00'> ``` If you need to pass *all* variations of ISO 8601 it will be a much more complicated regular expression, but it could still be done. If you also need to validate the numeric ranges, for example verifying that the hour is between 0 and 23, you can put parentheses into the regular expression to create match groups then validate each group.
41,129,921
I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise. I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1) [questions](https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python/30696682#30696682) that provide different ways of *parsing* datetime strings, but I want to return `True` in the case of ISO-8601 format only. Parsing doesn't help me unless I can get it to throw an error for formats that don't match ISO-8601. (I am using the nice [arrow](https://github.com/crsmithdev/arrow) library elsewhere in my code. A solution that uses `arrow` would be welcome.) --- **EDIT:** It appears that a general solution to "is this string a valid ISO 8601 datetime" does not exist among the common Python datetime packages. So, to make this question narrower, more concrete and answerable, I will settle for a format string that will validate a datetime string in this form: ``` '2016-12-13T21:20:37.593194+00:00' ``` Currently I am using: ``` format_string = '%Y-%m-%dT%H:%M:%S.%f%z' datetime.datetime.strptime(my_timestamp, format_string) ``` This gives: ``` ValueError: time data '2016-12-13T21:20:37.593194+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' ``` The problem seems to lie with the colon in the UTC offset (`+00:00`). If I use an offset without a colon (e.g. `'2016-12-13T21:20:37.593194+0000'`), this parses properly as expected. This is apparently because `datetime`'s `%z` token [does not respect the UTC offset form that has a colon](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior), only the form without, even though [both are valid per the spec](https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC).
2016/12/13
[ "https://Stackoverflow.com/questions/41129921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332936/" ]
<https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html> give many variants for validating date and times in ISO8601 format (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z). The regex for the XML Schema dateTime type is given as: ``` >>> regex = r'^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$' ``` So in order to validate you could do: ``` import re match_iso8601 = re.compile(regex).match def validate_iso8601(str_val): try: if match_iso8601( str_val ) is not None: return True except: pass return False ``` Some examples: ``` >>> validate_iso8601('2017-01-01') False >>> validate_iso8601('2008-08-30T01:45:36.123Z') True >>> validate_iso8601('2016-12-13T21:20:37.593194+00:00') True ```
Given the constraints you've put on the problem, you could easily solve it with a regular expression. ``` >>> import re >>> re.match(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}[+-]\d\d:\d\d$', '2016-12-13T21:20:37.593194+00:00') <_sre.SRE_Match object; span=(0, 32), match='2016-12-13T21:20:37.593194+00:00'> ``` If you need to pass *all* variations of ISO 8601 it will be a much more complicated regular expression, but it could still be done. If you also need to validate the numeric ranges, for example verifying that the hour is between 0 and 23, you can put parentheses into the regular expression to create match groups then validate each group.
41,129,921
I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise. I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1) [questions](https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python/30696682#30696682) that provide different ways of *parsing* datetime strings, but I want to return `True` in the case of ISO-8601 format only. Parsing doesn't help me unless I can get it to throw an error for formats that don't match ISO-8601. (I am using the nice [arrow](https://github.com/crsmithdev/arrow) library elsewhere in my code. A solution that uses `arrow` would be welcome.) --- **EDIT:** It appears that a general solution to "is this string a valid ISO 8601 datetime" does not exist among the common Python datetime packages. So, to make this question narrower, more concrete and answerable, I will settle for a format string that will validate a datetime string in this form: ``` '2016-12-13T21:20:37.593194+00:00' ``` Currently I am using: ``` format_string = '%Y-%m-%dT%H:%M:%S.%f%z' datetime.datetime.strptime(my_timestamp, format_string) ``` This gives: ``` ValueError: time data '2016-12-13T21:20:37.593194+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' ``` The problem seems to lie with the colon in the UTC offset (`+00:00`). If I use an offset without a colon (e.g. `'2016-12-13T21:20:37.593194+0000'`), this parses properly as expected. This is apparently because `datetime`'s `%z` token [does not respect the UTC offset form that has a colon](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior), only the form without, even though [both are valid per the spec](https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC).
2016/12/13
[ "https://Stackoverflow.com/questions/41129921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332936/" ]
Recent versions of Python (from 3.7 onwards) have a `fromisoformat()` function in the `datetime` standard library. See: <https://docs.python.org/3.7/library/datetime.html> So this will do the trick: ``` from datetime import datetime def datetime_valid(dt_str): try: datetime.fromisoformat(dt_str) except: return False return True ``` **Update:** I learned that Python does not recognize the 'Z'-suffix as valid. As I wanted to support this in my API, I'm now using (after incorporating Matt's feedback): ``` from datetime import datetime def datetime_valid(dt_str): try: datetime.fromisoformat(dt_str.replace('Z', '+00:00')) except: return False return True ```
Given the constraints you've put on the problem, you could easily solve it with a regular expression. ``` >>> import re >>> re.match(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}[+-]\d\d:\d\d$', '2016-12-13T21:20:37.593194+00:00') <_sre.SRE_Match object; span=(0, 32), match='2016-12-13T21:20:37.593194+00:00'> ``` If you need to pass *all* variations of ISO 8601 it will be a much more complicated regular expression, but it could still be done. If you also need to validate the numeric ranges, for example verifying that the hour is between 0 and 23, you can put parentheses into the regular expression to create match groups then validate each group.
41,129,921
I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise. I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1) [questions](https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python/30696682#30696682) that provide different ways of *parsing* datetime strings, but I want to return `True` in the case of ISO-8601 format only. Parsing doesn't help me unless I can get it to throw an error for formats that don't match ISO-8601. (I am using the nice [arrow](https://github.com/crsmithdev/arrow) library elsewhere in my code. A solution that uses `arrow` would be welcome.) --- **EDIT:** It appears that a general solution to "is this string a valid ISO 8601 datetime" does not exist among the common Python datetime packages. So, to make this question narrower, more concrete and answerable, I will settle for a format string that will validate a datetime string in this form: ``` '2016-12-13T21:20:37.593194+00:00' ``` Currently I am using: ``` format_string = '%Y-%m-%dT%H:%M:%S.%f%z' datetime.datetime.strptime(my_timestamp, format_string) ``` This gives: ``` ValueError: time data '2016-12-13T21:20:37.593194+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' ``` The problem seems to lie with the colon in the UTC offset (`+00:00`). If I use an offset without a colon (e.g. `'2016-12-13T21:20:37.593194+0000'`), this parses properly as expected. This is apparently because `datetime`'s `%z` token [does not respect the UTC offset form that has a colon](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior), only the form without, even though [both are valid per the spec](https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC).
2016/12/13
[ "https://Stackoverflow.com/questions/41129921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332936/" ]
<https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html> give many variants for validating date and times in ISO8601 format (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z). The regex for the XML Schema dateTime type is given as: ``` >>> regex = r'^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$' ``` So in order to validate you could do: ``` import re match_iso8601 = re.compile(regex).match def validate_iso8601(str_val): try: if match_iso8601( str_val ) is not None: return True except: pass return False ``` Some examples: ``` >>> validate_iso8601('2017-01-01') False >>> validate_iso8601('2008-08-30T01:45:36.123Z') True >>> validate_iso8601('2016-12-13T21:20:37.593194+00:00') True ```
Here is a crude but functional solution (for the narrower question) using `datetime.strptime()`: ``` import datetime def is_expected_datetime_format(timestamp): format_string = '%Y-%m-%dT%H:%M:%S.%f%z' try: colon = timestamp[-3] if not colon == ':': raise ValueError() colonless_timestamp = timestamp[:-3] + timestamp[-2:] datetime.datetime.strptime(colonless_timestamp, format_string) return True except ValueError: return False ```
41,129,921
I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise. I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1) [questions](https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python/30696682#30696682) that provide different ways of *parsing* datetime strings, but I want to return `True` in the case of ISO-8601 format only. Parsing doesn't help me unless I can get it to throw an error for formats that don't match ISO-8601. (I am using the nice [arrow](https://github.com/crsmithdev/arrow) library elsewhere in my code. A solution that uses `arrow` would be welcome.) --- **EDIT:** It appears that a general solution to "is this string a valid ISO 8601 datetime" does not exist among the common Python datetime packages. So, to make this question narrower, more concrete and answerable, I will settle for a format string that will validate a datetime string in this form: ``` '2016-12-13T21:20:37.593194+00:00' ``` Currently I am using: ``` format_string = '%Y-%m-%dT%H:%M:%S.%f%z' datetime.datetime.strptime(my_timestamp, format_string) ``` This gives: ``` ValueError: time data '2016-12-13T21:20:37.593194+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' ``` The problem seems to lie with the colon in the UTC offset (`+00:00`). If I use an offset without a colon (e.g. `'2016-12-13T21:20:37.593194+0000'`), this parses properly as expected. This is apparently because `datetime`'s `%z` token [does not respect the UTC offset form that has a colon](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior), only the form without, even though [both are valid per the spec](https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC).
2016/12/13
[ "https://Stackoverflow.com/questions/41129921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332936/" ]
Here is a crude but functional solution (for the narrower question) using `datetime.strptime()`: ``` import datetime def is_expected_datetime_format(timestamp): format_string = '%Y-%m-%dT%H:%M:%S.%f%z' try: colon = timestamp[-3] if not colon == ':': raise ValueError() colonless_timestamp = timestamp[:-3] + timestamp[-2:] datetime.datetime.strptime(colonless_timestamp, format_string) return True except ValueError: return False ```
``` In [1] import dateutil.parser as dp In [2]: import re ...: def validate_iso8601_us(str_val): ...: try: ...: dp.parse(str_val) ...: if re.search('\.\d\d\d\d\d\d',str_val): ...: return True ...: except: ...: pass ...: return False ...: In [3]: validate_iso8601_us('2019/08/15T16:03:5.12345') Out[3]: False In [4]: validate_iso8601_us('2019/08/15T16:03:5.123456') Out[4]: True In [5]: validate_iso8601_us('2019/08/15T16:03:5.123456+4') Out[5]: True In [6]: validate_iso8601_us('woof2019/08/15T16:03:5.123456+4') Out[6]: False ```
41,129,921
I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise. I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1) [questions](https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python/30696682#30696682) that provide different ways of *parsing* datetime strings, but I want to return `True` in the case of ISO-8601 format only. Parsing doesn't help me unless I can get it to throw an error for formats that don't match ISO-8601. (I am using the nice [arrow](https://github.com/crsmithdev/arrow) library elsewhere in my code. A solution that uses `arrow` would be welcome.) --- **EDIT:** It appears that a general solution to "is this string a valid ISO 8601 datetime" does not exist among the common Python datetime packages. So, to make this question narrower, more concrete and answerable, I will settle for a format string that will validate a datetime string in this form: ``` '2016-12-13T21:20:37.593194+00:00' ``` Currently I am using: ``` format_string = '%Y-%m-%dT%H:%M:%S.%f%z' datetime.datetime.strptime(my_timestamp, format_string) ``` This gives: ``` ValueError: time data '2016-12-13T21:20:37.593194+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' ``` The problem seems to lie with the colon in the UTC offset (`+00:00`). If I use an offset without a colon (e.g. `'2016-12-13T21:20:37.593194+0000'`), this parses properly as expected. This is apparently because `datetime`'s `%z` token [does not respect the UTC offset form that has a colon](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior), only the form without, even though [both are valid per the spec](https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC).
2016/12/13
[ "https://Stackoverflow.com/questions/41129921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332936/" ]
Recent versions of Python (from 3.7 onwards) have a `fromisoformat()` function in the `datetime` standard library. See: <https://docs.python.org/3.7/library/datetime.html> So this will do the trick: ``` from datetime import datetime def datetime_valid(dt_str): try: datetime.fromisoformat(dt_str) except: return False return True ``` **Update:** I learned that Python does not recognize the 'Z'-suffix as valid. As I wanted to support this in my API, I'm now using (after incorporating Matt's feedback): ``` from datetime import datetime def datetime_valid(dt_str): try: datetime.fromisoformat(dt_str.replace('Z', '+00:00')) except: return False return True ```
Here is a crude but functional solution (for the narrower question) using `datetime.strptime()`: ``` import datetime def is_expected_datetime_format(timestamp): format_string = '%Y-%m-%dT%H:%M:%S.%f%z' try: colon = timestamp[-3] if not colon == ':': raise ValueError() colonless_timestamp = timestamp[:-3] + timestamp[-2:] datetime.datetime.strptime(colonless_timestamp, format_string) return True except ValueError: return False ```
41,129,921
I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise. I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1) [questions](https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python/30696682#30696682) that provide different ways of *parsing* datetime strings, but I want to return `True` in the case of ISO-8601 format only. Parsing doesn't help me unless I can get it to throw an error for formats that don't match ISO-8601. (I am using the nice [arrow](https://github.com/crsmithdev/arrow) library elsewhere in my code. A solution that uses `arrow` would be welcome.) --- **EDIT:** It appears that a general solution to "is this string a valid ISO 8601 datetime" does not exist among the common Python datetime packages. So, to make this question narrower, more concrete and answerable, I will settle for a format string that will validate a datetime string in this form: ``` '2016-12-13T21:20:37.593194+00:00' ``` Currently I am using: ``` format_string = '%Y-%m-%dT%H:%M:%S.%f%z' datetime.datetime.strptime(my_timestamp, format_string) ``` This gives: ``` ValueError: time data '2016-12-13T21:20:37.593194+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' ``` The problem seems to lie with the colon in the UTC offset (`+00:00`). If I use an offset without a colon (e.g. `'2016-12-13T21:20:37.593194+0000'`), this parses properly as expected. This is apparently because `datetime`'s `%z` token [does not respect the UTC offset form that has a colon](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior), only the form without, even though [both are valid per the spec](https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC).
2016/12/13
[ "https://Stackoverflow.com/questions/41129921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332936/" ]
<https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s07.html> give many variants for validating date and times in ISO8601 format (e.g., 2008-08-30T01:45:36 or 2008-08-30T01:45:36.123Z). The regex for the XML Schema dateTime type is given as: ``` >>> regex = r'^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.[0-9]+)?(Z|[+-](?:2[0-3]|[01][0-9]):[0-5][0-9])?$' ``` So in order to validate you could do: ``` import re match_iso8601 = re.compile(regex).match def validate_iso8601(str_val): try: if match_iso8601( str_val ) is not None: return True except: pass return False ``` Some examples: ``` >>> validate_iso8601('2017-01-01') False >>> validate_iso8601('2008-08-30T01:45:36.123Z') True >>> validate_iso8601('2016-12-13T21:20:37.593194+00:00') True ```
``` In [1] import dateutil.parser as dp In [2]: import re ...: def validate_iso8601_us(str_val): ...: try: ...: dp.parse(str_val) ...: if re.search('\.\d\d\d\d\d\d',str_val): ...: return True ...: except: ...: pass ...: return False ...: In [3]: validate_iso8601_us('2019/08/15T16:03:5.12345') Out[3]: False In [4]: validate_iso8601_us('2019/08/15T16:03:5.123456') Out[4]: True In [5]: validate_iso8601_us('2019/08/15T16:03:5.123456+4') Out[5]: True In [6]: validate_iso8601_us('woof2019/08/15T16:03:5.123456+4') Out[6]: False ```
41,129,921
I want to write a function that takes a string and returns `True` if it is a valid ISO-8601 datetime--precise to microseconds, including a timezone offset--`False` otherwise. I have found [other](https://stackoverflow.com/questions/969285/how-do-i-translate-a-iso-8601-datetime-string-into-a-python-datetime-object?rq=1) [questions](https://stackoverflow.com/questions/127803/how-to-parse-an-iso-8601-formatted-date-in-python/30696682#30696682) that provide different ways of *parsing* datetime strings, but I want to return `True` in the case of ISO-8601 format only. Parsing doesn't help me unless I can get it to throw an error for formats that don't match ISO-8601. (I am using the nice [arrow](https://github.com/crsmithdev/arrow) library elsewhere in my code. A solution that uses `arrow` would be welcome.) --- **EDIT:** It appears that a general solution to "is this string a valid ISO 8601 datetime" does not exist among the common Python datetime packages. So, to make this question narrower, more concrete and answerable, I will settle for a format string that will validate a datetime string in this form: ``` '2016-12-13T21:20:37.593194+00:00' ``` Currently I am using: ``` format_string = '%Y-%m-%dT%H:%M:%S.%f%z' datetime.datetime.strptime(my_timestamp, format_string) ``` This gives: ``` ValueError: time data '2016-12-13T21:20:37.593194+00:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z' ``` The problem seems to lie with the colon in the UTC offset (`+00:00`). If I use an offset without a colon (e.g. `'2016-12-13T21:20:37.593194+0000'`), this parses properly as expected. This is apparently because `datetime`'s `%z` token [does not respect the UTC offset form that has a colon](https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior), only the form without, even though [both are valid per the spec](https://en.wikipedia.org/wiki/ISO_8601#Time_offsets_from_UTC).
2016/12/13
[ "https://Stackoverflow.com/questions/41129921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/332936/" ]
Recent versions of Python (from 3.7 onwards) have a `fromisoformat()` function in the `datetime` standard library. See: <https://docs.python.org/3.7/library/datetime.html> So this will do the trick: ``` from datetime import datetime def datetime_valid(dt_str): try: datetime.fromisoformat(dt_str) except: return False return True ``` **Update:** I learned that Python does not recognize the 'Z'-suffix as valid. As I wanted to support this in my API, I'm now using (after incorporating Matt's feedback): ``` from datetime import datetime def datetime_valid(dt_str): try: datetime.fromisoformat(dt_str.replace('Z', '+00:00')) except: return False return True ```
``` In [1] import dateutil.parser as dp In [2]: import re ...: def validate_iso8601_us(str_val): ...: try: ...: dp.parse(str_val) ...: if re.search('\.\d\d\d\d\d\d',str_val): ...: return True ...: except: ...: pass ...: return False ...: In [3]: validate_iso8601_us('2019/08/15T16:03:5.12345') Out[3]: False In [4]: validate_iso8601_us('2019/08/15T16:03:5.123456') Out[4]: True In [5]: validate_iso8601_us('2019/08/15T16:03:5.123456+4') Out[5]: True In [6]: validate_iso8601_us('woof2019/08/15T16:03:5.123456+4') Out[6]: False ```
19,593,456
Can the "standard" subprocess pipeline technique (e.g. <http://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline>) be "upgraded" to two pipelines? ``` # How about p1 = Popen(["cmd1"], stdout=PIPE, stderr=PIPE) p2 = Popen(["cmd2"], stdin=p1.stdout) p3 = Popen(["cmd3"], stdin=p1.stderr) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. p1.stderr.close() #p2.communicate() # or p3.communicate()? ``` OK, it's actually a different use case, but the closest starting point seems to be the pipeline example. By the way, how does p2.communicate() in a "normal" pipeline drive p1? Here's the normal pipeline for reference: ``` # From Python docs output=`dmesg | grep hda` # becomes p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. output = p2.communicate()[0] ``` I guess I'm ultimately interested in what kind of "process graphs" (or maybe just trees?) can `communicate()` support, but we'll leave the general case for another day. **Update**: Here's the baseline functionality. Without communicate(), create 2 threads reading from p1.stdout and p2.stdout. In the main process, inject input via p1.stdin.write(). The question is whether we can drive a 1-source, 2-sink graph using just communicate()
2013/10/25
[ "https://Stackoverflow.com/questions/19593456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/690620/" ]
You could use bash's [process substitution](http://en.wikipedia.org/wiki/Process_substitution): ``` from subprocess import check_call check_call("cmd1 > >(cmd2) 2> >(cmd3)", shell=True, executable="/bin/bash") ``` It redirects `cmd1`'s stdout to `cmd2` and `cmd1`'s stderr to `cmd3`. If you don't want to use `bash` then the code in your question should work as is e.g.: ``` #!/usr/bin/env python import sys from subprocess import Popen, PIPE from textwrap import dedent # generate some output on stdout/stderr source = Popen([sys.executable, "-c", dedent(""" from __future__ import print_function import sys from itertools import cycle from string import ascii_lowercase for i, c in enumerate(cycle(ascii_lowercase)): print(c) print(i, file=sys.stderr) """)], stdout=PIPE, stderr=PIPE) # convert input to upper case sink = Popen([sys.executable, "-c", dedent(""" import sys for line in sys.stdin: sys.stdout.write(line.upper()) """)], stdin=source.stdout) source.stdout.close() # allow source to receive SIGPIPE if sink exits # square input sink_stderr = Popen([sys.executable, "-c", dedent(""" import sys for line in sys.stdin: print(int(line)**2) """)], stdin=source.stderr) source.stderr.close() # allow source to receive SIGPIPE if sink_stderr exits sink.communicate() sink_stderr.communicate() source.wait() ```
The solution here is to create a couple of background threads which read the output from one process and then write that into the inputs of several processes: ``` targets = [...] # list of processes as returned by Popen() while True: line = p1.readline() if line is None: break for p in targets: p.stdin.write(line) ```
56,293,981
I'm writing a python script which has to internally create output path from the input path. However, I am facing issues to create the path which I can use irrespective of OS. I have tried to use os.path.join and it has its own limitations. Apart from that, I think simple string concatenation is not the way to go. Pathlib can be an option but I am not allowed to use it. ```py import os inputpath = "C:\projects\django\hereisinput" lastSlash = left.rfind("\\") # This won't work as os path join stops at a slash outputDir = os.path.join(left[:lastSlash], "\internal\morelevel\outputpath") OR OutDir = left[:lastSlash] + "\internal\morelevel\outputpath" ``` Expected output path : C:\projects\django\internal\morelevel\outputpath Also, the above code doesn't do it OS Specific where in Linux, the slash will be different. Is os.sep() some option ?
2019/05/24
[ "https://Stackoverflow.com/questions/56293981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5729921/" ]
From the documentation `os.path.join` can join "**one or more** path components...". So you could split `"\internal\morelevel\outputpath"` up into each of its components and pass all of them to your `os.path.join` function instead. That way you don't need to "hard-code" the separator between the path components. For example: ``` paths = ("internal", "morelevel", "outputpath") outputDir = os.path.join(left[:lastSlash], *paths) ``` Remember that the backslash (`\`) is a special character in Python so your strings containing singular backslashes wouldn't work as you expect them to! You need to escape them with another `\` in front. This part of your code `lastSlash = left.rfind("\\")` might also not work on any operating system. You could rather use something like [`os.path.split`](https://docs.python.org/3/library/os.path.html#os.path.split) to get the last part of the path that you need. For example, `_, lastSlash = os.path.split(left)`.
Assuming your original path is "C:\projects\django\hereisinput", your other part of the path as "internal\morelevel\outputpath" (notice this is a relative path, not absolute), you could always move your primary back one folder (or more) and then append the second part. Do note that your first path needs to contain only folders and can be absolute or relative, while your second path must always be relative for this hack to work ``` path_1 = r"C:\projects\django\hereisinput" path_2 = r"internal\morelevel\outputpath" path_1_one_folder_down = os.path.join(path_1, os.path.pardir) final_path = os.path.join(path_1_one_folder_down, path_2) 'C:\\projects\\django\\hereisinput\\..\\internal\\morelevel\\outputpath' ```
41,247,105
I am trying to run this script in parallel, for i<=4 in each set. The `runspr.py` is itself parallel, and thats fine. What I am trying to do is running only 4 i loop in any instance. In my present code, it will run everything. ``` #!bin/bash for i in * do if [[ -d $i ]]; then echo "$i id dir" cd $i python3 ~/bin/runspr.py SCF & cd .. else echo "$i nont dir" fi done ``` I have followed <https://www.biostars.org/p/63816/> and <https://unix.stackexchange.com/questions/35416/four-tasks-in-parallel-how-do-i-do-that> but unable to impliment the code in parallel.
2016/12/20
[ "https://Stackoverflow.com/questions/41247105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2005559/" ]
You don't need to use `for` loop. You can use [`gnu parallel`](https://www.gnu.org/software/parallel/parallel_tutorial.html) like this with `find`: ``` find . -mindepth 1 -maxdepth 1 -type d ! -print0 | parallel -0 --jobs 4 'cd {}; python3 ~/bin/runspr.py SCF' ```
Another possible solution is: ``` find . -mindepth 1 -maxdepth 1 -type d ! -print0 | xargs -I {} -P 4 sh -c 'cd {}; python3 ~/bin/runspr.py SCF' ```
58,478,181
I'm looking at breaking the enigma cipher with python, and need to generate plugboard combinations - what I need is a function which takes a `length` parameter and returns a generator object of all possible combinations as a list. Example code: ```py for comb in func(2): print(comb) ``` ```py # Example output ['AB', 'CD'] ['CD', 'EF'] ... ``` Does anyone know of a library that provides such a generator, or how to go about making one? EDIT: more detail about enigma Please see [here](https://en.wikipedia.org/wiki/Enigma_machine#Plugboard) for detail about the design of the plugboard Also, the output format of the generator must be concatanable to this format *without* running the whole generator: `'AB FO ZP GI HY KS JW MQ XE ...'` the number of pairs would be the `length` parameter in the function.
2019/10/20
[ "https://Stackoverflow.com/questions/58478181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I think what you're looking for is [itertools.combinations](https://docs.python.org/3/library/itertools.html#itertools.combinations) ``` >>> from itertools import combinations >>> list(combinations('abcd', 2)) [('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')] >>> [''.join(comb) for comb in combinations('abcd', 2)] ['ab', 'ac', 'ad', 'bc', 'bd', 'cd'] ```
Is this something close to what you're after? Let me know and I can revise. The `plugboard()` function returns (`yield`) a `generator` object which can be accessed either by an iterable loop, or by calling the `next()` function. ``` from itertools import product def plugboard(chars, length): for comb in product(chars, repeat=length): yield ''.join(comb) ``` ### A call such as this will create `combs` as a `generator` object: ``` combs = plugboard('abcde', 2) type(combs) >>> generator ``` ### To access the values you can use either: ``` next(combs) >>> 'aa' ``` ### Or: ``` for i in combs: print(i) ab ac ad ae ba bb bc ... ```
63,810,966
I try to remove outliers in a python list. But it removes only the first one (190000) and not the second (20000). What is the problem ? ``` import statistics dataset = [25000, 30000, 52000, 28000, 150000, 190000, 200000] def detect_outlier(data_1): threshold = 1 mean_1 = statistics.mean(data_1) std_1 = statistics.stdev(data_1) #print(std_1) for y in data_1: z_score = (y - mean_1)/std_1 print(z_score) if abs(z_score) > threshold: dataset.remove(y) return dataset dataset = detect_outlier(dataset) print(dataset) ``` Output: ``` [25000, 30000, 52000, 28000, 150000, 200000] ```
2020/09/09
[ "https://Stackoverflow.com/questions/63810966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9669017/" ]
It is because you are trying to make operations on the same data address. dataset's address is equals to the data\_1 address and when you are removing an element from the list, it pass the next element according to the foreach structure of Python. You must not make operations on a list during iteration. Shortly, try to call the method like this(this sends dataset's elements as a new list, doesn't send the dataset): ``` dataset = detect_outlier(dataset[:]) ```
``` import statistics def detect_outlier(data_1): threshold = 1 mean_1 = statistics.mean(data_1) std_1 = statistics.stdev(data_1) result_dataset = [y for y in data_1 if abs((y - mean_1)/std_1)<=threshold ] return result_dataset if __name__=="__main__": dataset = [25000, 30000, 52000, 28000, 150000, 190000, 200000] result_dataset = detect_outlier(dataset) print(result_dataset) ```
61,660,067
This is the code i used: ``` df = None from pyspark.sql.functions import lit for category in file_list_filtered: data_files = os.listdir('HMP_Dataset/'+category) for data_file in data_files: print(data_file) temp_df = spark.read.option('header', 'false').option('delimiter', ' ').csv('HMP_Dataset/'+category+'/'+data_file, schema = schema) temp_df = temp_df.withColumn('class', lit(category)) temp_df = temp_df.withColumn('source', lit(data_file)) if df is None: df = temp_df else: df = df.union(temp_df) ``` and i got this error: ``` NameError Traceback (most recent call last) <ipython-input-4-4296b4e97942> in <module> 9 for data_file in data_files: 10 print(data_file) ---> 11 temp_df = spark.read.option('header', 'false').option('delimiter', ' ').csv('HMP_Dataset/'+category+'/'+data_file, schema = schema) 12 temp_df = temp_df.withColumn('class', lit(category)) 13 temp_df = temp_df.withColumn('source', lit(data_file)) NameError: name 'spark' is not defined ``` How can i solve it?
2020/05/07
[ "https://Stackoverflow.com/questions/61660067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13491209/" ]
You can try *regular expressions* in order to parse. First, let's extract a model: since commands are in format ``` Start (zero or more Modifiers) ``` E.g. ``` %today-5day+3hour% ``` where `today` is `Start` and `-5day` and `+3hour` are `Modifiers` we want two *models* ``` using System.Linq; using System.Text.RegularExpressions; ... //TODO: add more starting points here private static Dictionary<string, Func<DateTime>> s_Starts = new Dictionary<string, Func<DateTime>>(StringComparer.OrdinalIgnoreCase) { { "now", () => DateTime.Now}, { "today", () => DateTime.Today}, { "yearend", () => new DateTime(DateTime.Today.Year, 12, 31) }, }; //TODO: add more modifiers here private static Dictionary<string, Func<DateTime, int, DateTime>> s_Modifiers = new Dictionary<string, Func<DateTime, int, DateTime>>(StringComparer.OrdinalIgnoreCase) { { "month", (source, x) => source.AddMonths(x)}, { "week", (source, x) => source.AddDays(x * 7)}, { "day", (source, x) => source.AddDays(x)}, { "hour", (source, x) => source.AddHours(x)}, { "min", (source, x) => source.AddMinutes(x)}, { "sec", (source, x) => source.AddSeconds(x)}, }; ``` Having a model (two dictionaries above) we can implement `MyParse` routine: ``` private static DateTime MyParse(string value) { if (null == value) throw new ArgumentNullException(nameof(value)); var match = Regex.Match(value, @"^%(?<start>[a-zA-Z]+)(?<modify>\s*[+-]\s*[0-9]+\s*[a-zA-Z]+)*%$"); if (!match.Success) throw new FormatException("Invalid format"); string start = match.Groups["start"].Value; DateTime result = s_Starts.TryGetValue(start, out var startFunc) ? startFunc() : throw new FormatException($"Start Date(Time) {start} is unknown."); var adds = Regex .Matches(match.Groups["modify"].Value, @"([+\-])\s*([0-9]+)\s*([a-zA-Z]+)") .Cast<Match>() .Select(m => (kind : m.Groups[3].Value, amount : int.Parse(m.Groups[1].Value + m.Groups[2].Value))); foreach (var (kind, amount) in adds) if (s_Modifiers.TryGetValue(kind, out var func)) result = func(result, amount); else throw new FormatException($"Modification {kind} is unknown."); return result; } ``` **Demo:** ``` string[] tests = new string[] { "%today%", "%today-5day%", "%today-1sec%", "%today+1month%", "%now+15min%", "%now-30sec%", "%now+1week%", }; string report = string.Join(Environment.NewLine, tests .Select(test => $"{test,-15} :: {MyParse(test):dd MM yyyy HH:mm:ss}") ); Console.Write(report); ``` **Outcome:** ``` %today% :: 07 05 2020 00:00:00 %today-5day% :: 02 05 2020 00:00:00 %today-1sec% :: 06 05 2020 23:59:59 %today+1month% :: 07 06 2020 00:00:00 %now+15min% :: 07 05 2020 18:34:55 %now-30sec% :: 07 05 2020 18:19:25 %now+1week% :: 14 05 2020 18:19:55 ```
This is a small example of parsing a string that has today and day in it (using the example of %today-5day%). Note: this will only work if the value passed in for the added days is between 0-9, to handle large numbers you will have to loop over the result of the string. You can follow this code block to parse other results as well. ``` switch (date) { case var a when a.Contains("day") && a.Contains("today"): return DateTime.Today.AddDays(char.GetNumericValue(date[date.Length - 5])); default: return DateTime.Today; } ```
46,574,860
I am trying to get percentage frequencies in pyspark. I did this in python as follows ``` Companies = df['Company'].value_counts(normalize = True) ``` Getting the frequencies is fairly straightforward: ``` # Dates in descending order of complaint frequency df.createOrReplaceTempView('Comp') CompDF = spark.sql("SELECT Company, count(*) as cnt \ FROM Comp \ GROUP BY Company \ ORDER BY cnt DESC") CompDF.show() ``` ``` +--------------------+----+ | Company| cnt| +--------------------+----+ |BANK OF AMERICA, ...|1387| | EQUIFAX, INC.|1285| |WELLS FARGO & COM...|1119| |Experian Informat...|1115| |TRANSUNION INTERM...|1001| |JPMORGAN CHASE & CO.| 905| | CITIBANK, N.A.| 772| |OCWEN LOAN SERVIC...| 481| ``` How do I get to percent frequencies from here? I tried a bunch of things with not much luck. Any help would be appreciated.
2017/10/04
[ "https://Stackoverflow.com/questions/46574860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8722941/" ]
As Suresh implies in the comments, assuming that `total_count` is the number of rows in dataframe `Companies`, you can use `withColumn` to add a new column named `percentages` in `CompDF`: ``` total_count = Companies.count() df = CompDF.withColumn('percentage', CompDF.cnt/float(total_counts)) ```
May be modifying the SQL query will get you the result you want. ``` "SELECT Company,cnt/(SELECT SUM(cnt) from (SELECT Company, count(*) as cnt FROM Comp GROUP BY Company ORDER BY cnt DESC) temp_tab) sum_freq from (SELECT Company, count(*) as cnt FROM Comp GROUP BY Company ORDER BY cnt DESC)" ```
67,205,402
I have a file and its name is (Pro\_data.sh) which contains these commands: ``` python preprocess.py dex python preprocess.py lex python process.py ``` I do not know how can I run the file in the python terminal (pycharm as an example). I can run each command alone but I want to know the right way to run the .sh file for saving execution time.
2021/04/22
[ "https://Stackoverflow.com/questions/67205402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10585944/" ]
Is this what you're looking for? main.py ``` import os os.system('sh x.sh') ``` x.sh ``` python test2.py ``` test2.py ``` print('up') ``` output from main.py ``` up ```
.sh is a mac/Linux shell. for windows: create one with the name Pro\_data.bat and put those three commands in it, and run Prod\_data.bat **Prod\_data.bat** ``` python preprocess.py dex python preprocess.py lex python process.py ```
4,743,016
I search a python builder IDE for wxpython similar to boa constructor. any suggestions ?
2011/01/20
[ "https://Stackoverflow.com/questions/4743016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348081/" ]
Well, there is [wxGlade](http://wxglade.sourceforge.net/), [DialogBlocks](http://www.dialogblocks.com/) and [wxDesigner](http://www.wxdesigner-software.de/), with both DialogBlocks and wxDesigner being commercial tools. There also used to be a open-source editor called wxFormBuilder, but the site hosting it seems down right now.
Boa constructor is working here....works with windows 10 <https://bitbucket.org/cwt/boa-constructor/overview>
68,640,517
I am trying to run a simple python script within a docker run command scheduled with Airflow. I have followed the instructions here [Airflow init](https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html). My `.env` file: ``` AIRFLOW_UID=1000 AIRFLOW_GID=0 ``` And the `docker-compose.yaml` is based on the default one [docker-compose.yaml](https://airflow.apache.org/docs/apache-airflow/2.1.2/docker-compose.yaml). I had to add `- /var/run/docker.sock:/var/run/docker.sock` as an additional volume to run docker inside of docker. My dag is configured as followed: ```py """ this is an example dag """ from datetime import timedelta from airflow import DAG from airflow.operators.docker_operator import DockerOperator from airflow.utils.dates import days_ago from docker.types import Mount default_args = { 'owner': 'airflow', 'depends_on_past': False, 'email': ['info@foo.com'], 'email_on_failure': True, 'email_on_retry': False, 'retries': 10, 'retry_delay': timedelta(minutes=5), } with DAG( 'msg_europe_etl', default_args=default_args, description='Process MSG_EUROPE ETL', schedule_interval=timedelta(minutes=15), start_date=days_ago(0), tags=['satellite_data'], ) as dag: download_and_store = DockerOperator( task_id='download_and_store', image='satellite_image:latest', auto_remove=True, api_version='1.41', mounts=[Mount(source='/home/archive_1/archive/satellite_data', target='/app/data'), Mount(source='/home/dlassahn/projects/forecast-system/meteoIntelligence-satellite', target='/app')], command="python3 src/scripts.py download_satellite_images " "{{ (execution_date - macros.timedelta(hours=4)).strftime('%Y-%m-%d %H:%M') }} " "'msg_europe' ", ) download_and_store ``` The Airflow log: ```py [2021-08-03 17:23:58,691] {docker.py:231} INFO - Starting docker container from image satellite_image:latest [2021-08-03 17:23:58,702] {taskinstance.py:1501} ERROR - Task failed with exception Traceback (most recent call last): File "/home/airflow/.local/lib/python3.6/site-packages/docker/api/client.py", line 268, in _raise_for_status response.raise_for_status() File "/home/airflow/.local/lib/python3.6/site-packages/requests/models.py", line 943, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: http+docker://localhost/v1.41/containers/create During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/airflow/.local/lib/python3.6/site-packages/airflow/models/taskinstance.py", line 1157, in _run_raw_task self._prepare_and_execute_task_with_callbacks(context, task) File "/home/airflow/.local/lib/python3.6/site-packages/airflow/models/taskinstance.py", line 1331, in _prepare_and_execute_task_with_callbacks result = self._execute_task(context, task_copy) File "/home/airflow/.local/lib/python3.6/site-packages/airflow/models/taskinstance.py", line 1361, in _execute_task result = task_copy.execute(context=context) File "/home/airflow/.local/lib/python3.6/site-packages/airflow/providers/docker/operators/docker.py", line 319, in execute return self._run_image() File "/home/airflow/.local/lib/python3.6/site-packages/airflow/providers/docker/operators/docker.py", line 258, in _run_image tty=self.tty, File "/home/airflow/.local/lib/python3.6/site-packages/docker/api/container.py", line 430, in create_container return self.create_container_from_config(config, name) File "/home/airflow/.local/lib/python3.6/site-packages/docker/api/container.py", line 441, in create_container_from_config return self._result(res, True) File "/home/airflow/.local/lib/python3.6/site-packages/docker/api/client.py", line 274, in _result self._raise_for_status(response) File "/home/airflow/.local/lib/python3.6/site-packages/docker/api/client.py", line 270, in _raise_for_status raise create_api_error_from_http_exception(e) File "/home/airflow/.local/lib/python3.6/site-packages/docker/errors.py", line 31, in create_api_error_from_http_exception raise cls(e, response=response, explanation=explanation) docker.errors.APIError: 400 Client Error for http+docker://localhost/v1.41/containers/create: Bad Request ("invalid mount config for type "bind": bind source path does not exist: /tmp/airflowtmp037k87u6") ``` Trying to set `mount_tmp_dir=False` yield to an Dag ImportError because of unknown Keyword Argument `mount_tmp_dir`. (this might be an issue for the Documentation) Nevertheless I do not know how to configure the tmp directory correctly. My Airflow Version: 2.1.2
2021/08/03
[ "https://Stackoverflow.com/questions/68640517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4390189/" ]
There was a bug in Docker Provider 2.0.0 which prevented Docker Operator to run with Docker-In-Docker solution. You need to upgrade to the latest Docker Provider 2.1.0 <https://airflow.apache.org/docs/apache-airflow-providers-docker/stable/index.html#id1> You can do it by extending the image as described in <https://airflow.apache.org/docs/docker-stack/build.html#extending-the-image> with - for example - this docker file: ``` FROM apache/airflow RUN pip install --no-cache-dir apache-airflow-providers-docker==2.1.0 ``` The operator will work out-of-the-box in this case with "fallback" mode (and Warning message), but you can also disable the mount that causes the problem. More explanation from the <https://airflow.apache.org/docs/apache-airflow-providers-docker/stable/_api/airflow/providers/docker/operators/docker/index.html> > > By default, a temporary directory is created on the host and mounted > into a container to allow storing files that together exceed the > default disk size of 10GB in a container. In this case The path to the > mounted directory can be accessed via the environment variable > AIRFLOW\_TMP\_DIR. > > > If the volume cannot be mounted, warning is printed and an attempt is > made to execute the docker command without the temporary folder > mounted. This is to make it works by default with remote docker engine > or when you run docker-in-docker solution and temporary directory is > not shared with the docker engine. Warning is printed in logs in this > case. > > > If you know you run DockerOperator with remote engine or via > docker-in-docker you should set mount\_tmp\_dir parameter to False. In > this case, you can still use mounts parameter to mount already > existing named volumes in your Docker Engine to achieve similar > capability where you can store files exceeding default disk size of > the container, > > >
I had the same issue and all "recommended" ways of solving the issue here and setting up mount\_dir params as descripted [here](https://airflow.apache.org/docs/apache-airflow-providers-docker/stable/_api/airflow/providers/docker/operators/docker/index.html) just lead to other errors. The one solution that helped me was wrapping the invocated by docker code with the VPN (actually this hack was taken from another docker-powered DAG that used VPN and worked well). So the final solution looks like: ``` #!/bin/bash connect_to_vpn.sh & sleep 10 python3 my_func.py sleep 10 stop_vpn.sh wait -n exit $? ``` To connect to VPN I used openconnect. The took can be installed with apt install and supports anyconnect protocol (it was my crucial requirement).
5,532,902
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): n = n + 1 result = s[ start: n ] + " " + result start = n return result ``` But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much. Any help would be appreciated.
2011/04/03
[ "https://Stackoverflow.com/questions/5532902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615585/" ]
If this isn't just a homework question and you're actually trying to reverse a string for some greater goal, just do `s[::-1]`.
I know it's too late to answer original question and there are multiple better ways which are answered here already. My answer is for documentation purpose in case someone is trying to implement tail recursion for string reversal. ``` def tail_rev(in_string,rev_string): if in_string=='': return rev_string else: rev_string+=in_string[-1] return tail_rev(in_string[:-1],rev_string) in_string=input("Enter String: ") rev_string=tail_rev(in_string,'') print(f"Reverse of {in_string} is {rev_string}") ```
5,532,902
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): n = n + 1 result = s[ start: n ] + " " + result start = n return result ``` But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much. Any help would be appreciated.
2011/04/03
[ "https://Stackoverflow.com/questions/5532902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615585/" ]
``` def rreverse(s): if s == "": return s else: return rreverse(s[1:]) + s[0] ``` (Very few people do heavy recursive processing in Python, the language [wasn't designed for it](http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html).)
if you do not want to return response than you can use this solution. This question is part of LeetCode. ``` class Solution: i = 0 def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ if self.i >= (len(s)//2): return s[self.i], s[len(s)-self.i-1] = s[len(s)-self.i-1], s[self.i] self.i += 1 self.reverseString(s) ```
5,532,902
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): n = n + 1 result = s[ start: n ] + " " + result start = n return result ``` But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much. Any help would be appreciated.
2011/04/03
[ "https://Stackoverflow.com/questions/5532902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615585/" ]
If this isn't just a homework question and you're actually trying to reverse a string for some greater goal, just do `s[::-1]`.
``` s = input("Enter your string: ") def rev(s): if len(s) == 1: print(s[0]) exit() else: #print the last char in string #end="" prints all chars in string on same line print(s[-1], end="") """Next line replaces whole string with same string, but with 1 char less""" return rev(s.replace(s, s[:-1])) rev(s) ```
5,532,902
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): n = n + 1 result = s[ start: n ] + " " + result start = n return result ``` But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much. Any help would be appreciated.
2011/04/03
[ "https://Stackoverflow.com/questions/5532902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615585/" ]
To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself. What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right? So the reverse of a string is the last character, followed by the reverse of everything *but* the last character, which is where the recursion comes in. The last character of a string can be written as `x[-1]` while everything *but* the last character is `x[:-1]`. Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done. But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, *also* be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set. Put it all together and you get: ``` def backward(text): if text == "": return text else: return text[-1] + backward(text[:-1]) ``` Or in one line: ``` backward = lambda t: t[-1] + backward(t[:-1]) if t else t ``` As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still. Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.
``` s = input("Enter your string: ") def rev(s): if len(s) == 1: print(s[0]) exit() else: #print the last char in string #end="" prints all chars in string on same line print(s[-1], end="") """Next line replaces whole string with same string, but with 1 char less""" return rev(s.replace(s, s[:-1])) rev(s) ```
5,532,902
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): n = n + 1 result = s[ start: n ] + " " + result start = n return result ``` But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much. Any help would be appreciated.
2011/04/03
[ "https://Stackoverflow.com/questions/5532902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615585/" ]
``` def reverse_string(s): if s: return s[-1] + reverse_string(s[0:-1]) else: return s ``` or ``` def reverse_string(s): return s[-1] + reverse_string(s[0:-1]) if s else s ```
if you do not want to return response than you can use this solution. This question is part of LeetCode. ``` class Solution: i = 0 def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ if self.i >= (len(s)//2): return s[self.i], s[len(s)-self.i-1] = s[len(s)-self.i-1], s[self.i] self.i += 1 self.reverseString(s) ```
5,532,902
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): n = n + 1 result = s[ start: n ] + " " + result start = n return result ``` But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much. Any help would be appreciated.
2011/04/03
[ "https://Stackoverflow.com/questions/5532902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615585/" ]
``` def rreverse(s): if s == "": return s else: return rreverse(s[1:]) + s[0] ``` (Very few people do heavy recursive processing in Python, the language [wasn't designed for it](http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html).)
``` s = input("Enter your string: ") def rev(s): if len(s) == 1: print(s[0]) exit() else: #print the last char in string #end="" prints all chars in string on same line print(s[-1], end="") """Next line replaces whole string with same string, but with 1 char less""" return rev(s.replace(s, s[:-1])) rev(s) ```
5,532,902
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): n = n + 1 result = s[ start: n ] + " " + result start = n return result ``` But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much. Any help would be appreciated.
2011/04/03
[ "https://Stackoverflow.com/questions/5532902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615585/" ]
To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself. What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right? So the reverse of a string is the last character, followed by the reverse of everything *but* the last character, which is where the recursion comes in. The last character of a string can be written as `x[-1]` while everything *but* the last character is `x[:-1]`. Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done. But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, *also* be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set. Put it all together and you get: ``` def backward(text): if text == "": return text else: return text[-1] + backward(text[:-1]) ``` Or in one line: ``` backward = lambda t: t[-1] + backward(t[:-1]) if t else t ``` As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still. Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.
``` def reverse_string(s): if s: return s[-1] + reverse_string(s[0:-1]) else: return s ``` or ``` def reverse_string(s): return s[-1] + reverse_string(s[0:-1]) if s else s ```
5,532,902
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): n = n + 1 result = s[ start: n ] + " " + result start = n return result ``` But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much. Any help would be appreciated.
2011/04/03
[ "https://Stackoverflow.com/questions/5532902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615585/" ]
``` def rreverse(s): if s == "": return s else: return rreverse(s[1:]) + s[0] ``` (Very few people do heavy recursive processing in Python, the language [wasn't designed for it](http://neopythonic.blogspot.com/2009/04/tail-recursion-elimination.html).)
To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself. What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right? So the reverse of a string is the last character, followed by the reverse of everything *but* the last character, which is where the recursion comes in. The last character of a string can be written as `x[-1]` while everything *but* the last character is `x[:-1]`. Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done. But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, *also* be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set. Put it all together and you get: ``` def backward(text): if text == "": return text else: return text[-1] + backward(text[:-1]) ``` Or in one line: ``` backward = lambda t: t[-1] + backward(t[:-1]) if t else t ``` As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still. Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.
5,532,902
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): n = n + 1 result = s[ start: n ] + " " + result start = n return result ``` But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much. Any help would be appreciated.
2011/04/03
[ "https://Stackoverflow.com/questions/5532902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615585/" ]
To solve a problem recursively, find a trivial case that is easy to solve, and figure out how to get to that trivial case by breaking the problem down into simpler and simpler versions of itself. What is the first thing you do in reversing a string? Literally the first thing? You get the last character of the string, right? So the reverse of a string is the last character, followed by the reverse of everything *but* the last character, which is where the recursion comes in. The last character of a string can be written as `x[-1]` while everything *but* the last character is `x[:-1]`. Now, how do you "bottom out"? That is, what is the trivial case you can solve without recursion? One answer is the one-character string, which is the same forward and reversed. So if you get a one-character string, you are done. But the empty string is even more trivial, and someone might actually pass that in to your function, so we should probably use that instead. A one-character string can, after all, *also* be broken down into the last character and everything but the last character; it's just that everything but the last character is the empty string. So if we handle the empty string by just returning it, we're set. Put it all together and you get: ``` def backward(text): if text == "": return text else: return text[-1] + backward(text[:-1]) ``` Or in one line: ``` backward = lambda t: t[-1] + backward(t[:-1]) if t else t ``` As others have pointed out, this is not the way you would usually do this in Python. An iterative solution is going to be faster, and using slicing to do it is going to be faster still. Additionally, Python imposes a limit on stack size, and there's no tail call optimization, so a recursive solution would be limited to reversing strings of only about a thousand characters. You can increase Python's stack size, but there would still be a fixed limit, while other solutions can always handle a string of any length.
I just want to add some explanations based on [Fred Foo's answer](https://stackoverflow.com/a/5532914). Let's say we have a string called 'abc', and we want to return its reverse which should be 'cba'. ``` def reverse(s): if s == "": return s else: return reverse(s[1:]) + s[0] s = "abc" print (reverse(s)) ``` How this code works is that: when we call the function ``` reverse('abc') #s = abc =reverse('bc') + 'a' #s[1:] = bc s[0] = a =reverse('c') + 'b' + 'a' #s[1:] = c s[0] = a =reverse('') + 'c' + 'b' + 'a' ='cba' ```
5,532,902
I want to use recursion to reverse a string in python so it displays the characters backwards (i.e "Hello" will become "olleh"/"o l l e h". I wrote one that does it iteratively: ``` def Reverse( s ): result = "" n = 0 start = 0 while ( s[n:] != "" ): while ( s[n:] != "" and s[n] != ' ' ): n = n + 1 result = s[ start: n ] + " " + result start = n return result ``` But how exactly do I do this recursively? I am confused on this part, especially because I don't work with python and recursion much. Any help would be appreciated.
2011/04/03
[ "https://Stackoverflow.com/questions/5532902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615585/" ]
``` def reverse_string(s): if s: return s[-1] + reverse_string(s[0:-1]) else: return s ``` or ``` def reverse_string(s): return s[-1] + reverse_string(s[0:-1]) if s else s ```
``` s = input("Enter your string: ") def rev(s): if len(s) == 1: print(s[0]) exit() else: #print the last char in string #end="" prints all chars in string on same line print(s[-1], end="") """Next line replaces whole string with same string, but with 1 char less""" return rev(s.replace(s, s[:-1])) rev(s) ```
69,422,541
I am using the python code below to attempt to create a graph that fills the entire figure. The problem is I need the graph portion to stretch to fill the entire figure, there should not be any of the green showing and the graphed data should start at one side and go all the way to the other. I have found similar examples online but nothing that exactly solves my problem and I a matplotlib noob. Any help is greatly appreciated. ``` import numpy as np import matplotlib.pyplot as plt data = np.fromfile("rawdata.bin", dtype='<u2') fig, ax = plt.subplots() fig.patch.set_facecolor('xkcd:mint green') ax.axes.xaxis.set_ticks([]) ax.axes.yaxis.set_ticks([]) ax.plot(data) fig.tight_layout() plt.show() ``` [![bad graph](https://i.stack.imgur.com/dWy7D.png)](https://i.stack.imgur.com/dWy7D.png)
2021/10/03
[ "https://Stackoverflow.com/questions/69422541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2231017/" ]
Just use `IsNullOrWhiteSpace`; it does what `IsNullOrEmpty` does: > > Return `true` if the value parameter is null or Empty, or if value consists exclusively of white-space characters. > *-- documentation for IsNullOrWhiteSpace* > > > And it is mapped by EF Core to an SQL of ``` @value IS NULL OR LTRIM(RTRIM(@value)) = N'' ``` Note that in EF Core 6 this changed to `@value IS NULL OR value= N''` - same deal; SQLS ignores trailing whitespace in string comp This means your `IsSomething` method is effectively `!IsNullOrWhiteSpace`, which EF will translate if you use it..
You cannot translate this method to SQL Server. However, you can use a method that returns Expression. For example: ``` public static Expression<Func<Student, bool>> IsSomething() { return (s) => string.IsNullOrEmpty(s.FirstName) || string.IsNullOrWhiteSpace(s.FirstName); } ``` Usually, you should call AsEnumerable before using methods: ``` dbset.AsEnumerable().Where(i => i.Title.IsSomething()); ``` But it will load all entities from data base.
15,034,105
Let say I have the a list of list ``` [ ['B','2'] , ['o','0'], ['y']] ``` and I want to combine the list into something like this without using iteratool ``` ["Boy","B0y","2oy","20y"] ``` I can't use itertool because I have to use python 2.5.
2013/02/22
[ "https://Stackoverflow.com/questions/15034105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1968057/" ]
[`itertools.product()`](http://docs.python.org/2/library/itertools.html#itertools.product) does what you want. ``` >>> [''.join(x) for x in itertools.product(*[['B', '2'], ['o', '0'], ['y']])] ['Boy', 'B0y', '2oy', '20y'] ```
If you don't want to use itertools, this list comprehension produces your output: ``` >>> LoL=[['B','2'], ['o','0'], ['y']] >>> [a+b+c for a in LoL[0] for b in LoL[1] for c in LoL[2]] ['Boy', 'B0y', '2oy', '20y'] ``` This is a more compact version of this: ``` LoL=[['B','2'], ['o','0'], ['y']] r=[] for a in LoL[0]: for b in LoL[1]: for c in LoL[2]: r.append(a+b+c) print r ``` In either case, you are producing a [cartesian product](http://en.wikipedia.org/wiki/Cartesian_product) which is better and more flexibly done with [itertools.product()](http://docs.python.org/2/library/itertools.html#itertools.product) (unless you are just curious about how to do it...)
51,115,744
How to set path for python 3.7.0? I tried the every possible way but it still shows the error! > > Could not install packages due to an EnvironmentError: [WinError 5] > > > Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt' > > > Consider using the `--user` option or check the permissions > > >
2018/06/30
[ "https://Stackoverflow.com/questions/51115744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014902/" ]
You can add --user in the end of your command. This works well in my case! ``` --user ``` My example: ``` python -m pip install --upgrade pip --user ```
Just try on Administrator cmd ``` pip install --user numpy ```
51,115,744
How to set path for python 3.7.0? I tried the every possible way but it still shows the error! > > Could not install packages due to an EnvironmentError: [WinError 5] > > > Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt' > > > Consider using the `--user` option or check the permissions > > >
2018/06/30
[ "https://Stackoverflow.com/questions/51115744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014902/" ]
Add `--user` to the command. eg: ``` pip install -r requirements.txt --user ```
The question was for windows but if any linux users that stumbled here (like me) : Permission Error Persists by adding `--user` in my virtualenv on Ubuntu 19 when I want to generate **requirements.txt**. Also, I can't `pip install --user` as well since I'm in an virtualenv. My solution was just using `sudo pip3 install pipreqs` to install another pipreqs for super user.
51,115,744
How to set path for python 3.7.0? I tried the every possible way but it still shows the error! > > Could not install packages due to an EnvironmentError: [WinError 5] > > > Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt' > > > Consider using the `--user` option or check the permissions > > >
2018/06/30
[ "https://Stackoverflow.com/questions/51115744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014902/" ]
Run your command Prompt on Admin-Mode in Windows,it will stop throwing errors for user-rights. Steps: 1. On Windows, type "Cmd" on searchbox to search for command prompt. 2. When "Command Prompt" search result appears,right-click>Run as Administrator.
Run your command prompt on admin mode. type : `cd\` then type: `cd [Your python location path]` on mycomputer it's: `cd C:\Users\hp\AppData\Local\Programs\Python\Python37-32` then type: ``` python -m pip install --upgrade pip ``` You can follow this guide~ <https://datatofish.com/upgrade-pip/>
51,115,744
How to set path for python 3.7.0? I tried the every possible way but it still shows the error! > > Could not install packages due to an EnvironmentError: [WinError 5] > > > Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt' > > > Consider using the `--user` option or check the permissions > > >
2018/06/30
[ "https://Stackoverflow.com/questions/51115744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014902/" ]
Run your command Prompt on Admin-Mode in Windows,it will stop throwing errors for user-rights. Steps: 1. On Windows, type "Cmd" on searchbox to search for command prompt. 2. When "Command Prompt" search result appears,right-click>Run as Administrator.
You can add --user in the end of your command. This works well in my case! ``` --user ``` My example: ``` python -m pip install --upgrade pip --user ```
51,115,744
How to set path for python 3.7.0? I tried the every possible way but it still shows the error! > > Could not install packages due to an EnvironmentError: [WinError 5] > > > Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt' > > > Consider using the `--user` option or check the permissions > > >
2018/06/30
[ "https://Stackoverflow.com/questions/51115744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014902/" ]
Add `--user` to the command. eg: ``` pip install -r requirements.txt --user ```
You can add --user in the end of your command. This works well in my case! ``` --user ``` My example: ``` python -m pip install --upgrade pip --user ```
51,115,744
How to set path for python 3.7.0? I tried the every possible way but it still shows the error! > > Could not install packages due to an EnvironmentError: [WinError 5] > > > Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt' > > > Consider using the `--user` option or check the permissions > > >
2018/06/30
[ "https://Stackoverflow.com/questions/51115744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014902/" ]
Run your command prompt on admin mode. type : `cd\` then type: `cd [Your python location path]` on mycomputer it's: `cd C:\Users\hp\AppData\Local\Programs\Python\Python37-32` then type: ``` python -m pip install --upgrade pip ``` You can follow this guide~ <https://datatofish.com/upgrade-pip/>
I had the same problem. After installing Python for all the users, wanted to install Django. For that I've gone to the Command Prompt (without using Admin mode) and ``` pip.exe install django==2.2 ``` This prompted the following message > > Could not install packages due to an EnvironmentError: [WinError 5] > Access is denied: 'c:\program > files\python37\lib\site-packages\pip-19.0.3.dist-info\entry\_points.txt' > Consider using the `--user` option or check the permissions. > > > The way I've used to solve it was to add **--user** in the end of the command, just like the prompt message suggests («Consider using the `--user`»). ``` pip.exe install django==2.2 --user ``` Then everything worked fine.
51,115,744
How to set path for python 3.7.0? I tried the every possible way but it still shows the error! > > Could not install packages due to an EnvironmentError: [WinError 5] > > > Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt' > > > Consider using the `--user` option or check the permissions > > >
2018/06/30
[ "https://Stackoverflow.com/questions/51115744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014902/" ]
Append the `--user` modifier to your command as suggested in the error. > > `--user` makes pip install packages in your home directory instead, which doesn't require any special privileges. > > > More: [What is the purpose "pip install --user ..."?](https://stackoverflow.com/questions/42988977/what-is-the-purpose-pip-install-user)
You can add --user in the end of your command. This works well in my case! ``` --user ``` My example: ``` python -m pip install --upgrade pip --user ```
51,115,744
How to set path for python 3.7.0? I tried the every possible way but it still shows the error! > > Could not install packages due to an EnvironmentError: [WinError 5] > > > Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt' > > > Consider using the `--user` option or check the permissions > > >
2018/06/30
[ "https://Stackoverflow.com/questions/51115744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014902/" ]
Append the `--user` modifier to your command as suggested in the error. > > `--user` makes pip install packages in your home directory instead, which doesn't require any special privileges. > > > More: [What is the purpose "pip install --user ..."?](https://stackoverflow.com/questions/42988977/what-is-the-purpose-pip-install-user)
Just try on Administrator cmd ``` pip install --user numpy ```
51,115,744
How to set path for python 3.7.0? I tried the every possible way but it still shows the error! > > Could not install packages due to an EnvironmentError: [WinError 5] > > > Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt' > > > Consider using the `--user` option or check the permissions > > >
2018/06/30
[ "https://Stackoverflow.com/questions/51115744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014902/" ]
Add `--user` to the command. eg: ``` pip install -r requirements.txt --user ```
Run your command prompt on admin mode. type : `cd\` then type: `cd [Your python location path]` on mycomputer it's: `cd C:\Users\hp\AppData\Local\Programs\Python\Python37-32` then type: ``` python -m pip install --upgrade pip ``` You can follow this guide~ <https://datatofish.com/upgrade-pip/>
51,115,744
How to set path for python 3.7.0? I tried the every possible way but it still shows the error! > > Could not install packages due to an EnvironmentError: [WinError 5] > > > Access is denied: 'c:\program files (x86)\python37-32\lib\site-packages\pip-10.0.1.dist-info\entry\_points.txt' > > > Consider using the `--user` option or check the permissions > > >
2018/06/30
[ "https://Stackoverflow.com/questions/51115744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10014902/" ]
Add `--user` to the command. eg: ``` pip install -r requirements.txt --user ```
I wanted to throw an answer out here because I've been against a rock wall since upgrading to python 3.18. Pip install stopped working with a module error which was rectified with py -m pip install --user. *but* I would still get this permissions error. I uninstalled, reinstalled, and downgraded Python and Pip. I ran command prompt as administrator. None of it worked. The only thing that worked was to pip download and then pip install the package from my c:/ drive. Totally BS workaround, but if you'r as stuck as I was it works.
10,396,640
My current plan is to determine which is the first entry in a number of [Tkinter](http://wiki.python.org/moin/TkInter) listboxes highlighted using `.curselection()` and combining all of the resulting tuples into a list, producing this: ``` tupleList = [(), (), ('24', '25', '26', '27'), (), (), (), ()] ``` I'm wondering as to how to determine the lowest integer. Using `.min(tupleList)` returns only `()`, being the lowest entry in the list, but I'm looking for a method that would return 24. What's the right way to get the lowest integer in any tuple in the list?
2012/05/01
[ "https://Stackoverflow.com/questions/10396640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367581/" ]
``` >>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()] >>> min(int(j) for i in nums for j in i) 24 ```
``` >>> from itertools import chain >>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()] >>> min(map(int,chain.from_iterable(nums))) 24 ```
10,396,640
My current plan is to determine which is the first entry in a number of [Tkinter](http://wiki.python.org/moin/TkInter) listboxes highlighted using `.curselection()` and combining all of the resulting tuples into a list, producing this: ``` tupleList = [(), (), ('24', '25', '26', '27'), (), (), (), ()] ``` I'm wondering as to how to determine the lowest integer. Using `.min(tupleList)` returns only `()`, being the lowest entry in the list, but I'm looking for a method that would return 24. What's the right way to get the lowest integer in any tuple in the list?
2012/05/01
[ "https://Stackoverflow.com/questions/10396640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367581/" ]
``` >>> from itertools import chain >>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()] >>> min(map(int,chain.from_iterable(nums))) 24 ```
``` >>> min(reduce(lambda x, y: x + y, nums)) ```
10,396,640
My current plan is to determine which is the first entry in a number of [Tkinter](http://wiki.python.org/moin/TkInter) listboxes highlighted using `.curselection()` and combining all of the resulting tuples into a list, producing this: ``` tupleList = [(), (), ('24', '25', '26', '27'), (), (), (), ()] ``` I'm wondering as to how to determine the lowest integer. Using `.min(tupleList)` returns only `()`, being the lowest entry in the list, but I'm looking for a method that would return 24. What's the right way to get the lowest integer in any tuple in the list?
2012/05/01
[ "https://Stackoverflow.com/questions/10396640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367581/" ]
``` >>> nums = [(), (), ('24', '25', '26', '27'), (), (), (), ()] >>> min(int(j) for i in nums for j in i) 24 ```
``` >>> min(reduce(lambda x, y: x + y, nums)) ```
61,629,693
I have a 3D numpy array with integer values, something defined as: ``` import numpy as np x = np.random.randint(0, 100, (10, 10, 10)) ``` Now what I want to do is find the last slice (or alternatively the first slice) along a given axes (say 1) where a particular value occurs. At the moment, I do something like: ``` first=None last=None val = 20 for i in range(len(x.shape[1]): slice = x[:, i, :] if len(slice[slice==val]) > 0: if not first: first = i last = i return first, last ``` This seems a bit unpythonic and I wonder if there is some `numpy` magic to do this?
2020/05/06
[ "https://Stackoverflow.com/questions/61629693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2713740/" ]
You probably can optimize this to be faster, but here is a vectorized version of what you search: ``` axis = 1 mask = np.where(x==val)[axis] first, last = np.amin(mask), np.amax(mask) ``` It first finds the element `val` in your array using `np.where` and returns the `min` and `max` of indices along desired axis.
Per your question, you want to check if there's any such valid slice and hence, get the start/first, stop/last indices. In absence of any such valid slice, we must return None's there. That needs extra check. Also, we can use `masking` to get those indices in an efficient manner, like so - ``` def slice_info(x, val): n = (x==val).any((0,2)) if n.any(): return n.argmax(), len(n)-n[::-1].argmax()-1 else: return None,None ``` ### Benchmarking Other proposed solution(s) : ``` # https://stackoverflow.com/a/61629916/ @Ehsan def where_amin_amax(x, val): axis = 1 mask = np.where(x==val)[axis] first, last = np.amin(mask), np.amax(mask) return first, last ``` Timings - ``` # Same setup as in given sample In [157]: np.random.seed(0) ...: x = np.random.randint(0, 100, (10, 10, 10)) In [158]: %timeit where_amin_amax(x, val=20) ...: %timeit slice_info(x, val=20) 15.1 µs ± 287 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) 9.63 µs ± 43.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) # Bigger In [159]: np.random.seed(0) ...: x = np.random.randint(0, 100, (100, 100, 100)) In [160]: %timeit where_amin_amax(x, val=20) ...: %timeit slice_info(x, val=20) 3.34 ms ± 31.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 691 µs ± 3.69 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) ```
44,987,098
Is it possible to install [nodejs](/questions/tagged/nodejs "show questions tagged 'nodejs'") packages (/modules) from files like in [ruby](/questions/tagged/ruby "show questions tagged 'ruby'")'s Gemfile as done with `bundle install` or [python](/questions/tagged/python "show questions tagged 'python'")'s requirements file (eg: `requirements.pip`) as done using `pip install -r` commands ? Say I have a file where three or four package names are listed. How would I instruct `npm` to install packages whose names are found in that file (and resolve dependencies which it also does)?
2017/07/08
[ "https://Stackoverflow.com/questions/44987098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Just create your package JSON, you can use yarn to manage your packages instead of npm, it's faster. Inside your package you can create a section of scripts accessed by `npm run` `scripts: { customBuild: 'your sh code/ruby/script whateve' }` And after you can run on terminal, `npm run customBuild` for example
you can use NPM init to create a package.json file which will store the node packages your application is dependent on, then use npm install which will install the node packages indicated in the package.json file
55,317,792
My sonar branch coverage results are not importing into sonarqube. coverage.xml are generating in jenkins workspace. following are the below jenkins and error details : WARN: No report was found for sonar.python.coverage.reportPaths using pattern coverage-reports/coverage.xml I have tried in my ways but nothing worked. ``` withSonarQubeEnv('Sonarqube') { sh "${scannerHome}/bin/sonar-scanner -Dsonar.login=$USERNAME -Dsonar.password=$PASSWORD -Dsonar.projectKey=${params.PROJECT_KEY} -Dsonar.projectName=${params.PROJECT_NAME} -Dsonar.branch=${params.GIT_BRANCH} -Dsonar.projectVersion=${params.PROJECT_VERSION} -Dsonar.sources=. -Dsonar.language=${params.LANGUAGE} -Dsonar.python.pylint=${params.PYLINT_PATH} -Dsonar.python.pylint_config=${params.PYLINT} -Dsonar.python.pylint.reportPath=${params.PYLINT_REPORT} -Dsonar.sourceEncoding=${params.ENCODING} -Dsonar.python.xunit.reportPath=${params.NOSE} -Dsonar.python.coverage.reportPaths=${params.COVERAGE}" } ``` I expect my coverage results to reflect on sonar
2019/03/23
[ "https://Stackoverflow.com/questions/55317792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11248384/" ]
You are having that error because you are specifying the coverage report path option wrong, and therefore sonar is using the default location `coverage-reports/coverage.xml`. The correct option is `-Dsonar.python.coverage.reportPath` (in singular).
I still have this problem on Azure Pipelines. Tried many ways without success. WARN: No report was found for sonar.python.coverage.reportPaths using pattern coverage.xml
35,857,389
Encountered the following problem when trying to use the module scipy.optimize.slsqp. ``` >>> import scipy.optimize.slsqp Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.5/site-packages/scipy/optimize/__init__.py", line 233, in <module> from ._minimize import * File "/usr/local/lib/python3.5/site- packages/scipy/optimize/_minimize.py", line 26, in <module> from ._trustregion_dogleg import _minimize_dogleg File "/usr/local/lib/python3.5/site- packages/scipy/optimize/_trustregion_dogleg.py", line 5, in <module> import scipy.linalg File "/usr/local/lib/python3.5/site-packages/scipy/linalg/__init__.py", line 190, in <module> from ._decomp_update import * File "scipy/linalg/_decomp_update.pyx", line 1, in init scipy.linalg._decomp_update (scipy/linalg/_decomp_update.c:39096) ImportError: /usr/local/lib/python3.5/site- packages/scipy/linalg/cython_lapack.cpython-35m-x86_64-linux-gnu.so: undefined symbol: zlacn2 ``` I'm using Python3.5, Scipy 0.17.0, Numpy 1.10.1, the OS is CentOS 5.11. Could anyone shed some lights into this? Thank you.
2016/03/08
[ "https://Stackoverflow.com/questions/35857389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6020400/" ]
Depending on the scope you use it would be loaded in an application context, therefore one time (say in a singleton class loaded at the application startup). But I wouldn't recommend this approach, I would recommend a proper designed database where you can put your csv data into. This way you would have the database engine to help you organize your data which would give you scalability and maintainability (although with a proper design of your classes say a DAO pattern would give you the same). Organized data in a database would give you more flexibility to search through your data using already made SQL functions. In order to make my case here are some advantages of a Database system over a file system: * No redundant data – Redundancy removed by data normalization * Data Consistency and Integrity – data normalization takes care of it too * Secure – Each user has a different set of access * Privacy – Limited access * Easy access to data * Easy recovery * Flexible * Concurrency - The database engine will allow you to concurrent read the data or even write to it. I'm not listing the disadvantages since I'm making my case :)
I can read from a CSV file to build your arrays. You can then add the arrays to session scope. The CSV file will only be read at the servlet that processes it. Future usage will be retrieved from session.
51,529,408
I must be missing something but I look around and couldn't find reference to this issue. I have the very basic code, as seen in flask-mongoengine documentation. test.py: ``` from flask import Flask from flask_mongoengine import MongoEngine ``` When I run python test.py ... ``` from flask_mongoengine import MongoEngine ImportError: cannot import name 'MongoEngine' ``` Module in virtual environment contain (requirements.txt): ``` click==6.7 Flask==1.0.2 flask-mongoengine==0.9.5 Flask-WTF==0.14.2 itsdangerous==0.24 Jinja2==2.10 MarkupSafe==1.0 mongoengine==0.15.3 pymongo==3.7.1 six==1.11.0 Werkzeug==0.14.1 WTForms==2.2.1 ``` My interpreter is Python 3.6.5 Any help would be appreciated. Thanks.
2018/07/26
[ "https://Stackoverflow.com/questions/51529408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5112112/" ]
Since your using a virtual environment did you try opening your editor from your virtual environment? For example opening the vscode editor from command-line is "code". Go to your virtual environment via the terminal and activate then type "code" at your prompt. ``` terminal:~path/to/virtual-enviroment$ source bin/activate (virtual-enviroment)terminal:~path/to/virtual-enviroment$ code ``` If that doesn't work I, myself, haven't used flask-mongoengine. I was nervous of any issues that would come from the abstraction of it and instead just used Mongoengine with Flask. I'm assuming you're only using this library for connection management so if you can't solve your issue with flask-mongoengine but are still interested in using mongoengine this was my approach. ~ I would put this in a config file somewhere and import it where appropriate- ``` from flask import Flask MONGODB_DB = 'DB_NAME' MONGODB_HOST = '127.0.0.1' # or whatever your db address MONGODB_PORT = 27017 # or whatever your port app = Flask(__name__) # you can import app from config and it will keep its configurations ``` then I would connect and disconnect from the database within each HTTP request function like this- ``` from config import MONGO_DB, MONGODB_HOST, MONGODB_PORT # to connect db = connect(MONGODB_DB, host=MONGODB_HOST, port=MONGODB_PORT) # to close connection before any returns db.close() ``` Hope this helps.
I had this issue and managed to fix it by deactivating, reinstalling flask-mongoengine and reactivating the venv (all in the Terminal): ``` deactivate pip install flask-mongoengine # Not required but good to check it was properly installed pip freeze venv\Scripts\activate flask run ```
55,659,835
I am new to Python and I am trying to separate polygon data into x and y coordinates. I keep getting error: "AttributeError: ("'MultiPolygon' object has no attribute 'exterior'", 'occurred at index 1')" From what I understand Python object MultiPolygon does not contain data exterior. But how do I remedy this to make the function work? ``` def getPolyCoords(row, geom, coord_type): """Returns the coordinates ('x' or 'y') of edges of a Polygon exterior""" # Parse the exterior of the coordinate geometry = row[geom] if coord_type == 'x': # Get the x coordinates of the exterior return list( geometry.exterior.coords.xy[0] ) elif coord_type == 'y': # Get the y coordinates of the exterior return list( geometry.exterior.coords.xy[1] ) # Get the Polygon x and y coordinates grid['x'] = grid.apply(getPolyCoords, geom='geometry', coord_type='x', axis=1) grid['y'] = grid.apply(getPolyCoords, geom='geometry', coord_type='y', axis=1) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-8-73511dbae283> in <module> 1 # Get the Polygon x and y coordinates ----> 2 grid['x'] = grid.apply(getPolyCoords, geom='geometry', coord_type='x', axis=1) 3 grid['y'] = grid.apply(getPolyCoords, geom='geometry', coord_type='y', axis=1) ~\Anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, result_type, args, **kwds) 6012 args=args, 6013 kwds=kwds) -> 6014 return op.get_result() 6015 6016 def applymap(self, func): ~\Anaconda3\lib\site-packages\pandas\core\apply.py in get_result(self) 140 return self.apply_raw() 141 --> 142 return self.apply_standard() 143 144 def apply_empty_result(self): ~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_standard(self) 246 247 # compute the result using the series generator --> 248 self.apply_series_generator() 249 250 # wrap results ~\Anaconda3\lib\site-packages\pandas\core\apply.py in apply_series_generator(self) 275 try: 276 for i, v in enumerate(series_gen): --> 277 results[i] = self.f(v) 278 keys.append(v.name) 279 except Exception as e: ~\Anaconda3\lib\site-packages\pandas\core\apply.py in f(x) 72 if kwds or args and not isinstance(func, np.ufunc): 73 def f(x): ---> 74 return func(x, *args, **kwds) 75 else: 76 f = func <ipython-input-4-8c3864d38986> in getPolyCoords(row, geom, coord_type) 7 if coord_type == 'x': 8 # Get the x coordinates of the exterior ----> 9 return list( geometry.exterior.coords.xy[0] ) 10 elif coord_type == 'y': 11 # Get the y coordinates of the exterior AttributeError: ("'MultiPolygon' object has no attribute 'exterior'", 'occurred at index 1') ```
2019/04/12
[ "https://Stackoverflow.com/questions/55659835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11053854/" ]
I have updated your function `getPolyCoords()` to enable the handling of other geometry types, namely, `MultiPolygon`, `Point`, and `LineString`. Hope it works for your project. ``` def getPolyCoords(row, geom, coord_type): """Returns the coordinates ('x|y') of edges/vertices of a Polygon/others""" # Parse the geometries and grab the coordinate geometry = row[geom] #print(geometry.type) if geometry.type=='Polygon': if coord_type == 'x': # Get the x coordinates of the exterior # Interior is more complex: xxx.interiors[0].coords.xy[0] return list( geometry.exterior.coords.xy[0] ) elif coord_type == 'y': # Get the y coordinates of the exterior return list( geometry.exterior.coords.xy[1] ) if geometry.type in ['Point', 'LineString']: if coord_type == 'x': return list( geometry.xy[0] ) elif coord_type == 'y': return list( geometry.xy[1] ) if geometry.type=='MultiLineString': all_xy = [] for ea in geometry: if coord_type == 'x': all_xy.append(list( ea.xy[0] )) elif coord_type == 'y': all_xy.append(list( ea.xy[1] )) return all_xy if geometry.type=='MultiPolygon': all_xy = [] for ea in geometry: if coord_type == 'x': all_xy.append(list( ea.exterior.coords.xy[0] )) elif coord_type == 'y': all_xy.append(list( ea.exterior.coords.xy[1] )) return all_xy else: # Finally, return empty list for unknown geometries return [] ``` The portion of the code that handles `MultiPolygon` geometries has a loop that iterates for all the member `Polygon`s, and processes each of them. The code for `Polygon` handling is reused there.
See the shapely docs about [multipolygons](https://shapely.readthedocs.io/en/stable/manual.html#MultiPolygons) A multipolygon is a sequence of polygons, and it is the polygon object that has the exterior attribute. You need to iterate through the polygons of the multipolygon, and get `exterior.coords` of each polygon. In practice, you probably want your geometries in the GeoDataFrame to be polygons, rather than multipolygons, but they aren't. You may want to split the rows in which have multipolygons into multiple rows each with one polygon (or not, depending on your use case)
65,146,279
I need to run K-means clustering algorithm to cluster textual data but by using cosine distance measure instead of Euclidean distance. Any reliable implementation of this in python? ***Edit:*** I have tried to use NLTK as following: ``` NUM_CLUSTERS=3 kclusterer = KMeansClusterer(NUM_CLUSTERS, distance= nltk.cluster.util.cosine_distance, repeats=25) clstr = kclusterer.cluster(X, clusters=False, trace=False) print (clstr) ``` But it gives me error: ``` TypeError: sparse matrix length is ambiguous; use getnnz() or shape[0] ``` X here is a TF-IDF matrix of shape (15, 155).
2020/12/04
[ "https://Stackoverflow.com/questions/65146279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10153492/" ]
If you want to do it yourself: [https://stanford.edu/~cpiech/cs221/handouts/kmeans.html](https://stanford.edu/%7Ecpiech/cs221/handouts/kmeans.html) just change the distance measruing entry. The distance measuring is in the for loop over `i` of the pseudo code.
You can use NLTK for this. The K-means from NLTK allows you to specify which measure of distance you want to use. [nltk](https://www.nltk.org/)